Skip to main content

nu_protocol/ast/
operator.rs

1use super::{Expr, Expression};
2use crate::{ShellError, Span, Type};
3use serde::{Deserialize, Serialize};
4use std::fmt;
5use strum_macros::{EnumIter, EnumMessage};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
8pub enum Comparison {
9    #[strum(message = "Equal to")]
10    Equal,
11    #[strum(message = "Not equal to")]
12    NotEqual,
13    #[strum(message = "Less than")]
14    LessThan,
15    #[strum(message = "Greater than")]
16    GreaterThan,
17    #[strum(message = "Less than or equal to")]
18    LessThanOrEqual,
19    #[strum(message = "Greater than or equal to")]
20    GreaterThanOrEqual,
21    #[strum(message = "Contains regex match")]
22    RegexMatch,
23    #[strum(message = "Does not contain regex match")]
24    NotRegexMatch,
25    #[strum(message = "Is a member of (doesn't use regex)")]
26    In,
27    #[strum(message = "Is not a member of (doesn't use regex)")]
28    NotIn,
29    #[strum(message = "Contains a value of (doesn't use regex)")]
30    Has,
31    #[strum(message = "Does not contain a value of (doesn't use regex)")]
32    NotHas,
33    #[strum(message = "Starts with")]
34    StartsWith,
35    #[strum(message = "Does not start with")]
36    NotStartsWith,
37    #[strum(message = "Ends with")]
38    EndsWith,
39    #[strum(message = "Does not end with")]
40    NotEndsWith,
41    #[strum(message = "Is before now minus a duration, or before a datetime (same as <)")]
42    OlderThan,
43    #[strum(message = "Is after now minus a duration, or after a datetime (same as >)")]
44    NewerThan,
45}
46
47impl Comparison {
48    pub const fn as_str(&self) -> &'static str {
49        match self {
50            Self::Equal => "==",
51            Self::NotEqual => "!=",
52            Self::LessThan => "<",
53            Self::GreaterThan => ">",
54            Self::LessThanOrEqual => "<=",
55            Self::GreaterThanOrEqual => ">=",
56            Self::RegexMatch => "=~",
57            Self::NotRegexMatch => "!~",
58            Self::In => "in",
59            Self::NotIn => "not-in",
60            Self::Has => "has",
61            Self::NotHas => "not-has",
62            Self::StartsWith => "starts-with",
63            Self::NotStartsWith => "not-starts-with",
64            Self::EndsWith => "ends-with",
65            Self::NotEndsWith => "not-ends-with",
66            Self::OlderThan => "older-than",
67            Self::NewerThan => "newer-than",
68        }
69    }
70}
71
72impl AsRef<str> for Comparison {
73    fn as_ref(&self) -> &str {
74        self.as_str()
75    }
76}
77
78impl fmt::Display for Comparison {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.write_str(self.as_str())
81    }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
85pub enum Math {
86    #[strum(message = "Add (Plus)")]
87    Add,
88    #[strum(message = "Subtract (Minus)")]
89    Subtract,
90    #[strum(message = "Multiply")]
91    Multiply,
92    #[strum(message = "Divide")]
93    Divide,
94    #[strum(message = "Floor division")]
95    FloorDivide,
96    #[strum(message = "Floor division remainder (Modulo)")]
97    Modulo,
98    #[strum(message = "Power of")]
99    Pow,
100    #[strum(message = "Concatenates two lists, two strings, or two binary values")]
101    Concatenate,
102}
103
104impl Math {
105    pub const fn as_str(&self) -> &'static str {
106        match self {
107            Self::Add => "+",
108            Self::Subtract => "-",
109            Self::Multiply => "*",
110            Self::Divide => "/",
111            Self::FloorDivide => "//",
112            Self::Modulo => "mod",
113            Self::Pow => "**",
114            Self::Concatenate => "++",
115        }
116    }
117}
118
119impl AsRef<str> for Math {
120    fn as_ref(&self) -> &str {
121        self.as_str()
122    }
123}
124
125impl fmt::Display for Math {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.write_str(self.as_str())
128    }
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
132pub enum Boolean {
133    #[strum(message = "Logical OR (short-circuiting)")]
134    Or,
135    #[strum(message = "Logical XOR")]
136    Xor,
137    #[strum(message = "Logical AND (short-circuiting)")]
138    And,
139}
140
141impl Boolean {
142    pub const fn as_str(&self) -> &'static str {
143        match self {
144            Self::Or => "or",
145            Self::Xor => "xor",
146            Self::And => "and",
147        }
148    }
149}
150
151impl AsRef<str> for Boolean {
152    fn as_ref(&self) -> &str {
153        self.as_str()
154    }
155}
156
157impl fmt::Display for Boolean {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.write_str(self.as_str())
160    }
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
164pub enum Bits {
165    #[strum(message = "Bitwise OR")]
166    BitOr,
167    #[strum(message = "Bitwise exclusive OR")]
168    BitXor,
169    #[strum(message = "Bitwise AND")]
170    BitAnd,
171    #[strum(message = "Bitwise shift left")]
172    ShiftLeft,
173    #[strum(message = "Bitwise shift right")]
174    ShiftRight,
175}
176
177impl AsRef<str> for Bits {
178    fn as_ref(&self) -> &str {
179        self.as_str()
180    }
181}
182
183impl Bits {
184    pub const fn as_str(&self) -> &'static str {
185        match self {
186            Self::BitOr => "bit-or",
187            Self::BitXor => "bit-xor",
188            Self::BitAnd => "bit-and",
189            Self::ShiftLeft => "bit-shl",
190            Self::ShiftRight => "bit-shr",
191        }
192    }
193}
194
195impl fmt::Display for Bits {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        f.write_str(self.as_str())
198    }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
202pub enum Assignment {
203    #[strum(message = "Assigns a value to a variable.")]
204    Assign,
205    #[strum(message = "Adds a value to a variable.")]
206    AddAssign,
207    #[strum(message = "Subtracts a value from a variable.")]
208    SubtractAssign,
209    #[strum(message = "Multiplies a variable by a value")]
210    MultiplyAssign,
211    #[strum(message = "Divides a variable by a value.")]
212    DivideAssign,
213    #[strum(message = "Concatenates a variable with a list, string or binary.")]
214    ConcatenateAssign,
215}
216
217impl AsRef<str> for Assignment {
218    fn as_ref(&self) -> &str {
219        self.as_str()
220    }
221}
222
223impl Assignment {
224    pub const fn as_str(&self) -> &'static str {
225        match self {
226            Self::Assign => "=",
227            Self::AddAssign => "+=",
228            Self::SubtractAssign => "-=",
229            Self::MultiplyAssign => "*=",
230            Self::DivideAssign => "/=",
231            Self::ConcatenateAssign => "++=",
232        }
233    }
234}
235
236impl fmt::Display for Assignment {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        f.write_str(self.as_str())
239    }
240}
241
242#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
243pub enum Operator {
244    Comparison(Comparison),
245    Math(Math),
246    Boolean(Boolean),
247    Bits(Bits),
248    Assignment(Assignment),
249}
250
251/// Precedence of the prefix `not`: it binds looser than comparisons and bitwise operators and
252/// tighter than `and`, `xor` and `or`, so `not a == b` is `not (a == b)` and `not a and b` is
253/// `(not a) and b`. `not` is not an [`Operator`], since it takes one operand.
254pub const NOT_PRECEDENCE: u8 = 55;
255
256impl Operator {
257    pub const fn as_str(&self) -> &'static str {
258        match self {
259            Self::Comparison(comparison) => comparison.as_str(),
260            Self::Math(math) => math.as_str(),
261            Self::Boolean(boolean) => boolean.as_str(),
262            Self::Bits(bits) => bits.as_str(),
263            Self::Assignment(assignment) => assignment.as_str(),
264        }
265    }
266
267    pub const fn precedence(&self) -> u8 {
268        match self {
269            Self::Math(Math::Pow) => 100,
270            Self::Math(Math::Multiply)
271            | Self::Math(Math::Divide)
272            | Self::Math(Math::Modulo)
273            | Self::Math(Math::FloorDivide) => 95,
274            Self::Math(Math::Add) | Self::Math(Math::Subtract) => 90,
275            Self::Bits(Bits::ShiftLeft) | Self::Bits(Bits::ShiftRight) => 85,
276            Self::Comparison(Comparison::NotRegexMatch)
277            | Self::Comparison(Comparison::RegexMatch)
278            | Self::Comparison(Comparison::StartsWith)
279            | Self::Comparison(Comparison::NotStartsWith)
280            | Self::Comparison(Comparison::EndsWith)
281            | Self::Comparison(Comparison::NotEndsWith)
282            | Self::Comparison(Comparison::LessThan)
283            | Self::Comparison(Comparison::LessThanOrEqual)
284            | Self::Comparison(Comparison::GreaterThan)
285            | Self::Comparison(Comparison::GreaterThanOrEqual)
286            | Self::Comparison(Comparison::Equal)
287            | Self::Comparison(Comparison::NotEqual)
288            | Self::Comparison(Comparison::In)
289            | Self::Comparison(Comparison::NotIn)
290            | Self::Comparison(Comparison::Has)
291            | Self::Comparison(Comparison::NotHas)
292            | Self::Comparison(Comparison::OlderThan)
293            | Self::Comparison(Comparison::NewerThan)
294            | Self::Math(Math::Concatenate) => 80,
295            Self::Bits(Bits::BitAnd) => 75,
296            Self::Bits(Bits::BitXor) => 70,
297            Self::Bits(Bits::BitOr) => 60,
298            Self::Boolean(Boolean::And) => 50,
299            Self::Boolean(Boolean::Xor) => 45,
300            Self::Boolean(Boolean::Or) => 40,
301            Self::Assignment(_) => 10,
302        }
303    }
304
305    /// Help for an operator type error, for operand types where the usual mistake has a known fix.
306    ///
307    /// # Arguments
308    ///
309    /// * `lhs` - Type of the left operand
310    /// * `rhs` - Type of the right operand
311    ///
312    /// # Returns
313    ///
314    /// The help text, or `None` when there is nothing more specific to say than the error itself.
315    pub fn incompatible_types_help(&self, lhs: &Type, rhs: &Type) -> Option<&'static str> {
316        let Self::Comparison(comparison) = self else {
317            return None;
318        };
319        match (comparison, lhs, rhs) {
320            (Comparison::LessThan, Type::Date, Type::Duration) => Some(
321                "to check that a datetime is before now minus a duration, use `older-than`: `$date older-than 2wk`",
322            ),
323            (Comparison::GreaterThan, Type::Date, Type::Duration) => Some(
324                "to check that a datetime is after now minus a duration, use `newer-than`: `$date newer-than 2wk`",
325            ),
326            (Comparison::LessThanOrEqual, Type::Date, Type::Duration) => Some(
327                "subtract the duration from now: `$date <= (date now) - 2wk`, or use `older-than`, which is strict: `$date older-than 2wk`",
328            ),
329            (Comparison::GreaterThanOrEqual, Type::Date, Type::Duration) => Some(
330                "subtract the duration from now: `$date >= (date now) - 2wk`, or use `newer-than`, which is strict: `$date newer-than 2wk`",
331            ),
332            (
333                Comparison::LessThan
334                | Comparison::LessThanOrEqual
335                | Comparison::GreaterThan
336                | Comparison::GreaterThanOrEqual,
337                Type::Duration,
338                Type::Date,
339            ) => Some(
340                "put the datetime on the left and use `older-than` or `newer-than`: `$date older-than 2wk`",
341            ),
342            (Comparison::OlderThan, Type::Duration, _) => {
343                Some("the datetime goes on the left: `$date older-than 2wk`")
344            }
345            (Comparison::NewerThan, Type::Duration, _) => {
346                Some("the datetime goes on the left: `$date newer-than 2wk`")
347            }
348            _ => None,
349        }
350    }
351}
352
353impl fmt::Display for Operator {
354    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355        f.write_str(self.as_str())
356    }
357}
358
359#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, EnumIter)]
360pub enum RangeInclusion {
361    Inclusive,
362    RightExclusive,
363}
364
365#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
366pub struct RangeOperator {
367    pub inclusion: RangeInclusion,
368    pub span: Span,
369    pub next_op_span: Span,
370}
371
372impl fmt::Display for RangeOperator {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        match self.inclusion {
375            RangeInclusion::Inclusive => write!(f, ".."),
376            RangeInclusion::RightExclusive => write!(f, "..<"),
377        }
378    }
379}
380
381pub fn eval_operator(op: &Expression) -> Result<Operator, ShellError> {
382    match op {
383        Expression {
384            expr: Expr::Operator(operator),
385            ..
386        } => Ok(*operator),
387        Expression { span, expr, .. } => Err(ShellError::UnknownOperator {
388            op_token: format!("{expr:?}"),
389            span: *span,
390        }),
391    }
392}