1 //! This module describes hir-level representation of expressions.
3 //! This representation is:
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
11 //! 4. Desugared. There's no `if let`.
13 //! See also a neighboring `body` module.
17 use hir_expand::name::Name;
18 use la_arena::{Idx, RawIdx};
21 builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
23 path::{GenericArgs, Path},
24 type_ref::{Mutability, Rawness, TypeRef},
28 pub use syntax::ast::{ArithOp, BinaryOp, CmpOp, LogicOp, Ordering, RangeOp, UnaryOp};
30 pub type ExprId = Idx<Expr>;
32 /// FIXME: this is a hacky function which should be removed
33 pub(crate) fn dummy_expr_id() -> ExprId {
34 ExprId::from_raw(RawIdx::from(u32::MAX))
37 pub type PatId = Idx<Pat>;
39 #[derive(Debug, Clone, Eq, PartialEq)]
43 pub type LabelId = Idx<Label>;
45 // We convert float values into bits and that's how we don't need to deal with f32 and f64.
46 // For PartialEq, bits comparison should work, as ordering is not important
47 // https://github.com/rust-lang/rust-analyzer/issues/12380#issuecomment-1137284360
48 #[derive(Default, Debug, Clone, Eq, PartialEq)]
49 pub struct FloatTypeWrapper(u64);
51 impl FloatTypeWrapper {
52 pub fn new(value: f64) -> Self {
57 impl fmt::Display for FloatTypeWrapper {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 write!(f, "{:?}", f64::from_bits(self.0))
63 #[derive(Debug, Clone, Eq, PartialEq)]
66 ByteString(Box<[u8]>),
69 Int(i128, Option<BuiltinInt>),
70 Uint(u128, Option<BuiltinUint>),
71 // Here we are using a wrapper around float because f32 and f64 do not implement Eq, so they
72 // could not be used directly here, to understand how the wrapper works go to definition of
74 Float(FloatTypeWrapper, Option<BuiltinFloat>),
77 #[derive(Debug, Clone, Eq, PartialEq)]
79 /// This is produced if the syntax tree does not have a required expression piece.
85 else_branch: Option<ExprId>,
93 statements: Box<[Statement]>,
95 label: Option<LabelId>,
99 label: Option<LabelId>,
104 label: Option<LabelId>,
110 label: Option<LabelId>,
115 is_assignee_expr: bool,
121 generic_args: Option<Box<GenericArgs>>,
125 arms: Box<[MatchArm]>,
131 expr: Option<ExprId>,
135 expr: Option<ExprId>,
138 expr: Option<ExprId>,
141 path: Option<Box<Path>>,
142 fields: Box<[RecordLitField]>,
143 spread: Option<ExprId>,
145 is_assignee_expr: bool,
168 type_ref: Interned<TypeRef>,
173 mutability: Mutability,
185 op: Option<BinaryOp>,
198 arg_types: Box<[Option<Interned<TypeRef>>]>,
199 ret_type: Option<Interned<TypeRef>>,
203 exprs: Box<[ExprId]>,
204 is_assignee_expr: bool,
214 #[derive(Debug, Clone, Eq, PartialEq)]
216 ElementList { elements: Box<[ExprId]>, is_assignee_expr: bool },
217 Repeat { initializer: ExprId, repeat: ExprId },
220 #[derive(Debug, Clone, Eq, PartialEq)]
221 pub struct MatchArm {
223 pub guard: Option<ExprId>,
227 #[derive(Debug, Clone, Eq, PartialEq)]
228 pub struct RecordLitField {
233 #[derive(Debug, Clone, Eq, PartialEq)]
237 type_ref: Option<Interned<TypeRef>>,
238 initializer: Option<ExprId>,
239 else_branch: Option<ExprId>,
248 pub fn walk_child_exprs(&self, mut f: impl FnMut(ExprId)) {
252 Expr::If { condition, then_branch, else_branch } => {
255 if let &Some(else_branch) = else_branch {
259 Expr::Let { expr, .. } => {
262 Expr::Block { statements, tail, .. } => {
263 for stmt in statements.iter() {
265 Statement::Let { initializer, .. } => {
266 if let &Some(expr) = initializer {
270 Statement::Expr { expr: expression, .. } => f(*expression),
273 if let &Some(expr) = tail {
277 Expr::TryBlock { body }
278 | Expr::Unsafe { body }
279 | Expr::Async { body }
280 | Expr::Const { body } => f(*body),
281 Expr::Loop { body, .. } => f(*body),
282 Expr::While { condition, body, .. } => {
286 Expr::For { iterable, body, .. } => {
290 Expr::Call { callee, args, .. } => {
292 args.iter().copied().for_each(f);
294 Expr::MethodCall { receiver, args, .. } => {
296 args.iter().copied().for_each(f);
298 Expr::Match { expr, arms } => {
300 arms.iter().map(|arm| arm.expr).for_each(f);
302 Expr::Continue { .. } => {}
303 Expr::Break { expr, .. } | Expr::Return { expr } | Expr::Yield { expr } => {
304 if let &Some(expr) = expr {
308 Expr::RecordLit { fields, spread, .. } => {
309 for field in fields.iter() {
312 if let &Some(expr) = spread {
316 Expr::Closure { body, .. } => {
319 Expr::BinaryOp { lhs, rhs, .. } => {
323 Expr::Range { lhs, rhs, .. } => {
324 if let &Some(lhs) = rhs {
327 if let &Some(rhs) = lhs {
331 Expr::Index { base, index } => {
335 Expr::Field { expr, .. }
336 | Expr::Await { expr }
338 | Expr::Cast { expr, .. }
339 | Expr::Ref { expr, .. }
340 | Expr::UnaryOp { expr, .. }
341 | Expr::Box { expr } => {
344 Expr::Tuple { exprs, .. } => exprs.iter().copied().for_each(f),
345 Expr::Array(a) => match a {
346 Array::ElementList { elements, .. } => elements.iter().copied().for_each(f),
347 Array::Repeat { initializer, repeat } => {
352 Expr::Literal(_) => {}
353 Expr::Underscore => {}
358 /// Explicit binding annotations given in the HIR for a binding. Note
359 /// that this is not the final binding *mode* that we infer after type
361 #[derive(Clone, PartialEq, Eq, Debug, Copy)]
362 pub enum BindingAnnotation {
363 /// No binding annotation given: this means that the final binding mode
364 /// will depend on whether we have skipped through a `&` reference
365 /// when matching. For example, the `x` in `Some(x)` will have binding
366 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
367 /// ultimately be inferred to be by-reference.
370 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
373 /// Annotated as `ref`, like `ref x`
376 /// Annotated as `ref mut x`.
380 impl BindingAnnotation {
381 pub fn new(is_mutable: bool, is_ref: bool) -> Self {
382 match (is_mutable, is_ref) {
383 (true, true) => BindingAnnotation::RefMut,
384 (false, true) => BindingAnnotation::Ref,
385 (true, false) => BindingAnnotation::Mutable,
386 (false, false) => BindingAnnotation::Unannotated,
391 #[derive(Debug, Clone, Eq, PartialEq)]
392 pub struct RecordFieldPat {
397 /// Close relative to rustc's hir::PatKind
398 #[derive(Debug, Clone, Eq, PartialEq)]
402 Tuple { args: Box<[PatId]>, ellipsis: Option<usize> },
404 Record { path: Option<Box<Path>>, args: Box<[RecordFieldPat]>, ellipsis: bool },
405 Range { start: ExprId, end: ExprId },
406 Slice { prefix: Box<[PatId]>, slice: Option<PatId>, suffix: Box<[PatId]> },
409 Bind { mode: BindingAnnotation, name: Name, subpat: Option<PatId> },
410 TupleStruct { path: Option<Box<Path>>, args: Box<[PatId]>, ellipsis: Option<usize> },
411 Ref { pat: PatId, mutability: Mutability },
412 Box { inner: PatId },
417 pub fn walk_child_pats(&self, mut f: impl FnMut(PatId)) {
422 | Pat::ConstBlock(..)
425 Pat::Bind { subpat, .. } => {
426 subpat.iter().copied().for_each(f);
428 Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => {
429 args.iter().copied().for_each(f);
431 Pat::Ref { pat, .. } => f(*pat),
432 Pat::Slice { prefix, slice, suffix } => {
433 let total_iter = prefix.iter().chain(slice.iter()).chain(suffix.iter());
434 total_iter.copied().for_each(f);
436 Pat::Record { args, .. } => {
437 args.iter().map(|f| f.pat).for_each(f);
439 Pat::Box { inner } => f(*inner),