]>
Commit | Line | Data |
---|---|---|
6a06907d | 1 | // ignore-tidy-filelength |
cdc7bbd5 | 2 | use crate::def::{CtorKind, DefKind, Res}; |
dfeec247 | 3 | use crate::def_id::DefId; |
17df50a5 | 4 | crate use crate::hir_id::{HirId, ItemLocalId}; |
3dfed10e | 5 | use crate::{itemlikevisit, LangItem}; |
dfeec247 | 6 | |
74b04a01 | 7 | use rustc_ast::util::parser::ExprPrecedence; |
3dfed10e | 8 | use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect}; |
6a06907d | 9 | use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, TraitObjectSyntax, UintTy}; |
3dfed10e XL |
10 | pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto}; |
11 | pub use rustc_ast::{CaptureBy, Movability, Mutability}; | |
12 | use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; | |
17df50a5 | 13 | use rustc_data_structures::fx::FxHashMap; |
dfeec247 | 14 | use rustc_data_structures::sync::{par_for_each_in, Send, Sync}; |
dfeec247 | 15 | use rustc_macros::HashStable_Generic; |
17df50a5 | 16 | use rustc_span::source_map::Spanned; |
f9f354fc | 17 | use rustc_span::symbol::{kw, sym, Ident, Symbol}; |
5869c6ff | 18 | use rustc_span::{def_id::LocalDefId, BytePos}; |
dfeec247 | 19 | use rustc_span::{MultiSpan, Span, DUMMY_SP}; |
f9f354fc | 20 | use rustc_target::asm::InlineAsmRegOrRegClass; |
dfeec247 | 21 | use rustc_target::spec::abi::Abi; |
74b04a01 | 22 | |
dfeec247 XL |
23 | use smallvec::SmallVec; |
24 | use std::collections::{BTreeMap, BTreeSet}; | |
25 | use std::fmt; | |
dfeec247 | 26 | |
3dfed10e | 27 | #[derive(Copy, Clone, Encodable, HashStable_Generic)] |
dfeec247 XL |
28 | pub struct Lifetime { |
29 | pub hir_id: HirId, | |
30 | pub span: Span, | |
31 | ||
32 | /// Either "`'a`", referring to a named lifetime definition, | |
5869c6ff | 33 | /// or "``" (i.e., `kw::Empty`), for elision placeholders. |
dfeec247 XL |
34 | /// |
35 | /// HIR lowering inserts these placeholders in type paths that | |
36 | /// refer to type definitions needing lifetime parameters, | |
37 | /// `&T` and `&mut T`, and trait objects without `... + 'a`. | |
38 | pub name: LifetimeName, | |
39 | } | |
40 | ||
3dfed10e | 41 | #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)] |
dfeec247 XL |
42 | #[derive(HashStable_Generic)] |
43 | pub enum ParamName { | |
44 | /// Some user-given name like `T` or `'x`. | |
45 | Plain(Ident), | |
46 | ||
47 | /// Synthetic name generated when user elided a lifetime in an impl header. | |
48 | /// | |
49 | /// E.g., the lifetimes in cases like these: | |
50 | /// | |
51 | /// impl Foo for &u32 | |
52 | /// impl Foo<'_> for u32 | |
53 | /// | |
54 | /// in that case, we rewrite to | |
55 | /// | |
56 | /// impl<'f> Foo for &'f u32 | |
57 | /// impl<'f> Foo<'f> for u32 | |
58 | /// | |
59 | /// where `'f` is something like `Fresh(0)`. The indices are | |
60 | /// unique per impl, but not necessarily continuous. | |
61 | Fresh(usize), | |
62 | ||
63 | /// Indicates an illegal name was given and an error has been | |
64 | /// reported (so we should squelch other derived errors). Occurs | |
65 | /// when, e.g., `'_` is used in the wrong place. | |
66 | Error, | |
67 | } | |
68 | ||
69 | impl ParamName { | |
70 | pub fn ident(&self) -> Ident { | |
71 | match *self { | |
72 | ParamName::Plain(ident) => ident, | |
73 | ParamName::Fresh(_) | ParamName::Error => { | |
74 | Ident::with_dummy_span(kw::UnderscoreLifetime) | |
75 | } | |
76 | } | |
77 | } | |
78 | ||
ba9703b0 | 79 | pub fn normalize_to_macros_2_0(&self) -> ParamName { |
dfeec247 | 80 | match *self { |
ba9703b0 | 81 | ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()), |
dfeec247 XL |
82 | param_name => param_name, |
83 | } | |
84 | } | |
85 | } | |
86 | ||
3dfed10e | 87 | #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)] |
dfeec247 XL |
88 | #[derive(HashStable_Generic)] |
89 | pub enum LifetimeName { | |
90 | /// User-given names or fresh (synthetic) names. | |
91 | Param(ParamName), | |
92 | ||
93 | /// User wrote nothing (e.g., the lifetime in `&u32`). | |
94 | Implicit, | |
95 | ||
96 | /// Implicit lifetime in a context like `dyn Foo`. This is | |
97 | /// distinguished from implicit lifetimes elsewhere because the | |
98 | /// lifetime that they default to must appear elsewhere within the | |
99 | /// enclosing type. This means that, in an `impl Trait` context, we | |
100 | /// don't have to create a parameter for them. That is, `impl | |
101 | /// Trait<Item = &u32>` expands to an opaque type like `type | |
102 | /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item = | |
103 | /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar + | |
104 | /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so | |
105 | /// that surrounding code knows not to create a lifetime | |
106 | /// parameter. | |
107 | ImplicitObjectLifetimeDefault, | |
108 | ||
109 | /// Indicates an error during lowering (usually `'_` in wrong place) | |
110 | /// that was already reported. | |
111 | Error, | |
112 | ||
113 | /// User wrote specifies `'_`. | |
114 | Underscore, | |
115 | ||
116 | /// User wrote `'static`. | |
117 | Static, | |
118 | } | |
119 | ||
120 | impl LifetimeName { | |
121 | pub fn ident(&self) -> Ident { | |
122 | match *self { | |
123 | LifetimeName::ImplicitObjectLifetimeDefault | |
124 | | LifetimeName::Implicit | |
125 | | LifetimeName::Error => Ident::invalid(), | |
126 | LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime), | |
127 | LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime), | |
128 | LifetimeName::Param(param_name) => param_name.ident(), | |
129 | } | |
130 | } | |
131 | ||
132 | pub fn is_elided(&self) -> bool { | |
133 | match self { | |
134 | LifetimeName::ImplicitObjectLifetimeDefault | |
135 | | LifetimeName::Implicit | |
136 | | LifetimeName::Underscore => true, | |
137 | ||
138 | // It might seem surprising that `Fresh(_)` counts as | |
139 | // *not* elided -- but this is because, as far as the code | |
140 | // in the compiler is concerned -- `Fresh(_)` variants act | |
141 | // equivalently to "some fresh name". They correspond to | |
142 | // early-bound regions on an impl, in other words. | |
143 | LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false, | |
144 | } | |
145 | } | |
146 | ||
147 | fn is_static(&self) -> bool { | |
148 | self == &LifetimeName::Static | |
149 | } | |
150 | ||
ba9703b0 | 151 | pub fn normalize_to_macros_2_0(&self) -> LifetimeName { |
dfeec247 | 152 | match *self { |
ba9703b0 XL |
153 | LifetimeName::Param(param_name) => { |
154 | LifetimeName::Param(param_name.normalize_to_macros_2_0()) | |
155 | } | |
dfeec247 XL |
156 | lifetime_name => lifetime_name, |
157 | } | |
158 | } | |
159 | } | |
160 | ||
161 | impl fmt::Display for Lifetime { | |
162 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
163 | self.name.ident().fmt(f) | |
164 | } | |
165 | } | |
166 | ||
167 | impl fmt::Debug for Lifetime { | |
168 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
ba9703b0 | 169 | write!(f, "lifetime({}: {})", self.hir_id, self.name.ident()) |
dfeec247 XL |
170 | } |
171 | } | |
172 | ||
173 | impl Lifetime { | |
174 | pub fn is_elided(&self) -> bool { | |
175 | self.name.is_elided() | |
176 | } | |
177 | ||
178 | pub fn is_static(&self) -> bool { | |
179 | self.name.is_static() | |
180 | } | |
181 | } | |
182 | ||
183 | /// A `Path` is essentially Rust's notion of a name; for instance, | |
184 | /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers, | |
185 | /// along with a bunch of supporting information. | |
3dfed10e | 186 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
187 | pub struct Path<'hir> { |
188 | pub span: Span, | |
189 | /// The resolution for the path. | |
190 | pub res: Res, | |
191 | /// The segments in the path: the things separated by `::`. | |
192 | pub segments: &'hir [PathSegment<'hir>], | |
193 | } | |
194 | ||
195 | impl Path<'_> { | |
196 | pub fn is_global(&self) -> bool { | |
197 | !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot | |
198 | } | |
199 | } | |
200 | ||
dfeec247 XL |
201 | /// A segment of a path: an identifier, an optional lifetime, and a set of |
202 | /// types. | |
3dfed10e | 203 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
204 | pub struct PathSegment<'hir> { |
205 | /// The identifier portion of this path segment. | |
206 | #[stable_hasher(project(name))] | |
207 | pub ident: Ident, | |
208 | // `id` and `res` are optional. We currently only use these in save-analysis, | |
209 | // any path segments without these will not have save-analysis info and | |
210 | // therefore will not have 'jump to def' in IDEs, but otherwise will not be | |
211 | // affected. (In general, we don't bother to get the defs for synthesized | |
212 | // segments, only for segments which have come from the AST). | |
213 | pub hir_id: Option<HirId>, | |
214 | pub res: Option<Res>, | |
215 | ||
216 | /// Type/lifetime parameters attached to this path. They come in | |
217 | /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that | |
218 | /// this is more than just simple syntactic sugar; the use of | |
219 | /// parens affects the region binding rules, so we preserve the | |
220 | /// distinction. | |
221 | pub args: Option<&'hir GenericArgs<'hir>>, | |
222 | ||
223 | /// Whether to infer remaining type parameters, if any. | |
224 | /// This only applies to expression and pattern paths, and | |
225 | /// out of those only the segments with no type parameters | |
226 | /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`. | |
227 | pub infer_args: bool, | |
228 | } | |
229 | ||
230 | impl<'hir> PathSegment<'hir> { | |
231 | /// Converts an identifier to the corresponding segment. | |
232 | pub fn from_ident(ident: Ident) -> PathSegment<'hir> { | |
233 | PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None } | |
234 | } | |
235 | ||
5869c6ff XL |
236 | pub fn invalid() -> Self { |
237 | Self::from_ident(Ident::invalid()) | |
238 | } | |
239 | ||
240 | pub fn args(&self) -> &GenericArgs<'hir> { | |
dfeec247 XL |
241 | if let Some(ref args) = self.args { |
242 | args | |
243 | } else { | |
244 | const DUMMY: &GenericArgs<'_> = &GenericArgs::none(); | |
245 | DUMMY | |
246 | } | |
247 | } | |
248 | } | |
249 | ||
3dfed10e | 250 | #[derive(Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
251 | pub struct ConstArg { |
252 | pub value: AnonConst, | |
253 | pub span: Span, | |
254 | } | |
255 | ||
3dfed10e | 256 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
257 | pub enum GenericArg<'hir> { |
258 | Lifetime(Lifetime), | |
259 | Type(Ty<'hir>), | |
260 | Const(ConstArg), | |
261 | } | |
262 | ||
263 | impl GenericArg<'_> { | |
264 | pub fn span(&self) -> Span { | |
265 | match self { | |
266 | GenericArg::Lifetime(l) => l.span, | |
267 | GenericArg::Type(t) => t.span, | |
268 | GenericArg::Const(c) => c.span, | |
269 | } | |
270 | } | |
271 | ||
272 | pub fn id(&self) -> HirId { | |
273 | match self { | |
274 | GenericArg::Lifetime(l) => l.hir_id, | |
275 | GenericArg::Type(t) => t.hir_id, | |
276 | GenericArg::Const(c) => c.value.hir_id, | |
277 | } | |
278 | } | |
279 | ||
280 | pub fn is_const(&self) -> bool { | |
29967ef6 | 281 | matches!(self, GenericArg::Const(_)) |
dfeec247 | 282 | } |
74b04a01 | 283 | |
5869c6ff XL |
284 | pub fn is_synthetic(&self) -> bool { |
285 | matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid()) | |
286 | } | |
287 | ||
74b04a01 XL |
288 | pub fn descr(&self) -> &'static str { |
289 | match self { | |
290 | GenericArg::Lifetime(_) => "lifetime", | |
291 | GenericArg::Type(_) => "type", | |
292 | GenericArg::Const(_) => "constant", | |
293 | } | |
294 | } | |
fc512014 | 295 | |
5869c6ff | 296 | pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd { |
fc512014 | 297 | match self { |
5869c6ff XL |
298 | GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime, |
299 | GenericArg::Type(_) => ast::ParamKindOrd::Type, | |
cdc7bbd5 XL |
300 | GenericArg::Const(_) => { |
301 | ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() } | |
302 | } | |
fc512014 XL |
303 | } |
304 | } | |
dfeec247 XL |
305 | } |
306 | ||
3dfed10e | 307 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
308 | pub struct GenericArgs<'hir> { |
309 | /// The generic arguments for this path segment. | |
310 | pub args: &'hir [GenericArg<'hir>], | |
311 | /// Bindings (equality constraints) on associated types, if present. | |
312 | /// E.g., `Foo<A = Bar>`. | |
313 | pub bindings: &'hir [TypeBinding<'hir>], | |
314 | /// Were arguments written in parenthesized form `Fn(T) -> U`? | |
315 | /// This is required mostly for pretty-printing and diagnostics, | |
316 | /// but also for changing lifetime elision rules to be "function-like". | |
317 | pub parenthesized: bool, | |
17df50a5 XL |
318 | /// The span encompassing arguments and the surrounding brackets `<>` or `()` |
319 | /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W | |
320 | /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^ | |
321 | /// Note that this may be: | |
322 | /// - empty, if there are no generic brackets (but there may be hidden lifetimes) | |
323 | /// - dummy, if this was generated while desugaring | |
324 | pub span_ext: Span, | |
dfeec247 XL |
325 | } |
326 | ||
327 | impl GenericArgs<'_> { | |
328 | pub const fn none() -> Self { | |
17df50a5 | 329 | Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP } |
dfeec247 XL |
330 | } |
331 | ||
dfeec247 XL |
332 | pub fn inputs(&self) -> &[Ty<'_>] { |
333 | if self.parenthesized { | |
334 | for arg in self.args { | |
335 | match arg { | |
336 | GenericArg::Lifetime(_) => {} | |
337 | GenericArg::Type(ref ty) => { | |
338 | if let TyKind::Tup(ref tys) = ty.kind { | |
339 | return tys; | |
340 | } | |
341 | break; | |
342 | } | |
343 | GenericArg::Const(_) => {} | |
344 | } | |
345 | } | |
346 | } | |
347 | panic!("GenericArgs::inputs: not a `Fn(T) -> U`"); | |
348 | } | |
349 | ||
350 | pub fn own_counts(&self) -> GenericParamCount { | |
351 | // We could cache this as a property of `GenericParamCount`, but | |
352 | // the aim is to refactor this away entirely eventually and the | |
353 | // presence of this method will be a constant reminder. | |
354 | let mut own_counts: GenericParamCount = Default::default(); | |
355 | ||
356 | for arg in self.args { | |
357 | match arg { | |
358 | GenericArg::Lifetime(_) => own_counts.lifetimes += 1, | |
359 | GenericArg::Type(_) => own_counts.types += 1, | |
360 | GenericArg::Const(_) => own_counts.consts += 1, | |
361 | }; | |
362 | } | |
363 | ||
364 | own_counts | |
365 | } | |
5869c6ff | 366 | |
17df50a5 XL |
367 | /// The span encompassing the text inside the surrounding brackets. |
368 | /// It will also include bindings if they aren't in the form `-> Ret` | |
369 | /// Returns `None` if the span is empty (e.g. no brackets) or dummy | |
5869c6ff | 370 | pub fn span(&self) -> Option<Span> { |
17df50a5 XL |
371 | let span_ext = self.span_ext()?; |
372 | Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1))) | |
5869c6ff XL |
373 | } |
374 | ||
375 | /// Returns span encompassing arguments and their surrounding `<>` or `()` | |
17df50a5 XL |
376 | pub fn span_ext(&self) -> Option<Span> { |
377 | Some(self.span_ext).filter(|span| !span.is_empty()) | |
5869c6ff XL |
378 | } |
379 | ||
380 | pub fn is_empty(&self) -> bool { | |
381 | self.args.is_empty() | |
382 | } | |
dfeec247 XL |
383 | } |
384 | ||
385 | /// A modifier on a bound, currently this is only used for `?Sized`, where the | |
386 | /// modifier is `Maybe`. Negative bounds should also be handled here. | |
3dfed10e | 387 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)] |
dfeec247 XL |
388 | #[derive(HashStable_Generic)] |
389 | pub enum TraitBoundModifier { | |
390 | None, | |
391 | Maybe, | |
392 | MaybeConst, | |
393 | } | |
394 | ||
395 | /// The AST represents all type param bounds as types. | |
396 | /// `typeck::collect::compute_bounds` matches these against | |
397 | /// the "special" built-in traits (see `middle::lang_items`) and | |
398 | /// detects `Copy`, `Send` and `Sync`. | |
cdc7bbd5 | 399 | #[derive(Clone, Debug, HashStable_Generic)] |
dfeec247 XL |
400 | pub enum GenericBound<'hir> { |
401 | Trait(PolyTraitRef<'hir>, TraitBoundModifier), | |
3dfed10e XL |
402 | // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem` |
403 | LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>), | |
dfeec247 XL |
404 | Outlives(Lifetime), |
405 | } | |
406 | ||
407 | impl GenericBound<'_> { | |
ba9703b0 | 408 | pub fn trait_ref(&self) -> Option<&TraitRef<'_>> { |
dfeec247 | 409 | match self { |
ba9703b0 | 410 | GenericBound::Trait(data, _) => Some(&data.trait_ref), |
dfeec247 XL |
411 | _ => None, |
412 | } | |
413 | } | |
414 | ||
415 | pub fn span(&self) -> Span { | |
416 | match self { | |
5869c6ff XL |
417 | GenericBound::Trait(t, ..) => t.span, |
418 | GenericBound::LangItemTrait(_, span, ..) => *span, | |
419 | GenericBound::Outlives(l) => l.span, | |
dfeec247 XL |
420 | } |
421 | } | |
422 | } | |
423 | ||
424 | pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>]; | |
425 | ||
3dfed10e | 426 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
427 | pub enum LifetimeParamKind { |
428 | // Indicates that the lifetime definition was explicitly declared (e.g., in | |
429 | // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`). | |
430 | Explicit, | |
431 | ||
432 | // Indicates that the lifetime definition was synthetically added | |
433 | // as a result of an in-band lifetime usage (e.g., in | |
434 | // `fn foo(x: &'a u8) -> &'a u8 { x }`). | |
435 | InBand, | |
436 | ||
437 | // Indication that the lifetime was elided (e.g., in both cases in | |
438 | // `fn foo(x: &u8) -> &'_ u8 { x }`). | |
439 | Elided, | |
440 | ||
441 | // Indication that the lifetime name was somehow in error. | |
442 | Error, | |
443 | } | |
444 | ||
3dfed10e | 445 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
446 | pub enum GenericParamKind<'hir> { |
447 | /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). | |
448 | Lifetime { | |
449 | kind: LifetimeParamKind, | |
450 | }, | |
451 | Type { | |
452 | default: Option<&'hir Ty<'hir>>, | |
453 | synthetic: Option<SyntheticTyParamKind>, | |
454 | }, | |
455 | Const { | |
456 | ty: &'hir Ty<'hir>, | |
5869c6ff XL |
457 | /// Optional default value for the const generic param |
458 | default: Option<AnonConst>, | |
dfeec247 XL |
459 | }, |
460 | } | |
461 | ||
3dfed10e | 462 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
463 | pub struct GenericParam<'hir> { |
464 | pub hir_id: HirId, | |
465 | pub name: ParamName, | |
dfeec247 XL |
466 | pub bounds: GenericBounds<'hir>, |
467 | pub span: Span, | |
468 | pub pure_wrt_drop: bool, | |
469 | pub kind: GenericParamKind<'hir>, | |
470 | } | |
471 | ||
74b04a01 XL |
472 | impl GenericParam<'hir> { |
473 | pub fn bounds_span(&self) -> Option<Span> { | |
474 | self.bounds.iter().fold(None, |span, bound| { | |
475 | let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span()); | |
476 | ||
477 | Some(span) | |
478 | }) | |
479 | } | |
480 | } | |
481 | ||
dfeec247 XL |
482 | #[derive(Default)] |
483 | pub struct GenericParamCount { | |
484 | pub lifetimes: usize, | |
485 | pub types: usize, | |
486 | pub consts: usize, | |
487 | } | |
488 | ||
489 | /// Represents lifetimes and type parameters attached to a declaration | |
490 | /// of a function, enum, trait, etc. | |
3dfed10e | 491 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
492 | pub struct Generics<'hir> { |
493 | pub params: &'hir [GenericParam<'hir>], | |
494 | pub where_clause: WhereClause<'hir>, | |
495 | pub span: Span, | |
496 | } | |
497 | ||
498 | impl Generics<'hir> { | |
499 | pub const fn empty() -> Generics<'hir> { | |
500 | Generics { | |
501 | params: &[], | |
502 | where_clause: WhereClause { predicates: &[], span: DUMMY_SP }, | |
503 | span: DUMMY_SP, | |
504 | } | |
505 | } | |
506 | ||
dfeec247 XL |
507 | pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> { |
508 | for param in self.params { | |
509 | if name == param.name.ident().name { | |
510 | return Some(param); | |
511 | } | |
512 | } | |
513 | None | |
514 | } | |
515 | ||
516 | pub fn spans(&self) -> MultiSpan { | |
517 | if self.params.is_empty() { | |
518 | self.span.into() | |
519 | } else { | |
520 | self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into() | |
521 | } | |
522 | } | |
523 | } | |
524 | ||
525 | /// Synthetic type parameters are converted to another form during lowering; this allows | |
526 | /// us to track the original form they had, and is useful for error messages. | |
3dfed10e | 527 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] |
dfeec247 XL |
528 | #[derive(HashStable_Generic)] |
529 | pub enum SyntheticTyParamKind { | |
530 | ImplTrait, | |
29967ef6 XL |
531 | // Created by the `#[rustc_synthetic]` attribute. |
532 | FromAttr, | |
dfeec247 XL |
533 | } |
534 | ||
535 | /// A where-clause in a definition. | |
3dfed10e | 536 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
537 | pub struct WhereClause<'hir> { |
538 | pub predicates: &'hir [WherePredicate<'hir>], | |
74b04a01 | 539 | // Only valid if predicates aren't empty. |
dfeec247 XL |
540 | pub span: Span, |
541 | } | |
542 | ||
543 | impl WhereClause<'_> { | |
544 | pub fn span(&self) -> Option<Span> { | |
545 | if self.predicates.is_empty() { None } else { Some(self.span) } | |
546 | } | |
547 | ||
548 | /// The `WhereClause` under normal circumstances points at either the predicates or the empty | |
549 | /// space where the `where` clause should be. Only of use for diagnostic suggestions. | |
550 | pub fn span_for_predicates_or_empty_place(&self) -> Span { | |
551 | self.span | |
552 | } | |
f9f354fc XL |
553 | |
554 | /// `Span` where further predicates would be suggested, accounting for trailing commas, like | |
555 | /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas. | |
556 | pub fn tail_span_for_suggestion(&self) -> Span { | |
557 | let end = self.span_for_predicates_or_empty_place().shrink_to_hi(); | |
5869c6ff | 558 | self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end) |
f9f354fc | 559 | } |
dfeec247 XL |
560 | } |
561 | ||
562 | /// A single predicate in a where-clause. | |
3dfed10e | 563 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
564 | pub enum WherePredicate<'hir> { |
565 | /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`). | |
566 | BoundPredicate(WhereBoundPredicate<'hir>), | |
567 | /// A lifetime predicate (e.g., `'a: 'b + 'c`). | |
568 | RegionPredicate(WhereRegionPredicate<'hir>), | |
569 | /// An equality predicate (unsupported). | |
570 | EqPredicate(WhereEqPredicate<'hir>), | |
571 | } | |
572 | ||
573 | impl WherePredicate<'_> { | |
574 | pub fn span(&self) -> Span { | |
575 | match self { | |
5869c6ff XL |
576 | WherePredicate::BoundPredicate(p) => p.span, |
577 | WherePredicate::RegionPredicate(p) => p.span, | |
578 | WherePredicate::EqPredicate(p) => p.span, | |
dfeec247 XL |
579 | } |
580 | } | |
581 | } | |
582 | ||
583 | /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`). | |
3dfed10e | 584 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
585 | pub struct WhereBoundPredicate<'hir> { |
586 | pub span: Span, | |
587 | /// Any generics from a `for` binding. | |
588 | pub bound_generic_params: &'hir [GenericParam<'hir>], | |
589 | /// The type being bounded. | |
590 | pub bounded_ty: &'hir Ty<'hir>, | |
591 | /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`). | |
592 | pub bounds: GenericBounds<'hir>, | |
593 | } | |
594 | ||
595 | /// A lifetime predicate (e.g., `'a: 'b + 'c`). | |
3dfed10e | 596 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
597 | pub struct WhereRegionPredicate<'hir> { |
598 | pub span: Span, | |
599 | pub lifetime: Lifetime, | |
600 | pub bounds: GenericBounds<'hir>, | |
601 | } | |
602 | ||
603 | /// An equality predicate (e.g., `T = int`); currently unsupported. | |
3dfed10e | 604 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
605 | pub struct WhereEqPredicate<'hir> { |
606 | pub hir_id: HirId, | |
607 | pub span: Span, | |
608 | pub lhs_ty: &'hir Ty<'hir>, | |
609 | pub rhs_ty: &'hir Ty<'hir>, | |
610 | } | |
611 | ||
6a06907d | 612 | #[derive(Default, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
613 | pub struct ModuleItems { |
614 | // Use BTreeSets here so items are in the same order as in the | |
615 | // list of all items in Crate | |
6a06907d | 616 | pub items: BTreeSet<ItemId>, |
dfeec247 XL |
617 | pub trait_items: BTreeSet<TraitItemId>, |
618 | pub impl_items: BTreeSet<ImplItemId>, | |
fc512014 | 619 | pub foreign_items: BTreeSet<ForeignItemId>, |
dfeec247 XL |
620 | } |
621 | ||
622 | /// The top-level data structure that stores the entire contents of | |
623 | /// the crate currently being compiled. | |
624 | /// | |
ba9703b0 | 625 | /// For more details, see the [rustc dev guide]. |
dfeec247 | 626 | /// |
ba9703b0 | 627 | /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html |
3dfed10e | 628 | #[derive(Debug)] |
dfeec247 | 629 | pub struct Crate<'hir> { |
cdc7bbd5 | 630 | pub item: Mod<'hir>, |
dfeec247 XL |
631 | pub exported_macros: &'hir [MacroDef<'hir>], |
632 | // Attributes from non-exported macros, kept only for collecting the library feature list. | |
633 | pub non_exported_macro_attrs: &'hir [Attribute], | |
634 | ||
635 | // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates | |
636 | // over the ids in increasing order. In principle it should not | |
637 | // matter what order we visit things in, but in *practice* it | |
638 | // does, because it can affect the order in which errors are | |
5869c6ff | 639 | // detected, which in turn can make UI tests yield |
dfeec247 | 640 | // slightly different results. |
6a06907d | 641 | pub items: BTreeMap<ItemId, Item<'hir>>, |
dfeec247 XL |
642 | |
643 | pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>, | |
644 | pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>, | |
fc512014 | 645 | pub foreign_items: BTreeMap<ForeignItemId, ForeignItem<'hir>>, |
dfeec247 | 646 | pub bodies: BTreeMap<BodyId, Body<'hir>>, |
6a06907d | 647 | pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>, |
dfeec247 XL |
648 | |
649 | /// A list of the body ids written out in the order in which they | |
650 | /// appear in the crate. If you're going to process all the bodies | |
651 | /// in the crate, you should iterate over this list rather than the keys | |
652 | /// of bodies. | |
653 | pub body_ids: Vec<BodyId>, | |
654 | ||
655 | /// A list of modules written out in the order in which they | |
656 | /// appear in the crate. This includes the main crate module. | |
6a06907d | 657 | pub modules: BTreeMap<LocalDefId, ModuleItems>, |
74b04a01 XL |
658 | /// A list of proc macro HirIds, written out in the order in which |
659 | /// they are declared in the static array generated by proc_macro_harness. | |
660 | pub proc_macros: Vec<HirId>, | |
f035d41b | 661 | |
17df50a5 XL |
662 | /// Map indicating what traits are in scope for places where this |
663 | /// is relevant; generated by resolve. | |
664 | pub trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Box<[TraitCandidate]>>>, | |
6a06907d XL |
665 | |
666 | /// Collected attributes from HIR nodes. | |
667 | pub attrs: BTreeMap<HirId, &'hir [Attribute]>, | |
dfeec247 XL |
668 | } |
669 | ||
670 | impl Crate<'hir> { | |
6a06907d | 671 | pub fn item(&self, id: ItemId) -> &Item<'hir> { |
dfeec247 XL |
672 | &self.items[&id] |
673 | } | |
674 | ||
675 | pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> { | |
676 | &self.trait_items[&id] | |
677 | } | |
678 | ||
679 | pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> { | |
680 | &self.impl_items[&id] | |
681 | } | |
682 | ||
fc512014 XL |
683 | pub fn foreign_item(&self, id: ForeignItemId) -> &ForeignItem<'hir> { |
684 | &self.foreign_items[&id] | |
685 | } | |
686 | ||
dfeec247 XL |
687 | pub fn body(&self, id: BodyId) -> &Body<'hir> { |
688 | &self.bodies[&id] | |
689 | } | |
690 | } | |
691 | ||
692 | impl Crate<'_> { | |
693 | /// Visits all items in the crate in some deterministic (but | |
694 | /// unspecified) order. If you just need to process every item, | |
695 | /// but don't care about nesting, this method is the best choice. | |
696 | /// | |
697 | /// If you do care about nesting -- usually because your algorithm | |
698 | /// follows lexical scoping rules -- then you want a different | |
699 | /// approach. You should override `visit_nested_item` in your | |
700 | /// visitor and then call `intravisit::walk_crate` instead. | |
701 | pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V) | |
702 | where | |
703 | V: itemlikevisit::ItemLikeVisitor<'hir>, | |
704 | { | |
74b04a01 | 705 | for item in self.items.values() { |
dfeec247 XL |
706 | visitor.visit_item(item); |
707 | } | |
708 | ||
74b04a01 | 709 | for trait_item in self.trait_items.values() { |
dfeec247 XL |
710 | visitor.visit_trait_item(trait_item); |
711 | } | |
712 | ||
74b04a01 | 713 | for impl_item in self.impl_items.values() { |
dfeec247 XL |
714 | visitor.visit_impl_item(impl_item); |
715 | } | |
fc512014 XL |
716 | |
717 | for foreign_item in self.foreign_items.values() { | |
718 | visitor.visit_foreign_item(foreign_item); | |
719 | } | |
dfeec247 XL |
720 | } |
721 | ||
722 | /// A parallel version of `visit_all_item_likes`. | |
723 | pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V) | |
724 | where | |
725 | V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send, | |
726 | { | |
727 | parallel!( | |
728 | { | |
729 | par_for_each_in(&self.items, |(_, item)| { | |
730 | visitor.visit_item(item); | |
731 | }); | |
732 | }, | |
733 | { | |
734 | par_for_each_in(&self.trait_items, |(_, trait_item)| { | |
735 | visitor.visit_trait_item(trait_item); | |
736 | }); | |
737 | }, | |
738 | { | |
739 | par_for_each_in(&self.impl_items, |(_, impl_item)| { | |
740 | visitor.visit_impl_item(impl_item); | |
741 | }); | |
fc512014 XL |
742 | }, |
743 | { | |
744 | par_for_each_in(&self.foreign_items, |(_, foreign_item)| { | |
745 | visitor.visit_foreign_item(foreign_item); | |
746 | }); | |
dfeec247 XL |
747 | } |
748 | ); | |
749 | } | |
750 | } | |
751 | ||
752 | /// A macro definition, in this crate or imported from another. | |
753 | /// | |
754 | /// Not parsed directly, but created on macro import or `macro_rules!` expansion. | |
6a06907d | 755 | #[derive(Debug)] |
dfeec247 | 756 | pub struct MacroDef<'hir> { |
ba9703b0 | 757 | pub ident: Ident, |
dfeec247 | 758 | pub vis: Visibility<'hir>, |
6a06907d | 759 | pub def_id: LocalDefId, |
dfeec247 | 760 | pub span: Span, |
ba9703b0 | 761 | pub ast: ast::MacroDef, |
dfeec247 XL |
762 | } |
763 | ||
6a06907d XL |
764 | impl MacroDef<'_> { |
765 | #[inline] | |
766 | pub fn hir_id(&self) -> HirId { | |
767 | HirId::make_owner(self.def_id) | |
768 | } | |
769 | } | |
770 | ||
dfeec247 XL |
771 | /// A block of statements `{ .. }`, which may have a label (in this case the |
772 | /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of | |
773 | /// the `rules` being anything but `DefaultBlock`. | |
3dfed10e | 774 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
775 | pub struct Block<'hir> { |
776 | /// Statements in a block. | |
777 | pub stmts: &'hir [Stmt<'hir>], | |
778 | /// An expression at the end of the block | |
779 | /// without a semicolon, if any. | |
780 | pub expr: Option<&'hir Expr<'hir>>, | |
781 | #[stable_hasher(ignore)] | |
782 | pub hir_id: HirId, | |
783 | /// Distinguishes between `unsafe { ... }` and `{ ... }`. | |
784 | pub rules: BlockCheckMode, | |
785 | pub span: Span, | |
786 | /// If true, then there may exist `break 'a` values that aim to | |
787 | /// break out of this block early. | |
788 | /// Used by `'label: {}` blocks and by `try {}` blocks. | |
789 | pub targeted_by_break: bool, | |
790 | } | |
791 | ||
3dfed10e | 792 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
793 | pub struct Pat<'hir> { |
794 | #[stable_hasher(ignore)] | |
795 | pub hir_id: HirId, | |
796 | pub kind: PatKind<'hir>, | |
797 | pub span: Span, | |
29967ef6 XL |
798 | // Whether to use default binding modes. |
799 | // At present, this is false only for destructuring assignment. | |
800 | pub default_binding_modes: bool, | |
dfeec247 XL |
801 | } |
802 | ||
5869c6ff | 803 | impl<'hir> Pat<'hir> { |
dfeec247 | 804 | // FIXME(#19596) this is a workaround, but there should be a better way |
5869c6ff | 805 | fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool { |
dfeec247 XL |
806 | if !it(self) { |
807 | return false; | |
808 | } | |
809 | ||
810 | use PatKind::*; | |
136023e0 | 811 | match self.kind { |
dfeec247 XL |
812 | Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true, |
813 | Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it), | |
814 | Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)), | |
815 | TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)), | |
816 | Slice(before, slice, after) => { | |
136023e0 | 817 | before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it)) |
dfeec247 XL |
818 | } |
819 | } | |
820 | } | |
821 | ||
822 | /// Walk the pattern in left-to-right order, | |
823 | /// short circuiting (with `.all(..)`) if `false` is returned. | |
824 | /// | |
825 | /// Note that when visiting e.g. `Tuple(ps)`, | |
826 | /// if visiting `ps[0]` returns `false`, | |
827 | /// then `ps[1]` will not be visited. | |
5869c6ff | 828 | pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool { |
dfeec247 XL |
829 | self.walk_short_(&mut it) |
830 | } | |
831 | ||
832 | // FIXME(#19596) this is a workaround, but there should be a better way | |
5869c6ff | 833 | fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) { |
dfeec247 XL |
834 | if !it(self) { |
835 | return; | |
836 | } | |
837 | ||
838 | use PatKind::*; | |
136023e0 | 839 | match self.kind { |
dfeec247 XL |
840 | Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {} |
841 | Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it), | |
842 | Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)), | |
843 | TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)), | |
844 | Slice(before, slice, after) => { | |
136023e0 | 845 | before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it)) |
dfeec247 XL |
846 | } |
847 | } | |
848 | } | |
849 | ||
850 | /// Walk the pattern in left-to-right order. | |
851 | /// | |
852 | /// If `it(pat)` returns `false`, the children are not visited. | |
5869c6ff | 853 | pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) { |
dfeec247 XL |
854 | self.walk_(&mut it) |
855 | } | |
856 | ||
857 | /// Walk the pattern in left-to-right order. | |
858 | /// | |
859 | /// If you always want to recurse, prefer this method over `walk`. | |
860 | pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) { | |
861 | self.walk(|p| { | |
862 | it(p); | |
863 | true | |
864 | }) | |
865 | } | |
866 | } | |
867 | ||
868 | /// A single field in a struct pattern. | |
869 | /// | |
870 | /// Patterns like the fields of Foo `{ x, ref y, ref mut z }` | |
871 | /// are treated the same as` x: x, y: ref y, z: ref mut z`, | |
872 | /// except `is_shorthand` is true. | |
3dfed10e | 873 | #[derive(Debug, HashStable_Generic)] |
6a06907d | 874 | pub struct PatField<'hir> { |
dfeec247 XL |
875 | #[stable_hasher(ignore)] |
876 | pub hir_id: HirId, | |
877 | /// The identifier for the field. | |
878 | #[stable_hasher(project(name))] | |
879 | pub ident: Ident, | |
880 | /// The pattern the field is destructured to. | |
881 | pub pat: &'hir Pat<'hir>, | |
882 | pub is_shorthand: bool, | |
883 | pub span: Span, | |
884 | } | |
885 | ||
886 | /// Explicit binding annotations given in the HIR for a binding. Note | |
887 | /// that this is not the final binding *mode* that we infer after type | |
888 | /// inference. | |
3dfed10e | 889 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
890 | pub enum BindingAnnotation { |
891 | /// No binding annotation given: this means that the final binding mode | |
892 | /// will depend on whether we have skipped through a `&` reference | |
893 | /// when matching. For example, the `x` in `Some(x)` will have binding | |
894 | /// mode `None`; if you do `let Some(x) = &Some(22)`, it will | |
895 | /// ultimately be inferred to be by-reference. | |
896 | /// | |
897 | /// Note that implicit reference skipping is not implemented yet (#42640). | |
898 | Unannotated, | |
899 | ||
900 | /// Annotated with `mut x` -- could be either ref or not, similar to `None`. | |
901 | Mutable, | |
902 | ||
903 | /// Annotated as `ref`, like `ref x` | |
904 | Ref, | |
905 | ||
906 | /// Annotated as `ref mut x`. | |
907 | RefMut, | |
908 | } | |
909 | ||
3dfed10e | 910 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
911 | pub enum RangeEnd { |
912 | Included, | |
913 | Excluded, | |
914 | } | |
915 | ||
916 | impl fmt::Display for RangeEnd { | |
917 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
918 | f.write_str(match self { | |
919 | RangeEnd::Included => "..=", | |
920 | RangeEnd::Excluded => "..", | |
921 | }) | |
922 | } | |
923 | } | |
924 | ||
3dfed10e | 925 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
926 | pub enum PatKind<'hir> { |
927 | /// Represents a wildcard pattern (i.e., `_`). | |
928 | Wild, | |
929 | ||
930 | /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`. | |
931 | /// The `HirId` is the canonical ID for the variable being bound, | |
932 | /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID), | |
933 | /// which is the pattern ID of the first `x`. | |
934 | Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>), | |
935 | ||
936 | /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`). | |
937 | /// The `bool` is `true` in the presence of a `..`. | |
6a06907d | 938 | Struct(QPath<'hir>, &'hir [PatField<'hir>], bool), |
dfeec247 XL |
939 | |
940 | /// A tuple struct/variant pattern `Variant(x, y, .., z)`. | |
941 | /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position. | |
942 | /// `0 <= position <= subpats.len()` | |
136023e0 | 943 | TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>), |
dfeec247 XL |
944 | |
945 | /// An or-pattern `A | B | C`. | |
946 | /// Invariant: `pats.len() >= 2`. | |
136023e0 | 947 | Or(&'hir [Pat<'hir>]), |
dfeec247 XL |
948 | |
949 | /// A path pattern for an unit struct/variant or a (maybe-associated) constant. | |
950 | Path(QPath<'hir>), | |
951 | ||
952 | /// A tuple pattern (e.g., `(a, b)`). | |
953 | /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position. | |
954 | /// `0 <= position <= subpats.len()` | |
136023e0 | 955 | Tuple(&'hir [Pat<'hir>], Option<usize>), |
dfeec247 XL |
956 | |
957 | /// A `box` pattern. | |
958 | Box(&'hir Pat<'hir>), | |
959 | ||
960 | /// A reference pattern (e.g., `&mut (a, b)`). | |
961 | Ref(&'hir Pat<'hir>, Mutability), | |
962 | ||
963 | /// A literal. | |
964 | Lit(&'hir Expr<'hir>), | |
965 | ||
966 | /// A range pattern (e.g., `1..=2` or `1..2`). | |
967 | Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd), | |
968 | ||
969 | /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`. | |
970 | /// | |
971 | /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`. | |
972 | /// If `slice` exists, then `after` can be non-empty. | |
973 | /// | |
974 | /// The representation for e.g., `[a, b, .., c, d]` is: | |
975 | /// ``` | |
976 | /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)]) | |
977 | /// ``` | |
136023e0 | 978 | Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]), |
dfeec247 XL |
979 | } |
980 | ||
3dfed10e | 981 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
982 | pub enum BinOpKind { |
983 | /// The `+` operator (addition). | |
984 | Add, | |
985 | /// The `-` operator (subtraction). | |
986 | Sub, | |
987 | /// The `*` operator (multiplication). | |
988 | Mul, | |
989 | /// The `/` operator (division). | |
990 | Div, | |
991 | /// The `%` operator (modulus). | |
992 | Rem, | |
993 | /// The `&&` operator (logical and). | |
994 | And, | |
995 | /// The `||` operator (logical or). | |
996 | Or, | |
997 | /// The `^` operator (bitwise xor). | |
998 | BitXor, | |
999 | /// The `&` operator (bitwise and). | |
1000 | BitAnd, | |
1001 | /// The `|` operator (bitwise or). | |
1002 | BitOr, | |
1003 | /// The `<<` operator (shift left). | |
1004 | Shl, | |
1005 | /// The `>>` operator (shift right). | |
1006 | Shr, | |
1007 | /// The `==` operator (equality). | |
1008 | Eq, | |
1009 | /// The `<` operator (less than). | |
1010 | Lt, | |
1011 | /// The `<=` operator (less than or equal to). | |
1012 | Le, | |
1013 | /// The `!=` operator (not equal to). | |
1014 | Ne, | |
1015 | /// The `>=` operator (greater than or equal to). | |
1016 | Ge, | |
1017 | /// The `>` operator (greater than). | |
1018 | Gt, | |
1019 | } | |
1020 | ||
1021 | impl BinOpKind { | |
1022 | pub fn as_str(self) -> &'static str { | |
1023 | match self { | |
1024 | BinOpKind::Add => "+", | |
1025 | BinOpKind::Sub => "-", | |
1026 | BinOpKind::Mul => "*", | |
1027 | BinOpKind::Div => "/", | |
1028 | BinOpKind::Rem => "%", | |
1029 | BinOpKind::And => "&&", | |
1030 | BinOpKind::Or => "||", | |
1031 | BinOpKind::BitXor => "^", | |
1032 | BinOpKind::BitAnd => "&", | |
1033 | BinOpKind::BitOr => "|", | |
1034 | BinOpKind::Shl => "<<", | |
1035 | BinOpKind::Shr => ">>", | |
1036 | BinOpKind::Eq => "==", | |
1037 | BinOpKind::Lt => "<", | |
1038 | BinOpKind::Le => "<=", | |
1039 | BinOpKind::Ne => "!=", | |
1040 | BinOpKind::Ge => ">=", | |
1041 | BinOpKind::Gt => ">", | |
1042 | } | |
1043 | } | |
1044 | ||
1045 | pub fn is_lazy(self) -> bool { | |
29967ef6 | 1046 | matches!(self, BinOpKind::And | BinOpKind::Or) |
dfeec247 XL |
1047 | } |
1048 | ||
1049 | pub fn is_shift(self) -> bool { | |
29967ef6 | 1050 | matches!(self, BinOpKind::Shl | BinOpKind::Shr) |
dfeec247 XL |
1051 | } |
1052 | ||
1053 | pub fn is_comparison(self) -> bool { | |
1054 | match self { | |
1055 | BinOpKind::Eq | |
1056 | | BinOpKind::Lt | |
1057 | | BinOpKind::Le | |
1058 | | BinOpKind::Ne | |
1059 | | BinOpKind::Gt | |
1060 | | BinOpKind::Ge => true, | |
1061 | BinOpKind::And | |
1062 | | BinOpKind::Or | |
1063 | | BinOpKind::Add | |
1064 | | BinOpKind::Sub | |
1065 | | BinOpKind::Mul | |
1066 | | BinOpKind::Div | |
1067 | | BinOpKind::Rem | |
1068 | | BinOpKind::BitXor | |
1069 | | BinOpKind::BitAnd | |
1070 | | BinOpKind::BitOr | |
1071 | | BinOpKind::Shl | |
1072 | | BinOpKind::Shr => false, | |
1073 | } | |
1074 | } | |
1075 | ||
1076 | /// Returns `true` if the binary operator takes its arguments by value. | |
1077 | pub fn is_by_value(self) -> bool { | |
1078 | !self.is_comparison() | |
1079 | } | |
1080 | } | |
1081 | ||
1082 | impl Into<ast::BinOpKind> for BinOpKind { | |
1083 | fn into(self) -> ast::BinOpKind { | |
1084 | match self { | |
1085 | BinOpKind::Add => ast::BinOpKind::Add, | |
1086 | BinOpKind::Sub => ast::BinOpKind::Sub, | |
1087 | BinOpKind::Mul => ast::BinOpKind::Mul, | |
1088 | BinOpKind::Div => ast::BinOpKind::Div, | |
1089 | BinOpKind::Rem => ast::BinOpKind::Rem, | |
1090 | BinOpKind::And => ast::BinOpKind::And, | |
1091 | BinOpKind::Or => ast::BinOpKind::Or, | |
1092 | BinOpKind::BitXor => ast::BinOpKind::BitXor, | |
1093 | BinOpKind::BitAnd => ast::BinOpKind::BitAnd, | |
1094 | BinOpKind::BitOr => ast::BinOpKind::BitOr, | |
1095 | BinOpKind::Shl => ast::BinOpKind::Shl, | |
1096 | BinOpKind::Shr => ast::BinOpKind::Shr, | |
1097 | BinOpKind::Eq => ast::BinOpKind::Eq, | |
1098 | BinOpKind::Lt => ast::BinOpKind::Lt, | |
1099 | BinOpKind::Le => ast::BinOpKind::Le, | |
1100 | BinOpKind::Ne => ast::BinOpKind::Ne, | |
1101 | BinOpKind::Ge => ast::BinOpKind::Ge, | |
1102 | BinOpKind::Gt => ast::BinOpKind::Gt, | |
1103 | } | |
1104 | } | |
1105 | } | |
1106 | ||
1107 | pub type BinOp = Spanned<BinOpKind>; | |
1108 | ||
3dfed10e | 1109 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
1110 | pub enum UnOp { |
1111 | /// The `*` operator (deferencing). | |
6a06907d | 1112 | Deref, |
dfeec247 | 1113 | /// The `!` operator (logical negation). |
6a06907d | 1114 | Not, |
dfeec247 | 1115 | /// The `-` operator (negation). |
6a06907d | 1116 | Neg, |
dfeec247 XL |
1117 | } |
1118 | ||
1119 | impl UnOp { | |
1120 | pub fn as_str(self) -> &'static str { | |
1121 | match self { | |
6a06907d XL |
1122 | Self::Deref => "*", |
1123 | Self::Not => "!", | |
1124 | Self::Neg => "-", | |
dfeec247 XL |
1125 | } |
1126 | } | |
1127 | ||
1128 | /// Returns `true` if the unary operator takes its argument by value. | |
1129 | pub fn is_by_value(self) -> bool { | |
6a06907d | 1130 | matches!(self, Self::Neg | Self::Not) |
dfeec247 XL |
1131 | } |
1132 | } | |
1133 | ||
1134 | /// A statement. | |
3dfed10e | 1135 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
1136 | pub struct Stmt<'hir> { |
1137 | pub hir_id: HirId, | |
1138 | pub kind: StmtKind<'hir>, | |
1139 | pub span: Span, | |
1140 | } | |
1141 | ||
dfeec247 | 1142 | /// The contents of a statement. |
3dfed10e | 1143 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
1144 | pub enum StmtKind<'hir> { |
1145 | /// A local (`let`) binding. | |
1146 | Local(&'hir Local<'hir>), | |
1147 | ||
1148 | /// An item binding. | |
1149 | Item(ItemId), | |
1150 | ||
1151 | /// An expression without a trailing semi-colon (must have unit type). | |
1152 | Expr(&'hir Expr<'hir>), | |
1153 | ||
1154 | /// An expression with a trailing semi-colon (may have any type). | |
1155 | Semi(&'hir Expr<'hir>), | |
1156 | } | |
1157 | ||
dfeec247 | 1158 | /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`). |
3dfed10e | 1159 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
1160 | pub struct Local<'hir> { |
1161 | pub pat: &'hir Pat<'hir>, | |
1162 | /// Type annotation, if any (otherwise the type will be inferred). | |
1163 | pub ty: Option<&'hir Ty<'hir>>, | |
1164 | /// Initializer expression to set the value, if any. | |
1165 | pub init: Option<&'hir Expr<'hir>>, | |
1166 | pub hir_id: HirId, | |
1167 | pub span: Span, | |
dfeec247 XL |
1168 | /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop |
1169 | /// desugaring. Otherwise will be `Normal`. | |
1170 | pub source: LocalSource, | |
1171 | } | |
1172 | ||
1173 | /// Represents a single arm of a `match` expression, e.g. | |
1174 | /// `<pat> (if <guard>) => <body>`. | |
3dfed10e | 1175 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
1176 | pub struct Arm<'hir> { |
1177 | #[stable_hasher(ignore)] | |
1178 | pub hir_id: HirId, | |
1179 | pub span: Span, | |
dfeec247 XL |
1180 | /// If this pattern and the optional guard matches, then `body` is evaluated. |
1181 | pub pat: &'hir Pat<'hir>, | |
1182 | /// Optional guard clause. | |
1183 | pub guard: Option<Guard<'hir>>, | |
1184 | /// The expression the arm evaluates to if this arm matches. | |
1185 | pub body: &'hir Expr<'hir>, | |
1186 | } | |
1187 | ||
3dfed10e | 1188 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
1189 | pub enum Guard<'hir> { |
1190 | If(&'hir Expr<'hir>), | |
fc512014 | 1191 | IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>), |
dfeec247 XL |
1192 | } |
1193 | ||
3dfed10e | 1194 | #[derive(Debug, HashStable_Generic)] |
6a06907d | 1195 | pub struct ExprField<'hir> { |
dfeec247 XL |
1196 | #[stable_hasher(ignore)] |
1197 | pub hir_id: HirId, | |
1198 | pub ident: Ident, | |
1199 | pub expr: &'hir Expr<'hir>, | |
1200 | pub span: Span, | |
1201 | pub is_shorthand: bool, | |
1202 | } | |
1203 | ||
3dfed10e | 1204 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
1205 | pub enum BlockCheckMode { |
1206 | DefaultBlock, | |
1207 | UnsafeBlock(UnsafeSource), | |
dfeec247 XL |
1208 | } |
1209 | ||
3dfed10e | 1210 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
1211 | pub enum UnsafeSource { |
1212 | CompilerGenerated, | |
1213 | UserProvided, | |
1214 | } | |
1215 | ||
3dfed10e | 1216 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)] |
dfeec247 XL |
1217 | pub struct BodyId { |
1218 | pub hir_id: HirId, | |
1219 | } | |
1220 | ||
1221 | /// The body of a function, closure, or constant value. In the case of | |
1222 | /// a function, the body contains not only the function body itself | |
1223 | /// (which is an expression), but also the argument patterns, since | |
1224 | /// those are something that the caller doesn't really care about. | |
1225 | /// | |
1226 | /// # Examples | |
1227 | /// | |
1228 | /// ``` | |
1229 | /// fn foo((x, y): (u32, u32)) -> u32 { | |
1230 | /// x + y | |
1231 | /// } | |
1232 | /// ``` | |
1233 | /// | |
1234 | /// Here, the `Body` associated with `foo()` would contain: | |
1235 | /// | |
1236 | /// - an `params` array containing the `(x, y)` pattern | |
1237 | /// - a `value` containing the `x + y` expression (maybe wrapped in a block) | |
1238 | /// - `generator_kind` would be `None` | |
1239 | /// | |
1240 | /// All bodies have an **owner**, which can be accessed via the HIR | |
1241 | /// map using `body_owner_def_id()`. | |
3dfed10e | 1242 | #[derive(Debug)] |
dfeec247 XL |
1243 | pub struct Body<'hir> { |
1244 | pub params: &'hir [Param<'hir>], | |
1245 | pub value: Expr<'hir>, | |
1246 | pub generator_kind: Option<GeneratorKind>, | |
1247 | } | |
1248 | ||
1249 | impl Body<'hir> { | |
1250 | pub fn id(&self) -> BodyId { | |
1251 | BodyId { hir_id: self.value.hir_id } | |
1252 | } | |
1253 | ||
1254 | pub fn generator_kind(&self) -> Option<GeneratorKind> { | |
1255 | self.generator_kind | |
1256 | } | |
1257 | } | |
1258 | ||
1259 | /// The type of source expression that caused this generator to be created. | |
6a06907d XL |
1260 | #[derive( |
1261 | Clone, | |
1262 | PartialEq, | |
1263 | PartialOrd, | |
1264 | Eq, | |
1265 | Hash, | |
1266 | HashStable_Generic, | |
1267 | Encodable, | |
1268 | Decodable, | |
1269 | Debug, | |
1270 | Copy | |
1271 | )] | |
dfeec247 XL |
1272 | pub enum GeneratorKind { |
1273 | /// An explicit `async` block or the body of an async function. | |
1274 | Async(AsyncGeneratorKind), | |
1275 | ||
1276 | /// A generator literal created via a `yield` inside a closure. | |
1277 | Gen, | |
1278 | } | |
1279 | ||
1280 | impl fmt::Display for GeneratorKind { | |
1281 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
1282 | match self { | |
1283 | GeneratorKind::Async(k) => fmt::Display::fmt(k, f), | |
1284 | GeneratorKind::Gen => f.write_str("generator"), | |
1285 | } | |
1286 | } | |
1287 | } | |
1288 | ||
6a06907d XL |
1289 | impl GeneratorKind { |
1290 | pub fn descr(&self) -> &'static str { | |
1291 | match self { | |
1292 | GeneratorKind::Async(ask) => ask.descr(), | |
1293 | GeneratorKind::Gen => "generator", | |
1294 | } | |
1295 | } | |
1296 | } | |
1297 | ||
dfeec247 XL |
1298 | /// In the case of a generator created as part of an async construct, |
1299 | /// which kind of async construct caused it to be created? | |
1300 | /// | |
1301 | /// This helps error messages but is also used to drive coercions in | |
1302 | /// type-checking (see #60424). | |
6a06907d XL |
1303 | #[derive( |
1304 | Clone, | |
1305 | PartialEq, | |
1306 | PartialOrd, | |
1307 | Eq, | |
1308 | Hash, | |
1309 | HashStable_Generic, | |
1310 | Encodable, | |
1311 | Decodable, | |
1312 | Debug, | |
1313 | Copy | |
1314 | )] | |
dfeec247 XL |
1315 | pub enum AsyncGeneratorKind { |
1316 | /// An explicit `async` block written by the user. | |
1317 | Block, | |
1318 | ||
1319 | /// An explicit `async` block written by the user. | |
1320 | Closure, | |
1321 | ||
1322 | /// The `async` block generated as the body of an async function. | |
1323 | Fn, | |
1324 | } | |
1325 | ||
1326 | impl fmt::Display for AsyncGeneratorKind { | |
1327 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
1328 | f.write_str(match self { | |
1329 | AsyncGeneratorKind::Block => "`async` block", | |
1330 | AsyncGeneratorKind::Closure => "`async` closure body", | |
1331 | AsyncGeneratorKind::Fn => "`async fn` body", | |
1332 | }) | |
1333 | } | |
1334 | } | |
1335 | ||
6a06907d XL |
1336 | impl AsyncGeneratorKind { |
1337 | pub fn descr(&self) -> &'static str { | |
1338 | match self { | |
1339 | AsyncGeneratorKind::Block => "`async` block", | |
1340 | AsyncGeneratorKind::Closure => "`async` closure body", | |
1341 | AsyncGeneratorKind::Fn => "`async fn` body", | |
1342 | } | |
1343 | } | |
1344 | } | |
1345 | ||
dfeec247 XL |
1346 | #[derive(Copy, Clone, Debug)] |
1347 | pub enum BodyOwnerKind { | |
1348 | /// Functions and methods. | |
1349 | Fn, | |
1350 | ||
1351 | /// Closures | |
1352 | Closure, | |
1353 | ||
1354 | /// Constants and associated constants. | |
1355 | Const, | |
1356 | ||
1357 | /// Initializer of a `static` item. | |
1358 | Static(Mutability), | |
1359 | } | |
1360 | ||
1361 | impl BodyOwnerKind { | |
1362 | pub fn is_fn_or_closure(self) -> bool { | |
1363 | match self { | |
1364 | BodyOwnerKind::Fn | BodyOwnerKind::Closure => true, | |
1365 | BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false, | |
1366 | } | |
1367 | } | |
1368 | } | |
1369 | ||
f9f354fc XL |
1370 | /// The kind of an item that requires const-checking. |
1371 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
1372 | pub enum ConstContext { | |
1373 | /// A `const fn`. | |
1374 | ConstFn, | |
1375 | ||
1376 | /// A `static` or `static mut`. | |
1377 | Static(Mutability), | |
1378 | ||
1379 | /// A `const`, associated `const`, or other const context. | |
1380 | /// | |
1381 | /// Other contexts include: | |
1382 | /// - Array length expressions | |
1383 | /// - Enum discriminants | |
1384 | /// - Const generics | |
1385 | /// | |
1386 | /// For the most part, other contexts are treated just like a regular `const`, so they are | |
1387 | /// lumped into the same category. | |
1388 | Const, | |
1389 | } | |
1390 | ||
1391 | impl ConstContext { | |
1392 | /// A description of this const context that can appear between backticks in an error message. | |
1393 | /// | |
1394 | /// E.g. `const` or `static mut`. | |
1395 | pub fn keyword_name(self) -> &'static str { | |
1396 | match self { | |
1397 | Self::Const => "const", | |
1398 | Self::Static(Mutability::Not) => "static", | |
1399 | Self::Static(Mutability::Mut) => "static mut", | |
1400 | Self::ConstFn => "const fn", | |
1401 | } | |
1402 | } | |
1403 | } | |
1404 | ||
1405 | /// A colloquial, trivially pluralizable description of this const context for use in error | |
1406 | /// messages. | |
1407 | impl fmt::Display for ConstContext { | |
1408 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
1409 | match *self { | |
1410 | Self::Const => write!(f, "constant"), | |
1411 | Self::Static(_) => write!(f, "static"), | |
1412 | Self::ConstFn => write!(f, "constant function"), | |
1413 | } | |
1414 | } | |
1415 | } | |
1416 | ||
dfeec247 XL |
1417 | /// A literal. |
1418 | pub type Lit = Spanned<LitKind>; | |
1419 | ||
1420 | /// A constant (expression) that's not an item or associated item, | |
1421 | /// but needs its own `DefId` for type-checking, const-eval, etc. | |
1422 | /// These are usually found nested inside types (e.g., array lengths) | |
1423 | /// or expressions (e.g., repeat counts), and also used to define | |
1424 | /// explicit discriminant values for enum variants. | |
3dfed10e | 1425 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
1426 | pub struct AnonConst { |
1427 | pub hir_id: HirId, | |
1428 | pub body: BodyId, | |
1429 | } | |
1430 | ||
1431 | /// An expression. | |
3dfed10e | 1432 | #[derive(Debug)] |
dfeec247 XL |
1433 | pub struct Expr<'hir> { |
1434 | pub hir_id: HirId, | |
1435 | pub kind: ExprKind<'hir>, | |
dfeec247 XL |
1436 | pub span: Span, |
1437 | } | |
1438 | ||
dfeec247 XL |
1439 | impl Expr<'_> { |
1440 | pub fn precedence(&self) -> ExprPrecedence { | |
1441 | match self.kind { | |
1442 | ExprKind::Box(_) => ExprPrecedence::Box, | |
29967ef6 | 1443 | ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock, |
dfeec247 XL |
1444 | ExprKind::Array(_) => ExprPrecedence::Array, |
1445 | ExprKind::Call(..) => ExprPrecedence::Call, | |
1446 | ExprKind::MethodCall(..) => ExprPrecedence::MethodCall, | |
1447 | ExprKind::Tup(_) => ExprPrecedence::Tup, | |
1448 | ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()), | |
1449 | ExprKind::Unary(..) => ExprPrecedence::Unary, | |
1450 | ExprKind::Lit(_) => ExprPrecedence::Lit, | |
1451 | ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast, | |
1452 | ExprKind::DropTemps(ref expr, ..) => expr.precedence(), | |
5869c6ff | 1453 | ExprKind::If(..) => ExprPrecedence::If, |
dfeec247 XL |
1454 | ExprKind::Loop(..) => ExprPrecedence::Loop, |
1455 | ExprKind::Match(..) => ExprPrecedence::Match, | |
1456 | ExprKind::Closure(..) => ExprPrecedence::Closure, | |
1457 | ExprKind::Block(..) => ExprPrecedence::Block, | |
1458 | ExprKind::Assign(..) => ExprPrecedence::Assign, | |
1459 | ExprKind::AssignOp(..) => ExprPrecedence::AssignOp, | |
1460 | ExprKind::Field(..) => ExprPrecedence::Field, | |
1461 | ExprKind::Index(..) => ExprPrecedence::Index, | |
1462 | ExprKind::Path(..) => ExprPrecedence::Path, | |
1463 | ExprKind::AddrOf(..) => ExprPrecedence::AddrOf, | |
1464 | ExprKind::Break(..) => ExprPrecedence::Break, | |
1465 | ExprKind::Continue(..) => ExprPrecedence::Continue, | |
1466 | ExprKind::Ret(..) => ExprPrecedence::Ret, | |
f9f354fc | 1467 | ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm, |
ba9703b0 | 1468 | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm, |
dfeec247 XL |
1469 | ExprKind::Struct(..) => ExprPrecedence::Struct, |
1470 | ExprKind::Repeat(..) => ExprPrecedence::Repeat, | |
1471 | ExprKind::Yield(..) => ExprPrecedence::Yield, | |
1472 | ExprKind::Err => ExprPrecedence::Err, | |
1473 | } | |
1474 | } | |
1475 | ||
1476 | // Whether this looks like a place expr, without checking for deref | |
1477 | // adjustments. | |
1478 | // This will return `true` in some potentially surprising cases such as | |
1479 | // `CONSTANT.field`. | |
1480 | pub fn is_syntactic_place_expr(&self) -> bool { | |
1481 | self.is_place_expr(|_| true) | |
1482 | } | |
1483 | ||
3dfed10e XL |
1484 | /// Whether this is a place expression. |
1485 | /// | |
1486 | /// `allow_projections_from` should return `true` if indexing a field or index expression based | |
1487 | /// on the given expression should be considered a place expression. | |
dfeec247 XL |
1488 | pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool { |
1489 | match self.kind { | |
29967ef6 XL |
1490 | ExprKind::Path(QPath::Resolved(_, ref path)) => { |
1491 | matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err) | |
1492 | } | |
dfeec247 XL |
1493 | |
1494 | // Type ascription inherits its place expression kind from its | |
1495 | // operand. See: | |
1496 | // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries | |
1497 | ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from), | |
1498 | ||
6a06907d | 1499 | ExprKind::Unary(UnOp::Deref, _) => true, |
dfeec247 XL |
1500 | |
1501 | ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => { | |
1502 | allow_projections_from(base) || base.is_place_expr(allow_projections_from) | |
1503 | } | |
1504 | ||
3dfed10e XL |
1505 | // Lang item paths cannot currently be local variables or statics. |
1506 | ExprKind::Path(QPath::LangItem(..)) => false, | |
1507 | ||
dfeec247 XL |
1508 | // Partially qualified paths in expressions can only legally |
1509 | // refer to associated items which are always rvalues. | |
1510 | ExprKind::Path(QPath::TypeRelative(..)) | |
1511 | | ExprKind::Call(..) | |
1512 | | ExprKind::MethodCall(..) | |
1513 | | ExprKind::Struct(..) | |
1514 | | ExprKind::Tup(..) | |
5869c6ff | 1515 | | ExprKind::If(..) |
dfeec247 XL |
1516 | | ExprKind::Match(..) |
1517 | | ExprKind::Closure(..) | |
1518 | | ExprKind::Block(..) | |
1519 | | ExprKind::Repeat(..) | |
1520 | | ExprKind::Array(..) | |
1521 | | ExprKind::Break(..) | |
1522 | | ExprKind::Continue(..) | |
1523 | | ExprKind::Ret(..) | |
1524 | | ExprKind::Loop(..) | |
1525 | | ExprKind::Assign(..) | |
f9f354fc | 1526 | | ExprKind::InlineAsm(..) |
ba9703b0 | 1527 | | ExprKind::LlvmInlineAsm(..) |
dfeec247 XL |
1528 | | ExprKind::AssignOp(..) |
1529 | | ExprKind::Lit(_) | |
29967ef6 | 1530 | | ExprKind::ConstBlock(..) |
dfeec247 XL |
1531 | | ExprKind::Unary(..) |
1532 | | ExprKind::Box(..) | |
1533 | | ExprKind::AddrOf(..) | |
1534 | | ExprKind::Binary(..) | |
1535 | | ExprKind::Yield(..) | |
1536 | | ExprKind::Cast(..) | |
1537 | | ExprKind::DropTemps(..) | |
1538 | | ExprKind::Err => false, | |
1539 | } | |
1540 | } | |
1541 | ||
1542 | /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps` | |
1543 | /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically | |
1544 | /// silent, only signaling the ownership system. By doing this, suggestions that check the | |
1545 | /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps` | |
1546 | /// beyond remembering to call this function before doing analysis on it. | |
1547 | pub fn peel_drop_temps(&self) -> &Self { | |
1548 | let mut expr = self; | |
1549 | while let ExprKind::DropTemps(inner) = &expr.kind { | |
1550 | expr = inner; | |
1551 | } | |
1552 | expr | |
1553 | } | |
6a06907d XL |
1554 | |
1555 | pub fn peel_blocks(&self) -> &Self { | |
1556 | let mut expr = self; | |
1557 | while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind { | |
1558 | expr = inner; | |
1559 | } | |
1560 | expr | |
1561 | } | |
1562 | ||
1563 | pub fn can_have_side_effects(&self) -> bool { | |
1564 | match self.peel_drop_temps().kind { | |
1565 | ExprKind::Path(_) | ExprKind::Lit(_) => false, | |
1566 | ExprKind::Type(base, _) | |
1567 | | ExprKind::Unary(_, base) | |
1568 | | ExprKind::Field(base, _) | |
1569 | | ExprKind::Index(base, _) | |
1570 | | ExprKind::AddrOf(.., base) | |
1571 | | ExprKind::Cast(base, _) => { | |
1572 | // This isn't exactly true for `Index` and all `Unnary`, but we are using this | |
1573 | // method exclusively for diagnostics and there's a *cultural* pressure against | |
1574 | // them being used only for its side-effects. | |
1575 | base.can_have_side_effects() | |
1576 | } | |
1577 | ExprKind::Struct(_, fields, init) => fields | |
1578 | .iter() | |
1579 | .map(|field| field.expr) | |
1580 | .chain(init.into_iter()) | |
1581 | .all(|e| e.can_have_side_effects()), | |
1582 | ||
1583 | ExprKind::Array(args) | |
1584 | | ExprKind::Tup(args) | |
1585 | | ExprKind::Call( | |
1586 | Expr { | |
1587 | kind: | |
1588 | ExprKind::Path(QPath::Resolved( | |
1589 | None, | |
1590 | Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. }, | |
1591 | )), | |
1592 | .. | |
1593 | }, | |
1594 | args, | |
1595 | ) => args.iter().all(|arg| arg.can_have_side_effects()), | |
1596 | ExprKind::If(..) | |
1597 | | ExprKind::Match(..) | |
1598 | | ExprKind::MethodCall(..) | |
1599 | | ExprKind::Call(..) | |
1600 | | ExprKind::Closure(..) | |
1601 | | ExprKind::Block(..) | |
1602 | | ExprKind::Repeat(..) | |
1603 | | ExprKind::Break(..) | |
1604 | | ExprKind::Continue(..) | |
1605 | | ExprKind::Ret(..) | |
1606 | | ExprKind::Loop(..) | |
1607 | | ExprKind::Assign(..) | |
1608 | | ExprKind::InlineAsm(..) | |
1609 | | ExprKind::LlvmInlineAsm(..) | |
1610 | | ExprKind::AssignOp(..) | |
1611 | | ExprKind::ConstBlock(..) | |
1612 | | ExprKind::Box(..) | |
1613 | | ExprKind::Binary(..) | |
1614 | | ExprKind::Yield(..) | |
1615 | | ExprKind::DropTemps(..) | |
1616 | | ExprKind::Err => true, | |
1617 | } | |
1618 | } | |
dfeec247 XL |
1619 | } |
1620 | ||
dfeec247 XL |
1621 | /// Checks if the specified expression is a built-in range literal. |
1622 | /// (See: `LoweringContext::lower_expr()`). | |
3dfed10e | 1623 | pub fn is_range_literal(expr: &Expr<'_>) -> bool { |
dfeec247 XL |
1624 | match expr.kind { |
1625 | // All built-in range literals but `..=` and `..` desugar to `Struct`s. | |
3dfed10e XL |
1626 | ExprKind::Struct(ref qpath, _, _) => matches!( |
1627 | **qpath, | |
1628 | QPath::LangItem( | |
1629 | LangItem::Range | |
5869c6ff XL |
1630 | | LangItem::RangeTo |
1631 | | LangItem::RangeFrom | |
1632 | | LangItem::RangeFull | |
1633 | | LangItem::RangeToInclusive, | |
3dfed10e XL |
1634 | _, |
1635 | ) | |
1636 | ), | |
dfeec247 XL |
1637 | |
1638 | // `..=` desugars into `::std::ops::RangeInclusive::new(...)`. | |
1639 | ExprKind::Call(ref func, _) => { | |
3dfed10e | 1640 | matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _))) |
dfeec247 XL |
1641 | } |
1642 | ||
3dfed10e | 1643 | _ => false, |
dfeec247 | 1644 | } |
dfeec247 XL |
1645 | } |
1646 | ||
3dfed10e | 1647 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
1648 | pub enum ExprKind<'hir> { |
1649 | /// A `box x` expression. | |
1650 | Box(&'hir Expr<'hir>), | |
29967ef6 XL |
1651 | /// Allow anonymous constants from an inline `const` block |
1652 | ConstBlock(AnonConst), | |
dfeec247 XL |
1653 | /// An array (e.g., `[a, b, c, d]`). |
1654 | Array(&'hir [Expr<'hir>]), | |
1655 | /// A function call. | |
1656 | /// | |
1657 | /// The first field resolves to the function itself (usually an `ExprKind::Path`), | |
1658 | /// and the second field is the list of arguments. | |
1659 | /// This also represents calling the constructor of | |
1660 | /// tuple-like ADTs such as tuple structs and enum variants. | |
1661 | Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]), | |
1662 | /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`). | |
1663 | /// | |
1664 | /// The `PathSegment`/`Span` represent the method name and its generic arguments | |
1665 | /// (within the angle brackets). | |
1666 | /// The first element of the vector of `Expr`s is the expression that evaluates | |
1667 | /// to the object on which the method is being called on (the receiver), | |
1668 | /// and the remaining elements are the rest of the arguments. | |
1669 | /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as | |
1670 | /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`. | |
f035d41b XL |
1671 | /// The final `Span` represents the span of the function and arguments |
1672 | /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)` | |
dfeec247 XL |
1673 | /// |
1674 | /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with | |
1675 | /// the `hir_id` of the `MethodCall` node itself. | |
1676 | /// | |
3dfed10e | 1677 | /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id |
f035d41b | 1678 | MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span), |
dfeec247 XL |
1679 | /// A tuple (e.g., `(a, b, c, d)`). |
1680 | Tup(&'hir [Expr<'hir>]), | |
1681 | /// A binary operation (e.g., `a + b`, `a * b`). | |
1682 | Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>), | |
1683 | /// A unary operation (e.g., `!x`, `*x`). | |
1684 | Unary(UnOp, &'hir Expr<'hir>), | |
1685 | /// A literal (e.g., `1`, `"foo"`). | |
1686 | Lit(Lit), | |
1687 | /// A cast (e.g., `foo as f64`). | |
1688 | Cast(&'hir Expr<'hir>, &'hir Ty<'hir>), | |
1689 | /// A type reference (e.g., `Foo`). | |
1690 | Type(&'hir Expr<'hir>, &'hir Ty<'hir>), | |
1691 | /// Wraps the expression in a terminating scope. | |
1692 | /// This makes it semantically equivalent to `{ let _t = expr; _t }`. | |
1693 | /// | |
1694 | /// This construct only exists to tweak the drop order in HIR lowering. | |
1695 | /// An example of that is the desugaring of `for` loops. | |
1696 | DropTemps(&'hir Expr<'hir>), | |
5869c6ff XL |
1697 | /// An `if` block, with an optional else block. |
1698 | /// | |
1699 | /// I.e., `if <expr> { <expr> } else { <expr> }`. | |
1700 | If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>), | |
dfeec247 XL |
1701 | /// A conditionless loop (can be exited with `break`, `continue`, or `return`). |
1702 | /// | |
1703 | /// I.e., `'label: loop { <block> }`. | |
5869c6ff XL |
1704 | /// |
1705 | /// The `Span` is the loop header (`for x in y`/`while let pat = expr`). | |
1706 | Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span), | |
dfeec247 XL |
1707 | /// A `match` block, with a source that indicates whether or not it is |
1708 | /// the result of a desugaring, and if so, which kind. | |
1709 | Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource), | |
1710 | /// A closure (e.g., `move |a, b, c| {a + b + c}`). | |
1711 | /// | |
1712 | /// The `Span` is the argument block `|...|`. | |
1713 | /// | |
1714 | /// This may also be a generator literal or an `async block` as indicated by the | |
1715 | /// `Option<Movability>`. | |
1716 | Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>), | |
1717 | /// A block (e.g., `'label: { ... }`). | |
1718 | Block(&'hir Block<'hir>, Option<Label>), | |
1719 | ||
1720 | /// An assignment (e.g., `a = foo()`). | |
1721 | Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span), | |
1722 | /// An assignment with an operator. | |
1723 | /// | |
1724 | /// E.g., `a += 1`. | |
1725 | AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>), | |
1726 | /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field. | |
1727 | Field(&'hir Expr<'hir>, Ident), | |
1728 | /// An indexing operation (`foo[2]`). | |
1729 | Index(&'hir Expr<'hir>, &'hir Expr<'hir>), | |
1730 | ||
1731 | /// Path to a definition, possibly containing lifetime or type parameters. | |
1732 | Path(QPath<'hir>), | |
1733 | ||
1734 | /// A referencing operation (i.e., `&a` or `&mut a`). | |
1735 | AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>), | |
1736 | /// A `break`, with an optional label to break. | |
1737 | Break(Destination, Option<&'hir Expr<'hir>>), | |
1738 | /// A `continue`, with an optional label. | |
1739 | Continue(Destination), | |
1740 | /// A `return`, with an optional value to be returned. | |
1741 | Ret(Option<&'hir Expr<'hir>>), | |
1742 | ||
f9f354fc XL |
1743 | /// Inline assembly (from `asm!`), with its outputs and inputs. |
1744 | InlineAsm(&'hir InlineAsm<'hir>), | |
ba9703b0 XL |
1745 | /// Inline assembly (from `llvm_asm!`), with its outputs and inputs. |
1746 | LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>), | |
dfeec247 XL |
1747 | |
1748 | /// A struct or struct-like variant literal expression. | |
1749 | /// | |
1750 | /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`, | |
1751 | /// where `base` is the `Option<Expr>`. | |
6a06907d | 1752 | Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>), |
dfeec247 XL |
1753 | |
1754 | /// An array literal constructed from one repeated element. | |
1755 | /// | |
1756 | /// E.g., `[1; 5]`. The first expression is the element | |
1757 | /// to be repeated; the second is the number of times to repeat it. | |
1758 | Repeat(&'hir Expr<'hir>, AnonConst), | |
1759 | ||
1760 | /// A suspension point for generators (i.e., `yield <expr>`). | |
1761 | Yield(&'hir Expr<'hir>, YieldSource), | |
1762 | ||
1763 | /// A placeholder for an expression that wasn't syntactically well formed in some way. | |
1764 | Err, | |
1765 | } | |
1766 | ||
1767 | /// Represents an optionally `Self`-qualified value/type path or associated extension. | |
1768 | /// | |
1769 | /// To resolve the path to a `DefId`, call [`qpath_res`]. | |
1770 | /// | |
3dfed10e XL |
1771 | /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res |
1772 | #[derive(Debug, HashStable_Generic)] | |
dfeec247 XL |
1773 | pub enum QPath<'hir> { |
1774 | /// Path to a definition, optionally "fully-qualified" with a `Self` | |
1775 | /// type, if the path points to an associated item in a trait. | |
1776 | /// | |
1777 | /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`, | |
1778 | /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`, | |
1779 | /// even though they both have the same two-segment `Clone::clone` `Path`. | |
1780 | Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>), | |
1781 | ||
1782 | /// Type-related paths (e.g., `<T>::default` or `<T>::Output`). | |
1783 | /// Will be resolved by type-checking to an associated item. | |
1784 | /// | |
1785 | /// UFCS source paths can desugar into this, with `Vec::new` turning into | |
1786 | /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`, | |
1787 | /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`. | |
1788 | TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>), | |
3dfed10e XL |
1789 | |
1790 | /// Reference to a `#[lang = "foo"]` item. | |
1791 | LangItem(LangItem, Span), | |
1792 | } | |
1793 | ||
1794 | impl<'hir> QPath<'hir> { | |
1795 | /// Returns the span of this `QPath`. | |
1796 | pub fn span(&self) -> Span { | |
1797 | match *self { | |
1798 | QPath::Resolved(_, path) => path.span, | |
6a06907d | 1799 | QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span), |
3dfed10e XL |
1800 | QPath::LangItem(_, span) => span, |
1801 | } | |
1802 | } | |
1803 | ||
1804 | /// Returns the span of the qself of this `QPath`. For example, `()` in | |
1805 | /// `<() as Trait>::method`. | |
1806 | pub fn qself_span(&self) -> Span { | |
1807 | match *self { | |
1808 | QPath::Resolved(_, path) => path.span, | |
1809 | QPath::TypeRelative(qself, _) => qself.span, | |
1810 | QPath::LangItem(_, span) => span, | |
1811 | } | |
1812 | } | |
1813 | ||
1814 | /// Returns the span of the last segment of this `QPath`. For example, `method` in | |
1815 | /// `<() as Trait>::method`. | |
1816 | pub fn last_segment_span(&self) -> Span { | |
1817 | match *self { | |
1818 | QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span, | |
1819 | QPath::TypeRelative(_, segment) => segment.ident.span, | |
1820 | QPath::LangItem(_, span) => span, | |
1821 | } | |
1822 | } | |
dfeec247 XL |
1823 | } |
1824 | ||
1825 | /// Hints at the original code for a let statement. | |
3dfed10e | 1826 | #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
1827 | pub enum LocalSource { |
1828 | /// A `match _ { .. }`. | |
1829 | Normal, | |
1830 | /// A desugared `for _ in _ { .. }` loop. | |
1831 | ForLoopDesugar, | |
1832 | /// When lowering async functions, we create locals within the `async move` so that | |
1833 | /// all parameters are dropped after the future is polled. | |
1834 | /// | |
1835 | /// ```ignore (pseudo-Rust) | |
1836 | /// async fn foo(<pattern> @ x: Type) { | |
1837 | /// async move { | |
1838 | /// let <pattern> = x; | |
1839 | /// } | |
1840 | /// } | |
1841 | /// ``` | |
1842 | AsyncFn, | |
1843 | /// A desugared `<expr>.await`. | |
1844 | AwaitDesugar, | |
29967ef6 XL |
1845 | /// A desugared `expr = expr`, where the LHS is a tuple, struct or array. |
1846 | /// The span is that of the `=` sign. | |
1847 | AssignDesugar(Span), | |
dfeec247 XL |
1848 | } |
1849 | ||
1850 | /// Hints at the original code for a `match _ { .. }`. | |
3dfed10e | 1851 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)] |
dfeec247 XL |
1852 | #[derive(HashStable_Generic)] |
1853 | pub enum MatchSource { | |
1854 | /// A `match _ { .. }`. | |
1855 | Normal, | |
dfeec247 XL |
1856 | /// An `if let _ = _ { .. }` (optionally with `else { .. }`). |
1857 | IfLetDesugar { contains_else_clause: bool }, | |
fc512014 XL |
1858 | /// An `if let _ = _ => { .. }` match guard. |
1859 | IfLetGuardDesugar, | |
dfeec247 XL |
1860 | /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`). |
1861 | WhileDesugar, | |
1862 | /// A `while let _ = _ { .. }` (which was desugared to a | |
1863 | /// `loop { match _ { .. } }`). | |
1864 | WhileLetDesugar, | |
1865 | /// A desugared `for _ in _ { .. }` loop. | |
1866 | ForLoopDesugar, | |
1867 | /// A desugared `?` operator. | |
1868 | TryDesugar, | |
1869 | /// A desugared `<expr>.await`. | |
1870 | AwaitDesugar, | |
1871 | } | |
1872 | ||
1873 | impl MatchSource { | |
1874 | pub fn name(self) -> &'static str { | |
1875 | use MatchSource::*; | |
1876 | match self { | |
1877 | Normal => "match", | |
5869c6ff | 1878 | IfLetDesugar { .. } | IfLetGuardDesugar => "if", |
dfeec247 XL |
1879 | WhileDesugar | WhileLetDesugar => "while", |
1880 | ForLoopDesugar => "for", | |
1881 | TryDesugar => "?", | |
1882 | AwaitDesugar => ".await", | |
1883 | } | |
1884 | } | |
1885 | } | |
1886 | ||
1887 | /// The loop type that yielded an `ExprKind::Loop`. | |
3dfed10e | 1888 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
1889 | pub enum LoopSource { |
1890 | /// A `loop { .. }` loop. | |
1891 | Loop, | |
1892 | /// A `while _ { .. }` loop. | |
1893 | While, | |
1894 | /// A `while let _ = _ { .. }` loop. | |
1895 | WhileLet, | |
1896 | /// A `for _ in _ { .. }` loop. | |
1897 | ForLoop, | |
1898 | } | |
1899 | ||
1900 | impl LoopSource { | |
1901 | pub fn name(self) -> &'static str { | |
1902 | match self { | |
1903 | LoopSource::Loop => "loop", | |
1904 | LoopSource::While | LoopSource::WhileLet => "while", | |
1905 | LoopSource::ForLoop => "for", | |
1906 | } | |
1907 | } | |
1908 | } | |
1909 | ||
3dfed10e | 1910 | #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
1911 | pub enum LoopIdError { |
1912 | OutsideLoopScope, | |
1913 | UnlabeledCfInWhileCondition, | |
1914 | UnresolvedLabel, | |
1915 | } | |
1916 | ||
1917 | impl fmt::Display for LoopIdError { | |
1918 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
1919 | f.write_str(match self { | |
1920 | LoopIdError::OutsideLoopScope => "not inside loop scope", | |
1921 | LoopIdError::UnlabeledCfInWhileCondition => { | |
1922 | "unlabeled control flow (break or continue) in while condition" | |
1923 | } | |
1924 | LoopIdError::UnresolvedLabel => "label not found", | |
1925 | }) | |
1926 | } | |
1927 | } | |
1928 | ||
3dfed10e | 1929 | #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
1930 | pub struct Destination { |
1931 | // This is `Some(_)` iff there is an explicit user-specified `label | |
1932 | pub label: Option<Label>, | |
1933 | ||
1934 | // These errors are caught and then reported during the diagnostics pass in | |
1935 | // librustc_passes/loops.rs | |
1936 | pub target_id: Result<HirId, LoopIdError>, | |
1937 | } | |
1938 | ||
1939 | /// The yield kind that caused an `ExprKind::Yield`. | |
3dfed10e | 1940 | #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)] |
dfeec247 XL |
1941 | pub enum YieldSource { |
1942 | /// An `<expr>.await`. | |
ba9703b0 | 1943 | Await { expr: Option<HirId> }, |
dfeec247 XL |
1944 | /// A plain `yield`. |
1945 | Yield, | |
1946 | } | |
1947 | ||
ba9703b0 XL |
1948 | impl YieldSource { |
1949 | pub fn is_await(&self) -> bool { | |
1950 | match self { | |
1951 | YieldSource::Await { .. } => true, | |
1952 | YieldSource::Yield => false, | |
1953 | } | |
1954 | } | |
1955 | } | |
1956 | ||
dfeec247 XL |
1957 | impl fmt::Display for YieldSource { |
1958 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
1959 | f.write_str(match self { | |
ba9703b0 | 1960 | YieldSource::Await { .. } => "`await`", |
dfeec247 XL |
1961 | YieldSource::Yield => "`yield`", |
1962 | }) | |
1963 | } | |
1964 | } | |
1965 | ||
1966 | impl From<GeneratorKind> for YieldSource { | |
1967 | fn from(kind: GeneratorKind) -> Self { | |
1968 | match kind { | |
1969 | // Guess based on the kind of the current generator. | |
1970 | GeneratorKind::Gen => Self::Yield, | |
ba9703b0 | 1971 | GeneratorKind::Async(_) => Self::Await { expr: None }, |
dfeec247 XL |
1972 | } |
1973 | } | |
1974 | } | |
1975 | ||
1976 | // N.B., if you change this, you'll probably want to change the corresponding | |
1977 | // type structure in middle/ty.rs as well. | |
3dfed10e | 1978 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
1979 | pub struct MutTy<'hir> { |
1980 | pub ty: &'hir Ty<'hir>, | |
1981 | pub mutbl: Mutability, | |
1982 | } | |
1983 | ||
1984 | /// Represents a function's signature in a trait declaration, | |
1985 | /// trait implementation, or a free function. | |
3dfed10e | 1986 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
1987 | pub struct FnSig<'hir> { |
1988 | pub header: FnHeader, | |
1989 | pub decl: &'hir FnDecl<'hir>, | |
3dfed10e | 1990 | pub span: Span, |
dfeec247 XL |
1991 | } |
1992 | ||
1993 | // The bodies for items are stored "out of line", in a separate | |
fc512014 | 1994 | // hashmap in the `Crate`. Here we just record the hir-id of the item |
dfeec247 | 1995 | // so it can fetched later. |
3dfed10e | 1996 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)] |
dfeec247 | 1997 | pub struct TraitItemId { |
6a06907d XL |
1998 | pub def_id: LocalDefId, |
1999 | } | |
2000 | ||
2001 | impl TraitItemId { | |
2002 | #[inline] | |
2003 | pub fn hir_id(&self) -> HirId { | |
2004 | // Items are always HIR owners. | |
2005 | HirId::make_owner(self.def_id) | |
2006 | } | |
dfeec247 XL |
2007 | } |
2008 | ||
2009 | /// Represents an item declaration within a trait declaration, | |
2010 | /// possibly including a default implementation. A trait item is | |
2011 | /// either required (meaning it doesn't have an implementation, just a | |
2012 | /// signature) or provided (meaning it has a default implementation). | |
3dfed10e | 2013 | #[derive(Debug)] |
dfeec247 XL |
2014 | pub struct TraitItem<'hir> { |
2015 | pub ident: Ident, | |
6a06907d | 2016 | pub def_id: LocalDefId, |
dfeec247 XL |
2017 | pub generics: Generics<'hir>, |
2018 | pub kind: TraitItemKind<'hir>, | |
2019 | pub span: Span, | |
2020 | } | |
2021 | ||
6a06907d XL |
2022 | impl TraitItem<'_> { |
2023 | #[inline] | |
2024 | pub fn hir_id(&self) -> HirId { | |
2025 | // Items are always HIR owners. | |
2026 | HirId::make_owner(self.def_id) | |
2027 | } | |
2028 | ||
2029 | pub fn trait_item_id(&self) -> TraitItemId { | |
2030 | TraitItemId { def_id: self.def_id } | |
2031 | } | |
2032 | } | |
2033 | ||
dfeec247 | 2034 | /// Represents a trait method's body (or just argument names). |
3dfed10e | 2035 | #[derive(Encodable, Debug, HashStable_Generic)] |
ba9703b0 | 2036 | pub enum TraitFn<'hir> { |
dfeec247 XL |
2037 | /// No default body in the trait, just a signature. |
2038 | Required(&'hir [Ident]), | |
2039 | ||
2040 | /// Both signature and body are provided in the trait. | |
2041 | Provided(BodyId), | |
2042 | } | |
2043 | ||
2044 | /// Represents a trait method or associated constant or type | |
3dfed10e | 2045 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2046 | pub enum TraitItemKind<'hir> { |
2047 | /// An associated constant with an optional value (otherwise `impl`s must contain a value). | |
2048 | Const(&'hir Ty<'hir>, Option<BodyId>), | |
ba9703b0 XL |
2049 | /// An associated function with an optional body. |
2050 | Fn(FnSig<'hir>, TraitFn<'hir>), | |
dfeec247 XL |
2051 | /// An associated type with (possibly empty) bounds and optional concrete |
2052 | /// type. | |
2053 | Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>), | |
2054 | } | |
2055 | ||
2056 | // The bodies for items are stored "out of line", in a separate | |
fc512014 | 2057 | // hashmap in the `Crate`. Here we just record the hir-id of the item |
dfeec247 | 2058 | // so it can fetched later. |
3dfed10e | 2059 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)] |
dfeec247 | 2060 | pub struct ImplItemId { |
6a06907d XL |
2061 | pub def_id: LocalDefId, |
2062 | } | |
2063 | ||
2064 | impl ImplItemId { | |
2065 | #[inline] | |
2066 | pub fn hir_id(&self) -> HirId { | |
2067 | // Items are always HIR owners. | |
2068 | HirId::make_owner(self.def_id) | |
2069 | } | |
dfeec247 XL |
2070 | } |
2071 | ||
2072 | /// Represents anything within an `impl` block. | |
3dfed10e | 2073 | #[derive(Debug)] |
dfeec247 XL |
2074 | pub struct ImplItem<'hir> { |
2075 | pub ident: Ident, | |
6a06907d | 2076 | pub def_id: LocalDefId, |
dfeec247 XL |
2077 | pub vis: Visibility<'hir>, |
2078 | pub defaultness: Defaultness, | |
dfeec247 XL |
2079 | pub generics: Generics<'hir>, |
2080 | pub kind: ImplItemKind<'hir>, | |
2081 | pub span: Span, | |
2082 | } | |
2083 | ||
6a06907d XL |
2084 | impl ImplItem<'_> { |
2085 | #[inline] | |
2086 | pub fn hir_id(&self) -> HirId { | |
2087 | // Items are always HIR owners. | |
2088 | HirId::make_owner(self.def_id) | |
2089 | } | |
2090 | ||
2091 | pub fn impl_item_id(&self) -> ImplItemId { | |
2092 | ImplItemId { def_id: self.def_id } | |
2093 | } | |
2094 | } | |
2095 | ||
dfeec247 | 2096 | /// Represents various kinds of content within an `impl`. |
3dfed10e | 2097 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2098 | pub enum ImplItemKind<'hir> { |
2099 | /// An associated constant of the given type, set to the constant result | |
2100 | /// of the expression. | |
2101 | Const(&'hir Ty<'hir>, BodyId), | |
ba9703b0 XL |
2102 | /// An associated function implementation with the given signature and body. |
2103 | Fn(FnSig<'hir>, BodyId), | |
dfeec247 XL |
2104 | /// An associated type. |
2105 | TyAlias(&'hir Ty<'hir>), | |
dfeec247 XL |
2106 | } |
2107 | ||
2108 | // The name of the associated type for `Fn` return types. | |
2109 | pub const FN_OUTPUT_NAME: Symbol = sym::Output; | |
2110 | ||
2111 | /// Bind a type to an associated type (i.e., `A = Foo`). | |
2112 | /// | |
2113 | /// Bindings like `A: Debug` are represented as a special type `A = | |
2114 | /// $::Debug` that is understood by the astconv code. | |
2115 | /// | |
2116 | /// FIXME(alexreg): why have a separate type for the binding case, | |
2117 | /// wouldn't it be better to make the `ty` field an enum like the | |
2118 | /// following? | |
2119 | /// | |
2120 | /// ``` | |
2121 | /// enum TypeBindingKind { | |
2122 | /// Equals(...), | |
2123 | /// Binding(...), | |
2124 | /// } | |
2125 | /// ``` | |
3dfed10e | 2126 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2127 | pub struct TypeBinding<'hir> { |
2128 | pub hir_id: HirId, | |
2129 | #[stable_hasher(project(name))] | |
2130 | pub ident: Ident, | |
5869c6ff | 2131 | pub gen_args: &'hir GenericArgs<'hir>, |
dfeec247 XL |
2132 | pub kind: TypeBindingKind<'hir>, |
2133 | pub span: Span, | |
2134 | } | |
2135 | ||
2136 | // Represents the two kinds of type bindings. | |
3dfed10e | 2137 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2138 | pub enum TypeBindingKind<'hir> { |
2139 | /// E.g., `Foo<Bar: Send>`. | |
2140 | Constraint { bounds: &'hir [GenericBound<'hir>] }, | |
2141 | /// E.g., `Foo<Bar = ()>`. | |
2142 | Equality { ty: &'hir Ty<'hir> }, | |
2143 | } | |
2144 | ||
2145 | impl TypeBinding<'_> { | |
2146 | pub fn ty(&self) -> &Ty<'_> { | |
2147 | match self.kind { | |
2148 | TypeBindingKind::Equality { ref ty } => ty, | |
2149 | _ => panic!("expected equality type binding for parenthesized generic args"), | |
2150 | } | |
2151 | } | |
2152 | } | |
2153 | ||
3dfed10e | 2154 | #[derive(Debug)] |
dfeec247 XL |
2155 | pub struct Ty<'hir> { |
2156 | pub hir_id: HirId, | |
2157 | pub kind: TyKind<'hir>, | |
2158 | pub span: Span, | |
2159 | } | |
2160 | ||
dfeec247 | 2161 | /// Not represented directly in the AST; referred to by name through a `ty_path`. |
3dfed10e | 2162 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] |
dfeec247 XL |
2163 | #[derive(HashStable_Generic)] |
2164 | pub enum PrimTy { | |
2165 | Int(IntTy), | |
2166 | Uint(UintTy), | |
2167 | Float(FloatTy), | |
2168 | Str, | |
2169 | Bool, | |
2170 | Char, | |
2171 | } | |
2172 | ||
1b1a35ee | 2173 | impl PrimTy { |
6a06907d XL |
2174 | /// All of the primitive types |
2175 | pub const ALL: [Self; 17] = [ | |
2176 | // any changes here should also be reflected in `PrimTy::from_name` | |
2177 | Self::Int(IntTy::I8), | |
2178 | Self::Int(IntTy::I16), | |
2179 | Self::Int(IntTy::I32), | |
2180 | Self::Int(IntTy::I64), | |
2181 | Self::Int(IntTy::I128), | |
2182 | Self::Int(IntTy::Isize), | |
2183 | Self::Uint(UintTy::U8), | |
2184 | Self::Uint(UintTy::U16), | |
2185 | Self::Uint(UintTy::U32), | |
2186 | Self::Uint(UintTy::U64), | |
2187 | Self::Uint(UintTy::U128), | |
2188 | Self::Uint(UintTy::Usize), | |
2189 | Self::Float(FloatTy::F32), | |
2190 | Self::Float(FloatTy::F64), | |
2191 | Self::Bool, | |
2192 | Self::Char, | |
2193 | Self::Str, | |
2194 | ]; | |
2195 | ||
cdc7bbd5 XL |
2196 | /// Like [`PrimTy::name`], but returns a &str instead of a symbol. |
2197 | /// | |
2198 | /// Used by clippy. | |
1b1a35ee XL |
2199 | pub fn name_str(self) -> &'static str { |
2200 | match self { | |
2201 | PrimTy::Int(i) => i.name_str(), | |
2202 | PrimTy::Uint(u) => u.name_str(), | |
2203 | PrimTy::Float(f) => f.name_str(), | |
2204 | PrimTy::Str => "str", | |
2205 | PrimTy::Bool => "bool", | |
2206 | PrimTy::Char => "char", | |
2207 | } | |
2208 | } | |
2209 | ||
2210 | pub fn name(self) -> Symbol { | |
2211 | match self { | |
2212 | PrimTy::Int(i) => i.name(), | |
2213 | PrimTy::Uint(u) => u.name(), | |
2214 | PrimTy::Float(f) => f.name(), | |
2215 | PrimTy::Str => sym::str, | |
2216 | PrimTy::Bool => sym::bool, | |
2217 | PrimTy::Char => sym::char, | |
2218 | } | |
2219 | } | |
6a06907d XL |
2220 | |
2221 | /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32". | |
2222 | /// Returns `None` if no matching type is found. | |
2223 | pub fn from_name(name: Symbol) -> Option<Self> { | |
2224 | let ty = match name { | |
2225 | // any changes here should also be reflected in `PrimTy::ALL` | |
2226 | sym::i8 => Self::Int(IntTy::I8), | |
2227 | sym::i16 => Self::Int(IntTy::I16), | |
2228 | sym::i32 => Self::Int(IntTy::I32), | |
2229 | sym::i64 => Self::Int(IntTy::I64), | |
2230 | sym::i128 => Self::Int(IntTy::I128), | |
2231 | sym::isize => Self::Int(IntTy::Isize), | |
2232 | sym::u8 => Self::Uint(UintTy::U8), | |
2233 | sym::u16 => Self::Uint(UintTy::U16), | |
2234 | sym::u32 => Self::Uint(UintTy::U32), | |
2235 | sym::u64 => Self::Uint(UintTy::U64), | |
2236 | sym::u128 => Self::Uint(UintTy::U128), | |
2237 | sym::usize => Self::Uint(UintTy::Usize), | |
2238 | sym::f32 => Self::Float(FloatTy::F32), | |
2239 | sym::f64 => Self::Float(FloatTy::F64), | |
2240 | sym::bool => Self::Bool, | |
2241 | sym::char => Self::Char, | |
2242 | sym::str => Self::Str, | |
2243 | _ => return None, | |
2244 | }; | |
2245 | Some(ty) | |
2246 | } | |
1b1a35ee XL |
2247 | } |
2248 | ||
3dfed10e | 2249 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2250 | pub struct BareFnTy<'hir> { |
2251 | pub unsafety: Unsafety, | |
2252 | pub abi: Abi, | |
2253 | pub generic_params: &'hir [GenericParam<'hir>], | |
2254 | pub decl: &'hir FnDecl<'hir>, | |
2255 | pub param_names: &'hir [Ident], | |
2256 | } | |
2257 | ||
3dfed10e | 2258 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2259 | pub struct OpaqueTy<'hir> { |
2260 | pub generics: Generics<'hir>, | |
2261 | pub bounds: GenericBounds<'hir>, | |
2262 | pub impl_trait_fn: Option<DefId>, | |
2263 | pub origin: OpaqueTyOrigin, | |
2264 | } | |
2265 | ||
2266 | /// From whence the opaque type came. | |
136023e0 | 2267 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)] |
dfeec247 | 2268 | pub enum OpaqueTyOrigin { |
dfeec247 XL |
2269 | /// `-> impl Trait` |
2270 | FnReturn, | |
2271 | /// `async fn` | |
2272 | AsyncFn, | |
6a06907d XL |
2273 | /// type aliases: `type Foo = impl Trait;` |
2274 | TyAlias, | |
dfeec247 XL |
2275 | } |
2276 | ||
2277 | /// The various kinds of types recognized by the compiler. | |
3dfed10e | 2278 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2279 | pub enum TyKind<'hir> { |
2280 | /// A variable length slice (i.e., `[T]`). | |
2281 | Slice(&'hir Ty<'hir>), | |
2282 | /// A fixed length array (i.e., `[T; n]`). | |
2283 | Array(&'hir Ty<'hir>, AnonConst), | |
2284 | /// A raw pointer (i.e., `*const T` or `*mut T`). | |
2285 | Ptr(MutTy<'hir>), | |
2286 | /// A reference (i.e., `&'a T` or `&'a mut T`). | |
2287 | Rptr(Lifetime, MutTy<'hir>), | |
2288 | /// A bare function (e.g., `fn(usize) -> bool`). | |
2289 | BareFn(&'hir BareFnTy<'hir>), | |
2290 | /// The never type (`!`). | |
2291 | Never, | |
2292 | /// A tuple (`(A, B, C, D, ...)`). | |
2293 | Tup(&'hir [Ty<'hir>]), | |
2294 | /// A path to a type definition (`module::module::...::Type`), or an | |
2295 | /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`). | |
2296 | /// | |
2297 | /// Type parameters may be stored in each `PathSegment`. | |
2298 | Path(QPath<'hir>), | |
f035d41b XL |
2299 | /// A opaque type definition itself. This is currently only used for the |
2300 | /// `opaque type Foo: Trait` item that `impl Trait` in desugars to. | |
dfeec247 | 2301 | /// |
f035d41b XL |
2302 | /// The generic argument list contains the lifetimes (and in the future |
2303 | /// possibly parameters) that are actually bound on the `impl Trait`. | |
2304 | OpaqueDef(ItemId, &'hir [GenericArg<'hir>]), | |
dfeec247 XL |
2305 | /// A trait object type `Bound1 + Bound2 + Bound3` |
2306 | /// where `Bound` is a trait or a lifetime. | |
6a06907d | 2307 | TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax), |
dfeec247 XL |
2308 | /// Unused for now. |
2309 | Typeof(AnonConst), | |
2310 | /// `TyKind::Infer` means the type should be inferred instead of it having been | |
2311 | /// specified. This can appear anywhere in a type. | |
2312 | Infer, | |
2313 | /// Placeholder for a type that has failed to be defined. | |
2314 | Err, | |
2315 | } | |
2316 | ||
3dfed10e | 2317 | #[derive(Debug, HashStable_Generic)] |
f9f354fc XL |
2318 | pub enum InlineAsmOperand<'hir> { |
2319 | In { | |
2320 | reg: InlineAsmRegOrRegClass, | |
2321 | expr: Expr<'hir>, | |
2322 | }, | |
2323 | Out { | |
2324 | reg: InlineAsmRegOrRegClass, | |
2325 | late: bool, | |
2326 | expr: Option<Expr<'hir>>, | |
2327 | }, | |
2328 | InOut { | |
2329 | reg: InlineAsmRegOrRegClass, | |
2330 | late: bool, | |
2331 | expr: Expr<'hir>, | |
2332 | }, | |
2333 | SplitInOut { | |
2334 | reg: InlineAsmRegOrRegClass, | |
2335 | late: bool, | |
2336 | in_expr: Expr<'hir>, | |
2337 | out_expr: Option<Expr<'hir>>, | |
2338 | }, | |
2339 | Const { | |
cdc7bbd5 | 2340 | anon_const: AnonConst, |
f9f354fc XL |
2341 | }, |
2342 | Sym { | |
2343 | expr: Expr<'hir>, | |
2344 | }, | |
2345 | } | |
2346 | ||
2347 | impl<'hir> InlineAsmOperand<'hir> { | |
2348 | pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> { | |
2349 | match *self { | |
2350 | Self::In { reg, .. } | |
2351 | | Self::Out { reg, .. } | |
2352 | | Self::InOut { reg, .. } | |
2353 | | Self::SplitInOut { reg, .. } => Some(reg), | |
2354 | Self::Const { .. } | Self::Sym { .. } => None, | |
2355 | } | |
2356 | } | |
2357 | } | |
2358 | ||
3dfed10e | 2359 | #[derive(Debug, HashStable_Generic)] |
f9f354fc XL |
2360 | pub struct InlineAsm<'hir> { |
2361 | pub template: &'hir [InlineAsmTemplatePiece], | |
fc512014 | 2362 | pub operands: &'hir [(InlineAsmOperand<'hir>, Span)], |
f9f354fc XL |
2363 | pub options: InlineAsmOptions, |
2364 | pub line_spans: &'hir [Span], | |
2365 | } | |
2366 | ||
6a06907d | 2367 | #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)] |
ba9703b0 | 2368 | pub struct LlvmInlineAsmOutput { |
dfeec247 XL |
2369 | pub constraint: Symbol, |
2370 | pub is_rw: bool, | |
2371 | pub is_indirect: bool, | |
2372 | pub span: Span, | |
2373 | } | |
2374 | ||
2375 | // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR, | |
3dfed10e XL |
2376 | // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of |
2377 | // arena-allocated slice. | |
6a06907d | 2378 | #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)] |
ba9703b0 | 2379 | pub struct LlvmInlineAsmInner { |
dfeec247 XL |
2380 | pub asm: Symbol, |
2381 | pub asm_str_style: StrStyle, | |
ba9703b0 | 2382 | pub outputs: Vec<LlvmInlineAsmOutput>, |
dfeec247 XL |
2383 | pub inputs: Vec<Symbol>, |
2384 | pub clobbers: Vec<Symbol>, | |
2385 | pub volatile: bool, | |
2386 | pub alignstack: bool, | |
ba9703b0 | 2387 | pub dialect: LlvmAsmDialect, |
dfeec247 XL |
2388 | } |
2389 | ||
3dfed10e | 2390 | #[derive(Debug, HashStable_Generic)] |
ba9703b0 XL |
2391 | pub struct LlvmInlineAsm<'hir> { |
2392 | pub inner: LlvmInlineAsmInner, | |
dfeec247 XL |
2393 | pub outputs_exprs: &'hir [Expr<'hir>], |
2394 | pub inputs_exprs: &'hir [Expr<'hir>], | |
2395 | } | |
2396 | ||
2397 | /// Represents a parameter in a function header. | |
3dfed10e | 2398 | #[derive(Debug, HashStable_Generic)] |
dfeec247 | 2399 | pub struct Param<'hir> { |
dfeec247 XL |
2400 | pub hir_id: HirId, |
2401 | pub pat: &'hir Pat<'hir>, | |
3dfed10e | 2402 | pub ty_span: Span, |
dfeec247 XL |
2403 | pub span: Span, |
2404 | } | |
2405 | ||
2406 | /// Represents the header (not the body) of a function declaration. | |
3dfed10e | 2407 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2408 | pub struct FnDecl<'hir> { |
2409 | /// The types of the function's parameters. | |
2410 | /// | |
f9f354fc | 2411 | /// Additional argument data is stored in the function's [body](Body::params). |
dfeec247 | 2412 | pub inputs: &'hir [Ty<'hir>], |
74b04a01 | 2413 | pub output: FnRetTy<'hir>, |
dfeec247 XL |
2414 | pub c_variadic: bool, |
2415 | /// Does the function have an implicit self? | |
2416 | pub implicit_self: ImplicitSelfKind, | |
2417 | } | |
2418 | ||
2419 | /// Represents what type of implicit self a function has, if any. | |
3dfed10e | 2420 | #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
dfeec247 XL |
2421 | pub enum ImplicitSelfKind { |
2422 | /// Represents a `fn x(self);`. | |
2423 | Imm, | |
2424 | /// Represents a `fn x(mut self);`. | |
2425 | Mut, | |
2426 | /// Represents a `fn x(&self);`. | |
2427 | ImmRef, | |
2428 | /// Represents a `fn x(&mut self);`. | |
2429 | MutRef, | |
2430 | /// Represents when a function does not have a self argument or | |
2431 | /// when a function has a `self: X` argument. | |
2432 | None, | |
2433 | } | |
2434 | ||
2435 | impl ImplicitSelfKind { | |
2436 | /// Does this represent an implicit self? | |
2437 | pub fn has_implicit_self(&self) -> bool { | |
29967ef6 | 2438 | !matches!(*self, ImplicitSelfKind::None) |
dfeec247 XL |
2439 | } |
2440 | } | |
2441 | ||
3dfed10e | 2442 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)] |
74b04a01 | 2443 | #[derive(HashStable_Generic)] |
dfeec247 XL |
2444 | pub enum IsAsync { |
2445 | Async, | |
2446 | NotAsync, | |
2447 | } | |
2448 | ||
3dfed10e | 2449 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)] |
dfeec247 XL |
2450 | pub enum Defaultness { |
2451 | Default { has_value: bool }, | |
2452 | Final, | |
2453 | } | |
2454 | ||
2455 | impl Defaultness { | |
2456 | pub fn has_value(&self) -> bool { | |
2457 | match *self { | |
ba9703b0 | 2458 | Defaultness::Default { has_value } => has_value, |
dfeec247 XL |
2459 | Defaultness::Final => true, |
2460 | } | |
2461 | } | |
2462 | ||
2463 | pub fn is_final(&self) -> bool { | |
2464 | *self == Defaultness::Final | |
2465 | } | |
2466 | ||
2467 | pub fn is_default(&self) -> bool { | |
29967ef6 | 2468 | matches!(*self, Defaultness::Default { .. }) |
dfeec247 XL |
2469 | } |
2470 | } | |
2471 | ||
3dfed10e | 2472 | #[derive(Debug, HashStable_Generic)] |
74b04a01 | 2473 | pub enum FnRetTy<'hir> { |
dfeec247 XL |
2474 | /// Return type is not specified. |
2475 | /// | |
2476 | /// Functions default to `()` and | |
2477 | /// closures default to inference. Span points to where return | |
2478 | /// type would be inserted. | |
2479 | DefaultReturn(Span), | |
2480 | /// Everything else. | |
2481 | Return(&'hir Ty<'hir>), | |
2482 | } | |
2483 | ||
74b04a01 | 2484 | impl FnRetTy<'_> { |
17df50a5 | 2485 | #[inline] |
dfeec247 XL |
2486 | pub fn span(&self) -> Span { |
2487 | match *self { | |
2488 | Self::DefaultReturn(span) => span, | |
2489 | Self::Return(ref ty) => ty.span, | |
2490 | } | |
2491 | } | |
2492 | } | |
2493 | ||
3dfed10e | 2494 | #[derive(Encodable, Debug)] |
dfeec247 XL |
2495 | pub struct Mod<'hir> { |
2496 | /// A span from the first token past `{` to the last token until `}`. | |
2497 | /// For `mod foo;`, the inner span ranges from the first token | |
2498 | /// to the last token in the external file. | |
2499 | pub inner: Span, | |
2500 | pub item_ids: &'hir [ItemId], | |
2501 | } | |
2502 | ||
3dfed10e | 2503 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2504 | pub struct EnumDef<'hir> { |
2505 | pub variants: &'hir [Variant<'hir>], | |
2506 | } | |
2507 | ||
3dfed10e | 2508 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2509 | pub struct Variant<'hir> { |
2510 | /// Name of the variant. | |
2511 | #[stable_hasher(project(name))] | |
2512 | pub ident: Ident, | |
dfeec247 XL |
2513 | /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`). |
2514 | pub id: HirId, | |
2515 | /// Fields and constructor id of the variant. | |
2516 | pub data: VariantData<'hir>, | |
2517 | /// Explicit discriminant (e.g., `Foo = 1`). | |
2518 | pub disr_expr: Option<AnonConst>, | |
2519 | /// Span | |
2520 | pub span: Span, | |
2521 | } | |
2522 | ||
3dfed10e | 2523 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
2524 | pub enum UseKind { |
2525 | /// One import, e.g., `use foo::bar` or `use foo::bar as baz`. | |
2526 | /// Also produced for each element of a list `use`, e.g. | |
2527 | /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`. | |
2528 | Single, | |
2529 | ||
2530 | /// Glob import, e.g., `use foo::*`. | |
2531 | Glob, | |
2532 | ||
2533 | /// Degenerate list import, e.g., `use foo::{a, b}` produces | |
2534 | /// an additional `use foo::{}` for performing checks such as | |
2535 | /// unstable feature gating. May be removed in the future. | |
2536 | ListStem, | |
2537 | } | |
2538 | ||
2539 | /// References to traits in impls. | |
2540 | /// | |
2541 | /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all | |
2542 | /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the | |
2543 | /// trait being referred to but just a unique `HirId` that serves as a key | |
2544 | /// within the resolution map. | |
cdc7bbd5 | 2545 | #[derive(Clone, Debug, HashStable_Generic)] |
dfeec247 XL |
2546 | pub struct TraitRef<'hir> { |
2547 | pub path: &'hir Path<'hir>, | |
2548 | // Don't hash the `ref_id`. It is tracked via the thing it is used to access. | |
2549 | #[stable_hasher(ignore)] | |
2550 | pub hir_ref_id: HirId, | |
2551 | } | |
2552 | ||
2553 | impl TraitRef<'_> { | |
2554 | /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias. | |
ba9703b0 | 2555 | pub fn trait_def_id(&self) -> Option<DefId> { |
dfeec247 | 2556 | match self.path.res { |
ba9703b0 XL |
2557 | Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did), |
2558 | Res::Err => None, | |
dfeec247 XL |
2559 | _ => unreachable!(), |
2560 | } | |
2561 | } | |
2562 | } | |
2563 | ||
cdc7bbd5 | 2564 | #[derive(Clone, Debug, HashStable_Generic)] |
dfeec247 | 2565 | pub struct PolyTraitRef<'hir> { |
74b04a01 | 2566 | /// The `'a` in `for<'a> Foo<&'a T>`. |
dfeec247 XL |
2567 | pub bound_generic_params: &'hir [GenericParam<'hir>], |
2568 | ||
74b04a01 | 2569 | /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`. |
dfeec247 XL |
2570 | pub trait_ref: TraitRef<'hir>, |
2571 | ||
2572 | pub span: Span, | |
2573 | } | |
2574 | ||
2575 | pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>; | |
2576 | ||
3dfed10e | 2577 | #[derive(Debug)] |
dfeec247 XL |
2578 | pub enum VisibilityKind<'hir> { |
2579 | Public, | |
2580 | Crate(CrateSugar), | |
2581 | Restricted { path: &'hir Path<'hir>, hir_id: HirId }, | |
2582 | Inherited, | |
2583 | } | |
2584 | ||
2585 | impl VisibilityKind<'_> { | |
2586 | pub fn is_pub(&self) -> bool { | |
29967ef6 | 2587 | matches!(*self, VisibilityKind::Public) |
dfeec247 XL |
2588 | } |
2589 | ||
2590 | pub fn is_pub_restricted(&self) -> bool { | |
2591 | match *self { | |
2592 | VisibilityKind::Public | VisibilityKind::Inherited => false, | |
2593 | VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true, | |
2594 | } | |
2595 | } | |
dfeec247 XL |
2596 | } |
2597 | ||
3dfed10e | 2598 | #[derive(Debug, HashStable_Generic)] |
6a06907d | 2599 | pub struct FieldDef<'hir> { |
dfeec247 XL |
2600 | pub span: Span, |
2601 | #[stable_hasher(project(name))] | |
2602 | pub ident: Ident, | |
2603 | pub vis: Visibility<'hir>, | |
2604 | pub hir_id: HirId, | |
2605 | pub ty: &'hir Ty<'hir>, | |
dfeec247 XL |
2606 | } |
2607 | ||
6a06907d | 2608 | impl FieldDef<'_> { |
dfeec247 XL |
2609 | // Still necessary in couple of places |
2610 | pub fn is_positional(&self) -> bool { | |
2611 | let first = self.ident.as_str().as_bytes()[0]; | |
fc512014 | 2612 | (b'0'..=b'9').contains(&first) |
dfeec247 XL |
2613 | } |
2614 | } | |
2615 | ||
2616 | /// Fields and constructor IDs of enum variants and structs. | |
3dfed10e | 2617 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2618 | pub enum VariantData<'hir> { |
2619 | /// A struct variant. | |
2620 | /// | |
2621 | /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`. | |
6a06907d | 2622 | Struct(&'hir [FieldDef<'hir>], /* recovered */ bool), |
dfeec247 XL |
2623 | /// A tuple variant. |
2624 | /// | |
2625 | /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`. | |
6a06907d | 2626 | Tuple(&'hir [FieldDef<'hir>], HirId), |
dfeec247 XL |
2627 | /// A unit variant. |
2628 | /// | |
2629 | /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`. | |
2630 | Unit(HirId), | |
2631 | } | |
2632 | ||
2633 | impl VariantData<'hir> { | |
2634 | /// Return the fields of this variant. | |
6a06907d | 2635 | pub fn fields(&self) -> &'hir [FieldDef<'hir>] { |
dfeec247 XL |
2636 | match *self { |
2637 | VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields, | |
2638 | _ => &[], | |
2639 | } | |
2640 | } | |
2641 | ||
2642 | /// Return the `HirId` of this variant's constructor, if it has one. | |
2643 | pub fn ctor_hir_id(&self) -> Option<HirId> { | |
2644 | match *self { | |
2645 | VariantData::Struct(_, _) => None, | |
2646 | VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id), | |
2647 | } | |
2648 | } | |
2649 | } | |
2650 | ||
2651 | // The bodies for items are stored "out of line", in a separate | |
fc512014 | 2652 | // hashmap in the `Crate`. Here we just record the hir-id of the item |
dfeec247 | 2653 | // so it can fetched later. |
6a06907d | 2654 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)] |
dfeec247 | 2655 | pub struct ItemId { |
6a06907d XL |
2656 | pub def_id: LocalDefId, |
2657 | } | |
2658 | ||
2659 | impl ItemId { | |
2660 | #[inline] | |
2661 | pub fn hir_id(&self) -> HirId { | |
2662 | // Items are always HIR owners. | |
2663 | HirId::make_owner(self.def_id) | |
2664 | } | |
dfeec247 XL |
2665 | } |
2666 | ||
2667 | /// An item | |
2668 | /// | |
2669 | /// The name might be a dummy name in case of anonymous items | |
3dfed10e | 2670 | #[derive(Debug)] |
dfeec247 XL |
2671 | pub struct Item<'hir> { |
2672 | pub ident: Ident, | |
6a06907d | 2673 | pub def_id: LocalDefId, |
dfeec247 XL |
2674 | pub kind: ItemKind<'hir>, |
2675 | pub vis: Visibility<'hir>, | |
2676 | pub span: Span, | |
2677 | } | |
2678 | ||
6a06907d XL |
2679 | impl Item<'_> { |
2680 | #[inline] | |
2681 | pub fn hir_id(&self) -> HirId { | |
2682 | // Items are always HIR owners. | |
2683 | HirId::make_owner(self.def_id) | |
2684 | } | |
2685 | ||
2686 | pub fn item_id(&self) -> ItemId { | |
2687 | ItemId { def_id: self.def_id } | |
2688 | } | |
2689 | } | |
2690 | ||
74b04a01 | 2691 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] |
3dfed10e | 2692 | #[derive(Encodable, Decodable, HashStable_Generic)] |
74b04a01 XL |
2693 | pub enum Unsafety { |
2694 | Unsafe, | |
2695 | Normal, | |
2696 | } | |
2697 | ||
2698 | impl Unsafety { | |
2699 | pub fn prefix_str(&self) -> &'static str { | |
2700 | match self { | |
2701 | Self::Unsafe => "unsafe ", | |
2702 | Self::Normal => "", | |
2703 | } | |
2704 | } | |
2705 | } | |
2706 | ||
2707 | impl fmt::Display for Unsafety { | |
2708 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
2709 | f.write_str(match *self { | |
2710 | Self::Unsafe => "unsafe", | |
2711 | Self::Normal => "normal", | |
2712 | }) | |
2713 | } | |
2714 | } | |
2715 | ||
2716 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] | |
3dfed10e | 2717 | #[derive(Encodable, Decodable, HashStable_Generic)] |
74b04a01 XL |
2718 | pub enum Constness { |
2719 | Const, | |
2720 | NotConst, | |
2721 | } | |
2722 | ||
3dfed10e | 2723 | #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
2724 | pub struct FnHeader { |
2725 | pub unsafety: Unsafety, | |
2726 | pub constness: Constness, | |
2727 | pub asyncness: IsAsync, | |
2728 | pub abi: Abi, | |
2729 | } | |
2730 | ||
2731 | impl FnHeader { | |
2732 | pub fn is_const(&self) -> bool { | |
29967ef6 | 2733 | matches!(&self.constness, Constness::Const) |
dfeec247 XL |
2734 | } |
2735 | } | |
2736 | ||
3dfed10e | 2737 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2738 | pub enum ItemKind<'hir> { |
2739 | /// An `extern crate` item, with optional *original* crate name if the crate was renamed. | |
2740 | /// | |
2741 | /// E.g., `extern crate foo` or `extern crate foo_bar as foo`. | |
f9f354fc | 2742 | ExternCrate(Option<Symbol>), |
dfeec247 XL |
2743 | |
2744 | /// `use foo::bar::*;` or `use foo::bar::baz as quux;` | |
2745 | /// | |
2746 | /// or just | |
2747 | /// | |
2748 | /// `use foo::bar::baz;` (with `as baz` implicitly on the right). | |
2749 | Use(&'hir Path<'hir>, UseKind), | |
2750 | ||
2751 | /// A `static` item. | |
2752 | Static(&'hir Ty<'hir>, Mutability, BodyId), | |
2753 | /// A `const` item. | |
2754 | Const(&'hir Ty<'hir>, BodyId), | |
2755 | /// A function declaration. | |
2756 | Fn(FnSig<'hir>, Generics<'hir>, BodyId), | |
2757 | /// A module. | |
2758 | Mod(Mod<'hir>), | |
2759 | /// An external module, e.g. `extern { .. }`. | |
fc512014 | 2760 | ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] }, |
dfeec247 | 2761 | /// Module-level inline assembly (from `global_asm!`). |
17df50a5 | 2762 | GlobalAsm(&'hir InlineAsm<'hir>), |
dfeec247 XL |
2763 | /// A type alias, e.g., `type Foo = Bar<u8>`. |
2764 | TyAlias(&'hir Ty<'hir>, Generics<'hir>), | |
2765 | /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`. | |
2766 | OpaqueTy(OpaqueTy<'hir>), | |
2767 | /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`. | |
2768 | Enum(EnumDef<'hir>, Generics<'hir>), | |
2769 | /// A struct definition, e.g., `struct Foo<A> {x: A}`. | |
2770 | Struct(VariantData<'hir>, Generics<'hir>), | |
2771 | /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`. | |
2772 | Union(VariantData<'hir>, Generics<'hir>), | |
2773 | /// A trait definition. | |
2774 | Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]), | |
2775 | /// A trait alias. | |
2776 | TraitAlias(Generics<'hir>, GenericBounds<'hir>), | |
2777 | ||
2778 | /// An implementation, e.g., `impl<A> Trait for Foo { .. }`. | |
5869c6ff XL |
2779 | Impl(Impl<'hir>), |
2780 | } | |
2781 | ||
2782 | #[derive(Debug, HashStable_Generic)] | |
2783 | pub struct Impl<'hir> { | |
2784 | pub unsafety: Unsafety, | |
2785 | pub polarity: ImplPolarity, | |
2786 | pub defaultness: Defaultness, | |
2787 | // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata | |
2788 | // decoding as `Span`s cannot be decoded when a `Session` is not available. | |
2789 | pub defaultness_span: Option<Span>, | |
2790 | pub constness: Constness, | |
2791 | pub generics: Generics<'hir>, | |
2792 | ||
2793 | /// The trait being implemented, if any. | |
2794 | pub of_trait: Option<TraitRef<'hir>>, | |
2795 | ||
2796 | pub self_ty: &'hir Ty<'hir>, | |
2797 | pub items: &'hir [ImplItemRef<'hir>], | |
dfeec247 XL |
2798 | } |
2799 | ||
2800 | impl ItemKind<'_> { | |
dfeec247 XL |
2801 | pub fn generics(&self) -> Option<&Generics<'_>> { |
2802 | Some(match *self { | |
2803 | ItemKind::Fn(_, ref generics, _) | |
2804 | | ItemKind::TyAlias(_, ref generics) | |
2805 | | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) | |
2806 | | ItemKind::Enum(_, ref generics) | |
2807 | | ItemKind::Struct(_, ref generics) | |
2808 | | ItemKind::Union(_, ref generics) | |
2809 | | ItemKind::Trait(_, _, ref generics, _, _) | |
5869c6ff | 2810 | | ItemKind::Impl(Impl { ref generics, .. }) => generics, |
dfeec247 XL |
2811 | _ => return None, |
2812 | }) | |
2813 | } | |
136023e0 XL |
2814 | |
2815 | pub fn descr(&self) -> &'static str { | |
2816 | match self { | |
2817 | ItemKind::ExternCrate(..) => "extern crate", | |
2818 | ItemKind::Use(..) => "`use` import", | |
2819 | ItemKind::Static(..) => "static item", | |
2820 | ItemKind::Const(..) => "constant item", | |
2821 | ItemKind::Fn(..) => "function", | |
2822 | ItemKind::Mod(..) => "module", | |
2823 | ItemKind::ForeignMod { .. } => "extern block", | |
2824 | ItemKind::GlobalAsm(..) => "global asm item", | |
2825 | ItemKind::TyAlias(..) => "type alias", | |
2826 | ItemKind::OpaqueTy(..) => "opaque type", | |
2827 | ItemKind::Enum(..) => "enum", | |
2828 | ItemKind::Struct(..) => "struct", | |
2829 | ItemKind::Union(..) => "union", | |
2830 | ItemKind::Trait(..) => "trait", | |
2831 | ItemKind::TraitAlias(..) => "trait alias", | |
2832 | ItemKind::Impl(..) => "implementation", | |
2833 | } | |
2834 | } | |
dfeec247 XL |
2835 | } |
2836 | ||
2837 | /// A reference from an trait to one of its associated items. This | |
2838 | /// contains the item's id, naturally, but also the item's name and | |
2839 | /// some other high-level details (like whether it is an associated | |
2840 | /// type or method, and whether it is public). This allows other | |
2841 | /// passes to find the impl they want without loading the ID (which | |
2842 | /// means fewer edges in the incremental compilation graph). | |
3dfed10e | 2843 | #[derive(Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
2844 | pub struct TraitItemRef { |
2845 | pub id: TraitItemId, | |
2846 | #[stable_hasher(project(name))] | |
2847 | pub ident: Ident, | |
2848 | pub kind: AssocItemKind, | |
2849 | pub span: Span, | |
2850 | pub defaultness: Defaultness, | |
2851 | } | |
2852 | ||
2853 | /// A reference from an impl to one of its associated items. This | |
2854 | /// contains the item's ID, naturally, but also the item's name and | |
2855 | /// some other high-level details (like whether it is an associated | |
2856 | /// type or method, and whether it is public). This allows other | |
2857 | /// passes to find the impl they want without loading the ID (which | |
2858 | /// means fewer edges in the incremental compilation graph). | |
3dfed10e | 2859 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2860 | pub struct ImplItemRef<'hir> { |
2861 | pub id: ImplItemId, | |
2862 | #[stable_hasher(project(name))] | |
2863 | pub ident: Ident, | |
2864 | pub kind: AssocItemKind, | |
2865 | pub span: Span, | |
2866 | pub vis: Visibility<'hir>, | |
2867 | pub defaultness: Defaultness, | |
2868 | } | |
2869 | ||
3dfed10e | 2870 | #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] |
dfeec247 XL |
2871 | pub enum AssocItemKind { |
2872 | Const, | |
ba9703b0 | 2873 | Fn { has_self: bool }, |
dfeec247 | 2874 | Type, |
dfeec247 XL |
2875 | } |
2876 | ||
fc512014 XL |
2877 | // The bodies for items are stored "out of line", in a separate |
2878 | // hashmap in the `Crate`. Here we just record the hir-id of the item | |
2879 | // so it can fetched later. | |
2880 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)] | |
2881 | pub struct ForeignItemId { | |
6a06907d XL |
2882 | pub def_id: LocalDefId, |
2883 | } | |
2884 | ||
2885 | impl ForeignItemId { | |
2886 | #[inline] | |
2887 | pub fn hir_id(&self) -> HirId { | |
2888 | // Items are always HIR owners. | |
2889 | HirId::make_owner(self.def_id) | |
2890 | } | |
fc512014 XL |
2891 | } |
2892 | ||
2893 | /// A reference from a foreign block to one of its items. This | |
2894 | /// contains the item's ID, naturally, but also the item's name and | |
2895 | /// some other high-level details (like whether it is an associated | |
2896 | /// type or method, and whether it is public). This allows other | |
2897 | /// passes to find the impl they want without loading the ID (which | |
2898 | /// means fewer edges in the incremental compilation graph). | |
2899 | #[derive(Debug, HashStable_Generic)] | |
2900 | pub struct ForeignItemRef<'hir> { | |
2901 | pub id: ForeignItemId, | |
2902 | #[stable_hasher(project(name))] | |
2903 | pub ident: Ident, | |
2904 | pub span: Span, | |
2905 | pub vis: Visibility<'hir>, | |
2906 | } | |
2907 | ||
6a06907d | 2908 | #[derive(Debug)] |
dfeec247 | 2909 | pub struct ForeignItem<'hir> { |
dfeec247 | 2910 | pub ident: Ident, |
dfeec247 | 2911 | pub kind: ForeignItemKind<'hir>, |
6a06907d | 2912 | pub def_id: LocalDefId, |
dfeec247 XL |
2913 | pub span: Span, |
2914 | pub vis: Visibility<'hir>, | |
2915 | } | |
2916 | ||
6a06907d XL |
2917 | impl ForeignItem<'_> { |
2918 | #[inline] | |
2919 | pub fn hir_id(&self) -> HirId { | |
2920 | // Items are always HIR owners. | |
2921 | HirId::make_owner(self.def_id) | |
2922 | } | |
2923 | ||
2924 | pub fn foreign_item_id(&self) -> ForeignItemId { | |
2925 | ForeignItemId { def_id: self.def_id } | |
2926 | } | |
2927 | } | |
2928 | ||
dfeec247 | 2929 | /// An item within an `extern` block. |
3dfed10e | 2930 | #[derive(Debug, HashStable_Generic)] |
dfeec247 XL |
2931 | pub enum ForeignItemKind<'hir> { |
2932 | /// A foreign function. | |
2933 | Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>), | |
2934 | /// A foreign static item (`static ext: u8`). | |
2935 | Static(&'hir Ty<'hir>, Mutability), | |
2936 | /// A foreign type. | |
2937 | Type, | |
2938 | } | |
2939 | ||
dfeec247 | 2940 | /// A variable captured by a closure. |
3dfed10e | 2941 | #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)] |
dfeec247 XL |
2942 | pub struct Upvar { |
2943 | // First span where it is accessed (there can be multiple). | |
2944 | pub span: Span, | |
2945 | } | |
2946 | ||
dfeec247 XL |
2947 | // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and |
2948 | // has length > 0 if the trait is found through an chain of imports, starting with the | |
2949 | // import/use statement in the scope where the trait is used. | |
3dfed10e | 2950 | #[derive(Encodable, Decodable, Clone, Debug)] |
f035d41b | 2951 | pub struct TraitCandidate { |
dfeec247 | 2952 | pub def_id: DefId, |
f035d41b | 2953 | pub import_ids: SmallVec<[LocalDefId; 1]>, |
dfeec247 XL |
2954 | } |
2955 | ||
ba9703b0 | 2956 | #[derive(Copy, Clone, Debug, HashStable_Generic)] |
dfeec247 XL |
2957 | pub enum Node<'hir> { |
2958 | Param(&'hir Param<'hir>), | |
2959 | Item(&'hir Item<'hir>), | |
2960 | ForeignItem(&'hir ForeignItem<'hir>), | |
2961 | TraitItem(&'hir TraitItem<'hir>), | |
2962 | ImplItem(&'hir ImplItem<'hir>), | |
2963 | Variant(&'hir Variant<'hir>), | |
6a06907d | 2964 | Field(&'hir FieldDef<'hir>), |
dfeec247 XL |
2965 | AnonConst(&'hir AnonConst), |
2966 | Expr(&'hir Expr<'hir>), | |
2967 | Stmt(&'hir Stmt<'hir>), | |
2968 | PathSegment(&'hir PathSegment<'hir>), | |
2969 | Ty(&'hir Ty<'hir>), | |
2970 | TraitRef(&'hir TraitRef<'hir>), | |
2971 | Binding(&'hir Pat<'hir>), | |
2972 | Pat(&'hir Pat<'hir>), | |
2973 | Arm(&'hir Arm<'hir>), | |
2974 | Block(&'hir Block<'hir>), | |
2975 | Local(&'hir Local<'hir>), | |
2976 | MacroDef(&'hir MacroDef<'hir>), | |
2977 | ||
2978 | /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants | |
2979 | /// with synthesized constructors. | |
2980 | Ctor(&'hir VariantData<'hir>), | |
2981 | ||
2982 | Lifetime(&'hir Lifetime), | |
2983 | GenericParam(&'hir GenericParam<'hir>), | |
2984 | Visibility(&'hir Visibility<'hir>), | |
2985 | ||
cdc7bbd5 | 2986 | Crate(&'hir Mod<'hir>), |
dfeec247 XL |
2987 | } |
2988 | ||
3dfed10e | 2989 | impl<'hir> Node<'hir> { |
dfeec247 XL |
2990 | pub fn ident(&self) -> Option<Ident> { |
2991 | match self { | |
2992 | Node::TraitItem(TraitItem { ident, .. }) | |
2993 | | Node::ImplItem(ImplItem { ident, .. }) | |
2994 | | Node::ForeignItem(ForeignItem { ident, .. }) | |
6a06907d | 2995 | | Node::Field(FieldDef { ident, .. }) |
29967ef6 XL |
2996 | | Node::Variant(Variant { ident, .. }) |
2997 | | Node::MacroDef(MacroDef { ident, .. }) | |
dfeec247 XL |
2998 | | Node::Item(Item { ident, .. }) => Some(*ident), |
2999 | _ => None, | |
3000 | } | |
3001 | } | |
74b04a01 | 3002 | |
3dfed10e | 3003 | pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> { |
74b04a01 | 3004 | match self { |
ba9703b0 XL |
3005 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. }) |
3006 | | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. }) | |
74b04a01 XL |
3007 | | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl), |
3008 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => { | |
3009 | Some(fn_decl) | |
3010 | } | |
3011 | _ => None, | |
3012 | } | |
3013 | } | |
3014 | ||
f035d41b XL |
3015 | pub fn body_id(&self) -> Option<BodyId> { |
3016 | match self { | |
3017 | Node::TraitItem(TraitItem { | |
3018 | kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)), | |
3019 | .. | |
3020 | }) | |
3021 | | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. }) | |
3022 | | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id), | |
3023 | _ => None, | |
3024 | } | |
3025 | } | |
3026 | ||
3dfed10e | 3027 | pub fn generics(&self) -> Option<&'hir Generics<'hir>> { |
74b04a01 XL |
3028 | match self { |
3029 | Node::TraitItem(TraitItem { generics, .. }) | |
f035d41b XL |
3030 | | Node::ImplItem(ImplItem { generics, .. }) => Some(generics), |
3031 | Node::Item(item) => item.kind.generics(), | |
74b04a01 XL |
3032 | _ => None, |
3033 | } | |
3034 | } | |
f9f354fc XL |
3035 | |
3036 | pub fn hir_id(&self) -> Option<HirId> { | |
3037 | match self { | |
6a06907d XL |
3038 | Node::Item(Item { def_id, .. }) |
3039 | | Node::TraitItem(TraitItem { def_id, .. }) | |
3040 | | Node::ImplItem(ImplItem { def_id, .. }) | |
3041 | | Node::ForeignItem(ForeignItem { def_id, .. }) | |
3042 | | Node::MacroDef(MacroDef { def_id, .. }) => Some(HirId::make_owner(*def_id)), | |
3043 | Node::Field(FieldDef { hir_id, .. }) | |
f9f354fc XL |
3044 | | Node::AnonConst(AnonConst { hir_id, .. }) |
3045 | | Node::Expr(Expr { hir_id, .. }) | |
3046 | | Node::Stmt(Stmt { hir_id, .. }) | |
3047 | | Node::Ty(Ty { hir_id, .. }) | |
3048 | | Node::Binding(Pat { hir_id, .. }) | |
3049 | | Node::Pat(Pat { hir_id, .. }) | |
3050 | | Node::Arm(Arm { hir_id, .. }) | |
3051 | | Node::Block(Block { hir_id, .. }) | |
3052 | | Node::Local(Local { hir_id, .. }) | |
f9f354fc XL |
3053 | | Node::Lifetime(Lifetime { hir_id, .. }) |
3054 | | Node::Param(Param { hir_id, .. }) | |
3055 | | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id), | |
3056 | Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id), | |
3057 | Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id, | |
3058 | Node::Variant(Variant { id, .. }) => Some(*id), | |
3059 | Node::Ctor(variant) => variant.ctor_hir_id(), | |
3060 | Node::Crate(_) | Node::Visibility(_) => None, | |
3061 | } | |
3062 | } | |
136023e0 XL |
3063 | |
3064 | /// Returns `Constness::Const` when this node is a const fn/impl. | |
3065 | pub fn constness(&self) -> Constness { | |
3066 | match self { | |
3067 | Node::Item(Item { | |
3068 | kind: ItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..), | |
3069 | .. | |
3070 | }) | |
3071 | | Node::TraitItem(TraitItem { | |
3072 | kind: TraitItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..), | |
3073 | .. | |
3074 | }) | |
3075 | | Node::ImplItem(ImplItem { | |
3076 | kind: ImplItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..), | |
3077 | .. | |
3078 | }) | |
3079 | | Node::Item(Item { kind: ItemKind::Impl(Impl { constness, .. }), .. }) => *constness, | |
3080 | ||
3081 | _ => Constness::NotConst, | |
3082 | } | |
3083 | } | |
dfeec247 | 3084 | } |
6a06907d XL |
3085 | |
3086 | // Some nodes are used a lot. Make sure they don't unintentionally get bigger. | |
3087 | #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] | |
3088 | mod size_asserts { | |
3089 | rustc_data_structures::static_assert_size!(super::Block<'static>, 48); | |
3090 | rustc_data_structures::static_assert_size!(super::Expr<'static>, 64); | |
3091 | rustc_data_structures::static_assert_size!(super::Pat<'static>, 88); | |
3092 | rustc_data_structures::static_assert_size!(super::QPath<'static>, 24); | |
3093 | rustc_data_structures::static_assert_size!(super::Ty<'static>, 72); | |
3094 | ||
3095 | rustc_data_structures::static_assert_size!(super::Item<'static>, 184); | |
3096 | rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128); | |
3097 | rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152); | |
3098 | rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136); | |
3099 | } |