swamp-script-semantic 0.1.10

semantic types for swamp script
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
/*
 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/script
 * Licensed under the MIT License. See LICENSE in the project root for license information.
 */
pub mod inst_cache;
pub mod instantiator;
pub mod intr;
pub mod prelude;
pub mod type_var_stack;
use crate::instantiator::Instantiator;
use crate::intr::IntrinsicFunction;
use crate::prelude::IntrinsicFunctionDefinitionRef;
pub use fixed32::Fp;
use seq_map::SeqMap;
use std::cmp::PartialEq;
use std::fmt;
use std::fmt::{Debug, Display, Formatter};
use std::rc::Rc;
use swamp_script_node::Node;
use swamp_script_types::GenericAwareSignature;
use swamp_script_types::prelude::*;
use tracing::error;

#[derive(Debug, Clone)]
pub struct TypeWithMut {
    pub resolved_type: Type,
    pub is_mutable: bool,
}

#[derive(Debug, Clone)]
pub enum SemanticError {
    CouldNotInsertStruct,
    DuplicateTypeAlias(String),
    CanOnlyUseStructForMemberFunctions,
    ResolveNotStruct,
    DuplicateStructName(String),
    DuplicateEnumType(String),
    DuplicateEnumVariantType(String, String),
    DuplicateFieldName(String),
    DuplicateExternalFunction(String),
    DuplicateRustType(String),
    DuplicateConstName(String),
    CircularConstantDependency(Vec<ConstantId>),
    DuplicateConstantId(ConstantId),
    IncompatibleTypes,
    WasNotImmutable,
    WasNotMutable,
    DuplicateSymbolName(String),
    DuplicateNamespaceLink(String),
    MismatchedTypes { expected: Type, found: Vec<Type> },
    UnknownImplOnType,
    UnknownTypeVariable,
}

#[derive(Debug, Eq, PartialEq)]
pub struct LocalIdentifier(pub Node);

#[derive(Debug)]
pub struct InternalMainExpression {
    pub expression: Expression,
    pub function_scope_state: Vec<VariableRef>,
    pub program_unique_id: InternalFunctionId,
}

//#[derive(Debug,Clone)]
pub struct InternalFunctionDefinition {
    pub body: Expression,
    pub name: LocalIdentifier,
    pub assigned_name: String,
    pub signature: GenericAwareSignature,
    pub variable_scopes: FunctionScopeState,
    pub function_scope_state: Vec<VariableRef>,
    pub program_unique_id: InternalFunctionId,
}

impl Default for InternalFunctionDefinition {
    fn default() -> Self {
        Self {
            body: Expression {
                ty: Type::Never,
                node: Node::default(),
                kind: ExpressionKind::Block(vec![]),
            },
            name: LocalIdentifier(Node::default()),
            assigned_name: String::new(),
            signature: GenericAwareSignature {
                signature: Signature {
                    parameters: vec![],
                    return_type: Box::new(Type::Never),
                },
                generic_type_variables: vec![],
            },
            variable_scopes: FunctionScopeState::new(Type::Unit),
            function_scope_state: Vec::new(),
            program_unique_id: 0,
        }
    }
}

impl Debug for InternalFunctionDefinition {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}\n{:?}", self.signature, self.body)
    }
}

impl PartialEq<Self> for InternalFunctionDefinition {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

impl Eq for InternalFunctionDefinition {}

pub type InternalFunctionDefinitionRef = Rc<InternalFunctionDefinition>;

pub type ExternalFunctionId = u32;

pub type InternalFunctionId = u16;

pub type ConstantId = u32;

#[derive(Eq, PartialEq)]
pub struct ExternalFunctionDefinition {
    pub name: Option<Node>,
    pub assigned_name: String,
    pub signature: Signature,
    pub id: ExternalFunctionId,
}

impl Debug for ExternalFunctionDefinition {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "external fn")
    }
}

pub type ExternalFunctionDefinitionRef = Rc<crate::ExternalFunctionDefinition>;

