Created
April 10, 2019 19:21
-
-
Save anmonteiro/6cc8ed5c5b130ba3ad348d2fac7ba80c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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