Skip to main content

nu_protocol/
signature.rs

1use crate::{
2    BlockId, CompareTypes, DeclId, DeprecationEntry, Example, FromValue, IntoValue, PipelineData,
3    ShellError, Span, SyntaxShape, Type, TypeSet, Value, VarId,
4    engine::{Call, Command, CommandType, EngineState, Stack},
5    shell_error::generic::GenericError,
6};
7use nu_derive_value::FromValue as DeriveFromValue;
8use nu_utils::NuCow;
9use serde::{Deserialize, Serialize};
10use std::fmt::Write;
11
12// Make nu_protocol available in this namespace, consumers of this crate will
13// have this without such an export.
14// The `FromValue` derive macro fully qualifies paths to "nu_protocol".
15use crate as nu_protocol;
16
17pub enum Parameter {
18    Required(PositionalArg),
19    Optional(PositionalArg),
20    Rest(PositionalArg),
21    Flag(Flag),
22}
23
24impl From<Flag> for Parameter {
25    fn from(value: Flag) -> Self {
26        Self::Flag(value)
27    }
28}
29
30/// The signature definition of a named flag that either accepts a value or acts as a toggle flag
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub struct Flag {
33    pub long: String,
34    pub short: Option<char>,
35    pub arg: Option<SyntaxShape>,
36    pub required: bool,
37    pub desc: String,
38    pub completion: Option<Completion>,
39
40    // For custom commands
41    pub var_id: Option<VarId>,
42    pub default_value: Option<Value>,
43}
44
45impl Flag {
46    /// The flag's long name, or `None` for a short-only flag (whose `long` is empty).
47    #[inline]
48    pub fn long_name(&self) -> Option<&str> {
49        (!self.long.is_empty()).then_some(self.long.as_str())
50    }
51
52    /// Whether this flag's value type accepts `nothing`/`null`.
53    ///
54    /// Used so `--flag=$null` can either pass `null` through (when the type allows it) or omit
55    /// the flag (when it does not). Switches (`arg: None`) never accept nothing — null means omit.
56    #[inline]
57    pub fn type_accepts_nothing(&self) -> bool {
58        match &self.arg {
59            Some(shape) => Type::Nothing.is_assignable_to(&shape.to_type()),
60            None => false,
61        }
62    }
63
64    #[inline]
65    pub fn new(long: impl Into<String>) -> Self {
66        Flag {
67            long: long.into(),
68            short: None,
69            arg: None,
70            required: false,
71            desc: String::new(),
72            completion: None,
73            var_id: None,
74            default_value: None,
75        }
76    }
77
78    #[inline]
79    pub fn short(self, short: char) -> Self {
80        Self {
81            short: Some(short),
82            ..self
83        }
84    }
85
86    #[inline]
87    pub fn arg(self, arg: SyntaxShape) -> Self {
88        Self {
89            arg: Some(arg),
90            ..self
91        }
92    }
93
94    #[inline]
95    pub fn required(self) -> Self {
96        Self {
97            required: true,
98            ..self
99        }
100    }
101
102    #[inline]
103    pub fn desc(self, desc: impl Into<String>) -> Self {
104        Self {
105            desc: desc.into(),
106            ..self
107        }
108    }
109
110    #[inline]
111    pub fn completion(self, completion: Completion) -> Self {
112        Self {
113            completion: Some(completion),
114            ..self
115        }
116    }
117}
118
119/// The signature definition for a positional argument
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121pub struct PositionalArg {
122    pub name: String,
123    pub desc: String,
124    pub shape: SyntaxShape,
125    pub completion: Option<Completion>,
126
127    // For custom commands
128    pub var_id: Option<VarId>,
129    pub default_value: Option<Value>,
130}
131
132impl PositionalArg {
133    #[inline]
134    pub fn new(name: impl Into<String>, shape: SyntaxShape) -> Self {
135        Self {
136            name: name.into(),
137            desc: String::new(),
138            shape,
139            completion: None,
140            var_id: None,
141            default_value: None,
142        }
143    }
144
145    #[inline]
146    pub fn desc(self, desc: impl Into<String>) -> Self {
147        Self {
148            desc: desc.into(),
149            ..self
150        }
151    }
152
153    #[inline]
154    pub fn completion(self, completion: Completion) -> Self {
155        Self {
156            completion: Some(completion),
157            ..self
158        }
159    }
160
161    #[inline]
162    pub fn required(self) -> Parameter {
163        Parameter::Required(self)
164    }
165
166    #[inline]
167    pub fn optional(self) -> Parameter {
168        Parameter::Optional(self)
169    }
170
171    #[inline]
172    pub fn rest(self) -> Parameter {
173        Parameter::Rest(self)
174    }
175}
176
177#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
178pub enum CommandWideCompleter {
179    External,
180    Command(DeclId),
181}
182
183/// A built-in completion a command declares for one of its arguments, dispatched on by the
184/// completer so renaming the command can't silently disable its argument completion.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
186pub enum BuiltinCompletion {
187    /// A `.nu` file or directory (`use`, `overlay use`, `source-env`); `std_virtual_path`
188    /// also offers the virtual `std/` modules (disabled for `source-env`).
189    NuFile { std_virtual_path: bool },
190    /// The exported members of an already-named module (`use spam <tab>`).
191    ModuleExports,
192    /// An environment variable name (`hide-env`).
193    EnvVar,
194    /// A command name; `internal_only` restricts to internal commands (`attr complete`).
195    Command { internal_only: bool },
196}
197
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub enum Completion {
200    Command(DeclId),
201    List(NuCow<&'static [&'static str], Vec<String>>),
202    /// A completion the engine provides for the argument (module/env/command names, …).
203    Builtin(BuiltinCompletion),
204}
205
206impl Completion {
207    pub const fn new_list(list: &'static [&'static str]) -> Self {
208        Self::List(NuCow::Borrowed(list))
209    }
210
211    pub fn to_value(&self, engine_state: &EngineState, span: Span) -> Value {
212        match self {
213            Completion::Command(id) => engine_state
214                .get_decl(*id)
215                .name()
216                .to_owned()
217                .into_value(span),
218            // No list to surface; name it so `scope commands` stays honest.
219            Completion::Builtin(kind) => Value::string(
220                match kind {
221                    BuiltinCompletion::NuFile { .. } => "<nu-file>",
222                    BuiltinCompletion::ModuleExports => "<module-exports>",
223                    BuiltinCompletion::EnvVar => "<env-var>",
224                    BuiltinCompletion::Command { .. } => "<command-name>",
225                },
226                span,
227            ),
228            Completion::List(list) => match list {
229                NuCow::Borrowed(list) => list
230                    .iter()
231                    .map(|&e| e.into_value(span))
232                    .collect::<Vec<Value>>()
233                    .into_value(span),
234                NuCow::Owned(list) => list
235                    .iter()
236                    .cloned()
237                    .map(|e| e.into_value(span))
238                    .collect::<Vec<Value>>()
239                    .into_value(span),
240            },
241        }
242    }
243}
244
245/// Command categories
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247pub enum Category {
248    Bits,
249    Bytes,
250    Chart,
251    Conversions,
252    Core,
253    Custom(String),
254    Database,
255    Date,
256    Debug,
257    Default,
258    Deprecated,
259    Removed,
260    Env,
261    Experimental,
262    FileSystem,
263    Filters,
264    Formats,
265    Generators,
266    Hash,
267    History,
268    Math,
269    Misc,
270    Network,
271    Path,
272    Platform,
273    Plugin,
274    Random,
275    Shells,
276    Strings,
277    System,
278    Viewers,
279}
280
281impl std::fmt::Display for Category {
282    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
283        let msg = match self {
284            Category::Bits => "bits",
285            Category::Bytes => "bytes",
286            Category::Chart => "chart",
287            Category::Conversions => "conversions",
288            Category::Core => "core",
289            Category::Custom(name) => name,
290            Category::Database => "database",
291            Category::Date => "date",
292            Category::Debug => "debug",
293            Category::Default => "default",
294            Category::Deprecated => "deprecated",
295            Category::Removed => "removed",
296            Category::Env => "env",
297            Category::Experimental => "experimental",
298            Category::FileSystem => "filesystem",
299            Category::Filters => "filters",
300            Category::Formats => "formats",
301            Category::Generators => "generators",
302            Category::Hash => "hash",
303            Category::History => "history",
304            Category::Math => "math",
305            Category::Misc => "misc",
306            Category::Network => "network",
307            Category::Path => "path",
308            Category::Platform => "platform",
309            Category::Plugin => "plugin",
310            Category::Random => "random",
311            Category::Shells => "shells",
312            Category::Strings => "strings",
313            Category::System => "system",
314            Category::Viewers => "viewers",
315        };
316
317        write!(f, "{msg}")
318    }
319}
320
321pub fn category_from_string(category: &str) -> Category {
322    match category {
323        "bits" => Category::Bits,
324        "bytes" => Category::Bytes,
325        "chart" => Category::Chart,
326        "conversions" => Category::Conversions,
327        // Let's protect our own "core" commands by preventing scripts from having this category.
328        "core" => Category::Custom("custom_core".to_string()),
329        "database" => Category::Database,
330        "date" => Category::Date,
331        "debug" => Category::Debug,
332        "default" => Category::Default,
333        "deprecated" => Category::Deprecated,
334        "removed" => Category::Removed,
335        "env" => Category::Env,
336        "experimental" => Category::Experimental,
337        "filesystem" => Category::FileSystem,
338        "filter" => Category::Filters,
339        "formats" => Category::Formats,
340        "generators" => Category::Generators,
341        "hash" => Category::Hash,
342        "history" => Category::History,
343        "math" => Category::Math,
344        "misc" => Category::Misc,
345        "network" => Category::Network,
346        "path" => Category::Path,
347        "platform" => Category::Platform,
348        "plugin" => Category::Plugin,
349        "random" => Category::Random,
350        "shells" => Category::Shells,
351        "strings" => Category::Strings,
352        "system" => Category::System,
353        "viewers" => Category::Viewers,
354        _ => Category::Custom(category.to_string()),
355    }
356}
357
358/// Signature information of a [`Command`]
359#[derive(Clone, Debug, Serialize, Deserialize)]
360pub struct Signature {
361    pub name: String,
362    pub description: String,
363    pub extra_description: String,
364    pub search_terms: Vec<String>,
365    pub required_positional: Vec<PositionalArg>,
366    pub optional_positional: Vec<PositionalArg>,
367    pub rest_positional: Option<PositionalArg>,
368    pub named: Vec<Flag>,
369    pub input_output_types: Vec<(Type, Type)>,
370    pub allow_variants_without_examples: bool,
371    pub is_filter: bool,
372    pub creates_scope: bool,
373    pub allows_unknown_args: bool,
374    /// Set by `extern --strict`: a flag the signature doesn't declare is a parse error, even
375    /// though `allows_unknown_args` still passes `--` and other arguments through.
376    #[serde(default)]
377    pub rejects_unknown_flags: bool,
378    pub complete: Option<CommandWideCompleter>,
379    // Signature category used to classify commands stored in the list of declarations
380    pub category: Category,
381}
382
383impl PartialEq for Signature {
384    fn eq(&self, other: &Self) -> bool {
385        self.name == other.name
386            && self.description == other.description
387            && self.required_positional == other.required_positional
388            && self.optional_positional == other.optional_positional
389            && self.rest_positional == other.rest_positional
390            && self.is_filter == other.is_filter
391    }
392}
393
394impl Eq for Signature {}
395
396fn type_involves_custom(ty: &Type) -> bool {
397    match ty {
398        Type::Custom(_) => true,
399        Type::OneOf(types) => types.iter().any(type_involves_custom),
400        Type::List(inner) => type_involves_custom(inner),
401        _ => false,
402    }
403}
404
405fn is_structured_type(ty: &Type) -> bool {
406    matches!(ty, Type::List(_) | Type::Table(_) | Type::Record(_))
407}
408
409/// Custom values are assignable to list/table/record so `get` / `into record` type-check.
410/// That special case must not steal the output type of a real custom IO pair
411/// (`semver | into string` is a string, not `oneof<list, table, record>`).
412///
413/// A union input is checked one member at a time. The pair is a fallback only when every member
414/// that is assignable to `declared` gets there through that special case. Comparing the whole
415/// union drops real pairs, such as the `list<any>` pair of `update` for
416/// `oneof<list<int>, matrix>` input. Callers check that `input` is assignable to `declared`
417/// first, so at least one member is.
418fn is_custom_structured_fallback(input: &Type, declared: &Type) -> bool {
419    if !type_involves_custom(input) || !is_structured_type(declared) {
420        return false;
421    }
422    match input {
423        Type::OneOf(types) => types
424            .iter()
425            .filter(|ty| ty.is_assignable_to(declared))
426            .all(|ty| is_custom_structured_fallback(ty, declared)),
427        _ => input.compare_types(declared).is_none(),
428    }
429}
430
431impl Signature {
432    /// Creates a new signature for a command with `name`
433    pub fn new(name: impl Into<String>) -> Signature {
434        Signature {
435            name: name.into(),
436            description: String::new(),
437            extra_description: String::new(),
438            search_terms: vec![],
439            required_positional: vec![],
440            optional_positional: vec![],
441            rest_positional: None,
442            input_output_types: vec![],
443            allow_variants_without_examples: false,
444            named: vec![],
445            is_filter: false,
446            creates_scope: false,
447            category: Category::Default,
448            allows_unknown_args: false,
449            rejects_unknown_flags: false,
450            complete: None,
451        }
452    }
453
454    /// Gets the input type from the signature
455    ///
456    /// - If the input was unspecified  [`Type::Any`] is returned.
457    /// - If the signature has a single input type, it is returned.
458    /// - If there are multiple input types, a [union](Type::union) of them is returned.
459    pub fn get_input_type(&self) -> Type {
460        match self.input_output_types.as_slice() {
461            [] => Type::Any,
462            [(input, _output)] => input.clone(),
463            multiple => Type::one_of(multiple.iter().map(|(input, _)| input.clone())),
464        }
465    }
466
467    /// Gets the output type from the signature based on `input`
468    ///
469    /// - If the signature's output was unspecified [`Type::Any`] is returned.
470    /// - If `input` is [`None`], it's treated as [`Type::Any`]. i.e. all IO pairs are considered.
471    /// - IO pairs where the given `input` is [assignable to](crate::CompareTypes::is_assignable_to)
472    ///   the input type are considered valid.
473    /// - Custom values are assignable to list/table/record. Those fallback pairs are ignored
474    ///   when a lattice match exists (so `semver | into string` is `string`).
475    /// - [Union](TypeSet::union) of remaining outputs is returned.
476    /// - If there are no valid IO pairs for the given `input`, [`None`] is returned.
477    // XXX: remove?
478    pub fn get_output_type(&self, input_type: Option<&Type>) -> Option<Type> {
479        if self.input_output_types.is_empty() {
480            return Some(Type::Any);
481        }
482        let input = input_type.unwrap_or(&Type::Any);
483        // Entries whose input type accepts `input` are the candidates; among those, the ones
484        // that are not merely a structured-type fallback for a custom value are preferred. Two
485        // passes without temporary collections: this runs for every call the parser
486        // type-checks.
487        let mut any_match = false;
488        let mut any_strict_match = false;
489        for (in_ty, _) in &self.input_output_types {
490            if input.is_assignable_to(in_ty) {
491                any_match = true;
492                if !is_custom_structured_fallback(input, in_ty) {
493                    any_strict_match = true;
494                    break;
495                }
496            }
497        }
498        if !any_match {
499            return None;
500        }
501
502        self.input_output_types
503            .iter()
504            .filter(|(in_ty, _)| {
505                input.is_assignable_to(in_ty)
506                    && (!any_strict_match || !is_custom_structured_fallback(input, in_ty))
507            })
508            .map(|(_, out)| out.clone())
509            .reduce(Type::union)
510    }
511
512    /// Add a default help option to a signature
513    pub fn add_help(mut self) -> Signature {
514        // default help flag
515        let flag = Flag {
516            long: "help".into(),
517            short: Some('h'),
518            arg: None,
519            desc: "Display the help message for this command".into(),
520            required: false,
521            var_id: None,
522            default_value: None,
523            completion: None,
524        };
525        self.named.push(flag);
526        self
527    }
528
529    /// Build an internal signature with default help option
530    ///
531    /// This is equivalent to `Signature::new(name).add_help()`.
532    pub fn build(name: impl Into<String>) -> Signature {
533        Signature::new(name.into()).add_help()
534    }
535
536    /// Add a description to the signature
537    ///
538    /// This should be a single sentence as it is the part shown for example in the completion
539    /// menu.
540    pub fn description(mut self, msg: impl Into<String>) -> Signature {
541        self.description = msg.into();
542        self
543    }
544
545    /// Add an extra description to the signature.
546    ///
547    /// Here additional documentation can be added
548    pub fn extra_description(mut self, msg: impl Into<String>) -> Signature {
549        self.extra_description = msg.into();
550        self
551    }
552
553    /// Add search terms to the signature
554    pub fn search_terms(mut self, terms: Vec<String>) -> Signature {
555        self.search_terms = terms;
556        self
557    }
558
559    /// Update signature's fields from a Command trait implementation
560    pub fn update_from_command(mut self, command: &dyn Command) -> Signature {
561        self.search_terms = command
562            .search_terms()
563            .into_iter()
564            .map(|term| term.to_string())
565            .collect();
566        self.extra_description = command.extra_description().to_string();
567        self.description = command.description().to_string();
568        self
569    }
570
571    /// Allow unknown signature parameters
572    pub fn allows_unknown_args(mut self) -> Signature {
573        self.allows_unknown_args = true;
574        self
575    }
576
577    pub fn param(mut self, param: impl Into<Parameter>) -> Self {
578        let param: Parameter = param.into();
579        match param {
580            Parameter::Flag(flag) => {
581                if let Some(s) = flag.short {
582                    assert!(
583                        !self.get_shorts().contains(&s),
584                        "There may be duplicate short flags for '-{s}'"
585                    );
586                }
587
588                let name = flag.long.as_str();
589                assert!(
590                    !self.get_names().contains(&name),
591                    "There may be duplicate name flags for '--{name}'"
592                );
593
594                self.named.push(flag);
595            }
596            Parameter::Required(positional_arg) => {
597                self.required_positional.push(positional_arg);
598            }
599            Parameter::Optional(positional_arg) => {
600                self.optional_positional.push(positional_arg);
601            }
602            Parameter::Rest(positional_arg) => {
603                assert!(
604                    self.rest_positional.is_none(),
605                    "Tried to set rest arguments more than once"
606                );
607                self.rest_positional = Some(positional_arg);
608            }
609        }
610        self
611    }
612
613    /// Add a required positional argument to the signature
614    pub fn required(
615        mut self,
616        name: impl Into<String>,
617        shape: impl Into<SyntaxShape>,
618        desc: impl Into<String>,
619    ) -> Signature {
620        self.required_positional.push(PositionalArg {
621            name: name.into(),
622            desc: desc.into(),
623            shape: shape.into(),
624            var_id: None,
625            default_value: None,
626            completion: None,
627        });
628
629        self
630    }
631
632    /// Add an optional positional argument to the signature
633    pub fn optional(
634        mut self,
635        name: impl Into<String>,
636        shape: impl Into<SyntaxShape>,
637        desc: impl Into<String>,
638    ) -> Signature {
639        self.optional_positional.push(PositionalArg {
640            name: name.into(),
641            desc: desc.into(),
642            shape: shape.into(),
643            var_id: None,
644            default_value: None,
645            completion: None,
646        });
647
648        self
649    }
650
651    /// Add a rest positional parameter
652    ///
653    /// Rest positionals (also called [rest parameters][rp]) are treated as
654    /// optional: passing 0 arguments is a valid call.  If the command requires
655    /// at least one argument, it must be checked by the implementation.
656    ///
657    /// [rp]: https://www.nushell.sh/book/custom_commands.html#rest-parameters
658    pub fn rest(
659        mut self,
660        name: &str,
661        shape: impl Into<SyntaxShape>,
662        desc: impl Into<String>,
663    ) -> Signature {
664        self.rest_positional = Some(PositionalArg {
665            name: name.into(),
666            desc: desc.into(),
667            shape: shape.into(),
668            var_id: None,
669            default_value: None,
670            completion: None,
671        });
672
673        self
674    }
675
676    /// Is this command capable of operating on its input via cell paths?
677    pub fn operates_on_cell_paths(&self) -> bool {
678        self.required_positional
679            .iter()
680            .chain(self.rest_positional.iter())
681            .any(|pos| {
682                matches!(
683                    pos,
684                    PositionalArg {
685                        shape: SyntaxShape::CellPath,
686                        ..
687                    }
688                )
689            })
690    }
691
692    /// Add an optional named flag argument to the signature
693    pub fn named(
694        mut self,
695        name: impl Into<String>,
696        shape: impl Into<SyntaxShape>,
697        desc: impl Into<String>,
698        short: Option<char>,
699    ) -> Signature {
700        let (name, s) = self.check_names(name, short);
701
702        self.named.push(Flag {
703            long: name,
704            short: s,
705            arg: Some(shape.into()),
706            required: false,
707            desc: desc.into(),
708            var_id: None,
709            default_value: None,
710            completion: None,
711        });
712
713        self
714    }
715
716    /// Add a required named flag argument to the signature
717    pub fn required_named(
718        mut self,
719        name: impl Into<String>,
720        shape: impl Into<SyntaxShape>,
721        desc: impl Into<String>,
722        short: Option<char>,
723    ) -> Signature {
724        let (name, s) = self.check_names(name, short);
725
726        self.named.push(Flag {
727            long: name,
728            short: s,
729            arg: Some(shape.into()),
730            required: true,
731            desc: desc.into(),
732            var_id: None,
733            default_value: None,
734            completion: None,
735        });
736
737        self
738    }
739
740    /// Add a switch to the signature
741    pub fn switch(
742        mut self,
743        name: impl Into<String>,
744        desc: impl Into<String>,
745        short: Option<char>,
746    ) -> Signature {
747        let (name, s) = self.check_names(name, short);
748
749        self.named.push(Flag {
750            long: name,
751            short: s,
752            arg: None,
753            required: false,
754            desc: desc.into(),
755            var_id: None,
756            default_value: None,
757            completion: None,
758        });
759
760        self
761    }
762
763    /// Changes the input type of the command signature
764    pub fn input_output_type(mut self, input_type: Type, output_type: Type) -> Signature {
765        self.input_output_types.push((input_type, output_type));
766        self
767    }
768
769    /// Set the input-output type signature variants of the command
770    pub fn input_output_types(mut self, input_output_types: Vec<(Type, Type)>) -> Signature {
771        self.input_output_types = input_output_types;
772        self
773    }
774
775    /// Changes the signature category
776    pub fn category(mut self, category: Category) -> Signature {
777        self.category = category;
778
779        self
780    }
781
782    /// Sets that signature will create a scope as it parses
783    pub fn creates_scope(mut self) -> Signature {
784        self.creates_scope = true;
785        self
786    }
787
788    // Is it allowed for the type signature to feature a variant that has no corresponding example?
789    pub fn allow_variants_without_examples(mut self, allow: bool) -> Signature {
790        self.allow_variants_without_examples = allow;
791        self
792    }
793
794    /// A string rendering of the command signature
795    ///
796    /// If the command has flags, all of them will be shown together as
797    /// `{flags}`.
798    pub fn call_signature(&self) -> String {
799        let mut one_liner = String::new();
800        one_liner.push_str(&self.name);
801        one_liner.push(' ');
802
803        // Note: the call signature needs flags first because on the nu commandline,
804        // flags will precede the script file name. Flags for internal commands can come
805        // either before or after (or around) positional parameters, so there isn't a strong
806        // preference, so we default to the more constrained example.
807        if self.named.len() > 1 {
808            one_liner.push_str("{flags} ");
809        }
810
811        for positional in &self.required_positional {
812            one_liner.push_str(&get_positional_short_name(positional, true));
813        }
814        for positional in &self.optional_positional {
815            one_liner.push_str(&get_positional_short_name(positional, false));
816        }
817
818        if let Some(rest) = &self.rest_positional {
819            let _ = write!(one_liner, "...{}", get_positional_short_name(rest, false));
820        }
821
822        // if !self.subcommands.is_empty() {
823        //     one_liner.push_str("<subcommand> ");
824        // }
825
826        one_liner
827    }
828
829    /// Get list of the short-hand flags
830    pub fn get_shorts(&self) -> Vec<char> {
831        self.named.iter().filter_map(|f| f.short).collect()
832    }
833
834    /// Get list of the long-hand flags
835    pub fn get_names(&self) -> Vec<&str> {
836        self.named.iter().map(|f| f.long.as_str()).collect()
837    }
838
839    /// Checks if short or long options are already present
840    ///
841    /// ## Panics
842    ///
843    /// Panics if one of them is found.
844    // XXX: return result instead of a panic
845    fn check_names(&self, name: impl Into<String>, short: Option<char>) -> (String, Option<char>) {
846        let s = short.inspect(|c| {
847            assert!(
848                !self.get_shorts().contains(c),
849                "There may be duplicate short flags for '-{c}'"
850            );
851        });
852
853        let name = {
854            let name: String = name.into();
855            assert!(
856                !self.get_names().contains(&name.as_str()),
857                "There may be duplicate name flags for '--{name}'"
858            );
859            name
860        };
861
862        (name, s)
863    }
864
865    /// Returns an argument with the index `position`
866    ///
867    /// It will index, in order, required arguments, then optional, then the
868    /// trailing `...rest` argument. Note that the `...rest` argument must be
869    /// a [`Value::List`], therefore this method may not work as intended when
870    /// the closure uses a rest argument.
871    pub fn get_positional(&self, position: usize) -> Option<&PositionalArg> {
872        if position < self.required_positional.len() {
873            self.required_positional.get(position)
874        } else if position < (self.required_positional.len() + self.optional_positional.len()) {
875            self.optional_positional
876                .get(position - self.required_positional.len())
877        } else {
878            self.rest_positional.as_ref()
879        }
880    }
881
882    /// Returns the number of (optional) positional parameters in a signature
883    ///
884    /// This does _not_ include the `...rest` parameter, even if it's present.
885    pub fn num_positionals(&self) -> usize {
886        let mut total = self.required_positional.len() + self.optional_positional.len();
887
888        for positional in &self.required_positional {
889            if let SyntaxShape::Keyword(..) = positional.shape {
890                // Keywords have a required argument, so account for that
891                total += 1;
892            }
893        }
894        for positional in &self.optional_positional {
895            if let SyntaxShape::Keyword(..) = positional.shape {
896                // Keywords have a required argument, so account for that
897                total += 1;
898            }
899        }
900        total
901    }
902
903    /// Find the matching long flag
904    pub fn get_long_flag(&self, name: &str) -> Option<Flag> {
905        if name.is_empty() {
906            return None;
907        }
908        for flag in &self.named {
909            if flag.long == name {
910                return Some(flag.clone());
911            }
912        }
913        None
914    }
915
916    /// Find the matching long flag
917    pub fn get_short_flag(&self, short: char) -> Option<Flag> {
918        for flag in &self.named {
919            if let Some(short_flag) = &flag.short
920                && *short_flag == short
921            {
922                return Some(flag.clone());
923            }
924        }
925        None
926    }
927
928    /// Set the filter flag for the signature
929    pub fn filter(mut self) -> Signature {
930        self.is_filter = true;
931        self
932    }
933
934    /// Create a placeholder implementation of Command as a way to predeclare a definition's
935    /// signature so other definitions can see it. This placeholder is later replaced with the
936    /// full definition in a second pass of the parser.
937    pub fn predeclare(self) -> Box<dyn Command> {
938        self.predeclare_with_command_type(CommandType::Builtin)
939    }
940
941    /// Create a placeholder implementation of Command as a way to predeclare a definition's
942    /// signature with an explicit command type.
943    pub fn predeclare_with_command_type(self, command_type: CommandType) -> Box<dyn Command> {
944        Box::new(Predeclaration {
945            signature: self,
946            command_type,
947        })
948    }
949
950    /// Combines a signature and a block into a runnable block
951    pub fn into_block_command(
952        self,
953        block_id: BlockId,
954        attributes: Vec<(String, Value)>,
955        examples: Vec<CustomExample>,
956    ) -> Box<dyn Command> {
957        Box::new(BlockCommand {
958            signature: self,
959            block_id,
960            attributes,
961            examples,
962        })
963    }
964}
965
966#[derive(Clone)]
967struct Predeclaration {
968    signature: Signature,
969    command_type: CommandType,
970}
971
972impl Command for Predeclaration {
973    fn name(&self) -> &str {
974        &self.signature.name
975    }
976
977    fn signature(&self) -> Signature {
978        self.signature.clone()
979    }
980
981    fn description(&self) -> &str {
982        &self.signature.description
983    }
984
985    fn extra_description(&self) -> &str {
986        &self.signature.extra_description
987    }
988
989    fn run(
990        &self,
991        _engine_state: &EngineState,
992        _stack: &mut Stack,
993        call: &Call,
994        _input: PipelineData,
995    ) -> Result<PipelineData, crate::ShellError> {
996        // A call can only resolve to a predeclaration whose `def` never defined it; report that
997        // instead of panicking on the user's input.
998        Err(crate::ShellError::NushellFailedSpanned {
999            msg: "Can't run a predeclaration without a body".to_string(),
1000            label: "originates from here".to_string(),
1001            span: call.head,
1002        })
1003    }
1004
1005    fn command_type(&self) -> CommandType {
1006        self.command_type
1007    }
1008}
1009
1010fn get_positional_short_name(arg: &PositionalArg, is_required: bool) -> String {
1011    match &arg.shape {
1012        SyntaxShape::Keyword(name, ..) => {
1013            if is_required {
1014                format!("{} <{}> ", String::from_utf8_lossy(name), arg.name)
1015            } else {
1016                format!("({} <{}>) ", String::from_utf8_lossy(name), arg.name)
1017            }
1018        }
1019        _ => {
1020            if is_required {
1021                format!("<{}> ", arg.name)
1022            } else {
1023                format!("({}) ", arg.name)
1024            }
1025        }
1026    }
1027}
1028
1029#[derive(Clone, DeriveFromValue)]
1030pub struct CustomExample {
1031    pub example: String,
1032    pub description: String,
1033    pub result: Option<Value>,
1034}
1035
1036impl CustomExample {
1037    pub fn to_example(&self) -> Example<'_> {
1038        Example {
1039            example: self.example.as_str(),
1040            description: self.description.as_str(),
1041            result: self.result.clone(),
1042        }
1043    }
1044}
1045
1046#[derive(Clone)]
1047struct BlockCommand {
1048    signature: Signature,
1049    block_id: BlockId,
1050    attributes: Vec<(String, Value)>,
1051    examples: Vec<CustomExample>,
1052}
1053
1054impl Command for BlockCommand {
1055    fn name(&self) -> &str {
1056        &self.signature.name
1057    }
1058
1059    fn signature(&self) -> Signature {
1060        self.signature.clone()
1061    }
1062
1063    fn description(&self) -> &str {
1064        &self.signature.description
1065    }
1066
1067    fn extra_description(&self) -> &str {
1068        &self.signature.extra_description
1069    }
1070
1071    fn run(
1072        &self,
1073        _engine_state: &EngineState,
1074        _stack: &mut Stack,
1075        _call: &Call,
1076        _input: PipelineData,
1077    ) -> Result<crate::PipelineData, crate::ShellError> {
1078        Err(ShellError::Generic(GenericError::new_internal(
1079            "Internal error: can't run custom command with 'run', use block_id",
1080            "",
1081        )))
1082    }
1083
1084    fn command_type(&self) -> CommandType {
1085        CommandType::Custom
1086    }
1087
1088    fn block_id(&self) -> Option<BlockId> {
1089        Some(self.block_id)
1090    }
1091
1092    fn attributes(&self) -> Vec<(String, Value)> {
1093        self.attributes.clone()
1094    }
1095
1096    fn examples(&self) -> Vec<Example<'_>> {
1097        self.examples
1098            .iter()
1099            .map(CustomExample::to_example)
1100            .collect()
1101    }
1102
1103    fn search_terms(&self) -> Vec<&str> {
1104        self.signature
1105            .search_terms
1106            .iter()
1107            .map(String::as_str)
1108            .collect()
1109    }
1110
1111    fn deprecation_info(&self) -> Vec<DeprecationEntry> {
1112        self.attributes
1113            .iter()
1114            .filter_map(|(key, value)| {
1115                (key == "deprecated")
1116                    .then_some(value.clone())
1117                    .map(DeprecationEntry::from_value)
1118                    .and_then(Result::ok)
1119            })
1120            .collect()
1121    }
1122}