-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
expand.rs
1678 lines (1513 loc) · 68.9 KB
/
expand.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use ast::{self, Block, Ident, LitKind, NodeId, PatKind, Path};
use ast::{MacStmtStyle, StmtKind, ItemKind};
use attr::{self, HasAttrs};
use source_map::{ExpnInfo, MacroBang, MacroAttribute, dummy_spanned, respan};
use config::StripUnconfigured;
use errors::{Applicability, FatalError};
use ext::base::*;
use ext::derive::{add_derived_markers, collect_derives};
use ext::hygiene::{self, Mark, SyntaxContext};
use ext::placeholders::{placeholder, PlaceholderExpander};
use feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
use fold;
use fold::*;
use parse::{DirectoryOwnership, PResult, ParseSess};
use parse::token::{self, Token};
use parse::parser::Parser;
use ptr::P;
use smallvec::SmallVec;
use symbol::Symbol;
use symbol::keywords;
use syntax_pos::{Span, DUMMY_SP, FileName};
use syntax_pos::hygiene::ExpnFormat;
use tokenstream::{TokenStream, TokenTree};
use visit::{self, Visitor};
use rustc_data_structures::fx::FxHashMap;
use std::fs;
use std::io::ErrorKind;
use std::{iter, mem};
use std::rc::Rc;
use std::path::PathBuf;
macro_rules! ast_fragments {
(
$($Kind:ident($AstTy:ty) {
$kind_name:expr;
// FIXME: HACK: this should be `$(one ...)?` and `$(many ...)?` but `?` macro
// repetition was removed from 2015 edition in #51587 because of ambiguities.
$(one fn $fold_ast:ident; fn $visit_ast:ident;)*
$(many fn $fold_ast_elt:ident; fn $visit_ast_elt:ident;)*
fn $make_ast:ident;
})*
) => {
/// A fragment of AST that can be produced by a single macro expansion.
/// Can also serve as an input and intermediate result for macro expansion operations.
pub enum AstFragment {
OptExpr(Option<P<ast::Expr>>),
$($Kind($AstTy),)*
}
/// "Discriminant" of an AST fragment.
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum AstFragmentKind {
OptExpr,
$($Kind,)*
}
impl AstFragmentKind {
pub fn name(self) -> &'static str {
match self {
AstFragmentKind::OptExpr => "expression",
$(AstFragmentKind::$Kind => $kind_name,)*
}
}
fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
match self {
AstFragmentKind::OptExpr =>
result.make_expr().map(Some).map(AstFragment::OptExpr),
$(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
}
}
}
impl AstFragment {
pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
match self {
AstFragment::OptExpr(expr) => expr,
_ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
}
}
$(pub fn $make_ast(self) -> $AstTy {
match self {
AstFragment::$Kind(ast) => ast,
_ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
}
})*
pub fn fold_with<F: Folder>(self, folder: &mut F) -> Self {
match self {
AstFragment::OptExpr(expr) =>
AstFragment::OptExpr(expr.and_then(|expr| folder.fold_opt_expr(expr))),
$($(AstFragment::$Kind(ast) =>
AstFragment::$Kind(folder.$fold_ast(ast)),)*)*
$($(AstFragment::$Kind(ast) =>
AstFragment::$Kind(ast.into_iter()
.flat_map(|ast| folder.$fold_ast_elt(ast))
.collect()),)*)*
}
}
pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
match *self {
AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
AstFragment::OptExpr(None) => {}
$($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)*)*
$($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
visitor.$visit_ast_elt(ast_elt);
})*)*
}
}
}
impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
self.expand_fragment(AstFragment::OptExpr(Some(expr))).make_opt_expr()
}
$($(fn $fold_ast(&mut self, ast: $AstTy) -> $AstTy {
self.expand_fragment(AstFragment::$Kind(ast)).$make_ast()
})*)*
$($(fn $fold_ast_elt(&mut self, ast_elt: <$AstTy as IntoIterator>::Item) -> $AstTy {
self.expand_fragment(AstFragment::$Kind(smallvec![ast_elt])).$make_ast()
})*)*
}
impl<'a> MacResult for ::ext::tt::macro_rules::ParserAnyMacro<'a> {
$(fn $make_ast(self: Box<::ext::tt::macro_rules::ParserAnyMacro<'a>>)
-> Option<$AstTy> {
Some(self.make(AstFragmentKind::$Kind).$make_ast())
})*
}
}
}
ast_fragments! {
Expr(P<ast::Expr>) { "expression"; one fn fold_expr; fn visit_expr; fn make_expr; }
Pat(P<ast::Pat>) { "pattern"; one fn fold_pat; fn visit_pat; fn make_pat; }
Ty(P<ast::Ty>) { "type"; one fn fold_ty; fn visit_ty; fn make_ty; }
Stmts(SmallVec<[ast::Stmt; 1]>) {
"statement"; many fn fold_stmt; fn visit_stmt; fn make_stmts;
}
Items(SmallVec<[P<ast::Item>; 1]>) {
"item"; many fn fold_item; fn visit_item; fn make_items;
}
TraitItems(SmallVec<[ast::TraitItem; 1]>) {
"trait item"; many fn fold_trait_item; fn visit_trait_item; fn make_trait_items;
}
ImplItems(SmallVec<[ast::ImplItem; 1]>) {
"impl item"; many fn fold_impl_item; fn visit_impl_item; fn make_impl_items;
}
ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
"foreign item"; many fn fold_foreign_item; fn visit_foreign_item; fn make_foreign_items;
}
}
impl AstFragmentKind {
fn dummy(self, span: Span) -> Option<AstFragment> {
self.make_from(DummyResult::any(span))
}
fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
-> AstFragment {
let mut items = items.into_iter();
match self {
AstFragmentKind::Items =>
AstFragment::Items(items.map(Annotatable::expect_item).collect()),
AstFragmentKind::ImplItems =>
AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
AstFragmentKind::TraitItems =>
AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
AstFragmentKind::ForeignItems =>
AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
AstFragmentKind::Stmts =>
AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
AstFragmentKind::Expr => AstFragment::Expr(
items.next().expect("expected exactly one expression").expect_expr()
),
AstFragmentKind::OptExpr =>
AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
AstFragmentKind::Pat | AstFragmentKind::Ty =>
panic!("patterns and types aren't annotatable"),
}
}
}
fn macro_bang_format(path: &ast::Path) -> ExpnFormat {
// We don't want to format a path using pretty-printing,
// `format!("{}", path)`, because that tries to insert
// line-breaks and is slow.
let mut path_str = String::with_capacity(64);
for (i, segment) in path.segments.iter().enumerate() {
if i != 0 {
path_str.push_str("::");
}
if segment.ident.name != keywords::PathRoot.name() {
path_str.push_str(&segment.ident.as_str())
}
}
MacroBang(Symbol::intern(&path_str))
}
pub struct Invocation {
pub kind: InvocationKind,
fragment_kind: AstFragmentKind,
pub expansion_data: ExpansionData,
}
pub enum InvocationKind {
Bang {
mac: ast::Mac,
ident: Option<Ident>,
span: Span,
},
Attr {
attr: Option<ast::Attribute>,
traits: Vec<Path>,
item: Annotatable,
// We temporarily report errors for attribute macros placed after derives
after_derive: bool,
},
Derive {
path: Path,
item: Annotatable,
},
}
impl Invocation {
pub fn span(&self) -> Span {
match self.kind {
InvocationKind::Bang { span, .. } => span,
InvocationKind::Attr { attr: Some(ref attr), .. } => attr.span,
InvocationKind::Attr { attr: None, .. } => DUMMY_SP,
InvocationKind::Derive { ref path, .. } => path.span,
}
}
}
pub struct MacroExpander<'a, 'b:'a> {
pub cx: &'a mut ExtCtxt<'b>,
monotonic: bool, // cf. `cx.monotonic_expander()`
}
impl<'a, 'b> MacroExpander<'a, 'b> {
pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
MacroExpander { cx: cx, monotonic: monotonic }
}
pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
let mut module = ModuleData {
mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
FileName::Real(path) => path,
other => PathBuf::from(other.to_string()),
},
};
module.directory.pop();
self.cx.root_path = module.directory.clone();
self.cx.current_expansion.module = Rc::new(module);
self.cx.current_expansion.crate_span = Some(krate.span);
let orig_mod_span = krate.module.inner;
let krate_item = AstFragment::Items(smallvec![P(ast::Item {
attrs: krate.attrs,
span: krate.span,
node: ast::ItemKind::Mod(krate.module),
ident: keywords::Invalid.ident(),
id: ast::DUMMY_NODE_ID,
vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
tokens: None,
})]);
match self.expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
krate.attrs = attrs;
krate.module = module;
},
None => {
// Resolution failed so we return an empty expansion
krate.attrs = vec![];
krate.module = ast::Mod {
inner: orig_mod_span,
items: vec![],
inline: true,
};
},
_ => unreachable!(),
};
self.cx.trace_macros_diag();
krate
}
// Fully expand all macro invocations in this AST fragment.
fn expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
let orig_expansion_data = self.cx.current_expansion.clone();
self.cx.current_expansion.depth = 0;
// Collect all macro invocations and replace them with placeholders.
let (fragment_with_placeholders, mut invocations)
= self.collect_invocations(input_fragment, &[]);
// Optimization: if we resolve all imports now,
// we'll be able to immediately resolve most of imported macros.
self.resolve_imports();
// Resolve paths in all invocations and produce output expanded fragments for them, but
// do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
// The output fragments also go through expansion recursively until no invocations are left.
// Unresolved macros produce dummy outputs as a recovery measure.
invocations.reverse();
let mut expanded_fragments = Vec::new();
let mut derives: FxHashMap<Mark, Vec<_>> = FxHashMap::default();
let mut undetermined_invocations = Vec::new();
let (mut progress, mut force) = (false, !self.monotonic);
loop {
let invoc = if let Some(invoc) = invocations.pop() {
invoc
} else {
self.resolve_imports();
if undetermined_invocations.is_empty() { break }
invocations = mem::replace(&mut undetermined_invocations, Vec::new());
force = !mem::replace(&mut progress, false);
continue
};
let scope =
if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark };
let ext = match self.cx.resolver.resolve_macro_invocation(&invoc, scope, force) {
Ok(ext) => Some(ext),
Err(Determinacy::Determined) => None,
Err(Determinacy::Undetermined) => {
undetermined_invocations.push(invoc);
continue
}
};
progress = true;
let ExpansionData { depth, mark, .. } = invoc.expansion_data;
self.cx.current_expansion = invoc.expansion_data.clone();
self.cx.current_expansion.mark = scope;
// FIXME(jseyfried): Refactor out the following logic
let (expanded_fragment, new_invocations) = if let Some(ext) = ext {
if let Some(ext) = ext {
let (invoc_fragment_kind, invoc_span) = (invoc.fragment_kind, invoc.span());
let fragment = self.expand_invoc(invoc, &*ext).unwrap_or_else(|| {
invoc_fragment_kind.dummy(invoc_span).unwrap()
});
self.collect_invocations(fragment, &[])
} else if let InvocationKind::Attr { attr: None, traits, item, .. } = invoc.kind {
if !item.derive_allowed() {
let attr = attr::find_by_name(item.attrs(), "derive")
.expect("`derive` attribute should exist");
let span = attr.span;
let mut err = self.cx.mut_span_err(span,
"`derive` may only be applied to \
structs, enums and unions");
if let ast::AttrStyle::Inner = attr.style {
let trait_list = traits.iter()
.map(|t| t.to_string()).collect::<Vec<_>>();
let suggestion = format!("#[derive({})]", trait_list.join(", "));
err.span_suggestion_with_applicability(
span, "try an outer attribute", suggestion,
// We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
Applicability::MaybeIncorrect
);
}
err.emit();
}
let item = self.fully_configure(item)
.map_attrs(|mut attrs| { attrs.retain(|a| a.path != "derive"); attrs });
let item_with_markers =
add_derived_markers(&mut self.cx, item.span(), &traits, item.clone());
let derives = derives.entry(invoc.expansion_data.mark).or_default();
derives.reserve(traits.len());
invocations.reserve(traits.len());
for path in &traits {
let mark = Mark::fresh(self.cx.current_expansion.mark);
derives.push(mark);
let item = match self.cx.resolver.resolve_macro_path(
path, MacroKind::Derive, Mark::root(), Vec::new(), false) {
Ok(ext) => match *ext {
BuiltinDerive(..) => item_with_markers.clone(),
_ => item.clone(),
},
_ => item.clone(),
};
invocations.push(Invocation {
kind: InvocationKind::Derive { path: path.clone(), item: item },
fragment_kind: invoc.fragment_kind,
expansion_data: ExpansionData {
mark,
..invoc.expansion_data.clone()
},
});
}
let fragment = invoc.fragment_kind
.expect_from_annotatables(::std::iter::once(item_with_markers));
self.collect_invocations(fragment, derives)
} else {
unreachable!()
}
} else {
self.collect_invocations(invoc.fragment_kind.dummy(invoc.span()).unwrap(), &[])
};
if expanded_fragments.len() < depth {
expanded_fragments.push(Vec::new());
}
expanded_fragments[depth - 1].push((mark, expanded_fragment));
if !self.cx.ecfg.single_step {
invocations.extend(new_invocations.into_iter().rev());
}
}
self.cx.current_expansion = orig_expansion_data;
// Finally incorporate all the expanded macros into the input AST fragment.
let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
while let Some(expanded_fragments) = expanded_fragments.pop() {
for (mark, expanded_fragment) in expanded_fragments.into_iter().rev() {
let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
placeholder_expander.add(NodeId::placeholder_from_mark(mark),
expanded_fragment, derives);
}
}
fragment_with_placeholders.fold_with(&mut placeholder_expander)
}
fn resolve_imports(&mut self) {
if self.monotonic {
self.cx.resolver.resolve_imports();
}
}
/// Collect all macro invocations reachable at this time in this AST fragment, and replace
/// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
/// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
/// prepares data for resolving paths of macro invocations.
fn collect_invocations(&mut self, fragment: AstFragment, derives: &[Mark])
-> (AstFragment, Vec<Invocation>) {
let (fragment_with_placeholders, invocations) = {
let mut collector = InvocationCollector {
cfg: StripUnconfigured {
sess: self.cx.parse_sess,
features: self.cx.ecfg.features,
},
cx: self.cx,
invocations: Vec::new(),
monotonic: self.monotonic,
};
(fragment.fold_with(&mut collector), collector.invocations)
};
if self.monotonic {
self.cx.resolver.visit_ast_fragment_with_placeholders(
self.cx.current_expansion.mark, &fragment_with_placeholders, derives
);
}
(fragment_with_placeholders, invocations)
}
fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
let mut cfg = StripUnconfigured {
sess: self.cx.parse_sess,
features: self.cx.ecfg.features,
};
// Since the item itself has already been configured by the InvocationCollector,
// we know that fold result vector will contain exactly one element
match item {
Annotatable::Item(item) => {
Annotatable::Item(cfg.fold_item(item).pop().unwrap())
}
Annotatable::TraitItem(item) => {
Annotatable::TraitItem(item.map(|item| cfg.fold_trait_item(item).pop().unwrap()))
}
Annotatable::ImplItem(item) => {
Annotatable::ImplItem(item.map(|item| cfg.fold_impl_item(item).pop().unwrap()))
}
Annotatable::ForeignItem(item) => {
Annotatable::ForeignItem(
item.map(|item| cfg.fold_foreign_item(item).pop().unwrap())
)
}
Annotatable::Stmt(stmt) => {
Annotatable::Stmt(stmt.map(|stmt| cfg.fold_stmt(stmt).pop().unwrap()))
}
Annotatable::Expr(expr) => {
Annotatable::Expr(cfg.fold_expr(expr))
}
}
}
fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtension) -> Option<AstFragment> {
if invoc.fragment_kind == AstFragmentKind::ForeignItems &&
!self.cx.ecfg.macros_in_extern_enabled() {
if let SyntaxExtension::NonMacroAttr { .. } = *ext {} else {
emit_feature_err(&self.cx.parse_sess, "macros_in_extern",
invoc.span(), GateIssue::Language,
"macro invocations in `extern {}` blocks are experimental");
}
}
let result = match invoc.kind {
InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext)?,
InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext)?,
InvocationKind::Derive { .. } => self.expand_derive_invoc(invoc, ext)?,
};
if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
let info = self.cx.current_expansion.mark.expn_info().unwrap();
let suggested_limit = self.cx.ecfg.recursion_limit * 2;
let mut err = self.cx.struct_span_err(info.call_site,
&format!("recursion limit reached while expanding the macro `{}`",
info.format.name()));
err.help(&format!(
"consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
suggested_limit));
err.emit();
self.cx.trace_macros_diag();
FatalError.raise();
}
Some(result)
}
fn expand_attr_invoc(&mut self,
invoc: Invocation,
ext: &SyntaxExtension)
-> Option<AstFragment> {
let (attr, item) = match invoc.kind {
InvocationKind::Attr { attr, item, .. } => (attr?, item),
_ => unreachable!(),
};
if let NonMacroAttr { mark_used: false } = *ext {} else {
// Macro attrs are always used when expanded,
// non-macro attrs are considered used when the field says so.
attr::mark_used(&attr);
}
invoc.expansion_data.mark.set_expn_info(ExpnInfo {
call_site: attr.span,
def_site: None,
format: MacroAttribute(Symbol::intern(&attr.path.to_string())),
allow_internal_unstable: false,
allow_internal_unsafe: false,
local_inner_macros: false,
edition: ext.edition(),
});
match *ext {
NonMacroAttr { .. } => {
attr::mark_known(&attr);
let item = item.map_attrs(|mut attrs| { attrs.push(attr); attrs });
Some(invoc.fragment_kind.expect_from_annotatables(iter::once(item)))
}
MultiModifier(ref mac) => {
let meta = attr.parse_meta(self.cx.parse_sess)
.map_err(|mut e| { e.emit(); }).ok()?;
let item = mac.expand(self.cx, attr.span, &meta, item);
Some(invoc.fragment_kind.expect_from_annotatables(item))
}
MultiDecorator(ref mac) => {
let mut items = Vec::new();
let meta = attr.parse_meta(self.cx.parse_sess)
.expect("derive meta should already have been parsed");
mac.expand(self.cx, attr.span, &meta, &item, &mut |item| items.push(item));
items.push(item);
Some(invoc.fragment_kind.expect_from_annotatables(items))
}
AttrProcMacro(ref mac, ..) => {
// Resolve `$crate`s in case we have to go though stringification.
self.cx.resolver.resolve_dollar_crates(&item);
self.gate_proc_macro_attr_item(attr.span, &item);
let item_tok = TokenTree::Token(DUMMY_SP, Token::interpolated(match item {
Annotatable::Item(item) => token::NtItem(item),
Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
Annotatable::Expr(expr) => token::NtExpr(expr),
})).into();
let input = self.extract_proc_macro_attr_input(attr.tokens, attr.span);
let tok_result = mac.expand(self.cx, attr.span, input, item_tok);
let res = self.parse_ast_fragment(tok_result, invoc.fragment_kind,
&attr.path, attr.span);
self.gate_proc_macro_expansion(attr.span, &res);
res
}
ProcMacroDerive(..) | BuiltinDerive(..) => {
self.cx.span_err(attr.span, &format!("`{}` is a derive mode", attr.path));
self.cx.trace_macros_diag();
invoc.fragment_kind.dummy(attr.span)
}
_ => {
let msg = &format!("macro `{}` may not be used in attributes", attr.path);
self.cx.span_err(attr.span, msg);
self.cx.trace_macros_diag();
invoc.fragment_kind.dummy(attr.span)
}
}
}
fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
let mut trees = tokens.trees();
match trees.next() {
Some(TokenTree::Delimited(_, _, tts)) => {
if trees.next().is_none() {
return tts.into()
}
}
Some(TokenTree::Token(..)) => {}
None => return TokenStream::empty(),
}
self.cx.span_err(span, "custom attribute invocations must be \
of the form #[foo] or #[foo(..)], the macro name must only be \
followed by a delimiter token");
TokenStream::empty()
}
fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
let (kind, gate) = match *item {
Annotatable::Item(ref item) => {
match item.node {
ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
ItemKind::Mod(_) => ("modules", "proc_macro_hygiene"),
_ => return,
}
}
Annotatable::TraitItem(_) => return,
Annotatable::ImplItem(_) => return,
Annotatable::ForeignItem(_) => return,
Annotatable::Stmt(_) |
Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
Annotatable::Stmt(_) => ("statements", "proc_macro_hygiene"),
Annotatable::Expr(_) => ("expressions", "proc_macro_hygiene"),
};
emit_feature_err(
self.cx.parse_sess,
gate,
span,
GateIssue::Language,
&format!("custom attributes cannot be applied to {}", kind),
);
}
fn gate_proc_macro_expansion(&self, span: Span, fragment: &Option<AstFragment>) {
if self.cx.ecfg.proc_macro_hygiene() {
return
}
let fragment = match fragment {
Some(fragment) => fragment,
None => return,
};
fragment.visit_with(&mut DisallowMacros {
span,
parse_sess: self.cx.parse_sess,
});
struct DisallowMacros<'a> {
span: Span,
parse_sess: &'a ParseSess,
}
impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
fn visit_item(&mut self, i: &'ast ast::Item) {
if let ast::ItemKind::MacroDef(_) = i.node {
emit_feature_err(
self.parse_sess,
"proc_macro_hygiene",
self.span,
GateIssue::Language,
"procedural macros cannot expand to macro definitions",
);
}
visit::walk_item(self, i);
}
fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
// ...
}
}
}
/// Expand a macro invocation. Returns the resulting expanded AST fragment.
fn expand_bang_invoc(&mut self,
invoc: Invocation,
ext: &SyntaxExtension)
-> Option<AstFragment> {
let (mark, kind) = (invoc.expansion_data.mark, invoc.fragment_kind);
let (mac, ident, span) = match invoc.kind {
InvocationKind::Bang { mac, ident, span } => (mac, ident, span),
_ => unreachable!(),
};
let path = &mac.node.path;
let ident = ident.unwrap_or_else(|| keywords::Invalid.ident());
let validate_and_set_expn_info = |this: &mut Self, // arg instead of capture
def_site_span: Option<Span>,
allow_internal_unstable,
allow_internal_unsafe,
local_inner_macros,
// can't infer this type
unstable_feature: Option<(Symbol, u32)>,
edition| {
// feature-gate the macro invocation
if let Some((feature, issue)) = unstable_feature {
let crate_span = this.cx.current_expansion.crate_span.unwrap();
// don't stability-check macros in the same crate
// (the only time this is null is for syntax extensions registered as macros)
if def_site_span.map_or(false, |def_span| !crate_span.contains(def_span))
&& !span.allows_unstable() && this.cx.ecfg.features.map_or(true, |feats| {
// macro features will count as lib features
!feats.declared_lib_features.iter().any(|&(feat, _)| feat == feature)
}) {
let explain = format!("macro {}! is unstable", path);
emit_feature_err(this.cx.parse_sess, &*feature.as_str(), span,
GateIssue::Library(Some(issue)), &explain);
this.cx.trace_macros_diag();
}
}
if ident.name != keywords::Invalid.name() {
let msg = format!("macro {}! expects no ident argument, given '{}'", path, ident);
this.cx.span_err(path.span, &msg);
this.cx.trace_macros_diag();
return Err(kind.dummy(span));
}
mark.set_expn_info(ExpnInfo {
call_site: span,
def_site: def_site_span,
format: macro_bang_format(path),
allow_internal_unstable,
allow_internal_unsafe,
local_inner_macros,
edition,
});
Ok(())
};
let opt_expanded = match *ext {
DeclMacro { ref expander, def_info, edition, .. } => {
if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s),
false, false, false, None,
edition) {
dummy_span
} else {
kind.make_from(expander.expand(self.cx, span, mac.node.stream(), None))
}
}
NormalTT {
ref expander,
def_info,
allow_internal_unstable,
allow_internal_unsafe,
local_inner_macros,
unstable_feature,
edition,
} => {
if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s),
allow_internal_unstable,
allow_internal_unsafe,
local_inner_macros,
unstable_feature,
edition) {
dummy_span
} else {
kind.make_from(expander.expand(
self.cx,
span,
mac.node.stream(),
def_info.map(|(_, s)| s),
))
}
}
IdentTT(ref expander, tt_span, allow_internal_unstable) => {
if ident.name == keywords::Invalid.name() {
self.cx.span_err(path.span,
&format!("macro {}! expects an ident argument", path));
self.cx.trace_macros_diag();
kind.dummy(span)
} else {
invoc.expansion_data.mark.set_expn_info(ExpnInfo {
call_site: span,
def_site: tt_span,
format: macro_bang_format(path),
allow_internal_unstable,
allow_internal_unsafe: false,
local_inner_macros: false,
edition: hygiene::default_edition(),
});
let input: Vec<_> = mac.node.stream().into_trees().collect();
kind.make_from(expander.expand(self.cx, span, ident, input))
}
}
MultiDecorator(..) | MultiModifier(..) |
AttrProcMacro(..) | SyntaxExtension::NonMacroAttr { .. } => {
self.cx.span_err(path.span,
&format!("`{}` can only be used in attributes", path));
self.cx.trace_macros_diag();
kind.dummy(span)
}
ProcMacroDerive(..) | BuiltinDerive(..) => {
self.cx.span_err(path.span, &format!("`{}` is a derive mode", path));
self.cx.trace_macros_diag();
kind.dummy(span)
}
SyntaxExtension::ProcMacro { ref expander, allow_internal_unstable, edition } => {
if ident.name != keywords::Invalid.name() {
let msg =
format!("macro {}! expects no ident argument, given '{}'", path, ident);
self.cx.span_err(path.span, &msg);
self.cx.trace_macros_diag();
kind.dummy(span)
} else {
self.gate_proc_macro_expansion_kind(span, kind);
invoc.expansion_data.mark.set_expn_info(ExpnInfo {
call_site: span,
// FIXME procedural macros do not have proper span info
// yet, when they do, we should use it here.
def_site: None,
format: macro_bang_format(path),
// FIXME probably want to follow macro_rules macros here.
allow_internal_unstable,
allow_internal_unsafe: false,
local_inner_macros: false,
edition,
});
let tok_result = expander.expand(self.cx, span, mac.node.stream());
let result = self.parse_ast_fragment(tok_result, kind, path, span);
self.gate_proc_macro_expansion(span, &result);
result
}
}
};
if opt_expanded.is_some() {
opt_expanded
} else {
let msg = format!("non-{kind} macro in {kind} position: {name}",
name = path.segments[0].ident.name, kind = kind.name());
self.cx.span_err(path.span, &msg);
self.cx.trace_macros_diag();
kind.dummy(span)
}
}
fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
let kind = match kind {
AstFragmentKind::Expr => "expressions",
AstFragmentKind::OptExpr => "expressions",
AstFragmentKind::Pat => "patterns",
AstFragmentKind::Ty => "types",
AstFragmentKind::Stmts => "statements",
AstFragmentKind::Items => return,
AstFragmentKind::TraitItems => return,
AstFragmentKind::ImplItems => return,
AstFragmentKind::ForeignItems => return,
};
if self.cx.ecfg.proc_macro_hygiene() {
return
}
emit_feature_err(
self.cx.parse_sess,
"proc_macro_hygiene",
span,
GateIssue::Language,
&format!("procedural macros cannot be expanded to {}", kind),
);
}
/// Expand a derive invocation. Returns the resulting expanded AST fragment.
fn expand_derive_invoc(&mut self,
invoc: Invocation,
ext: &SyntaxExtension)
-> Option<AstFragment> {
let (path, item) = match invoc.kind {
InvocationKind::Derive { path, item } => (path, item),
_ => unreachable!(),
};
if !item.derive_allowed() {
return None;
}
let pretty_name = Symbol::intern(&format!("derive({})", path));
let span = path.span;
let attr = ast::Attribute {
path, span,
tokens: TokenStream::empty(),
// irrelevant:
id: ast::AttrId(0), style: ast::AttrStyle::Outer, is_sugared_doc: false,
};
let mut expn_info = ExpnInfo {
call_site: span,
def_site: None,
format: MacroAttribute(pretty_name),
allow_internal_unstable: false,
allow_internal_unsafe: false,
local_inner_macros: false,
edition: ext.edition(),
};
match *ext {
ProcMacroDerive(ref ext, ..) => {
// Resolve `$crate`s in case we have to go though stringification.
self.cx.resolver.resolve_dollar_crates(&item);
invoc.expansion_data.mark.set_expn_info(expn_info);
let span = span.with_ctxt(self.cx.backtrace());
let dummy = ast::MetaItem { // FIXME(jseyfried) avoid this
ident: Path::from_ident(keywords::Invalid.ident()),
span: DUMMY_SP,
node: ast::MetaItemKind::Word,
};
let items = ext.expand(self.cx, span, &dummy, item);
Some(invoc.fragment_kind.expect_from_annotatables(items))
}
BuiltinDerive(func) => {
expn_info.allow_internal_unstable = true;
invoc.expansion_data.mark.set_expn_info(expn_info);
let span = span.with_ctxt(self.cx.backtrace());
let mut items = Vec::new();
func(self.cx, span, &attr.meta()?, &item, &mut |a| items.push(a));
Some(invoc.fragment_kind.expect_from_annotatables(items))
}
_ => {
let msg = &format!("macro `{}` may not be used for derive attributes", attr.path);
self.cx.span_err(span, msg);
self.cx.trace_macros_diag();
invoc.fragment_kind.dummy(span)
}
}
}
fn parse_ast_fragment(&mut self,
toks: TokenStream,
kind: AstFragmentKind,
path: &Path,
span: Span)
-> Option<AstFragment> {
let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
match parser.parse_ast_fragment(kind, false) {
Ok(fragment) => {
parser.ensure_complete_parse(path, kind.name(), span);
Some(fragment)
}
Err(mut err) => {
err.set_span(span);
err.emit();
self.cx.trace_macros_diag();
kind.dummy(span)
}
}
}
}
impl<'a> Parser<'a> {
pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
-> PResult<'a, AstFragment> {
Ok(match kind {
AstFragmentKind::Items => {
let mut items = SmallVec::new();
while let Some(item) = self.parse_item()? {
items.push(item);
}
AstFragment::Items(items)
}
AstFragmentKind::TraitItems => {
let mut items = SmallVec::new();
while self.token != token::Eof {
items.push(self.parse_trait_item(&mut false)?);
}
AstFragment::TraitItems(items)
}
AstFragmentKind::ImplItems => {
let mut items = SmallVec::new();
while self.token != token::Eof {
items.push(self.parse_impl_item(&mut false)?);
}
AstFragment::ImplItems(items)
}
AstFragmentKind::ForeignItems => {
let mut items = SmallVec::new();
while self.token != token::Eof {
items.push(self.parse_foreign_item()?);
}