swamp_script_ast/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/script
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5pub mod prelude;
6
7use std::fmt;
8use std::fmt::{Debug, Formatter};
9use std::hash::Hash;
10
11#[derive(PartialEq, Eq, Hash, Default, Clone)]
12pub struct SpanWithoutFileId {
13    pub offset: u32,
14    pub length: u16,
15}
16
17impl Debug for SpanWithoutFileId {
18    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
19        write!(f, "<{}:{}>", self.offset, self.length)
20    }
21}
22
23// Common metadata that can be shared across all AST nodes
24#[derive(PartialEq, Eq, Hash, Default, Clone)]
25pub struct Node {
26    pub span: SpanWithoutFileId,
27    // TODO: Add comments and attributes
28}
29
30impl Debug for Node {
31    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
32        write!(f, "{:?}", self.span)
33    }
34}
35
36/// Identifiers ================
37#[derive(Debug, PartialEq, Eq, Clone, Hash)]
38pub struct QualifiedTypeIdentifier {
39    pub name: LocalTypeIdentifier,
40    pub module_path: Option<ModulePath>,
41    pub generic_params: Vec<Type>,
42}
43
44impl QualifiedTypeIdentifier {
45    #[must_use]
46    pub fn new(name: LocalTypeIdentifier, module_path: Vec<Node>) -> Self {
47        let module_path = if module_path.is_empty() {
48            None
49        } else {
50            Some(ModulePath(module_path))
51        };
52
53        Self {
54            name,
55            module_path,
56            generic_params: Vec::new(),
57        }
58    }
59
60    #[must_use]
61    pub fn new_with_generics(
62        name: LocalTypeIdentifier,
63        module_path: Vec<Node>,
64        generic_params: Vec<Type>,
65    ) -> Self {
66        let module_path = if module_path.is_empty() {
67            None
68        } else {
69            Some(ModulePath(module_path))
70        };
71
72        Self {
73            name,
74            module_path,
75            generic_params,
76        }
77    }
78}
79
80#[derive(Debug, PartialEq, Eq, Hash, Clone)]
81pub struct QualifiedIdentifier {
82    pub name: Node,
83    pub module_path: Option<ModulePath>,
84    pub generic_params: Vec<Type>,
85}
86
87impl QualifiedIdentifier {
88    #[must_use]
89    pub fn new(name: Node, module_path: Vec<Node>) -> Self {
90        let module_path = if module_path.is_empty() {
91            None
92        } else {
93            Some(ModulePath(module_path))
94        };
95
96        Self {
97            name,
98            module_path,
99            generic_params: vec![],
100        }
101    }
102
103    #[must_use]
104    pub fn new_with_generics(
105        name: Node,
106        module_path: Vec<Node>,
107        generic_params: Vec<Type>,
108    ) -> Self {
109        let module_path = if module_path.is_empty() {
110            None
111        } else {
112            Some(ModulePath(module_path))
113        };
114
115        Self {
116            name,
117            module_path,
118            generic_params,
119        }
120    }
121}
122
123#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
124pub struct LocalTypeIdentifier(pub Node);
125
126impl LocalTypeIdentifier {
127    #[must_use]
128    pub const fn new(node: Node) -> Self {
129        Self(node)
130    }
131}
132
133#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
134pub struct TypeVariable(pub Node);
135
136#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
137pub struct LocalTypeIdentifierWithOptionalTypeVariables {
138    pub name: Node,
139    pub type_variables: Vec<TypeVariable>,
140}
141
142#[derive(PartialEq, Eq, Hash, Debug, Clone)]
143pub struct LocalIdentifier(pub Node);
144
145impl LocalIdentifier {
146    #[must_use]
147    pub const fn new(node: Node) -> Self {
148        Self(node)
149    }
150}
151
152#[derive(Debug, PartialEq, Eq, Hash, Default, Clone)]
153pub struct LocalConstantIdentifier(pub Node);
154
155#[derive(Debug, PartialEq, Eq, Clone, Hash)]
156pub struct QualifiedConstantIdentifier {
157    pub name: Node,
158    pub module_path: Option<ModulePath>,
159}
160
161impl QualifiedConstantIdentifier {
162    #[must_use]
163    pub const fn new(name: Node, module_path: Option<ModulePath>) -> Self {
164        Self { name, module_path }
165    }
166}
167
168#[derive(Debug, Eq, Hash, Clone, PartialEq)]
169pub struct FieldName(pub Node);
170
171#[derive(Debug, Eq, Hash, PartialEq, Clone)]
172pub struct ModulePath(pub Vec<Node>);
173
174impl Default for ModulePath {
175    fn default() -> Self {
176        Self::new()
177    }
178}
179
180impl ModulePath {
181    #[must_use]
182    pub const fn new() -> Self {
183        Self(vec![])
184    }
185}
186
187#[derive(Debug, Clone)]
188pub enum ImportItem {
189    Identifier(LocalIdentifier),
190    Type(LocalTypeIdentifier),
191}
192
193#[derive(Debug, Clone)]
194pub enum ImportItems {
195    Nothing,
196    Items(Vec<ImportItem>),
197    All,
198}
199
200#[derive(Debug, Clone)]
201pub struct Mod {
202    pub module_path: ModulePath,
203    pub items: ImportItems,
204}
205
206#[derive(Debug, Clone)]
207pub struct Use {
208    pub module_path: ModulePath,
209    pub items: ImportItems,
210}
211
212#[derive(Debug, Eq, Clone, PartialEq)]
213pub struct AliasType {
214    pub identifier: LocalTypeIdentifier,
215    pub referenced_type: Type,
216}
217
218#[derive(Debug, Eq, PartialEq, Hash, Clone, Default)]
219pub struct AnonymousStructType {
220    pub fields: Vec<StructTypeField>,
221}
222
223impl AnonymousStructType {
224    #[must_use]
225    pub const fn new(fields: Vec<StructTypeField>) -> Self {
226        Self { fields }
227    }
228}
229
230#[derive(Debug, Clone)]
231pub struct ConstantInfo {
232    pub constant_identifier: LocalConstantIdentifier,
233    pub expression: Box<Expression>,
234}
235
236#[derive(Debug, Clone)]
237pub struct NamedStructDef {
238    pub identifier: LocalTypeIdentifierWithOptionalTypeVariables,
239    pub struct_type: AnonymousStructType,
240}
241
242#[derive(Debug, Clone)]
243pub enum Definition {
244    AliasDef(AliasType),
245    NamedStructDef(NamedStructDef),
246    EnumDef(
247        LocalTypeIdentifierWithOptionalTypeVariables,
248        Vec<EnumVariantType>,
249    ),
250    FunctionDef(Function),
251    ImplDef(LocalTypeIdentifierWithOptionalTypeVariables, Vec<Function>),
252    Mod(Mod),
253    Use(Use),
254    // Other
255    Constant(ConstantInfo),
256}
257
258#[derive(Debug, Clone)]
259pub struct ForVar {
260    pub identifier: Node,
261    pub is_mut: Option<Node>,
262}
263
264#[derive(Debug, Clone)]
265pub enum ForPattern {
266    Single(ForVar),
267    Pair(ForVar, ForVar),
268}
269
270impl ForPattern {
271    #[must_use]
272    pub fn any_mut(&self) -> Option<Node> {
273        match self {
274            Self::Single(a) => a.is_mut.clone(),
275            Self::Pair(a, b) => a.is_mut.clone().or_else(|| b.is_mut.clone()),
276        }
277    }
278}
279
280#[derive(Debug, Clone)]
281pub struct IterableExpression {
282    pub expression: Box<MutableOrImmutableExpression>,
283}
284
285#[derive(Clone, Eq, PartialEq)]
286pub struct Variable {
287    pub name: Node,
288    pub is_mutable: Option<Node>,
289}
290
291#[derive(Debug, Clone)]
292pub struct VariableBinding {
293    pub variable: Variable,
294    pub expression: MutableOrImmutableExpression,
295}
296
297#[derive(Debug, Clone)]
298pub struct WhenBinding {
299    pub variable: Variable,
300    pub expression: Option<MutableOrImmutableExpression>,
301}
302
303impl Variable {
304    #[must_use]
305    pub const fn new(name: Node, is_mutable: Option<Node>) -> Self {
306        Self { name, is_mutable }
307    }
308}
309
310// Since this is a helper struct, we want to implement the debug output for it
311// to have it more concise
312impl Debug for Variable {
313    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
314        if let Some(found) = &self.is_mutable {
315            write!(f, "mut {found:?} {:?}", self.name)
316        } else {
317            write!(f, "{:?}", self.name)
318        }
319    }
320}
321
322#[derive(Debug, Eq, Clone, PartialEq)]
323pub struct Parameter {
324    pub variable: Variable,
325    pub param_type: Type,
326}
327
328#[derive(Debug, Clone)]
329pub struct FunctionDeclaration {
330    pub name: Node,
331    pub params: Vec<Parameter>,
332    pub self_parameter: Option<SelfParameter>,
333    pub return_type: Option<Type>,
334}
335
336#[derive(Debug, Clone)]
337pub struct FunctionWithBody {
338    pub declaration: FunctionDeclaration,
339    pub body: Expression,
340}
341
342#[derive(Debug, Clone)]
343pub enum Function {
344    Internal(FunctionWithBody),
345    External(FunctionDeclaration),
346}
347
348#[derive(Debug, Clone)]
349pub struct SelfParameter {
350    pub is_mutable: Option<Node>,
351    pub self_node: Node,
352}
353
354#[derive(Debug, PartialEq, Eq)]
355pub enum AssignmentOperatorKind {
356    Compound(CompoundOperatorKind),
357    Assign, // =
358}
359
360#[derive(Debug, PartialEq, Eq, Clone)]
361pub enum CompoundOperatorKind {
362    Add,    // +=
363    Sub,    // -=
364    Mul,    // *=
365    Div,    // /=
366    Modulo, // %=
367}
368
369#[derive(Debug, Clone)]
370pub struct CompoundOperator {
371    pub node: Node,
372    pub kind: CompoundOperatorKind,
373}
374
375#[derive(Debug, Clone)]
376pub enum RangeMode {
377    Inclusive,
378    Exclusive,
379}
380
381#[derive(Debug, Clone)]
382pub struct MutableOrImmutableExpression {
383    pub is_mutable: Option<Node>,
384    pub expression: Expression,
385}
386
387#[derive(Clone)]
388pub struct Expression {
389    pub kind: ExpressionKind,
390    pub node: Node,
391}
392
393impl Debug for Expression {
394    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
395        write!(f, "{:?}{:?}", self.node.span, self.kind)
396    }
397}
398
399#[derive(Debug, Clone)]
400pub enum Postfix {
401    FieldAccess(Node),
402    Subscript(Expression),
403    MemberCall(Node, Vec<MutableOrImmutableExpression>),
404    FunctionCall(Node, Vec<MutableOrImmutableExpression>),
405    OptionUnwrap(Node),       // ?-postfix
406    NoneCoalesce(Expression), // ??-postfix
407}
408
409#[derive(Debug, Clone)]
410pub struct PostfixChain {
411    pub base: Box<Expression>,
412    pub postfixes: Vec<Postfix>,
413}
414
415/// Expressions are things that "converts" to a value when evaluated.
416#[derive(Debug, Clone)]
417pub enum ExpressionKind {
418    // Access
419    PostfixChain(PostfixChain),
420
421    // References
422    VariableReference(Variable),
423    ConstantReference(QualifiedConstantIdentifier),
424    StaticMemberFunctionReference(QualifiedTypeIdentifier, Node),
425    IdentifierReference(QualifiedIdentifier),
426
427    // Assignments
428    VariableDefinition(Variable, Option<Type>, Box<MutableOrImmutableExpression>),
429    VariableAssignment(Variable, Box<MutableOrImmutableExpression>),
430    Assignment(Box<Expression>, Box<Expression>),
431    CompoundAssignment(Box<Expression>, CompoundOperator, Box<Expression>),
432    DestructuringAssignment(Vec<Variable>, Box<Expression>),
433
434    // Operators
435    BinaryOp(Box<Expression>, BinaryOperator, Box<Expression>),
436    UnaryOp(UnaryOperator, Box<Expression>),
437
438    //
439    Block(Vec<Expression>),
440    With(Vec<VariableBinding>, Box<Expression>),
441    When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
442
443    // Control flow
444    ForLoop(
445        ForPattern,
446        IterableExpression,
447        Option<Box<Expression>>,
448        Box<Expression>,
449    ),
450    WhileLoop(Box<Expression>, Box<Expression>),
451
452    // Compare and Matching
453    If(Box<Expression>, Box<Expression>, Option<Box<Expression>>),
454    Match(Box<MutableOrImmutableExpression>, Vec<MatchArm>),
455    Guard(Vec<GuardExpr>),
456
457    InterpolatedString(Vec<StringPart>),
458
459    // Literals
460    AnonymousStructLiteral(Vec<FieldExpression>, bool),
461    NamedStructLiteral(QualifiedTypeIdentifier, Vec<FieldExpression>, bool),
462    Range(Box<Expression>, Box<Expression>, RangeMode),
463    Literal(LiteralKind),
464}
465
466#[derive(Debug, Clone)]
467pub struct MatchArm {
468    pub pattern: Pattern,
469    pub expression: Expression,
470}
471
472// Are constructed by themselves
473#[derive(Debug, Clone)]
474pub enum LiteralKind {
475    Int,
476    Float,
477    String(String),
478    Bool,
479    EnumVariant(EnumVariantLiteral),
480    Tuple(Vec<Expression>),
481    Slice(Vec<Expression>),
482    SlicePair(Vec<(Expression, Expression)>),
483    None,
484}
485
486#[derive(Debug, Clone)]
487pub struct FieldExpression {
488    pub field_name: FieldName,
489    pub expression: Expression,
490}
491
492#[derive(Debug, Eq, Hash, Clone, PartialEq)]
493pub struct StructTypeField {
494    pub field_name: FieldName,
495    pub field_type: Type,
496}
497
498#[derive(Debug, Clone)]
499pub enum EnumVariantLiteral {
500    Simple(QualifiedTypeIdentifier, LocalTypeIdentifier),
501    Tuple(
502        QualifiedTypeIdentifier,
503        LocalTypeIdentifier,
504        Vec<Expression>,
505    ),
506    Struct(
507        QualifiedTypeIdentifier,
508        LocalTypeIdentifier,
509        Vec<FieldExpression>,
510        bool,
511    ),
512}
513
514#[derive(Debug, Clone)]
515pub enum EnumVariantType {
516    Simple(Node),
517    Tuple(Node, Vec<Type>),
518    Struct(Node, AnonymousStructType),
519}
520
521#[derive(Debug, PartialEq, Eq, Clone, Hash)]
522pub struct TypeForParameter {
523    pub ast_type: Type,
524    pub is_mutable: bool,
525}
526
527#[derive(Debug, PartialEq, Eq, Clone, Hash)]
528pub enum Type {
529    // Composite
530    Slice(Box<Type>),                // Value array
531    SlicePair(Box<Type>, Box<Type>), // Key : Value
532    AnonymousStruct(AnonymousStructType),
533    Tuple(Vec<Type>),
534    Function(Vec<TypeForParameter>, Box<Type>),
535
536    Named(QualifiedTypeIdentifier),
537
538    Optional(Box<Type>, Node),
539}
540
541#[derive(Debug, Clone)]
542pub struct BinaryOperator {
543    pub kind: BinaryOperatorKind,
544    pub node: Node,
545}
546
547// Takes a left and right side expression
548#[derive(Debug, Clone)]
549pub enum BinaryOperatorKind {
550    Add,
551    Subtract,
552    Multiply,
553    Divide,
554    Modulo,
555    LogicalOr,
556    LogicalAnd,
557    Equal,
558    NotEqual,
559    LessThan,
560    LessEqual,
561    GreaterThan,
562    GreaterEqual,
563    RangeExclusive,
564}
565
566// Only takes one expression argument
567#[derive(Debug, Clone)]
568pub enum UnaryOperator {
569    Not(Node),
570    Negate(Node),
571}
572
573#[derive(Debug, Clone)]
574pub struct GuardExpr {
575    pub clause: GuardClause,
576    pub result: Expression,
577}
578
579#[derive(Debug, Clone)]
580pub enum GuardClause {
581    Wildcard(Node),
582    Expression(Expression),
583}
584
585// Patterns are used in matching and destructuring
586#[derive(Debug, Clone)]
587pub enum Pattern {
588    Wildcard(Node),
589    NormalPattern(Node, NormalPattern, Option<GuardClause>),
590}
591
592// Patterns are used in matching and destructuring
593#[derive(Debug, Clone)]
594pub enum NormalPattern {
595    PatternList(Vec<PatternElement>),
596    EnumPattern(Node, Option<Vec<PatternElement>>),
597    Literal(LiteralKind),
598}
599
600#[derive(Debug, Clone)]
601pub enum PatternElement {
602    Variable(Variable),
603    Expression(Expression),
604    Wildcard(Node),
605}
606
607#[derive(Debug, Clone)]
608pub enum StringPart {
609    Literal(Node, String),
610    Interpolation(Box<Expression>, Option<FormatSpecifier>),
611}
612
613#[derive(Debug, Clone)]
614pub enum FormatSpecifier {
615    LowerHex(Node),                      // :x
616    UpperHex(Node),                      // :X
617    Binary(Node),                        // :b
618    Float(Node),                         // :f
619    Precision(u32, Node, PrecisionType), // :..2f or :..5s
620}
621
622#[derive(Debug, Clone)]
623pub enum PrecisionType {
624    Float(Node),
625    String(Node),
626}
627
628#[derive()]
629pub struct Module {
630    pub expression: Option<Expression>,
631    pub definitions: Vec<Definition>,
632}
633
634impl Debug for Module {
635    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
636        for definition in &self.definitions {
637            writeln!(f, "{definition:?}")?;
638        }
639
640        if !self.definitions.is_empty() && self.expression.is_some() {
641            writeln!(f, "---")?;
642        }
643
644        if let Some(found_expression) = &self.expression {
645            match &found_expression.kind {
646                ExpressionKind::Block(expressions) => {
647                    for expression in expressions {
648                        writeln!(f, "{expression:?}")?;
649                    }
650                }
651                _ => writeln!(f, "{found_expression:?}")?,
652            }
653        }
654
655        Ok(())
656    }
657}
658
659impl Module {
660    #[must_use]
661    pub const fn new(definitions: Vec<Definition>, expression: Option<Expression>) -> Self {
662        Self {
663            expression,
664            definitions,
665        }
666    }
667
668    #[must_use]
669    pub const fn expression(&self) -> &Option<Expression> {
670        &self.expression
671    }
672
673    #[must_use]
674    pub const fn definitions(&self) -> &Vec<Definition> {
675        &self.definitions
676    }
677
678    #[must_use]
679    pub fn imports(&self) -> Vec<&Use> {
680        let mut use_items = Vec::new();
681
682        for def in &self.definitions {
683            if let Definition::Use(use_info) = def {
684                use_items.push(use_info);
685            }
686        }
687
688        use_items
689    }
690}