Skip to content

Commit 261944c

Browse files
committed
Use syn + prettyplease to format
This replaces the dependency on the rustfmt executable with an actual tracked build dependency. Since we have to parse with syn anyway now, I also took the opportunity to swap the string replacement for a syntax-tree based replacement.
1 parent d2bf6e9 commit 261944c

File tree

2 files changed

+15
-20
lines changed

2 files changed

+15
-20
lines changed

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ optional = true
155155
svd2rust = "0.35.0"
156156
svdtools = "0.4.0"
157157
atdf2svd = "0.4.0"
158+
prettyplease = "0.2"
159+
syn = { version = "2", default-features = false, features = ["full", "parsing"] }
158160

159161
[dev-dependencies]
160162
nb = "0.1.2"

build.rs

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ use std::{
88
fs::{self, File},
99
io::{self, Write},
1010
path::{Path, PathBuf},
11-
process::{Command, Stdio},
1211
};
1312
use svdtools::patch;
13+
use syn::Item;
1414

1515
fn main() {
1616
println!("cargo::rustc-check-cfg=cfg(single_mcu)");
@@ -135,26 +135,19 @@ _include:
135135
svd2rust_config.interrupt_link_section = Some(".text.vector".to_owned());
136136
let generated = svd2rust::generate(&svd_content, &svd2rust_config).unwrap();
137137

138-
// HACK: Using simple pattern replacement like this is likely to break
139-
// with any formatting changes in the input. Ideally we'd parse it somehow,
140-
// but that'd increase compile time. Perhaps reopening the file after
141-
// rustfmt runs and patching that would be less fickle.
142-
let pat = "# [no_mangle] static mut DEVICE_PERIPHERALS : bool = false ;";
143-
let lib_rs = generated
144-
.lib_rs
145-
.replace(pat, "use super::DEVICE_PERIPHERALS;");
146-
let module_file = pac_dir.join(mcu).with_extension("rs");
147-
fs::write(&module_file, lib_rs).unwrap();
148-
149-
let status = Command::new("rustfmt")
150-
.arg(module_file.to_str().unwrap())
151-
.stdin(Stdio::null())
152-
.stdout(Stdio::null())
153-
.status()
154-
.unwrap();
155-
if let Err(what) = status.exit_ok() {
156-
panic!("rustfmt failed to format generated source with: {}", what);
138+
let mut syntax_tree = syn::parse_file(&generated.lib_rs).unwrap();
139+
for item in syntax_tree.items.iter_mut().rev() {
140+
{
141+
let Item::Static(statik) = item else { continue };
142+
if &statik.ident.to_string() != "DEVICE_PERIPHERALS" {
143+
continue;
144+
}
145+
}
146+
*item = syn::parse_quote! {use super::DEVICE_PERIPHERALS;};
157147
}
148+
let formatted = prettyplease::unparse(&syntax_tree);
149+
let module_file = pac_dir.join(mcu).with_extension("rs");
150+
fs::write(&module_file, &formatted).unwrap();
158151
}
159152

160153
fn ensure_directory(dir: &Path) {

0 commit comments

Comments
 (0)