Debian Codegraph @

third_party/rust/askama_parser/src/target.rs

raw
1 use winnow::combinator::{alt, opt, peek, preceded, separated};
2 use winnow::token::one_of;
3 use winnow::{ModalParser, Parser};
4
5 use crate::{
6 CharLit, ErrorContext, Num, ParseErr, ParseResult, PathOrIdentifier, State, StrLit, WithSpan,
7 bool_lit, char_lit, identifier, is_rust_keyword, keyword, num_lit, path_or_identifier, str_lit,
8 ws,
9 };
10
11 #[derive(Clone, Debug, PartialEq)]
12 pub enum Target<'a> {
13 Name(&'a str),
14 Tuple(Vec<&'a str>, Vec<Target<'a>>),
15 Array(Vec<&'a str>, Vec<Target<'a>>),
16 Struct(Vec<&'a str>, Vec<(&'a str, Target<'a>)>),
17 NumLit(&'a str, Num<'a>),
18 StrLit(StrLit<'a>),
19 CharLit(CharLit<'a>),
20 BoolLit(&'a str),
21 Path(Vec<&'a str>),
22 OrChain(Vec<Target<'a>>),
23 Placeholder(WithSpan<'a, ()>),
24 /// The `Option` is the variable name (if any) in `var_name @ ..`.
25 Rest(WithSpan<'a, Option<&'a str>>),
26 }
27
28 impl<'a> Target<'a> {
29 /// Parses multiple targets with `or` separating them
30 pub(super) fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
31 let _level_guard = s.level.nest(i)?;
32 let mut p = opt(preceded(ws(keyword("or")), |i: &mut _| {
33 Self::parse_one(i, s)
34 }));
35
36 let target = Self::parse_one(i, s)?;
37 let Some(snd_target) = p.parse_next(i)? else {
38 return Ok(target);
39 };
40
41 let mut targets = vec![target, snd_target];
42 while let Some(target) = p.parse_next(i)? {
43 targets.push(target);
44 }
45 Ok(Self::OrChain(targets))
46 }
47
48 /// Parses a single target without an `or`, unless it is wrapped in parentheses.
49 fn parse_one(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
50 let mut opt_opening_paren = opt(ws('(')).map(|o| o.is_some());
51 let mut opt_opening_brace = opt(ws('{')).map(|o| o.is_some());
52 let mut opt_opening_bracket = opt(ws('[')).map(|o| o.is_some());
53
54 let lit = opt(Self::lit).parse_next(i)?;
55 if let Some(lit) = lit {
56 return Ok(lit);
57 }
58
59 // match tuples and unused parentheses
60 let target_is_tuple = opt_opening_paren.parse_next(i)?;
61 if target_is_tuple {
62 let (singleton, mut targets) =
63 collect_targets(i, ')', |i: &mut _| Self::unnamed(i, s))?;
64 if singleton {
65 return Ok(targets.pop().unwrap());
66 }
67 return Ok(Self::Tuple(
68 Vec::new(),
69 only_one_rest_pattern(targets, false, "tuple")?,
70 ));
71 }
72 let target_is_array = opt_opening_bracket.parse_next(i)?;
73 if target_is_array {
74 let (singleton, mut targets) =
75 collect_targets(i, ']', |i: &mut _| Self::unnamed(i, s))?;
76 if singleton {
77 return Ok(targets.pop().unwrap());
78 }
79 return Ok(Self::Array(
80 Vec::new(),
81 only_one_rest_pattern(targets, true, "array")?,
82 ));
83 }
84
85 let path = path_or_identifier.try_map(|v| match v {
86 PathOrIdentifier::Path(v) => Ok(v),
87 PathOrIdentifier::Identifier(v) => Err(v),
88 });
89
90 // match structs
91 let path = opt(path).parse_next(i)?;
92 if let Some(path) = path {
93 let i_before_matching_with = *i;
94 let _ = opt(ws(keyword("with"))).parse_next(i)?;
95
96 let is_unnamed_struct = opt_opening_paren.parse_next(i)?;
97 if is_unnamed_struct {
98 let (_, targets) = collect_targets(i, ')', |i: &mut _| Self::unnamed(i, s))?;
99 return Ok(Self::Tuple(
100 path,
101 only_one_rest_pattern(targets, false, "struct")?,
102 ));
103 }
104
105 let is_named_struct = opt_opening_brace.parse_next(i)?;
106 if is_named_struct {
107 let (_, targets) = collect_targets(i, '}', |i: &mut _| Self::named(i, s))?;
108 return Ok(Self::Struct(path, targets));
109 }
110
111 *i = i_before_matching_with;
112 return Ok(Self::Path(path));
113 }
114
115 // neither literal nor struct nor path
116 let i_before_identifier = *i;
117 let name = identifier.parse_next(i)?;
118 let target = match name {
119 "_" => Self::Placeholder(WithSpan::new((), i_before_identifier)),
120 _ => verify_name(i_before_identifier, name)?,
121 };
122 Ok(target)
123 }
124
125 fn lit(i: &mut &'a str) -> ParseResult<'a, Self> {
126 alt((
127 str_lit.map(Self::StrLit),
128 char_lit.map(Self::CharLit),
129 num_lit
130 .with_taken()
131 .map(|(num, full)| Target::NumLit(full, num)),
132 bool_lit.map(Self::BoolLit),
133 ))
134 .parse_next(i)
135 }
136
137 fn unnamed(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
138 alt((Self::rest, |i: &mut _| Self::parse(i, s))).parse_next(i)
139 }
140
141 fn named(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, (&'a str, Self)> {
142 let start = *i;
143 let rest = opt(Self::rest.with_taken()).parse_next(i)?;
144 if let Some(rest) = rest {
145 let chr = peek(ws(opt(one_of([',', ':'])))).parse_next(i)?;
146 if let Some(chr) = chr {
147 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
148 format!(
149 "unexpected `{chr}` character after `..`\n\
150 note that in a named struct, `..` must come last to ignore other members"
151 ),
152 *i,
153 )));
154 }
155 if let Target::Rest(ref s) = rest.0 {
156 if s.inner.is_some() {
157 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
158 "`@ ..` cannot be used in struct",
159 s.span,
160 )));
161 }
162 }
163 return Ok((rest.1, rest.0));
164 }
165
166 *i = start;
167 let (src, target) = (
168 identifier,
169 opt(preceded(ws(':'), |i: &mut _| Self::parse(i, s))),
170 )
171 .parse_next(i)?;
172
173 if src == "_" {
174 *i = start;
175 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
176 "cannot use placeholder `_` as source in named struct",
177 *i,
178 )));
179 }
180
181 let target = match target {
182 Some(target) => target,
183 None => verify_name(start, src)?,
184 };
185 Ok((src, target))
186 }
187
188 fn rest(i: &mut &'a str) -> ParseResult<'a, Self> {
189 let start = *i;
190 let (ident, _) = (opt((identifier, ws('@'))), "..").parse_next(i)?;
191 Ok(Self::Rest(WithSpan::new(
192 ident.map(|(ident, _)| ident),
193 start,
194 )))
195 }
196 }
197
198 fn verify_name<'a>(
199 input: &'a str,
200 name: &'a str,
201 ) -> Result<Target<'a>, winnow::error::ErrMode<ErrorContext<'a>>> {
202 if is_rust_keyword(name) {
203 Err(winnow::error::ErrMode::Cut(ErrorContext::new(
204 format!("cannot use `{name}` as a name: it is a rust keyword"),
205 input,
206 )))
207 } else if name.starts_with("__askama") {
208 Err(winnow::error::ErrMode::Cut(ErrorContext::new(
209 format!("cannot use `{name}` as a name: it is reserved for `askama`"),
210 input,
211 )))
212 } else {
213 Ok(Target::Name(name))
214 }
215 }
216
217 fn collect_targets<'a, T>(
218 i: &mut &'a str,
219 delim: char,
220 one: impl ModalParser<&'a str, T, ErrorContext<'a>>,
221 ) -> ParseResult<'a, (bool, Vec<T>)> {
222 let opt_comma = ws(opt(',')).map(|o| o.is_some());
223 let mut opt_end = ws(opt(one_of(delim))).map(|o| o.is_some());
224
225 let has_end = opt_end.parse_next(i)?;
226 if has_end {
227 return Ok((false, Vec::new()));
228 }
229
230 let targets = opt(separated(1.., one, ws(',')).map(|v: Vec<_>| v)).parse_next(i)?;
231 let Some(targets) = targets else {
232 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
233 "expected comma separated list of members",
234 *i,
235 )));
236 };
237
238 let (has_comma, has_end) = (opt_comma, opt_end).parse_next(i)?;
239 if !has_end {
240 let msg = match has_comma {
241 true => format!("expected member, or `{delim}` as terminator"),
242 false => format!("expected `,` for more members, or `{delim}` as terminator"),
243 };
244 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(msg, *i)));
245 }
246
247 let singleton = !has_comma && targets.len() == 1;
248 Ok((singleton, targets))
249 }
250
251 fn only_one_rest_pattern<'a>(
252 targets: Vec<Target<'a>>,
253 allow_named_rest: bool,
254 type_kind: &str,
255 ) -> Result<Vec<Target<'a>>, ParseErr<'a>> {
256 let mut found_rest = false;
257
258 for target in &targets {
259 if let Target::Rest(s) = target {
260 if !allow_named_rest && s.inner.is_some() {
261 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
262 "`@ ..` is only allowed in slice patterns",
263 s.span,
264 )));
265 }
266 if found_rest {
267 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
268 format!("`..` can only be used once per {type_kind} pattern"),
269 s.span,
270 )));
271 }
272 found_rest = true;
273 }
274 }
275 Ok(targets)
276 }