]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/expr.rs
Track labels in the HIR
[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 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     Cast {
124         expr: ExprId,
125         type_ref: TypeRef,
126     },
127     Ref {
128         expr: ExprId,
129         rawness: Rawness,
130         mutability: Mutability,
131     },
132     Box {
133         expr: ExprId,
134     },
135     UnaryOp {
136         expr: ExprId,
137         op: UnaryOp,
138     },
139     BinaryOp {
140         lhs: ExprId,
141         rhs: ExprId,
142         op: Option<BinaryOp>,
143     },
144     Range {
145         lhs: Option<ExprId>,
146         rhs: Option<ExprId>,
147         range_type: RangeOp,
148     },
149     Index {
150         base: ExprId,
151         index: ExprId,
152     },
153     Lambda {
154         args: Vec<PatId>,
155         arg_types: Vec<Option<TypeRef>>,
156         ret_type: Option<TypeRef>,
157         body: ExprId,
158     },
159     Tuple {
160         exprs: Vec<ExprId>,
161     },
162     Unsafe {
163         body: ExprId,
164     },
165     Array(Array),
166     Literal(Literal),
167 }
168
169 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
170 pub enum BinaryOp {
171     LogicOp(LogicOp),
172     ArithOp(ArithOp),
173     CmpOp(CmpOp),
174     Assignment { op: Option<ArithOp> },
175 }
176
177 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
178 pub enum LogicOp {
179     And,
180     Or,
181 }
182
183 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
184 pub enum CmpOp {
185     Eq { negated: bool },
186     Ord { ordering: Ordering, strict: bool },
187 }
188
189 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
190 pub enum Ordering {
191     Less,
192     Greater,
193 }
194
195 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
196 pub enum ArithOp {
197     Add,
198     Mul,
199     Sub,
200     Div,
201     Rem,
202     Shl,
203     Shr,
204     BitXor,
205     BitOr,
206     BitAnd,
207 }
208
209 pub use syntax::ast::PrefixOp as UnaryOp;
210 #[derive(Debug, Clone, Eq, PartialEq)]
211 pub enum Array {
212     ElementList(Vec<ExprId>),
213     Repeat { initializer: ExprId, repeat: ExprId },
214 }
215
216 #[derive(Debug, Clone, Eq, PartialEq)]
217 pub struct MatchArm {
218     pub pat: PatId,
219     pub guard: Option<ExprId>,
220     pub expr: ExprId,
221 }
222
223 #[derive(Debug, Clone, Eq, PartialEq)]
224 pub struct RecordLitField {
225     pub name: Name,
226     pub expr: ExprId,
227 }
228
229 #[derive(Debug, Clone, Eq, PartialEq)]
230 pub enum Statement {
231     Let { pat: PatId, type_ref: Option<TypeRef>, initializer: Option<ExprId> },
232     Expr(ExprId),
233 }
234
235 impl Expr {
236     pub fn walk_child_exprs(&self, mut f: impl FnMut(ExprId)) {
237         match self {
238             Expr::Missing => {}
239             Expr::Path(_) => {}
240             Expr::If { condition, then_branch, else_branch } => {
241                 f(*condition);
242                 f(*then_branch);
243                 if let Some(else_branch) = else_branch {
244                     f(*else_branch);
245                 }
246             }
247             Expr::Block { statements, tail, .. } => {
248                 for stmt in statements {
249                     match stmt {
250                         Statement::Let { initializer, .. } => {
251                             if let Some(expr) = initializer {
252                                 f(*expr);
253                             }
254                         }
255                         Statement::Expr(e) => f(*e),
256                     }
257                 }
258                 if let Some(expr) = tail {
259                     f(*expr);
260                 }
261             }
262             Expr::TryBlock { body } | Expr::Unsafe { body } | Expr::Async { 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 }
409
410 impl Pat {
411     pub fn walk_child_pats(&self, mut f: impl FnMut(PatId)) {
412         match self {
413             Pat::Range { .. } | Pat::Lit(..) | Pat::Path(..) | Pat::Wild | Pat::Missing => {}
414             Pat::Bind { subpat, .. } => {
415                 subpat.iter().copied().for_each(f);
416             }
417             Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => {
418                 args.iter().copied().for_each(f);
419             }
420             Pat::Ref { pat, .. } => f(*pat),
421             Pat::Slice { prefix, slice, suffix } => {
422                 let total_iter = prefix.iter().chain(slice.iter()).chain(suffix.iter());
423                 total_iter.copied().for_each(f);
424             }
425             Pat::Record { args, .. } => {
426                 args.iter().map(|f| f.pat).for_each(f);
427             }
428             Pat::Box { inner } => f(*inner),
429         }
430     }
431 }