blob: 10872eacb04d4f476e48b7ff9a57f76a850f01a3 [file] [log] [blame]
Carl Lerche058ff472019-02-13 16:23:52 -08001use crate::types;
2
David Tolnay14d463e2019-02-15 14:23:51 -08003use indexmap::IndexMap;
Carl Lerche058ff472019-02-13 16:23:52 -08004use syn::{Data, DataStruct, DeriveInput, Ident, Item};
5
6use std::collections::BTreeMap;
7use std::fs::File;
8use std::io::Read;
9use std::path::Path;
10
11const SYN_CRATE_ROOT: &str = "../src/lib.rs";
12const TOKEN_SRC: &str = "../src/token.rs";
13const IGNORED_MODS: &[&str] = &["fold", "visit", "visit_mut"];
14const EXTRA_TYPES: &[&str] = &["Lifetime"];
Carl Lerche058ff472019-02-13 16:23:52 -080015
16// NOTE: BTreeMap is used here instead of HashMap to have deterministic output.
17type ItemLookup = BTreeMap<Ident, AstItem>;
18type TokenLookup = BTreeMap<String, String>;
19
20/// Parse the contents of `src` and return a list of AST types.
David Tolnayf9bb8ff2019-02-15 13:10:14 -080021pub fn parse() -> types::Definitions {
Carl Lerche058ff472019-02-13 16:23:52 -080022 let mut item_lookup = BTreeMap::new();
23 load_file(SYN_CRATE_ROOT, &[], &mut item_lookup).unwrap();
24
25 let token_lookup = load_token_file(TOKEN_SRC).unwrap();
26
David Tolnayf9bb8ff2019-02-15 13:10:14 -080027 let types = item_lookup
Carl Lerche058ff472019-02-13 16:23:52 -080028 .values()
29 .map(|item| introspect_item(item, &item_lookup, &token_lookup))
David Tolnayf9bb8ff2019-02-15 13:10:14 -080030 .collect();
31
David Tolnay47fe7402019-02-15 14:35:25 -080032 let tokens = token_lookup
33 .into_iter()
34 .map(|(name, ty)| (ty, name))
35 .collect();
David Tolnayf9bb8ff2019-02-15 13:10:14 -080036
37 types::Definitions { types, tokens }
Carl Lerche058ff472019-02-13 16:23:52 -080038}
39
40/// Data extracted from syn source
41#[derive(Clone)]
42pub struct AstItem {
43 ast: DeriveInput,
44 features: Vec<syn::Attribute>,
45}
46
David Tolnayf9bb8ff2019-02-15 13:10:14 -080047fn introspect_item(item: &AstItem, items: &ItemLookup, tokens: &TokenLookup) -> types::Node {
Carl Lerche058ff472019-02-13 16:23:52 -080048 let features = introspect_features(&item.features);
49
50 match &item.ast.data {
David Tolnayc2be7b22019-02-15 18:48:31 -080051 Data::Enum(ref data) => types::Node {
52 ident: item.ast.ident.to_string(),
Carl Lerche058ff472019-02-13 16:23:52 -080053 features,
David Tolnayc2be7b22019-02-15 18:48:31 -080054 data: types::Data::Enum(introspect_enum(data, items, tokens)),
55 },
56 Data::Struct(ref data) => types::Node {
57 ident: item.ast.ident.to_string(),
Carl Lerche058ff472019-02-13 16:23:52 -080058 features,
David Tolnayc2be7b22019-02-15 18:48:31 -080059 data: {
60 if data.fields.iter().all(|f| is_pub(&f.vis)) {
61 types::Data::Struct(introspect_struct(data, items, tokens))
62 } else {
63 types::Data::Private
64 }
65 },
66 },
Carl Lerche058ff472019-02-13 16:23:52 -080067 Data::Union(..) => panic!("Union not supported"),
68 }
69}
70
71fn introspect_enum(
Carl Lerche058ff472019-02-13 16:23:52 -080072 item: &syn::DataEnum,
73 items: &ItemLookup,
74 tokens: &TokenLookup,
David Tolnayc2be7b22019-02-15 18:48:31 -080075) -> Vec<types::Variant> {
76 item.variants
Carl Lerche058ff472019-02-13 16:23:52 -080077 .iter()
78 .map(|variant| {
79 let fields = match &variant.fields {
80 syn::Fields::Unnamed(fields) => fields
81 .unnamed
82 .iter()
83 .map(|field| introspect_type(&field.ty, items, tokens))
84 .collect(),
85 syn::Fields::Unit => vec![],
86 _ => panic!("Enum representation not supported"),
87 };
88
89 types::Variant::new(variant.ident.to_string(), fields)
90 })
David Tolnayc2be7b22019-02-15 18:48:31 -080091 .collect()
Carl Lerche058ff472019-02-13 16:23:52 -080092}
93
94fn introspect_struct(
Carl Lerche058ff472019-02-13 16:23:52 -080095 item: &syn::DataStruct,
96 items: &ItemLookup,
97 tokens: &TokenLookup,
David Tolnayc2be7b22019-02-15 18:48:31 -080098) -> IndexMap<String, types::Type> {
99 match &item.fields {
Carl Lerche058ff472019-02-13 16:23:52 -0800100 syn::Fields::Named(fields) => fields
101 .named
102 .iter()
103 .map(|field| {
David Tolnay14d463e2019-02-15 14:23:51 -0800104 (
Carl Lerche058ff472019-02-13 16:23:52 -0800105 field.ident.as_ref().unwrap().to_string(),
106 introspect_type(&field.ty, items, tokens),
107 )
108 })
109 .collect(),
David Tolnay14d463e2019-02-15 14:23:51 -0800110 syn::Fields::Unit => IndexMap::new(),
Carl Lerche058ff472019-02-13 16:23:52 -0800111 _ => panic!("Struct representation not supported"),
David Tolnayc2be7b22019-02-15 18:48:31 -0800112 }
Carl Lerche058ff472019-02-13 16:23:52 -0800113}
114
115fn introspect_type(item: &syn::Type, items: &ItemLookup, tokens: &TokenLookup) -> types::Type {
116 match item {
117 syn::Type::Path(syn::TypePath {
118 qself: None,
119 ref path,
120 }) => {
121 let last = path.segments.last().unwrap().into_value();
122
123 match &last.ident.to_string()[..] {
124 "Option" => {
125 let nested = introspect_type(first_arg(&last.arguments), items, tokens);
126 types::Type::Option(Box::new(nested))
127 }
128 "Punctuated" => {
129 let nested = introspect_type(first_arg(&last.arguments), items, tokens);
130 let punct = match introspect_type(last_arg(&last.arguments), items, tokens) {
131 types::Type::Token(s) => s,
132 _ => panic!(),
133 };
134
David Tolnay295141b2019-02-15 12:45:33 -0800135 types::Type::Punctuated(types::Punctuated::new(nested, punct))
Carl Lerche058ff472019-02-13 16:23:52 -0800136 }
137 "Vec" => {
138 let nested = introspect_type(first_arg(&last.arguments), items, tokens);
139 types::Type::Vec(Box::new(nested))
140 }
141 "Box" => {
142 let nested = introspect_type(first_arg(&last.arguments), items, tokens);
143 types::Type::Box(Box::new(nested))
144 }
145 "Brace" | "Bracket" | "Paren" | "Group" => {
David Tolnay295141b2019-02-15 12:45:33 -0800146 types::Type::Group(last.ident.to_string())
Carl Lerche058ff472019-02-13 16:23:52 -0800147 }
David Tolnay47fe7402019-02-15 14:35:25 -0800148 "TokenStream" | "Literal" | "Ident" | "Span" => {
149 types::Type::Ext(last.ident.to_string())
150 }
Carl Lerche058ff472019-02-13 16:23:52 -0800151 "String" | "u32" | "usize" | "bool" => types::Type::Std(last.ident.to_string()),
152 _ => {
153 if items.get(&last.ident).is_some() {
David Tolnayd3076572019-02-15 13:32:44 -0800154 types::Type::Syn(last.ident.to_string())
Carl Lerche058ff472019-02-13 16:23:52 -0800155 } else {
156 unimplemented!("{}", last.ident.to_string());
157 }
158 }
159 }
160 }
161 syn::Type::Tuple(syn::TypeTuple { ref elems, .. }) => {
162 let tys = elems
163 .iter()
164 .map(|ty| introspect_type(&ty, items, tokens))
165 .collect();
166 types::Type::Tuple(tys)
167 }
168 syn::Type::Macro(syn::TypeMacro { ref mac })
169 if mac.path.segments.last().unwrap().into_value().ident == "Token" =>
170 {
171 let content = mac.tts.to_string();
172 let ty = tokens.get(&content).unwrap().to_string();
173
David Tolnay157c7eb2019-02-15 13:21:48 -0800174 types::Type::Token(ty)
Carl Lerche058ff472019-02-13 16:23:52 -0800175 }
176 _ => panic!("{}", quote!(#item).to_string()),
177 }
178}
179
180fn introspect_features(attrs: &[syn::Attribute]) -> types::Features {
181 let mut ret = types::Features::default();
182
183 for attr in attrs {
184 if !attr.path.is_ident("cfg") {
185 continue;
186 }
187
188 let features: types::Features = syn::parse2(attr.tts.clone()).unwrap();
189 ret.join(&features);
190 }
191
192 ret
193}
194
195fn is_pub(vis: &syn::Visibility) -> bool {
196 match vis {
197 syn::Visibility::Public(_) => true,
198 _ => false,
199 }
200}
201
202fn first_arg(params: &syn::PathArguments) -> &syn::Type {
203 let data = match *params {
204 syn::PathArguments::AngleBracketed(ref data) => data,
205 _ => panic!("Expected at least 1 type argument here"),
206 };
207
208 match **data
209 .args
210 .first()
211 .expect("Expected at least 1 type argument here")
212 .value()
213 {
214 syn::GenericArgument::Type(ref ty) => ty,
215 _ => panic!("Expected at least 1 type argument here"),
216 }
217}
218
219fn last_arg(params: &syn::PathArguments) -> &syn::Type {
220 let data = match *params {
221 syn::PathArguments::AngleBracketed(ref data) => data,
222 _ => panic!("Expected at least 1 type argument here"),
223 };
224
225 match **data
226 .args
227 .last()
228 .expect("Expected at least 1 type argument here")
229 .value()
230 {
231 syn::GenericArgument::Type(ref ty) => ty,
232 _ => panic!("Expected at least 1 type argument here"),
233 }
234}
235
236mod parsing {
237 use super::{AstItem, TokenLookup};
238 use crate::types;
239
240 use proc_macro2::TokenStream;
241 use syn;
242 use syn::parse::{Parse, ParseStream, Result};
243 use syn::*;
244
245 use std::collections::BTreeMap;
246
247 fn peek_tag(input: ParseStream, tag: &str) -> bool {
248 let ahead = input.fork();
249 ahead.parse::<Token![#]>().is_ok()
250 && ahead
251 .parse::<Ident>()
252 .map(|ident| ident == tag)
253 .unwrap_or(false)
254 }
255
256 // Parses #full - returns #[cfg(feature = "full")] if it is present, and
257 // nothing otherwise.
258 fn full(input: ParseStream) -> Vec<syn::Attribute> {
259 if peek_tag(input, "full") {
260 input.parse::<Token![#]>().unwrap();
261 input.parse::<Ident>().unwrap();
262 vec![parse_quote!(#[cfg(feature = "full")])]
263 } else {
264 vec![]
265 }
266 }
267
268 fn skip_manual_extra_traits(input: ParseStream) {
269 if peek_tag(input, "manual_extra_traits") {
270 input.parse::<Token![#]>().unwrap();
271 input.parse::<Ident>().unwrap();
272 }
273 }
274
275 // Parses a simple AstStruct without the `pub struct` prefix.
276 fn ast_struct_inner(input: ParseStream) -> Result<AstItem> {
277 let ident: Ident = input.parse()?;
278 let features = full(input);
279 skip_manual_extra_traits(input);
280 let rest: TokenStream = input.parse()?;
281 Ok(AstItem {
282 ast: syn::parse2(quote! {
283 pub struct #ident #rest
284 })?,
285 features,
286 })
287 }
288
289 // ast_struct! parsing
290 pub struct AstStruct(pub(super) Vec<AstItem>);
291 impl Parse for AstStruct {
292 fn parse(input: ParseStream) -> Result<Self> {
293 input.call(Attribute::parse_outer)?;
294 input.parse::<Token![pub]>()?;
295 input.parse::<Token![struct]>()?;
296 let res = input.call(ast_struct_inner)?;
297 Ok(AstStruct(vec![res]))
298 }
299 }
300
301 fn no_visit(input: ParseStream) -> bool {
302 if peek_tag(input, "no_visit") {
303 input.parse::<Token![#]>().unwrap();
304 input.parse::<Ident>().unwrap();
305 true
306 } else {
307 false
308 }
309 }
310
311 // ast_enum! parsing
312 pub struct AstEnum(pub Vec<AstItem>);
313 impl Parse for AstEnum {
314 fn parse(input: ParseStream) -> Result<Self> {
315 input.call(Attribute::parse_outer)?;
316 input.parse::<Token![pub]>()?;
317 input.parse::<Token![enum]>()?;
318 let ident: Ident = input.parse()?;
319 let no_visit = no_visit(input);
320 let rest: TokenStream = input.parse()?;
321 Ok(AstEnum(if no_visit {
322 vec![]
323 } else {
324 vec![AstItem {
325 ast: syn::parse2(quote! {
326 pub enum #ident #rest
327 })?,
328 features: vec![],
329 }]
330 }))
331 }
332 }
333
334 // A single variant of an ast_enum_of_structs!
335 struct EosVariant {
336 name: Ident,
337 member: Option<Path>,
338 inner: Option<AstItem>,
339 }
340 fn eos_variant(input: ParseStream) -> Result<EosVariant> {
341 input.call(Attribute::parse_outer)?;
342 input.parse::<Token![pub]>()?;
343 let variant: Ident = input.parse()?;
344 let (member, inner) = if input.peek(token::Paren) {
345 let content;
346 parenthesized!(content in input);
347 if content.fork().call(ast_struct_inner).is_ok() {
348 let item = content.call(ast_struct_inner)?;
349 (Some(Path::from(item.ast.ident.clone())), Some(item))
350 } else {
351 let path: Path = content.parse()?;
352 (Some(path), None)
353 }
354 } else {
355 (None, None)
356 };
357 input.parse::<Token![,]>()?;
358 Ok(EosVariant {
359 name: variant,
360 member,
361 inner,
362 })
363 }
364
365 // ast_enum_of_structs! parsing
366 pub struct AstEnumOfStructs(pub Vec<AstItem>);
367 impl Parse for AstEnumOfStructs {
368 fn parse(input: ParseStream) -> Result<Self> {
369 input.call(Attribute::parse_outer)?;
370 input.parse::<Token![pub]>()?;
371 input.parse::<Token![enum]>()?;
372 let ident: Ident = input.parse()?;
373
374 let content;
375 braced!(content in input);
376 let mut variants = Vec::new();
377 while !content.is_empty() {
378 variants.push(content.call(eos_variant)?);
379 }
380
381 if let Some(ident) = input.parse::<Option<Ident>>()? {
382 assert_eq!(ident, "do_not_generate_to_tokens");
383 }
384
385 let enum_item = {
386 let variants = variants.iter().map(|v| {
387 let name = v.name.clone();
388 match v.member {
389 Some(ref member) => quote!(#name(#member)),
390 None => quote!(#name),
391 }
392 });
393 parse_quote! {
394 pub enum #ident {
395 #(#variants),*
396 }
397 }
398 };
399 let mut items = vec![AstItem {
400 ast: enum_item,
401 features: vec![],
402 }];
403 items.extend(variants.into_iter().filter_map(|v| v.inner));
404 Ok(AstEnumOfStructs(items))
405 }
406 }
407
408 pub struct TokenMacro(pub TokenLookup);
409 impl Parse for TokenMacro {
410 fn parse(input: ParseStream) -> Result<Self> {
411 let mut tokens = BTreeMap::new();
412 while !input.is_empty() {
413 let content;
414 parenthesized!(content in input);
415 let token = content.parse::<TokenStream>()?.to_string();
416 input.parse::<Token![=]>()?;
417 input.parse::<Token![>]>()?;
418 let content;
419 braced!(content in input);
420 input.parse::<Token![;]>()?;
421 content.parse::<token::Dollar>()?;
422 let path: Path = content.parse()?;
423 let ty = path.segments.last().unwrap().into_value().ident.to_string();
424 tokens.insert(token, ty.to_string());
425 }
426 Ok(TokenMacro(tokens))
427 }
428 }
429
430 fn parse_feature(input: ParseStream) -> Result<String> {
431 let i: syn::Ident = input.parse()?;
432 assert_eq!(i, "feature");
433
434 input.parse::<Token![=]>()?;
435 let s = input.parse::<syn::LitStr>()?;
436
437 Ok(s.value())
438 }
439
440 impl Parse for types::Features {
441 fn parse(input: ParseStream) -> Result<Self> {
442 let mut features = vec![];
443
444 let level_1;
445 parenthesized!(level_1 in input);
446
447 let i: syn::Ident = level_1.fork().parse()?;
448
449 if i == "any" {
450 level_1.parse::<syn::Ident>()?;
451
452 let level_2;
453 parenthesized!(level_2 in level_1);
454
455 while !level_2.is_empty() {
456 features.push(parse_feature(&level_2)?);
457
458 if !level_2.is_empty() {
459 level_2.parse::<Token![,]>()?;
460 }
461 }
462 } else if i == "feature" {
463 features.push(parse_feature(&level_1)?);
464 assert!(level_1.is_empty());
465 } else {
466 panic!("{:?}", i);
467 }
468
469 assert!(input.is_empty());
470
471 Ok(types::Features::new(features))
472 }
473 }
474}
475
476fn get_features(attrs: &[syn::Attribute], base: &[syn::Attribute]) -> Vec<syn::Attribute> {
477 let mut ret = base.to_owned();
478
479 for attr in attrs {
480 if attr.path.is_ident("cfg") {
481 ret.push(attr.clone());
482 }
483 }
484
485 ret
486}
487
488type Error = Box<::std::error::Error>;
489
490fn load_file<P: AsRef<Path>>(
491 name: P,
492 features: &[syn::Attribute],
493 lookup: &mut ItemLookup,
494) -> Result<(), Error> {
495 let name = name.as_ref();
496 let parent = name.parent().ok_or("no parent path")?;
497
498 let mut f = File::open(name)?;
499 let mut src = String::new();
500 f.read_to_string(&mut src)?;
501
502 // Parse the file
503 let file = syn::parse_file(&src)?;
504
505 // Collect all of the interesting AstItems declared in this file or submodules.
506 'items: for item in file.items {
507 match item {
508 Item::Mod(item) => {
509 // Don't inspect inline modules.
510 if item.content.is_some() {
511 continue;
512 }
513
514 // We don't want to try to load the generated rust files and
515 // parse them, so we ignore them here.
516 for name in IGNORED_MODS {
517 if item.ident == name {
518 continue 'items;
519 }
520 }
521
522 // Lookup any #[cfg()] attributes on the module and add them to
523 // the feature set.
524 //
525 // The derive module is weird because it is built with either
526 // `full` or `derive` but exported only under `derive`.
527 let features = if item.ident == "derive" {
528 vec![parse_quote!(#[cfg(feature = "derive")])]
529 } else {
530 get_features(&item.attrs, features)
531 };
532
533 // Look up the submodule file, and recursively parse it.
534 // XXX: Only handles same-directory .rs file submodules.
535 let path = parent.join(&format!("{}.rs", item.ident));
536 load_file(path, &features, lookup)?;
537 }
538 Item::Macro(item) => {
539 // Lookip any #[cfg()] attributes directly on the macro
540 // invocation, and add them to the feature set.
541 let features = get_features(&item.attrs, features);
542
543 // Try to parse the AstItem declaration out of the item.
544 let tts = &item.mac.tts;
545 let found = if item.mac.path.is_ident("ast_struct") {
546 syn::parse2::<parsing::AstStruct>(quote!(#tts))?.0
547 } else if item.mac.path.is_ident("ast_enum") {
548 syn::parse2::<parsing::AstEnum>(quote!(#tts))?.0
549 } else if item.mac.path.is_ident("ast_enum_of_structs") {
550 syn::parse2::<parsing::AstEnumOfStructs>(quote!(#tts))?.0
551 } else {
552 continue;
553 };
554
555 // Record our features on the parsed AstItems.
556 for mut item in found {
557 item.features.extend(features.clone());
558 lookup.insert(item.ast.ident.clone(), item);
559 }
560 }
561 Item::Struct(item) => {
562 let ident = item.ident;
563 if EXTRA_TYPES.contains(&&ident.to_string()[..]) {
564 lookup.insert(
565 ident.clone(),
566 AstItem {
567 ast: DeriveInput {
568 ident,
569 vis: item.vis,
570 attrs: item.attrs,
571 generics: item.generics,
572 data: Data::Struct(DataStruct {
573 fields: item.fields,
574 struct_token: item.struct_token,
575 semi_token: item.semi_token,
576 }),
577 },
578 features: features.to_owned(),
579 },
580 );
581 }
582 }
583 _ => {}
584 }
585 }
586 Ok(())
587}
588
589fn load_token_file<P: AsRef<Path>>(name: P) -> Result<TokenLookup, Error> {
590 let name = name.as_ref();
591 let mut f = File::open(name)?;
592 let mut src = String::new();
593 f.read_to_string(&mut src)?;
594 let file = syn::parse_file(&src)?;
595 for item in file.items {
596 match item {
597 Item::Macro(item) => {
598 match item.ident {
599 Some(ref i) if i == "Token" => {}
600 _ => continue,
601 }
602 let tts = &item.mac.tts;
603 let tokens = syn::parse2::<parsing::TokenMacro>(quote!(#tts))?.0;
604 return Ok(tokens);
605 }
606 _ => {}
607 }
608 }
609
610 Err("failed to parse Token macro".into())
611}