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