Function syn::parse_file
source · [−]Expand description
Parse the content of a file of Rust code.
This is different from syn::parse_str::<File>(content)
in two ways:
- It discards a leading byte order mark
\u{FEFF}
if the file has one. - It preserves the shebang line of the file, such as
#!/usr/bin/env rustx
.
If present, either of these would be an error using from_str
.
This function is available only if Syn is built with the "parsing"
and
"full"
features.
Examples
use std::error::Error;
use std::fs::File;
use std::io::Read;
fn run() -> Result<(), Box<Error>> {
let mut file = File::open("path/to/code.rs")?;
let mut content = String::new();
file.read_to_string(&mut content)?;
let ast = syn::parse_file(&content)?;
if let Some(shebang) = ast.shebang {
println!("{}", shebang);
}
println!("{} items", ast.items.len());
Ok(())
}