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