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