swamp_ast/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/swamp
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<'_>) -> 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<Expression>,
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: Option<Expression>,
295}
296
297impl Variable {
298    #[must_use]
299    pub const fn new(name: Node, is_mutable: Option<Node>) -> Self {
300        Self { name, is_mutable }
301    }
302}
303
304// Since this is a helper struct, we want to implement the debug output for it
305// to have it more concise
306impl Debug for Variable {
307    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
308        if let Some(found) = &self.is_mutable {
309            write!(f, "mut {found:?} {:?}", self.name)
310        } else {
311            write!(f, "{:?}", self.name)
312        }
313    }
314}
315
316#[derive(Debug, Eq, Clone, PartialEq)]
317pub struct Parameter {
318    pub variable: Variable,
319    pub param_type: Type,
320}
321
322#[derive(Debug, Clone)]
323pub struct FunctionDeclaration {
324    pub name: Node,
325    pub params: Vec<Parameter>,
326    pub self_parameter: Option<SelfParameter>,
327    pub return_type: Option<Type>,
328    pub generic_variables: Vec<TypeVariable>,
329}
330
331#[derive(Debug, Clone)]
332pub struct FunctionWithBody {
333    pub declaration: FunctionDeclaration,
334    pub body: Expression,
335}
336
337#[derive(Debug, Clone)]
338pub enum Function {
339    Internal(FunctionWithBody),
340    External(FunctionDeclaration),
341}
342
343#[derive(Debug, Clone)]
344pub struct SelfParameter {
345    pub is_mutable: Option<Node>,
346    pub self_node: Node,
347}
348
349#[derive(Debug, PartialEq, Eq)]
350pub enum AssignmentOperatorKind {
351    Compound(CompoundOperatorKind),
352    Assign, // =
353}
354
355#[derive(Debug, PartialEq, Eq, Clone)]
356pub enum CompoundOperatorKind {
357    Add,    // +=
358    Sub,    // -=
359    Mul,    // *=
360    Div,    // /=
361    Modulo, // %=
362}
363
364#[derive(Debug, Clone)]
365pub struct CompoundOperator {
366    pub node: Node,
367    pub kind: CompoundOperatorKind,
368}
369
370#[derive(Debug, Clone)]
371pub enum RangeMode {
372    Inclusive,
373    Exclusive,
374}
375
376#[derive(Clone)]
377pub struct Expression {
378    pub kind: ExpressionKind,
379    pub node: Node,
380}
381
382impl Debug for Expression {
383    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
384        write!(f, "{:?}{:?}", self.node.span, self.kind)
385    }
386}
387
388#[derive(Debug, Clone)]
389pub enum Postfix {
390    FieldAccess(Node),
391    Subscript(Expression),
392    MemberCall(Node, Option<Vec<Type>>, Vec<Expression>),
393    FunctionCall(Node, Option<Vec<Type>>, Vec<Expression>),
394    OptionalChainingOperator(Node),     // ?-postfix
395    NoneCoalescingOperator(Expression), // ??-postfix
396}
397
398#[derive(Debug, Clone)]
399pub struct PostfixChain {
400    pub base: Box<Expression>,
401    pub postfixes: Vec<Postfix>,
402}
403
404/// Expressions are things that "converts" to a value when evaluated.
405#[derive(Debug, Clone)]
406pub enum ExpressionKind {
407    // Access
408    PostfixChain(PostfixChain),
409
410    // References
411    VariableReference(Variable),
412    ConstantReference(QualifiedConstantIdentifier),
413    StaticMemberFunctionReference(QualifiedTypeIdentifier, Node),
414    IdentifierReference(QualifiedIdentifier),
415
416    // Assignments
417    VariableDefinition(Variable, Option<Type>, Box<Expression>),
418    VariableAssignment(Variable, Box<Expression>),
419    Assignment(Box<Expression>, Box<Expression>),
420    CompoundAssignment(Box<Expression>, CompoundOperator, Box<Expression>),
421    DestructuringAssignment(Vec<Variable>, Box<Expression>),
422
423    // Operators
424    BinaryOp(Box<Expression>, BinaryOperator, Box<Expression>),
425    UnaryOp(UnaryOperator, Box<Expression>),
426
427    //
428    Block(Vec<Expression>),
429    With(Vec<VariableBinding>, Box<Expression>),
430    When(
431        Vec<VariableBinding>,
432        Box<Expression>,
433        Option<Box<Expression>>,
434    ),
435
436    // Control flow
437    ForLoop(
438        ForPattern,
439        IterableExpression,
440        Option<Box<Expression>>,
441        Box<Expression>,
442    ),
443    WhileLoop(Box<Expression>, Box<Expression>),
444
445    // Compare and Matching
446    If(Box<Expression>, Box<Expression>, Option<Box<Expression>>),
447    Match(Box<Expression>, Vec<MatchArm>),
448    Guard(Vec<GuardExpr>),
449
450    InterpolatedString(Vec<StringPart>),
451
452    // Literals
453    AnonymousStructLiteral(Vec<FieldExpression>, bool),
454    NamedStructLiteral(QualifiedTypeIdentifier, Vec<FieldExpression>, bool),
455    Range(Box<Expression>, Box<Expression>, RangeMode),
456    Literal(LiteralKind),
457    Lambda(Vec<Variable>, Box<Expression>),
458}
459
460#[derive(Debug, Clone)]
461pub struct MatchArm {
462    pub pattern: Pattern,
463    pub expression: Expression,
464}
465
466// Are constructed by themselves
467#[derive(Debug, Clone)]
468pub enum LiteralKind {
469    Int,
470    Float,
471    String(String),
472    Bool,
473    EnumVariant(EnumVariantLiteral),
474    Tuple(Vec<Expression>),
475    Slice(Vec<Expression>),
476    SlicePair(Vec<(Expression, Expression)>),
477    None,
478}
479
480#[derive(Debug, Clone)]
481pub struct FieldExpression {
482    pub field_name: FieldName,
483    pub expression: Expression,
484}
485
486#[derive(Debug, Eq, Hash, Clone, PartialEq)]
487pub struct StructTypeField {
488    pub field_name: FieldName,
489    pub field_type: Type,
490}
491
492#[derive(Debug, Clone)]
493pub enum EnumVariantLiteral {
494    Simple(QualifiedTypeIdentifier, LocalTypeIdentifier),
495    Tuple(
496        QualifiedTypeIdentifier,
497        LocalTypeIdentifier,
498        Vec<Expression>,
499    ),
500    Struct(
501        QualifiedTypeIdentifier,
502        LocalTypeIdentifier,
503        Vec<FieldExpression>,
504        bool,
505    ),
506}
507
508impl EnumVariantLiteral {
509    #[must_use]
510    pub const fn node(&self) -> &Node {
511        match self {
512            Self::Tuple(ident, _, _) | Self::Struct(ident, _, _, _) | Self::Simple(ident, _) => {
513                &ident.name.0
514            }
515        }
516    }
517}
518
519#[derive(Debug, Clone)]
520pub enum EnumVariantType {
521    Simple(Node),
522    Tuple(Node, Vec<Type>),
523    Struct(Node, AnonymousStructType),
524}
525
526#[derive(Debug, PartialEq, Eq, Clone, Hash)]
527pub struct TypeForParameter {
528    pub ast_type: Type,
529    pub is_mutable: bool,
530}
531
532#[derive(Debug, PartialEq, Eq, Clone, Hash)]
533pub enum Type {
534    // Composite
535    Slice(Box<Type>),                // Value array
536    SlicePair(Box<Type>, Box<Type>), // Key : Value
537    AnonymousStruct(AnonymousStructType),
538    Unit,
539    Tuple(Vec<Type>),
540    Function(Vec<TypeForParameter>, Box<Type>),
541
542    Named(QualifiedTypeIdentifier),
543
544    Optional(Box<Type>, Node),
545}
546
547#[derive(Debug, Clone)]
548pub struct BinaryOperator {
549    pub kind: BinaryOperatorKind,
550    pub node: Node,
551}
552
553// Takes a left and right side expression
554#[derive(Debug, Clone)]
555pub enum BinaryOperatorKind {
556    Add,
557    Subtract,
558    Multiply,
559    Divide,
560    Modulo,
561    LogicalOr,
562    LogicalAnd,
563    Equal,
564    NotEqual,
565    LessThan,
566    LessEqual,
567    GreaterThan,
568    GreaterEqual,
569    RangeExclusive,
570}
571
572// Only takes one expression argument
573#[derive(Debug, Clone)]
574pub enum UnaryOperator {
575    Not(Node),
576    Negate(Node),
577    BorrowMutRef(Node),
578}
579
580#[derive(Debug, Clone)]
581pub struct GuardExpr {
582    pub clause: GuardClause,
583    pub result: Expression,
584}
585
586#[derive(Debug, Clone)]
587pub enum GuardClause {
588    Wildcard(Node),
589    Expression(Expression),
590}
591
592// Patterns are used in matching and destructuring
593#[derive(Debug, Clone)]
594pub enum Pattern {
595    Wildcard(Node),
596    NormalPattern(Node, NormalPattern, Option<GuardClause>),
597}
598
599// Patterns are used in matching and destructuring
600#[derive(Debug, Clone)]
601pub enum NormalPattern {
602    PatternList(Vec<PatternElement>),
603    EnumPattern(Node, Option<Vec<PatternElement>>),
604    Literal(LiteralKind),
605}
606
607#[derive(Debug, Clone)]
608pub enum PatternElement {
609    Variable(Variable),
610    Expression(Expression),
611    Wildcard(Node),
612}
613
614#[derive(Debug, Clone)]
615pub enum StringPart {
616    Literal(Node, String),
617    Interpolation(Box<Expression>, Option<FormatSpecifier>),
618}
619
620#[derive(Debug, Clone)]
621pub enum FormatSpecifier {
622    LowerHex(Node),                      // :x
623    UpperHex(Node),                      // :X
624    Binary(Node),                        // :b
625    Float(Node),                         // :f
626    Precision(u32, Node, PrecisionType), // :..2f or :..5s
627}
628
629#[derive(Debug, Clone)]
630pub enum PrecisionType {
631    Float(Node),
632    String(Node),
633}
634
635#[derive()]
636pub struct Module {
637    pub expression: Option<Expression>,
638    pub definitions: Vec<Definition>,
639}
640
641impl Debug for Module {
642    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
643        for definition in &self.definitions {
644            writeln!(f, "{definition:?}")?;
645        }
646
647        if !self.definitions.is_empty() && self.expression.is_some() {
648            writeln!(f, "---")?;
649        }
650
651        if let Some(found_expression) = &self.expression {
652            match &found_expression.kind {
653                ExpressionKind::Block(expressions) => {
654                    for expression in expressions {
655                        writeln!(f, "{expression:?}")?;
656                    }
657                }
658                _ => writeln!(f, "{found_expression:?}")?,
659            }
660        }
661
662        Ok(())
663    }
664}
665
666impl Module {
667    #[must_use]
668    pub const fn new(definitions: Vec<Definition>, expression: Option<Expression>) -> Self {
669        Self {
670            expression,
671            definitions,
672        }
673    }
674
675    #[must_use]
676    pub const fn expression(&self) -> &Option<Expression> {
677        &self.expression
678    }
679
680    #[must_use]
681    pub const fn definitions(&self) -> &Vec<Definition> {
682        &self.definitions
683    }
684
685    #[must_use]
686    pub fn imports(&self) -> Vec<&Use> {
687        let mut use_items = Vec::new();
688
689        for def in &self.definitions {
690            if let Definition::Use(use_info) = def {
691                use_items.push(use_info);
692            }
693        }
694
695        use_items
696    }
697}