2 use crate::config::StripUnconfigured;
3 use crate::hygiene::{ExpnData, ExpnId, ExpnKind, SyntaxContext};
4 use crate::mbe::macro_rules::annotate_err_with_kind;
5 use crate::placeholders::{placeholder, PlaceholderExpander};
6 use crate::proc_macro::collect_derives;
8 use rustc_ast_pretty::pprust;
9 use rustc_attr::{self as attr, is_builtin_attr, HasAttrs};
10 use rustc_data_structures::sync::Lrc;
11 use rustc_errors::{Applicability, FatalError, PResult};
12 use rustc_feature::Features;
13 use rustc_parse::configure;
14 use rustc_parse::parser::Parser;
15 use rustc_parse::validate_attr;
16 use rustc_parse::DirectoryOwnership;
17 use rustc_session::parse::{feature_err, ParseSess};
18 use rustc_span::source_map::respan;
19 use rustc_span::symbol::{sym, Symbol};
20 use rustc_span::{FileName, Span, DUMMY_SP};
21 use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
22 use syntax::ast::{ItemKind, MacArgs, MacStmtStyle, StmtKind};
23 use syntax::mut_visit::*;
26 use syntax::tokenstream::{TokenStream, TokenTree};
27 use syntax::util::map_in_place::MapInPlace;
28 use syntax::visit::{self, AssocCtxt, Visitor};
30 use smallvec::{smallvec, SmallVec};
31 use std::io::ErrorKind;
32 use std::ops::DerefMut;
33 use std::path::PathBuf;
35 use std::{iter, mem, slice};
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($($args:tt)*);)?
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 macro _repeating($flat_map_ast_elt) {}
87 placeholder(AstFragmentKind::$Kind, *id, None).$make_ast()
89 _ => panic!("unexpected AST fragment kind")
93 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
95 AstFragment::OptExpr(expr) => expr,
96 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
100 $(pub fn $make_ast(self) -> $AstTy {
102 AstFragment::$Kind(ast) => ast,
103 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
107 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
109 AstFragment::OptExpr(opt_expr) => {
110 visit_clobber(opt_expr, |opt_expr| {
111 if let Some(expr) = opt_expr {
112 vis.filter_map_expr(expr)
118 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
119 $($(AstFragment::$Kind(ast) =>
120 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
124 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
126 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
127 AstFragment::OptExpr(None) => {}
128 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
129 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
130 visitor.$visit_ast_elt(ast_elt, $($args)*);
136 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
137 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
139 Some(self.make(AstFragmentKind::$Kind).$make_ast())
146 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
147 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
148 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
149 Stmts(SmallVec<[ast::Stmt; 1]>) {
150 "statement"; many fn flat_map_stmt; fn visit_stmt(); fn make_stmts;
152 Items(SmallVec<[P<ast::Item>; 1]>) {
153 "item"; many fn flat_map_item; fn visit_item(); fn make_items;
155 TraitItems(SmallVec<[P<ast::AssocItem>; 1]>) {
157 many fn flat_map_trait_item;
158 fn visit_assoc_item(AssocCtxt::Trait);
161 ImplItems(SmallVec<[P<ast::AssocItem>; 1]>) {
163 many fn flat_map_impl_item;
164 fn visit_assoc_item(AssocCtxt::Impl);
167 ForeignItems(SmallVec<[P<ast::ForeignItem>; 1]>) {
169 many fn flat_map_foreign_item;
170 fn visit_foreign_item();
171 fn make_foreign_items;
173 Arms(SmallVec<[ast::Arm; 1]>) {
174 "match arm"; many fn flat_map_arm; fn visit_arm(); fn make_arms;
176 Fields(SmallVec<[ast::Field; 1]>) {
177 "field expression"; many fn flat_map_field; fn visit_field(); fn make_fields;
179 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
181 many fn flat_map_field_pattern;
182 fn visit_field_pattern();
183 fn make_field_patterns;
185 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
187 many fn flat_map_generic_param;
188 fn visit_generic_param();
189 fn make_generic_params;
191 Params(SmallVec<[ast::Param; 1]>) {
192 "function parameter"; many fn flat_map_param; fn visit_param(); fn make_params;
194 StructFields(SmallVec<[ast::StructField; 1]>) {
196 many fn flat_map_struct_field;
197 fn visit_struct_field();
198 fn make_struct_fields;
200 Variants(SmallVec<[ast::Variant; 1]>) {
201 "variant"; many fn flat_map_variant; fn visit_variant(); fn make_variants;
205 impl AstFragmentKind {
206 fn dummy(self, span: Span) -> AstFragment {
207 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
210 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(
214 let mut items = items.into_iter();
216 AstFragmentKind::Arms => {
217 AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
219 AstFragmentKind::Fields => {
220 AstFragment::Fields(items.map(Annotatable::expect_field).collect())
222 AstFragmentKind::FieldPats => {
223 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect())
225 AstFragmentKind::GenericParams => {
226 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
228 AstFragmentKind::Params => {
229 AstFragment::Params(items.map(Annotatable::expect_param).collect())
231 AstFragmentKind::StructFields => {
232 AstFragment::StructFields(items.map(Annotatable::expect_struct_field).collect())
234 AstFragmentKind::Variants => {
235 AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
237 AstFragmentKind::Items => {
238 AstFragment::Items(items.map(Annotatable::expect_item).collect())
240 AstFragmentKind::ImplItems => {
241 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
243 AstFragmentKind::TraitItems => {
244 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
246 AstFragmentKind::ForeignItems => {
247 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
249 AstFragmentKind::Stmts => {
250 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
252 AstFragmentKind::Expr => AstFragment::Expr(
253 items.next().expect("expected exactly one expression").expect_expr(),
255 AstFragmentKind::OptExpr => {
256 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
258 AstFragmentKind::Pat | AstFragmentKind::Ty => {
259 panic!("patterns and types aren't annotatable")
265 pub struct Invocation {
266 pub kind: InvocationKind,
267 pub fragment_kind: AstFragmentKind,
268 pub expansion_data: ExpansionData,
271 pub enum InvocationKind {
277 attr: ast::Attribute,
279 // Required for resolving derive helper attributes.
281 // We temporarily report errors for attribute macros placed after derives
288 /// "Invocation" that contains all derives from an item,
289 /// broken into multiple `Derive` invocations when expanded.
290 /// FIXME: Find a way to remove it.
297 impl InvocationKind {
298 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
299 // HACK: For unnamed fields placeholders should have the same visibility as the actual
300 // fields because for tuple structs/variants resolve determines visibilities of their
301 // constructor using these field visibilities before attributes on them are are expanded.
302 // The assumption is that the attribute expansion cannot change field visibilities,
303 // and it holds because only inert attributes are supported in this position.
305 InvocationKind::Attr { item: Annotatable::StructField(field), .. }
306 | InvocationKind::Derive { item: Annotatable::StructField(field), .. }
307 | InvocationKind::DeriveContainer { item: Annotatable::StructField(field), .. }
308 if field.ident.is_none() =>
310 Some(field.vis.clone())
318 pub fn span(&self) -> Span {
320 InvocationKind::Bang { span, .. } => *span,
321 InvocationKind::Attr { attr, .. } => attr.span,
322 InvocationKind::Derive { path, .. } => path.span,
323 InvocationKind::DeriveContainer { item, .. } => item.span(),
328 pub struct MacroExpander<'a, 'b> {
329 pub cx: &'a mut ExtCtxt<'b>,
330 monotonic: bool, // cf. `cx.monotonic_expander()`
333 impl<'a, 'b> MacroExpander<'a, 'b> {
334 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
335 MacroExpander { cx, monotonic }
338 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
339 let mut module = ModuleData {
340 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
341 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
342 FileName::Real(path) => path,
343 other => PathBuf::from(other.to_string()),
346 module.directory.pop();
347 self.cx.root_path = module.directory.clone();
348 self.cx.current_expansion.module = Rc::new(module);
350 let orig_mod_span = krate.module.inner;
352 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
355 kind: ast::ItemKind::Mod(krate.module),
356 ident: Ident::invalid(),
357 id: ast::DUMMY_NODE_ID,
358 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
362 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
363 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
365 krate.module = module;
368 // Resolution failed so we return an empty expansion
369 krate.attrs = vec![];
370 krate.module = ast::Mod { inner: orig_mod_span, items: vec![], inline: true };
372 Some(ast::Item { span, kind, .. }) => {
373 krate.attrs = vec![];
374 krate.module = ast::Mod { inner: orig_mod_span, items: vec![], inline: true };
378 "expected crate top-level item to be a module after macro expansion, found a {}",
379 kind.descriptive_variant()
384 self.cx.trace_macros_diag();
388 // Recursively expand all macro invocations in this AST fragment.
389 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
390 let orig_expansion_data = self.cx.current_expansion.clone();
391 self.cx.current_expansion.depth = 0;
393 // Collect all macro invocations and replace them with placeholders.
394 let (mut fragment_with_placeholders, mut invocations) =
395 self.collect_invocations(input_fragment, &[]);
397 // Optimization: if we resolve all imports now,
398 // we'll be able to immediately resolve most of imported macros.
399 self.resolve_imports();
401 // Resolve paths in all invocations and produce output expanded fragments for them, but
402 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
403 // The output fragments also go through expansion recursively until no invocations are left.
404 // Unresolved macros produce dummy outputs as a recovery measure.
405 invocations.reverse();
406 let mut expanded_fragments = Vec::new();
407 let mut undetermined_invocations = Vec::new();
408 let (mut progress, mut force) = (false, !self.monotonic);
410 let invoc = if let Some(invoc) = invocations.pop() {
413 self.resolve_imports();
414 if undetermined_invocations.is_empty() {
417 invocations = mem::take(&mut undetermined_invocations);
418 force = !mem::replace(&mut progress, false);
422 let eager_expansion_root =
423 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
424 let res = match self.cx.resolver.resolve_macro_invocation(
426 eager_expansion_root,
430 Err(Indeterminate) => {
431 undetermined_invocations.push(invoc);
437 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
438 self.cx.current_expansion = invoc.expansion_data.clone();
440 // FIXME(jseyfried): Refactor out the following logic
441 let (expanded_fragment, new_invocations) = match res {
442 InvocationRes::Single(ext) => {
443 let fragment = self.expand_invoc(invoc, &ext.kind);
444 self.collect_invocations(fragment, &[])
446 InvocationRes::DeriveContainer(_exts) => {
447 // FIXME: Consider using the derive resolutions (`_exts`) immediately,
448 // instead of enqueuing the derives to be resolved again later.
449 let (derives, item) = match invoc.kind {
450 InvocationKind::DeriveContainer { derives, item } => (derives, item),
453 if !item.derive_allowed() {
454 self.error_derive_forbidden_on_non_adt(&derives, &item);
457 let mut item = self.fully_configure(item);
458 item.visit_attrs(|attrs| attrs.retain(|a| !a.has_name(sym::derive)));
460 let mut derive_placeholders = Vec::with_capacity(derives.len());
461 invocations.reserve(derives.len());
462 for path in derives {
463 let expn_id = ExpnId::fresh(None);
464 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
465 invocations.push(Invocation {
466 kind: InvocationKind::Derive { path, item: item.clone() },
467 fragment_kind: invoc.fragment_kind,
468 expansion_data: ExpansionData {
470 ..invoc.expansion_data.clone()
475 invoc.fragment_kind.expect_from_annotatables(::std::iter::once(item));
476 self.collect_invocations(fragment, &derive_placeholders)
480 if expanded_fragments.len() < depth {
481 expanded_fragments.push(Vec::new());
483 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
484 if !self.cx.ecfg.single_step {
485 invocations.extend(new_invocations.into_iter().rev());
489 self.cx.current_expansion = orig_expansion_data;
491 // Finally incorporate all the expanded macros into the input AST fragment.
492 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
493 while let Some(expanded_fragments) = expanded_fragments.pop() {
494 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
496 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
499 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
500 fragment_with_placeholders
503 fn error_derive_forbidden_on_non_adt(&self, derives: &[Path], item: &Annotatable) {
505 attr::find_by_name(item.attrs(), sym::derive).expect("`derive` attribute should exist");
506 let span = attr.span;
509 .struct_span_err(span, "`derive` may only be applied to structs, enums and unions");
510 if let ast::AttrStyle::Inner = attr.style {
511 let trait_list = derives.iter().map(|t| pprust::path_to_string(t)).collect::<Vec<_>>();
512 let suggestion = format!("#[derive({})]", trait_list.join(", "));
515 "try an outer attribute",
517 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
518 Applicability::MaybeIncorrect,
524 fn resolve_imports(&mut self) {
526 self.cx.resolver.resolve_imports();
530 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
531 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
532 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
533 /// prepares data for resolving paths of macro invocations.
534 fn collect_invocations(
536 mut fragment: AstFragment,
537 extra_placeholders: &[NodeId],
538 ) -> (AstFragment, Vec<Invocation>) {
539 // Resolve `$crate`s in the fragment for pretty-printing.
540 self.cx.resolver.resolve_dollar_crates();
543 let mut collector = InvocationCollector {
544 cfg: StripUnconfigured {
545 sess: self.cx.parse_sess,
546 features: self.cx.ecfg.features,
549 invocations: Vec::new(),
550 monotonic: self.monotonic,
552 fragment.mut_visit_with(&mut collector);
553 fragment.add_placeholders(extra_placeholders);
554 collector.invocations
560 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
563 (fragment, invocations)
566 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
568 StripUnconfigured { sess: self.cx.parse_sess, features: self.cx.ecfg.features };
569 // Since the item itself has already been configured by the InvocationCollector,
570 // we know that fold result vector will contain exactly one element
572 Annotatable::Item(item) => Annotatable::Item(cfg.flat_map_item(item).pop().unwrap()),
573 Annotatable::TraitItem(item) => {
574 Annotatable::TraitItem(cfg.flat_map_trait_item(item).pop().unwrap())
576 Annotatable::ImplItem(item) => {
577 Annotatable::ImplItem(cfg.flat_map_impl_item(item).pop().unwrap())
579 Annotatable::ForeignItem(item) => {
580 Annotatable::ForeignItem(cfg.flat_map_foreign_item(item).pop().unwrap())
582 Annotatable::Stmt(stmt) => {
583 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
585 Annotatable::Expr(mut expr) => Annotatable::Expr({
586 cfg.visit_expr(&mut expr);
589 Annotatable::Arm(arm) => Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap()),
590 Annotatable::Field(field) => {
591 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
593 Annotatable::FieldPat(fp) => {
594 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
596 Annotatable::GenericParam(param) => {
597 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
599 Annotatable::Param(param) => {
600 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
602 Annotatable::StructField(sf) => {
603 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
605 Annotatable::Variant(v) => Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap()),
609 fn error_recursion_limit_reached(&mut self) {
610 let expn_data = self.cx.current_expansion.id.expn_data();
611 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
615 &format!("recursion limit reached while expanding `{}`", expn_data.kind.descr()),
618 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
619 suggested_limit, self.cx.ecfg.crate_name,
622 self.cx.trace_macros_diag();
626 /// A macro's expansion does not fit in this fragment kind.
627 /// For example, a non-type macro in a type position.
628 fn error_wrong_fragment_kind(&mut self, kind: AstFragmentKind, mac: &ast::Mac, span: Span) {
630 "non-{kind} macro in {kind} position: {path}",
632 path = pprust::path_to_string(&mac.path),
634 self.cx.span_err(span, &msg);
635 self.cx.trace_macros_diag();
638 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
639 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
640 self.error_recursion_limit_reached();
643 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
645 InvocationKind::Bang { mac, .. } => match ext {
646 SyntaxExtensionKind::Bang(expander) => {
647 self.gate_proc_macro_expansion_kind(span, fragment_kind);
648 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
649 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
651 SyntaxExtensionKind::LegacyBang(expander) => {
652 let prev = self.cx.current_expansion.prior_type_ascription;
653 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
654 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
655 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
658 self.error_wrong_fragment_kind(fragment_kind, &mac, span);
659 fragment_kind.dummy(span)
661 self.cx.current_expansion.prior_type_ascription = prev;
666 InvocationKind::Attr { attr, mut item, .. } => match ext {
667 SyntaxExtensionKind::Attr(expander) => {
668 self.gate_proc_macro_input(&item);
669 self.gate_proc_macro_attr_item(span, &item);
670 let item_tok = TokenTree::token(
671 token::Interpolated(Lrc::new(match item {
672 Annotatable::Item(item) => token::NtItem(item),
673 Annotatable::TraitItem(item) => token::NtTraitItem(item),
674 Annotatable::ImplItem(item) => token::NtImplItem(item),
675 Annotatable::ForeignItem(item) => token::NtForeignItem(item),
676 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
677 Annotatable::Expr(expr) => token::NtExpr(expr),
679 | Annotatable::Field(..)
680 | Annotatable::FieldPat(..)
681 | Annotatable::GenericParam(..)
682 | Annotatable::Param(..)
683 | Annotatable::StructField(..)
684 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
689 let item = attr.unwrap_normal_item();
690 if let MacArgs::Eq(..) = item.args {
691 self.cx.span_err(span, "key-value macro attributes are not supported");
694 expander.expand(self.cx, span, item.args.inner_tokens(), item_tok);
695 self.parse_ast_fragment(tok_result, fragment_kind, &item.path, span)
697 SyntaxExtensionKind::LegacyAttr(expander) => {
698 match validate_attr::parse_meta(self.cx.parse_sess, &attr) {
700 let item = expander.expand(self.cx, span, &meta, item);
701 fragment_kind.expect_from_annotatables(item)
705 fragment_kind.dummy(span)
709 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
710 attr::mark_known(&attr);
712 attr::mark_used(&attr);
714 item.visit_attrs(|attrs| attrs.push(attr));
715 fragment_kind.expect_from_annotatables(iter::once(item))
719 InvocationKind::Derive { path, item } => match ext {
720 SyntaxExtensionKind::Derive(expander)
721 | SyntaxExtensionKind::LegacyDerive(expander) => {
722 if !item.derive_allowed() {
723 return fragment_kind.dummy(span);
725 if let SyntaxExtensionKind::Derive(..) = ext {
726 self.gate_proc_macro_input(&item);
728 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
729 let items = expander.expand(self.cx, span, &meta, item);
730 fragment_kind.expect_from_annotatables(items)
734 InvocationKind::DeriveContainer { .. } => unreachable!(),
738 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
739 let kind = match item {
741 | Annotatable::TraitItem(_)
742 | Annotatable::ImplItem(_)
743 | Annotatable::ForeignItem(_) => return,
744 Annotatable::Stmt(_) => "statements",
745 Annotatable::Expr(_) => "expressions",
747 | Annotatable::Field(..)
748 | Annotatable::FieldPat(..)
749 | Annotatable::GenericParam(..)
750 | Annotatable::Param(..)
751 | Annotatable::StructField(..)
752 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
754 if self.cx.ecfg.proc_macro_hygiene() {
759 sym::proc_macro_hygiene,
761 &format!("custom attributes cannot be applied to {}", kind),
766 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
767 struct GateProcMacroInput<'a> {
768 parse_sess: &'a ParseSess,
771 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
772 fn visit_item(&mut self, item: &'ast ast::Item) {
774 ast::ItemKind::Mod(module) if !module.inline => {
777 sym::proc_macro_hygiene,
779 "non-inline modules in proc macro input are unstable",
786 visit::walk_item(self, item);
789 fn visit_mac(&mut self, _: &'ast ast::Mac) {}
792 if !self.cx.ecfg.proc_macro_hygiene() {
793 annotatable.visit_with(&mut GateProcMacroInput { parse_sess: self.cx.parse_sess });
797 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
798 let kind = match kind {
799 AstFragmentKind::Expr | AstFragmentKind::OptExpr => "expressions",
800 AstFragmentKind::Pat => "patterns",
801 AstFragmentKind::Stmts => "statements",
803 | AstFragmentKind::Items
804 | AstFragmentKind::TraitItems
805 | AstFragmentKind::ImplItems
806 | AstFragmentKind::ForeignItems => return,
807 AstFragmentKind::Arms
808 | AstFragmentKind::Fields
809 | AstFragmentKind::FieldPats
810 | AstFragmentKind::GenericParams
811 | AstFragmentKind::Params
812 | AstFragmentKind::StructFields
813 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
815 if self.cx.ecfg.proc_macro_hygiene() {
820 sym::proc_macro_hygiene,
822 &format!("procedural macros cannot be expanded to {}", kind),
827 fn parse_ast_fragment(
830 kind: AstFragmentKind,
834 let mut parser = self.cx.new_parser_from_tts(toks);
835 match parse_ast_fragment(&mut parser, kind, false) {
837 ensure_complete_parse(&mut parser, path, kind.name(), span);
842 annotate_err_with_kind(&mut err, kind, span);
844 self.cx.trace_macros_diag();
851 pub fn parse_ast_fragment<'a>(
852 this: &mut Parser<'a>,
853 kind: AstFragmentKind,
854 macro_legacy_warnings: bool,
855 ) -> PResult<'a, AstFragment> {
857 AstFragmentKind::Items => {
858 let mut items = SmallVec::new();
859 while let Some(item) = this.parse_item()? {
862 AstFragment::Items(items)
864 AstFragmentKind::TraitItems => {
865 let mut items = SmallVec::new();
866 while this.token != token::Eof {
867 items.push(this.parse_trait_item(&mut false)?);
869 AstFragment::TraitItems(items)
871 AstFragmentKind::ImplItems => {
872 let mut items = SmallVec::new();
873 while this.token != token::Eof {
874 items.push(this.parse_impl_item(&mut false)?);
876 AstFragment::ImplItems(items)
878 AstFragmentKind::ForeignItems => {
879 let mut items = SmallVec::new();
880 while this.token != token::Eof {
881 items.push(this.parse_foreign_item(&mut false)?);
883 AstFragment::ForeignItems(items)
885 AstFragmentKind::Stmts => {
886 let mut stmts = SmallVec::new();
887 while this.token != token::Eof &&
888 // won't make progress on a `}`
889 this.token != token::CloseDelim(token::Brace)
891 if let Some(stmt) = this.parse_full_stmt(macro_legacy_warnings)? {
895 AstFragment::Stmts(stmts)
897 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
898 AstFragmentKind::OptExpr => {
899 if this.token != token::Eof {
900 AstFragment::OptExpr(Some(this.parse_expr()?))
902 AstFragment::OptExpr(None)
905 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
906 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?),
907 AstFragmentKind::Arms
908 | AstFragmentKind::Fields
909 | AstFragmentKind::FieldPats
910 | AstFragmentKind::GenericParams
911 | AstFragmentKind::Params
912 | AstFragmentKind::StructFields
913 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
917 pub fn ensure_complete_parse<'a>(
918 this: &mut Parser<'a>,
923 if this.token != token::Eof {
924 let token = pprust::token_to_string(&this.token);
925 let msg = format!("macro expansion ignores token `{}` and any following", token);
926 // Avoid emitting backtrace info twice.
927 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
928 let mut err = this.struct_span_err(def_site_span, &msg);
929 err.span_label(span, "caused by the macro expansion here");
931 "the usage of `{}!` is likely invalid in {} context",
932 pprust::path_to_string(macro_path),
936 let semi_span = this.sess.source_map().next_point(span);
938 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
939 match this.sess.source_map().span_to_snippet(semi_full_span) {
940 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
943 "you might be missing a semicolon here",
945 Applicability::MaybeIncorrect,
954 struct InvocationCollector<'a, 'b> {
955 cx: &'a mut ExtCtxt<'b>,
956 cfg: StripUnconfigured<'a>,
957 invocations: Vec<Invocation>,
961 impl<'a, 'b> InvocationCollector<'a, 'b> {
962 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
963 // Expansion data for all the collected invocations is set upon their resolution,
964 // with exception of the derive container case which is not resolved and can get
965 // its expansion data immediately.
966 let expn_data = match &kind {
967 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
968 parent: self.cx.current_expansion.id,
970 ExpnKind::Macro(MacroKind::Attr, sym::derive),
972 self.cx.parse_sess.edition,
977 let expn_id = ExpnId::fresh(expn_data);
978 let vis = kind.placeholder_visibility();
979 self.invocations.push(Invocation {
982 expansion_data: ExpansionData {
984 depth: self.cx.current_expansion.depth + 1,
985 ..self.cx.current_expansion.clone()
988 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
991 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
992 self.collect(kind, InvocationKind::Bang { mac, span })
997 attr: Option<ast::Attribute>,
1000 kind: AstFragmentKind,
1006 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
1007 None => InvocationKind::DeriveContainer { derives, item },
1014 attrs: &mut Vec<ast::Attribute>,
1015 after_derive: &mut bool,
1016 ) -> Option<ast::Attribute> {
1020 if a.has_name(sym::derive) {
1021 *after_derive = true;
1023 !attr::is_known(a) && !is_builtin_attr(a)
1025 .map(|i| attrs.remove(i));
1026 if let Some(attr) = &attr {
1027 if !self.cx.ecfg.custom_inner_attributes()
1028 && attr.style == ast::AttrStyle::Inner
1029 && !attr.has_name(sym::test)
1032 &self.cx.parse_sess,
1033 sym::custom_inner_attributes,
1035 "non-builtin inner attributes are unstable",
1043 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
1046 item: &mut impl HasAttrs,
1047 ) -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool) {
1048 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
1050 item.visit_attrs(|mut attrs| {
1051 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1052 traits = collect_derives(&mut self.cx, &mut attrs);
1055 (attr, traits, after_derive)
1058 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1059 /// to the unused-attributes lint (making it an error on statements and expressions
1060 /// is a breaking change)
1061 fn classify_nonitem(
1063 nonitem: &mut impl HasAttrs,
1064 ) -> (Option<ast::Attribute>, /* after_derive */ bool) {
1065 let (mut attr, mut after_derive) = (None, false);
1067 nonitem.visit_attrs(|mut attrs| {
1068 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1071 (attr, after_derive)
1074 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1075 self.cfg.configure(node)
1078 // Detect use of feature-gated or invalid attributes on macro invocations
1079 // since they will not be detected after macro expansion.
1080 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1081 let features = self.cx.ecfg.features.unwrap();
1082 for attr in attrs.iter() {
1083 rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1084 validate_attr::check_meta(self.cx.parse_sess, attr);
1086 // macros are expanded before any lint passes so this warning has to be hardcoded
1087 if attr.has_name(sym::derive) {
1089 .struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1090 .note("this may become a hard error in a future release")
1097 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1098 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1099 self.cfg.configure_expr(expr);
1100 visit_clobber(expr.deref_mut(), |mut expr| {
1101 self.cfg.configure_expr_kind(&mut expr.kind);
1103 // ignore derives so they remain unused
1104 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1107 // Collect the invoc regardless of whether or not attributes are permitted here
1108 // expansion will eat the attribute so it won't error later.
1109 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1111 // AstFragmentKind::Expr requires the macro to emit an expression.
1116 Annotatable::Expr(P(expr)),
1117 AstFragmentKind::Expr,
1124 if let ast::ExprKind::Mac(mac) = expr.kind {
1125 self.check_attributes(&expr.attrs);
1126 self.collect_bang(mac, expr.span, AstFragmentKind::Expr).make_expr().into_inner()
1128 noop_visit_expr(&mut expr, self);
1134 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1135 let mut arm = configure!(self, arm);
1137 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1138 if attr.is_some() || !traits.is_empty() {
1143 Annotatable::Arm(arm),
1144 AstFragmentKind::Arms,
1150 noop_flat_map_arm(arm, self)
1153 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1154 let mut field = configure!(self, field);
1156 let (attr, traits, after_derive) = self.classify_item(&mut field);
1157 if attr.is_some() || !traits.is_empty() {
1162 Annotatable::Field(field),
1163 AstFragmentKind::Fields,
1169 noop_flat_map_field(field, self)
1172 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1173 let mut fp = configure!(self, fp);
1175 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1176 if attr.is_some() || !traits.is_empty() {
1181 Annotatable::FieldPat(fp),
1182 AstFragmentKind::FieldPats,
1185 .make_field_patterns();
1188 noop_flat_map_field_pattern(fp, self)
1191 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1192 let mut p = configure!(self, p);
1194 let (attr, traits, after_derive) = self.classify_item(&mut p);
1195 if attr.is_some() || !traits.is_empty() {
1200 Annotatable::Param(p),
1201 AstFragmentKind::Params,
1207 noop_flat_map_param(p, self)
1210 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1211 let mut sf = configure!(self, sf);
1213 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1214 if attr.is_some() || !traits.is_empty() {
1219 Annotatable::StructField(sf),
1220 AstFragmentKind::StructFields,
1223 .make_struct_fields();
1226 noop_flat_map_struct_field(sf, self)
1229 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1230 let mut variant = configure!(self, variant);
1232 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1233 if attr.is_some() || !traits.is_empty() {
1238 Annotatable::Variant(variant),
1239 AstFragmentKind::Variants,
1245 noop_flat_map_variant(variant, self)
1248 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1249 let expr = configure!(self, expr);
1250 expr.filter_map(|mut expr| {
1251 self.cfg.configure_expr_kind(&mut expr.kind);
1253 // Ignore derives so they remain unused.
1254 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1257 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1263 Annotatable::Expr(P(expr)),
1264 AstFragmentKind::OptExpr,
1268 .map(|expr| expr.into_inner());
1271 if let ast::ExprKind::Mac(mac) = expr.kind {
1272 self.check_attributes(&expr.attrs);
1273 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1275 .map(|expr| expr.into_inner())
1278 noop_visit_expr(&mut expr, self);
1285 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1286 self.cfg.configure_pat(pat);
1288 PatKind::Mac(_) => {}
1289 _ => return noop_visit_pat(pat, self),
1292 visit_clobber(pat, |mut pat| match mem::replace(&mut pat.kind, PatKind::Wild) {
1293 PatKind::Mac(mac) => self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1294 _ => unreachable!(),
1298 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1299 let mut stmt = configure!(self, stmt);
1301 // we'll expand attributes on expressions separately
1302 if !stmt.is_expr() {
1303 let (attr, derives, after_derive) = if stmt.is_item() {
1304 self.classify_item(&mut stmt)
1306 // ignore derives on non-item statements so it falls through
1307 // to the unused-attributes lint
1308 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1309 (attr, vec![], after_derive)
1312 if attr.is_some() || !derives.is_empty() {
1317 Annotatable::Stmt(P(stmt)),
1318 AstFragmentKind::Stmts,
1325 if let StmtKind::Mac(mac) = stmt.kind {
1326 let (mac, style, attrs) = mac.into_inner();
1327 self.check_attributes(&attrs);
1328 let mut placeholder =
1329 self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts).make_stmts();
1331 // If this is a macro invocation with a semicolon, then apply that
1332 // semicolon to the final statement produced by expansion.
1333 if style == MacStmtStyle::Semicolon {
1334 if let Some(stmt) = placeholder.pop() {
1335 placeholder.push(stmt.add_trailing_semicolon());
1342 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1343 let ast::Stmt { id, kind, span } = stmt;
1344 noop_flat_map_stmt_kind(kind, self)
1346 .map(|kind| ast::Stmt { id, kind, span })
1350 fn visit_block(&mut self, block: &mut P<Block>) {
1351 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1352 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1353 noop_visit_block(block, self);
1354 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1357 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1358 let mut item = configure!(self, item);
1360 let (attr, traits, after_derive) = self.classify_item(&mut item);
1361 if attr.is_some() || !traits.is_empty() {
1366 Annotatable::Item(item),
1367 AstFragmentKind::Items,
1374 ast::ItemKind::Mac(..) => {
1375 self.check_attributes(&item.attrs);
1376 item.and_then(|item| match item.kind {
1377 ItemKind::Mac(mac) => self
1379 AstFragmentKind::Items,
1380 InvocationKind::Bang { mac, span: item.span },
1383 _ => unreachable!(),
1386 ast::ItemKind::Mod(ast::Mod { inner, inline, .. })
1387 if item.ident != Ident::invalid() =>
1389 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1390 let mut module = (*self.cx.current_expansion.module).clone();
1391 module.mod_path.push(item.ident);
1394 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1395 self.cx.current_expansion.directory_ownership =
1396 DirectoryOwnership::Owned { relative: None };
1397 module.directory.push(&*path.as_str());
1399 module.directory.push(&*item.ident.as_str());
1402 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1403 let mut path = match path {
1404 FileName::Real(path) => path,
1405 other => PathBuf::from(other.to_string()),
1407 let directory_ownership = match path.file_name().unwrap().to_str() {
1408 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1409 Some(_) => DirectoryOwnership::Owned { relative: Some(item.ident) },
1410 None => DirectoryOwnership::UnownedViaMod,
1413 module.directory = path;
1414 self.cx.current_expansion.directory_ownership = directory_ownership;
1418 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1419 let result = noop_flat_map_item(item, self);
1420 self.cx.current_expansion.module = orig_module;
1421 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1425 _ => noop_flat_map_item(item, self),
1429 fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1430 let mut item = configure!(self, item);
1432 let (attr, traits, after_derive) = self.classify_item(&mut item);
1433 if attr.is_some() || !traits.is_empty() {
1438 Annotatable::TraitItem(item),
1439 AstFragmentKind::TraitItems,
1442 .make_trait_items();
1446 ast::AssocItemKind::Macro(..) => {
1447 self.check_attributes(&item.attrs);
1448 item.and_then(|item| match item.kind {
1449 ast::AssocItemKind::Macro(mac) => self
1450 .collect_bang(mac, item.span, AstFragmentKind::TraitItems)
1451 .make_trait_items(),
1452 _ => unreachable!(),
1455 _ => noop_flat_map_assoc_item(item, self),
1459 fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1460 let mut item = configure!(self, item);
1462 let (attr, traits, after_derive) = self.classify_item(&mut item);
1463 if attr.is_some() || !traits.is_empty() {
1468 Annotatable::ImplItem(item),
1469 AstFragmentKind::ImplItems,
1476 ast::AssocItemKind::Macro(..) => {
1477 self.check_attributes(&item.attrs);
1478 item.and_then(|item| match item.kind {
1479 ast::AssocItemKind::Macro(mac) => self
1480 .collect_bang(mac, item.span, AstFragmentKind::ImplItems)
1482 _ => unreachable!(),
1485 _ => noop_flat_map_assoc_item(item, self),
1489 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1491 ast::TyKind::Mac(_) => {}
1492 _ => return noop_visit_ty(ty, self),
1495 visit_clobber(ty, |mut ty| match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1496 ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1497 _ => unreachable!(),
1501 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1502 self.cfg.configure_foreign_mod(foreign_mod);
1503 noop_visit_foreign_mod(foreign_mod, self);
1506 fn flat_map_foreign_item(
1508 mut foreign_item: P<ast::ForeignItem>,
1509 ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
1510 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1512 if attr.is_some() || !traits.is_empty() {
1517 Annotatable::ForeignItem(foreign_item),
1518 AstFragmentKind::ForeignItems,
1521 .make_foreign_items();
1524 match foreign_item.kind {
1525 ast::ForeignItemKind::Macro(..) => {
1526 self.check_attributes(&foreign_item.attrs);
1527 foreign_item.and_then(|item| match item.kind {
1528 ast::ForeignItemKind::Macro(mac) => self
1529 .collect_bang(mac, item.span, AstFragmentKind::ForeignItems)
1530 .make_foreign_items(),
1531 _ => unreachable!(),
1534 _ => noop_flat_map_foreign_item(foreign_item, self),
1538 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1540 ast::ItemKind::MacroDef(..) => {}
1542 self.cfg.configure_item_kind(item);
1543 noop_visit_item_kind(item, self);
1548 fn flat_map_generic_param(
1550 param: ast::GenericParam,
1551 ) -> SmallVec<[ast::GenericParam; 1]> {
1552 let mut param = configure!(self, param);
1554 let (attr, traits, after_derive) = self.classify_item(&mut param);
1555 if attr.is_some() || !traits.is_empty() {
1560 Annotatable::GenericParam(param),
1561 AstFragmentKind::GenericParams,
1564 .make_generic_params();
1567 noop_flat_map_generic_param(param, self)
1570 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1571 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1572 // contents="file contents")]` attributes
1573 if !at.check_name(sym::doc) {
1574 return noop_visit_attribute(at, self);
1577 if let Some(list) = at.meta_item_list() {
1578 if !list.iter().any(|it| it.check_name(sym::include)) {
1579 return noop_visit_attribute(at, self);
1582 let mut items = vec![];
1584 for mut it in list {
1585 if !it.check_name(sym::include) {
1587 noop_visit_meta_list_item(&mut it, self);
1593 if let Some(file) = it.value_str() {
1594 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1595 self.check_attributes(slice::from_ref(at));
1596 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1597 // avoid loading the file if they haven't enabled the feature
1598 return noop_visit_attribute(at, self);
1601 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1602 Ok(filename) => filename,
1609 match self.cx.source_map().load_file(&filename) {
1610 Ok(source_file) => {
1611 let src = source_file
1614 .expect("freshly loaded file should have a source");
1615 let src_interned = Symbol::intern(src.as_str());
1617 let include_info = vec![
1618 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1619 Ident::with_dummy_span(sym::file),
1623 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1624 Ident::with_dummy_span(sym::contents),
1630 let include_ident = Ident::with_dummy_span(sym::include);
1631 let item = attr::mk_list_item(include_ident, include_info);
1632 items.push(ast::NestedMetaItem::MetaItem(item));
1636 it.meta_item().and_then(|item| item.name_value_literal()).unwrap();
1638 if e.kind() == ErrorKind::InvalidData {
1642 &format!("{} wasn't a utf-8 file", filename.display()),
1644 .span_label(lit.span, "contains invalid utf-8")
1647 let mut err = self.cx.struct_span_err(
1649 &format!("couldn't read {}: {}", filename.display(), e),
1651 err.span_label(lit.span, "couldn't read file");
1658 let mut err = self.cx.struct_span_err(
1660 &format!("expected path to external documentation"),
1663 // Check if the user erroneously used `doc(include(...))` syntax.
1664 let literal = it.meta_item_list().and_then(|list| {
1665 if list.len() == 1 {
1666 list[0].literal().map(|literal| &literal.kind)
1672 let (path, applicability) = match &literal {
1673 Some(LitKind::Str(path, ..)) => {
1674 (path.to_string(), Applicability::MachineApplicable)
1676 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1679 err.span_suggestion(
1681 "provide a file path with `=`",
1682 format!("include = \"{}\"", path),
1690 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1691 *at = ast::Attribute {
1692 kind: ast::AttrKind::Normal(AttrItem {
1694 args: meta.kind.mac_args(meta.span),
1701 noop_visit_attribute(at, self)
1705 fn visit_id(&mut self, id: &mut ast::NodeId) {
1707 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1708 *id = self.cx.resolver.next_node_id()
1712 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1713 self.cfg.configure_fn_decl(&mut fn_decl);
1714 noop_visit_fn_decl(fn_decl, self);
1718 pub struct ExpansionConfig<'feat> {
1719 pub crate_name: String,
1720 pub features: Option<&'feat Features>,
1721 pub recursion_limit: usize,
1722 pub trace_mac: bool,
1723 pub should_test: bool, // If false, strip `#[test]` nodes
1724 pub single_step: bool,
1725 pub keep_macs: bool,
1728 impl<'feat> ExpansionConfig<'feat> {
1729 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1733 recursion_limit: 1024,
1741 fn proc_macro_hygiene(&self) -> bool {
1742 self.features.map_or(false, |features| features.proc_macro_hygiene)
1744 fn custom_inner_attributes(&self) -> bool {
1745 self.features.map_or(false, |features| features.custom_inner_attributes)