1 use crate::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
2 use crate::ast::{MacStmtStyle, StmtKind, ItemKind};
3 use crate::attr::{self, HasAttrs};
4 use crate::source_map::respan;
5 use crate::config::StripUnconfigured;
6 use crate::ext::base::*;
7 use crate::ext::proc_macro::{collect_derives, MarkAttrs};
8 use crate::ext::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
9 use crate::ext::mbe::macro_rules::annotate_err_with_kind;
10 use crate::ext::placeholders::{placeholder, PlaceholderExpander};
11 use crate::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
12 use crate::mut_visit::*;
13 use crate::parse::{DirectoryOwnership, PResult, ParseSess};
14 use crate::parse::token;
15 use crate::parse::parser::Parser;
16 use crate::print::pprust;
18 use crate::symbol::{sym, Symbol};
19 use crate::tokenstream::{TokenStream, TokenTree};
20 use crate::visit::{self, Visitor};
21 use crate::util::map_in_place::MapInPlace;
23 use errors::{Applicability, FatalError};
24 use smallvec::{smallvec, SmallVec};
25 use syntax_pos::{Span, DUMMY_SP, FileName};
27 use rustc_data_structures::fx::FxHashMap;
28 use rustc_data_structures::sync::Lrc;
29 use std::io::ErrorKind;
30 use std::{iter, mem, slice};
31 use std::ops::DerefMut;
33 use std::path::PathBuf;
35 macro_rules! ast_fragments {
37 $($Kind:ident($AstTy:ty) {
39 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
40 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
44 /// A fragment of AST that can be produced by a single macro expansion.
45 /// Can also serve as an input and intermediate result for macro expansion operations.
46 pub enum AstFragment {
47 OptExpr(Option<P<ast::Expr>>),
51 /// "Discriminant" of an AST fragment.
52 #[derive(Copy, Clone, PartialEq, Eq)]
53 pub enum AstFragmentKind {
58 impl AstFragmentKind {
59 pub fn name(self) -> &'static str {
61 AstFragmentKind::OptExpr => "expression",
62 $(AstFragmentKind::$Kind => $kind_name,)*
66 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
68 AstFragmentKind::OptExpr =>
69 result.make_expr().map(Some).map(AstFragment::OptExpr),
70 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
76 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
78 AstFragment::OptExpr(expr) => expr,
79 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
83 $(pub fn $make_ast(self) -> $AstTy {
85 AstFragment::$Kind(ast) => ast,
86 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
90 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
92 AstFragment::OptExpr(opt_expr) => {
93 visit_clobber(opt_expr, |opt_expr| {
94 if let Some(expr) = opt_expr {
95 vis.filter_map_expr(expr)
101 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
102 $($(AstFragment::$Kind(ast) =>
103 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
107 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
109 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
110 AstFragment::OptExpr(None) => {}
111 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
112 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
113 visitor.$visit_ast_elt(ast_elt);
119 impl<'a> MacResult for crate::ext::mbe::macro_rules::ParserAnyMacro<'a> {
120 $(fn $make_ast(self: Box<crate::ext::mbe::macro_rules::ParserAnyMacro<'a>>)
122 Some(self.make(AstFragmentKind::$Kind).$make_ast())
129 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
130 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
131 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
132 Stmts(SmallVec<[ast::Stmt; 1]>) {
133 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
135 Items(SmallVec<[P<ast::Item>; 1]>) {
136 "item"; many fn flat_map_item; fn visit_item; fn make_items;
138 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
139 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
141 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
142 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
144 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
146 many fn flat_map_foreign_item;
147 fn visit_foreign_item;
148 fn make_foreign_items;
150 Arms(SmallVec<[ast::Arm; 1]>) {
151 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
153 Fields(SmallVec<[ast::Field; 1]>) {
154 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
156 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
158 many fn flat_map_field_pattern;
159 fn visit_field_pattern;
160 fn make_field_patterns;
162 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
164 many fn flat_map_generic_param;
165 fn visit_generic_param;
166 fn make_generic_params;
168 Params(SmallVec<[ast::Param; 1]>) {
169 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
171 StructFields(SmallVec<[ast::StructField; 1]>) {
173 many fn flat_map_struct_field;
174 fn visit_struct_field;
175 fn make_struct_fields;
177 Variants(SmallVec<[ast::Variant; 1]>) {
178 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
182 impl AstFragmentKind {
183 fn dummy(self, span: Span) -> AstFragment {
184 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
187 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
189 let mut items = items.into_iter();
191 AstFragmentKind::Arms =>
192 AstFragment::Arms(items.map(Annotatable::expect_arm).collect()),
193 AstFragmentKind::Fields =>
194 AstFragment::Fields(items.map(Annotatable::expect_field).collect()),
195 AstFragmentKind::FieldPats =>
196 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()),
197 AstFragmentKind::GenericParams =>
198 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()),
199 AstFragmentKind::Params =>
200 AstFragment::Params(items.map(Annotatable::expect_param).collect()),
201 AstFragmentKind::StructFields => AstFragment::StructFields(
202 items.map(Annotatable::expect_struct_field).collect()
204 AstFragmentKind::Variants =>
205 AstFragment::Variants(items.map(Annotatable::expect_variant).collect()),
206 AstFragmentKind::Items =>
207 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
208 AstFragmentKind::ImplItems =>
209 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
210 AstFragmentKind::TraitItems =>
211 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
212 AstFragmentKind::ForeignItems =>
213 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
214 AstFragmentKind::Stmts =>
215 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
216 AstFragmentKind::Expr => AstFragment::Expr(
217 items.next().expect("expected exactly one expression").expect_expr()
219 AstFragmentKind::OptExpr =>
220 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
221 AstFragmentKind::Pat | AstFragmentKind::Ty =>
222 panic!("patterns and types aren't annotatable"),
227 pub struct Invocation {
228 pub kind: InvocationKind,
229 pub fragment_kind: AstFragmentKind,
230 pub expansion_data: ExpansionData,
233 pub enum InvocationKind {
239 attr: ast::Attribute,
241 // Required for resolving derive helper attributes.
243 // We temporarily report errors for attribute macros placed after derives
250 /// "Invocation" that contains all derives from an item,
251 /// broken into multiple `Derive` invocations when expanded.
252 /// FIXME: Find a way to remove it.
260 pub fn span(&self) -> Span {
262 InvocationKind::Bang { span, .. } => *span,
263 InvocationKind::Attr { attr, .. } => attr.span,
264 InvocationKind::Derive { path, .. } => path.span,
265 InvocationKind::DeriveContainer { item, .. } => item.span(),
270 pub struct MacroExpander<'a, 'b> {
271 pub cx: &'a mut ExtCtxt<'b>,
272 monotonic: bool, // cf. `cx.monotonic_expander()`
275 impl<'a, 'b> MacroExpander<'a, 'b> {
276 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
277 MacroExpander { cx, monotonic }
280 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
281 let mut module = ModuleData {
282 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
283 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
284 FileName::Real(path) => path,
285 other => PathBuf::from(other.to_string()),
288 module.directory.pop();
289 self.cx.root_path = module.directory.clone();
290 self.cx.current_expansion.module = Rc::new(module);
292 let orig_mod_span = krate.module.inner;
294 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
297 kind: ast::ItemKind::Mod(krate.module),
298 ident: Ident::invalid(),
299 id: ast::DUMMY_NODE_ID,
300 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
304 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
305 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
307 krate.module = module;
310 // Resolution failed so we return an empty expansion
311 krate.attrs = vec![];
312 krate.module = ast::Mod {
313 inner: orig_mod_span,
320 self.cx.trace_macros_diag();
324 // Recursively expand all macro invocations in this AST fragment.
325 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
326 let orig_expansion_data = self.cx.current_expansion.clone();
327 self.cx.current_expansion.depth = 0;
329 // Collect all macro invocations and replace them with placeholders.
330 let (mut fragment_with_placeholders, mut invocations)
331 = self.collect_invocations(input_fragment, &[]);
333 // Optimization: if we resolve all imports now,
334 // we'll be able to immediately resolve most of imported macros.
335 self.resolve_imports();
337 // Resolve paths in all invocations and produce output expanded fragments for them, but
338 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
339 // The output fragments also go through expansion recursively until no invocations are left.
340 // Unresolved macros produce dummy outputs as a recovery measure.
341 invocations.reverse();
342 let mut expanded_fragments = Vec::new();
343 let mut all_derive_placeholders: FxHashMap<ExpnId, Vec<_>> = FxHashMap::default();
344 let mut undetermined_invocations = Vec::new();
345 let (mut progress, mut force) = (false, !self.monotonic);
347 let invoc = if let Some(invoc) = invocations.pop() {
350 self.resolve_imports();
351 if undetermined_invocations.is_empty() { break }
352 invocations = mem::take(&mut undetermined_invocations);
353 force = !mem::replace(&mut progress, false);
357 let eager_expansion_root =
358 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
359 let res = match self.cx.resolver.resolve_macro_invocation(
360 &invoc, eager_expansion_root, force
363 Err(Indeterminate) => {
364 undetermined_invocations.push(invoc);
370 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
371 self.cx.current_expansion = invoc.expansion_data.clone();
373 // FIXME(jseyfried): Refactor out the following logic
374 let (expanded_fragment, new_invocations) = match res {
375 InvocationRes::Single(ext) => {
376 let fragment = self.expand_invoc(invoc, &ext.kind);
377 self.collect_invocations(fragment, &[])
379 InvocationRes::DeriveContainer(exts) => {
380 let (derives, item) = match invoc.kind {
381 InvocationKind::DeriveContainer { derives, item } => (derives, item),
384 if !item.derive_allowed() {
385 let attr = attr::find_by_name(item.attrs(), sym::derive)
386 .expect("`derive` attribute should exist");
387 let span = attr.span;
388 let mut err = self.cx.struct_span_err(span,
389 "`derive` may only be applied to structs, enums and unions");
390 if let ast::AttrStyle::Inner = attr.style {
391 let trait_list = derives.iter()
392 .map(|t| pprust::path_to_string(t))
393 .collect::<Vec<_>>();
394 let suggestion = format!("#[derive({})]", trait_list.join(", "));
396 span, "try an outer attribute", suggestion,
397 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
398 Applicability::MaybeIncorrect
404 let mut item = self.fully_configure(item);
405 item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
406 let mut helper_attrs = Vec::new();
407 let mut has_copy = false;
409 helper_attrs.extend(&ext.helper_attrs);
410 has_copy |= ext.is_derive_copy;
412 // Mark derive helpers inside this item as known and used.
413 // FIXME: This is a hack, derive helpers should be integrated with regular name
414 // resolution instead. For example, helpers introduced by a derive container
415 // can be in scope for all code produced by that container's expansion.
416 item.visit_with(&mut MarkAttrs(&helper_attrs));
418 self.cx.resolver.add_derives(invoc.expansion_data.id, SpecialDerives::COPY);
421 let derive_placeholders =
422 all_derive_placeholders.entry(invoc.expansion_data.id).or_default();
423 derive_placeholders.reserve(derives.len());
424 invocations.reserve(derives.len());
425 for path in derives {
426 let expn_id = ExpnId::fresh(None);
427 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
428 invocations.push(Invocation {
429 kind: InvocationKind::Derive { path, item: item.clone() },
430 fragment_kind: invoc.fragment_kind,
431 expansion_data: ExpansionData {
433 ..invoc.expansion_data.clone()
437 let fragment = invoc.fragment_kind
438 .expect_from_annotatables(::std::iter::once(item));
439 self.collect_invocations(fragment, derive_placeholders)
443 if expanded_fragments.len() < depth {
444 expanded_fragments.push(Vec::new());
446 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
447 if !self.cx.ecfg.single_step {
448 invocations.extend(new_invocations.into_iter().rev());
452 self.cx.current_expansion = orig_expansion_data;
454 // Finally incorporate all the expanded macros into the input AST fragment.
455 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
456 while let Some(expanded_fragments) = expanded_fragments.pop() {
457 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
458 let derive_placeholders =
459 all_derive_placeholders.remove(&expn_id).unwrap_or_else(Vec::new);
460 placeholder_expander.add(NodeId::placeholder_from_expn_id(expn_id),
461 expanded_fragment, derive_placeholders);
464 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
465 fragment_with_placeholders
468 fn resolve_imports(&mut self) {
470 self.cx.resolver.resolve_imports();
474 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
475 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
476 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
477 /// prepares data for resolving paths of macro invocations.
478 fn collect_invocations(&mut self, mut fragment: AstFragment, extra_placeholders: &[NodeId])
479 -> (AstFragment, Vec<Invocation>) {
480 // Resolve `$crate`s in the fragment for pretty-printing.
481 self.cx.resolver.resolve_dollar_crates();
484 let mut collector = InvocationCollector {
485 cfg: StripUnconfigured {
486 sess: self.cx.parse_sess,
487 features: self.cx.ecfg.features,
490 invocations: Vec::new(),
491 monotonic: self.monotonic,
493 fragment.mut_visit_with(&mut collector);
494 collector.invocations
497 // FIXME: Merge `extra_placeholders` into the `fragment` as regular placeholders.
499 self.cx.resolver.visit_ast_fragment_with_placeholders(
500 self.cx.current_expansion.id, &fragment, extra_placeholders);
503 (fragment, invocations)
506 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
507 let mut cfg = StripUnconfigured {
508 sess: self.cx.parse_sess,
509 features: self.cx.ecfg.features,
511 // Since the item itself has already been configured by the InvocationCollector,
512 // we know that fold result vector will contain exactly one element
514 Annotatable::Item(item) => {
515 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
517 Annotatable::TraitItem(item) => {
518 Annotatable::TraitItem(
519 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
521 Annotatable::ImplItem(item) => {
522 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
524 Annotatable::ForeignItem(item) => {
525 Annotatable::ForeignItem(
526 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
529 Annotatable::Stmt(stmt) => {
530 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
532 Annotatable::Expr(mut expr) => {
533 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
535 Annotatable::Arm(arm) => {
536 Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap())
538 Annotatable::Field(field) => {
539 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
541 Annotatable::FieldPat(fp) => {
542 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
544 Annotatable::GenericParam(param) => {
545 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
547 Annotatable::Param(param) => {
548 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
550 Annotatable::StructField(sf) => {
551 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
553 Annotatable::Variant(v) => {
554 Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap())
559 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
560 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
561 let expn_data = self.cx.current_expansion.id.expn_data();
562 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
563 let mut err = self.cx.struct_span_err(expn_data.call_site,
564 &format!("recursion limit reached while expanding the macro `{}`",
565 expn_data.kind.descr()));
567 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
570 self.cx.trace_macros_diag();
574 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
576 InvocationKind::Bang { mac, .. } => match ext {
577 SyntaxExtensionKind::Bang(expander) => {
578 self.gate_proc_macro_expansion_kind(span, fragment_kind);
579 let tok_result = expander.expand(self.cx, span, mac.stream());
581 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span);
582 self.gate_proc_macro_expansion(span, &result);
585 SyntaxExtensionKind::LegacyBang(expander) => {
586 let prev = self.cx.current_expansion.prior_type_ascription;
587 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
588 let tok_result = expander.expand(self.cx, span, mac.stream());
589 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
593 "non-{kind} macro in {kind} position: {path}",
594 kind = fragment_kind.name(),
595 path = pprust::path_to_string(&mac.path),
597 self.cx.span_err(span, &msg);
598 self.cx.trace_macros_diag();
599 fragment_kind.dummy(span)
601 self.cx.current_expansion.prior_type_ascription = prev;
606 InvocationKind::Attr { attr, mut item, .. } => match ext {
607 SyntaxExtensionKind::Attr(expander) => {
608 self.gate_proc_macro_attr_item(span, &item);
609 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
610 Annotatable::Item(item) => token::NtItem(item),
611 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
612 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
613 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
614 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
615 Annotatable::Expr(expr) => token::NtExpr(expr),
617 | Annotatable::Field(..)
618 | Annotatable::FieldPat(..)
619 | Annotatable::GenericParam(..)
620 | Annotatable::Param(..)
621 | Annotatable::StructField(..)
622 | Annotatable::Variant(..)
623 => panic!("unexpected annotatable"),
624 })), DUMMY_SP).into();
625 let input = self.extract_proc_macro_attr_input(attr.item.tokens, span);
626 let tok_result = expander.expand(self.cx, span, input, item_tok);
628 self.parse_ast_fragment(tok_result, fragment_kind, &attr.item.path, span);
629 self.gate_proc_macro_expansion(span, &res);
632 SyntaxExtensionKind::LegacyAttr(expander) => {
633 match attr.parse_meta(self.cx.parse_sess) {
635 let item = expander.expand(self.cx, span, &meta, item);
636 fragment_kind.expect_from_annotatables(item)
640 fragment_kind.dummy(span)
644 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
645 attr::mark_known(&attr);
647 attr::mark_used(&attr);
649 item.visit_attrs(|attrs| attrs.push(attr));
650 fragment_kind.expect_from_annotatables(iter::once(item))
654 InvocationKind::Derive { path, item } => match ext {
655 SyntaxExtensionKind::Derive(expander) |
656 SyntaxExtensionKind::LegacyDerive(expander) => {
657 if !item.derive_allowed() {
658 return fragment_kind.dummy(span);
660 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
661 let items = expander.expand(self.cx, span, &meta, item);
662 fragment_kind.expect_from_annotatables(items)
666 InvocationKind::DeriveContainer { .. } => unreachable!()
670 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
671 let mut trees = tokens.trees();
673 Some(TokenTree::Delimited(_, _, tts)) => {
674 if trees.next().is_none() {
678 Some(TokenTree::Token(..)) => {}
679 None => return TokenStream::default(),
681 self.cx.span_err(span, "custom attribute invocations must be \
682 of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
683 followed by a delimiter token");
684 TokenStream::default()
687 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
688 let (kind, gate) = match *item {
689 Annotatable::Item(ref item) => {
691 ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
692 ItemKind::Mod(_) => ("modules", sym::proc_macro_hygiene),
696 Annotatable::TraitItem(_) => return,
697 Annotatable::ImplItem(_) => return,
698 Annotatable::ForeignItem(_) => return,
699 Annotatable::Stmt(_) |
700 Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
701 Annotatable::Stmt(_) => ("statements", sym::proc_macro_hygiene),
702 Annotatable::Expr(_) => ("expressions", sym::proc_macro_hygiene),
704 | Annotatable::Field(..)
705 | Annotatable::FieldPat(..)
706 | Annotatable::GenericParam(..)
707 | Annotatable::Param(..)
708 | Annotatable::StructField(..)
709 | Annotatable::Variant(..)
710 => panic!("unexpected annotatable"),
717 &format!("custom attributes cannot be applied to {}", kind),
721 fn gate_proc_macro_expansion(&self, span: Span, fragment: &AstFragment) {
722 if self.cx.ecfg.proc_macro_hygiene() {
726 fragment.visit_with(&mut DisallowMacros {
728 parse_sess: self.cx.parse_sess,
731 struct DisallowMacros<'a> {
733 parse_sess: &'a ParseSess,
736 impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
737 fn visit_item(&mut self, i: &'ast ast::Item) {
738 if let ast::ItemKind::MacroDef(_) = i.kind {
741 sym::proc_macro_hygiene,
744 "procedural macros cannot expand to macro definitions",
747 visit::walk_item(self, i);
750 fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
756 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
757 let kind = match kind {
758 AstFragmentKind::Expr |
759 AstFragmentKind::OptExpr => "expressions",
760 AstFragmentKind::Pat => "patterns",
761 AstFragmentKind::Stmts => "statements",
762 AstFragmentKind::Ty |
763 AstFragmentKind::Items |
764 AstFragmentKind::TraitItems |
765 AstFragmentKind::ImplItems |
766 AstFragmentKind::ForeignItems => return,
767 AstFragmentKind::Arms
768 | AstFragmentKind::Fields
769 | AstFragmentKind::FieldPats
770 | AstFragmentKind::GenericParams
771 | AstFragmentKind::Params
772 | AstFragmentKind::StructFields
773 | AstFragmentKind::Variants
774 => panic!("unexpected AST fragment kind"),
776 if self.cx.ecfg.proc_macro_hygiene() {
781 sym::proc_macro_hygiene,
784 &format!("procedural macros cannot be expanded to {}", kind),
788 fn parse_ast_fragment(
791 kind: AstFragmentKind,
795 let mut parser = self.cx.new_parser_from_tts(toks);
796 match parser.parse_ast_fragment(kind, false) {
798 parser.ensure_complete_parse(path, kind.name(), span);
803 annotate_err_with_kind(&mut err, kind, span);
805 self.cx.trace_macros_diag();
812 impl<'a> Parser<'a> {
813 pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
814 -> PResult<'a, AstFragment> {
816 AstFragmentKind::Items => {
817 let mut items = SmallVec::new();
818 while let Some(item) = self.parse_item()? {
821 AstFragment::Items(items)
823 AstFragmentKind::TraitItems => {
824 let mut items = SmallVec::new();
825 while self.token != token::Eof {
826 items.push(self.parse_trait_item(&mut false)?);
828 AstFragment::TraitItems(items)
830 AstFragmentKind::ImplItems => {
831 let mut items = SmallVec::new();
832 while self.token != token::Eof {
833 items.push(self.parse_impl_item(&mut false)?);
835 AstFragment::ImplItems(items)
837 AstFragmentKind::ForeignItems => {
838 let mut items = SmallVec::new();
839 while self.token != token::Eof {
840 items.push(self.parse_foreign_item(DUMMY_SP)?);
842 AstFragment::ForeignItems(items)
844 AstFragmentKind::Stmts => {
845 let mut stmts = SmallVec::new();
846 while self.token != token::Eof &&
847 // won't make progress on a `}`
848 self.token != token::CloseDelim(token::Brace) {
849 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
853 AstFragment::Stmts(stmts)
855 AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
856 AstFragmentKind::OptExpr => {
857 if self.token != token::Eof {
858 AstFragment::OptExpr(Some(self.parse_expr()?))
860 AstFragment::OptExpr(None)
863 AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
864 AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat(None)?),
865 AstFragmentKind::Arms
866 | AstFragmentKind::Fields
867 | AstFragmentKind::FieldPats
868 | AstFragmentKind::GenericParams
869 | AstFragmentKind::Params
870 | AstFragmentKind::StructFields
871 | AstFragmentKind::Variants
872 => panic!("unexpected AST fragment kind"),
876 pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
877 if self.token != token::Eof {
878 let msg = format!("macro expansion ignores token `{}` and any following",
879 self.this_token_to_string());
880 // Avoid emitting backtrace info twice.
881 let def_site_span = self.token.span.with_ctxt(SyntaxContext::root());
882 let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
883 err.span_label(span, "caused by the macro expansion here");
885 "the usage of `{}!` is likely invalid in {} context",
886 pprust::path_to_string(¯o_path),
890 let semi_span = self.sess.source_map().next_point(span);
892 let semi_full_span = semi_span.to(self.sess.source_map().next_point(semi_span));
893 match self.sess.source_map().span_to_snippet(semi_full_span) {
894 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
897 "you might be missing a semicolon here",
899 Applicability::MaybeIncorrect,
909 struct InvocationCollector<'a, 'b> {
910 cx: &'a mut ExtCtxt<'b>,
911 cfg: StripUnconfigured<'a>,
912 invocations: Vec<Invocation>,
916 impl<'a, 'b> InvocationCollector<'a, 'b> {
917 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
918 // Expansion data for all the collected invocations is set upon their resolution,
919 // with exception of the derive container case which is not resolved and can get
920 // its expansion data immediately.
921 let expn_data = match &kind {
922 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
923 parent: self.cx.current_expansion.id,
925 ExpnKind::Macro(MacroKind::Attr, sym::derive),
926 item.span(), self.cx.parse_sess.edition,
931 let expn_id = ExpnId::fresh(expn_data);
932 self.invocations.push(Invocation {
935 expansion_data: ExpansionData {
937 depth: self.cx.current_expansion.depth + 1,
938 ..self.cx.current_expansion.clone()
941 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
944 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
945 self.collect(kind, InvocationKind::Bang { mac, span })
948 fn collect_attr(&mut self,
949 attr: Option<ast::Attribute>,
952 kind: AstFragmentKind,
955 self.collect(kind, match attr {
956 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
957 None => InvocationKind::DeriveContainer { derives, item },
961 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
962 -> Option<ast::Attribute> {
963 let attr = attrs.iter()
965 if a.path == sym::derive {
966 *after_derive = true;
968 !attr::is_known(a) && !is_builtin_attr(a)
970 .map(|i| attrs.remove(i));
971 if let Some(attr) = &attr {
972 if !self.cx.ecfg.custom_inner_attributes() &&
973 attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
974 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
975 attr.span, GateIssue::Language,
976 "non-builtin inner attributes are unstable");
982 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
983 fn classify_item<T>(&mut self, item: &mut T)
984 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
987 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
989 item.visit_attrs(|mut attrs| {
990 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
991 traits = collect_derives(&mut self.cx, &mut attrs);
994 (attr, traits, after_derive)
997 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
998 /// to the unused-attributes lint (making it an error on statements and expressions
999 /// is a breaking change)
1000 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
1001 -> (Option<ast::Attribute>, /* after_derive */ bool) {
1002 let (mut attr, mut after_derive) = (None, false);
1004 nonitem.visit_attrs(|mut attrs| {
1005 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1008 (attr, after_derive)
1011 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1012 self.cfg.configure(node)
1015 // Detect use of feature-gated or invalid attributes on macro invocations
1016 // since they will not be detected after macro expansion.
1017 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1018 let features = self.cx.ecfg.features.unwrap();
1019 for attr in attrs.iter() {
1020 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1022 // macros are expanded before any lint passes so this warning has to be hardcoded
1023 if attr.path == sym::derive {
1024 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1025 .note("this may become a hard error in a future release")
1032 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1033 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1034 self.cfg.configure_expr(expr);
1035 visit_clobber(expr.deref_mut(), |mut expr| {
1036 self.cfg.configure_expr_kind(&mut expr.kind);
1038 // ignore derives so they remain unused
1039 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1042 // Collect the invoc regardless of whether or not attributes are permitted here
1043 // expansion will eat the attribute so it won't error later.
1044 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1046 // AstFragmentKind::Expr requires the macro to emit an expression.
1047 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1048 AstFragmentKind::Expr, after_derive)
1053 if let ast::ExprKind::Mac(mac) = expr.kind {
1054 self.check_attributes(&expr.attrs);
1055 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1059 noop_visit_expr(&mut expr, self);
1065 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1066 let mut arm = configure!(self, arm);
1068 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1069 if attr.is_some() || !traits.is_empty() {
1070 return self.collect_attr(attr, traits, Annotatable::Arm(arm),
1071 AstFragmentKind::Arms, after_derive)
1075 noop_flat_map_arm(arm, self)
1078 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1079 let mut field = configure!(self, field);
1081 let (attr, traits, after_derive) = self.classify_item(&mut field);
1082 if attr.is_some() || !traits.is_empty() {
1083 return self.collect_attr(attr, traits, Annotatable::Field(field),
1084 AstFragmentKind::Fields, after_derive)
1088 noop_flat_map_field(field, self)
1091 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1092 let mut fp = configure!(self, fp);
1094 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1095 if attr.is_some() || !traits.is_empty() {
1096 return self.collect_attr(attr, traits, Annotatable::FieldPat(fp),
1097 AstFragmentKind::FieldPats, after_derive)
1098 .make_field_patterns();
1101 noop_flat_map_field_pattern(fp, self)
1104 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1105 let mut p = configure!(self, p);
1107 let (attr, traits, after_derive) = self.classify_item(&mut p);
1108 if attr.is_some() || !traits.is_empty() {
1109 return self.collect_attr(attr, traits, Annotatable::Param(p),
1110 AstFragmentKind::Params, after_derive)
1114 noop_flat_map_param(p, self)
1117 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1118 let mut sf = configure!(self, sf);
1120 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1121 if attr.is_some() || !traits.is_empty() {
1122 return self.collect_attr(attr, traits, Annotatable::StructField(sf),
1123 AstFragmentKind::StructFields, after_derive)
1124 .make_struct_fields();
1127 noop_flat_map_struct_field(sf, self)
1130 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1131 let mut variant = configure!(self, variant);
1133 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1134 if attr.is_some() || !traits.is_empty() {
1135 return self.collect_attr(attr, traits, Annotatable::Variant(variant),
1136 AstFragmentKind::Variants, after_derive)
1140 noop_flat_map_variant(variant, self)
1143 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1144 let expr = configure!(self, expr);
1145 expr.filter_map(|mut expr| {
1146 self.cfg.configure_expr_kind(&mut expr.kind);
1148 // Ignore derives so they remain unused.
1149 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1152 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1154 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1155 AstFragmentKind::OptExpr, after_derive)
1157 .map(|expr| expr.into_inner())
1160 if let ast::ExprKind::Mac(mac) = expr.kind {
1161 self.check_attributes(&expr.attrs);
1162 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1164 .map(|expr| expr.into_inner())
1166 Some({ noop_visit_expr(&mut expr, self); expr })
1171 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1172 self.cfg.configure_pat(pat);
1174 PatKind::Mac(_) => {}
1175 _ => return noop_visit_pat(pat, self),
1178 visit_clobber(pat, |mut pat| {
1179 match mem::replace(&mut pat.kind, PatKind::Wild) {
1180 PatKind::Mac(mac) =>
1181 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1182 _ => unreachable!(),
1187 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1188 let mut stmt = configure!(self, stmt);
1190 // we'll expand attributes on expressions separately
1191 if !stmt.is_expr() {
1192 let (attr, derives, after_derive) = if stmt.is_item() {
1193 self.classify_item(&mut stmt)
1195 // ignore derives on non-item statements so it falls through
1196 // to the unused-attributes lint
1197 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1198 (attr, vec![], after_derive)
1201 if attr.is_some() || !derives.is_empty() {
1202 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1203 AstFragmentKind::Stmts, after_derive).make_stmts();
1207 if let StmtKind::Mac(mac) = stmt.kind {
1208 let (mac, style, attrs) = mac.into_inner();
1209 self.check_attributes(&attrs);
1210 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1213 // If this is a macro invocation with a semicolon, then apply that
1214 // semicolon to the final statement produced by expansion.
1215 if style == MacStmtStyle::Semicolon {
1216 if let Some(stmt) = placeholder.pop() {
1217 placeholder.push(stmt.add_trailing_semicolon());
1224 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1225 let ast::Stmt { id, kind, span } = stmt;
1226 noop_flat_map_stmt_kind(kind, self).into_iter().map(|kind| {
1227 ast::Stmt { id, kind, span }
1232 fn visit_block(&mut self, block: &mut P<Block>) {
1233 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1234 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1235 noop_visit_block(block, self);
1236 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1239 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1240 let mut item = configure!(self, item);
1242 let (attr, traits, after_derive) = self.classify_item(&mut item);
1243 if attr.is_some() || !traits.is_empty() {
1244 return self.collect_attr(attr, traits, Annotatable::Item(item),
1245 AstFragmentKind::Items, after_derive).make_items();
1249 ast::ItemKind::Mac(..) => {
1250 self.check_attributes(&item.attrs);
1251 item.and_then(|item| match item.kind {
1252 ItemKind::Mac(mac) => self.collect(
1253 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1255 _ => unreachable!(),
1258 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1259 if item.ident == Ident::invalid() {
1260 return noop_flat_map_item(item, self);
1263 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1264 let mut module = (*self.cx.current_expansion.module).clone();
1265 module.mod_path.push(item.ident);
1267 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1268 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1269 // Thus, if `inner` is the dummy span, we know the module is inline.
1270 let inline_module = item.span.contains(inner) || inner.is_dummy();
1273 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1274 self.cx.current_expansion.directory_ownership =
1275 DirectoryOwnership::Owned { relative: None };
1276 module.directory.push(&*path.as_str());
1278 module.directory.push(&*item.ident.as_str());
1281 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1282 let mut path = match path {
1283 FileName::Real(path) => path,
1284 other => PathBuf::from(other.to_string()),
1286 let directory_ownership = match path.file_name().unwrap().to_str() {
1287 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1288 Some(_) => DirectoryOwnership::Owned {
1289 relative: Some(item.ident),
1291 None => DirectoryOwnership::UnownedViaMod(false),
1294 module.directory = path;
1295 self.cx.current_expansion.directory_ownership = directory_ownership;
1299 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1300 let result = noop_flat_map_item(item, self);
1301 self.cx.current_expansion.module = orig_module;
1302 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1306 _ => noop_flat_map_item(item, self),
1310 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1311 let mut item = configure!(self, item);
1313 let (attr, traits, after_derive) = self.classify_item(&mut item);
1314 if attr.is_some() || !traits.is_empty() {
1315 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1316 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1320 ast::TraitItemKind::Macro(mac) => {
1321 let ast::TraitItem { attrs, span, .. } = item;
1322 self.check_attributes(&attrs);
1323 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1325 _ => noop_flat_map_trait_item(item, self),
1329 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1330 let mut item = configure!(self, item);
1332 let (attr, traits, after_derive) = self.classify_item(&mut item);
1333 if attr.is_some() || !traits.is_empty() {
1334 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1335 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1339 ast::ImplItemKind::Macro(mac) => {
1340 let ast::ImplItem { attrs, span, .. } = item;
1341 self.check_attributes(&attrs);
1342 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1344 _ => noop_flat_map_impl_item(item, self),
1348 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1350 ast::TyKind::Mac(_) => {}
1351 _ => return noop_visit_ty(ty, self),
1354 visit_clobber(ty, |mut ty| {
1355 match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1356 ast::TyKind::Mac(mac) =>
1357 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1358 _ => unreachable!(),
1363 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1364 self.cfg.configure_foreign_mod(foreign_mod);
1365 noop_visit_foreign_mod(foreign_mod, self);
1368 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1369 -> SmallVec<[ast::ForeignItem; 1]>
1371 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1373 if attr.is_some() || !traits.is_empty() {
1374 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1375 AstFragmentKind::ForeignItems, after_derive)
1376 .make_foreign_items();
1379 if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind {
1380 self.check_attributes(&foreign_item.attrs);
1381 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1382 .make_foreign_items();
1385 noop_flat_map_foreign_item(foreign_item, self)
1388 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1390 ast::ItemKind::MacroDef(..) => {}
1392 self.cfg.configure_item_kind(item);
1393 noop_visit_item_kind(item, self);
1398 fn flat_map_generic_param(
1400 param: ast::GenericParam
1401 ) -> SmallVec<[ast::GenericParam; 1]>
1403 let mut param = configure!(self, param);
1405 let (attr, traits, after_derive) = self.classify_item(&mut param);
1406 if attr.is_some() || !traits.is_empty() {
1407 return self.collect_attr(attr, traits, Annotatable::GenericParam(param),
1408 AstFragmentKind::GenericParams, after_derive)
1409 .make_generic_params();
1412 noop_flat_map_generic_param(param, self)
1415 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1416 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1417 // contents="file contents")]` attributes
1418 if !at.check_name(sym::doc) {
1419 return noop_visit_attribute(at, self);
1422 if let Some(list) = at.meta_item_list() {
1423 if !list.iter().any(|it| it.check_name(sym::include)) {
1424 return noop_visit_attribute(at, self);
1427 let mut items = vec![];
1429 for mut it in list {
1430 if !it.check_name(sym::include) {
1431 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1435 if let Some(file) = it.value_str() {
1436 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1437 self.check_attributes(slice::from_ref(at));
1438 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1439 // avoid loading the file if they haven't enabled the feature
1440 return noop_visit_attribute(at, self);
1443 let filename = self.cx.resolve_path(&*file.as_str(), it.span());
1444 match self.cx.source_map().load_file(&filename) {
1445 Ok(source_file) => {
1446 let src = source_file.src.as_ref()
1447 .expect("freshly loaded file should have a source");
1448 let src_interned = Symbol::intern(src.as_str());
1450 let include_info = vec![
1451 ast::NestedMetaItem::MetaItem(
1452 attr::mk_name_value_item_str(
1453 Ident::with_dummy_span(sym::file),
1458 ast::NestedMetaItem::MetaItem(
1459 attr::mk_name_value_item_str(
1460 Ident::with_dummy_span(sym::contents),
1467 let include_ident = Ident::with_dummy_span(sym::include);
1468 let item = attr::mk_list_item(include_ident, include_info);
1469 items.push(ast::NestedMetaItem::MetaItem(item));
1474 .and_then(|item| item.name_value_literal())
1477 if e.kind() == ErrorKind::InvalidData {
1481 &format!("{} wasn't a utf-8 file", filename.display()),
1483 .span_label(lit.span, "contains invalid utf-8")
1486 let mut err = self.cx.struct_span_err(
1488 &format!("couldn't read {}: {}", filename.display(), e),
1490 err.span_label(lit.span, "couldn't read file");
1497 let mut err = self.cx.struct_span_err(
1499 &format!("expected path to external documentation"),
1502 // Check if the user erroneously used `doc(include(...))` syntax.
1503 let literal = it.meta_item_list().and_then(|list| {
1504 if list.len() == 1 {
1505 list[0].literal().map(|literal| &literal.kind)
1511 let (path, applicability) = match &literal {
1512 Some(LitKind::Str(path, ..)) => {
1513 (path.to_string(), Applicability::MachineApplicable)
1515 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1518 err.span_suggestion(
1520 "provide a file path with `=`",
1521 format!("include = \"{}\"", path),
1529 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1530 *at = attr::Attribute {
1531 item: AttrItem { path: meta.path, tokens: meta.kind.tokens(meta.span) },
1535 is_sugared_doc: false,
1538 noop_visit_attribute(at, self)
1542 fn visit_id(&mut self, id: &mut ast::NodeId) {
1544 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1545 *id = self.cx.resolver.next_node_id()
1549 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1550 self.cfg.configure_fn_decl(&mut fn_decl);
1551 noop_visit_fn_decl(fn_decl, self);
1555 pub struct ExpansionConfig<'feat> {
1556 pub crate_name: String,
1557 pub features: Option<&'feat Features>,
1558 pub recursion_limit: usize,
1559 pub trace_mac: bool,
1560 pub should_test: bool, // If false, strip `#[test]` nodes
1561 pub single_step: bool,
1562 pub keep_macs: bool,
1565 impl<'feat> ExpansionConfig<'feat> {
1566 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1570 recursion_limit: 1024,
1578 fn proc_macro_hygiene(&self) -> bool {
1579 self.features.map_or(false, |features| features.proc_macro_hygiene)
1581 fn custom_inner_attributes(&self) -> bool {
1582 self.features.map_or(false, |features| features.custom_inner_attributes)