我正在尝试使用syn从Rust文件创建AST,然后使用引号将其写入另一个文件。但是,当我编写它时,它在所有内容之间都留有多余的空间。
请注意,下面的示例仅用于说明我遇到的最小可复制问题。我意识到,如果我只想复制代码,则可以复制文件,但不适合我的情况,因此我需要使用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),
}
但这似乎没有任何区别。
该quote
箱子是不是真的关心漂亮的打印生成的代码。您可以通过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");
另请参见“是否对Syn的漂亮包装箱感兴趣?” 在Rust论坛上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句