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