2 use crate::config::StripUnconfigured;
4 use crate::hygiene::SyntaxContext;
5 use crate::mbe::macro_rules::annotate_err_with_kind;
6 use crate::module::{mod_dir_path, parse_external_mod, DirOwnership, ParsedExternalMod};
7 use crate::placeholders::{placeholder, PlaceholderExpander};
10 use rustc_ast::mut_visit::*;
11 use rustc_ast::ptr::P;
13 use rustc_ast::tokenstream::TokenStream;
14 use rustc_ast::visit::{self, AssocCtxt, Visitor};
15 use rustc_ast::{AstLike, AttrItem, Block, Inline, ItemKind, LitKind, MacArgs};
16 use rustc_ast::{MacCallStmt, MacStmtStyle, MetaItemKind, ModKind, NestedMetaItem};
17 use rustc_ast::{NodeId, PatKind, Path, StmtKind, Unsafe};
18 use rustc_ast_pretty::pprust;
19 use rustc_attr::{self as attr, is_builtin_attr};
20 use rustc_data_structures::map_in_place::MapInPlace;
21 use rustc_data_structures::stack::ensure_sufficient_stack;
22 use rustc_data_structures::sync::Lrc;
23 use rustc_errors::{Applicability, FatalError, PResult};
24 use rustc_feature::Features;
25 use rustc_parse::parser::{AttemptLocalParseRecovery, ForceCollect, Parser, RecoverComma};
26 use rustc_parse::validate_attr;
27 use rustc_session::lint::builtin::UNUSED_DOC_COMMENTS;
28 use rustc_session::lint::BuiltinLintDiagnostics;
29 use rustc_session::parse::{feature_err, ParseSess};
30 use rustc_session::Limit;
31 use rustc_span::symbol::{sym, Ident, Symbol};
32 use rustc_span::{ExpnId, FileName, Span, DUMMY_SP};
34 use smallvec::{smallvec, SmallVec};
35 use std::io::ErrorKind;
36 use std::ops::DerefMut;
37 use std::path::PathBuf;
39 use std::{iter, mem, slice};
41 macro_rules! ast_fragments {
43 $($Kind:ident($AstTy:ty) {
45 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
46 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident($($args:tt)*);)?
50 /// A fragment of AST that can be produced by a single macro expansion.
51 /// Can also serve as an input and intermediate result for macro expansion operations.
52 pub enum AstFragment {
53 OptExpr(Option<P<ast::Expr>>),
57 /// "Discriminant" of an AST fragment.
58 #[derive(Copy, Clone, PartialEq, Eq)]
59 pub enum AstFragmentKind {
64 impl AstFragmentKind {
65 pub fn name(self) -> &'static str {
67 AstFragmentKind::OptExpr => "expression",
68 $(AstFragmentKind::$Kind => $kind_name,)*
72 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
74 AstFragmentKind::OptExpr =>
75 result.make_expr().map(Some).map(AstFragment::OptExpr),
76 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
82 pub fn add_placeholders(&mut self, placeholders: &[NodeId]) {
83 if placeholders.is_empty() {
87 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
88 // We are repeating through arguments with `many`, to do that we have to
89 // mention some macro variable from those arguments even if it's not used.
90 macro _repeating($flat_map_ast_elt) {}
91 placeholder(AstFragmentKind::$Kind, *id, None).$make_ast()
93 _ => panic!("unexpected AST fragment kind")
97 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
99 AstFragment::OptExpr(expr) => expr,
100 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
104 $(pub fn $make_ast(self) -> $AstTy {
106 AstFragment::$Kind(ast) => ast,
107 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
111 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
113 AstFragment::OptExpr(opt_expr) => {
114 visit_clobber(opt_expr, |opt_expr| {
115 if let Some(expr) = opt_expr {
116 vis.filter_map_expr(expr)
122 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
123 $($(AstFragment::$Kind(ast) =>
124 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
128 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
130 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
131 AstFragment::OptExpr(None) => {}
132 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
133 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
134 visitor.$visit_ast_elt(ast_elt, $($args)*);
140 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
141 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
143 Some(self.make(AstFragmentKind::$Kind).$make_ast())
150 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
151 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
152 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
153 Stmts(SmallVec<[ast::Stmt; 1]>) {
154 "statement"; many fn flat_map_stmt; fn visit_stmt(); fn make_stmts;
156 Items(SmallVec<[P<ast::Item>; 1]>) {
157 "item"; many fn flat_map_item; fn visit_item(); fn make_items;
159 TraitItems(SmallVec<[P<ast::AssocItem>; 1]>) {
161 many fn flat_map_trait_item;
162 fn visit_assoc_item(AssocCtxt::Trait);
165 ImplItems(SmallVec<[P<ast::AssocItem>; 1]>) {
167 many fn flat_map_impl_item;
168 fn visit_assoc_item(AssocCtxt::Impl);
171 ForeignItems(SmallVec<[P<ast::ForeignItem>; 1]>) {
173 many fn flat_map_foreign_item;
174 fn visit_foreign_item();
175 fn make_foreign_items;
177 Arms(SmallVec<[ast::Arm; 1]>) {
178 "match arm"; many fn flat_map_arm; fn visit_arm(); fn make_arms;
180 Fields(SmallVec<[ast::ExprField; 1]>) {
181 "field expression"; many fn flat_map_expr_field; fn visit_expr_field(); fn make_expr_fields;
183 FieldPats(SmallVec<[ast::PatField; 1]>) {
185 many fn flat_map_pat_field;
186 fn visit_pat_field();
189 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
191 many fn flat_map_generic_param;
192 fn visit_generic_param();
193 fn make_generic_params;
195 Params(SmallVec<[ast::Param; 1]>) {
196 "function parameter"; many fn flat_map_param; fn visit_param(); fn make_params;
198 StructFields(SmallVec<[ast::FieldDef; 1]>) {
200 many fn flat_map_field_def;
201 fn visit_field_def();
204 Variants(SmallVec<[ast::Variant; 1]>) {
205 "variant"; many fn flat_map_variant; fn visit_variant(); fn make_variants;
209 pub enum SupportsMacroExpansion {
211 Yes { supports_inner_attrs: bool },
214 impl AstFragmentKind {
215 crate fn dummy(self, span: Span) -> AstFragment {
216 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
219 pub fn supports_macro_expansion(self) -> SupportsMacroExpansion {
221 AstFragmentKind::OptExpr
222 | AstFragmentKind::Expr
223 | AstFragmentKind::Stmts
224 | AstFragmentKind::Ty
225 | AstFragmentKind::Pat => SupportsMacroExpansion::Yes { supports_inner_attrs: false },
226 AstFragmentKind::Items
227 | AstFragmentKind::TraitItems
228 | AstFragmentKind::ImplItems
229 | AstFragmentKind::ForeignItems => {
230 SupportsMacroExpansion::Yes { supports_inner_attrs: true }
232 AstFragmentKind::Arms
233 | AstFragmentKind::Fields
234 | AstFragmentKind::FieldPats
235 | AstFragmentKind::GenericParams
236 | AstFragmentKind::Params
237 | AstFragmentKind::StructFields
238 | AstFragmentKind::Variants => SupportsMacroExpansion::No,
242 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(
246 let mut items = items.into_iter();
248 AstFragmentKind::Arms => {
249 AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
251 AstFragmentKind::Fields => {
252 AstFragment::Fields(items.map(Annotatable::expect_expr_field).collect())
254 AstFragmentKind::FieldPats => {
255 AstFragment::FieldPats(items.map(Annotatable::expect_pat_field).collect())
257 AstFragmentKind::GenericParams => {
258 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
260 AstFragmentKind::Params => {
261 AstFragment::Params(items.map(Annotatable::expect_param).collect())
263 AstFragmentKind::StructFields => {
264 AstFragment::StructFields(items.map(Annotatable::expect_field_def).collect())
266 AstFragmentKind::Variants => {
267 AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
269 AstFragmentKind::Items => {
270 AstFragment::Items(items.map(Annotatable::expect_item).collect())
272 AstFragmentKind::ImplItems => {
273 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
275 AstFragmentKind::TraitItems => {
276 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
278 AstFragmentKind::ForeignItems => {
279 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
281 AstFragmentKind::Stmts => {
282 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
284 AstFragmentKind::Expr => AstFragment::Expr(
285 items.next().expect("expected exactly one expression").expect_expr(),
287 AstFragmentKind::OptExpr => {
288 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
290 AstFragmentKind::Pat | AstFragmentKind::Ty => {
291 panic!("patterns and types aren't annotatable")
297 pub struct Invocation {
298 pub kind: InvocationKind,
299 pub fragment_kind: AstFragmentKind,
300 pub expansion_data: ExpansionData,
303 pub enum InvocationKind {
309 attr: ast::Attribute,
310 // Re-insertion position for inert attributes.
313 // Required for resolving derive helper attributes.
322 impl InvocationKind {
323 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
324 // HACK: For unnamed fields placeholders should have the same visibility as the actual
325 // fields because for tuple structs/variants resolve determines visibilities of their
326 // constructor using these field visibilities before attributes on them are are expanded.
327 // The assumption is that the attribute expansion cannot change field visibilities,
328 // and it holds because only inert attributes are supported in this position.
330 InvocationKind::Attr { item: Annotatable::FieldDef(field), .. }
331 | InvocationKind::Derive { item: Annotatable::FieldDef(field), .. }
332 if field.ident.is_none() =>
334 Some(field.vis.clone())
342 pub fn span(&self) -> Span {
344 InvocationKind::Bang { span, .. } => *span,
345 InvocationKind::Attr { attr, .. } => attr.span,
346 InvocationKind::Derive { path, .. } => path.span,
351 pub struct MacroExpander<'a, 'b> {
352 pub cx: &'a mut ExtCtxt<'b>,
353 monotonic: bool, // cf. `cx.monotonic_expander()`
356 impl<'a, 'b> MacroExpander<'a, 'b> {
357 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
358 MacroExpander { cx, monotonic }
361 // FIXME: Avoid visiting the crate as a `Mod` item,
362 // make crate a first class expansion target instead.
363 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
364 let file_path = match self.cx.source_map().span_to_unmapped_path(krate.span) {
365 FileName::Real(name) => name.into_local_path(),
366 other => PathBuf::from(other.to_string()),
368 let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
369 self.cx.root_path = dir_path.clone();
370 self.cx.current_expansion.module = Rc::new(ModuleData {
371 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
372 file_path_stack: vec![file_path],
376 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
379 kind: ast::ItemKind::Mod(
381 ModKind::Loaded(krate.items, Inline::Yes, krate.span)
383 ident: Ident::invalid(),
384 id: ast::DUMMY_NODE_ID,
385 vis: ast::Visibility {
386 span: krate.span.shrink_to_lo(),
387 kind: ast::VisibilityKind::Public,
393 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
396 kind: ast::ItemKind::Mod(_, ModKind::Loaded(items, ..)),
403 // Resolution failed so we return an empty expansion
404 krate.attrs = vec![];
405 krate.items = vec![];
407 Some(ast::Item { span, kind, .. }) => {
408 krate.attrs = vec![];
409 krate.items = vec![];
413 "expected crate top-level item to be a module after macro expansion, found {} {}",
414 kind.article(), kind.descr()
417 // FIXME: this workaround issue #84569
421 self.cx.trace_macros_diag();
425 // Recursively expand all macro invocations in this AST fragment.
426 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
427 let orig_expansion_data = self.cx.current_expansion.clone();
428 let orig_force_mode = self.cx.force_mode;
429 self.cx.current_expansion.depth = 0;
431 // Collect all macro invocations and replace them with placeholders.
432 let (mut fragment_with_placeholders, mut invocations) =
433 self.collect_invocations(input_fragment, &[]);
435 // Optimization: if we resolve all imports now,
436 // we'll be able to immediately resolve most of imported macros.
437 self.resolve_imports();
439 // Resolve paths in all invocations and produce output expanded fragments for them, but
440 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
441 // The output fragments also go through expansion recursively until no invocations are left.
442 // Unresolved macros produce dummy outputs as a recovery measure.
443 invocations.reverse();
444 let mut expanded_fragments = Vec::new();
445 let mut undetermined_invocations = Vec::new();
446 let (mut progress, mut force) = (false, !self.monotonic);
448 let (invoc, ext) = if let Some(invoc) = invocations.pop() {
451 self.resolve_imports();
452 if undetermined_invocations.is_empty() {
455 invocations = mem::take(&mut undetermined_invocations);
456 force = !mem::replace(&mut progress, false);
457 if force && self.monotonic {
458 self.cx.sess.delay_span_bug(
459 invocations.last().unwrap().0.span(),
460 "expansion entered force mode without producing any errors",
466 let ext = match ext {
469 let eager_expansion_root = if self.monotonic {
470 invoc.expansion_data.id
472 orig_expansion_data.id
474 match self.cx.resolver.resolve_macro_invocation(
476 eager_expansion_root,
480 Err(Indeterminate) => {
481 // Cannot resolve, will retry this invocation later.
482 undetermined_invocations.push((invoc, None));
489 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
490 self.cx.current_expansion = invoc.expansion_data.clone();
491 self.cx.force_mode = force;
493 let fragment_kind = invoc.fragment_kind;
494 let (expanded_fragment, new_invocations) = match self.expand_invoc(invoc, &ext.kind) {
495 ExpandResult::Ready(fragment) => {
496 let mut derive_invocations = Vec::new();
497 let derive_placeholders = self
500 .take_derive_resolutions(expn_id)
502 enum AnnotatableRef<'a> {
503 Item(&'a P<ast::Item>),
506 let item = match &fragment {
507 AstFragment::Items(items) => match &items[..] {
508 [item] => AnnotatableRef::Item(item),
511 AstFragment::Stmts(stmts) => match &stmts[..] {
512 [stmt] => AnnotatableRef::Stmt(stmt),
518 derive_invocations.reserve(derives.len());
521 .map(|(path, _exts)| {
522 // FIXME: Consider using the derive resolutions (`_exts`)
523 // instead of enqueuing the derives to be resolved again later.
524 let expn_id = ExpnId::fresh(None);
525 derive_invocations.push((
527 kind: InvocationKind::Derive {
530 AnnotatableRef::Item(item) => {
531 Annotatable::Item(item.clone())
533 AnnotatableRef::Stmt(stmt) => {
534 Annotatable::Stmt(P(stmt.clone()))
539 expansion_data: ExpansionData {
541 ..self.cx.current_expansion.clone()
546 NodeId::placeholder_from_expn_id(expn_id)
550 .unwrap_or_default();
552 let (fragment, collected_invocations) =
553 self.collect_invocations(fragment, &derive_placeholders);
554 // We choose to expand any derive invocations associated with this macro invocation
555 // *before* any macro invocations collected from the output fragment
556 derive_invocations.extend(collected_invocations);
557 (fragment, derive_invocations)
559 ExpandResult::Retry(invoc) => {
563 "expansion entered force mode but is still stuck",
566 // Cannot expand, will retry this invocation later.
567 undetermined_invocations.push((invoc, Some(ext)));
574 if expanded_fragments.len() < depth {
575 expanded_fragments.push(Vec::new());
577 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
578 invocations.extend(new_invocations.into_iter().rev());
581 self.cx.current_expansion = orig_expansion_data;
582 self.cx.force_mode = orig_force_mode;
584 // Finally incorporate all the expanded macros into the input AST fragment.
585 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
586 while let Some(expanded_fragments) = expanded_fragments.pop() {
587 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
589 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
592 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
593 fragment_with_placeholders
596 fn resolve_imports(&mut self) {
598 self.cx.resolver.resolve_imports();
602 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
603 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
604 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
605 /// prepares data for resolving paths of macro invocations.
606 fn collect_invocations(
608 mut fragment: AstFragment,
609 extra_placeholders: &[NodeId],
610 ) -> (AstFragment, Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>) {
611 // Resolve `$crate`s in the fragment for pretty-printing.
612 self.cx.resolver.resolve_dollar_crates();
615 let mut collector = InvocationCollector {
616 // Non-derive macro invocations cannot see the results of cfg expansion - they
617 // will either be removed along with the item, or invoked before the cfg/cfg_attr
618 // attribute is expanded. Therefore, we don't need to configure the tokens
619 // Derive macros *can* see the results of cfg-expansion - they are handled
620 // specially in `fully_expand_fragment`
621 cfg: StripUnconfigured {
623 features: self.cx.ecfg.features,
624 config_tokens: false,
627 invocations: Vec::new(),
628 monotonic: self.monotonic,
630 fragment.mut_visit_with(&mut collector);
631 fragment.add_placeholders(extra_placeholders);
632 collector.invocations
638 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
641 (fragment, invocations)
644 fn error_recursion_limit_reached(&mut self) {
645 let expn_data = self.cx.current_expansion.id.expn_data();
646 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
650 &format!("recursion limit reached while expanding `{}`", expn_data.kind.descr()),
653 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
654 suggested_limit, self.cx.ecfg.crate_name,
657 self.cx.trace_macros_diag();
660 /// A macro's expansion does not fit in this fragment kind.
661 /// For example, a non-type macro in a type position.
662 fn error_wrong_fragment_kind(&mut self, kind: AstFragmentKind, mac: &ast::MacCall, span: Span) {
664 "non-{kind} macro in {kind} position: {path}",
666 path = pprust::path_to_string(&mac.path),
668 self.cx.span_err(span, &msg);
669 self.cx.trace_macros_diag();
675 ext: &SyntaxExtensionKind,
676 ) -> ExpandResult<AstFragment, Invocation> {
677 let recursion_limit =
678 self.cx.reduced_recursion_limit.unwrap_or(self.cx.ecfg.recursion_limit);
679 if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) {
680 if self.cx.reduced_recursion_limit.is_none() {
681 self.error_recursion_limit_reached();
684 // Reduce the recursion limit by half each time it triggers.
685 self.cx.reduced_recursion_limit = Some(recursion_limit / 2);
687 return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span()));
690 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
691 ExpandResult::Ready(match invoc.kind {
692 InvocationKind::Bang { mac, .. } => match ext {
693 SyntaxExtensionKind::Bang(expander) => {
694 let tok_result = match expander.expand(self.cx, span, mac.args.inner_tokens()) {
695 Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)),
698 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
700 SyntaxExtensionKind::LegacyBang(expander) => {
701 let prev = self.cx.current_expansion.prior_type_ascription;
702 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
703 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
704 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
707 self.error_wrong_fragment_kind(fragment_kind, &mac, span);
708 fragment_kind.dummy(span)
710 self.cx.current_expansion.prior_type_ascription = prev;
715 InvocationKind::Attr { attr, pos, mut item, derives } => match ext {
716 SyntaxExtensionKind::Attr(expander) => {
717 self.gate_proc_macro_input(&item);
718 self.gate_proc_macro_attr_item(span, &item);
719 let mut fake_tokens = false;
720 if let Annotatable::Item(item_inner) = &item {
721 if let ItemKind::Mod(_, mod_kind) = &item_inner.kind {
722 // FIXME: Collect tokens and use them instead of generating
723 // fake ones. These are unstable, so it needs to be
724 // fixed prior to stabilization
725 // Fake tokens when we are invoking an inner attribute, and:
726 fake_tokens = matches!(attr.style, ast::AttrStyle::Inner) &&
727 // We are invoking an attribute on the crate root, or an outline
729 (item_inner.ident.name.is_empty() || !matches!(mod_kind, ast::ModKind::Loaded(_, Inline::Yes, _)));
732 let tokens = if fake_tokens {
733 rustc_parse::fake_token_stream(
734 &self.cx.sess.parse_sess,
735 &item.into_nonterminal(),
738 item.into_tokens(&self.cx.sess.parse_sess)
740 let attr_item = attr.unwrap_normal_item();
741 if let MacArgs::Eq(..) = attr_item.args {
742 self.cx.span_err(span, "key-value macro attributes are not supported");
744 let inner_tokens = attr_item.args.inner_tokens();
745 let tok_result = match expander.expand(self.cx, span, inner_tokens, tokens) {
746 Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)),
749 self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span)
751 SyntaxExtensionKind::LegacyAttr(expander) => {
752 match validate_attr::parse_meta(&self.cx.sess.parse_sess, &attr) {
754 let items = match expander.expand(self.cx, span, &meta, item) {
755 ExpandResult::Ready(items) => items,
756 ExpandResult::Retry(item) => {
757 // Reassemble the original invocation for retrying.
758 return ExpandResult::Retry(Invocation {
759 kind: InvocationKind::Attr { attr, pos, item, derives },
764 if fragment_kind == AstFragmentKind::Expr && items.is_empty() {
766 "removing an expression is not supported in this position";
767 self.cx.span_err(span, msg);
768 fragment_kind.dummy(span)
770 fragment_kind.expect_from_annotatables(items)
775 fragment_kind.dummy(span)
779 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
780 self.cx.sess.mark_attr_known(&attr);
782 self.cx.sess.mark_attr_used(&attr);
784 item.visit_attrs(|attrs| attrs.insert(pos, attr));
785 fragment_kind.expect_from_annotatables(iter::once(item))
789 InvocationKind::Derive { path, item } => match ext {
790 SyntaxExtensionKind::Derive(expander)
791 | SyntaxExtensionKind::LegacyDerive(expander) => {
792 if let SyntaxExtensionKind::Derive(..) = ext {
793 self.gate_proc_macro_input(&item);
795 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
796 let items = match expander.expand(self.cx, span, &meta, item) {
797 ExpandResult::Ready(items) => items,
798 ExpandResult::Retry(item) => {
799 // Reassemble the original invocation for retrying.
800 return ExpandResult::Retry(Invocation {
801 kind: InvocationKind::Derive { path: meta.path, item },
806 fragment_kind.expect_from_annotatables(items)
813 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
814 let kind = match item {
816 | Annotatable::TraitItem(_)
817 | Annotatable::ImplItem(_)
818 | Annotatable::ForeignItem(_) => return,
819 Annotatable::Stmt(stmt) => {
820 // Attributes are stable on item statements,
821 // but unstable on all other kinds of statements
827 Annotatable::Expr(_) => "expressions",
829 | Annotatable::ExprField(..)
830 | Annotatable::PatField(..)
831 | Annotatable::GenericParam(..)
832 | Annotatable::Param(..)
833 | Annotatable::FieldDef(..)
834 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
836 if self.cx.ecfg.proc_macro_hygiene() {
840 &self.cx.sess.parse_sess,
841 sym::proc_macro_hygiene,
843 &format!("custom attributes cannot be applied to {}", kind),
848 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
849 struct GateProcMacroInput<'a> {
850 parse_sess: &'a ParseSess,
853 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
854 fn visit_item(&mut self, item: &'ast ast::Item) {
856 ast::ItemKind::Mod(_, mod_kind)
857 if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _)) =>
861 sym::proc_macro_hygiene,
863 "non-inline modules in proc macro input are unstable",
870 visit::walk_item(self, item);
874 if !self.cx.ecfg.proc_macro_hygiene() {
876 .visit_with(&mut GateProcMacroInput { parse_sess: &self.cx.sess.parse_sess });
880 fn parse_ast_fragment(
883 kind: AstFragmentKind,
887 let mut parser = self.cx.new_parser_from_tts(toks);
888 match parse_ast_fragment(&mut parser, kind) {
890 ensure_complete_parse(&mut parser, path, kind.name(), span);
894 if err.span.is_dummy() {
897 annotate_err_with_kind(&mut err, kind, span);
899 self.cx.trace_macros_diag();
906 pub fn parse_ast_fragment<'a>(
907 this: &mut Parser<'a>,
908 kind: AstFragmentKind,
909 ) -> PResult<'a, AstFragment> {
911 AstFragmentKind::Items => {
912 let mut items = SmallVec::new();
913 while let Some(item) = this.parse_item(ForceCollect::No)? {
916 AstFragment::Items(items)
918 AstFragmentKind::TraitItems => {
919 let mut items = SmallVec::new();
920 while let Some(item) = this.parse_trait_item(ForceCollect::No)? {
923 AstFragment::TraitItems(items)
925 AstFragmentKind::ImplItems => {
926 let mut items = SmallVec::new();
927 while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
930 AstFragment::ImplItems(items)
932 AstFragmentKind::ForeignItems => {
933 let mut items = SmallVec::new();
934 while let Some(item) = this.parse_foreign_item(ForceCollect::No)? {
937 AstFragment::ForeignItems(items)
939 AstFragmentKind::Stmts => {
940 let mut stmts = SmallVec::new();
941 // Won't make progress on a `}`.
942 while this.token != token::Eof && this.token != token::CloseDelim(token::Brace) {
943 if let Some(stmt) = this.parse_full_stmt(AttemptLocalParseRecovery::Yes)? {
947 AstFragment::Stmts(stmts)
949 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
950 AstFragmentKind::OptExpr => {
951 if this.token != token::Eof {
952 AstFragment::OptExpr(Some(this.parse_expr()?))
954 AstFragment::OptExpr(None)
957 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
958 AstFragmentKind::Pat => {
959 AstFragment::Pat(this.parse_pat_allow_top_alt(None, RecoverComma::No)?)
961 AstFragmentKind::Arms
962 | AstFragmentKind::Fields
963 | AstFragmentKind::FieldPats
964 | AstFragmentKind::GenericParams
965 | AstFragmentKind::Params
966 | AstFragmentKind::StructFields
967 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
971 pub fn ensure_complete_parse<'a>(
972 this: &mut Parser<'a>,
977 if this.token != token::Eof {
978 let token = pprust::token_to_string(&this.token);
979 let msg = format!("macro expansion ignores token `{}` and any following", token);
980 // Avoid emitting backtrace info twice.
981 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
982 let mut err = this.struct_span_err(def_site_span, &msg);
983 err.span_label(span, "caused by the macro expansion here");
985 "the usage of `{}!` is likely invalid in {} context",
986 pprust::path_to_string(macro_path),
990 let semi_span = this.sess.source_map().next_point(span);
992 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
993 match this.sess.source_map().span_to_snippet(semi_full_span) {
994 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
997 "you might be missing a semicolon here",
999 Applicability::MaybeIncorrect,
1008 struct InvocationCollector<'a, 'b> {
1009 cx: &'a mut ExtCtxt<'b>,
1010 cfg: StripUnconfigured<'a>,
1011 invocations: Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>,
1015 impl<'a, 'b> InvocationCollector<'a, 'b> {
1016 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
1017 let expn_id = ExpnId::fresh(None);
1018 let vis = kind.placeholder_visibility();
1019 self.invocations.push((
1023 expansion_data: ExpansionData {
1025 depth: self.cx.current_expansion.depth + 1,
1026 ..self.cx.current_expansion.clone()
1031 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
1038 kind: AstFragmentKind,
1040 self.collect(kind, InvocationKind::Bang { mac, span })
1045 (attr, pos, derives): (ast::Attribute, usize, Vec<Path>),
1047 kind: AstFragmentKind,
1049 self.collect(kind, InvocationKind::Attr { attr, pos, item, derives })
1052 /// If `item` is an attribute invocation, remove the attribute and return it together with
1053 /// its position and derives following it. We have to collect the derives in order to resolve
1054 /// legacy derive helpers (helpers written before derives that introduce them).
1057 item: &mut impl AstLike,
1058 ) -> Option<(ast::Attribute, usize, Vec<Path>)> {
1059 let mut attr = None;
1061 item.visit_attrs(|attrs| {
1064 .position(|a| !self.cx.sess.is_attr_known(a) && !is_builtin_attr(a))
1066 let attr = attrs.remove(attr_pos);
1067 let following_derives = attrs[attr_pos..]
1069 .filter(|a| a.has_name(sym::derive))
1070 .flat_map(|a| a.meta_item_list().unwrap_or_default())
1071 .filter_map(|nested_meta| match nested_meta {
1072 NestedMetaItem::MetaItem(ast::MetaItem {
1073 kind: MetaItemKind::Word,
1081 (attr, attr_pos, following_derives)
1088 fn configure<T: AstLike>(&mut self, node: T) -> Option<T> {
1089 self.cfg.configure(node)
1092 // Detect use of feature-gated or invalid attributes on macro invocations
1093 // since they will not be detected after macro expansion.
1094 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1095 let features = self.cx.ecfg.features.unwrap();
1096 let mut attrs = attrs.iter().peekable();
1097 let mut span: Option<Span> = None;
1098 while let Some(attr) = attrs.next() {
1099 rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features);
1100 validate_attr::check_meta(&self.cx.sess.parse_sess, attr);
1102 let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
1103 span = Some(current_span);
1105 if attrs.peek().map_or(false, |next_attr| next_attr.doc_str().is_some()) {
1109 if attr.doc_str().is_some() {
1110 self.cx.sess.parse_sess.buffer_lint_with_diagnostic(
1111 &UNUSED_DOC_COMMENTS,
1114 "unused doc comment",
1115 BuiltinLintDiagnostics::UnusedDocComment(attr.span),
1122 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1123 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1124 self.cfg.configure_expr(expr);
1125 visit_clobber(expr.deref_mut(), |mut expr| {
1126 if let Some(attr) = self.take_first_attr(&mut expr) {
1127 // Collect the invoc regardless of whether or not attributes are permitted here
1128 // expansion will eat the attribute so it won't error later.
1129 self.cfg.maybe_emit_expr_attr_err(&attr.0);
1131 // AstFragmentKind::Expr requires the macro to emit an expression.
1133 .collect_attr(attr, Annotatable::Expr(P(expr)), AstFragmentKind::Expr)
1138 if let ast::ExprKind::MacCall(mac) = expr.kind {
1139 self.check_attributes(&expr.attrs);
1140 self.collect_bang(mac, expr.span, AstFragmentKind::Expr).make_expr().into_inner()
1142 ensure_sufficient_stack(|| noop_visit_expr(&mut expr, self));
1148 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1149 let mut arm = configure!(self, arm);
1151 if let Some(attr) = self.take_first_attr(&mut arm) {
1153 .collect_attr(attr, Annotatable::Arm(arm), AstFragmentKind::Arms)
1157 noop_flat_map_arm(arm, self)
1160 fn flat_map_expr_field(&mut self, field: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
1161 let mut field = configure!(self, field);
1163 if let Some(attr) = self.take_first_attr(&mut field) {
1165 .collect_attr(attr, Annotatable::ExprField(field), AstFragmentKind::Fields)
1166 .make_expr_fields();
1169 noop_flat_map_expr_field(field, self)
1172 fn flat_map_pat_field(&mut self, fp: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
1173 let mut fp = configure!(self, fp);
1175 if let Some(attr) = self.take_first_attr(&mut fp) {
1177 .collect_attr(attr, Annotatable::PatField(fp), AstFragmentKind::FieldPats)
1181 noop_flat_map_pat_field(fp, self)
1184 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1185 let mut p = configure!(self, p);
1187 if let Some(attr) = self.take_first_attr(&mut p) {
1189 .collect_attr(attr, Annotatable::Param(p), AstFragmentKind::Params)
1193 noop_flat_map_param(p, self)
1196 fn flat_map_field_def(&mut self, sf: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
1197 let mut sf = configure!(self, sf);
1199 if let Some(attr) = self.take_first_attr(&mut sf) {
1201 .collect_attr(attr, Annotatable::FieldDef(sf), AstFragmentKind::StructFields)
1205 noop_flat_map_field_def(sf, self)
1208 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1209 let mut variant = configure!(self, variant);
1211 if let Some(attr) = self.take_first_attr(&mut variant) {
1213 .collect_attr(attr, Annotatable::Variant(variant), AstFragmentKind::Variants)
1217 noop_flat_map_variant(variant, self)
1220 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1221 let expr = configure!(self, expr);
1222 expr.filter_map(|mut expr| {
1223 if let Some(attr) = self.take_first_attr(&mut expr) {
1224 self.cfg.maybe_emit_expr_attr_err(&attr.0);
1227 .collect_attr(attr, Annotatable::Expr(P(expr)), AstFragmentKind::OptExpr)
1229 .map(|expr| expr.into_inner());
1232 if let ast::ExprKind::MacCall(mac) = expr.kind {
1233 self.check_attributes(&expr.attrs);
1234 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1236 .map(|expr| expr.into_inner())
1239 noop_visit_expr(&mut expr, self);
1246 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1248 PatKind::MacCall(_) => {}
1249 _ => return noop_visit_pat(pat, self),
1252 visit_clobber(pat, |mut pat| match mem::replace(&mut pat.kind, PatKind::Wild) {
1253 PatKind::MacCall(mac) => {
1254 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat()
1256 _ => unreachable!(),
1260 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1261 let mut stmt = configure!(self, stmt);
1263 // we'll expand attributes on expressions separately
1264 if !stmt.is_expr() {
1265 if let Some(attr) = self.take_first_attr(&mut stmt) {
1267 .collect_attr(attr, Annotatable::Stmt(P(stmt)), AstFragmentKind::Stmts)
1272 if let StmtKind::MacCall(mac) = stmt.kind {
1273 let MacCallStmt { mac, style, attrs, tokens: _ } = mac.into_inner();
1274 self.check_attributes(&attrs);
1275 let mut placeholder =
1276 self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts).make_stmts();
1278 // If this is a macro invocation with a semicolon, then apply that
1279 // semicolon to the final statement produced by expansion.
1280 if style == MacStmtStyle::Semicolon {
1281 if let Some(stmt) = placeholder.pop() {
1282 placeholder.push(stmt.add_trailing_semicolon());
1289 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1290 let ast::Stmt { id, kind, span } = stmt;
1291 noop_flat_map_stmt_kind(kind, self)
1293 .map(|kind| ast::Stmt { id, kind, span })
1297 fn visit_block(&mut self, block: &mut P<Block>) {
1298 let orig_dir_ownership = mem::replace(
1299 &mut self.cx.current_expansion.dir_ownership,
1300 DirOwnership::UnownedViaBlock,
1302 noop_visit_block(block, self);
1303 self.cx.current_expansion.dir_ownership = orig_dir_ownership;
1306 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1307 let mut item = configure!(self, item);
1309 if let Some(attr) = self.take_first_attr(&mut item) {
1311 .collect_attr(attr, Annotatable::Item(item), AstFragmentKind::Items)
1315 let mut attrs = mem::take(&mut item.attrs); // We do this to please borrowck.
1316 let ident = item.ident;
1317 let span = item.span;
1320 ast::ItemKind::MacCall(..) => {
1322 self.check_attributes(&item.attrs);
1323 item.and_then(|item| match item.kind {
1324 ItemKind::MacCall(mac) => {
1325 self.collect_bang(mac, span, AstFragmentKind::Items).make_items()
1327 _ => unreachable!(),
1330 ast::ItemKind::Mod(_, ref mut mod_kind) if ident != Ident::invalid() => {
1331 let (file_path, dir_path, dir_ownership) = match mod_kind {
1332 ModKind::Loaded(_, inline, _) => {
1333 // Inline `mod foo { ... }`, but we still need to push directories.
1334 let (dir_path, dir_ownership) = mod_dir_path(
1338 &self.cx.current_expansion.module,
1339 self.cx.current_expansion.dir_ownership,
1343 (None, dir_path, dir_ownership)
1345 ModKind::Unloaded => {
1346 // We have an outline `mod foo;` so we need to parse the file.
1347 let old_attrs_len = attrs.len();
1348 let ParsedExternalMod {
1354 } = parse_external_mod(
1358 &self.cx.current_expansion.module,
1359 self.cx.current_expansion.dir_ownership,
1363 if let Some(extern_mod_loaded) = self.cx.extern_mod_loaded {
1364 (attrs, items) = extern_mod_loaded(ident, attrs, items, inner_span);
1367 *mod_kind = ModKind::Loaded(items, Inline::No, inner_span);
1369 if item.attrs.len() > old_attrs_len {
1370 // If we loaded an out-of-line module and added some inner attributes,
1371 // then we need to re-configure it and re-collect attributes for
1372 // resolution and expansion.
1373 item = configure!(self, item);
1375 if let Some(attr) = self.take_first_attr(&mut item) {
1379 Annotatable::Item(item),
1380 AstFragmentKind::Items,
1385 (Some(file_path), dir_path, dir_ownership)
1389 // Set the module info before we flat map.
1390 let mut module = self.cx.current_expansion.module.with_dir_path(dir_path);
1391 module.mod_path.push(ident);
1392 if let Some(file_path) = file_path {
1393 module.file_path_stack.push(file_path);
1397 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1398 let orig_dir_ownership =
1399 mem::replace(&mut self.cx.current_expansion.dir_ownership, dir_ownership);
1401 let result = noop_flat_map_item(item, self);
1403 // Restore the module info.
1404 self.cx.current_expansion.dir_ownership = orig_dir_ownership;
1405 self.cx.current_expansion.module = orig_module;
1411 noop_flat_map_item(item, self)
1416 fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1417 let mut item = configure!(self, item);
1419 if let Some(attr) = self.take_first_attr(&mut item) {
1421 .collect_attr(attr, Annotatable::TraitItem(item), AstFragmentKind::TraitItems)
1422 .make_trait_items();
1426 ast::AssocItemKind::MacCall(..) => {
1427 self.check_attributes(&item.attrs);
1428 item.and_then(|item| match item.kind {
1429 ast::AssocItemKind::MacCall(mac) => self
1430 .collect_bang(mac, item.span, AstFragmentKind::TraitItems)
1431 .make_trait_items(),
1432 _ => unreachable!(),
1435 _ => noop_flat_map_assoc_item(item, self),
1439 fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1440 let mut item = configure!(self, item);
1442 if let Some(attr) = self.take_first_attr(&mut item) {
1444 .collect_attr(attr, Annotatable::ImplItem(item), AstFragmentKind::ImplItems)
1449 ast::AssocItemKind::MacCall(..) => {
1450 self.check_attributes(&item.attrs);
1451 item.and_then(|item| match item.kind {
1452 ast::AssocItemKind::MacCall(mac) => self
1453 .collect_bang(mac, item.span, AstFragmentKind::ImplItems)
1455 _ => unreachable!(),
1458 _ => noop_flat_map_assoc_item(item, self),
1462 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1464 ast::TyKind::MacCall(_) => {}
1465 _ => return noop_visit_ty(ty, self),
1468 visit_clobber(ty, |mut ty| match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1469 ast::TyKind::MacCall(mac) => {
1470 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty()
1472 _ => unreachable!(),
1476 fn flat_map_foreign_item(
1478 foreign_item: P<ast::ForeignItem>,
1479 ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
1480 let mut foreign_item = configure!(self, foreign_item);
1482 if let Some(attr) = self.take_first_attr(&mut foreign_item) {
1486 Annotatable::ForeignItem(foreign_item),
1487 AstFragmentKind::ForeignItems,
1489 .make_foreign_items();
1492 match foreign_item.kind {
1493 ast::ForeignItemKind::MacCall(..) => {
1494 self.check_attributes(&foreign_item.attrs);
1495 foreign_item.and_then(|item| match item.kind {
1496 ast::ForeignItemKind::MacCall(mac) => self
1497 .collect_bang(mac, item.span, AstFragmentKind::ForeignItems)
1498 .make_foreign_items(),
1499 _ => unreachable!(),
1502 _ => noop_flat_map_foreign_item(foreign_item, self),
1506 fn flat_map_generic_param(
1508 param: ast::GenericParam,
1509 ) -> SmallVec<[ast::GenericParam; 1]> {
1510 let mut param = configure!(self, param);
1512 if let Some(attr) = self.take_first_attr(&mut param) {
1516 Annotatable::GenericParam(param),
1517 AstFragmentKind::GenericParams,
1519 .make_generic_params();
1522 noop_flat_map_generic_param(param, self)
1525 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1526 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1527 // contents="file contents")]` attributes
1528 if !self.cx.sess.check_name(at, sym::doc) {
1529 return noop_visit_attribute(at, self);
1532 if let Some(list) = at.meta_item_list() {
1533 if !list.iter().any(|it| it.has_name(sym::include)) {
1534 return noop_visit_attribute(at, self);
1537 let mut items = vec![];
1539 for mut it in list {
1540 if !it.has_name(sym::include) {
1542 noop_visit_meta_list_item(&mut it, self);
1548 if let Some(file) = it.value_str() {
1549 let err_count = self.cx.sess.parse_sess.span_diagnostic.err_count();
1550 self.check_attributes(slice::from_ref(at));
1551 if self.cx.sess.parse_sess.span_diagnostic.err_count() > err_count {
1552 // avoid loading the file if they haven't enabled the feature
1553 return noop_visit_attribute(at, self);
1556 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1557 Ok(filename) => filename,
1564 match self.cx.source_map().load_file(&filename) {
1565 Ok(source_file) => {
1566 let src = source_file
1569 .expect("freshly loaded file should have a source");
1570 let src_interned = Symbol::intern(src.as_str());
1572 let include_info = vec![
1573 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1574 Ident::with_dummy_span(sym::file),
1578 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1579 Ident::with_dummy_span(sym::contents),
1585 let include_ident = Ident::with_dummy_span(sym::include);
1586 let item = attr::mk_list_item(include_ident, include_info);
1587 items.push(ast::NestedMetaItem::MetaItem(item));
1590 let lit_span = it.name_value_literal_span().unwrap();
1592 if e.kind() == ErrorKind::InvalidData {
1596 &format!("{} wasn't a utf-8 file", filename.display()),
1598 .span_label(lit_span, "contains invalid utf-8")
1601 let mut err = self.cx.struct_span_err(
1603 &format!("couldn't read {}: {}", filename.display(), e),
1605 err.span_label(lit_span, "couldn't read file");
1614 .struct_span_err(it.span(), "expected path to external documentation");
1616 // Check if the user erroneously used `doc(include(...))` syntax.
1617 let literal = it.meta_item_list().and_then(|list| {
1618 if list.len() == 1 {
1619 list[0].literal().map(|literal| &literal.kind)
1625 let (path, applicability) = match &literal {
1626 Some(LitKind::Str(path, ..)) => {
1627 (path.to_string(), Applicability::MachineApplicable)
1629 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1632 err.span_suggestion(
1634 "provide a file path with `=`",
1635 format!("include = \"{}\"", path),
1643 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1644 *at = ast::Attribute {
1645 kind: ast::AttrKind::Normal(
1646 AttrItem { path: meta.path, args: meta.kind.mac_args(meta.span), tokens: None },
1654 noop_visit_attribute(at, self)
1658 fn visit_id(&mut self, id: &mut ast::NodeId) {
1660 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1661 *id = self.cx.resolver.next_node_id()
1666 pub struct ExpansionConfig<'feat> {
1667 pub crate_name: String,
1668 pub features: Option<&'feat Features>,
1669 pub recursion_limit: Limit,
1670 pub trace_mac: bool,
1671 pub should_test: bool, // If false, strip `#[test]` nodes
1672 pub span_debug: bool, // If true, use verbose debugging for `proc_macro::Span`
1673 pub proc_macro_backtrace: bool, // If true, show backtraces for proc-macro panics
1676 impl<'feat> ExpansionConfig<'feat> {
1677 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1681 recursion_limit: Limit::new(1024),
1685 proc_macro_backtrace: false,
1689 fn proc_macro_hygiene(&self) -> bool {
1690 self.features.map_or(false, |features| features.proc_macro_hygiene)