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