Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/syntax/ast.rs

45.7 KiB, 1 run

created by r1870400018:63560, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// SPDX-License-Identifier: Apache-2.0
2// Portions Copyright (c) The Typst Project Developers, from typst-syntax 0.15.1's `src/ast.rs`; see
3// fe2o3_austenite/licences/typst-LICENSE.txt for the full Apache-2.0 text.
4// Modified for Austenite.
5//! Ported from typst-syntax 0.15.1 (`src/ast.rs`, Apache-2.0, (c) the Typst authors): typed, zero-cost
6//! views over [`SyntaxNode`], with the same names and accessors, so the evaluator reads the tree as
7//! typst-eval does. A view never panics on a malformed tree: where the child it wants is missing it
8//! falls back to a placeholder, and the error node already in the tree carries the diagnostic.
9
10use crate::syntax::{
11 Span,
12 SyntaxKind,
13 SyntaxNode,
14};
15use crate::syntax::lexer::{
16 Scanner,
17 is_ident,
18 is_newline,
19};
20
21use std::ops::Deref;
22use std::path::Path;
23
24/// A typed view of a node.
25pub trait AstNode<'a>: Sized {
26 fn from_untyped(node: &'a SyntaxNode) -> Option<Self>;
27 fn to_untyped(self) -> &'a SyntaxNode;
28 /// A view over a detached placeholder node, for a child the tree lacks.
29 fn placeholder() -> Self;
30 fn span(self) -> Span { self.to_untyped().span() }
31}
32
33impl SyntaxNode {
34 /// Can the node be viewed as `T`?
35 pub fn is<'a, T: AstNode<'a>>(&'a self) -> bool { self.cast::<T>().is_some() }
36
37 pub fn cast<'a, T: AstNode<'a>>(&'a self) -> Option<T> { T::from_untyped(self) }
38
39 pub fn try_cast_first<'a, T: AstNode<'a>>(&'a self) -> Option<T> {
40 self.children().iter().find_map(|c| c.cast())
41 }
42
43 pub fn try_cast_last<'a, T: AstNode<'a>>(&'a self) -> Option<T> {
44 self.children().iter().rev().find_map(|c| c.cast())
45 }
46
47 pub fn cast_first<'a, T: AstNode<'a>>(&'a self) -> T {
48 match self.try_cast_first() {
49 Some(t) => t,
50 Option::None => T::placeholder(),
51 }
52 }
53
54 pub fn cast_last<'a, T: AstNode<'a>>(&'a self) -> T {
55 match self.try_cast_last() {
56 Some(t) => t,
57 Option::None => T::placeholder(),
58 }
59 }
60}
61
62macro_rules! node {
63 ($(#[$attr:meta])* struct $name:ident) => {
64 $(#[$attr])*
65 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
66 #[repr(transparent)]
67 pub struct $name<'a>(&'a SyntaxNode);
68
69 impl<'a> AstNode<'a> for $name<'a> {
70 #[inline]
71 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
72 if node.kind() == SyntaxKind::$name { Some(Self(node)) } else { Option::None }
73 }
74
75 #[inline]
76 fn to_untyped(self) -> &'a SyntaxNode { self.0 }
77
78 #[inline]
79 fn placeholder() -> Self {
80 static PLACEHOLDER: SyntaxNode = SyntaxNode::placeholder(SyntaxKind::$name);
81 Self(&PLACEHOLDER)
82 }
83 }
84 };
85}
86
87// ┌───────────────────────────────────────────────────────────────────────────────────────────┐
88// │ Comments and markup │
89// └───────────────────────────────────────────────────────────────────────────────────────────┘
90
91node! { struct LineComment }
92
93impl<'a> LineComment<'a> {
94 pub fn text(&self) -> &'a str {
95 let t = self.0.text();
96 match t.strip_prefix("//") {
97 Some(s) => s,
98 Option::None => t,
99 }
100 }
101}
102
103node! { struct BlockComment }
104
105impl<'a> BlockComment<'a> {
106 pub fn text(&self) -> &'a str {
107 let t = self.0.text();
108 match t.strip_prefix("/*").and_then(|s| s.strip_suffix("*/")) {
109 Some(s) => s,
110 Option::None => t,
111 }
112 }
113}
114
115node! {
116 /// The root of a file, and the body of a content block, heading, list item and so on.
117 struct Markup
118}
119
120impl<'a> Markup<'a> {
121 /// The expressions, spaces included, except the line break straight after a statement written
122 /// without a semicolon.
123 pub fn exprs(self) -> impl DoubleEndedIterator<Item = Expr<'a>> {
124 let mut was_stmt = false;
125 self.0.children().iter()
126 .filter(move |n| {
127 let kind = n.kind();
128 let keep = !was_stmt || kind != SyntaxKind::Space;
129 was_stmt = kind.is_stmt();
130 keep
131 })
132 .filter_map(Expr::cast_with_space)
133 }
134}
135
136/// Any expression, in any of the three modes.
137#[derive(Debug, Copy, Clone, Hash)]
138pub enum Expr<'a> {
139 Text(Text<'a>),
140 Space(Space<'a>),
141 Linebreak(Linebreak<'a>),
142 Parbreak(Parbreak<'a>),
143 Escape(Escape<'a>),
144 Shorthand(Shorthand<'a>),
145 SmartQuote(SmartQuote<'a>),
146 Strong(Strong<'a>),
147 Emph(Emph<'a>),
148 Raw(Raw<'a>),
149 Link(Link<'a>),
150 Label(Label<'a>),
151 Ref(Ref<'a>),
152 Heading(Heading<'a>),
153 ListItem(ListItem<'a>),
154 EnumItem(EnumItem<'a>),
155 TermItem(TermItem<'a>),
156 Equation(Equation<'a>),
157 Math(Math<'a>),
158 MathText(MathText<'a>),
159 MathIdent(MathIdent<'a>),
160 MathFieldAccess(MathFieldAccess<'a>),
161 MathShorthand(MathShorthand<'a>),
162 MathAlignPoint(MathAlignPoint<'a>),
163 MathCall(MathCall<'a>),
164 MathDelimited(MathDelimited<'a>),
165 MathAttach(MathAttach<'a>),
166 MathPrimes(MathPrimes<'a>),
167 MathFrac(MathFrac<'a>),
168 MathRoot(MathRoot<'a>),
169 Ident(Ident<'a>),
170 None(None<'a>),
171 Auto(Auto<'a>),
172 Bool(Bool<'a>),
173 Int(Int<'a>),
174 Float(Float<'a>),
175 Numeric(Numeric<'a>),
176 Str(Str<'a>),
177 CodeBlock(CodeBlock<'a>),
178 ContentBlock(ContentBlock<'a>),
179 Parenthesized(Parenthesized<'a>),
180 Array(Array<'a>),
181 Dict(Dict<'a>),
182 Unary(Unary<'a>),
183 Binary(Binary<'a>),
184 FieldAccess(FieldAccess<'a>),
185 FuncCall(FuncCall<'a>),
186 Closure(Closure<'a>),
187 LetBinding(LetBinding<'a>),
188 DestructAssignment(DestructAssignment<'a>),
189 SetRule(SetRule<'a>),
190 ShowRule(ShowRule<'a>),
191 Contextual(Contextual<'a>),
192 Conditional(Conditional<'a>),
193 WhileLoop(WhileLoop<'a>),
194 ForLoop(ForLoop<'a>),
195 ModuleImport(ModuleImport<'a>),
196 ModuleInclude(ModuleInclude<'a>),
197 LoopBreak(LoopBreak<'a>),
198 LoopContinue(LoopContinue<'a>),
199 FuncReturn(FuncReturn<'a>),
200}
201
202impl<'a> Expr<'a> {
203 fn cast_with_space(node: &'a SyntaxNode) -> Option<Self> {
204 match node.kind() {
205 SyntaxKind::Space => Some(Self::Space(Space(node))),
206 _ => Self::from_untyped(node),
207 }
208 }
209}
210
211impl<'a> AstNode<'a> for Expr<'a> {
212 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
213 let n = node;
214 Some(match node.kind() {
215 SyntaxKind::Space => return Option::None, // only through `cast_with_space`
216 SyntaxKind::Linebreak => Self::Linebreak(Linebreak(n)),
217 SyntaxKind::Parbreak => Self::Parbreak(Parbreak(n)),
218 SyntaxKind::Text => Self::Text(Text(n)),
219 SyntaxKind::Escape => Self::Escape(Escape(n)),
220 SyntaxKind::Shorthand => Self::Shorthand(Shorthand(n)),
221 SyntaxKind::SmartQuote => Self::SmartQuote(SmartQuote(n)),
222 SyntaxKind::Strong => Self::Strong(Strong(n)),
223 SyntaxKind::Emph => Self::Emph(Emph(n)),
224 SyntaxKind::Raw => Self::Raw(Raw(n)),
225 SyntaxKind::Link => Self::Link(Link(n)),
226 SyntaxKind::Label => Self::Label(Label(n)),
227 SyntaxKind::Ref => Self::Ref(Ref(n)),
228 SyntaxKind::Heading => Self::Heading(Heading(n)),
229 SyntaxKind::ListItem => Self::ListItem(ListItem(n)),
230 SyntaxKind::EnumItem => Self::EnumItem(EnumItem(n)),
231 SyntaxKind::TermItem => Self::TermItem(TermItem(n)),
232 SyntaxKind::Equation => Self::Equation(Equation(n)),
233 SyntaxKind::Math => Self::Math(Math(n)),
234 SyntaxKind::MathText => Self::MathText(MathText(n)),
235 SyntaxKind::MathIdent => Self::MathIdent(MathIdent(n)),
236 SyntaxKind::MathFieldAccess => Self::MathFieldAccess(MathFieldAccess(n)),
237 SyntaxKind::MathShorthand => Self::MathShorthand(MathShorthand(n)),
238 SyntaxKind::MathAlignPoint => Self::MathAlignPoint(MathAlignPoint(n)),
239 SyntaxKind::MathCall => Self::MathCall(MathCall(n)),
240 SyntaxKind::MathDelimited => Self::MathDelimited(MathDelimited(n)),
241 SyntaxKind::MathAttach => Self::MathAttach(MathAttach(n)),
242 SyntaxKind::MathPrimes => Self::MathPrimes(MathPrimes(n)),
243 SyntaxKind::MathFrac => Self::MathFrac(MathFrac(n)),
244 SyntaxKind::MathRoot => Self::MathRoot(MathRoot(n)),
245 SyntaxKind::Ident => Self::Ident(Ident(n)),
246 SyntaxKind::None => Self::None(None(n)),
247 SyntaxKind::Auto => Self::Auto(Auto(n)),
248 SyntaxKind::Bool => Self::Bool(Bool(n)),
249 SyntaxKind::Int => Self::Int(Int(n)),
250 SyntaxKind::Float => Self::Float(Float(n)),
251 SyntaxKind::Numeric => Self::Numeric(Numeric(n)),
252 SyntaxKind::Str => Self::Str(Str(n)),
253 SyntaxKind::CodeBlock => Self::CodeBlock(CodeBlock(n)),
254 SyntaxKind::ContentBlock => Self::ContentBlock(ContentBlock(n)),
255 SyntaxKind::Parenthesized => Self::Parenthesized(Parenthesized(n)),
256 SyntaxKind::Array => Self::Array(Array(n)),
257 SyntaxKind::Dict => Self::Dict(Dict(n)),
258 SyntaxKind::Unary => Self::Unary(Unary(n)),
259 SyntaxKind::Binary => Self::Binary(Binary(n)),
260 SyntaxKind::FieldAccess => Self::FieldAccess(FieldAccess(n)),
261 SyntaxKind::FuncCall => Self::FuncCall(FuncCall(n)),
262 SyntaxKind::Closure => Self::Closure(Closure(n)),
263 SyntaxKind::LetBinding => Self::LetBinding(LetBinding(n)),
264 SyntaxKind::DestructAssignment => Self::DestructAssignment(DestructAssignment(n)),
265 SyntaxKind::SetRule => Self::SetRule(SetRule(n)),
266 SyntaxKind::ShowRule => Self::ShowRule(ShowRule(n)),
267 SyntaxKind::Contextual => Self::Contextual(Contextual(n)),
268 SyntaxKind::Conditional => Self::Conditional(Conditional(n)),
269 SyntaxKind::WhileLoop => Self::WhileLoop(WhileLoop(n)),
270 SyntaxKind::ForLoop => Self::ForLoop(ForLoop(n)),
271 SyntaxKind::ModuleImport => Self::ModuleImport(ModuleImport(n)),
272 SyntaxKind::ModuleInclude => Self::ModuleInclude(ModuleInclude(n)),
273 SyntaxKind::LoopBreak => Self::LoopBreak(LoopBreak(n)),
274 SyntaxKind::LoopContinue => Self::LoopContinue(LoopContinue(n)),
275 SyntaxKind::FuncReturn => Self::FuncReturn(FuncReturn(n)),
276 _ => return Option::None,
277 })
278 }
279
280 fn to_untyped(self) -> &'a SyntaxNode {
281 match self {
282 Self::Text(v) => v.0,
283 Self::Space(v) => v.0,
284 Self::Linebreak(v) => v.0,
285 Self::Parbreak(v) => v.0,
286 Self::Escape(v) => v.0,
287 Self::Shorthand(v) => v.0,
288 Self::SmartQuote(v) => v.0,
289 Self::Strong(v) => v.0,
290 Self::Emph(v) => v.0,
291 Self::Raw(v) => v.0,
292 Self::Link(v) => v.0,
293 Self::Label(v) => v.0,
294 Self::Ref(v) => v.0,
295 Self::Heading(v) => v.0,
296 Self::ListItem(v) => v.0,
297 Self::EnumItem(v) => v.0,
298 Self::TermItem(v) => v.0,
299 Self::Equation(v) => v.0,
300 Self::Math(v) => v.0,
301 Self::MathText(v) => v.0,
302 Self::MathIdent(v) => v.0,
303 Self::MathFieldAccess(v) => v.0,
304 Self::MathShorthand(v) => v.0,
305 Self::MathAlignPoint(v) => v.0,
306 Self::MathCall(v) => v.0,
307 Self::MathDelimited(v) => v.0,
308 Self::MathAttach(v) => v.0,
309 Self::MathPrimes(v) => v.0,
310 Self::MathFrac(v) => v.0,
311 Self::MathRoot(v) => v.0,
312 Self::Ident(v) => v.0,
313 Self::None(v) => v.0,
314 Self::Auto(v) => v.0,
315 Self::Bool(v) => v.0,
316 Self::Int(v) => v.0,
317 Self::Float(v) => v.0,
318 Self::Numeric(v) => v.0,
319 Self::Str(v) => v.0,
320 Self::CodeBlock(v) => v.0,
321 Self::ContentBlock(v) => v.0,
322 Self::Parenthesized(v) => v.0,
323 Self::Array(v) => v.0,
324 Self::Dict(v) => v.0,
325 Self::Unary(v) => v.0,
326 Self::Binary(v) => v.0,
327 Self::FieldAccess(v) => v.0,
328 Self::FuncCall(v) => v.0,
329 Self::Closure(v) => v.0,
330 Self::LetBinding(v) => v.0,
331 Self::DestructAssignment(v) => v.0,
332 Self::SetRule(v) => v.0,
333 Self::ShowRule(v) => v.0,
334 Self::Contextual(v) => v.0,
335 Self::Conditional(v) => v.0,
336 Self::WhileLoop(v) => v.0,
337 Self::ForLoop(v) => v.0,
338 Self::ModuleImport(v) => v.0,
339 Self::ModuleInclude(v) => v.0,
340 Self::LoopBreak(v) => v.0,
341 Self::LoopContinue(v) => v.0,
342 Self::FuncReturn(v) => v.0,
343 }
344 }
345
346 fn placeholder() -> Self { Self::None(None::placeholder()) }
347}
348
349impl Expr<'_> {
350 /// Can the expression follow a `#` in markup or maths?
351 pub fn hash(self) -> bool {
352 matches!(self,
353 Self::Ident(_) | Self::None(_) | Self::Auto(_) | Self::Bool(_) | Self::Int(_) | Self::Float(_)
354 | Self::Numeric(_) | Self::Str(_) | Self::CodeBlock(_) | Self::ContentBlock(_) | Self::Array(_)
355 | Self::Dict(_) | Self::Parenthesized(_) | Self::FieldAccess(_) | Self::FuncCall(_)
356 | Self::LetBinding(_) | Self::SetRule(_) | Self::ShowRule(_) | Self::Contextual(_)
357 | Self::Conditional(_) | Self::WhileLoop(_) | Self::ForLoop(_) | Self::ModuleImport(_)
358 | Self::ModuleInclude(_) | Self::LoopBreak(_) | Self::LoopContinue(_) | Self::FuncReturn(_))
359 }
360
361 pub fn is_literal(self) -> bool {
362 matches!(self,
363 Self::None(_) | Self::Auto(_) | Self::Bool(_) | Self::Int(_) | Self::Float(_) | Self::Numeric(_)
364 | Self::Str(_))
365 }
366}
367
368node! { struct Text }
369
370impl<'a> Text<'a> {
371 pub fn get(self) -> &'a str { self.0.text() }
372}
373
374node! { struct Space }
375node! { struct Linebreak }
376node! { struct Parbreak }
377
378node! { struct Escape }
379
380impl Escape<'_> {
381 /// The escaped char: `\#` is `#`, `\u{1F600}` is the code point.
382 pub fn get(self) -> char {
383 let mut s = Scanner::new(self.0.text());
384 s.eat_if('\\');
385 if s.eat_if("u{") {
386 let hex = s.eat_while(|c: char| c.is_ascii_hexdigit());
387 match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) {
388 Some(c) => c,
389 Option::None => char::default(),
390 }
391 } else {
392 match s.eat() {
393 Some(c) => c,
394 Option::None => char::default(),
395 }
396 }
397 }
398}
399
400node! { struct Shorthand }
401
402impl Shorthand<'_> {
403 pub const LIST: &'static [(&'static str, char)] = &[
404 ("...", '…'),
405 ("~", '\u{00A0}'),
406 ("-", '\u{2212}'), // only before a digit
407 ("--", '\u{2013}'),
408 ("---", '\u{2014}'),
409 ("-?", '\u{00AD}'),
410 ];
411
412 pub fn get(self) -> char { lookup(Self::LIST, self.0.text()) }
413}
414
415fn lookup(list: &[(&str, char)], text: &str) -> char {
416 match list.iter().find(|(s, _)| *s == text) {
417 Some((_, c)) => *c,
418 Option::None => char::default(),
419 }
420}
421
422node! { struct SmartQuote }
423
424impl SmartQuote<'_> {
425 pub fn double(self) -> bool { self.0.text() == "\"" }
426}
427
428node! { struct Strong }
429
430impl<'a> Strong<'a> {
431 pub fn body(self) -> Markup<'a> { self.0.cast_first() }
432}
433
434node! { struct Emph }
435
436impl<'a> Emph<'a> {
437 pub fn body(self) -> Markup<'a> { self.0.cast_first() }
438}
439
440node! { struct Raw }
441
442impl<'a> Raw<'a> {
443 /// The lines of text, without the trimmed indentation and newlines.
444 pub fn lines(self) -> impl DoubleEndedIterator<Item = Text<'a>> {
445 self.0.children().iter().filter_map(|c| c.cast())
446 }
447
448 /// The language tag; only a raw of three or more backticks has one.
449 pub fn lang(self) -> Option<RawLang<'a>> {
450 let delim: RawDelim = match self.0.try_cast_first() {
451 Some(d) => d,
452 Option::None => return Option::None,
453 };
454 if delim.0.len() < 3 {
455 return Option::None;
456 }
457 self.0.try_cast_first()
458 }
459
460 /// Is it a block: three or more backticks and a newline among the trimmed parts?
461 pub fn block(self) -> bool {
462 let blocky = match self.0.try_cast_first::<RawDelim>() {
463 Some(d) => d.0.len() >= 3,
464 Option::None => false,
465 };
466 blocky && self.0.children().iter().any(|e|
467 e.kind() == SyntaxKind::RawTrimmed && e.text().chars().any(is_newline))
468 }
469}
470
471node! { struct RawLang }
472
473impl<'a> RawLang<'a> {
474 pub fn get(self) -> &'a str { self.0.text() }
475}
476
477node! { struct RawDelim }
478
479node! { struct Link }
480
481impl<'a> Link<'a> {
482 pub fn get(self) -> &'a str { self.0.text() }
483}
484
485node! { struct Label }
486
487impl<'a> Label<'a> {
488 /// The name between the angle brackets.
489 pub fn get(self) -> &'a str { self.0.text().trim_start_matches('<').trim_end_matches('>') }
490}
491
492node! { struct Ref }
493
494impl<'a> Ref<'a> {
495 pub fn target(self) -> &'a str {
496 match self.0.children().iter().find(|n| n.kind() == SyntaxKind::RefMarker) {
497 Some(n) => n.text().trim_start_matches('@'),
498 Option::None => "",
499 }
500 }
501
502 pub fn supplement(self) -> Option<ContentBlock<'a>> { self.0.try_cast_last() }
503}
504
505node! { struct Heading }
506
507impl<'a> Heading<'a> {
508 pub fn body(self) -> Markup<'a> { self.0.cast_first() }
509
510 /// The number of `=` in the marker, at least one.
511 pub fn depth(self) -> usize {
512 match self.0.children().iter().find(|n| n.kind() == SyntaxKind::HeadingMarker) {
513 Some(n) if n.len() > 0 => n.len(),
514 _ => 1,
515 }
516 }
517}
518
519node! { struct ListItem }
520
521impl<'a> ListItem<'a> {
522 pub fn body(self) -> Markup<'a> { self.0.cast_first() }
523}
524
525node! { struct EnumItem }
526
527impl<'a> EnumItem<'a> {
528 /// The explicit number of a `3.` marker; `None` for `+`.
529 pub fn number(self) -> Option<u64> {
530 self.0.children().iter().find_map(|n| match n.kind() {
531 SyntaxKind::EnumMarker => n.text().trim_end_matches('.').parse().ok(),
532 _ => Option::None,
533 })
534 }
535
536 pub fn body(self) -> Markup<'a> { self.0.cast_first() }
537}
538
539node! { struct TermItem }
540
541impl<'a> TermItem<'a> {
542 pub fn term(self) -> Markup<'a> { self.0.cast_first() }
543 pub fn description(self) -> Markup<'a> { self.0.cast_last() }
544}
545
546node! { struct Equation }
547
548impl<'a> Equation<'a> {
549 pub fn body(self) -> Math<'a> { self.0.cast_first() }
550
551 /// Is it a display equation, with space inside both dollars?
552 pub fn block(self) -> bool {
553 let c = self.0.children();
554 let is_space = |n: Option<&SyntaxNode>| matches!(n.map(|n| n.kind()), Some(SyntaxKind::Space));
555 c.len() >= 2 && is_space(c.get(1)) && is_space(c.len().checked_sub(2).and_then(|i| c.get(i)))
556 }
557}
558
559// ┌───────────────────────────────────────────────────────────────────────────────────────────┐
560// │ Maths │
561// └───────────────────────────────────────────────────────────────────────────────────────────┘
562
563node! { struct Math }
564
565impl<'a> Math<'a> {
566 pub fn exprs(self) -> impl DoubleEndedIterator<Item = Expr<'a>> {
567 self.0.children().iter().filter_map(Expr::cast_with_space)
568 }
569
570 /// Did a fraction, attachment or root strip this sequence's round parentheses?
571 pub fn was_deparenthesized(self) -> bool {
572 let c = self.0.children();
573 matches!(c.first().map(|n| n.kind()), Some(SyntaxKind::LeftParen))
574 && matches!(c.last().map(|n| n.kind()), Some(SyntaxKind::RightParen))
575 }
576}
577
578node! { struct MathText }
579
580/// What a `MathText` holds: a number, possibly several chars, or one grapheme.
581pub enum MathTextKind<'a> {
582 Grapheme(&'a str),
583 Number(&'a str),
584}
585
586impl<'a> MathText<'a> {
587 pub fn get(self) -> MathTextKind<'a> {
588 let text = self.0.text();
589 match text.chars().next() {
590 Some(c) if c.is_numeric() => MathTextKind::Number(text),
591 _ => MathTextKind::Grapheme(text),
592 }
593 }
594}
595
596node! { struct MathIdent }
597
598impl<'a> MathIdent<'a> {
599 pub fn get(self) -> &'a str { self.0.text() }
600 pub fn as_str(self) -> &'a str { self.get() }
601}
602
603impl Deref for MathIdent<'_> {
604 type Target = str;
605 fn deref(&self) -> &Self::Target { self.0.text() }
606}
607
608node! { struct MathFieldAccess }
609
610impl<'a> MathFieldAccess<'a> {
611 pub fn target(self) -> MathAccess<'a> { self.0.cast_first() }
612 pub fn field(self) -> MathIdent<'a> { self.0.cast_last() }
613}
614
615/// The callee of a maths call: an identifier or a field access chain.
616#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
617pub enum MathAccess<'a> {
618 MathIdent(MathIdent<'a>),
619 MathFieldAccess(MathFieldAccess<'a>),
620}
621
622impl<'a> AstNode<'a> for MathAccess<'a> {
623 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
624 match node.kind() {
625 SyntaxKind::MathIdent => Some(Self::MathIdent(MathIdent(node))),
626 SyntaxKind::MathFieldAccess => Some(Self::MathFieldAccess(MathFieldAccess(node))),
627 _ => Option::None,
628 }
629 }
630
631 fn to_untyped(self) -> &'a SyntaxNode {
632 match self {
633 Self::MathIdent(v) => v.0,
634 Self::MathFieldAccess(v) => v.0,
635 }
636 }
637
638 fn placeholder() -> Self { Self::MathIdent(MathIdent::placeholder()) }
639}
640
641node! { struct MathShorthand }
642
643impl MathShorthand<'_> {
644 pub const LIST: &'static [(&'static str, char)] = &[
645 ("...", '…'),
646 ("-", '−'),
647 ("*", '∗'),
648 ("~", '∼'),
649 ("!=", '≠'),
650 (":=", '≔'),
651 ("::=", '⩴'),
652 ("=:", '≕'),
653 ("<<", '≪'),
654 ("<<<", '⋘'),
655 (">>", '≫'),
656 (">>>", '⋙'),
657 ("<=", '≤'),
658 (">=", '≥'),
659 ("->", '→'),
660 ("-->", '⟶'),
661 ("|->", '↦'),
662 (">->", '↣'),
663 ("->>", '↠'),
664 ("<-", '←'),
665 ("<--", '⟵'),
666 ("<-<", '↢'),
667 ("<<-", '↞'),
668 ("<->", '↔'),
669 ("<-->", '⟷'),
670 ("~>", '⇝'),
671 ("~~>", '⟿'),
672 ("<~", '⇜'),
673 ("<~~", '⬳'),
674 ("=>", '⇒'),
675 ("|=>", '⤇'),
676 ("==>", '⟹'),
677 ("<==", '⟸'),
678 ("<=>", '⇔'),
679 ("<==>", '⟺'),
680 ("[|", '⟦'),
681 ("|]", '⟧'),
682 ("||", '‖'),
683 ];
684
685 pub fn get(self) -> char { lookup(Self::LIST, self.0.text()) }
686}
687
688node! { struct MathCall }
689
690impl<'a> MathCall<'a> {
691 pub fn callee(self) -> MathAccess<'a> { self.0.cast_first() }
692 pub fn args(self) -> MathArgs<'a> { self.0.cast_last() }
693}
694
695node! { struct MathArgs }
696
697/// One argument of a maths call and whether a semicolon ends it, which makes rows of a matrix.
698#[derive(Debug, Copy, Clone, Hash)]
699pub struct MathArg<'a> {
700 pub arg: Arg<'a>,
701 pub ends_in_semicolon: bool,
702}
703
704/// An argument or a piece of punctuation of a maths call, for rebuilding the call as content when the
705/// callee is not a function.
706#[derive(Debug, Copy, Clone, Hash)]
707pub enum MathArgItem<'a> {
708 Arg(Arg<'a>),
709 Space(Space<'a>),
710 Comma(char, &'a SyntaxNode),
711 Semicolon(char, &'a SyntaxNode),
712 LeftParen(char, &'a SyntaxNode),
713 RightParen(char, &'a SyntaxNode),
714}
715
716impl<'a> MathArgs<'a> {
717 pub fn arg_items(self) -> impl Iterator<Item = MathArg<'a>> {
718 let mut items = self.content_items().peekable();
719 std::iter::from_fn(move || {
720 let arg = items.find_map(|n| match n {
721 MathArgItem::Arg(a) => Some(a),
722 _ => Option::None,
723 });
724 let arg = match arg {
725 Some(a) => a,
726 Option::None => return Option::None,
727 };
728 let ends_in_semicolon = loop {
729 match items.peek() {
730 Option::None | Some(MathArgItem::Arg(_)) => break false,
731 Some(MathArgItem::Semicolon(_, _)) => break true,
732 Some(_) => (),
733 }
734 items.next();
735 };
736 Some(MathArg { arg, ends_in_semicolon })
737 })
738 }
739
740 /// The arguments with the punctuation between them; a semicolon that ends an embedded code
741 /// expression (`#x;`) is not punctuation.
742 pub fn content_items(self) -> impl Iterator<Item = MathArgItem<'a>> {
743 let mut children = self.0.children().iter();
744 let mut prev_hash = false;
745 std::iter::from_fn(move || {
746 for node in children.by_ref() {
747 if let Some(arg) = node.cast() {
748 return Some(MathArgItem::Arg(arg));
749 }
750 let ends_code = prev_hash;
751 prev_hash = false;
752 let item = match node.kind() {
753 SyntaxKind::Space => MathArgItem::Space(Space(node)),
754 SyntaxKind::Comma => MathArgItem::Comma(',', node),
755 SyntaxKind::LeftParen => MathArgItem::LeftParen('(', node),
756 SyntaxKind::RightParen => MathArgItem::RightParen(')', node),
757 SyntaxKind::Semicolon if !ends_code => MathArgItem::Semicolon(';', node),
758 SyntaxKind::Hash => {
759 prev_hash = true;
760 continue;
761 },
762 _ => continue,
763 };
764 return Some(item);
765 }
766 Option::None
767 })
768 }
769}
770
771node! { struct MathAlignPoint }
772
773node! { struct MathDelimited }
774
775impl<'a> MathDelimited<'a> {
776 pub fn open(self) -> Expr<'a> { self.0.cast_first() }
777 pub fn body(self) -> Math<'a> { self.0.cast_first() }
778 pub fn close(self) -> Expr<'a> { self.0.cast_last() }
779}
780
781node! { struct MathAttach }
782
783impl<'a> MathAttach<'a> {
784 pub fn base(self) -> Expr<'a> { self.0.cast_first() }
785
786 pub fn bottom(self) -> Option<Expr<'a>> {
787 self.0.children().iter()
788 .skip_while(|n| n.kind() != SyntaxKind::Underscore)
789 .find_map(|n| n.cast())
790 }
791
792 pub fn top(self) -> Option<Expr<'a>> {
793 self.0.children().iter()
794 .skip_while(|n| n.kind() != SyntaxKind::Hat)
795 .find_map(|n| n.cast())
796 }
797
798 /// The primes straight after the base.
799 pub fn primes(self) -> Option<MathPrimes<'a>> {
800 self.0.children().iter()
801 .skip_while(|n| n.cast::<Expr<'_>>().is_none())
802 .nth(1)
803 .and_then(|n| n.cast())
804 }
805}
806
807node! { struct MathPrimes }
808
809impl MathPrimes<'_> {
810 pub fn count(self) -> usize { self.0.text().len() }
811}
812
813node! { struct MathFrac }
814
815impl<'a> MathFrac<'a> {
816 pub fn num(self) -> Expr<'a> { self.0.cast_first() }
817 pub fn denom(self) -> Expr<'a> { self.0.cast_last() }
818}
819
820node! { struct MathRoot }
821
822impl<'a> MathRoot<'a> {
823 /// 3 for `∛`, 4 for `∜`, none for `√`.
824 pub fn index(self) -> Option<u8> {
825 match self.0.children().first().map(|n| n.text()) {
826 Some("∜") => Some(4),
827 Some("∛") => Some(3),
828 _ => Option::None,
829 }
830 }
831
832 pub fn radicand(self) -> Expr<'a> { self.0.cast_first() }
833}
834
835// ┌───────────────────────────────────────────────────────────────────────────────────────────┐
836// │ Literals │
837// └───────────────────────────────────────────────────────────────────────────────────────────┘
838
839node! { struct Ident }
840
841impl<'a> Ident<'a> {
842 pub fn get(self) -> &'a str { self.0.text() }
843 pub fn as_str(self) -> &'a str { self.get() }
844}
845
846impl Deref for Ident<'_> {
847 type Target = str;
848 fn deref(&self) -> &Self::Target { self.0.text() }
849}
850
851node! { struct None }
852node! { struct Auto }
853
854node! { struct Bool }
855
856impl Bool<'_> {
857 pub fn get(self) -> bool { self.0.text() == "true" }
858}
859
860node! { struct Int }
861
862impl Int<'_> {
863 pub fn get(self) -> i64 {
864 let text = self.0.text();
865 let parsed = if let Some(rest) = text.strip_prefix("0x") {
866 i64::from_str_radix(rest, 16)
867 } else if let Some(rest) = text.strip_prefix("0o") {
868 i64::from_str_radix(rest, 8)
869 } else if let Some(rest) = text.strip_prefix("0b") {
870 i64::from_str_radix(rest, 2)
871 } else {
872 text.parse()
873 };
874 match parsed {
875 Ok(n) => n,
876 Err(_) => 0,
877 }
878 }
879}
880
881node! { struct Float }
882
883impl Float<'_> {
884 pub fn get(self) -> f64 {
885 match self.0.text().parse() {
886 Ok(f) => f,
887 Err(_) => 0.0,
888 }
889 }
890}
891
892node! { struct Numeric }
893
894impl Numeric<'_> {
895 pub fn get(self) -> (f64, Unit) {
896 let text = self.0.text();
897 let count = text.chars().rev().take_while(|c| matches!(c, 'a'..='z' | '%')).count();
898 let split = text.len() - count;
899 let value = match text.get(..split).map(|s| s.parse::<f64>()) {
900 Some(Ok(v)) => v,
901 _ => 0.0,
902 };
903 let unit = match text.get(split..) {
904 Some("pt") => Unit::Pt,
905 Some("mm") => Unit::Mm,
906 Some("cm") => Unit::Cm,
907 Some("in") => Unit::In,
908 Some("deg") => Unit::Deg,
909 Some("rad") => Unit::Rad,
910 Some("em") => Unit::Em,
911 Some("fr") => Unit::Fr,
912 _ => Unit::Percent,
913 };
914 (value, unit)
915 }
916}
917
918/// The unit of a numeric literal.
919#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
920pub enum Unit {
921 Pt,
922 Mm,
923 Cm,
924 In,
925 Rad,
926 Deg,
927 Em,
928 Fr,
929 Percent,
930}
931
932node! { struct Str }
933
934impl Str<'_> {
935 /// The string's value, escapes resolved.
936 pub fn get(self) -> String { unescape_str(self.0.text()) }
937}
938
939/// Resolves a quoted string literal: `\\ \" \n \r \t \u{..}`; any other escape stays as written.
940pub fn unescape_str(quoted: &str) -> String {
941 let inner = match quoted.get(1..quoted.len().saturating_sub(1)) {
942 Some(s) if quoted.len() >= 2 => s,
943 _ => "",
944 };
945 if !inner.contains('\\') {
946 return inner.to_string();
947 }
948 let mut out = String::with_capacity(inner.len());
949 let mut s = Scanner::new(inner);
950 while let Some(c) = s.eat() {
951 if c != '\\' {
952 out.push(c);
953 continue;
954 }
955 let start = s.cursor() - 1;
956 match s.eat() {
957 Some('\\') => out.push('\\'),
958 Some('"') => out.push('"'),
959 Some('n') => out.push('\n'),
960 Some('r') => out.push('\r'),
961 Some('t') => out.push('\t'),
962 Some('u') if s.eat_if('{') => {
963 let seq = s.eat_while(|c: char| c.is_ascii_hexdigit());
964 s.eat_if('}');
965 match u32::from_str_radix(seq, 16).ok().and_then(char::from_u32) {
966 Some(c) => out.push(c),
967 Option::None => out.push_str(s.from(start)),
968 }
969 },
970 _ => out.push_str(s.from(start)),
971 }
972 }
973 out
974}
975
976// ┌───────────────────────────────────────────────────────────────────────────────────────────┐
977// │ Code │
978// └───────────────────────────────────────────────────────────────────────────────────────────┘
979
980node! { struct CodeBlock }
981
982impl<'a> CodeBlock<'a> {
983 pub fn body(self) -> Code<'a> { self.0.cast_first() }
984}
985
986node! { struct Code }
987
988impl<'a> Code<'a> {
989 pub fn exprs(self) -> impl DoubleEndedIterator<Item = Expr<'a>> {
990 self.0.children().iter().filter_map(|c| c.cast())
991 }
992}
993
994node! { struct ContentBlock }
995
996impl<'a> ContentBlock<'a> {
997 pub fn body(self) -> Markup<'a> { self.0.cast_first() }
998}
999
1000node! { struct Parenthesized }
1001
1002impl<'a> Parenthesized<'a> {
1003 pub fn expr(self) -> Expr<'a> { self.0.cast_first() }
1004 pub fn pattern(self) -> Pattern<'a> { self.0.cast_first() }
1005}
1006
1007node! { struct Array }
1008
1009impl<'a> Array<'a> {
1010 pub fn items(self) -> impl DoubleEndedIterator<Item = ArrayItem<'a>> {
1011 self.0.children().iter().filter_map(|c| c.cast())
1012 }
1013}
1014
1015#[derive(Debug, Copy, Clone, Hash)]
1016pub enum ArrayItem<'a> {
1017 Pos(Expr<'a>),
1018 Spread(Spread<'a>),
1019}
1020
1021impl<'a> AstNode<'a> for ArrayItem<'a> {
1022 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
1023 match node.kind() {
1024 SyntaxKind::Spread => Some(Self::Spread(Spread(node))),
1025 _ => node.cast().map(Self::Pos),
1026 }
1027 }
1028
1029 fn to_untyped(self) -> &'a SyntaxNode {
1030 match self {
1031 Self::Pos(v) => v.to_untyped(),
1032 Self::Spread(v) => v.0,
1033 }
1034 }
1035
1036 fn placeholder() -> Self { Self::Pos(Expr::placeholder()) }
1037}
1038
1039node! { struct Dict }
1040
1041impl<'a> Dict<'a> {
1042 pub fn items(self) -> impl DoubleEndedIterator<Item = DictItem<'a>> {
1043 self.0.children().iter().filter_map(|c| c.cast())
1044 }
1045}
1046
1047#[derive(Debug, Copy, Clone, Hash)]
1048pub enum DictItem<'a> {
1049 Named(Named<'a>),
1050 Keyed(Keyed<'a>),
1051 Spread(Spread<'a>),
1052}
1053
1054impl<'a> AstNode<'a> for DictItem<'a> {
1055 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
1056 match node.kind() {
1057 SyntaxKind::Named => Some(Self::Named(Named(node))),
1058 SyntaxKind::Keyed => Some(Self::Keyed(Keyed(node))),
1059 SyntaxKind::Spread => Some(Self::Spread(Spread(node))),
1060 _ => Option::None,
1061 }
1062 }
1063
1064 fn to_untyped(self) -> &'a SyntaxNode {
1065 match self {
1066 Self::Named(v) => v.0,
1067 Self::Keyed(v) => v.0,
1068 Self::Spread(v) => v.0,
1069 }
1070 }
1071
1072 fn placeholder() -> Self { Self::Spread(Spread::placeholder()) }
1073}
1074
1075node! { struct Named }
1076
1077impl<'a> Named<'a> {
1078 pub fn name(self) -> Ident<'a> { self.0.cast_first() }
1079 pub fn expr(self) -> Expr<'a> { self.0.cast_last() }
1080 pub fn pattern(self) -> Pattern<'a> { self.0.cast_last() }
1081}
1082
1083node! { struct Keyed }
1084
1085impl<'a> Keyed<'a> {
1086 pub fn key(self) -> Expr<'a> { self.0.cast_first() }
1087 pub fn expr(self) -> Expr<'a> { self.0.cast_last() }
1088}
1089
1090node! { struct Spread }
1091
1092impl<'a> Spread<'a> {
1093 pub fn expr(self) -> Expr<'a> { self.0.cast_first() }
1094 pub fn sink_ident(self) -> Option<Ident<'a>> { self.0.try_cast_first() }
1095 pub fn sink_expr(self) -> Option<Expr<'a>> { self.0.try_cast_first() }
1096}
1097
1098node! { struct Unary }
1099
1100impl<'a> Unary<'a> {
1101 pub fn op(self) -> UnOp {
1102 match self.0.children().iter().find_map(|n| UnOp::from_kind(n.kind())) {
1103 Some(op) => op,
1104 Option::None => UnOp::Pos,
1105 }
1106 }
1107
1108 pub fn expr(self) -> Expr<'a> { self.0.cast_last() }
1109}
1110
1111/// A unary operator.
1112#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1113pub enum UnOp {
1114 Pos,
1115 Neg,
1116 Not,
1117}
1118
1119impl UnOp {
1120 pub fn from_kind(token: SyntaxKind) -> Option<Self> {
1121 match token {
1122 SyntaxKind::Plus => Some(Self::Pos),
1123 SyntaxKind::Minus => Some(Self::Neg),
1124 SyntaxKind::Not => Some(Self::Not),
1125 _ => Option::None,
1126 }
1127 }
1128
1129 pub fn precedence(self) -> u8 {
1130 match self {
1131 Self::Pos | Self::Neg => 7,
1132 Self::Not => 4,
1133 }
1134 }
1135
1136 pub fn as_str(self) -> &'static str {
1137 match self {
1138 Self::Pos => "+",
1139 Self::Neg => "-",
1140 Self::Not => "not",
1141 }
1142 }
1143}
1144
1145node! { struct Binary }
1146
1147impl<'a> Binary<'a> {
1148 pub fn op(self) -> BinOp {
1149 let mut not = false;
1150 let op = self.0.children().iter().find_map(|n| match n.kind() {
1151 SyntaxKind::Not => {
1152 not = true;
1153 Option::None
1154 },
1155 SyntaxKind::In if not => Some(BinOp::NotIn),
1156 k => BinOp::from_kind(k),
1157 });
1158 match op {
1159 Some(op) => op,
1160 Option::None => BinOp::Add,
1161 }
1162 }
1163
1164 pub fn lhs(self) -> Expr<'a> { self.0.cast_first() }
1165 pub fn rhs(self) -> Expr<'a> { self.0.cast_last() }
1166}
1167
1168/// A binary operator.
1169#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1170pub enum BinOp {
1171 Add,
1172 Sub,
1173 Mul,
1174 Div,
1175 And,
1176 Or,
1177 Eq,
1178 Neq,
1179 Lt,
1180 Leq,
1181 Gt,
1182 Geq,
1183 Assign,
1184 In,
1185 NotIn,
1186 AddAssign,
1187 SubAssign,
1188 MulAssign,
1189 DivAssign,
1190}
1191
1192impl BinOp {
1193 pub fn from_kind(token: SyntaxKind) -> Option<Self> {
1194 Some(match token {
1195 SyntaxKind::Plus => Self::Add,
1196 SyntaxKind::Minus => Self::Sub,
1197 SyntaxKind::Star => Self::Mul,
1198 SyntaxKind::Slash => Self::Div,
1199 SyntaxKind::And => Self::And,
1200 SyntaxKind::Or => Self::Or,
1201 SyntaxKind::EqEq => Self::Eq,
1202 SyntaxKind::ExclEq => Self::Neq,
1203 SyntaxKind::Lt => Self::Lt,
1204 SyntaxKind::LtEq => Self::Leq,
1205 SyntaxKind::Gt => Self::Gt,
1206 SyntaxKind::GtEq => Self::Geq,
1207 SyntaxKind::Eq => Self::Assign,
1208 SyntaxKind::In => Self::In,
1209 SyntaxKind::PlusEq => Self::AddAssign,
1210 SyntaxKind::HyphEq => Self::SubAssign,
1211 SyntaxKind::StarEq => Self::MulAssign,
1212 SyntaxKind::SlashEq => Self::DivAssign,
1213 _ => return Option::None,
1214 })
1215 }
1216
1217 pub fn precedence(self) -> u8 {
1218 match self {
1219 Self::Mul | Self::Div => 6,
1220 Self::Add | Self::Sub => 5,
1221 Self::Eq | Self::Neq | Self::Lt | Self::Leq | Self::Gt | Self::Geq
1222 | Self::In | Self::NotIn => 4,
1223 Self::And => 3,
1224 Self::Or => 2,
1225 Self::Assign | Self::AddAssign | Self::SubAssign | Self::MulAssign
1226 | Self::DivAssign => 1,
1227 }
1228 }
1229
1230 pub fn assoc(self) -> Assoc {
1231 match self {
1232 Self::Assign | Self::AddAssign | Self::SubAssign | Self::MulAssign | Self::DivAssign =>
1233 Assoc::Right,
1234 _ => Assoc::Left,
1235 }
1236 }
1237
1238 pub fn as_str(self) -> &'static str {
1239 match self {
1240 Self::Add => "+",
1241 Self::Sub => "-",
1242 Self::Mul => "*",
1243 Self::Div => "/",
1244 Self::And => "and",
1245 Self::Or => "or",
1246 Self::Eq => "==",
1247 Self::Neq => "!=",
1248 Self::Lt => "<",
1249 Self::Leq => "<=",
1250 Self::Gt => ">",
1251 Self::Geq => ">=",
1252 Self::In => "in",
1253 Self::NotIn => "not in",
1254 Self::Assign => "=",
1255 Self::AddAssign => "+=",
1256 Self::SubAssign => "-=",
1257 Self::MulAssign => "*=",
1258 Self::DivAssign => "/=",
1259 }
1260 }
1261}
1262
1263/// Which side an operator chain groups from.
1264#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1265pub enum Assoc {
1266 Left,
1267 Right,
1268}
1269
1270node! { struct FieldAccess }
1271
1272impl<'a> FieldAccess<'a> {
1273 pub fn target(self) -> Expr<'a> { self.0.cast_first() }
1274 pub fn field(self) -> Ident<'a> { self.0.cast_last() }
1275}
1276
1277node! { struct FuncCall }
1278
1279impl<'a> FuncCall<'a> {
1280 pub fn callee(self) -> Expr<'a> { self.0.cast_first() }
1281 pub fn args(self) -> Args<'a> { self.0.cast_last() }
1282}
1283
1284node! { struct Args }
1285
1286impl<'a> Args<'a> {
1287 pub fn items(self) -> impl DoubleEndedIterator<Item = Arg<'a>> {
1288 self.0.children().iter().filter_map(|c| c.cast())
1289 }
1290
1291 /// Does the parenthesised list end in a comma, as `(a,)` does?
1292 pub fn trailing_comma(self) -> bool {
1293 self.0.children().iter().rev().skip(1)
1294 .find(|n| !n.kind().is_trivia())
1295 .is_some_and(|n| n.kind() == SyntaxKind::Comma)
1296 }
1297}
1298
1299#[derive(Debug, Copy, Clone, Hash)]
1300pub enum Arg<'a> {
1301 Pos(Expr<'a>),
1302 Named(Named<'a>),
1303 Spread(Spread<'a>),
1304}
1305
1306impl<'a> AstNode<'a> for Arg<'a> {
1307 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
1308 match node.kind() {
1309 SyntaxKind::Named => Some(Self::Named(Named(node))),
1310 SyntaxKind::Spread => Some(Self::Spread(Spread(node))),
1311 _ => node.cast().map(Self::Pos),
1312 }
1313 }
1314
1315 fn to_untyped(self) -> &'a SyntaxNode {
1316 match self {
1317 Self::Pos(v) => v.to_untyped(),
1318 Self::Named(v) => v.0,
1319 Self::Spread(v) => v.0,
1320 }
1321 }
1322
1323 fn placeholder() -> Self { Self::Pos(Expr::placeholder()) }
1324}
1325
1326node! { struct Closure }
1327
1328impl<'a> Closure<'a> {
1329 /// The name of a `let f(x) = ..` closure.
1330 pub fn name(self) -> Option<Ident<'a>> { self.0.children().first().and_then(|n| n.cast()) }
1331 pub fn params(self) -> Params<'a> { self.0.cast_first() }
1332 pub fn body(self) -> Expr<'a> { self.0.cast_last() }
1333}
1334
1335node! { struct Params }
1336
1337impl<'a> Params<'a> {
1338 pub fn children(self) -> impl DoubleEndedIterator<Item = Param<'a>> {
1339 self.0.children().iter().filter_map(|c| c.cast())
1340 }
1341}
1342
1343#[derive(Debug, Copy, Clone, Hash)]
1344pub enum Param<'a> {
1345 Pos(Pattern<'a>),
1346 Named(Named<'a>),
1347 Spread(Spread<'a>),
1348}
1349
1350impl<'a> AstNode<'a> for Param<'a> {
1351 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
1352 match node.kind() {
1353 SyntaxKind::Named => Some(Self::Named(Named(node))),
1354 SyntaxKind::Spread => Some(Self::Spread(Spread(node))),
1355 _ => node.cast().map(Self::Pos),
1356 }
1357 }
1358
1359 fn to_untyped(self) -> &'a SyntaxNode {
1360 match self {
1361 Self::Pos(v) => v.to_untyped(),
1362 Self::Named(v) => v.0,
1363 Self::Spread(v) => v.0,
1364 }
1365 }
1366
1367 fn placeholder() -> Self { Self::Pos(Pattern::placeholder()) }
1368}
1369
1370/// A binding or reassignment target.
1371#[derive(Debug, Copy, Clone, Hash)]
1372pub enum Pattern<'a> {
1373 Normal(Expr<'a>),
1374 Placeholder(Underscore<'a>),
1375 Parenthesized(Parenthesized<'a>),
1376 Destructuring(Destructuring<'a>),
1377}
1378
1379impl<'a> AstNode<'a> for Pattern<'a> {
1380 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
1381 match node.kind() {
1382 SyntaxKind::Underscore => Some(Self::Placeholder(Underscore(node))),
1383 SyntaxKind::Parenthesized => Some(Self::Parenthesized(Parenthesized(node))),
1384 SyntaxKind::Destructuring => Some(Self::Destructuring(Destructuring(node))),
1385 _ => node.cast().map(Self::Normal),
1386 }
1387 }
1388
1389 fn to_untyped(self) -> &'a SyntaxNode {
1390 match self {
1391 Self::Normal(v) => v.to_untyped(),
1392 Self::Placeholder(v) => v.0,
1393 Self::Parenthesized(v) => v.0,
1394 Self::Destructuring(v) => v.0,
1395 }
1396 }
1397
1398 fn placeholder() -> Self { Self::Normal(Expr::placeholder()) }
1399}
1400
1401impl<'a> Pattern<'a> {
1402 /// The identifiers the pattern binds.
1403 pub fn bindings(self) -> Vec<Ident<'a>> {
1404 match self {
1405 Self::Normal(Expr::Ident(ident)) => vec![ident],
1406 Self::Parenthesized(v) => v.pattern().bindings(),
1407 Self::Destructuring(v) => v.bindings(),
1408 _ => Vec::new(),
1409 }
1410 }
1411}
1412
1413node! { struct Underscore }
1414
1415node! { struct Destructuring }
1416
1417impl<'a> Destructuring<'a> {
1418 pub fn items(self) -> impl DoubleEndedIterator<Item = DestructuringItem<'a>> {
1419 self.0.children().iter().filter_map(|c| c.cast())
1420 }
1421
1422 pub fn bindings(self) -> Vec<Ident<'a>> {
1423 self.items()
1424 .flat_map(|b| match b {
1425 DestructuringItem::Pattern(p) => p.bindings(),
1426 DestructuringItem::Named(n) => n.pattern().bindings(),
1427 DestructuringItem::Spread(s) => s.sink_ident().into_iter().collect(),
1428 })
1429 .collect()
1430 }
1431}
1432
1433#[derive(Debug, Copy, Clone, Hash)]
1434pub enum DestructuringItem<'a> {
1435 Pattern(Pattern<'a>),
1436 Named(Named<'a>),
1437 Spread(Spread<'a>),
1438}
1439
1440impl<'a> AstNode<'a> for DestructuringItem<'a> {
1441 fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
1442 match node.kind() {
1443 SyntaxKind::Named => Some(Self::Named(Named(node))),
1444 SyntaxKind::Spread => Some(Self::Spread(Spread(node))),
1445 _ => node.cast().map(Self::Pattern),
1446 }
1447 }
1448
1449 fn to_untyped(self) -> &'a SyntaxNode {
1450 match self {
1451 Self::Pattern(v) => v.to_untyped(),
1452 Self::Named(v) => v.0,
1453 Self::Spread(v) => v.0,
1454 }
1455 }
1456
1457 fn placeholder() -> Self { Self::Pattern(Pattern::placeholder()) }
1458}
1459
1460node! { struct LetBinding }
1461
1462/// What a `let` binds: a pattern, or a named closure.
1463#[derive(Debug)]
1464pub enum LetBindingKind<'a> {
1465 Normal(Pattern<'a>),
1466 Closure(Ident<'a>),
1467}
1468
1469impl<'a> LetBindingKind<'a> {
1470 pub fn bindings(self) -> Vec<Ident<'a>> {
1471 match self {
1472 LetBindingKind::Normal(p) => p.bindings(),
1473 LetBindingKind::Closure(i) => vec![i],
1474 }
1475 }
1476}
1477
1478impl<'a> LetBinding<'a> {
1479 pub fn kind(self) -> LetBindingKind<'a> {
1480 match self.0.cast_first() {
1481 Pattern::Normal(Expr::Closure(c)) => LetBindingKind::Closure(match c.name() {
1482 Some(n) => n,
1483 Option::None => Ident::placeholder(),
1484 }),
1485 pattern => LetBindingKind::Normal(pattern),
1486 }
1487 }
1488
1489 /// The initial value; a named closure is its own.
1490 pub fn init(self) -> Option<Expr<'a>> {
1491 match self.kind() {
1492 LetBindingKind::Normal(Pattern::Normal(_) | Pattern::Parenthesized(_)) =>
1493 self.0.children().iter().filter_map(|c| c.cast::<Expr>()).nth(1),
1494 LetBindingKind::Normal(_) => self.0.try_cast_first(),
1495 LetBindingKind::Closure(_) => self.0.try_cast_first(),
1496 }
1497 }
1498}
1499
1500node! { struct DestructAssignment }
1501
1502impl<'a> DestructAssignment<'a> {
1503 pub fn pattern(self) -> Pattern<'a> { self.0.cast_first() }
1504 pub fn value(self) -> Expr<'a> { self.0.cast_last() }
1505}
1506
1507node! { struct SetRule }
1508
1509impl<'a> SetRule<'a> {
1510 pub fn target(self) -> Expr<'a> { self.0.cast_first() }
1511 pub fn args(self) -> Args<'a> { self.0.cast_last() }
1512
1513 pub fn condition(self) -> Option<Expr<'a>> {
1514 self.0.children().iter()
1515 .skip_while(|c| c.kind() != SyntaxKind::If)
1516 .find_map(|c| c.cast())
1517 }
1518}
1519
1520node! { struct ShowRule }
1521
1522impl<'a> ShowRule<'a> {
1523 /// The selector before the colon; none for `show: f`.
1524 pub fn selector(self) -> Option<Expr<'a>> {
1525 self.0.children().iter().rev()
1526 .skip_while(|c| c.kind() != SyntaxKind::Colon)
1527 .find_map(|c| c.cast())
1528 }
1529
1530 pub fn transform(self) -> Expr<'a> { self.0.cast_last() }
1531}
1532
1533node! { struct Contextual }
1534
1535impl<'a> Contextual<'a> {
1536 pub fn body(self) -> Expr<'a> { self.0.cast_first() }
1537}
1538
1539node! { struct Conditional }
1540
1541impl<'a> Conditional<'a> {
1542 pub fn condition(self) -> Expr<'a> { self.0.cast_first() }
1543
1544 pub fn if_body(self) -> Expr<'a> {
1545 match self.0.children().iter().filter_map(|c| c.cast()).nth(1) {
1546 Some(e) => e,
1547 Option::None => Expr::placeholder(),
1548 }
1549 }
1550
1551 pub fn else_body(self) -> Option<Expr<'a>> {
1552 self.0.children().iter().filter_map(|c| c.cast()).nth(2)
1553 }
1554}
1555
1556node! { struct WhileLoop }
1557
1558impl<'a> WhileLoop<'a> {
1559 pub fn condition(self) -> Expr<'a> { self.0.cast_first() }
1560 pub fn body(self) -> Expr<'a> { self.0.cast_last() }
1561}
1562
1563node! { struct ForLoop }
1564
1565impl<'a> ForLoop<'a> {
1566 pub fn pattern(self) -> Pattern<'a> { self.0.cast_first() }
1567
1568 pub fn iterable(self) -> Expr<'a> {
1569 let found = self.0.children().iter()
1570 .skip_while(|c| c.kind() != SyntaxKind::In)
1571 .find_map(|c| c.cast());
1572 match found {
1573 Some(e) => e,
1574 Option::None => Expr::placeholder(),
1575 }
1576 }
1577
1578 pub fn body(self) -> Expr<'a> { self.0.cast_last() }
1579}
1580
1581node! { struct ModuleImport }
1582
1583impl<'a> ModuleImport<'a> {
1584 pub fn source(self) -> Expr<'a> { self.0.cast_first() }
1585
1586 pub fn imports(self) -> Option<Imports<'a>> {
1587 self.0.children().iter().find_map(|n| match n.kind() {
1588 SyntaxKind::Star => Some(Imports::Wildcard),
1589 SyntaxKind::ImportItems => n.cast().map(Imports::Items),
1590 _ => Option::None,
1591 })
1592 }
1593
1594 /// The name a bare `import "a/b.typ"` or `import "@preview/pkg:1.0.0"` binds: the file stem, the
1595 /// package name or the last identifier.
1596 pub fn bare_name(self) -> Result<String, BareImportError> {
1597 match self.source() {
1598 Expr::Ident(ident) => Ok(ident.get().to_string()),
1599 Expr::FieldAccess(access) => Ok(access.field().get().to_string()),
1600 Expr::Str(string) => {
1601 let string = string.get();
1602 let name = if string.starts_with('@') {
1603 match crate::eval::package::parse_spec(&string) {
1604 Ok(spec) => spec.name,
1605 Err(_) => return Err(BareImportError::PackageInvalid),
1606 }
1607 } else {
1608 match Path::new(&string).file_stem().and_then(|p| p.to_str()) {
1609 Some(n) => n.to_string(),
1610 Option::None => return Err(BareImportError::PathInvalid),
1611 }
1612 };
1613 if !is_ident(&name) {
1614 return Err(BareImportError::PathInvalid);
1615 }
1616 Ok(name)
1617 },
1618 _ => Err(BareImportError::Dynamic),
1619 }
1620 }
1621
1622 pub fn new_name(self) -> Option<Ident<'a>> {
1623 self.0.children().iter()
1624 .skip_while(|c| c.kind() != SyntaxKind::As)
1625 .find_map(|c| c.cast())
1626 }
1627}
1628
1629/// Why a bare import has no name to bind.
1630#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1631pub enum BareImportError {
1632 Dynamic,
1633 PathInvalid,
1634 PackageInvalid,
1635}
1636
1637#[derive(Debug, Copy, Clone, Hash)]
1638pub enum Imports<'a> {
1639 Wildcard,
1640 Items(ImportItems<'a>),
1641}
1642
1643node! { struct ImportItems }
1644
1645impl<'a> ImportItems<'a> {
1646 pub fn iter(self) -> impl DoubleEndedIterator<Item = ImportItem<'a>> {
1647 self.0.children().iter().filter_map(|c| match c.kind() {
1648 SyntaxKind::RenamedImportItem => c.cast().map(ImportItem::Renamed),
1649 SyntaxKind::ImportItemPath => c.cast().map(ImportItem::Simple),
1650 _ => Option::None,
1651 })
1652 }
1653}
1654
1655node! { struct ImportItemPath }
1656
1657impl<'a> ImportItemPath<'a> {
1658 pub fn iter(self) -> impl DoubleEndedIterator<Item = Ident<'a>> {
1659 self.0.children().iter().filter_map(|c| c.cast())
1660 }
1661
1662 pub fn name(self) -> Ident<'a> { self.0.cast_last() }
1663}
1664
1665#[derive(Debug, Copy, Clone, Hash)]
1666pub enum ImportItem<'a> {
1667 Simple(ImportItemPath<'a>),
1668 Renamed(RenamedImportItem<'a>),
1669}
1670
1671impl<'a> ImportItem<'a> {
1672 pub fn path(self) -> ImportItemPath<'a> {
1673 match self {
1674 Self::Simple(p) => p,
1675 Self::Renamed(r) => r.path(),
1676 }
1677 }
1678
1679 pub fn original_name(self) -> Ident<'a> {
1680 match self {
1681 Self::Simple(p) => p.name(),
1682 Self::Renamed(r) => r.original_name(),
1683 }
1684 }
1685
1686 pub fn bound_name(self) -> Ident<'a> {
1687 match self {
1688 Self::Simple(p) => p.name(),
1689 Self::Renamed(r) => r.new_name(),
1690 }
1691 }
1692}
1693
1694node! { struct RenamedImportItem }
1695
1696impl<'a> RenamedImportItem<'a> {
1697 pub fn path(self) -> ImportItemPath<'a> { self.0.cast_first() }
1698 pub fn original_name(self) -> Ident<'a> { self.path().name() }
1699 pub fn new_name(self) -> Ident<'a> { self.0.cast_last() }
1700}
1701
1702node! { struct ModuleInclude }
1703
1704impl<'a> ModuleInclude<'a> {
1705 pub fn source(self) -> Expr<'a> { self.0.cast_last() }
1706}
1707
1708node! { struct LoopBreak }
1709node! { struct LoopContinue }
1710
1711node! { struct FuncReturn }
1712
1713impl<'a> FuncReturn<'a> {
1714 pub fn body(self) -> Option<Expr<'a>> { self.0.try_cast_last() }
1715}