Skip to main content

nu_protocol/ast/
block.rs

1use super::Pipeline;
2use crate::{
3    OutDest, Signature, Span, Type, VarId,
4    engine::{BoundNames, ScopeBindings, StateWorkingSet},
5    ir::IrBlock,
6};
7use serde::{Deserialize, Serialize};
8use std::sync::Arc;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Block {
12    pub signature: Box<Signature>,
13    pub pipelines: Vec<Pipeline>,
14    pub captures: Vec<(VarId, Span)>,
15    pub redirect_env: bool,
16    /// The block compiled to IR instructions. Not available for subexpressions.
17    pub ir_block: Option<IrBlock>,
18    pub span: Option<Span>, // None option encodes no span to avoid using test_span()
19    /// Local command/module name bindings introduced while parsing this block.
20    ///
21    /// Nested parse scopes discard their name maps on exit; this snapshot lets `scope`
22    /// subcommands report those locals while the block is being evaluated.
23    ///
24    /// Not serialized: only meaningful within the process that parsed the block.
25    #[serde(skip)]
26    pub scope_bindings: Option<Arc<ScopeBindings>>,
27    /// Whether `parse_block` ran with `scoped = true` (`enter_scope`).
28    ///
29    /// Distinct from `scope_bindings`: a scoped parse of a let-only file still
30    /// snapshots as `None`. Needed so `source` does not reuse a `source-env` parse.
31    #[serde(skip)]
32    pub parsed_scoped: bool,
33    /// For a file parsed without a scope of its own (`scoped = false`), the names the parse bound
34    /// in the caller's scope frame, or `None` if it changed that frame in other ways too.
35    ///
36    /// The parser reuses a cached unscoped block only where these names are still bound, since
37    /// reusing it doesn't declare them again. See [`BoundNames`].
38    #[serde(skip)]
39    pub bound_names: Option<Arc<BoundNames>>,
40}
41
42impl Block {
43    pub fn len(&self) -> usize {
44        self.pipelines.len()
45    }
46
47    pub fn is_empty(&self) -> bool {
48        self.pipelines.is_empty()
49    }
50
51    pub fn pipe_redirection(
52        &self,
53        working_set: &StateWorkingSet,
54    ) -> (Option<OutDest>, Option<OutDest>) {
55        if let Some(first) = self.pipelines.first() {
56            first.pipe_redirection(working_set)
57        } else {
58            (None, None)
59        }
60    }
61}
62
63impl Default for Block {
64    fn default() -> Self {
65        Self::new()
66    }
67}
68
69impl Block {
70    pub fn new() -> Self {
71        Self {
72            signature: Box::new(Signature::new("")),
73            pipelines: vec![],
74            captures: vec![],
75            redirect_env: false,
76            ir_block: None,
77            span: None,
78            scope_bindings: None,
79            parsed_scoped: false,
80            bound_names: None,
81        }
82    }
83
84    pub fn new_with_capacity(capacity: usize) -> Self {
85        Self {
86            signature: Box::new(Signature::new("")),
87            pipelines: Vec::with_capacity(capacity),
88            captures: vec![],
89            redirect_env: false,
90            ir_block: None,
91            span: None,
92            scope_bindings: None,
93            parsed_scoped: false,
94            bound_names: None,
95        }
96    }
97
98    pub fn output_type(&self) -> Type {
99        match self.pipelines.last().and_then(|pl| pl.elements.last()) {
100            Some(pe) if pe.redirection.is_none() => pe.expr.ty.clone(),
101            Some(_) => Type::Any,
102            None => Type::Nothing,
103        }
104    }
105
106    /// Replace any `$in` variables in the initial element of pipelines within the block
107    pub fn replace_in_variable(
108        &mut self,
109        working_set: &mut StateWorkingSet<'_>,
110        new_var_id: VarId,
111    ) {
112        for pipeline in self.pipelines.iter_mut() {
113            if let Some(element) = pipeline.elements.first_mut() {
114                element.replace_in_variable(working_set, new_var_id);
115            }
116        }
117    }
118}
119
120impl<T> From<T> for Block
121where
122    T: Iterator<Item = Pipeline>,
123{
124    fn from(pipelines: T) -> Self {
125        Self {
126            signature: Box::new(Signature::new("")),
127            pipelines: pipelines.collect(),
128            captures: vec![],
129            redirect_env: false,
130            ir_block: None,
131            span: None,
132            scope_bindings: None,
133            parsed_scoped: false,
134            bound_names: None,
135        }
136    }
137}