Skip to main content

nu_protocol/ast/
expression.rs

1use crate::{
2    BlockId, GetSpan, IN_VARIABLE_ID, Signature, Span, SpanId, Type, VarId,
3    ast::{Argument, Block, Expr, ExternalArgument, ImportPattern, MatchPattern, RecordItem},
4    engine::StateWorkingSet,
5};
6use serde::{Deserialize, Serialize};
7use std::sync::Arc;
8
9use super::ListItem;
10
11/// Wrapper around [`Expr`]
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13pub struct Expression {
14    pub expr: Expr,
15    pub span: Span,
16    pub span_id: SpanId,
17    pub ty: Type,
18}
19
20impl Expression {
21    pub fn garbage(working_set: &mut StateWorkingSet, span: Span) -> Expression {
22        let span_id = working_set.add_span(span);
23        Expression {
24            expr: Expr::Garbage,
25            span,
26            span_id,
27            ty: Type::Any,
28        }
29    }
30
31    pub fn precedence(&self) -> u8 {
32        match &self.expr {
33            Expr::Operator(operator) => operator.precedence(),
34            _ => 0,
35        }
36    }
37
38    pub fn as_block(&self) -> Option<BlockId> {
39        match self.expr {
40            Expr::Block(block_id) => Some(block_id),
41            Expr::Closure(block_id) => Some(block_id),
42            _ => None,
43        }
44    }
45
46    pub fn as_row_condition_block(&self) -> Option<BlockId> {
47        match self.expr {
48            Expr::RowCondition(block_id) => Some(block_id),
49            _ => None,
50        }
51    }
52
53    pub fn as_match_block(&self) -> Option<&[(MatchPattern, Expression)]> {
54        match &self.expr {
55            Expr::MatchBlock(matches) => Some(matches),
56            _ => None,
57        }
58    }
59
60    pub fn as_signature(&self) -> Option<Box<Signature>> {
61        match &self.expr {
62            Expr::Signature(sig) => Some(sig.clone()),
63            _ => None,
64        }
65    }
66
67    pub fn as_keyword(&self) -> Option<&Expression> {
68        match &self.expr {
69            Expr::Keyword(kw) => Some(&kw.expr),
70            _ => None,
71        }
72    }
73
74    pub fn as_keyword_with_name(&self) -> Option<(&[u8], &Expression)> {
75        match &self.expr {
76            Expr::Keyword(kw) => Some((&kw.keyword, &kw.expr)),
77            _ => None,
78        }
79    }
80
81    pub fn as_var(&self) -> Option<VarId> {
82        match self.expr {
83            Expr::Var(var_id) => Some(var_id),
84            Expr::VarDecl(var_id) => Some(var_id),
85            _ => None,
86        }
87    }
88
89    /// The variable a bare `$name` refers to: an [`Expr::Var`], or a cell path on one with no
90    /// members, which is how `$name` is parsed as an argument.
91    pub fn as_bare_var(&self) -> Option<VarId> {
92        match &self.expr {
93            Expr::Var(var_id) => Some(*var_id),
94            Expr::FullCellPath(cell_path) if cell_path.tail.is_empty() => {
95                match cell_path.head.expr {
96                    Expr::Var(var_id) => Some(var_id),
97                    _ => None,
98                }
99            }
100            _ => None,
101        }
102    }
103
104    pub fn as_string(&self) -> Option<String> {
105        match &self.expr {
106            Expr::String(string) => Some(string.clone()),
107            _ => None,
108        }
109    }
110
111    pub fn as_filepath(&self) -> Option<(String, bool)> {
112        match &self.expr {
113            Expr::Filepath(string, quoted) => Some((string.clone(), *quoted)),
114            _ => None,
115        }
116    }
117
118    pub fn as_import_pattern(&self) -> Option<ImportPattern> {
119        match &self.expr {
120            Expr::ImportPattern(pattern) => Some(*pattern.clone()),
121            _ => None,
122        }
123    }
124
125    pub fn has_in_variable(&self, working_set: &StateWorkingSet) -> bool {
126        match &self.expr {
127            Expr::AttributeBlock(ab) => ab.item.has_in_variable(working_set),
128            Expr::BinaryOp(left, _, right) => {
129                left.has_in_variable(working_set) || right.has_in_variable(working_set)
130            }
131            Expr::UnaryNot(expr) | Expr::UnaryMinus(expr) => expr.has_in_variable(working_set),
132            Expr::Block(block_id) | Expr::Closure(block_id) => {
133                let block = working_set.get_block(*block_id);
134                block
135                    .captures
136                    .iter()
137                    .any(|(var_id, _)| var_id == &IN_VARIABLE_ID)
138                    || block
139                        .pipelines
140                        .iter()
141                        .flat_map(|pipeline| pipeline.elements.first())
142                        .any(|element| element.has_in_variable(working_set))
143            }
144            Expr::Binary(_) => false,
145            Expr::Bool(_) => false,
146            Expr::Call(call) => {
147                for arg in &call.arguments {
148                    match arg {
149                        Argument::Positional(expr)
150                        | Argument::Unknown(expr)
151                        | Argument::Spread(expr) => {
152                            if expr.has_in_variable(working_set) {
153                                return true;
154                            }
155                        }
156                        Argument::Named(named) => {
157                            if let Some(expr) = &named.2
158                                && expr.has_in_variable(working_set)
159                            {
160                                return true;
161                            }
162                        }
163                    }
164                }
165                false
166            }
167            Expr::CellPath(_) => false,
168            Expr::DateTime(_) => false,
169            Expr::ExternalCall(head, args) => {
170                if head.has_in_variable(working_set) {
171                    return true;
172                }
173                for ExternalArgument::Regular(expr) | ExternalArgument::Spread(expr) in
174                    args.as_ref()
175                {
176                    if expr.has_in_variable(working_set) {
177                        return true;
178                    }
179                }
180                false
181            }
182            Expr::ImportPattern(_) => false,
183            Expr::Overlay(_) => false,
184            Expr::Filepath(_, _) => false,
185            Expr::Directory(_, _) => false,
186            Expr::Float(_) => false,
187            Expr::FullCellPath(full_cell_path) => {
188                if full_cell_path.head.has_in_variable(working_set) {
189                    return true;
190                }
191                false
192            }
193            Expr::Garbage => false,
194            Expr::Nothing => false,
195            Expr::GlobPattern(_, _) => false,
196            Expr::Int(_) => false,
197            Expr::Keyword(kw) => kw.expr.has_in_variable(working_set),
198            Expr::List(list) => {
199                for item in list {
200                    if item.expr().has_in_variable(working_set) {
201                        return true;
202                    }
203                }
204                false
205            }
206            Expr::StringInterpolation(items) | Expr::GlobInterpolation(items, _) => {
207                for i in items {
208                    if i.has_in_variable(working_set) {
209                        return true;
210                    }
211                }
212                false
213            }
214            Expr::Operator(_) => false,
215            Expr::MatchBlock(_) => false,
216            Expr::Range(range) => {
217                if let Some(left) = &range.from
218                    && left.has_in_variable(working_set)
219                {
220                    return true;
221                }
222                if let Some(middle) = &range.next
223                    && middle.has_in_variable(working_set)
224                {
225                    return true;
226                }
227                if let Some(right) = &range.to
228                    && right.has_in_variable(working_set)
229                {
230                    return true;
231                }
232                false
233            }
234            Expr::Record(items) => {
235                for item in items {
236                    match item {
237                        RecordItem::Pair(field_name, field_value) => {
238                            if field_name.has_in_variable(working_set) {
239                                return true;
240                            }
241                            if field_value.has_in_variable(working_set) {
242                                return true;
243                            }
244                        }
245                        RecordItem::Spread(_, record) => {
246                            if record.has_in_variable(working_set) {
247                                return true;
248                            }
249                        }
250                    }
251                }
252                false
253            }
254            Expr::Signature(_) => false,
255            Expr::String(_) => false,
256            Expr::RawString(_) => false,
257            // A `$in` variable found within a `Collect` is local, as it's already been wrapped
258            // This is probably unlikely to happen anyway - the expressions are wrapped depth-first
259            Expr::Collect(_, _) => false,
260            Expr::RowCondition(block_id) | Expr::Subexpression(block_id) => {
261                let block = working_set.get_block(*block_id);
262
263                if let Some(pipeline) = block.pipelines.first() {
264                    if let Some(expr) = pipeline.elements.first() {
265                        expr.has_in_variable(working_set)
266                    } else {
267                        false
268                    }
269                } else {
270                    false
271                }
272            }
273            Expr::Table(table) => {
274                for header in table.columns.as_ref() {
275                    if header.has_in_variable(working_set) {
276                        return true;
277                    }
278                }
279
280                for row in table.rows.as_ref() {
281                    for cell in row.iter() {
282                        if cell.has_in_variable(working_set) {
283                            return true;
284                        }
285                    }
286                }
287
288                false
289            }
290
291            Expr::ValueWithUnit(value) => value.expr.has_in_variable(working_set),
292            Expr::Var(var_id) => *var_id == IN_VARIABLE_ID,
293            Expr::VarDecl(_) => false,
294        }
295    }
296
297    pub fn replace_span(
298        &mut self,
299        working_set: &mut StateWorkingSet,
300        replaced: Span,
301        new_span: Span,
302    ) {
303        if replaced.contains_span(self.span) {
304            self.span = new_span;
305        }
306        match &mut self.expr {
307            Expr::AttributeBlock(ab) => ab.item.replace_span(working_set, replaced, new_span),
308            Expr::BinaryOp(left, _, right) => {
309                left.replace_span(working_set, replaced, new_span);
310                right.replace_span(working_set, replaced, new_span);
311            }
312            Expr::UnaryNot(expr) | Expr::UnaryMinus(expr) => {
313                expr.replace_span(working_set, replaced, new_span);
314            }
315            Expr::Block(block_id) => {
316                // We are cloning the Block itself, rather than the Arc around it.
317                let mut block = Block::clone(working_set.get_block(*block_id));
318
319                for pipeline in block.pipelines.iter_mut() {
320                    for element in pipeline.elements.iter_mut() {
321                        element.replace_span(working_set, replaced, new_span)
322                    }
323                }
324
325                *block_id = working_set.add_block(Arc::new(block));
326            }
327            Expr::Closure(block_id) => {
328                let mut block = (**working_set.get_block(*block_id)).clone();
329
330                for pipeline in block.pipelines.iter_mut() {
331                    for element in pipeline.elements.iter_mut() {
332                        element.replace_span(working_set, replaced, new_span)
333                    }
334                }
335
336                *block_id = working_set.add_block(Arc::new(block));
337            }
338            Expr::Binary(_) => {}
339            Expr::Bool(_) => {}
340            Expr::Call(call) => {
341                if replaced.contains_span(call.head) {
342                    call.head = new_span;
343                }
344                for arg in call.arguments.iter_mut() {
345                    match arg {
346                        Argument::Positional(expr)
347                        | Argument::Unknown(expr)
348                        | Argument::Spread(expr) => {
349                            expr.replace_span(working_set, replaced, new_span);
350                        }
351                        Argument::Named(named) => {
352                            if let Some(expr) = &mut named.2 {
353                                expr.replace_span(working_set, replaced, new_span);
354                            }
355                        }
356                    }
357                }
358            }
359            Expr::CellPath(_) => {}
360            Expr::DateTime(_) => {}
361            Expr::ExternalCall(head, args) => {
362                head.replace_span(working_set, replaced, new_span);
363                for ExternalArgument::Regular(expr) | ExternalArgument::Spread(expr) in
364                    args.as_mut()
365                {
366                    expr.replace_span(working_set, replaced, new_span);
367                }
368            }
369            Expr::Filepath(_, _) => {}
370            Expr::Directory(_, _) => {}
371            Expr::Float(_) => {}
372            Expr::FullCellPath(full_cell_path) => {
373                full_cell_path
374                    .head
375                    .replace_span(working_set, replaced, new_span);
376            }
377            Expr::ImportPattern(_) => {}
378            Expr::Overlay(_) => {}
379            Expr::Garbage => {}
380            Expr::Nothing => {}
381            Expr::GlobPattern(_, _) => {}
382            Expr::MatchBlock(_) => {}
383            Expr::Int(_) => {}
384            Expr::Keyword(kw) => kw.expr.replace_span(working_set, replaced, new_span),
385            Expr::List(list) => {
386                for item in list {
387                    item.expr_mut()
388                        .replace_span(working_set, replaced, new_span);
389                }
390            }
391            Expr::Operator(_) => {}
392            Expr::Range(range) => {
393                if let Some(left) = &mut range.from {
394                    left.replace_span(working_set, replaced, new_span)
395                }
396                if let Some(middle) = &mut range.next {
397                    middle.replace_span(working_set, replaced, new_span)
398                }
399                if let Some(right) = &mut range.to {
400                    right.replace_span(working_set, replaced, new_span)
401                }
402            }
403            Expr::Record(items) => {
404                for item in items {
405                    match item {
406                        RecordItem::Pair(field_name, field_value) => {
407                            field_name.replace_span(working_set, replaced, new_span);
408                            field_value.replace_span(working_set, replaced, new_span);
409                        }
410                        RecordItem::Spread(_, record) => {
411                            record.replace_span(working_set, replaced, new_span);
412                        }
413                    }
414                }
415            }
416            Expr::Signature(_) => {}
417            Expr::String(_) => {}
418            Expr::RawString(_) => {}
419            Expr::StringInterpolation(items) | Expr::GlobInterpolation(items, _) => {
420                for i in items {
421                    i.replace_span(working_set, replaced, new_span)
422                }
423            }
424            Expr::Collect(_, expr) => expr.replace_span(working_set, replaced, new_span),
425            Expr::RowCondition(block_id) | Expr::Subexpression(block_id) => {
426                let mut block = (**working_set.get_block(*block_id)).clone();
427
428                for pipeline in block.pipelines.iter_mut() {
429                    for element in pipeline.elements.iter_mut() {
430                        element.replace_span(working_set, replaced, new_span)
431                    }
432                }
433
434                *block_id = working_set.add_block(Arc::new(block));
435            }
436            Expr::Table(table) => {
437                for header in table.columns.as_mut() {
438                    header.replace_span(working_set, replaced, new_span)
439                }
440
441                for row in table.rows.as_mut() {
442                    for cell in row.iter_mut() {
443                        cell.replace_span(working_set, replaced, new_span)
444                    }
445                }
446            }
447
448            Expr::ValueWithUnit(value) => value.expr.replace_span(working_set, replaced, new_span),
449            Expr::Var(_) => {}
450            Expr::VarDecl(_) => {}
451        }
452    }
453
454    pub fn replace_in_variable(&mut self, working_set: &mut StateWorkingSet, new_var_id: VarId) {
455        match &mut self.expr {
456            Expr::AttributeBlock(ab) => ab.item.replace_in_variable(working_set, new_var_id),
457            Expr::Bool(_) => {}
458            Expr::Int(_) => {}
459            Expr::Float(_) => {}
460            Expr::Binary(_) => {}
461            Expr::Range(range) => {
462                if let Some(from) = &mut range.from {
463                    from.replace_in_variable(working_set, new_var_id);
464                }
465                if let Some(next) = &mut range.next {
466                    next.replace_in_variable(working_set, new_var_id);
467                }
468                if let Some(to) = &mut range.to {
469                    to.replace_in_variable(working_set, new_var_id);
470                }
471            }
472            Expr::Var(var_id) | Expr::VarDecl(var_id) => {
473                if *var_id == IN_VARIABLE_ID {
474                    *var_id = new_var_id;
475                }
476            }
477            Expr::Call(call) => {
478                for arg in call.arguments.iter_mut() {
479                    match arg {
480                        Argument::Positional(expr)
481                        | Argument::Unknown(expr)
482                        | Argument::Named((_, _, Some(expr)))
483                        | Argument::Spread(expr) => {
484                            expr.replace_in_variable(working_set, new_var_id)
485                        }
486                        Argument::Named((_, _, None)) => {}
487                    }
488                }
489                for expr in call.parser_info.values_mut() {
490                    expr.replace_in_variable(working_set, new_var_id)
491                }
492            }
493            Expr::ExternalCall(head, args) => {
494                head.replace_in_variable(working_set, new_var_id);
495                for arg in args.iter_mut() {
496                    match arg {
497                        ExternalArgument::Regular(expr) | ExternalArgument::Spread(expr) => {
498                            expr.replace_in_variable(working_set, new_var_id)
499                        }
500                    }
501                }
502            }
503            Expr::Operator(_) => {}
504            // `$in` in `Collect` has already been handled, so we don't need to check further
505            Expr::Collect(_, _) => {}
506            Expr::Block(block_id)
507            | Expr::Closure(block_id)
508            | Expr::RowCondition(block_id)
509            | Expr::Subexpression(block_id) => {
510                if block_id.get() < working_set.permanent_state.num_blocks() {
511                    // For aliased blocks, duplicate to avoid panics
512                    // TODO: consider making them mutable in the future
513                    let mut block = Block::clone(working_set.get_block(*block_id));
514                    block.replace_in_variable(working_set, new_var_id);
515                    *block_id = working_set.add_block(Arc::new(block));
516                } else {
517                    // Take the block out of the working set rather than cloning it: the walk only
518                    // visits the blocks nested in it, never this one, so nothing sees the
519                    // placeholder before the block is put back.
520                    let mut block = std::mem::take(working_set.get_block_mut(*block_id));
521                    block.replace_in_variable(working_set, new_var_id);
522                    *working_set.get_block_mut(*block_id) = block;
523                }
524            }
525            Expr::UnaryNot(expr) | Expr::UnaryMinus(expr) => {
526                expr.replace_in_variable(working_set, new_var_id);
527            }
528            Expr::BinaryOp(lhs, op, rhs) => {
529                for expr in [lhs, op, rhs] {
530                    expr.replace_in_variable(working_set, new_var_id);
531                }
532            }
533            Expr::MatchBlock(match_patterns) => {
534                for (_, expr) in match_patterns.iter_mut() {
535                    expr.replace_in_variable(working_set, new_var_id);
536                }
537            }
538            Expr::List(items) => {
539                for item in items.iter_mut() {
540                    match item {
541                        ListItem::Item(expr) | ListItem::Spread(_, expr) => {
542                            expr.replace_in_variable(working_set, new_var_id)
543                        }
544                    }
545                }
546            }
547            Expr::Table(table) => {
548                for col_expr in table.columns.iter_mut() {
549                    col_expr.replace_in_variable(working_set, new_var_id);
550                }
551                for row in table.rows.iter_mut() {
552                    for row_expr in row.iter_mut() {
553                        row_expr.replace_in_variable(working_set, new_var_id);
554                    }
555                }
556            }
557            Expr::Record(items) => {
558                for item in items.iter_mut() {
559                    match item {
560                        RecordItem::Pair(key, val) => {
561                            key.replace_in_variable(working_set, new_var_id);
562                            val.replace_in_variable(working_set, new_var_id);
563                        }
564                        RecordItem::Spread(_, expr) => {
565                            expr.replace_in_variable(working_set, new_var_id)
566                        }
567                    }
568                }
569            }
570            Expr::Keyword(kw) => kw.expr.replace_in_variable(working_set, new_var_id),
571            Expr::ValueWithUnit(value_with_unit) => value_with_unit
572                .expr
573                .replace_in_variable(working_set, new_var_id),
574            Expr::DateTime(_) => {}
575            Expr::Filepath(_, _) => {}
576            Expr::Directory(_, _) => {}
577            Expr::GlobPattern(_, _) => {}
578            Expr::String(_) => {}
579            Expr::RawString(_) => {}
580            Expr::CellPath(_) => {}
581            Expr::FullCellPath(full_cell_path) => {
582                full_cell_path
583                    .head
584                    .replace_in_variable(working_set, new_var_id);
585            }
586            Expr::ImportPattern(_) => {}
587            Expr::Overlay(_) => {}
588            Expr::Signature(_) => {}
589            Expr::StringInterpolation(exprs) | Expr::GlobInterpolation(exprs, _) => {
590                for expr in exprs.iter_mut() {
591                    expr.replace_in_variable(working_set, new_var_id);
592                }
593            }
594            Expr::Nothing => {}
595            Expr::Garbage => {}
596        }
597    }
598
599    pub fn new(working_set: &mut StateWorkingSet, expr: Expr, span: Span, ty: Type) -> Expression {
600        let span_id = working_set.add_span(span);
601        Expression {
602            expr,
603            span,
604            span_id,
605            ty,
606        }
607    }
608
609    pub fn new_existing(expr: Expr, span: Span, span_id: SpanId, ty: Type) -> Expression {
610        Expression {
611            expr,
612            span,
613            span_id,
614            ty,
615        }
616    }
617
618    pub fn new_unknown(expr: Expr, span: Span, ty: Type) -> Expression {
619        Expression {
620            expr,
621            span,
622            span_id: SpanId::new(0),
623            ty,
624        }
625    }
626
627    pub fn with_span_id(self, span_id: SpanId) -> Expression {
628        Expression {
629            expr: self.expr,
630            span: self.span,
631            span_id,
632            ty: self.ty,
633        }
634    }
635
636    pub fn span(&self, state: &impl GetSpan) -> Span {
637        state.get_span(self.span_id)
638    }
639}