Skip to main content

css_value_definition_parser/
lib.rs

1use heck::ToPascalCase;
2use proc_macro2::{Span, TokenStream};
3use quote::{ToTokens, TokenStreamExt, format_ident};
4use std::{
5	fmt::Display,
6	ops::{Deref, Range},
7};
8use syn::{
9	Error, Ident, Lit, LitFloat, LitInt, LitStr, Result, Token, braced, bracketed,
10	ext::IdentExt,
11	parenthesized,
12	parse::{Parse, ParseStream},
13	parse2, token,
14};
15
16mod sized_types;
17pub use sized_types::is_sized_type;
18#[cfg(test)]
19mod test;
20
21pub struct StrWrapped<T: Parse>(pub T);
22impl<T: Parse> Parse for StrWrapped<T> {
23	fn parse(input_raw: ParseStream) -> Result<Self> {
24		Ok(Self(parse2::<T>(
25			input_raw.parse::<LitStr>()?.value().replace("'", "\"").replace("∞", "").parse::<TokenStream>()?,
26		)?))
27	}
28}
29
30#[derive(Debug, PartialEq, Clone)]
31pub enum Def {
32	Ident(DefIdent),
33	Function(DefIdent, Box<Def>),
34	AutoOr(Box<Def>),
35	NoneOr(Box<Def>),
36	AutoNoneOr(Box<Def>),
37	NormalOr(Box<Def>),
38	Type(DefType),
39	StyleValue(DefType),
40	FunctionType(DefType),
41	Optional(Box<Def>), // ?
42	Combinator(Vec<Def>, DefCombinatorStyle),
43	Group(Box<Def>, DefGroupStyle),
44	Multiplier(Box<Def>, DefMultiplierSeparator, DefRange),
45	Punct(char),
46	IntLiteral(i32),
47	DimensionLiteral(f32, String),
48}
49
50#[derive(Debug, PartialEq, Copy, Clone)]
51pub enum DefGroupStyle {
52	None,         // [ ] - regular group notation
53	OneMustOccur, // [ ]! - at least one in the group must occur
54}
55
56#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
57pub enum DefCombinatorStyle {
58	Ordered,      // <space>
59	AllMustOccur, // && - all must occur
60	Options,      // || - one or more must occur
61	Alternatives, // | - exactly one must occur
62}
63
64#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
65pub enum DefMultiplierSeparator {
66	None,   // *, +, or {,}
67	Commas, // #, #? or #{,}
68}
69
70#[derive(Debug, PartialEq, Clone)]
71pub enum DefRange {
72	None,
73	Range(Range<f32>), // {A,B}
74	RangeFrom(f32),    // {A,}
75	RangeTo(f32),      // {,B}
76	Fixed(f32),        // {A}
77}
78
79#[derive(Debug, PartialEq, Clone)]
80pub struct DefIdent(pub String);
81
82#[derive(Debug, PartialEq, Clone)]
83pub struct DefType {
84	pub ident: DefIdent,
85	pub range: DefRange,
86}
87
88impl DefType {
89	pub fn new(str: &str, range: DefRange) -> Self {
90		DefType { ident: DefIdent(str.to_string()), range }
91	}
92
93	pub fn ident_str(&self) -> &str {
94		self.ident.0.as_str()
95	}
96
97	/// Returns true if this type *intrinsically* carries its own `'a` lifetime (i.e. the hand-written or generated type
98	/// is declared as `Foo<'a>`). This is independent of the `Value<'a, T>` substitution wrapper, which always supplies
99	/// `'a` separately. Almost every value type is unsized; the sized minority (numeric primitives like `Integer` and
100	/// `Length`, keyword enums, `Url`, ident newtypes) is enumerated in `sized_types`, so a type is unsized unless it
101	/// appears there.
102	pub fn maybe_unsized(&self) -> bool {
103		!sized_types::is_sized_type(self.ident_str())
104	}
105}
106
107impl Parse for Def {
108	fn parse(input: ParseStream) -> Result<Self> {
109		let mut root = if input.peek(Token![<]) {
110			input.parse::<Token![<]>()?;
111			let mut style_value = false;
112			let mut function = false;
113			let ident = if input.peek(LitStr) {
114				style_value = true;
115				input.parse::<StrWrapped<DefIdent>>()?.0.0
116			} else {
117				input.parse::<DefIdent>()?.0
118			}
119			.to_pascal_case();
120			let range = if input.peek(token::Bracket) {
121				let content;
122				bracketed!(content in input);
123				content.parse::<DefRange>()?
124			} else {
125				DefRange::None
126			};
127			if input.peek(token::Paren) {
128				let content;
129				parenthesized!(content in input);
130				if !content.is_empty() {
131					Err(Error::new(input.span(), "disallowed content inside deftype function"))?
132				}
133				debug_assert!(!style_value, "Can't be function and style value");
134				function = true;
135			}
136			debug_assert!(!(function && style_value), "Can't be function or style value and or-none");
137			let ty = if let Some(without_auto) = ident.strip_suffix("-or-auto") {
138				Self::AutoOr(Box::new(Def::Type(DefType { ident: DefIdent(without_auto.into()), range })))
139			} else if let Some(without_none) = ident.strip_suffix("-or-none") {
140				Self::NoneOr(Box::new(Def::Type(DefType { ident: DefIdent(without_none.into()), range })))
141			} else if function {
142				Self::FunctionType(DefType { ident: DefIdent(ident), range })
143			} else if style_value {
144				Self::StyleValue(DefType { ident: DefIdent(ident), range })
145			} else {
146				Self::Type(DefType { ident: DefIdent(ident), range })
147			};
148			input.parse::<Token![>]>()?;
149			ty
150		} else if input.peek(token::Bracket) {
151			let content;
152			bracketed!(content in input);
153			let inner = Box::new(content.parse::<Def>()?);
154			if input.peek(Token![!]) {
155				input.parse::<Token![!]>()?;
156				Self::Group(inner, DefGroupStyle::OneMustOccur)
157			} else if input.peek(Token![#]) {
158				input.parse::<Token![#]>()?;
159				Self::Multiplier(inner, DefMultiplierSeparator::Commas, DefRange::RangeFrom(1.))
160			} else if input.peek(Token![+]) {
161				input.parse::<Token![+]>()?;
162				Self::Multiplier(inner, DefMultiplierSeparator::None, DefRange::RangeFrom(1.))
163			} else if input.peek(token::Brace) {
164				let content;
165				braced!(content in input);
166				let range = content.parse::<DefRange>()?;
167				debug_assert!(matches!(range, DefRange::Range(_) | DefRange::Fixed(_)));
168				Self::Multiplier(inner, DefMultiplierSeparator::None, range)
169			} else {
170				Self::Group(inner, DefGroupStyle::None)
171			}
172		} else if input.peek(Ident::peek_any) {
173			let ident = input.parse::<DefIdent>()?;
174			if input.peek(token::Paren) {
175				let content;
176				parenthesized!(content in input);
177				Self::Function(ident, Box::new(content.parse::<Def>()?))
178			} else {
179				Self::Ident(ident)
180			}
181		} else if input.peek(Token![-]) && input.peek2(Ident::peek_any) {
182			input.parse::<Token![-]>()?;
183			let mut ident = input.parse::<DefIdent>()?;
184			ident.0.insert(0, '-');
185			Self::Ident(ident)
186		} else if input.peek(Lit) {
187			let lit = input.parse::<Lit>()?;
188			match lit {
189				Lit::Int(lit) => {
190					if lit.suffix() == "" {
191						Self::IntLiteral(lit.base10_parse::<i32>()?)
192					} else {
193						let unit = lit.suffix();
194						if unit.is_empty() {
195							Err(Error::new(lit.span(), "Invalid dimension unit"))?
196						}
197						Self::DimensionLiteral(lit.base10_parse::<f32>()?, unit.to_string())
198					}
199				}
200				Lit::Char(lit) => Self::Punct(lit.value()),
201				Lit::Str(lit) if lit.value().len() == 1 => Self::Punct(lit.value().chars().next().unwrap()),
202				_ => Err(Error::new(input.span(), "unknown token in Def parse"))?,
203			}
204		} else {
205			input.step(|cursor| {
206				if let Some((p, next)) = cursor.punct() {
207					return Ok((Self::Punct(p.as_char()), next));
208				}
209				Err(Error::new(input.span(), "unknown token in Def parse"))?
210			})?
211		}
212		.optimize();
213		loop {
214			if input.is_empty() {
215				return Ok(root);
216			} else if input.peek(Token![?]) {
217				input.parse::<Token![?]>()?;
218				let inner = root;
219				root = Self::Optional(Box::new(inner.optimize()));
220			} else if input.peek(Token![+])
221				|| input.peek(Token![#])
222				|| input.peek(token::Brace)
223				|| input.peek(Token![*])
224			{
225				let inner = root;
226				let (sep, range) = if input.peek(Token![*]) {
227					input.parse::<Token![*]>()?;
228					(DefMultiplierSeparator::None, DefRange::RangeFrom(0.))
229				} else if input.peek(Token![+]) {
230					input.parse::<Token![+]>()?;
231					(DefMultiplierSeparator::None, DefRange::RangeFrom(1.))
232				} else if input.peek(Token![#]) {
233					input.parse::<Token![#]>()?;
234					let range = if input.peek(token::Brace) {
235						let content;
236						braced!(content in input);
237						content.parse::<DefRange>()?
238					} else if input.peek(Token![?]) {
239						input.parse::<Token![?]>()?;
240						DefRange::RangeFrom(0.)
241					} else {
242						DefRange::RangeFrom(1.)
243					};
244					(DefMultiplierSeparator::Commas, range)
245				} else if input.peek(token::Brace) {
246					let content;
247					braced!(content in input);
248					(DefMultiplierSeparator::None, content.parse::<DefRange>()?)
249				} else {
250					Err(Error::new(input.span(), "Unknown token in DefMultiplierStyle parse!"))?
251				};
252				root = Self::Multiplier(Box::new(inner.optimize()), sep, range).optimize();
253			} else {
254				let style = if input.peek(Token![||]) {
255					input.parse::<Token![||]>()?;
256					DefCombinatorStyle::Options
257				} else if input.peek(Token![|]) {
258					input.parse::<Token![|]>()?;
259					DefCombinatorStyle::Alternatives
260				} else if input.peek(Token![&&]) {
261					input.parse::<Token![&&]>()?;
262					DefCombinatorStyle::AllMustOccur
263				} else {
264					DefCombinatorStyle::Ordered
265				};
266				let mut next = input.parse::<Def>()?;
267				match (&mut root, &mut next) {
268					(_, &mut Self::Combinator(ref mut children, ref s)) if s == &style => {
269						children.insert(0, root);
270						root = next;
271					}
272					(&mut Self::Combinator(ref mut children, ref s), _) if s == &style => {
273						children.push(next);
274					}
275					(_, &mut Self::Combinator(ref mut children, ref other_style)) if &style < other_style => {
276						let options = Self::Combinator(vec![root, children.remove(0)], style);
277						children.insert(0, options);
278						root = next;
279					}
280					(_, Self::Group(inner, DefGroupStyle::None)) => {
281						let children = vec![root, inner.as_ref().clone()];
282						root = Self::Combinator(children, style);
283					}
284					(Self::Group(inner, DefGroupStyle::None), _) => {
285						let children = vec![inner.as_ref().clone(), next];
286						root = Self::Combinator(children, style);
287					}
288					_ => {
289						let children = vec![root, next];
290						root = Self::Combinator(children, style);
291					}
292				}
293			}
294		}
295	}
296}
297
298impl Def {
299	/// Returns true if this type is unsized, in other words it requires heap allocations
300	/// to contain a full representation.
301	pub fn maybe_unsized(&self) -> bool {
302		match self {
303			Self::IntLiteral(_) | Self::DimensionLiteral(_, _) | Self::Punct(_) => false,
304			Self::Ident(_) => true,
305			// Functions that contain multipliers or known allocating types
306			Self::Function(_, inner) => inner.maybe_unsized(),
307			Self::FunctionType(ty) => {
308				matches!(
309					ty.ident_str(),
310					"CalcSize"
311						| "DynamicRangeLimitMix"
312						| "Fade"
313						| "Param"
314						| "Rect"
315						| "Repeat"
316						| "Attr"
317						| "PaletteMix"
318						| "SnapBlock"
319						| "SnapInline"
320						| "Superellipse"
321				)
322			}
323			Self::Type(_) => true,
324			Self::StyleValue(_) => true,
325			Self::AutoOr(d) | Self::NoneOr(d) | Self::AutoNoneOr(d) | Self::NormalOr(d) => d.maybe_unsized(),
326			Self::Optional(d) => d.maybe_unsized(),
327			Self::Combinator(ds, _) => ds.iter().any(|d| d.maybe_unsized()),
328			Self::Group(d, _) => d.maybe_unsized(),
329			Self::Multiplier(inner, sep, range) => {
330				// Bounded ranges are optimized to Optionals combinators and only need 'a if the
331				// inner type does.
332				matches!(sep, DefMultiplierSeparator::Commas)
333					|| matches!(range, DefRange::RangeFrom(_) | DefRange::RangeTo(_))
334					|| inner.maybe_unsized()
335			}
336		}
337	}
338
339	pub fn suggested_data_type(&self) -> DataType {
340		match self {
341			Self::Combinator(_, DefCombinatorStyle::Alternatives) => DataType::Enum,
342			_ => DataType::SingleUnnamedStruct,
343		}
344	}
345
346	pub fn optimize(&self) -> Self {
347		if let Self::Combinator(defs, DefCombinatorStyle::Alternatives) = self {
348			let optimized: Vec<Def> = defs.iter().map(Self::optimize).collect();
349			let is_nested_alternatives = |def: &Def| match def {
350				Def::Combinator(_, DefCombinatorStyle::Alternatives) => true,
351				Def::Group(inner, DefGroupStyle::None) => {
352					matches!(inner.as_ref(), Def::Combinator(_, DefCombinatorStyle::Alternatives))
353				}
354				_ => false,
355			};
356			if optimized.iter().any(is_nested_alternatives) {
357				let flat: Vec<Def> = optimized
358					.into_iter()
359					.flat_map(|d| match d {
360						Def::Combinator(inner, DefCombinatorStyle::Alternatives) => inner,
361						Def::Group(inner, DefGroupStyle::None) => match *inner {
362							Def::Combinator(inner, DefCombinatorStyle::Alternatives) => inner,
363							other => vec![Def::Group(Box::new(other), DefGroupStyle::None)],
364						},
365						other => vec![other],
366					})
367					.collect();
368				return Self::Combinator(flat, DefCombinatorStyle::Alternatives).optimize();
369			}
370		}
371		match self {
372			Self::Combinator(defs, DefCombinatorStyle::Alternatives)
373				if defs.iter().any(Self::has_distributable_group) =>
374			{
375				let distributed: Vec<Def> =
376					defs.iter()
377						.flat_map(|d| match d {
378							Def::Combinator(
379								children,
380								style @ (DefCombinatorStyle::Ordered | DefCombinatorStyle::AllMustOccur),
381							) => {
382								if let Some((group_idx, alts, wrap_optional)) =
383									children.iter().enumerate().find_map(|(i, c)| {
384										Self::extract_alternatives(c).map(|(alts, wrap)| (i, alts, wrap))
385									}) {
386									let prefix = &children[..group_idx];
387									let suffix = &children[group_idx + 1..];
388									let mut result: Vec<Def> = alts
389										.iter()
390										.map(|alt| {
391											let mut new_children: Vec<Def> = prefix.to_vec();
392											new_children.push(alt.clone());
393											new_children.extend_from_slice(suffix);
394											Def::Combinator(new_children, *style)
395										})
396										.collect();
397									if wrap_optional {
398										let mut absent: Vec<Def> = prefix.to_vec();
399										absent.extend_from_slice(suffix);
400										match absent.len() {
401											0 => {}
402											1 => {
403												let single = absent.into_iter().next().unwrap();
404												if let Some((alts, _)) = Self::extract_alternatives(&single) {
405													result.extend(alts.iter().cloned());
406												} else {
407													result.push(single);
408												}
409											}
410											_ => result.push(Def::Combinator(absent, *style)),
411										}
412									}
413									result
414								} else {
415									vec![d.clone()]
416								}
417							}
418							_ => vec![d.clone()],
419						})
420						.collect();
421				return Self::Combinator(distributed, DefCombinatorStyle::Alternatives).optimize();
422			}
423
424			Self::Combinator(defs, DefCombinatorStyle::Alternatives) if defs.len() == 2 => {
425				let [first, second] = defs.as_slice() else { panic!("defs.len() was 2!") };
426				match (first, second) {
427					// "none | AutoOr<X>" can become "AutoNoneOr<X>"
428					(Def::Ident(DefIdent(ident)), Def::AutoOr(def))
429					| (Def::AutoOr(def), Def::Ident(DefIdent(ident)))
430						if ident == "none" =>
431					{
432						Def::AutoNoneOr(Box::new(*def.clone()))
433					}
434					// "auto | NoneOr<X>" can become "AutoNoneOr<X>"
435					(Def::Ident(DefIdent(ident)), Def::NoneOr(def))
436					| (Def::NoneOr(def), Def::Ident(DefIdent(ident)))
437						if ident == "auto" =>
438					{
439						Def::AutoNoneOr(Box::new(*def.clone()))
440					}
441					// "<X> | auto" can be simplified to "AutoOr<X>"
442					(Def::Ident(DefIdent(ident)), def) | (def, Def::Ident(DefIdent(ident)))
443						if ident == "auto" &&
444						// Avoid AutoOr<Ident>, or AutoOr<NoneOr<>> though
445						!matches!(def, Def::Ident(_) | Def::AutoOr(_) | Def::NoneOr(_)) =>
446					{
447						Def::AutoOr(Box::new(def.clone()))
448					}
449					// "<X> | none" can be simplified to "NoneOr<X>"
450					(Def::Ident(DefIdent(ident)), def) | (def, Def::Ident(DefIdent(ident)))
451						if ident == "none"  &&
452						// Avoid NoneOr<Ident>, or NoneOr<AutoOr<>> though
453						!matches!(def, Def::Ident(_) | Def::AutoOr(_) | Def::NoneOr(_)) =>
454					{
455						Def::NoneOr(Box::new(def.clone()))
456					}
457					// "<X> | normal" can be simplified to "NormalOr<X>"
458					(Def::Ident(DefIdent(ident)), def) | (def, Def::Ident(DefIdent(ident)))
459						if ident == "normal" &&
460						// Avoid NormalOr<Ident>, or NormalOr<AutoOr<>> though
461						!matches!(def, Def::Ident(_) | Def::AutoOr(_) | Def::NoneOr(_) | Def::NormalOr(_)) =>
462					{
463						Def::NormalOr(Box::new(def.clone()))
464					}
465					// "<length-percentage> | <flex>" can be simplified to "<length-percentage-or-flex>"
466					(Def::Type(type1), Def::Type(type2)) => match (type1.ident_str(), type2.ident_str()) {
467						// "<gap-rule-list> | <gap-auto-rule-list>" can be flattened to "<gap-rule-list>"
468						("GapRuleList", "GapAutoRuleList") => {
469							Def::Type(DefType::new("GapRuleList", type1.range.clone()))
470						}
471						("GapAutoRuleList", "GapRuleList") => {
472							Def::Type(DefType::new("GapRuleList", type2.range.clone()))
473						}
474						("LengthPercentage", "Flex") | ("Flex", "LengthPercentage") => {
475							Def::Type(DefType::new("LengthPercentageOrFlex", type1.range.clone()))
476						}
477						("Number", "Percentage") | ("Percentage", "Number") => {
478							Def::Type(DefType::new("NumberPercentage", type1.range.clone()))
479						}
480						("Number", "Length") | ("Length", "Number") => {
481							Def::Type(DefType::new("NumberLength", type1.range.clone()))
482						}
483						_ => {
484							return Self::Combinator(
485								vec![first.optimize(), second.optimize()],
486								DefCombinatorStyle::Alternatives,
487							);
488						}
489					},
490					_ => {
491						return Self::Combinator(
492							vec![first.optimize(), second.optimize()],
493							DefCombinatorStyle::Alternatives,
494						);
495					}
496				}
497			}
498			Self::Combinator(defs, DefCombinatorStyle::Alternatives) if defs.len() == 3 => {
499				let [first, second, third] = defs.as_slice() else { panic!("defs.len() was 3!") };
500				match (first, second, third) {
501					// "auto | none | <X>" can be simplified to "AutoNoneOr<X>"
502					(def, Def::Ident(DefIdent(first)), Def::Ident(DefIdent(second)))
503					| (Def::Ident(DefIdent(first)), def, Def::Ident(DefIdent(second)))
504					| (Def::Ident(DefIdent(first)), Def::Ident(DefIdent(second)), def)
505						if matches!((first.as_str(), second.as_str()), ("auto", "none") | ("none", "auto")) &&
506						// Avoid AutoNoneOr<Ident>, or AutoNoneOr<AutoOr<>> though
507						!matches!(def, Def::Ident(_) | Def::AutoOr(_) | Def::NoneOr(_)) =>
508					{
509						Def::AutoNoneOr(Box::new(def.clone()))
510					}
511					// "<number> | <length> | auto" can be simplified to "AutoOr<NumberLength>"
512					(Def::Type(type1), Def::Type(type2), Def::Ident(DefIdent(ident)))
513					| (Def::Ident(DefIdent(ident)), Def::Type(type1), Def::Type(type2))
514					| (Def::Type(type1), Def::Ident(DefIdent(ident)), Def::Type(type2))
515						if ident == "auto" =>
516					{
517						match (type1.ident_str(), type2.ident_str()) {
518							("Number", "Length") | ("Length", "Number") => {
519								Def::AutoOr(Box::new(Def::Type(DefType::new("NumberLength", type1.range.clone()))))
520							}
521							("Percentage", "Length") | ("Length", "Percentage") => {
522								Def::AutoOr(Box::new(Def::Type(DefType::new("LengthPercentage", type1.range.clone()))))
523							}
524							("Number", "Percentage") | ("Percentage", "Number") => {
525								Def::AutoOr(Box::new(Def::Type(DefType::new("NumberPercentage", type1.range.clone()))))
526							}
527							("LengthPercentage", "Number") | ("Number", "LengthPercentage") => Def::AutoOr(Box::new(
528								Def::Type(DefType::new("LengthPercentageNumber", type1.range.clone())),
529							)),
530							_ => {
531								return Self::Combinator(
532									vec![first.optimize(), second.optimize(), third.optimize()],
533									DefCombinatorStyle::Alternatives,
534								);
535							}
536						}
537					}
538					// "<x> | <length-percentage> | <flex>" can be simplified to "<x> | <length-percentage-or-flex>"
539					// "<x> | <number> | <percentage>" can be simplified to "<number-or-percentage>"
540					(def, Def::Type(type1), Def::Type(type2))
541					| (Def::Type(type1), def, Def::Type(type2))
542					| (Def::Type(type1), Def::Type(type2), def) => match (type1.ident_str(), type2.ident_str()) {
543						("LengthPercentage", "Flex") | ("Flex", "LengthPercentage") => Def::Combinator(
544							vec![
545								def.optimize(),
546								Def::Type(DefType::new("LengthPercentageOrFlex", type1.range.clone())),
547							],
548							DefCombinatorStyle::Alternatives,
549						),
550						("Number", "Percentage") | ("Percentage", "Number") => Def::Combinator(
551							vec![def.optimize(), Def::Type(DefType::new("NumberPercentage", type1.range.clone()))],
552							DefCombinatorStyle::Alternatives,
553						),
554						("Number", "Length") | ("Length", "Number") => Def::Combinator(
555							vec![def.optimize(), Def::Type(DefType::new("NumberLength", type1.range.clone()))],
556							DefCombinatorStyle::Alternatives,
557						),
558						_ => {
559							return Self::Combinator(
560								vec![first.optimize(), second.optimize(), third.optimize()],
561								DefCombinatorStyle::Alternatives,
562							);
563						}
564					},
565					_ => {
566						return Self::Combinator(
567							vec![first.optimize(), second.optimize(), third.optimize()],
568							DefCombinatorStyle::Alternatives,
569						);
570					}
571				}
572			}
573			Self::Combinator(defs, style) => {
574				// First optimize all children.
575				let optimized: Vec<Def> = defs.iter().map(|d| d.optimize()).collect();
576				let is_repeated_multiplier = {
577					let extractable: Vec<_> = optimized.iter().filter_map(Self::extract_alternatives).collect();
578					extractable.len() == optimized.len() && {
579						let first = extractable[0].0;
580						extractable.iter().all(|(alts, _)| *alts == first)
581					}
582				};
583				let exempt_keyword_groups = matches!(style, DefCombinatorStyle::Options)
584					&& optimized.iter().filter(|c| Self::is_keyword_group(c)).count() >= 2;
585				if !matches!(style, DefCombinatorStyle::Alternatives)
586					&& !is_repeated_multiplier
587					&& let Some((group_idx, alts, wrap_optional)) = optimized.iter().enumerate().find_map(|(i, c)| {
588						if exempt_keyword_groups && Self::is_keyword_group(c) {
589							return None;
590						}
591						Self::extract_distributable(c, *style).map(|(alts, wrap)| (i, alts, wrap))
592					}) {
593					let prefix = &optimized[..group_idx];
594					let suffix = &optimized[group_idx + 1..];
595					let mut distributed: Vec<Def> = alts
596						.iter()
597						.map(|alt| {
598							let mut new_children: Vec<Def> = prefix.to_vec();
599							new_children.push(alt.clone());
600							new_children.extend_from_slice(suffix);
601							Def::Combinator(new_children, *style)
602						})
603						.collect();
604					if wrap_optional {
605						let mut absent: Vec<Def> = prefix.to_vec();
606						absent.extend_from_slice(suffix);
607						match absent.len() {
608							0 => {}
609							1 => {
610								let single = absent.into_iter().next().unwrap();
611								if let Some((alts, _)) = Self::extract_alternatives(&single) {
612									distributed.extend(alts.iter().cloned());
613								} else {
614									distributed.push(single);
615								}
616							}
617							_ => distributed.push(Def::Combinator(absent, *style)),
618						}
619					}
620					return Self::Combinator(distributed, DefCombinatorStyle::Alternatives).optimize();
621				}
622				return Self::Combinator(optimized, *style);
623			}
624			// Optimize multiplier styles to avoid unnecessarily allocating.
625			// A Multiplier with a fixed range can be normalised to an Ordered combinator of the same value.
626			Self::Multiplier(inner, DefMultiplierSeparator::None, DefRange::Fixed(i)) => {
627				let opts: Vec<_> = (1..=*i as u32).map(|_| inner.deref().clone()).collect();
628				Self::Combinator(opts, DefCombinatorStyle::Ordered)
629			}
630			// Optimize multiplier styles to avoid unnecessarily allocating.
631			// A multiplier with a bounded range can be normalised to an Ordered combinator of some optionals.
632			Self::Multiplier(inner, DefMultiplierSeparator::None, DefRange::Range(Range { start, end })) => {
633				let opts: Vec<Def> = (1..=*end as i32)
634					.map(|i| if i <= (*start as i32) { inner.deref().clone() } else { Self::Optional(inner.clone()) })
635					.collect();
636				Self::Combinator(opts, DefCombinatorStyle::Ordered)
637			}
638			Self::Multiplier(inner, sep, range) => {
639				return Self::Multiplier(Box::new(inner.optimize()), *sep, range.clone());
640			}
641			Self::Optional(inner) => return Self::Optional(Box::new(inner.optimize())),
642			Self::Group(inner, DefGroupStyle::OneMustOccur)
643				if matches!(inner.as_ref(), Self::Combinator(defs, DefCombinatorStyle::Ordered)
644					if defs.iter().any(|def| matches!(def, Self::Optional(_)))) =>
645			{
646				let Self::Combinator(defs, _) = inner.as_ref() else { unreachable!("guarded above") };
647				let mut alternatives = Vec::with_capacity(defs.len());
648				for (i, def) in defs.iter().enumerate() {
649					let mut children = Vec::with_capacity(defs.len() - i);
650					children.push(if let Self::Optional(required) = def {
651						required.deref().clone()
652					} else {
653						def.clone()
654					});
655					children.extend_from_slice(&defs[i + 1..]);
656					alternatives.push(if children.len() == 1 {
657						children.remove(0)
658					} else {
659						Self::Combinator(children, DefCombinatorStyle::Ordered)
660					});
661					if !matches!(def, Self::Optional(_)) {
662						break;
663					}
664				}
665				Self::Combinator(alternatives, DefCombinatorStyle::Alternatives)
666			}
667			Self::Group(inner, style) => return Self::Group(Box::new(inner.optimize()), *style),
668			_ => return self.clone(),
669		}
670		.optimize()
671	}
672
673	fn extract_alternatives(def: &Def) -> Option<(&[Def], bool)> {
674		match def {
675			Def::Combinator(alts, DefCombinatorStyle::Alternatives) => Some((alts, false)),
676			Def::Group(inner, _) => {
677				if let Def::Combinator(alts, DefCombinatorStyle::Alternatives) = inner.as_ref() {
678					Some((alts, false))
679				} else {
680					None
681				}
682			}
683			Def::Optional(inner) => {
684				let inner_def = match inner.as_ref() {
685					Def::Group(g, _) => g.as_ref(),
686					other => other,
687				};
688				if let Def::Combinator(alts, DefCombinatorStyle::Alternatives) = inner_def {
689					Some((alts, true))
690				} else {
691					None
692				}
693			}
694			_ => None,
695		}
696	}
697
698	fn is_keyword_group(def: &Def) -> bool {
699		Self::extract_alternatives(def)
700			.is_some_and(|(alts, wrapped)| !wrapped && alts.iter().all(|d| matches!(d, Def::Ident(_))))
701	}
702
703	/// Extracts alternatives that need distribution for the given combinator style.
704	/// For top-level Ordered structs, all-keyword alternatives are handled by codegen's
705	/// `is_all_keywords()` → `keyword_ident` path and don't need distribution.
706	/// For AllMustOccur and other styles, all alternatives need distribution.
707	fn extract_distributable(def: &Def, style: DefCombinatorStyle) -> Option<(&[Def], bool)> {
708		Self::extract_alternatives(def).filter(|(alts, _)| {
709			!matches!(style, DefCombinatorStyle::Ordered) || !alts.iter().all(|d| matches!(d, Def::Ident(_)))
710		})
711	}
712
713	fn has_distributable_group(def: &Def) -> bool {
714		match def {
715			Def::Combinator(children, DefCombinatorStyle::Ordered | DefCombinatorStyle::AllMustOccur) => {
716				let extractable: Vec<_> = children.iter().filter_map(Self::extract_alternatives).collect();
717				if extractable.is_empty() {
718					return false;
719				}
720				if extractable.len() == children.len() {
721					let first_alts = extractable[0].0;
722					if extractable.iter().all(|(alts, _)| *alts == first_alts) {
723						return false;
724					}
725				}
726				true
727			}
728			_ => false,
729		}
730	}
731
732	/// Returns the keyword name if `self` is a keyword-optional-prefixed ordered sequence:
733	/// either `Group(Ordered([Optional(Ident(kw)), ...]))` or a bare
734	/// `Combinator(Ordered, [Optional(Ident(kw)), ...])` (groups are elided by optimize()).
735	/// These need a named helper struct so that `Peek` includes both the optional keyword
736	/// and the required subsequent tokens.
737	pub fn keyword_prefix_name(&self) -> Option<&str> {
738		let inner = match self {
739			Def::Group(inner, _) => inner.as_ref(),
740			Def::Combinator(_, DefCombinatorStyle::Ordered) => self,
741			_ => return None,
742		};
743		if let Def::Combinator(defs, DefCombinatorStyle::Ordered) = inner
744			&& let Some(Def::Optional(first)) = defs.first()
745			&& let Def::Ident(DefIdent(name)) = first.as_ref()
746		{
747			return Some(name.as_str());
748		}
749		None
750	}
751}
752
753impl Parse for DefIdent {
754	fn parse(input: ParseStream) -> Result<Self> {
755		let mut str = "".to_owned();
756		let mut last_was_ident = false;
757		loop {
758			if input.peek(Token![>]) || input.peek(token::Bracket) {
759				return Ok(Self(str));
760			} else if input.peek(Ident::peek_any) && !last_was_ident {
761				last_was_ident = true;
762				let ident = input.call(Ident::parse_any)?;
763				str.push_str(&ident.to_string());
764			// LitInt might pick up identifier parts like "3d"
765			} else if input.peek(LitInt) && last_was_ident {
766				last_was_ident = true;
767				let int = input.parse::<LitInt>()?;
768				str.push_str(&int.to_string());
769			} else if input.peek(Token![-]) {
770				last_was_ident = false;
771				input.parse::<Token![-]>()?;
772				str.push('-');
773			} else {
774				return Ok(Self(str));
775			}
776		}
777	}
778}
779
780impl Parse for DefRange {
781	fn parse(input: ParseStream) -> Result<Self> {
782		let mut lhs = None;
783		let mut rhs = None;
784		if input.peek(LitFloat) {
785			lhs = Some(input.parse::<LitFloat>()?.base10_parse()?);
786		} else if input.peek(LitInt) {
787			lhs = Some(input.parse::<LitInt>()?.base10_parse::<f32>()?);
788		}
789		if input.peek(Token![,]) {
790			input.parse::<Token![,]>()?;
791			if input.peek(LitFloat) {
792				rhs = Some(input.parse::<LitFloat>()?.base10_parse()?);
793			} else if input.peek(LitInt) {
794				rhs = Some(input.parse::<LitInt>()?.base10_parse::<f32>()?);
795			}
796		} else if let Some(lhs) = lhs {
797			return Ok(Self::Fixed(lhs));
798		}
799		Ok(match (lhs, rhs) {
800			(Some(start), Some(end)) => Self::Range(Range { start, end }),
801			(None, Some(end)) => Self::RangeTo(end),
802			(Some(start), None) => Self::RangeFrom(start),
803			(None, None) => Self::None,
804		})
805	}
806}
807
808pub enum DataType {
809	SingleUnnamedStruct,
810	Enum,
811}
812
813impl DataType {
814	pub fn is_struct(&self) -> bool {
815		matches!(self, Self::SingleUnnamedStruct)
816	}
817
818	pub fn is_enum(&self) -> bool {
819		matches!(self, Self::Enum)
820	}
821}
822
823impl Display for DefIdent {
824	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
825		self.0.fmt(f)
826	}
827}
828
829impl ToTokens for DefIdent {
830	fn to_tokens(&self, tokens: &mut TokenStream) {
831		tokens.append(Ident::new(&self.to_string(), Span::call_site()));
832	}
833}
834
835impl From<DefIdent> for Ident {
836	fn from(value: DefIdent) -> Self {
837		format_ident!("{}", value.0)
838	}
839}
840
841impl From<Ident> for DefIdent {
842	fn from(value: Ident) -> Self {
843		Self(value.to_string())
844	}
845}