swamp_script_semantic/
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 inst_cache;
6pub mod intr;
7pub mod prelude;
8
9pub mod instantiator;
10
11use crate::intr::IntrinsicFunction;
12use crate::prelude::IntrinsicFunctionDefinitionRef;
13
14use crate::instantiator::Instantiator;
15pub use fixed32::Fp;
16use seq_map::SeqMap;
17use std::cmp::PartialEq;
18use std::fmt;
19use std::fmt::{Debug, Display, Formatter};
20use std::rc::Rc;
21use swamp_script_node::Node;
22use swamp_script_types::prelude::*;
23use tracing::error;
24
25#[derive(Debug, Clone)]
26pub struct TypeWithMut {
27    pub resolved_type: Type,
28    pub is_mutable: bool,
29}
30
31#[derive(Debug, Clone)]
32pub enum SemanticError {
33    CouldNotInsertStruct,
34    DuplicateTypeAlias(String),
35    CanOnlyUseStructForMemberFunctions,
36    ResolveNotStruct,
37    DuplicateStructName(String),
38    DuplicateEnumType(String),
39    DuplicateEnumVariantType(String, String),
40    DuplicateFieldName(String),
41    DuplicateExternalFunction(String),
42    DuplicateRustType(String),
43    DuplicateConstName(String),
44    CircularConstantDependency(Vec<ConstantId>),
45    DuplicateConstantId(ConstantId),
46    IncompatibleTypes,
47    WasNotImmutable,
48    WasNotMutable,
49    DuplicateSymbolName(String),
50    DuplicateNamespaceLink(String),
51    MismatchedTypes { expected: Type, found: Vec<Type> },
52    UnknownImplOnType,
53    UnknownTypeVariable,
54}
55
56#[derive(Debug, Eq, PartialEq)]
57pub struct LocalIdentifier(pub Node);
58
59#[derive(Debug)]
60pub struct InternalMainExpression {
61    pub expression: Expression,
62    pub function_scope_state: Vec<VariableRef>,
63    pub program_unique_id: InternalFunctionId,
64}
65
66//#[derive(Debug,Clone)]
67pub struct InternalFunctionDefinition {
68    pub body: Expression,
69    pub name: LocalIdentifier,
70    pub assigned_name: String,
71    pub signature: Signature,
72    pub variable_scopes: FunctionScopeState,
73    pub function_scope_state: Vec<VariableRef>,
74    pub program_unique_id: InternalFunctionId,
75}
76
77impl Default for InternalFunctionDefinition {
78    fn default() -> Self {
79        Self {
80            body: Expression {
81                ty: Type::Never,
82                node: Node::default(),
83                kind: ExpressionKind::Block(vec![]),
84            },
85            name: LocalIdentifier(Node::default()),
86            assigned_name: String::new(),
87            signature: Signature {
88                parameters: vec![],
89                return_type: Box::new(Type::Never),
90            },
91            variable_scopes: FunctionScopeState::new(Type::Unit),
92            function_scope_state: Vec::new(),
93            program_unique_id: 0,
94        }
95    }
96}
97
98impl Debug for InternalFunctionDefinition {
99    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
100        write!(f, "{:?}\n{:?}", self.signature, self.body)
101    }
102}
103
104impl PartialEq<Self> for InternalFunctionDefinition {
105    fn eq(&self, other: &Self) -> bool {
106        self.name == other.name
107    }
108}
109
110impl Eq for InternalFunctionDefinition {}
111
112pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
113
114pub type ExternalFunctionId = u32;
115
116pub type InternalFunctionId = u16;
117
118pub type ConstantId = u32;
119
120#[derive(Eq, PartialEq)]
121pub struct ExternalFunctionDefinition {
122    pub name: Option<Node>,
123    pub assigned_name: String,
124    pub signature: Signature,
125    pub id: ExternalFunctionId,
126}
127
128impl Debug for ExternalFunctionDefinition {
129    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
130        write!(f, "external fn")
131    }
132}
133
134pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
135
136#[derive(Debug, Eq, Clone, PartialEq)]
137pub enum BlockScopeMode {
138    Open,
139    Closed,
140}
141
142#[derive(Debug, Clone)]
143pub struct BlockScope {
144    pub mode: BlockScopeMode,
145    pub variables: SeqMap<String, VariableRef>,
146}
147
148impl Display for BlockScope {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
150        writeln!(f, "-- scope {:?}", self.mode)?;
151
152        for (index, (name, var)) in self.variables.iter().enumerate() {
153            writeln!(f, "  var({index}): {name}:{var:?}")?;
154        }
155        Ok(())
156    }
157}
158
159impl Default for BlockScope {
160    fn default() -> Self {
161        Self::new()
162    }
163}
164
165impl BlockScope {
166    #[must_use]
167    pub fn new() -> Self {
168        Self {
169            mode: BlockScopeMode::Open,
170            variables: SeqMap::new(),
171        }
172    }
173}
174
175#[derive(Clone)]
176pub struct FunctionScopeState {
177    pub block_scope_stack: Vec<BlockScope>,
178    pub return_type: Type,
179    pub variable_index: usize,
180}
181
182impl Display for FunctionScopeState {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
184        for (index, scope) in self.block_scope_stack.iter().enumerate() {
185            writeln!(f, "block({index}):\n{scope}")?;
186        }
187        Ok(())
188    }
189}
190
191impl FunctionScopeState {
192    pub fn gen_variable_index(&mut self) -> usize {
193        let index = self.variable_index;
194        self.variable_index += 1;
195        index
196    }
197}
198
199impl FunctionScopeState {
200    #[must_use]
201    pub fn new(return_type: Type) -> Self {
202        Self {
203            block_scope_stack: vec![BlockScope::new()],
204            return_type,
205            variable_index: 0,
206        }
207    }
208}
209
210#[derive(Debug, Clone)]
211pub struct Variable {
212    pub name: Node,
213    pub assigned_name: String,
214    pub resolved_type: Type,
215    pub mutable_node: Option<Node>,
216
217    pub scope_index: usize,
218    pub variable_index: usize,
219
220    pub unique_id_within_function: usize,
221    pub is_unused: bool,
222}
223
224impl Variable {
225    #[must_use]
226    pub const fn is_mutable(&self) -> bool {
227        self.mutable_node.is_some()
228    }
229}
230
231pub type VariableRef = Rc<Variable>;
232
233#[derive(Debug, Clone)]
234pub struct MutVariable {
235    pub variable_ref: VariableRef,
236}
237
238//type MutVariableRef = Rc<MutVariable>;
239
240#[derive(Debug, Clone)]
241pub enum BinaryOperatorKind {
242    Add,
243    Subtract,
244    Multiply,
245    Divide,
246    Modulo,
247    LogicalOr,
248    LogicalAnd,
249    Equal,
250    NotEqual,
251    LessThan,
252    LessEqual,
253    GreaterThan,
254    GreaterEqual,
255    RangeExclusive,
256}
257
258#[derive(Debug, Clone)]
259pub struct BinaryOperator {
260    pub left: Box<Expression>,
261    pub right: Box<Expression>,
262    pub kind: BinaryOperatorKind,
263    pub node: Node,
264}
265
266#[derive(Debug, Clone)]
267pub enum UnaryOperatorKind {
268    Not,
269    Negate,
270}
271#[derive(Debug, Clone)]
272pub struct UnaryOperator {
273    pub left: Box<Expression>,
274    pub kind: UnaryOperatorKind,
275    pub node: Node,
276}
277
278#[derive()]
279pub struct InternalFunctionCall {
280    pub arguments: Vec<ArgumentExpressionOrLocation>,
281
282    pub function_definition: InternalFunctionDefinitionRef,
283    pub function_expression: Box<Expression>,
284}
285
286impl Debug for InternalFunctionCall {
287    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
288        write!(
289            f,
290            "InFuncCall({:?} {:?})",
291            self.function_expression, self.arguments
292        )
293    }
294}
295
296#[derive(Debug, Clone)]
297pub struct ExternalFunctionCall {
298    pub arguments: Vec<ArgumentExpressionOrLocation>,
299    pub function_definition: ExternalFunctionDefinitionRef,
300    pub function_expression: Box<Expression>,
301}
302
303pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
304    let mut result = String::new();
305    for (i, (key, value)) in values.iter().enumerate() {
306        if i > 0 {
307            result.push_str(", ");
308        }
309        result.push_str(format!("{}: {}", key, value).as_str());
310    }
311    result
312}
313
314#[derive(Debug, Clone)]
315pub struct MemberCall {
316    pub function: FunctionRef,
317    pub arguments: Vec<ArgumentExpressionOrLocation>,
318}
319
320#[derive(Debug, Clone)]
321pub struct ArrayItem {
322    pub item_type: Type,
323    pub int_expression: Expression,
324    pub array_expression: Expression,
325    pub array_type: Type,
326}
327
328pub type ArrayItemRef = Rc<ArrayItem>;
329
330#[derive(Debug, Clone)]
331pub enum PrecisionType {
332    Float,
333    String,
334}
335
336#[derive(Debug, Clone)]
337pub enum FormatSpecifierKind {
338    LowerHex,                            // :x
339    UpperHex,                            // :X
340    Binary,                              // :b
341    Float,                               // :f
342    Precision(u32, Node, PrecisionType), // :..2f or :..5s
343}
344
345#[derive(Debug, Clone)]
346pub struct FormatSpecifier {
347    pub node: Node,
348    pub kind: FormatSpecifierKind,
349}
350
351#[derive(Debug, Clone)]
352pub enum StringPart {
353    Literal(Node, String),
354    Interpolation(Expression, Option<FormatSpecifier>),
355}
356
357pub type FunctionRef = Rc<Function>;
358
359#[derive(Debug, Eq, Clone, PartialEq)]
360pub enum Function {
361    Internal(InternalFunctionDefinitionRef),
362    External(ExternalFunctionDefinitionRef),
363}
364
365impl Function {
366    #[must_use]
367    pub fn name(&self) -> String {
368        match self {
369            Self::Internal(x) => x.assigned_name.clone(),
370            Self::External(y) => y.assigned_name.clone(),
371        }
372    }
373
374    #[must_use]
375    pub fn maybe_node(&self) -> Option<&Node> {
376        match self {
377            Self::Internal(x) => Some(&x.name.0),
378            Self::External(y) => y.name.as_ref(),
379        }
380    }
381
382    #[must_use]
383    pub fn node(&self) -> Node {
384        match self {
385            Self::Internal(x) => x.name.0.clone(),
386            Self::External(_y) => Node::new_unknown(),
387        }
388    }
389
390    #[must_use]
391    pub fn signature(&self) -> &Signature {
392        match self {
393            Self::Internal(internal) => &internal.signature,
394            Self::External(external) => &external.signature,
395        }
396    }
397}
398
399#[derive(Debug, Clone)]
400pub struct BooleanExpression {
401    #[allow(unused)]
402    pub expression: Box<Expression>,
403}
404
405// TODO: Maybe have different Match types, one specific for enums and one for other values
406#[derive(Debug, Clone)]
407pub struct Match {
408    pub arms: Vec<MatchArm>,
409    pub expression: Box<MutOrImmutableExpression>,
410}
411
412impl Match {
413    #[must_use]
414    pub fn contains_wildcard(&self) -> bool {
415        for arm in &self.arms {
416            if let Pattern::Wildcard(_) = arm.pattern {
417                return true;
418            }
419        }
420        false
421    }
422}
423
424#[derive(Debug, Clone)]
425pub struct MatchArm {
426    #[allow(unused)]
427    pub pattern: Pattern,
428    pub expression: Box<Expression>,
429    pub expression_type: Type,
430}
431
432#[derive(Debug, Clone)]
433pub enum Pattern {
434    Normal(NormalPattern, Option<BooleanExpression>),
435    Wildcard(Node),
436}
437
438#[derive(Debug, Clone)]
439pub enum NormalPattern {
440    PatternList(Vec<PatternElement>),
441    EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
442    Literal(Literal),
443}
444
445#[derive(Debug, Clone)]
446pub enum PatternElement {
447    Variable(VariableRef),
448    VariableWithFieldIndex(VariableRef, usize),
449    Wildcard(Node),
450}
451
452#[derive(Debug, Clone)]
453pub struct Iterable {
454    pub key_type: Option<Type>, // It does not have to support a key type
455    pub value_type: Type,
456
457    pub resolved_expression: Box<MutOrImmutableExpression>,
458}
459
460#[derive(Debug, Clone)]
461pub struct StructInstantiation {
462    pub source_order_expressions: Vec<(usize, Expression)>,
463    pub struct_type_ref: NamedStructType,
464}
465
466#[derive(Debug, Clone)]
467pub struct AnonymousStructLiteral {
468    pub source_order_expressions: Vec<(usize, Expression)>,
469    pub anonymous_struct_type: AnonymousStructType,
470}
471
472#[derive(Debug, Clone, Eq, PartialEq)]
473pub enum CompoundOperatorKind {
474    Add,
475    Sub,
476    Mul,
477    Div,
478    Modulo,
479}
480
481#[derive(Debug, Clone)]
482pub struct CompoundOperator {
483    pub node: Node,
484    pub kind: CompoundOperatorKind,
485}
486
487#[derive(Debug, Clone)]
488pub struct VariableCompoundAssignment {
489    pub variable_ref: VariableRef, // compound only support single variable
490    pub expression: Box<Expression>,
491    pub compound_operator: CompoundOperator,
492}
493
494pub fn create_rust_type(name: &str, external_number: u32) -> ExternalType {
495    ExternalType {
496        type_name: name.to_string(),
497        number: external_number,
498    }
499}
500
501#[derive(Debug, Clone)]
502pub struct Guard {
503    pub condition: Option<BooleanExpression>,
504    pub result: Expression,
505}
506
507#[derive(Debug, Clone)]
508pub struct Postfix {
509    pub node: Node,
510    pub ty: Type,
511    pub kind: PostfixKind,
512}
513
514#[derive(Debug, Clone)]
515pub enum PostfixKind {
516    StructField(AnonymousStructType, usize),
517    MemberCall(FunctionRef, Vec<ArgumentExpressionOrLocation>),
518    FunctionCall(Vec<ArgumentExpressionOrLocation>),
519    OptionUnwrap, // ? operator
520    NoneCoalesce(Expression),
521}
522
523#[derive(Debug, Clone)]
524pub enum LocationAccessKind {
525    FieldIndex(AnonymousStructType, usize),
526    IntrinsicCallMut(IntrinsicFunction, Vec<Expression>),
527}
528
529#[derive(Debug, Clone)]
530pub struct LocationAccess {
531    pub node: Node,
532    pub ty: Type,
533    pub kind: LocationAccessKind,
534}
535
536#[derive(Debug, Clone)]
537pub struct SingleLocationExpression {
538    pub kind: SingleLocationExpressionKind,
539    pub node: Node,
540    pub ty: Type,
541
542    pub starting_variable: VariableRef,
543    pub access_chain: Vec<LocationAccess>,
544}
545
546#[derive(Debug, Clone)]
547pub struct SingleMutLocationExpression(pub SingleLocationExpression);
548
549#[derive(Debug, Clone)]
550pub enum SingleLocationExpressionKind {
551    MutVariableRef,
552    MutStructFieldRef(NamedStructType, usize),
553}
554
555#[derive(Debug, Clone)]
556pub struct MutOrImmutableExpression {
557    pub expression_or_location: ArgumentExpressionOrLocation,
558    pub is_mutable: Option<Node>,
559}
560
561impl MutOrImmutableExpression {
562    pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
563        match self.expression_or_location {
564            ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
565            ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
566        }
567    }
568
569    pub fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
570        match &self.expression_or_location {
571            ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
572            ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
573        }
574    }
575
576    pub fn ty(&self) -> &Type {
577        match &self.expression_or_location {
578            ArgumentExpressionOrLocation::Expression(expr) => &expr.ty,
579            ArgumentExpressionOrLocation::Location(loc) => &loc.ty,
580        }
581    }
582
583    #[must_use]
584    pub const fn node(&self) -> &Node {
585        match &self.expression_or_location {
586            ArgumentExpressionOrLocation::Expression(expr) => &expr.node,
587            ArgumentExpressionOrLocation::Location(loc) => &loc.node,
588        }
589    }
590}
591
592#[derive(Debug, Clone)]
593pub enum ArgumentExpressionOrLocation {
594    Expression(Expression),
595    Location(SingleLocationExpression),
596}
597
598impl ArgumentExpressionOrLocation {
599    #[must_use]
600    pub fn ty(&self) -> Type {
601        match self {
602            Self::Expression(expr) => expr.ty.clone(),
603            Self::Location(location) => location.ty.clone(),
604        }
605    }
606}
607
608#[derive(Clone)]
609pub struct Expression {
610    pub ty: Type,
611    pub node: Node,
612    pub kind: ExpressionKind,
613}
614
615impl Debug for Expression {
616    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
617        write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
618    }
619}
620
621#[derive(Debug, Clone)]
622pub struct WhenBinding {
623    pub variable: VariableRef,
624    pub expr: MutOrImmutableExpression,
625}
626
627impl WhenBinding {
628    #[must_use]
629    pub const fn has_expression(&self) -> bool {
630        match &self.expr.expression_or_location {
631            ArgumentExpressionOrLocation::Expression(expr) => {
632                !matches!(expr.kind, ExpressionKind::VariableAccess(_))
633            }
634            ArgumentExpressionOrLocation::Location(_) => true,
635        }
636    }
637}
638
639#[derive(Debug, Clone)]
640pub enum ExpressionKind {
641    // Access Lookup values
642    ConstantAccess(ConstantRef),
643    VariableAccess(VariableRef),
644
645    // ----
646    IntrinsicFunctionAccess(IntrinsicFunctionDefinitionRef),
647    InternalFunctionAccess(InternalFunctionDefinitionRef),
648    ExternalFunctionAccess(ExternalFunctionDefinitionRef),
649
650    // Operators
651    BinaryOp(BinaryOperator),
652    UnaryOp(UnaryOperator),
653    PostfixChain(Box<Expression>, Vec<Postfix>),
654
655    // Conversion
656    // the `?` operator. unwraps the value, unless it is none
657    CoerceOptionToBool(Box<Expression>),
658
659    // Calls
660
661    // For calls from returned function values
662    FunctionValueCall(
663        Signature,
664        Box<Expression>,
665        Vec<ArgumentExpressionOrLocation>,
666    ),
667
668    InterpolatedString(Vec<StringPart>),
669
670    // Constructing
671    VariableDefinition(VariableRef, Box<MutOrImmutableExpression>), // First time assignment
672    VariableReassignment(VariableRef, Box<MutOrImmutableExpression>),
673    Assignment(Box<SingleMutLocationExpression>, Box<Expression>),
674    CompoundAssignment(
675        SingleMutLocationExpression,
676        CompoundOperatorKind,
677        Box<Expression>,
678    ),
679
680    StructInstantiation(StructInstantiation),
681    AnonymousStructLiteral(AnonymousStructLiteral),
682    Literal(Literal),
683    Option(Option<Box<Expression>>), // Wrapping an expression in `Some()`
684    //Range(Box<Expression>, Box<Expression>, RangeMode),
685
686    // Loops
687    ForLoop(ForPattern, Iterable, Box<Expression>),
688    WhileLoop(BooleanExpression, Box<Expression>),
689
690    Block(Vec<Expression>),
691
692    // Match and compare
693    Match(Match),
694    Guard(Vec<Guard>),
695    If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
696    When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
697
698    TupleDestructuring(Vec<VariableRef>, Vec<Type>, Box<Expression>),
699
700    // --------------------------------------------------------------------
701    // Built In members
702    // --------------------------------------------------------------------
703    IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpressionOrLocation>),
704    /*
705    //NoneCoalesceOperator(Box<Expression>, Box<Expression>),
706
707    IntrinsicCallMut(
708        IntrinsicFunction,
709        SingleMutLocationExpression,
710        Vec<Expression>,
711    ),
712
713     */
714    //IntrinsicCall(IntrinsicFunction, Vec<Expression>),
715    Lambda(Vec<VariableRef>, Box<Expression>),
716}
717
718#[derive(Debug, Clone)]
719pub struct StringConst(pub Node);
720
721#[derive(Debug, Clone)]
722pub enum Literal {
723    FloatLiteral(Fp),
724    NoneLiteral,
725    IntLiteral(i32),
726    StringLiteral(String),
727    BoolLiteral(bool),
728
729    EnumVariantLiteral(EnumType, EnumVariantType, EnumLiteralData),
730    TupleLiteral(Vec<Type>, Vec<Expression>),
731
732    Slice(Type, Vec<Expression>),
733    SlicePair(Type, Vec<(Expression, Expression)>),
734}
735
736#[derive(Debug, Clone)]
737pub struct ArrayInstantiation {
738    pub expressions: Vec<Expression>,
739    pub item_type: Type,
740    pub array_type: Type,
741    pub array_type_ref: Type,
742}
743
744#[derive(Debug, Clone)]
745pub enum ForPattern {
746    Single(VariableRef),
747    Pair(VariableRef, VariableRef),
748}
749
750impl ForPattern {
751    #[must_use]
752    pub fn is_mutable(&self) -> bool {
753        match self {
754            Self::Single(variable) => variable.is_mutable(),
755            Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
756        }
757    }
758}
759
760impl Display for ForPattern {
761    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
762        write!(f, "resolved_for_pattern")
763    }
764}
765
766#[derive(Debug, Eq, PartialEq)]
767pub struct ModulePathItem(pub Node);
768
769#[derive(Debug, Clone, Eq, PartialEq)]
770pub struct LocalTypeIdentifier(pub Node);
771
772#[derive(Debug, Clone)]
773pub struct Constant {
774    pub name: Node,
775    pub assigned_name: String,
776    pub id: ConstantId,
777    pub expr: Expression,
778    pub resolved_type: Type,
779}
780pub type ConstantRef = Rc<Constant>;
781
782pub type OptionTypeRef = Rc<crate::OptionType>;
783
784#[derive(Debug, Clone)]
785pub struct OptionType {
786    pub item_type: Type,
787}
788
789/*
790pub fn sort_struct_fields(
791    unordered_seq_map: &SeqMap<String, StructTypeField>,
792) -> SeqMap<String, StructTypeField> {
793    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
794    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
795    let mut ordered_seq_map = SeqMap::new();
796
797    for (name, field) in sorted_pairs {
798        ordered_seq_map.insert(name, field).unwrap() // We know already that the key fields are unique
799    }
800
801    ordered_seq_map
802}
803
804 */
805
806#[derive(Debug, Clone)]
807pub struct ImplMember {}
808
809#[derive(Debug, Clone)]
810pub enum UseItem {
811    Identifier(Node),
812    TypeIdentifier(Node),
813}
814
815#[derive(Debug, Clone)]
816pub struct Use {
817    pub path: Vec<Node>,
818    pub items: Vec<UseItem>,
819}
820
821#[derive(Debug, Clone)]
822pub struct ImplFunctions {
823    pub functions: SeqMap<String, FunctionRef>,
824}
825
826impl Default for ImplFunctions {
827    fn default() -> Self {
828        Self::new()
829    }
830}
831
832impl ImplFunctions {
833    #[must_use]
834    pub fn new() -> Self {
835        Self {
836            functions: SeqMap::default(),
837        }
838    }
839}
840
841#[derive(Debug, Clone)]
842pub struct AssociatedImpls {
843    pub functions: SeqMap<Type, ImplFunctions>,
844}
845
846impl Default for AssociatedImpls {
847    fn default() -> Self {
848        Self::new()
849    }
850}
851
852impl AssociatedImpls {
853    #[must_use]
854    pub fn new() -> Self {
855        Self {
856            functions: SeqMap::default(),
857        }
858    }
859}
860
861impl AssociatedImpls {
862    pub fn prepare(&mut self, ty: &Type) {
863        self.functions
864            .insert(ty.clone(), ImplFunctions::new())
865            .expect("should work");
866    }
867    #[must_use]
868    pub fn get_member_function(&self, ty: &Type, function_name: &str) -> Option<&FunctionRef> {
869        let maybe_found_impl = self.functions.get(&ty);
870        if let Some(found_impl) = maybe_found_impl {
871            if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
872                return Some(func);
873            }
874        }
875        None
876    }
877
878    pub fn api_get_external_function(
879        &self,
880        ty: &Type,
881        function_name: &str,
882    ) -> Option<&ExternalFunctionDefinitionRef> {
883        if let Some(found) = self.get_member_function(ty, function_name) {
884            if let Function::External(ext_fn) = &**found {
885                return Some(ext_fn);
886            }
887        }
888        None
889    }
890
891    pub fn api_fetch_external_function_id(
892        &self,
893        ty: &Type,
894        function_name: &str,
895    ) -> ExternalFunctionId {
896        self.api_get_external_function(ty, function_name)
897            .unwrap()
898            .id
899    }
900
901    pub fn get_internal_member_function(
902        &self,
903        ty: &Type,
904        function_name: &str,
905    ) -> Option<&InternalFunctionDefinitionRef> {
906        if let Some(found) = self.get_member_function(ty, function_name) {
907            if let Function::Internal(int_fn) = &**found {
908                return Some(int_fn);
909            }
910        }
911        None
912    }
913
914    pub fn add_member_function(
915        &mut self,
916        ty: &Type,
917        name: &str,
918        func: FunctionRef,
919    ) -> Result<(), SemanticError> {
920        let maybe_found_impl = self.functions.get_mut(&ty);
921
922        if let Some(found_impl) = maybe_found_impl {
923            found_impl
924                .functions
925                .insert(name.to_string(), func)
926                .expect("todo");
927            Ok(())
928        } else {
929            error!(%ty, ?name, "wasn't prepared");
930            Err(SemanticError::UnknownImplOnType)
931        }
932    }
933
934    pub fn add_external_member_function(
935        &mut self,
936        ty: &Type,
937        func: ExternalFunctionDefinition,
938    ) -> Result<(), SemanticError> {
939        self.add_member_function(
940            ty,
941            &func.assigned_name.clone(),
942            Function::External(func.into()).into(),
943        )
944    }
945
946    pub fn add_external_struct_member_function(
947        &mut self,
948        named_struct_type: &NamedStructType,
949        func: Function,
950    ) -> Result<(), SemanticError> {
951        self.add_member_function(
952            &Type::NamedStruct(named_struct_type.clone()),
953            &func.name().clone(),
954            func.into(),
955        )
956    }
957
958    pub fn add_external_struct_member_function_external(
959        &mut self,
960        named_struct_type: NamedStructType,
961        func: ExternalFunctionDefinition,
962    ) -> Result<(), SemanticError> {
963        self.add_member_function(
964            &Type::NamedStruct(named_struct_type.clone()),
965            &func.assigned_name.clone(),
966            Function::External(func.into()).into(),
967        )
968    }
969
970    pub fn add_external_struct_member_function_external_ref(
971        &mut self,
972        named_struct_type: NamedStructType,
973        func: ExternalFunctionDefinitionRef,
974    ) -> Result<(), SemanticError> {
975        self.add_member_function(
976            &Type::NamedStruct(named_struct_type.clone()),
977            &func.assigned_name.clone(),
978            Function::External(func.into()).into(),
979        )
980    }
981}
982
983// Mutable part
984#[derive(Debug, Clone)]
985pub struct ProgramState {
986    pub external_function_number: ExternalFunctionId,
987    pub internal_function_id_allocator: InternalFunctionIdAllocator,
988    // It is just so we don't have to do another dependency check of the
989    // modules, we know that these constants have been
990    // evaluated in order already
991    pub constants_in_dependency_order: Vec<ConstantRef>,
992    pub instantiator: Instantiator,
993}
994
995impl Default for ProgramState {
996    fn default() -> Self {
997        Self::new()
998    }
999}
1000
1001#[derive(Debug, Clone)]
1002pub struct InternalFunctionIdAllocator {
1003    pub internal_function_number: InternalFunctionId,
1004}
1005
1006impl Default for InternalFunctionIdAllocator {
1007    fn default() -> Self {
1008        Self::new()
1009    }
1010}
1011
1012impl InternalFunctionIdAllocator {
1013    #[must_use]
1014    pub const fn new() -> Self {
1015        Self {
1016            internal_function_number: 0,
1017        }
1018    }
1019    pub fn alloc(&mut self) -> InternalFunctionId {
1020        self.internal_function_number += 1;
1021        self.internal_function_number
1022    }
1023}
1024
1025impl ProgramState {
1026    #[must_use]
1027    pub fn new() -> Self {
1028        Self {
1029            external_function_number: 0,
1030            internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1031            constants_in_dependency_order: Vec::new(),
1032            instantiator: Instantiator::new(),
1033        }
1034    }
1035
1036    pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
1037        self.external_function_number += 1;
1038        self.external_function_number
1039    }
1040
1041    pub fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1042        self.internal_function_id_allocator.alloc()
1043    }
1044}
1045
1046#[derive(Clone)]
1047pub enum EnumLiteralData {
1048    Nothing,
1049    Tuple(Vec<Expression>),
1050    Struct(Vec<(usize, Expression)>),
1051}
1052
1053impl Debug for EnumLiteralData {
1054    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1055        match self {
1056            Self::Nothing => Ok(()),
1057            Self::Tuple(x) => write!(f, "{x:?}"),
1058            Self::Struct(s) => write!(f, "{s:?}"),
1059        }
1060    }
1061}