我正在尝试使用 syn 从 Rust 文件创建 AST,然后使用 quote 将其写入另一个文件。但是,当我写它时,它在所有内容之间添加了额外的空格。
请注意,下面的示例只是为了演示我遇到的最小可重现问题。我意识到如果我只想复制代码,我可以复制文件,但它不适合我的情况,我需要使用 AST。
pub fn build_file() {
let current_dir = std::env::current_dir().expect("Unable to get current directory");
let rust_file = std::fs::read_to_string(current_dir.join("src").join("lib.rs")).expect("Unable to read rust file");
let ast = syn::parse_file(&rust_file).expect("Unable to create AST from rust file");
match std::fs::write("src/utils.rs", quote::quote!(#ast).to_string());
}
它创建 AST 的文件是这样的:
#[macro_use]
extern crate foo;
mod test;
fn init(handle: foo::InitHandle) {
handle.add_class::<Test::test>();
}
它输出的是这样的:
# [macro_use] extern crate foo ; mod test ; fn init (handle : foo :: InitHandle) { handle . add_class :: < Test :: test > () ; }
我什至尝试在将它写入文件后通过 rustfmt
运行它,如下所示:
utils::write_file("src/utils.rs", quote::quote!(#ast).to_string());
match std::process::Command::new("cargo").arg("fmt").output() {
Ok(_v) => (),
Err(e) => std::process::exit(1),
}
但这似乎没有任何区别。
答案 0 :(得分:2)
quote
crate 并不真正关心漂亮地打印生成的代码。您可以通过 rustfmt 运行它,只需执行 rustfmt src/utils.rs
或 cargo fmt -- src/utils.rs
。
use std::fs;
use std::io;
use std::path::Path;
use std::process::Command;
fn write_and_fmt<P: AsRef<Path>, S: ToString>(path: P, code: S) -> io::Result<()> {
fs::write(&path, code.to_string())?;
Command::new("rustfmt")
.arg(path.as_ref())
.spawn()?
.wait()?;
Ok(())
}
现在您可以执行:
write_and_fmt("src/utils.rs", quote::quote!(#ast)).expect("unable to save or format");
另见 Rust 论坛上的 "Any interest in a pretty-printing crate for Syn?"。