swamp_semantic/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/swamp
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5pub mod err;
6pub mod intr;
7pub mod prelude;
8use crate::err::{Error, ErrorKind};
9use crate::intr::IntrinsicFunction;
10use crate::prelude::IntrinsicFunctionDefinitionRef;
11pub use fixed32::Fp;
12use seq_map::SeqMap;
13use source_map_node::Node;
14use std::cmp::PartialEq;
15use std::fmt;
16use std::fmt::{Debug, Display, Formatter};
17use std::rc::Rc;
18use swamp_attributes::Attributes;
19use swamp_types::prelude::*;
20use swamp_types::{Type, TypeRef};
21use tracing::error;
22
23#[derive(Debug, Clone)]
24pub struct TypeWithMut {
25    pub resolved_type: TypeRef,
26    pub is_mutable: bool,
27}
28
29#[derive(Debug, Clone)]
30pub enum SemanticError {
31    CouldNotInsertStruct,
32    DuplicateTypeAlias(String),
33    CanOnlyUseStructForMemberFunctions,
34    ResolveNotStruct,
35    DuplicateStructName(String),
36    DuplicateEnumType(String),
37    DuplicateEnumVariantType(String, String),
38    DuplicateFieldName(String),
39    DuplicateExternalFunction(String),
40    DuplicateRustType(String),
41    DuplicateConstName(String),
42    CircularConstantDependency(Vec<ConstantId>),
43    DuplicateConstantId(ConstantId),
44    IncompatibleTypes,
45    WasNotImmutable,
46    WasNotMutable,
47    DuplicateSymbolName(String),
48    DuplicateNamespaceLink(String),
49    MismatchedTypes {
50        expected: TypeRef,
51        found: Vec<TypeRef>,
52    },
53    UnknownImplOnType,
54    UnknownTypeVariable,
55    DuplicateDefinition(String),
56}
57
58#[derive(Debug, Eq, PartialEq)]
59pub struct LocalIdentifier(pub Node);
60
61#[derive(Debug)]
62pub struct InternalMainExpression {
63    pub expression: Expression,
64    pub scopes: VariableScopes,
65    pub program_unique_id: InternalFunctionId,
66}
67
68pub fn formal_function_name(internal_fn_def: &InternalFunctionDefinition) -> String {
69    let prefix = internal_fn_def
70        .associated_with_type
71        .as_ref()
72        .map_or_else(String::new, |associated_with_type| {
73            format!("{associated_with_type}::")
74        });
75    format!(
76        "{}::{}{}",
77        formal_module_name(&internal_fn_def.defined_in_module_path),
78        prefix,
79        internal_fn_def.assigned_name
80    )
81}
82
83//#[derive(Debug,Clone)]
84pub struct InternalFunctionDefinition {
85    pub body: Expression,
86    pub name: LocalIdentifier,
87    pub assigned_name: String,
88    pub associated_with_type: Option<TypeRef>,
89    pub defined_in_module_path: Vec<String>,
90    pub signature: Signature,
91    pub function_variables: VariableScopes,
92    pub program_unique_id: InternalFunctionId,
93    pub attributes: Attributes,
94}
95
96impl Default for InternalFunctionDefinition {
97    fn default() -> Self {
98        Self {
99            body: Expression {
100                ty: Rc::new(Type {
101                    id: TypeId::new(0),
102                    flags: TypeFlags::default(),
103                    kind: Rc::new(TypeKind::Byte),
104                }),
105                node: Node::default(),
106                kind: ExpressionKind::NoneLiteral,
107            },
108            name: LocalIdentifier(Node::default()),
109            assigned_name: String::new(),
110            associated_with_type: None,
111            defined_in_module_path: vec![],
112            signature: Signature {
113                parameters: vec![],
114                return_type: Rc::new(Type {
115                    id: TypeId::new(0),
116                    flags: TypeFlags::default(),
117                    kind: Rc::new(TypeKind::Byte),
118                }),
119            },
120            function_variables: VariableScopes::default(),
121            program_unique_id: 0,
122            attributes: Attributes::default(),
123        }
124    }
125}
126
127impl InternalFunctionDefinition {}
128
129impl Debug for InternalFunctionDefinition {
130    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
131        write!(f, "{:?}\n{:?}", self.signature, self.body)
132    }
133}
134
135impl PartialEq<Self> for InternalFunctionDefinition {
136    fn eq(&self, other: &Self) -> bool {
137        self.name == other.name
138    }
139}
140
141impl Eq for InternalFunctionDefinition {}
142
143pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
144
145pub type ExternalFunctionId = u32;
146
147pub type InternalFunctionId = u16;
148
149pub type ConstantId = u32;
150
151#[must_use]
152pub fn pretty_module_name(parts: &[String]) -> String {
153    if parts[0] == "crate" {
154        parts[1..].join("::")
155    } else {
156        parts.join("::")
157    }
158}
159
160#[must_use]
161pub fn formal_module_name(parts: &[String]) -> String {
162    parts.join("::")
163}
164
165#[derive(Eq, PartialEq)]
166pub struct ExternalFunctionDefinition {
167    pub name: Option<Node>,
168    pub assigned_name: String,
169    pub signature: Signature,
170    pub id: ExternalFunctionId,
171}
172
173impl Debug for ExternalFunctionDefinition {
174    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
175        write!(f, "external fn")
176    }
177}
178
179pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
180
181#[derive(Debug, Eq, Clone, PartialEq)]
182pub enum BlockScopeMode {
183    Open,
184    Closed,
185    Lambda,
186}
187
188#[derive(Debug, Clone)]
189pub struct BlockScope {
190    pub mode: BlockScopeMode,
191    pub lookup: SeqMap<String, VariableRef>,
192    pub variables: SeqMap<usize, VariableRef>,
193    pub register_watermark: usize,
194}
195
196impl Display for BlockScope {
197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
198        writeln!(f, "-- scope {:?}", self.mode)?;
199
200        for (index, (name, var)) in self.variables.iter().enumerate() {
201            writeln!(f, "  var({index}): {name}:{var:?}")?;
202        }
203        Ok(())
204    }
205}
206
207impl Default for BlockScope {
208    fn default() -> Self {
209        Self::new()
210    }
211}
212
213impl BlockScope {
214    #[must_use]
215    pub fn new() -> Self {
216        Self {
217            mode: BlockScopeMode::Open,
218            variables: SeqMap::new(),
219            lookup: SeqMap::new(),
220            register_watermark: 0,
221        }
222    }
223}
224
225#[derive(Debug, Clone)]
226pub struct VariableScope {
227    pub mode: BlockScopeMode,
228    pub variables: SeqMap<usize, VariableRef>,
229}
230
231#[derive(Clone, Debug)]
232pub struct VariableScopes {
233    //pub block_scope_stack: Vec<VariableScope>,
234    pub current_register: usize,
235    pub highest_virtual_register: usize,
236    pub all_variables: Vec<VariableRef>,
237}
238
239impl VariableScopes {
240    #[must_use]
241    pub const fn new() -> Self {
242        Self {
243            //block_scope_stack: vec![],
244            current_register: 0,
245            all_variables: vec![],
246            highest_virtual_register: 0,
247        }
248    }
249
250    pub const fn finalize(&mut self) {
251        self.highest_virtual_register = self.current_register;
252    }
253}
254impl Default for VariableScopes {
255    fn default() -> Self {
256        Self::new()
257    }
258}
259
260#[derive(Clone, Debug)]
261pub struct FunctionScopeState {
262    pub block_scope_stack: Vec<BlockScope>,
263    pub variable_index: usize,
264}
265
266#[derive(Clone, Debug)]
267pub struct ScopeInfo {
268    pub active_scope: FunctionScopeState,
269    pub total_scopes: VariableScopes,
270}
271
272impl ScopeInfo {
273    #[must_use]
274    pub fn new() -> Self {
275        Self {
276            active_scope: FunctionScopeState::default(),
277            total_scopes: VariableScopes::default(),
278        }
279    }
280}
281
282impl Default for ScopeInfo {
283    fn default() -> Self {
284        Self::new()
285    }
286}
287
288impl Display for FunctionScopeState {
289    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
290        for (index, scope) in self.block_scope_stack.iter().enumerate() {
291            writeln!(f, "block({index}):\n{scope}")?;
292        }
293        Ok(())
294    }
295}
296
297impl FunctionScopeState {
298    pub const fn emit_variable_index(&mut self) -> usize {
299        self.variable_index += 1;
300
301        self.variable_index
302    }
303}
304
305impl Default for FunctionScopeState {
306    fn default() -> Self {
307        Self::new()
308    }
309}
310
311impl FunctionScopeState {
312    #[must_use]
313    pub fn new() -> Self {
314        Self {
315            block_scope_stack: vec![BlockScope::new()],
316            //return_type,
317            variable_index: 0,
318        }
319    }
320}
321
322#[derive(Debug, Clone)]
323pub enum VariableType {
324    Local,
325    Parameter,
326}
327
328#[derive(Debug, Clone)]
329pub struct Variable {
330    pub name: Node,
331    pub assigned_name: String,
332    pub resolved_type: TypeRef,
333    pub mutable_node: Option<Node>,
334    pub variable_type: VariableType,
335
336    pub scope_index: usize,
337    pub variable_index: usize,
338    pub unique_id_within_function: usize,
339    pub virtual_register: u8,
340
341    pub is_unused: bool,
342}
343
344impl Variable {
345    #[must_use]
346    pub fn create_err(unit_type: TypeRef) -> Self {
347        Self {
348            name: Node::default(),
349            assigned_name: "err".to_string(),
350            resolved_type: unit_type,
351            mutable_node: None,
352            variable_type: VariableType::Local,
353            scope_index: 0,
354            variable_index: 0,
355            virtual_register: 0,
356            unique_id_within_function: 0,
357            is_unused: false,
358        }
359    }
360}
361
362impl Variable {
363    #[must_use]
364    pub const fn is_mutable(&self) -> bool {
365        self.mutable_node.is_some()
366    }
367
368    #[must_use]
369    pub const fn is_immutable(&self) -> bool {
370        !self.is_mutable()
371    }
372}
373
374pub type VariableRef = Rc<Variable>;
375
376#[derive(Debug, Clone)]
377pub struct MutVariable {
378    pub variable_ref: VariableRef,
379}
380
381//type MutVariableRef = Rc<MutVariable>;
382
383#[derive(Debug, Clone)]
384pub enum BinaryOperatorKind {
385    Add,
386    Subtract,
387    Multiply,
388    Divide,
389    Modulo,
390    LogicalOr,
391    LogicalAnd,
392    Equal,
393    NotEqual,
394    LessThan,
395    LessEqual,
396    GreaterThan,
397    GreaterEqual,
398}
399
400#[derive(Debug, Clone)]
401pub struct BinaryOperator {
402    pub left: Box<Expression>,
403    pub right: Box<Expression>,
404    pub kind: BinaryOperatorKind,
405    pub node: Node,
406}
407
408#[derive(Debug, Clone)]
409pub enum UnaryOperatorKind {
410    Not,
411    Negate,
412}
413#[derive(Debug, Clone)]
414pub struct UnaryOperator {
415    pub left: Box<Expression>,
416    pub kind: UnaryOperatorKind,
417    pub node: Node,
418}
419
420#[derive()]
421pub struct InternalFunctionCall {
422    pub arguments: Vec<ArgumentExpression>,
423
424    pub function_definition: InternalFunctionDefinitionRef,
425    pub function_expression: Box<Expression>,
426}
427
428impl Debug for InternalFunctionCall {
429    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
430        write!(
431            f,
432            "InFuncCall({:?} {:?})",
433            self.function_expression, self.arguments
434        )
435    }
436}
437
438#[derive(Debug, Clone)]
439pub struct ExternalFunctionCall {
440    pub arguments: Vec<ArgumentExpression>,
441    pub function_definition: ExternalFunctionDefinitionRef,
442    pub function_expression: Box<Expression>,
443}
444
445pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
446    let mut result = String::new();
447    for (i, (key, value)) in values.iter().enumerate() {
448        if i > 0 {
449            result.push_str(", ");
450        }
451        result.push_str(format!("{key}: {value}").as_str());
452    }
453    result
454}
455
456#[derive(Debug, Clone)]
457pub struct MemberCall {
458    pub function: FunctionRef,
459    pub arguments: Vec<ArgumentExpression>,
460}
461
462#[derive(Debug, Clone)]
463pub struct ArrayItem {
464    pub item_type: Rc<TypeRef>,
465    pub int_expression: Expression,
466    pub array_expression: Expression,
467    pub array_type: Rc<TypeRef>,
468}
469
470pub type ArrayItemRef = Rc<ArrayItem>;
471
472#[derive(Debug, Clone)]
473pub enum PrecisionType {
474    Float,
475    String,
476}
477
478#[derive(Debug, Clone)]
479pub enum FormatSpecifierKind {
480    LowerHex,                            // :x
481    UpperHex,                            // :X
482    Binary,                              // :b
483    Float,                               // :f
484    Precision(u32, Node, PrecisionType), // :..2f or :..5s
485}
486
487#[derive(Debug, Clone)]
488pub struct FormatSpecifier {
489    pub node: Node,
490    pub kind: FormatSpecifierKind,
491}
492
493pub type FunctionRef = Rc<Function>;
494
495#[derive(Debug, Eq, Clone, PartialEq)]
496pub enum Function {
497    Internal(InternalFunctionDefinitionRef),
498    External(ExternalFunctionDefinitionRef),
499    Intrinsic(IntrinsicFunctionDefinitionRef),
500}
501
502impl Function {
503    #[must_use]
504    pub fn name(&self) -> String {
505        match self {
506            Self::Internal(x) => x.assigned_name.clone(),
507            Self::External(y) => y.assigned_name.clone(),
508            Self::Intrinsic(i) => i.name.clone(),
509        }
510    }
511
512    #[must_use]
513    pub fn maybe_node(&self) -> Option<&Node> {
514        match self {
515            Self::Internal(x) => Some(&x.name.0),
516            Self::External(y) => y.name.as_ref(),
517            Self::Intrinsic(_i) => None,
518        }
519    }
520
521    #[must_use]
522    pub fn node(&self) -> Node {
523        match self {
524            Self::Internal(x) => x.name.0.clone(),
525            Self::External(_y) => Node::new_unknown(),
526            Self::Intrinsic(_i) => Node::new_unknown(),
527        }
528    }
529
530    #[must_use]
531    pub fn signature(&self) -> &Signature {
532        match self {
533            Self::Internal(internal) => &internal.signature,
534            Self::External(external) => &external.signature,
535            Self::Intrinsic(i) => &i.signature,
536        }
537    }
538}
539
540#[derive(Debug, Clone)]
541pub struct BooleanExpression {
542    #[allow(unused)]
543    pub expression: Box<Expression>,
544}
545
546// TODO: Maybe have different Match types, one specific for enums and one for other values
547#[derive(Debug, Clone)]
548pub struct Match {
549    pub arms: Vec<MatchArm>,
550    pub expression: Box<Expression>,
551}
552
553impl Match {
554    #[must_use]
555    pub fn contains_wildcard(&self) -> bool {
556        for arm in &self.arms {
557            if let Pattern::Wildcard(_) = arm.pattern {
558                return true;
559            }
560        }
561        false
562    }
563}
564
565#[derive(Debug, Clone)]
566pub struct MatchArm {
567    #[allow(unused)]
568    pub pattern: Pattern,
569    pub expression: Box<Expression>,
570    pub expression_type: TypeRef,
571}
572
573#[derive(Debug, Clone)]
574pub enum Pattern {
575    Normal(NormalPattern, Option<BooleanExpression>),
576    Wildcard(Node),
577}
578
579#[derive(Debug, Clone)]
580pub enum NormalPattern {
581    PatternList(Vec<PatternElement>),
582    EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
583    Literal(Expression),
584}
585
586#[derive(Debug, Clone)]
587pub enum PatternElement {
588    Variable(VariableRef),
589    VariableWithFieldIndex(VariableRef, usize),
590    Wildcard(Node),
591}
592
593#[derive(Debug, Clone)]
594pub struct Iterable {
595    pub key_type: Option<TypeRef>, // It does not have to support a key type
596    pub value_type: TypeRef,
597
598    pub resolved_expression: Box<Expression>,
599}
600
601#[derive(Debug, Clone)]
602pub struct AnonymousStructLiteral {
603    pub source_order_expressions: Vec<(usize, Option<Node>, Expression)>,
604    pub struct_like_type: TypeRef,
605}
606
607#[derive(Debug, Clone, Eq, PartialEq)]
608pub enum CompoundOperatorKind {
609    Add,
610    Sub,
611    Mul,
612    Div,
613    Modulo,
614}
615
616#[derive(Debug, Clone)]
617pub struct CompoundOperator {
618    pub node: Node,
619    pub kind: CompoundOperatorKind,
620}
621
622#[derive(Debug, Clone)]
623pub struct VariableCompoundAssignment {
624    pub variable_ref: VariableRef, // compound only support single variable
625    pub expression: Box<Expression>,
626    pub compound_operator: CompoundOperator,
627}
628
629#[derive(Debug, Clone)]
630pub struct Guard {
631    pub condition: Option<BooleanExpression>,
632    pub result: Expression,
633}
634
635#[derive(Debug, Clone)]
636pub struct Postfix {
637    pub node: Node,
638    pub ty: TypeRef,
639    pub kind: PostfixKind,
640}
641
642#[derive(Debug, Clone)]
643pub struct SliceViewType {
644    pub element: TypeRef,
645}
646
647#[derive(Debug, Clone)]
648pub struct VecType {
649    pub element: TypeRef,
650}
651
652#[derive(Debug, Clone)]
653pub struct GridType {
654    pub element: TypeRef,
655}
656
657#[derive(Debug, Clone)]
658pub struct SparseType {
659    pub element: TypeRef,
660}
661
662#[derive(Debug, Clone)]
663pub struct MapType {
664    pub key: TypeRef,
665    pub value: TypeRef,
666}
667
668#[derive(Debug, Clone)]
669pub enum PostfixKind {
670    StructField(TypeRef, usize),
671    MemberCall(FunctionRef, Vec<ArgumentExpression>),
672    OptionalChainingOperator,           // ? operator
673    NoneCoalescingOperator(Expression), // ?? operator
674    SliceViewSubscript(SliceViewType, Expression),
675    VecSubscript(VecType, Expression),
676    SparseSubscript(SparseType, Expression),
677    MapSubscript(MapType, Expression),
678    GridSubscript(GridType, Expression, Expression),
679}
680
681#[derive(Debug, Clone)]
682pub enum LocationAccessKind {
683    FieldIndex(AnonymousStructType, usize),
684    IntrinsicSubscript(IntrinsicFunction, Vec<Expression>),
685    SliceViewSubscript(SliceViewType, Expression),
686    MapSubscriptCreateIfNeeded(MapType, Expression),
687    MapSubscriptMustExist(MapType, Expression),
688    SparseSubscript(SparseType, Expression),
689    GridSubscript(GridType, Expression, Expression),
690}
691
692#[derive(Debug, Clone)]
693pub struct LocationAccess {
694    pub node: Node,
695    pub ty: TypeRef,
696    pub kind: LocationAccessKind,
697}
698
699#[derive(Debug, Clone)]
700pub struct SingleLocationExpression {
701    pub kind: MutableReferenceKind,
702    pub node: Node,
703    pub ty: TypeRef,
704
705    pub starting_variable: VariableRef,
706    pub access_chain: Vec<LocationAccess>,
707}
708
709#[derive(Debug, Clone)]
710pub struct TargetAssignmentLocation(pub SingleLocationExpression);
711
712#[derive(Debug, Clone)]
713pub enum MutableReferenceKind {
714    MutVariableRef,
715    MutStructFieldRef(AnonymousStructType, usize),
716}
717
718#[derive(Debug, Clone)]
719pub enum ArgumentExpression {
720    Expression(Expression),
721    BorrowMutableReference(SingleLocationExpression),
722}
723
724impl ArgumentExpression {
725    #[must_use]
726    pub fn ty(&self) -> TypeRef {
727        match self {
728            Self::Expression(expr) => expr.ty.clone(),
729            Self::BorrowMutableReference(location) => location.ty.clone(),
730        }
731    }
732
733    pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
734        match self {
735            Self::Expression(expr) => Ok(expr),
736            Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
737        }
738    }
739
740    pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
741        match &self {
742            Self::Expression(expr) => Ok(expr),
743            Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
744        }
745    }
746
747    #[must_use]
748    pub const fn is_mutable_reference(&self) -> bool {
749        matches!(self, Self::BorrowMutableReference(_))
750    }
751
752    #[must_use]
753    pub const fn node(&self) -> &Node {
754        match &self {
755            Self::Expression(expr) => &expr.node,
756            Self::BorrowMutableReference(loc) => &loc.node,
757        }
758    }
759}
760
761#[derive(Clone)]
762pub struct Expression {
763    pub ty: TypeRef,
764    pub node: Node,
765    pub kind: ExpressionKind,
766}
767
768impl Expression {
769    #[must_use]
770    pub fn debug_last_expression(&self) -> &Self {
771        match &self.kind {
772            ExpressionKind::ConstantAccess(a) => a.expr.debug_last_expression(),
773            ExpressionKind::BinaryOp(binary) => binary.right.debug_last_expression(),
774            ExpressionKind::UnaryOp(a) => a.left.debug_last_expression(),
775            ExpressionKind::ForLoop(_, _, a) => a.debug_last_expression(),
776            ExpressionKind::WhileLoop(_, a) => a.debug_last_expression(),
777            ExpressionKind::Block(block) => block.last().unwrap_or(self),
778            ExpressionKind::Match(a) => a.arms.last().unwrap().expression.debug_last_expression(),
779            ExpressionKind::Guard(g) => g.last().unwrap().result.debug_last_expression(),
780            ExpressionKind::If(_, a, _) => a.debug_last_expression(),
781            ExpressionKind::When(_, b, _a) => b,
782            ExpressionKind::TupleDestructuring(_, _, x) => x,
783            ExpressionKind::Lambda(_, a) => a.debug_last_expression(),
784            _ => self,
785        }
786    }
787}
788
789impl Debug for Expression {
790    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
791        write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
792    }
793}
794
795#[derive(Debug, Clone)]
796pub struct WhenBinding {
797    pub variable: VariableRef,
798    pub expr: Expression,
799}
800
801impl WhenBinding {
802    #[must_use]
803    pub const fn has_expression(&self) -> bool {
804        !matches!(self.expr.kind, ExpressionKind::VariableAccess(_))
805    }
806}
807
808#[derive(Debug, Clone)]
809pub enum StartOfChainKind {
810    Expression(Box<Expression>),
811    Variable(VariableRef),
812}
813
814#[derive(Debug, Clone)]
815pub struct StartOfChain {
816    pub kind: StartOfChainKind,
817    pub node: Node,
818}
819
820impl StartOfChain {}
821
822impl StartOfChainKind {
823    #[must_use]
824    pub fn ty(&self) -> TypeRef {
825        match self {
826            Self::Expression(expr) => expr.ty.clone(),
827            Self::Variable(var) => var.resolved_type.clone(),
828        }
829    }
830
831    #[must_use]
832    pub fn is_mutable(&self) -> bool {
833        match self {
834            Self::Expression(_call) => {
835                // The language can never return something that is mutable
836                false
837            }
838            Self::Variable(var) => var.is_mutable(),
839        }
840    }
841}
842
843#[derive(Debug, Clone)]
844pub enum ExpressionKind {
845    // Access Lookup values
846    ConstantAccess(ConstantRef),
847    VariableAccess(VariableRef),
848
849    // ----
850
851    // Operators
852    BinaryOp(BinaryOperator),
853    UnaryOp(UnaryOperator),
854    PostfixChain(StartOfChain, Vec<Postfix>),
855
856    // Conversion
857    // the `?` operator. unwraps the value, unless it is none
858    CoerceOptionToBool(Box<Expression>),
859    CoerceIntToChar(Box<Expression>),
860
861    // Calls
862    IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
863    InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
864    HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
865
866    // Constructing
867    VariableDefinition(VariableRef, Box<Expression>), // First time assignment
868    VariableDefinitionLValue(VariableRef, SingleLocationExpression), // Bind variable to memory location
869    VariableReassignment(VariableRef, Box<Expression>),
870
871    Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
872    CompoundAssignment(
873        TargetAssignmentLocation,
874        CompoundOperatorKind,
875        Box<Expression>,
876    ),
877
878    AnonymousStructLiteral(AnonymousStructLiteral),
879
880    FloatLiteral(Fp),
881    NoneLiteral,
882    IntLiteral(i32),
883    StringLiteral(String),
884    BoolLiteral(bool),
885    EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), // TypeRef: EnumType
886    TupleLiteral(Vec<Expression>),
887
888    InitializerList(TypeRef, Vec<Expression>),
889    InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
890
891    Option(Option<Box<Expression>>), // Wrapping an expression in `Some()`
892
893    // Loops
894    ForLoop(ForPattern, Iterable, Box<Expression>),
895    WhileLoop(BooleanExpression, Box<Expression>),
896
897    Block(Vec<Expression>),
898
899    // Match and compare
900    Match(Match),
901    Guard(Vec<Guard>),
902    If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
903    When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
904
905    TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
906
907    Lambda(Vec<VariableRef>, Box<Expression>),
908    BorrowMutRef(Box<SingleLocationExpression>),
909    Error(ErrorKind),
910}
911
912#[derive(Debug, Clone)]
913pub struct StringConst(pub Node);
914
915#[derive(Debug, Clone)]
916pub struct ArrayInstantiation {
917    pub expressions: Vec<Expression>,
918    pub item_type: TypeRef,
919    pub array_type: TypeRef,
920    pub array_type_ref: TypeRef,
921}
922
923#[derive(Debug, Clone)]
924pub enum ForPattern {
925    Single(VariableRef),
926    Pair(VariableRef, VariableRef),
927}
928
929impl ForPattern {
930    #[must_use]
931    pub fn is_mutable(&self) -> bool {
932        match self {
933            Self::Single(variable) => variable.is_mutable(),
934            Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
935        }
936    }
937}
938
939impl Display for ForPattern {
940    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
941        write!(f, "resolved_for_pattern")
942    }
943}
944
945#[derive(Debug, Eq, PartialEq)]
946pub struct ModulePathItem(pub Node);
947
948#[derive(Debug, Clone, Eq, PartialEq)]
949pub struct LocalTypeIdentifier(pub Node);
950
951#[derive(Debug, Clone)]
952pub struct Constant {
953    pub name: Node,
954    pub assigned_name: String,
955    pub id: ConstantId,
956    pub expr: Expression,
957    pub resolved_type: TypeRef,
958    pub function_scope_state: VariableScopes,
959}
960pub type ConstantRef = Rc<Constant>;
961
962pub type OptionTypeRef = Rc<OptionType>;
963
964#[derive(Debug, Clone)]
965pub struct OptionType {
966    pub item_type: TypeRef,
967}
968
969/*
970pub fn sort_struct_fields(
971    unordered_seq_map: &SeqMap<String, StructTypeField>,
972) -> SeqMap<String, StructTypeField> {
973    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
974    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
975    let mut ordered_seq_map = SeqMap::new();
976
977    for (name, field) in sorted_pairs {
978        ordered_seq_map.insert(name, field).unwrap() // We know already that the key fields are unique
979    }
980
981    ordered_seq_map
982}
983*/
984
985#[derive(Debug, Clone)]
986pub struct ImplMember {}
987
988#[derive(Debug, Clone)]
989pub enum UseItem {
990    Identifier(Node),
991    TypeIdentifier(Node),
992}
993
994#[derive(Debug, Clone)]
995pub struct Use {
996    pub path: Vec<Node>,
997    pub items: Vec<UseItem>,
998}
999
1000#[derive(Debug, Clone)]
1001pub struct ImplFunctions {
1002    pub functions: SeqMap<String, FunctionRef>,
1003}
1004
1005impl Default for ImplFunctions {
1006    fn default() -> Self {
1007        Self::new()
1008    }
1009}
1010
1011impl ImplFunctions {
1012    #[must_use]
1013    pub fn new() -> Self {
1014        Self {
1015            functions: SeqMap::default(),
1016        }
1017    }
1018}
1019
1020#[derive(Debug, Clone)]
1021pub struct AssociatedImpls {
1022    pub functions: SeqMap<TypeRef, ImplFunctions>,
1023}
1024
1025impl AssociatedImpls {}
1026
1027impl AssociatedImpls {}
1028
1029impl AssociatedImpls {}
1030
1031impl Default for AssociatedImpls {
1032    fn default() -> Self {
1033        Self::new()
1034    }
1035}
1036
1037impl AssociatedImpls {
1038    #[must_use]
1039    pub fn new() -> Self {
1040        Self {
1041            functions: SeqMap::default(),
1042        }
1043    }
1044}
1045
1046impl AssociatedImpls {
1047    pub fn prepare(&mut self, ty: &TypeRef) {
1048        self.functions
1049            .insert(ty.clone(), ImplFunctions::new())
1050            .unwrap_or_else(|_| panic!("should work {ty:?}"));
1051    }
1052
1053    #[must_use]
1054    pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1055        self.functions.contains_key(ty)
1056    }
1057    #[must_use]
1058    pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1059        let maybe_found_impl = self.functions.get(ty);
1060        if let Some(found_impl) = maybe_found_impl {
1061            if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
1062                return Some(func);
1063            }
1064        }
1065        None
1066    }
1067
1068    fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1069        let maybe_found_impl = self.functions.get(ty);
1070        if let Some(found_impl) = maybe_found_impl {
1071            if let Some(_func) = found_impl.functions.get(&function_name.to_string()) {
1072                return true;
1073            }
1074        }
1075        false
1076    }
1077
1078    #[must_use]
1079    pub fn api_get_external_function(
1080        &self,
1081        ty: &TypeRef,
1082        function_name: &str,
1083    ) -> Option<&ExternalFunctionDefinitionRef> {
1084        if let Some(found) = self.get_member_function(ty, function_name) {
1085            if let Function::External(ext_fn) = &**found {
1086                return Some(ext_fn);
1087            }
1088        }
1089        None
1090    }
1091
1092    #[must_use]
1093    pub fn get_internal_member_function(
1094        &self,
1095        ty: &TypeRef,
1096        function_name: &str,
1097    ) -> Option<&InternalFunctionDefinitionRef> {
1098        if let Some(found) = self.get_member_function(ty, function_name) {
1099            if let Function::Internal(int_fn) = &**found {
1100                return Some(int_fn);
1101            }
1102        }
1103        None
1104    }
1105
1106    pub fn remove_internal_function_if_exists(
1107        &mut self,
1108        ty: &TypeRef,
1109        function_name: &str,
1110    ) -> bool {
1111        if self.has_internal_member_function(ty, function_name) {
1112            let functions = self.functions.get_mut(ty).unwrap();
1113
1114            functions.functions.remove(&function_name.to_string());
1115            true
1116        } else {
1117            false
1118        }
1119    }
1120
1121    pub fn add_member_function(
1122        &mut self,
1123        ty: &TypeRef,
1124        name: &str,
1125        func: FunctionRef,
1126    ) -> Result<(), SemanticError> {
1127        let maybe_found_impl = self.functions.get_mut(ty);
1128
1129        if let Some(found_impl) = maybe_found_impl {
1130            found_impl
1131                .functions
1132                .insert(name.to_string(), func)
1133                .expect("todo");
1134            Ok(())
1135        } else {
1136            error!(%ty, ?name, "wasn't prepared");
1137            Err(SemanticError::UnknownImplOnType)
1138        }
1139    }
1140
1141    pub fn add_internal_function(
1142        &mut self,
1143        ty: &TypeRef,
1144        func: InternalFunctionDefinition,
1145    ) -> Result<(), SemanticError> {
1146        //info!(name=?func.assigned_name, ?ty, "adding member function");
1147        self.add_member_function(
1148            ty,
1149            &func.assigned_name.clone(),
1150            Function::Internal(func.into()).into(),
1151        )
1152    }
1153
1154    pub fn add_external_member_function(
1155        &mut self,
1156        ty: &TypeRef,
1157        func: ExternalFunctionDefinition,
1158    ) -> Result<(), SemanticError> {
1159        self.add_member_function(
1160            ty,
1161            &func.assigned_name.clone(),
1162            Function::External(func.into()).into(),
1163        )
1164    }
1165
1166    pub fn add_external_struct_member_function(
1167        &mut self,
1168        named_struct_type: TypeRef,
1169        func: Function,
1170    ) -> Result<(), SemanticError> {
1171        self.add_member_function(&named_struct_type, &func.name(), func.into())
1172    }
1173
1174    pub fn add_external_struct_member_function_external(
1175        &mut self,
1176        named_struct_type: TypeRef,
1177        func: ExternalFunctionDefinition,
1178    ) -> Result<(), SemanticError> {
1179        self.add_member_function(
1180            &named_struct_type,
1181            &func.assigned_name.clone(),
1182            Function::External(func.into()).into(),
1183        )
1184    }
1185
1186    pub fn add_external_struct_member_function_external_ref(
1187        &mut self,
1188        named_struct_type: TypeRef,
1189        func: ExternalFunctionDefinitionRef,
1190    ) -> Result<(), SemanticError> {
1191        self.add_member_function(
1192            &named_struct_type,
1193            &func.assigned_name.clone(),
1194            Function::External(func).into(),
1195        )
1196    }
1197}
1198
1199// Mutable part
1200#[derive(Debug, Clone)]
1201pub struct ProgramState {
1202    pub internal_function_id_allocator: InternalFunctionIdAllocator,
1203    // It is just so we don't have to do another dependency check of the
1204    // modules, we know that these constants have been
1205    // evaluated in order already
1206    pub constants_in_dependency_order: Vec<ConstantRef>,
1207    pub associated_impls: AssociatedImpls,
1208    pub types: TypeCache,
1209    pub errors: Vec<Error>,
1210    pub hints: Vec<Error>,
1211    pub infos: Vec<Error>,
1212}
1213
1214impl ProgramState {
1215    #[must_use]
1216    pub const fn errors(&self) -> &Vec<Error> {
1217        &self.errors
1218    }
1219}
1220
1221impl Default for ProgramState {
1222    fn default() -> Self {
1223        Self::new()
1224    }
1225}
1226
1227#[derive(Debug, Clone)]
1228pub struct InternalFunctionIdAllocator {
1229    pub internal_function_number: InternalFunctionId,
1230}
1231
1232impl Default for InternalFunctionIdAllocator {
1233    fn default() -> Self {
1234        Self::new()
1235    }
1236}
1237
1238impl InternalFunctionIdAllocator {
1239    #[must_use]
1240    pub const fn new() -> Self {
1241        Self {
1242            internal_function_number: 0,
1243        }
1244    }
1245    pub const fn alloc(&mut self) -> InternalFunctionId {
1246        self.internal_function_number += 1;
1247        self.internal_function_number
1248    }
1249}
1250
1251impl ProgramState {
1252    #[must_use]
1253    pub fn new() -> Self {
1254        Self {
1255            internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1256            constants_in_dependency_order: Vec::new(),
1257            associated_impls: AssociatedImpls::new(),
1258            types: TypeCache::new(),
1259            errors: vec![],
1260            hints: vec![],
1261            infos: vec![],
1262        }
1263    }
1264    pub const fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1265        self.internal_function_id_allocator.alloc()
1266    }
1267}
1268
1269#[derive(Clone)]
1270pub enum EnumLiteralExpressions {
1271    Nothing,
1272    Tuple(Vec<Expression>),
1273    Struct(Vec<(usize, Option<Node>, Expression)>),
1274}
1275
1276impl Debug for EnumLiteralExpressions {
1277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1278        match self {
1279            Self::Nothing => Ok(()),
1280            Self::Tuple(x) => write!(f, "{x:?}"),
1281            Self::Struct(s) => write!(f, "{s:?}"),
1282        }
1283    }
1284}