nu_protocol/
syntax_shape.rs

1use crate::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(Vec<(String, 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    /// Strings and string-like bare words are allowed
114    String,
115
116    /// A table is allowed, eg `[[first, second]; [1, 2]]`
117    Table(Vec<(String, SyntaxShape)>),
118
119    /// A variable with optional type, `x` or `x: int`
120    VarWithOptType,
121}
122
123impl SyntaxShape {
124    /// If possible provide the associated concrete [`Type`]
125    ///
126    /// Note: Some [`SyntaxShape`]s don't have a corresponding [`Value`](crate::Value)
127    /// Here we currently return [`Type::Any`]
128    ///
129    /// ```rust
130    /// use nu_protocol::{SyntaxShape, Type};
131    /// let non_value = SyntaxShape::ImportPattern;
132    /// assert_eq!(non_value.to_type(), Type::Any);
133    /// ```
134    pub fn to_type(&self) -> Type {
135        let mk_ty = |tys: &[(String, SyntaxShape)]| {
136            tys.iter()
137                .map(|(key, val)| (key.clone(), val.to_type()))
138                .collect()
139        };
140
141        match self {
142            SyntaxShape::Any => Type::Any,
143            SyntaxShape::Block => Type::Block,
144            SyntaxShape::Closure(_) => Type::Closure,
145            SyntaxShape::Binary => Type::Binary,
146            SyntaxShape::CellPath => Type::Any,
147            SyntaxShape::DateTime => Type::Date,
148            SyntaxShape::Duration => Type::Duration,
149            SyntaxShape::Expression => Type::Any,
150            SyntaxShape::ExternalArgument => Type::Any,
151            SyntaxShape::Filepath => Type::String,
152            SyntaxShape::Directory => Type::String,
153            SyntaxShape::Float => Type::Float,
154            SyntaxShape::Filesize => Type::Filesize,
155            SyntaxShape::FullCellPath => Type::Any,
156            SyntaxShape::GlobPattern => Type::Glob,
157            SyntaxShape::Error => Type::Error,
158            SyntaxShape::ImportPattern => Type::Any,
159            SyntaxShape::Int => Type::Int,
160            SyntaxShape::List(x) => {
161                let contents = x.to_type();
162                Type::List(Box::new(contents))
163            }
164            SyntaxShape::Keyword(_, expr) => expr.to_type(),
165            SyntaxShape::MatchBlock => Type::Any,
166            SyntaxShape::MathExpression => Type::Any,
167            SyntaxShape::Nothing => Type::Nothing,
168            SyntaxShape::Number => Type::Number,
169            SyntaxShape::OneOf(_) => Type::Any,
170            SyntaxShape::Operator => Type::Any,
171            SyntaxShape::Range => Type::Range,
172            SyntaxShape::Record(entries) => Type::Record(mk_ty(entries)),
173            SyntaxShape::RowCondition => Type::Bool,
174            SyntaxShape::Boolean => Type::Bool,
175            SyntaxShape::Signature => Type::Any,
176            SyntaxShape::String => Type::String,
177            SyntaxShape::Table(columns) => Type::Table(mk_ty(columns)),
178            SyntaxShape::VarWithOptType => Type::Any,
179        }
180    }
181}
182
183impl Display for SyntaxShape {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        let mk_fmt = |tys: &[(String, SyntaxShape)]| -> String {
186            tys.iter()
187                .map(|(x, y)| format!("{x}: {y}"))
188                .collect::<Vec<String>>()
189                .join(", ")
190        };
191
192        match self {
193            SyntaxShape::Keyword(kw, shape) => {
194                write!(f, "\"{}\" {}", String::from_utf8_lossy(kw), shape)
195            }
196            SyntaxShape::Any => write!(f, "any"),
197            SyntaxShape::String => write!(f, "string"),
198            SyntaxShape::CellPath => write!(f, "cell-path"),
199            SyntaxShape::FullCellPath => write!(f, "cell-path"),
200            SyntaxShape::Number => write!(f, "number"),
201            SyntaxShape::Range => write!(f, "range"),
202            SyntaxShape::Int => write!(f, "int"),
203            SyntaxShape::Float => write!(f, "float"),
204            SyntaxShape::Filepath => write!(f, "path"),
205            SyntaxShape::Directory => write!(f, "directory"),
206            SyntaxShape::GlobPattern => write!(f, "glob"),
207            SyntaxShape::ImportPattern => write!(f, "import"),
208            SyntaxShape::Block => write!(f, "block"),
209            SyntaxShape::Closure(args) => {
210                if let Some(args) = args {
211                    let arg_vec: Vec<_> = args.iter().map(|x| x.to_string()).collect();
212                    let arg_string = arg_vec.join(", ");
213                    write!(f, "closure({arg_string})")
214                } else {
215                    write!(f, "closure()")
216                }
217            }
218            SyntaxShape::Binary => write!(f, "binary"),
219            SyntaxShape::List(x) => write!(f, "list<{x}>"),
220            SyntaxShape::Table(columns) => {
221                if columns.is_empty() {
222                    write!(f, "table")
223                } else {
224                    write!(f, "table<{}>", mk_fmt(columns))
225                }
226            }
227            SyntaxShape::Record(entries) => {
228                if entries.is_empty() {
229                    write!(f, "record")
230                } else {
231                    write!(f, "record<{}>", mk_fmt(entries))
232                }
233            }
234            SyntaxShape::Filesize => write!(f, "filesize"),
235            SyntaxShape::Duration => write!(f, "duration"),
236            SyntaxShape::DateTime => write!(f, "datetime"),
237            SyntaxShape::Operator => write!(f, "operator"),
238            SyntaxShape::RowCondition => write!(
239                f,
240                "oneof<condition, {}>",
241                SyntaxShape::Closure(Some(vec![SyntaxShape::Any]))
242            ),
243            SyntaxShape::MathExpression => write!(f, "variable"),
244            SyntaxShape::VarWithOptType => write!(f, "vardecl"),
245            SyntaxShape::Signature => write!(f, "signature"),
246            SyntaxShape::MatchBlock => write!(f, "match-block"),
247            SyntaxShape::Expression => write!(f, "expression"),
248            SyntaxShape::ExternalArgument => write!(f, "external-argument"),
249            SyntaxShape::Boolean => write!(f, "bool"),
250            SyntaxShape::Error => write!(f, "error"),
251            SyntaxShape::OneOf(list) => {
252                write!(f, "oneof<")?;
253                if let Some((last, rest)) = list.split_last() {
254                    for ty in rest {
255                        write!(f, "{ty}, ")?;
256                    }
257                    write!(f, "{last}")?;
258                }
259                write!(f, ">")
260            }
261            SyntaxShape::Nothing => write!(f, "nothing"),
262        }
263    }
264}