Skip to main content

varyk_syntax/
ast.rs

1//! The AST produced by the parser (spec section 6.3). Every node carries a
2//! [`Span`], except [`Program`] and [`Item`], whose span is whichever
3//! variant/item they hold.
4
5use crate::span::Span;
6
7/// A name plus the span it was written at.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Ident {
10    pub name: String,
11    pub span: Span,
12}
13
14/// Where a path starts (spec 3.1, 3.3): one of the three keyword prefixes,
15/// or nothing (a plain module name declared in this file, or no module
16/// segment at all). The parser records whichever prefix is written;
17/// resolving `Crate` and `Super` to an actual module, and rejecting
18/// `Super` in the crate root (V0111), is the compiler's resolver's job.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum PathStart {
21    Crate,
22    SelfMod,
23    Super,
24    None,
25}
26
27/// A `::`-separated path (spec 3.1, 3.3): an optional keyword prefix
28/// (`crate`, `self`, `super`) followed by name segments. What the segments
29/// (and any name that follows them, for a type or expression path) resolve
30/// to -- a chain of modules, a type, a function, a variant -- is decided by
31/// where the path appears and, ultimately, the compiler's resolver, never
32/// the parser.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Path {
35    pub leading: PathStart,
36    pub segments: Vec<Ident>,
37    pub span: Span,
38}
39
40/// A named type: `string`, `i32`, `User`, and so on are all just names,
41/// resolved later by the compiler's resolver. A type may carry a module
42/// path (`m::User`, `shop::cart::Cart`, spec 2.10, 3.1) and generic
43/// arguments (`Vec<i32>`, `Result<User, string>`, nested freely, spec 2.6);
44/// the parser only records them, and the resolver checks that the path,
45/// the name, and the argument count exist.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct TypeExpr {
48    pub path: Option<Path>,
49    pub name: Ident,
50    pub args: Vec<TypeExpr>,
51    pub span: Span,
52}
53
54impl TypeExpr {
55    /// Renders the whole type back to source text: the path (if any), the
56    /// name, and any generic arguments, recursively. Used wherever a
57    /// diagnostic or fix-it needs to show the type as written, rather than
58    /// just its base name.
59    pub fn display_name(&self) -> String {
60        let mut out = String::new();
61        if let Some(path) = &self.path {
62            match path.leading {
63                PathStart::Crate => out.push_str("crate::"),
64                PathStart::SelfMod => out.push_str("self::"),
65                PathStart::Super => out.push_str("super::"),
66                PathStart::None => {}
67            }
68            for segment in &path.segments {
69                out.push_str(&segment.name);
70                out.push_str("::");
71            }
72        }
73        out.push_str(&self.name.name);
74        if !self.args.is_empty() {
75            out.push('<');
76            for (i, arg) in self.args.iter().enumerate() {
77                if i > 0 {
78                    out.push_str(", ");
79                }
80                out.push_str(&arg.display_name());
81            }
82            out.push('>');
83        }
84        out
85    }
86}
87
88/// An attribute, `#[name]` or `#[name(literal)]` (M5a spec 2.2), written
89/// before an item, a struct field, an enum variant, a field of a variant,
90/// or a method. The parser keeps every one it reads; which names exist and
91/// where each may go is the compiler's resolver's to check.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct Attribute {
94    pub name: Ident,
95    /// What is between the parentheses; `None` when there are none.
96    pub arg: Option<AttrArg>,
97    /// From `#` through `]`.
98    pub span: Span,
99}
100
101/// The argument of an attribute: one literal, a number optionally after
102/// `-`, with a number's raw text as lexed and a string's text between the
103/// quotes, unmodified.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum AttrArg {
106    Str(String),
107    Int {
108        text: String,
109        negative: bool,
110    },
111    Float {
112        text: String,
113        negative: bool,
114    },
115    Bool(bool),
116    /// Anything else between the parentheses (`#[derive(Clone)]`): kept
117    /// so the resolver can name the attribute, never a valid argument.
118    Other,
119}
120
121/// A whole parsed source file: the top-level items it declares, in order.
122#[derive(Debug, Clone, PartialEq)]
123pub struct Program {
124    pub items: Vec<Item>,
125}
126
127/// A top-level declaration (spec 4.1, 2.2, 2.5): a function, a struct, an
128/// enum, an `impl` block, or a module declaration. `mod name;` only
129/// declares a submodule; resolving it to the submodule's own file and items
130/// is the compiler's `resolve` module's job.
131#[derive(Debug, Clone, PartialEq)]
132pub enum Item {
133    Function(Function),
134    Struct(StructDecl),
135    Enum(EnumDecl),
136    Impl(ImplBlock),
137    Mod(ModDecl),
138    Use(UseDecl),
139}
140
141/// Whether a function is a plain function, or a method with a `self`
142/// receiver (spec 2.5): `self` is a shared borrow, `mut self` a mutable
143/// borrow. There is no owned `self` in milestone 2.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum SelfMode {
146    None,
147    Shared,
148    Mutable,
149}
150
151/// `fn name(params) -> ReturnType { body }`, optionally `pub` and then
152/// `async` (milestone 5b1 spec 2.2). Inside an
153/// `impl` block the parameter list may start with a `self` receiver
154/// (`self_mode`), which is never a [`Param`] (spec 2.5).
155#[derive(Debug, Clone, PartialEq)]
156pub struct Function {
157    pub attrs: Vec<Attribute>,
158    pub name: Ident,
159    pub is_pub: bool,
160    /// `async fn` (milestone 5b1 spec 2.2).
161    pub is_async: bool,
162    pub self_mode: SelfMode,
163    /// The `self` keyword of the receiver, where a `mut ` fix-it inserts;
164    /// `None` exactly when `self_mode` is [`SelfMode::None`].
165    pub self_span: Option<Span>,
166    pub params: Vec<Param>,
167    pub return_type: Option<TypeExpr>,
168    pub body: Block,
169    pub span: Span,
170}
171
172/// One parameter: `name: T` is a shared borrow, `mut name: T` is a mutable
173/// borrow (spec 4.2).
174#[derive(Debug, Clone, PartialEq)]
175pub struct Param {
176    pub name: Ident,
177    pub mutable: bool,
178    pub ty: TypeExpr,
179    pub span: Span,
180}
181
182/// `struct Name { fields... }`, optionally `pub` (spec 4.1). Whether a
183/// field is visible follows the same rule as everything else (spec 3.2):
184/// see [`FieldDecl::is_pub`].
185#[derive(Debug, Clone, PartialEq)]
186pub struct StructDecl {
187    pub attrs: Vec<Attribute>,
188    pub name: Ident,
189    pub is_pub: bool,
190    pub fields: Vec<FieldDecl>,
191    pub span: Span,
192}
193
194/// A struct field: `name: T`, optionally `pub` (spec 3.4). Visibility
195/// follows the same rule as everything else (section 3.2): a private
196/// field is visible in the declaring module and its descendants, which
197/// includes the struct's own methods.
198#[derive(Debug, Clone, PartialEq)]
199pub struct FieldDecl {
200    pub attrs: Vec<Attribute>,
201    pub name: Ident,
202    pub ty: TypeExpr,
203    pub is_pub: bool,
204    pub span: Span,
205}
206
207/// `enum Name { variants... }` (spec 2.2), optionally `pub`. An enum has one
208/// or more variants; an empty `{ }` is `V0002`, since the parser found a
209/// complete-looking declaration missing the one thing it must have.
210#[derive(Debug, Clone, PartialEq)]
211pub struct EnumDecl {
212    pub attrs: Vec<Attribute>,
213    pub name: Ident,
214    pub is_pub: bool,
215    pub variants: Vec<EnumVariant>,
216    pub span: Span,
217}
218
219/// A variant of an enum: a unit variant (`Point`), a tuple variant
220/// (`Circle(f64)`), or a variant with named fields (`Click { x: i32 }`, M4
221/// spec 2.5).
222#[derive(Debug, Clone, PartialEq)]
223pub struct EnumVariant {
224    pub attrs: Vec<Attribute>,
225    pub name: Ident,
226    pub fields: VariantFields,
227    pub span: Span,
228}
229
230/// What a variant holds: nothing, values by position (`Circle(f64)`; an
231/// empty `Circle()` is a `Tuple` of no types), or named fields.
232#[derive(Debug, Clone, PartialEq)]
233pub enum VariantFields {
234    Unit,
235    Tuple(Vec<TypeExpr>),
236    Named(Vec<VariantField>),
237}
238
239/// A named field of a variant: `name: T`. It has no visibility of its own:
240/// a variant's fields are as visible as the enum, and Rust rejects `pub`
241/// on them.
242#[derive(Debug, Clone, PartialEq)]
243pub struct VariantField {
244    pub attrs: Vec<Attribute>,
245    pub name: Ident,
246    pub ty: TypeExpr,
247    pub span: Span,
248}
249
250/// `impl Name { fns... }` (spec 2.5): a block of functions and methods for
251/// a struct or enum declared in the same file. Whether `name` actually
252/// names a struct or enum is the compiler's `resolve` module's job.
253#[derive(Debug, Clone, PartialEq)]
254pub struct ImplBlock {
255    pub attrs: Vec<Attribute>,
256    pub type_name: Ident,
257    pub functions: Vec<Function>,
258    pub span: Span,
259}
260
261/// `mod name;` (spec 4.5): declares a submodule resolved to `name.vr` or
262/// `name.rs` in the same directory. Resolving and merging the submodule's
263/// items is the compiler's `resolve` module's job; this node only records
264/// the declaration.
265#[derive(Debug, Clone, PartialEq)]
266pub struct ModDecl {
267    pub attrs: Vec<Attribute>,
268    pub name: Ident,
269    pub is_pub: bool,
270    pub span: Span,
271}
272
273/// `use path;` or `use path as name;` (spec 3.3): introduces a local alias
274/// for whatever `path` names -- a module, a struct, an enum, or a function
275/// -- resolved and checked by the compiler's resolver, never the parser.
276#[derive(Debug, Clone, PartialEq)]
277pub struct UseDecl {
278    pub attrs: Vec<Attribute>,
279    pub path: Path,
280    pub alias: Option<Ident>,
281    pub span: Span,
282}
283
284/// A statement: `let`, assignment, `return`, `while`, `break`, `continue`,
285/// or an expression used for its side effects (or as a block's tail,
286/// distinguished by `has_semi` on [`Stmt::Expr`] so the type checker can tell a
287/// mid-block statement from a block's value).
288#[derive(Debug, Clone, PartialEq)]
289pub enum Stmt {
290    Let {
291        name: Ident,
292        mutable: bool,
293        ty: Option<TypeExpr>,
294        value: Expr,
295        span: Span,
296    },
297    /// Assignment to a place expression: a path (a variable) or a field
298    /// access. Anything else as the target is rejected (`V0002`) before
299    /// this node is ever built.
300    Assign {
301        target: Expr,
302        value: Expr,
303        span: Span,
304    },
305    /// An expression statement. `has_semi` is false only for a block-like
306    /// expression (`if`, a bare block) written without a trailing `;` in
307    /// the middle of a block, not at its end.
308    Expr {
309        expr: Expr,
310        span: Span,
311        has_semi: bool,
312    },
313    Return {
314        value: Option<Expr>,
315        span: Span,
316    },
317    While {
318        cond: Expr,
319        body: Block,
320        span: Span,
321    },
322    /// `while let pattern = value { body }` (M4 spec 2.4): `value` is
323    /// parsed in condition position, as `while`'s condition is.
324    WhileLet {
325        pattern: Pattern,
326        value: Expr,
327        body: Block,
328        span: Span,
329    },
330    /// `for var in head { body }` (spec 2.4). `head` is either a half-open
331    /// range or a `Vec` iterated element by element; the loop variable's
332    /// type and whether the `Vec` case borrows or owns each element is the
333    /// type checker's job (task 8).
334    For {
335        var: Ident,
336        head: ForHead,
337        body: Block,
338        span: Span,
339    },
340    Break {
341        span: Span,
342    },
343    Continue {
344        span: Span,
345    },
346}
347
348/// The head of a `for` loop (spec 2.4): an integer range, half-open
349/// (`a..b`) or `inclusive` (`a..=b`, M4 spec 2.11), parsed only here since
350/// an expression range exists nowhere else in Varyk, or an expression
351/// iterated element by element as a `Vec`.
352#[derive(Debug, Clone, PartialEq)]
353pub enum ForHead {
354    Range {
355        start: Box<Expr>,
356        end: Box<Expr>,
357        inclusive: bool,
358    },
359    Expr(Box<Expr>),
360}
361
362/// `{ stmts...; tail }`. The tail expression, if present, is the block's
363/// value.
364#[derive(Debug, Clone, PartialEq)]
365pub struct Block {
366    pub stmts: Vec<Stmt>,
367    pub tail: Option<Box<Expr>>,
368    pub span: Span,
369}
370
371/// Unary operators (spec 4.1). Unary binds tighter than any binary
372/// operator.
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum UnaryOp {
375    Neg,
376    Not,
377}
378
379/// Binary operators (spec 4.1), in Rust's precedence order from loosest to
380/// tightest: `||`, `&&`, the comparisons (non-associative), `+ -`, then
381/// `* / %`.
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383pub enum BinaryOp {
384    Or,
385    And,
386    Eq,
387    Ne,
388    Lt,
389    Le,
390    Gt,
391    Ge,
392    Add,
393    Sub,
394    Mul,
395    Div,
396    Rem,
397}
398
399impl BinaryOp {
400    /// The operator as written, the same in Varyk and Rust.
401    pub fn as_str(self) -> &'static str {
402        match self {
403            BinaryOp::Or => "||",
404            BinaryOp::And => "&&",
405            BinaryOp::Eq => "==",
406            BinaryOp::Ne => "!=",
407            BinaryOp::Lt => "<",
408            BinaryOp::Le => "<=",
409            BinaryOp::Gt => ">",
410            BinaryOp::Ge => ">=",
411            BinaryOp::Add => "+",
412            BinaryOp::Sub => "-",
413            BinaryOp::Mul => "*",
414            BinaryOp::Div => "/",
415            BinaryOp::Rem => "%",
416        }
417    }
418}
419
420/// An expression node: its kind plus the span it spans in the source.
421#[derive(Debug, Clone, PartialEq)]
422pub struct Expr {
423    pub kind: ExprKind,
424    pub span: Span,
425}
426
427#[derive(Debug, Clone, PartialEq)]
428pub enum ExprKind {
429    /// Raw digits, as lexed: the type checker decides the type from context.
430    Integer(String),
431    /// Raw `digits.digits`, as lexed.
432    Float(String),
433    Bool(bool),
434    /// Raw text between the quotes, as written: escapes are copied unchanged
435    /// into the generated Rust, which resolves them.
436    String(String),
437
438    /// `name`, `module::name`, or `module::Type::name` (spec 2.5, 2.10,
439    /// 3.1): a plain name, a module-qualified one, or a
440    /// module-and-type-qualified one (an associated function or enum
441    /// variant reached through a module), with paths now growing to any
442    /// depth as nested modules do. `path` covers every segment before the
443    /// final one (the module chain, and the type name when the path names
444    /// an associated function or a variant); `name` is that final segment,
445    /// the thing actually read or called. Whether `path`'s segments name a
446    /// deeper module chain than milestone 3 resolves, a single module, or a
447    /// type in this file (the two-way ambiguity a bare one-segment `path`
448    /// carries, spec 2.10) is the compiler's resolver's job, not the
449    /// parser's.
450    Path {
451        path: Option<Path>,
452        name: Ident,
453    },
454
455    Unary {
456        op: UnaryOp,
457        operand: Box<Expr>,
458    },
459
460    Binary {
461        op: BinaryOp,
462        lhs: Box<Expr>,
463        rhs: Box<Expr>,
464    },
465
466    /// `callee(args...)`. `callee` must be a `Path`, naming a plain
467    /// function or an associated function (spec 2.5); `x.f(args)` is
468    /// method-call syntax and parses as [`ExprKind::MethodCall`] instead,
469    /// never as a `Call` with a `Field` callee. Any other callee shape
470    /// (calling the result of a grouped expression, an index, and so on)
471    /// is rejected: `V0002` from the parser, and defensively `V0001` from
472    /// the type checker if such a node ever reaches it.
473    Call {
474        callee: Box<Expr>,
475        args: Vec<Expr>,
476    },
477
478    Field {
479        base: Box<Expr>,
480        name: Ident,
481    },
482
483    /// `receiver.method(args...)` (spec 2.5): a method call, `value.name(args)`.
484    MethodCall {
485        receiver: Box<Expr>,
486        method: Ident,
487        args: Vec<Expr>,
488    },
489
490    /// `base[index]` (spec 2.6): indexing, `v[i]`. Whether `base` is
491    /// actually a `Vec`, and whether `index` is a `usize`, is the type
492    /// checker's job.
493    Index {
494        base: Box<Expr>,
495        index: Box<Expr>,
496    },
497
498    /// `operand?` (spec 2.8): propagates an `Err` out of the enclosing
499    /// function. Whether `operand` is actually a `Result` compatible with
500    /// the function's return type is the type checker's job.
501    Try {
502        operand: Box<Expr>,
503    },
504
505    /// `operand.await` (milestone 5b1 spec 2.3). Whether `operand` is
506    /// something that can be waited for is the type checker's job.
507    Await(Box<Expr>),
508
509    /// `match scrutinee { arms... }` (spec 2.3), an expression like `if`.
510    /// It may also stand as a statement without a trailing `;`, the same
511    /// as `if` and a bare block, distinguished the same way by
512    /// `Stmt::Expr`'s `has_semi`.
513    Match {
514        scrutinee: Box<Expr>,
515        arms: Vec<MatchArm>,
516    },
517
518    /// `vec![a, b, c]` (spec 2.9), a compiler intrinsic like `println!`,
519    /// not a macro system: its elements, each an owned slot.
520    VecLit(Vec<Expr>),
521
522    /// `Name { field: expr, ... }`, or `path::Name { field: expr, ... }`
523    /// with a module path of any depth and an optional `crate::`,
524    /// `self::`, or `super::` prefix (spec 2.10, 3.1). Never parsed in
525    /// condition position.
526    StructLit {
527        path: Option<Path>,
528        name: Ident,
529        fields: Vec<(Ident, Expr)>,
530    },
531
532    Block(Block),
533
534    /// `if cond { ... }` or `if cond { ... } else { ... }`. `cond` is
535    /// parsed in condition position, so no struct literal is parsed
536    /// directly in it. An `else if` is represented as `else_` holding a
537    /// synthetic block whose only content is the nested `If` as its tail
538    /// expression.
539    If {
540        cond: Box<Expr>,
541        then: Block,
542        else_: Option<Block>,
543    },
544
545    /// `if let pattern = value { ... }`, with an optional `else` (M4 spec
546    /// 2.4). `value` is parsed in condition position, as `if`'s condition
547    /// is, and `else if` and `else if let` are a synthetic block holding
548    /// the nested expression as its tail, as for [`ExprKind::If`].
549    IfLet {
550        pattern: Pattern,
551        value: Box<Expr>,
552        then: Block,
553        else_: Option<Block>,
554        span: Span,
555    },
556
557    /// `|params| body` (M4 spec 2.2). The parameters carry no type; how
558    /// many there may be, and where a closure may appear, is the
559    /// checker's to decide.
560    Closure {
561        params: Vec<Ident>,
562        body: Box<Expr>,
563        span: Span,
564    },
565
566    /// `expr as T` (M4 spec 2.9), binding tighter than `*`. `ty` is a
567    /// plain name with no path and no generic arguments.
568    Cast {
569        expr: Box<Expr>,
570        ty: TypeExpr,
571        span: Span,
572    },
573
574    /// `println!(format, args...)` or `format!(format, args...)` (spec
575    /// 2.9): compiler intrinsics sharing one shape, told apart by `name`.
576    /// `format` keeps the format string's raw text and span; placeholder
577    /// checking is the type checker's job.
578    Intrinsic {
579        name: Ident,
580        format: (String, Span),
581        args: Vec<Expr>,
582    },
583}
584
585/// One arm of a `match` (spec 2.3): `pattern => body`, with an optional
586/// trailing comma the parser consumes but does not record.
587#[derive(Debug, Clone, PartialEq)]
588pub struct MatchArm {
589    pub pattern: Pattern,
590    pub body: Expr,
591    pub span: Span,
592}
593
594/// A pattern (spec 2.3, M4 spec 2.5), in a `match` arm, an `if let`, or a
595/// `while let`, nested to any depth. Not in Varyk, each `V0001` from the
596/// parser: guards (`pattern if cond`), alternatives (`a | b`), rest
597/// patterns (`..`), and `@` bindings.
598#[derive(Debug, Clone, PartialEq)]
599pub enum Pattern {
600    /// `_`: matches anything, binds nothing.
601    Wildcard(Span),
602    /// A bare name: matches anything and binds it. The parser cannot tell
603    /// this apart from a zero-argument variant written without its type
604    /// (`None`): the type checker decides against the matched value's
605    /// type.
606    Name(Ident),
607    /// A variant, optionally reached through a type and a module, with its
608    /// values by position: `Point`, `Some(p)`, `Shape::Circle(p, q)`,
609    /// `geo::Shape::Point`. `path`'s last segment is always the type
610    /// (unlike an expression path, a pattern never calls anything, so
611    /// there is no bare-module case to weigh it against); any segments
612    /// before that are the module chain. `span` ends at the closing `)`
613    /// when there are parentheses, so `Point()` is told apart from
614    /// `Point`.
615    Variant {
616        path: Option<Path>,
617        name: Ident,
618        fields: Vec<Pattern>,
619        span: Span,
620    },
621    /// A variant or struct with named fields: `Event::Click { x: 0, y }`.
622    /// A shorthand field `y` is `(y, Pattern::Name(y))`.
623    Struct {
624        path: Option<Path>,
625        name: Ident,
626        fields: Vec<(Ident, Pattern)>,
627        span: Span,
628    },
629    /// A literal: an integer with an optional `-`, a string, `true`, or
630    /// `false` (and a float, which the checker rejects).
631    Literal(Literal, Span),
632    /// `start..=end`, both ends included.
633    Range {
634        start: Literal,
635        end: Literal,
636        span: Span,
637    },
638}
639
640impl Pattern {
641    pub fn span(&self) -> Span {
642        match self {
643            Pattern::Wildcard(span) | Pattern::Literal(_, span) => *span,
644            Pattern::Name(ident) => ident.span,
645            Pattern::Variant { span, .. }
646            | Pattern::Struct { span, .. }
647            | Pattern::Range { span, .. } => *span,
648        }
649    }
650}
651
652/// The value of a literal pattern or of a range pattern's end, with the
653/// raw text of a number as lexed.
654#[derive(Debug, Clone, PartialEq, Eq)]
655pub enum Literal {
656    Int { text: String, negative: bool },
657    Float { text: String, negative: bool },
658    Str(String),
659    Bool(bool),
660}