Skip to main content

nu_protocol/ir/
call.rs

1use std::sync::Arc;
2
3use crate::{
4    DeclId, ShellError, Span, Spanned, Value,
5    ast::Expression,
6    engine::{self, Argument, Stack},
7};
8
9use super::DataSlice;
10
11/// Contains the information for a call being made to a declared command.
12#[derive(Debug, Clone)]
13pub struct Call {
14    /// The declaration ID of the command to be invoked.
15    pub decl_id: DeclId,
16    /// The span encompassing the command name, before the arguments.
17    pub head: Span,
18    /// The span encompassing the command name and all arguments.
19    pub span: Span,
20    /// The base index of the arguments for this call within the
21    /// [argument stack](crate::engine::ArgumentStack).
22    pub args_base: usize,
23    /// The number of [`Argument`]s for the call. Note that this just counts the number of
24    /// `Argument` entries on the stack, and has nothing to do with the actual number of positional
25    /// or spread arguments.
26    pub args_len: usize,
27}
28
29impl Call {
30    /// Build a new call with arguments.
31    pub fn build(decl_id: DeclId, head: Span) -> CallBuilder {
32        CallBuilder {
33            inner: Call {
34                decl_id,
35                head,
36                span: head,
37                args_base: 0,
38                args_len: 0,
39            },
40        }
41    }
42
43    /// Get the arguments for this call from the arguments stack.
44    pub fn arguments<'a>(&self, stack: &'a Stack) -> &'a [Argument] {
45        stack.arguments.get_args(self.args_base, self.args_len)
46    }
47
48    /// The span encompassing the arguments
49    ///
50    /// If there are no arguments the span covers where the first argument would exist
51    ///
52    /// If there are one or more arguments the span encompasses the start of the first argument to
53    /// end of the last argument
54    pub fn arguments_span(&self) -> Span {
55        let past = self.head.past();
56        Span::new(past.start, self.span.end)
57    }
58
59    /// The number of named arguments, with or without values.
60    pub fn named_len(&self, stack: &Stack) -> usize {
61        self.arguments(stack)
62            .iter()
63            .filter(|arg| matches!(arg, Argument::Named { .. } | Argument::Flag { .. }))
64            .count()
65    }
66
67    /// Iterate through named arguments, with or without values.
68    pub fn named_iter<'a>(
69        &'a self,
70        stack: &'a Stack,
71    ) -> impl Iterator<Item = (Spanned<&'a str>, Option<&'a Value>)> + 'a {
72        self.arguments(stack).iter().filter_map(
73            |arg: &Argument| -> Option<(Spanned<&str>, Option<&Value>)> {
74                match arg {
75                    Argument::Flag {
76                        data, name, span, ..
77                    } => Some((
78                        Spanned {
79                            item: std::str::from_utf8(&data[*name]).expect("invalid arg name"),
80                            span: *span,
81                        },
82                        None,
83                    )),
84                    Argument::Named {
85                        data,
86                        name,
87                        span,
88                        val,
89                        ..
90                    } => Some((
91                        Spanned {
92                            item: std::str::from_utf8(&data[*name]).expect("invalid arg name"),
93                            span: *span,
94                        },
95                        Some(val),
96                    )),
97                    _ => None,
98                }
99            },
100        )
101    }
102
103    /// Get a named argument's value by name. Returns [`None`] for named arguments with no value as
104    /// well.
105    pub fn get_named_arg<'a>(&self, stack: &'a Stack, flag_name: &str) -> Option<&'a Value> {
106        // Optimized to avoid str::from_utf8()
107        self.arguments(stack)
108            .iter()
109            .find_map(|arg: &Argument| -> Option<Option<&Value>> {
110                match arg {
111                    Argument::Flag { data, name, .. } if &data[*name] == flag_name.as_bytes() => {
112                        Some(None)
113                    }
114                    Argument::Named {
115                        data, name, val, ..
116                    } if &data[*name] == flag_name.as_bytes() => Some(Some(val)),
117                    _ => None,
118                }
119            })
120            .flatten()
121    }
122
123    /// The number of positional arguments, excluding spread arguments.
124    pub fn positional_len(&self, stack: &Stack) -> usize {
125        self.arguments(stack)
126            .iter()
127            .filter(|arg| matches!(arg, Argument::Positional { .. }))
128            .count()
129    }
130
131    /// Iterate through positional arguments. Does not include spread arguments.
132    pub fn positional_iter<'a>(&self, stack: &'a Stack) -> impl Iterator<Item = &'a Value> {
133        self.arguments(stack).iter().filter_map(|arg| match arg {
134            Argument::Positional { val, .. } => Some(val),
135            _ => None,
136        })
137    }
138
139    /// Get a positional argument by index. Does not include spread arguments.
140    pub fn positional_nth<'a>(&self, stack: &'a Stack, index: usize) -> Option<&'a Value> {
141        self.positional_iter(stack).nth(index)
142    }
143
144    /// Returns every argument to the rest parameter, as well as whether each argument
145    /// is spread or a normal positional argument (true for spread, false for normal)
146    pub fn rest_iter<'a>(
147        &self,
148        stack: &'a Stack,
149        start: usize,
150    ) -> impl Iterator<Item = (&'a Value, bool)> + 'a {
151        self.arguments(stack)
152            .iter()
153            .filter_map(|arg| match arg {
154                Argument::Positional { val, .. } => Some((val, false)),
155                Argument::Spread { vals, .. } => Some((vals, true)),
156                _ => None,
157            })
158            .skip(start)
159    }
160
161    /// Returns all of the positional arguments including and after `start`, with spread arguments
162    /// flattened into a single `Vec`.
163    pub fn rest_iter_flattened(
164        &self,
165        stack: &Stack,
166        start: usize,
167    ) -> Result<Vec<Value>, ShellError> {
168        let mut acc = vec![];
169        for (rest_val, spread) in self.rest_iter(stack, start) {
170            if spread {
171                match rest_val {
172                    Value::List { vals, .. } => acc.extend(vals.iter().cloned()),
173                    Value::Nothing { .. } => (),
174                    Value::Error { error, .. } => return Err(ShellError::clone(error)),
175                    _ => {
176                        return Err(ShellError::CannotSpreadAsList {
177                            span: rest_val.span(),
178                        });
179                    }
180                }
181            } else {
182                acc.push(rest_val.clone());
183            }
184        }
185        Ok(acc)
186    }
187
188    /// Get a parser info argument by name.
189    pub fn get_parser_info<'a>(&self, stack: &'a Stack, name: &str) -> Option<&'a Expression> {
190        self.arguments(stack)
191            .iter()
192            .find_map(|argument| match argument {
193                Argument::ParserInfo {
194                    data,
195                    name: name_slice,
196                    info: expr,
197                } if &data[*name_slice] == name.as_bytes() => Some(expr.as_ref()),
198                _ => None,
199            })
200    }
201
202    /// Returns a span encompassing the entire call.
203    pub fn span(&self) -> Span {
204        self.span
205    }
206
207    /// Resets the [`Stack`] to its state before the call was made.
208    pub fn leave(&self, stack: &mut Stack) {
209        // A call without arguments put nothing on the stack, and its `args_base` was never set,
210        // so leaving its frame would remove every argument on the stack.
211        if self.args_len > 0 {
212            stack.arguments.leave_frame(self.args_base);
213        }
214    }
215}
216
217/// Utility struct for building a [`Call`] with arguments on the [`Stack`].
218pub struct CallBuilder {
219    inner: Call,
220}
221
222impl CallBuilder {
223    /// Add an argument to the [`Stack`] and reference it from the [`Call`].
224    pub fn add_argument(&mut self, stack: &mut Stack, argument: Argument) -> &mut Self {
225        if self.inner.args_len == 0 {
226            self.inner.args_base = stack.arguments.get_base();
227        }
228        self.inner.args_len += 1;
229        if let Some(span) = argument.span() {
230            self.inner.span = self.inner.span.merge(span);
231        }
232        stack.arguments.push(argument);
233        self
234    }
235
236    /// Add a positional argument to the [`Stack`] and reference it from the [`Call`].
237    pub fn add_positional(&mut self, stack: &mut Stack, span: Span, val: Value) -> &mut Self {
238        self.add_argument(stack, Argument::Positional { span, val })
239    }
240
241    /// Add a spread argument to the [`Stack`] and reference it from the [`Call`].
242    pub fn add_spread(&mut self, stack: &mut Stack, span: Span, vals: Value) -> &mut Self {
243        self.add_argument(stack, Argument::Spread { span, vals })
244    }
245
246    /// Add a flag (no-value named) argument to the [`Stack`] and reference it from the [`Call`].
247    pub fn add_flag(
248        &mut self,
249        stack: &mut Stack,
250        name: impl AsRef<str>,
251        short: impl AsRef<str>,
252        span: Span,
253    ) -> &mut Self {
254        let (data, name, short) = data_from_name_and_short(name.as_ref(), short.as_ref());
255        self.add_argument(
256            stack,
257            Argument::Flag {
258                data,
259                name,
260                short,
261                span,
262            },
263        )
264    }
265
266    /// Add a named argument to the [`Stack`] and reference it from the [`Call`].
267    pub fn add_named(
268        &mut self,
269        stack: &mut Stack,
270        name: impl AsRef<str>,
271        short: impl AsRef<str>,
272        span: Span,
273        val: Value,
274    ) -> &mut Self {
275        let (data, name, short) = data_from_name_and_short(name.as_ref(), short.as_ref());
276        self.add_argument(
277            stack,
278            Argument::Named {
279                data,
280                name,
281                short,
282                span,
283                val,
284            },
285        )
286    }
287
288    /// Produce the finished [`Call`] from the builder.
289    ///
290    /// The call should be entered / run before any other calls are constructed, because the
291    /// argument stack will be reset when they exit.
292    pub fn finish(&self) -> Call {
293        self.inner.clone()
294    }
295
296    /// Run a closure with the [`Call`] as an [`engine::Call`] reference, and then clean up the
297    /// arguments that were added to the [`Stack`] after.
298    ///
299    /// For convenience. Calls [`Call::leave`] after the closure ends.
300    pub fn with<T>(
301        self,
302        stack: &mut Stack,
303        f: impl FnOnce(&mut Stack, &engine::Call<'_>) -> T,
304    ) -> T {
305        let call = engine::Call::from(&self.inner);
306        let result = f(stack, &call);
307        self.inner.leave(stack);
308        result
309    }
310}
311
312fn data_from_name_and_short(name: &str, short: &str) -> (Arc<[u8]>, DataSlice, DataSlice) {
313    let data: Vec<u8> = name.bytes().chain(short.bytes()).collect();
314    let data: Arc<[u8]> = data.into();
315    let name = DataSlice {
316        start: 0,
317        len: name.len().try_into().expect("flag name too big"),
318    };
319    let short = DataSlice {
320        start: name.start.checked_add(name.len).expect("flag name too big"),
321        len: short.len().try_into().expect("flag short name too big"),
322    };
323    (data, name, short)
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn leaving_a_call_without_arguments_keeps_the_stack() {
332        let mut stack = Stack::new();
333        let mut outer = Call::build(DeclId::new(0), Span::test_data());
334        outer.add_positional(&mut stack, Span::test_data(), Value::test_int(1));
335        let outer = outer.finish();
336
337        Call::build(DeclId::new(1), Span::test_data())
338            .finish()
339            .leave(&mut stack);
340
341        assert_eq!(outer.positional_len(&stack), 1);
342    }
343}