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