summaryrefslogtreecommitdiff
path: root/src/syntax/mod.rs
blob: 9fd2b21d2d571bfd77244128ecfd419297dada45 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! Syntax types.

mod ast;
mod ident;
mod pretty;
mod span;

use std::fmt;
use std::fmt::{Debug, Display, Formatter};
use std::mem;
use std::rc::Rc;

pub use ast::*;
pub use ident::*;
pub use pretty::*;
pub use span::*;

use crate::geom::{AngularUnit, LengthUnit};
use crate::source::SourceId;
use crate::util::EcoString;

/// Children of a [`GreenNode`].
#[derive(Clone, PartialEq)]
pub enum Green {
    /// A non-terminal node in an Rc.
    Node(Rc<GreenNode>),
    /// A terminal owned token.
    Token(GreenData),
}

impl Green {
    fn data(&self) -> &GreenData {
        match self {
            Green::Node(n) => &n.data,
            Green::Token(t) => &t,
        }
    }

    pub fn kind(&self) -> &NodeKind {
        self.data().kind()
    }

    pub fn len(&self) -> usize {
        self.data().len()
    }

    pub fn erroneous(&self) -> bool {
        self.data().erroneous()
    }

    pub fn children(&self) -> &[Green] {
        match self {
            Green::Node(n) => &n.children(),
            Green::Token(_) => &[],
        }
    }
}

impl Default for Green {
    fn default() -> Self {
        Self::Token(GreenData::new(NodeKind::None, 0))
    }
}

impl Debug for Green {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{:?}: {}", self.kind(), self.len())?;
        if let Self::Node(n) = self {
            if !n.children.is_empty() {
                f.write_str(" ")?;
                f.debug_list().entries(&n.children).finish()?;
            }
        }

        Ok(())
    }
}

/// A syntactical node.
#[derive(Clone, PartialEq)]
pub struct GreenNode {
    /// Node metadata.
    data: GreenData,
    /// This node's children, losslessly make up this node.
    children: Vec<Green>,
}

impl GreenNode {
    pub fn new(kind: NodeKind, len: usize) -> Self {
        Self {
            data: GreenData::new(kind, len),
            children: Vec::new(),
        }
    }

    pub fn with_children(kind: NodeKind, len: usize, children: Vec<Green>) -> Self {
        let mut meta = GreenData::new(kind, len);
        meta.erroneous |= children.iter().any(|c| c.erroneous());
        Self { data: meta, children }
    }

    pub fn with_child(kind: NodeKind, len: usize, child: impl Into<Green>) -> Self {
        Self::with_children(kind, len, vec![child.into()])
    }

    pub fn children(&self) -> &[Green] {
        &self.children
    }
}

impl From<GreenNode> for Green {
    fn from(node: GreenNode) -> Self {
        Rc::new(node).into()
    }
}

impl From<Rc<GreenNode>> for Green {
    fn from(node: Rc<GreenNode>) -> Self {
        Self::Node(node)
    }
}

/// Data shared between [`GreenNode`]s and [`GreenToken`]s.
#[derive(Clone, PartialEq)]
pub struct GreenData {
    /// What kind of node this is (each kind would have its own struct in a
    /// strongly typed AST).
    kind: NodeKind,
    /// The byte length of the node in the source.
    len: usize,
    /// Whether this node or any of its children are erroneous.
    erroneous: bool,
}

impl GreenData {
    pub fn new(kind: NodeKind, len: usize) -> Self {
        Self { len, erroneous: kind.is_error(), kind }
    }

    pub fn kind(&self) -> &NodeKind {
        &self.kind
    }

    pub fn len(&self) -> usize {
        self.len
    }

    pub fn erroneous(&self) -> bool {
        self.erroneous
    }
}

impl From<GreenData> for Green {
    fn from(token: GreenData) -> Self {
        Self::Token(token)
    }
}

#[derive(Copy, Clone, PartialEq)]
pub struct RedRef<'a> {
    id: SourceId,
    offset: usize,
    green: &'a Green,
}

impl<'a> RedRef<'a> {
    pub fn own(self) -> RedNode {
        RedNode {
            id: self.id,
            offset: self.offset,
            green: self.green.clone(),
        }
    }

    pub fn kind(&self) -> &NodeKind {
        self.green.kind()
    }

