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, 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;)?
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);
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]>) {
156 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
158 ImplItems(SmallVec<[P<ast::AssocItem>; 1]>) {
159 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
161 ForeignItems(SmallVec<[P<ast::ForeignItem>; 1]>) {
163 many fn flat_map_foreign_item;
164 fn visit_foreign_item;
165 fn make_foreign_items;
167 Arms(SmallVec<[ast::Arm; 1]>) {
168 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
170 Fields(SmallVec<[ast::Field; 1]>) {
171 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
173 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
175 many fn flat_map_field_pattern;
176 fn visit_field_pattern;
177 fn make_field_patterns;
179 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
181 many fn flat_map_generic_param;
182 fn visit_generic_param;
183 fn make_generic_params;
185 Params(SmallVec<[ast::Param; 1]>) {
186 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
188 StructFields(SmallVec<[ast::StructField; 1]>) {
190 many fn flat_map_struct_field;
191 fn visit_struct_field;
192 fn make_struct_fields;
194 Variants(SmallVec<[ast::Variant; 1]>) {
195 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
199 impl AstFragmentKind {
200 fn dummy(self, span: Span) -> AstFragment {
201 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
204 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(
208 let mut items = items.into_iter();
210 AstFragmentKind::Arms => {
211 AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
213 AstFragmentKind::Fields => {
214 AstFragment::Fields(items.map(Annotatable::expect_field).collect())
216 AstFragmentKind::FieldPats => {
217 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect())
219 AstFragmentKind::GenericParams => {
220 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
222 AstFragmentKind::Params => {
223 AstFragment::Params(items.map(Annotatable::expect_param).collect())
225 AstFragmentKind::StructFields => {
226 AstFragment::StructFields(items.map(Annotatable::expect_struct_field).collect())
228 AstFragmentKind::Variants => {
229 AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
231 AstFragmentKind::Items => {
232 AstFragment::Items(items.map(Annotatable::expect_item).collect())
234 AstFragmentKind::ImplItems => {
235 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
237 AstFragmentKind::TraitItems => {
238 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
240 AstFragmentKind::ForeignItems => {
241 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
243 AstFragmentKind::Stmts => {
244 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
246 AstFragmentKind::Expr => AstFragment::Expr(
247 items.next().expect("expected exactly one expression").expect_expr(),
249 AstFragmentKind::OptExpr => {
250 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
252 AstFragmentKind::Pat | AstFragmentKind::Ty => {
253 panic!("patterns and types aren't annotatable")
259 pub struct Invocation {
260 pub kind: InvocationKind,
261 pub fragment_kind: AstFragmentKind,
262 pub expansion_data: ExpansionData,
265 pub enum InvocationKind {
271 attr: ast::Attribute,
273 // Required for resolving derive helper attributes.
275 // We temporarily report errors for attribute macros placed after derives
282 /// "Invocation" that contains all derives from an item,
283 /// broken into multiple `Derive` invocations when expanded.
284 /// FIXME: Find a way to remove it.
291 impl InvocationKind {
292 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
293 // HACK: For unnamed fields placeholders should have the same visibility as the actual
294 // fields because for tuple structs/variants resolve determines visibilities of their
295 // constructor using these field visibilities before attributes on them are are expanded.
296 // The assumption is that the attribute expansion cannot change field visibilities,
297 // and it holds because only inert attributes are supported in this position.
299 InvocationKind::Attr { item: Annotatable::StructField(field), .. }
300 | InvocationKind::Derive { item: Annotatable::StructField(field), .. }
301 | InvocationKind::DeriveContainer { item: Annotatable::StructField(field), .. }
302 if field.ident.is_none() =>
304 Some(field.vis.clone())
312 pub fn span(&self) -> Span {
314 InvocationKind::Bang { span, .. } => *span,
315 InvocationKind::Attr { attr, .. } => attr.span,
316 InvocationKind::Derive { path, .. } => path.span,
317 InvocationKind::DeriveContainer { item, .. } => item.span(),
322 pub struct MacroExpander<'a, 'b> {
323 pub cx: &'a mut ExtCtxt<'b>,
324 monotonic: bool, // cf. `cx.monotonic_expander()`
327 impl<'a, 'b> MacroExpander<'a, 'b> {
328 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
329 MacroExpander { cx, monotonic }
332 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
333 let mut module = ModuleData {
334 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
335 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
336 FileName::Real(path) => path,
337 other => PathBuf::from(other.to_string()),
340 module.directory.pop();
341 self.cx.root_path = module.directory.clone();
342 self.cx.current_expansion.module = Rc::new(module);
344 let orig_mod_span = krate.module.inner;
346 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
349 kind: ast::ItemKind::Mod(krate.module),
350 ident: Ident::invalid(),
351 id: ast::DUMMY_NODE_ID,
352 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
356 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
357 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
359 krate.module = module;
362 // Resolution failed so we return an empty expansion
363 krate.attrs = vec![];
364 krate.module = ast::Mod { inner: orig_mod_span, items: vec![], inline: true };
368 self.cx.trace_macros_diag();
372 // Recursively expand all macro invocations in this AST fragment.
373 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
374 let orig_expansion_data = self.cx.current_expansion.clone();
375 self.cx.current_expansion.depth = 0;
377 // Collect all macro invocations and replace them with placeholders.
378 let (mut fragment_with_placeholders, mut invocations) =
379 self.collect_invocations(input_fragment, &[]);
381 // Optimization: if we resolve all imports now,
382 // we'll be able to immediately resolve most of imported macros.
383 self.resolve_imports();
385 // Resolve paths in all invocations and produce output expanded fragments for them, but
386 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
387 // The output fragments also go through expansion recursively until no invocations are left.
388 // Unresolved macros produce dummy outputs as a recovery measure.
389 invocations.reverse();
390 let mut expanded_fragments = Vec::new();
391 let mut undetermined_invocations = Vec::new();
392 let (mut progress, mut force) = (false, !self.monotonic);
394 let invoc = if let Some(invoc) = invocations.pop() {
397 self.resolve_imports();
398 if undetermined_invocations.is_empty() {
401 invocations = mem::take(&mut undetermined_invocations);
402 force = !mem::replace(&mut progress, false);
406 let eager_expansion_root =
407 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
408 let res = match self.cx.resolver.resolve_macro_invocation(
410 eager_expansion_root,
414 Err(Indeterminate) => {
415 undetermined_invocations.push(invoc);
421 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
422 self.cx.current_expansion = invoc.expansion_data.clone();
424 // FIXME(jseyfried): Refactor out the following logic
425 let (expanded_fragment, new_invocations) = match res {
426 InvocationRes::Single(ext) => {
427 let fragment = self.expand_invoc(invoc, &ext.kind);
428 self.collect_invocations(fragment, &[])
430 InvocationRes::DeriveContainer(_exts) => {
431 // FIXME: Consider using the derive resolutions (`_exts`) immediately,
432 // instead of enqueuing the derives to be resolved again later.
433 let (derives, item) = match invoc.kind {
434 InvocationKind::DeriveContainer { derives, item } => (derives, item),
437 if !item.derive_allowed() {
438 let attr = attr::find_by_name(item.attrs(), sym::derive)
439 .expect("`derive` attribute should exist");
440 let span = attr.span;
441 let mut err = self.cx.struct_span_err(
443 "`derive` may only be applied to structs, enums and unions",
445 if let ast::AttrStyle::Inner = attr.style {
446 let trait_list = derives
448 .map(|t| pprust::path_to_string(t))
449 .collect::<Vec<_>>();
450 let suggestion = format!("#[derive({})]", trait_list.join(", "));
453 "try an outer attribute",
455 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
456 Applicability::MaybeIncorrect,
462 let mut item = self.fully_configure(item);
463 item.visit_attrs(|attrs| attrs.retain(|a| !a.has_name(sym::derive)));
465 let mut derive_placeholders = Vec::with_capacity(derives.len());
466 invocations.reserve(derives.len());
467 for path in derives {
468 let expn_id = ExpnId::fresh(None);
469 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
470 invocations.push(Invocation {
471 kind: InvocationKind::Derive { path, item: item.clone() },
472 fragment_kind: invoc.fragment_kind,
473 expansion_data: ExpansionData {
475 ..invoc.expansion_data.clone()
480 invoc.fragment_kind.expect_from_annotatables(::std::iter::once(item));
481 self.collect_invocations(fragment, &derive_placeholders)
485 if expanded_fragments.len() < depth {
486 expanded_fragments.push(Vec::new());
488 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
489 if !self.cx.ecfg.single_step {
490 invocations.extend(new_invocations.into_iter().rev());
494 self.cx.current_expansion = orig_expansion_data;
496 // Finally incorporate all the expanded macros into the input AST fragment.
497 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
498 while let Some(expanded_fragments) = expanded_fragments.pop() {
499 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
501 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
504 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
505 fragment_with_placeholders
508 fn resolve_imports(&mut self) {
510 self.cx.resolver.resolve_imports();
514 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
515 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
516 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
517 /// prepares data for resolving paths of macro invocations.
518 fn collect_invocations(
520 mut fragment: AstFragment,
521 extra_placeholders: &[NodeId],
522 ) -> (AstFragment, Vec<Invocation>) {
523 // Resolve `$crate`s in the fragment for pretty-printing.
524 self.cx.resolver.resolve_dollar_crates();
527 let mut collector = InvocationCollector {
528 cfg: StripUnconfigured {
529 sess: self.cx.parse_sess,
530 features: self.cx.ecfg.features,
533 invocations: Vec::new(),
534 monotonic: self.monotonic,
536 fragment.mut_visit_with(&mut collector);
537 fragment.add_placeholders(extra_placeholders);
538 collector.invocations
544 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
547 (fragment, invocations)
550 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
552 StripUnconfigured { sess: self.cx.parse_sess, features: self.cx.ecfg.features };
553 // Since the item itself has already been configured by the InvocationCollector,
554 // we know that fold result vector will contain exactly one element
556 Annotatable::Item(item) => Annotatable::Item(cfg.flat_map_item(item).pop().unwrap()),
557 Annotatable::TraitItem(item) => {
558 Annotatable::TraitItem(cfg.flat_map_trait_item(item).pop().unwrap())
560 Annotatable::ImplItem(item) => {
561 Annotatable::ImplItem(cfg.flat_map_impl_item(item).pop().unwrap())
563 Annotatable::ForeignItem(item) => {
564 Annotatable::ForeignItem(cfg.flat_map_foreign_item(item).pop().unwrap())
566 Annotatable::Stmt(stmt) => {
567 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
569 Annotatable::Expr(mut expr) => Annotatable::Expr({
570 cfg.visit_expr(&mut expr);
573 Annotatable::Arm(arm) => Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap()),
574 Annotatable::Field(field) => {
575 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
577 Annotatable::FieldPat(fp) => {
578 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
580 Annotatable::GenericParam(param) => {
581 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
583 Annotatable::Param(param) => {
584 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
586 Annotatable::StructField(sf) => {
587 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
589 Annotatable::Variant(v) => Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap()),
593 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
594 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
595 let expn_data = self.cx.current_expansion.id.expn_data();
596 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
597 let mut err = self.cx.struct_span_err(
599 &format!("recursion limit reached while expanding `{}`", expn_data.kind.descr()),
602 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
606 self.cx.trace_macros_diag();
610 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
612 InvocationKind::Bang { mac, .. } => match ext {
613 SyntaxExtensionKind::Bang(expander) => {
614 self.gate_proc_macro_expansion_kind(span, fragment_kind);
615 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
616 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
618 SyntaxExtensionKind::LegacyBang(expander) => {
619 let prev = self.cx.current_expansion.prior_type_ascription;
620 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
621 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
622 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
626 "non-{kind} macro in {kind} position: {path}",
627 kind = fragment_kind.name(),
628 path = pprust::path_to_string(&mac.path),
630 self.cx.span_err(span, &msg);
631 self.cx.trace_macros_diag();
632 fragment_kind.dummy(span)
634 self.cx.current_expansion.prior_type_ascription = prev;
639 InvocationKind::Attr { attr, mut item, .. } => match ext {
640 SyntaxExtensionKind::Attr(expander) => {
641 self.gate_proc_macro_input(&item);
642 self.gate_proc_macro_attr_item(span, &item);
643 let item_tok = TokenTree::token(
644 token::Interpolated(Lrc::new(match item {
645 Annotatable::Item(item) => token::NtItem(item),
646 Annotatable::TraitItem(item) => token::NtTraitItem(item),
647 Annotatable::ImplItem(item) => token::NtImplItem(item),
648 Annotatable::ForeignItem(item) => token::NtForeignItem(item),
649 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
650 Annotatable::Expr(expr) => token::NtExpr(expr),
652 | Annotatable::Field(..)
653 | Annotatable::FieldPat(..)
654 | Annotatable::GenericParam(..)
655 | Annotatable::Param(..)
656 | Annotatable::StructField(..)
657 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
662 let item = attr.unwrap_normal_item();
663 if let MacArgs::Eq(..) = item.args {
664 self.cx.span_err(span, "key-value macro attributes are not supported");
667 expander.expand(self.cx, span, item.args.inner_tokens(), item_tok);
668 self.parse_ast_fragment(tok_result, fragment_kind, &item.path, span)
670 SyntaxExtensionKind::LegacyAttr(expander) => {
671 match validate_attr::parse_meta(self.cx.parse_sess, &attr) {
673 let item = expander.expand(self.cx, span, &meta, item);
674 fragment_kind.expect_from_annotatables(item)
678 fragment_kind.dummy(span)
682 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
683 attr::mark_known(&attr);
685 attr::mark_used(&attr);
687 item.visit_attrs(|attrs| attrs.push(attr));
688 fragment_kind.expect_from_annotatables(iter::once(item))
692 InvocationKind::Derive { path, item } => match ext {
693 SyntaxExtensionKind::Derive(expander)
694 | SyntaxExtensionKind::LegacyDerive(expander) => {
695 if !item.derive_allowed() {
696 return fragment_kind.dummy(span);
698 if let SyntaxExtensionKind::Derive(..) = ext {
699 self.gate_proc_macro_input(&item);
701 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
702 let items = expander.expand(self.cx, span, &meta, item);
703 fragment_kind.expect_from_annotatables(items)
707 InvocationKind::DeriveContainer { .. } => unreachable!(),
711 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
712 let kind = match item {
714 | Annotatable::TraitItem(_)
715 | Annotatable::ImplItem(_)
716 | Annotatable::ForeignItem(_) => return,
717 Annotatable::Stmt(_) => "statements",
718 Annotatable::Expr(_) => "expressions",
720 | Annotatable::Field(..)
721 | Annotatable::FieldPat(..)
722 | Annotatable::GenericParam(..)
723 | Annotatable::Param(..)
724 | Annotatable::StructField(..)
725 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
727 if self.cx.ecfg.proc_macro_hygiene() {
732 sym::proc_macro_hygiene,
734 &format!("custom attributes cannot be applied to {}", kind),
739 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
740 struct GateProcMacroInput<'a> {
741 parse_sess: &'a ParseSess,
744 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
745 fn visit_item(&mut self, item: &'ast ast::Item) {
747 ast::ItemKind::Mod(module) if !module.inline => {
750 sym::proc_macro_hygiene,
752 "non-inline modules in proc macro input are unstable",
759 visit::walk_item(self, item);
762 fn visit_mac(&mut self, _: &'ast ast::Mac) {}
765 if !self.cx.ecfg.proc_macro_hygiene() {
766 annotatable.visit_with(&mut GateProcMacroInput { parse_sess: self.cx.parse_sess });
770 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
771 let kind = match kind {
772 AstFragmentKind::Expr | AstFragmentKind::OptExpr => "expressions",
773 AstFragmentKind::Pat => "patterns",
774 AstFragmentKind::Stmts => "statements",
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 => panic!("unexpected AST fragment kind"),
788 if self.cx.ecfg.proc_macro_hygiene() {
793 sym::proc_macro_hygiene,
795 &format!("procedural macros cannot be expanded to {}", kind),
800 fn parse_ast_fragment(
803 kind: AstFragmentKind,
807 let mut parser = self.cx.new_parser_from_tts(toks);
808 match parse_ast_fragment(&mut parser, kind, false) {
810 ensure_complete_parse(&mut parser, path, kind.name(), span);
815 annotate_err_with_kind(&mut err, kind, span);
817 self.cx.trace_macros_diag();
824 pub fn parse_ast_fragment<'a>(
825 this: &mut Parser<'a>,
826 kind: AstFragmentKind,
827 macro_legacy_warnings: bool,
828 ) -> PResult<'a, AstFragment> {
830 AstFragmentKind::Items => {
831 let mut items = SmallVec::new();
832 while let Some(item) = this.parse_item()? {
835 AstFragment::Items(items)
837 AstFragmentKind::TraitItems => {
838 let mut items = SmallVec::new();
839 while this.token != token::Eof {
840 items.push(this.parse_trait_item(&mut false)?);
842 AstFragment::TraitItems(items)
844 AstFragmentKind::ImplItems => {
845 let mut items = SmallVec::new();
846 while this.token != token::Eof {
847 items.push(this.parse_impl_item(&mut false)?);
849 AstFragment::ImplItems(items)
851 AstFragmentKind::ForeignItems => {
852 let mut items = SmallVec::new();
853 while this.token != token::Eof {
854 items.push(this.parse_foreign_item(DUMMY_SP)?);
856 AstFragment::ForeignItems(items)
858 AstFragmentKind::Stmts => {
859 let mut stmts = SmallVec::new();
860 while this.token != token::Eof &&
861 // won't make progress on a `}`
862 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 => panic!("unexpected AST fragment kind"),
890 pub fn ensure_complete_parse<'a>(
891 this: &mut Parser<'a>,
896 if this.token != token::Eof {
897 let token = pprust::token_to_string(&this.token);
898 let msg = format!("macro expansion ignores token `{}` and any following", token);
899 // Avoid emitting backtrace info twice.
900 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
901 let mut err = this.struct_span_err(def_site_span, &msg);
902 err.span_label(span, "caused by the macro expansion here");
904 "the usage of `{}!` is likely invalid in {} context",
905 pprust::path_to_string(macro_path),
909 let semi_span = this.sess.source_map().next_point(span);
911 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
912 match this.sess.source_map().span_to_snippet(semi_full_span) {
913 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
916 "you might be missing a semicolon here",
918 Applicability::MaybeIncorrect,
927 struct InvocationCollector<'a, 'b> {
928 cx: &'a mut ExtCtxt<'b>,
929 cfg: StripUnconfigured<'a>,
930 invocations: Vec<Invocation>,
934 impl<'a, 'b> InvocationCollector<'a, 'b> {
935 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
936 // Expansion data for all the collected invocations is set upon their resolution,
937 // with exception of the derive container case which is not resolved and can get
938 // its expansion data immediately.
939 let expn_data = match &kind {
940 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
941 parent: self.cx.current_expansion.id,
943 ExpnKind::Macro(MacroKind::Attr, sym::derive),
945 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 })
970 attr: Option<ast::Attribute>,
973 kind: AstFragmentKind,
979 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
980 None => InvocationKind::DeriveContainer { derives, item },
987 attrs: &mut Vec<ast::Attribute>,
988 after_derive: &mut bool,
989 ) -> Option<ast::Attribute> {
993 if a.has_name(sym::derive) {
994 *after_derive = true;
996 !attr::is_known(a) && !is_builtin_attr(a)
998 .map(|i| attrs.remove(i));
999 if let Some(attr) = &attr {
1000 if !self.cx.ecfg.custom_inner_attributes()
1001 && attr.style == ast::AttrStyle::Inner
1002 && !attr.has_name(sym::test)
1005 &self.cx.parse_sess,
1006 sym::custom_inner_attributes,
1008 "non-builtin inner attributes are unstable",
1016 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
1017 fn classify_item<T>(
1020 ) -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
1024 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
1026 item.visit_attrs(|mut attrs| {
1027 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1028 traits = collect_derives(&mut self.cx, &mut attrs);
1031 (attr, traits, after_derive)
1034 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1035 /// to the unused-attributes lint (making it an error on statements and expressions
1036 /// is a breaking change)
1037 fn classify_nonitem<T: HasAttrs>(
1040 ) -> (Option<ast::Attribute>, /* after_derive */ bool) {
1041 let (mut attr, mut after_derive) = (None, false);
1043 nonitem.visit_attrs(|mut attrs| {
1044 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1047 (attr, after_derive)
1050 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1051 self.cfg.configure(node)
1054 // Detect use of feature-gated or invalid attributes on macro invocations
1055 // since they will not be detected after macro expansion.
1056 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1057 let features = self.cx.ecfg.features.unwrap();
1058 for attr in attrs.iter() {
1059 rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1060 validate_attr::check_meta(self.cx.parse_sess, attr);
1062 // macros are expanded before any lint passes so this warning has to be hardcoded
1063 if attr.has_name(sym::derive) {
1065 .struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1066 .note("this may become a hard error in a future release")
1073 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1074 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1075 self.cfg.configure_expr(expr);
1076 visit_clobber(expr.deref_mut(), |mut expr| {
1077 self.cfg.configure_expr_kind(&mut expr.kind);
1079 // ignore derives so they remain unused
1080 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1083 // Collect the invoc regardless of whether or not attributes are permitted here
1084 // expansion will eat the attribute so it won't error later.
1085 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1087 // AstFragmentKind::Expr requires the macro to emit an expression.
1092 Annotatable::Expr(P(expr)),
1093 AstFragmentKind::Expr,
1100 if let ast::ExprKind::Mac(mac) = expr.kind {
1101 self.check_attributes(&expr.attrs);
1102 self.collect_bang(mac, expr.span, AstFragmentKind::Expr).make_expr().into_inner()
1104 noop_visit_expr(&mut expr, self);
1110 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1111 let mut arm = configure!(self, arm);
1113 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1114 if attr.is_some() || !traits.is_empty() {
1119 Annotatable::Arm(arm),
1120 AstFragmentKind::Arms,
1126 noop_flat_map_arm(arm, self)
1129 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1130 let mut field = configure!(self, field);
1132 let (attr, traits, after_derive) = self.classify_item(&mut field);
1133 if attr.is_some() || !traits.is_empty() {
1138 Annotatable::Field(field),
1139 AstFragmentKind::Fields,
1145 noop_flat_map_field(field, self)
1148 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1149 let mut fp = configure!(self, fp);
1151 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1152 if attr.is_some() || !traits.is_empty() {
1157 Annotatable::FieldPat(fp),
1158 AstFragmentKind::FieldPats,
1161 .make_field_patterns();
1164 noop_flat_map_field_pattern(fp, self)
1167 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1168 let mut p = configure!(self, p);
1170 let (attr, traits, after_derive) = self.classify_item(&mut p);
1171 if attr.is_some() || !traits.is_empty() {
1176 Annotatable::Param(p),
1177 AstFragmentKind::Params,
1183 noop_flat_map_param(p, self)
1186 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1187 let mut sf = configure!(self, sf);
1189 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1190 if attr.is_some() || !traits.is_empty() {
1195 Annotatable::StructField(sf),
1196 AstFragmentKind::StructFields,
1199 .make_struct_fields();
1202 noop_flat_map_struct_field(sf, self)
1205 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1206 let mut variant = configure!(self, variant);
1208 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1209 if attr.is_some() || !traits.is_empty() {
1214 Annotatable::Variant(variant),
1215 AstFragmentKind::Variants,
1221 noop_flat_map_variant(variant, self)
1224 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1225 let expr = configure!(self, expr);
1226 expr.filter_map(|mut expr| {
1227 self.cfg.configure_expr_kind(&mut expr.kind);
1229 // Ignore derives so they remain unused.
1230 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1233 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1239 Annotatable::Expr(P(expr)),
1240 AstFragmentKind::OptExpr,
1244 .map(|expr| expr.into_inner());
1247 if let ast::ExprKind::Mac(mac) = expr.kind {
1248 self.check_attributes(&expr.attrs);
1249 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1251 .map(|expr| expr.into_inner())
1254 noop_visit_expr(&mut expr, self);
1261 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1262 self.cfg.configure_pat(pat);
1264 PatKind::Mac(_) => {}
1265 _ => return noop_visit_pat(pat, self),
1268 visit_clobber(pat, |mut pat| match mem::replace(&mut pat.kind, PatKind::Wild) {
1269 PatKind::Mac(mac) => self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1270 _ => unreachable!(),
1274 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1275 let mut stmt = configure!(self, stmt);
1277 // we'll expand attributes on expressions separately
1278 if !stmt.is_expr() {
1279 let (attr, derives, after_derive) = if stmt.is_item() {
1280 self.classify_item(&mut stmt)
1282 // ignore derives on non-item statements so it falls through
1283 // to the unused-attributes lint
1284 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1285 (attr, vec![], after_derive)
1288 if attr.is_some() || !derives.is_empty() {
1293 Annotatable::Stmt(P(stmt)),
1294 AstFragmentKind::Stmts,
1301 if let StmtKind::Mac(mac) = stmt.kind {
1302 let (mac, style, attrs) = mac.into_inner();
1303 self.check_attributes(&attrs);
1304 let mut placeholder =
1305 self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts).make_stmts();
1307 // If this is a macro invocation with a semicolon, then apply that
1308 // semicolon to the final statement produced by expansion.
1309 if style == MacStmtStyle::Semicolon {
1310 if let Some(stmt) = placeholder.pop() {
1311 placeholder.push(stmt.add_trailing_semicolon());
1318 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1319 let ast::Stmt { id, kind, span } = stmt;
1320 noop_flat_map_stmt_kind(kind, self)
1322 .map(|kind| ast::Stmt { id, kind, span })
1326 fn visit_block(&mut self, block: &mut P<Block>) {
1327 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1328 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1329 noop_visit_block(block, self);
1330 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1333 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1334 let mut item = configure!(self, item);
1336 let (attr, traits, after_derive) = self.classify_item(&mut item);
1337 if attr.is_some() || !traits.is_empty() {
1342 Annotatable::Item(item),
1343 AstFragmentKind::Items,
1350 ast::ItemKind::Mac(..) => {
1351 self.check_attributes(&item.attrs);
1352 item.and_then(|item| match item.kind {
1353 ItemKind::Mac(mac) => self
1355 AstFragmentKind::Items,
1356 InvocationKind::Bang { mac, span: item.span },
1359 _ => unreachable!(),
1362 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1363 if item.ident == Ident::invalid() {
1364 return noop_flat_map_item(item, self);
1367 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1368 let mut module = (*self.cx.current_expansion.module).clone();
1369 module.mod_path.push(item.ident);
1371 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1372 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1373 // Thus, if `inner` is the dummy span, we know the module is inline.
1374 let inline_module = item.span.contains(inner) || inner.is_dummy();
1377 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1378 self.cx.current_expansion.directory_ownership =
1379 DirectoryOwnership::Owned { relative: None };
1380 module.directory.push(&*path.as_str());
1382 module.directory.push(&*item.ident.as_str());
1385 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1386 let mut path = match path {
1387 FileName::Real(path) => path,
1388 other => PathBuf::from(other.to_string()),
1390 let directory_ownership = match path.file_name().unwrap().to_str() {
1391 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1392 Some(_) => DirectoryOwnership::Owned { relative: Some(item.ident) },
1393 None => DirectoryOwnership::UnownedViaMod,
1396 module.directory = path;
1397 self.cx.current_expansion.directory_ownership = directory_ownership;
1401 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1402 let result = noop_flat_map_item(item, self);
1403 self.cx.current_expansion.module = orig_module;
1404 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1408 _ => noop_flat_map_item(item, self),
1412 fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1413 let mut item = configure!(self, item);
1415 let (attr, traits, after_derive) = self.classify_item(&mut item);
1416 if attr.is_some() || !traits.is_empty() {
1421 Annotatable::TraitItem(item),
1422 AstFragmentKind::TraitItems,
1425 .make_trait_items();
1429 ast::AssocItemKind::Macro(..) => {
1430 self.check_attributes(&item.attrs);
1431 item.and_then(|item| match item.kind {
1432 ast::AssocItemKind::Macro(mac) => self
1433 .collect_bang(mac, item.span, AstFragmentKind::TraitItems)
1434 .make_trait_items(),
1435 _ => unreachable!(),
1438 _ => noop_flat_map_assoc_item(item, self),
1442 fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1443 let mut item = configure!(self, item);
1445 let (attr, traits, after_derive) = self.classify_item(&mut item);
1446 if attr.is_some() || !traits.is_empty() {
1451 Annotatable::ImplItem(item),
1452 AstFragmentKind::ImplItems,
1459 ast::AssocItemKind::Macro(..) => {
1460 self.check_attributes(&item.attrs);
1461 item.and_then(|item| match item.kind {
1462 ast::AssocItemKind::Macro(mac) => self
1463 .collect_bang(mac, item.span, AstFragmentKind::ImplItems)
1465 _ => unreachable!(),
1468 _ => noop_flat_map_assoc_item(item, self),
1472 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1474 ast::TyKind::Mac(_) => {}
1475 _ => return noop_visit_ty(ty, self),
1478 visit_clobber(ty, |mut ty| match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1479 ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1480 _ => unreachable!(),
1484 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1485 self.cfg.configure_foreign_mod(foreign_mod);
1486 noop_visit_foreign_mod(foreign_mod, self);
1489 fn flat_map_foreign_item(
1491 mut foreign_item: P<ast::ForeignItem>,
1492 ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
1493 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1495 if attr.is_some() || !traits.is_empty() {
1500 Annotatable::ForeignItem(foreign_item),
1501 AstFragmentKind::ForeignItems,
1504 .make_foreign_items();
1507 match foreign_item.kind {
1508 ast::ForeignItemKind::Macro(..) => {
1509 self.check_attributes(&foreign_item.attrs);
1510 foreign_item.and_then(|item| match item.kind {
1511 ast::ForeignItemKind::Macro(mac) => self
1512 .collect_bang(mac, item.span, AstFragmentKind::ForeignItems)
1513 .make_foreign_items(),
1514 _ => unreachable!(),
1517 _ => noop_flat_map_foreign_item(foreign_item, self),
1521 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1523 ast::ItemKind::MacroDef(..) => {}
1525 self.cfg.configure_item_kind(item);
1526 noop_visit_item_kind(item, self);
1531 fn flat_map_generic_param(
1533 param: ast::GenericParam,
1534 ) -> SmallVec<[ast::GenericParam; 1]> {
1535 let mut param = configure!(self, param);
1537 let (attr, traits, after_derive) = self.classify_item(&mut param);
1538 if attr.is_some() || !traits.is_empty() {
1543 Annotatable::GenericParam(param),
1544 AstFragmentKind::GenericParams,
1547 .make_generic_params();
1550 noop_flat_map_generic_param(param, self)
1553 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1554 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1555 // contents="file contents")]` attributes
1556 if !at.check_name(sym::doc) {
1557 return noop_visit_attribute(at, self);
1560 if let Some(list) = at.meta_item_list() {
1561 if !list.iter().any(|it| it.check_name(sym::include)) {
1562 return noop_visit_attribute(at, self);
1565 let mut items = vec![];
1567 for mut it in list {
1568 if !it.check_name(sym::include) {
1570 noop_visit_meta_list_item(&mut it, self);
1576 if let Some(file) = it.value_str() {
1577 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1578 self.check_attributes(slice::from_ref(at));
1579 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1580 // avoid loading the file if they haven't enabled the feature
1581 return noop_visit_attribute(at, self);
1584 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1585 Ok(filename) => filename,
1592 match self.cx.source_map().load_file(&filename) {
1593 Ok(source_file) => {
1594 let src = source_file
1597 .expect("freshly loaded file should have a source");
1598 let src_interned = Symbol::intern(src.as_str());
1600 let include_info = vec![
1601 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1602 Ident::with_dummy_span(sym::file),
1606 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1607 Ident::with_dummy_span(sym::contents),
1613 let include_ident = Ident::with_dummy_span(sym::include);
1614 let item = attr::mk_list_item(include_ident, include_info);
1615 items.push(ast::NestedMetaItem::MetaItem(item));
1619 it.meta_item().and_then(|item| item.name_value_literal()).unwrap();
1621 if e.kind() == ErrorKind::InvalidData {
1625 &format!("{} wasn't a utf-8 file", filename.display()),
1627 .span_label(lit.span, "contains invalid utf-8")
1630 let mut err = self.cx.struct_span_err(
1632 &format!("couldn't read {}: {}", filename.display(), e),
1634 err.span_label(lit.span, "couldn't read file");
1641 let mut err = self.cx.struct_span_err(
1643 &format!("expected path to external documentation"),
1646 // Check if the user erroneously used `doc(include(...))` syntax.
1647 let literal = it.meta_item_list().and_then(|list| {
1648 if list.len() == 1 {
1649 list[0].literal().map(|literal| &literal.kind)
1655 let (path, applicability) = match &literal {
1656 Some(LitKind::Str(path, ..)) => {
1657 (path.to_string(), Applicability::MachineApplicable)
1659 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1662 err.span_suggestion(
1664 "provide a file path with `=`",
1665 format!("include = \"{}\"", path),
1673 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1674 *at = ast::Attribute {
1675 kind: ast::AttrKind::Normal(AttrItem {
1677 args: meta.kind.mac_args(meta.span),
1684 noop_visit_attribute(at, self)
1688 fn visit_id(&mut self, id: &mut ast::NodeId) {
1690 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1691 *id = self.cx.resolver.next_node_id()
1695 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1696 self.cfg.configure_fn_decl(&mut fn_decl);
1697 noop_visit_fn_decl(fn_decl, self);
1701 pub struct ExpansionConfig<'feat> {
1702 pub crate_name: String,
1703 pub features: Option<&'feat Features>,
1704 pub recursion_limit: usize,
1705 pub trace_mac: bool,
1706 pub should_test: bool, // If false, strip `#[test]` nodes
1707 pub single_step: bool,
1708 pub keep_macs: bool,
1711 impl<'feat> ExpansionConfig<'feat> {
1712 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1716 recursion_limit: 1024,
1724 fn proc_macro_hygiene(&self) -> bool {
1725 self.features.map_or(false, |features| features.proc_macro_hygiene)
1727 fn custom_inner_attributes(&self) -> bool {
1728 self.features.map_or(false, |features| features.custom_inner_attributes)