1use std::any::Any;
2use std::default::Default;
3use std::iter;
4use std::path::PathBuf;
5use std::rc::Rc;
6use std::sync::Arc;
7
8use rustc_ast::attr::MarkedAttrs;
9use rustc_ast::tokenstream::TokenStream;
10use rustc_ast::visit::{AssocCtxt, Visitor};
11use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind, Safety};
12use rustc_attr_ir::{self as attrs, CfgEntry, Deprecation, Stability, find_attr};
13use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
14use rustc_data_structures::sync;
15use rustc_errors::{BufferedEarlyLint, DiagCtxtHandle, ErrorGuaranteed};
16use rustc_feature::Features;
17use rustc_hir::def::MacroKinds;
18use rustc_lint_defs::RegisteredTools;
19use rustc_parse::MACRO_ARGUMENTS;
20use rustc_parse::parser::Parser;
21use rustc_session::Session;
22use rustc_session::parse::ParseSess;
23use rustc_span::def_id::{CrateNum, DefId, LocalDefId, ModId};
24use rustc_span::edition::Edition;
25use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind};
26use rustc_span::source_map::SourceMap;
27use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw};
28use rustc_structures::{CollapseMacroDebuginfo, Limit};
29use smallvec::{SmallVec, smallvec};
30use thin_vec::ThinVec;
31
32use crate::diagnostics;
33use crate::expand::{self, AstFragment, Invocation};
34use crate::mbe::macro_rules::ParserAnyMacro;
35use crate::module::DirOwnership;
36use crate::stats::MacroStat;
37
38#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Annotatable {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Annotatable::Item(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Item",
&__self_0),
Annotatable::AssocItem(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"AssocItem", __self_0, &__self_1),
Annotatable::ForeignItem(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ForeignItem", &__self_0),
Annotatable::Stmt(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Stmt",
&__self_0),
Annotatable::Expr(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Expr",
&__self_0),
Annotatable::Arm(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Arm",
&__self_0),
Annotatable::ExprField(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ExprField", &__self_0),
Annotatable::PatField(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"PatField", &__self_0),
Annotatable::GenericParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"GenericParam", &__self_0),
Annotatable::Param(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Param",
&__self_0),
Annotatable::FieldDef(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FieldDef", &__self_0),
Annotatable::Variant(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Variant", &__self_0),
Annotatable::WherePredicate(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"WherePredicate", &__self_0),
Annotatable::Crate(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Crate",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for Annotatable {
#[inline]
fn clone(&self) -> Annotatable {
match self {
Annotatable::Item(__self_0) =>
Annotatable::Item(::core::clone::Clone::clone(__self_0)),
Annotatable::AssocItem(__self_0, __self_1) =>
Annotatable::AssocItem(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Annotatable::ForeignItem(__self_0) =>
Annotatable::ForeignItem(::core::clone::Clone::clone(__self_0)),
Annotatable::Stmt(__self_0) =>
Annotatable::Stmt(::core::clone::Clone::clone(__self_0)),
Annotatable::Expr(__self_0) =>
Annotatable::Expr(::core::clone::Clone::clone(__self_0)),
Annotatable::Arm(__self_0) =>
Annotatable::Arm(::core::clone::Clone::clone(__self_0)),
Annotatable::ExprField(__self_0) =>
Annotatable::ExprField(::core::clone::Clone::clone(__self_0)),
Annotatable::PatField(__self_0) =>
Annotatable::PatField(::core::clone::Clone::clone(__self_0)),
Annotatable::GenericParam(__self_0) =>
Annotatable::GenericParam(::core::clone::Clone::clone(__self_0)),
Annotatable::Param(__self_0) =>
Annotatable::Param(::core::clone::Clone::clone(__self_0)),
Annotatable::FieldDef(__self_0) =>
Annotatable::FieldDef(::core::clone::Clone::clone(__self_0)),
Annotatable::Variant(__self_0) =>
Annotatable::Variant(::core::clone::Clone::clone(__self_0)),
Annotatable::WherePredicate(__self_0) =>
Annotatable::WherePredicate(::core::clone::Clone::clone(__self_0)),
Annotatable::Crate(__self_0) =>
Annotatable::Crate(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
44pub enum Annotatable {
45 Item(Box<ast::Item>),
46 AssocItem(Box<ast::AssocItem>, AssocCtxt),
47 ForeignItem(Box<ast::ForeignItem>),
48 Stmt(Box<ast::Stmt>),
49 Expr(Box<ast::Expr>),
50 Arm(ast::Arm),
51 ExprField(ast::ExprField),
52 PatField(ast::PatField),
53 GenericParam(ast::GenericParam),
54 Param(ast::Param),
55 FieldDef(ast::FieldDef),
56 Variant(ast::Variant),
57 WherePredicate(ast::WherePredicate),
58 Crate(ast::Crate),
59}
60
61impl Annotatable {
62 pub fn span(&self) -> Span {
63 match self {
64 Annotatable::Item(item) => item.span,
65 Annotatable::AssocItem(assoc_item, _) => assoc_item.span,
66 Annotatable::ForeignItem(foreign_item) => foreign_item.span,
67 Annotatable::Stmt(stmt) => stmt.span,
68 Annotatable::Expr(expr) => expr.span,
69 Annotatable::Arm(arm) => arm.span,
70 Annotatable::ExprField(field) => field.span,
71 Annotatable::PatField(fp) => fp.pat.span,
72 Annotatable::GenericParam(gp) => gp.ident.span,
73 Annotatable::Param(p) => p.span,
74 Annotatable::FieldDef(sf) => sf.span,
75 Annotatable::Variant(v) => v.span,
76 Annotatable::WherePredicate(wp) => wp.span,
77 Annotatable::Crate(c) => c.spans.inner_span,
78 }
79 }
80
81 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
82 match self {
83 Annotatable::Item(item) => item.visit_attrs(f),
84 Annotatable::AssocItem(assoc_item, _) => assoc_item.visit_attrs(f),
85 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
86 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
87 Annotatable::Expr(expr) => expr.visit_attrs(f),
88 Annotatable::Arm(arm) => arm.visit_attrs(f),
89 Annotatable::ExprField(field) => field.visit_attrs(f),
90 Annotatable::PatField(fp) => fp.visit_attrs(f),
91 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
92 Annotatable::Param(p) => p.visit_attrs(f),
93 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
94 Annotatable::Variant(v) => v.visit_attrs(f),
95 Annotatable::WherePredicate(wp) => wp.visit_attrs(f),
96 Annotatable::Crate(c) => c.visit_attrs(f),
97 }
98 }
99
100 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) -> V::Result {
101 match self {
102 Annotatable::Item(item) => visitor.visit_item(item),
103 Annotatable::AssocItem(item, ctxt) => visitor.visit_assoc_item(item, *ctxt),
104 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
105 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
106 Annotatable::Expr(expr) => visitor.visit_expr(expr),
107 Annotatable::Arm(arm) => visitor.visit_arm(arm),
108 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
109 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
110 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
111 Annotatable::Param(p) => visitor.visit_param(p),
112 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
113 Annotatable::Variant(v) => visitor.visit_variant(v),
114 Annotatable::WherePredicate(wp) => visitor.visit_where_predicate(wp),
115 Annotatable::Crate(c) => visitor.visit_crate(c),
116 }
117 }
118
119 pub fn to_tokens(&self) -> TokenStream {
121 match self {
122 Annotatable::Item(node) => TokenStream::from_ast(node),
123 Annotatable::AssocItem(node, _) => TokenStream::from_ast(node),
124 Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
125 Annotatable::Stmt(node) => {
126 if !!#[allow(non_exhaustive_omitted_patterns)] match node.kind {
ast::StmtKind::Empty => true,
_ => false,
} {
::core::panicking::panic("assertion failed: !matches!(node.kind, ast::StmtKind::Empty)")
};assert!(!matches!(node.kind, ast::StmtKind::Empty));
127 TokenStream::from_ast(node)
128 }
129 Annotatable::Expr(node) => TokenStream::from_ast(node),
130 Annotatable::Arm(..)
131 | Annotatable::ExprField(..)
132 | Annotatable::PatField(..)
133 | Annotatable::GenericParam(..)
134 | Annotatable::Param(..)
135 | Annotatable::FieldDef(..)
136 | Annotatable::Variant(..)
137 | Annotatable::WherePredicate(..)
138 | Annotatable::Crate(..) => { ::core::panicking::panic_fmt(format_args!("unexpected annotatable")); }panic!("unexpected annotatable"),
139 }
140 }
141
142 pub fn expect_item(self) -> Box<ast::Item> {
143 match self {
144 Annotatable::Item(i) => i,
145 _ => { ::core::panicking::panic_fmt(format_args!("expected Item")); }panic!("expected Item"),
146 }
147 }
148
149 pub fn expect_trait_item(self) -> Box<ast::AssocItem> {
150 match self {
151 Annotatable::AssocItem(i, AssocCtxt::Trait) => i,
152 _ => { ::core::panicking::panic_fmt(format_args!("expected trait item")); }panic!("expected trait item"),
153 }
154 }
155
156 pub fn expect_impl_item(self) -> Box<ast::AssocItem> {
157 match self {
158 Annotatable::AssocItem(i, AssocCtxt::Impl { .. }) => i,
159 _ => { ::core::panicking::panic_fmt(format_args!("expected impl item")); }panic!("expected impl item"),
160 }
161 }
162
163 pub fn expect_foreign_item(self) -> Box<ast::ForeignItem> {
164 match self {
165 Annotatable::ForeignItem(i) => i,
166 _ => { ::core::panicking::panic_fmt(format_args!("expected foreign item")); }panic!("expected foreign item"),
167 }
168 }
169
170 pub fn expect_stmt(self) -> ast::Stmt {
171 match self {
172 Annotatable::Stmt(stmt) => *stmt,
173 _ => { ::core::panicking::panic_fmt(format_args!("expected statement")); }panic!("expected statement"),
174 }
175 }
176
177 pub fn expect_expr(self) -> Box<ast::Expr> {
178 match self {
179 Annotatable::Expr(expr) => expr,
180 _ => { ::core::panicking::panic_fmt(format_args!("expected expression")); }panic!("expected expression"),
181 }
182 }
183
184 pub fn expect_arm(self) -> ast::Arm {
185 match self {
186 Annotatable::Arm(arm) => arm,
187 _ => { ::core::panicking::panic_fmt(format_args!("expected match arm")); }panic!("expected match arm"),
188 }
189 }
190
191 pub fn expect_expr_field(self) -> ast::ExprField {
192 match self {
193 Annotatable::ExprField(field) => field,
194 _ => { ::core::panicking::panic_fmt(format_args!("expected field")); }panic!("expected field"),
195 }
196 }
197
198 pub fn expect_pat_field(self) -> ast::PatField {
199 match self {
200 Annotatable::PatField(fp) => fp,
201 _ => { ::core::panicking::panic_fmt(format_args!("expected field pattern")); }panic!("expected field pattern"),
202 }
203 }
204
205 pub fn expect_generic_param(self) -> ast::GenericParam {
206 match self {
207 Annotatable::GenericParam(gp) => gp,
208 _ => { ::core::panicking::panic_fmt(format_args!("expected generic parameter")); }panic!("expected generic parameter"),
209 }
210 }
211
212 pub fn expect_param(self) -> ast::Param {
213 match self {
214 Annotatable::Param(param) => param,
215 _ => { ::core::panicking::panic_fmt(format_args!("expected parameter")); }panic!("expected parameter"),
216 }
217 }
218
219 pub fn expect_field_def(self) -> ast::FieldDef {
220 match self {
221 Annotatable::FieldDef(sf) => sf,
222 _ => { ::core::panicking::panic_fmt(format_args!("expected struct field")); }panic!("expected struct field"),
223 }
224 }
225
226 pub fn expect_variant(self) -> ast::Variant {
227 match self {
228 Annotatable::Variant(v) => v,
229 _ => { ::core::panicking::panic_fmt(format_args!("expected variant")); }panic!("expected variant"),
230 }
231 }
232
233 pub fn expect_where_predicate(self) -> ast::WherePredicate {
234 match self {
235 Annotatable::WherePredicate(wp) => wp,
236 _ => { ::core::panicking::panic_fmt(format_args!("expected where predicate")); }panic!("expected where predicate"),
237 }
238 }
239
240 pub fn expect_crate(self) -> ast::Crate {
241 match self {
242 Annotatable::Crate(krate) => krate,
243 _ => { ::core::panicking::panic_fmt(format_args!("expected krate")); }panic!("expected krate"),
244 }
245 }
246}
247
248pub enum ExpandResult<T, U> {
251 Ready(T),
253 Retry(U),
255}
256
257impl<T, U> ExpandResult<T, U> {
258 pub fn map<E, F: FnOnce(T) -> E>(self, f: F) -> ExpandResult<E, U> {
259 match self {
260 ExpandResult::Ready(t) => ExpandResult::Ready(f(t)),
261 ExpandResult::Retry(u) => ExpandResult::Retry(u),
262 }
263 }
264}
265
266impl<'cx> MacroExpanderResult<'cx> {
267 pub fn from_tts(
271 cx: &'cx mut ExtCtxt<'_>,
272 tts: TokenStream,
273 site_span: Span,
274 arm_span: Span,
275 macro_ident: Ident,
276 ) -> Self {
277 let is_local = true;
279 let parser =
280 ParserAnyMacro::from_tts(cx, tts, site_span, arm_span, is_local, macro_ident, &[], &[]);
281 ExpandResult::Ready(Box::new(parser))
282 }
283}
284
285pub trait MultiItemModifier {
286 fn expand(
288 &self,
289 ecx: &mut ExtCtxt<'_>,
290 span: Span,
291 meta_item: &ast::MetaItem,
292 item: Annotatable,
293 is_derive_const: bool,
294 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
295}
296
297impl<F> MultiItemModifier for F
298where
299 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
300{
301 fn expand(
302 &self,
303 ecx: &mut ExtCtxt<'_>,
304 span: Span,
305 meta_item: &ast::MetaItem,
306 item: Annotatable,
307 _is_derive_const: bool,
308 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
309 ExpandResult::Ready(self(ecx, span, meta_item, item))
310 }
311}
312
313pub trait BangProcMacro {
314 fn expand<'cx>(
315 &self,
316 ecx: &'cx mut ExtCtxt<'_>,
317 span: Span,
318 ts: TokenStream,
319 ) -> Result<TokenStream, ErrorGuaranteed>;
320}
321
322impl<F> BangProcMacro for F
323where
324 F: Fn(&mut ExtCtxt<'_>, Span, TokenStream) -> Result<TokenStream, ErrorGuaranteed>,
325{
326 fn expand<'cx>(
327 &self,
328 ecx: &'cx mut ExtCtxt<'_>,
329 span: Span,
330 ts: TokenStream,
331 ) -> Result<TokenStream, ErrorGuaranteed> {
332 self(ecx, span, ts)
334 }
335}
336
337pub trait AttrProcMacro {
338 fn expand<'cx>(
339 &self,
340 ecx: &'cx mut ExtCtxt<'_>,
341 span: Span,
342 annotation: TokenStream,
343 annotated: TokenStream,
344 ) -> Result<TokenStream, ErrorGuaranteed>;
345
346 fn expand_with_safety<'cx>(
348 &self,
349 ecx: &'cx mut ExtCtxt<'_>,
350 safety: Safety,
351 span: Span,
352 annotation: TokenStream,
353 annotated: TokenStream,
354 ) -> Result<TokenStream, ErrorGuaranteed> {
355 if let Safety::Unsafe(span) = safety {
356 ecx.dcx().span_err(span, "unnecessary `unsafe` on safe attribute");
357 }
358 self.expand(ecx, span, annotation, annotated)
359 }
360}
361
362impl<F> AttrProcMacro for F
363where
364 F: Fn(TokenStream, TokenStream) -> TokenStream,
365{
366 fn expand<'cx>(
367 &self,
368 _ecx: &'cx mut ExtCtxt<'_>,
369 _span: Span,
370 annotation: TokenStream,
371 annotated: TokenStream,
372 ) -> Result<TokenStream, ErrorGuaranteed> {
373 Ok(self(annotation, annotated))
375 }
376}
377
378pub trait TTMacroExpander: Any {
380 fn expand<'cx, 'a: 'cx>(
381 &'a self,
382 ecx: &'cx mut ExtCtxt<'_>,
383 span: Span,
384 input: TokenStream,
385 ) -> MacroExpanderResult<'cx>;
386}
387
388pub type MacroExpanderResult<'cx> = ExpandResult<Box<dyn MacResult + 'cx>, ()>;
389
390pub type MacroExpanderFn =
391 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> MacroExpanderResult<'cx>;
392
393impl<F: 'static> TTMacroExpander for F
394where
395 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> MacroExpanderResult<'cx>,
396{
397 fn expand<'cx, 'a: 'cx>(
398 &'a self,
399 ecx: &'cx mut ExtCtxt<'_>,
400 span: Span,
401 input: TokenStream,
402 ) -> MacroExpanderResult<'cx> {
403 self(ecx, span, input)
404 }
405}
406
407pub trait GlobDelegationExpander {
408 fn expand(&self, ecx: &mut ExtCtxt<'_>) -> ExpandResult<Vec<(Ident, Option<Ident>)>, ()>;
409}
410
411fn make_stmts_default(expr: Option<Box<ast::Expr>>) -> Option<SmallVec<[ast::Stmt; 1]>> {
412 expr.map(|e| {
413 {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(ast::Stmt {
id: ast::DUMMY_NODE_ID,
span: e.span,
kind: ast::StmtKind::Expr(e),
});
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ast::Stmt {
id: ast::DUMMY_NODE_ID,
span: e.span,
kind: ast::StmtKind::Expr(e),
}])))
}
}smallvec![ast::Stmt { id: ast::DUMMY_NODE_ID, span: e.span, kind: ast::StmtKind::Expr(e) }]
414 })
415}
416
417pub trait MacResult {
420 fn make_expr(self: Box<Self>) -> Option<Box<ast::Expr>> {
422 None
423 }
424
425 fn make_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
427 None
428 }
429
430 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
432 None
433 }
434
435 fn make_trait_impl_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
437 None
438 }
439
440 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
442 None
443 }
444
445 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
447 None
448 }
449
450 fn make_pat(self: Box<Self>) -> Option<Box<ast::Pat>> {
452 None
453 }
454
455 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
460 make_stmts_default(self.make_expr())
461 }
462
463 fn make_ty(self: Box<Self>) -> Option<Box<ast::Ty>> {
464 None
465 }
466
467 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
468 None
469 }
470
471 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
472 None
473 }
474
475 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
476 None
477 }
478
479 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
480 None
481 }
482
483 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
484 None
485 }
486
487 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
488 None
489 }
490
491 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
492 None
493 }
494
495 fn make_where_predicates(self: Box<Self>) -> Option<SmallVec<[ast::WherePredicate; 1]>> {
496 None
497 }
498
499 fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
500 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
502 }
503}
504
505#[derive(#[automatically_derived]
impl ::core::default::Default for MacEager {
#[inline]
fn default() -> MacEager {
MacEager {
expr: ::core::default::Default::default(),
items: ::core::default::Default::default(),
ty: ::core::default::Default::default(),
}
}
}Default)]
508pub struct MacEager {
509 pub expr: Option<Box<ast::Expr>>,
510 pub items: Option<SmallVec<[Box<ast::Item>; 1]>>,
511 pub ty: Option<Box<ast::Ty>>,
512}
513
514impl MacEager {
515 pub fn expr(v: Box<ast::Expr>) -> Box<dyn MacResult> {
516 Box::new(MacEager { expr: Some(v), ..Default::default() })
517 }
518
519 pub fn items(v: SmallVec<[Box<ast::Item>; 1]>) -> Box<dyn MacResult> {
520 Box::new(MacEager { items: Some(v), ..Default::default() })
521 }
522
523 pub fn ty(v: Box<ast::Ty>) -> Box<dyn MacResult> {
524 Box::new(MacEager { ty: Some(v), ..Default::default() })
525 }
526}
527
528impl MacResult for MacEager {
529 fn make_expr(self: Box<Self>) -> Option<Box<ast::Expr>> {
530 self.expr
531 }
532
533 fn make_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
534 self.items
535 }
536
537 fn make_pat(self: Box<Self>) -> Option<Box<ast::Pat>> {
538 if let Some(e) = self.expr {
539 if #[allow(non_exhaustive_omitted_patterns)] match e.kind {
ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_) => true,
_ => false,
}matches!(e.kind, ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_)) {
540 return Some(Box::new(ast::Pat {
541 id: ast::DUMMY_NODE_ID,
542 span: e.span,
543 kind: PatKind::Expr(e),
544 }));
545 }
546 }
547 None
548 }
549
550 fn make_ty(self: Box<Self>) -> Option<Box<ast::Ty>> {
551 self.ty
552 }
553}
554
555#[derive(#[automatically_derived]
impl ::core::marker::Copy for DummyResult { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DummyResult { }
#[automatically_derived]
impl ::core::clone::Clone for DummyResult {
#[inline]
fn clone(&self) -> DummyResult {
let _: ::core::clone::AssertParamIsClone<Option<ErrorGuaranteed>>;
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone)]
558pub struct DummyResult {
559 guar: Option<ErrorGuaranteed>,
560 span: Span,
561}
562
563impl DummyResult {
564 pub fn any(span: Span, guar: ErrorGuaranteed) -> Box<dyn MacResult + 'static> {
569 Box::new(DummyResult { guar: Some(guar), span })
570 }
571
572 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
574 Box::new(DummyResult { guar: None, span })
575 }
576
577 pub fn raw_expr(sp: Span, guar: Option<ErrorGuaranteed>) -> Box<ast::Expr> {
579 Box::new(ast::Expr {
580 id: ast::DUMMY_NODE_ID,
581 kind: if let Some(guar) = guar {
582 ast::ExprKind::Err(guar)
583 } else {
584 ast::ExprKind::Tup(ThinVec::new())
585 },
586 span: sp,
587 attrs: ast::AttrVec::new(),
588 tokens: None,
589 })
590 }
591}
592
593impl MacResult for DummyResult {
594 fn make_expr(self: Box<DummyResult>) -> Option<Box<ast::Expr>> {
595 Some(DummyResult::raw_expr(self.span, self.guar))
596 }
597
598 fn make_pat(self: Box<DummyResult>) -> Option<Box<ast::Pat>> {
599 Some(Box::new(ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: self.span }))
600 }
601
602 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
603 Some(SmallVec::new())
604 }
605
606 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
607 Some(SmallVec::new())
608 }
609
610 fn make_trait_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
611 Some(SmallVec::new())
612 }
613
614 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
615 Some(SmallVec::new())
616 }
617
618 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
619 Some(SmallVec::new())
620 }
621
622 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
623 Some({
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(ast::Stmt {
id: ast::DUMMY_NODE_ID,
kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span,
self.guar)),
span: self.span,
});
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ast::Stmt {
id: ast::DUMMY_NODE_ID,
kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span,
self.guar)),
span: self.span,
}])))
}
}smallvec![ast::Stmt {
624 id: ast::DUMMY_NODE_ID,
625 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.guar)),
626 span: self.span,
627 }])
628 }
629
630 fn make_ty(self: Box<DummyResult>) -> Option<Box<ast::Ty>> {
631 Some(Box::new(ast::Ty {
635 id: ast::DUMMY_NODE_ID,
636 kind: ast::TyKind::Tup(ThinVec::new()),
637 span: self.span,
638 }))
639 }
640
641 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
642 Some(SmallVec::new())
643 }
644
645 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
646 Some(SmallVec::new())
647 }
648
649 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
650 Some(SmallVec::new())
651 }
652
653 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
654 Some(SmallVec::new())
655 }
656
657 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
658 Some(SmallVec::new())
659 }
660
661 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
662 Some(SmallVec::new())
663 }
664
665 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
666 Some(SmallVec::new())
667 }
668
669 fn make_crate(self: Box<DummyResult>) -> Option<ast::Crate> {
670 Some(ast::Crate {
671 attrs: Default::default(),
672 items: Default::default(),
673 spans: Default::default(),
674 id: ast::DUMMY_NODE_ID,
675 is_placeholder: Default::default(),
676 })
677 }
678}
679
680#[derive(#[automatically_derived]
impl ::core::clone::Clone for SyntaxExtensionKind {
#[inline]
fn clone(&self) -> SyntaxExtensionKind {
match self {
SyntaxExtensionKind::MacroRules(__self_0) =>
SyntaxExtensionKind::MacroRules(::core::clone::Clone::clone(__self_0)),
SyntaxExtensionKind::Bang(__self_0) =>
SyntaxExtensionKind::Bang(::core::clone::Clone::clone(__self_0)),
SyntaxExtensionKind::LegacyBang(__self_0) =>
SyntaxExtensionKind::LegacyBang(::core::clone::Clone::clone(__self_0)),
SyntaxExtensionKind::Attr(__self_0) =>
SyntaxExtensionKind::Attr(::core::clone::Clone::clone(__self_0)),
SyntaxExtensionKind::LegacyAttr(__self_0) =>
SyntaxExtensionKind::LegacyAttr(::core::clone::Clone::clone(__self_0)),
SyntaxExtensionKind::NonMacroAttr =>
SyntaxExtensionKind::NonMacroAttr,
SyntaxExtensionKind::Derive(__self_0) =>
SyntaxExtensionKind::Derive(::core::clone::Clone::clone(__self_0)),
SyntaxExtensionKind::LegacyDerive(__self_0) =>
SyntaxExtensionKind::LegacyDerive(::core::clone::Clone::clone(__self_0)),
SyntaxExtensionKind::GlobDelegation(__self_0) =>
SyntaxExtensionKind::GlobDelegation(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
682pub enum SyntaxExtensionKind {
683 MacroRules(Arc<crate::MacroRulesMacroExpander>),
685
686 Bang(
688 Arc<dyn BangProcMacro + sync::DynSync + sync::DynSend>,
690 ),
691
692 LegacyBang(
694 Arc<dyn TTMacroExpander + sync::DynSync + sync::DynSend>,
696 ),
697
698 Attr(
700 Arc<dyn AttrProcMacro + sync::DynSync + sync::DynSend>,
704 ),
705
706 LegacyAttr(
708 Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
712 ),
713
714 NonMacroAttr,
719
720 Derive(
722 Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
730 ),
731
732 LegacyDerive(
734 Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
737 ),
738
739 GlobDelegation(Arc<dyn GlobDelegationExpander + sync::DynSync + sync::DynSend>),
743}
744
745impl SyntaxExtensionKind {
746 pub fn as_legacy_bang(&self) -> Option<&(dyn TTMacroExpander + sync::DynSync + sync::DynSend)> {
750 match self {
751 SyntaxExtensionKind::LegacyBang(exp) => Some(exp.as_ref()),
752 SyntaxExtensionKind::MacroRules(exp) if exp.kinds().contains(MacroKinds::BANG) => {
753 Some(exp.as_ref())
754 }
755 _ => None,
756 }
757 }
758
759 pub fn as_attr(&self) -> Option<&(dyn AttrProcMacro + sync::DynSync + sync::DynSend)> {
763 match self {
764 SyntaxExtensionKind::Attr(exp) => Some(exp.as_ref()),
765 SyntaxExtensionKind::MacroRules(exp) if exp.kinds().contains(MacroKinds::ATTR) => {
766 Some(exp.as_ref())
767 }
768 _ => None,
769 }
770 }
771}
772
773pub struct SyntaxExtension {
775 pub kind: SyntaxExtensionKind,
777 pub span: Span,
779 pub allow_internal_unstable: Option<Arc<[Symbol]>>,
781 pub stability: Option<Stability>,
783 pub deprecation: Option<Deprecation>,
785 pub helper_attrs: Vec<Symbol>,
787 pub edition: Edition,
789 pub builtin_name: Option<Symbol>,
792 pub allow_internal_unsafe: bool,
794 pub local_inner_macros: bool,
796 pub collapse_debuginfo: bool,
799 pub diagnostic_opaque: bool,
802}
803
804impl SyntaxExtension {
805 pub fn macro_kinds(&self) -> MacroKinds {
807 match self.kind {
808 SyntaxExtensionKind::Bang(..)
809 | SyntaxExtensionKind::LegacyBang(..)
810 | SyntaxExtensionKind::GlobDelegation(..) => MacroKinds::BANG,
811 SyntaxExtensionKind::Attr(..)
812 | SyntaxExtensionKind::LegacyAttr(..)
813 | SyntaxExtensionKind::NonMacroAttr => MacroKinds::ATTR,
814 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
815 MacroKinds::DERIVE
816 }
817 SyntaxExtensionKind::MacroRules(ref m) => m.kinds(),
818 }
819 }
820
821 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
823 SyntaxExtension {
824 span: DUMMY_SP,
825 allow_internal_unstable: None,
826 stability: None,
827 deprecation: None,
828 helper_attrs: Vec::new(),
829 edition,
830 builtin_name: None,
831 kind,
832 allow_internal_unsafe: false,
833 local_inner_macros: false,
834 collapse_debuginfo: false,
835 diagnostic_opaque: false,
836 }
837 }
838
839 fn get_collapse_debuginfo(sess: &Session, attrs: &[attrs::Attribute], ext: bool) -> bool {
846 let flag = sess.opts.cg.collapse_macro_debuginfo;
847 let attr = if let Some(info) = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(CollapseDebugInfo(info)) =>
{
break 'done Some(info);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, CollapseDebugInfo(info) => info) {
848 *info
849 } else if {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcBuiltinMacro { .. })
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, RustcBuiltinMacro { .. }) {
850 CollapseMacroDebuginfo::Yes
851 } else {
852 CollapseMacroDebuginfo::Unspecified
853 };
854
855 #[rustfmt::skip]
856 let collapse_table = [
857 [false, false, false, false],
858 [false, ext, ext, true],
859 [false, ext, ext, true],
860 [true, true, true, true],
861 ];
862 collapse_table[flag as usize][attr as usize]
863 }
864
865 pub fn new(
868 sess: &Session,
869 kind: SyntaxExtensionKind,
870 span: Span,
871 helper_attrs: Vec<Symbol>,
872 edition: Edition,
873 name: Symbol,
874 attrs: &[attrs::Attribute],
875 is_local: bool,
876 ) -> SyntaxExtension {
877 let allow_internal_unstable = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(AllowInternalUnstable(i,
_)) => {
break 'done Some(i);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, AllowInternalUnstable(i, _) => i)
878 .map(|i| i.as_slice())
879 .unwrap_or_default();
880 let allow_internal_unsafe = {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(AllowInternalUnsafe(_))
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, AllowInternalUnsafe(_));
881
882 let local_inner_macros =
883 *{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(MacroExport {
local_inner_macros: l, .. }) => {
break 'done Some(l);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, MacroExport {local_inner_macros: l, ..} => l).unwrap_or(&false);
884 let collapse_debuginfo = Self::get_collapse_debuginfo(sess, attrs, !is_local);
885 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_expand/src/base.rs:885",
"rustc_expand::base", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_expand/src/base.rs"),
::tracing_core::__macro_support::Option::Some(885u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::base"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("name")
}> =
::tracing::__macro_support::FieldName::new("name");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("local_inner_macros")
}> =
::tracing::__macro_support::FieldName::new("local_inner_macros");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("collapse_debuginfo")
}> =
::tracing::__macro_support::FieldName::new("collapse_debuginfo");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("allow_internal_unsafe")
}> =
::tracing::__macro_support::FieldName::new("allow_internal_unsafe");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_inner_macros)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&collapse_debuginfo)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&allow_internal_unsafe)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};tracing::debug!(?name, ?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
886
887 let (builtin_name, helper_attrs) = match {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcBuiltinMacro {
builtin_name, helper_attrs }) => {
break 'done Some((builtin_name, helper_attrs));
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, RustcBuiltinMacro { builtin_name, helper_attrs } => (builtin_name, helper_attrs))
888 {
889 Some((Some(name), helper_attrs)) => {
892 (Some(*name), helper_attrs.iter().copied().collect())
893 }
894 Some((None, _)) => (Some(name), Vec::new()),
895
896 None => (None, helper_attrs),
898 };
899 let diagnostic_opaque = builtin_name.is_some()
900 || (!sess.opts.unstable_opts.macro_backtrace && {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Opaque) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, Opaque));
901
902 let stability = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Stability { stability, ..
}) => {
break 'done Some(*stability);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Stability { stability, .. } => *stability);
903
904 if let Some(sp) = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcBodyStability { span,
.. }) => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, RustcBodyStability{ span, .. } => *span) {
905 sess.dcx().emit_err(diagnostics::MacroBodyStability {
906 span: sp,
907 head_span: sess.source_map().guess_head_span(span),
908 });
909 }
910
911 SyntaxExtension {
912 kind,
913 span,
914 allow_internal_unstable: (!allow_internal_unstable.is_empty())
915 .then(|| allow_internal_unstable.iter().map(|i| i.0).collect::<Vec<_>>().into()),
917 stability,
918 deprecation: {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Deprecated { deprecation,
.. }) => {
break 'done Some(*deprecation);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(
919 attrs,
920 Deprecated { deprecation, .. } => *deprecation
921 ),
922 helper_attrs,
923 edition,
924 builtin_name,
925 allow_internal_unsafe,
926 local_inner_macros,
927 collapse_debuginfo,
928 diagnostic_opaque,
929 }
930 }
931
932 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
934 fn expand(
935 ecx: &mut ExtCtxt<'_>,
936 span: Span,
937 _ts: TokenStream,
938 ) -> Result<TokenStream, ErrorGuaranteed> {
939 Err(ecx.dcx().span_delayed_bug(span, "expanded a dummy bang macro"))
940 }
941 SyntaxExtension::default(SyntaxExtensionKind::Bang(Arc::new(expand)), edition)
942 }
943
944 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
946 fn expander(
947 _: &mut ExtCtxt<'_>,
948 _: Span,
949 _: &ast::MetaItem,
950 _: Annotatable,
951 ) -> Vec<Annotatable> {
952 Vec::new()
953 }
954 SyntaxExtension::default(SyntaxExtensionKind::Derive(Arc::new(expander)), edition)
955 }
956
957 pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
958 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
959 }
960
961 pub fn glob_delegation(
962 trait_def_id: DefId,
963 impl_def_id: LocalDefId,
964 star_span: Span,
965 edition: Edition,
966 ) -> SyntaxExtension {
967 struct GlobDelegationExpanderImpl {
968 trait_def_id: DefId,
969 impl_def_id: LocalDefId,
970 star_span: Span,
971 }
972 impl GlobDelegationExpander for GlobDelegationExpanderImpl {
973 fn expand(
974 &self,
975 ecx: &mut ExtCtxt<'_>,
976 ) -> ExpandResult<Vec<(Ident, Option<Ident>)>, ()> {
977 match ecx.resolver.glob_delegation_suffixes(
978 self.trait_def_id,
979 self.impl_def_id,
980 self.star_span,
981 ) {
982 Ok(suffixes) => ExpandResult::Ready(suffixes),
983 Err(Indeterminate) if ecx.force_mode => ExpandResult::Ready(Vec::new()),
984 Err(Indeterminate) => ExpandResult::Retry(()),
985 }
986 }
987 }
988
989 let expander = GlobDelegationExpanderImpl { trait_def_id, impl_def_id, star_span };
990 SyntaxExtension::default(SyntaxExtensionKind::GlobDelegation(Arc::new(expander)), edition)
991 }
992
993 pub fn expn_data(
994 &self,
995 parent: LocalExpnId,
996 call_site: Span,
997 descr: Symbol,
998 kind: MacroKind,
999 macro_def_id: Option<DefId>,
1000 parent_module: Option<ModId>,
1001 ) -> ExpnData {
1002 ExpnData::new(
1003 ExpnKind::Macro(kind, descr),
1004 parent.to_expn_id(),
1005 call_site,
1006 self.span,
1007 self.allow_internal_unstable.clone(),
1008 self.edition,
1009 macro_def_id,
1010 parent_module,
1011 self.allow_internal_unsafe,
1012 self.local_inner_macros,
1013 self.collapse_debuginfo,
1014 self.diagnostic_opaque,
1015 )
1016 }
1017}
1018
1019pub struct Indeterminate;
1021
1022pub struct DeriveResolution {
1023 pub path: ast::Path,
1024 pub item: Annotatable,
1025 pub exts: Option<Arc<SyntaxExtension>>,
1029 pub is_const: bool,
1030}
1031
1032pub trait ResolverExpand {
1033 fn next_node_id(&mut self) -> NodeId;
1034 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
1035
1036 fn resolve_dollar_crates(&self);
1037 fn visit_ast_fragment_with_placeholders(
1038 &mut self,
1039 expn_id: LocalExpnId,
1040 fragment: &AstFragment,
1041 );
1042 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
1043
1044 fn expansion_for_ast_pass(
1045 &mut self,
1046 call_site: Span,
1047 pass: AstPass,
1048 features: &[Symbol],
1049 parent_module_id: Option<NodeId>,
1050 ) -> LocalExpnId;
1051
1052 fn resolve_imports(&mut self);
1053
1054 fn resolve_macro_invocation(
1055 &mut self,
1056 invoc: &Invocation,
1057 eager_expansion_root: LocalExpnId,
1058 force: bool,
1059 ) -> Result<Arc<SyntaxExtension>, Indeterminate>;
1060
1061 fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
1062
1063 fn check_unused_macros(&mut self);
1064
1065 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
1068 fn has_derive_ord(&self, expn_id: LocalExpnId) -> bool;
1070 fn resolve_derives(
1072 &mut self,
1073 expn_id: LocalExpnId,
1074 force: bool,
1075 derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
1076 ) -> Result<(), Indeterminate>;
1077 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>>;
1080 fn cfg_accessible(
1082 &mut self,
1083 expn_id: LocalExpnId,
1084 path: &ast::Path,
1085 ) -> Result<bool, Indeterminate>;
1086 fn macro_accessible(
1087 &mut self,
1088 expn_id: LocalExpnId,
1089 path: &ast::Path,
1090 ) -> Result<bool, Indeterminate>;
1091
1092 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
1095
1096 fn declare_proc_macro(&mut self, id: NodeId);
1103
1104 fn append_stripped_cfg_item(
1105 &mut self,
1106 parent_node: NodeId,
1107 ident: Ident,
1108 cfg: CfgEntry,
1109 cfg_span: Span,
1110 );
1111
1112 fn registered_attr_tools(&self) -> &RegisteredTools;
1114
1115 fn registered_lint_tools(&self) -> &RegisteredTools;
1117
1118 fn register_glob_delegation(&mut self, invoc_id: LocalExpnId);
1120
1121 fn glob_delegation_suffixes(
1123 &self,
1124 trait_def_id: DefId,
1125 impl_def_id: LocalDefId,
1126 star_span: Span,
1127 ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate>;
1128
1129 fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol);
1132
1133 fn mark_scope_with_compile_error(&mut self, parent_node: NodeId);
1136}
1137
1138pub trait LintStoreExpand {
1139 fn pre_expansion_lint(
1140 &self,
1141 sess: &Session,
1142 features: &Features,
1143 registered_lint_tools: &RegisteredTools,
1144 node_id: NodeId,
1145 attrs: &[Attribute],
1146 items: &[Box<Item>],
1147 name: Symbol,
1148 );
1149}
1150
1151type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
1152
1153#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleData {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "ModuleData",
"mod_path", &self.mod_path, "file_path_stack",
&self.file_path_stack, "dir_path", &&self.dir_path)
}
}Debug, #[automatically_derived]
impl ::core::default::Default for ModuleData {
#[inline]
fn default() -> ModuleData {
ModuleData {
mod_path: ::core::default::Default::default(),
file_path_stack: ::core::default::Default::default(),
dir_path: ::core::default::Default::default(),
}
}
}Default)]
1154pub struct ModuleData {
1155 pub mod_path: Vec<Ident>,
1157 pub file_path_stack: Vec<PathBuf>,
1160 pub dir_path: PathBuf,
1163}
1164
1165impl ModuleData {
1166 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
1167 ModuleData {
1168 mod_path: self.mod_path.clone(),
1169 file_path_stack: self.file_path_stack.clone(),
1170 dir_path,
1171 }
1172 }
1173}
1174
1175#[derive(#[automatically_derived]
impl ::core::clone::Clone for ExpansionData {
#[inline]
fn clone(&self) -> ExpansionData {
ExpansionData {
id: ::core::clone::Clone::clone(&self.id),
depth: ::core::clone::Clone::clone(&self.depth),
module: ::core::clone::Clone::clone(&self.module),
dir_ownership: ::core::clone::Clone::clone(&self.dir_ownership),
lint_node_id: ::core::clone::Clone::clone(&self.lint_node_id),
is_trailing_mac: ::core::clone::Clone::clone(&self.is_trailing_mac),
}
}
}Clone)]
1176pub struct ExpansionData {
1177 pub id: LocalExpnId,
1178 pub depth: usize,
1179 pub module: Rc<ModuleData>,
1180 pub dir_ownership: DirOwnership,
1181 pub lint_node_id: NodeId,
1183 pub is_trailing_mac: bool,
1184}
1185
1186pub struct ExtCtxt<'a> {
1190 pub sess: &'a Session,
1191 pub ecfg: expand::ExpansionConfig<'a>,
1192 pub num_standard_library_imports: usize,
1193 pub reduced_recursion_limit: Option<(Limit, ErrorGuaranteed)>,
1194 pub root_path: PathBuf,
1195 pub resolver: &'a mut dyn ResolverExpand,
1196 pub current_expansion: ExpansionData,
1197 pub force_mode: bool,
1200 pub expansions: FxIndexMap<Span, Vec<String>>,
1201 pub(super) lint_store: LintStoreExpandDyn<'a>,
1203 pub buffered_early_lint: Vec<BufferedEarlyLint>,
1205 pub(super) expanded_inert_attrs: MarkedAttrs,
1209 pub macro_stats: FxHashMap<(Symbol, MacroKind), MacroStat>,
1211 pub nb_macro_errors: usize,
1212}
1213
1214impl<'a> ExtCtxt<'a> {
1215 pub fn new(
1216 sess: &'a Session,
1217 ecfg: expand::ExpansionConfig<'a>,
1218 resolver: &'a mut dyn ResolverExpand,
1219 lint_store: LintStoreExpandDyn<'a>,
1220 ) -> ExtCtxt<'a> {
1221 ExtCtxt {
1222 sess,
1223 ecfg,
1224 num_standard_library_imports: 0,
1225 reduced_recursion_limit: None,
1226 resolver,
1227 lint_store,
1228 root_path: PathBuf::new(),
1229 current_expansion: ExpansionData {
1230 id: LocalExpnId::ROOT,
1231 depth: 0,
1232 module: Default::default(),
1233 dir_ownership: DirOwnership::Owned { relative: None },
1234 lint_node_id: ast::CRATE_NODE_ID,
1235 is_trailing_mac: false,
1236 },
1237 force_mode: false,
1238 expansions: FxIndexMap::default(),
1239 expanded_inert_attrs: MarkedAttrs::new(),
1240 buffered_early_lint: ::alloc::vec::Vec::new()vec![],
1241 macro_stats: Default::default(),
1242 nb_macro_errors: 0,
1243 }
1244 }
1245
1246 pub fn dcx(&self) -> DiagCtxtHandle<'a> {
1247 self.sess.dcx()
1248 }
1249
1250 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1252 expand::MacroExpander::new(self, false)
1253 }
1254
1255 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1258 expand::MacroExpander::new(self, true)
1259 }
1260 pub fn new_parser_from_tts(&self, stream: TokenStream) -> Parser<'a> {
1261 Parser::new(&self.sess.psess, stream, MACRO_ARGUMENTS)
1262 }
1263 pub fn source_map(&self) -> &'a SourceMap {
1264 self.sess.psess.source_map()
1265 }
1266 pub fn psess(&self) -> &'a ParseSess {
1267 &self.sess.psess
1268 }
1269 pub fn call_site(&self) -> Span {
1270 self.current_expansion.id.expn_data().call_site
1271 }
1272
1273 pub(crate) fn expansion_descr(&self) -> String {
1275 let expn_data = self.current_expansion.id.expn_data();
1276 expn_data.kind.descr()
1277 }
1278
1279 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1282 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1283 }
1284
1285 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1288 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1289 }
1290
1291 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1294 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1295 }
1296
1297 pub fn expansion_cause(&self) -> Option<Span> {
1301 self.current_expansion.id.expansion_cause()
1302 }
1303
1304 pub fn macro_error_and_trace_macros_diag(&mut self) {
1306 self.nb_macro_errors += 1;
1307 self.trace_macros_diag();
1308 }
1309
1310 pub fn trace_macros_diag(&mut self) {
1311 for (span, notes) in self.expansions.iter() {
1312 let mut db = self.dcx().create_note(diagnostics::TraceMacro { span: *span });
1313 for note in notes {
1314 db.note(note.clone());
1315 }
1316 db.emit();
1317 }
1318 self.expansions.clear();
1320 }
1321 pub fn trace_macros(&self) -> bool {
1322 self.ecfg.trace_mac
1323 }
1324 pub fn set_trace_macros(&mut self, x: bool) {
1325 self.ecfg.trace_mac = x
1326 }
1327 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1328 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1329 iter::once(Ident::new(kw::DollarCrate, def_site))
1330 .chain(components.iter().map(|&s| Ident::new(s, def_site)))
1331 .collect()
1332 }
1333 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1334 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1335 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1336 }
1337
1338 pub fn check_unused_macros(&mut self) {
1339 self.resolver.check_unused_macros();
1340 }
1341}