Skip to content

Instantly share code, notes, and snippets.

@anmonteiro
Created April 10, 2019 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anmonteiro/6cc8ed5c5b130ba3ad348d2fac7ba80c to your computer and use it in GitHub Desktop.
Save anmonteiro/6cc8ed5c5b130ba3ad348d2fac7ba80c to your computer and use it in GitHub Desktop.
use syn::{self, Item, ItemMod, ItemUse, UseGroup, UsePath, UseTree};
use std::collections::HashSet;
use std::env;
use std::fs::File;
use std::io::Read;
use std::process;
fn main() {
let mut args = env::args();
let _ = args.next(); // executable name
let filename = match (args.next(), args.next()) {
(Some(filename), None) => filename,
_ => {
eprintln!("Usage: dump-syntax path/to/filename.rs");
process::exit(1);
}
};
let mut file = File::open(&filename).expect("Unable to open file");
let mut src = String::new();
file.read_to_string(&mut src).expect("Unable to read file");
let ast = syn::parse_file(&src).expect("Unable to parse file");
let uses: HashSet<_> = ast
.items
.into_iter()
.filter_map(|x| match x {
// use crate::identifier
Item::Use(ItemUse {
tree:
UseTree::Path(UsePath {
ref ident,
tree: ref ident_tree,
..
}),
..
}) if ident == "crate" => {
(match **ident_tree {
UseTree::Path(UsePath {
ident: ref crate_ident,
..
}) => Some([crate_ident.to_string()].to_vec()),
UseTree::Group(UseGroup { ref items, .. }) => {
let idents = items
.into_iter()
.filter_map(|x| match x {
UseTree::Path(UsePath { ref ident, .. }) => Some(ident.to_string()),
_ => None,
})
.collect();
Some(idents)
}
_ => None,
})
}
Item::Mod(ItemMod { ident, .. }) => Some([ident.to_string()].to_vec()),
_ => None,
})
.flatten()
.collect();
let mods: Vec<_> = uses.into_iter().collect();
println!("{:#?}", mods);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment