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