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 intr;
6pub mod modules;
7pub mod ns;
8pub mod prelude;
9pub mod symtbl;
10
11use crate::intr::IntrinsicFunction;
12pub use fixed32::Fp;
13use seq_fmt::comma;
14use seq_map::SeqMap;
15use std::cell::RefCell;
16use std::cmp::PartialEq;
17use std::fmt;
18use std::fmt::{Debug, Display, Formatter};
19use std::hash::Hash;
20use std::rc::Rc;
21use tracing::{error, info};
22
23#[derive(Clone, Eq, PartialEq, Default)]
24pub struct Node {
25    pub span: Span,
26}
27
28impl Debug for Node {
29    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
30        if self.span.file_id == 0xffff {
31            write!(f, "<{}:{}>", self.span.offset, self.span.length)
32        } else {
33            write!(
34                f,
35                "<{}:{} ({})>",
36                self.span.offset, self.span.length, self.span.file_id
37            )
38        }
39    }
40}
41
42pub type FileId = u16;
43
44#[derive(PartialEq, Eq, Hash, Default, Clone)]
45pub struct Span {
46    pub file_id: FileId,
47    pub offset: u32,
48    pub length: u16,
49}
50
51impl Span {
52    pub fn dummy() -> Self {
53        Span {
54            offset: 0,
55            length: 0,
56            file_id: 0xffff,
57        }
58    }
59
60    // Helper method to get the end position
61    pub fn end(&self) -> u32 {
62        self.offset + self.length as u32
63    }
64}
65
66impl Debug for Span {
67    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
68        write!(f, "<{}:{} ({})>", self.offset, self.length, self.file_id)
69    }
70}
71
72#[derive(Clone, Eq, PartialEq)]
73pub struct ParameterNode {
74    pub name: Node,
75    pub is_mutable: Option<Node>,
76}
77
78impl Debug for ParameterNode {
79    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
80        write!(f, "Parameter")
81    }
82}
83
84impl ParameterNode {
85    #[inline]
86    #[must_use]
87    pub const fn is_mutable(&self) -> bool {
88        self.is_mutable.is_some()
89    }
90}
91
92#[derive(Debug, Clone, Eq, PartialEq)]
93pub struct Signature {
94    pub parameters: Vec<TypeForParameter>,
95    pub return_type: Box<Type>,
96}
97
98impl Display for Signature {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
100        write!(f, "({})->{}", comma(&self.parameters), self.return_type)
101    }
102}
103
104impl Signature {
105    pub fn same_type(&self, other: &Signature) -> bool {
106        if self.parameters.len() != other.parameters.len()
107            || !self.return_type.compatible_with(&other.return_type)
108        {
109            return false;
110        }
111
112        for (param, other_param) in self.parameters.iter().zip(other.parameters.clone()) {
113            if !&param
114                .resolved_type
115                .compatible_with(&other_param.resolved_type)
116            {
117                return false;
118            }
119
120            if param.is_mutable != other_param.is_mutable {
121                return false;
122            }
123        }
124
125        true
126    }
127}
128
129#[derive(Debug, Clone, Eq, PartialEq)]
130pub struct ExternalType {
131    pub type_name: String, // To identify the specific Rust type
132    pub number: u32,       // For type comparison
133}
134
135pub type ExternalTypeRef = Rc<ExternalType>;
136
137#[derive(Debug, Clone)]
138pub struct TypeWithMut {
139    pub resolved_type: Type,
140    pub is_mutable: bool,
141}
142
143#[derive(Debug, Clone)]
144pub struct TypeForParameter {
145    pub name: String,
146    pub resolved_type: Type,
147    pub is_mutable: bool,
148    pub node: Option<ParameterNode>,
149}
150
151impl Display for TypeForParameter {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
153        write!(
154            f,
155            "{}{}: {:?}",
156            if self.is_mutable { "mut " } else { "" },
157            self.name,
158            self.resolved_type
159        )
160    }
161}
162
163impl Eq for TypeForParameter {}
164
165impl PartialEq for TypeForParameter {
166    fn eq(&self, other: &Self) -> bool {
167        let types_equal = self.resolved_type.compatible_with(&other.resolved_type);
168
169        types_equal && (self.is_mutable == other.is_mutable)
170    }
171}
172
173#[derive(Clone, Eq, PartialEq)]
174pub enum Type {
175    // Primitives
176    Int,
177    Float,
178    String,
179    Bool,
180
181    Unit,  // Empty or nothing
182    Never, // Not even empty since control flow has escaped with break or return.
183
184    // Containers
185    Array(ArrayTypeRef),
186    Tuple(TupleTypeRef),
187    NamedStruct(StructTypeRef),
188    AnonymousStruct(AnonymousStructType),
189    Map(MapTypeRef),
190
191    Enum(EnumTypeRef),
192    Generic(Box<Type>, Vec<Type>),
193
194    Function(Signature),
195    Iterable(Box<Type>),
196
197    Optional(Box<Type>),
198    External(ExternalTypeRef),
199}
200
201impl Type {
202    #[must_use]
203    pub const fn is_concrete(&self) -> bool {
204        !matches!(self, Self::Unit | Self::Never)
205    }
206
207    pub fn id(&self) -> Option<TypeNumber> {
208        let found_id = match self {
209            Self::Unit => 0,
210            Self::Int => 1,
211            Self::Bool => 2,
212            Self::Float => 3,
213            Self::String => 4,
214            Self::NamedStruct(struct_ref) => struct_ref.borrow().type_id,
215            Self::Enum(enum_type) => enum_type.borrow().type_id,
216            _ => return None,
217        };
218        Some(found_id)
219    }
220}
221
222impl Debug for Type {
223    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
224        match self {
225            Self::Int => write!(f, "Int"),
226            Self::Float => write!(f, "Float"),
227            Self::String => write!(f, "String"),
228            Self::Bool => write!(f, "Bool"),
229            Self::Unit => write!(f, "Unit"),
230            Self::Never => write!(f, "!"),
231            Self::Array(array_type_ref) => write!(f, "[{:?}]", array_type_ref.item_type),
232            Self::Tuple(tuple_type_ref) => write!(f, "( {:?} )", tuple_type_ref.0),
233            Self::NamedStruct(struct_type_ref) => {
234                write!(f, "{}", struct_type_ref.borrow().assigned_name)
235            }
236            Self::AnonymousStruct(anonymous_struct_type) => {
237                write!(f, "{:?}", anonymous_struct_type)
238            }
239            Self::Map(map_type_ref) => write!(
240                f,
241                "[{:?}:{:?}]",
242                map_type_ref.key_type, map_type_ref.value_type
243            ),
244            Self::Generic(base, parameters) => write!(f, "{base:?}<{parameters:?}>"),
245            Self::Enum(enum_type_ref) => write!(f, "{:?}", enum_type_ref.borrow().assigned_name),
246            Self::Function(function_type_signature) => {
247                write!(f, "{:?}", function_type_signature)
248            }
249            Self::Iterable(type_generated) => write!(f, "Iterable<{type_generated:?}>"),
250            Self::Optional(base_type) => write!(f, "{base_type:?}?"),
251            Self::External(rust_type) => write!(f, "{:?}?", rust_type.type_name),
252        }
253    }
254}
255
256impl Display for Type {
257    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
258        match self {
259            Self::Int => write!(f, "Int"),
260            Self::Float => write!(f, "Float"),
261            Self::String => write!(f, "String"),
262            Self::Bool => write!(f, "Bool"),
263            Self::Unit => write!(f, "Unit"),
264            Self::Never => write!(f, "!"),
265            Self::Array(array_ref) => write!(f, "[{}]", &array_ref.item_type.to_string()),
266            Self::Tuple(tuple) => write!(f, "({})", comma(&tuple.0)),
267            Self::NamedStruct(struct_ref) => write!(f, "{}", struct_ref.borrow().assigned_name),
268            Self::AnonymousStruct(struct_ref) => write!(f, "{:?}", struct_ref),
269            Self::Map(map_ref) => write!(f, "[{}:{}]", map_ref.key_type, map_ref.value_type),
270            Self::Generic(base_type, params) => write!(f, "{base_type}<{}>", comma(params)),
271            Self::Enum(enum_type) => write!(f, "{}", enum_type.borrow().assigned_name),
272            Self::Function(signature) => write!(f, "function {signature}"),
273            Self::Iterable(generating_type) => write!(f, "Iterable<{generating_type}>"),
274            Self::Optional(base_type) => write!(f, "{base_type}?"),
275            Self::External(rust_type) => write!(f, "RustType {}", rust_type.type_name),
276        }
277    }
278}
279
280#[derive(Debug)]
281pub enum SemanticError {
282    CouldNotInsertStruct,
283    DuplicateTypeAlias(String),
284    CanOnlyUseStructForMemberFunctions,
285    ResolveNotStruct,
286    DuplicateStructName(String),
287    DuplicateEnumType(String),
288    DuplicateEnumVariantType(String, String),
289    DuplicateFieldName(String),
290    DuplicateExternalFunction(String),
291    DuplicateRustType(String),
292    DuplicateConstName(String),
293    CircularConstantDependency(Vec<ConstantId>),
294    DuplicateConstantId(ConstantId),
295    IncompatibleTypes,
296    WasNotImmutable,
297    WasNotMutable,
298    DuplicateSymbolName,
299    DuplicateNamespaceLink(String),
300    MismatchedTypes { expected: Type, found: Vec<Type> },
301    UnknownImplOnType,
302}
303
304impl Type {
305    pub fn expect_struct_type(&self) -> Result<StructTypeRef, SemanticError> {
306        match self {
307            Type::NamedStruct(struct_type_ref) => Ok(struct_type_ref.clone()),
308            _ => Err(SemanticError::ResolveNotStruct),
309        }
310    }
311
312    pub fn assignable_type(&self, other: &Type) -> bool {
313        if self.compatible_with(other) {
314            true
315        } else if let Self::Optional(inner_type) = self {
316            inner_type.compatible_with(other)
317        } else {
318            false
319        }
320    }
321
322    #[must_use]
323    pub fn compatible_with(&self, other: &Type) -> bool {
324        match (self, other) {
325            (Self::Function(a), Self::Function(b)) => a.same_type(b),
326            (_, Self::Never) => true,
327            (Self::Int, Self::Int) => true,
328            (Self::Float, Self::Float) => true,
329            (Self::String, Self::String) => true,
330            (Self::Bool, Self::Bool) => true,
331            (Self::Unit, Self::Unit) => true,
332            (Self::Array(_), Self::Array(_)) => true,
333            (Self::Map(a), Self::Map(b)) => {
334                a.key_type.compatible_with(&b.key_type)
335                    && a.value_type.compatible_with(&b.value_type)
336            }
337            (Self::NamedStruct(a), Self::NamedStruct(b)) => compare_struct_types(a, b),
338            (Self::AnonymousStruct(a), Self::AnonymousStruct(b)) => {
339                compare_anonymous_struct_types(a, b)
340            }
341            (Self::Tuple(a), Self::Tuple(b)) => {
342                if a.0.len() != b.0.len() {
343                    return false;
344                }
345                a.0.iter()
346                    .zip(b.0.iter())
347                    .all(|(a, b)| a.compatible_with(b))
348            }
349            (Self::Enum(_), Self::Enum(_)) => true,
350            (Self::Iterable(a), Self::Iterable(b)) => a.compatible_with(b),
351            //(Self::EnumVariant(a), Self::EnumVariant(b)) => a.owner.number == b.owner.number,
352            (Self::Optional(inner_type_a), Self::Optional(inner_type_b)) => {
353                inner_type_a.compatible_with(inner_type_b)
354            }
355            (Self::External(type_ref_a), Self::External(type_ref_b)) => {
356                type_ref_a.number == type_ref_b.number
357            }
358
359            (Self::Generic(base_a, params_a), Self::Generic(base_b, params_b)) => {
360                if !base_a.compatible_with(base_b) {
361                    return false;
362                }
363
364                if params_a.len() != params_b.len() {
365                    return false;
366                }
367
368                for (param_a, param_b) in params_a.iter().zip(params_b) {
369                    if !param_a.compatible_with(param_b) {
370                        return false;
371                    }
372                }
373                true
374            }
375            _ => false,
376        }
377    }
378}
379
380fn compare_struct_types(a: &StructTypeRef, b: &StructTypeRef) -> bool {
381    let a_borrow = a.borrow();
382    let b_borrow = b.borrow();
383    if a_borrow.assigned_name != b_borrow.assigned_name {
384        return false;
385    }
386
387    compare_anonymous_struct_types(&a_borrow.anon_struct_type, &b_borrow.anon_struct_type)
388}
389
390fn compare_anonymous_struct_types(a: &AnonymousStructType, b: &AnonymousStructType) -> bool {
391    if a.field_name_sorted_fields.len() != b.field_name_sorted_fields.len() {
392        return false;
393    }
394
395    for ((a_name, a_type), (b_name, b_type)) in a
396        .field_name_sorted_fields
397        .iter()
398        .zip(b.field_name_sorted_fields.clone())
399    {
400        if *a_name != b_name {
401            return false;
402        }
403
404        if !a_type.field_type.compatible_with(&b_type.field_type) {
405            return false;
406        }
407    }
408
409    true
410}
411
412#[must_use]
413pub fn check_assignable_anonymous_struct_types(
414    a: &AnonymousStructType,
415    b: &AnonymousStructType,
416) -> bool {
417    if a.field_name_sorted_fields.len() != b.field_name_sorted_fields.len() {
418        return false;
419    }
420
421    for (name, field) in &a.field_name_sorted_fields {
422        if let Some(found_field) = b.field_name_sorted_fields.get(name) {
423            if !found_field.field_type.compatible_with(&field.field_type) {
424                return false;
425            }
426        } else {
427            return false;
428        }
429    }
430
431    true
432}
433
434impl Node {
435    pub fn new_unknown() -> Self {
436        Self {
437            span: Span {
438                file_id: 0xffff,
439                offset: 0,
440                length: 0,
441            },
442        }
443    }
444}
445
446#[derive(Debug, Eq, PartialEq)]
447pub struct LocalIdentifier(pub Node);
448
449//#[derive(Debug)]
450pub struct InternalFunctionDefinition {
451    pub body: Expression,
452    pub name: LocalIdentifier,
453    pub assigned_name: String,
454    pub signature: Signature,
455}
456
457impl Debug for InternalFunctionDefinition {
458    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
459        write!(f, "{:?}\n{:?}", self.signature, self.body)
460    }
461}
462
463impl PartialEq<Self> for InternalFunctionDefinition {
464    fn eq(&self, other: &Self) -> bool {
465        self.name == other.name
466    }
467}
468
469impl Eq for InternalFunctionDefinition {}
470
471pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
472
473pub type ExternalFunctionId = u32;
474
475pub type ConstantId = u32;
476
477pub struct ExternalFunctionDefinition {
478    pub name: Option<Node>,
479    pub assigned_name: String,
480    pub signature: Signature,
481    pub id: ExternalFunctionId,
482}
483
484impl PartialEq<Self> for ExternalFunctionDefinition {
485    fn eq(&self, other: &Self) -> bool {
486        self.id == other.id
487    }
488}
489
490impl Eq for ExternalFunctionDefinition {}
491
492impl Debug for ExternalFunctionDefinition {
493    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
494        write!(f, "external fn")
495    }
496}
497
498pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
499
500#[derive(Debug)]
501pub struct Variable {
502    pub name: Node,
503    pub resolved_type: Type,
504    pub mutable_node: Option<Node>,
505
506    pub scope_index: usize,
507    pub variable_index: usize,
508}
509
510impl Variable {
511    #[must_use]
512    pub const fn is_mutable(&self) -> bool {
513        self.mutable_node.is_some()
514    }
515}
516
517pub type VariableRef = Rc<Variable>;
518
519#[derive(Debug)]
520pub struct MutVariable {
521    pub variable_ref: VariableRef,
522}
523
524//type MutVariableRef = Rc<MutVariable>;
525
526#[derive(Debug)]
527pub enum BinaryOperatorKind {
528    Add,
529    Subtract,
530    Multiply,
531    Divide,
532    Modulo,
533    LogicalOr,
534    LogicalAnd,
535    Equal,
536    NotEqual,
537    LessThan,
538    LessEqual,
539    GreaterThan,
540    GreaterEqual,
541    RangeExclusive,
542}
543
544#[derive(Debug)]
545pub struct BinaryOperator {
546    pub left: Box<Expression>,
547    pub right: Box<Expression>,
548    pub kind: BinaryOperatorKind,
549    pub node: Node,
550}
551
552#[derive(Debug)]
553pub enum UnaryOperatorKind {
554    Not,
555    Negate,
556}
557#[derive(Debug)]
558pub struct UnaryOperator {
559    pub left: Box<Expression>,
560    pub kind: UnaryOperatorKind,
561    pub node: Node,
562}
563
564#[derive()]
565pub struct InternalFunctionCall {
566    pub arguments: Vec<ArgumentExpressionOrLocation>,
567
568    pub function_definition: InternalFunctionDefinitionRef,
569    pub function_expression: Box<Expression>,
570}
571
572impl Debug for InternalFunctionCall {
573    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
574        write!(
575            f,
576            "InFuncCall({:?} {:?})",
577            self.function_expression, self.arguments
578        )
579    }
580}
581
582#[derive(Debug)]
583pub struct ExternalFunctionCall {
584    pub arguments: Vec<ArgumentExpressionOrLocation>,
585    pub function_definition: ExternalFunctionDefinitionRef,
586    pub function_expression: Box<Expression>,
587}
588
589#[must_use]
590pub fn comma_seq<K: Clone + Hash + Eq + Display, V: Display>(values: &SeqMap<K, V>) -> String {
591    let mut result = String::new();
592    for (i, (key, value)) in values.iter().enumerate() {
593        if i > 0 {
594            result.push_str(", ");
595        }
596        result.push_str(format!("{key}: {value}").as_str());
597    }
598    result
599}
600
601pub fn comma_seq_nl<K: Clone + Hash + Eq + Display, V: Display>(
602    values: &SeqMap<K, V>,
603    prefix: &str,
604) -> String {
605    let mut result = String::new();
606    for (key, value) in values.iter() {
607        result.push_str(format!("{}{}: {}\n", prefix, key, value).as_str());
608    }
609    result
610}
611
612pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
613    let mut result = String::new();
614    for (i, (key, value)) in values.iter().enumerate() {
615        if i > 0 {
616            result.push_str(", ");
617        }
618        result.push_str(format!("{}: {}", key, value).as_str());
619    }
620    result
621}
622
623#[derive(Debug)]
624pub struct MemberCall {
625    pub function: FunctionRef,
626    pub arguments: Vec<ArgumentExpressionOrLocation>,
627}
628
629#[derive(Debug, Eq, PartialEq, Clone)]
630pub struct StructTypeField {
631    pub identifier: Option<Node>,
632    pub field_type: Type,
633}
634
635impl Display for StructTypeField {
636    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
637        write!(f, "{:?}:{}", self.identifier, self.field_type)
638    }
639}
640
641#[derive(Debug)]
642pub struct MapIndexLookup {
643    pub map_type: Type,
644    pub item_type: Type,
645    pub map_type_ref: MapTypeRef,
646    pub index_expression: Box<Expression>,
647    pub map_expression: Box<Expression>,
648}
649
650#[derive(Debug)]
651pub struct ArrayItem {
652    pub item_type: Type,
653    pub int_expression: Expression,
654    pub array_expression: Expression,
655    pub array_type: Type,
656}
657
658pub type ArrayItemRef = Rc<ArrayItem>;
659
660#[derive(Debug)]
661pub enum PrecisionType {
662    Float,
663    String,
664}
665
666#[derive(Debug)]
667pub enum FormatSpecifierKind {
668    LowerHex,                            // :x
669    UpperHex,                            // :X
670    Binary,                              // :b
671    Float,                               // :f
672    Precision(u32, Node, PrecisionType), // :..2f or :..5s
673}
674
675#[derive(Debug)]
676pub struct FormatSpecifier {
677    pub node: Node,
678    pub kind: FormatSpecifierKind,
679}
680
681#[derive(Debug)]
682pub enum StringPart {
683    Literal(Node, String),
684    Interpolation(Expression, Option<FormatSpecifier>),
685}
686
687pub type FunctionRef = Rc<Function>;
688
689#[derive(Debug, Eq, PartialEq)]
690pub enum Function {
691    Internal(InternalFunctionDefinitionRef),
692    External(ExternalFunctionDefinitionRef),
693}
694
695impl Function {
696    #[must_use]
697    pub fn name(&self) -> String {
698        match self {
699            Self::Internal(x) => x.assigned_name.clone(),
700            Self::External(y) => y.assigned_name.clone(),
701        }
702    }
703
704    #[must_use]
705    pub fn maybe_node(&self) -> Option<&Node> {
706        match self {
707            Self::Internal(x) => Some(&x.name.0),
708            Self::External(y) => y.name.as_ref(),
709        }
710    }
711
712    #[must_use]
713    pub fn node(&self) -> Node {
714        match self {
715            Self::Internal(x) => x.name.0.clone(),
716            Self::External(_y) => Node::new_unknown(),
717        }
718    }
719
720    #[must_use]
721    pub fn signature(&self) -> &Signature {
722        match self {
723            Self::Internal(internal) => &internal.signature,
724            Self::External(external) => &external.signature,
725        }
726    }
727}
728
729#[derive(Debug)]
730pub struct BooleanExpression {
731    #[allow(unused)]
732    pub expression: Box<Expression>,
733}
734
735#[derive(Debug)]
736pub struct Match {
737    pub arms: Vec<MatchArm>,
738    pub expression: Box<MutOrImmutableExpression>,
739}
740
741#[derive(Debug)]
742pub struct MatchArm {
743    #[allow(unused)]
744    pub pattern: Pattern,
745    pub expression: Box<Expression>,
746    pub expression_type: Type,
747}
748
749#[derive(Debug)]
750pub enum Pattern {
751    Normal(NormalPattern, Option<BooleanExpression>),
752    Wildcard(Node),
753}
754
755#[derive(Debug)]
756pub enum NormalPattern {
757    PatternList(Vec<PatternElement>),
758    EnumPattern(EnumVariantTypeRef, Option<Vec<PatternElement>>),
759    Literal(Literal),
760}
761
762#[derive(Debug)]
763pub enum PatternElement {
764    Variable(VariableRef),
765    VariableWithFieldIndex(VariableRef, usize),
766    Wildcard(Node),
767}
768
769#[derive(Debug)]
770pub struct Iterable {
771    pub key_type: Option<Type>, // It does not have to support a key type
772    pub value_type: Type,
773
774    pub resolved_expression: Box<MutOrImmutableExpression>,
775}
776
777#[derive(Debug)]
778pub struct StructInstantiation {
779    pub source_order_expressions: Vec<(usize, Expression)>,
780    pub struct_type_ref: StructTypeRef,
781}
782
783#[derive(Debug)]
784pub struct AnonymousStructLiteral {
785    pub source_order_expressions: Vec<(usize, Expression)>,
786    pub anonymous_struct_type: AnonymousStructType,
787}
788
789#[derive(Debug, Eq, PartialEq)]
790pub enum CompoundOperatorKind {
791    Add,
792    Sub,
793    Mul,
794    Div,
795    Modulo,
796}
797
798#[derive(Debug)]
799pub struct CompoundOperator {
800    pub node: Node,
801    pub kind: CompoundOperatorKind,
802}
803
804#[derive(Debug)]
805pub struct VariableCompoundAssignment {
806    pub variable_ref: VariableRef, // compound only support single variable
807    pub expression: Box<Expression>,
808    pub compound_operator: CompoundOperator,
809}
810
811pub fn create_rust_type(name: &str, type_number: TypeNumber) -> ExternalTypeRef {
812    let rust_type = ExternalType {
813        type_name: name.to_string(),
814        number: type_number,
815    };
816    Rc::new(rust_type)
817}
818
819#[derive(Debug)]
820pub struct Guard {
821    pub condition: Option<BooleanExpression>,
822    pub result: Expression,
823}
824
825#[derive(Debug, Clone, Eq, PartialEq)]
826pub enum RangeMode {
827    Inclusive,
828    Exclusive,
829}
830
831#[derive(Debug)]
832pub struct Postfix {
833    pub node: Node,
834    pub ty: Type,
835    pub kind: PostfixKind,
836}
837
838#[derive(Debug)]
839pub struct Range {
840    pub min: Expression,
841    pub max: Expression,
842    pub mode: RangeMode,
843}
844
845#[derive(Debug)]
846pub enum PostfixKind {
847    StructField(AnonymousStructType, usize),
848    ArrayIndex(ArrayTypeRef, Expression),
849    ArrayRangeIndex(ArrayTypeRef, Range),
850    StringIndex(Expression),
851    StringRangeIndex(Range),
852    MapIndex(MapTypeRef, Expression),
853    ExternalTypeIndexRef(ExternalTypeRef, Expression),
854    MemberCall(FunctionRef, Vec<ArgumentExpressionOrLocation>),
855    FunctionCall(Vec<ArgumentExpressionOrLocation>),
856    OptionUnwrap, // ? operator
857    NoneCoalesce(Expression),
858
859    IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpressionOrLocation>),
860    IntrinsicCall(IntrinsicFunction, Vec<Expression>),
861}
862
863#[derive(Debug)]
864pub enum LocationAccessKind {
865    FieldIndex(AnonymousStructType, usize),
866    ArrayIndex(ArrayTypeRef, Expression),
867    ArrayRange(ArrayTypeRef, Range),
868    StringIndex(Expression),
869    StringRange(Range),
870    MapIndex(MapTypeRef, Expression),
871    MapIndexInsertIfNonExisting(MapTypeRef, Expression),
872    ExternalTypeIndex(ExternalTypeRef, Expression),
873}
874
875#[derive(Debug)]
876pub struct LocationAccess {
877    pub node: Node,
878    pub ty: Type,
879    pub kind: LocationAccessKind,
880}
881
882#[derive(Debug)]
883pub struct SingleLocationExpression {
884    pub kind: SingleLocationExpressionKind,
885    pub node: Node,
886    pub ty: Type,
887
888    pub starting_variable: VariableRef,
889    pub access_chain: Vec<LocationAccess>,
890}
891
892#[derive(Debug)]
893pub struct SingleMutLocationExpression(pub SingleLocationExpression);
894
895#[derive(Debug)]
896pub enum SingleLocationExpressionKind {
897    MutVariableRef,
898    MutStructFieldRef(StructTypeRef, usize),
899    MutArrayIndexRef(ArrayTypeRef),
900    MutMapIndexRef(MapTypeRef),
901    MutExternalTypeIndexRef(ExternalTypeRef),
902}
903
904#[derive(Debug)]
905pub struct SliceLocationExpression {
906    pub start: Box<Expression>,
907    pub range_start: Box<Expression>,
908    pub range_end: Box<Expression>,
909    pub mode: RangeMode,
910    pub ty: Type,
911}
912
913#[derive(Debug)]
914pub struct MutOrImmutableExpression {
915    pub expression_or_location: ArgumentExpressionOrLocation,
916    pub is_mutable: Option<Node>,
917}
918
919impl MutOrImmutableExpression {}
920
921impl MutOrImmutableExpression {
922    pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
923        match self.expression_or_location {
924            ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
925            ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
926        }
927    }
928
929    pub fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
930        match &self.expression_or_location {
931            ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
932            ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
933        }
934    }
935
936    pub fn ty(&self) -> &Type {
937        match &self.expression_or_location {
938            ArgumentExpressionOrLocation::Expression(expr) => &expr.ty,
939            ArgumentExpressionOrLocation::Location(loc) => &loc.ty,
940        }
941    }
942}
943
944#[derive(Debug)]
945pub enum ArgumentExpressionOrLocation {
946    Expression(Expression),
947    Location(SingleLocationExpression),
948}
949
950#[derive()]
951pub struct Expression {
952    pub ty: Type,
953    pub node: Node,
954    pub kind: ExpressionKind,
955}
956
957impl Debug for Expression {
958    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
959        write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
960    }
961}
962
963#[derive(Debug)]
964pub struct WhenBinding {
965    pub variable: VariableRef,
966    pub expr: MutOrImmutableExpression,
967}
968
969#[derive(Debug)]
970pub enum ExpressionKind {
971    // Access Lookup values
972    ConstantAccess(ConstantRef),
973    VariableAccess(VariableRef),
974    FieldAccess(Box<Expression>, usize),
975    ArrayAccess(
976        Box<Expression>,
977        ArrayTypeRef,
978        Box<Expression>, // int index lookup
979    ), // Read from an array: arr[3]
980    MapIndexAccess(Box<Expression>, MapTypeRef, Box<Expression>),
981    StringRangeAccess(Box<Expression>, Box<Range>),
982    ArrayRangeAccess(Box<Expression>, Box<Range>),
983
984    // ----
985    InternalFunctionAccess(InternalFunctionDefinitionRef),
986    ExternalFunctionAccess(ExternalFunctionDefinitionRef),
987
988    // Adding to a collection
989    MapAssignment(
990        Box<SingleMutLocationExpression>,
991        Box<Expression>,
992        Box<Expression>,
993    ), // Motivation: Can not use location since adding is more complex
994
995    // Operators
996    BinaryOp(BinaryOperator),
997    UnaryOp(UnaryOperator),
998    PostfixChain(Box<Expression>, Vec<Postfix>),
999
1000    // Conversion
1001    // the `?` operator. unwraps the value, unless it is none
1002    //NoneCoalesceOperator(Box<Expression>, Box<Expression>),
1003    CoerceOptionToBool(Box<Expression>),
1004
1005    // Calls
1006
1007    // For calls from returned function values
1008    FunctionCall(
1009        Signature,
1010        Box<Expression>,
1011        Vec<ArgumentExpressionOrLocation>,
1012    ),
1013
1014    MemberCall(MemberCall),
1015    InterpolatedString(Vec<StringPart>),
1016
1017    // Constructing
1018    VariableDefinition(VariableRef, Box<MutOrImmutableExpression>), // First time assignment
1019    VariableReassignment(VariableRef, Box<MutOrImmutableExpression>),
1020
1021    StructInstantiation(StructInstantiation),
1022    AnonymousStructLiteral(AnonymousStructLiteral),
1023    Array(ArrayInstantiation),
1024    Tuple(Vec<Expression>),
1025    Literal(Literal),
1026    Option(Option<Box<Expression>>), // Wrapping an expression in `Some()`
1027    Range(Box<Expression>, Box<Expression>, RangeMode),
1028
1029    // Control
1030    ForLoop(ForPattern, Iterable, Box<Expression>),
1031    WhileLoop(BooleanExpression, Box<Expression>),
1032    Return(Option<Box<Expression>>),
1033    Break,
1034    Continue, //
1035
1036    Block(Vec<Expression>),
1037
1038    // Match and compare
1039    Match(Match),
1040    Guard(Vec<Guard>),
1041    If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
1042
1043    When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
1044
1045    TupleDestructuring(Vec<VariableRef>, TupleTypeRef, Box<Expression>),
1046
1047    Assignment(Box<SingleMutLocationExpression>, Box<Expression>),
1048    AssignmentSlice(Box<SliceLocationExpression>, Box<Expression>),
1049    CompoundAssignment(
1050        SingleMutLocationExpression,
1051        CompoundOperatorKind,
1052        Box<Expression>,
1053    ),
1054
1055    // --------------------------------------------------------------------
1056    // Built In members
1057    // --------------------------------------------------------------------
1058    IntrinsicCallMut(
1059        IntrinsicFunction,
1060        SingleMutLocationExpression,
1061        Vec<Expression>,
1062    ),
1063
1064    // Sparse Built in
1065    SparseNew(ExternalTypeRef, Type), // item type
1066}
1067
1068#[derive(Debug)]
1069pub struct StringConst(pub Node);
1070
1071#[derive(Debug)]
1072pub enum Literal {
1073    FloatLiteral(Fp),
1074    NoneLiteral,
1075    IntLiteral(i32),
1076    StringLiteral(String),
1077    BoolLiteral(bool),
1078
1079    EnumVariantLiteral(EnumVariantTypeRef, EnumLiteralData),
1080    TupleLiteral(TupleTypeRef, Vec<Expression>),
1081    Array(ArrayTypeRef, Vec<Expression>),
1082    Map(MapTypeRef, Vec<(Expression, Expression)>),
1083}
1084
1085#[derive(Debug)]
1086pub struct ArrayInstantiation {
1087    pub expressions: Vec<Expression>,
1088    pub item_type: Type,
1089    pub array_type: Type,
1090    pub array_type_ref: ArrayTypeRef,
1091}
1092
1093#[derive(Debug)]
1094pub enum ForPattern {
1095    Single(VariableRef),
1096    Pair(VariableRef, VariableRef),
1097}
1098
1099impl ForPattern {
1100    #[must_use]
1101    pub fn is_mutable(&self) -> bool {
1102        match self {
1103            Self::Single(variable) => variable.is_mutable(),
1104            Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
1105        }
1106    }
1107}
1108
1109impl Display for ForPattern {
1110    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1111        write!(f, "resolved_for_pattern")
1112    }
1113}
1114
1115#[derive(Debug, Eq, PartialEq)]
1116pub struct ModulePathItem(pub Node);
1117
1118pub type StructTypeRef = Rc<RefCell<NamedStructType>>;
1119
1120pub fn same_anon_struct_ref(a: &AnonymousStructType, b: &AnonymousStructType) -> bool {
1121    compare_anonymous_struct_types(a, b)
1122}
1123
1124pub fn same_named_struct_ref(a: &StructTypeRef, b: &StructTypeRef) -> bool {
1125    if a.borrow().assigned_name != b.borrow().assigned_name {
1126        return false;
1127    }
1128
1129    compare_anonymous_struct_types(&a.borrow().anon_struct_type, &b.borrow().anon_struct_type)
1130}
1131
1132pub type TypeNumber = u32;
1133
1134#[derive(Debug, Clone, Eq, PartialEq)]
1135pub struct LocalTypeIdentifier(pub Node);
1136
1137#[derive(Debug)]
1138pub struct Constant {
1139    pub name: Node,
1140    pub assigned_name: String,
1141    pub id: ConstantId,
1142    pub expr: Expression,
1143    pub resolved_type: Type,
1144}
1145pub type ConstantRef = Rc<Constant>;
1146
1147#[derive(Debug)]
1148pub struct AliasType {
1149    pub name: Node,
1150    pub assigned_name: String,
1151    pub referenced_type: Type,
1152}
1153pub type AliasTypeRef = Rc<AliasType>;
1154
1155#[derive(Eq, PartialEq)]
1156pub struct NamedStructType {
1157    pub name: Node,
1158    pub assigned_name: String,
1159    pub anon_struct_type: AnonymousStructType,
1160    pub type_id: TypeNumber,
1161}
1162
1163impl Debug for NamedStructType {
1164    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1165        write!(f, "struct {:?}", self.assigned_name)
1166    }
1167}
1168
1169impl NamedStructType {
1170    pub fn new(
1171        name: Node,
1172        assigned_name: &str,
1173        anon_struct_type: AnonymousStructType,
1174        type_id: TypeNumber,
1175    ) -> Self {
1176        Self {
1177            //defined_in_module,
1178            anon_struct_type,
1179            name,
1180            assigned_name: assigned_name.to_string(),
1181            type_id,
1182        }
1183    }
1184
1185    pub fn field_index(&self, field_name: &str) -> Option<usize> {
1186        self.anon_struct_type
1187            .field_name_sorted_fields
1188            .get_index(&field_name.to_string())
1189    }
1190
1191    pub fn name(&self) -> &Node {
1192        &self.name
1193    }
1194}
1195
1196pub type OptionTypeRef = Rc<crate::OptionType>;
1197
1198#[derive(Debug)]
1199pub struct OptionType {
1200    pub item_type: Type,
1201}
1202
1203pub type ArrayTypeRef = Rc<ArrayType>;
1204
1205pub fn compatible_arrays(a: &ArrayTypeRef, b: &ArrayTypeRef) -> bool {
1206    a.item_type.compatible_with(&b.item_type)
1207}
1208
1209#[derive(Debug, Eq, PartialEq)]
1210pub struct ArrayType {
1211    pub item_type: Type,
1212}
1213
1214pub type MapTypeRef = Rc<MapType>;
1215
1216#[derive(Debug, Eq, PartialEq)]
1217pub struct MapType {
1218    pub key_type: Type,
1219    pub value_type: Type,
1220}
1221
1222pub type EnumVariantStructTypeRef = Rc<EnumVariantStructType>;
1223
1224/*
1225pub fn sort_struct_fields(
1226    unordered_seq_map: &SeqMap<String, StructTypeField>,
1227) -> SeqMap<String, StructTypeField> {
1228    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
1229    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
1230    let mut ordered_seq_map = SeqMap::new();
1231
1232    for (name, field) in sorted_pairs {
1233        ordered_seq_map.insert(name, field).unwrap() // We know already that the key fields are unique
1234    }
1235
1236    ordered_seq_map
1237}
1238
1239 */
1240
1241pub fn sort_struct_fields2(
1242    unordered_seq_map: &SeqMap<String, StructTypeField>,
1243) -> SeqMap<String, StructTypeField> {
1244    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
1245    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
1246
1247    sorted_pairs
1248        .into_iter()
1249        .map(|(name, field)| (name.clone(), field.clone()))
1250        .collect()
1251}
1252
1253#[derive(Clone, Eq, PartialEq)]
1254pub struct AnonymousStructType {
1255    //pub source_ordered_fields: SeqMap<String, StructTypeField>,
1256    pub field_name_sorted_fields: SeqMap<String, StructTypeField>,
1257}
1258
1259impl Debug for AnonymousStructType {
1260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1261        write!(f, "{}", comma_seq(&self.field_name_sorted_fields))
1262    }
1263}
1264
1265impl AnonymousStructType {
1266    pub fn new_and_sort_fields(source_ordered_fields: SeqMap<String, StructTypeField>) -> Self {
1267        Self {
1268            field_name_sorted_fields: sort_struct_fields2(&source_ordered_fields),
1269        }
1270    }
1271
1272    pub fn new(defined_order: SeqMap<String, StructTypeField>) -> Self {
1273        Self {
1274            field_name_sorted_fields: defined_order,
1275        }
1276    }
1277}
1278
1279#[derive(Debug, Eq, PartialEq)]
1280pub struct EnumVariantStructType {
1281    pub common: EnumVariantCommon,
1282    pub anon_struct: AnonymousStructType,
1283}
1284
1285pub type EnumVariantTupleTypeRef = Rc<EnumVariantTupleType>;
1286
1287#[derive(Debug, Eq, PartialEq)]
1288pub struct EnumVariantTupleType {
1289    pub common: EnumVariantCommon,
1290    pub fields_in_order: Vec<Type>,
1291}
1292
1293pub type TupleTypeRef = Rc<TupleType>;
1294
1295#[derive(Debug, Eq, PartialEq)]
1296pub struct TupleType(pub Vec<Type>);
1297
1298impl TupleType {
1299    pub fn new(types: Vec<Type>) -> Self {
1300        Self(types)
1301    }
1302}
1303
1304pub type EnumTypeRef = Rc<RefCell<EnumType>>;
1305
1306#[derive(Eq, PartialEq)]
1307pub struct EnumType {
1308    pub name: LocalTypeIdentifier,
1309    pub assigned_name: String,
1310    pub module_path: Vec<String>,
1311    pub type_id: TypeNumber,
1312
1313    pub variants: SeqMap<String, EnumVariantTypeRef>,
1314}
1315
1316impl Debug for EnumType {
1317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1318        write!(f, "{}", self.assigned_name)?;
1319        let s = comma(
1320            &self
1321                .variants
1322                .iter()
1323                .map(|(name, _variant)| name)
1324                .collect::<Vec<&String>>(),
1325        );
1326        write!(f, "{{ {s} }}")
1327    }
1328}
1329
1330impl EnumType {
1331    #[must_use]
1332    pub fn new(
1333        name: LocalTypeIdentifier,
1334        assigned_name: &str,
1335        module_path: Vec<String>,
1336        number: TypeNumber,
1337    ) -> Self {
1338        Self {
1339            name,
1340            assigned_name: assigned_name.to_string(),
1341            module_path,
1342            type_id: number,
1343            variants: SeqMap::new(),
1344        }
1345    }
1346
1347    #[must_use]
1348    pub const fn name(&self) -> &LocalTypeIdentifier {
1349        &self.name
1350    }
1351
1352    pub fn get_variant(&self, name: &str) -> Option<&EnumVariantTypeRef> {
1353        self.variants.get(&name.to_string())
1354    }
1355
1356    pub fn get_variant_from_index(&self, index: usize) -> Option<&EnumVariantTypeRef> {
1357        Some(self.variants.values().collect::<Vec<_>>()[index])
1358    }
1359}
1360
1361pub type EnumVariantTypeRef = Rc<EnumVariantType>;
1362
1363#[derive(Eq, PartialEq, Clone)]
1364pub struct EnumVariantCommon {
1365    pub name: LocalTypeIdentifier,
1366    pub assigned_name: String,
1367    pub number: TypeNumber,
1368    pub container_index: u8,
1369    pub owner: EnumTypeRef,
1370}
1371
1372impl Debug for EnumVariantCommon {
1373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
1374        write!(
1375            f,
1376            "<{}>{}::{}",
1377            self.number,
1378            self.owner.borrow().assigned_name,
1379            self.assigned_name
1380        )
1381    }
1382}
1383
1384pub type EnumVariantStructFieldTypeRef = Rc<EnumVariantStructFieldType>;
1385
1386#[derive(Debug)]
1387pub struct EnumVariantStructFieldType {
1388    pub name: LocalIdentifier,
1389    pub enum_variant: EnumVariantTypeRef,
1390    pub resolved_type: Type,
1391
1392    pub field_index: usize,
1393}
1394
1395pub type EnumVariantTupleFieldTypeRef = Rc<EnumVariantTupleFieldType>;
1396
1397#[derive(Debug, Eq, PartialEq)]
1398pub struct EnumVariantTupleFieldType {
1399    pub name: LocalIdentifier,
1400    pub enum_variant: EnumVariantTypeRef,
1401    pub resolved_type: Type,
1402
1403    pub field_index: usize,
1404}
1405
1406#[derive(Debug, Clone, Eq, PartialEq)]
1407pub struct EnumVariantSimpleType {
1408    pub common: EnumVariantCommon,
1409}
1410
1411pub type EnumVariantSimpleTypeRef = Rc<EnumVariantSimpleType>;
1412
1413#[derive(Clone, Eq, PartialEq)]
1414pub enum EnumVariantType {
1415    Struct(EnumVariantStructTypeRef),
1416    Tuple(EnumVariantTupleTypeRef),
1417    Nothing(EnumVariantSimpleTypeRef),
1418}
1419impl EnumVariantType {
1420    pub fn common(&self) -> &EnumVariantCommon {
1421        match self {
1422            Self::Tuple(tuple) => &tuple.common,
1423            Self::Struct(c) => &c.common,
1424            Self::Nothing(c) => &c.common,
1425        }
1426    }
1427}
1428
1429impl Debug for EnumVariantType {
1430    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1431        match self {
1432            Self::Struct(x) => write!(f, "{{ {x:?} }}"),
1433            Self::Tuple(x) => write!(f, "({x:?})"),
1434            Self::Nothing(_x) => Ok(()),
1435        }
1436    }
1437}
1438
1439#[derive(Debug)]
1440pub struct ImplMember {}
1441
1442#[derive(Debug)]
1443pub enum UseItem {
1444    Identifier(Node),
1445    TypeIdentifier(Node),
1446}
1447
1448#[derive(Debug)]
1449pub struct Use {
1450    pub path: Vec<Node>,
1451    pub items: Vec<UseItem>,
1452}
1453
1454#[derive(Debug)]
1455pub struct ImplFunctions {
1456    pub functions: SeqMap<String, FunctionRef>,
1457}
1458
1459impl Default for ImplFunctions {
1460    fn default() -> Self {
1461        Self::new()
1462    }
1463}
1464
1465impl ImplFunctions {
1466    #[must_use]
1467    pub fn new() -> Self {
1468        Self {
1469            functions: SeqMap::default(),
1470        }
1471    }
1472}
1473
1474#[derive(Debug)]
1475pub struct AssociatedImpls {
1476    pub functions: SeqMap<TypeNumber, ImplFunctions>,
1477}
1478
1479impl Default for AssociatedImpls {
1480    fn default() -> Self {
1481        Self::new()
1482    }
1483}
1484
1485impl AssociatedImpls {
1486    #[must_use]
1487    pub fn new() -> Self {
1488        Self {
1489            functions: SeqMap::default(),
1490        }
1491    }
1492}
1493
1494impl AssociatedImpls {
1495    pub fn prepare(&mut self, ty: &Type) {
1496        let type_id = ty.id().expect("type can not be attached to");
1497        self.functions
1498            .insert(type_id, ImplFunctions::new())
1499            .expect("should work");
1500    }
1501    #[must_use]
1502    pub fn get_member_function(&self, ty: &Type, function_name: &str) -> Option<&FunctionRef> {
1503        let type_id = ty.id().expect("type can not be attached to");
1504        let maybe_found_impl = self.functions.get(&type_id);
1505        if let Some(found_impl) = maybe_found_impl {
1506            if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
1507                return Some(func);
1508            }
1509        }
1510        None
1511    }
1512
1513    pub fn get_internal_member_function(
1514        &self,
1515        ty: &Type,
1516        function_name: &str,
1517    ) -> Option<&InternalFunctionDefinitionRef> {
1518        if let Some(found) = self.get_member_function(ty, function_name) {
1519            if let Function::Internal(int_fn) = &**found {
1520                return Some(int_fn);
1521            }
1522        }
1523        None
1524    }
1525
1526    pub fn add_member_function(
1527        &mut self,
1528        ty: &Type,
1529        name: &str,
1530        func: FunctionRef,
1531    ) -> Result<(), SemanticError> {
1532        let type_id = ty.id().expect("type can not have associated functions");
1533        let maybe_found_impl = self.functions.get_mut(&type_id);
1534
1535        if let Some(found_impl) = maybe_found_impl {
1536            found_impl
1537                .functions
1538                .insert(name.to_string(), func)
1539                .expect("todo");
1540            Ok(())
1541        } else {
1542            error!(%ty, %type_id, ?name, "wasn't prepared");
1543            Err(SemanticError::UnknownImplOnType)
1544        }
1545    }
1546
1547    pub fn add_external_member_function(
1548        &mut self,
1549        ty: &Type,
1550        func: ExternalFunctionDefinition,
1551    ) -> Result<(), SemanticError> {
1552        self.add_member_function(
1553            ty,
1554            &func.assigned_name.clone(),
1555            Function::External(func.into()).into(),
1556        )
1557    }
1558
1559    pub fn add_external_struct_member_function(
1560        &mut self,
1561        named_struct_type: &StructTypeRef,
1562        func: Function,
1563    ) -> Result<(), SemanticError> {
1564        self.add_member_function(
1565            &Type::NamedStruct(named_struct_type.clone()),
1566            &func.name().clone(),
1567            func.into(),
1568        )
1569    }
1570
1571    pub fn add_external_struct_member_function_external(
1572        &mut self,
1573        named_struct_type: StructTypeRef,
1574        func: ExternalFunctionDefinition,
1575    ) -> Result<(), SemanticError> {
1576        self.add_member_function(
1577            &Type::NamedStruct(named_struct_type.clone()),
1578            &func.assigned_name.clone(),
1579            Function::External(func.into()).into(),
1580        )
1581    }
1582
1583    pub fn add_external_struct_member_function_external_ref(
1584        &mut self,
1585        named_struct_type: StructTypeRef,
1586        func: ExternalFunctionDefinitionRef,
1587    ) -> Result<(), SemanticError> {
1588        self.add_member_function(
1589            &Type::NamedStruct(named_struct_type.clone()),
1590            &func.assigned_name.clone(),
1591            Function::External(func.into()).into(),
1592        )
1593    }
1594}
1595
1596// Mutable part
1597#[derive(Debug)]
1598pub struct ProgramState {
1599    pub array_types: Vec<ArrayTypeRef>,
1600    pub number: TypeNumber,
1601    pub external_function_number: ExternalFunctionId,
1602    // It is just so we don't have to do another dependency check of the
1603    // modules, we know that these constants have been
1604    // evaluated in order already
1605    pub constants_in_dependency_order: Vec<ConstantRef>,
1606    pub associated_impls: AssociatedImpls,
1607}
1608
1609impl Default for ProgramState {
1610    fn default() -> Self {
1611        Self::new()
1612    }
1613}
1614
1615impl ProgramState {
1616    #[must_use]
1617    pub fn new() -> Self {
1618        Self {
1619            array_types: Vec::new(),
1620            number: 0,
1621            external_function_number: 0,
1622            constants_in_dependency_order: Vec::new(),
1623            associated_impls: AssociatedImpls::new(),
1624        }
1625    }
1626
1627    pub fn allocate_number(&mut self) -> TypeNumber {
1628        self.number += 1;
1629        self.number
1630    }
1631
1632    pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
1633        self.external_function_number += 1;
1634        self.external_function_number
1635    }
1636}
1637
1638#[derive()]
1639pub enum EnumLiteralData {
1640    Nothing,
1641    Tuple(Vec<Expression>),
1642    Struct(Vec<(usize, Expression)>),
1643}
1644
1645impl Debug for EnumLiteralData {
1646    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1647        match self {
1648            Self::Nothing => Ok(()),
1649            Self::Tuple(x) => write!(f, "{x:?}"),
1650            Self::Struct(s) => write!(f, "{s:?}"),
1651        }
1652    }
1653}