    pub fn span(&self) -> Span {
        Span::new(self.id, self.offset, self.offset + self.green.len())
    }

    pub fn cast<T>(self) -> Option<T>
    where
        T: TypedNode,
    {
        T::cast_from(self)
    }

    pub fn erroneous(&self) -> bool {
        self.green.erroneous()
    }

    pub fn children(self) -> impl Iterator<Item = RedRef<'a>> + Clone {
        let children = match &self.green {
            Green::Node(node) => node.children(),
            Green::Token(_) => &[],
        };

        let mut offset = self.offset;
        children.iter().map(move |green| {
            let child_offset = offset;
            offset += green.len();
            RedRef { id: self.id, offset: child_offset, green }
        })
    }

    pub(crate) fn typed_child(&self, kind: &NodeKind) -> Option<RedRef> {
        self.children()
            .find(|x| mem::discriminant(x.kind()) == mem::discriminant(kind))
    }

    pub(crate) fn cast_first_child<T: TypedNode>(&self) -> Option<T> {
        self.children().find_map(RedRef::cast)
    }

    pub(crate) fn cast_last_child<T: TypedNode>(&self) -> Option<T> {
        self.children().filter_map(RedRef::cast).last()
    }
}

#[derive(Clone, PartialEq)]
pub struct RedNode {
    id: SourceId,
    offset: usize,
    green: Green,
}

impl RedNode {
    pub fn new_root(root: Rc<GreenNode>, id: SourceId) -> Self {
        Self { id, offset: 0, green: root.into() }
    }

    pub fn span(&self) -> Span {
        self.as_ref().span()
    }

    pub fn len(&self) -> usize {
        self.green.len()
    }

    pub fn kind(&self) -> &NodeKind {
        self.green.kind()
    }

    pub fn children<'a>(&'a self) -> impl Iterator<Item = RedRef<'a>> + Clone {
        self.as_ref().children()
    }

    pub fn errors(&self) -> Vec<(Span, EcoString)> {
        if !self.green.erroneous() {
            return vec![];
        }

        match self.kind() {
            NodeKind::Error(pos, msg) => {
                let span = match pos {
                    ErrorPosition::Start => self.span().at_start(),
                    ErrorPosition::Full => self.span(),
                    ErrorPosition::End => self.span().at_end(),
                };

                vec![(span, msg.clone())]
            }
            _ => self
                .as_ref()
                .children()
                .filter(|red| red.green.erroneous())
                .flat_map(|red| red.own().errors())
                .collect(),
        }
    }

    pub fn as_ref<'a>(&'a self) -> RedRef<'a> {
        RedRef {
            id: self.id,
            offset: self.offset,
            green: &self.green,
        }
    }

    pub(crate) fn typed_child(&self, kind: &NodeKind) -> Option<RedNode> {
        self.as_ref().typed_child(kind).map(RedRef::own)
    }

    pub(crate) fn cast_first_child<T: TypedNode>(&self) -> Option<T> {
        self.as_ref().cast_first_child()
    }

    pub(crate) fn cast_last_child<T: TypedNode>(&self) -> Option<T> {
        self.as_ref().cast_last_child()
    }
}

impl Debug for RedNode {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{:?}: {:?}", self.kind(), self.span())?;
        let children = self.as_ref().children().collect::<Vec<_>>();
        if !children.is_empty() {
            f.write_str(" ")?;
            f.debug_list()
                .entries(children.into_iter().map(RedRef::own))
                .finish()?;
        }
        Ok(())
    }
}

pub trait TypedNode: Sized {
    /// Performs the conversion.
    fn cast_from(value: RedRef) -> Option<Self>;
}

