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