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