#[derive(Debug, Eq, Clone, PartialEq)]
pub enum BlockScopeMode {
    Open,
    Closed,
}

#[derive(Debug, Clone)]
pub struct BlockScope {
    pub mode: BlockScopeMode,
    pub variables: SeqMap<String, VariableRef>,
}

impl Display for BlockScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        writeln!(f, "-- scope {:?}", self.mode)?;

        for (index, (name, var)) in self.variables.iter().enumerate() {
            writeln!(f, "  var({index}): {name}:{var:?}")?;
        }
        Ok(())
    }
}

impl Default for BlockScope {
    fn default() -> Self {
        Self::new()
    }
}

impl BlockScope {
    #[must_use]
    pub fn new() -> Self {
        Self {
            mode: BlockScopeMode::Open,
            variables: SeqMap::new(),
        }
    }
}

#[derive(Clone)]
pub struct FunctionScopeState {
    pub block_scope_stack: Vec<BlockScope>,
    pub return_type: Type,
    pub variable_index: usize,
}

impl Display for FunctionScopeState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        for (index, scope) in self.block_scope_stack.iter().enumerate() {
            writeln!(f, "block({index}):\n{scope}")?;
        }
        Ok(())
    }
}

impl FunctionScopeState {
    pub fn gen_variable_index(&mut self) -> usize {
        let index = self.variable_index;
        self.variable_index += 1;
        index
    }
}

impl FunctionScopeState {
    #[must_use]
    pub fn new(return_type: Type) -> Self {
        Self {
            block_scope_stack: vec![BlockScope::new()],
            return_type,
            variable_index: 0,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Variable {
    pub name: Node,
    pub assigned_name: String,
    pub resolved_type: Type,
    pub mutable_node: Option<Node>,

    pub scope_index: usize,
    pub variable_index: usize,

    pub unique_id_within_function: usize,
    pub is_unused: bool,
}

impl Variable {
    #[must_use]
    pub const fn is_mutable(&self) -> bool {
        self.mutable_node.is_some()
    }
}

pub type VariableRef = Rc<Variable>;

#[derive(Debug, Clone)]
pub struct MutVariable {
    pub variable_ref: VariableRef,
}

//type MutVariableRef = Rc<MutVariable>;

#[derive(Debug, Clone)]
pub enum BinaryOperatorKind {
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo,
    LogicalOr,
    LogicalAnd,
    Equal,
    NotEqual,
    LessThan,
    LessEqual,
    GreaterThan,
    GreaterEqual,
    RangeExclusive,
}

#[derive(Debug, Clone)]
pub struct BinaryOperator {
    pub left: Box<Expression>,
    pub right: Box<Expression>,
    pub kind: BinaryOperatorKind,
    pub node: Node,
}

#[derive(Debug, Clone)]
pub enum UnaryOperatorKind {
    Not,
    Negate,
}
#[derive(Debug, Clone)]
pub struct UnaryOperator {
    pub left: Box<Expression>,
    pub kind: UnaryOperatorKind,
    pub node: Node,
}

#[derive()]
pub struct InternalFunctionCall {
    pub arguments: Vec<ArgumentExpressionOrLocation>,

    pub function_definition: InternalFunctionDefinitionRef,
    pub function_expression: Box<Expression>,
}

impl Debug for InternalFunctionCall {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "InFuncCall({:?} {:?})",
            self.function_expression, self.arguments
        )
    }
}

#[derive(Debug, Clone)]
pub struct ExternalFunctionCall {
    pub arguments: Vec<ArgumentExpressionOrLocation>,
    pub function_definition: ExternalFunctionDefinitionRef,
    pub function_expression: Box<Expression>,
}

pub fn comma_tuple_ref<K: Display, V: Display>(values: &[(&K, &V)]) -> String {
    let mut result = String::new();
    for (i, (key, value)) in values.iter().enumerate() {
        if i > 0 {
            result.push_str(", ");
        }
        result.push_str(format!("{}: {}", key, value).as_str());
    }
    result
}

#[derive(Debug, Clone)]
pub struct MemberCall {
    pub function: FunctionRef,
    pub arguments: Vec<ArgumentExpressionOrLocation>,
}

#[derive(Debug, Clone)]
pub struct ArrayItem {
    pub item_type: Type,
    pub int_expression: Expression,
    pub array_expression: Expression,
    pub array_type: Type,
}

pub type ArrayItemRef = Rc<ArrayItem>;

#[derive(Debug, Clone)]
pub enum PrecisionType {
    Float,
    String,
}

#[derive(Debug, Clone)]
pub enum FormatSpecifierKind {
    LowerHex,                            // :x
    UpperHex,                            // :X
    Binary,                              // :b
    Float,                               // :f
    Precision(u32, Node, PrecisionType), // :..2f or :..5s
}

#[derive(Debug, Clone)]
pub struct FormatSpecifier {
    pub node: Node,
    pub kind: FormatSpecifierKind,
}

#[derive(Debug, Clone)]
pub enum StringPart {
    Literal(Node, String),
    Interpolation(Expression, Option<FormatSpecifier>),
}

pub type FunctionRef = Rc<Function>;

#[derive(Debug, Eq, Clone, PartialEq)]
pub enum Function {
    Internal(InternalFunctionDefinitionRef),
    External(ExternalFunctionDefinitionRef),
}

impl Function {
    #[must_use]
    pub fn name(&self) -> String {
        match self {
            Self::Internal(x) => x.assigned_name.clone(),
            Self::External(y) => y.assigned_name.clone(),
        }
    }

