]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/expr.rs
Merge #10474
[rust.git] / crates / hir_def / src / expr.rs
1 //! This module describes hir-level representation of expressions.
2 //!
3 //! This representation is:
4 //!
5 //! 1. Identity-based. Each expression has an `id`, so we can distinguish
6 //!    between different `1` in `1 + 1`.
7 //! 2. Independent of syntax. Though syntactic provenance information can be
8 //!    attached separately via id-based side map.
9 //! 3. Unresolved. Paths are stored as sequences of names, and not as defs the
10 //!    names refer to.
11 //! 4. Desugared. There's no `if let`.
12 //!
13 //! See also a neighboring `body` module.
14
15 use hir_expand::name::Name;
16 use la_arena::{Idx, RawIdx};
17
18 use crate::{
19     builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
20     intern::Interned,
21     path::{GenericArgs, Path},
22     type_ref::{Mutability, Rawness, TypeRef},
23     BlockId,
24 };
25
26 pub use syntax::ast::{ArithOp, BinaryOp, CmpOp, LogicOp, Ordering, RangeOp, UnaryOp};
27
28 pub type ExprId = Idx<Expr>;
29 pub(crate) fn dummy_expr_id() -> ExprId {
30     ExprId::from_raw(RawIdx::from(!0))
31 }
32
33 pub type PatId = Idx<Pat>;
34
35 #[derive(Debug, Clone, Eq, PartialEq)]
36 pub struct Label {
37     pub name: Name,
38 }
39 pub type LabelId = Idx<Label>;
40
41 #[derive(Debug, Clone, Eq, PartialEq)]
42 pub enum Literal {
43     String(String),
44     ByteString(Vec<u8>),
45     Char(char),
46     Bool(bool),
47     Int(i128, Option<BuiltinInt>),
48     Uint(u128, Option<BuiltinUint>),
49     Float(u64, Option<BuiltinFloat>), // FIXME: f64 is not Eq
50 }
51
52 #[derive(Debug, Clone, Eq, PartialEq)]
53 pub enum Expr {
54     /// This is produced if the syntax tree does not have a required expression piece.
55     Missing,
56     Path(Path),
57     If {
58         condition: ExprId,
59         then_branch: ExprId,
60         else_branch: Option<ExprId>,
61     },
62     Block {
63         id: BlockId,
64         statements: Vec<Statement>,
65         tail: Option<ExprId>,
66         label: Option<LabelId>,
67     },
68     Loop {
69         body: ExprId,
70         label: Option<LabelId>,
71     },
72     While {
73         condition: ExprId,
74         body: ExprId,
75         label: Option<LabelId>,
76     },
77     For {
78         iterable: ExprId,
79         pat: PatId,
80         body: ExprId,
81         label: Option<LabelId>,
82     },
83     Call {
84         callee: ExprId,
85         args: Vec<ExprId>,
86     },
87     MethodCall {
88         receiver: ExprId,
89         method_name: Name,
90         args: Vec<ExprId>,
91         generic_args: Option<Box<GenericArgs>>,
92     },
93     Match {
94         expr: ExprId,
95         arms: Vec<MatchArm>,
96     },
97     Continue {
98         label: Option<Name>,
99     },
100     Break {
101         expr: Option<ExprId>,
102         label: Option<Name>,
103     },
104     Return {
105         expr: Option<ExprId>,
106     },
107     Yield {
108         expr: Option<ExprId>,
109     },
110     RecordLit {
111         path: Option<Box<Path>>,
112         fields: Vec<RecordLitField>,
113         spread: Option<ExprId>,
114     },
115     Field {
116         expr: ExprId,
117         name: Name,
118     },
119     Await {
120         expr: ExprId,
121     },
122     Try {
123         expr: ExprId,
124     },
125     TryBlock {
126         body: ExprId,
127     },
128     Async {
129         body: ExprId,
130     },
131     Const {
132         body: ExprId,
133     },
134     Cast {
135         expr: ExprId,
136         type_ref: Interned<TypeRef>,
137     },
138     Ref {
139         expr: ExprId,
140         rawness: Rawness,
141         mutability: Mutability,
142     },
143     Box {
144         expr: ExprId,
145     },
146     UnaryOp {
147         expr: ExprId,
148         op: UnaryOp,
149     },
150     BinaryOp {
151         lhs: ExprId,
152         rhs: ExprId,
153         op: Option<BinaryOp>,
154     },
155     Range {
156         lhs: Option<ExprId>,
157         rhs: Option<ExprId>,
158         range_type: RangeOp,
159     },
160     Index {
161         base: ExprId,
162         index: ExprId,
163     },
164     Lambda {
165         args: Vec<PatId>,
166         arg_types: Vec<Option<Interned<TypeRef>>>,
167         ret_type: Option<Interned<TypeRef>>,
168         body: ExprId,
169     },
170     Tuple {
171         exprs: Vec<ExprId>,
172     },
173     Unsafe {
174         body: ExprId,
175     },
176     MacroStmts {
177         tail: ExprId,
178     },
179     Array(Array),
180     Literal(Literal),
181 }
182
183 #[derive(Debug, Clone, Eq, PartialEq)]
184 pub enum Array {
185     ElementList(Vec<ExprId>),
186     Repeat { initializer: ExprId, repeat: ExprId },
187 }
188
189 #[derive(Debug, Clone, Eq, PartialEq)]
190 pub struct MatchArm {
191     pub pat: PatId,
192     pub guard: Option<MatchGuard>,
193     pub expr: ExprId,
194 }
195
196 #[derive(Debug, Clone, Eq, PartialEq)]
197 pub enum MatchGuard {
198     If { expr: ExprId },
199
200     IfLet { pat: PatId, expr: ExprId },
201 }
202
203 #[derive(Debug, Clone, Eq, PartialEq)]
204 pub struct RecordLitField {
205     pub name: Name,
206     pub expr: ExprId,
207 }
208
209 #[derive(Debug, Clone, Eq, PartialEq)]
210 pub enum Statement {
211     Let {
212         pat: PatId,
213         type_ref: Option<Interned<TypeRef>>,
214         initializer: Option<ExprId>,
215         else_branch: Option<ExprId>,
216     },
217     Expr {
218         expr: ExprId,
219         has_semi: bool,
220     },
221 }
222
223 impl Expr {
224     pub fn walk_child_exprs(&self, mut f: impl FnMut(ExprId)) {
225         match self {
226             Expr::Missing => {}
227             Expr::Path(_) => {}
228             Expr::If { condition, then_branch, else_branch } => {
229                 f(*condition);
230                 f(*then_branch);
231                 if let Some(else_branch) = else_branch {
232                     f(*else_branch);
233                 }
234             }
235             Expr::Block { statements, tail, .. } => {
236                 for stmt in statements {
237                     match stmt {
238                         Statement::Let { initializer, .. } => {
239                             if let Some(expr) = initializer {
240                                 f(*expr);
241                             }
242                         }
243                         Statement::Expr { expr: expression, .. } => f(*expression),
244                     }
245                 }
246                 if let Some(expr) = tail {
247                     f(*expr);
248                 }
249             }
250             Expr::TryBlock { body }
251             | Expr::Unsafe { body }
252             | Expr::Async { body }
253             | Expr::Const { body } => f(*body),
254             Expr::Loop { body, .. } => f(*body),
255             Expr::While { condition, body, .. } => {
256                 f(*condition);
257                 f(*body);
258             }
259             Expr::For { iterable, body, .. } => {
260                 f(*iterable);
261                 f(*body);
262             }
263             Expr::Call { callee, args } => {
264                 f(*callee);
265                 for arg in args {
266                     f(*arg);
267                 }
268             }
269             Expr::MethodCall { receiver, args, .. } => {
270                 f(*receiver);
271                 for arg in args {
272                     f(*arg);
273                 }
274             }
275             Expr::Match { expr, arms } => {
276                 f(*expr);
277                 for arm in arms {
278                     f(arm.expr);
279                 }
280             }
281             Expr::Continue { .. } => {}
282             Expr::Break { expr, .. } | Expr::Return { expr } | Expr::Yield { expr } => {
283                 if let Some(expr) = expr {
284                     f(*expr);
285                 }
286             }
287             Expr::RecordLit { fields, spread, .. } => {
288                 for field in fields {
289                     f(field.expr);
290                 }
291                 if let Some(expr) = spread {
292                     f(*expr);
293                 }
294             }
295             Expr::Lambda { body, .. } => {
296                 f(*body);
297             }
298             Expr::BinaryOp { lhs, rhs, .. } => {
299                 f(*lhs);
300                 f(*rhs);
301             }
302             Expr::Range { lhs, rhs, .. } => {
303                 if let Some(lhs) = rhs {
304                     f(*lhs);
305                 }
306                 if let Some(rhs) = lhs {
307                     f(*rhs);
308                 }
309             }
310             Expr::Index { base, index } => {
311                 f(*base);
312                 f(*index);
313             }
314             Expr::Field { expr, .. }
315             | Expr::Await { expr }
316             | Expr::Try { expr }
317             | Expr::Cast { expr, .. }
318             | Expr::Ref { expr, .. }
319             | Expr::UnaryOp { expr, .. }
320             | Expr::Box { expr } => {
321                 f(*expr);
322             }
323             Expr::Tuple { exprs } => {
324                 for expr in exprs {
325                     f(*expr);
326                 }
327             }
328             Expr::Array(a) => match a {
329                 Array::ElementList(exprs) => {
330                     for expr in exprs {
331                         f(*expr);
332                     }
333                 }
334                 Array::Repeat { initializer, repeat } => {
335                     f(*initializer);
336                     f(*repeat)
337                 }
338             },
339             Expr::MacroStmts { tail } => f(*tail),
340             Expr::Literal(_) => {}
341         }
342     }
343 }
344
345 /// Explicit binding annotations given in the HIR for a binding. Note
346 /// that this is not the final binding *mode* that we infer after type
347 /// inference.
348 #[derive(Clone, PartialEq, Eq, Debug, Copy)]
349 pub enum BindingAnnotation {
350     /// No binding annotation given: this means that the final binding mode
351     /// will depend on whether we have skipped through a `&` reference
352     /// when matching. For example, the `x` in `Some(x)` will have binding
353     /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
354     /// ultimately be inferred to be by-reference.
355     Unannotated,
356
357     /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
358     Mutable,
359
360     /// Annotated as `ref`, like `ref x`
361     Ref,
362
363     /// Annotated as `ref mut x`.
364     RefMut,
365 }
366
367 impl BindingAnnotation {
368     pub fn new(is_mutable: bool, is_ref: bool) -> Self {
369         match (is_mutable, is_ref) {
370             (true, true) => BindingAnnotation::RefMut,
371             (false, true) => BindingAnnotation::Ref,
372             (true, false) => BindingAnnotation::Mutable,
373             (false, false) => BindingAnnotation::Unannotated,
374         }
375     }
376 }
377
378 #[derive(Debug, Clone, Eq, PartialEq)]
379 pub struct RecordFieldPat {
380     pub name: Name,
381     pub pat: PatId,
382 }
383
384 /// Close relative to rustc's hir::PatKind
385 #[derive(Debug, Clone, Eq, PartialEq)]
386 pub enum Pat {
387     Missing,
388     Wild,
389     Tuple { args: Vec<PatId>, ellipsis: Option<usize> },
390     Or(Vec<PatId>),
391     Record { path: Option<Box<Path>>, args: Vec<RecordFieldPat>, ellipsis: bool },
392     Range { start: ExprId, end: ExprId },
393     Slice { prefix: Vec<PatId>, slice: Option<PatId>, suffix: Vec<PatId> },
394     Path(Box<Path>),
395     Lit(ExprId),
396     Bind { mode: BindingAnnotation, name: Name, subpat: Option<PatId> },
397     TupleStruct { path: Option<Box<Path>>, args: Vec<PatId>, ellipsis: Option<usize> },
398     Ref { pat: PatId, mutability: Mutability },
399     Box { inner: PatId },
400     ConstBlock(ExprId),
401 }
402
403 impl Pat {
404     pub fn walk_child_pats(&self, mut f: impl FnMut(PatId)) {
405         match self {
406             Pat::Range { .. }
407             | Pat::Lit(..)
408             | Pat::Path(..)
409             | Pat::ConstBlock(..)
410             | Pat::Wild
411             | Pat::Missing => {}
412             Pat::Bind { subpat, .. } => {
413                 subpat.iter().copied().for_each(f);
414             }
415             Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => {
416                 args.iter().copied().for_each(f);
417             }
418             Pat::Ref { pat, .. } => f(*pat),
419             Pat::Slice { prefix, slice, suffix } => {
420                 let total_iter = prefix.iter().chain(slice.iter()).chain(suffix.iter());
421                 total_iter.copied().for_each(f);
422             }
423             Pat::Record { args, .. } => {
424                 args.iter().map(|f| f.pat).for_each(f);
425             }
426             Pat::Box { inner } => f(*inner),
427         }
428     }
429 }