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    Lambda(Vec<Variable>, Box<Expression>),
465}
466
467#[derive(Debug, Clone)]
468pub struct MatchArm {
469    pub pattern: Pattern,
470    pub expression: Expression,
471}
472
473// Are constructed by themselves
474#[derive(Debug, Clone)]
475pub enum LiteralKind {
476    Int,
477    Float,
478    String(String),
479    Bool,
480    EnumVariant(EnumVariantLiteral),
481    Tuple(Vec<Expression>),
482    Slice(Vec<Expression>),
483    SlicePair(Vec<(Expression, Expression)>),
484    None,
485}
486
487#[derive(Debug, Clone)]
488pub struct FieldExpression {
489    pub field_name: FieldName,
490    pub expression: Expression,
491}
492
493#[derive(Debug, Eq, Hash, Clone, PartialEq)]
494pub struct StructTypeField {
495    pub field_name: FieldName,
496    pub field_type: Type,
497}
498
499#[derive(Debug, Clone)]
500pub enum EnumVariantLiteral {
501    Simple(QualifiedTypeIdentifier, LocalTypeIdentifier),
502    Tuple(
503        QualifiedTypeIdentifier,
504        LocalTypeIdentifier,
505        Vec<Expression>,
506    ),
507    Struct(
508        QualifiedTypeIdentifier,
509        LocalTypeIdentifier,
510        Vec<FieldExpression>,
511        bool,
512    ),
513}
514
515impl EnumVariantLiteral {
516    #[must_use]
517    pub const fn node(&self) -> &Node {
518        match self {
519            EnumVariantLiteral::Simple(ident, _) => &ident.name.0,
520            EnumVariantLiteral::Tuple(ident, _, _) => &ident.name.0,
521            EnumVariantLiteral::Struct(ident, _, _, _) => &ident.name.0,
522        }
523    }
524}
525
526#[derive(Debug, Clone)]
527pub enum EnumVariantType {
528    Simple(Node),
529    Tuple(Node, Vec<Type>),
530    Struct(Node, AnonymousStructType),
531}
532
533#[derive(Debug, PartialEq, Eq, Clone, Hash)]
534pub struct TypeForParameter {
535    pub ast_type: Type,
536    pub is_mutable: bool,
537}
538
539#[derive(Debug, PartialEq, Eq, Clone, Hash)]
540pub enum Type {
541    // Composite
542    Slice(Box<Type>),                // Value array
543    SlicePair(Box<Type>, Box<Type>), // Key : Value
544    AnonymousStruct(AnonymousStructType),
545    Unit,
546    Tuple(Vec<Type>),
547    Function(Vec<TypeForParameter>, Box<Type>),
548
549    Named(QualifiedTypeIdentifier),
550
551    Optional(Box<Type>, Node),
552}
553
554#[derive(Debug, Clone)]
555pub struct BinaryOperator {
556    pub kind: BinaryOperatorKind,
557    pub node: Node,
558}
559
560// Takes a left and right side expression
561#[derive(Debug, Clone)]
562pub enum BinaryOperatorKind {
563    Add,
564    Subtract,
565    Multiply,
566    Divide,
567    Modulo,
568    LogicalOr,
569    LogicalAnd,
570    Equal,
571    NotEqual,
572    LessThan,
573    LessEqual,
574    GreaterThan,
575    GreaterEqual,
576    RangeExclusive,
577}
578
579// Only takes one expression argument
580#[derive(Debug, Clone)]
581pub enum UnaryOperator {
582    Not(Node),
583    Negate(Node),
584}
585
586#[derive(Debug, Clone)]
587pub struct GuardExpr {
588    pub clause: GuardClause,
589    pub result: Expression,
590}
591
592#[derive(Debug, Clone)]
593pub enum GuardClause {
594    Wildcard(Node),
595    Expression(Expression),
596}
597
598// Patterns are used in matching and destructuring
599#[derive(Debug, Clone)]
600pub enum Pattern {
601    Wildcard(Node),
602    NormalPattern(Node, NormalPattern, Option<GuardClause>),
603}
604
605// Patterns are used in matching and destructuring
606#[derive(Debug, Clone)]
607pub enum NormalPattern {
608    PatternList(Vec<PatternElement>),
609    EnumPattern(Node, Option<Vec<PatternElement>>),
610    Literal(LiteralKind),
611}
612
613#[derive(Debug, Clone)]
614pub enum PatternElement {
615    Variable(Variable),
616    Expression(Expression),
617    Wildcard(Node),
618}
619
620#[derive(Debug, Clone)]
621pub enum StringPart {
622    Literal(Node, String),
623    Interpolation(Box<Expression>, Option<FormatSpecifier>),
624}
625
626#[derive(Debug, Clone)]
627pub enum FormatSpecifier {
628    LowerHex(Node),                      // :x
629    UpperHex(Node),                      // :X
630    Binary(Node),                        // :b
631    Float(Node),                         // :f
632    Precision(u32, Node, PrecisionType), // :..2f or :..5s
633}
634
635#[derive(Debug, Clone)]
636pub enum PrecisionType {
637    Float(Node),
638    String(Node),
639}
640
641#[derive()]
642pub struct Module {
643    pub expression: Option<Expression>,
644    pub definitions: Vec<Definition>,
645}
646
647impl Debug for Module {
648    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
649        for definition in &self.definitions {
650            writeln!(f, "{definition:?}")?;
651        }
652
653        if !self.definitions.is_empty() && self.expression.is_some() {
654            writeln!(f, "---")?;
655        }
656
657        if let Some(found_expression) = &self.expression {
658            match &found_expression.kind {
659                ExpressionKind::Block(expressions) => {
660                    for expression in expressions {
661                        writeln!(f, "{expression:?}")?;
662                    }
663                }
664                _ => writeln!(f, "{found_expression:?}")?,
665            }
666        }
667
668        Ok(())
669    }
670}
671
672impl Module {
673    #[must_use]
674    pub const fn new(definitions: Vec<Definition>, expression: Option<Expression>) -> Self {
675        Self {
676            expression,
677            definitions,
678        }
679    }
680
681    #[must_use]
682    pub const fn expression(&self) -> &Option<Expression> {
683        &self.expression
684    }
685
686    #[must_use]
687    pub const fn definitions(&self) -> &Vec<Definition> {
688        &self.definitions
689    }
690
691    #[must_use]
692    pub fn imports(&self) -> Vec<&Use> {
693        let mut use_items = Vec::new();
694
695        for def in &self.definitions {
696            if let Definition::Use(use_info) = def {
697                use_items.push(use_info);
698            }
699        }
700
701        use_items
702    }
703}