    #[must_use]
    pub fn maybe_node(&self) -> Option<&Node> {
        match self {
            Self::Internal(x) => Some(&x.name.0),
            Self::External(y) => y.name.as_ref(),
        }
    }

    #[must_use]
    pub fn node(&self) -> Node {
        match self {
            Self::Internal(x) => x.name.0.clone(),
            Self::External(_y) => Node::new_unknown(),
        }
    }

    #[must_use]
    pub fn signature(&self) -> &Signature {
        match self {
            Self::Internal(internal) => &internal.signature.signature,
            Self::External(external) => &external.signature,
        }
    }
}

#[derive(Debug, Clone)]
pub struct BooleanExpression {
    #[allow(unused)]
    pub expression: Box<Expression>,
}

// TODO: Maybe have different Match types, one specific for enums and one for other values
#[derive(Debug, Clone)]
pub struct Match {
    pub arms: Vec<MatchArm>,
    pub expression: Box<MutOrImmutableExpression>,
}

impl Match {
    #[must_use]
    pub fn contains_wildcard(&self) -> bool {
        for arm in &self.arms {
            if let Pattern::Wildcard(_) = arm.pattern {
                return true;
            }
        }
        false
    }
}

#[derive(Debug, Clone)]
pub struct MatchArm {
    #[allow(unused)]
    pub pattern: Pattern,
    pub expression: Box<Expression>,
    pub expression_type: Type,
}

#[derive(Debug, Clone)]
pub enum Pattern {
    Normal(NormalPattern, Option<BooleanExpression>),
    Wildcard(Node),
}

#[derive(Debug, Clone)]
pub enum NormalPattern {
    PatternList(Vec<PatternElement>),
    EnumPattern(EnumVariantType, Option<Vec<PatternElement>>),
    Literal(Literal),
}

#[derive(Debug, Clone)]
pub enum PatternElement {
    Variable(VariableRef),
    VariableWithFieldIndex(VariableRef, usize),
    Wildcard(Node),
}

#[derive(Debug, Clone)]
pub struct Iterable {
    pub key_type: Option<Type>, // It does not have to support a key type
    pub value_type: Type,

