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