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 struct Iterable {
611    pub key_type: Option<TypeRef>, // It does not have to support a key type
612    pub value_type: TypeRef,
613
614    pub resolved_expression: Box<Expression>,
615}
616
617#[derive(Debug, Clone)]
618pub struct AnonymousStructLiteral {
619    pub source_order_expressions: Vec<(usize, Option<Node>, Expression)>,
620    pub struct_like_type: TypeRef,
621}
622
623#[derive(Debug, Clone, Eq, PartialEq)]
624pub enum CompoundOperatorKind {
625    Add,
626    Sub,
627    Mul,
628    Div,
629    Modulo,
630}
631
632#[derive(Debug, Clone)]
633pub struct CompoundOperator {
634    pub node: Node,
635    pub kind: CompoundOperatorKind,
636}
637
638#[derive(Debug, Clone)]
639pub struct VariableCompoundAssignment {
640    pub variable_ref: VariableRef, // compound only support single variable
641    pub expression: Box<Expression>,
642    pub compound_operator: CompoundOperator,
643}
644
645#[derive(Debug, Clone)]
646pub struct Guard {
647    pub condition: Option<BooleanExpression>,
648    pub result: Expression,
649}
650
651#[derive(Debug, Clone)]
652pub struct Postfix {
653    pub node: Node,
654    pub ty: TypeRef,
655    pub kind: PostfixKind,
656}
657
658#[derive(Debug, Clone)]
659pub struct SliceViewType {
660    pub element: TypeRef,
661}
662
663#[derive(Debug, Clone)]
664pub struct VecType {
665    pub vec_type: TypeRef,
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 struct Block {
866    pub statements: Vec<Expression>,
867    pub tail: Box<Expression>,
868}
869
870#[derive(Debug, Clone)]
871pub enum ExpressionKind {
872    // Access Lookup values
873    ConstantAccess(ConstantRef),
874    VariableAccess(VariableRef),
875
876    // ----
877
878    // Operators
879    BinaryOp(BinaryOperator),
880    UnaryOp(UnaryOperator),
881    PostfixChain(StartOfChain, Vec<Postfix>),
882
883    // Coerce
884    // the `?` operator. unwraps the value, unless it is none
885    CoerceOptionToBool(Box<Expression>),
886    CoerceIntToChar(Box<Expression>),
887    CoerceIntToByte(Box<Expression>),
888    CoerceIntToShort(Box<Expression>),
889
890    CoerceIntToPointer(Box<Expression>),
891    CoerceToAny(Box<Expression>),
892
893    // Calls
894    IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpression>),
895    InternalCall(InternalFunctionDefinitionRef, Vec<ArgumentExpression>),
896    HostCall(ExternalFunctionDefinitionRef, Vec<ArgumentExpression>),
897
898    // Constructing
899    VariableDefinition(VariableRef, Box<Expression>), // First time assignment
900    VariableDefinitionLValue(VariableRef, SingleLocationExpression), // Bind variable to memory location
901    VariableReassignment(VariableRef, Box<Expression>),
902
903    Assignment(Box<TargetAssignmentLocation>, Box<Expression>),
904    CompoundAssignment(
905        TargetAssignmentLocation,
906        CompoundOperatorKind,
907        Box<Expression>,
908    ),
909
910    AnonymousStructLiteral(AnonymousStructLiteral),
911    NamedStructLiteral(Box<Expression>),
912
913    FloatLiteral(Fp),
914    NoneLiteral,
915    IntLiteral(i32),
916    ByteLiteral(u8),
917    StringLiteral(String),
918    BoolLiteral(bool),
919    EnumVariantLiteral(EnumVariantType, EnumLiteralExpressions), // TypeRef: EnumType
920    TupleLiteral(Vec<Expression>),
921
922    InitializerList(TypeRef, Vec<Expression>),
923    InitializerPairList(TypeRef, Vec<(Expression, Expression)>),
924
925    Option(Option<Box<Expression>>), // Wrapping an expression in `Some()`
926
927    // Loops
928    ForLoop(ForPattern, Iterable, Box<Expression>),
929    WhileLoop(BooleanExpression, Box<Expression>),
930
931    Block(Vec<Expression>),
932
933    // Match and compare
934    Match(Match),
935    Guard(Vec<Guard>),
936    If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
937    When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),
938
939    TupleDestructuring(Vec<VariableRef>, TypeRef, Box<Expression>),
940
941    Lambda(Vec<VariableRef>, Box<Expression>),
942    BorrowMutRef(Box<SingleLocationExpression>),
943    Error(ErrorKind),
944}
945
946impl Display for ExpressionKind {
947    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
948        match self {
949            Self::ConstantAccess(_) => {
950                write!(f, "constant")
951            }
952            Self::VariableAccess(_) => {
953                write!(f, "varaccess")
954            }
955            Self::BinaryOp(_) => {
956                write!(f, "binaryop")
957            }
958            Self::UnaryOp(_) => {
959                write!(f, "unaryop")
960            }
961            Self::PostfixChain(_, _) => {
962                write!(f, "prefix")
963            }
964            Self::CoerceOptionToBool(_) => {
965                write!(f, "byte")
966            }
967            Self::CoerceIntToChar(_) => {
968                write!(f, "byte")
969            }
970            Self::CoerceIntToByte(_) => {
971                write!(f, "byte")
972            }
973            Self::CoerceIntToShort(_) => {
974                write!(f, "IntToShort")
975            }
976            Self::CoerceIntToPointer(pointer) => {
977                write!(f, "ptr<{pointer:?}>")
978            }
979            Self::CoerceToAny(_) => {
980                write!(f, "byte")
981            }
982            Self::IntrinsicCallEx(_, _) => {
983                write!(f, "byte")
984            }
985            Self::InternalCall(_, _) => {
986                write!(f, "byte")
987            }
988            Self::HostCall(_, _) => {
989                write!(f, "byte")
990            }
991            Self::VariableDefinition(a, b) => {
992                write!(f, "vardef {a:?} {}", b.kind)
993            }
994            Self::VariableDefinitionLValue(a, _b) => {
995                write!(f, "vardefl {a:?}")
996            }
997            Self::VariableReassignment(_, _) => {
998                write!(f, "var  reassignment")
999            }
1000            Self::Assignment(_, _) => {
1001                write!(f, "byte")
1002            }
1003            Self::CompoundAssignment(_, _, _) => {
1004                write!(f, "byte")
1005            }
1006            Self::AnonymousStructLiteral(_) => {
1007                write!(f, "byte")
1008            }
1009            Self::NamedStructLiteral(_) => {
1010                write!(f, "byte")
1011            }
1012            Self::FloatLiteral(_) => {
1013                write!(f, "byte")
1014            }
1015            Self::NoneLiteral => {
1016                write!(f, "byte")
1017            }
1018            Self::IntLiteral(_) => {
1019                write!(f, "byte")
1020            }
1021            Self::ByteLiteral(_) => {
1022                write!(f, "byte")
1023            }
1024            Self::StringLiteral(_) => {
1025                write!(f, "byte")
1026            }
1027            Self::BoolLiteral(_) => {
1028                write!(f, "byte")
1029            }
1030            Self::EnumVariantLiteral(_, _) => {
1031                write!(f, "byte")
1032            }
1033            Self::TupleLiteral(_) => {
1034                write!(f, "byte")
1035            }
1036            Self::InitializerList(_, _) => {
1037                write!(f, "byte")
1038            }
1039            Self::InitializerPairList(_, _) => {
1040                write!(f, "byte")
1041            }
1042            Self::Option(_) => {
1043                write!(f, "byte")
1044            }
1045            Self::ForLoop(_, _, _) => {
1046                write!(f, "byte")
1047            }
1048            Self::WhileLoop(_, _) => {
1049                write!(f, "byte")
1050            }
1051            Self::Block(_) => {
1052                write!(f, "byte")
1053            }
1054            Self::Match(_) => {
1055                write!(f, "byte")
1056            }
1057            Self::Guard(_) => {
1058                write!(f, "byte")
1059            }
1060            Self::If(_, _, _) => {
1061                write!(f, "byte")
1062            }
1063            Self::When(_, _, _) => {
1064                write!(f, "byte")
1065            }
1066            Self::TupleDestructuring(_, _, _) => {
1067                write!(f, "byte")
1068            }
1069            Self::Lambda(_, _) => {
1070                write!(f, "byte")
1071            }
1072            Self::BorrowMutRef(_) => {
1073                write!(f, "byte")
1074            }
1075            Self::Error(_) => {
1076                write!(f, "byte")
1077            }
1078        }
1079    }
1080}
1081
1082#[derive(Debug, Clone)]
1083pub struct StringConst(pub Node);
1084
1085#[derive(Debug, Clone)]
1086pub struct ArrayInstantiation {
1087    pub expressions: Vec<Expression>,
1088    pub item_type: TypeRef,
1089    pub array_type: TypeRef,
1090    pub array_type_ref: TypeRef,
1091}
1092
1093#[derive(Debug, Clone)]
1094pub enum ForPattern {
1095    Single(VariableRef),
1096    Pair(VariableRef, VariableRef),
1097}
1098
1099impl ForPattern {
1100    #[must_use]
1101    pub fn is_mutable(&self) -> bool {
1102        match self {
1103            Self::Single(variable) => variable.is_mutable(),
1104            Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
1105        }
1106    }
1107}
1108
1109impl Display for ForPattern {
1110    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1111        write!(f, "resolved_for_pattern")
1112    }
1113}
1114
1115#[derive(Debug, Eq, PartialEq)]
1116pub struct ModulePathItem(pub Node);
1117
1118#[derive(Debug, Clone, Eq, PartialEq)]
1119pub struct LocalTypeIdentifier(pub Node);
1120
1121#[derive(Debug, Clone)]
1122pub struct Constant {
1123    pub symbol_id: TopLevelSymbolId,
1124    pub name: Node,
1125    pub assigned_name: String,
1126    pub id: ConstantId,
1127    pub expr: Expression,
1128    pub resolved_type: TypeRef,
1129    pub function_scope_state: VariableScopes,
1130}
1131pub type ConstantRef = Rc<Constant>;
1132
1133pub type OptionTypeRef = Rc<OptionType>;
1134
1135#[derive(Debug, Clone)]
1136pub struct OptionType {
1137    pub item_type: TypeRef,
1138}
1139
1140/*
1141pub fn sort_struct_fields(
1142    unordered_seq_map: &SeqMap<String, StructTypeField>,
1143) -> SeqMap<String, StructTypeField> {
1144    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
1145    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
1146    let mut ordered_seq_map = SeqMap::new();
1147
1148    for (name, field) in sorted_pairs {
1149        ordered_seq_map.insert(name, field).unwrap() // We know already that the key fields are unique
1150    }
1151
1152    ordered_seq_map
1153}
1154*/
1155
1156#[derive(Debug, Clone)]
1157pub struct ImplMember {}
1158
1159#[derive(Debug, Clone)]
1160pub enum UseItem {
1161    Identifier(Node),
1162    TypeIdentifier(Node),
1163}
1164
1165#[derive(Debug, Clone)]
1166pub struct Use {
1167    pub path: Vec<Node>,
1168    pub items: Vec<UseItem>,
1169}
1170
1171#[derive(Debug, Clone)]
1172pub struct ImplFunctions {
1173    pub functions: SeqMap<String, FunctionRef>,
1174}
1175
1176impl Default for ImplFunctions {
1177    fn default() -> Self {
1178        Self::new()
1179    }
1180}
1181
1182impl ImplFunctions {
1183    #[must_use]
1184    pub fn new() -> Self {
1185        Self {
1186            functions: SeqMap::default(),
1187        }
1188    }
1189}
1190
1191#[derive(Debug, Clone)]
1192pub struct AssociatedImpls {
1193    pub functions: SeqMap<TypeRef, ImplFunctions>,
1194}
1195
1196impl Default for AssociatedImpls {
1197    fn default() -> Self {
1198        Self::new()
1199    }
1200}
1201
1202impl AssociatedImpls {
1203    #[must_use]
1204    pub fn new() -> Self {
1205        Self {
1206            functions: SeqMap::default(),
1207        }
1208    }
1209}
1210
1211impl AssociatedImpls {
1212    pub fn prepare(&mut self, ty: &TypeRef) {
1213        self.functions
1214            .insert(ty.clone(), ImplFunctions::new())
1215            .unwrap_or_else(|_| panic!("should work {ty:?}"));
1216    }
1217
1218    #[must_use]
1219    pub fn is_prepared(&self, ty: &TypeRef) -> bool {
1220        self.functions.contains_key(ty)
1221    }
1222    #[must_use]
1223    pub fn get_member_function(&self, ty: &TypeRef, function_name: &str) -> Option<&FunctionRef> {
1224        let maybe_found_impl = self.functions.get(ty);
1225        if let Some(found_impl) = maybe_found_impl
1226            && let Some(func) = found_impl.functions.get(&function_name.to_string())
1227        {
1228            return Some(func);
1229        }
1230        None
1231    }
1232
1233    fn has_internal_member_function(&self, ty: &TypeRef, function_name: &str) -> bool {
1234        let maybe_found_impl = self.functions.get(ty);
1235        if let Some(found_impl) = maybe_found_impl
1236            && let Some(_func) = found_impl.functions.get(&function_name.to_string())
1237        {
1238            return true;
1239        }
1240        false
1241    }
1242
1243    #[must_use]
1244    pub fn api_get_external_function(
1245        &self,
1246        ty: &TypeRef,
1247        function_name: &str,
1248    ) -> Option<&ExternalFunctionDefinitionRef> {
1249        if let Some(found) = self.get_member_function(ty, function_name)
1250            && let Function::External(ext_fn) = &**found
1251        {
1252            return Some(ext_fn);
1253        }
1254        None
1255    }
1256
1257    #[must_use]
1258    pub fn get_internal_member_function(
1259        &self,
1260        ty: &TypeRef,
1261        function_name: &str,
1262    ) -> Option<&InternalFunctionDefinitionRef> {
1263        if let Some(found) = self.get_member_function(ty, function_name)
1264            && let Function::Internal(int_fn) = &**found
1265        {
1266            return Some(int_fn);
1267        }
1268        None
1269    }
1270
1271    #[must_use]
1272    pub fn get_internal_member_function_from_id(
1273        &self,
1274        function_id: InternalFunctionId,
1275    ) -> Option<&InternalFunctionDefinitionRef> {
1276        for functions in self.functions.values() {
1277            for func in functions.functions.values() {
1278                if let Function::Internal(int_fn) = &**func
1279                    && int_fn.program_unique_id == function_id
1280                {
1281                    return Some(int_fn);
1282                }
1283            }
1284        }
1285        None
1286    }
1287
1288    pub fn remove_internal_function_if_exists(
1289        &mut self,
1290        ty: &TypeRef,
1291        function_name: &str,
1292    ) -> bool {
1293        if self.has_internal_member_function(ty, function_name) {
1294            let functions = self.functions.get_mut(ty).unwrap();
1295
1296            functions.functions.remove(&function_name.to_string());
1297            true
1298        } else {
1299            false
1300        }
1301    }
1302
1303    pub fn add_member_function(
1304        &mut self,
1305        ty: &TypeRef,
1306        name: &str,
1307        func: FunctionRef,
1308    ) -> Result<(), SemanticError> {
1309        let maybe_found_impl = self.functions.get_mut(ty);
1310
1311        if let Some(found_impl) = maybe_found_impl {
1312            found_impl
1313                .functions
1314                .insert(name.to_string(), func)
1315                .unwrap_or_else(|_| panic!("already had key {name}"));
1316            Ok(())
1317        } else {
1318            error!(%ty, ?name, "wasn't prepared");
1319            Err(SemanticError::UnknownImplOnType)
1320        }
1321    }
1322
1323    pub fn add_internal_function(
1324        &mut self,
1325        ty: &TypeRef,
1326        func: InternalFunctionDefinition,
1327    ) -> Result<(), SemanticError> {
1328        //info!(name=?func.assigned_name, ?ty, "adding member function");
1329        self.add_member_function(
1330            ty,
1331            &func.assigned_name.clone(),
1332            Function::Internal(func.into()).into(),
1333        )
1334    }
1335
1336    pub fn add_external_member_function(
1337        &mut self,
1338        ty: &TypeRef,
1339        func: ExternalFunctionDefinition,
1340    ) -> Result<(), SemanticError> {
1341        self.add_member_function(
1342            ty,
1343            &func.assigned_name.clone(),
1344            Function::External(func.into()).into(),
1345        )
1346    }
1347
1348    pub fn add_external_struct_member_function(
1349        &mut self,
1350        named_struct_type: TypeRef,
1351        func: Function,
1352    ) -> Result<(), SemanticError> {
1353        self.add_member_function(&named_struct_type, &func.name(), func.into())
1354    }
1355
1356    pub fn add_external_struct_member_function_external(
1357        &mut self,
1358        named_struct_type: TypeRef,
1359        func: ExternalFunctionDefinition,
1360    ) -> Result<(), SemanticError> {
1361        self.add_member_function(
1362            &named_struct_type,
1363            &func.assigned_name.clone(),
1364            Function::External(func.into()).into(),
1365        )
1366    }
1367
1368    pub fn add_external_struct_member_function_external_ref(
1369        &mut self,
1370        named_struct_type: TypeRef,
1371        func: ExternalFunctionDefinitionRef,
1372    ) -> Result<(), SemanticError> {
1373        self.add_member_function(
1374            &named_struct_type,
1375            &func.assigned_name.clone(),
1376            Function::External(func).into(),
1377        )
1378    }
1379}
1380
1381#[derive(Clone)]
1382pub enum EnumLiteralExpressions {
1383    Nothing,
1384    Tuple(Vec<Expression>),
1385    Struct(Vec<(usize, Option<Node>, Expression)>),
1386}
1387
1388impl Debug for EnumLiteralExpressions {
1389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1390        match self {
1391            Self::Nothing => Ok(()),
1392            Self::Tuple(x) => write!(f, "{x:?}"),
1393            Self::Struct(s) => write!(f, "{s:?}"),
1394        }
1395    }
1396}