1pub 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
83pub 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 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            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            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#[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,                            UpperHex,                            Binary,                              Float,                               Precision(u32, Node, PrecisionType), }
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#[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>, 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, 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,           NoneCoalescingOperator(Expression), 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                false
837            }
838            Self::Variable(var) => var.is_mutable(),
839        }
840    }
841}
842
843#[derive(Debug, Clone)]
844pub enum ExpressionKind {
845    ConstantAccess(ConstantRef),
847    VariableAccess(VariableRef),
848
849    BinaryOp(BinaryOperator),
853    UnaryOp(UnaryOperator),
854    PostfixChain(StartOfChain, Vec<Postfix>),
855
856    CoerceOptionToBool(Box<Expression>),
859
860    IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
862    InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
863    HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
864
865    VariableDefinition(VariableRef, Box<Expression>), VariableDefinitionLValue(VariableRef, SingleLocationExpression), VariableReassignment(VariableRef, Box<Expression>),
869
870    Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
871    CompoundAssignment(
872        TargetAssignmentLocation,
873        CompoundOperatorKind,
874        Box<Expression>,
875    ),
876
877    AnonymousStructLiteral(AnonymousStructLiteral),
878
879    FloatLiteral(Fp),
880    NoneLiteral,
881    IntLiteral(i32),
882    StringLiteral(String),
883    BoolLiteral(bool),
884    EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), TupleLiteral(Vec<Expression>),
886
887    InitializerList(TypeRef, Vec<Expression>),
888    InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
889
890    Option(Option<Box<Expression>>), ForLoop(ForPattern, Iterable, Box<Expression>),
894    WhileLoop(BooleanExpression, Box<Expression>),
895
896    Block(Vec<Expression>),
897
898    Match(Match),
900    Guard(Vec<Guard>),
901    If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
902    When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
903
904    TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
905
906    Lambda(Vec<VariableRef>, Box<Expression>),
907    BorrowMutRef(Box<SingleLocationExpression>),
908    Error(ErrorKind),
909}
910
911#[derive(Debug, Clone)]
912pub struct StringConst(pub Node);
913
914#[derive(Debug, Clone)]
915pub struct ArrayInstantiation {
916    pub expressions: Vec<Expression>,
917    pub item_type: TypeRef,
918    pub array_type: TypeRef,
919    pub array_type_ref: TypeRef,
920}
921
922#[derive(Debug, Clone)]
923pub enum ForPattern {
924    Single(VariableRef),
925    Pair(VariableRef, VariableRef),
926}
927
928impl ForPattern {
929    #[must_use]
930    pub fn is_mutable(&self) -> bool {
931        match self {
932            Self::Single(variable) => variable.is_mutable(),
933            Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
934        }
935    }
936}
937
938impl Display for ForPattern {
939    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
940        write!(f, "resolved_for_pattern")
941    }
942}
943
944#[derive(Debug, Eq, PartialEq)]
945pub struct ModulePathItem(pub Node);
946
947#[derive(Debug, Clone, Eq, PartialEq)]
948pub struct LocalTypeIdentifier(pub Node);
949
950#[derive(Debug, Clone)]
951pub struct Constant {
952    pub name: Node,
953    pub assigned_name: String,
954    pub id: ConstantId,
955    pub expr: Expression,
956    pub resolved_type: TypeRef,
957    pub function_scope_state: VariableScopes,
958}
959pub type ConstantRef = Rc<Constant>;
960
961pub type OptionTypeRef = Rc<OptionType>;
962
963#[derive(Debug, Clone)]
964pub struct OptionType {
965    pub item_type: TypeRef,
966}
967
968#[derive(Debug, Clone)]
985pub struct ImplMember {}
986
987#[derive(Debug, Clone)]
988pub enum UseItem {
989    Identifier(Node),
990    TypeIdentifier(Node),
991}
992
993#[derive(Debug, Clone)]
994pub struct Use {
995    pub path: Vec<Node>,
996    pub items: Vec<UseItem>,
997}
998
999#[derive(Debug, Clone)]
1000pub struct ImplFunctions {
1001    pub functions: SeqMap<String, FunctionRef>,
1002}
1003
1004impl Default for ImplFunctions {
1005    fn default() -> Self {
1006        Self::new()
1007    }
1008}
1009
1010impl ImplFunctions {
1011    #[must_use]
1012    pub fn new() -> Self {
1013        Self {
1014            functions: SeqMap::default(),
1015        }
1016    }
1017}
1018
1019#[derive(Debug, Clone)]
1020pub struct AssociatedImpls {
1021    pub functions: SeqMap<TypeRef, ImplFunctions>,
1022}
1023
1024impl AssociatedImpls {}
1025
1026impl AssociatedImpls {}
1027
1028impl AssociatedImpls {}
1029
1030impl Default for AssociatedImpls {
1031    fn default() -> Self {
1032        Self::new()
1033    }
1034}
1035
1036impl AssociatedImpls {
1037    #[must_use]
1038    pub fn new() -> Self {
1039        Self {
1040            functions: SeqMap::default(),
1041        }
1042    }
1043}
1044
1045impl AssociatedImpls {
1046    pub fn prepare(&mut self, ty: &TypeRef) {
1047        self.functions
1048            .insert(ty.clone(), ImplFunctions::new())
1049            .unwrap_or_else(|_| panic!("should work {ty:?}"));
1050    }
1051
1052    #[must_use]
1053    pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1054        self.functions.contains_key(ty)
1055    }
1056    #[must_use]
1057    pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1058        let maybe_found_impl = self.functions.get(ty);
1059        if let Some(found_impl) = maybe_found_impl {
1060            if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
1061                return Some(func);
1062            }
1063        }
1064        None
1065    }
1066
1067    fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1068        let maybe_found_impl = self.functions.get(ty);
1069        if let Some(found_impl) = maybe_found_impl {
1070            if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
1071                return true;
1072            }
1073        }
1074        false
1075    }
1076
1077    #[must_use]
1078    pub fn api_get_external_function(
1079        &self,
1080        ty: &TypeRef,
1081        function_name: &str,
1082    ) -> Option<&ExternalFunctionDefinitionRef> {
1083        if let Some(found) = self.get_member_function(ty, function_name) {
1084            if let Function::External(ext_fn) = &**found {
1085                return Some(ext_fn);
1086            }
1087        }
1088        None
1089    }
1090
1091    #[must_use]
1092    pub fn get_internal_member_function(
1093        &self,
1094        ty: &TypeRef,
1095        function_name: &str,
1096    ) -> Option<&InternalFunctionDefinitionRef> {
1097        if let Some(found) = self.get_member_function(ty, function_name) {
1098            if let Function::Internal(int_fn) = &**found {
1099                return Some(int_fn);
1100            }
1101        }
1102        None
1103    }
1104
1105    pub fn remove_internal_function_if_exists(
1106        &mut self,
1107        ty: &TypeRef,
1108        function_name: &str,
1109    ) -> bool {
1110        if self.has_internal_member_function(ty, function_name) {
1111            let functions = self.functions.get_mut(ty).unwrap();
1112
1113            functions.functions.remove(&function_name.to_string());
1114            true
1115        } else {
1116            false
1117        }
1118    }
1119
1120    pub fn add_member_function(
1121        &mut self,
1122        ty: &TypeRef,
1123        name: &str,
1124        func: FunctionRef,
1125    ) -> Result<(), SemanticError> {
1126        let maybe_found_impl = self.functions.get_mut(ty);
1127
1128        if let Some(found_impl) = maybe_found_impl {
1129            found_impl
1130                .functions
1131                .insert(name.to_string(), func)
1132                .expect("todo");
1133            Ok(())
1134        } else {
1135            error!(%ty, ?name, "wasn't prepared");
1136            Err(SemanticError::UnknownImplOnType)
1137        }
1138    }
1139
1140    pub fn add_internal_function(
1141        &mut self,
1142        ty: &TypeRef,
1143        func: InternalFunctionDefinition,
1144    ) -> Result<(), SemanticError> {
1145        self.add_member_function(
1147            ty,
1148            &func.assigned_name.clone(),
1149            Function::Internal(func.into()).into(),
1150        )
1151    }
1152
1153    pub fn add_external_member_function(
1154        &mut self,
1155        ty: &TypeRef,
1156        func: ExternalFunctionDefinition,
1157    ) -> Result<(), SemanticError> {
1158        self.add_member_function(
1159            ty,
1160            &func.assigned_name.clone(),
1161            Function::External(func.into()).into(),
1162        )
1163    }
1164
1165    pub fn add_external_struct_member_function(
1166        &mut self,
1167        named_struct_type: TypeRef,
1168        func: Function,
1169    ) -> Result<(), SemanticError> {
1170        self.add_member_function(&named_struct_type, &func.name(), func.into())
1171    }
1172
1173    pub fn add_external_struct_member_function_external(
1174        &mut self,
1175        named_struct_type: TypeRef,
1176        func: ExternalFunctionDefinition,
1177    ) -> Result<(), SemanticError> {
1178        self.add_member_function(
1179            &named_struct_type,
1180            &func.assigned_name.clone(),
1181            Function::External(func.into()).into(),
1182        )
1183    }
1184
1185    pub fn add_external_struct_member_function_external_ref(
1186        &mut self,
1187        named_struct_type: TypeRef,
1188        func: ExternalFunctionDefinitionRef,
1189    ) -> Result<(), SemanticError> {
1190        self.add_member_function(
1191            &named_struct_type,
1192            &func.assigned_name.clone(),
1193            Function::External(func).into(),
1194        )
1195    }
1196}
1197
1198#[derive(Debug, Clone)]
1200pub struct ProgramState {
1201    pub internal_function_id_allocator: InternalFunctionIdAllocator,
1202    pub constants_in_dependency_order: Vec<ConstantRef>,
1206    pub associated_impls: AssociatedImpls,
1207    pub types: TypeCache,
1208    pub errors: Vec<Error>,
1209}
1210
1211impl ProgramState {
1212    #[must_use]
1213    pub const fn errors(&self) -> &Vec<Error> {
1214        &self.errors
1215    }
1216}
1217
1218impl Default for ProgramState {
1219    fn default() -> Self {
1220        Self::new()
1221    }
1222}
1223
1224#[derive(Debug, Clone)]
1225pub struct InternalFunctionIdAllocator {
1226    pub internal_function_number: InternalFunctionId,
1227}
1228
1229impl Default for InternalFunctionIdAllocator {
1230    fn default() -> Self {
1231        Self::new()
1232    }
1233}
1234
1235impl InternalFunctionIdAllocator {
1236    #[must_use]
1237    pub const fn new() -> Self {
1238        Self {
1239            internal_function_number: 0,
1240        }
1241    }
1242    pub const fn alloc(&mut self) -> InternalFunctionId {
1243        self.internal_function_number += 1;
1244        self.internal_function_number
1245    }
1246}
1247
1248impl ProgramState {
1249    #[must_use]
1250    pub fn new() -> Self {
1251        Self {
1252            internal_function_id_allocator: InternalFunctionIdAllocator::new(),
1253            constants_in_dependency_order: Vec::new(),
1254            associated_impls: AssociatedImpls::new(),
1255            types: TypeCache::new(),
1256            errors: vec![],
1257        }
1258    }
1259    pub const fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
1260        self.internal_function_id_allocator.alloc()
1261    }
1262}
1263
1264#[derive(Clone)]
1265pub enum EnumLiteralExpressions {
1266    Nothing,
1267    Tuple(Vec<Expression>),
1268    Struct(Vec<(usize, Option<Node>, Expression)>),
1269}
1270
1271impl Debug for EnumLiteralExpressions {
1272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1273        match self {
1274            Self::Nothing => Ok(()),
1275            Self::Tuple(x) => write!(f, "{x:?}"),
1276            Self::Struct(s) => write!(f, "{s:?}"),
1277        }
1278    }
1279}