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