    pub resolved_expression: Box<MutOrImmutableExpression>,
}

#[derive(Debug, Clone)]
pub struct StructInstantiation {
    pub source_order_expressions: Vec<(usize, Expression)>,
    pub struct_type_ref: NamedStructType,
}

#[derive(Debug, Clone)]
pub struct AnonymousStructLiteral {
    pub source_order_expressions: Vec<(usize, Expression)>,
    pub anonymous_struct_type: AnonymousStructType,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum CompoundOperatorKind {
    Add,
    Sub,
    Mul,
    Div,
    Modulo,
}

#[derive(Debug, Clone)]
pub struct CompoundOperator {
    pub node: Node,
    pub kind: CompoundOperatorKind,
}

#[derive(Debug, Clone)]
pub struct VariableCompoundAssignment {
    pub variable_ref: VariableRef, // compound only support single variable
    pub expression: Box<Expression>,
    pub compound_operator: CompoundOperator,
}

pub fn create_rust_type(name: &str, external_number: u32) -> ExternalType {
    ExternalType {
        type_name: name.to_string(),
        number: external_number,
    }
}

#[derive(Debug, Clone)]
pub struct Guard {
    pub condition: Option<BooleanExpression>,
    pub result: Expression,
}

#[derive(Debug, Clone)]
pub struct Postfix {
    pub node: Node,
    pub ty: Type,
    pub kind: PostfixKind,
}

#[derive(Debug, Clone)]
pub enum PostfixKind {
    StructField(AnonymousStructType, usize),
    MemberCall(FunctionRef, Vec<ArgumentExpressionOrLocation>),
    FunctionCall(Vec<ArgumentExpressionOrLocation>),
    OptionalChainingOperator,           // ? operator
    NoneCoalescingOperator(Expression), // ?? operator
}

#[derive(Debug, Clone)]
pub enum LocationAccessKind {
    FieldIndex(AnonymousStructType, usize),
    IntrinsicCallMut(IntrinsicFunction, Vec<Expression>),
}

#[derive(Debug, Clone)]
pub struct LocationAccess {
    pub node: Node,
    pub ty: Type,
    pub kind: LocationAccessKind,
}

#[derive(Debug, Clone)]
pub struct SingleLocationExpression {
    pub kind: SingleLocationExpressionKind,
    pub node: Node,
    pub ty: Type,

    pub starting_variable: VariableRef,
    pub access_chain: Vec<LocationAccess>,
}

#[derive(Debug, Clone)]
pub struct SingleMutLocationExpression(pub SingleLocationExpression);

#[derive(Debug, Clone)]
pub enum SingleLocationExpressionKind {
    MutVariableRef,
    MutStructFieldRef(NamedStructType, usize),
}

#[derive(Debug, Clone)]
pub struct MutOrImmutableExpression {
    pub expression_or_location: ArgumentExpressionOrLocation,
    pub is_mutable: Option<Node>,
}

impl MutOrImmutableExpression {
    pub fn expect_immutable(self) -> Result<Expression, SemanticError> {
        match self.expression_or_location {
            ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
            ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
        }
    }

    pub fn expect_immutable_ref(&self) -> Result<&Expression, SemanticError> {
        match &self.expression_or_location {
            ArgumentExpressionOrLocation::Expression(expr) => Ok(expr),
            ArgumentExpressionOrLocation::Location(_) => Err(SemanticError::WasNotImmutable),
        }
    }

    pub fn ty(&self) -> &Type {
        match &self.expression_or_location {
            ArgumentExpressionOrLocation::Expression(expr) => &expr.ty,
            ArgumentExpressionOrLocation::Location(loc) => &loc.ty,
        }
    }

    #[must_use]
    pub const fn node(&self) -> &Node {
        match &self.expression_or_location {
            ArgumentExpressionOrLocation::Expression(expr) => &expr.node,
            ArgumentExpressionOrLocation::Location(loc) => &loc.node,
        }
    }
}

#[derive(Debug, Clone)]
pub enum ArgumentExpressionOrLocation {
    Expression(Expression),
    Location(SingleLocationExpression),
}

impl ArgumentExpressionOrLocation {
    #[must_use]
    pub fn ty(&self) -> Type {
        match self {
            Self::Expression(expr) => expr.ty.clone(),
            Self::Location(location) => location.ty.clone(),
        }
    }
}

#[derive(Clone)]
pub struct Expression {
    pub ty: Type,
    pub node: Node,
    pub kind: ExpressionKind,
}

impl Debug for Expression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "{:?}{},{:?}", self.node, self.ty, self.kind)
    }
}

