swamp_semantic/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/semantic
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::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_symbol::{ScopedSymbolId, TopLevelSymbolId};
20use swamp_types::prelude::*;
21pub use swamp_types::{Type, TypeRef};
22use tracing::error;
23
24#[derive(Debug, Clone)]
25pub struct TypeWithMut {
26    pub resolved_type: TypeRef,
27    pub is_mutable: bool,
28}
29
30#[derive(Debug, Clone)]
31pub enum SemanticError {
32    CouldNotInsertStruct,
33    DuplicateTypeAlias(String),
34    CanOnlyUseStructForMemberFunctions,
35    ResolveNotStruct,
36    DuplicateStructName(String),
37    DuplicateEnumType(String),
38    DuplicateEnumVariantType(String, String),
39    DuplicateFieldName(String),
40    DuplicateExternalFunction(String),
41    DuplicateRustType(String),
42    DuplicateConstName(String),
43    CircularConstantDependency(Vec<ConstantId>),
44    DuplicateConstantId(ConstantId),
45    IncompatibleTypes,
46    WasNotImmutable,
47    WasNotMutable,
48    DuplicateSymbolName(String),
49    DuplicateNamespaceLink(String),
50    MismatchedTypes {
51        expected: TypeRef,
52        found: Vec<TypeRef>,
53    },
54    UnknownImplOnType,
55    UnknownTypeVariable,
56    DuplicateDefinition(String),
57}
58
59#[derive(Debug, Eq, PartialEq)]
60pub struct LocalIdentifier(pub Node);
61
62#[derive(Debug)]
63pub struct InternalMainExpression {
64    pub expression: Expression,
65    pub scopes: VariableScopes,
66    pub program_unique_id: InternalFunctionId,
67}
68
69pub fn formal_function_name(internal_fn_def: &InternalFunctionDefinition) -> String {
70    let prefix = internal_fn_def
71        .associated_with_type
72        .as_ref()
73        .map_or_else(String::new, |associated_with_type| {
74            format!("{associated_with_type}::")
75        });
76    format!(
77        "{}::{}{}",
78        formal_module_name(&internal_fn_def.defined_in_module_path),
79        prefix,
80        internal_fn_def.assigned_name
81    )
82}
83
84//#[derive(Debug,Clone)]
85pub struct InternalFunctionDefinition {
86    pub symbol_id: TopLevelSymbolId,
87    pub body: Expression,
88    pub name: LocalIdentifier,
89    pub assigned_name: String,
90    pub associated_with_type: Option<TypeRef>,
91    pub defined_in_module_path: Vec<String>,
92    pub signature: Signature,
93    pub function_variables: VariableScopes,
94    pub program_unique_id: InternalFunctionId,
95    pub attributes: Attributes,
96}
97
98impl Default for InternalFunctionDefinition {
99    fn default() -> Self {
100        Self {
101            body: Expression {
102                ty: Rc::new(Type {
103                    id: TypeId::new(0),
104                    flags: TypeFlags::default(),
105                    kind: Rc::new(TypeKind::Byte),
106                }),
107                node: Node::default(),
108                kind: ExpressionKind::NoneLiteral,
109            },
110            name: LocalIdentifier(Node::default()),
111            assigned_name: String::new(),
112            associated_with_type: None,
113            defined_in_module_path: vec![],
114            signature: Signature {
115                parameters: vec![],
116                return_type: Rc::new(Type {
117                    id: TypeId::new(0),
118                    flags: TypeFlags::default(),
119                    kind: Rc::new(TypeKind::Byte),
120                }),
121            },
122            function_variables: VariableScopes::default(),
123            symbol_id: TopLevelSymbolId::new_illegal(),
124            program_unique_id: 0,
125            attributes: Attributes::default(),
126        }
127    }
128}
129
130impl InternalFunctionDefinition {}
131
132impl Debug for InternalFunctionDefinition {
133    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
134        write!(f, "{:?}\n{:?}", self.signature, self.body)
135    }
136}
137
138impl PartialEq<Self> for InternalFunctionDefinition {
139    fn eq(&self, other: &Self) -> bool {
140        self.name == other.name
141    }
142}
143
144impl Eq for InternalFunctionDefinition {}
145
146pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;
147
148pub type ExternalFunctionId = u32;
149
150pub type InternalFunctionId = u16;
151
152pub type ConstantId = u32;
153
154#[must_use]
155pub fn pretty_module_name(parts: &[String]) -> String {
156    if parts[0] == "crate" {
157        parts[1..].join("::")
158    } else {
159        parts.join("::")
160    }
161}
162
163#[must_use]
164pub fn formal_module_name(parts: &[String]) -> String {
165    parts.join("::")
166}
167
168#[derive(Eq, PartialEq)]
169pub struct ExternalFunctionDefinition {
170    pub name: Node,
171    pub assigned_name: String,
172    pub signature: Signature,
173    pub id: ExternalFunctionId,
174}
175
176impl Debug for ExternalFunctionDefinition {
177    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
178        write!(f, "external fn")
179    }
180}
181
182pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;
183
184#[derive(Debug, Eq, Clone, PartialEq)]
185pub enum BlockScopeMode {
186    Open,
187    Closed,
188    Lambda,
189}
190
191#[derive(Debug, Clone)]
192pub struct BlockScope {
193    pub mode: BlockScopeMode,
194    pub lookup: SeqMap<String, VariableRef>,
195    pub variables: SeqMap<usize, VariableRef>,
196    pub register_watermark: usize,
197}
198
199impl Display for BlockScope {
200    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
201        writeln!(f, "-- scope {:?}", self.mode)?;
202
203        for (index, (name, var)) in self.variables.iter().enumerate() {
204            writeln!(f, "  var({index}): {name}:{var:?}")?;
205        }
206        Ok(())
207    }
208}
209
210impl Default for BlockScope {
211    fn default() -> Self {
212        Self::new()
213    }
214}
215
216impl BlockScope {
217    #[must_use]
218    pub fn new() -> Self {
219        Self {
220            mode: BlockScopeMode::Open,
221            variables: SeqMap::new(),
222            lookup: SeqMap::new(),
223            register_watermark: 0,
224        }
225    }
226}
227
228#[derive(Debug, Clone)]
229pub struct VariableScope {
230    pub mode: BlockScopeMode,
231    pub variables: SeqMap<usize, VariableRef>,
232}
233
234#[derive(Clone, Debug)]
235pub struct VariableScopes {
236    //pub block_scope_stack: Vec<VariableScope>,
237    pub current_register: usize,
238    pub highest_virtual_register: usize,
239    pub all_variables: Vec<VariableRef>,
240}
241
242impl VariableScopes {
243    #[must_use]
244    pub const fn new() -> Self {
245        Self {
246            //block_scope_stack: vec![],
247            current_register: 0,
248            all_variables: vec![],
249            highest_virtual_register: 0,
250        }
251    }
252
253    pub const fn finalize(&mut self) {
254        self.highest_virtual_register = self.current_register;
255        //        info!(?self.highest_virtual_register, "finalize");
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    #[must_use]
529    pub fn maybe_node(&self) -> Option<&Node> {
530        match self {
531            Self::Internal(x) => Some(&x.name.0),
532            Self::External(y) => Some(&y.name),
533            Self::Intrinsic(_i) => None,
534        }
535    }
536
537    #[must_use]
538    pub fn node(&self) -> Node {
539        match self {
540            Self::Internal(x) => x.name.0.clone(),
541            Self::External(_y) => Node::new_unknown(),
542            Self::Intrinsic(_i) => Node::new_unknown(),
543        }
544    }
545
546    #[must_use]
547    pub fn signature(&self) -> &Signature {
548        match self {
549            Self::Internal(internal) => &internal.signature,
550            Self::External(external) => &external.signature,
551            Self::Intrinsic(i) => &i.signature,
552        }
553    }
554}
555
556#[derive(Debug, Clone)]
557pub struct BooleanExpression {
558    #[allow(unused)]
559    pub expression: Box<Expression>,
560}
561
562// TODO: Maybe have different Match types, one specific for enums and one for other values
563#[derive(Debug, Clone)]
564pub struct Match {
565    pub arms: Vec<MatchArm>,
566    pub expression: Box<Expression>,
567}
568
569impl Match {
570    #[must_use]
571    pub fn contains_wildcard(&self) -> bool {
572        for arm in &self.arms {
573            if let Pattern::Wildcard(_) = arm.pattern {
574                return true;
575            }
576        }
577        false
578    }
579}
580
581#[derive(Debug, Clone)]
582pub struct MatchArm {
583    #[allow(unused)]
584    pub pattern: Pattern,
585    pub expression: Box<Expression>,
586    pub expression_type: TypeRef,
587}
588
589#[derive(Debug, Clone)]
590pub enum Pattern {
591    Normal(NormalPattern, Option<BooleanExpression>),
592    Wildcard(Node),
593}
594
595#[derive(Debug, Clone)]
596pub enum NormalPattern {
597    PatternList(Vec<PatternElement>),
598    EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
599    Literal(Expression),
600}
601
602#[derive(Debug, Clone)]
603pub enum PatternElement {
604    Variable(VariableRef),
605    VariableWithFieldIndex(VariableRef, usize),
606    Wildcard(Node),
607}
608
609#[derive(Debug, Clone)]
610pub enum IterableKind {
611    IntRange { min: Box<Expression>, max: Box<Expression>, is_inclusive: bool },
612    VecOrArray {
613        array_expression: Box<Expression>,
614    },
615}
616
617#[derive(Debug, Clone)]
618pub struct Iterable {
619    pub key_type: Option<TypeRef>, // It does not have to support a key type
620    pub value_type: TypeRef,
621    pub kind: IterableKind,
622}
623
624#[derive(Debug, Clone)]
625pub struct AnonymousStructLiteral {
626    pub source_order_expressions: Vec<(usize, Option<Node>, Expression)>,
627    pub struct_like_type: TypeRef,
628}
629
630#[derive(Debug, Clone, Eq, PartialEq)]
631pub enum CompoundOperatorKind {
632    Add,
633    Sub,
634    Mul,
635    Div,
636    Modulo,
637}
638
639#[derive(Debug, Clone)]
640pub struct CompoundOperator {
641    pub node: Node,
642    pub kind: CompoundOperatorKind,
643}
644
645#[derive(Debug, Clone)]
646pub struct VariableCompoundAssignment {
647    pub variable_ref: VariableRef, // compound only support single variable
648    pub expression: Box<Expression>,
649    pub compound_operator: CompoundOperator,
650}
651
652#[derive(Debug, Clone)]
653pub struct Guard {
654    pub condition: Option<BooleanExpression>,
655    pub result: Expression,
656}
657
658#[derive(Debug, Clone)]
659pub struct Postfix {
660    pub node: Node,
661    pub ty: TypeRef,
662    pub kind: PostfixKind,
663}
664
665#[derive(Debug, Clone)]
666pub struct SliceViewType {
667    pub element: TypeRef,
668}
669
670#[derive(Debug, Clone)]
671pub struct VecType {
672    pub vec_type: TypeRef,
673    pub element: TypeRef,
674}
675
676#[derive(Debug, Clone)]
677pub struct GridType {
678    pub element: TypeRef,
679}
680
681#[derive(Debug, Clone)]
682pub struct SparseType {
683    pub element: TypeRef,
684}
685
686#[derive(Debug, Clone)]
687pub struct MapType {
688    pub key: TypeRef,
689    pub value: TypeRef,
690}
691
692#[derive(Debug, Clone)]
693pub enum PostfixKind {
694    StructField(TypeRef, usize),
695    MemberCall(FunctionRef, Vec<ArgumentExpression>),
696    OptionalChainingOperator, // ? operator
697    // Subscripts
698    VecSubscript(VecType, Expression),
699    VecSubscriptRange { vec: VecType, min: Expression, max: Expression, is_inclusive: bool },
700    SparseSubscript(SparseType, Expression),
701    MapSubscript(MapType, Expression),
702    GridSubscript(GridType, Expression, Expression),
703}
704
705#[derive(Debug, Clone)]
706pub enum LocationAccessKind {
707    FieldIndex(AnonymousStructType, usize),
708    SliceViewSubscript(SliceViewType, Expression),
709    MapSubscriptCreateIfNeeded(MapType, Expression),
710    MapSubscriptMustExist(MapType, Expression),
711    SparseSubscript(SparseType, Expression),
712    GridSubscript(GridType, Expression, Expression),
713}
714
715#[derive(Debug, Clone)]
716pub struct LocationAccess {
717    pub node: Node,
718    pub ty: TypeRef,
719    pub kind: LocationAccessKind,
720}
721
722#[derive(Debug, Clone)]
723pub struct SingleLocationExpression {
724    pub kind: MutableReferenceKind,
725    pub node: Node,
726    pub ty: TypeRef,
727
728    pub starting_variable: VariableRef,
729    pub access_chain: Vec<LocationAccess>,
730}
731
732#[derive(Debug, Clone)]
733pub struct TargetAssignmentLocation(pub SingleLocationExpression);
734
735#[derive(Debug, Clone)]
736pub enum MutableReferenceKind {
737    MutVariableRef,
738    MutStructFieldRef(AnonymousStructType, usize),
739}
740
741#[derive(Debug, Clone)]
742pub enum ArgumentExpression {
743    Expression(Expression),
744    MaterializedExpression(Expression),
745    BorrowMutableReference(SingleLocationExpression),
746}
747
748impl ArgumentExpression {
749    #[must_use]
750    pub fn ty(&self) -> TypeRef {
751        match self {
752            Self::Expression(expr) => expr.ty.clone(),
753            Self::MaterializedExpression(expr) => expr.ty.clone(),
754            Self::BorrowMutableReference(location) => location.ty.clone(),
755        }
756    }
757
758    pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
759        match self {
760            Self::Expression(expr) => Ok(expr),
761            Self::MaterializedExpression(expr) => Ok(expr),
762            Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
763        }
764    }
765
766    pub const fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
767        match &self {
768            Self::Expression(expr) => Ok(expr),
769            Self::MaterializedExpression(expr) => Ok(expr),
770            Self::BorrowMutableReference(_) => Err(SemanticError::WasNotImmutable),
771        }
772    }
773
774    #[must_use]
775    pub const fn is_mutable_reference(&self) -> bool {
776        matches!(self, Self::BorrowMutableReference(_))
777    }
778
779    #[must_use]
780    pub const fn node(&self) -> &Node {
781        match &self {
782            Self::Expression(expr) => &expr.node,
783            Self::MaterializedExpression(expr) => &expr.node,
784            Self::BorrowMutableReference(loc) => &loc.node,
785        }
786    }
787}
788
789#[derive(Clone)]
790pub struct Expression {
791    pub ty: TypeRef,
792    pub node: Node,
793    pub kind: ExpressionKind,
794}
795
796impl Expression {
797    #[must_use]
798    pub fn debug_last_expression(&self) -> &Self {
799        match &self.kind {
800            ExpressionKind::ConstantAccess(a) => a.expr.debug_last_expression(),
801            ExpressionKind::BinaryOp(binary) => binary.right.debug_last_expression(),
802            ExpressionKind::UnaryOp(a) => a.left.debug_last_expression(),
803            ExpressionKind::ForLoop(_, _, a) => a.debug_last_expression(),
804            ExpressionKind::WhileLoop(_, a) => a.debug_last_expression(),
805            ExpressionKind::Block(block) => block.last().unwrap_or(self),
806            ExpressionKind::Match(a) => a.arms.last().unwrap().expression.debug_last_expression(),
807            ExpressionKind::Guard(g) => g.last().unwrap().result.debug_last_expression(),
808            ExpressionKind::If(_, a, _) => a.debug_last_expression(),
809            ExpressionKind::When(_, b, _a) => b,
810            ExpressionKind::TupleDestructuring(_, _, x) => x,
811            ExpressionKind::Lambda(_, a) => a.debug_last_expression(),
812            _ => self,
813        }
814    }
815}
816
817impl Debug for Expression {
818    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
819        write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
820    }
821}
822
823#[derive(Debug, Clone)]
824pub struct WhenBinding {
825    pub variable: VariableRef,
826    pub expr: Expression,
827}
828
829impl WhenBinding {
830    #[must_use]
831    pub const fn has_expression(&self) -> bool {
832        !matches!(self.expr.kind, ExpressionKind::VariableAccess(_))
833    }
834}
835
836#[derive(Debug, Clone)]
837pub enum StartOfChainKind {
838    Expression(Box<Expression>),
839    Variable(VariableRef),
840}
841
842#[derive(Debug, Clone)]
843pub struct StartOfChain {
844    pub kind: StartOfChainKind,
845    pub node: Node,
846}
847
848impl StartOfChain {}
849
850impl StartOfChainKind {
851    #[must_use]
852    pub fn ty(&self) -> TypeRef {
853        match self {
854            Self::Expression(expr) => expr.ty.clone(),
855            Self::Variable(var) => var.resolved_type.clone(),
856        }
857    }
858
859    #[must_use]
860    pub fn is_mutable(&self) -> bool {
861        match self {
862            Self::Expression(_call) => {
863                // The language can never return something that is mutable
864                false
865            }
866            Self::Variable(var) => var.is_mutable(),
867        }
868    }
869}
870
871#[derive(Debug, Clone)]
872pub struct Block {
873    pub statements: Vec<Expression>,
874    pub tail: Box<Expression>,
875}
876
877#[derive(Debug, Clone)]
878pub enum ExpressionKind {
879    // Access Lookup values
880    ConstantAccess(ConstantRef),
881    VariableAccess(VariableRef),
882
883    // ----
884
885    // Operators
886    BinaryOp(BinaryOperator),
887    UnaryOp(UnaryOperator),
888    PostfixChain(StartOfChain, Vec<Postfix>),
889
890    // Coerce
891    // the `?` operator. unwraps the value, unless it is none
892    CoerceOptionToBool(Box<Expression>),
893    CoerceIntToChar(Box<Expression>),
894    CoerceIntToByte(Box<Expression>),
895    CoerceIntToShort(Box<Expression>),
896
897    CoerceIntToPointer(Box<Expression>),
898    CoerceToAny(Box<Expression>),
899
900    // Calls
901    IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
902    InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
903    HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
904
905    // Constructing
906    VariableDefinition(VariableRef, Box<Expression>), // First time assignment
907    VariableDefinitionLValue(VariableRef, SingleLocationExpression), // Bind variable to memory location
908    VariableReassignment(VariableRef, Box<Expression>),
909
910    Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
911    CompoundAssignment(
912        TargetAssignmentLocation,
913        CompoundOperatorKind,
914        Box<Expression>,
915    ),
916
917    AnonymousStructLiteral(AnonymousStructLiteral),
918    NamedStructLiteral(Box<Expression>),
919
920    FloatLiteral(Fp),
921    NoneLiteral,
922    IntLiteral(i32),
923    ByteLiteral(u8),
924    StringLiteral(String),
925    BoolLiteral(bool),
926    EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), // TypeRef: EnumType
927    TupleLiteral(Vec<Expression>),
928    Range { min: Box<Expression>, max: Box<Expression>, is_inclusive: bool },
929
930    InitializerList(TypeRef, Vec<Expression>),
931    InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
932
933    Option(Option<Box<Expression>>), // Wrapping an expression in `Some()`
934
935    // Loops
936    ForLoop(ForPattern, Iterable, Box<Expression>),
937    WhileLoop(BooleanExpression, Box<Expression>),
938
939    Block(Vec<Expression>),
940
941    // Match and compare
942    Match(Match),
943    Guard(Vec<Guard>),
944    If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
945    When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
946
947    TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
948
949    Lambda(Vec<VariableRef>, Box<Expression>),
950    BorrowMutRef(Box<SingleLocationExpression>),
951    Error(ErrorKind),
952}
953
954impl Display for ExpressionKind {
955    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
956        match self {
957            Self::ConstantAccess(_) => {
958                write!(f, "constant")
959            }
960            Self::VariableAccess(_) => {
961                write!(f, "varaccess")
962            }
963            Self::BinaryOp(_) => {
964                write!(f, "binaryop")
965            }
966            Self::UnaryOp(_) => {
967                write!(f, "unaryop")
968            }
969            Self::PostfixChain(_, _) => {
970                write!(f, "prefix")
971            }
972            Self::CoerceOptionToBool(_) => {
973                write!(f, "byte")
974            }
975            Self::CoerceIntToChar(_) => {
976                write!(f, "byte")
977            }
978            Self::CoerceIntToByte(_) => {
979                write!(f, "byte")
980            }
981            Self::CoerceIntToShort(_) => {
982                write!(f, "IntToShort")
983            }
984            Self::CoerceIntToPointer(pointer) => {
985                write!(f, "ptr<{pointer:?}>")
986            }
987            Self::CoerceToAny(_) => {
988                write!(f, "byte")
989            }
990            Self::IntrinsicCallEx(_, _) => {
991                write!(f, "byte")
992            }
993            Self::InternalCall(_, _) => {
994                write!(f, "byte")
995            }
996            Self::HostCall(_, _) => {
997                write!(f, "byte")
998            }
999            Self::VariableDefinition(a, b) => {
1000                write!(f, "vardef {a:?} {}", b.kind)
1001            }
1002            Self::VariableDefinitionLValue(a, _b) => {
1003                write!(f, "vardefl {a:?}")
1004            }
1005            Self::Range { .. } => write!(f, "range"),
1006            Self::VariableReassignment(_, _) => {
1007                write!(f, "var  reassignment")
1008            }
1009            Self::Assignment(_, _) => {
1010                write!(f, "byte")
1011            }
1012            Self::CompoundAssignment(_, _, _) => {
1013                write!(f, "byte")
1014            }
1015            Self::AnonymousStructLiteral(_) => {
1016                write!(f, "byte")
1017            }
1018            Self::NamedStructLiteral(_) => {
1019                write!(f, "byte")
1020            }
1021            Self::FloatLiteral(_) => {
1022                write!(f, "byte")
1023            }
1024            Self::NoneLiteral => {
1025                write!(f, "byte")
1026            }
1027            Self::IntLiteral(_) => {
1028                write!(f, "byte")
1029            }
1030            Self::ByteLiteral(_) => {
1031                write!(f, "byte")
1032            }
1033            Self::StringLiteral(_) => {
1034                write!(f, "byte")
1035            }
1036            Self::BoolLiteral(_) => {
1037                write!(f, "byte")
1038            }
1039            Self::EnumVariantLiteral(_, _) => {
1040                write!(f, "byte")
1041            }
1042            Self::TupleLiteral(_) => {
1043                write!(f, "byte")
1044            }
1045            Self::InitializerList(_, _) => {
1046                write!(f, "byte")
1047            }
1048            Self::InitializerPairList(_, _) => {
1049                write!(f, "byte")
1050            }
1051            Self::Option(_) => {
1052                write!(f, "byte")
1053            }
1054            Self::ForLoop(_, _, _) => {
1055                write!(f, "byte")
1056            }
1057            Self::WhileLoop(_, _) => {
1058                write!(f, "byte")
1059            }
1060            Self::Block(_) => {
1061                write!(f, "byte")
1062            }
1063            Self::Match(_) => {
1064                write!(f, "byte")
1065            }
1066            Self::Guard(_) => {
1067                write!(f, "byte")
1068            }
1069            Self::If(_, _, _) => {
1070                write!(f, "byte")
1071            }
1072            Self::When(_, _, _) => {
1073                write!(f, "byte")
1074            }
1075            Self::TupleDestructuring(_, _, _) => {
1076                write!(f, "byte")
1077            }
1078            Self::Lambda(_, _) => {
1079                write!(f, "byte")
1080            }
1081            Self::BorrowMutRef(_) => {
1082                write!(f, "byte")
1083            }
1084            Self::Error(_) => {
1085                write!(f, "byte")
1086            }
1087        }
1088    }
1089}
1090
1091#[derive(Debug, Clone)]
1092pub struct StringConst(pub Node);
1093
1094#[derive(Debug, Clone)]
1095pub struct ArrayInstantiation {
1096    pub expressions: Vec<Expression>,
1097    pub item_type: TypeRef,
1098    pub array_type: TypeRef,
1099    pub array_type_ref: TypeRef,
1100}
1101
1102#[derive(Debug, Clone)]
1103pub enum ForPattern {
1104    Single(VariableRef),
1105    Pair(VariableRef, VariableRef),
1106}
1107
1108impl ForPattern {
1109    #[must_use]
1110    pub fn is_mutable(&self) -> bool {
1111        match self {
1112            Self::Single(variable) => variable.is_mutable(),
1113            Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
1114        }
1115    }
1116}
1117
1118impl Display for ForPattern {
1119    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1120        write!(f, "resolved_for_pattern")
1121    }
1122}
1123
1124#[derive(Debug, Eq, PartialEq)]
1125pub struct ModulePathItem(pub Node);
1126
1127#[derive(Debug, Clone, Eq, PartialEq)]
1128pub struct LocalTypeIdentifier(pub Node);
1129
1130#[derive(Debug, Clone)]
1131pub struct Constant {
1132    pub symbol_id: TopLevelSymbolId,
1133    pub name: Node,
1134    pub assigned_name: String,
1135    pub id: ConstantId,
1136    pub expr: Expression,
1137    pub resolved_type: TypeRef,
1138    pub function_scope_state: VariableScopes,
1139}
1140pub type ConstantRef = Rc<Constant>;
1141
1142pub type OptionTypeRef = Rc<OptionType>;
1143
1144#[derive(Debug, Clone)]
1145pub struct OptionType {
1146    pub item_type: TypeRef,
1147}
1148
1149/*
1150pub fn sort_struct_fields(
1151    unordered_seq_map: &SeqMap<String, StructTypeField>,
1152) -> SeqMap<String, StructTypeField> {
1153    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
1154    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
1155    let mut ordered_seq_map = SeqMap::new();
1156
1157    for (name, field) in sorted_pairs {
1158        ordered_seq_map.insert(name, field).unwrap() // We know already that the key fields are unique
1159    }
1160
1161    ordered_seq_map
1162}
1163*/
1164
1165#[derive(Debug, Clone)]
1166pub struct ImplMember {}
1167
1168#[derive(Debug, Clone)]
1169pub enum UseItem {
1170    Identifier(Node),
1171    TypeIdentifier(Node),
1172}
1173
1174#[derive(Debug, Clone)]
1175pub struct Use {
1176    pub path: Vec<Node>,
1177    pub items: Vec<UseItem>,
1178}
1179
1180#[derive(Debug, Clone)]
1181pub struct ImplFunctions {
1182    pub functions: SeqMap<String, FunctionRef>,
1183}
1184
1185impl Default for ImplFunctions {
1186    fn default() -> Self {
1187        Self::new()
1188    }
1189}
1190
1191impl ImplFunctions {
1192    #[must_use]
1193    pub fn new() -> Self {
1194        Self {
1195            functions: SeqMap::default(),
1196        }
1197    }
1198}
1199
1200#[derive(Debug, Clone)]
1201pub struct AssociatedImpls {
1202    pub functions: SeqMap<TypeRef, ImplFunctions>,
1203}
1204
1205impl Default for AssociatedImpls {
1206    fn default() -> Self {
1207        Self::new()
1208    }
1209}
1210
1211impl AssociatedImpls {
1212    #[must_use]
1213    pub fn new() -> Self {
1214        Self {
1215            functions: SeqMap::default(),
1216        }
1217    }
1218}
1219
1220impl AssociatedImpls {
1221    pub fn prepare(&mut self, ty: &TypeRef) {
1222        self.functions
1223            .insert(ty.clone(), ImplFunctions::new())
1224            .unwrap_or_else(|_| panic!("should work {ty:?}"));
1225    }
1226
1227    #[must_use]
1228    pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1229        self.functions.contains_key(ty)
1230    }
1231    #[must_use]
1232    pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1233        let maybe_found_impl = self.functions.get(ty);
1234        if let Some(found_impl) = maybe_found_impl
1235            && let Some(func) = found_impl.functions.get(&function_name.to_string())
1236        {
1237            return Some(func);
1238        }
1239        None
1240    }
1241
1242    fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1243        let maybe_found_impl = self.functions.get(ty);
1244        if let Some(found_impl) = maybe_found_impl
1245            && let Some(_func) = found_impl.functions.get(&function_name.to_string())
1246        {
1247            return true;
1248        }
1249        false
1250    }
1251
1252    #[must_use]
1253    pub fn api_get_external_function(
1254        &self,
1255        ty: &TypeRef,
1256        function_name: &str,
1257    ) -> Option<&ExternalFunctionDefinitionRef> {
1258        if let Some(found) = self.get_member_function(ty, function_name)
1259            && let Function::External(ext_fn) = &**found
1260        {
1261            return Some(ext_fn);
1262        }
1263        None
1264    }
1265
1266    #[must_use]
1267    pub fn get_internal_member_function(
1268        &self,
1269        ty: &TypeRef,
1270        function_name: &str,
1271    ) -> Option<&InternalFunctionDefinitionRef> {
1272        if let Some(found) = self.get_member_function(ty, function_name)
1273            && let Function::Internal(int_fn) = &**found
1274        {
1275            return Some(int_fn);
1276        }
1277        None
1278    }
1279
1280    #[must_use]
1281    pub fn get_internal_member_function_from_id(
1282        &self,
1283        function_id: InternalFunctionId,
1284    ) -> Option<&InternalFunctionDefinitionRef> {
1285        for functions in self.functions.values() {
1286            for func in functions.functions.values() {
1287                if let Function::Internal(int_fn) = &**func
1288                    && int_fn.program_unique_id == function_id
1289                {
1290                    return Some(int_fn);
1291                }
1292            }
1293        }
1294        None
1295    }
1296
1297    pub fn remove_internal_function_if_exists(
1298        &mut self,
1299        ty: &TypeRef,
1300        function_name: &str,
1301    ) -> bool {
1302        if self.has_internal_member_function(ty, function_name) {
1303            let functions = self.functions.get_mut(ty).unwrap();
1304
1305            functions.functions.remove(&function_name.to_string());
1306            true
1307        } else {
1308            false
1309        }
1310    }
1311
1312    pub fn add_member_function(
1313        &mut self,
1314        ty: &TypeRef,
1315        name: &str,
1316        func: FunctionRef,
1317    ) -> Result<(), SemanticError> {
1318        let maybe_found_impl = self.functions.get_mut(ty);
1319
1320        if let Some(found_impl) = maybe_found_impl {
1321            found_impl
1322                .functions
1323                .insert(name.to_string(), func)
1324                .unwrap_or_else(|_| panic!("already had key {name}"));
1325            Ok(())
1326        } else {
1327            error!(%ty, ?name, "wasn't prepared");
1328            Err(SemanticError::UnknownImplOnType)
1329        }
1330    }
1331
1332    pub fn add_internal_function(
1333        &mut self,
1334        ty: &TypeRef,
1335        func: InternalFunctionDefinition,
1336    ) -> Result<(), SemanticError> {
1337        //info!(name=?func.assigned_name, ?ty, "adding member function");
1338        self.add_member_function(
1339            ty,
1340            &func.assigned_name.clone(),
1341            Function::Internal(func.into()).into(),
1342        )
1343    }
1344
1345    pub fn add_external_member_function(
1346        &mut self,
1347        ty: &TypeRef,
1348        func: ExternalFunctionDefinition,
1349    ) -> Result<(), SemanticError> {
1350        self.add_member_function(
1351            ty,
1352            &func.assigned_name.clone(),
1353            Function::External(func.into()).into(),
1354        )
1355    }
1356
1357    pub fn add_external_struct_member_function(
1358        &mut self,
1359        named_struct_type: TypeRef,
1360        func: Function,
1361    ) -> Result<(), SemanticError> {
1362        self.add_member_function(&named_struct_type, &func.name(), func.into())
1363    }
1364
1365    pub fn add_external_struct_member_function_external(
1366        &mut self,
1367        named_struct_type: TypeRef,
1368        func: ExternalFunctionDefinition,
1369    ) -> Result<(), SemanticError> {
1370        self.add_member_function(
1371            &named_struct_type,
1372            &func.assigned_name.clone(),
1373            Function::External(func.into()).into(),
1374        )
1375    }
1376
1377    pub fn add_external_struct_member_function_external_ref(
1378        &mut self,
1379        named_struct_type: TypeRef,
1380        func: ExternalFunctionDefinitionRef,
1381    ) -> Result<(), SemanticError> {
1382        self.add_member_function(
1383            &named_struct_type,
1384            &func.assigned_name.clone(),
1385            Function::External(func).into(),
1386        )
1387    }
1388}
1389
1390#[derive(Clone)]
1391pub enum EnumLiteralExpressions {
1392    Nothing,
1393    Tuple(Vec<Expression>),
1394    Struct(Vec<(usize, Option<Node>, Expression)>),
1395}
1396
1397impl Debug for EnumLiteralExpressions {
1398    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1399        match self {
1400            Self::Nothing => Ok(()),
1401            Self::Tuple(x) => write!(f, "{x:?}"),
1402            Self::Struct(s) => write!(f, "{s:?}"),
1403        }
1404    }
1405}