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