#[derive(Debug, Clone)]
pub struct WhenBinding {
    pub variable: VariableRef,
    pub expr: MutOrImmutableExpression,
}

impl WhenBinding {
    #[must_use]
    pub const fn has_expression(&self) -> bool {
        match &self.expr.expression_or_location {
            ArgumentExpressionOrLocation::Expression(expr) => {
                !matches!(expr.kind, ExpressionKind::VariableAccess(_))
            }
            ArgumentExpressionOrLocation::Location(_) => true,
        }
    }
}

#[derive(Debug, Clone)]
pub enum ExpressionKind {
    // Access Lookup values
    ConstantAccess(ConstantRef),
    VariableAccess(VariableRef),

    // ----
    IntrinsicFunctionAccess(IntrinsicFunctionDefinitionRef),
    InternalFunctionAccess(InternalFunctionDefinitionRef),
    ExternalFunctionAccess(ExternalFunctionDefinitionRef),

    // Operators
    BinaryOp(BinaryOperator),
    UnaryOp(UnaryOperator),
    PostfixChain(Box<Expression>, Vec<Postfix>),

    // Conversion
    // the `?` operator. unwraps the value, unless it is none
    CoerceOptionToBool(Box<Expression>),

    // Calls

    // For calls from returned function values
    FunctionValueCall(
        Signature,
        Box<Expression>,
        Vec<ArgumentExpressionOrLocation>,
    ),

    InterpolatedString(Vec<StringPart>),

    // Constructing
    VariableDefinition(VariableRef, Box<MutOrImmutableExpression>), // First time assignment
    VariableReassignment(VariableRef, Box<MutOrImmutableExpression>),
    Assignment(Box<SingleMutLocationExpression>, Box<Expression>),
    CompoundAssignment(
        SingleMutLocationExpression,
        CompoundOperatorKind,
        Box<Expression>,
    ),

    StructInstantiation(StructInstantiation),
    AnonymousStructLiteral(AnonymousStructLiteral),
    Literal(Literal),
    Option(Option<Box<Expression>>), // Wrapping an expression in `Some()`

    // Loops
    ForLoop(ForPattern, Iterable, Box<Expression>),
    WhileLoop(BooleanExpression, Box<Expression>),

    Block(Vec<Expression>),

    // Match and compare
    Match(Match),
    Guard(Vec<Guard>),
    If(BooleanExpression, Box<Expression>, Option<Box<Expression>>),
    When(Vec<WhenBinding>, Box<Expression>, Option<Box<Expression>>),

    TupleDestructuring(Vec<VariableRef>, Vec<Type>, Box<Expression>),

    // --------------------------------------------------------------------
    // Built In members
    // --------------------------------------------------------------------
    IntrinsicCallEx(IntrinsicFunction, Vec<ArgumentExpressionOrLocation>),
    /*
    //NoneCoalesceOperator(Box<Expression>, Box<Expression>),

    IntrinsicCallMut(
        IntrinsicFunction,
        SingleMutLocationExpression,
        Vec<Expression>,
    ),
    */
    Lambda(Vec<VariableRef>, Box<Expression>),
}

#[derive(Debug, Clone)]
pub struct StringConst(pub Node);

#[derive(Debug, Clone)]
pub enum Literal {
    FloatLiteral(Fp),
    NoneLiteral,
    IntLiteral(i32),
    StringLiteral(String),
    BoolLiteral(bool),

    EnumVariantLiteral(EnumType, EnumVariantType, EnumLiteralData),
    TupleLiteral(Vec<Type>, Vec<Expression>),

    Slice(Type, Vec<Expression>),
    SlicePair(Type, Vec<(Expression, Expression)>),
}

