Skip to main content

nu_protocol/
syntax_shape.rs

1use crate::{CollectionColumns, Type};
2use serde::{Deserialize, Serialize};
3use std::fmt::Display;
4
5/// The syntactic shapes that describe how a sequence should be parsed.
6///
7/// This extends beyond [`Type`] which describes how [`Value`](crate::Value)s are represented.
8/// `SyntaxShape`s can describe the parsing rules for arguments to a command.
9/// e.g. [`SyntaxShape::GlobPattern`]/[`SyntaxShape::Filepath`] serve the completer,
10/// but don't have an associated [`Value`](crate::Value)
11/// There are additional `SyntaxShape`s that only make sense in particular expressions or keywords
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub enum SyntaxShape {
14    /// Any syntactic form is allowed
15    Any,
16
17    /// A plugin-defined custom value, named by its `CustomValue::type_name`
18    /// (e.g. `polars_dataframe`).
19    Custom(Box<str>),
20
21    /// A binary literal
22    Binary,
23
24    /// A block is allowed, eg `{start this thing}`
25    Block,
26
27    /// A boolean value, eg `true` or `false`
28    Boolean,
29
30    /// A dotted path to navigate the table
31    CellPath,
32
33    /// A closure is allowed, eg `{|| start this thing}`
34    Closure(Option<Vec<SyntaxShape>>),
35
36    /// A datetime value, eg `2022-02-02` or `2019-10-12T07:20:50.52+00:00`
37    DateTime,
38
39    /// A directory is allowed
40    Directory,
41
42    /// A duration value is allowed, eg `19day`
43    Duration,
44
45    /// An error value
46    Error,
47
48    /// A general expression, eg `1 + 2` or `foo --bar`
49    Expression,
50
51    /// A (typically) string argument that follows external command argument parsing rules.
52    ///
53    /// Filepaths are expanded if unquoted, globs are allowed, and quotes embedded within unknown
54    /// args are unquoted.
55    ExternalArgument,
56
57    /// A filepath is allowed
58    Filepath,
59
60    /// A filesize value is allowed, eg `10kb`
61    Filesize,
62
63    /// A floating point value, eg `1.0`
64    Float,
65
66    /// A dotted path including the variable to access items
67    ///
68    /// Fully qualified
69    FullCellPath,
70
71    /// A glob pattern is allowed, eg `foo*`
72    GlobPattern,
73
74    /// Only an integer value is allowed
75    Int,
76
77    /// A module path pattern used for imports
78    ImportPattern,
79
80    /// A specific match to a word or symbol
81    Keyword(Vec<u8>, Box<SyntaxShape>),
82
83    /// A list is allowed, eg `[first second]`
84    List(Box<SyntaxShape>),
85
86    /// A general math expression, eg `1 + 2`
87    MathExpression,
88
89    /// A block of matches, used by `match`
90    MatchBlock,
91
92    /// Nothing
93    Nothing,
94
95    /// Only a numeric (integer or float) value is allowed
96    Number,
97
98    /// One of a list of possible items, checked in order, except that for an argument not
99    /// starting with `$`, `(` or `{`, shapes accepting any bare word (string, path, directory,
100    /// glob, cell-path, external-argument, any) are checked last
101    OneOf(Vec<SyntaxShape>),
102
103    /// An operator, eg `+`
104    Operator,
105
106    /// A range is allowed (eg, `1..3`)
107    Range,
108
109    /// A record value, eg `{x: 1, y: 2}`
110    Record(CollectionColumns<SyntaxShape>),
111
112    /// A math expression which expands shorthand forms on the lefthand side, eg `foo > 1`
113    /// The shorthand allows us to more easily reach columns inside of the row being passed in
114    RowCondition,
115
116    /// A signature for a definition, `[x:int, --foo]`
117    Signature,
118
119    /// A signature for command `extern`, which allows some reserved variable names, such as `[--env(-e), --in]`
120    ExternalSignature,
121
122    /// Strings and string-like bare words are allowed
123    String,
124
125    /// A table is allowed, eg `[[first, second]; [1, 2]]`
126    Table(CollectionColumns<SyntaxShape>),
127
128    /// A variable with optional type, `x` or `x: int`
129    VarWithOptType,
130}
131
132impl SyntaxShape {
133    /// If possible provide the associated concrete [`Type`]
134    ///
135    /// Note: Some [`SyntaxShape`]s don't have a corresponding [`Value`](crate::Value)
136    /// Here we currently return [`Type::Any`]
137    ///
138    /// ```rust
139    /// use nu_protocol::{SyntaxShape, Type};
140    /// let non_value = SyntaxShape::ImportPattern;
141    /// assert_eq!(non_value.to_type(), Type::Any);
142    /// ```
143    pub fn to_type(&self) -> Type {
144        match self {
145            SyntaxShape::Any => Type::Any,
146            SyntaxShape::Custom(name) => Type::Custom(name.clone()),
147            SyntaxShape::Block => Type::Block,
148            SyntaxShape::Closure(_) => Type::Closure,
149            SyntaxShape::Binary => Type::Binary,
150            SyntaxShape::CellPath => Type::CellPath,
151            SyntaxShape::DateTime => Type::Date,
152            SyntaxShape::Duration => Type::Duration,
153            SyntaxShape::Expression => Type::Any,
154            SyntaxShape::ExternalArgument => Type::Any,
155            SyntaxShape::Filepath => Type::String,
156            SyntaxShape::Directory => Type::String,
157            SyntaxShape::Float => Type::Float,
158            SyntaxShape::Filesize => Type::Filesize,
159            SyntaxShape::FullCellPath => Type::Any,
160            SyntaxShape::GlobPattern => Type::Glob,
161            SyntaxShape::Error => Type::Error,
162            SyntaxShape::ImportPattern => Type::Any,
163            SyntaxShape::Int => Type::Int,
164            SyntaxShape::List(x) => {
165                let contents = x.to_type();
166                Type::List(Box::new(contents))
167            }
168            SyntaxShape::Keyword(_, expr) => expr.to_type(),
169            SyntaxShape::MatchBlock => Type::Any,
170            SyntaxShape::MathExpression => Type::Any,
171            SyntaxShape::Nothing => Type::Nothing,
172            SyntaxShape::Number => Type::Number,
173            SyntaxShape::OneOf(types) => Type::one_of(types.iter().map(SyntaxShape::to_type)),
174            SyntaxShape::Operator => Type::Any,
175            SyntaxShape::Range => Type::Range,
176            SyntaxShape::Record(entries) => Type::Record(entries.map(SyntaxShape::to_type)),
177            SyntaxShape::RowCondition => Type::Bool,
178            SyntaxShape::Boolean => Type::Bool,
179            SyntaxShape::Signature | SyntaxShape::ExternalSignature => Type::Any,
180            SyntaxShape::String => Type::String,
181            SyntaxShape::Table(columns) => Type::Table(columns.map(SyntaxShape::to_type)),
182            SyntaxShape::VarWithOptType => Type::Any,
183        }
184    }
185
186    pub fn record() -> Self {
187        Self::Record(Default::default())
188    }
189
190    pub fn table() -> Self {
191        Self::Table(Default::default())
192    }
193}
194
195impl Display for SyntaxShape {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        match self {
198            SyntaxShape::Keyword(kw, shape) => {
199                write!(f, "\"{}\" {}", String::from_utf8_lossy(kw), shape)
200            }
201            SyntaxShape::Any => write!(f, "any"),
202            SyntaxShape::Custom(name) => write!(f, "{name}"),
203            SyntaxShape::String => write!(f, "string"),
204            SyntaxShape::CellPath => write!(f, "cell-path"),
205            SyntaxShape::FullCellPath => write!(f, "cell-path"),
206            SyntaxShape::Number => write!(f, "number"),
207            SyntaxShape::Range => write!(f, "range"),
208            SyntaxShape::Int => write!(f, "int"),
209            SyntaxShape::Float => write!(f, "float"),
210            SyntaxShape::Filepath => write!(f, "path"),
211            SyntaxShape::Directory => write!(f, "directory"),
212            SyntaxShape::GlobPattern => write!(f, "glob"),
213            SyntaxShape::ImportPattern => write!(f, "import"),
214            SyntaxShape::Block => write!(f, "block"),
215            SyntaxShape::Closure(args) => {
216                if let Some(args) = args {
217                    let arg_vec: Vec<_> = args.iter().map(|x| x.to_string()).collect();
218                    let arg_string = arg_vec.join(", ");
219                    write!(f, "closure({arg_string})")
220                } else {
221                    write!(f, "closure()")
222                }
223            }
224            SyntaxShape::Binary => write!(f, "binary"),
225            SyntaxShape::List(x) => write!(f, "list<{x}>"),
226            SyntaxShape::Table(columns) => write!(f, "table{columns}"),
227            SyntaxShape::Record(columns) => write!(f, "record{columns}"),
228            SyntaxShape::Filesize => write!(f, "filesize"),
229            SyntaxShape::Duration => write!(f, "duration"),
230            SyntaxShape::DateTime => write!(f, "datetime"),
231            SyntaxShape::Operator => write!(f, "operator"),
232            SyntaxShape::RowCondition => write!(
233                f,
234                "oneof<condition, {}>",
235                SyntaxShape::Closure(Some(vec![SyntaxShape::Any]))
236            ),
237            SyntaxShape::MathExpression => write!(f, "variable"),
238            SyntaxShape::VarWithOptType => write!(f, "vardecl"),
239            SyntaxShape::Signature => write!(f, "signature"),
240            SyntaxShape::ExternalSignature => write!(f, "external-signature"),
241            SyntaxShape::MatchBlock => write!(f, "match-block"),
242            SyntaxShape::Expression => write!(f, "expression"),
243            SyntaxShape::ExternalArgument => write!(f, "external-argument"),
244            SyntaxShape::Boolean => write!(f, "bool"),
245            SyntaxShape::Error => write!(f, "error"),
246            SyntaxShape::OneOf(list) => {
247                write!(f, "oneof")?;
248                let [first, rest @ ..] = &**list else {
249                    return Ok(());
250                };
251                write!(f, "<{first}")?;
252                for t in rest {
253                    write!(f, ", {t}")?;
254                }
255                f.write_str(">")
256            }
257            SyntaxShape::Nothing => write!(f, "nothing"),
258        }
259    }
260}