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    Rc::ptr_eq(a, b)
1126}
1127
1128pub type TypeNumber = u32;
1129
1130#[derive(Debug, Clone, Eq, PartialEq)]
1131pub struct LocalTypeIdentifier(pub Node);
1132
1133#[derive(Debug)]
1134pub struct Constant {
1135    pub name: Node,
1136    pub assigned_name: String,
1137    pub id: ConstantId,
1138    pub expr: Expression,
1139    pub resolved_type: Type,
1140}
1141pub type ConstantRef = Rc<Constant>;
1142
1143#[derive(Debug)]
1144pub struct AliasType {
1145    pub name: Node,
1146    pub assigned_name: String,
1147    pub referenced_type: Type,
1148}
1149pub type AliasTypeRef = Rc<AliasType>;
1150
1151#[derive(Eq, PartialEq)]
1152pub struct NamedStructType {
1153    pub name: Node,
1154    pub assigned_name: String,
1155    pub anon_struct_type: AnonymousStructType,
1156    pub type_id: TypeNumber,
1157}
1158
1159impl Debug for NamedStructType {
1160    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1161        write!(f, "struct {:?}", self.assigned_name)
1162    }
1163}
1164
1165impl NamedStructType {
1166    pub fn new(
1167        name: Node,
1168        assigned_name: &str,
1169        anon_struct_type: AnonymousStructType,
1170        type_id: TypeNumber,
1171    ) -> Self {
1172        Self {
1173            //defined_in_module,
1174            anon_struct_type,
1175            name,
1176            assigned_name: assigned_name.to_string(),
1177            type_id,
1178        }
1179    }
1180
1181    pub fn field_index(&self, field_name: &str) -> Option<usize> {
1182        self.anon_struct_type
1183            .field_name_sorted_fields
1184            .get_index(&field_name.to_string())
1185    }
1186
1187    pub fn name(&self) -> &Node {
1188        &self.name
1189    }
1190}
1191
1192pub type OptionTypeRef = Rc<crate::OptionType>;
1193
1194#[derive(Debug)]
1195pub struct OptionType {
1196    pub item_type: Type,
1197}
1198
1199pub type ArrayTypeRef = Rc<ArrayType>;
1200
1201pub fn same_array_ref(a: &ArrayTypeRef, b: &ArrayTypeRef) -> bool {
1202    Rc::ptr_eq(a, b)
1203}
1204
1205#[derive(Debug, Eq, PartialEq)]
1206pub struct ArrayType {
1207    pub item_type: Type,
1208}
1209
1210pub type MapTypeRef = Rc<MapType>;
1211
1212#[derive(Debug, Eq, PartialEq)]
1213pub struct MapType {
1214    pub key_type: Type,
1215    pub value_type: Type,
1216}
1217
1218pub type EnumVariantStructTypeRef = Rc<EnumVariantStructType>;
1219
1220/*
1221pub fn sort_struct_fields(
1222    unordered_seq_map: &SeqMap<String, StructTypeField>,
1223) -> SeqMap<String, StructTypeField> {
1224    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
1225    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
1226    let mut ordered_seq_map = SeqMap::new();
1227
1228    for (name, field) in sorted_pairs {
1229        ordered_seq_map.insert(name, field).unwrap() // We know already that the key fields are unique
1230    }
1231
1232    ordered_seq_map
1233}
1234
1235 */
1236
1237pub fn sort_struct_fields2(
1238    unordered_seq_map: &SeqMap<String, StructTypeField>,
1239) -> SeqMap<String, StructTypeField> {
1240    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
1241    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
1242
1243    sorted_pairs
1244        .into_iter()
1245        .map(|(name, field)| (name.clone(), field.clone()))
1246        .collect()
1247}
1248
1249#[derive(Clone, Eq, PartialEq)]
1250pub struct AnonymousStructType {
1251    //pub source_ordered_fields: SeqMap<String, StructTypeField>,
1252    pub field_name_sorted_fields: SeqMap<String, StructTypeField>,
1253}
1254
1255impl Debug for AnonymousStructType {
1256    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1257        write!(f, "{}", comma_seq(&self.field_name_sorted_fields))
1258    }
1259}
1260
1261impl AnonymousStructType {
1262    pub fn new_and_sort_fields(source_ordered_fields: SeqMap<String, StructTypeField>) -> Self {
1263        Self {
1264            field_name_sorted_fields: sort_struct_fields2(&source_ordered_fields),
1265        }
1266    }
1267
1268    pub fn new(defined_order: SeqMap<String, StructTypeField>) -> Self {
1269        Self {
1270            field_name_sorted_fields: defined_order,
1271        }
1272    }
1273}
1274
1275#[derive(Debug, Eq, PartialEq)]
1276pub struct EnumVariantStructType {
1277    pub common: EnumVariantCommon,
1278    pub anon_struct: AnonymousStructType,
1279}
1280
1281pub type EnumVariantTupleTypeRef = Rc<EnumVariantTupleType>;
1282
1283#[derive(Debug, Eq, PartialEq)]
1284pub struct EnumVariantTupleType {
1285    pub common: EnumVariantCommon,
1286    pub fields_in_order: Vec<Type>,
1287}
1288
1289pub type TupleTypeRef = Rc<TupleType>;
1290
1291#[derive(Debug, Eq, PartialEq)]
1292pub struct TupleType(pub Vec<Type>);
1293
1294impl TupleType {
1295    pub fn new(types: Vec<Type>) -> Self {
1296        Self(types)
1297    }
1298}
1299
1300pub type EnumTypeRef = Rc<RefCell<EnumType>>;
1301
1302#[derive(Eq, PartialEq)]
1303pub struct EnumType {
1304    pub name: LocalTypeIdentifier,
1305    pub assigned_name: String,
1306    pub module_path: Vec<String>,
1307    pub type_id: TypeNumber,
1308
1309    pub variants: SeqMap<String, EnumVariantTypeRef>,
1310}
1311
1312impl Debug for EnumType {
1313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1314        write!(f, "{}", self.assigned_name)?;
1315        let s = comma(
1316            &self
1317                .variants
1318                .iter()
1319                .map(|(name, _variant)| name)
1320                .collect::<Vec<&String>>(),
1321        );
1322        write!(f, "{{ {s} }}")
1323    }
1324}
1325
1326impl EnumType {
1327    #[must_use]
1328    pub fn new(
1329        name: LocalTypeIdentifier,
1330        assigned_name: &str,
1331        module_path: Vec<String>,
1332        number: TypeNumber,
1333    ) -> Self {
1334        Self {
1335            name,
1336            assigned_name: assigned_name.to_string(),
1337            module_path,
1338            type_id: number,
1339            variants: SeqMap::new(),
1340        }
1341    }
1342
1343    #[must_use]
1344    pub const fn name(&self) -> &LocalTypeIdentifier {
1345        &self.name
1346    }
1347
1348    pub fn get_variant(&self, name: &str) -> Option<&EnumVariantTypeRef> {
1349        self.variants.get(&name.to_string())
1350    }
1351
1352    pub fn get_variant_from_index(&self, index: usize) -> Option<&EnumVariantTypeRef> {
1353        Some(self.variants.values().collect::<Vec<_>>()[index])
1354    }
1355}
1356
1357pub type EnumVariantTypeRef = Rc<EnumVariantType>;
1358
1359#[derive(Eq, PartialEq, Clone)]
1360pub struct EnumVariantCommon {
1361    pub name: LocalTypeIdentifier,
1362    pub assigned_name: String,
1363    pub number: TypeNumber,
1364    pub container_index: u8,
1365    pub owner: EnumTypeRef,
1366}
1367
1368impl Debug for EnumVariantCommon {
1369    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
1370        write!(
1371            f,
1372            "<{}>{}::{}",
1373            self.number,
1374            self.owner.borrow().assigned_name,
1375            self.assigned_name
1376        )
1377    }
1378}
1379
1380pub type EnumVariantStructFieldTypeRef = Rc<EnumVariantStructFieldType>;
1381
1382#[derive(Debug)]
1383pub struct EnumVariantStructFieldType {
1384    pub name: LocalIdentifier,
1385    pub enum_variant: EnumVariantTypeRef,
1386    pub resolved_type: Type,
1387
1388    pub field_index: usize,
1389}
1390
1391pub type EnumVariantTupleFieldTypeRef = Rc<EnumVariantTupleFieldType>;
1392
1393#[derive(Debug, Eq, PartialEq)]
1394pub struct EnumVariantTupleFieldType {
1395    pub name: LocalIdentifier,
1396    pub enum_variant: EnumVariantTypeRef,
1397    pub resolved_type: Type,
1398
1399    pub field_index: usize,
1400}
1401
1402#[derive(Debug, Clone, Eq, PartialEq)]
1403pub struct EnumVariantSimpleType {
1404    pub common: EnumVariantCommon,
1405}
1406
1407pub type EnumVariantSimpleTypeRef = Rc<EnumVariantSimpleType>;
1408
1409#[derive(Clone, Eq, PartialEq)]
1410pub enum EnumVariantType {
1411    Struct(EnumVariantStructTypeRef),
1412    Tuple(EnumVariantTupleTypeRef),
1413    Nothing(EnumVariantSimpleTypeRef),
1414}
1415impl EnumVariantType {
1416    pub fn common(&self) -> &EnumVariantCommon {
1417        match self {
1418            Self::Tuple(tuple) => &tuple.common,
1419            Self::Struct(c) => &c.common,
1420            Self::Nothing(c) => &c.common,
1421        }
1422    }
1423}
1424
1425impl Debug for EnumVariantType {
1426    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1427        match self {
1428            Self::Struct(x) => write!(f, "{{ {x:?} }}"),
1429            Self::Tuple(x) => write!(f, "({x:?})"),
1430            Self::Nothing(_x) => Ok(()),
1431        }
1432    }
1433}
1434
1435#[derive(Debug)]
1436pub struct ImplMember {}
1437
1438#[derive(Debug)]
1439pub enum UseItem {
1440    Identifier(Node),
1441    TypeIdentifier(Node),
1442}
1443
1444#[derive(Debug)]
1445pub struct Use {
1446    pub path: Vec<Node>,
1447    pub items: Vec<UseItem>,
1448}
1449
1450#[derive(Debug)]
1451pub struct ImplFunctions {
1452    pub functions: SeqMap<String, FunctionRef>,
1453}
1454
1455impl Default for ImplFunctions {
1456    fn default() -> Self {
1457        Self::new()
1458    }
1459}
1460
1461impl ImplFunctions {
1462    #[must_use]
1463    pub fn new() -> Self {
1464        Self {
1465            functions: SeqMap::default(),
1466        }
1467    }
1468}
1469
1470#[derive(Debug)]
1471pub struct AssociatedImpls {
1472    pub functions: SeqMap<TypeNumber, ImplFunctions>,
1473}
1474
1475impl Default for AssociatedImpls {
1476    fn default() -> Self {
1477        Self::new()
1478    }
1479}
1480
1481impl AssociatedImpls {
1482    #[must_use]
1483    pub fn new() -> Self {
1484        Self {
1485            functions: SeqMap::default(),
1486        }
1487    }
1488}
1489
1490impl AssociatedImpls {
1491    pub fn prepare(&mut self, ty: &Type) {
1492        let type_id = ty.id().expect("type can not be attached to");
1493        self.functions
1494            .insert(type_id, ImplFunctions::new())
1495            .expect("should work");
1496    }
1497    #[must_use]
1498    pub fn get_member_function(&self, ty: &Type, function_name: &str) -> Option<&FunctionRef> {
1499        let type_id = ty.id().expect("type can not be attached to");
1500        let maybe_found_impl = self.functions.get(&type_id);
1501        if let Some(found_impl) = maybe_found_impl {
1502            if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
1503                return Some(func);
1504            }
1505        }
1506        None
1507    }
1508
1509    pub fn get_internal_member_function(
1510        &self,
1511        ty: &Type,
1512        function_name: &str,
1513    ) -> Option<&InternalFunctionDefinitionRef> {
1514        if let Some(found) = self.get_member_function(ty, function_name) {
1515            if let Function::Internal(int_fn) = &**found {
1516                return Some(int_fn);
1517            }
1518        }
1519        None
1520    }
1521
1522    pub fn add_member_function(
1523        &mut self,
1524        ty: &Type,
1525        name: &str,
1526        func: FunctionRef,
1527    ) -> Result<(), SemanticError> {
1528        let type_id = ty.id().expect("type can not have associated functions");
1529        let maybe_found_impl = self.functions.get_mut(&type_id);
1530
1531        if let Some(found_impl) = maybe_found_impl {
1532            found_impl
1533                .functions
1534                .insert(name.to_string(), func)
1535                .expect("todo");
1536            Ok(())
1537        } else {
1538            error!(%ty, %type_id, ?name, "wasn't prepared");
1539            Err(SemanticError::UnknownImplOnType)
1540        }
1541    }
1542
1543    pub fn add_external_member_function(
1544        &mut self,
1545        ty: &Type,
1546        func: ExternalFunctionDefinition,
1547    ) -> Result<(), SemanticError> {
1548        self.add_member_function(
1549            ty,
1550            &func.assigned_name.clone(),
1551            Function::External(func.into()).into(),
1552        )
1553    }
1554
1555    pub fn add_external_struct_member_function(
1556        &mut self,
1557        named_struct_type: &StructTypeRef,
1558        func: Function,
1559    ) -> Result<(), SemanticError> {
1560        self.add_member_function(
1561            &Type::NamedStruct(named_struct_type.clone()),
1562            &func.name().clone(),
1563            func.into(),
1564        )
1565    }
1566
1567    pub fn add_external_struct_member_function_external(
1568        &mut self,
1569        named_struct_type: StructTypeRef,
1570        func: ExternalFunctionDefinition,
1571    ) -> Result<(), SemanticError> {
1572        self.add_member_function(
1573            &Type::NamedStruct(named_struct_type.clone()),
1574            &func.assigned_name.clone(),
1575            Function::External(func.into()).into(),
1576        )
1577    }
1578
1579    pub fn add_external_struct_member_function_external_ref(
1580        &mut self,
1581        named_struct_type: StructTypeRef,
1582        func: ExternalFunctionDefinitionRef,
1583    ) -> Result<(), SemanticError> {
1584        self.add_member_function(
1585            &Type::NamedStruct(named_struct_type.clone()),
1586            &func.assigned_name.clone(),
1587            Function::External(func.into()).into(),
1588        )
1589    }
1590}
1591
1592// Mutable part
1593#[derive(Debug)]
1594pub struct ProgramState {
1595    pub array_types: Vec<ArrayTypeRef>,
1596    pub number: TypeNumber,
1597    pub external_function_number: ExternalFunctionId,
1598    // It is just so we don't have to do another dependency check of the
1599    // modules, we know that these constants have been
1600    // evaluated in order already
1601    pub constants_in_dependency_order: Vec<ConstantRef>,
1602    pub associated_impls: AssociatedImpls,
1603}
1604
1605impl Default for ProgramState {
1606    fn default() -> Self {
1607        Self::new()
1608    }
1609}
1610
1611impl ProgramState {
1612    #[must_use]
1613    pub fn new() -> Self {
1614        Self {
1615            array_types: Vec::new(),
1616            number: 0,
1617            external_function_number: 0,
1618            constants_in_dependency_order: Vec::new(),
1619            associated_impls: AssociatedImpls::new(),
1620        }
1621    }
1622
1623    pub fn allocate_number(&mut self) -> TypeNumber {
1624        self.number += 1;
1625        self.number
1626    }
1627
1628    pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
1629        self.external_function_number += 1;
1630        self.external_function_number
1631    }
1632}
1633
1634#[derive()]
1635pub enum EnumLiteralData {
1636    Nothing,
1637    Tuple(Vec<Expression>),
1638    Struct(Vec<(usize, Expression)>),
1639}
1640
1641impl Debug for EnumLiteralData {
1642    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
1643        match self {
1644            Self::Nothing => Ok(()),
1645            Self::Tuple(x) => write!(f, "{x:?}"),
1646            Self::Struct(s) => write!(f, "{s:?}"),
1647        }
1648    }
1649}