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