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