]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/expr.rs
Merge #11424
[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(Box<str>),
44     ByteString(Box<[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     Let {
63         pat: PatId,
64         expr: ExprId,
65     },
66     Block {
67         id: BlockId,
68         statements: Box<[Statement]>,
69         tail: Option<ExprId>,
70         label: Option<LabelId>,
71     },
72     Loop {
73         body: ExprId,
74         label: Option<LabelId>,
75     },
76     While {
77         condition: ExprId,
78         body: ExprId,
79         label: Option<LabelId>,
80     },
81     For {
82         iterable: ExprId,
83         pat: PatId,
84         body: ExprId,
85         label: Option<LabelId>,
86     },
87     Call {
88         callee: ExprId,
89         args: Box<[ExprId]>,
90     },
91     MethodCall {
92         receiver: ExprId,
93         method_name: Name,
94         args: Box<[ExprId]>,
95         generic_args: Option<Box<GenericArgs>>,
96     },
97     Match {
98         expr: ExprId,
99         arms: Box<[MatchArm]>,
100     },
101     Continue {
102         label: Option<Name>,
103     },
104     Break {
105         expr: Option<ExprId>,
106         label: Option<Name>,
107     },
108     Return {
109         expr: Option<ExprId>,
110     },
111     Yield {
112         expr: Option<ExprId>,
113     },
114     RecordLit {
115         path: Option<Box<Path>>,
116         fields: Box<[RecordLitField]>,
117         spread: Option<ExprId>,
118     },
119     Field {
120         expr: ExprId,
121         name: Name,
122     },
123     Await {
124         expr: ExprId,
125     },
126     Try {
127         expr: ExprId,
128     },
129     TryBlock {
130         body: ExprId,
131     },
132     Async {
133         body: ExprId,
134     },
135     Const {
136         body: ExprId,
137     },
138     Cast {
139         expr: ExprId,
140         type_ref: Interned<TypeRef>,
141     },
142     Ref {
143         expr: ExprId,
144         rawness: Rawness,
145         mutability: Mutability,
146     },
147     Box {
148         expr: ExprId,
149     },
150     UnaryOp {
151         expr: ExprId,
152         op: UnaryOp,
153     },
154     BinaryOp {
155         lhs: ExprId,
156         rhs: ExprId,
157         op: Option<BinaryOp>,
158     },
159     Range {
160         lhs: Option<ExprId>,
161         rhs: Option<ExprId>,
162         range_type: RangeOp,
163     },
164     Index {
165         base: ExprId,
166         index: ExprId,
167     },
168     Lambda {
169         args: Box<[PatId]>,
170         arg_types: Box<[Option<Interned<TypeRef>>]>,
171         ret_type: Option<Interned<TypeRef>>,
172         body: ExprId,
173     },
174     Tuple {
175         exprs: Box<[ExprId]>,
176     },
177     Unsafe {
178         body: ExprId,
179     },
180     MacroStmts {
181         tail: ExprId,
182     },
183     Array(Array),
184     Literal(Literal),
185 }
186
187 #[derive(Debug, Clone, Eq, PartialEq)]
188 pub enum Array {
189     ElementList(Box<[ExprId]>),
190     Repeat { initializer: ExprId, repeat: ExprId },
191 }
192
193 #[derive(Debug, Clone, Eq, PartialEq)]
194 pub struct MatchArm {
195     pub pat: PatId,
196     pub guard: Option<ExprId>,
197     pub expr: ExprId,
198 }
199
200 #[derive(Debug, Clone, Eq, PartialEq)]
201 pub struct RecordLitField {
202     pub name: Name,
203     pub expr: ExprId,
204 }
205
206 #[derive(Debug, Clone, Eq, PartialEq)]
207 pub enum Statement {
208     Let {
209         pat: PatId,
210         type_ref: Option<Interned<TypeRef>>,
211         initializer: Option<ExprId>,
212         else_branch: Option<ExprId>,
213     },
214     Expr {
215         expr: ExprId,
216         has_semi: bool,
217     },
218 }
219
220 impl Expr {
221     pub fn walk_child_exprs(&self, mut f: impl FnMut(ExprId)) {
222         match self {
223             Expr::Missing => {}
224             Expr::Path(_) => {}
225             Expr::If { condition, then_branch, else_branch } => {
226                 f(*condition);
227                 f(*then_branch);
228                 if let &Some(else_branch) = else_branch {
229                     f(else_branch);
230                 }
231             }
232             Expr::Let { expr, .. } => {
233                 f(*expr);
234             }
235             Expr::Block { statements, tail, .. } => {
236                 for stmt in statements.iter() {
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                 args.iter().copied().for_each(f);
266             }
267             Expr::MethodCall { receiver, args, .. } => {
268                 f(*receiver);
269                 args.iter().copied().for_each(f);
270             }
271             Expr::Match { expr, arms } => {
272                 f(*expr);
273                 arms.iter().map(|arm| arm.expr).for_each(f);
274             }
275             Expr::Continue { .. } => {}
276             Expr::Break { expr, .. } | Expr::Return { expr } | Expr::Yield { expr } => {
277                 if let &Some(expr) = expr {
278                     f(expr);
279                 }
280             }
281             Expr::RecordLit { fields, spread, .. } => {
282                 for field in fields.iter() {
283                     f(field.expr);
284                 }
285                 if let &Some(expr) = spread {
286                     f(expr);
287                 }
288             }
289             Expr::Lambda { body, .. } => {
290                 f(*body);
291             }
292             Expr::BinaryOp { lhs, rhs, .. } => {
293                 f(*lhs);
294                 f(*rhs);
295             }
296             Expr::Range { lhs, rhs, .. } => {
297                 if let &Some(lhs) = rhs {
298                     f(lhs);
299                 }
300                 if let &Some(rhs) = lhs {
301                     f(rhs);
302                 }
303             }
304             Expr::Index { base, index } => {
305                 f(*base);
306                 f(*index);
307             }
308             Expr::Field { expr, .. }
309             | Expr::Await { expr }
310             | Expr::Try { expr }
311             | Expr::Cast { expr, .. }
312             | Expr::Ref { expr, .. }
313             | Expr::UnaryOp { expr, .. }
314             | Expr::Box { expr } => {
315                 f(*expr);
316             }
317             Expr::Tuple { exprs } => exprs.iter().copied().for_each(f),
318             Expr::Array(a) => match a {
319                 Array::ElementList(exprs) => exprs.iter().copied().for_each(f),
320                 Array::Repeat { initializer, repeat } => {
321                     f(*initializer);
322                     f(*repeat)
323                 }
324             },
325             Expr::MacroStmts { tail } => f(*tail),
326             Expr::Literal(_) => {}
327         }
328     }
329 }
330
331 /// Explicit binding annotations given in the HIR for a binding. Note
332 /// that this is not the final binding *mode* that we infer after type
333 /// inference.
334 #[derive(Clone, PartialEq, Eq, Debug, Copy)]
335 pub enum BindingAnnotation {
336     /// No binding annotation given: this means that the final binding mode
337     /// will depend on whether we have skipped through a `&` reference
338     /// when matching. For example, the `x` in `Some(x)` will have binding
339     /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
340     /// ultimately be inferred to be by-reference.
341     Unannotated,
342
343     /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
344     Mutable,
345
346     /// Annotated as `ref`, like `ref x`
347     Ref,
348
349     /// Annotated as `ref mut x`.
350     RefMut,
351 }
352
353 impl BindingAnnotation {
354     pub fn new(is_mutable: bool, is_ref: bool) -> Self {
355         match (is_mutable, is_ref) {
356             (true, true) => BindingAnnotation::RefMut,
357             (false, true) => BindingAnnotation::Ref,
358             (true, false) => BindingAnnotation::Mutable,
359             (false, false) => BindingAnnotation::Unannotated,
360         }
361     }
362 }
363
364 #[derive(Debug, Clone, Eq, PartialEq)]
365 pub struct RecordFieldPat {
366     pub name: Name,
367     pub pat: PatId,
368 }
369
370 /// Close relative to rustc's hir::PatKind
371 #[derive(Debug, Clone, Eq, PartialEq)]
372 pub enum Pat {
373     Missing,
374     Wild,
375     Tuple { args: Box<[PatId]>, ellipsis: Option<usize> },
376     Or(Box<[PatId]>),
377     Record { path: Option<Box<Path>>, args: Box<[RecordFieldPat]>, ellipsis: bool },
378     Range { start: ExprId, end: ExprId },
379     Slice { prefix: Box<[PatId]>, slice: Option<PatId>, suffix: Box<[PatId]> },
380     Path(Box<Path>),
381     Lit(ExprId),
382     Bind { mode: BindingAnnotation, name: Name, subpat: Option<PatId> },
383     TupleStruct { path: Option<Box<Path>>, args: Box<[PatId]>, ellipsis: Option<usize> },
384     Ref { pat: PatId, mutability: Mutability },
385     Box { inner: PatId },
386     ConstBlock(ExprId),
387 }
388
389 impl Pat {
390     pub fn walk_child_pats(&self, mut f: impl FnMut(PatId)) {
391         match self {
392             Pat::Range { .. }
393             | Pat::Lit(..)
394             | Pat::Path(..)
395             | Pat::ConstBlock(..)
396             | Pat::Wild
397             | Pat::Missing => {}
398             Pat::Bind { subpat, .. } => {
399                 subpat.iter().copied().for_each(f);
400             }
401             Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => {
402                 args.iter().copied().for_each(f);
403             }
404             Pat::Ref { pat, .. } => f(*pat),
405             Pat::Slice { prefix, slice, suffix } => {
406                 let total_iter = prefix.iter().chain(slice.iter()).chain(suffix.iter());
407                 total_iter.copied().for_each(f);
408             }
409             Pat::Record { args, .. } => {
410                 args.iter().map(|f| f.pat).for_each(f);
411             }
412             Pat::Box { inner } => f(*inner),
413         }
414     }
415 }