2 use crate::proc_macro::collect_derives;
3 use crate::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
4 use crate::mbe::macro_rules::annotate_err_with_kind;
5 use crate::placeholders::{placeholder, PlaceholderExpander};
6 use crate::config::StripUnconfigured;
9 use rustc_parse::DirectoryOwnership;
10 use rustc_parse::parser::Parser;
11 use rustc_parse::validate_attr;
12 use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
13 use syntax::ast::{MacStmtStyle, StmtKind, ItemKind};
14 use syntax::attr::{self, HasAttrs};
15 use syntax::source_map::respan;
16 use syntax::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
17 use syntax::mut_visit::*;
18 use syntax::print::pprust;
20 use syntax::sess::ParseSess;
21 use syntax::symbol::{sym, Symbol};
23 use syntax::tokenstream::{TokenStream, TokenTree};
24 use syntax::visit::{self, Visitor};
25 use syntax::util::map_in_place::MapInPlace;
27 use errors::{PResult, Applicability, FatalError};
28 use smallvec::{smallvec, SmallVec};
29 use syntax_pos::{Span, DUMMY_SP, FileName};
31 use rustc_data_structures::sync::Lrc;
32 use std::io::ErrorKind;
33 use std::{iter, mem, slice};
34 use std::ops::DerefMut;
36 use std::path::PathBuf;
38 macro_rules! ast_fragments {
40 $($Kind:ident($AstTy:ty) {
42 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
43 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
47 /// A fragment of AST that can be produced by a single macro expansion.
48 /// Can also serve as an input and intermediate result for macro expansion operations.
49 pub enum AstFragment {
50 OptExpr(Option<P<ast::Expr>>),
54 /// "Discriminant" of an AST fragment.
55 #[derive(Copy, Clone, PartialEq, Eq)]
56 pub enum AstFragmentKind {
61 impl AstFragmentKind {
62 pub fn name(self) -> &'static str {
64 AstFragmentKind::OptExpr => "expression",
65 $(AstFragmentKind::$Kind => $kind_name,)*
69 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
71 AstFragmentKind::OptExpr =>
72 result.make_expr().map(Some).map(AstFragment::OptExpr),
73 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
79 pub fn add_placeholders(&mut self, placeholders: &[NodeId]) {
80 if placeholders.is_empty() {
84 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
85 // We are repeating through arguments with `many`, to do that we have to
86 // mention some macro variable from those arguments even if it's not used.
87 #[cfg_attr(bootstrap, allow(unused_macros))]
88 macro _repeating($flat_map_ast_elt) {}
89 placeholder(AstFragmentKind::$Kind, *id).$make_ast()
91 _ => panic!("unexpected AST fragment kind")
95 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
97 AstFragment::OptExpr(expr) => expr,
98 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
102 $(pub fn $make_ast(self) -> $AstTy {
104 AstFragment::$Kind(ast) => ast,
105 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
109 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
111 AstFragment::OptExpr(opt_expr) => {
112 visit_clobber(opt_expr, |opt_expr| {
113 if let Some(expr) = opt_expr {
114 vis.filter_map_expr(expr)
120 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
121 $($(AstFragment::$Kind(ast) =>
122 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
126 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
128 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
129 AstFragment::OptExpr(None) => {}
130 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
131 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
132 visitor.$visit_ast_elt(ast_elt);
138 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
139 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
141 Some(self.make(AstFragmentKind::$Kind).$make_ast())
148 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
149 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
150 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
151 Stmts(SmallVec<[ast::Stmt; 1]>) {
152 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
154 Items(SmallVec<[P<ast::Item>; 1]>) {
155 "item"; many fn flat_map_item; fn visit_item; fn make_items;
157 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
158 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
160 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
161 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
163 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
165 many fn flat_map_foreign_item;
166 fn visit_foreign_item;
167 fn make_foreign_items;
169 Arms(SmallVec<[ast::Arm; 1]>) {
170 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
172 Fields(SmallVec<[ast::Field; 1]>) {
173 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
175 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
177 many fn flat_map_field_pattern;
178 fn visit_field_pattern;
179 fn make_field_patterns;
181 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
183 many fn flat_map_generic_param;
184 fn visit_generic_param;
185 fn make_generic_params;
187 Params(SmallVec<[ast::Param; 1]>) {
188 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
190 StructFields(SmallVec<[ast::StructField; 1]>) {
192 many fn flat_map_struct_field;
193 fn visit_struct_field;
194 fn make_struct_fields;
196 Variants(SmallVec<[ast::Variant; 1]>) {
197 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
201 impl AstFragmentKind {
202 fn dummy(self, span: Span) -> AstFragment {
203 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
206 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
208 let mut items = items.into_iter();
210 AstFragmentKind::Arms =>
211 AstFragment::Arms(items.map(Annotatable::expect_arm).collect()),
212 AstFragmentKind::Fields =>
213 AstFragment::Fields(items.map(Annotatable::expect_field).collect()),
214 AstFragmentKind::FieldPats =>
215 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()),
216 AstFragmentKind::GenericParams =>
217 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()),
218 AstFragmentKind::Params =>
219 AstFragment::Params(items.map(Annotatable::expect_param).collect()),
220 AstFragmentKind::StructFields => AstFragment::StructFields(
221 items.map(Annotatable::expect_struct_field).collect()
223 AstFragmentKind::Variants =>
224 AstFragment::Variants(items.map(Annotatable::expect_variant).collect()),
225 AstFragmentKind::Items =>
226 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
227 AstFragmentKind::ImplItems =>
228 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
229 AstFragmentKind::TraitItems =>
230 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
231 AstFragmentKind::ForeignItems =>
232 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
233 AstFragmentKind::Stmts =>
234 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
235 AstFragmentKind::Expr => AstFragment::Expr(
236 items.next().expect("expected exactly one expression").expect_expr()
238 AstFragmentKind::OptExpr =>
239 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
240 AstFragmentKind::Pat | AstFragmentKind::Ty =>
241 panic!("patterns and types aren't annotatable"),
246 pub struct Invocation {
247 pub kind: InvocationKind,
248 pub fragment_kind: AstFragmentKind,
249 pub expansion_data: ExpansionData,
252 pub enum InvocationKind {
258 attr: ast::Attribute,
260 // Required for resolving derive helper attributes.
262 // We temporarily report errors for attribute macros placed after derives
269 /// "Invocation" that contains all derives from an item,
270 /// broken into multiple `Derive` invocations when expanded.
271 /// FIXME: Find a way to remove it.
279 pub fn span(&self) -> Span {
281 InvocationKind::Bang { span, .. } => *span,
282 InvocationKind::Attr { attr, .. } => attr.span,
283 InvocationKind::Derive { path, .. } => path.span,
284 InvocationKind::DeriveContainer { item, .. } => item.span(),
289 pub struct MacroExpander<'a, 'b> {
290 pub cx: &'a mut ExtCtxt<'b>,
291 monotonic: bool, // cf. `cx.monotonic_expander()`
294 impl<'a, 'b> MacroExpander<'a, 'b> {
295 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
296 MacroExpander { cx, monotonic }
299 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
300 let mut module = ModuleData {
301 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
302 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
303 FileName::Real(path) => path,
304 other => PathBuf::from(other.to_string()),
307 module.directory.pop();
308 self.cx.root_path = module.directory.clone();
309 self.cx.current_expansion.module = Rc::new(module);
311 let orig_mod_span = krate.module.inner;
313 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
316 kind: ast::ItemKind::Mod(krate.module),
317 ident: Ident::invalid(),
318 id: ast::DUMMY_NODE_ID,
319 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
323 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
324 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
326 krate.module = module;
329 // Resolution failed so we return an empty expansion
330 krate.attrs = vec![];
331 krate.module = ast::Mod {
332 inner: orig_mod_span,
339 self.cx.trace_macros_diag();
343 // Recursively expand all macro invocations in this AST fragment.
344 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
345 let orig_expansion_data = self.cx.current_expansion.clone();
346 self.cx.current_expansion.depth = 0;
348 // Collect all macro invocations and replace them with placeholders.
349 let (mut fragment_with_placeholders, mut invocations)
350 = self.collect_invocations(input_fragment, &[]);
352 // Optimization: if we resolve all imports now,
353 // we'll be able to immediately resolve most of imported macros.
354 self.resolve_imports();
356 // Resolve paths in all invocations and produce output expanded fragments for them, but
357 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
358 // The output fragments also go through expansion recursively until no invocations are left.
359 // Unresolved macros produce dummy outputs as a recovery measure.
360 invocations.reverse();
361 let mut expanded_fragments = Vec::new();
362 let mut undetermined_invocations = Vec::new();
363 let (mut progress, mut force) = (false, !self.monotonic);
365 let invoc = if let Some(invoc) = invocations.pop() {
368 self.resolve_imports();
369 if undetermined_invocations.is_empty() { break }
370 invocations = mem::take(&mut undetermined_invocations);
371 force = !mem::replace(&mut progress, false);
375 let eager_expansion_root =
376 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
377 let res = match self.cx.resolver.resolve_macro_invocation(
378 &invoc, eager_expansion_root, force
381 Err(Indeterminate) => {
382 undetermined_invocations.push(invoc);
388 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
389 self.cx.current_expansion = invoc.expansion_data.clone();
391 // FIXME(jseyfried): Refactor out the following logic
392 let (expanded_fragment, new_invocations) = match res {
393 InvocationRes::Single(ext) => {
394 let fragment = self.expand_invoc(invoc, &ext.kind);
395 self.collect_invocations(fragment, &[])
397 InvocationRes::DeriveContainer(_exts) => {
398 // FIXME: Consider using the derive resolutions (`_exts`) immediately,
399 // instead of enqueuing the derives to be resolved again later.
400 let (derives, item) = match invoc.kind {
401 InvocationKind::DeriveContainer { derives, item } => (derives, item),
404 if !item.derive_allowed() {
405 let attr = attr::find_by_name(item.attrs(), sym::derive)
406 .expect("`derive` attribute should exist");
407 let span = attr.span;
408 let mut err = self.cx.struct_span_err(span,
409 "`derive` may only be applied to structs, enums and unions");
410 if let ast::AttrStyle::Inner = attr.style {
411 let trait_list = derives.iter()
412 .map(|t| pprust::path_to_string(t))
413 .collect::<Vec<_>>();
414 let suggestion = format!("#[derive({})]", trait_list.join(", "));
416 span, "try an outer attribute", suggestion,
417 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
418 Applicability::MaybeIncorrect
424 let mut item = self.fully_configure(item);
425 item.visit_attrs(|attrs| attrs.retain(|a| !a.has_name(sym::derive)));
427 let mut derive_placeholders = Vec::with_capacity(derives.len());
428 invocations.reserve(derives.len());
429 for path in derives {
430 let expn_id = ExpnId::fresh(None);
431 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
432 invocations.push(Invocation {
433 kind: InvocationKind::Derive { path, item: item.clone() },
434 fragment_kind: invoc.fragment_kind,
435 expansion_data: ExpansionData {
437 ..invoc.expansion_data.clone()
441 let fragment = invoc.fragment_kind
442 .expect_from_annotatables(::std::iter::once(item));
443 self.collect_invocations(fragment, &derive_placeholders)
447 if expanded_fragments.len() < depth {
448 expanded_fragments.push(Vec::new());
450 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
451 if !self.cx.ecfg.single_step {
452 invocations.extend(new_invocations.into_iter().rev());
456 self.cx.current_expansion = orig_expansion_data;
458 // Finally incorporate all the expanded macros into the input AST fragment.
459 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
460 while let Some(expanded_fragments) = expanded_fragments.pop() {
461 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
462 placeholder_expander.add(NodeId::placeholder_from_expn_id(expn_id),
466 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
467 fragment_with_placeholders
470 fn resolve_imports(&mut self) {
472 self.cx.resolver.resolve_imports();
476 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
477 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
478 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
479 /// prepares data for resolving paths of macro invocations.
480 fn collect_invocations(&mut self, mut fragment: AstFragment, extra_placeholders: &[NodeId])
481 -> (AstFragment, Vec<Invocation>) {
482 // Resolve `$crate`s in the fragment for pretty-printing.
483 self.cx.resolver.resolve_dollar_crates();
486 let mut collector = InvocationCollector {
487 cfg: StripUnconfigured {
488 sess: self.cx.parse_sess,
489 features: self.cx.ecfg.features,
492 invocations: Vec::new(),
493 monotonic: self.monotonic,
495 fragment.mut_visit_with(&mut collector);
496 fragment.add_placeholders(extra_placeholders);
497 collector.invocations
501 self.cx.resolver.visit_ast_fragment_with_placeholders(
502 self.cx.current_expansion.id, &fragment
506 (fragment, invocations)
509 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
510 let mut cfg = StripUnconfigured {
511 sess: self.cx.parse_sess,
512 features: self.cx.ecfg.features,
514 // Since the item itself has already been configured by the InvocationCollector,
515 // we know that fold result vector will contain exactly one element
517 Annotatable::Item(item) => {
518 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
520 Annotatable::TraitItem(item) => {
521 Annotatable::TraitItem(
522 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
524 Annotatable::ImplItem(item) => {
525 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
527 Annotatable::ForeignItem(item) => {
528 Annotatable::ForeignItem(
529 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
532 Annotatable::Stmt(stmt) => {
533 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
535 Annotatable::Expr(mut expr) => {
536 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
538 Annotatable::Arm(arm) => {
539 Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap())
541 Annotatable::Field(field) => {
542 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
544 Annotatable::FieldPat(fp) => {
545 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
547 Annotatable::GenericParam(param) => {
548 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
550 Annotatable::Param(param) => {
551 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
553 Annotatable::StructField(sf) => {
554 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
556 Annotatable::Variant(v) => {
557 Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap())
562 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
563 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
564 let expn_data = self.cx.current_expansion.id.expn_data();
565 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
566 let mut err = self.cx.struct_span_err(expn_data.call_site,
567 &format!("recursion limit reached while expanding the macro `{}`",
568 expn_data.kind.descr()));
570 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
573 self.cx.trace_macros_diag();
577 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
579 InvocationKind::Bang { mac, .. } => match ext {
580 SyntaxExtensionKind::Bang(expander) => {
581 self.gate_proc_macro_expansion_kind(span, fragment_kind);
582 let tok_result = expander.expand(self.cx, span, mac.stream());
583 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
585 SyntaxExtensionKind::LegacyBang(expander) => {
586 let prev = self.cx.current_expansion.prior_type_ascription;
587 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
588 let tok_result = expander.expand(self.cx, span, mac.stream());
589 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
593 "non-{kind} macro in {kind} position: {path}",
594 kind = fragment_kind.name(),
595 path = pprust::path_to_string(&mac.path),
597 self.cx.span_err(span, &msg);
598 self.cx.trace_macros_diag();
599 fragment_kind.dummy(span)
601 self.cx.current_expansion.prior_type_ascription = prev;
606 InvocationKind::Attr { attr, mut item, .. } => match ext {
607 SyntaxExtensionKind::Attr(expander) => {
608 self.gate_proc_macro_input(&item);
609 self.gate_proc_macro_attr_item(span, &item);
610 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
611 Annotatable::Item(item) => token::NtItem(item),
612 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
613 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
614 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
615 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
616 Annotatable::Expr(expr) => token::NtExpr(expr),
618 | Annotatable::Field(..)
619 | Annotatable::FieldPat(..)
620 | Annotatable::GenericParam(..)
621 | Annotatable::Param(..)
622 | Annotatable::StructField(..)
623 | Annotatable::Variant(..)
624 => panic!("unexpected annotatable"),
625 })), DUMMY_SP).into();
626 let item = attr.unwrap_normal_item();
627 let input = self.extract_proc_macro_attr_input(item.tokens, span);
628 let tok_result = expander.expand(self.cx, span, input, item_tok);
629 self.parse_ast_fragment(tok_result, fragment_kind, &item.path, span)
631 SyntaxExtensionKind::LegacyAttr(expander) => {
632 match validate_attr::parse_meta(self.cx.parse_sess, &attr) {
634 let item = expander.expand(self.cx, span, &meta, item);
635 fragment_kind.expect_from_annotatables(item)
639 fragment_kind.dummy(span)
643 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
644 attr::mark_known(&attr);
646 attr::mark_used(&attr);
648 item.visit_attrs(|attrs| attrs.push(attr));
649 fragment_kind.expect_from_annotatables(iter::once(item))
653 InvocationKind::Derive { path, item } => match ext {
654 SyntaxExtensionKind::Derive(expander) |
655 SyntaxExtensionKind::LegacyDerive(expander) => {
656 if !item.derive_allowed() {
657 return fragment_kind.dummy(span);
659 if let SyntaxExtensionKind::Derive(..) = ext {
660 self.gate_proc_macro_input(&item);
662 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
663 let items = expander.expand(self.cx, span, &meta, item);
664 fragment_kind.expect_from_annotatables(items)
668 InvocationKind::DeriveContainer { .. } => unreachable!()
672 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
673 let mut trees = tokens.trees();
675 Some(TokenTree::Delimited(_, _, tts)) => {
676 if trees.next().is_none() {
680 Some(TokenTree::Token(..)) => {}
681 None => return TokenStream::default(),
683 self.cx.span_err(span, "custom attribute invocations must be \
684 of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
685 followed by a delimiter token");
686 TokenStream::default()
689 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
690 let kind = match item {
691 Annotatable::Item(item) => match &item.kind {
692 ItemKind::Mod(m) if m.inline => "modules",
695 Annotatable::TraitItem(_)
696 | Annotatable::ImplItem(_)
697 | Annotatable::ForeignItem(_) => return,
698 Annotatable::Stmt(_) => "statements",
699 Annotatable::Expr(_) => "expressions",
701 | Annotatable::Field(..)
702 | Annotatable::FieldPat(..)
703 | Annotatable::GenericParam(..)
704 | Annotatable::Param(..)
705 | Annotatable::StructField(..)
706 | Annotatable::Variant(..)
707 => panic!("unexpected annotatable"),
709 if self.cx.ecfg.proc_macro_hygiene() {
714 sym::proc_macro_hygiene,
717 &format!("custom attributes cannot be applied to {}", kind),
721 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
722 struct GateProcMacroInput<'a> {
723 parse_sess: &'a ParseSess,
726 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
727 fn visit_item(&mut self, item: &'ast ast::Item) {
729 ast::ItemKind::Mod(module) if !module.inline => {
732 sym::proc_macro_hygiene,
735 "non-inline modules in proc macro input are unstable",
741 visit::walk_item(self, item);
744 fn visit_mac(&mut self, _: &'ast ast::Mac) {}
747 if !self.cx.ecfg.proc_macro_hygiene() {
748 annotatable.visit_with(&mut GateProcMacroInput { parse_sess: self.cx.parse_sess });
752 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
753 let kind = match kind {
754 AstFragmentKind::Expr |
755 AstFragmentKind::OptExpr => "expressions",
756 AstFragmentKind::Pat => "patterns",
757 AstFragmentKind::Stmts => "statements",
758 AstFragmentKind::Ty |
759 AstFragmentKind::Items |
760 AstFragmentKind::TraitItems |
761 AstFragmentKind::ImplItems |
762 AstFragmentKind::ForeignItems => return,
763 AstFragmentKind::Arms
764 | AstFragmentKind::Fields
765 | AstFragmentKind::FieldPats
766 | AstFragmentKind::GenericParams
767 | AstFragmentKind::Params
768 | AstFragmentKind::StructFields
769 | AstFragmentKind::Variants
770 => panic!("unexpected AST fragment kind"),
772 if self.cx.ecfg.proc_macro_hygiene() {
777 sym::proc_macro_hygiene,
780 &format!("procedural macros cannot be expanded to {}", kind),
784 fn parse_ast_fragment(
787 kind: AstFragmentKind,
791 let mut parser = self.cx.new_parser_from_tts(toks);
792 match parse_ast_fragment(&mut parser, kind, false) {
794 ensure_complete_parse(&mut parser, path, kind.name(), span);
799 annotate_err_with_kind(&mut err, kind, span);
801 self.cx.trace_macros_diag();
808 pub fn parse_ast_fragment<'a>(
809 this: &mut Parser<'a>,
810 kind: AstFragmentKind,
811 macro_legacy_warnings: bool,
812 ) -> PResult<'a, AstFragment> {
814 AstFragmentKind::Items => {
815 let mut items = SmallVec::new();
816 while let Some(item) = this.parse_item()? {
819 AstFragment::Items(items)
821 AstFragmentKind::TraitItems => {
822 let mut items = SmallVec::new();
823 while this.token != token::Eof {
824 items.push(this.parse_trait_item(&mut false)?);
826 AstFragment::TraitItems(items)
828 AstFragmentKind::ImplItems => {
829 let mut items = SmallVec::new();
830 while this.token != token::Eof {
831 items.push(this.parse_impl_item(&mut false)?);
833 AstFragment::ImplItems(items)
835 AstFragmentKind::ForeignItems => {
836 let mut items = SmallVec::new();
837 while this.token != token::Eof {
838 items.push(this.parse_foreign_item(DUMMY_SP)?);
840 AstFragment::ForeignItems(items)
842 AstFragmentKind::Stmts => {
843 let mut stmts = SmallVec::new();
844 while this.token != token::Eof &&
845 // won't make progress on a `}`
846 this.token != token::CloseDelim(token::Brace) {
847 if let Some(stmt) = this.parse_full_stmt(macro_legacy_warnings)? {
851 AstFragment::Stmts(stmts)
853 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
854 AstFragmentKind::OptExpr => {
855 if this.token != token::Eof {
856 AstFragment::OptExpr(Some(this.parse_expr()?))
858 AstFragment::OptExpr(None)
861 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
862 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?),
863 AstFragmentKind::Arms
864 | AstFragmentKind::Fields
865 | AstFragmentKind::FieldPats
866 | AstFragmentKind::GenericParams
867 | AstFragmentKind::Params
868 | AstFragmentKind::StructFields
869 | AstFragmentKind::Variants
870 => panic!("unexpected AST fragment kind"),
874 pub fn ensure_complete_parse<'a>(
875 this: &mut Parser<'a>,
880 if this.token != token::Eof {
881 let msg = format!("macro expansion ignores token `{}` and any following",
882 this.this_token_to_string());
883 // Avoid emitting backtrace info twice.
884 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
885 let mut err = this.struct_span_err(def_site_span, &msg);
886 err.span_label(span, "caused by the macro expansion here");
888 "the usage of `{}!` is likely invalid in {} context",
889 pprust::path_to_string(macro_path),
893 let semi_span = this.sess.source_map().next_point(span);
895 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
896 match this.sess.source_map().span_to_snippet(semi_full_span) {
897 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
900 "you might be missing a semicolon here",
902 Applicability::MaybeIncorrect,
911 struct InvocationCollector<'a, 'b> {
912 cx: &'a mut ExtCtxt<'b>,
913 cfg: StripUnconfigured<'a>,
914 invocations: Vec<Invocation>,
918 impl<'a, 'b> InvocationCollector<'a, 'b> {
919 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
920 // Expansion data for all the collected invocations is set upon their resolution,
921 // with exception of the derive container case which is not resolved and can get
922 // its expansion data immediately.
923 let expn_data = match &kind {
924 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
925 parent: self.cx.current_expansion.id,
927 ExpnKind::Macro(MacroKind::Attr, sym::derive),
928 item.span(), self.cx.parse_sess.edition,
933 let expn_id = ExpnId::fresh(expn_data);
934 self.invocations.push(Invocation {
937 expansion_data: ExpansionData {
939 depth: self.cx.current_expansion.depth + 1,
940 ..self.cx.current_expansion.clone()
943 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
946 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
947 self.collect(kind, InvocationKind::Bang { mac, span })
950 fn collect_attr(&mut self,
951 attr: Option<ast::Attribute>,
954 kind: AstFragmentKind,
957 self.collect(kind, match attr {
958 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
959 None => InvocationKind::DeriveContainer { derives, item },
963 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
964 -> Option<ast::Attribute> {
965 let attr = attrs.iter()
967 if a.has_name(sym::derive) {
968 *after_derive = true;
970 !attr::is_known(a) && !is_builtin_attr(a)
972 .map(|i| attrs.remove(i));
973 if let Some(attr) = &attr {
974 if !self.cx.ecfg.custom_inner_attributes() &&
975 attr.style == ast::AttrStyle::Inner && !attr.has_name(sym::test) {
976 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
977 attr.span, GateIssue::Language,
978 "non-builtin inner attributes are unstable");
984 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
985 fn classify_item<T>(&mut self, item: &mut T)
986 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
989 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
991 item.visit_attrs(|mut attrs| {
992 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
993 traits = collect_derives(&mut self.cx, &mut attrs);
996 (attr, traits, after_derive)
999 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1000 /// to the unused-attributes lint (making it an error on statements and expressions
1001 /// is a breaking change)
1002 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
1003 -> (Option<ast::Attribute>, /* after_derive */ bool) {
1004 let (mut attr, mut after_derive) = (None, false);
1006 nonitem.visit_attrs(|mut attrs| {
1007 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1010 (attr, after_derive)
1013 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1014 self.cfg.configure(node)
1017 // Detect use of feature-gated or invalid attributes on macro invocations
1018 // since they will not be detected after macro expansion.
1019 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1020 let features = self.cx.ecfg.features.unwrap();
1021 for attr in attrs.iter() {
1022 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1023 validate_attr::check_meta(self.cx.parse_sess, attr);
1025 // macros are expanded before any lint passes so this warning has to be hardcoded
1026 if attr.has_name(sym::derive) {
1027 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1028 .note("this may become a hard error in a future release")
1035 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1036 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1037 self.cfg.configure_expr(expr);
1038 visit_clobber(expr.deref_mut(), |mut expr| {
1039 self.cfg.configure_expr_kind(&mut expr.kind);
1041 // ignore derives so they remain unused
1042 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1045 // Collect the invoc regardless of whether or not attributes are permitted here
1046 // expansion will eat the attribute so it won't error later.
1047 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1049 // AstFragmentKind::Expr requires the macro to emit an expression.
1050 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1051 AstFragmentKind::Expr, after_derive)
1056 if let ast::ExprKind::Mac(mac) = expr.kind {
1057 self.check_attributes(&expr.attrs);
1058 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1062 noop_visit_expr(&mut expr, self);
1068 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1069 let mut arm = configure!(self, arm);
1071 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1072 if attr.is_some() || !traits.is_empty() {
1073 return self.collect_attr(attr, traits, Annotatable::Arm(arm),
1074 AstFragmentKind::Arms, after_derive)
1078 noop_flat_map_arm(arm, self)
1081 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1082 let mut field = configure!(self, field);
1084 let (attr, traits, after_derive) = self.classify_item(&mut field);
1085 if attr.is_some() || !traits.is_empty() {
1086 return self.collect_attr(attr, traits, Annotatable::Field(field),
1087 AstFragmentKind::Fields, after_derive)
1091 noop_flat_map_field(field, self)
1094 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1095 let mut fp = configure!(self, fp);
1097 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1098 if attr.is_some() || !traits.is_empty() {
1099 return self.collect_attr(attr, traits, Annotatable::FieldPat(fp),
1100 AstFragmentKind::FieldPats, after_derive)
1101 .make_field_patterns();
1104 noop_flat_map_field_pattern(fp, self)
1107 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1108 let mut p = configure!(self, p);
1110 let (attr, traits, after_derive) = self.classify_item(&mut p);
1111 if attr.is_some() || !traits.is_empty() {
1112 return self.collect_attr(attr, traits, Annotatable::Param(p),
1113 AstFragmentKind::Params, after_derive)
1117 noop_flat_map_param(p, self)
1120 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1121 let mut sf = configure!(self, sf);
1123 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1124 if attr.is_some() || !traits.is_empty() {
1125 return self.collect_attr(attr, traits, Annotatable::StructField(sf),
1126 AstFragmentKind::StructFields, after_derive)
1127 .make_struct_fields();
1130 noop_flat_map_struct_field(sf, self)
1133 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1134 let mut variant = configure!(self, variant);
1136 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1137 if attr.is_some() || !traits.is_empty() {
1138 return self.collect_attr(attr, traits, Annotatable::Variant(variant),
1139 AstFragmentKind::Variants, after_derive)
1143 noop_flat_map_variant(variant, self)
1146 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1147 let expr = configure!(self, expr);
1148 expr.filter_map(|mut expr| {
1149 self.cfg.configure_expr_kind(&mut expr.kind);
1151 // Ignore derives so they remain unused.
1152 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1155 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1157 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1158 AstFragmentKind::OptExpr, after_derive)
1160 .map(|expr| expr.into_inner())
1163 if let ast::ExprKind::Mac(mac) = expr.kind {
1164 self.check_attributes(&expr.attrs);
1165 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1167 .map(|expr| expr.into_inner())
1169 Some({ noop_visit_expr(&mut expr, self); expr })
1174 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1175 self.cfg.configure_pat(pat);
1177 PatKind::Mac(_) => {}
1178 _ => return noop_visit_pat(pat, self),
1181 visit_clobber(pat, |mut pat| {
1182 match mem::replace(&mut pat.kind, PatKind::Wild) {
1183 PatKind::Mac(mac) =>
1184 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1185 _ => unreachable!(),
1190 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1191 let mut stmt = configure!(self, stmt);
1193 // we'll expand attributes on expressions separately
1194 if !stmt.is_expr() {
1195 let (attr, derives, after_derive) = if stmt.is_item() {
1196 self.classify_item(&mut stmt)
1198 // ignore derives on non-item statements so it falls through
1199 // to the unused-attributes lint
1200 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1201 (attr, vec![], after_derive)
1204 if attr.is_some() || !derives.is_empty() {
1205 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1206 AstFragmentKind::Stmts, after_derive).make_stmts();
1210 if let StmtKind::Mac(mac) = stmt.kind {
1211 let (mac, style, attrs) = mac.into_inner();
1212 self.check_attributes(&attrs);
1213 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1216 // If this is a macro invocation with a semicolon, then apply that
1217 // semicolon to the final statement produced by expansion.
1218 if style == MacStmtStyle::Semicolon {
1219 if let Some(stmt) = placeholder.pop() {
1220 placeholder.push(stmt.add_trailing_semicolon());
1227 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1228 let ast::Stmt { id, kind, span } = stmt;
1229 noop_flat_map_stmt_kind(kind, self).into_iter().map(|kind| {
1230 ast::Stmt { id, kind, span }
1235 fn visit_block(&mut self, block: &mut P<Block>) {
1236 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1237 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1238 noop_visit_block(block, self);
1239 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1242 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1243 let mut item = configure!(self, item);
1245 let (attr, traits, after_derive) = self.classify_item(&mut item);
1246 if attr.is_some() || !traits.is_empty() {
1247 return self.collect_attr(attr, traits, Annotatable::Item(item),
1248 AstFragmentKind::Items, after_derive).make_items();
1252 ast::ItemKind::Mac(..) => {
1253 self.check_attributes(&item.attrs);
1254 item.and_then(|item| match item.kind {
1255 ItemKind::Mac(mac) => self.collect(
1256 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1258 _ => unreachable!(),
1261 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1262 if item.ident == Ident::invalid() {
1263 return noop_flat_map_item(item, self);
1266 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1267 let mut module = (*self.cx.current_expansion.module).clone();
1268 module.mod_path.push(item.ident);
1270 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1271 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1272 // Thus, if `inner` is the dummy span, we know the module is inline.
1273 let inline_module = item.span.contains(inner) || inner.is_dummy();
1276 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1277 self.cx.current_expansion.directory_ownership =
1278 DirectoryOwnership::Owned { relative: None };
1279 module.directory.push(&*path.as_str());
1281 module.directory.push(&*item.ident.as_str());
1284 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1285 let mut path = match path {
1286 FileName::Real(path) => path,
1287 other => PathBuf::from(other.to_string()),
1289 let directory_ownership = match path.file_name().unwrap().to_str() {
1290 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1291 Some(_) => DirectoryOwnership::Owned {
1292 relative: Some(item.ident),
1294 None => DirectoryOwnership::UnownedViaMod,
1297 module.directory = path;
1298 self.cx.current_expansion.directory_ownership = directory_ownership;
1302 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1303 let result = noop_flat_map_item(item, self);
1304 self.cx.current_expansion.module = orig_module;
1305 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1309 _ => noop_flat_map_item(item, self),
1313 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1314 let mut item = configure!(self, item);
1316 let (attr, traits, after_derive) = self.classify_item(&mut item);
1317 if attr.is_some() || !traits.is_empty() {
1318 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1319 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1323 ast::TraitItemKind::Macro(mac) => {
1324 let ast::TraitItem { attrs, span, .. } = item;
1325 self.check_attributes(&attrs);
1326 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1328 _ => noop_flat_map_trait_item(item, self),
1332 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1333 let mut item = configure!(self, item);
1335 let (attr, traits, after_derive) = self.classify_item(&mut item);
1336 if attr.is_some() || !traits.is_empty() {
1337 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1338 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1342 ast::ImplItemKind::Macro(mac) => {
1343 let ast::ImplItem { attrs, span, .. } = item;
1344 self.check_attributes(&attrs);
1345 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1347 _ => noop_flat_map_impl_item(item, self),
1351 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1353 ast::TyKind::Mac(_) => {}
1354 _ => return noop_visit_ty(ty, self),
1357 visit_clobber(ty, |mut ty| {
1358 match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1359 ast::TyKind::Mac(mac) =>
1360 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1361 _ => unreachable!(),
1366 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1367 self.cfg.configure_foreign_mod(foreign_mod);
1368 noop_visit_foreign_mod(foreign_mod, self);
1371 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1372 -> SmallVec<[ast::ForeignItem; 1]>
1374 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1376 if attr.is_some() || !traits.is_empty() {
1377 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1378 AstFragmentKind::ForeignItems, after_derive)
1379 .make_foreign_items();
1382 if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind {
1383 self.check_attributes(&foreign_item.attrs);
1384 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1385 .make_foreign_items();
1388 noop_flat_map_foreign_item(foreign_item, self)
1391 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1393 ast::ItemKind::MacroDef(..) => {}
1395 self.cfg.configure_item_kind(item);
1396 noop_visit_item_kind(item, self);
1401 fn flat_map_generic_param(
1403 param: ast::GenericParam
1404 ) -> SmallVec<[ast::GenericParam; 1]>
1406 let mut param = configure!(self, param);
1408 let (attr, traits, after_derive) = self.classify_item(&mut param);
1409 if attr.is_some() || !traits.is_empty() {
1410 return self.collect_attr(attr, traits, Annotatable::GenericParam(param),
1411 AstFragmentKind::GenericParams, after_derive)
1412 .make_generic_params();
1415 noop_flat_map_generic_param(param, self)
1418 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1419 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1420 // contents="file contents")]` attributes
1421 if !at.check_name(sym::doc) {
1422 return noop_visit_attribute(at, self);
1425 if let Some(list) = at.meta_item_list() {
1426 if !list.iter().any(|it| it.check_name(sym::include)) {
1427 return noop_visit_attribute(at, self);
1430 let mut items = vec![];
1432 for mut it in list {
1433 if !it.check_name(sym::include) {
1434 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1438 if let Some(file) = it.value_str() {
1439 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1440 self.check_attributes(slice::from_ref(at));
1441 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1442 // avoid loading the file if they haven't enabled the feature
1443 return noop_visit_attribute(at, self);
1446 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1447 Ok(filename) => filename,
1454 match self.cx.source_map().load_file(&filename) {
1455 Ok(source_file) => {
1456 let src = source_file.src.as_ref()
1457 .expect("freshly loaded file should have a source");
1458 let src_interned = Symbol::intern(src.as_str());
1460 let include_info = vec![
1461 ast::NestedMetaItem::MetaItem(
1462 attr::mk_name_value_item_str(
1463 Ident::with_dummy_span(sym::file),
1468 ast::NestedMetaItem::MetaItem(
1469 attr::mk_name_value_item_str(
1470 Ident::with_dummy_span(sym::contents),
1477 let include_ident = Ident::with_dummy_span(sym::include);
1478 let item = attr::mk_list_item(include_ident, include_info);
1479 items.push(ast::NestedMetaItem::MetaItem(item));
1484 .and_then(|item| item.name_value_literal())
1487 if e.kind() == ErrorKind::InvalidData {
1491 &format!("{} wasn't a utf-8 file", filename.display()),
1493 .span_label(lit.span, "contains invalid utf-8")
1496 let mut err = self.cx.struct_span_err(
1498 &format!("couldn't read {}: {}", filename.display(), e),
1500 err.span_label(lit.span, "couldn't read file");
1507 let mut err = self.cx.struct_span_err(
1509 &format!("expected path to external documentation"),
1512 // Check if the user erroneously used `doc(include(...))` syntax.
1513 let literal = it.meta_item_list().and_then(|list| {
1514 if list.len() == 1 {
1515 list[0].literal().map(|literal| &literal.kind)
1521 let (path, applicability) = match &literal {
1522 Some(LitKind::Str(path, ..)) => {
1523 (path.to_string(), Applicability::MachineApplicable)
1525 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1528 err.span_suggestion(
1530 "provide a file path with `=`",
1531 format!("include = \"{}\"", path),
1539 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1540 *at = attr::Attribute {
1541 kind: ast::AttrKind::Normal(
1542 AttrItem { path: meta.path, tokens: meta.kind.tokens(meta.span) },
1549 noop_visit_attribute(at, self)
1553 fn visit_id(&mut self, id: &mut ast::NodeId) {
1555 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1556 *id = self.cx.resolver.next_node_id()
1560 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1561 self.cfg.configure_fn_decl(&mut fn_decl);
1562 noop_visit_fn_decl(fn_decl, self);
1566 pub struct ExpansionConfig<'feat> {
1567 pub crate_name: String,
1568 pub features: Option<&'feat Features>,
1569 pub recursion_limit: usize,
1570 pub trace_mac: bool,
1571 pub should_test: bool, // If false, strip `#[test]` nodes
1572 pub single_step: bool,
1573 pub keep_macs: bool,
1576 impl<'feat> ExpansionConfig<'feat> {
1577 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1581 recursion_limit: 1024,
1589 fn proc_macro_hygiene(&self) -> bool {
1590 self.features.map_or(false, |features| features.proc_macro_hygiene)
1592 fn custom_inner_attributes(&self) -> bool {
1593 self.features.map_or(false, |features| features.custom_inner_attributes)