Available on crate feature
parsing
only.Expand description
Parse a string of Rust code into the chosen syntax tree node.
This function is available only if Syn is built with the "parsing"
feature.
Hygiene
Every span in the resulting syntax tree will be set to resolve at the macro call site.
Examples
use syn::{Expr, Result};
fn run() -> Result<()> {
let code = "assert_eq!(u8::max_value(), 255)";
let expr = syn::parse_str::<Expr>(code)?;
println!("{:#?}", expr);
Ok(())
}
Examples found in repository?
src/lib.rs (line 981)
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
pub fn parse_file(mut content: &str) -> Result<File> {
// Strip the BOM if it is present
const BOM: &str = "\u{feff}";
if content.starts_with(BOM) {
content = &content[BOM.len()..];
}
let mut shebang = None;
if content.starts_with("#!") {
let rest = whitespace::skip(&content[2..]);
if !rest.starts_with('[') {
if let Some(idx) = content.find('\n') {
shebang = Some(content[..idx].to_string());
content = &content[idx..];
} else {
shebang = Some(content.to_string());
content = "";
}
}
}
let mut file: File = parse_str(content)?;
file.shebang = shebang;
Ok(file)
}
More examples
src/expr.rs (line 2904)
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
fn multi_index(e: &mut Expr, dot_token: &mut Token![.], float: LitFloat) -> Result<bool> {
let mut float_repr = float.to_string();
let trailing_dot = float_repr.ends_with('.');
if trailing_dot {
float_repr.truncate(float_repr.len() - 1);
}
for part in float_repr.split('.') {
let index = crate::parse_str(part).map_err(|err| Error::new(float.span(), err))?;
#[cfg(not(syn_no_const_vec_new))]
let base = mem::replace(e, Expr::DUMMY);
#[cfg(syn_no_const_vec_new)]
let base = mem::replace(e, Expr::Verbatim(TokenStream::new()));
*e = Expr::Field(ExprField {
attrs: Vec::new(),
base: Box::new(base),
dot_token: Token![.](dot_token.span),
member: Member::Unnamed(index),
});
*dot_token = Token![.](float.span());
}
Ok(!trailing_dot)
}