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_data_structures::sync::Lrc;
9 use rustc_errors::{Applicability, FatalError, PResult};
10 use rustc_feature::Features;
11 use rustc_parse::configure;
12 use rustc_parse::parser::Parser;
13 use rustc_parse::validate_attr;
14 use rustc_parse::DirectoryOwnership;
15 use rustc_span::source_map::respan;
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_span::{FileName, Span, DUMMY_SP};
18 use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
19 use syntax::ast::{ItemKind, MacArgs, MacStmtStyle, StmtKind};
20 use syntax::attr::{self, is_builtin_attr, HasAttrs};
21 use syntax::feature_gate::{self, feature_err};
22 use syntax::mut_visit::*;
23 use syntax::print::pprust;
25 use syntax::sess::ParseSess;
27 use syntax::tokenstream::{TokenStream, TokenTree};
28 use syntax::util::map_in_place::MapInPlace;
29 use syntax::visit::{self, Visitor};
31 use smallvec::{smallvec, SmallVec};
32 use std::io::ErrorKind;
33 use std::ops::DerefMut;
34 use std::path::PathBuf;
36 use std::{iter, mem, slice};
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 macro _repeating($flat_map_ast_elt) {}
88 placeholder(AstFragmentKind::$Kind, *id, None).$make_ast()
90 _ => panic!("unexpected AST fragment kind")
94 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
96 AstFragment::OptExpr(expr) => expr,
97 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
101 $(pub fn $make_ast(self) -> $AstTy {
103 AstFragment::$Kind(ast) => ast,
104 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
108 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
110 AstFragment::OptExpr(opt_expr) => {
111 visit_clobber(opt_expr, |opt_expr| {
112 if let Some(expr) = opt_expr {
113 vis.filter_map_expr(expr)
119 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
120 $($(AstFragment::$Kind(ast) =>
121 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
125 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
127 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
128 AstFragment::OptExpr(None) => {}
129 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
130 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
131 visitor.$visit_ast_elt(ast_elt);
137 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
138 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
140 Some(self.make(AstFragmentKind::$Kind).$make_ast())
147 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
148 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
149 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
150 Stmts(SmallVec<[ast::Stmt; 1]>) {
151 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
153 Items(SmallVec<[P<ast::Item>; 1]>) {
154 "item"; many fn flat_map_item; fn visit_item; fn make_items;
156 TraitItems(SmallVec<[ast::AssocItem; 1]>) {
157 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
159 ImplItems(SmallVec<[ast::AssocItem; 1]>) {
160 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
162 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
164 many fn flat_map_foreign_item;
165 fn visit_foreign_item;
166 fn make_foreign_items;
168 Arms(SmallVec<[ast::Arm; 1]>) {
169 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
171 Fields(SmallVec<[ast::Field; 1]>) {
172 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
174 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
176 many fn flat_map_field_pattern;
177 fn visit_field_pattern;
178 fn make_field_patterns;
180 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
182 many fn flat_map_generic_param;
183 fn visit_generic_param;
184 fn make_generic_params;
186 Params(SmallVec<[ast::Param; 1]>) {
187 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
189 StructFields(SmallVec<[ast::StructField; 1]>) {
191 many fn flat_map_struct_field;
192 fn visit_struct_field;
193 fn make_struct_fields;
195 Variants(SmallVec<[ast::Variant; 1]>) {
196 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
200 impl AstFragmentKind {
201 fn dummy(self, span: Span) -> AstFragment {
202 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
205 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(
209 let mut items = items.into_iter();
211 AstFragmentKind::Arms => {
212 AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
214 AstFragmentKind::Fields => {
215 AstFragment::Fields(items.map(Annotatable::expect_field).collect())
217 AstFragmentKind::FieldPats => {
218 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect())
220 AstFragmentKind::GenericParams => {
221 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
223 AstFragmentKind::Params => {
224 AstFragment::Params(items.map(Annotatable::expect_param).collect())
226 AstFragmentKind::StructFields => {
227 AstFragment::StructFields(items.map(Annotatable::expect_struct_field).collect())
229 AstFragmentKind::Variants => {
230 AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
232 AstFragmentKind::Items => {
233 AstFragment::Items(items.map(Annotatable::expect_item).collect())
235 AstFragmentKind::ImplItems => {
236 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
238 AstFragmentKind::TraitItems => {
239 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
241 AstFragmentKind::ForeignItems => {
242 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
244 AstFragmentKind::Stmts => {
245 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
247 AstFragmentKind::Expr => AstFragment::Expr(
248 items.next().expect("expected exactly one expression").expect_expr(),
250 AstFragmentKind::OptExpr => {
251 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
253 AstFragmentKind::Pat | AstFragmentKind::Ty => {
254 panic!("patterns and types aren't annotatable")
260 pub struct Invocation {
261 pub kind: InvocationKind,
262 pub fragment_kind: AstFragmentKind,
263 pub expansion_data: ExpansionData,
266 pub enum InvocationKind {
272 attr: ast::Attribute,
274 // Required for resolving derive helper attributes.
276 // We temporarily report errors for attribute macros placed after derives
283 /// "Invocation" that contains all derives from an item,
284 /// broken into multiple `Derive` invocations when expanded.
285 /// FIXME: Find a way to remove it.
292 impl InvocationKind {
293 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
294 // HACK: For unnamed fields placeholders should have the same visibility as the actual
295 // fields because for tuple structs/variants resolve determines visibilities of their
296 // constructor using these field visibilities before attributes on them are are expanded.
297 // The assumption is that the attribute expansion cannot change field visibilities,
298 // and it holds because only inert attributes are supported in this position.
300 InvocationKind::Attr { item: Annotatable::StructField(field), .. }
301 | InvocationKind::Derive { item: Annotatable::StructField(field), .. }
302 | InvocationKind::DeriveContainer { item: Annotatable::StructField(field), .. }
303 if field.ident.is_none() =>
305 Some(field.vis.clone())
313 pub fn span(&self) -> Span {
315 InvocationKind::Bang { span, .. } => *span,
316 InvocationKind::Attr { attr, .. } => attr.span,
317 InvocationKind::Derive { path, .. } => path.span,
318 InvocationKind::DeriveContainer { item, .. } => item.span(),
323 pub struct MacroExpander<'a, 'b> {
324 pub cx: &'a mut ExtCtxt<'b>,
325 monotonic: bool, // cf. `cx.monotonic_expander()`
328 impl<'a, 'b> MacroExpander<'a, 'b> {
329 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
330 MacroExpander { cx, monotonic }
333 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
334 let mut module = ModuleData {
335 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
336 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
337 FileName::Real(path) => path,
338 other => PathBuf::from(other.to_string()),
341 module.directory.pop();
342 self.cx.root_path = module.directory.clone();
343 self.cx.current_expansion.module = Rc::new(module);
345 let orig_mod_span = krate.module.inner;
347 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
350 kind: ast::ItemKind::Mod(krate.module),
351 ident: Ident::invalid(),
352 id: ast::DUMMY_NODE_ID,
353 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
357 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
358 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
360 krate.module = module;
363 // Resolution failed so we return an empty expansion
364 krate.attrs = vec![];
365 krate.module = ast::Mod { inner: orig_mod_span, items: vec![], inline: true };
369 self.cx.trace_macros_diag();
373 // Recursively expand all macro invocations in this AST fragment.
374 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
375 let orig_expansion_data = self.cx.current_expansion.clone();
376 self.cx.current_expansion.depth = 0;
378 // Collect all macro invocations and replace them with placeholders.
379 let (mut fragment_with_placeholders, mut invocations) =
380 self.collect_invocations(input_fragment, &[]);
382 // Optimization: if we resolve all imports now,
383 // we'll be able to immediately resolve most of imported macros.
384 self.resolve_imports();
386 // Resolve paths in all invocations and produce output expanded fragments for them, but
387 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
388 // The output fragments also go through expansion recursively until no invocations are left.
389 // Unresolved macros produce dummy outputs as a recovery measure.
390 invocations.reverse();
391 let mut expanded_fragments = Vec::new();
392 let mut undetermined_invocations = Vec::new();
393 let (mut progress, mut force) = (false, !self.monotonic);
395 let invoc = if let Some(invoc) = invocations.pop() {
398 self.resolve_imports();
399 if undetermined_invocations.is_empty() {
402 invocations = mem::take(&mut undetermined_invocations);
403 force = !mem::replace(&mut progress, false);
407 let eager_expansion_root =
408 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
409 let res = match self.cx.resolver.resolve_macro_invocation(
411 eager_expansion_root,
415 Err(Indeterminate) => {
416 undetermined_invocations.push(invoc);
422 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
423 self.cx.current_expansion = invoc.expansion_data.clone();
425 // FIXME(jseyfried): Refactor out the following logic
426 let (expanded_fragment, new_invocations) = match res {
427 InvocationRes::Single(ext) => {
428 let fragment = self.expand_invoc(invoc, &ext.kind);
429 self.collect_invocations(fragment, &[])
431 InvocationRes::DeriveContainer(_exts) => {
432 // FIXME: Consider using the derive resolutions (`_exts`) immediately,
433 // instead of enqueuing the derives to be resolved again later.
434 let (derives, item) = match invoc.kind {
435 InvocationKind::DeriveContainer { derives, item } => (derives, item),
438 if !item.derive_allowed() {
439 let attr = attr::find_by_name(item.attrs(), sym::derive)
440 .expect("`derive` attribute should exist");
441 let span = attr.span;
442 let mut err = self.cx.struct_span_err(
444 "`derive` may only be applied to structs, enums and unions",
446 if let ast::AttrStyle::Inner = attr.style {
447 let trait_list = derives
449 .map(|t| pprust::path_to_string(t))
450 .collect::<Vec<_>>();
451 let suggestion = format!("#[derive({})]", trait_list.join(", "));
454 "try an outer attribute",
456 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
457 Applicability::MaybeIncorrect,
463 let mut item = self.fully_configure(item);
464 item.visit_attrs(|attrs| attrs.retain(|a| !a.has_name(sym::derive)));
466 let mut derive_placeholders = Vec::with_capacity(derives.len());
467 invocations.reserve(derives.len());
468 for path in derives {
469 let expn_id = ExpnId::fresh(None);
470 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
471 invocations.push(Invocation {
472 kind: InvocationKind::Derive { path, item: item.clone() },
473 fragment_kind: invoc.fragment_kind,
474 expansion_data: ExpansionData {
476 ..invoc.expansion_data.clone()
481 invoc.fragment_kind.expect_from_annotatables(::std::iter::once(item));
482 self.collect_invocations(fragment, &derive_placeholders)
486 if expanded_fragments.len() < depth {
487 expanded_fragments.push(Vec::new());
489 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
490 if !self.cx.ecfg.single_step {
491 invocations.extend(new_invocations.into_iter().rev());
495 self.cx.current_expansion = orig_expansion_data;
497 // Finally incorporate all the expanded macros into the input AST fragment.
498 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
499 while let Some(expanded_fragments) = expanded_fragments.pop() {
500 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
502 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
505 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
506 fragment_with_placeholders
509 fn resolve_imports(&mut self) {
511 self.cx.resolver.resolve_imports();
515 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
516 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
517 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
518 /// prepares data for resolving paths of macro invocations.
519 fn collect_invocations(
521 mut fragment: AstFragment,
522 extra_placeholders: &[NodeId],
523 ) -> (AstFragment, Vec<Invocation>) {
524 // Resolve `$crate`s in the fragment for pretty-printing.
525 self.cx.resolver.resolve_dollar_crates();
528 let mut collector = InvocationCollector {
529 cfg: StripUnconfigured {
530 sess: self.cx.parse_sess,
531 features: self.cx.ecfg.features,
534 invocations: Vec::new(),
535 monotonic: self.monotonic,
537 fragment.mut_visit_with(&mut collector);
538 fragment.add_placeholders(extra_placeholders);
539 collector.invocations
545 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
548 (fragment, invocations)
551 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
553 StripUnconfigured { sess: self.cx.parse_sess, features: self.cx.ecfg.features };
554 // Since the item itself has already been configured by the InvocationCollector,
555 // we know that fold result vector will contain exactly one element
557 Annotatable::Item(item) => Annotatable::Item(cfg.flat_map_item(item).pop().unwrap()),
558 Annotatable::TraitItem(item) => Annotatable::TraitItem(
559 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()),
561 Annotatable::ImplItem(item) => {
562 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
564 Annotatable::ForeignItem(item) => Annotatable::ForeignItem(
565 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap()),
567 Annotatable::Stmt(stmt) => {
568 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
570 Annotatable::Expr(mut expr) => Annotatable::Expr({
571 cfg.visit_expr(&mut expr);
574 Annotatable::Arm(arm) => Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap()),
575 Annotatable::Field(field) => {
576 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
578 Annotatable::FieldPat(fp) => {
579 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
581 Annotatable::GenericParam(param) => {
582 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
584 Annotatable::Param(param) => {
585 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
587 Annotatable::StructField(sf) => {
588 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
590 Annotatable::Variant(v) => Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap()),
594 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
595 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
596 let expn_data = self.cx.current_expansion.id.expn_data();
597 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
598 let mut err = self.cx.struct_span_err(
601 "recursion limit reached while expanding the macro `{}`",
602 expn_data.kind.descr()
606 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
610 self.cx.trace_macros_diag();
614 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
616 InvocationKind::Bang { mac, .. } => match ext {
617 SyntaxExtensionKind::Bang(expander) => {
618 self.gate_proc_macro_expansion_kind(span, fragment_kind);
619 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
620 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
622 SyntaxExtensionKind::LegacyBang(expander) => {
623 let prev = self.cx.current_expansion.prior_type_ascription;
624 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
625 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
626 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
630 "non-{kind} macro in {kind} position: {path}",
631 kind = fragment_kind.name(),
632 path = pprust::path_to_string(&mac.path),
634 self.cx.span_err(span, &msg);
635 self.cx.trace_macros_diag();
636 fragment_kind.dummy(span)
638 self.cx.current_expansion.prior_type_ascription = prev;
643 InvocationKind::Attr { attr, mut item, .. } => match ext {
644 SyntaxExtensionKind::Attr(expander) => {
645 self.gate_proc_macro_input(&item);
646 self.gate_proc_macro_attr_item(span, &item);
647 let item_tok = TokenTree::token(
648 token::Interpolated(Lrc::new(match item {
649 Annotatable::Item(item) => token::NtItem(item),
650 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
651 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
652 Annotatable::ForeignItem(item) => {
653 token::NtForeignItem(item.into_inner())
655 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
656 Annotatable::Expr(expr) => token::NtExpr(expr),
658 | Annotatable::Field(..)
659 | Annotatable::FieldPat(..)
660 | Annotatable::GenericParam(..)
661 | Annotatable::Param(..)
662 | Annotatable::StructField(..)
663 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
668 let item = attr.unwrap_normal_item();
669 if let MacArgs::Eq(..) = item.args {
670 self.cx.span_err(span, "key-value macro attributes are not supported");
673 expander.expand(self.cx, span, item.args.inner_tokens(), item_tok);
674 self.parse_ast_fragment(tok_result, fragment_kind, &item.path, span)
676 SyntaxExtensionKind::LegacyAttr(expander) => {
677 match validate_attr::parse_meta(self.cx.parse_sess, &attr) {
679 let item = expander.expand(self.cx, span, &meta, item);
680 fragment_kind.expect_from_annotatables(item)
684 fragment_kind.dummy(span)
688 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
689 attr::mark_known(&attr);
691 attr::mark_used(&attr);
693 item.visit_attrs(|attrs| attrs.push(attr));
694 fragment_kind.expect_from_annotatables(iter::once(item))
698 InvocationKind::Derive { path, item } => match ext {
699 SyntaxExtensionKind::Derive(expander)
700 | SyntaxExtensionKind::LegacyDerive(expander) => {
701 if !item.derive_allowed() {
702 return fragment_kind.dummy(span);
704 if let SyntaxExtensionKind::Derive(..) = ext {
705 self.gate_proc_macro_input(&item);
707 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
708 let items = expander.expand(self.cx, span, &meta, item);
709 fragment_kind.expect_from_annotatables(items)
713 InvocationKind::DeriveContainer { .. } => unreachable!(),
717 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
718 let kind = match item {
720 | Annotatable::TraitItem(_)
721 | Annotatable::ImplItem(_)
722 | Annotatable::ForeignItem(_) => return,
723 Annotatable::Stmt(_) => "statements",
724 Annotatable::Expr(_) => "expressions",
726 | Annotatable::Field(..)
727 | Annotatable::FieldPat(..)
728 | Annotatable::GenericParam(..)
729 | Annotatable::Param(..)
730 | Annotatable::StructField(..)
731 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
733 if self.cx.ecfg.proc_macro_hygiene() {
738 sym::proc_macro_hygiene,
740 &format!("custom attributes cannot be applied to {}", kind),
745 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
746 struct GateProcMacroInput<'a> {
747 parse_sess: &'a ParseSess,
750 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
751 fn visit_item(&mut self, item: &'ast ast::Item) {
753 ast::ItemKind::Mod(module) if !module.inline => {
756 sym::proc_macro_hygiene,
758 "non-inline modules in proc macro input are unstable",
765 visit::walk_item(self, item);
768 fn visit_mac(&mut self, _: &'ast ast::Mac) {}
771 if !self.cx.ecfg.proc_macro_hygiene() {
772 annotatable.visit_with(&mut GateProcMacroInput { parse_sess: self.cx.parse_sess });
776 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
777 let kind = match kind {
778 AstFragmentKind::Expr | AstFragmentKind::OptExpr => "expressions",
779 AstFragmentKind::Pat => "patterns",
780 AstFragmentKind::Stmts => "statements",
782 | AstFragmentKind::Items
783 | AstFragmentKind::TraitItems
784 | AstFragmentKind::ImplItems
785 | AstFragmentKind::ForeignItems => return,
786 AstFragmentKind::Arms
787 | AstFragmentKind::Fields
788 | AstFragmentKind::FieldPats
789 | AstFragmentKind::GenericParams
790 | AstFragmentKind::Params
791 | AstFragmentKind::StructFields
792 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
794 if self.cx.ecfg.proc_macro_hygiene() {
799 sym::proc_macro_hygiene,
801 &format!("procedural macros cannot be expanded to {}", kind),
806 fn parse_ast_fragment(
809 kind: AstFragmentKind,
813 let mut parser = self.cx.new_parser_from_tts(toks);
814 match parse_ast_fragment(&mut parser, kind, false) {
816 ensure_complete_parse(&mut parser, path, kind.name(), span);
821 annotate_err_with_kind(&mut err, kind, span);
823 self.cx.trace_macros_diag();
830 pub fn parse_ast_fragment<'a>(
831 this: &mut Parser<'a>,
832 kind: AstFragmentKind,
833 macro_legacy_warnings: bool,
834 ) -> PResult<'a, AstFragment> {
836 AstFragmentKind::Items => {
837 let mut items = SmallVec::new();
838 while let Some(item) = this.parse_item()? {
841 AstFragment::Items(items)
843 AstFragmentKind::TraitItems => {
844 let mut items = SmallVec::new();
845 while this.token != token::Eof {
846 items.push(this.parse_trait_item(&mut false)?);
848 AstFragment::TraitItems(items)
850 AstFragmentKind::ImplItems => {
851 let mut items = SmallVec::new();
852 while this.token != token::Eof {
853 items.push(this.parse_impl_item(&mut false)?);
855 AstFragment::ImplItems(items)
857 AstFragmentKind::ForeignItems => {
858 let mut items = SmallVec::new();
859 while this.token != token::Eof {
860 items.push(this.parse_foreign_item(DUMMY_SP)?);
862 AstFragment::ForeignItems(items)
864 AstFragmentKind::Stmts => {
865 let mut stmts = SmallVec::new();
866 while this.token != token::Eof &&
867 // won't make progress on a `}`
868 this.token != token::CloseDelim(token::Brace)
870 if let Some(stmt) = this.parse_full_stmt(macro_legacy_warnings)? {
874 AstFragment::Stmts(stmts)
876 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
877 AstFragmentKind::OptExpr => {
878 if this.token != token::Eof {
879 AstFragment::OptExpr(Some(this.parse_expr()?))
881 AstFragment::OptExpr(None)
884 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
885 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?),
886 AstFragmentKind::Arms
887 | AstFragmentKind::Fields
888 | AstFragmentKind::FieldPats
889 | AstFragmentKind::GenericParams
890 | AstFragmentKind::Params
891 | AstFragmentKind::StructFields
892 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
896 pub fn ensure_complete_parse<'a>(
897 this: &mut Parser<'a>,
902 if this.token != token::Eof {
903 let token = pprust::token_to_string(&this.token);
904 let msg = format!("macro expansion ignores token `{}` and any following", token);
905 // Avoid emitting backtrace info twice.
906 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
907 let mut err = this.struct_span_err(def_site_span, &msg);
908 err.span_label(span, "caused by the macro expansion here");
910 "the usage of `{}!` is likely invalid in {} context",
911 pprust::path_to_string(macro_path),
915 let semi_span = this.sess.source_map().next_point(span);
917 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
918 match this.sess.source_map().span_to_snippet(semi_full_span) {
919 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
922 "you might be missing a semicolon here",
924 Applicability::MaybeIncorrect,
933 struct InvocationCollector<'a, 'b> {
934 cx: &'a mut ExtCtxt<'b>,
935 cfg: StripUnconfigured<'a>,
936 invocations: Vec<Invocation>,
940 impl<'a, 'b> InvocationCollector<'a, 'b> {
941 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
942 // Expansion data for all the collected invocations is set upon their resolution,
943 // with exception of the derive container case which is not resolved and can get
944 // its expansion data immediately.
945 let expn_data = match &kind {
946 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
947 parent: self.cx.current_expansion.id,
949 ExpnKind::Macro(MacroKind::Attr, sym::derive),
951 self.cx.parse_sess.edition,
956 let expn_id = ExpnId::fresh(expn_data);
957 let vis = kind.placeholder_visibility();
958 self.invocations.push(Invocation {
961 expansion_data: ExpansionData {
963 depth: self.cx.current_expansion.depth + 1,
964 ..self.cx.current_expansion.clone()
967 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
970 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
971 self.collect(kind, InvocationKind::Bang { mac, span })
976 attr: Option<ast::Attribute>,
979 kind: AstFragmentKind,
985 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
986 None => InvocationKind::DeriveContainer { derives, item },
993 attrs: &mut Vec<ast::Attribute>,
994 after_derive: &mut bool,
995 ) -> Option<ast::Attribute> {
999 if a.has_name(sym::derive) {
1000 *after_derive = true;
1002 !attr::is_known(a) && !is_builtin_attr(a)
1004 .map(|i| attrs.remove(i));
1005 if let Some(attr) = &attr {
1006 if !self.cx.ecfg.custom_inner_attributes()
1007 && attr.style == ast::AttrStyle::Inner
1008 && !attr.has_name(sym::test)
1011 &self.cx.parse_sess,
1012 sym::custom_inner_attributes,
1014 "non-builtin inner attributes are unstable",
1022 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
1023 fn classify_item<T>(
1026 ) -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
1030 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
1032 item.visit_attrs(|mut attrs| {
1033 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1034 traits = collect_derives(&mut self.cx, &mut attrs);
1037 (attr, traits, after_derive)
1040 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1041 /// to the unused-attributes lint (making it an error on statements and expressions
1042 /// is a breaking change)
1043 fn classify_nonitem<T: HasAttrs>(
1046 ) -> (Option<ast::Attribute>, /* after_derive */ bool) {
1047 let (mut attr, mut after_derive) = (None, false);
1049 nonitem.visit_attrs(|mut attrs| {
1050 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1053 (attr, after_derive)
1056 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1057 self.cfg.configure(node)
1060 // Detect use of feature-gated or invalid attributes on macro invocations
1061 // since they will not be detected after macro expansion.
1062 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1063 let features = self.cx.ecfg.features.unwrap();
1064 for attr in attrs.iter() {
1065 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1066 validate_attr::check_meta(self.cx.parse_sess, attr);
1068 // macros are expanded before any lint passes so this warning has to be hardcoded
1069 if attr.has_name(sym::derive) {
1071 .struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1072 .note("this may become a hard error in a future release")
1079 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1080 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1081 self.cfg.configure_expr(expr);
1082 visit_clobber(expr.deref_mut(), |mut expr| {
1083 self.cfg.configure_expr_kind(&mut expr.kind);
1085 // ignore derives so they remain unused
1086 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1089 // Collect the invoc regardless of whether or not attributes are permitted here
1090 // expansion will eat the attribute so it won't error later.
1091 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1093 // AstFragmentKind::Expr requires the macro to emit an expression.
1098 Annotatable::Expr(P(expr)),
1099 AstFragmentKind::Expr,
1106 if let ast::ExprKind::Mac(mac) = expr.kind {
1107 self.check_attributes(&expr.attrs);
1108 self.collect_bang(mac, expr.span, AstFragmentKind::Expr).make_expr().into_inner()
1110 noop_visit_expr(&mut expr, self);
1116 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1117 let mut arm = configure!(self, arm);
1119 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1120 if attr.is_some() || !traits.is_empty() {
1125 Annotatable::Arm(arm),
1126 AstFragmentKind::Arms,
1132 noop_flat_map_arm(arm, self)
1135 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1136 let mut field = configure!(self, field);
1138 let (attr, traits, after_derive) = self.classify_item(&mut field);
1139 if attr.is_some() || !traits.is_empty() {
1144 Annotatable::Field(field),
1145 AstFragmentKind::Fields,
1151 noop_flat_map_field(field, self)
1154 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1155 let mut fp = configure!(self, fp);
1157 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1158 if attr.is_some() || !traits.is_empty() {
1163 Annotatable::FieldPat(fp),
1164 AstFragmentKind::FieldPats,
1167 .make_field_patterns();
1170 noop_flat_map_field_pattern(fp, self)
1173 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1174 let mut p = configure!(self, p);
1176 let (attr, traits, after_derive) = self.classify_item(&mut p);
1177 if attr.is_some() || !traits.is_empty() {
1182 Annotatable::Param(p),
1183 AstFragmentKind::Params,
1189 noop_flat_map_param(p, self)
1192 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1193 let mut sf = configure!(self, sf);
1195 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1196 if attr.is_some() || !traits.is_empty() {
1201 Annotatable::StructField(sf),
1202 AstFragmentKind::StructFields,
1205 .make_struct_fields();
1208 noop_flat_map_struct_field(sf, self)
1211 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1212 let mut variant = configure!(self, variant);
1214 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1215 if attr.is_some() || !traits.is_empty() {
1220 Annotatable::Variant(variant),
1221 AstFragmentKind::Variants,
1227 noop_flat_map_variant(variant, self)
1230 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1231 let expr = configure!(self, expr);
1232 expr.filter_map(|mut expr| {
1233 self.cfg.configure_expr_kind(&mut expr.kind);
1235 // Ignore derives so they remain unused.
1236 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1239 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1245 Annotatable::Expr(P(expr)),
1246 AstFragmentKind::OptExpr,
1250 .map(|expr| expr.into_inner());
1253 if let ast::ExprKind::Mac(mac) = expr.kind {
1254 self.check_attributes(&expr.attrs);
1255 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1257 .map(|expr| expr.into_inner())
1260 noop_visit_expr(&mut expr, self);
1267 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1268 self.cfg.configure_pat(pat);
1270 PatKind::Mac(_) => {}
1271 _ => return noop_visit_pat(pat, self),
1274 visit_clobber(pat, |mut pat| match mem::replace(&mut pat.kind, PatKind::Wild) {
1275 PatKind::Mac(mac) => self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1276 _ => unreachable!(),
1280 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1281 let mut stmt = configure!(self, stmt);
1283 // we'll expand attributes on expressions separately
1284 if !stmt.is_expr() {
1285 let (attr, derives, after_derive) = if stmt.is_item() {
1286 self.classify_item(&mut stmt)
1288 // ignore derives on non-item statements so it falls through
1289 // to the unused-attributes lint
1290 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1291 (attr, vec![], after_derive)
1294 if attr.is_some() || !derives.is_empty() {
1299 Annotatable::Stmt(P(stmt)),
1300 AstFragmentKind::Stmts,
1307 if let StmtKind::Mac(mac) = stmt.kind {
1308 let (mac, style, attrs) = mac.into_inner();
1309 self.check_attributes(&attrs);
1310 let mut placeholder =
1311 self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts).make_stmts();
1313 // If this is a macro invocation with a semicolon, then apply that
1314 // semicolon to the final statement produced by expansion.
1315 if style == MacStmtStyle::Semicolon {
1316 if let Some(stmt) = placeholder.pop() {
1317 placeholder.push(stmt.add_trailing_semicolon());
1324 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1325 let ast::Stmt { id, kind, span } = stmt;
1326 noop_flat_map_stmt_kind(kind, self)
1328 .map(|kind| ast::Stmt { id, kind, span })
1332 fn visit_block(&mut self, block: &mut P<Block>) {
1333 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1334 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1335 noop_visit_block(block, self);
1336 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1339 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1340 let mut item = configure!(self, item);
1342 let (attr, traits, after_derive) = self.classify_item(&mut item);
1343 if attr.is_some() || !traits.is_empty() {
1348 Annotatable::Item(item),
1349 AstFragmentKind::Items,
1356 ast::ItemKind::Mac(..) => {
1357 self.check_attributes(&item.attrs);
1358 item.and_then(|item| match item.kind {
1359 ItemKind::Mac(mac) => self
1361 AstFragmentKind::Items,
1362 InvocationKind::Bang { mac, span: item.span },
1365 _ => unreachable!(),
1368 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1369 if item.ident == Ident::invalid() {
1370 return noop_flat_map_item(item, self);
1373 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1374 let mut module = (*self.cx.current_expansion.module).clone();
1375 module.mod_path.push(item.ident);
1377 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1378 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1379 // Thus, if `inner` is the dummy span, we know the module is inline.
1380 let inline_module = item.span.contains(inner) || inner.is_dummy();
1383 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1384 self.cx.current_expansion.directory_ownership =
1385 DirectoryOwnership::Owned { relative: None };
1386 module.directory.push(&*path.as_str());
1388 module.directory.push(&*item.ident.as_str());
1391 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1392 let mut path = match path {
1393 FileName::Real(path) => path,
1394 other => PathBuf::from(other.to_string()),
1396 let directory_ownership = match path.file_name().unwrap().to_str() {
1397 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1398 Some(_) => DirectoryOwnership::Owned { relative: Some(item.ident) },
1399 None => DirectoryOwnership::UnownedViaMod,
1402 module.directory = path;
1403 self.cx.current_expansion.directory_ownership = directory_ownership;
1407 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1408 let result = noop_flat_map_item(item, self);
1409 self.cx.current_expansion.module = orig_module;
1410 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1414 _ => noop_flat_map_item(item, self),
1418 fn flat_map_trait_item(&mut self, item: ast::AssocItem) -> SmallVec<[ast::AssocItem; 1]> {
1419 let mut item = configure!(self, item);
1421 let (attr, traits, after_derive) = self.classify_item(&mut item);
1422 if attr.is_some() || !traits.is_empty() {
1427 Annotatable::TraitItem(P(item)),
1428 AstFragmentKind::TraitItems,
1431 .make_trait_items();
1435 ast::AssocItemKind::Macro(mac) => {
1436 let ast::AssocItem { attrs, span, .. } = item;
1437 self.check_attributes(&attrs);
1438 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1440 _ => noop_flat_map_assoc_item(item, self),
1444 fn flat_map_impl_item(&mut self, item: ast::AssocItem) -> SmallVec<[ast::AssocItem; 1]> {
1445 let mut item = configure!(self, item);
1447 let (attr, traits, after_derive) = self.classify_item(&mut item);
1448 if attr.is_some() || !traits.is_empty() {
1453 Annotatable::ImplItem(P(item)),
1454 AstFragmentKind::ImplItems,
1461 ast::AssocItemKind::Macro(mac) => {
1462 let ast::AssocItem { attrs, span, .. } = item;
1463 self.check_attributes(&attrs);
1464 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1466 _ => noop_flat_map_assoc_item(item, self),
1470 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1472 ast::TyKind::Mac(_) => {}
1473 _ => return noop_visit_ty(ty, self),
1476 visit_clobber(ty, |mut ty| match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1477 ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1478 _ => unreachable!(),
1482 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1483 self.cfg.configure_foreign_mod(foreign_mod);
1484 noop_visit_foreign_mod(foreign_mod, self);
1487 fn flat_map_foreign_item(
1489 mut foreign_item: ast::ForeignItem,
1490 ) -> SmallVec<[ast::ForeignItem; 1]> {
1491 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1493 if attr.is_some() || !traits.is_empty() {
1498 Annotatable::ForeignItem(P(foreign_item)),
1499 AstFragmentKind::ForeignItems,
1502 .make_foreign_items();
1505 if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind {
1506 self.check_attributes(&foreign_item.attrs);
1508 .collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1509 .make_foreign_items();
1512 noop_flat_map_foreign_item(foreign_item, self)
1515 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1517 ast::ItemKind::MacroDef(..) => {}
1519 self.cfg.configure_item_kind(item);
1520 noop_visit_item_kind(item, self);
1525 fn flat_map_generic_param(
1527 param: ast::GenericParam,
1528 ) -> SmallVec<[ast::GenericParam; 1]> {
1529 let mut param = configure!(self, param);
1531 let (attr, traits, after_derive) = self.classify_item(&mut param);
1532 if attr.is_some() || !traits.is_empty() {
1537 Annotatable::GenericParam(param),
1538 AstFragmentKind::GenericParams,
1541 .make_generic_params();
1544 noop_flat_map_generic_param(param, self)
1547 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1548 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1549 // contents="file contents")]` attributes
1550 if !at.check_name(sym::doc) {
1551 return noop_visit_attribute(at, self);
1554 if let Some(list) = at.meta_item_list() {
1555 if !list.iter().any(|it| it.check_name(sym::include)) {
1556 return noop_visit_attribute(at, self);
1559 let mut items = vec![];
1561 for mut it in list {
1562 if !it.check_name(sym::include) {
1564 noop_visit_meta_list_item(&mut it, self);
1570 if let Some(file) = it.value_str() {
1571 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1572 self.check_attributes(slice::from_ref(at));
1573 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1574 // avoid loading the file if they haven't enabled the feature
1575 return noop_visit_attribute(at, self);
1578 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1579 Ok(filename) => filename,
1586 match self.cx.source_map().load_file(&filename) {
1587 Ok(source_file) => {
1588 let src = source_file
1591 .expect("freshly loaded file should have a source");
1592 let src_interned = Symbol::intern(src.as_str());
1594 let include_info = vec![
1595 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1596 Ident::with_dummy_span(sym::file),
1600 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1601 Ident::with_dummy_span(sym::contents),
1607 let include_ident = Ident::with_dummy_span(sym::include);
1608 let item = attr::mk_list_item(include_ident, include_info);
1609 items.push(ast::NestedMetaItem::MetaItem(item));
1613 it.meta_item().and_then(|item| item.name_value_literal()).unwrap();
1615 if e.kind() == ErrorKind::InvalidData {
1619 &format!("{} wasn't a utf-8 file", filename.display()),
1621 .span_label(lit.span, "contains invalid utf-8")
1624 let mut err = self.cx.struct_span_err(
1626 &format!("couldn't read {}: {}", filename.display(), e),
1628 err.span_label(lit.span, "couldn't read file");
1635 let mut err = self.cx.struct_span_err(
1637 &format!("expected path to external documentation"),
1640 // Check if the user erroneously used `doc(include(...))` syntax.
1641 let literal = it.meta_item_list().and_then(|list| {
1642 if list.len() == 1 {
1643 list[0].literal().map(|literal| &literal.kind)
1649 let (path, applicability) = match &literal {
1650 Some(LitKind::Str(path, ..)) => {
1651 (path.to_string(), Applicability::MachineApplicable)
1653 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1656 err.span_suggestion(
1658 "provide a file path with `=`",
1659 format!("include = \"{}\"", path),
1667 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1668 *at = attr::Attribute {
1669 kind: ast::AttrKind::Normal(AttrItem {
1671 args: meta.kind.mac_args(meta.span),
1678 noop_visit_attribute(at, self)
1682 fn visit_id(&mut self, id: &mut ast::NodeId) {
1684 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1685 *id = self.cx.resolver.next_node_id()
1689 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1690 self.cfg.configure_fn_decl(&mut fn_decl);
1691 noop_visit_fn_decl(fn_decl, self);
1695 pub struct ExpansionConfig<'feat> {
1696 pub crate_name: String,
1697 pub features: Option<&'feat Features>,
1698 pub recursion_limit: usize,
1699 pub trace_mac: bool,
1700 pub should_test: bool, // If false, strip `#[test]` nodes
1701 pub single_step: bool,
1702 pub keep_macs: bool,
1705 impl<'feat> ExpansionConfig<'feat> {
1706 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1710 recursion_limit: 1024,
1718 fn proc_macro_hygiene(&self) -> bool {
1719 self.features.map_or(false, |features| features.proc_macro_hygiene)
1721 fn custom_inner_attributes(&self) -> bool {
1722 self.features.map_or(false, |features| features.custom_inner_attributes)