-
Notifications
You must be signed in to change notification settings - Fork 13k
/
Copy pathhir.rs
2618 lines (2333 loc) · 85.3 KB
/
hir.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 crate::def::{DefKind, Res};
use crate::def_id::DefId;
crate use crate::hir_id::HirId;
use crate::itemlikevisit;
use crate::print;
crate use BlockCheckMode::*;
crate use FunctionRetTy::*;
crate use UnsafeSource::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
use rustc_errors::FatalError;
use rustc_macros::HashStable_Generic;
use rustc_session::node_id::NodeMap;
use rustc_span::source_map::{SourceMap, Spanned};
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::{MultiSpan, Span, DUMMY_SP};
use rustc_target::spec::abi::Abi;
use smallvec::SmallVec;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use syntax::ast::{self, AsmDialect, CrateSugar, Ident, Name, NodeId};
use syntax::ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
pub use syntax::ast::{BorrowKind, ImplPolarity, IsAuto};
pub use syntax::ast::{CaptureBy, Constness, Movability, Mutability, Unsafety};
use syntax::tokenstream::TokenStream;
use syntax::util::parser::ExprPrecedence;
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable_Generic)]
pub struct Lifetime {
pub hir_id: HirId,
pub span: Span,
/// Either "`'a`", referring to a named lifetime definition,
/// or "``" (i.e., `kw::Invalid`), for elision placeholders.
///
/// HIR lowering inserts these placeholders in type paths that
/// refer to type definitions needing lifetime parameters,
/// `&T` and `&mut T`, and trait objects without `... + 'a`.
pub name: LifetimeName,
}
#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
#[derive(HashStable_Generic)]
pub enum ParamName {
/// Some user-given name like `T` or `'x`.
Plain(Ident),
/// Synthetic name generated when user elided a lifetime in an impl header.
///
/// E.g., the lifetimes in cases like these:
///
/// impl Foo for &u32
/// impl Foo<'_> for u32
///
/// in that case, we rewrite to
///
/// impl<'f> Foo for &'f u32
/// impl<'f> Foo<'f> for u32
///
/// where `'f` is something like `Fresh(0)`. The indices are
/// unique per impl, but not necessarily continuous.
Fresh(usize),
/// Indicates an illegal name was given and an error has been
/// reported (so we should squelch other derived errors). Occurs
/// when, e.g., `'_` is used in the wrong place.
Error,
}
impl ParamName {
pub fn ident(&self) -> Ident {
match *self {
ParamName::Plain(ident) => ident,
ParamName::Fresh(_) | ParamName::Error => {
Ident::with_dummy_span(kw::UnderscoreLifetime)
}
}
}
pub fn modern(&self) -> ParamName {
match *self {
ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
param_name => param_name,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
#[derive(HashStable_Generic)]
pub enum LifetimeName {
/// User-given names or fresh (synthetic) names.
Param(ParamName),
/// User wrote nothing (e.g., the lifetime in `&u32`).
Implicit,
/// Implicit lifetime in a context like `dyn Foo`. This is
/// distinguished from implicit lifetimes elsewhere because the
/// lifetime that they default to must appear elsewhere within the
/// enclosing type. This means that, in an `impl Trait` context, we
/// don't have to create a parameter for them. That is, `impl
/// Trait<Item = &u32>` expands to an opaque type like `type
/// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
/// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
/// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
/// that surrounding code knows not to create a lifetime
/// parameter.
ImplicitObjectLifetimeDefault,
/// Indicates an error during lowering (usually `'_` in wrong place)
/// that was already reported.
Error,
/// User wrote specifies `'_`.
Underscore,
/// User wrote `'static`.
Static,
}
impl LifetimeName {
pub fn ident(&self) -> Ident {
match *self {
LifetimeName::ImplicitObjectLifetimeDefault
| LifetimeName::Implicit
| LifetimeName::Error => Ident::invalid(),
LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
LifetimeName::Param(param_name) => param_name.ident(),
}
}
pub fn is_elided(&self) -> bool {
match self {
LifetimeName::ImplicitObjectLifetimeDefault
| LifetimeName::Implicit
| LifetimeName::Underscore => true,
// It might seem surprising that `Fresh(_)` counts as
// *not* elided -- but this is because, as far as the code
// in the compiler is concerned -- `Fresh(_)` variants act
// equivalently to "some fresh name". They correspond to
// early-bound regions on an impl, in other words.
LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
}
}
fn is_static(&self) -> bool {
self == &LifetimeName::Static
}
pub fn modern(&self) -> LifetimeName {
match *self {
LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
lifetime_name => lifetime_name,
}
}
}
impl fmt::Display for Lifetime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.name.ident().fmt(f)
}
}
impl fmt::Debug for Lifetime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"lifetime({}: {})",
self.hir_id,
print::to_string(print::NO_ANN, |s| s.print_lifetime(self))
)
}
}
impl Lifetime {
pub fn is_elided(&self) -> bool {
self.name.is_elided()
}
pub fn is_static(&self) -> bool {
self.name.is_static()
}
}
/// A `Path` is essentially Rust's notion of a name; for instance,
/// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
/// along with a bunch of supporting information.
#[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
pub struct Path<'hir> {
pub span: Span,
/// The resolution for the path.
pub res: Res,
/// The segments in the path: the things separated by `::`.
pub segments: &'hir [PathSegment<'hir>],
}
impl Path<'_> {
pub fn is_global(&self) -> bool {
!self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
}
}
impl fmt::Debug for Path<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "path({})", self)
}
}
impl fmt::Display for Path<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
}
}
/// A segment of a path: an identifier, an optional lifetime, and a set of
/// types.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct PathSegment<'hir> {
/// The identifier portion of this path segment.
#[stable_hasher(project(name))]
pub ident: Ident,
// `id` and `res` are optional. We currently only use these in save-analysis,
// any path segments without these will not have save-analysis info and
// therefore will not have 'jump to def' in IDEs, but otherwise will not be
// affected. (In general, we don't bother to get the defs for synthesized
// segments, only for segments which have come from the AST).
pub hir_id: Option<HirId>,
pub res: Option<Res>,
/// Type/lifetime parameters attached to this path. They come in
/// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
/// this is more than just simple syntactic sugar; the use of
/// parens affects the region binding rules, so we preserve the
/// distinction.
pub args: Option<&'hir GenericArgs<'hir>>,
/// Whether to infer remaining type parameters, if any.
/// This only applies to expression and pattern paths, and
/// out of those only the segments with no type parameters
/// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
pub infer_args: bool,
}
impl<'hir> PathSegment<'hir> {
/// Converts an identifier to the corresponding segment.
pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
}
pub fn generic_args(&self) -> &GenericArgs<'hir> {
if let Some(ref args) = self.args {
args
} else {
const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
DUMMY
}
}
}
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct ConstArg {
pub value: AnonConst,
pub span: Span,
}
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum GenericArg<'hir> {
Lifetime(Lifetime),
Type(Ty<'hir>),
Const(ConstArg),
}
impl GenericArg<'_> {
pub fn span(&self) -> Span {
match self {
GenericArg::Lifetime(l) => l.span,
GenericArg::Type(t) => t.span,
GenericArg::Const(c) => c.span,
}
}
pub fn id(&self) -> HirId {
match self {
GenericArg::Lifetime(l) => l.hir_id,
GenericArg::Type(t) => t.hir_id,
GenericArg::Const(c) => c.value.hir_id,
}
}
pub fn is_const(&self) -> bool {
match self {
GenericArg::Const(_) => true,
_ => false,
}
}
}
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct GenericArgs<'hir> {
/// The generic arguments for this path segment.
pub args: &'hir [GenericArg<'hir>],
/// Bindings (equality constraints) on associated types, if present.
/// E.g., `Foo<A = Bar>`.
pub bindings: &'hir [TypeBinding<'hir>],
/// Were arguments written in parenthesized form `Fn(T) -> U`?
/// This is required mostly for pretty-printing and diagnostics,
/// but also for changing lifetime elision rules to be "function-like".
pub parenthesized: bool,
}
impl GenericArgs<'_> {
pub const fn none() -> Self {
Self { args: &[], bindings: &[], parenthesized: false }
}
pub fn is_empty(&self) -> bool {
self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
}
pub fn inputs(&self) -> &[Ty<'_>] {
if self.parenthesized {
for arg in self.args {
match arg {
GenericArg::Lifetime(_) => {}
GenericArg::Type(ref ty) => {
if let TyKind::Tup(ref tys) = ty.kind {
return tys;
}
break;
}
GenericArg::Const(_) => {}
}
}
}
panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
}
pub fn own_counts(&self) -> GenericParamCount {
// We could cache this as a property of `GenericParamCount`, but
// the aim is to refactor this away entirely eventually and the
// presence of this method will be a constant reminder.
let mut own_counts: GenericParamCount = Default::default();
for arg in self.args {
match arg {
GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
GenericArg::Type(_) => own_counts.types += 1,
GenericArg::Const(_) => own_counts.consts += 1,
};
}
own_counts
}
}
/// A modifier on a bound, currently this is only used for `?Sized`, where the
/// modifier is `Maybe`. Negative bounds should also be handled here.
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
#[derive(HashStable_Generic)]
pub enum TraitBoundModifier {
None,
Maybe,
}
/// The AST represents all type param bounds as types.
/// `typeck::collect::compute_bounds` matches these against
/// the "special" built-in traits (see `middle::lang_items`) and
/// detects `Copy`, `Send` and `Sync`.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum GenericBound<'hir> {
Trait(PolyTraitRef<'hir>, TraitBoundModifier),
Outlives(Lifetime),
}
impl GenericBound<'_> {
pub fn span(&self) -> Span {
match self {
&GenericBound::Trait(ref t, ..) => t.span,
&GenericBound::Outlives(ref l) => l.span,
}
}
}
pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum LifetimeParamKind {
// Indicates that the lifetime definition was explicitly declared (e.g., in
// `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
Explicit,
// Indicates that the lifetime definition was synthetically added
// as a result of an in-band lifetime usage (e.g., in
// `fn foo(x: &'a u8) -> &'a u8 { x }`).
InBand,
// Indication that the lifetime was elided (e.g., in both cases in
// `fn foo(x: &u8) -> &'_ u8 { x }`).
Elided,
// Indication that the lifetime name was somehow in error.
Error,
}
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum GenericParamKind<'hir> {
/// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
Lifetime {
kind: LifetimeParamKind,
},
Type {
default: Option<&'hir Ty<'hir>>,
synthetic: Option<SyntheticTyParamKind>,
},
Const {
ty: &'hir Ty<'hir>,
},
}
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct GenericParam<'hir> {
pub hir_id: HirId,
pub name: ParamName,
pub attrs: &'hir [Attribute],
pub bounds: GenericBounds<'hir>,
pub span: Span,
pub pure_wrt_drop: bool,
pub kind: GenericParamKind<'hir>,
}
#[derive(Default)]
pub struct GenericParamCount {
pub lifetimes: usize,
pub types: usize,
pub consts: usize,
}
/// Represents lifetimes and type parameters attached to a declaration
/// of a function, enum, trait, etc.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct Generics<'hir> {
pub params: &'hir [GenericParam<'hir>],
pub where_clause: WhereClause<'hir>,
pub span: Span,
}
impl Generics<'hir> {
pub const fn empty() -> Generics<'hir> {
Generics {
params: &[],
where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
span: DUMMY_SP,
}
}
pub fn own_counts(&self) -> GenericParamCount {
// We could cache this as a property of `GenericParamCount`, but
// the aim is to refactor this away entirely eventually and the
// presence of this method will be a constant reminder.
let mut own_counts: GenericParamCount = Default::default();
for param in self.params {
match param.kind {
GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
GenericParamKind::Type { .. } => own_counts.types += 1,
GenericParamKind::Const { .. } => own_counts.consts += 1,
};
}
own_counts
}
pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
for param in self.params {
if name == param.name.ident().name {
return Some(param);
}
}
None
}
pub fn spans(&self) -> MultiSpan {
if self.params.is_empty() {
self.span.into()
} else {
self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
}
}
}
/// Synthetic type parameters are converted to another form during lowering; this allows
/// us to track the original form they had, and is useful for error messages.
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
#[derive(HashStable_Generic)]
pub enum SyntheticTyParamKind {
ImplTrait,
}
/// A where-clause in a definition.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct WhereClause<'hir> {
pub predicates: &'hir [WherePredicate<'hir>],
// Only valid if predicates isn't empty.
pub span: Span,
}
impl WhereClause<'_> {
pub fn span(&self) -> Option<Span> {
if self.predicates.is_empty() { None } else { Some(self.span) }
}
/// The `WhereClause` under normal circumstances points at either the predicates or the empty
/// space where the `where` clause should be. Only of use for diagnostic suggestions.
pub fn span_for_predicates_or_empty_place(&self) -> Span {
self.span
}
}
/// A single predicate in a where-clause.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum WherePredicate<'hir> {
/// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
BoundPredicate(WhereBoundPredicate<'hir>),
/// A lifetime predicate (e.g., `'a: 'b + 'c`).
RegionPredicate(WhereRegionPredicate<'hir>),
/// An equality predicate (unsupported).
EqPredicate(WhereEqPredicate<'hir>),
}
impl WherePredicate<'_> {
pub fn span(&self) -> Span {
match self {
&WherePredicate::BoundPredicate(ref p) => p.span,
&WherePredicate::RegionPredicate(ref p) => p.span,
&WherePredicate::EqPredicate(ref p) => p.span,
}
}
}
/// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct WhereBoundPredicate<'hir> {
pub span: Span,
/// Any generics from a `for` binding.
pub bound_generic_params: &'hir [GenericParam<'hir>],
/// The type being bounded.
pub bounded_ty: &'hir Ty<'hir>,
/// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
pub bounds: GenericBounds<'hir>,
}
/// A lifetime predicate (e.g., `'a: 'b + 'c`).
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct WhereRegionPredicate<'hir> {
pub span: Span,
pub lifetime: Lifetime,
pub bounds: GenericBounds<'hir>,
}
/// An equality predicate (e.g., `T = int`); currently unsupported.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct WhereEqPredicate<'hir> {
pub hir_id: HirId,
pub span: Span,
pub lhs_ty: &'hir Ty<'hir>,
pub rhs_ty: &'hir Ty<'hir>,
}
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct ModuleItems {
// Use BTreeSets here so items are in the same order as in the
// list of all items in Crate
pub items: BTreeSet<HirId>,
pub trait_items: BTreeSet<TraitItemId>,
pub impl_items: BTreeSet<ImplItemId>,
}
/// The top-level data structure that stores the entire contents of
/// the crate currently being compiled.
///
/// For more details, see the [rustc guide].
///
/// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html
#[derive(RustcEncodable, RustcDecodable, Debug)]
pub struct Crate<'hir> {
pub module: Mod<'hir>,
pub attrs: &'hir [Attribute],
pub span: Span,
pub exported_macros: &'hir [MacroDef<'hir>],
// Attributes from non-exported macros, kept only for collecting the library feature list.
pub non_exported_macro_attrs: &'hir [Attribute],
// N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
// over the ids in increasing order. In principle it should not
// matter what order we visit things in, but in *practice* it
// does, because it can affect the order in which errors are
// detected, which in turn can make compile-fail tests yield
// slightly different results.
pub items: BTreeMap<HirId, Item<'hir>>,
pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
pub bodies: BTreeMap<BodyId, Body<'hir>>,
pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
/// A list of the body ids written out in the order in which they
/// appear in the crate. If you're going to process all the bodies
/// in the crate, you should iterate over this list rather than the keys
/// of bodies.
pub body_ids: Vec<BodyId>,
/// A list of modules written out in the order in which they
/// appear in the crate. This includes the main crate module.
pub modules: BTreeMap<HirId, ModuleItems>,
}
impl Crate<'hir> {
pub fn item(&self, id: HirId) -> &Item<'hir> {
&self.items[&id]
}
pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
&self.trait_items[&id]
}
pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
&self.impl_items[&id]
}
pub fn body(&self, id: BodyId) -> &Body<'hir> {
&self.bodies[&id]
}
}
impl Crate<'_> {
/// Visits all items in the crate in some deterministic (but
/// unspecified) order. If you just need to process every item,
/// but don't care about nesting, this method is the best choice.
///
/// If you do care about nesting -- usually because your algorithm
/// follows lexical scoping rules -- then you want a different
/// approach. You should override `visit_nested_item` in your
/// visitor and then call `intravisit::walk_crate` instead.
pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
where
V: itemlikevisit::ItemLikeVisitor<'hir>,
{
for (_, item) in &self.items {
visitor.visit_item(item);
}
for (_, trait_item) in &self.trait_items {
visitor.visit_trait_item(trait_item);
}
for (_, impl_item) in &self.impl_items {
visitor.visit_impl_item(impl_item);
}
}
/// A parallel version of `visit_all_item_likes`.
pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
where
V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
{
parallel!(
{
par_for_each_in(&self.items, |(_, item)| {
visitor.visit_item(item);
});
},
{
par_for_each_in(&self.trait_items, |(_, trait_item)| {
visitor.visit_trait_item(trait_item);
});
},
{
par_for_each_in(&self.impl_items, |(_, impl_item)| {
visitor.visit_impl_item(impl_item);
});
}
);
}
}
/// A macro definition, in this crate or imported from another.
///
/// Not parsed directly, but created on macro import or `macro_rules!` expansion.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct MacroDef<'hir> {
pub name: Name,
pub vis: Visibility<'hir>,
pub attrs: &'hir [Attribute],
pub hir_id: HirId,
pub span: Span,
pub body: TokenStream,
pub legacy: bool,
}
/// A block of statements `{ .. }`, which may have a label (in this case the
/// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
/// the `rules` being anything but `DefaultBlock`.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct Block<'hir> {
/// Statements in a block.
pub stmts: &'hir [Stmt<'hir>],
/// An expression at the end of the block
/// without a semicolon, if any.
pub expr: Option<&'hir Expr<'hir>>,
#[stable_hasher(ignore)]
pub hir_id: HirId,
/// Distinguishes between `unsafe { ... }` and `{ ... }`.
pub rules: BlockCheckMode,
pub span: Span,
/// If true, then there may exist `break 'a` values that aim to
/// break out of this block early.
/// Used by `'label: {}` blocks and by `try {}` blocks.
pub targeted_by_break: bool,
}
#[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
pub struct Pat<'hir> {
#[stable_hasher(ignore)]
pub hir_id: HirId,
pub kind: PatKind<'hir>,
pub span: Span,
}
impl fmt::Debug for Pat<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"pat({}: {})",
self.hir_id,
print::to_string(print::NO_ANN, |s| s.print_pat(self))
)
}
}
impl Pat<'_> {
// FIXME(#19596) this is a workaround, but there should be a better way
fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
if !it(self) {
return false;
}
use PatKind::*;
match &self.kind {
Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
Slice(before, slice, after) => {
before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
}
}
}
/// Walk the pattern in left-to-right order,
/// short circuiting (with `.all(..)`) if `false` is returned.
///
/// Note that when visiting e.g. `Tuple(ps)`,
/// if visiting `ps[0]` returns `false`,
/// then `ps[1]` will not be visited.
pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
self.walk_short_(&mut it)
}
// FIXME(#19596) this is a workaround, but there should be a better way
fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
if !it(self) {
return;
}
use PatKind::*;
match &self.kind {
Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
Slice(before, slice, after) => {
before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
}
}
}
/// Walk the pattern in left-to-right order.
///
/// If `it(pat)` returns `false`, the children are not visited.
pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
self.walk_(&mut it)
}
/// Walk the pattern in left-to-right order.
///
/// If you always want to recurse, prefer this method over `walk`.
pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
self.walk(|p| {
it(p);
true
})
}
}
/// A single field in a struct pattern.
///
/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
/// are treated the same as` x: x, y: ref y, z: ref mut z`,
/// except `is_shorthand` is true.
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct FieldPat<'hir> {
#[stable_hasher(ignore)]
pub hir_id: HirId,
/// The identifier for the field.
#[stable_hasher(project(name))]
pub ident: Ident,
/// The pattern the field is destructured to.
pub pat: &'hir Pat<'hir>,
pub is_shorthand: bool,
pub span: Span,
}
/// Explicit binding annotations given in the HIR for a binding. Note
/// that this is not the final binding *mode* that we infer after type
/// inference.
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum BindingAnnotation {
/// No binding annotation given: this means that the final binding mode
/// will depend on whether we have skipped through a `&` reference
/// when matching. For example, the `x` in `Some(x)` will have binding
/// mode `None`; if you do `let Some(x) = &Some(22)`, it will
/// ultimately be inferred to be by-reference.
///
/// Note that implicit reference skipping is not implemented yet (#42640).
Unannotated,
/// Annotated with `mut x` -- could be either ref or not, similar to `None`.
Mutable,
/// Annotated as `ref`, like `ref x`
Ref,
/// Annotated as `ref mut x`.
RefMut,
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum RangeEnd {
Included,
Excluded,
}
impl fmt::Display for RangeEnd {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
RangeEnd::Included => "..=",
RangeEnd::Excluded => "..",
})
}
}
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum PatKind<'hir> {
/// Represents a wildcard pattern (i.e., `_`).
Wild,
/// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
/// The `HirId` is the canonical ID for the variable being bound,
/// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
/// which is the pattern ID of the first `x`.
Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
/// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
/// The `bool` is `true` in the presence of a `..`.
Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
/// A tuple struct/variant pattern `Variant(x, y, .., z)`.
/// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
/// `0 <= position <= subpats.len()`
TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
/// An or-pattern `A | B | C`.
/// Invariant: `pats.len() >= 2`.
Or(&'hir [&'hir Pat<'hir>]),
/// A path pattern for an unit struct/variant or a (maybe-associated) constant.
Path(QPath<'hir>),
/// A tuple pattern (e.g., `(a, b)`).
/// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
/// `0 <= position <= subpats.len()`
Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
/// A `box` pattern.
Box(&'hir Pat<'hir>),
/// A reference pattern (e.g., `&mut (a, b)`).
Ref(&'hir Pat<'hir>, Mutability),
/// A literal.
Lit(&'hir Expr<'hir>),
/// A range pattern (e.g., `1..=2` or `1..2`).
Range(&'hir Expr<'hir>, &'hir Expr<'hir>, RangeEnd),
/// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
///
/// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
/// If `slice` exists, then `after` can be non-empty.
///
/// The representation for e.g., `[a, b, .., c, d]` is:
/// ```
/// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
/// ```
Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum BinOpKind {
/// The `+` operator (addition).
Add,
/// The `-` operator (subtraction).
Sub,
/// The `*` operator (multiplication).
Mul,
/// The `/` operator (division).
Div,
/// The `%` operator (modulus).
Rem,
/// The `&&` operator (logical and).
And,
/// The `||` operator (logical or).
Or,
/// The `^` operator (bitwise xor).
BitXor,
/// The `&` operator (bitwise and).
BitAnd,
/// The `|` operator (bitwise or).
BitOr,
/// The `<<` operator (shift left).
Shl,
/// The `>>` operator (shift right).
Shr,
/// The `==` operator (equality).
Eq,
/// The `<` operator (less than).
Lt,
/// The `<=` operator (less than or equal to).
Le,
/// The `!=` operator (not equal to).
Ne,
/// The `>=` operator (greater than or equal to).
Ge,
/// The `>` operator (greater than).
Gt,
}
impl BinOpKind {
pub fn as_str(self) -> &'static str {
match self {
BinOpKind::Add => "+",
BinOpKind::Sub => "-",
BinOpKind::Mul => "*",
BinOpKind::Div => "/",
BinOpKind::Rem => "%",
BinOpKind::And => "&&",
BinOpKind::Or => "||",
BinOpKind::BitXor => "^",
BinOpKind::BitAnd => "&",
BinOpKind::BitOr => "|",
BinOpKind::Shl => "<<",
BinOpKind::Shr => ">>",
BinOpKind::Eq => "==",
BinOpKind::Lt => "<",
BinOpKind::Le => "<=",
BinOpKind::Ne => "!=",
BinOpKind::Ge => ">=",
BinOpKind::Gt => ">",
}
}
pub fn is_lazy(self) -> bool {
match self {
BinOpKind::And | BinOpKind::Or => true,
_ => false,
}
}
pub fn is_shift(self) -> bool {
match self {
BinOpKind::Shl | BinOpKind::Shr => true,
_ => false,
}
}
pub fn is_comparison(self) -> bool {