2 use crate::proc_macro::collect_derives;
3 use crate::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
4 use crate::mbe::macro_rules::annotate_err_with_kind;
5 use crate::placeholders::{placeholder, PlaceholderExpander};
6 use crate::config::StripUnconfigured;
7 use rustc_parse::configure;
9 use rustc_parse::DirectoryOwnership;
10 use rustc_parse::parser::Parser;
11 use rustc_parse::validate_attr;
12 use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
13 use syntax::ast::{MacStmtStyle, StmtKind, ItemKind};
14 use syntax::attr::{self, HasAttrs};
15 use syntax::source_map::respan;
16 use syntax::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
17 use syntax::mut_visit::*;
18 use syntax::print::pprust;
20 use syntax::sess::ParseSess;
21 use syntax::symbol::{sym, Symbol};
23 use syntax::tokenstream::{TokenStream, TokenTree};
24 use syntax::visit::{self, Visitor};
25 use syntax::util::map_in_place::MapInPlace;
27 use errors::{PResult, Applicability, FatalError};
28 use smallvec::{smallvec, SmallVec};
29 use syntax_pos::{Span, DUMMY_SP, FileName};
31 use rustc_data_structures::sync::Lrc;
32 use std::io::ErrorKind;
33 use std::{iter, mem, slice};
34 use std::ops::DerefMut;
36 use std::path::PathBuf;
38 macro_rules! ast_fragments {
40 $($Kind:ident($AstTy:ty) {
42 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
43 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
47 /// A fragment of AST that can be produced by a single macro expansion.
48 /// Can also serve as an input and intermediate result for macro expansion operations.
49 pub enum AstFragment {
50 OptExpr(Option<P<ast::Expr>>),
54 /// "Discriminant" of an AST fragment.
55 #[derive(Copy, Clone, PartialEq, Eq)]
56 pub enum AstFragmentKind {
61 impl AstFragmentKind {
62 pub fn name(self) -> &'static str {
64 AstFragmentKind::OptExpr => "expression",
65 $(AstFragmentKind::$Kind => $kind_name,)*
69 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
71 AstFragmentKind::OptExpr =>
72 result.make_expr().map(Some).map(AstFragment::OptExpr),
73 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
79 pub fn add_placeholders(&mut self, placeholders: &[NodeId]) {
80 if placeholders.is_empty() {
84 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
85 // We are repeating through arguments with `many`, to do that we have to
86 // mention some macro variable from those arguments even if it's not used.
87 #[cfg_attr(bootstrap, allow(unused_macros))]
88 macro _repeating($flat_map_ast_elt) {}
89 placeholder(AstFragmentKind::$Kind, *id, None).$make_ast()
91 _ => panic!("unexpected AST fragment kind")
95 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
97 AstFragment::OptExpr(expr) => expr,
98 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
102 $(pub fn $make_ast(self) -> $AstTy {
104 AstFragment::$Kind(ast) => ast,
105 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
109 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
111 AstFragment::OptExpr(opt_expr) => {
112 visit_clobber(opt_expr, |opt_expr| {
113 if let Some(expr) = opt_expr {
114 vis.filter_map_expr(expr)
120 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
121 $($(AstFragment::$Kind(ast) =>
122 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
126 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
128 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
129 AstFragment::OptExpr(None) => {}
130 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
131 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
132 visitor.$visit_ast_elt(ast_elt);
138 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
139 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
141 Some(self.make(AstFragmentKind::$Kind).$make_ast())
148 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
149 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
150 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
151 Stmts(SmallVec<[ast::Stmt; 1]>) {
152 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
154 Items(SmallVec<[P<ast::Item>; 1]>) {
155 "item"; many fn flat_map_item; fn visit_item; fn make_items;
157 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
158 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
160 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
161 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
163 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
165 many fn flat_map_foreign_item;
166 fn visit_foreign_item;
167 fn make_foreign_items;
169 Arms(SmallVec<[ast::Arm; 1]>) {
170 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
172 Fields(SmallVec<[ast::Field; 1]>) {
173 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
175 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
177 many fn flat_map_field_pattern;
178 fn visit_field_pattern;
179 fn make_field_patterns;
181 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
183 many fn flat_map_generic_param;
184 fn visit_generic_param;
185 fn make_generic_params;
187 Params(SmallVec<[ast::Param; 1]>) {
188 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
190 StructFields(SmallVec<[ast::StructField; 1]>) {
192 many fn flat_map_struct_field;
193 fn visit_struct_field;
194 fn make_struct_fields;
196 Variants(SmallVec<[ast::Variant; 1]>) {
197 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
201 impl AstFragmentKind {
202 fn dummy(self, span: Span) -> AstFragment {
203 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
206 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
208 let mut items = items.into_iter();
210 AstFragmentKind::Arms =>
211 AstFragment::Arms(items.map(Annotatable::expect_arm).collect()),
212 AstFragmentKind::Fields =>
213 AstFragment::Fields(items.map(Annotatable::expect_field).collect()),
214 AstFragmentKind::FieldPats =>
215 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()),
216 AstFragmentKind::GenericParams =>
217 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()),
218 AstFragmentKind::Params =>
219 AstFragment::Params(items.map(Annotatable::expect_param).collect()),
220 AstFragmentKind::StructFields => AstFragment::StructFields(
221 items.map(Annotatable::expect_struct_field).collect()
223 AstFragmentKind::Variants =>
224 AstFragment::Variants(items.map(Annotatable::expect_variant).collect()),
225 AstFragmentKind::Items =>
226 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
227 AstFragmentKind::ImplItems =>
228 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
229 AstFragmentKind::TraitItems =>
230 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
231 AstFragmentKind::ForeignItems =>
232 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
233 AstFragmentKind::Stmts =>
234 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
235 AstFragmentKind::Expr => AstFragment::Expr(
236 items.next().expect("expected exactly one expression").expect_expr()
238 AstFragmentKind::OptExpr =>
239 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
240 AstFragmentKind::Pat | AstFragmentKind::Ty =>
241 panic!("patterns and types aren't annotatable"),
246 pub struct Invocation {
247 pub kind: InvocationKind,
248 pub fragment_kind: AstFragmentKind,
249 pub expansion_data: ExpansionData,
252 pub enum InvocationKind {
258 attr: ast::Attribute,
260 // Required for resolving derive helper attributes.
262 // We temporarily report errors for attribute macros placed after derives
269 /// "Invocation" that contains all derives from an item,
270 /// broken into multiple `Derive` invocations when expanded.
271 /// FIXME: Find a way to remove it.
278 impl InvocationKind {
279 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
280 // HACK: For unnamed fields placeholders should have the same visibility as the actual
281 // fields because for tuple structs/variants resolve determines visibilities of their
282 // constructor using these field visibilities before attributes on them are are expanded.
283 // The assumption is that the attribute expansion cannot change field visibilities,
284 // and it holds because only inert attributes are supported in this position.
286 InvocationKind::Attr { item: Annotatable::StructField(field), .. } |
287 InvocationKind::Derive { item: Annotatable::StructField(field), .. } |
288 InvocationKind::DeriveContainer { item: Annotatable::StructField(field), .. }
289 if field.ident.is_none() => Some(field.vis.clone()),
296 pub fn span(&self) -> Span {
298 InvocationKind::Bang { span, .. } => *span,
299 InvocationKind::Attr { attr, .. } => attr.span,
300 InvocationKind::Derive { path, .. } => path.span,
301 InvocationKind::DeriveContainer { item, .. } => item.span(),
306 pub struct MacroExpander<'a, 'b> {
307 pub cx: &'a mut ExtCtxt<'b>,
308 monotonic: bool, // cf. `cx.monotonic_expander()`
311 impl<'a, 'b> MacroExpander<'a, 'b> {
312 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
313 MacroExpander { cx, monotonic }
316 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
317 let mut module = ModuleData {
318 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
319 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
320 FileName::Real(path) => path,
321 other => PathBuf::from(other.to_string()),
324 module.directory.pop();
325 self.cx.root_path = module.directory.clone();
326 self.cx.current_expansion.module = Rc::new(module);
328 let orig_mod_span = krate.module.inner;
330 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
333 kind: ast::ItemKind::Mod(krate.module),
334 ident: Ident::invalid(),
335 id: ast::DUMMY_NODE_ID,
336 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
340 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
341 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
343 krate.module = module;
346 // Resolution failed so we return an empty expansion
347 krate.attrs = vec![];
348 krate.module = ast::Mod {
349 inner: orig_mod_span,
356 self.cx.trace_macros_diag();
360 // Recursively expand all macro invocations in this AST fragment.
361 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
362 let orig_expansion_data = self.cx.current_expansion.clone();
363 self.cx.current_expansion.depth = 0;
365 // Collect all macro invocations and replace them with placeholders.
366 let (mut fragment_with_placeholders, mut invocations)
367 = self.collect_invocations(input_fragment, &[]);
369 // Optimization: if we resolve all imports now,
370 // we'll be able to immediately resolve most of imported macros.
371 self.resolve_imports();
373 // Resolve paths in all invocations and produce output expanded fragments for them, but
374 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
375 // The output fragments also go through expansion recursively until no invocations are left.
376 // Unresolved macros produce dummy outputs as a recovery measure.
377 invocations.reverse();
378 let mut expanded_fragments = Vec::new();
379 let mut undetermined_invocations = Vec::new();
380 let (mut progress, mut force) = (false, !self.monotonic);
382 let invoc = if let Some(invoc) = invocations.pop() {
385 self.resolve_imports();
386 if undetermined_invocations.is_empty() { break }
387 invocations = mem::take(&mut undetermined_invocations);
388 force = !mem::replace(&mut progress, false);
392 let eager_expansion_root =
393 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
394 let res = match self.cx.resolver.resolve_macro_invocation(
395 &invoc, eager_expansion_root, force
398 Err(Indeterminate) => {
399 undetermined_invocations.push(invoc);
405 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
406 self.cx.current_expansion = invoc.expansion_data.clone();
408 // FIXME(jseyfried): Refactor out the following logic
409 let (expanded_fragment, new_invocations) = match res {
410 InvocationRes::Single(ext) => {
411 let fragment = self.expand_invoc(invoc, &ext.kind);
412 self.collect_invocations(fragment, &[])
414 InvocationRes::DeriveContainer(_exts) => {
415 // FIXME: Consider using the derive resolutions (`_exts`) immediately,
416 // instead of enqueuing the derives to be resolved again later.
417 let (derives, item) = match invoc.kind {
418 InvocationKind::DeriveContainer { derives, item } => (derives, item),
421 if !item.derive_allowed() {
422 let attr = attr::find_by_name(item.attrs(), sym::derive)
423 .expect("`derive` attribute should exist");
424 let span = attr.span;
425 let mut err = self.cx.struct_span_err(span,
426 "`derive` may only be applied to structs, enums and unions");
427 if let ast::AttrStyle::Inner = attr.style {
428 let trait_list = derives.iter()
429 .map(|t| pprust::path_to_string(t))
430 .collect::<Vec<_>>();
431 let suggestion = format!("#[derive({})]", trait_list.join(", "));
433 span, "try an outer attribute", suggestion,
434 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
435 Applicability::MaybeIncorrect
441 let mut item = self.fully_configure(item);
442 item.visit_attrs(|attrs| attrs.retain(|a| !a.has_name(sym::derive)));
444 let mut derive_placeholders = Vec::with_capacity(derives.len());
445 invocations.reserve(derives.len());
446 for path in derives {
447 let expn_id = ExpnId::fresh(None);
448 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
449 invocations.push(Invocation {
450 kind: InvocationKind::Derive { path, item: item.clone() },
451 fragment_kind: invoc.fragment_kind,
452 expansion_data: ExpansionData {
454 ..invoc.expansion_data.clone()
458 let fragment = invoc.fragment_kind
459 .expect_from_annotatables(::std::iter::once(item));
460 self.collect_invocations(fragment, &derive_placeholders)
464 if expanded_fragments.len() < depth {
465 expanded_fragments.push(Vec::new());
467 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
468 if !self.cx.ecfg.single_step {
469 invocations.extend(new_invocations.into_iter().rev());
473 self.cx.current_expansion = orig_expansion_data;
475 // Finally incorporate all the expanded macros into the input AST fragment.
476 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
477 while let Some(expanded_fragments) = expanded_fragments.pop() {
478 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
479 placeholder_expander.add(NodeId::placeholder_from_expn_id(expn_id),
483 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
484 fragment_with_placeholders
487 fn resolve_imports(&mut self) {
489 self.cx.resolver.resolve_imports();
493 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
494 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
495 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
496 /// prepares data for resolving paths of macro invocations.
497 fn collect_invocations(&mut self, mut fragment: AstFragment, extra_placeholders: &[NodeId])
498 -> (AstFragment, Vec<Invocation>) {
499 // Resolve `$crate`s in the fragment for pretty-printing.
500 self.cx.resolver.resolve_dollar_crates();
503 let mut collector = InvocationCollector {
504 cfg: StripUnconfigured {
505 sess: self.cx.parse_sess,
506 features: self.cx.ecfg.features,
509 invocations: Vec::new(),
510 monotonic: self.monotonic,
512 fragment.mut_visit_with(&mut collector);
513 fragment.add_placeholders(extra_placeholders);
514 collector.invocations
518 self.cx.resolver.visit_ast_fragment_with_placeholders(
519 self.cx.current_expansion.id, &fragment
523 (fragment, invocations)
526 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
527 let mut cfg = StripUnconfigured {
528 sess: self.cx.parse_sess,
529 features: self.cx.ecfg.features,
531 // Since the item itself has already been configured by the InvocationCollector,
532 // we know that fold result vector will contain exactly one element
534 Annotatable::Item(item) => {
535 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
537 Annotatable::TraitItem(item) => {
538 Annotatable::TraitItem(
539 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
541 Annotatable::ImplItem(item) => {
542 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
544 Annotatable::ForeignItem(item) => {
545 Annotatable::ForeignItem(
546 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
549 Annotatable::Stmt(stmt) => {
550 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
552 Annotatable::Expr(mut expr) => {
553 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
555 Annotatable::Arm(arm) => {
556 Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap())
558 Annotatable::Field(field) => {
559 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
561 Annotatable::FieldPat(fp) => {
562 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
564 Annotatable::GenericParam(param) => {
565 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
567 Annotatable::Param(param) => {
568 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
570 Annotatable::StructField(sf) => {
571 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
573 Annotatable::Variant(v) => {
574 Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap())
579 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
580 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
581 let expn_data = self.cx.current_expansion.id.expn_data();
582 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
583 let mut err = self.cx.struct_span_err(expn_data.call_site,
584 &format!("recursion limit reached while expanding the macro `{}`",
585 expn_data.kind.descr()));
587 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
590 self.cx.trace_macros_diag();
594 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
596 InvocationKind::Bang { mac, .. } => match ext {
597 SyntaxExtensionKind::Bang(expander) => {
598 self.gate_proc_macro_expansion_kind(span, fragment_kind);
599 let tok_result = expander.expand(self.cx, span, mac.stream());
600 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
602 SyntaxExtensionKind::LegacyBang(expander) => {
603 let prev = self.cx.current_expansion.prior_type_ascription;
604 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
605 let tok_result = expander.expand(self.cx, span, mac.stream());
606 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
610 "non-{kind} macro in {kind} position: {path}",
611 kind = fragment_kind.name(),
612 path = pprust::path_to_string(&mac.path),
614 self.cx.span_err(span, &msg);
615 self.cx.trace_macros_diag();
616 fragment_kind.dummy(span)
618 self.cx.current_expansion.prior_type_ascription = prev;
623 InvocationKind::Attr { attr, mut item, .. } => match ext {
624 SyntaxExtensionKind::Attr(expander) => {
625 self.gate_proc_macro_input(&item);
626 self.gate_proc_macro_attr_item(span, &item);
627 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
628 Annotatable::Item(item) => token::NtItem(item),
629 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
630 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
631 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
632 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
633 Annotatable::Expr(expr) => token::NtExpr(expr),
635 | Annotatable::Field(..)
636 | Annotatable::FieldPat(..)
637 | Annotatable::GenericParam(..)
638 | Annotatable::Param(..)
639 | Annotatable::StructField(..)
640 | Annotatable::Variant(..)
641 => panic!("unexpected annotatable"),
642 })), DUMMY_SP).into();
643 let item = attr.unwrap_normal_item();
644 let input = self.extract_proc_macro_attr_input(item.tokens, span);
645 let tok_result = expander.expand(self.cx, span, input, item_tok);
646 self.parse_ast_fragment(tok_result, fragment_kind, &item.path, span)
648 SyntaxExtensionKind::LegacyAttr(expander) => {
649 match validate_attr::parse_meta(self.cx.parse_sess, &attr) {
651 let item = expander.expand(self.cx, span, &meta, item);
652 fragment_kind.expect_from_annotatables(item)
656 fragment_kind.dummy(span)
660 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
661 attr::mark_known(&attr);
663 attr::mark_used(&attr);
665 item.visit_attrs(|attrs| attrs.push(attr));
666 fragment_kind.expect_from_annotatables(iter::once(item))
670 InvocationKind::Derive { path, item } => match ext {
671 SyntaxExtensionKind::Derive(expander) |
672 SyntaxExtensionKind::LegacyDerive(expander) => {
673 if !item.derive_allowed() {
674 return fragment_kind.dummy(span);
676 if let SyntaxExtensionKind::Derive(..) = ext {
677 self.gate_proc_macro_input(&item);
679 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
680 let items = expander.expand(self.cx, span, &meta, item);
681 fragment_kind.expect_from_annotatables(items)
685 InvocationKind::DeriveContainer { .. } => unreachable!()
689 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
690 let mut trees = tokens.trees();
692 Some(TokenTree::Delimited(_, _, tts)) => {
693 if trees.next().is_none() {
697 Some(TokenTree::Token(..)) => {}
698 None => return TokenStream::default(),
700 self.cx.span_err(span, "custom attribute invocations must be \
701 of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
702 followed by a delimiter token");
703 TokenStream::default()
706 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
707 let kind = match item {
708 Annotatable::Item(item) => match &item.kind {
709 ItemKind::Mod(m) if m.inline => "modules",
712 Annotatable::TraitItem(_)
713 | Annotatable::ImplItem(_)
714 | Annotatable::ForeignItem(_) => return,
715 Annotatable::Stmt(_) => "statements",
716 Annotatable::Expr(_) => "expressions",
718 | Annotatable::Field(..)
719 | Annotatable::FieldPat(..)
720 | Annotatable::GenericParam(..)
721 | Annotatable::Param(..)
722 | Annotatable::StructField(..)
723 | Annotatable::Variant(..)
724 => panic!("unexpected annotatable"),
726 if self.cx.ecfg.proc_macro_hygiene() {
731 sym::proc_macro_hygiene,
734 &format!("custom attributes cannot be applied to {}", kind),
738 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
739 struct GateProcMacroInput<'a> {
740 parse_sess: &'a ParseSess,
743 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
744 fn visit_item(&mut self, item: &'ast ast::Item) {
746 ast::ItemKind::Mod(module) if !module.inline => {
749 sym::proc_macro_hygiene,
752 "non-inline modules in proc macro input are unstable",
758 visit::walk_item(self, item);
761 fn visit_mac(&mut self, _: &'ast ast::Mac) {}
764 if !self.cx.ecfg.proc_macro_hygiene() {
765 annotatable.visit_with(&mut GateProcMacroInput { parse_sess: self.cx.parse_sess });
769 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
770 let kind = match kind {
771 AstFragmentKind::Expr |
772 AstFragmentKind::OptExpr => "expressions",
773 AstFragmentKind::Pat => "patterns",
774 AstFragmentKind::Stmts => "statements",
775 AstFragmentKind::Ty |
776 AstFragmentKind::Items |
777 AstFragmentKind::TraitItems |
778 AstFragmentKind::ImplItems |
779 AstFragmentKind::ForeignItems => return,
780 AstFragmentKind::Arms
781 | AstFragmentKind::Fields
782 | AstFragmentKind::FieldPats
783 | AstFragmentKind::GenericParams
784 | AstFragmentKind::Params
785 | AstFragmentKind::StructFields
786 | AstFragmentKind::Variants
787 => panic!("unexpected AST fragment kind"),
789 if self.cx.ecfg.proc_macro_hygiene() {
794 sym::proc_macro_hygiene,
797 &format!("procedural macros cannot be expanded to {}", kind),
801 fn parse_ast_fragment(
804 kind: AstFragmentKind,
808 let mut parser = self.cx.new_parser_from_tts(toks);
809 match parse_ast_fragment(&mut parser, kind, false) {
811 ensure_complete_parse(&mut parser, path, kind.name(), span);
816 annotate_err_with_kind(&mut err, kind, span);
818 self.cx.trace_macros_diag();
825 pub fn parse_ast_fragment<'a>(
826 this: &mut Parser<'a>,
827 kind: AstFragmentKind,
828 macro_legacy_warnings: bool,
829 ) -> PResult<'a, AstFragment> {
831 AstFragmentKind::Items => {
832 let mut items = SmallVec::new();
833 while let Some(item) = this.parse_item()? {
836 AstFragment::Items(items)
838 AstFragmentKind::TraitItems => {
839 let mut items = SmallVec::new();
840 while this.token != token::Eof {
841 items.push(this.parse_trait_item(&mut false)?);
843 AstFragment::TraitItems(items)
845 AstFragmentKind::ImplItems => {
846 let mut items = SmallVec::new();
847 while this.token != token::Eof {
848 items.push(this.parse_impl_item(&mut false)?);
850 AstFragment::ImplItems(items)
852 AstFragmentKind::ForeignItems => {
853 let mut items = SmallVec::new();
854 while this.token != token::Eof {
855 items.push(this.parse_foreign_item(DUMMY_SP)?);
857 AstFragment::ForeignItems(items)
859 AstFragmentKind::Stmts => {
860 let mut stmts = SmallVec::new();
861 while this.token != token::Eof &&
862 // won't make progress on a `}`
863 this.token != token::CloseDelim(token::Brace) {
864 if let Some(stmt) = this.parse_full_stmt(macro_legacy_warnings)? {
868 AstFragment::Stmts(stmts)
870 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
871 AstFragmentKind::OptExpr => {
872 if this.token != token::Eof {
873 AstFragment::OptExpr(Some(this.parse_expr()?))
875 AstFragment::OptExpr(None)
878 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
879 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?),
880 AstFragmentKind::Arms
881 | AstFragmentKind::Fields
882 | AstFragmentKind::FieldPats
883 | AstFragmentKind::GenericParams
884 | AstFragmentKind::Params
885 | AstFragmentKind::StructFields
886 | AstFragmentKind::Variants
887 => panic!("unexpected AST fragment kind"),
891 pub fn ensure_complete_parse<'a>(
892 this: &mut Parser<'a>,
897 if this.token != token::Eof {
898 let msg = format!("macro expansion ignores token `{}` and any following",
899 this.this_token_to_string());
900 // Avoid emitting backtrace info twice.
901 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
902 let mut err = this.struct_span_err(def_site_span, &msg);
903 err.span_label(span, "caused by the macro expansion here");
905 "the usage of `{}!` is likely invalid in {} context",
906 pprust::path_to_string(macro_path),
910 let semi_span = this.sess.source_map().next_point(span);
912 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
913 match this.sess.source_map().span_to_snippet(semi_full_span) {
914 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
917 "you might be missing a semicolon here",
919 Applicability::MaybeIncorrect,
928 struct InvocationCollector<'a, 'b> {
929 cx: &'a mut ExtCtxt<'b>,
930 cfg: StripUnconfigured<'a>,
931 invocations: Vec<Invocation>,
935 impl<'a, 'b> InvocationCollector<'a, 'b> {
936 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
937 // Expansion data for all the collected invocations is set upon their resolution,
938 // with exception of the derive container case which is not resolved and can get
939 // its expansion data immediately.
940 let expn_data = match &kind {
941 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
942 parent: self.cx.current_expansion.id,
944 ExpnKind::Macro(MacroKind::Attr, sym::derive),
945 item.span(), self.cx.parse_sess.edition,
950 let expn_id = ExpnId::fresh(expn_data);
951 let vis = kind.placeholder_visibility();
952 self.invocations.push(Invocation {
955 expansion_data: ExpansionData {
957 depth: self.cx.current_expansion.depth + 1,
958 ..self.cx.current_expansion.clone()
961 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
964 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
965 self.collect(kind, InvocationKind::Bang { mac, span })
968 fn collect_attr(&mut self,
969 attr: Option<ast::Attribute>,
972 kind: AstFragmentKind,
975 self.collect(kind, match attr {
976 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
977 None => InvocationKind::DeriveContainer { derives, item },
981 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
982 -> Option<ast::Attribute> {
983 let attr = attrs.iter()
985 if a.has_name(sym::derive) {
986 *after_derive = true;
988 !attr::is_known(a) && !is_builtin_attr(a)
990 .map(|i| attrs.remove(i));
991 if let Some(attr) = &attr {
992 if !self.cx.ecfg.custom_inner_attributes() &&
993 attr.style == ast::AttrStyle::Inner && !attr.has_name(sym::test) {
994 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
995 attr.span, GateIssue::Language,
996 "non-builtin inner attributes are unstable");
1002 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
1003 fn classify_item<T>(&mut self, item: &mut T)
1004 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
1007 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
1009 item.visit_attrs(|mut attrs| {
1010 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1011 traits = collect_derives(&mut self.cx, &mut attrs);
1014 (attr, traits, after_derive)
1017 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1018 /// to the unused-attributes lint (making it an error on statements and expressions
1019 /// is a breaking change)
1020 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
1021 -> (Option<ast::Attribute>, /* after_derive */ bool) {
1022 let (mut attr, mut after_derive) = (None, false);
1024 nonitem.visit_attrs(|mut attrs| {
1025 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1028 (attr, after_derive)
1031 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1032 self.cfg.configure(node)
1035 // Detect use of feature-gated or invalid attributes on macro invocations
1036 // since they will not be detected after macro expansion.
1037 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1038 let features = self.cx.ecfg.features.unwrap();
1039 for attr in attrs.iter() {
1040 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1041 validate_attr::check_meta(self.cx.parse_sess, attr);
1043 // macros are expanded before any lint passes so this warning has to be hardcoded
1044 if attr.has_name(sym::derive) {
1045 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1046 .note("this may become a hard error in a future release")
1053 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1054 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1055 self.cfg.configure_expr(expr);
1056 visit_clobber(expr.deref_mut(), |mut expr| {
1057 self.cfg.configure_expr_kind(&mut expr.kind);
1059 // ignore derives so they remain unused
1060 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1063 // Collect the invoc regardless of whether or not attributes are permitted here
1064 // expansion will eat the attribute so it won't error later.
1065 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1067 // AstFragmentKind::Expr requires the macro to emit an expression.
1068 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1069 AstFragmentKind::Expr, after_derive)
1074 if let ast::ExprKind::Mac(mac) = expr.kind {
1075 self.check_attributes(&expr.attrs);
1076 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1080 noop_visit_expr(&mut expr, self);
1086 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1087 let mut arm = configure!(self, arm);
1089 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1090 if attr.is_some() || !traits.is_empty() {
1091 return self.collect_attr(attr, traits, Annotatable::Arm(arm),
1092 AstFragmentKind::Arms, after_derive)
1096 noop_flat_map_arm(arm, self)
1099 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1100 let mut field = configure!(self, field);
1102 let (attr, traits, after_derive) = self.classify_item(&mut field);
1103 if attr.is_some() || !traits.is_empty() {
1104 return self.collect_attr(attr, traits, Annotatable::Field(field),
1105 AstFragmentKind::Fields, after_derive)
1109 noop_flat_map_field(field, self)
1112 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1113 let mut fp = configure!(self, fp);
1115 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1116 if attr.is_some() || !traits.is_empty() {
1117 return self.collect_attr(attr, traits, Annotatable::FieldPat(fp),
1118 AstFragmentKind::FieldPats, after_derive)
1119 .make_field_patterns();
1122 noop_flat_map_field_pattern(fp, self)
1125 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1126 let mut p = configure!(self, p);
1128 let (attr, traits, after_derive) = self.classify_item(&mut p);
1129 if attr.is_some() || !traits.is_empty() {
1130 return self.collect_attr(attr, traits, Annotatable::Param(p),
1131 AstFragmentKind::Params, after_derive)
1135 noop_flat_map_param(p, self)
1138 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1139 let mut sf = configure!(self, sf);
1141 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1142 if attr.is_some() || !traits.is_empty() {
1143 return self.collect_attr(attr, traits, Annotatable::StructField(sf),
1144 AstFragmentKind::StructFields, after_derive)
1145 .make_struct_fields();
1148 noop_flat_map_struct_field(sf, self)
1151 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1152 let mut variant = configure!(self, variant);
1154 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1155 if attr.is_some() || !traits.is_empty() {
1156 return self.collect_attr(attr, traits, Annotatable::Variant(variant),
1157 AstFragmentKind::Variants, after_derive)
1161 noop_flat_map_variant(variant, self)
1164 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1165 let expr = configure!(self, expr);
1166 expr.filter_map(|mut expr| {
1167 self.cfg.configure_expr_kind(&mut expr.kind);
1169 // Ignore derives so they remain unused.
1170 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1173 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1175 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1176 AstFragmentKind::OptExpr, after_derive)
1178 .map(|expr| expr.into_inner())
1181 if let ast::ExprKind::Mac(mac) = expr.kind {
1182 self.check_attributes(&expr.attrs);
1183 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1185 .map(|expr| expr.into_inner())
1187 Some({ noop_visit_expr(&mut expr, self); expr })
1192 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1193 self.cfg.configure_pat(pat);
1195 PatKind::Mac(_) => {}
1196 _ => return noop_visit_pat(pat, self),
1199 visit_clobber(pat, |mut pat| {
1200 match mem::replace(&mut pat.kind, PatKind::Wild) {
1201 PatKind::Mac(mac) =>
1202 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1203 _ => unreachable!(),
1208 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1209 let mut stmt = configure!(self, stmt);
1211 // we'll expand attributes on expressions separately
1212 if !stmt.is_expr() {
1213 let (attr, derives, after_derive) = if stmt.is_item() {
1214 self.classify_item(&mut stmt)
1216 // ignore derives on non-item statements so it falls through
1217 // to the unused-attributes lint
1218 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1219 (attr, vec![], after_derive)
1222 if attr.is_some() || !derives.is_empty() {
1223 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1224 AstFragmentKind::Stmts, after_derive).make_stmts();
1228 if let StmtKind::Mac(mac) = stmt.kind {
1229 let (mac, style, attrs) = mac.into_inner();
1230 self.check_attributes(&attrs);
1231 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1234 // If this is a macro invocation with a semicolon, then apply that
1235 // semicolon to the final statement produced by expansion.
1236 if style == MacStmtStyle::Semicolon {
1237 if let Some(stmt) = placeholder.pop() {
1238 placeholder.push(stmt.add_trailing_semicolon());
1245 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1246 let ast::Stmt { id, kind, span } = stmt;
1247 noop_flat_map_stmt_kind(kind, self).into_iter().map(|kind| {
1248 ast::Stmt { id, kind, span }
1253 fn visit_block(&mut self, block: &mut P<Block>) {
1254 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1255 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1256 noop_visit_block(block, self);
1257 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1260 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1261 let mut item = configure!(self, item);
1263 let (attr, traits, after_derive) = self.classify_item(&mut item);
1264 if attr.is_some() || !traits.is_empty() {
1265 return self.collect_attr(attr, traits, Annotatable::Item(item),
1266 AstFragmentKind::Items, after_derive).make_items();
1270 ast::ItemKind::Mac(..) => {
1271 self.check_attributes(&item.attrs);
1272 item.and_then(|item| match item.kind {
1273 ItemKind::Mac(mac) => self.collect(
1274 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1276 _ => unreachable!(),
1279 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1280 if item.ident == Ident::invalid() {
1281 return noop_flat_map_item(item, self);
1284 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1285 let mut module = (*self.cx.current_expansion.module).clone();
1286 module.mod_path.push(item.ident);
1288 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1289 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1290 // Thus, if `inner` is the dummy span, we know the module is inline.
1291 let inline_module = item.span.contains(inner) || inner.is_dummy();
1294 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1295 self.cx.current_expansion.directory_ownership =
1296 DirectoryOwnership::Owned { relative: None };
1297 module.directory.push(&*path.as_str());
1299 module.directory.push(&*item.ident.as_str());
1302 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1303 let mut path = match path {
1304 FileName::Real(path) => path,
1305 other => PathBuf::from(other.to_string()),
1307 let directory_ownership = match path.file_name().unwrap().to_str() {
1308 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1309 Some(_) => DirectoryOwnership::Owned {
1310 relative: Some(item.ident),
1312 None => DirectoryOwnership::UnownedViaMod,
1315 module.directory = path;
1316 self.cx.current_expansion.directory_ownership = directory_ownership;
1320 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1321 let result = noop_flat_map_item(item, self);
1322 self.cx.current_expansion.module = orig_module;
1323 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1327 _ => noop_flat_map_item(item, self),
1331 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1332 let mut item = configure!(self, item);
1334 let (attr, traits, after_derive) = self.classify_item(&mut item);
1335 if attr.is_some() || !traits.is_empty() {
1336 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1337 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1341 ast::TraitItemKind::Macro(mac) => {
1342 let ast::TraitItem { attrs, span, .. } = item;
1343 self.check_attributes(&attrs);
1344 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1346 _ => noop_flat_map_trait_item(item, self),
1350 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1351 let mut item = configure!(self, item);
1353 let (attr, traits, after_derive) = self.classify_item(&mut item);
1354 if attr.is_some() || !traits.is_empty() {
1355 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1356 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1360 ast::ImplItemKind::Macro(mac) => {
1361 let ast::ImplItem { attrs, span, .. } = item;
1362 self.check_attributes(&attrs);
1363 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1365 _ => noop_flat_map_impl_item(item, self),
1369 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1371 ast::TyKind::Mac(_) => {}
1372 _ => return noop_visit_ty(ty, self),
1375 visit_clobber(ty, |mut ty| {
1376 match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1377 ast::TyKind::Mac(mac) =>
1378 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1379 _ => unreachable!(),
1384 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1385 self.cfg.configure_foreign_mod(foreign_mod);
1386 noop_visit_foreign_mod(foreign_mod, self);
1389 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1390 -> SmallVec<[ast::ForeignItem; 1]>
1392 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1394 if attr.is_some() || !traits.is_empty() {
1395 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1396 AstFragmentKind::ForeignItems, after_derive)
1397 .make_foreign_items();
1400 if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind {
1401 self.check_attributes(&foreign_item.attrs);
1402 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1403 .make_foreign_items();
1406 noop_flat_map_foreign_item(foreign_item, self)
1409 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1411 ast::ItemKind::MacroDef(..) => {}
1413 self.cfg.configure_item_kind(item);
1414 noop_visit_item_kind(item, self);
1419 fn flat_map_generic_param(
1421 param: ast::GenericParam
1422 ) -> SmallVec<[ast::GenericParam; 1]>
1424 let mut param = configure!(self, param);
1426 let (attr, traits, after_derive) = self.classify_item(&mut param);
1427 if attr.is_some() || !traits.is_empty() {
1428 return self.collect_attr(attr, traits, Annotatable::GenericParam(param),
1429 AstFragmentKind::GenericParams, after_derive)
1430 .make_generic_params();
1433 noop_flat_map_generic_param(param, self)
1436 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1437 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1438 // contents="file contents")]` attributes
1439 if !at.check_name(sym::doc) {
1440 return noop_visit_attribute(at, self);
1443 if let Some(list) = at.meta_item_list() {
1444 if !list.iter().any(|it| it.check_name(sym::include)) {
1445 return noop_visit_attribute(at, self);
1448 let mut items = vec![];
1450 for mut it in list {
1451 if !it.check_name(sym::include) {
1452 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1456 if let Some(file) = it.value_str() {
1457 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1458 self.check_attributes(slice::from_ref(at));
1459 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1460 // avoid loading the file if they haven't enabled the feature
1461 return noop_visit_attribute(at, self);
1464 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1465 Ok(filename) => filename,
1472 match self.cx.source_map().load_file(&filename) {
1473 Ok(source_file) => {
1474 let src = source_file.src.as_ref()
1475 .expect("freshly loaded file should have a source");
1476 let src_interned = Symbol::intern(src.as_str());
1478 let include_info = vec![
1479 ast::NestedMetaItem::MetaItem(
1480 attr::mk_name_value_item_str(
1481 Ident::with_dummy_span(sym::file),
1486 ast::NestedMetaItem::MetaItem(
1487 attr::mk_name_value_item_str(
1488 Ident::with_dummy_span(sym::contents),
1495 let include_ident = Ident::with_dummy_span(sym::include);
1496 let item = attr::mk_list_item(include_ident, include_info);
1497 items.push(ast::NestedMetaItem::MetaItem(item));
1502 .and_then(|item| item.name_value_literal())
1505 if e.kind() == ErrorKind::InvalidData {
1509 &format!("{} wasn't a utf-8 file", filename.display()),
1511 .span_label(lit.span, "contains invalid utf-8")
1514 let mut err = self.cx.struct_span_err(
1516 &format!("couldn't read {}: {}", filename.display(), e),
1518 err.span_label(lit.span, "couldn't read file");
1525 let mut err = self.cx.struct_span_err(
1527 &format!("expected path to external documentation"),
1530 // Check if the user erroneously used `doc(include(...))` syntax.
1531 let literal = it.meta_item_list().and_then(|list| {
1532 if list.len() == 1 {
1533 list[0].literal().map(|literal| &literal.kind)
1539 let (path, applicability) = match &literal {
1540 Some(LitKind::Str(path, ..)) => {
1541 (path.to_string(), Applicability::MachineApplicable)
1543 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1546 err.span_suggestion(
1548 "provide a file path with `=`",
1549 format!("include = \"{}\"", path),
1557 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1558 *at = attr::Attribute {
1559 kind: ast::AttrKind::Normal(
1560 AttrItem { path: meta.path, tokens: meta.kind.tokens(meta.span) },
1567 noop_visit_attribute(at, self)
1571 fn visit_id(&mut self, id: &mut ast::NodeId) {
1573 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1574 *id = self.cx.resolver.next_node_id()
1578 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1579 self.cfg.configure_fn_decl(&mut fn_decl);
1580 noop_visit_fn_decl(fn_decl, self);
1584 pub struct ExpansionConfig<'feat> {
1585 pub crate_name: String,
1586 pub features: Option<&'feat Features>,
1587 pub recursion_limit: usize,
1588 pub trace_mac: bool,
1589 pub should_test: bool, // If false, strip `#[test]` nodes
1590 pub single_step: bool,
1591 pub keep_macs: bool,
1594 impl<'feat> ExpansionConfig<'feat> {
1595 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1599 recursion_limit: 1024,
1607 fn proc_macro_hygiene(&self) -> bool {
1608 self.features.map_or(false, |features| features.proc_macro_hygiene)
1610 fn custom_inner_attributes(&self) -> bool {
1611 self.features.map_or(false, |features| features.custom_inner_attributes)