#[derive(Debug, Clone, PartialEq)]
pub enum NodeKind {
    /// A left square bracket: `[`.
    LeftBracket,
    /// A right square bracket: `]`.
    RightBracket,
    /// A left curly brace: `{`.
    LeftBrace,
    /// A right curly brace: `}`.
    RightBrace,
    /// A left round parenthesis: `(`.
    LeftParen,
    /// A right round parenthesis: `)`.
    RightParen,
    /// An asterisk: `*`.
    Star,
    /// A comma: `,`.
    Comma,
    /// A semicolon: `;`.
    Semicolon,
    /// A colon: `:`.
    Colon,
    /// A plus: `+`.
    Plus,
    /// A hyphen: `-`.
    Minus,
    /// A slash: `/`.
    Slash,
    /// A single equals sign: `=`.
    Eq,
    /// Two equals signs: `==`.
    EqEq,
    /// An exclamation mark followed by an equals sign: `!=`.
    ExclEq,
    /// A less-than sign: `<`.
    Lt,
    /// A less-than sign followed by an equals sign: `<=`.
    LtEq,
    /// A greater-than sign: `>`.
    Gt,
    /// A greater-than sign followed by an equals sign: `>=`.
    GtEq,
    /// A plus followed by an equals sign: `+=`.
    PlusEq,
    /// A hyphen followed by an equals sign: `-=`.
    HyphEq,
    /// An asterisk followed by an equals sign: `*=`.
    StarEq,
    /// A slash followed by an equals sign: `/=`.
    SlashEq,
    /// The `not` operator.
    Not,
    /// The `and` operator.
    And,
    /// The `or` operator.
    Or,
    /// The `with` operator.
    With,
    /// Two dots: `..`.
    Dots,
    /// An equals sign followed by a greater-than sign: `=>`.
    Arrow,
    /// The none literal: `none`.
    None,
    /// The auto literal: `auto`.
    Auto,
    /// The `let` keyword.
    Let,
    /// The `if` keyword.
    If,
    /// The `else` keyword.
    Else,
    /// The `for` keyword.
    For,
    /// The `in` keyword.
    In,
    /// The `while` keyword.
    While,
    /// The `break` keyword.
    Break,
    /// The `continue` keyword.
    Continue,
    /// The `return` keyword.
    Return,
    /// The `import` keyword.
    Import,
    /// The `include` keyword.
    Include,
    /// The `from` keyword.
    From,
    /// Template markup.
    Markup,
    /// One or more whitespace characters.
    Space(usize),
    /// A forced line break: `\`.
    Linebreak,
    /// A paragraph break: Two or more newlines.
    Parbreak,
    /// A consecutive non-markup string.
    Text(EcoString),
    /// A non-breaking space: `~`.
    NonBreakingSpace,
    /// An en-dash: `--`.
    EnDash,
    /// An em-dash: `---`.
    EmDash,
    /// A slash and the letter "u" followed by a hexadecimal unicode entity
    /// enclosed in curly braces: `\u{1F5FA}`.
    UnicodeEscape(UnicodeEscapeToken),
    /// Strong text was enabled / disabled: `*`.
    Strong,
    /// Emphasized text was enabled / disabled: `_`.
    Emph,
    /// A section heading: `= Introduction`.
    Heading,
    /// A heading's level: `=`, `==`, `===`, etc.
    HeadingLevel(u8),
    /// An item in an enumeration (ordered list): `1. ...`.
    Enum,
    /// A numbering: `23.`.
    ///
    /// Can also exist without the number: `.`.
    EnumNumbering(Option<usize>),
    /// An item in an unordered list: `- ...`.
    List,
    /// The bullet character of an item in an unordered list: `-`.
    ListBullet,
    /// An arbitrary number of backticks followed by inner contents, terminated
    /// with the same number of backticks: `` `...` ``.
    Raw(Rc<RawToken>),
    /// Dollar signs surrounding inner contents.
    Math(Rc<MathToken>),
    /// An identifier: `center`.
    Ident(EcoString),
    /// A boolean: `true`, `false`.
    Bool(bool),
    /// An integer: `120`.
    Int(i64),
    /// A floating-point number: `1.2`, `10e-4`.
    Float(f64),
    /// A length: `12pt`, `3cm`.
    Length(f64, LengthUnit),
    /// An angle: `90deg`.
    Angle(f64, AngularUnit),
    /// A percentage: `50%`.
    ///
    /// _Note_: `50%` is stored as `50.0` here, as in the corresponding
    /// [literal](super::Lit::Percent).
    Percentage(f64),
    /// A fraction unit: `3fr`.
    Fraction(f64),
    /// A quoted string: `"..."`.
    Str(StrToken),
    /// An array expression: `(1, "hi", 12cm)`.
    Array,
    /// A dictionary expression: `(thickness: 3pt, pattern: dashed)`.
    Dict,
    /// A named argument: `thickness: 3pt`.
    Named,
    /// A grouped expression: `(1 + 2)`.
    Group,
    /// A unary operation: `-x`.
    Unary,
    /// A binary operation: `a + b`.
    Binary,
    /// An invocation of a function: `f(x, y)`.
    Call,
    /// A function call's argument list: `(x, y)`.
    CallArgs,
    /// A closure expression: `(x, y) => z`.
    Closure,
    /// A closure's parameters: `(x, y)`.
    ClosureParams,
    /// A parameter sink: `..x`.
    ParameterSink,
    /// A template expression: `[*Hi* there!]`.
    Template,
    /// A block expression: `{ let x = 1; x + 2 }`.
    Block,
    /// A for loop expression: `for x in y { ... }`.
    ForExpr,
    /// A while loop expression: `while x { ... }`.
    WhileExpr,
    /// An if expression: `if x { ... }`.
    IfExpr,
    /// A let expression: `let x = 1`.
    LetExpr,
    /// The `with` expression: `with (1)`.
    WithExpr,
    /// A for loop's destructuring pattern: `x` or `x, y`.
    ForPattern,
    /// The import expression: `import x from "foo.typ"`.
    ImportExpr,
    /// Items to import: `a, b, c`.
    ImportItems,
    /// The include expression: `include "foo.typ"`.
    IncludeExpr,
    /// Two slashes followed by inner contents, terminated with a newline:
    /// `//<str>\n`.
    LineComment,
    /// A slash and a star followed by inner contents,  terminated with a star
    /// and a slash: `/*<str>*/`.
    ///
    /// The comment can contain nested block comments.
    BlockComment,
    /// Tokens that appear in the wrong place.
    Error(ErrorPosition, EcoString),
    /// Unknown character sequences.
    Unknown(EcoString),
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ErrorPosition {
    /// At the start of the node.
    Start,
    /// Over the full width of the node.
    Full,
    /// At the end of the node.
    End,
}

/// A quoted string token: `"..."`.
#[derive(Debug, Clone, PartialEq)]
#[repr(transparent)]
pub struct StrToken {
    /// The string inside the quotes.
    pub string: EcoString,
}

/// A raw block token: `` `...` ``.
#[derive(Debug, Clone, PartialEq)]
pub struct RawToken {
    /// The raw text in the block.
    pub text: EcoString,
    /// The programming language of the raw text.
    pub lang: Option<EcoString>,
    /// The number of opening backticks.
    pub backticks: u8,
    /// Whether to display this as a block.
    pub block: bool,
}

/// A math formula token: `$2pi + x$` or `$[f'(x) = x^2]$`.
#[derive(Debug, Clone, PartialEq)]
pub struct MathToken {
    /// The formula between the dollars.
    pub formula: EcoString,
    /// Whether the formula is display-level, that is, it is surrounded by
    /// `$[..]`.
    pub display: bool,
}

/// A unicode escape sequence token: `\u{1F5FA}`.
#[derive(Debug, Clone, PartialEq)]
#[repr(transparent)]
pub struct UnicodeEscapeToken {
    /// The resulting unicode character.
    pub character: char,
}

impl Display for NodeKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.pad(self.as_str())
    }
}

