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,
210 statements: Box<[Statement]>,
211 tail: Option<ExprId>,
218 #[derive(Debug, Clone, Eq, PartialEq)]
220 ElementList { elements: Box<[ExprId]>, is_assignee_expr: bool },
221 Repeat { initializer: ExprId, repeat: ExprId },
224 #[derive(Debug, Clone, Eq, PartialEq)]
225 pub struct MatchArm {
227 pub guard: Option<ExprId>,
231 #[derive(Debug, Clone, Eq, PartialEq)]
232 pub struct RecordLitField {
237 #[derive(Debug, Clone, Eq, PartialEq)]
241 type_ref: Option<Interned<TypeRef>>,
242 initializer: Option<ExprId>,
243 else_branch: Option<ExprId>,
252 pub fn walk_child_exprs(&self, mut f: impl FnMut(ExprId)) {
256 Expr::If { condition, then_branch, else_branch } => {
259 if let &Some(else_branch) = else_branch {
263 Expr::Let { expr, .. } => {
266 Expr::MacroStmts { tail, statements } | Expr::Block { statements, tail, .. } => {
267 for stmt in statements.iter() {
269 Statement::Let { initializer, .. } => {
270 if let &Some(expr) = initializer {
274 Statement::Expr { expr: expression, .. } => f(*expression),
277 if let &Some(expr) = tail {
281 Expr::TryBlock { body }
282 | Expr::Unsafe { body }
283 | Expr::Async { body }
284 | Expr::Const { body } => f(*body),
285 Expr::Loop { body, .. } => f(*body),
286 Expr::While { condition, body, .. } => {
290 Expr::For { iterable, body, .. } => {
294 Expr::Call { callee, args, .. } => {
296 args.iter().copied().for_each(f);
298 Expr::MethodCall { receiver, args, .. } => {
300 args.iter().copied().for_each(f);
302 Expr::Match { expr, arms } => {
304 arms.iter().map(|arm| arm.expr).for_each(f);
306 Expr::Continue { .. } => {}
307 Expr::Break { expr, .. } | Expr::Return { expr } | Expr::Yield { expr } => {
308 if let &Some(expr) = expr {
312 Expr::RecordLit { fields, spread, .. } => {
313 for field in fields.iter() {
316 if let &Some(expr) = spread {
320 Expr::Closure { body, .. } => {
323 Expr::BinaryOp { lhs, rhs, .. } => {
327 Expr::Range { lhs, rhs, .. } => {
328 if let &Some(lhs) = rhs {
331 if let &Some(rhs) = lhs {
335 Expr::Index { base, index } => {
339 Expr::Field { expr, .. }
340 | Expr::Await { expr }
342 | Expr::Cast { expr, .. }
343 | Expr::Ref { expr, .. }
344 | Expr::UnaryOp { expr, .. }
345 | Expr::Box { expr } => {
348 Expr::Tuple { exprs, .. } => exprs.iter().copied().for_each(f),
349 Expr::Array(a) => match a {
350 Array::ElementList { elements, .. } => elements.iter().copied().for_each(f),
351 Array::Repeat { initializer, repeat } => {
356 Expr::Literal(_) => {}
357 Expr::Underscore => {}
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
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.
374 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
377 /// Annotated as `ref`, like `ref x`
380 /// Annotated as `ref mut x`.
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,
395 #[derive(Debug, Clone, Eq, PartialEq)]
396 pub struct RecordFieldPat {
401 /// Close relative to rustc's hir::PatKind
402 #[derive(Debug, Clone, Eq, PartialEq)]
406 Tuple { args: Box<[PatId]>, ellipsis: Option<usize> },
408 Record { path: Option<Box<Path>>, args: Box<[RecordFieldPat]>, ellipsis: bool },
409 Range { start: ExprId, end: ExprId },
410 Slice { prefix: Box<[PatId]>, slice: Option<PatId>, suffix: Box<[PatId]> },
413 Bind { mode: BindingAnnotation, name: Name, subpat: Option<PatId> },
414 TupleStruct { path: Option<Box<Path>>, args: Box<[PatId]>, ellipsis: Option<usize> },
415 Ref { pat: PatId, mutability: Mutability },
416 Box { inner: PatId },
421 pub fn walk_child_pats(&self, mut f: impl FnMut(PatId)) {
426 | Pat::ConstBlock(..)
429 Pat::Bind { subpat, .. } => {
430 subpat.iter().copied().for_each(f);
432 Pat::Or(args) | Pat::Tuple { args, .. } | Pat::TupleStruct { args, .. } => {
433 args.iter().copied().for_each(f);
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);
440 Pat::Record { args, .. } => {
441 args.iter().map(|f| f.pat).for_each(f);
443 Pat::Box { inner } => f(*inner),