compose_syntax/ast/
unary.rs

1use crate::ast::expr::Expr;
2use crate::ast::macros::node;
3use crate::kind::SyntaxKind;
4use crate::precedence::{Precedence, PrecedenceTrait};
5
6node! {
7    struct Unary
8}
9
10impl<'a> Unary<'a> {
11    pub fn op(self) -> UnOp {
12        self.0
13            .children()
14            .find_map(|node| UnOp::from_kind(node.kind()))
15            .unwrap_or(UnOp::Plus)
16    }
17
18    pub fn expr(self) -> Expr<'a> { self.0.cast_last() }
19}
20
21#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
22pub enum UnOp {
23    Plus,
24    Minus,
25    Bang,
26    Tilde,
27    Star,
28}
29
30impl UnOp {
31    pub fn from_kind(kind: SyntaxKind) -> Option<Self> {
32        Some(match kind {
33            SyntaxKind::Plus => Self::Plus,
34            SyntaxKind::Minus => Self::Minus,
35            SyntaxKind::Bang => Self::Bang,
36            SyntaxKind::Tilde => Self::Tilde,
37            SyntaxKind::Star => Self::Star,
38            _ => return None,
39        })
40    }
41
42    pub fn as_str(self) -> &'static str {
43        match self {
44            Self::Plus => "+",
45            Self::Minus => "-",
46            Self::Bang => "!",
47            Self::Tilde => "~",
48            Self::Star => "*",
49        }
50    }
51}
52
53impl PrecedenceTrait for UnOp {
54    fn precedence(&self) -> Precedence {
55        match self {
56            Self::Plus | Self::Minus => Precedence::Sum,
57            Self::Bang | Self::Tilde => Precedence::Prefix,
58            Self::Star => Precedence::Prefix,
59        }
60    }
61}
62