Skip to main content

nu_protocol/ast/
expr.rs

1use chrono::FixedOffset;
2use serde::{Deserialize, Serialize};
3
4use super::{
5    AttributeBlock, Call, CellPath, Expression, ExternalArgument, FullCellPath, Keyword,
6    MatchPattern, Operator, Range, Table, ValueWithUnit,
7};
8use crate::{
9    BlockId, ModuleId, OutDest, Signature, Span, VarId, ast::ImportPattern, engine::StateWorkingSet,
10};
11
12/// An [`Expression`] AST node
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub enum Expr {
15    AttributeBlock(AttributeBlock),
16    Bool(bool),
17    Int(i64),
18    Float(f64),
19    Binary(Vec<u8>),
20    Range(Box<Range>),
21    Var(VarId),
22    VarDecl(VarId),
23    Call(Box<Call>),
24    ExternalCall(Box<Expression>, Box<[ExternalArgument]>), // head, args
25    Operator(Operator),
26    RowCondition(BlockId),
27    UnaryNot(Box<Expression>),
28    /// Negation of a number, duration or filesize, written `-$x` or `-(expr)`.
29    UnaryMinus(Box<Expression>),
30    BinaryOp(Box<Expression>, Box<Expression>, Box<Expression>), //lhs, op, rhs
31    Collect(VarId, Box<Expression>),
32    Subexpression(BlockId),
33    Block(BlockId),
34    Closure(BlockId),
35    MatchBlock(Vec<(MatchPattern, Expression)>),
36    List(Vec<ListItem>),
37    Table(Table),
38    Record(Vec<RecordItem>),
39    Keyword(Box<Keyword>),
40    ValueWithUnit(Box<ValueWithUnit>),
41    DateTime(chrono::DateTime<FixedOffset>),
42    /// The boolean is `true` if the string is quoted.
43    Filepath(String, bool),
44    /// The boolean is `true` if the string is quoted.
45    Directory(String, bool),
46    /// The boolean is `true` if the string is quoted.
47    GlobPattern(String, bool),
48    String(String),
49    RawString(String),
50    CellPath(CellPath),
51    FullCellPath(Box<FullCellPath>),
52    ImportPattern(Box<ImportPattern>),
53    Overlay(Option<ModuleId>),
54    Signature(Box<Signature>),
55    StringInterpolation(Vec<Expression>),
56    /// The boolean is `true` if the string is quoted.
57    GlobInterpolation(Vec<Expression>, bool),
58    Nothing,
59    Garbage,
60}
61
62// This is to document/enforce the size of `Expr` in bytes.
63// We should try to avoid increasing the size of `Expr`,
64// and PRs that do so will have to change the number below so that it's noted in review.
65const _: () = assert!(std::mem::size_of::<Expr>() <= 40);
66
67impl Expr {
68    /// Returns a user-friendly description of the expression variant.
69    ///
70    /// This is used in error messages to avoid exposing internal Rust type names
71    /// (e.g. "FullCellPath") to users.
72    pub fn description(&self) -> &str {
73        match self {
74            Expr::AttributeBlock(_) => "an attribute block",
75            Expr::Bool(_) => "a boolean",
76            Expr::Int(_) => "an integer",
77            Expr::Float(_) => "a float",
78            Expr::Binary(_) => "a binary value",
79            Expr::Range(_) => "a range",
80            Expr::Var(_) => "a variable",
81            Expr::VarDecl(_) => "a variable declaration",
82            Expr::Call(_) => "a command call",
83            Expr::ExternalCall(_, _) => "an external command call",
84            Expr::Operator(_) => "an operator",
85            Expr::RowCondition(_) => "a row condition",
86            Expr::UnaryNot(_) => "a negation",
87            Expr::UnaryMinus(_) => "a numeric negation",
88            Expr::BinaryOp(_, _, _) => "a binary operation",
89            Expr::Collect(_, _) => "a collect expression",
90            Expr::Subexpression(_) => "a subexpression",
91            Expr::Block(_) => "a block",
92            Expr::Closure(_) => "a closure",
93            Expr::MatchBlock(_) => "a match block",
94            Expr::List(_) => "a list",
95            Expr::Table(_) => "a table",
96            Expr::Record(_) => "a record",
97            Expr::Keyword(_) => "a keyword",
98            Expr::ValueWithUnit(_) => "a value with unit",
99            Expr::DateTime(_) => "a datetime",
100            Expr::Filepath(_, _) => "a filepath",
101            Expr::Directory(_, _) => "a directory",
102            Expr::GlobPattern(_, _) => "a glob pattern",
103            Expr::String(_) => "a string",
104            Expr::RawString(_) => "a raw string",
105            Expr::CellPath(_) => "a cell path",
106            Expr::FullCellPath(_) => "a cell path expression",
107            Expr::ImportPattern(_) => "an import pattern",
108            Expr::Overlay(_) => "an overlay",
109            Expr::Signature(_) => "a signature",
110            Expr::StringInterpolation(_) => "a string interpolation",
111            Expr::GlobInterpolation(_, _) => "a glob interpolation",
112            Expr::Nothing => "a nothing",
113            Expr::Garbage => "a garbage expression",
114        }
115    }
116
117    pub fn pipe_redirection(
118        &self,
119        working_set: &StateWorkingSet,
120    ) -> (Option<OutDest>, Option<OutDest>) {
121        match self {
122            Expr::AttributeBlock(ab) => ab.item.expr.pipe_redirection(working_set),
123            Expr::Call(call) => working_set.get_decl(call.decl_id).pipe_redirection(),
124            Expr::Collect(_, expr) => {
125                // A collect expression always has default redirection, it's just going to collect
126                // stdout unless another type of redirection is specified. A command that reads
127                // the output as text (`^cmd $in`) still gets it as text.
128                match expr.expr.pipe_redirection(working_set) {
129                    (Some(OutDest::PipeRaw), _) => (Some(OutDest::PipeRaw), None),
130                    _ => (None, None),
131                }
132            },
133            Expr::Subexpression(block_id) | Expr::Block(block_id) => working_set
134                .get_block(*block_id)
135                .pipe_redirection(working_set),
136            Expr::FullCellPath(cell_path) => cell_path.head.expr.pipe_redirection(working_set),
137            Expr::Bool(_)
138            | Expr::Int(_)
139            | Expr::Float(_)
140            | Expr::Binary(_)
141            | Expr::Range(_)
142            | Expr::Var(_)
143            | Expr::UnaryNot(_)
144            | Expr::UnaryMinus(_)
145            | Expr::BinaryOp(_, _, _)
146            | Expr::Closure(_) // piping into a closure value, not into a closure call
147            | Expr::List(_)
148            | Expr::Table(_)
149            | Expr::Record(_)
150            | Expr::ValueWithUnit(_)
151            | Expr::DateTime(_)
152            | Expr::String(_)
153            | Expr::RawString(_)
154            | Expr::CellPath(_)
155            | Expr::StringInterpolation(_)
156            | Expr::GlobInterpolation(_, _)
157            | Expr::Nothing => {
158                // These expressions do not use the output of the pipeline in any meaningful way,
159                // but we still need to use the pipeline output, so the previous command
160                // can be stopped with SIGPIPE(in unix).
161                (None, None)
162            }
163            Expr::VarDecl(_)
164            | Expr::Operator(_)
165            | Expr::Filepath(_, _)
166            | Expr::Directory(_, _)
167            | Expr::GlobPattern(_, _)
168            | Expr::ImportPattern(_)
169            | Expr::Overlay(_)
170            | Expr::Signature(_)
171            | Expr::Garbage => {
172                // These should be impossible to pipe to,
173                // but even it is, the pipeline output is not used in any way.
174                (Some(OutDest::Null), None)
175            }
176            Expr::RowCondition(_) | Expr::MatchBlock(_) => {
177                // These should be impossible to pipe to,
178                // but if they are, then the pipeline output could be used.
179                (None, None)
180            }
181            Expr::ExternalCall(_, _) => {
182                // An external command reads its input as text
183                (Some(OutDest::PipeRaw), None)
184            }
185            Expr::Keyword(_) => {
186                // Not sure about this; let's return no redirection override for now.
187                (None, None)
188            }
189        }
190    }
191}
192
193/// Expressions permitted inside a record expression/literal
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195pub enum RecordItem {
196    /// A key: val mapping
197    Pair(Expression, Expression),
198    /// Span for the "..." and the expression that's being spread
199    Spread(Span, Expression),
200}
201
202/// Expressions permitted inside a list expression/literal
203#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
204pub enum ListItem {
205    /// A normal expression
206    Item(Expression),
207    /// Span for the "..." and the expression that's being spread
208    Spread(Span, Expression),
209}
210
211impl ListItem {
212    pub fn expr(&self) -> &Expression {
213        let (ListItem::Item(expr) | ListItem::Spread(_, expr)) = self;
214        expr
215    }
216
217    pub fn expr_mut(&mut self) -> &mut Expression {
218        let (ListItem::Item(expr) | ListItem::Spread(_, expr)) = self;
219        expr
220    }
221}