impl NodeKind {
    pub fn is_paren(&self) -> bool {
        match self {
            Self::LeftParen => true,
            Self::RightParen => true,
            _ => false,
        }
    }

    pub fn is_bracket(&self) -> bool {
        match self {
            Self::LeftBracket => true,
            Self::RightBracket => true,
            _ => false,
        }
    }

    pub fn is_brace(&self) -> bool {
        match self {
            Self::LeftBrace => true,
            Self::RightBrace => true,
            _ => false,
        }
    }

    pub fn is_error(&self) -> bool {
        matches!(self, NodeKind::Error(_, _))
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::LeftBracket => "opening bracket",
            Self::RightBracket => "closing bracket",
            Self::LeftBrace => "opening brace",
            Self::RightBrace => "closing brace",
            Self::LeftParen => "opening paren",
            Self::RightParen => "closing paren",
            Self::Star => "star",
            Self::Comma => "comma",
            Self::Semicolon => "semicolon",
            Self::Colon => "colon",
            Self::Plus => "plus",
            Self::Minus => "minus",
            Self::Slash => "slash",
            Self::Eq => "assignment operator",
            Self::EqEq => "equality operator",
            Self::ExclEq => "inequality operator",
            Self::Lt => "less-than operator",
            Self::LtEq => "less-than or equal operator",
            Self::Gt => "greater-than operator",
            Self::GtEq => "greater-than or equal operator",
            Self::PlusEq => "add-assign operator",
            Self::HyphEq => "subtract-assign operator",
            Self::StarEq => "multiply-assign operator",
            Self::SlashEq => "divide-assign operator",
            Self::Not => "operator `not`",
            Self::And => "operator `and`",
            Self::Or => "operator `or`",
            Self::With => "operator `with`",
            Self::Dots => "dots",
            Self::Arrow => "arrow",
            Self::None => "`none`",
            Self::Auto => "`auto`",
            Self::Let => "keyword `let`",
            Self::If => "keyword `if`",
            Self::Else => "keyword `else`",
            Self::For => "keyword `for`",
            Self::In => "keyword `in`",
            Self::While => "keyword `while`",
            Self::Break => "keyword `break`",
            Self::Continue => "keyword `continue`",
            Self::Return => "keyword `return`",
            Self::Import => "keyword `import`",
            Self::Include => "keyword `include`",
            Self::From => "keyword `from`",
            Self::Markup => "markup",
            Self::Space(_) => "space",
            Self::Linebreak => "forced linebreak",
            Self::Parbreak => "paragraph break",
            Self::Text(_) => "text",
            Self::NonBreakingSpace => "non-breaking space",
            Self::EnDash => "en dash",
            Self::EmDash => "em dash",
            Self::UnicodeEscape(_) => "unicode escape sequence",
            Self::Strong => "strong",
            Self::Emph => "emphasis",
            Self::Heading => "heading",
            Self::HeadingLevel(_) => "heading level",
            Self::Enum => "enumeration item",
            Self::EnumNumbering(_) => "enumeration item numbering",
            Self::List => "list item",
            Self::ListBullet => "list bullet",
            Self::Raw(_) => "raw block",
            Self::Math(_) => "math formula",
            Self::Ident(_) => "identifier",
            Self::Bool(_) => "boolean",
            Self::Int(_) => "integer",
            Self::Float(_) => "float",
            Self::Length(_, _) => "length",
            Self::Angle(_, _) => "angle",
            Self::Percentage(_) => "percentage",
            Self::Fraction(_) => "`fr` value",
            Self::Str(_) => "string",
            Self::Array => "array",
            Self::Dict => "dictionary",
            Self::Named => "named argument",
            Self::Group => "group",
            Self::Unary => "unary expression",
            Self::Binary => "binary expression",
            Self::Call => "call",
            Self::CallArgs => "call arguments",
            Self::Closure => "closure",
            Self::ClosureParams => "closure parameters",
            Self::ParameterSink => "parameter sink",
            Self::Template => "template",
            Self::Block => "block",
            Self::ForExpr => "for-loop expression",
            Self::WhileExpr => "while-loop expression",
            Self::IfExpr => "`if` expression",
            Self::LetExpr => "`let` expression",
            Self::WithExpr => "`with` expression",
            Self::ForPattern => "for-loop destructuring pattern",
            Self::ImportExpr => "`import` expression",
            Self::ImportItems => "import items",
            Self::IncludeExpr => "`include` expression",
            Self::LineComment => "line comment",
            Self::BlockComment => "block comment",
            Self::Error(_, _) => "parse error",
            Self::Unknown(src) => match src.as_str() {
                "*/" => "end of block comment",
                _ => "invalid token",
            },
        }
    }
}

#[macro_export]
macro_rules! node {
    ($(#[$attr:meta])* $name:ident) => {
        node!{$(#[$attr])* $name => $name}
    };
    ($(#[$attr:meta])* $variant:ident => $name:ident) => {
        #[derive(Debug, Clone, PartialEq)]
        #[repr(transparent)]
        $(#[$attr])*
        pub struct $name(RedNode);

        impl TypedNode for $name {
            fn cast_from(node: RedRef) -> Option<Self> {
                if node.kind() != &NodeKind::$variant {
                    return None;
                }

                Some(Self(node.own()))
            }
        }

        impl $name {
            pub fn span(&self) -> Span {
                self.0.span()
            }

            pub fn underlying(&self) -> RedRef {
                self.0.as_ref()
            }
        }
    };
}