2 use crate::proc_macro::{collect_derives, MarkAttrs};
3 use crate::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
4 use crate::mbe::macro_rules::annotate_err_with_kind;
5 use crate::placeholders::{placeholder, PlaceholderExpander};
7 use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
8 use syntax::ast::{MacStmtStyle, StmtKind, ItemKind};
9 use syntax::attr::{self, HasAttrs};
10 use syntax::source_map::respan;
11 use syntax::configure;
12 use syntax::config::StripUnconfigured;
13 use syntax::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
14 use syntax::mut_visit::*;
15 use syntax::parse::{DirectoryOwnership, PResult};
16 use syntax::parse::token;
17 use syntax::parse::parser::Parser;
18 use syntax::print::pprust;
20 use syntax::sess::ParseSess;
21 use syntax::symbol::{sym, Symbol};
22 use syntax::tokenstream::{TokenStream, TokenTree};
23 use syntax::visit::{self, Visitor};
24 use syntax::util::map_in_place::MapInPlace;
26 use errors::{Applicability, FatalError};
27 use smallvec::{smallvec, SmallVec};
28 use syntax_pos::{Span, DUMMY_SP, FileName};
30 use rustc_data_structures::sync::Lrc;
31 use std::io::ErrorKind;
32 use std::{iter, mem, slice};
33 use std::ops::DerefMut;
35 use std::path::PathBuf;
37 macro_rules! ast_fragments {
39 $($Kind:ident($AstTy:ty) {
41 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
42 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
46 /// A fragment of AST that can be produced by a single macro expansion.
47 /// Can also serve as an input and intermediate result for macro expansion operations.
48 pub enum AstFragment {
49 OptExpr(Option<P<ast::Expr>>),
53 /// "Discriminant" of an AST fragment.
54 #[derive(Copy, Clone, PartialEq, Eq)]
55 pub enum AstFragmentKind {
60 impl AstFragmentKind {
61 pub fn name(self) -> &'static str {
63 AstFragmentKind::OptExpr => "expression",
64 $(AstFragmentKind::$Kind => $kind_name,)*
68 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
70 AstFragmentKind::OptExpr =>
71 result.make_expr().map(Some).map(AstFragment::OptExpr),
72 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
78 pub fn add_placeholders(&mut self, placeholders: &[NodeId]) {
79 if placeholders.is_empty() {
83 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
84 // We are repeating through arguments with `many`, to do that we have to
85 // mention some macro variable from those arguments even if it's not used.
86 #[cfg_attr(bootstrap, allow(unused_macros))]
87 macro _repeating($flat_map_ast_elt) {}
88 placeholder(AstFragmentKind::$Kind, *id).$make_ast()
90 _ => panic!("unexpected AST fragment kind")
94 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
96 AstFragment::OptExpr(expr) => expr,
97 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
101 $(pub fn $make_ast(self) -> $AstTy {
103 AstFragment::$Kind(ast) => ast,
104 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
108 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
110 AstFragment::OptExpr(opt_expr) => {
111 visit_clobber(opt_expr, |opt_expr| {
112 if let Some(expr) = opt_expr {
113 vis.filter_map_expr(expr)
119 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
120 $($(AstFragment::$Kind(ast) =>
121 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
125 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
127 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
128 AstFragment::OptExpr(None) => {}
129 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
130 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
131 visitor.$visit_ast_elt(ast_elt);
137 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
138 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
140 Some(self.make(AstFragmentKind::$Kind).$make_ast())
147 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
148 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
149 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
150 Stmts(SmallVec<[ast::Stmt; 1]>) {
151 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
153 Items(SmallVec<[P<ast::Item>; 1]>) {
154 "item"; many fn flat_map_item; fn visit_item; fn make_items;
156 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
157 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
159 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
160 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
162 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
164 many fn flat_map_foreign_item;
165 fn visit_foreign_item;
166 fn make_foreign_items;
168 Arms(SmallVec<[ast::Arm; 1]>) {
169 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
171 Fields(SmallVec<[ast::Field; 1]>) {
172 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
174 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
176 many fn flat_map_field_pattern;
177 fn visit_field_pattern;
178 fn make_field_patterns;
180 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
182 many fn flat_map_generic_param;
183 fn visit_generic_param;
184 fn make_generic_params;
186 Params(SmallVec<[ast::Param; 1]>) {
187 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
189 StructFields(SmallVec<[ast::StructField; 1]>) {
191 many fn flat_map_struct_field;
192 fn visit_struct_field;
193 fn make_struct_fields;
195 Variants(SmallVec<[ast::Variant; 1]>) {
196 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
200 impl AstFragmentKind {
201 fn dummy(self, span: Span) -> AstFragment {
202 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
205 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
207 let mut items = items.into_iter();
209 AstFragmentKind::Arms =>
210 AstFragment::Arms(items.map(Annotatable::expect_arm).collect()),
211 AstFragmentKind::Fields =>
212 AstFragment::Fields(items.map(Annotatable::expect_field).collect()),
213 AstFragmentKind::FieldPats =>
214 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()),
215 AstFragmentKind::GenericParams =>
216 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()),
217 AstFragmentKind::Params =>
218 AstFragment::Params(items.map(Annotatable::expect_param).collect()),
219 AstFragmentKind::StructFields => AstFragment::StructFields(
220 items.map(Annotatable::expect_struct_field).collect()
222 AstFragmentKind::Variants =>
223 AstFragment::Variants(items.map(Annotatable::expect_variant).collect()),
224 AstFragmentKind::Items =>
225 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
226 AstFragmentKind::ImplItems =>
227 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
228 AstFragmentKind::TraitItems =>
229 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
230 AstFragmentKind::ForeignItems =>
231 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
232 AstFragmentKind::Stmts =>
233 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
234 AstFragmentKind::Expr => AstFragment::Expr(
235 items.next().expect("expected exactly one expression").expect_expr()
237 AstFragmentKind::OptExpr =>
238 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
239 AstFragmentKind::Pat | AstFragmentKind::Ty =>
240 panic!("patterns and types aren't annotatable"),
245 pub struct Invocation {
246 pub kind: InvocationKind,
247 pub fragment_kind: AstFragmentKind,
248 pub expansion_data: ExpansionData,
251 pub enum InvocationKind {
257 attr: ast::Attribute,
259 // Required for resolving derive helper attributes.
261 // We temporarily report errors for attribute macros placed after derives
268 /// "Invocation" that contains all derives from an item,
269 /// broken into multiple `Derive` invocations when expanded.
270 /// FIXME: Find a way to remove it.
278 pub fn span(&self) -> Span {
280 InvocationKind::Bang { span, .. } => *span,
281 InvocationKind::Attr { attr, .. } => attr.span,
282 InvocationKind::Derive { path, .. } => path.span,
283 InvocationKind::DeriveContainer { item, .. } => item.span(),
288 pub struct MacroExpander<'a, 'b> {
289 pub cx: &'a mut ExtCtxt<'b>,
290 monotonic: bool, // cf. `cx.monotonic_expander()`
293 impl<'a, 'b> MacroExpander<'a, 'b> {
294 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
295 MacroExpander { cx, monotonic }
298 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
299 let mut module = ModuleData {
300 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
301 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
302 FileName::Real(path) => path,
303 other => PathBuf::from(other.to_string()),
306 module.directory.pop();
307 self.cx.root_path = module.directory.clone();
308 self.cx.current_expansion.module = Rc::new(module);
310 let orig_mod_span = krate.module.inner;
312 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
315 kind: ast::ItemKind::Mod(krate.module),
316 ident: Ident::invalid(),
317 id: ast::DUMMY_NODE_ID,
318 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
322 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
323 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
325 krate.module = module;
328 // Resolution failed so we return an empty expansion
329 krate.attrs = vec![];
330 krate.module = ast::Mod {
331 inner: orig_mod_span,
338 self.cx.trace_macros_diag();
342 // Recursively expand all macro invocations in this AST fragment.
343 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
344 let orig_expansion_data = self.cx.current_expansion.clone();
345 self.cx.current_expansion.depth = 0;
347 // Collect all macro invocations and replace them with placeholders.
348 let (mut fragment_with_placeholders, mut invocations)
349 = self.collect_invocations(input_fragment, &[]);
351 // Optimization: if we resolve all imports now,
352 // we'll be able to immediately resolve most of imported macros.
353 self.resolve_imports();
355 // Resolve paths in all invocations and produce output expanded fragments for them, but
356 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
357 // The output fragments also go through expansion recursively until no invocations are left.
358 // Unresolved macros produce dummy outputs as a recovery measure.
359 invocations.reverse();
360 let mut expanded_fragments = Vec::new();
361 let mut undetermined_invocations = Vec::new();
362 let (mut progress, mut force) = (false, !self.monotonic);
364 let invoc = if let Some(invoc) = invocations.pop() {
367 self.resolve_imports();
368 if undetermined_invocations.is_empty() { break }
369 invocations = mem::take(&mut undetermined_invocations);
370 force = !mem::replace(&mut progress, false);
374 let eager_expansion_root =
375 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
376 let res = match self.cx.resolver.resolve_macro_invocation(
377 &invoc, eager_expansion_root, force
380 Err(Indeterminate) => {
381 undetermined_invocations.push(invoc);
387 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
388 self.cx.current_expansion = invoc.expansion_data.clone();
390 // FIXME(jseyfried): Refactor out the following logic
391 let (expanded_fragment, new_invocations) = match res {
392 InvocationRes::Single(ext) => {
393 let fragment = self.expand_invoc(invoc, &ext.kind);
394 self.collect_invocations(fragment, &[])
396 InvocationRes::DeriveContainer(exts) => {
397 let (derives, item) = match invoc.kind {
398 InvocationKind::DeriveContainer { derives, item } => (derives, item),
401 if !item.derive_allowed() {
402 let attr = attr::find_by_name(item.attrs(), sym::derive)
403 .expect("`derive` attribute should exist");
404 let span = attr.span;
405 let mut err = self.cx.struct_span_err(span,
406 "`derive` may only be applied to structs, enums and unions");
407 if let ast::AttrStyle::Inner = attr.style {
408 let trait_list = derives.iter()
409 .map(|t| pprust::path_to_string(t))
410 .collect::<Vec<_>>();
411 let suggestion = format!("#[derive({})]", trait_list.join(", "));
413 span, "try an outer attribute", suggestion,
414 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
415 Applicability::MaybeIncorrect
421 let mut item = self.fully_configure(item);
422 item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
423 let mut helper_attrs = Vec::new();
424 let mut has_copy = false;
426 helper_attrs.extend(&ext.helper_attrs);
427 has_copy |= ext.is_derive_copy;
429 // Mark derive helpers inside this item as known and used.
430 // FIXME: This is a hack, derive helpers should be integrated with regular name
431 // resolution instead. For example, helpers introduced by a derive container
432 // can be in scope for all code produced by that container's expansion.
433 item.visit_with(&mut MarkAttrs(&helper_attrs));
435 self.cx.resolver.add_derive_copy(invoc.expansion_data.id);
438 let mut derive_placeholders = Vec::with_capacity(derives.len());
439 invocations.reserve(derives.len());
440 for path in derives {
441 let expn_id = ExpnId::fresh(None);
442 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
443 invocations.push(Invocation {
444 kind: InvocationKind::Derive { path, item: item.clone() },
445 fragment_kind: invoc.fragment_kind,
446 expansion_data: ExpansionData {
448 ..invoc.expansion_data.clone()
452 let fragment = invoc.fragment_kind
453 .expect_from_annotatables(::std::iter::once(item));
454 self.collect_invocations(fragment, &derive_placeholders)
458 if expanded_fragments.len() < depth {
459 expanded_fragments.push(Vec::new());
461 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
462 if !self.cx.ecfg.single_step {
463 invocations.extend(new_invocations.into_iter().rev());
467 self.cx.current_expansion = orig_expansion_data;
469 // Finally incorporate all the expanded macros into the input AST fragment.
470 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
471 while let Some(expanded_fragments) = expanded_fragments.pop() {
472 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
473 placeholder_expander.add(NodeId::placeholder_from_expn_id(expn_id),
477 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
478 fragment_with_placeholders
481 fn resolve_imports(&mut self) {
483 self.cx.resolver.resolve_imports();
487 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
488 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
489 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
490 /// prepares data for resolving paths of macro invocations.
491 fn collect_invocations(&mut self, mut fragment: AstFragment, extra_placeholders: &[NodeId])
492 -> (AstFragment, Vec<Invocation>) {
493 // Resolve `$crate`s in the fragment for pretty-printing.
494 self.cx.resolver.resolve_dollar_crates();
497 let mut collector = InvocationCollector {
498 cfg: StripUnconfigured {
499 sess: self.cx.parse_sess,
500 features: self.cx.ecfg.features,
503 invocations: Vec::new(),
504 monotonic: self.monotonic,
506 fragment.mut_visit_with(&mut collector);
507 fragment.add_placeholders(extra_placeholders);
508 collector.invocations
512 self.cx.resolver.visit_ast_fragment_with_placeholders(
513 self.cx.current_expansion.id, &fragment
517 (fragment, invocations)
520 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
521 let mut cfg = StripUnconfigured {
522 sess: self.cx.parse_sess,
523 features: self.cx.ecfg.features,
525 // Since the item itself has already been configured by the InvocationCollector,
526 // we know that fold result vector will contain exactly one element
528 Annotatable::Item(item) => {
529 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
531 Annotatable::TraitItem(item) => {
532 Annotatable::TraitItem(
533 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
535 Annotatable::ImplItem(item) => {
536 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
538 Annotatable::ForeignItem(item) => {
539 Annotatable::ForeignItem(
540 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
543 Annotatable::Stmt(stmt) => {
544 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
546 Annotatable::Expr(mut expr) => {
547 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
549 Annotatable::Arm(arm) => {
550 Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap())
552 Annotatable::Field(field) => {
553 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
555 Annotatable::FieldPat(fp) => {
556 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
558 Annotatable::GenericParam(param) => {
559 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
561 Annotatable::Param(param) => {
562 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
564 Annotatable::StructField(sf) => {
565 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
567 Annotatable::Variant(v) => {
568 Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap())
573 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
574 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
575 let expn_data = self.cx.current_expansion.id.expn_data();
576 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
577 let mut err = self.cx.struct_span_err(expn_data.call_site,
578 &format!("recursion limit reached while expanding the macro `{}`",
579 expn_data.kind.descr()));
581 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
584 self.cx.trace_macros_diag();
588 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
590 InvocationKind::Bang { mac, .. } => match ext {
591 SyntaxExtensionKind::Bang(expander) => {
592 self.gate_proc_macro_expansion_kind(span, fragment_kind);
593 let tok_result = expander.expand(self.cx, span, mac.stream());
594 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
596 SyntaxExtensionKind::LegacyBang(expander) => {
597 let prev = self.cx.current_expansion.prior_type_ascription;
598 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
599 let tok_result = expander.expand(self.cx, span, mac.stream());
600 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
604 "non-{kind} macro in {kind} position: {path}",
605 kind = fragment_kind.name(),
606 path = pprust::path_to_string(&mac.path),
608 self.cx.span_err(span, &msg);
609 self.cx.trace_macros_diag();
610 fragment_kind.dummy(span)
612 self.cx.current_expansion.prior_type_ascription = prev;
617 InvocationKind::Attr { attr, mut item, .. } => match ext {
618 SyntaxExtensionKind::Attr(expander) => {
619 self.gate_proc_macro_input(&item);
620 self.gate_proc_macro_attr_item(span, &item);
621 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
622 Annotatable::Item(item) => token::NtItem(item),
623 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
624 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
625 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
626 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
627 Annotatable::Expr(expr) => token::NtExpr(expr),
629 | Annotatable::Field(..)
630 | Annotatable::FieldPat(..)
631 | Annotatable::GenericParam(..)
632 | Annotatable::Param(..)
633 | Annotatable::StructField(..)
634 | Annotatable::Variant(..)
635 => panic!("unexpected annotatable"),
636 })), DUMMY_SP).into();
637 let input = self.extract_proc_macro_attr_input(attr.item.tokens, span);
638 let tok_result = expander.expand(self.cx, span, input, item_tok);
639 self.parse_ast_fragment(tok_result, fragment_kind, &attr.item.path, span)
641 SyntaxExtensionKind::LegacyAttr(expander) => {
642 match attr.parse_meta(self.cx.parse_sess) {
644 let item = expander.expand(self.cx, span, &meta, item);
645 fragment_kind.expect_from_annotatables(item)
649 fragment_kind.dummy(span)
653 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
654 attr::mark_known(&attr);
656 attr::mark_used(&attr);
658 item.visit_attrs(|attrs| attrs.push(attr));
659 fragment_kind.expect_from_annotatables(iter::once(item))
663 InvocationKind::Derive { path, item } => match ext {
664 SyntaxExtensionKind::Derive(expander) |
665 SyntaxExtensionKind::LegacyDerive(expander) => {
666 if !item.derive_allowed() {
667 return fragment_kind.dummy(span);
669 if let SyntaxExtensionKind::Derive(..) = ext {
670 self.gate_proc_macro_input(&item);
672 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
673 let items = expander.expand(self.cx, span, &meta, item);
674 fragment_kind.expect_from_annotatables(items)
678 InvocationKind::DeriveContainer { .. } => unreachable!()
682 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
683 let mut trees = tokens.trees();
685 Some(TokenTree::Delimited(_, _, tts)) => {
686 if trees.next().is_none() {
690 Some(TokenTree::Token(..)) => {}
691 None => return TokenStream::default(),
693 self.cx.span_err(span, "custom attribute invocations must be \
694 of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
695 followed by a delimiter token");
696 TokenStream::default()
699 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
700 let kind = match item {
701 Annotatable::Item(item) => match &item.kind {
702 ItemKind::Mod(m) if m.inline => "modules",
705 Annotatable::TraitItem(_)
706 | Annotatable::ImplItem(_)
707 | Annotatable::ForeignItem(_) => return,
708 Annotatable::Stmt(_) => "statements",
709 Annotatable::Expr(_) => "expressions",
711 | Annotatable::Field(..)
712 | Annotatable::FieldPat(..)
713 | Annotatable::GenericParam(..)
714 | Annotatable::Param(..)
715 | Annotatable::StructField(..)
716 | Annotatable::Variant(..)
717 => panic!("unexpected annotatable"),
719 if self.cx.ecfg.proc_macro_hygiene() {
724 sym::proc_macro_hygiene,
727 &format!("custom attributes cannot be applied to {}", kind),
731 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
732 struct GateProcMacroInput<'a> {
733 parse_sess: &'a ParseSess,
736 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
737 fn visit_item(&mut self, item: &'ast ast::Item) {
739 ast::ItemKind::Mod(module) if !module.inline => {
742 sym::proc_macro_hygiene,
745 "non-inline modules in proc macro input are unstable",
751 visit::walk_item(self, item);
754 fn visit_mac(&mut self, _: &'ast ast::Mac) {}
757 if !self.cx.ecfg.proc_macro_hygiene() {
758 annotatable.visit_with(&mut GateProcMacroInput { parse_sess: self.cx.parse_sess });
762 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
763 let kind = match kind {
764 AstFragmentKind::Expr |
765 AstFragmentKind::OptExpr => "expressions",
766 AstFragmentKind::Pat => "patterns",
767 AstFragmentKind::Stmts => "statements",
768 AstFragmentKind::Ty |
769 AstFragmentKind::Items |
770 AstFragmentKind::TraitItems |
771 AstFragmentKind::ImplItems |
772 AstFragmentKind::ForeignItems => return,
773 AstFragmentKind::Arms
774 | AstFragmentKind::Fields
775 | AstFragmentKind::FieldPats
776 | AstFragmentKind::GenericParams
777 | AstFragmentKind::Params
778 | AstFragmentKind::StructFields
779 | AstFragmentKind::Variants
780 => panic!("unexpected AST fragment kind"),
782 if self.cx.ecfg.proc_macro_hygiene() {
787 sym::proc_macro_hygiene,
790 &format!("procedural macros cannot be expanded to {}", kind),
794 fn parse_ast_fragment(
797 kind: AstFragmentKind,
801 let mut parser = self.cx.new_parser_from_tts(toks);
802 match parse_ast_fragment(&mut parser, kind, false) {
804 ensure_complete_parse(&mut parser, path, kind.name(), span);
809 annotate_err_with_kind(&mut err, kind, span);
811 self.cx.trace_macros_diag();
818 pub fn parse_ast_fragment<'a>(
819 this: &mut Parser<'a>,
820 kind: AstFragmentKind,
821 macro_legacy_warnings: bool,
822 ) -> PResult<'a, AstFragment> {
824 AstFragmentKind::Items => {
825 let mut items = SmallVec::new();
826 while let Some(item) = this.parse_item()? {
829 AstFragment::Items(items)
831 AstFragmentKind::TraitItems => {
832 let mut items = SmallVec::new();
833 while this.token != token::Eof {
834 items.push(this.parse_trait_item(&mut false)?);
836 AstFragment::TraitItems(items)
838 AstFragmentKind::ImplItems => {
839 let mut items = SmallVec::new();
840 while this.token != token::Eof {
841 items.push(this.parse_impl_item(&mut false)?);
843 AstFragment::ImplItems(items)
845 AstFragmentKind::ForeignItems => {
846 let mut items = SmallVec::new();
847 while this.token != token::Eof {
848 items.push(this.parse_foreign_item(DUMMY_SP)?);
850 AstFragment::ForeignItems(items)
852 AstFragmentKind::Stmts => {
853 let mut stmts = SmallVec::new();
854 while this.token != token::Eof &&
855 // won't make progress on a `}`
856 this.token != token::CloseDelim(token::Brace) {
857 if let Some(stmt) = this.parse_full_stmt(macro_legacy_warnings)? {
861 AstFragment::Stmts(stmts)
863 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
864 AstFragmentKind::OptExpr => {
865 if this.token != token::Eof {
866 AstFragment::OptExpr(Some(this.parse_expr()?))
868 AstFragment::OptExpr(None)
871 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
872 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?),
873 AstFragmentKind::Arms
874 | AstFragmentKind::Fields
875 | AstFragmentKind::FieldPats
876 | AstFragmentKind::GenericParams
877 | AstFragmentKind::Params
878 | AstFragmentKind::StructFields
879 | AstFragmentKind::Variants
880 => panic!("unexpected AST fragment kind"),
884 pub fn ensure_complete_parse<'a>(
885 this: &mut Parser<'a>,
890 if this.token != token::Eof {
891 let msg = format!("macro expansion ignores token `{}` and any following",
892 this.this_token_to_string());
893 // Avoid emitting backtrace info twice.
894 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
895 let mut err = this.struct_span_err(def_site_span, &msg);
896 err.span_label(span, "caused by the macro expansion here");
898 "the usage of `{}!` is likely invalid in {} context",
899 pprust::path_to_string(macro_path),
903 let semi_span = this.sess.source_map().next_point(span);
905 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
906 match this.sess.source_map().span_to_snippet(semi_full_span) {
907 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
910 "you might be missing a semicolon here",
912 Applicability::MaybeIncorrect,
921 struct InvocationCollector<'a, 'b> {
922 cx: &'a mut ExtCtxt<'b>,
923 cfg: StripUnconfigured<'a>,
924 invocations: Vec<Invocation>,
928 impl<'a, 'b> InvocationCollector<'a, 'b> {
929 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
930 // Expansion data for all the collected invocations is set upon their resolution,
931 // with exception of the derive container case which is not resolved and can get
932 // its expansion data immediately.
933 let expn_data = match &kind {
934 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
935 parent: self.cx.current_expansion.id,
937 ExpnKind::Macro(MacroKind::Attr, sym::derive),
938 item.span(), self.cx.parse_sess.edition,
943 let expn_id = ExpnId::fresh(expn_data);
944 self.invocations.push(Invocation {
947 expansion_data: ExpansionData {
949 depth: self.cx.current_expansion.depth + 1,
950 ..self.cx.current_expansion.clone()
953 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
956 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
957 self.collect(kind, InvocationKind::Bang { mac, span })
960 fn collect_attr(&mut self,
961 attr: Option<ast::Attribute>,
964 kind: AstFragmentKind,
967 self.collect(kind, match attr {
968 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
969 None => InvocationKind::DeriveContainer { derives, item },
973 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
974 -> Option<ast::Attribute> {
975 let attr = attrs.iter()
977 if a.path == sym::derive {
978 *after_derive = true;
980 !attr::is_known(a) && !is_builtin_attr(a)
982 .map(|i| attrs.remove(i));
983 if let Some(attr) = &attr {
984 if !self.cx.ecfg.custom_inner_attributes() &&
985 attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
986 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
987 attr.span, GateIssue::Language,
988 "non-builtin inner attributes are unstable");
994 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
995 fn classify_item<T>(&mut self, item: &mut T)
996 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
999 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
1001 item.visit_attrs(|mut attrs| {
1002 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1003 traits = collect_derives(&mut self.cx, &mut attrs);
1006 (attr, traits, after_derive)
1009 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1010 /// to the unused-attributes lint (making it an error on statements and expressions
1011 /// is a breaking change)
1012 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
1013 -> (Option<ast::Attribute>, /* after_derive */ bool) {
1014 let (mut attr, mut after_derive) = (None, false);
1016 nonitem.visit_attrs(|mut attrs| {
1017 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1020 (attr, after_derive)
1023 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1024 self.cfg.configure(node)
1027 // Detect use of feature-gated or invalid attributes on macro invocations
1028 // since they will not be detected after macro expansion.
1029 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1030 let features = self.cx.ecfg.features.unwrap();
1031 for attr in attrs.iter() {
1032 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1034 // macros are expanded before any lint passes so this warning has to be hardcoded
1035 if attr.path == sym::derive {
1036 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1037 .note("this may become a hard error in a future release")
1044 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1045 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1046 self.cfg.configure_expr(expr);
1047 visit_clobber(expr.deref_mut(), |mut expr| {
1048 self.cfg.configure_expr_kind(&mut expr.kind);
1050 // ignore derives so they remain unused
1051 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1054 // Collect the invoc regardless of whether or not attributes are permitted here
1055 // expansion will eat the attribute so it won't error later.
1056 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1058 // AstFragmentKind::Expr requires the macro to emit an expression.
1059 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1060 AstFragmentKind::Expr, after_derive)
1065 if let ast::ExprKind::Mac(mac) = expr.kind {
1066 self.check_attributes(&expr.attrs);
1067 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1071 noop_visit_expr(&mut expr, self);
1077 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1078 let mut arm = configure!(self, arm);
1080 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1081 if attr.is_some() || !traits.is_empty() {
1082 return self.collect_attr(attr, traits, Annotatable::Arm(arm),
1083 AstFragmentKind::Arms, after_derive)
1087 noop_flat_map_arm(arm, self)
1090 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1091 let mut field = configure!(self, field);
1093 let (attr, traits, after_derive) = self.classify_item(&mut field);
1094 if attr.is_some() || !traits.is_empty() {
1095 return self.collect_attr(attr, traits, Annotatable::Field(field),
1096 AstFragmentKind::Fields, after_derive)
1100 noop_flat_map_field(field, self)
1103 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1104 let mut fp = configure!(self, fp);
1106 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1107 if attr.is_some() || !traits.is_empty() {
1108 return self.collect_attr(attr, traits, Annotatable::FieldPat(fp),
1109 AstFragmentKind::FieldPats, after_derive)
1110 .make_field_patterns();
1113 noop_flat_map_field_pattern(fp, self)
1116 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1117 let mut p = configure!(self, p);
1119 let (attr, traits, after_derive) = self.classify_item(&mut p);
1120 if attr.is_some() || !traits.is_empty() {
1121 return self.collect_attr(attr, traits, Annotatable::Param(p),
1122 AstFragmentKind::Params, after_derive)
1126 noop_flat_map_param(p, self)
1129 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1130 let mut sf = configure!(self, sf);
1132 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1133 if attr.is_some() || !traits.is_empty() {
1134 return self.collect_attr(attr, traits, Annotatable::StructField(sf),
1135 AstFragmentKind::StructFields, after_derive)
1136 .make_struct_fields();
1139 noop_flat_map_struct_field(sf, self)
1142 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1143 let mut variant = configure!(self, variant);
1145 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1146 if attr.is_some() || !traits.is_empty() {
1147 return self.collect_attr(attr, traits, Annotatable::Variant(variant),
1148 AstFragmentKind::Variants, after_derive)
1152 noop_flat_map_variant(variant, self)
1155 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1156 let expr = configure!(self, expr);
1157 expr.filter_map(|mut expr| {
1158 self.cfg.configure_expr_kind(&mut expr.kind);
1160 // Ignore derives so they remain unused.
1161 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1164 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1166 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1167 AstFragmentKind::OptExpr, after_derive)
1169 .map(|expr| expr.into_inner())
1172 if let ast::ExprKind::Mac(mac) = expr.kind {
1173 self.check_attributes(&expr.attrs);
1174 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1176 .map(|expr| expr.into_inner())
1178 Some({ noop_visit_expr(&mut expr, self); expr })
1183 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1184 self.cfg.configure_pat(pat);
1186 PatKind::Mac(_) => {}
1187 _ => return noop_visit_pat(pat, self),
1190 visit_clobber(pat, |mut pat| {
1191 match mem::replace(&mut pat.kind, PatKind::Wild) {
1192 PatKind::Mac(mac) =>
1193 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1194 _ => unreachable!(),
1199 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1200 let mut stmt = configure!(self, stmt);
1202 // we'll expand attributes on expressions separately
1203 if !stmt.is_expr() {
1204 let (attr, derives, after_derive) = if stmt.is_item() {
1205 self.classify_item(&mut stmt)
1207 // ignore derives on non-item statements so it falls through
1208 // to the unused-attributes lint
1209 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1210 (attr, vec![], after_derive)
1213 if attr.is_some() || !derives.is_empty() {
1214 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1215 AstFragmentKind::Stmts, after_derive).make_stmts();
1219 if let StmtKind::Mac(mac) = stmt.kind {
1220 let (mac, style, attrs) = mac.into_inner();
1221 self.check_attributes(&attrs);
1222 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1225 // If this is a macro invocation with a semicolon, then apply that
1226 // semicolon to the final statement produced by expansion.
1227 if style == MacStmtStyle::Semicolon {
1228 if let Some(stmt) = placeholder.pop() {
1229 placeholder.push(stmt.add_trailing_semicolon());
1236 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1237 let ast::Stmt { id, kind, span } = stmt;
1238 noop_flat_map_stmt_kind(kind, self).into_iter().map(|kind| {
1239 ast::Stmt { id, kind, span }
1244 fn visit_block(&mut self, block: &mut P<Block>) {
1245 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1246 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1247 noop_visit_block(block, self);
1248 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1251 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1252 let mut item = configure!(self, item);
1254 let (attr, traits, after_derive) = self.classify_item(&mut item);
1255 if attr.is_some() || !traits.is_empty() {
1256 return self.collect_attr(attr, traits, Annotatable::Item(item),
1257 AstFragmentKind::Items, after_derive).make_items();
1261 ast::ItemKind::Mac(..) => {
1262 self.check_attributes(&item.attrs);
1263 item.and_then(|item| match item.kind {
1264 ItemKind::Mac(mac) => self.collect(
1265 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1267 _ => unreachable!(),
1270 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1271 if item.ident == Ident::invalid() {
1272 return noop_flat_map_item(item, self);
1275 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1276 let mut module = (*self.cx.current_expansion.module).clone();
1277 module.mod_path.push(item.ident);
1279 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1280 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1281 // Thus, if `inner` is the dummy span, we know the module is inline.
1282 let inline_module = item.span.contains(inner) || inner.is_dummy();
1285 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1286 self.cx.current_expansion.directory_ownership =
1287 DirectoryOwnership::Owned { relative: None };
1288 module.directory.push(&*path.as_str());
1290 module.directory.push(&*item.ident.as_str());
1293 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1294 let mut path = match path {
1295 FileName::Real(path) => path,
1296 other => PathBuf::from(other.to_string()),
1298 let directory_ownership = match path.file_name().unwrap().to_str() {
1299 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1300 Some(_) => DirectoryOwnership::Owned {
1301 relative: Some(item.ident),
1303 None => DirectoryOwnership::UnownedViaMod(false),
1306 module.directory = path;
1307 self.cx.current_expansion.directory_ownership = directory_ownership;
1311 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1312 let result = noop_flat_map_item(item, self);
1313 self.cx.current_expansion.module = orig_module;
1314 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1318 _ => noop_flat_map_item(item, self),
1322 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1323 let mut item = configure!(self, item);
1325 let (attr, traits, after_derive) = self.classify_item(&mut item);
1326 if attr.is_some() || !traits.is_empty() {
1327 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1328 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1332 ast::TraitItemKind::Macro(mac) => {
1333 let ast::TraitItem { attrs, span, .. } = item;
1334 self.check_attributes(&attrs);
1335 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1337 _ => noop_flat_map_trait_item(item, self),
1341 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1342 let mut item = configure!(self, item);
1344 let (attr, traits, after_derive) = self.classify_item(&mut item);
1345 if attr.is_some() || !traits.is_empty() {
1346 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1347 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1351 ast::ImplItemKind::Macro(mac) => {
1352 let ast::ImplItem { attrs, span, .. } = item;
1353 self.check_attributes(&attrs);
1354 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1356 _ => noop_flat_map_impl_item(item, self),
1360 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1362 ast::TyKind::Mac(_) => {}
1363 _ => return noop_visit_ty(ty, self),
1366 visit_clobber(ty, |mut ty| {
1367 match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1368 ast::TyKind::Mac(mac) =>
1369 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1370 _ => unreachable!(),
1375 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1376 self.cfg.configure_foreign_mod(foreign_mod);
1377 noop_visit_foreign_mod(foreign_mod, self);
1380 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1381 -> SmallVec<[ast::ForeignItem; 1]>
1383 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1385 if attr.is_some() || !traits.is_empty() {
1386 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1387 AstFragmentKind::ForeignItems, after_derive)
1388 .make_foreign_items();
1391 if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind {
1392 self.check_attributes(&foreign_item.attrs);
1393 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1394 .make_foreign_items();
1397 noop_flat_map_foreign_item(foreign_item, self)
1400 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1402 ast::ItemKind::MacroDef(..) => {}
1404 self.cfg.configure_item_kind(item);
1405 noop_visit_item_kind(item, self);
1410 fn flat_map_generic_param(
1412 param: ast::GenericParam
1413 ) -> SmallVec<[ast::GenericParam; 1]>
1415 let mut param = configure!(self, param);
1417 let (attr, traits, after_derive) = self.classify_item(&mut param);
1418 if attr.is_some() || !traits.is_empty() {
1419 return self.collect_attr(attr, traits, Annotatable::GenericParam(param),
1420 AstFragmentKind::GenericParams, after_derive)
1421 .make_generic_params();
1424 noop_flat_map_generic_param(param, self)
1427 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1428 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1429 // contents="file contents")]` attributes
1430 if !at.check_name(sym::doc) {
1431 return noop_visit_attribute(at, self);
1434 if let Some(list) = at.meta_item_list() {
1435 if !list.iter().any(|it| it.check_name(sym::include)) {
1436 return noop_visit_attribute(at, self);
1439 let mut items = vec![];
1441 for mut it in list {
1442 if !it.check_name(sym::include) {
1443 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1447 if let Some(file) = it.value_str() {
1448 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1449 self.check_attributes(slice::from_ref(at));
1450 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1451 // avoid loading the file if they haven't enabled the feature
1452 return noop_visit_attribute(at, self);
1455 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1456 Ok(filename) => filename,
1463 match self.cx.source_map().load_file(&filename) {
1464 Ok(source_file) => {
1465 let src = source_file.src.as_ref()
1466 .expect("freshly loaded file should have a source");
1467 let src_interned = Symbol::intern(src.as_str());
1469 let include_info = vec![
1470 ast::NestedMetaItem::MetaItem(
1471 attr::mk_name_value_item_str(
1472 Ident::with_dummy_span(sym::file),
1477 ast::NestedMetaItem::MetaItem(
1478 attr::mk_name_value_item_str(
1479 Ident::with_dummy_span(sym::contents),
1486 let include_ident = Ident::with_dummy_span(sym::include);
1487 let item = attr::mk_list_item(include_ident, include_info);
1488 items.push(ast::NestedMetaItem::MetaItem(item));
1493 .and_then(|item| item.name_value_literal())
1496 if e.kind() == ErrorKind::InvalidData {
1500 &format!("{} wasn't a utf-8 file", filename.display()),
1502 .span_label(lit.span, "contains invalid utf-8")
1505 let mut err = self.cx.struct_span_err(
1507 &format!("couldn't read {}: {}", filename.display(), e),
1509 err.span_label(lit.span, "couldn't read file");
1516 let mut err = self.cx.struct_span_err(
1518 &format!("expected path to external documentation"),
1521 // Check if the user erroneously used `doc(include(...))` syntax.
1522 let literal = it.meta_item_list().and_then(|list| {
1523 if list.len() == 1 {
1524 list[0].literal().map(|literal| &literal.kind)
1530 let (path, applicability) = match &literal {
1531 Some(LitKind::Str(path, ..)) => {
1532 (path.to_string(), Applicability::MachineApplicable)
1534 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1537 err.span_suggestion(
1539 "provide a file path with `=`",
1540 format!("include = \"{}\"", path),
1548 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1549 *at = attr::Attribute {
1550 item: AttrItem { path: meta.path, tokens: meta.kind.tokens(meta.span) },
1554 is_sugared_doc: false,
1557 noop_visit_attribute(at, self)
1561 fn visit_id(&mut self, id: &mut ast::NodeId) {
1563 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1564 *id = self.cx.resolver.next_node_id()
1568 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1569 self.cfg.configure_fn_decl(&mut fn_decl);
1570 noop_visit_fn_decl(fn_decl, self);
1574 pub struct ExpansionConfig<'feat> {
1575 pub crate_name: String,
1576 pub features: Option<&'feat Features>,
1577 pub recursion_limit: usize,
1578 pub trace_mac: bool,
1579 pub should_test: bool, // If false, strip `#[test]` nodes
1580 pub single_step: bool,
1581 pub keep_macs: bool,
1584 impl<'feat> ExpansionConfig<'feat> {
1585 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1589 recursion_limit: 1024,
1597 fn proc_macro_hygiene(&self) -> bool {
1598 self.features.map_or(false, |features| features.proc_macro_hygiene)
1600 fn custom_inner_attributes(&self) -> bool {
1601 self.features.map_or(false, |features| features.custom_inner_attributes)