Skip to main content

nu_protocol/ast/
call.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::{
6    DeclId, FromValue, ShellError, Span, Spanned, Value, ast::Expression, engine::StateWorkingSet,
7    eval_const::eval_constant,
8};
9
10/// Parsed command arguments
11///
12/// Primarily for internal commands
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub enum Argument {
15    /// A positional argument (that is not [`Argument::Spread`])
16    ///
17    /// ```nushell
18    /// my_cmd positional
19    /// ```
20    Positional(Expression),
21    /// A named/flag argument that can optionally receive a [`Value`] as an [`Expression`]
22    ///
23    /// The optional second `Spanned<String>` refers to the short-flag version if used
24    /// ```nushell
25    /// my_cmd --flag
26    /// my_cmd -f
27    /// my_cmd --flag-with-value <expr>
28    /// ```
29    Named((Spanned<String>, Option<Spanned<String>>, Option<Expression>)),
30    /// unknown argument used in "fall-through" signatures
31    Unknown(Expression),
32    /// a list spread to fill in rest arguments
33    Spread(Expression),
34}
35
36/// A named argument's flag identity (long, or short when the long name is empty).
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum FlagRef<'a> {
39    Long(&'a str),
40    Short(&'a str),
41}
42
43impl<'a> FlagRef<'a> {
44    /// The `(long, short)` pair's identity: the long name, else the short spelling.
45    pub fn from_named(long: &'a Spanned<String>, short: Option<&'a Spanned<String>>) -> Self {
46        match short.filter(|_| long.item.is_empty()) {
47            Some(short) => FlagRef::Short(&short.item),
48            None => FlagRef::Long(&long.item),
49        }
50    }
51
52    /// The flag's name, without any dash prefix.
53    pub fn name(self) -> &'a str {
54        let (FlagRef::Long(name) | FlagRef::Short(name)) = self;
55        name
56    }
57}
58
59impl Argument {
60    /// The span for an argument
61    pub fn span(&self) -> Span {
62        match self {
63            Argument::Positional(e) => e.span,
64            Argument::Named((named, short, expr)) => {
65                let start = named.span.start;
66                let end = if let Some(expr) = expr {
67                    expr.span.end
68                } else if let Some(short) = short {
69                    short.span.end
70                } else {
71                    named.span.end
72                };
73
74                Span::new(start, end)
75            }
76            Argument::Unknown(e) => e.span,
77            Argument::Spread(e) => e.span,
78        }
79    }
80
81    pub fn expr(&self) -> Option<&Expression> {
82        match self {
83            Argument::Named((_, _, expr)) => expr.as_ref(),
84            Argument::Positional(expr) | Argument::Unknown(expr) | Argument::Spread(expr) => {
85                Some(expr)
86            }
87        }
88    }
89}
90
91/// Argument passed to an external command
92///
93/// Here the parsing rules slightly differ to directly pass strings to the external process
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
95pub enum ExternalArgument {
96    /// Expression that needs to be evaluated to turn into an external process argument
97    Regular(Expression),
98    /// Occurrence of a `...` spread operator that needs to be expanded
99    Spread(Expression),
100}
101
102impl ExternalArgument {
103    pub fn expr(&self) -> &Expression {
104        match self {
105            ExternalArgument::Regular(expr) => expr,
106            ExternalArgument::Spread(expr) => expr,
107        }
108    }
109}
110
111/// Parsed call of a `Command`
112///
113/// As we also implement some internal keywords in terms of the `Command` trait, this type stores the passed arguments as [`Expression`].
114/// Some of its methods lazily evaluate those to [`Value`] while others return the underlying
115/// [`Expression`].
116///
117/// For further utilities check the `nu_engine::CallExt` trait that extends [`Call`]
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119pub struct Call {
120    /// identifier of the declaration to call
121    pub decl_id: DeclId,
122    pub head: Span,
123    pub arguments: Vec<Argument>,
124    /// this field is used by the parser to pass additional command-specific information
125    pub parser_info: HashMap<String, Expression>,
126}
127
128impl Call {
129    pub fn new(head: Span) -> Call {
130        Self {
131            decl_id: DeclId::new(0),
132            head,
133            arguments: vec![],
134            parser_info: HashMap::new(),
135        }
136    }
137
138    /// The span encompassing the arguments
139    ///
140    /// If there are no arguments the span covers where the first argument would exist
141    ///
142    /// If there are one or more arguments the span encompasses the start of the first argument to
143    /// end of the last argument
144    pub fn arguments_span(&self) -> Span {
145        if self.arguments.is_empty() {
146            self.head.past()
147        } else {
148            Span::merge_many(self.arguments.iter().map(|a| a.span()))
149        }
150    }
151
152    pub fn named_iter(
153        &self,
154    ) -> impl DoubleEndedIterator<Item = &(Spanned<String>, Option<Spanned<String>>, Option<Expression>)>
155    {
156        self.arguments.iter().filter_map(|arg| match arg {
157            Argument::Named(named) => Some(named),
158            Argument::Positional(_) => None,
159            Argument::Unknown(_) => None,
160            Argument::Spread(_) => None,
161        })
162    }
163
164    pub fn named_iter_mut(
165        &mut self,
166    ) -> impl Iterator<Item = &mut (Spanned<String>, Option<Spanned<String>>, Option<Expression>)>
167    {
168        self.arguments.iter_mut().filter_map(|arg| match arg {
169            Argument::Named(named) => Some(named),
170            Argument::Positional(_) => None,
171            Argument::Unknown(_) => None,
172            Argument::Spread(_) => None,
173        })
174    }
175
176    pub fn named_len(&self) -> usize {
177        self.named_iter().count()
178    }
179
180    pub fn add_named(
181        &mut self,
182        named: (Spanned<String>, Option<Spanned<String>>, Option<Expression>),
183    ) {
184        self.arguments.push(Argument::Named(named));
185    }
186
187    pub fn add_positional(&mut self, positional: Expression) {
188        self.arguments.push(Argument::Positional(positional));
189    }
190
191    pub fn add_unknown(&mut self, unknown: Expression) {
192        self.arguments.push(Argument::Unknown(unknown));
193    }
194
195    pub fn add_spread(&mut self, args: Expression) {
196        self.arguments.push(Argument::Spread(args));
197    }
198
199    pub fn positional_iter(&self) -> impl Iterator<Item = &Expression> {
200        self.arguments
201            .iter()
202            .take_while(|arg| match arg {
203                Argument::Spread(_) => false, // Don't include positional arguments given to rest parameter
204                _ => true,
205            })
206            .filter_map(|arg| match arg {
207                Argument::Named(_) => None,
208                Argument::Positional(positional) => Some(positional),
209                Argument::Unknown(unknown) => Some(unknown),
210                Argument::Spread(_) => None,
211            })
212    }
213
214    /// Returns every argument to the rest parameter, as well as whether each argument
215    /// is spread or a normal positional argument (true for spread, false for normal)
216    pub fn rest_iter(&self, start: usize) -> impl Iterator<Item = (&Expression, bool)> {
217        // todo maybe rewrite to be more elegant or something
218        let args = self
219            .arguments
220            .iter()
221            .filter_map(|arg| match arg {
222                Argument::Named(_) => None,
223                Argument::Positional(positional) => Some((positional, false)),
224                Argument::Unknown(unknown) => Some((unknown, false)),
225                Argument::Spread(args) => Some((args, true)),
226            })
227            .collect::<Vec<_>>();
228        let spread_start = args.iter().position(|(_, spread)| *spread).unwrap_or(start);
229        args.into_iter().skip(start.min(spread_start))
230    }
231
232    pub fn get_parser_info(&self, name: &str) -> Option<&Expression> {
233        self.parser_info.get(name)
234    }
235
236    pub fn set_parser_info(&mut self, name: String, val: Expression) -> Option<Expression> {
237        self.parser_info.insert(name, val)
238    }
239
240    pub fn set_kth_argument(&mut self, k: usize, arg: Argument) -> bool {
241        self.arguments.get_mut(k).map(|a| *a = arg).is_some()
242    }
243
244    pub fn get_flag_expr(&self, flag_name: &str) -> Option<&Expression> {
245        for name in self.named_iter().rev() {
246            if flag_name == name.0.item {
247                return name.2.as_ref();
248            }
249        }
250
251        None
252    }
253
254    pub fn get_named_arg(&self, flag_name: &str) -> Option<Spanned<String>> {
255        for name in self.named_iter().rev() {
256            if flag_name == name.0.item {
257                return Some(name.0.clone());
258            }
259        }
260
261        None
262    }
263
264    /// Check if a boolean flag is set (i.e. `--bool` or `--bool=true`)
265    /// evaluating the expression after = as a constant command
266    pub fn has_flag_const(
267        &self,
268        working_set: &StateWorkingSet,
269        flag_name: &str,
270    ) -> Result<bool, ShellError> {
271        for name in self.named_iter() {
272            if flag_name == name.0.item {
273                return if let Some(expr) = &name.2 {
274                    // Check --flag=false
275                    let result = eval_constant(working_set, expr)?;
276                    match result {
277                        Value::Bool { val, .. } => Ok(val),
278                        _ => Err(ShellError::CantConvert {
279                            to_type: "bool".into(),
280                            from_type: result.get_type().to_string(),
281                            span: result.span(),
282                            help: Some("".into()),
283                        }),
284                    }
285                } else {
286                    Ok(true)
287                };
288            }
289        }
290
291        Ok(false)
292    }
293
294    pub fn get_flag_const<T: FromValue>(
295        &self,
296        working_set: &StateWorkingSet,
297        name: &str,
298    ) -> Result<Option<T>, ShellError> {
299        if let Some(expr) = self.get_flag_expr(name) {
300            let result = eval_constant(working_set, expr)?;
301            FromValue::from_value(result).map(Some)
302        } else {
303            Ok(None)
304        }
305    }
306
307    pub fn rest_const<T: FromValue>(
308        &self,
309        working_set: &StateWorkingSet,
310        starting_pos: usize,
311    ) -> Result<Vec<T>, ShellError> {
312        let mut output = vec![];
313
314        for result in
315            self.rest_iter_flattened(starting_pos, |expr| eval_constant(working_set, expr))?
316        {
317            output.push(FromValue::from_value(result)?);
318        }
319
320        Ok(output)
321    }
322
323    pub fn rest_iter_flattened<F>(
324        &self,
325        start: usize,
326        mut eval: F,
327    ) -> Result<Vec<Value>, ShellError>
328    where
329        F: FnMut(&Expression) -> Result<Value, ShellError>,
330    {
331        let mut output = Vec::new();
332
333        for (expr, spread) in self.rest_iter(start) {
334            let result = eval(expr)?;
335            if spread {
336                match result {
337                    Value::List { vals, .. } => output.extend(vals),
338                    Value::Nothing { .. } => (),
339                    _ => return Err(ShellError::CannotSpreadAsList { span: expr.span }),
340                }
341            } else {
342                output.push(result);
343            }
344        }
345
346        Ok(output)
347    }
348
349    pub fn req_const<T: FromValue>(
350        &self,
351        working_set: &StateWorkingSet,
352        pos: usize,
353    ) -> Result<T, ShellError> {
354        let expr = self.positional_iter().nth(pos).ok_or_else(|| {
355            match self.positional_iter().count().checked_sub(1) {
356                None => ShellError::AccessEmptyContent { span: self.head },
357                Some(n) => ShellError::AccessBeyondEnd {
358                    max_idx: n,
359                    span: self.head,
360                },
361            }
362        })?;
363
364        let result = eval_constant(working_set, expr)?;
365        FromValue::from_value(result)
366    }
367
368    pub fn span(&self) -> Span {
369        self.head.merge(self.arguments_span())
370    }
371}
372
373#[cfg(test)]
374mod test {
375    use super::*;
376    use crate::engine::EngineState;
377
378    #[test]
379    fn argument_span_named() {
380        let engine_state = EngineState::new();
381        let mut working_set = StateWorkingSet::new(&engine_state);
382
383        let named = Spanned {
384            item: "named".to_string(),
385            span: Span::new(2, 3),
386        };
387        let short = Spanned {
388            item: "short".to_string(),
389            span: Span::new(5, 7),
390        };
391        let expr = Expression::garbage(&mut working_set, Span::new(11, 13));
392
393        let arg = Argument::Named((named.clone(), None, None));
394
395        assert_eq!(Span::new(2, 3), arg.span());
396
397        let arg = Argument::Named((named.clone(), Some(short.clone()), None));
398
399        assert_eq!(Span::new(2, 7), arg.span());
400
401        let arg = Argument::Named((named.clone(), None, Some(expr.clone())));
402
403        assert_eq!(Span::new(2, 13), arg.span());
404
405        let arg = Argument::Named((named.clone(), Some(short.clone()), Some(expr.clone())));
406
407        assert_eq!(Span::new(2, 13), arg.span());
408    }
409
410    #[test]
411    fn argument_span_positional() {
412        let engine_state = EngineState::new();
413        let mut working_set = StateWorkingSet::new(&engine_state);
414
415        let span = Span::new(2, 3);
416        let expr = Expression::garbage(&mut working_set, span);
417        let arg = Argument::Positional(expr);
418
419        assert_eq!(span, arg.span());
420    }
421
422    #[test]
423    fn argument_span_unknown() {
424        let engine_state = EngineState::new();
425        let mut working_set = StateWorkingSet::new(&engine_state);
426
427        let span = Span::new(2, 3);
428        let expr = Expression::garbage(&mut working_set, span);
429        let arg = Argument::Unknown(expr);
430
431        assert_eq!(span, arg.span());
432    }
433
434    #[test]
435    fn call_arguments_span() {
436        let engine_state = EngineState::new();
437        let mut working_set = StateWorkingSet::new(&engine_state);
438
439        let mut call = Call::new(Span::new(0, 1));
440        call.add_positional(Expression::garbage(&mut working_set, Span::new(2, 3)));
441        call.add_positional(Expression::garbage(&mut working_set, Span::new(5, 7)));
442
443        assert_eq!(Span::new(2, 7), call.arguments_span());
444    }
445}