]>
Commit | Line | Data |
---|---|---|
e74abb32 XL |
1 | //! The Rust abstract syntax tree module. |
2 | //! | |
3 | //! This module contains common structures forming the language AST. | |
4 | //! Two main entities in the module are [`Item`] (which represents an AST element with | |
5 | //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains | |
6 | //! information specific to the type of the item). | |
7 | //! | |
f035d41b | 8 | //! Other module items worth mentioning: |
e74abb32 XL |
9 | //! - [`Ty`] and [`TyKind`]: A parsed Rust type. |
10 | //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression. | |
11 | //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions. | |
12 | //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value. | |
13 | //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration. | |
14 | //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters. | |
15 | //! - [`EnumDef`] and [`Variant`]: Enum declaration. | |
16 | //! - [`Lit`] and [`LitKind`]: Literal expressions. | |
f9f354fc | 17 | //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation. |
e74abb32 | 18 | //! - [`Attribute`]: Metadata associated with item. |
f9f354fc | 19 | //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators. |
223e47cc | 20 | |
dfeec247 | 21 | pub use crate::util::parser::ExprPrecedence; |
9fa01778 XL |
22 | pub use GenericArgs::*; |
23 | pub use UnsafeSource::*; | |
9fa01778 | 24 | |
9fa01778 | 25 | use crate::ptr::P; |
3dfed10e | 26 | use crate::token::{self, CommentKind, DelimToken}; |
fc512014 | 27 | use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream}; |
1a4d82fc | 28 | |
60c5eb7d | 29 | use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; |
29967ef6 | 30 | use rustc_data_structures::stack::ensure_sufficient_stack; |
0531ce1d | 31 | use rustc_data_structures::sync::Lrc; |
e74abb32 | 32 | use rustc_data_structures::thin_vec::ThinVec; |
60c5eb7d | 33 | use rustc_macros::HashStable_Generic; |
dfeec247 | 34 | use rustc_serialize::{self, Decoder, Encoder}; |
74b04a01 | 35 | use rustc_span::source_map::{respan, Spanned}; |
f9f354fc | 36 | use rustc_span::symbol::{kw, sym, Ident, Symbol}; |
dfeec247 | 37 | use rustc_span::{Span, DUMMY_SP}; |
e74abb32 | 38 | |
3dfed10e | 39 | use std::cmp::Ordering; |
74b04a01 | 40 | use std::convert::TryFrom; |
e74abb32 | 41 | use std::fmt; |
94b46f34 | 42 | |
416331ca XL |
43 | #[cfg(test)] |
44 | mod tests; | |
45 | ||
e74abb32 XL |
46 | /// A "Label" is an identifier of some point in sources, |
47 | /// e.g. in the following code: | |
48 | /// | |
49 | /// ```rust | |
50 | /// 'outer: loop { | |
51 | /// break 'outer; | |
52 | /// } | |
53 | /// ``` | |
54 | /// | |
55 | /// `'outer` is a label. | |
3dfed10e | 56 | #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic)] |
2c00a5a8 XL |
57 | pub struct Label { |
58 | pub ident: Ident, | |
2c00a5a8 XL |
59 | } |
60 | ||
61 | impl fmt::Debug for Label { | |
9fa01778 | 62 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
2c00a5a8 XL |
63 | write!(f, "label({:?})", self.ident) |
64 | } | |
65 | } | |
66 | ||
e74abb32 XL |
67 | /// A "Lifetime" is an annotation of the scope in which variable |
68 | /// can be used, e.g. `'a` in `&'a i32`. | |
3dfed10e | 69 | #[derive(Clone, Encodable, Decodable, Copy)] |
223e47cc | 70 | pub struct Lifetime { |
1a4d82fc | 71 | pub id: NodeId, |
7cac9316 | 72 | pub ident: Ident, |
1a4d82fc JJ |
73 | } |
74 | ||
62682a34 | 75 | impl fmt::Debug for Lifetime { |
9fa01778 | 76 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
dfeec247 | 77 | write!(f, "lifetime({}: {})", self.id, self) |
62682a34 SL |
78 | } |
79 | } | |
80 | ||
416331ca XL |
81 | impl fmt::Display for Lifetime { |
82 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
60c5eb7d | 83 | write!(f, "{}", self.ident.name) |
416331ca XL |
84 | } |
85 | } | |
86 | ||
3157f602 XL |
87 | /// A "Path" is essentially Rust's notion of a name. |
88 | /// | |
89 | /// It's represented as a sequence of identifiers, | |
1a4d82fc | 90 | /// along with a bunch of supporting information. |
3157f602 | 91 | /// |
0731742a | 92 | /// E.g., `std::cmp::PartialEq`. |
3dfed10e | 93 | #[derive(Clone, Encodable, Decodable, Debug)] |
970d7e83 | 94 | pub struct Path { |
1a4d82fc | 95 | pub span: Span, |
1a4d82fc | 96 | /// The segments in the path: the things separated by `::`. |
dc9dc135 | 97 | /// Global paths begin with `kw::PathRoot`. |
1a4d82fc | 98 | pub segments: Vec<PathSegment>, |
29967ef6 | 99 | pub tokens: Option<LazyTokenStream>, |
1a4d82fc JJ |
100 | } |
101 | ||
48663c56 XL |
102 | impl PartialEq<Symbol> for Path { |
103 | fn eq(&self, symbol: &Symbol) -> bool { | |
dfeec247 | 104 | self.segments.len() == 1 && { self.segments[0].ident.name == *symbol } |
cc61c64b XL |
105 | } |
106 | } | |
107 | ||
60c5eb7d XL |
108 | impl<CTX> HashStable<CTX> for Path { |
109 | fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { | |
110 | self.segments.len().hash_stable(hcx, hasher); | |
111 | for segment in &self.segments { | |
112 | segment.ident.name.hash_stable(hcx, hasher); | |
113 | } | |
114 | } | |
115 | } | |
116 | ||
54a0048b | 117 | impl Path { |
0731742a XL |
118 | // Convert a span and an identifier to the corresponding |
119 | // one-segment path. | |
83c7162d | 120 | pub fn from_ident(ident: Ident) -> Path { |
1b1a35ee | 121 | Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None } |
54a0048b | 122 | } |
32a655c1 | 123 | |
32a655c1 | 124 | pub fn is_global(&self) -> bool { |
dc9dc135 | 125 | !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot |
32a655c1 | 126 | } |
54a0048b SL |
127 | } |
128 | ||
3157f602 XL |
129 | /// A segment of a path: an identifier, an optional lifetime, and a set of types. |
130 | /// | |
0731742a | 131 | /// E.g., `std`, `String` or `Box<T>`. |
3dfed10e | 132 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
133 | pub struct PathSegment { |
134 | /// The identifier portion of this path segment. | |
83c7162d | 135 | pub ident: Ident, |
1a4d82fc | 136 | |
13cf67c4 XL |
137 | pub id: NodeId, |
138 | ||
1a4d82fc | 139 | /// Type/lifetime parameters attached to this path. They come in |
3b2f2976 XL |
140 | /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. |
141 | /// `None` means that no parameter list is supplied (`Path`), | |
142 | /// `Some` means that parameter list is supplied (`Path<X, Y>`) | |
143 | /// but it can be empty (`Path<>`). | |
144 | /// `P` is used as a size optimization for the common case with no parameters. | |
8faf50e0 | 145 | pub args: Option<P<GenericArgs>>, |
32a655c1 SL |
146 | } |
147 | ||
32a655c1 | 148 | impl PathSegment { |
83c7162d | 149 | pub fn from_ident(ident: Ident) -> Self { |
13cf67c4 | 150 | PathSegment { ident, id: DUMMY_NODE_ID, args: None } |
8bb4bdeb | 151 | } |
0731742a | 152 | pub fn path_root(span: Span) -> Self { |
dc9dc135 | 153 | PathSegment::from_ident(Ident::new(kw::PathRoot, span)) |
32a655c1 | 154 | } |
1a4d82fc JJ |
155 | } |
156 | ||
9fa01778 | 157 | /// The arguments of a path segment. |
3157f602 | 158 | /// |
0731742a | 159 | /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`. |
3dfed10e | 160 | #[derive(Clone, Encodable, Decodable, Debug)] |
8faf50e0 | 161 | pub enum GenericArgs { |
9fa01778 | 162 | /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`. |
8faf50e0 | 163 | AngleBracketed(AngleBracketedArgs), |
9fa01778 XL |
164 | /// The `(A, B)` and `C` in `Foo(A, B) -> C`. |
165 | Parenthesized(ParenthesizedArgs), | |
1a4d82fc JJ |
166 | } |
167 | ||
8faf50e0 | 168 | impl GenericArgs { |
9fa01778 XL |
169 | pub fn is_angle_bracketed(&self) -> bool { |
170 | match *self { | |
171 | AngleBracketed(..) => true, | |
172 | _ => false, | |
173 | } | |
174 | } | |
175 | ||
3b2f2976 XL |
176 | pub fn span(&self) -> Span { |
177 | match *self { | |
178 | AngleBracketed(ref data) => data.span, | |
179 | Parenthesized(ref data) => data.span, | |
180 | } | |
181 | } | |
182 | } | |
183 | ||
e74abb32 | 184 | /// Concrete argument in the sequence of generic args. |
3dfed10e | 185 | #[derive(Clone, Encodable, Decodable, Debug)] |
8faf50e0 | 186 | pub enum GenericArg { |
e74abb32 | 187 | /// `'a` in `Foo<'a>` |
8faf50e0 | 188 | Lifetime(Lifetime), |
e74abb32 | 189 | /// `Bar` in `Foo<Bar>` |
8faf50e0 | 190 | Type(P<Ty>), |
e74abb32 | 191 | /// `1` in `Foo<1>` |
9fa01778 | 192 | Const(AnonConst), |
8faf50e0 XL |
193 | } |
194 | ||
9fa01778 XL |
195 | impl GenericArg { |
196 | pub fn span(&self) -> Span { | |
197 | match self { | |
198 | GenericArg::Lifetime(lt) => lt.ident.span, | |
199 | GenericArg::Type(ty) => ty.span, | |
200 | GenericArg::Const(ct) => ct.value.span, | |
201 | } | |
202 | } | |
203 | } | |
204 | ||
205 | /// A path like `Foo<'a, T>`. | |
3dfed10e | 206 | #[derive(Clone, Encodable, Decodable, Debug, Default)] |
8faf50e0 | 207 | pub struct AngleBracketedArgs { |
9fa01778 | 208 | /// The overall span. |
3b2f2976 | 209 | pub span: Span, |
ba9703b0 XL |
210 | /// The comma separated parts in the `<...>`. |
211 | pub args: Vec<AngleBracketedArg>, | |
212 | } | |
213 | ||
214 | /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`, | |
215 | /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`. | |
3dfed10e | 216 | #[derive(Clone, Encodable, Decodable, Debug)] |
ba9703b0 XL |
217 | pub enum AngleBracketedArg { |
218 | /// Argument for a generic parameter. | |
219 | Arg(GenericArg), | |
220 | /// Constraint for an associated item. | |
221 | Constraint(AssocTyConstraint), | |
223e47cc LB |
222 | } |
223 | ||
29967ef6 XL |
224 | impl AngleBracketedArg { |
225 | pub fn span(&self) -> Span { | |
226 | match self { | |
227 | AngleBracketedArg::Arg(arg) => arg.span(), | |
228 | AngleBracketedArg::Constraint(constraint) => constraint.span, | |
229 | } | |
230 | } | |
231 | } | |
232 | ||
8faf50e0 XL |
233 | impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs { |
234 | fn into(self) -> Option<P<GenericArgs>> { | |
235 | Some(P(GenericArgs::AngleBracketed(self))) | |
3b2f2976 XL |
236 | } |
237 | } | |
238 | ||
9fa01778 | 239 | impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs { |
8faf50e0 XL |
240 | fn into(self) -> Option<P<GenericArgs>> { |
241 | Some(P(GenericArgs::Parenthesized(self))) | |
1a4d82fc JJ |
242 | } |
243 | } | |
244 | ||
9fa01778 | 245 | /// A path like `Foo(A, B) -> C`. |
3dfed10e | 246 | #[derive(Clone, Encodable, Decodable, Debug)] |
9fa01778 | 247 | pub struct ParenthesizedArgs { |
85aaf69f SL |
248 | /// Overall span |
249 | pub span: Span, | |
250 | ||
dc9dc135 | 251 | /// `(A, B)` |
1a4d82fc JJ |
252 | pub inputs: Vec<P<Ty>>, |
253 | ||
254 | /// `C` | |
74b04a01 | 255 | pub output: FnRetTy, |
1a4d82fc JJ |
256 | } |
257 | ||
9fa01778 XL |
258 | impl ParenthesizedArgs { |
259 | pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs { | |
ba9703b0 XL |
260 | let args = self |
261 | .inputs | |
262 | .iter() | |
263 | .cloned() | |
264 | .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input))) | |
265 | .collect(); | |
266 | AngleBracketedArgs { span: self.span, args } | |
9fa01778 XL |
267 | } |
268 | } | |
269 | ||
74b04a01 | 270 | pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID}; |
1a4d82fc | 271 | |
dfeec247 XL |
272 | /// A modifier on a bound, e.g., `?Sized` or `?const Trait`. |
273 | /// | |
274 | /// Negative bounds should also be handled here. | |
3dfed10e | 275 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)] |
8faf50e0 | 276 | pub enum TraitBoundModifier { |
dfeec247 | 277 | /// No modifiers |
8faf50e0 | 278 | None, |
dfeec247 XL |
279 | |
280 | /// `?Trait` | |
8faf50e0 | 281 | Maybe, |
dfeec247 XL |
282 | |
283 | /// `?const Trait` | |
284 | MaybeConst, | |
285 | ||
286 | /// `?const ?Trait` | |
287 | // | |
288 | // This parses but will be rejected during AST validation. | |
289 | MaybeConstMaybe, | |
8faf50e0 XL |
290 | } |
291 | ||
1a4d82fc | 292 | /// The AST represents all type param bounds as types. |
a1dfa0c6 XL |
293 | /// `typeck::collect::compute_bounds` matches these against |
294 | /// the "special" built-in traits (see `middle::lang_items`) and | |
295 | /// detects `Copy`, `Send` and `Sync`. | |
3dfed10e | 296 | #[derive(Clone, Encodable, Decodable, Debug)] |
8faf50e0 XL |
297 | pub enum GenericBound { |
298 | Trait(PolyTraitRef, TraitBoundModifier), | |
0bf4aa26 | 299 | Outlives(Lifetime), |
223e47cc LB |
300 | } |
301 | ||
8faf50e0 | 302 | impl GenericBound { |
0531ce1d XL |
303 | pub fn span(&self) -> Span { |
304 | match self { | |
ba9703b0 XL |
305 | GenericBound::Trait(ref t, ..) => t.span, |
306 | GenericBound::Outlives(ref l) => l.ident.span, | |
0531ce1d XL |
307 | } |
308 | } | |
309 | } | |
310 | ||
8faf50e0 | 311 | pub type GenericBounds = Vec<GenericBound>; |
1a4d82fc | 312 | |
9fa01778 XL |
313 | /// Specifies the enforced ordering for generic parameters. In the future, |
314 | /// if we wanted to relax this order, we could override `PartialEq` and | |
315 | /// `PartialOrd`, to allow the kinds to be unordered. | |
3dfed10e | 316 | #[derive(Hash, Clone, Copy)] |
9fa01778 XL |
317 | pub enum ParamKindOrd { |
318 | Lifetime, | |
319 | Type, | |
3dfed10e XL |
320 | // `unordered` is only `true` if `sess.has_features().const_generics` |
321 | // is active. Specifically, if it's only `min_const_generics`, it will still require | |
322 | // ordering consts after types. | |
323 | Const { unordered: bool }, | |
324 | } | |
325 | ||
326 | impl Ord for ParamKindOrd { | |
327 | fn cmp(&self, other: &Self) -> Ordering { | |
328 | use ParamKindOrd::*; | |
329 | let to_int = |v| match v { | |
330 | Lifetime => 0, | |
331 | Type | Const { unordered: true } => 1, | |
332 | // technically both consts should be ordered equally, | |
333 | // but only one is ever encountered at a time, so this is | |
334 | // fine. | |
335 | Const { unordered: false } => 2, | |
336 | }; | |
337 | ||
338 | to_int(*self).cmp(&to_int(*other)) | |
339 | } | |
340 | } | |
341 | impl PartialOrd for ParamKindOrd { | |
342 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
343 | Some(self.cmp(other)) | |
344 | } | |
345 | } | |
346 | impl PartialEq for ParamKindOrd { | |
347 | fn eq(&self, other: &Self) -> bool { | |
348 | self.cmp(other) == Ordering::Equal | |
349 | } | |
9fa01778 | 350 | } |
3dfed10e | 351 | impl Eq for ParamKindOrd {} |
9fa01778 XL |
352 | |
353 | impl fmt::Display for ParamKindOrd { | |
354 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
355 | match self { | |
356 | ParamKindOrd::Lifetime => "lifetime".fmt(f), | |
357 | ParamKindOrd::Type => "type".fmt(f), | |
3dfed10e | 358 | ParamKindOrd::Const { .. } => "const".fmt(f), |
9fa01778 XL |
359 | } |
360 | } | |
361 | } | |
362 | ||
3dfed10e | 363 | #[derive(Clone, Encodable, Decodable, Debug)] |
8faf50e0 | 364 | pub enum GenericParamKind { |
0731742a | 365 | /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). |
8faf50e0 | 366 | Lifetime, |
dfeec247 XL |
367 | Type { |
368 | default: Option<P<Ty>>, | |
369 | }, | |
370 | Const { | |
371 | ty: P<Ty>, | |
f035d41b XL |
372 | /// Span of the `const` keyword. |
373 | kw_span: Span, | |
dfeec247 | 374 | }, |
ff7c6d11 XL |
375 | } |
376 | ||
3dfed10e | 377 | #[derive(Clone, Encodable, Decodable, Debug)] |
8faf50e0 XL |
378 | pub struct GenericParam { |
379 | pub id: NodeId, | |
380 | pub ident: Ident, | |
dfeec247 | 381 | pub attrs: AttrVec, |
8faf50e0 | 382 | pub bounds: GenericBounds, |
e1599b0c | 383 | pub is_placeholder: bool, |
8faf50e0 | 384 | pub kind: GenericParamKind, |
ff7c6d11 XL |
385 | } |
386 | ||
387 | /// Represents lifetime, type and const parameters attached to a declaration of | |
388 | /// a function, enum, trait, etc. | |
3dfed10e | 389 | #[derive(Clone, Encodable, Decodable, Debug)] |
223e47cc | 390 | pub struct Generics { |
ff7c6d11 | 391 | pub params: Vec<GenericParam>, |
1a4d82fc | 392 | pub where_clause: WhereClause, |
9e0c209e | 393 | pub span: Span, |
223e47cc LB |
394 | } |
395 | ||
9cc50fc6 | 396 | impl Default for Generics { |
9e0c209e | 397 | /// Creates an instance of `Generics`. |
0bf4aa26 | 398 | fn default() -> Generics { |
9cc50fc6 | 399 | Generics { |
ff7c6d11 | 400 | params: Vec::new(), |
f035d41b XL |
401 | where_clause: WhereClause { |
402 | has_where_token: false, | |
403 | predicates: Vec::new(), | |
404 | span: DUMMY_SP, | |
405 | }, | |
9e0c209e | 406 | span: DUMMY_SP, |
9cc50fc6 SL |
407 | } |
408 | } | |
409 | } | |
410 | ||
9fa01778 | 411 | /// A where-clause in a definition. |
3dfed10e | 412 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 413 | pub struct WhereClause { |
f035d41b | 414 | /// `true` if we ate a `where` token: this can happen |
3dfed10e | 415 | /// if we parsed no predicates (e.g. `struct Foo where {}`). |
f035d41b XL |
416 | /// This allows us to accurately pretty-print |
417 | /// in `nt_to_tokenstream` | |
418 | pub has_where_token: bool, | |
1a4d82fc | 419 | pub predicates: Vec<WherePredicate>, |
3b2f2976 | 420 | pub span: Span, |
223e47cc LB |
421 | } |
422 | ||
9fa01778 | 423 | /// A single predicate in a where-clause. |
3dfed10e | 424 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 425 | pub enum WherePredicate { |
0731742a | 426 | /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`). |
1a4d82fc | 427 | BoundPredicate(WhereBoundPredicate), |
0731742a | 428 | /// A lifetime predicate (e.g., `'a: 'b + 'c`). |
1a4d82fc | 429 | RegionPredicate(WhereRegionPredicate), |
0731742a | 430 | /// An equality predicate (unsupported). |
e9174d1e | 431 | EqPredicate(WhereEqPredicate), |
223e47cc LB |
432 | } |
433 | ||
0531ce1d XL |
434 | impl WherePredicate { |
435 | pub fn span(&self) -> Span { | |
436 | match self { | |
437 | &WherePredicate::BoundPredicate(ref p) => p.span, | |
438 | &WherePredicate::RegionPredicate(ref p) => p.span, | |
439 | &WherePredicate::EqPredicate(ref p) => p.span, | |
440 | } | |
441 | } | |
442 | } | |
443 | ||
3157f602 XL |
444 | /// A type bound. |
445 | /// | |
0731742a | 446 | /// E.g., `for<'c> Foo: Send + Clone + 'c`. |
3dfed10e | 447 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
448 | pub struct WhereBoundPredicate { |
449 | pub span: Span, | |
e1599b0c | 450 | /// Any generics from a `for` binding. |
ff7c6d11 | 451 | pub bound_generic_params: Vec<GenericParam>, |
e1599b0c | 452 | /// The type being bounded. |
1a4d82fc | 453 | pub bounded_ty: P<Ty>, |
e1599b0c | 454 | /// Trait and lifetime bounds (`Clone + Send + 'static`). |
8faf50e0 | 455 | pub bounds: GenericBounds, |
223e47cc LB |
456 | } |
457 | ||
3157f602 XL |
458 | /// A lifetime predicate. |
459 | /// | |
0731742a | 460 | /// E.g., `'a: 'b + 'c`. |
3dfed10e | 461 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
462 | pub struct WhereRegionPredicate { |
463 | pub span: Span, | |
464 | pub lifetime: Lifetime, | |
8faf50e0 | 465 | pub bounds: GenericBounds, |
1a4d82fc | 466 | } |
223e47cc | 467 | |
3157f602 XL |
468 | /// An equality predicate (unsupported). |
469 | /// | |
0731742a | 470 | /// E.g., `T = int`. |
3dfed10e | 471 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
472 | pub struct WhereEqPredicate { |
473 | pub id: NodeId, | |
474 | pub span: Span, | |
32a655c1 SL |
475 | pub lhs_ty: P<Ty>, |
476 | pub rhs_ty: P<Ty>, | |
1a4d82fc JJ |
477 | } |
478 | ||
3dfed10e | 479 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
480 | pub struct Crate { |
481 | pub module: Mod, | |
482 | pub attrs: Vec<Attribute>, | |
1a4d82fc | 483 | pub span: Span, |
74b04a01 XL |
484 | /// The order of items in the HIR is unrelated to the order of |
485 | /// items in the AST. However, we generate proc macro harnesses | |
486 | /// based on the AST order, and later refer to these harnesses | |
487 | /// from the HIR. This field keeps track of the order in which | |
488 | /// we generated proc macros harnesses, so that we can map | |
489 | /// HIR proc macros items back to their harness items. | |
490 | pub proc_macros: Vec<NodeId>, | |
970d7e83 | 491 | } |
223e47cc | 492 | |
9e0c209e SL |
493 | /// Possible values inside of compile-time attribute lists. |
494 | /// | |
0731742a | 495 | /// E.g., the '..' in `#[name(..)]`. |
3dfed10e | 496 | #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
532ac7d7 | 497 | pub enum NestedMetaItem { |
9e0c209e | 498 | /// A full MetaItem, for recursive meta items. |
476ff2be | 499 | MetaItem(MetaItem), |
9e0c209e SL |
500 | /// A literal. |
501 | /// | |
0731742a | 502 | /// E.g., `"foo"`, `64`, `true`. |
9e0c209e SL |
503 | Literal(Lit), |
504 | } | |
505 | ||
3157f602 XL |
506 | /// A spanned compile-time attribute item. |
507 | /// | |
0731742a | 508 | /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`. |
3dfed10e | 509 | #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
476ff2be | 510 | pub struct MetaItem { |
532ac7d7 | 511 | pub path: Path, |
e74abb32 | 512 | pub kind: MetaItemKind, |
476ff2be SL |
513 | pub span: Span, |
514 | } | |
1a4d82fc | 515 | |
3157f602 XL |
516 | /// A compile-time attribute item. |
517 | /// | |
0731742a | 518 | /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`. |
3dfed10e | 519 | #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
7453a54e | 520 | pub enum MetaItemKind { |
3157f602 XL |
521 | /// Word meta item. |
522 | /// | |
0731742a | 523 | /// E.g., `test` as in `#[test]`. |
476ff2be | 524 | Word, |
3157f602 XL |
525 | /// List meta item. |
526 | /// | |
0731742a | 527 | /// E.g., `derive(..)` as in `#[derive(..)]`. |
476ff2be | 528 | List(Vec<NestedMetaItem>), |
3157f602 XL |
529 | /// Name value meta item. |
530 | /// | |
0731742a | 531 | /// E.g., `feature = "foo"` as in `#[feature = "foo"]`. |
0bf4aa26 | 532 | NameValue(Lit), |
223e47cc LB |
533 | } |
534 | ||
e1599b0c | 535 | /// A block (`{ .. }`). |
3157f602 | 536 | /// |
0731742a | 537 | /// E.g., `{ .. }` as in `fn foo() { .. }`. |
3dfed10e | 538 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 539 | pub struct Block { |
e1599b0c | 540 | /// The statements in the block. |
7453a54e | 541 | pub stmts: Vec<Stmt>, |
1a4d82fc | 542 | pub id: NodeId, |
e1599b0c | 543 | /// Distinguishes between `unsafe { ... }` and `{ ... }`. |
1a4d82fc JJ |
544 | pub rules: BlockCheckMode, |
545 | pub span: Span, | |
29967ef6 | 546 | pub tokens: Option<LazyTokenStream>, |
1a4d82fc JJ |
547 | } |
548 | ||
f035d41b XL |
549 | /// A match pattern. |
550 | /// | |
551 | /// Patterns appear in match statements and some other contexts, such as `let` and `if let`. | |
3dfed10e | 552 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
553 | pub struct Pat { |
554 | pub id: NodeId, | |
e74abb32 | 555 | pub kind: PatKind, |
1a4d82fc | 556 | pub span: Span, |
29967ef6 | 557 | pub tokens: Option<LazyTokenStream>, |
1a4d82fc JJ |
558 | } |
559 | ||
a7813a04 | 560 | impl Pat { |
416331ca XL |
561 | /// Attempt reparsing the pattern as a type. |
562 | /// This is intended for use by diagnostics. | |
60c5eb7d | 563 | pub fn to_ty(&self) -> Option<P<Ty>> { |
e74abb32 | 564 | let kind = match &self.kind { |
416331ca | 565 | // In a type expression `_` is an inference variable. |
ff7c6d11 | 566 | PatKind::Wild => TyKind::Infer, |
416331ca | 567 | // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`. |
dfeec247 | 568 | PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => { |
0bf4aa26 XL |
569 | TyKind::Path(None, Path::from_ident(*ident)) |
570 | } | |
ff7c6d11 | 571 | PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), |
ba9703b0 | 572 | PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()), |
416331ca | 573 | // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type. |
dfeec247 XL |
574 | PatKind::Ref(pat, mutbl) => { |
575 | pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))? | |
576 | } | |
416331ca XL |
577 | // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array, |
578 | // when `P` can be reparsed as a type `T`. | |
579 | PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?, | |
580 | // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)` | |
581 | // assuming `T0` to `Tn` are all syntactically valid as types. | |
582 | PatKind::Tuple(pats) => { | |
b7449926 XL |
583 | let mut tys = Vec::with_capacity(pats.len()); |
584 | // FIXME(#48994) - could just be collected into an Option<Vec> | |
585 | for pat in pats { | |
586 | tys.push(pat.to_ty()?); | |
587 | } | |
ff7c6d11 XL |
588 | TyKind::Tup(tys) |
589 | } | |
590 | _ => return None, | |
591 | }; | |
592 | ||
1b1a35ee | 593 | Some(P(Ty { kind, id: self.id, span: self.span, tokens: None })) |
ff7c6d11 XL |
594 | } |
595 | ||
e1599b0c XL |
596 | /// Walk top-down and call `it` in each place where a pattern occurs |
597 | /// starting with the root pattern `walk` is called on. If `it` returns | |
598 | /// false then we will descend no further but siblings will be processed. | |
599 | pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) { | |
a7813a04 | 600 | if !it(self) { |
e1599b0c | 601 | return; |
a7813a04 XL |
602 | } |
603 | ||
e74abb32 XL |
604 | match &self.kind { |
605 | // Walk into the pattern associated with `Ident` (if any). | |
416331ca | 606 | PatKind::Ident(_, _, Some(p)) => p.walk(it), |
e74abb32 XL |
607 | |
608 | // Walk into each field of struct. | |
e1599b0c | 609 | PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)), |
e74abb32 XL |
610 | |
611 | // Sequence of patterns. | |
dfeec247 XL |
612 | PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => { |
613 | s.iter().for_each(|p| p.walk(it)) | |
614 | } | |
e74abb32 XL |
615 | |
616 | // Trivial wrappers over inner patterns. | |
dfeec247 | 617 | PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it), |
e74abb32 XL |
618 | |
619 | // These patterns do not contain subpatterns, skip. | |
0bf4aa26 | 620 | PatKind::Wild |
416331ca | 621 | | PatKind::Rest |
0bf4aa26 XL |
622 | | PatKind::Lit(_) |
623 | | PatKind::Range(..) | |
624 | | PatKind::Ident(..) | |
625 | | PatKind::Path(..) | |
ba9703b0 | 626 | | PatKind::MacCall(_) => {} |
a7813a04 XL |
627 | } |
628 | } | |
416331ca XL |
629 | |
630 | /// Is this a `..` pattern? | |
631 | pub fn is_rest(&self) -> bool { | |
e74abb32 | 632 | match self.kind { |
416331ca XL |
633 | PatKind::Rest => true, |
634 | _ => false, | |
635 | } | |
636 | } | |
a7813a04 XL |
637 | } |
638 | ||
c34b1796 AL |
639 | /// A single field in a struct pattern |
640 | /// | |
641 | /// Patterns like the fields of Foo `{ x, ref y, ref mut z }` | |
642 | /// are treated the same as` x: x, y: ref y, z: ref mut z`, | |
643 | /// except is_shorthand is true | |
3dfed10e | 644 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 645 | pub struct FieldPat { |
c34b1796 | 646 | /// The identifier for the field |
1a4d82fc | 647 | pub ident: Ident, |
c34b1796 | 648 | /// The pattern the field is destructured to |
1a4d82fc JJ |
649 | pub pat: P<Pat>, |
650 | pub is_shorthand: bool, | |
dfeec247 | 651 | pub attrs: AttrVec, |
e1599b0c XL |
652 | pub id: NodeId, |
653 | pub span: Span, | |
654 | pub is_placeholder: bool, | |
1a4d82fc JJ |
655 | } |
656 | ||
3dfed10e | 657 | #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] |
1a4d82fc | 658 | pub enum BindingMode { |
9cc50fc6 SL |
659 | ByRef(Mutability), |
660 | ByValue(Mutability), | |
1a4d82fc JJ |
661 | } |
662 | ||
3dfed10e | 663 | #[derive(Clone, Encodable, Decodable, Debug)] |
32a655c1 | 664 | pub enum RangeEnd { |
ea8adc8c | 665 | Included(RangeSyntax), |
32a655c1 SL |
666 | Excluded, |
667 | } | |
668 | ||
3dfed10e | 669 | #[derive(Clone, Encodable, Decodable, Debug)] |
ea8adc8c | 670 | pub enum RangeSyntax { |
e74abb32 | 671 | /// `...` |
ea8adc8c | 672 | DotDotDot, |
e74abb32 | 673 | /// `..=` |
ea8adc8c XL |
674 | DotDotEq, |
675 | } | |
676 | ||
3dfed10e | 677 | #[derive(Clone, Encodable, Decodable, Debug)] |
7453a54e | 678 | pub enum PatKind { |
0731742a | 679 | /// Represents a wildcard pattern (`_`). |
7453a54e | 680 | Wild, |
1a4d82fc | 681 | |
3157f602 XL |
682 | /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`), |
683 | /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third | |
684 | /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens | |
685 | /// during name resolution. | |
83c7162d | 686 | Ident(BindingMode, Ident, Option<P<Pat>>), |
1a4d82fc | 687 | |
0731742a | 688 | /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`). |
7453a54e | 689 | /// The `bool` is `true` in the presence of a `..`. |
e1599b0c | 690 | Struct(Path, Vec<FieldPat>, /* recovered */ bool), |
7453a54e | 691 | |
0731742a | 692 | /// A tuple struct/variant pattern (`Variant(x, y, .., z)`). |
416331ca | 693 | TupleStruct(Path, Vec<P<Pat>>), |
1a4d82fc | 694 | |
e1599b0c XL |
695 | /// An or-pattern `A | B | C`. |
696 | /// Invariant: `pats.len() >= 2`. | |
697 | Or(Vec<P<Pat>>), | |
698 | ||
3157f602 | 699 | /// A possibly qualified path pattern. |
3b2f2976 XL |
700 | /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants |
701 | /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can | |
3157f602 XL |
702 | /// only legally refer to associated constants. |
703 | Path(Option<QSelf>, Path), | |
d9579d0f | 704 | |
0731742a | 705 | /// A tuple pattern (`(a, b)`). |
416331ca | 706 | Tuple(Vec<P<Pat>>), |
9fa01778 | 707 | |
0731742a | 708 | /// A `box` pattern. |
7453a54e | 709 | Box(P<Pat>), |
9fa01778 | 710 | |
0731742a | 711 | /// A reference pattern (e.g., `&mut (a, b)`). |
7453a54e | 712 | Ref(P<Pat>, Mutability), |
9fa01778 | 713 | |
0731742a | 714 | /// A literal. |
7453a54e | 715 | Lit(P<Expr>), |
9fa01778 | 716 | |
0731742a | 717 | /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`). |
dfeec247 | 718 | Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>), |
9fa01778 | 719 | |
416331ca XL |
720 | /// A slice pattern `[a, b, c]`. |
721 | Slice(Vec<P<Pat>>), | |
722 | ||
723 | /// A rest pattern `..`. | |
724 | /// | |
725 | /// Syntactically it is valid anywhere. | |
726 | /// | |
727 | /// Semantically however, it only has meaning immediately inside: | |
728 | /// - a slice pattern: `[a, .., b]`, | |
729 | /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`, | |
730 | /// - a tuple pattern: `(a, .., b)`, | |
731 | /// - a tuple struct/variant pattern: `$path(a, .., b)`. | |
732 | /// | |
733 | /// In all of these cases, an additional restriction applies, | |
734 | /// only one rest pattern may occur in the pattern sequences. | |
735 | Rest, | |
9fa01778 | 736 | |
0731742a | 737 | /// Parentheses in patterns used for grouping (i.e., `(PAT)`). |
0531ce1d | 738 | Paren(P<Pat>), |
9fa01778 | 739 | |
0731742a | 740 | /// A macro pattern; pre-expansion. |
ba9703b0 | 741 | MacCall(MacCall), |
1a4d82fc JJ |
742 | } |
743 | ||
3dfed10e XL |
744 | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)] |
745 | #[derive(HashStable_Generic, Encodable, Decodable)] | |
1a4d82fc | 746 | pub enum Mutability { |
dfeec247 XL |
747 | Mut, |
748 | Not, | |
1a4d82fc JJ |
749 | } |
750 | ||
60c5eb7d XL |
751 | impl Mutability { |
752 | /// Returns `MutMutable` only if both `self` and `other` are mutable. | |
753 | pub fn and(self, other: Self) -> Self { | |
754 | match self { | |
dfeec247 XL |
755 | Mutability::Mut => other, |
756 | Mutability::Not => Mutability::Not, | |
60c5eb7d XL |
757 | } |
758 | } | |
759 | ||
760 | pub fn invert(self) -> Self { | |
761 | match self { | |
dfeec247 XL |
762 | Mutability::Mut => Mutability::Not, |
763 | Mutability::Not => Mutability::Mut, | |
60c5eb7d XL |
764 | } |
765 | } | |
766 | ||
767 | pub fn prefix_str(&self) -> &'static str { | |
768 | match self { | |
dfeec247 XL |
769 | Mutability::Mut => "mut ", |
770 | Mutability::Not => "", | |
60c5eb7d XL |
771 | } |
772 | } | |
773 | } | |
774 | ||
775 | /// The kind of borrow in an `AddrOf` expression, | |
776 | /// e.g., `&place` or `&raw const place`. | |
777 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] | |
3dfed10e | 778 | #[derive(Encodable, Decodable, HashStable_Generic)] |
60c5eb7d | 779 | pub enum BorrowKind { |
60c5eb7d XL |
780 | /// A normal borrow, `&$expr` or `&mut $expr`. |
781 | /// The resulting type is either `&'a T` or `&'a mut T` | |
782 | /// where `T = typeof($expr)` and `'a` is some lifetime. | |
dfeec247 XL |
783 | Ref, |
784 | /// A raw borrow, `&raw const $expr` or `&raw mut $expr`. | |
785 | /// The resulting type is either `*const T` or `*mut T` | |
786 | /// where `T = typeof($expr)`. | |
60c5eb7d XL |
787 | Raw, |
788 | } | |
789 | ||
3dfed10e | 790 | #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] |
7453a54e | 791 | pub enum BinOpKind { |
c34b1796 | 792 | /// The `+` operator (addition) |
7453a54e | 793 | Add, |
c34b1796 | 794 | /// The `-` operator (subtraction) |
7453a54e | 795 | Sub, |
c34b1796 | 796 | /// The `*` operator (multiplication) |
7453a54e | 797 | Mul, |
c34b1796 | 798 | /// The `/` operator (division) |
7453a54e | 799 | Div, |
c34b1796 | 800 | /// The `%` operator (modulus) |
7453a54e | 801 | Rem, |
c34b1796 | 802 | /// The `&&` operator (logical and) |
7453a54e | 803 | And, |
c34b1796 | 804 | /// The `||` operator (logical or) |
7453a54e | 805 | Or, |
c34b1796 | 806 | /// The `^` operator (bitwise xor) |
7453a54e | 807 | BitXor, |
c34b1796 | 808 | /// The `&` operator (bitwise and) |
7453a54e | 809 | BitAnd, |
c34b1796 | 810 | /// The `|` operator (bitwise or) |
7453a54e | 811 | BitOr, |
c34b1796 | 812 | /// The `<<` operator (shift left) |
7453a54e | 813 | Shl, |
c34b1796 | 814 | /// The `>>` operator (shift right) |
7453a54e | 815 | Shr, |
c34b1796 | 816 | /// The `==` operator (equality) |
7453a54e | 817 | Eq, |
c34b1796 | 818 | /// The `<` operator (less than) |
7453a54e | 819 | Lt, |
c34b1796 | 820 | /// The `<=` operator (less than or equal to) |
7453a54e | 821 | Le, |
c34b1796 | 822 | /// The `!=` operator (not equal to) |
7453a54e | 823 | Ne, |
c34b1796 | 824 | /// The `>=` operator (greater than or equal to) |
7453a54e | 825 | Ge, |
c34b1796 | 826 | /// The `>` operator (greater than) |
7453a54e | 827 | Gt, |
1a4d82fc JJ |
828 | } |
829 | ||
7453a54e | 830 | impl BinOpKind { |
9cc50fc6 | 831 | pub fn to_string(&self) -> &'static str { |
9fa01778 | 832 | use BinOpKind::*; |
9cc50fc6 | 833 | match *self { |
7453a54e SL |
834 | Add => "+", |
835 | Sub => "-", | |
836 | Mul => "*", | |
837 | Div => "/", | |
838 | Rem => "%", | |
839 | And => "&&", | |
840 | Or => "||", | |
841 | BitXor => "^", | |
842 | BitAnd => "&", | |
843 | BitOr => "|", | |
844 | Shl => "<<", | |
845 | Shr => ">>", | |
846 | Eq => "==", | |
847 | Lt => "<", | |
848 | Le => "<=", | |
849 | Ne => "!=", | |
850 | Ge => ">=", | |
851 | Gt => ">", | |
9cc50fc6 SL |
852 | } |
853 | } | |
854 | pub fn lazy(&self) -> bool { | |
855 | match *self { | |
7453a54e | 856 | BinOpKind::And | BinOpKind::Or => true, |
0bf4aa26 | 857 | _ => false, |
9cc50fc6 SL |
858 | } |
859 | } | |
860 | ||
9cc50fc6 | 861 | pub fn is_comparison(&self) -> bool { |
9fa01778 | 862 | use BinOpKind::*; |
e74abb32 XL |
863 | // Note for developers: please keep this as is; |
864 | // we want compilation to fail if another variant is added. | |
9cc50fc6 | 865 | match *self { |
0bf4aa26 XL |
866 | Eq | Lt | Le | Ne | Gt | Ge => true, |
867 | And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false, | |
9cc50fc6 SL |
868 | } |
869 | } | |
9cc50fc6 SL |
870 | } |
871 | ||
7453a54e | 872 | pub type BinOp = Spanned<BinOpKind>; |
85aaf69f | 873 | |
e74abb32 XL |
874 | /// Unary operator. |
875 | /// | |
876 | /// Note that `&data` is not an operator, it's an `AddrOf` expression. | |
3dfed10e | 877 | #[derive(Clone, Encodable, Decodable, Debug, Copy)] |
1a4d82fc | 878 | pub enum UnOp { |
c34b1796 | 879 | /// The `*` operator for dereferencing |
7453a54e | 880 | Deref, |
c34b1796 | 881 | /// The `!` operator for logical inversion |
7453a54e | 882 | Not, |
c34b1796 | 883 | /// The `-` operator for negation |
7453a54e | 884 | Neg, |
1a4d82fc JJ |
885 | } |
886 | ||
9cc50fc6 | 887 | impl UnOp { |
9cc50fc6 SL |
888 | pub fn to_string(op: UnOp) -> &'static str { |
889 | match op { | |
7453a54e SL |
890 | UnOp::Deref => "*", |
891 | UnOp::Not => "!", | |
892 | UnOp::Neg => "-", | |
9cc50fc6 SL |
893 | } |
894 | } | |
895 | } | |
896 | ||
c34b1796 | 897 | /// A statement |
3dfed10e | 898 | #[derive(Clone, Encodable, Decodable, Debug)] |
3157f602 XL |
899 | pub struct Stmt { |
900 | pub id: NodeId, | |
e74abb32 | 901 | pub kind: StmtKind, |
3157f602 XL |
902 | pub span: Span, |
903 | } | |
1a4d82fc | 904 | |
5bcae85e | 905 | impl Stmt { |
fc512014 XL |
906 | pub fn tokens(&self) -> Option<&LazyTokenStream> { |
907 | match self.kind { | |
908 | StmtKind::Local(ref local) => local.tokens.as_ref(), | |
909 | StmtKind::Item(ref item) => item.tokens.as_ref(), | |
910 | StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => expr.tokens.as_ref(), | |
911 | StmtKind::Empty => None, | |
912 | StmtKind::MacCall(ref mac) => mac.tokens.as_ref(), | |
913 | } | |
914 | } | |
915 | ||
916 | pub fn tokens_mut(&mut self) -> Option<&mut LazyTokenStream> { | |
917 | match self.kind { | |
918 | StmtKind::Local(ref mut local) => local.tokens.as_mut(), | |
919 | StmtKind::Item(ref mut item) => item.tokens.as_mut(), | |
920 | StmtKind::Expr(ref mut expr) | StmtKind::Semi(ref mut expr) => expr.tokens.as_mut(), | |
921 | StmtKind::Empty => None, | |
922 | StmtKind::MacCall(ref mut mac) => mac.tokens.as_mut(), | |
923 | } | |
924 | } | |
925 | ||
926 | pub fn set_tokens(&mut self, tokens: Option<LazyTokenStream>) { | |
927 | match self.kind { | |
928 | StmtKind::Local(ref mut local) => local.tokens = tokens, | |
929 | StmtKind::Item(ref mut item) => item.tokens = tokens, | |
930 | StmtKind::Expr(ref mut expr) | StmtKind::Semi(ref mut expr) => expr.tokens = tokens, | |
931 | StmtKind::Empty => {} | |
932 | StmtKind::MacCall(ref mut mac) => mac.tokens = tokens, | |
933 | } | |
934 | } | |
935 | ||
29967ef6 XL |
936 | pub fn has_trailing_semicolon(&self) -> bool { |
937 | match &self.kind { | |
938 | StmtKind::Semi(_) => true, | |
939 | StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon), | |
940 | _ => false, | |
941 | } | |
942 | } | |
fc512014 XL |
943 | |
944 | /// Converts a parsed `Stmt` to a `Stmt` with | |
945 | /// a trailing semicolon. | |
946 | /// | |
947 | /// This only modifies the parsed AST struct, not the attached | |
948 | /// `LazyTokenStream`. The parser is responsible for calling | |
949 | /// `CreateTokenStream::add_trailing_semi` when there is actually | |
950 | /// a semicolon in the tokenstream. | |
5bcae85e | 951 | pub fn add_trailing_semicolon(mut self) -> Self { |
e74abb32 | 952 | self.kind = match self.kind { |
5bcae85e | 953 | StmtKind::Expr(expr) => StmtKind::Semi(expr), |
1b1a35ee | 954 | StmtKind::MacCall(mac) => { |
fc512014 XL |
955 | StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| { |
956 | MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens } | |
1b1a35ee XL |
957 | })) |
958 | } | |
e74abb32 | 959 | kind => kind, |
5bcae85e | 960 | }; |
fc512014 | 961 | |
5bcae85e SL |
962 | self |
963 | } | |
3b2f2976 XL |
964 | |
965 | pub fn is_item(&self) -> bool { | |
e74abb32 | 966 | match self.kind { |
0531ce1d XL |
967 | StmtKind::Item(_) => true, |
968 | _ => false, | |
969 | } | |
970 | } | |
971 | ||
972 | pub fn is_expr(&self) -> bool { | |
e74abb32 | 973 | match self.kind { |
0531ce1d | 974 | StmtKind::Expr(_) => true, |
3b2f2976 XL |
975 | _ => false, |
976 | } | |
977 | } | |
5bcae85e SL |
978 | } |
979 | ||
3dfed10e | 980 | #[derive(Clone, Encodable, Decodable, Debug)] |
7453a54e | 981 | pub enum StmtKind { |
3157f602 XL |
982 | /// A local (let) binding. |
983 | Local(P<Local>), | |
3157f602 XL |
984 | /// An item definition. |
985 | Item(P<Item>), | |
3157f602 XL |
986 | /// Expr without trailing semi-colon. |
987 | Expr(P<Expr>), | |
ea8adc8c | 988 | /// Expr with a trailing semi-colon. |
3157f602 | 989 | Semi(P<Expr>), |
74b04a01 XL |
990 | /// Just a trailing semi-colon. |
991 | Empty, | |
ea8adc8c | 992 | /// Macro. |
1b1a35ee XL |
993 | MacCall(P<MacCallStmt>), |
994 | } | |
995 | ||
996 | #[derive(Clone, Encodable, Decodable, Debug)] | |
997 | pub struct MacCallStmt { | |
998 | pub mac: MacCall, | |
999 | pub style: MacStmtStyle, | |
1000 | pub attrs: AttrVec, | |
fc512014 | 1001 | pub tokens: Option<LazyTokenStream>, |
92a42be0 SL |
1002 | } |
1003 | ||
3dfed10e | 1004 | #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)] |
1a4d82fc | 1005 | pub enum MacStmtStyle { |
0731742a XL |
1006 | /// The macro statement had a trailing semicolon (e.g., `foo! { ... };` |
1007 | /// `foo!(...);`, `foo![...];`). | |
7453a54e | 1008 | Semicolon, |
0731742a | 1009 | /// The macro statement had braces (e.g., `foo! { ... }`). |
7453a54e | 1010 | Braces, |
0731742a XL |
1011 | /// The macro statement had parentheses or brackets and no semicolon (e.g., |
1012 | /// `foo!(...)`). All of these will end up being converted into macro | |
1a4d82fc | 1013 | /// expressions. |
7453a54e | 1014 | NoBraces, |
1a4d82fc JJ |
1015 | } |
1016 | ||
0731742a | 1017 | /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`. |
3dfed10e | 1018 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 1019 | pub struct Local { |
e1599b0c | 1020 | pub id: NodeId, |
1a4d82fc JJ |
1021 | pub pat: P<Pat>, |
1022 | pub ty: Option<P<Ty>>, | |
0731742a | 1023 | /// Initializer expression to set the value, if any. |
1a4d82fc | 1024 | pub init: Option<P<Expr>>, |
1a4d82fc | 1025 | pub span: Span, |
dfeec247 | 1026 | pub attrs: AttrVec, |
fc512014 | 1027 | pub tokens: Option<LazyTokenStream>, |
1a4d82fc JJ |
1028 | } |
1029 | ||
3157f602 XL |
1030 | /// An arm of a 'match'. |
1031 | /// | |
0731742a | 1032 | /// E.g., `0..=10 => { println!("match!") }` as in |
3157f602 | 1033 | /// |
041b39d2 XL |
1034 | /// ``` |
1035 | /// match 123 { | |
8faf50e0 | 1036 | /// 0..=10 => { println!("match!") }, |
041b39d2 | 1037 | /// _ => { println!("no match!") }, |
3157f602 XL |
1038 | /// } |
1039 | /// ``` | |
3dfed10e | 1040 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
1041 | pub struct Arm { |
1042 | pub attrs: Vec<Attribute>, | |
e74abb32 | 1043 | /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }` |
e1599b0c | 1044 | pub pat: P<Pat>, |
e74abb32 | 1045 | /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }` |
dc9dc135 | 1046 | pub guard: Option<P<Expr>>, |
e74abb32 | 1047 | /// Match arm body. |
1a4d82fc | 1048 | pub body: P<Expr>, |
dc9dc135 | 1049 | pub span: Span, |
e1599b0c XL |
1050 | pub id: NodeId, |
1051 | pub is_placeholder: bool, | |
b7449926 XL |
1052 | } |
1053 | ||
e74abb32 | 1054 | /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field. |
3dfed10e | 1055 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 1056 | pub struct Field { |
dfeec247 | 1057 | pub attrs: AttrVec, |
60c5eb7d XL |
1058 | pub id: NodeId, |
1059 | pub span: Span, | |
83c7162d | 1060 | pub ident: Ident, |
1a4d82fc | 1061 | pub expr: P<Expr>, |
c30ab7b3 | 1062 | pub is_shorthand: bool, |
e1599b0c | 1063 | pub is_placeholder: bool, |
1a4d82fc JJ |
1064 | } |
1065 | ||
3dfed10e | 1066 | #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] |
1a4d82fc | 1067 | pub enum BlockCheckMode { |
7453a54e SL |
1068 | Default, |
1069 | Unsafe(UnsafeSource), | |
1a4d82fc JJ |
1070 | } |
1071 | ||
3dfed10e | 1072 | #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] |
1a4d82fc JJ |
1073 | pub enum UnsafeSource { |
1074 | CompilerGenerated, | |
1075 | UserProvided, | |
1076 | } | |
1077 | ||
94b46f34 XL |
1078 | /// A constant (expression) that's not an item or associated item, |
1079 | /// but needs its own `DefId` for type-checking, const-eval, etc. | |
0731742a XL |
1080 | /// These are usually found nested inside types (e.g., array lengths) |
1081 | /// or expressions (e.g., repeat counts), and also used to define | |
94b46f34 | 1082 | /// explicit discriminant values for enum variants. |
3dfed10e | 1083 | #[derive(Clone, Encodable, Decodable, Debug)] |
94b46f34 XL |
1084 | pub struct AnonConst { |
1085 | pub id: NodeId, | |
1086 | pub value: P<Expr>, | |
1087 | } | |
1088 | ||
e1599b0c | 1089 | /// An expression. |
3dfed10e | 1090 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
1091 | pub struct Expr { |
1092 | pub id: NodeId, | |
e74abb32 | 1093 | pub kind: ExprKind, |
1a4d82fc | 1094 | pub span: Span, |
dfeec247 | 1095 | pub attrs: AttrVec, |
29967ef6 | 1096 | pub tokens: Option<LazyTokenStream>, |
1a4d82fc JJ |
1097 | } |
1098 | ||
a1dfa0c6 XL |
1099 | // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger. |
1100 | #[cfg(target_arch = "x86_64")] | |
29967ef6 | 1101 | rustc_data_structures::static_assert_size!(Expr, 120); |
a1dfa0c6 | 1102 | |
3b2f2976 | 1103 | impl Expr { |
e1599b0c XL |
1104 | /// Returns `true` if this expression would be valid somewhere that expects a value; |
1105 | /// for example, an `if` condition. | |
3b2f2976 | 1106 | pub fn returns(&self) -> bool { |
e74abb32 XL |
1107 | if let ExprKind::Block(ref block, _) = self.kind { |
1108 | match block.stmts.last().map(|last_stmt| &last_stmt.kind) { | |
e1599b0c | 1109 | // Implicit return |
3b2f2976 XL |
1110 | Some(&StmtKind::Expr(_)) => true, |
1111 | Some(&StmtKind::Semi(ref expr)) => { | |
e74abb32 | 1112 | if let ExprKind::Ret(_) = expr.kind { |
e1599b0c | 1113 | // Last statement is explicit return. |
3b2f2976 XL |
1114 | true |
1115 | } else { | |
1116 | false | |
1117 | } | |
1118 | } | |
e1599b0c | 1119 | // This is a block that doesn't end in either an implicit or explicit return. |
3b2f2976 XL |
1120 | _ => false, |
1121 | } | |
1122 | } else { | |
e1599b0c | 1123 | // This is not a block, it is a value. |
3b2f2976 XL |
1124 | true |
1125 | } | |
1126 | } | |
ff7c6d11 | 1127 | |
3dfed10e XL |
1128 | /// Is this expr either `N`, or `{ N }`. |
1129 | /// | |
1130 | /// If this is not the case, name resolution does not resolve `N` when using | |
1131 | /// `feature(min_const_generics)` as more complex expressions are not supported. | |
1132 | pub fn is_potential_trivial_const_param(&self) -> bool { | |
1133 | let this = if let ExprKind::Block(ref block, None) = self.kind { | |
1134 | if block.stmts.len() == 1 { | |
1135 | if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self } | |
1136 | } else { | |
1137 | self | |
1138 | } | |
1139 | } else { | |
1140 | self | |
1141 | }; | |
1142 | ||
1143 | if let ExprKind::Path(None, ref path) = this.kind { | |
1144 | if path.segments.len() == 1 && path.segments[0].args.is_none() { | |
1145 | return true; | |
1146 | } | |
1147 | } | |
1148 | ||
1149 | false | |
1150 | } | |
1151 | ||
60c5eb7d | 1152 | pub fn to_bound(&self) -> Option<GenericBound> { |
e74abb32 | 1153 | match &self.kind { |
0bf4aa26 XL |
1154 | ExprKind::Path(None, path) => Some(GenericBound::Trait( |
1155 | PolyTraitRef::new(Vec::new(), path.clone(), self.span), | |
1156 | TraitBoundModifier::None, | |
1157 | )), | |
ff7c6d11 XL |
1158 | _ => None, |
1159 | } | |
1160 | } | |
1161 | ||
e74abb32 | 1162 | /// Attempts to reparse as `Ty` (for diagnostic purposes). |
60c5eb7d | 1163 | pub fn to_ty(&self) -> Option<P<Ty>> { |
e74abb32 XL |
1164 | let kind = match &self.kind { |
1165 | // Trivial conversions. | |
ff7c6d11 | 1166 | ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), |
ba9703b0 | 1167 | ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()), |
e74abb32 | 1168 | |
ff7c6d11 | 1169 | ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?, |
e74abb32 | 1170 | |
dfeec247 XL |
1171 | ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => { |
1172 | expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))? | |
1173 | } | |
e74abb32 | 1174 | |
0bf4aa26 XL |
1175 | ExprKind::Repeat(expr, expr_len) => { |
1176 | expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))? | |
1177 | } | |
e74abb32 | 1178 | |
0bf4aa26 | 1179 | ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?, |
e74abb32 | 1180 | |
ff7c6d11 | 1181 | ExprKind::Tup(exprs) => { |
dfeec247 | 1182 | let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?; |
ff7c6d11 XL |
1183 | TyKind::Tup(tys) |
1184 | } | |
e74abb32 XL |
1185 | |
1186 | // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds, | |
1187 | // then type of result is trait object. | |
74b04a01 | 1188 | // Otherwise we don't assume the result type. |
0bf4aa26 | 1189 | ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => { |
ff7c6d11 XL |
1190 | if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) { |
1191 | TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None) | |
1192 | } else { | |
1193 | return None; | |
1194 | } | |
0bf4aa26 | 1195 | } |
e74abb32 XL |
1196 | |
1197 | // This expression doesn't look like a type syntactically. | |
ff7c6d11 XL |
1198 | _ => return None, |
1199 | }; | |
1200 | ||
1b1a35ee | 1201 | Some(P(Ty { kind, id: self.id, span: self.span, tokens: None })) |
ff7c6d11 | 1202 | } |
2c00a5a8 XL |
1203 | |
1204 | pub fn precedence(&self) -> ExprPrecedence { | |
e74abb32 | 1205 | match self.kind { |
2c00a5a8 | 1206 | ExprKind::Box(_) => ExprPrecedence::Box, |
2c00a5a8 | 1207 | ExprKind::Array(_) => ExprPrecedence::Array, |
29967ef6 | 1208 | ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock, |
2c00a5a8 XL |
1209 | ExprKind::Call(..) => ExprPrecedence::Call, |
1210 | ExprKind::MethodCall(..) => ExprPrecedence::MethodCall, | |
1211 | ExprKind::Tup(_) => ExprPrecedence::Tup, | |
1212 | ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node), | |
1213 | ExprKind::Unary(..) => ExprPrecedence::Unary, | |
1214 | ExprKind::Lit(_) => ExprPrecedence::Lit, | |
1215 | ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast, | |
dc9dc135 | 1216 | ExprKind::Let(..) => ExprPrecedence::Let, |
2c00a5a8 | 1217 | ExprKind::If(..) => ExprPrecedence::If, |
2c00a5a8 | 1218 | ExprKind::While(..) => ExprPrecedence::While, |
2c00a5a8 XL |
1219 | ExprKind::ForLoop(..) => ExprPrecedence::ForLoop, |
1220 | ExprKind::Loop(..) => ExprPrecedence::Loop, | |
1221 | ExprKind::Match(..) => ExprPrecedence::Match, | |
1222 | ExprKind::Closure(..) => ExprPrecedence::Closure, | |
1223 | ExprKind::Block(..) => ExprPrecedence::Block, | |
b7449926 | 1224 | ExprKind::TryBlock(..) => ExprPrecedence::TryBlock, |
8faf50e0 | 1225 | ExprKind::Async(..) => ExprPrecedence::Async, |
48663c56 | 1226 | ExprKind::Await(..) => ExprPrecedence::Await, |
2c00a5a8 XL |
1227 | ExprKind::Assign(..) => ExprPrecedence::Assign, |
1228 | ExprKind::AssignOp(..) => ExprPrecedence::AssignOp, | |
1229 | ExprKind::Field(..) => ExprPrecedence::Field, | |
2c00a5a8 XL |
1230 | ExprKind::Index(..) => ExprPrecedence::Index, |
1231 | ExprKind::Range(..) => ExprPrecedence::Range, | |
fc512014 | 1232 | ExprKind::Underscore => ExprPrecedence::Path, |
2c00a5a8 XL |
1233 | ExprKind::Path(..) => ExprPrecedence::Path, |
1234 | ExprKind::AddrOf(..) => ExprPrecedence::AddrOf, | |
1235 | ExprKind::Break(..) => ExprPrecedence::Break, | |
1236 | ExprKind::Continue(..) => ExprPrecedence::Continue, | |
1237 | ExprKind::Ret(..) => ExprPrecedence::Ret, | |
f9f354fc | 1238 | ExprKind::InlineAsm(..) | ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm, |
ba9703b0 | 1239 | ExprKind::MacCall(..) => ExprPrecedence::Mac, |
2c00a5a8 XL |
1240 | ExprKind::Struct(..) => ExprPrecedence::Struct, |
1241 | ExprKind::Repeat(..) => ExprPrecedence::Repeat, | |
1242 | ExprKind::Paren(..) => ExprPrecedence::Paren, | |
1243 | ExprKind::Try(..) => ExprPrecedence::Try, | |
1244 | ExprKind::Yield(..) => ExprPrecedence::Yield, | |
0731742a | 1245 | ExprKind::Err => ExprPrecedence::Err, |
2c00a5a8 XL |
1246 | } |
1247 | } | |
3b2f2976 XL |
1248 | } |
1249 | ||
54a0048b | 1250 | /// Limit types of a range (inclusive or exclusive) |
3dfed10e | 1251 | #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)] |
54a0048b SL |
1252 | pub enum RangeLimits { |
1253 | /// Inclusive at the beginning, exclusive at the end | |
1254 | HalfOpen, | |
1255 | /// Inclusive at the beginning and end | |
1256 | Closed, | |
1257 | } | |
1258 | ||
29967ef6 XL |
1259 | #[derive(Clone, Encodable, Decodable, Debug)] |
1260 | pub enum StructRest { | |
1261 | /// `..x`. | |
1262 | Base(P<Expr>), | |
1263 | /// `..`. | |
1264 | Rest(Span), | |
1265 | /// No trailing `..` or expression. | |
1266 | None, | |
1267 | } | |
1268 | ||
3dfed10e | 1269 | #[derive(Clone, Encodable, Decodable, Debug)] |
7453a54e | 1270 | pub enum ExprKind { |
b039eaaf | 1271 | /// A `box x` expression. |
7453a54e | 1272 | Box(P<Expr>), |
c34b1796 | 1273 | /// An array (`[a, b, c, d]`) |
32a655c1 | 1274 | Array(Vec<P<Expr>>), |
29967ef6 XL |
1275 | /// Allow anonymous constants from an inline `const` block |
1276 | ConstBlock(AnonConst), | |
c34b1796 AL |
1277 | /// A function call |
1278 | /// | |
1279 | /// The first field resolves to the function itself, | |
abe05a73 XL |
1280 | /// and the second field is the list of arguments. |
1281 | /// This also represents calling the constructor of | |
1282 | /// tuple-like ADTs such as tuple structs and enum variants. | |
7453a54e | 1283 | Call(P<Expr>, Vec<P<Expr>>), |
041b39d2 | 1284 | /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`) |
c34b1796 | 1285 | /// |
041b39d2 | 1286 | /// The `PathSegment` represents the method name and its generic arguments |
c34b1796 | 1287 | /// (within the angle brackets). |
0731742a | 1288 | /// The first element of the vector of an `Expr` is the expression that evaluates |
c34b1796 AL |
1289 | /// to the object on which the method is being called on (the receiver), |
1290 | /// and the remaining elements are the rest of the arguments. | |
c34b1796 | 1291 | /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as |
041b39d2 | 1292 | /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`. |
f035d41b XL |
1293 | /// This `Span` is the span of the function, without the dot and receiver |
1294 | /// (e.g. `foo(a, b)` in `x.foo(a, b)` | |
1295 | MethodCall(PathSegment, Vec<P<Expr>>, Span), | |
0731742a | 1296 | /// A tuple (e.g., `(a, b, c, d)`). |
7453a54e | 1297 | Tup(Vec<P<Expr>>), |
0731742a | 1298 | /// A binary operation (e.g., `a + b`, `a * b`). |
7453a54e | 1299 | Binary(BinOp, P<Expr>, P<Expr>), |
0731742a | 1300 | /// A unary operation (e.g., `!x`, `*x`). |
7453a54e | 1301 | Unary(UnOp, P<Expr>), |
0731742a | 1302 | /// A literal (e.g., `1`, `"foo"`). |
a1dfa0c6 | 1303 | Lit(Lit), |
0731742a | 1304 | /// A cast (e.g., `foo as f64`). |
7453a54e | 1305 | Cast(P<Expr>, P<Ty>), |
48663c56 | 1306 | /// A type ascription (e.g., `42: usize`). |
7453a54e | 1307 | Type(P<Expr>, P<Ty>), |
e1599b0c | 1308 | /// A `let pat = expr` expression that is only semantically allowed in the condition |
dc9dc135 | 1309 | /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`). |
e1599b0c | 1310 | Let(P<Pat>, P<Expr>), |
0731742a | 1311 | /// An `if` block, with an optional `else` block. |
c34b1796 AL |
1312 | /// |
1313 | /// `if expr { block } else { expr }` | |
7453a54e | 1314 | If(P<Expr>, P<Block>, Option<P<Expr>>), |
dc9dc135 | 1315 | /// A while loop, with an optional label. |
c34b1796 AL |
1316 | /// |
1317 | /// `'label: while expr { block }` | |
2c00a5a8 | 1318 | While(P<Expr>, P<Block>, Option<Label>), |
0731742a | 1319 | /// A `for` loop, with an optional label. |
c34b1796 AL |
1320 | /// |
1321 | /// `'label: for pat in expr { block }` | |
1322 | /// | |
1323 | /// This is desugared to a combination of `loop` and `match` expressions. | |
2c00a5a8 | 1324 | ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>), |
0731742a | 1325 | /// Conditionless loop (can be exited with `break`, `continue`, or `return`). |
c34b1796 AL |
1326 | /// |
1327 | /// `'label: loop { block }` | |
2c00a5a8 | 1328 | Loop(P<Block>, Option<Label>), |
b039eaaf | 1329 | /// A `match` block. |
7453a54e | 1330 | Match(P<Expr>, Vec<Arm>), |
0731742a | 1331 | /// A closure (e.g., `move |a, b, c| a + b + c`). |
a7813a04 | 1332 | /// |
0731742a | 1333 | /// The final span is the span of the argument block `|...|`. |
74b04a01 | 1334 | Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span), |
0731742a | 1335 | /// A block (`'label: { ... }`). |
94b46f34 | 1336 | Block(P<Block>, Option<Label>), |
0731742a | 1337 | /// An async block (`async move { ... }`). |
8faf50e0 XL |
1338 | /// |
1339 | /// The `NodeId` is the `NodeId` for the closure that results from | |
1340 | /// desugaring an async block, just like the NodeId field in the | |
74b04a01 | 1341 | /// `Async::Yes` variant. This is necessary in order to create a def for the |
8faf50e0 XL |
1342 | /// closure which can be used as a parent of any child defs. Defs |
1343 | /// created during lowering cannot be made the parent of any other | |
1344 | /// preexisting defs. | |
1345 | Async(CaptureBy, NodeId, P<Block>), | |
48663c56 | 1346 | /// An await expression (`my_future.await`). |
416331ca | 1347 | Await(P<Expr>), |
48663c56 | 1348 | |
0731742a | 1349 | /// A try block (`try { ... }`). |
b7449926 | 1350 | TryBlock(P<Block>), |
1a4d82fc | 1351 | |
0731742a | 1352 | /// An assignment (`a = foo()`). |
dfeec247 XL |
1353 | /// The `Span` argument is the span of the `=` token. |
1354 | Assign(P<Expr>, P<Expr>, Span), | |
0731742a | 1355 | /// An assignment with an operator. |
c34b1796 | 1356 | /// |
0731742a | 1357 | /// E.g., `a += 1`. |
7453a54e | 1358 | AssignOp(BinOp, P<Expr>, P<Expr>), |
0731742a | 1359 | /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field. |
83c7162d | 1360 | Field(P<Expr>, Ident), |
0731742a | 1361 | /// An indexing operation (e.g., `foo[2]`). |
7453a54e | 1362 | Index(P<Expr>, P<Expr>), |
29967ef6 | 1363 | /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assingment). |
54a0048b | 1364 | Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits), |
fc512014 XL |
1365 | /// An underscore, used in destructuring assignment to ignore a value. |
1366 | Underscore, | |
1a4d82fc | 1367 | |
c34b1796 | 1368 | /// Variable reference, possibly containing `::` and/or type |
0731742a | 1369 | /// parameters (e.g., `foo::bar::<baz>`). |
c34b1796 | 1370 | /// |
0731742a | 1371 | /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`). |
7453a54e | 1372 | Path(Option<QSelf>, Path), |
1a4d82fc | 1373 | |
60c5eb7d XL |
1374 | /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`). |
1375 | AddrOf(BorrowKind, Mutability, P<Expr>), | |
0731742a | 1376 | /// A `break`, with an optional label to break, and an optional expression. |
2c00a5a8 | 1377 | Break(Option<Label>, Option<P<Expr>>), |
0731742a | 1378 | /// A `continue`, with an optional label. |
2c00a5a8 | 1379 | Continue(Option<Label>), |
0731742a | 1380 | /// A `return`, with an optional value to be returned. |
7453a54e | 1381 | Ret(Option<P<Expr>>), |
1a4d82fc | 1382 | |
f9f354fc XL |
1383 | /// Output of the `asm!()` macro. |
1384 | InlineAsm(P<InlineAsm>), | |
ba9703b0 XL |
1385 | /// Output of the `llvm_asm!()` macro. |
1386 | LlvmInlineAsm(P<LlvmInlineAsm>), | |
1a4d82fc | 1387 | |
0731742a | 1388 | /// A macro invocation; pre-expansion. |
ba9703b0 | 1389 | MacCall(MacCall), |
1a4d82fc JJ |
1390 | |
1391 | /// A struct literal expression. | |
c34b1796 | 1392 | /// |
29967ef6 XL |
1393 | /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`. |
1394 | Struct(Path, Vec<Field>, StructRest), | |
1a4d82fc | 1395 | |
e9174d1e | 1396 | /// An array literal constructed from one repeated element. |
c34b1796 | 1397 | /// |
0731742a | 1398 | /// E.g., `[1; 5]`. The expression is the element to be |
94b46f34 XL |
1399 | /// repeated; the constant is the number of times to repeat it. |
1400 | Repeat(P<Expr>, AnonConst), | |
1a4d82fc | 1401 | |
0731742a | 1402 | /// No-op: used solely so we can pretty-print faithfully. |
7453a54e | 1403 | Paren(P<Expr>), |
54a0048b | 1404 | |
0731742a | 1405 | /// A try expression (`expr?`). |
54a0048b | 1406 | Try(P<Expr>), |
ea8adc8c | 1407 | |
0731742a | 1408 | /// A `yield`, with an optional value to be yielded. |
ea8adc8c | 1409 | Yield(Option<P<Expr>>), |
0731742a XL |
1410 | |
1411 | /// Placeholder for an expression that wasn't syntactically well formed in some way. | |
1412 | Err, | |
1a4d82fc JJ |
1413 | } |
1414 | ||
0731742a | 1415 | /// The explicit `Self` type in a "qualified path". The actual |
c34b1796 AL |
1416 | /// path, including the trait and the associated item, is stored |
1417 | /// separately. `position` represents the index of the associated | |
0731742a | 1418 | /// item qualified with this `Self` type. |
c34b1796 | 1419 | /// |
041b39d2 | 1420 | /// ```ignore (only-for-syntax-highlight) |
92a42be0 SL |
1421 | /// <Vec<T> as a::b::Trait>::AssociatedItem |
1422 | /// ^~~~~ ~~~~~~~~~~~~~~^ | |
1423 | /// ty position = 3 | |
1a4d82fc | 1424 | /// |
92a42be0 SL |
1425 | /// <Vec<T>>::AssociatedItem |
1426 | /// ^~~~~ ^ | |
1427 | /// ty position = 0 | |
1428 | /// ``` | |
3dfed10e | 1429 | #[derive(Clone, Encodable, Decodable, Debug)] |
c34b1796 AL |
1430 | pub struct QSelf { |
1431 | pub ty: P<Ty>, | |
94b46f34 XL |
1432 | |
1433 | /// The span of `a::b::Trait` in a path like `<Vec<T> as | |
1434 | /// a::b::Trait>::AssociatedItem`; in the case where `position == | |
1435 | /// 0`, this is an empty span. | |
1436 | pub path_span: Span, | |
0bf4aa26 | 1437 | pub position: usize, |
1a4d82fc JJ |
1438 | } |
1439 | ||
e74abb32 | 1440 | /// A capture clause used in closures and `async` blocks. |
3dfed10e | 1441 | #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] |
7453a54e | 1442 | pub enum CaptureBy { |
e74abb32 | 1443 | /// `move |x| y + x`. |
7453a54e | 1444 | Value, |
e74abb32 | 1445 | /// `move` keyword was not specified. |
7453a54e | 1446 | Ref, |
1a4d82fc JJ |
1447 | } |
1448 | ||
60c5eb7d XL |
1449 | /// The movability of a generator / closure literal: |
1450 | /// whether a generator contains self-references, causing it to be `!Unpin`. | |
3dfed10e | 1451 | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)] |
ba9703b0 | 1452 | #[derive(HashStable_Generic)] |
2c00a5a8 | 1453 | pub enum Movability { |
60c5eb7d | 1454 | /// May contain self-references, `!Unpin`. |
2c00a5a8 | 1455 | Static, |
60c5eb7d | 1456 | /// Must not contain self-references, `Unpin`. |
2c00a5a8 XL |
1457 | Movable, |
1458 | } | |
1459 | ||
60c5eb7d XL |
1460 | /// Represents a macro invocation. The `path` indicates which macro |
1461 | /// is being invoked, and the `args` are arguments passed to it. | |
3dfed10e | 1462 | #[derive(Clone, Encodable, Decodable, Debug)] |
ba9703b0 | 1463 | pub struct MacCall { |
b039eaaf | 1464 | pub path: Path, |
60c5eb7d | 1465 | pub args: P<MacArgs>, |
416331ca | 1466 | pub prior_type_ascription: Option<(Span, bool)>, |
8bb4bdeb XL |
1467 | } |
1468 | ||
ba9703b0 | 1469 | impl MacCall { |
60c5eb7d XL |
1470 | pub fn span(&self) -> Span { |
1471 | self.path.span.to(self.args.span().unwrap_or(self.path.span)) | |
1472 | } | |
1473 | } | |
1474 | ||
1475 | /// Arguments passed to an attribute or a function-like macro. | |
3dfed10e | 1476 | #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
60c5eb7d XL |
1477 | pub enum MacArgs { |
1478 | /// No arguments - `#[attr]`. | |
1479 | Empty, | |
1480 | /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`. | |
1481 | Delimited(DelimSpan, MacDelimiter, TokenStream), | |
1482 | /// Arguments of a key-value attribute - `#[attr = "value"]`. | |
1483 | Eq( | |
1484 | /// Span of the `=` token. | |
1485 | Span, | |
1486 | /// Token stream of the "value". | |
1487 | TokenStream, | |
1488 | ), | |
1489 | } | |
1490 | ||
1491 | impl MacArgs { | |
1492 | pub fn delim(&self) -> DelimToken { | |
1493 | match self { | |
1494 | MacArgs::Delimited(_, delim, _) => delim.to_token(), | |
1495 | MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim, | |
1496 | } | |
1497 | } | |
1498 | ||
1499 | pub fn span(&self) -> Option<Span> { | |
1500 | match *self { | |
1501 | MacArgs::Empty => None, | |
1502 | MacArgs::Delimited(dspan, ..) => Some(dspan.entire()), | |
1503 | MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))), | |
1504 | } | |
1505 | } | |
1506 | ||
1507 | /// Tokens inside the delimiters or after `=`. | |
1508 | /// Proc macros see these tokens, for example. | |
1509 | pub fn inner_tokens(&self) -> TokenStream { | |
1510 | match self { | |
1511 | MacArgs::Empty => TokenStream::default(), | |
dfeec247 | 1512 | MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(), |
60c5eb7d XL |
1513 | } |
1514 | } | |
1515 | ||
60c5eb7d XL |
1516 | /// Whether a macro with these arguments needs a semicolon |
1517 | /// when used as a standalone item or statement. | |
1518 | pub fn need_semicolon(&self) -> bool { | |
dfeec247 | 1519 | !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _)) |
60c5eb7d XL |
1520 | } |
1521 | } | |
1522 | ||
3dfed10e | 1523 | #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)] |
94b46f34 XL |
1524 | pub enum MacDelimiter { |
1525 | Parenthesis, | |
1526 | Bracket, | |
1527 | Brace, | |
1528 | } | |
1529 | ||
416331ca | 1530 | impl MacDelimiter { |
74b04a01 | 1531 | pub fn to_token(self) -> DelimToken { |
416331ca XL |
1532 | match self { |
1533 | MacDelimiter::Parenthesis => DelimToken::Paren, | |
1534 | MacDelimiter::Bracket => DelimToken::Bracket, | |
1535 | MacDelimiter::Brace => DelimToken::Brace, | |
1536 | } | |
1537 | } | |
60c5eb7d XL |
1538 | |
1539 | pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> { | |
1540 | match delim { | |
1541 | token::Paren => Some(MacDelimiter::Parenthesis), | |
1542 | token::Bracket => Some(MacDelimiter::Bracket), | |
1543 | token::Brace => Some(MacDelimiter::Brace), | |
1544 | token::NoDelim => None, | |
1545 | } | |
1546 | } | |
416331ca XL |
1547 | } |
1548 | ||
e74abb32 | 1549 | /// Represents a macro definition. |
3dfed10e | 1550 | #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
7cac9316 | 1551 | pub struct MacroDef { |
60c5eb7d | 1552 | pub body: P<MacArgs>, |
e74abb32 | 1553 | /// `true` if macro was defined with `macro_rules`. |
ba9703b0 | 1554 | pub macro_rules: bool, |
7cac9316 XL |
1555 | } |
1556 | ||
3dfed10e | 1557 | #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)] |
dfeec247 | 1558 | #[derive(HashStable_Generic)] |
1a4d82fc | 1559 | pub enum StrStyle { |
0731742a | 1560 | /// A regular string, like `"foo"`. |
7453a54e | 1561 | Cooked, |
0731742a | 1562 | /// A raw string, like `r##"foo"##`. |
c34b1796 | 1563 | /// |
83c7162d | 1564 | /// The value is the number of `#` symbols used. |
0bf4aa26 | 1565 | Raw(u16), |
223e47cc LB |
1566 | } |
1567 | ||
48663c56 | 1568 | /// An AST literal. |
3dfed10e | 1569 | #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
48663c56 XL |
1570 | pub struct Lit { |
1571 | /// The original literal token as written in source code. | |
1572 | pub token: token::Lit, | |
48663c56 XL |
1573 | /// The "semantic" representation of the literal lowered from the original tokens. |
1574 | /// Strings are unescaped, hexadecimal forms are eliminated, etc. | |
1575 | /// FIXME: Remove this and only create the semantic representation during lowering to HIR. | |
e74abb32 | 1576 | pub kind: LitKind, |
48663c56 XL |
1577 | pub span: Span, |
1578 | } | |
9346a6ac | 1579 | |
60c5eb7d | 1580 | /// Same as `Lit`, but restricted to string literals. |
3dfed10e | 1581 | #[derive(Clone, Copy, Encodable, Decodable, Debug)] |
60c5eb7d XL |
1582 | pub struct StrLit { |
1583 | /// The original literal token as written in source code. | |
1584 | pub style: StrStyle, | |
1585 | pub symbol: Symbol, | |
1586 | pub suffix: Option<Symbol>, | |
1587 | pub span: Span, | |
1588 | /// The unescaped "semantic" representation of the literal lowered from the original token. | |
1589 | /// FIXME: Remove this and only create the semantic representation during lowering to HIR. | |
1590 | pub symbol_unescaped: Symbol, | |
1591 | } | |
1592 | ||
1593 | impl StrLit { | |
74b04a01 | 1594 | pub fn as_lit(&self) -> Lit { |
60c5eb7d XL |
1595 | let token_kind = match self.style { |
1596 | StrStyle::Cooked => token::Str, | |
1597 | StrStyle::Raw(n) => token::StrRaw(n), | |
1598 | }; | |
1599 | Lit { | |
1600 | token: token::Lit::new(token_kind, self.symbol, self.suffix), | |
1601 | span: self.span, | |
1602 | kind: LitKind::Str(self.symbol_unescaped, self.style), | |
1603 | } | |
1604 | } | |
1605 | } | |
1606 | ||
e74abb32 | 1607 | /// Type of the integer literal based on provided suffix. |
3dfed10e | 1608 | #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)] |
dfeec247 | 1609 | #[derive(HashStable_Generic)] |
1a4d82fc | 1610 | pub enum LitIntType { |
e74abb32 | 1611 | /// e.g. `42_i32`. |
7453a54e | 1612 | Signed(IntTy), |
e74abb32 | 1613 | /// e.g. `42_u32`. |
7453a54e | 1614 | Unsigned(UintTy), |
e74abb32 | 1615 | /// e.g. `42`. |
7453a54e | 1616 | Unsuffixed, |
223e47cc LB |
1617 | } |
1618 | ||
60c5eb7d | 1619 | /// Type of the float literal based on provided suffix. |
3dfed10e | 1620 | #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)] |
dfeec247 | 1621 | #[derive(HashStable_Generic)] |
60c5eb7d XL |
1622 | pub enum LitFloatType { |
1623 | /// A float literal with a suffix (`1f32` or `1E10f32`). | |
1624 | Suffixed(FloatTy), | |
1625 | /// A float literal without a suffix (`1.0 or 1.0E10`). | |
1626 | Unsuffixed, | |
1627 | } | |
1628 | ||
3157f602 XL |
1629 | /// Literal kind. |
1630 | /// | |
0731742a | 1631 | /// E.g., `"foo"`, `42`, `12.34`, or `bool`. |
3dfed10e | 1632 | #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)] |
7453a54e | 1633 | pub enum LitKind { |
0731742a | 1634 | /// A string literal (`"foo"`). |
476ff2be | 1635 | Str(Symbol, StrStyle), |
0731742a | 1636 | /// A byte string (`b"foo"`). |
29967ef6 | 1637 | ByteStr(Lrc<[u8]>), |
0731742a | 1638 | /// A byte char (`b'f'`). |
7453a54e | 1639 | Byte(u8), |
0731742a | 1640 | /// A character literal (`'a'`). |
7453a54e | 1641 | Char(char), |
0731742a | 1642 | /// An integer literal (`1`). |
32a655c1 | 1643 | Int(u128, LitIntType), |
0731742a | 1644 | /// A float literal (`1f64` or `1E10f64`). |
60c5eb7d | 1645 | Float(Symbol, LitFloatType), |
0731742a | 1646 | /// A boolean literal. |
7453a54e | 1647 | Bool(bool), |
dc9dc135 | 1648 | /// Placeholder for a literal that wasn't well-formed in some way. |
9fa01778 | 1649 | Err(Symbol), |
223e47cc LB |
1650 | } |
1651 | ||
7453a54e | 1652 | impl LitKind { |
0731742a | 1653 | /// Returns `true` if this literal is a string. |
9cc50fc6 SL |
1654 | pub fn is_str(&self) -> bool { |
1655 | match *self { | |
7453a54e | 1656 | LitKind::Str(..) => true, |
9cc50fc6 SL |
1657 | _ => false, |
1658 | } | |
1659 | } | |
9e0c209e | 1660 | |
0731742a | 1661 | /// Returns `true` if this literal is byte literal string. |
a1dfa0c6 XL |
1662 | pub fn is_bytestr(&self) -> bool { |
1663 | match self { | |
1664 | LitKind::ByteStr(_) => true, | |
1665 | _ => false, | |
1666 | } | |
1667 | } | |
1668 | ||
0731742a | 1669 | /// Returns `true` if this is a numeric literal. |
8faf50e0 XL |
1670 | pub fn is_numeric(&self) -> bool { |
1671 | match *self { | |
60c5eb7d | 1672 | LitKind::Int(..) | LitKind::Float(..) => true, |
8faf50e0 XL |
1673 | _ => false, |
1674 | } | |
1675 | } | |
1676 | ||
0731742a XL |
1677 | /// Returns `true` if this literal has no suffix. |
1678 | /// Note: this will return true for literals with prefixes such as raw strings and byte strings. | |
9e0c209e | 1679 | pub fn is_unsuffixed(&self) -> bool { |
e74abb32 XL |
1680 | !self.is_suffixed() |
1681 | } | |
1682 | ||
1683 | /// Returns `true` if this literal has a suffix. | |
1684 | pub fn is_suffixed(&self) -> bool { | |
9e0c209e | 1685 | match *self { |
e74abb32 | 1686 | // suffixed variants |
ba9703b0 | 1687 | LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..)) |
60c5eb7d | 1688 | | LitKind::Float(_, LitFloatType::Suffixed(..)) => true, |
9e0c209e | 1689 | // unsuffixed variants |
0bf4aa26 XL |
1690 | LitKind::Str(..) |
1691 | | LitKind::ByteStr(..) | |
1692 | | LitKind::Byte(..) | |
1693 | | LitKind::Char(..) | |
1694 | | LitKind::Int(_, LitIntType::Unsuffixed) | |
60c5eb7d | 1695 | | LitKind::Float(_, LitFloatType::Unsuffixed) |
dc9dc135 | 1696 | | LitKind::Bool(..) |
e74abb32 | 1697 | | LitKind::Err(..) => false, |
9e0c209e SL |
1698 | } |
1699 | } | |
9cc50fc6 SL |
1700 | } |
1701 | ||
0731742a XL |
1702 | // N.B., If you change this, you'll probably want to change the corresponding |
1703 | // type structure in `middle/ty.rs` as well. | |
3dfed10e | 1704 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
1705 | pub struct MutTy { |
1706 | pub ty: P<Ty>, | |
1707 | pub mutbl: Mutability, | |
1708 | } | |
1709 | ||
60c5eb7d XL |
1710 | /// Represents a function's signature in a trait declaration, |
1711 | /// trait implementation, or free function. | |
3dfed10e | 1712 | #[derive(Clone, Encodable, Decodable, Debug)] |
60c5eb7d | 1713 | pub struct FnSig { |
8faf50e0 | 1714 | pub header: FnHeader, |
1a4d82fc | 1715 | pub decl: P<FnDecl>, |
3dfed10e | 1716 | pub span: Span, |
1a4d82fc JJ |
1717 | } |
1718 | ||
3dfed10e XL |
1719 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] |
1720 | #[derive(Encodable, Decodable, HashStable_Generic)] | |
60c5eb7d XL |
1721 | pub enum FloatTy { |
1722 | F32, | |
1723 | F64, | |
1724 | } | |
1725 | ||
1726 | impl FloatTy { | |
1727 | pub fn name_str(self) -> &'static str { | |
1728 | match self { | |
1729 | FloatTy::F32 => "f32", | |
1730 | FloatTy::F64 => "f64", | |
1731 | } | |
1732 | } | |
1733 | ||
1734 | pub fn name(self) -> Symbol { | |
1735 | match self { | |
1736 | FloatTy::F32 => sym::f32, | |
1737 | FloatTy::F64 => sym::f64, | |
1738 | } | |
1739 | } | |
1740 | ||
ba9703b0 | 1741 | pub fn bit_width(self) -> u64 { |
60c5eb7d XL |
1742 | match self { |
1743 | FloatTy::F32 => 32, | |
1744 | FloatTy::F64 => 64, | |
1745 | } | |
1746 | } | |
1747 | } | |
1748 | ||
3dfed10e XL |
1749 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] |
1750 | #[derive(Encodable, Decodable, HashStable_Generic)] | |
1a4d82fc | 1751 | pub enum IntTy { |
2c00a5a8 | 1752 | Isize, |
7453a54e SL |
1753 | I8, |
1754 | I16, | |
1755 | I32, | |
1756 | I64, | |
32a655c1 | 1757 | I128, |
1a4d82fc JJ |
1758 | } |
1759 | ||
1a4d82fc | 1760 | impl IntTy { |
60c5eb7d | 1761 | pub fn name_str(&self) -> &'static str { |
9cc50fc6 | 1762 | match *self { |
2c00a5a8 | 1763 | IntTy::Isize => "isize", |
7453a54e SL |
1764 | IntTy::I8 => "i8", |
1765 | IntTy::I16 => "i16", | |
1766 | IntTy::I32 => "i32", | |
32a655c1 SL |
1767 | IntTy::I64 => "i64", |
1768 | IntTy::I128 => "i128", | |
9cc50fc6 SL |
1769 | } |
1770 | } | |
1771 | ||
60c5eb7d | 1772 | pub fn name(&self) -> Symbol { |
dc9dc135 XL |
1773 | match *self { |
1774 | IntTy::Isize => sym::isize, | |
1775 | IntTy::I8 => sym::i8, | |
1776 | IntTy::I16 => sym::i16, | |
1777 | IntTy::I32 => sym::i32, | |
1778 | IntTy::I64 => sym::i64, | |
1779 | IntTy::I128 => sym::i128, | |
1780 | } | |
1781 | } | |
1782 | ||
ba9703b0 | 1783 | pub fn bit_width(&self) -> Option<u64> { |
e9174d1e | 1784 | Some(match *self { |
2c00a5a8 | 1785 | IntTy::Isize => return None, |
7453a54e SL |
1786 | IntTy::I8 => 8, |
1787 | IntTy::I16 => 16, | |
1788 | IntTy::I32 => 32, | |
1789 | IntTy::I64 => 64, | |
32a655c1 | 1790 | IntTy::I128 => 128, |
e9174d1e | 1791 | }) |
1a4d82fc | 1792 | } |
60c5eb7d XL |
1793 | |
1794 | pub fn normalize(&self, target_width: u32) -> Self { | |
1795 | match self { | |
1796 | IntTy::Isize => match target_width { | |
1797 | 16 => IntTy::I16, | |
1798 | 32 => IntTy::I32, | |
1799 | 64 => IntTy::I64, | |
1800 | _ => unreachable!(), | |
1801 | }, | |
1802 | _ => *self, | |
1803 | } | |
1804 | } | |
223e47cc LB |
1805 | } |
1806 | ||
3dfed10e XL |
1807 | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)] |
1808 | #[derive(Encodable, Decodable, HashStable_Generic)] | |
1a4d82fc | 1809 | pub enum UintTy { |
2c00a5a8 | 1810 | Usize, |
7453a54e SL |
1811 | U8, |
1812 | U16, | |
1813 | U32, | |
1814 | U64, | |
32a655c1 | 1815 | U128, |
1a4d82fc JJ |
1816 | } |
1817 | ||
1a4d82fc | 1818 | impl UintTy { |
60c5eb7d | 1819 | pub fn name_str(&self) -> &'static str { |
9cc50fc6 | 1820 | match *self { |
2c00a5a8 | 1821 | UintTy::Usize => "usize", |
7453a54e SL |
1822 | UintTy::U8 => "u8", |
1823 | UintTy::U16 => "u16", | |
1824 | UintTy::U32 => "u32", | |
32a655c1 SL |
1825 | UintTy::U64 => "u64", |
1826 | UintTy::U128 => "u128", | |
9cc50fc6 SL |
1827 | } |
1828 | } | |
1829 | ||
60c5eb7d | 1830 | pub fn name(&self) -> Symbol { |
dc9dc135 XL |
1831 | match *self { |
1832 | UintTy::Usize => sym::usize, | |
1833 | UintTy::U8 => sym::u8, | |
1834 | UintTy::U16 => sym::u16, | |
1835 | UintTy::U32 => sym::u32, | |
1836 | UintTy::U64 => sym::u64, | |
1837 | UintTy::U128 => sym::u128, | |
1838 | } | |
1839 | } | |
1840 | ||
ba9703b0 | 1841 | pub fn bit_width(&self) -> Option<u64> { |
e9174d1e | 1842 | Some(match *self { |
2c00a5a8 | 1843 | UintTy::Usize => return None, |
7453a54e SL |
1844 | UintTy::U8 => 8, |
1845 | UintTy::U16 => 16, | |
1846 | UintTy::U32 => 32, | |
1847 | UintTy::U64 => 64, | |
32a655c1 | 1848 | UintTy::U128 => 128, |
e9174d1e | 1849 | }) |
1a4d82fc | 1850 | } |
223e47cc | 1851 | |
60c5eb7d XL |
1852 | pub fn normalize(&self, target_width: u32) -> Self { |
1853 | match self { | |
1854 | UintTy::Usize => match target_width { | |
1855 | 16 => UintTy::U16, | |
1856 | 32 => UintTy::U32, | |
1857 | 64 => UintTy::U64, | |
1858 | _ => unreachable!(), | |
1859 | }, | |
1860 | _ => *self, | |
1861 | } | |
1a4d82fc JJ |
1862 | } |
1863 | } | |
1864 | ||
dc9dc135 XL |
1865 | /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or |
1866 | /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`). | |
3dfed10e | 1867 | #[derive(Clone, Encodable, Decodable, Debug)] |
dc9dc135 | 1868 | pub struct AssocTyConstraint { |
1a4d82fc JJ |
1869 | pub id: NodeId, |
1870 | pub ident: Ident, | |
fc512014 | 1871 | pub gen_args: Option<GenericArgs>, |
dc9dc135 | 1872 | pub kind: AssocTyConstraintKind, |
1a4d82fc JJ |
1873 | pub span: Span, |
1874 | } | |
1875 | ||
dc9dc135 | 1876 | /// The kinds of an `AssocTyConstraint`. |
3dfed10e | 1877 | #[derive(Clone, Encodable, Decodable, Debug)] |
dc9dc135 XL |
1878 | pub enum AssocTyConstraintKind { |
1879 | /// E.g., `A = Bar` in `Foo<A = Bar>`. | |
dfeec247 | 1880 | Equality { ty: P<Ty> }, |
dc9dc135 | 1881 | /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`. |
dfeec247 | 1882 | Bound { bounds: GenericBounds }, |
dc9dc135 XL |
1883 | } |
1884 | ||
29967ef6 | 1885 | #[derive(Encodable, Decodable, Debug)] |
223e47cc | 1886 | pub struct Ty { |
1a4d82fc | 1887 | pub id: NodeId, |
e74abb32 | 1888 | pub kind: TyKind, |
1a4d82fc | 1889 | pub span: Span, |
29967ef6 XL |
1890 | pub tokens: Option<LazyTokenStream>, |
1891 | } | |
1892 | ||
1893 | impl Clone for Ty { | |
1894 | fn clone(&self) -> Self { | |
1895 | ensure_sufficient_stack(|| Self { | |
1896 | id: self.id, | |
1897 | kind: self.kind.clone(), | |
1898 | span: self.span, | |
1899 | tokens: self.tokens.clone(), | |
1900 | }) | |
1901 | } | |
1902 | } | |
1903 | ||
1904 | impl Ty { | |
1905 | pub fn peel_refs(&self) -> &Self { | |
1906 | let mut final_ty = self; | |
1907 | while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind { | |
1908 | final_ty = &ty; | |
1909 | } | |
1910 | final_ty | |
1911 | } | |
223e47cc LB |
1912 | } |
1913 | ||
3dfed10e | 1914 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 1915 | pub struct BareFnTy { |
74b04a01 | 1916 | pub unsafety: Unsafe, |
60c5eb7d | 1917 | pub ext: Extern, |
ff7c6d11 | 1918 | pub generic_params: Vec<GenericParam>, |
0bf4aa26 | 1919 | pub decl: P<FnDecl>, |
1a4d82fc JJ |
1920 | } |
1921 | ||
9fa01778 | 1922 | /// The various kinds of type recognized by the compiler. |
3dfed10e | 1923 | #[derive(Clone, Encodable, Decodable, Debug)] |
7453a54e | 1924 | pub enum TyKind { |
0731742a | 1925 | /// A variable-length slice (`[T]`). |
c30ab7b3 | 1926 | Slice(P<Ty>), |
0731742a | 1927 | /// A fixed length array (`[T; n]`). |
94b46f34 | 1928 | Array(P<Ty>, AnonConst), |
0731742a | 1929 | /// A raw pointer (`*const T` or `*mut T`). |
7453a54e | 1930 | Ptr(MutTy), |
0731742a | 1931 | /// A reference (`&'a T` or `&'a mut T`). |
7453a54e | 1932 | Rptr(Option<Lifetime>, MutTy), |
0731742a | 1933 | /// A bare function (e.g., `fn(usize) -> bool`). |
7453a54e | 1934 | BareFn(P<BareFnTy>), |
0731742a | 1935 | /// The never type (`!`). |
5bcae85e | 1936 | Never, |
0731742a | 1937 | /// A tuple (`(A, B, C, D,...)`). |
0bf4aa26 | 1938 | Tup(Vec<P<Ty>>), |
c34b1796 | 1939 | /// A path (`module::module::...::Type`), optionally |
0731742a | 1940 | /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`. |
1a4d82fc | 1941 | /// |
0731742a | 1942 | /// Type parameters are stored in the `Path` itself. |
7453a54e | 1943 | Path(Option<QSelf>, Path), |
32a655c1 SL |
1944 | /// A trait object type `Bound1 + Bound2 + Bound3` |
1945 | /// where `Bound` is a trait or a lifetime. | |
8faf50e0 | 1946 | TraitObject(GenericBounds, TraitObjectSyntax), |
32a655c1 SL |
1947 | /// An `impl Bound1 + Bound2 + Bound3` type |
1948 | /// where `Bound` is a trait or a lifetime. | |
8faf50e0 XL |
1949 | /// |
1950 | /// The `NodeId` exists to prevent lowering from having to | |
1951 | /// generate `NodeId`s on the fly, which would complicate | |
416331ca | 1952 | /// the generation of opaque `type Foo = impl Trait` items significantly. |
8faf50e0 | 1953 | ImplTrait(NodeId, GenericBounds), |
0731742a | 1954 | /// No-op; kept solely so that we can pretty-print faithfully. |
7453a54e | 1955 | Paren(P<Ty>), |
0731742a | 1956 | /// Unused for now. |
94b46f34 | 1957 | Typeof(AnonConst), |
0731742a | 1958 | /// This means the type should be inferred instead of it having been |
1a4d82fc | 1959 | /// specified. This can appear anywhere in a type. |
7453a54e | 1960 | Infer, |
3157f602 XL |
1961 | /// Inferred type of a `self` or `&self` argument in a method. |
1962 | ImplicitSelf, | |
0731742a | 1963 | /// A macro in the type position. |
ba9703b0 | 1964 | MacCall(MacCall), |
cc61c64b XL |
1965 | /// Placeholder for a kind that has failed to be defined. |
1966 | Err, | |
532ac7d7 XL |
1967 | /// Placeholder for a `va_list`. |
1968 | CVarArgs, | |
1a4d82fc JJ |
1969 | } |
1970 | ||
8faf50e0 XL |
1971 | impl TyKind { |
1972 | pub fn is_implicit_self(&self) -> bool { | |
1b1a35ee | 1973 | matches!(self, TyKind::ImplicitSelf) |
8faf50e0 XL |
1974 | } |
1975 | ||
b7449926 | 1976 | pub fn is_unit(&self) -> bool { |
dfeec247 | 1977 | if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false } |
8faf50e0 XL |
1978 | } |
1979 | } | |
1980 | ||
abe05a73 | 1981 | /// Syntax used to declare a trait object. |
3dfed10e | 1982 | #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)] |
abe05a73 XL |
1983 | pub enum TraitObjectSyntax { |
1984 | Dyn, | |
1985 | None, | |
1986 | } | |
1987 | ||
f9f354fc XL |
1988 | /// Inline assembly operand explicit register or register class. |
1989 | /// | |
1990 | /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`. | |
3dfed10e | 1991 | #[derive(Clone, Copy, Encodable, Decodable, Debug)] |
f9f354fc XL |
1992 | pub enum InlineAsmRegOrRegClass { |
1993 | Reg(Symbol), | |
1994 | RegClass(Symbol), | |
1995 | } | |
1996 | ||
1997 | bitflags::bitflags! { | |
3dfed10e | 1998 | #[derive(Encodable, Decodable, HashStable_Generic)] |
f9f354fc XL |
1999 | pub struct InlineAsmOptions: u8 { |
2000 | const PURE = 1 << 0; | |
2001 | const NOMEM = 1 << 1; | |
2002 | const READONLY = 1 << 2; | |
2003 | const PRESERVES_FLAGS = 1 << 3; | |
2004 | const NORETURN = 1 << 4; | |
2005 | const NOSTACK = 1 << 5; | |
2006 | const ATT_SYNTAX = 1 << 6; | |
2007 | } | |
2008 | } | |
2009 | ||
3dfed10e | 2010 | #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] |
f9f354fc XL |
2011 | pub enum InlineAsmTemplatePiece { |
2012 | String(String), | |
2013 | Placeholder { operand_idx: usize, modifier: Option<char>, span: Span }, | |
2014 | } | |
2015 | ||
2016 | impl fmt::Display for InlineAsmTemplatePiece { | |
2017 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
2018 | match self { | |
2019 | Self::String(s) => { | |
2020 | for c in s.chars() { | |
2021 | match c { | |
2022 | '{' => f.write_str("{{")?, | |
2023 | '}' => f.write_str("}}")?, | |
f035d41b | 2024 | _ => c.fmt(f)?, |
f9f354fc XL |
2025 | } |
2026 | } | |
2027 | Ok(()) | |
2028 | } | |
2029 | Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => { | |
2030 | write!(f, "{{{}:{}}}", operand_idx, modifier) | |
2031 | } | |
2032 | Self::Placeholder { operand_idx, modifier: None, .. } => { | |
2033 | write!(f, "{{{}}}", operand_idx) | |
2034 | } | |
2035 | } | |
2036 | } | |
2037 | } | |
2038 | ||
2039 | impl InlineAsmTemplatePiece { | |
2040 | /// Rebuilds the asm template string from its pieces. | |
2041 | pub fn to_string(s: &[Self]) -> String { | |
2042 | use fmt::Write; | |
2043 | let mut out = String::new(); | |
2044 | for p in s.iter() { | |
2045 | let _ = write!(out, "{}", p); | |
2046 | } | |
2047 | out | |
2048 | } | |
2049 | } | |
2050 | ||
2051 | /// Inline assembly operand. | |
2052 | /// | |
2053 | /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`. | |
3dfed10e | 2054 | #[derive(Clone, Encodable, Decodable, Debug)] |
f9f354fc XL |
2055 | pub enum InlineAsmOperand { |
2056 | In { | |
2057 | reg: InlineAsmRegOrRegClass, | |
2058 | expr: P<Expr>, | |
2059 | }, | |
2060 | Out { | |
2061 | reg: InlineAsmRegOrRegClass, | |
2062 | late: bool, | |
2063 | expr: Option<P<Expr>>, | |
2064 | }, | |
2065 | InOut { | |
2066 | reg: InlineAsmRegOrRegClass, | |
2067 | late: bool, | |
2068 | expr: P<Expr>, | |
2069 | }, | |
2070 | SplitInOut { | |
2071 | reg: InlineAsmRegOrRegClass, | |
2072 | late: bool, | |
2073 | in_expr: P<Expr>, | |
2074 | out_expr: Option<P<Expr>>, | |
2075 | }, | |
2076 | Const { | |
2077 | expr: P<Expr>, | |
2078 | }, | |
2079 | Sym { | |
2080 | expr: P<Expr>, | |
2081 | }, | |
2082 | } | |
2083 | ||
2084 | /// Inline assembly. | |
2085 | /// | |
2086 | /// E.g., `asm!("NOP");`. | |
3dfed10e | 2087 | #[derive(Clone, Encodable, Decodable, Debug)] |
f9f354fc XL |
2088 | pub struct InlineAsm { |
2089 | pub template: Vec<InlineAsmTemplatePiece>, | |
2090 | pub operands: Vec<(InlineAsmOperand, Span)>, | |
2091 | pub options: InlineAsmOptions, | |
2092 | pub line_spans: Vec<Span>, | |
2093 | } | |
2094 | ||
3157f602 XL |
2095 | /// Inline assembly dialect. |
2096 | /// | |
ba9703b0 | 2097 | /// E.g., `"intel"` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`. |
3dfed10e | 2098 | #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)] |
ba9703b0 | 2099 | pub enum LlvmAsmDialect { |
b039eaaf SL |
2100 | Att, |
2101 | Intel, | |
1a4d82fc JJ |
2102 | } |
2103 | ||
ba9703b0 | 2104 | /// LLVM-style inline assembly. |
3157f602 | 2105 | /// |
ba9703b0 | 2106 | /// E.g., `"={eax}"(result)` as in `llvm_asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`. |
3dfed10e | 2107 | #[derive(Clone, Encodable, Decodable, Debug)] |
ba9703b0 | 2108 | pub struct LlvmInlineAsmOutput { |
476ff2be | 2109 | pub constraint: Symbol, |
9cc50fc6 SL |
2110 | pub expr: P<Expr>, |
2111 | pub is_rw: bool, | |
2112 | pub is_indirect: bool, | |
2113 | } | |
2114 | ||
ba9703b0 | 2115 | /// LLVM-style inline assembly. |
3157f602 | 2116 | /// |
ba9703b0 | 2117 | /// E.g., `llvm_asm!("NOP");`. |
3dfed10e | 2118 | #[derive(Clone, Encodable, Decodable, Debug)] |
ba9703b0 | 2119 | pub struct LlvmInlineAsm { |
476ff2be | 2120 | pub asm: Symbol, |
1a4d82fc | 2121 | pub asm_str_style: StrStyle, |
ba9703b0 | 2122 | pub outputs: Vec<LlvmInlineAsmOutput>, |
476ff2be SL |
2123 | pub inputs: Vec<(Symbol, P<Expr>)>, |
2124 | pub clobbers: Vec<Symbol>, | |
1a4d82fc JJ |
2125 | pub volatile: bool, |
2126 | pub alignstack: bool, | |
ba9703b0 | 2127 | pub dialect: LlvmAsmDialect, |
1a4d82fc JJ |
2128 | } |
2129 | ||
e1599b0c | 2130 | /// A parameter in a function header. |
3157f602 | 2131 | /// |
0731742a | 2132 | /// E.g., `bar: usize` as in `fn foo(bar: usize)`. |
3dfed10e | 2133 | #[derive(Clone, Encodable, Decodable, Debug)] |
e1599b0c | 2134 | pub struct Param { |
dfeec247 | 2135 | pub attrs: AttrVec, |
1a4d82fc JJ |
2136 | pub ty: P<Ty>, |
2137 | pub pat: P<Pat>, | |
2138 | pub id: NodeId, | |
416331ca | 2139 | pub span: Span, |
e1599b0c | 2140 | pub is_placeholder: bool, |
1a4d82fc JJ |
2141 | } |
2142 | ||
3157f602 XL |
2143 | /// Alternative representation for `Arg`s describing `self` parameter of methods. |
2144 | /// | |
0731742a | 2145 | /// E.g., `&mut self` as in `fn foo(&mut self)`. |
3dfed10e | 2146 | #[derive(Clone, Encodable, Decodable, Debug)] |
a7813a04 | 2147 | pub enum SelfKind { |
a7813a04 | 2148 | /// `self`, `mut self` |
3157f602 | 2149 | Value(Mutability), |
a7813a04 | 2150 | /// `&'lt self`, `&'lt mut self` |
3157f602 | 2151 | Region(Option<Lifetime>, Mutability), |
a7813a04 | 2152 | /// `self: TYPE`, `mut self: TYPE` |
3157f602 | 2153 | Explicit(P<Ty>, Mutability), |
a7813a04 XL |
2154 | } |
2155 | ||
2156 | pub type ExplicitSelf = Spanned<SelfKind>; | |
2157 | ||
e1599b0c | 2158 | impl Param { |
e74abb32 | 2159 | /// Attempts to cast parameter to `ExplicitSelf`. |
a7813a04 | 2160 | pub fn to_self(&self) -> Option<ExplicitSelf> { |
e74abb32 | 2161 | if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind { |
dc9dc135 | 2162 | if ident.name == kw::SelfLower { |
e74abb32 | 2163 | return match self.ty.kind { |
3157f602 | 2164 | TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))), |
e74abb32 | 2165 | TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => { |
3157f602 | 2166 | Some(respan(self.pat.span, SelfKind::Region(lt, mutbl))) |
a7813a04 | 2167 | } |
0bf4aa26 XL |
2168 | _ => Some(respan( |
2169 | self.pat.span.to(self.ty.span), | |
2170 | SelfKind::Explicit(self.ty.clone(), mutbl), | |
2171 | )), | |
2172 | }; | |
a7813a04 XL |
2173 | } |
2174 | } | |
2175 | None | |
2176 | } | |
2177 | ||
e74abb32 | 2178 | /// Returns `true` if parameter is `self`. |
3157f602 | 2179 | pub fn is_self(&self) -> bool { |
e74abb32 | 2180 | if let PatKind::Ident(_, ident, _) = self.pat.kind { |
dc9dc135 | 2181 | ident.name == kw::SelfLower |
3157f602 XL |
2182 | } else { |
2183 | false | |
2184 | } | |
2185 | } | |
2186 | ||
e74abb32 | 2187 | /// Builds a `Param` object from `ExplicitSelf`. |
dfeec247 | 2188 | pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param { |
cc61c64b | 2189 | let span = eself.span.to(eself_ident.span); |
1b1a35ee | 2190 | let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None }); |
e1599b0c | 2191 | let param = |mutbl, ty| Param { |
dc9dc135 | 2192 | attrs, |
3157f602 XL |
2193 | pat: P(Pat { |
2194 | id: DUMMY_NODE_ID, | |
e74abb32 | 2195 | kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None), |
3b2f2976 | 2196 | span, |
3dfed10e | 2197 | tokens: None, |
3157f602 | 2198 | }), |
416331ca | 2199 | span, |
3b2f2976 | 2200 | ty, |
a7813a04 | 2201 | id: DUMMY_NODE_ID, |
dfeec247 | 2202 | is_placeholder: false, |
a7813a04 XL |
2203 | }; |
2204 | match eself.node { | |
e1599b0c XL |
2205 | SelfKind::Explicit(ty, mutbl) => param(mutbl, ty), |
2206 | SelfKind::Value(mutbl) => param(mutbl, infer_ty), | |
2207 | SelfKind::Region(lt, mutbl) => param( | |
dfeec247 | 2208 | Mutability::Not, |
0bf4aa26 XL |
2209 | P(Ty { |
2210 | id: DUMMY_NODE_ID, | |
dfeec247 | 2211 | kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }), |
0bf4aa26 | 2212 | span, |
1b1a35ee | 2213 | tokens: None, |
0bf4aa26 XL |
2214 | }), |
2215 | ), | |
a7813a04 XL |
2216 | } |
2217 | } | |
223e47cc LB |
2218 | } |
2219 | ||
e74abb32 | 2220 | /// A signature (not the body) of a function declaration. |
3157f602 | 2221 | /// |
0731742a | 2222 | /// E.g., `fn foo(bar: baz)`. |
e74abb32 XL |
2223 | /// |
2224 | /// Please note that it's different from `FnHeader` structure | |
2225 | /// which contains metadata about function safety, asyncness, constness and ABI. | |
3dfed10e | 2226 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 2227 | pub struct FnDecl { |
e1599b0c | 2228 | pub inputs: Vec<Param>, |
74b04a01 | 2229 | pub output: FnRetTy, |
1a4d82fc JJ |
2230 | } |
2231 | ||
3157f602 XL |
2232 | impl FnDecl { |
2233 | pub fn get_self(&self) -> Option<ExplicitSelf> { | |
e1599b0c | 2234 | self.inputs.get(0).and_then(Param::to_self) |
3157f602 XL |
2235 | } |
2236 | pub fn has_self(&self) -> bool { | |
e74abb32 XL |
2237 | self.inputs.get(0).map_or(false, Param::is_self) |
2238 | } | |
2239 | pub fn c_variadic(&self) -> bool { | |
2240 | self.inputs.last().map_or(false, |arg| match arg.ty.kind { | |
2241 | TyKind::CVarArgs => true, | |
2242 | _ => false, | |
2243 | }) | |
3157f602 XL |
2244 | } |
2245 | } | |
2246 | ||
abe05a73 | 2247 | /// Is the trait definition an auto trait? |
3dfed10e | 2248 | #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] |
abe05a73 XL |
2249 | pub enum IsAuto { |
2250 | Yes, | |
0bf4aa26 | 2251 | No, |
abe05a73 XL |
2252 | } |
2253 | ||
3dfed10e | 2254 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug)] |
74b04a01 XL |
2255 | #[derive(HashStable_Generic)] |
2256 | pub enum Unsafe { | |
2257 | Yes(Span), | |
2258 | No, | |
60c5eb7d XL |
2259 | } |
2260 | ||
3dfed10e | 2261 | #[derive(Copy, Clone, Encodable, Decodable, Debug)] |
74b04a01 XL |
2262 | pub enum Async { |
2263 | Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId }, | |
2264 | No, | |
8faf50e0 XL |
2265 | } |
2266 | ||
74b04a01 | 2267 | impl Async { |
dc9dc135 | 2268 | pub fn is_async(self) -> bool { |
1b1a35ee | 2269 | matches!(self, Async::Yes { .. }) |
8faf50e0 | 2270 | } |
0731742a | 2271 | |
74b04a01 | 2272 | /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item. |
dc9dc135 | 2273 | pub fn opt_return_id(self) -> Option<NodeId> { |
8faf50e0 | 2274 | match self { |
74b04a01 XL |
2275 | Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id), |
2276 | Async::No => None, | |
8faf50e0 XL |
2277 | } |
2278 | } | |
2279 | } | |
2280 | ||
3dfed10e | 2281 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)] |
dfeec247 | 2282 | #[derive(HashStable_Generic)] |
74b04a01 XL |
2283 | pub enum Const { |
2284 | Yes(Span), | |
2285 | No, | |
62682a34 SL |
2286 | } |
2287 | ||
e74abb32 XL |
2288 | /// Item defaultness. |
2289 | /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532). | |
3dfed10e | 2290 | #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] |
54a0048b | 2291 | pub enum Defaultness { |
74b04a01 | 2292 | Default(Span), |
54a0048b SL |
2293 | Final, |
2294 | } | |
2295 | ||
3dfed10e | 2296 | #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] |
1a4d82fc | 2297 | pub enum ImplPolarity { |
c34b1796 | 2298 | /// `impl Trait for Type` |
1a4d82fc | 2299 | Positive, |
c34b1796 | 2300 | /// `impl !Trait for Type` |
ba9703b0 | 2301 | Negative(Span), |
1a4d82fc JJ |
2302 | } |
2303 | ||
85aaf69f | 2304 | impl fmt::Debug for ImplPolarity { |
9fa01778 | 2305 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
223e47cc | 2306 | match *self { |
1a4d82fc | 2307 | ImplPolarity::Positive => "positive".fmt(f), |
ba9703b0 | 2308 | ImplPolarity::Negative(_) => "negative".fmt(f), |
223e47cc LB |
2309 | } |
2310 | } | |
2311 | } | |
2312 | ||
3dfed10e | 2313 | #[derive(Clone, Encodable, Decodable, Debug)] |
74b04a01 | 2314 | pub enum FnRetTy { |
9fa01778 | 2315 | /// Returns type is not specified. |
c34b1796 | 2316 | /// |
0731742a XL |
2317 | /// Functions default to `()` and closures default to inference. |
2318 | /// Span points to where return type would be inserted. | |
7453a54e | 2319 | Default(Span), |
0731742a | 2320 | /// Everything else. |
7453a54e | 2321 | Ty(P<Ty>), |
1a4d82fc JJ |
2322 | } |
2323 | ||
74b04a01 | 2324 | impl FnRetTy { |
1a4d82fc JJ |
2325 | pub fn span(&self) -> Span { |
2326 | match *self { | |
74b04a01 XL |
2327 | FnRetTy::Default(span) => span, |
2328 | FnRetTy::Ty(ref ty) => ty.span, | |
1a4d82fc JJ |
2329 | } |
2330 | } | |
223e47cc LB |
2331 | } |
2332 | ||
3157f602 XL |
2333 | /// Module declaration. |
2334 | /// | |
0731742a | 2335 | /// E.g., `mod foo;` or `mod foo { .. }`. |
1b1a35ee | 2336 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
2337 | pub struct Mod { |
2338 | /// A span from the first token past `{` to the last token until `}`. | |
2339 | /// For `mod foo;`, the inner span ranges from the first token | |
2340 | /// to the last token in the external file. | |
2341 | pub inner: Span, | |
1b1a35ee XL |
2342 | /// `unsafe` keyword accepted syntactically for macro DSLs, but not |
2343 | /// semantically by Rust. | |
2344 | pub unsafety: Unsafe, | |
1a4d82fc | 2345 | pub items: Vec<P<Item>>, |
0731742a | 2346 | /// `true` for `mod foo { .. }`; `false` for `mod foo;`. |
0bf4aa26 | 2347 | pub inline: bool, |
1a4d82fc | 2348 | } |
223e47cc | 2349 | |
3157f602 XL |
2350 | /// Foreign module declaration. |
2351 | /// | |
1b1a35ee | 2352 | /// E.g., `extern { .. }` or `extern "C" { .. }`. |
3dfed10e | 2353 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 2354 | pub struct ForeignMod { |
1b1a35ee XL |
2355 | /// `unsafe` keyword accepted syntactically for macro DSLs, but not |
2356 | /// semantically by Rust. | |
2357 | pub unsafety: Unsafe, | |
60c5eb7d | 2358 | pub abi: Option<StrLit>, |
74b04a01 | 2359 | pub items: Vec<P<ForeignItem>>, |
223e47cc LB |
2360 | } |
2361 | ||
0731742a | 2362 | /// Global inline assembly. |
cc61c64b | 2363 | /// |
0731742a | 2364 | /// Also known as "module-level assembly" or "file-scoped assembly". |
3dfed10e | 2365 | #[derive(Clone, Encodable, Decodable, Debug, Copy)] |
cc61c64b XL |
2366 | pub struct GlobalAsm { |
2367 | pub asm: Symbol, | |
cc61c64b XL |
2368 | } |
2369 | ||
3dfed10e | 2370 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 2371 | pub struct EnumDef { |
7453a54e | 2372 | pub variants: Vec<Variant>, |
223e47cc | 2373 | } |
e74abb32 | 2374 | /// Enum variant. |
3dfed10e | 2375 | #[derive(Clone, Encodable, Decodable, Debug)] |
e1599b0c | 2376 | pub struct Variant { |
532ac7d7 | 2377 | /// Attributes of the variant. |
1a4d82fc | 2378 | pub attrs: Vec<Attribute>, |
532ac7d7 XL |
2379 | /// Id of the variant (not the constructor, see `VariantData::ctor_id()`). |
2380 | pub id: NodeId, | |
60c5eb7d XL |
2381 | /// Span |
2382 | pub span: Span, | |
2383 | /// The visibility of the variant. Syntactically accepted but not semantically. | |
2384 | pub vis: Visibility, | |
2385 | /// Name of the variant. | |
2386 | pub ident: Ident, | |
2387 | ||
532ac7d7 | 2388 | /// Fields and constructor id of the variant. |
b039eaaf | 2389 | pub data: VariantData, |
0731742a | 2390 | /// Explicit discriminant, e.g., `Foo = 1`. |
94b46f34 | 2391 | pub disr_expr: Option<AnonConst>, |
e1599b0c XL |
2392 | /// Is a macro placeholder |
2393 | pub is_placeholder: bool, | |
223e47cc LB |
2394 | } |
2395 | ||
0531ce1d | 2396 | /// Part of `use` item to the right of its prefix. |
3dfed10e | 2397 | #[derive(Clone, Encodable, Decodable, Debug)] |
ff7c6d11 | 2398 | pub enum UseTreeKind { |
0531ce1d | 2399 | /// `use prefix` or `use prefix as rename` |
94b46f34 XL |
2400 | /// |
2401 | /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each | |
2402 | /// namespace. | |
2403 | Simple(Option<Ident>, NodeId, NodeId), | |
0531ce1d | 2404 | /// `use prefix::{...}` |
ff7c6d11 | 2405 | Nested(Vec<(UseTree, NodeId)>), |
0531ce1d XL |
2406 | /// `use prefix::*` |
2407 | Glob, | |
223e47cc LB |
2408 | } |
2409 | ||
0531ce1d XL |
2410 | /// A tree of paths sharing common prefixes. |
2411 | /// Used in `use` items both at top-level and inside of braces in import groups. | |
3dfed10e | 2412 | #[derive(Clone, Encodable, Decodable, Debug)] |
ff7c6d11 | 2413 | pub struct UseTree { |
ff7c6d11 | 2414 | pub prefix: Path, |
0531ce1d | 2415 | pub kind: UseTreeKind, |
ff7c6d11 | 2416 | pub span: Span, |
3157f602 XL |
2417 | } |
2418 | ||
0531ce1d XL |
2419 | impl UseTree { |
2420 | pub fn ident(&self) -> Ident { | |
2421 | match self.kind { | |
94b46f34 | 2422 | UseTreeKind::Simple(Some(rename), ..) => rename, |
0bf4aa26 | 2423 | UseTreeKind::Simple(None, ..) => { |
dfeec247 | 2424 | self.prefix.segments.last().expect("empty prefix in a simple import").ident |
0bf4aa26 | 2425 | } |
0531ce1d XL |
2426 | _ => panic!("`UseTree::ident` can only be used on a simple import"), |
2427 | } | |
2428 | } | |
2429 | } | |
2430 | ||
0731742a | 2431 | /// Distinguishes between `Attribute`s that decorate items and Attributes that |
1a4d82fc JJ |
2432 | /// are contained as statements within items. These two cases need to be |
2433 | /// distinguished for pretty-printing. | |
3dfed10e | 2434 | #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)] |
1a4d82fc | 2435 | pub enum AttrStyle { |
b039eaaf SL |
2436 | Outer, |
2437 | Inner, | |
1a4d82fc | 2438 | } |
223e47cc | 2439 | |
ba9703b0 XL |
2440 | rustc_index::newtype_index! { |
2441 | pub struct AttrId { | |
2442 | ENCODABLE = custom | |
2443 | DEBUG_FORMAT = "AttrId({})" | |
b7449926 XL |
2444 | } |
2445 | } | |
2446 | ||
3dfed10e XL |
2447 | impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId { |
2448 | fn encode(&self, s: &mut S) -> Result<(), S::Error> { | |
416331ca XL |
2449 | s.emit_unit() |
2450 | } | |
2451 | } | |
2452 | ||
3dfed10e XL |
2453 | impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId { |
2454 | fn decode(d: &mut D) -> Result<AttrId, D::Error> { | |
416331ca XL |
2455 | d.read_nil().map(|_| crate::attr::mk_attr_id()) |
2456 | } | |
2457 | } | |
2458 | ||
3dfed10e | 2459 | #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
e74abb32 XL |
2460 | pub struct AttrItem { |
2461 | pub path: Path, | |
60c5eb7d | 2462 | pub args: MacArgs, |
29967ef6 | 2463 | pub tokens: Option<LazyTokenStream>, |
e74abb32 XL |
2464 | } |
2465 | ||
dfeec247 XL |
2466 | /// A list of attributes. |
2467 | pub type AttrVec = ThinVec<Attribute>; | |
2468 | ||
0731742a | 2469 | /// Metadata associated with an item. |
3dfed10e | 2470 | #[derive(Clone, Encodable, Decodable, Debug)] |
476ff2be | 2471 | pub struct Attribute { |
60c5eb7d | 2472 | pub kind: AttrKind, |
1a4d82fc | 2473 | pub id: AttrId, |
e74abb32 XL |
2474 | /// Denotes if the attribute decorates the following construct (outer) |
2475 | /// or the construct this attribute is contained within (inner). | |
1a4d82fc | 2476 | pub style: AttrStyle, |
476ff2be | 2477 | pub span: Span, |
223e47cc LB |
2478 | } |
2479 | ||
3dfed10e | 2480 | #[derive(Clone, Encodable, Decodable, Debug)] |
60c5eb7d XL |
2481 | pub enum AttrKind { |
2482 | /// A normal attribute. | |
29967ef6 | 2483 | Normal(AttrItem, Option<LazyTokenStream>), |
60c5eb7d XL |
2484 | |
2485 | /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`). | |
2486 | /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal` | |
2487 | /// variant (which is much less compact and thus more expensive). | |
3dfed10e | 2488 | DocComment(CommentKind, Symbol), |
e74abb32 XL |
2489 | } |
2490 | ||
0731742a | 2491 | /// `TraitRef`s appear in impls. |
c34b1796 | 2492 | /// |
9fa01778 | 2493 | /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all |
0731742a XL |
2494 | /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl. |
2495 | /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the | |
9fa01778 | 2496 | /// same as the impl's `NodeId`). |
3dfed10e | 2497 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc JJ |
2498 | pub struct TraitRef { |
2499 | pub path: Path, | |
2500 | pub ref_id: NodeId, | |
223e47cc LB |
2501 | } |
2502 | ||
3dfed10e | 2503 | #[derive(Clone, Encodable, Decodable, Debug)] |
1a4d82fc | 2504 | pub struct PolyTraitRef { |
dc9dc135 | 2505 | /// The `'a` in `<'a> Foo<&'a T>`. |
ff7c6d11 | 2506 | pub bound_generic_params: Vec<GenericParam>, |
223e47cc | 2507 | |
dc9dc135 | 2508 | /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`. |
1a4d82fc | 2509 | pub trait_ref: TraitRef, |
85aaf69f SL |
2510 | |
2511 | pub span: Span, | |
1a4d82fc JJ |
2512 | } |
2513 | ||
cc61c64b | 2514 | impl PolyTraitRef { |
ff7c6d11 | 2515 | pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self { |
cc61c64b | 2516 | PolyTraitRef { |
ff7c6d11 | 2517 | bound_generic_params: generic_params, |
dfeec247 | 2518 | trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID }, |
3b2f2976 | 2519 | span, |
cc61c64b XL |
2520 | } |
2521 | } | |
2522 | } | |
2523 | ||
3dfed10e | 2524 | #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)] |
abe05a73 | 2525 | pub enum CrateSugar { |
0731742a | 2526 | /// Source is `pub(crate)`. |
abe05a73 XL |
2527 | PubCrate, |
2528 | ||
0731742a | 2529 | /// Source is (just) `crate`. |
abe05a73 XL |
2530 | JustCrate, |
2531 | } | |
2532 | ||
1b1a35ee XL |
2533 | #[derive(Clone, Encodable, Decodable, Debug)] |
2534 | pub struct Visibility { | |
2535 | pub kind: VisibilityKind, | |
2536 | pub span: Span, | |
29967ef6 | 2537 | pub tokens: Option<LazyTokenStream>, |
1b1a35ee | 2538 | } |
0531ce1d | 2539 | |
3dfed10e | 2540 | #[derive(Clone, Encodable, Decodable, Debug)] |
0531ce1d | 2541 | pub enum VisibilityKind { |
1a4d82fc | 2542 | Public, |
0531ce1d | 2543 | Crate(CrateSugar), |
54a0048b | 2544 | Restricted { path: P<Path>, id: NodeId }, |
1a4d82fc JJ |
2545 | Inherited, |
2546 | } | |
2547 | ||
8faf50e0 XL |
2548 | impl VisibilityKind { |
2549 | pub fn is_pub(&self) -> bool { | |
1b1a35ee | 2550 | matches!(self, VisibilityKind::Public) |
8faf50e0 XL |
2551 | } |
2552 | } | |
2553 | ||
3157f602 XL |
2554 | /// Field of a struct. |
2555 | /// | |
0731742a | 2556 | /// E.g., `bar: usize` as in `struct Foo { bar: usize }`. |
3dfed10e | 2557 | #[derive(Clone, Encodable, Decodable, Debug)] |
54a0048b | 2558 | pub struct StructField { |
60c5eb7d XL |
2559 | pub attrs: Vec<Attribute>, |
2560 | pub id: NodeId, | |
54a0048b | 2561 | pub span: Span, |
54a0048b | 2562 | pub vis: Visibility, |
60c5eb7d XL |
2563 | pub ident: Option<Ident>, |
2564 | ||
1a4d82fc | 2565 | pub ty: P<Ty>, |
e1599b0c | 2566 | pub is_placeholder: bool, |
1a4d82fc JJ |
2567 | } |
2568 | ||
532ac7d7 | 2569 | /// Fields and constructor ids of enum variants and structs. |
3dfed10e | 2570 | #[derive(Clone, Encodable, Decodable, Debug)] |
b039eaaf | 2571 | pub enum VariantData { |
3157f602 XL |
2572 | /// Struct variant. |
2573 | /// | |
0731742a | 2574 | /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`. |
532ac7d7 | 2575 | Struct(Vec<StructField>, bool), |
3157f602 XL |
2576 | /// Tuple variant. |
2577 | /// | |
0731742a | 2578 | /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`. |
b039eaaf | 2579 | Tuple(Vec<StructField>, NodeId), |
3157f602 XL |
2580 | /// Unit variant. |
2581 | /// | |
0731742a | 2582 | /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`. |
b039eaaf SL |
2583 | Unit(NodeId), |
2584 | } | |
2585 | ||
2586 | impl VariantData { | |
532ac7d7 | 2587 | /// Return the fields of this variant. |
b039eaaf SL |
2588 | pub fn fields(&self) -> &[StructField] { |
2589 | match *self { | |
532ac7d7 | 2590 | VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields, |
b039eaaf SL |
2591 | _ => &[], |
2592 | } | |
2593 | } | |
532ac7d7 XL |
2594 | |
2595 | /// Return the `NodeId` of this variant's constructor, if it has one. | |
2596 | pub fn ctor_id(&self) -> Option<NodeId> { | |
b039eaaf | 2597 | match *self { |
532ac7d7 XL |
2598 | VariantData::Struct(..) => None, |
2599 | VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id), | |
0bf4aa26 | 2600 | } |
b039eaaf | 2601 | } |
223e47cc LB |
2602 | } |
2603 | ||
74b04a01 | 2604 | /// An item definition. |
3dfed10e | 2605 | #[derive(Clone, Encodable, Decodable, Debug)] |
60c5eb7d | 2606 | pub struct Item<K = ItemKind> { |
1a4d82fc JJ |
2607 | pub attrs: Vec<Attribute>, |
2608 | pub id: NodeId, | |
1a4d82fc | 2609 | pub span: Span, |
60c5eb7d | 2610 | pub vis: Visibility, |
74b04a01 XL |
2611 | /// The name of the item. |
2612 | /// It might be a dummy name in case of anonymous items. | |
60c5eb7d XL |
2613 | pub ident: Ident, |
2614 | ||
2615 | pub kind: K, | |
3b2f2976 XL |
2616 | |
2617 | /// Original tokens this item was parsed from. This isn't necessarily | |
2618 | /// available for all items, although over time more and more items should | |
2619 | /// have this be `Some`. Right now this is primarily used for procedural | |
2620 | /// macros, notably custom attributes. | |
2621 | /// | |
2622 | /// Note that the tokens here do not include the outer attributes, but will | |
2623 | /// include inner attributes. | |
29967ef6 | 2624 | pub tokens: Option<LazyTokenStream>, |
1a4d82fc JJ |
2625 | } |
2626 | ||
9fa01778 XL |
2627 | impl Item { |
2628 | /// Return the span that encompasses the attributes. | |
2629 | pub fn span_with_attributes(&self) -> Span { | |
532ac7d7 | 2630 | self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span)) |
9fa01778 XL |
2631 | } |
2632 | } | |
2633 | ||
74b04a01 XL |
2634 | impl<K: Into<ItemKind>> Item<K> { |
2635 | pub fn into_item(self) -> Item { | |
2636 | let Item { attrs, id, span, vis, ident, kind, tokens } = self; | |
2637 | Item { attrs, id, span, vis, ident, kind: kind.into(), tokens } | |
2638 | } | |
2639 | } | |
2640 | ||
60c5eb7d | 2641 | /// `extern` qualifier on a function item or function type. |
3dfed10e | 2642 | #[derive(Clone, Copy, Encodable, Decodable, Debug)] |
60c5eb7d XL |
2643 | pub enum Extern { |
2644 | None, | |
2645 | Implicit, | |
2646 | Explicit(StrLit), | |
2647 | } | |
2648 | ||
2649 | impl Extern { | |
2650 | pub fn from_abi(abi: Option<StrLit>) -> Extern { | |
2651 | abi.map_or(Extern::Implicit, Extern::Explicit) | |
2652 | } | |
2653 | } | |
2654 | ||
0731742a | 2655 | /// A function header. |
8faf50e0 | 2656 | /// |
0731742a XL |
2657 | /// All the information between the visibility and the name of the function is |
2658 | /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`). | |
3dfed10e | 2659 | #[derive(Clone, Copy, Encodable, Decodable, Debug)] |
8faf50e0 | 2660 | pub struct FnHeader { |
74b04a01 XL |
2661 | pub unsafety: Unsafe, |
2662 | pub asyncness: Async, | |
2663 | pub constness: Const, | |
60c5eb7d | 2664 | pub ext: Extern, |
8faf50e0 XL |
2665 | } |
2666 | ||
74b04a01 XL |
2667 | impl FnHeader { |
2668 | /// Does this function header have any qualifiers or is it empty? | |
2669 | pub fn has_qualifiers(&self) -> bool { | |
2670 | let Self { unsafety, asyncness, constness, ext } = self; | |
2671 | matches!(unsafety, Unsafe::Yes(_)) | |
2672 | || asyncness.is_async() | |
2673 | || matches!(constness, Const::Yes(_)) | |
2674 | || !matches!(ext, Extern::None) | |
2675 | } | |
2676 | } | |
2677 | ||
8faf50e0 XL |
2678 | impl Default for FnHeader { |
2679 | fn default() -> FnHeader { | |
2680 | FnHeader { | |
74b04a01 XL |
2681 | unsafety: Unsafe::No, |
2682 | asyncness: Async::No, | |
2683 | constness: Const::No, | |
60c5eb7d | 2684 | ext: Extern::None, |
8faf50e0 XL |
2685 | } |
2686 | } | |
2687 | } | |
2688 | ||
3dfed10e | 2689 | #[derive(Clone, Encodable, Decodable, Debug)] |
7453a54e | 2690 | pub enum ItemKind { |
e1599b0c | 2691 | /// An `extern crate` item, with the optional *original* crate name if the crate was renamed. |
c34b1796 | 2692 | /// |
0731742a | 2693 | /// E.g., `extern crate foo` or `extern crate foo_bar as foo`. |
f9f354fc | 2694 | ExternCrate(Option<Symbol>), |
e1599b0c | 2695 | /// A use declaration item (`use`). |
3157f602 | 2696 | /// |
0731742a | 2697 | /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`. |
ff7c6d11 | 2698 | Use(P<UseTree>), |
e1599b0c | 2699 | /// A static item (`static`). |
3157f602 | 2700 | /// |
0731742a | 2701 | /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`. |
74b04a01 | 2702 | Static(P<Ty>, Mutability, Option<P<Expr>>), |
e1599b0c | 2703 | /// A constant item (`const`). |
3157f602 | 2704 | /// |
0731742a | 2705 | /// E.g., `const FOO: i32 = 42;`. |
74b04a01 | 2706 | Const(Defaultness, P<Ty>, Option<P<Expr>>), |
e1599b0c | 2707 | /// A function declaration (`fn`). |
3157f602 | 2708 | /// |
0731742a | 2709 | /// E.g., `fn foo(bar: usize) -> usize { .. }`. |
74b04a01 | 2710 | Fn(Defaultness, FnSig, Generics, Option<P<Block>>), |
e1599b0c | 2711 | /// A module declaration (`mod`). |
3157f602 | 2712 | /// |
0731742a | 2713 | /// E.g., `mod foo;` or `mod foo { .. }`. |
7453a54e | 2714 | Mod(Mod), |
e1599b0c | 2715 | /// An external module (`extern`). |
3157f602 | 2716 | /// |
0731742a | 2717 | /// E.g., `extern {}` or `extern "C" {}`. |
7453a54e | 2718 | ForeignMod(ForeignMod), |
0731742a | 2719 | /// Module-level inline assembly (from `global_asm!()`). |
cc61c64b | 2720 | GlobalAsm(P<GlobalAsm>), |
e1599b0c | 2721 | /// A type alias (`type`). |
3157f602 | 2722 | /// |
0731742a | 2723 | /// E.g., `type Foo = Bar<u8>;`. |
74b04a01 | 2724 | TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>), |
e1599b0c | 2725 | /// An enum definition (`enum`). |
3157f602 | 2726 | /// |
0731742a | 2727 | /// E.g., `enum Foo<A, B> { C<A>, D<B> }`. |
7453a54e | 2728 | Enum(EnumDef, Generics), |
e1599b0c | 2729 | /// A struct definition (`struct`). |
3157f602 | 2730 | /// |
0731742a | 2731 | /// E.g., `struct Foo<A> { x: A }`. |
7453a54e | 2732 | Struct(VariantData, Generics), |
e1599b0c | 2733 | /// A union definition (`union`). |
9e0c209e | 2734 | /// |
0731742a | 2735 | /// E.g., `union Foo<A, B> { x: A, y: B }`. |
9e0c209e | 2736 | Union(VariantData, Generics), |
e1599b0c | 2737 | /// A trait declaration (`trait`). |
3157f602 | 2738 | /// |
0731742a | 2739 | /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`. |
74b04a01 | 2740 | Trait(IsAuto, Unsafe, Generics, GenericBounds, Vec<P<AssocItem>>), |
ff7c6d11 XL |
2741 | /// Trait alias |
2742 | /// | |
0731742a | 2743 | /// E.g., `trait Foo = Bar + Quux;`. |
8faf50e0 | 2744 | TraitAlias(Generics, GenericBounds), |
3157f602 XL |
2745 | /// An implementation. |
2746 | /// | |
0731742a | 2747 | /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`. |
dfeec247 | 2748 | Impl { |
74b04a01 | 2749 | unsafety: Unsafe, |
dfeec247 XL |
2750 | polarity: ImplPolarity, |
2751 | defaultness: Defaultness, | |
74b04a01 | 2752 | constness: Const, |
dfeec247 XL |
2753 | generics: Generics, |
2754 | ||
2755 | /// The trait being implemented, if any. | |
2756 | of_trait: Option<TraitRef>, | |
2757 | ||
2758 | self_ty: P<Ty>, | |
74b04a01 | 2759 | items: Vec<P<AssocItem>>, |
dfeec247 | 2760 | }, |
8bb4bdeb | 2761 | /// A macro invocation. |
3157f602 | 2762 | /// |
e1599b0c | 2763 | /// E.g., `foo!(..)`. |
ba9703b0 | 2764 | MacCall(MacCall), |
8bb4bdeb XL |
2765 | |
2766 | /// A macro definition. | |
7cac9316 | 2767 | MacroDef(MacroDef), |
1a4d82fc JJ |
2768 | } |
2769 | ||
7453a54e | 2770 | impl ItemKind { |
74b04a01 XL |
2771 | pub fn article(&self) -> &str { |
2772 | use ItemKind::*; | |
2773 | match self { | |
2774 | Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..) | |
2775 | | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a", | |
ba9703b0 | 2776 | ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an", |
74b04a01 XL |
2777 | } |
2778 | } | |
2779 | ||
2780 | pub fn descr(&self) -> &str { | |
2781 | match self { | |
7453a54e | 2782 | ItemKind::ExternCrate(..) => "extern crate", |
74b04a01 | 2783 | ItemKind::Use(..) => "`use` import", |
7453a54e SL |
2784 | ItemKind::Static(..) => "static item", |
2785 | ItemKind::Const(..) => "constant item", | |
2786 | ItemKind::Fn(..) => "function", | |
2787 | ItemKind::Mod(..) => "module", | |
74b04a01 XL |
2788 | ItemKind::ForeignMod(..) => "extern block", |
2789 | ItemKind::GlobalAsm(..) => "global asm item", | |
416331ca | 2790 | ItemKind::TyAlias(..) => "type alias", |
7453a54e SL |
2791 | ItemKind::Enum(..) => "enum", |
2792 | ItemKind::Struct(..) => "struct", | |
9e0c209e | 2793 | ItemKind::Union(..) => "union", |
7453a54e | 2794 | ItemKind::Trait(..) => "trait", |
ff7c6d11 | 2795 | ItemKind::TraitAlias(..) => "trait alias", |
ba9703b0 | 2796 | ItemKind::MacCall(..) => "item macro invocation", |
74b04a01 XL |
2797 | ItemKind::MacroDef(..) => "macro definition", |
2798 | ItemKind::Impl { .. } => "implementation", | |
dfeec247 XL |
2799 | } |
2800 | } | |
2801 | ||
2802 | pub fn generics(&self) -> Option<&Generics> { | |
2803 | match self { | |
74b04a01 XL |
2804 | Self::Fn(_, _, generics, _) |
2805 | | Self::TyAlias(_, generics, ..) | |
dfeec247 XL |
2806 | | Self::Enum(_, generics) |
2807 | | Self::Struct(_, generics) | |
2808 | | Self::Union(_, generics) | |
2809 | | Self::Trait(_, _, generics, ..) | |
2810 | | Self::TraitAlias(generics, _) | |
2811 | | Self::Impl { generics, .. } => Some(generics), | |
2812 | _ => None, | |
1a4d82fc | 2813 | } |
970d7e83 | 2814 | } |
1a4d82fc | 2815 | } |
970d7e83 | 2816 | |
74b04a01 XL |
2817 | /// Represents associated items. |
2818 | /// These include items in `impl` and `trait` definitions. | |
2819 | pub type AssocItem = Item<AssocItemKind>; | |
2820 | ||
2821 | /// Represents associated item kinds. | |
2822 | /// | |
2823 | /// The term "provided" in the variants below refers to the item having a default | |
2824 | /// definition / body. Meanwhile, a "required" item lacks a definition / body. | |
2825 | /// In an implementation, all items must be provided. | |
2826 | /// The `Option`s below denote the bodies, where `Some(_)` | |
2827 | /// means "provided" and conversely `None` means "required". | |
3dfed10e | 2828 | #[derive(Clone, Encodable, Decodable, Debug)] |
74b04a01 XL |
2829 | pub enum AssocItemKind { |
2830 | /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`. | |
2831 | /// If `def` is parsed, then the constant is provided, and otherwise required. | |
2832 | Const(Defaultness, P<Ty>, Option<P<Expr>>), | |
2833 | /// An associated function. | |
2834 | Fn(Defaultness, FnSig, Generics, Option<P<Block>>), | |
2835 | /// An associated type. | |
2836 | TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>), | |
2837 | /// A macro expanding to associated items. | |
ba9703b0 | 2838 | MacCall(MacCall), |
74b04a01 XL |
2839 | } |
2840 | ||
2841 | impl AssocItemKind { | |
2842 | pub fn defaultness(&self) -> Defaultness { | |
2843 | match *self { | |
2844 | Self::Const(def, ..) | Self::Fn(def, ..) | Self::TyAlias(def, ..) => def, | |
ba9703b0 | 2845 | Self::MacCall(..) => Defaultness::Final, |
74b04a01 XL |
2846 | } |
2847 | } | |
2848 | } | |
2849 | ||
2850 | impl From<AssocItemKind> for ItemKind { | |
2851 | fn from(assoc_item_kind: AssocItemKind) -> ItemKind { | |
2852 | match assoc_item_kind { | |
2853 | AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c), | |
2854 | AssocItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d), | |
2855 | AssocItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d), | |
ba9703b0 | 2856 | AssocItemKind::MacCall(a) => ItemKind::MacCall(a), |
74b04a01 XL |
2857 | } |
2858 | } | |
2859 | } | |
970d7e83 | 2860 | |
74b04a01 XL |
2861 | impl TryFrom<ItemKind> for AssocItemKind { |
2862 | type Error = ItemKind; | |
2863 | ||
2864 | fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> { | |
2865 | Ok(match item_kind { | |
2866 | ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c), | |
2867 | ItemKind::Fn(a, b, c, d) => AssocItemKind::Fn(a, b, c, d), | |
2868 | ItemKind::TyAlias(a, b, c, d) => AssocItemKind::TyAlias(a, b, c, d), | |
ba9703b0 | 2869 | ItemKind::MacCall(a) => AssocItemKind::MacCall(a), |
74b04a01 XL |
2870 | _ => return Err(item_kind), |
2871 | }) | |
2872 | } | |
2873 | } | |
2874 | ||
2875 | /// An item in `extern` block. | |
3dfed10e | 2876 | #[derive(Clone, Encodable, Decodable, Debug)] |
7453a54e | 2877 | pub enum ForeignItemKind { |
74b04a01 XL |
2878 | /// A foreign static item (`static FOO: u8`). |
2879 | Static(P<Ty>, Mutability, Option<P<Expr>>), | |
0731742a | 2880 | /// A foreign function. |
74b04a01 | 2881 | Fn(Defaultness, FnSig, Generics, Option<P<Block>>), |
0731742a | 2882 | /// A foreign type. |
74b04a01 XL |
2883 | TyAlias(Defaultness, Generics, GenericBounds, Option<P<Ty>>), |
2884 | /// A macro expanding to foreign items. | |
ba9703b0 | 2885 | MacCall(MacCall), |
1a4d82fc | 2886 | } |
970d7e83 | 2887 | |
74b04a01 XL |
2888 | impl From<ForeignItemKind> for ItemKind { |
2889 | fn from(foreign_item_kind: ForeignItemKind) -> ItemKind { | |
2890 | match foreign_item_kind { | |
2891 | ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c), | |
2892 | ForeignItemKind::Fn(a, b, c, d) => ItemKind::Fn(a, b, c, d), | |
2893 | ForeignItemKind::TyAlias(a, b, c, d) => ItemKind::TyAlias(a, b, c, d), | |
ba9703b0 | 2894 | ForeignItemKind::MacCall(a) => ItemKind::MacCall(a), |
1a4d82fc | 2895 | } |
223e47cc | 2896 | } |
1a4d82fc | 2897 | } |
74b04a01 XL |
2898 | |
2899 | impl TryFrom<ItemKind> for ForeignItemKind { | |
2900 | type Error = ItemKind; | |
2901 | ||
2902 | fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> { | |
2903 | Ok(match item_kind { | |
2904 | ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c), | |
2905 | ItemKind::Fn(a, b, c, d) => ForeignItemKind::Fn(a, b, c, d), | |
2906 | ItemKind::TyAlias(a, b, c, d) => ForeignItemKind::TyAlias(a, b, c, d), | |
ba9703b0 | 2907 | ItemKind::MacCall(a) => ForeignItemKind::MacCall(a), |
74b04a01 XL |
2908 | _ => return Err(item_kind), |
2909 | }) | |
2910 | } | |
2911 | } | |
2912 | ||
2913 | pub type ForeignItem = Item<ForeignItemKind>; |