Skip to main content

syntax/ast/
prec.rs

1//! Precedence representation.
2
3use stdx::always;
4
5use crate::{
6    AstNode, Direction, SyntaxNode, T,
7    algo::skip_trivia_token,
8    ast::{self, BinaryOp, Expr, HasArgList, RangeItem},
9    match_ast,
10};
11
12#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
13pub enum ExprPrecedence {
14    // return, break, continue, yield, yeet, become (with or without value)
15    Jump,
16    // = += -= *= /= %= &= |= ^= <<= >>=
17    Assign,
18    // .. ..=
19    Range,
20    // ||
21    LOr,
22    // &&
23    LAnd,
24    // == != < > <= >=
25    Compare,
26    // |
27    BitOr,
28    // ^
29    BitXor,
30    // &
31    BitAnd,
32    // << >>
33    Shift,
34    // + -
35    Sum,
36    // * / %
37    Product,
38    // as
39    Cast,
40    // unary - * ! & &mut
41    Prefix,
42    // function calls, array indexing, field expressions, method calls
43    Postfix,
44    // paths, loops,
45    Unambiguous,
46}
47
48impl ExprPrecedence {
49    pub fn needs_parentheses_in(self, other: ExprPrecedence) -> bool {
50        match other {
51            ExprPrecedence::Unambiguous => false,
52            // postfix ops have higher precedence than any other operator, so we need to wrap
53            // any inner expression that is below
54            ExprPrecedence::Postfix => self < ExprPrecedence::Postfix,
55            // We need to wrap all binary like things, thats everything below prefix except for
56            // jumps (as those are prefix operations as well)
57            ExprPrecedence::Prefix => ExprPrecedence::Jump < self && self < ExprPrecedence::Prefix,
58            parent => self <= parent,
59        }
60    }
61}
62
63#[derive(PartialEq, Debug)]
64pub enum Fixity {
65    /// The operator is left-associative
66    Left,
67    /// The operator is right-associative
68    Right,
69    /// The operator is not associative
70    None,
71}
72
73pub fn precedence(expr: &ast::Expr) -> ExprPrecedence {
74    match expr {
75        Expr::ClosureExpr(closure) => match closure.ret_type() {
76            None => ExprPrecedence::Jump,
77            Some(_) => ExprPrecedence::Unambiguous,
78        },
79
80        Expr::BreakExpr(_)
81        | Expr::BecomeExpr(_)
82        | Expr::ReturnExpr(_)
83        | Expr::YeetExpr(_)
84        | Expr::YieldExpr(_)
85        | Expr::ContinueExpr(_) => ExprPrecedence::Jump,
86
87        Expr::RangeExpr(..) => ExprPrecedence::Range,
88
89        Expr::BinExpr(bin_expr) => match bin_expr.op_kind() {
90            Some(it) => match it {
91                BinaryOp::LogicOp(logic_op) => match logic_op {
92                    ast::LogicOp::And => ExprPrecedence::LAnd,
93                    ast::LogicOp::Or => ExprPrecedence::LOr,
94                },
95                BinaryOp::ArithOp(arith_op) => match arith_op {
96                    ast::ArithOp::Add | ast::ArithOp::Sub => ExprPrecedence::Sum,
97                    ast::ArithOp::Div | ast::ArithOp::Rem | ast::ArithOp::Mul => {
98                        ExprPrecedence::Product
99                    }
100                    ast::ArithOp::Shl | ast::ArithOp::Shr => ExprPrecedence::Shift,
101                    ast::ArithOp::BitXor => ExprPrecedence::BitXor,
102                    ast::ArithOp::BitOr => ExprPrecedence::BitOr,
103                    ast::ArithOp::BitAnd => ExprPrecedence::BitAnd,
104                },
105                BinaryOp::CmpOp(_) => ExprPrecedence::Compare,
106                BinaryOp::Assignment { .. } => ExprPrecedence::Assign,
107            },
108            None => ExprPrecedence::Unambiguous,
109        },
110        Expr::CastExpr(_) => ExprPrecedence::Cast,
111
112        Expr::LetExpr(_) | Expr::PrefixExpr(_) | Expr::RefExpr(_) => ExprPrecedence::Prefix,
113
114        Expr::AwaitExpr(_)
115        | Expr::CallExpr(_)
116        | Expr::FieldExpr(_)
117        | Expr::IndexExpr(_)
118        | Expr::MethodCallExpr(_)
119        | Expr::TryExpr(_) => ExprPrecedence::Postfix,
120
121        Expr::ArrayExpr(_)
122        | Expr::AsmExpr(_)
123        | Expr::BlockExpr(_)
124        | Expr::ForExpr(_)
125        | Expr::FormatArgsExpr(_)
126        | Expr::IfExpr(_)
127        | Expr::Literal(_)
128        | Expr::LoopExpr(_)
129        | Expr::MacroExpr(_)
130        | Expr::MatchExpr(_)
131        | Expr::OffsetOfExpr(_)
132        | Expr::ParenExpr(_)
133        | Expr::PathExpr(_)
134        | Expr::RecordExpr(_)
135        | Expr::TupleExpr(_)
136        | Expr::UnderscoreExpr(_)
137        | Expr::WhileExpr(_)
138        | Expr::IncludeBytesExpr(_)
139        | Expr::CfgPredExpr(_) => ExprPrecedence::Unambiguous,
140    }
141}
142
143fn check_ancestry(ancestor: &SyntaxNode, descendent: &SyntaxNode) -> bool {
144    let bail = || always!(false, "{} is not an ancestor of {}", ancestor, descendent);
145
146    if !ancestor.text_range().contains_range(descendent.text_range()) {
147        return bail();
148    }
149
150    for anc in descendent.ancestors() {
151        if anc == *ancestor {
152            return true;
153        }
154    }
155
156    bail()
157}
158
159fn next_token_of(node: &SyntaxNode) -> Option<ast::SyntaxToken> {
160    let last = node.last_token()?;
161    skip_trivia_token(last.next_token()?, Direction::Next)
162}
163
164impl Expr {
165    pub fn precedence(&self) -> ExprPrecedence {
166        precedence(self)
167    }
168
169    // Implementation is based on
170    // - https://doc.rust-lang.org/reference/expressions.html#expression-precedence
171    // - https://matklad.github.io/2020/04/13/simple-but-powerful-pratt-parsing.html
172    // - rustc source, including, but not limited to
173    //   - https://github.com/rust-lang/rust/blob/b6852428a8ea9728369b64b9964cad8e258403d3/compiler/rustc_ast/src/util/parser.rs#L296
174
175    /// Returns `true` if `self` would need to be wrapped in parentheses given that its parent is `parent`.
176    pub fn needs_parens_in(&self, parent: &SyntaxNode) -> bool {
177        self.needs_parens_in_place_of(parent, self.syntax())
178    }
179
180    /// Returns `true` if `self` would need to be wrapped in parentheses if it replaces `place_of`
181    /// given that `place_of`'s parent is `parent`.
182    pub fn needs_parens_in_place_of(&self, parent: &SyntaxNode, place_of: &SyntaxNode) -> bool {
183        if !check_ancestry(parent, place_of) {
184            return false;
185        }
186
187        match_ast! {
188            match parent {
189                ast::Expr(e) => self.needs_parens_in_expr(&e, place_of),
190                ast::Stmt(e) => self.needs_parens_in_stmt(Some(&e)),
191                ast::StmtList(_) => self.needs_parens_in_stmt(None),
192                ast::ArgList(_) => false,
193                ast::MatchArm(_) => false,
194                _ => false,
195            }
196        }
197    }
198
199    fn needs_parens_in_expr(&self, parent: &Expr, place_of: &SyntaxNode) -> bool {
200        // Parentheses are necessary when calling a function-like pointer that is a member of a struct or union
201        // (e.g. `(a.f)()`).
202        let is_parent_call_expr = matches!(parent, ast::Expr::CallExpr(_));
203        let is_field_expr = matches!(self, ast::Expr::FieldExpr(_));
204        if is_parent_call_expr && is_field_expr {
205            return true;
206        }
207        let place_of_parent =
208            || place_of.ancestors().find(|it| it.parent().is_none_or(|p| &p == parent.syntax()));
209
210        // Special-case block weirdness
211        if parent.child_is_followed_by_a_block() {
212            use Expr::*;
213            match self {
214                // Cases like `if return {}` (need parens or else `{}` is returned, instead of being `if`'s body)
215                ReturnExpr(e) if e.expr().is_none() => return true,
216                BreakExpr(e) if e.expr().is_none() => return true,
217                YieldExpr(e) if e.expr().is_none() => return true,
218
219                // Same but with `..{}`
220                RangeExpr(e) if matches!(e.end(), Some(BlockExpr(..))) => return true,
221
222                // Similarly with struct literals, e.g. `if S{} == 1 {}`
223                _ if self.contains_exterior_struct_lit() => return true,
224                _ => {}
225            }
226        }
227
228        // Special-case `return.f()`
229        if self.is_ret_like_with_no_value() && parent.is_postfix() {
230            return false;
231        }
232
233        // Keep parens when a ret-like expr is followed by `||` or `&&`.
234        // For `||`, removing parens could reparse as `<ret-like> || <closure>`.
235        // For `&&`, we avoid introducing `<ret-like> && <expr>` into a binary chain.
236
237        if self.precedence() == ExprPrecedence::Jump
238            && let Some(node) = place_of_parent()
239            && let Some(next) = next_token_of(&node)
240            && matches!(next.kind(), T![||] | T![&&])
241        {
242            return true;
243        }
244
245        // Special-case `2 as x < 3`
246        if let Some(it) = self.right_side_cast_expr()
247            && let Some(ty) = it.ty()
248            && ty.syntax().last_token().and_then(|it| ast::NameLike::cast(it.parent()?)).is_some()
249            && let Some(node) = place_of_parent()
250            && let Some(next) = next_token_of(&node)
251            && matches!(next.kind(), T![<] | T![<<])
252        {
253            return true;
254        }
255
256        if self.is_paren_like()
257            || parent.is_paren_like()
258            || self.is_prefix()
259                && (parent.is_prefix()
260                    || !self.is_ordered_before_parent_in_place_of(parent, place_of))
261            || self.is_postfix()
262                && (parent.is_postfix()
263                    || self.is_ordered_before_parent_in_place_of(parent, place_of))
264        {
265            return false;
266        }
267
268        // Special-case `cond && <let-chain>`
269        if let ast::Expr::BinExpr(parent) = parent
270            && parent.op_kind() == Some(ast::BinaryOp::LogicOp(ast::LogicOp::And))
271            && self.contains_let_expr()
272        {
273            return false;
274        }
275
276        let (left, right, inv) = match self.is_ordered_before_parent_in_place_of(parent, place_of) {
277            true => (self, parent, false),
278            false => (parent, self, true),
279        };
280
281        let (_, left_right_bp) = left.binding_power();
282        let (right_left_bp, _) = right.binding_power();
283
284        (left_right_bp < right_left_bp) ^ inv
285    }
286
287    fn needs_parens_in_stmt(&self, stmt: Option<&ast::Stmt>) -> bool {
288        use Expr::*;
289
290        // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`,
291        // `{ { 0 } + 1 }` won't parse -- `{ 0 }` would be parsed as a self-contained stmt,
292        // leaving `+ 1` as a parse error.
293        let mut innermost = self.clone();
294        loop {
295            let next = match &innermost {
296                BinExpr(e) => e.lhs(),
297                CallExpr(e) => e.expr(),
298                CastExpr(e) => e.expr(),
299                IndexExpr(e) => e.base(),
300                _ => break,
301            };
302
303            if let Some(next) = next {
304                innermost = next;
305                if !innermost.requires_semi_to_be_stmt() {
306                    return true;
307                }
308            } else {
309                break;
310            }
311        }
312
313        // Not every expression can be followed by `else` in the `let-else`
314        if let Some(ast::Stmt::LetStmt(e)) = stmt
315            && e.let_else().is_some()
316        {
317            match self {
318                BinExpr(e)
319                    if e.op_kind()
320                        .map(|op| matches!(op, BinaryOp::LogicOp(_)))
321                        .unwrap_or(false) =>
322                {
323                    return true;
324                }
325                _ if self.clone().trailing_brace().is_some() => return true,
326                _ => {}
327            }
328        }
329
330        false
331    }
332
333    /// Returns left and right so-called "binding powers" of this expression.
334    fn binding_power(&self) -> (u8, u8) {
335        use ast::{ArithOp::*, BinaryOp::*, Expr::*, LogicOp::*};
336
337        match self {
338            // (0, 0)   -- paren-like/nullary
339            // (0, N)   -- prefix
340            // (N, 0)   -- postfix
341            // (N, N)   -- infix, requires parens
342            // (N, N+1) -- infix, left to right associative
343            // (N+1, N) -- infix, right to left associative
344            // N is odd
345            //
346            ContinueExpr(_) => (0, 0),
347
348            ClosureExpr(_) | ReturnExpr(_) | BecomeExpr(_) | YieldExpr(_) | YeetExpr(_)
349            | BreakExpr(_) | OffsetOfExpr(_) | FormatArgsExpr(_) | AsmExpr(_) => (0, 1),
350
351            RangeExpr(_) => (5, 5),
352
353            BinExpr(e) => {
354                // Return a dummy value if we don't know the op
355                let Some(op) = e.op_kind() else { return (0, 0) };
356                match op {
357                    Assignment { .. } => (4, 3),
358                    //
359                    // Ranges are here in order :)
360                    //
361                    LogicOp(op) => match op {
362                        Or => (7, 8),
363                        And => (9, 10),
364                    },
365                    CmpOp(_) => (11, 11),
366                    ArithOp(op) => match op {
367                        BitOr => (13, 14),
368                        BitXor => (15, 16),
369                        BitAnd => (17, 18),
370                        Shl | Shr => (19, 20),
371                        Add | Sub => (21, 22),
372                        Mul | Div | Rem => (23, 24),
373                    },
374                }
375            }
376
377            CastExpr(_) => (25, 26),
378
379            RefExpr(_) | LetExpr(_) | PrefixExpr(_) => (0, 27),
380
381            AwaitExpr(_) | CallExpr(_) | MethodCallExpr(_) | IndexExpr(_) | TryExpr(_)
382            | MacroExpr(_) => (29, 0),
383
384            FieldExpr(_) => (31, 32),
385
386            ArrayExpr(_) | TupleExpr(_) | Literal(_) | PathExpr(_) | ParenExpr(_) | IfExpr(_)
387            | WhileExpr(_) | ForExpr(_) | LoopExpr(_) | MatchExpr(_) | BlockExpr(_)
388            | RecordExpr(_) | UnderscoreExpr(_) | IncludeBytesExpr(_) | CfgPredExpr(_) => (0, 0),
389        }
390    }
391
392    fn is_paren_like(&self) -> bool {
393        matches!(self.binding_power(), (0, 0))
394    }
395
396    fn is_prefix(&self) -> bool {
397        matches!(self.binding_power(), (0, 1..))
398    }
399
400    fn is_postfix(&self) -> bool {
401        matches!(self.binding_power(), (1.., 0))
402    }
403
404    /// Returns `true` if this expression can't be a standalone statement.
405    fn requires_semi_to_be_stmt(&self) -> bool {
406        use Expr::*;
407        !matches!(
408            self,
409            IfExpr(..) | MatchExpr(..) | BlockExpr(..) | WhileExpr(..) | LoopExpr(..) | ForExpr(..)
410        )
411    }
412
413    /// If an expression ends with `}`, returns the innermost expression ending in this `}`.
414    fn trailing_brace(mut self) -> Option<Expr> {
415        use Expr::*;
416
417        loop {
418            let rhs = match self {
419                RefExpr(e) => e.expr(),
420                BinExpr(e) => e.rhs(),
421                BreakExpr(e) => e.expr(),
422                LetExpr(e) => e.expr(),
423                RangeExpr(e) => e.end(),
424                ReturnExpr(e) => e.expr(),
425                PrefixExpr(e) => e.expr(),
426                YieldExpr(e) => e.expr(),
427                ClosureExpr(e) => e.body(),
428
429                BlockExpr(..) | ForExpr(..) | IfExpr(..) | LoopExpr(..) | MatchExpr(..)
430                | RecordExpr(..) | WhileExpr(..) => break Some(self),
431                _ => break None,
432            };
433
434            self = rhs?;
435        }
436    }
437
438    /// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any
439    /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
440    /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
441    fn contains_exterior_struct_lit(&self) -> bool {
442        return contains_exterior_struct_lit_inner(self).is_some();
443
444        fn contains_exterior_struct_lit_inner(expr: &Expr) -> Option<()> {
445            use Expr::*;
446
447            match expr {
448                RecordExpr(..) => Some(()),
449
450                // X { y: 1 } + X { y: 2 }
451                BinExpr(e) => e
452                    .lhs()
453                    .as_ref()
454                    .and_then(contains_exterior_struct_lit_inner)
455                    .or_else(|| e.rhs().as_ref().and_then(contains_exterior_struct_lit_inner)),
456
457                // `&X { y: 1 }`, `X { y: 1 }.y`, `X { y: 1 }.bar(...)`, etc
458                IndexExpr(e) => contains_exterior_struct_lit_inner(&e.base()?),
459                AwaitExpr(e) => contains_exterior_struct_lit_inner(&e.expr()?),
460                PrefixExpr(e) => contains_exterior_struct_lit_inner(&e.expr()?),
461                CastExpr(e) => contains_exterior_struct_lit_inner(&e.expr()?),
462                FieldExpr(e) => contains_exterior_struct_lit_inner(&e.expr()?),
463                MethodCallExpr(e) => contains_exterior_struct_lit_inner(&e.receiver()?),
464
465                _ => None,
466            }
467        }
468    }
469
470    /// Returns true if self is one of `return`, `break`, `continue` or `yield` with **no associated value**.
471    pub fn is_ret_like_with_no_value(&self) -> bool {
472        use Expr::*;
473
474        match self {
475            ReturnExpr(e) => e.expr().is_none(),
476            BreakExpr(e) => e.expr().is_none(),
477            ContinueExpr(_) => true,
478            YieldExpr(e) => e.expr().is_none(),
479            BecomeExpr(e) => e.expr().is_none(),
480            _ => false,
481        }
482    }
483
484    fn is_ordered_before_parent_in_place_of(&self, parent: &Expr, place_of: &SyntaxNode) -> bool {
485        use Expr::*;
486        use rowan::TextSize;
487
488        let self_range = self.syntax().text_range();
489        let place_of_range = place_of.text_range();
490
491        let self_order_adjusted = order(self) - self_range.start() + place_of_range.start();
492
493        let parent_order = order(parent);
494        let parent_order_adjusted = if parent_order <= place_of_range.start() {
495            parent_order
496        } else if parent_order >= place_of_range.end() {
497            parent_order - place_of_range.len() + self_range.len()
498        } else {
499            return false;
500        };
501
502        return self_order_adjusted < parent_order_adjusted;
503
504        /// Returns text range that can be used to compare two expression for order (which goes first).
505        fn order(this: &Expr) -> TextSize {
506            // For non-paren-like operators: get the operator itself
507            let token = match this {
508                RangeExpr(e) => e.op_token(),
509                BinExpr(e) => e.op_token(),
510                CastExpr(e) => e.as_token(),
511                FieldExpr(e) => e.dot_token(),
512                AwaitExpr(e) => e.dot_token(),
513                BreakExpr(e) => e.break_token(),
514                CallExpr(e) => e.arg_list().and_then(|args| args.l_paren_token()),
515                ClosureExpr(e) => e.param_list().and_then(|params| params.l_paren_token()),
516                ContinueExpr(e) => e.continue_token(),
517                IndexExpr(e) => e.l_brack_token(),
518                MethodCallExpr(e) => e.dot_token(),
519                PrefixExpr(e) => e.op_token(),
520                RefExpr(e) => e.amp_token(),
521                ReturnExpr(e) => e.return_token(),
522                BecomeExpr(e) => e.become_token(),
523                TryExpr(e) => e.question_mark_token(),
524                YieldExpr(e) => e.yield_token(),
525                YeetExpr(e) => e.do_token(),
526                LetExpr(e) => e.let_token(),
527                OffsetOfExpr(e) => e.offset_of_token(),
528                FormatArgsExpr(e) => e.format_args_token(),
529                AsmExpr(e) => {
530                    e.asm_token().or_else(|| e.global_asm_token()).or_else(|| e.naked_asm_token())
531                }
532                ArrayExpr(_) | TupleExpr(_) | Literal(_) | PathExpr(_) | ParenExpr(_)
533                | IfExpr(_) | WhileExpr(_) | ForExpr(_) | LoopExpr(_) | MatchExpr(_)
534                | BlockExpr(_) | RecordExpr(_) | UnderscoreExpr(_) | MacroExpr(_)
535                | IncludeBytesExpr(_) | CfgPredExpr(_) => None,
536            };
537
538            token.map(|t| t.text_range()).unwrap_or_else(|| this.syntax().text_range()).start()
539        }
540    }
541
542    fn child_is_followed_by_a_block(&self) -> bool {
543        use Expr::*;
544
545        match self {
546            ArrayExpr(_) | AwaitExpr(_) | BlockExpr(_) | CallExpr(_) | CastExpr(_)
547            | ClosureExpr(_) | FieldExpr(_) | IndexExpr(_) | Literal(_) | LoopExpr(_)
548            | MacroExpr(_) | MethodCallExpr(_) | ParenExpr(_) | PathExpr(_) | RecordExpr(_)
549            | TryExpr(_) | TupleExpr(_) | UnderscoreExpr(_) | OffsetOfExpr(_)
550            | FormatArgsExpr(_) | AsmExpr(_) | CfgPredExpr(_) => false,
551
552            // For BinExpr and RangeExpr this is technically wrong -- the child can be on the left...
553            BinExpr(_) | RangeExpr(_) | BreakExpr(_) | ContinueExpr(_) | PrefixExpr(_)
554            | RefExpr(_) | ReturnExpr(_) | BecomeExpr(_) | YieldExpr(_) | YeetExpr(_)
555            | LetExpr(_) => self
556                .syntax()
557                .parent()
558                .and_then(Expr::cast)
559                .map(|e| e.child_is_followed_by_a_block())
560                .unwrap_or(false),
561
562            ForExpr(_) | IfExpr(_) | MatchExpr(_) | WhileExpr(_) | IncludeBytesExpr(_) => true,
563        }
564    }
565
566    fn contains_let_expr(&self) -> bool {
567        use Expr::*;
568
569        match self {
570            LetExpr(_) => true,
571            BinExpr(e) => {
572                // if we find something other than a `&&`, then this can't be a let chain
573                e.op_kind() == Some(ast::BinaryOp::LogicOp(ast::LogicOp::And))
574                    && (e.lhs().is_none_or(|it| it.contains_let_expr())
575                        || e.rhs().is_none_or(|it| it.contains_let_expr()))
576            }
577            _ => false,
578        }
579    }
580
581    fn right_side_cast_expr(&self) -> Option<ast::CastExpr> {
582        std::iter::successors(Some(self.syntax().clone()), |it| {
583            it.last_child_or_token()?.into_node()
584        })
585        .find_map(ast::CastExpr::cast)
586    }
587}
588
589impl ast::Type {
590    pub fn needs_parens_in(&self, parent: &SyntaxNode) -> bool {
591        if !matches!(self, ast::Type::DynTraitType(_) | ast::Type::ImplTraitType(_)) {
592            return false;
593        }
594        let kind = parent.kind();
595        ast::CastExpr::can_cast(kind)
596            || ast::RefType::can_cast(kind)
597            || ast::PtrType::can_cast(kind)
598    }
599}