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