#[derive(Debug, Clone)]
pub struct ArrayInstantiation {
    pub expressions: Vec<Expression>,
    pub item_type: Type,
    pub array_type: Type,
    pub array_type_ref: Type,
}

#[derive(Debug, Clone)]
pub enum ForPattern {
    Single(VariableRef),
    Pair(VariableRef, VariableRef),
}

impl ForPattern {
    #[must_use]
    pub fn is_mutable(&self) -> bool {
        match self {
            Self::Single(variable) => variable.is_mutable(),
            Self::Pair(a, b) => a.is_mutable() || b.is_mutable(),
        }
    }
}

impl Display for ForPattern {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "resolved_for_pattern")
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct ModulePathItem(pub Node);

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct LocalTypeIdentifier(pub Node);

#[derive(Debug, Clone)]
pub struct Constant {
    pub name: Node,
    pub assigned_name: String,
    pub id: ConstantId,
    pub expr: Expression,
    pub resolved_type: Type,
}
pub type ConstantRef = Rc<Constant>;

pub type OptionTypeRef = Rc<crate::OptionType>;

#[derive(Debug, Clone)]
pub struct OptionType {
    pub item_type: Type,
}

/*
pub fn sort_struct_fields(
    unordered_seq_map: &SeqMap<String, StructTypeField>,
) -> SeqMap<String, StructTypeField> {
    let mut sorted_pairs: Vec<(&String, &StructTypeField)> = unordered_seq_map.iter().collect();
    sorted_pairs.sort_by(|a, b| a.0.cmp(b.0));
    let mut ordered_seq_map = SeqMap::new();

    for (name, field) in sorted_pairs {
        ordered_seq_map.insert(name, field).unwrap() // We know already that the key fields are unique
    }

    ordered_seq_map
}

 */

#[derive(Debug, Clone)]
pub struct ImplMember {}

#[derive(Debug, Clone)]
pub enum UseItem {
    Identifier(Node),
    TypeIdentifier(Node),
}

#[derive(Debug, Clone)]
pub struct Use {
    pub path: Vec<Node>,
    pub items: Vec<UseItem>,
}

#[derive(Debug, Clone)]
pub struct ImplFunctions {
    pub functions: SeqMap<String, FunctionRef>,
}

impl Default for ImplFunctions {
    fn default() -> Self {
        Self::new()
    }
}

