]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/expr.rs
6534f970ee6b860f245fa89f6073f921ab07adf4
[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     Block {
63         id: BlockId,
64         statements: Box<[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: Box<[ExprId]>,
86     },
87     MethodCall {
88         receiver: ExprId,
89         method_name: Name,
90         args: Box<[ExprId]>,
91         generic_args: Option<Box<GenericArgs>>,
92     },
93     Match {
94         expr: ExprId,
95         arms: Box<[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: Box<[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: Box<[PatId]>,
166         arg_types: Box<[Option<Interned<TypeRef>>]>,
167         ret_type: Option<Interned<TypeRef>>,
168         body: ExprId,
169     },
170     Tuple {
171         exprs: Box<[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(Box<[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.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 }