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