impl ImplFunctions {
    #[must_use]
    pub fn new() -> Self {
        Self {
            functions: SeqMap::default(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct AssociatedImpls {
    pub functions: SeqMap<Type, ImplFunctions>,
}

impl Default for AssociatedImpls {
    fn default() -> Self {
        Self::new()
    }
}

impl AssociatedImpls {
    #[must_use]
    pub fn new() -> Self {
        Self {
            functions: SeqMap::default(),
        }
    }
}

impl AssociatedImpls {
    pub fn prepare(&mut self, ty: &Type) {
        self.functions
            .insert(ty.clone(), ImplFunctions::new())
            .expect("should work");
    }
    #[must_use]
    pub fn get_member_function(&self, ty: &Type, function_name: &str) -> Option<&FunctionRef> {
        let maybe_found_impl = self.functions.get(&ty);
        if let Some(found_impl) = maybe_found_impl {
            if let Some(func) = found_impl.functions.get(&function_name.to_string()) {
                return Some(func);
            }
        }
        None
    }

    pub fn api_get_external_function(
        &self,
        ty: &Type,
        function_name: &str,
    ) -> Option<&ExternalFunctionDefinitionRef> {
        if let Some(found) = self.get_member_function(ty, function_name) {
            if let Function::External(ext_fn) = &**found {
                return Some(ext_fn);
            }
        }
        None
    }

    pub fn api_fetch_external_function_id(
        &self,
        ty: &Type,
        function_name: &str,
    ) -> ExternalFunctionId {
        self.api_get_external_function(ty, function_name)
            .unwrap()
            .id
    }

    pub fn get_internal_member_function(
        &self,
        ty: &Type,
        function_name: &str,
    ) -> Option<&InternalFunctionDefinitionRef> {
        if let Some(found) = self.get_member_function(ty, function_name) {
            if let Function::Internal(int_fn) = &**found {
                return Some(int_fn);
            }
        }
        None
    }

    pub fn add_member_function(
        &mut self,
        ty: &Type,
        name: &str,
        func: FunctionRef,
    ) -> Result<(), SemanticError> {
        let maybe_found_impl = self.functions.get_mut(&ty);

        if let Some(found_impl) = maybe_found_impl {
            found_impl
                .functions
                .insert(name.to_string(), func)
                .expect("todo");
            Ok(())
        } else {
            error!(%ty, ?name, "wasn't prepared");
            Err(SemanticError::UnknownImplOnType)
        }
    }

    pub fn add_external_member_function(
        &mut self,
        ty: &Type,
        func: ExternalFunctionDefinition,
    ) -> Result<(), SemanticError> {
        self.add_member_function(
            ty,
            &func.assigned_name.clone(),
            Function::External(func.into()).into(),
        )
    }

    pub fn add_external_struct_member_function(
        &mut self,
        named_struct_type: &NamedStructType,
        func: Function,
    ) -> Result<(), SemanticError> {
        self.add_member_function(
            &Type::NamedStruct(named_struct_type.clone()),
            &func.name().clone(),
            func.into(),
        )
    }

    pub fn add_external_struct_member_function_external(
        &mut self,
        named_struct_type: NamedStructType,
        func: ExternalFunctionDefinition,
    ) -> Result<(), SemanticError> {
        self.add_member_function(
            &Type::NamedStruct(named_struct_type.clone()),
            &func.assigned_name.clone(),
            Function::External(func.into()).into(),
        )
    }

    pub fn add_external_struct_member_function_external_ref(
        &mut self,
        named_struct_type: NamedStructType,
        func: ExternalFunctionDefinitionRef,
    ) -> Result<(), SemanticError> {
        self.add_member_function(
            &Type::NamedStruct(named_struct_type.clone()),
            &func.assigned_name.clone(),
            Function::External(func.into()).into(),
        )
    }
}

// Mutable part
#[derive(Debug, Clone)]
pub struct ProgramState {
    pub external_function_number: ExternalFunctionId,
    pub internal_function_id_allocator: InternalFunctionIdAllocator,
    // It is just so we don't have to do another dependency check of the
    // modules, we know that these constants have been
    // evaluated in order already
    pub constants_in_dependency_order: Vec<ConstantRef>,
    pub instantiator: Instantiator,
}

impl Default for ProgramState {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Clone)]
pub struct InternalFunctionIdAllocator {
    pub internal_function_number: InternalFunctionId,
}

impl Default for InternalFunctionIdAllocator {
    fn default() -> Self {
        Self::new()
    }
}

impl InternalFunctionIdAllocator {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            internal_function_number: 0,
        }
    }
    pub fn alloc(&mut self) -> InternalFunctionId {
        self.internal_function_number += 1;
        self.internal_function_number
    }
}

impl ProgramState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            external_function_number: 0,
            internal_function_id_allocator: InternalFunctionIdAllocator::new(),
            constants_in_dependency_order: Vec::new(),
            instantiator: Instantiator::new(),
        }
    }

    pub fn allocate_external_function_id(&mut self) -> ExternalFunctionId {
        self.external_function_number += 1;
        self.external_function_number
    }

    pub fn allocate_internal_function_id(&mut self) -> InternalFunctionId {
        self.internal_function_id_allocator.alloc()
    }
}

#[derive(Clone)]
pub enum EnumLiteralData {
    Nothing,
    Tuple(Vec<Expression>),
    Struct(Vec<(usize, Expression)>),
}

impl Debug for EnumLiteralData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Self::Nothing => Ok(()),
            Self::Tuple(x) => write!(f, "{x:?}"),
            Self::Struct(s) => write!(f, "{s:?}"),
        }
    }
}