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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
//  AST.rs
//    by Lut99
//
//  Created:
//    10 Aug 2022, 14:00:59
//  Last edited:
//    31 Jan 2024, 11:30:40
//  Auto updated?
//    Yes
//
//  Description:
//!   Defines the AST that the `brane-dsl` parses to.
//

use std::cell::RefCell;
use std::collections::HashSet;
use std::fmt::{Debug, Display, Formatter, Result as FResult};
use std::rc::Rc;
use std::str::FromStr as _;

use enum_debug::EnumDebug;
use specifications::version::{ParseError, Version};

use crate::data_type::DataType;
use crate::location::AllowedLocations;
use crate::spec::{TextPos, TextRange};
use crate::symbol_table::{ClassEntry, FunctionEntry, SymbolTable, SymbolTableEntry, VarEntry};


/***** STATICS *****/
/// Defines a none-range.
static NONE_RANGE: TextRange = TextRange::none();





/***** LIBRARY TRAITS *****/
/// Defines a general AST node.
pub trait Node: Clone + Debug {
    /// Returns the node's source range.
    fn range(&self) -> &TextRange;

    /// Returns the node's start position.
    #[inline]
    fn start(&self) -> &TextPos { &self.range().start }

    /// Returns the node's end position.
    #[inline]
    fn end(&self) -> &TextPos { &self.range().end }
}





/***** LIBRARY STRUCTS *****/
/// Defines the toplevel Program element.
#[derive(Clone, Debug)]
pub struct Program {
    /// The toplevel program is simply a code block with global variables.
    pub block:    Block,
    /// Metadata for the entire program.
    pub metadata: HashSet<Metadata>,
}

impl Node for Program {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange { self.block.range() }
}



/// Defines a pair of metadata.
///
/// In particular, it's a "namespaced tag".
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Metadata {
    /// The owning user.
    pub owner: String,
    /// The tag itself.
    pub tag:   String,
}

/// Defines an attribute (i.e., compiler directive).
#[derive(Clone, Debug, EnumDebug)]
pub enum Attribute {
    /// It's a simple key/pair value
    KeyPair {
        /// The given key.
        key:   Identifier,
        /// The given value, as a BraneScript literal.
        value: Literal,

        /// The range of the attribute in the source text.
        range: TextRange,
    },
    /// It's a list of stuff
    List {
        /// The given key.
        key:    Identifier,
        /// The values we parsed
        values: Vec<Literal>,
        /// The range of the attribute in the source text.
        range:  TextRange,
    },
}
impl Attribute {
    /// Constructor for the attribute that initializes it as a key/pair value.
    ///
    /// # Arguments
    /// - `key`: The given key, as a BraneScript [`Identifier`].
    /// - `value`: The given value, as a BraneScript [`Literal`].
    /// - `range`: The [`TextRange`] linking this attribute to the source text.
    ///
    /// # Returns
    /// A new Attribute.
    #[inline]
    pub fn keypair(key: impl Into<Identifier>, value: impl Into<Literal>, range: impl Into<TextRange>) -> Self {
        Self::KeyPair {
            key:   key.into(),
            value: value.into(),

            range: range.into(),
        }
    }

    /// Constructor for the attribute that initializes it as a list of values.
    ///
    /// # Arguments
    /// - `key`: The given key, as a BraneScript [`Identifier`].
    /// - `values`: The given values, as a list of BraneScript [`Literal`]s.
    /// - `range`: The [`TextRange`] linking this attribute to the source text.
    ///
    /// # Returns
    /// A new Attribute.
    #[inline]
    pub fn list(key: impl Into<Identifier>, values: impl Into<Vec<Literal>>, range: impl Into<TextRange>) -> Self {
        Self::List { key: key.into(), values: values.into(), range: range.into() }
    }
}
impl Node for Attribute {
    #[inline]
    fn range(&self) -> &TextRange {
        match self {
            Self::KeyPair { range, .. } => range,
            Self::List { range, .. } => range,
        }
    }
}



/// Defines a code block (i.e., a series of statements).
#[derive(Clone, Debug)]
pub struct Block {
    /// The list of statements in this Block.
    pub stmts: Vec<Stmt>,

    /// The SymbolTable that remembers the scope of this block.
    pub table:    Rc<RefCell<SymbolTable>>,
    /// The return type as found in this block.
    pub ret_type: Option<DataType>,

    /// A list of attributes attached to this block.
    pub attrs: Vec<Attribute>,
    /// The range of the block in the source text.
    pub range: TextRange,
}

impl Block {
    /// Constructor for the Block that auto-initializes some auxillary fields.
    ///
    /// # Arguments
    /// - `stmts`: The statements that live in this block.
    /// - `range`: The TextRange that anchors this block in the source file.
    ///
    /// # Returns
    /// A new Block instance.
    #[inline]
    pub fn new(stmts: Vec<Stmt>, range: TextRange) -> Self { Self { stmts, table: SymbolTable::new(), ret_type: None, attrs: vec![], range } }
}

impl Default for Block {
    #[inline]
    fn default() -> Self {
        Self {
            stmts: vec![],

            table:    SymbolTable::new(),
            ret_type: None,

            attrs: vec![],
            range: TextRange::none(),
        }
    }
}

impl Node for Block {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange { &self.range }
}



/// Defines a single statement.
#[derive(Clone, Debug, EnumDebug)]
pub enum Stmt {
    /// Defines an unprocessed `#[...]` attirbute.
    Attribute(Attribute),
    /// Defines an unprocessed `#![...]` attriute.
    AttributeInner(Attribute),

    /// Defines a block statement (i.e., `{ ... }`).
    Block {
        /// The actual block it references
        block: Box<Block>,
    },

    /// Defines a package import.
    Import {
        /// The name of the package that we import.
        name:    Identifier,
        /// The version of the package that we import.
        version: Literal,

        /// Reference to the function symbol table entries that this import generates.
        st_funcs:   Option<Vec<Rc<RefCell<FunctionEntry>>>>,
        /// Reference to the class symbol table entries that this import generates.
        st_classes: Option<Vec<Rc<RefCell<ClassEntry>>>>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the import statement in the source text.
        range: TextRange,
    },
    /// Defines a function definition.
    FuncDef {
        /// The name of the function, as an identifier.
        ident:  Identifier,
        /// The parameters of the function, as identifiers.
        params: Vec<Identifier>,
        /// The code to execute when running this function.
        code:   Box<Block>,

        /// Reference to the symbol table entry this function generates.
        st_entry: Option<Rc<RefCell<FunctionEntry>>>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the function definition in the source text.
        range: TextRange,
    },
    /// Defines a class definition.
    ClassDef {
        /// The name of the class, as an identifier.
        ident:   Identifier,
        /// The properties of the class, as (identifier, type) pairs.
        props:   Vec<Property>,
        /// The methods belonging to this class, as a vector of function definitions.
        methods: Vec<Box<Stmt>>,

        /// Reference to the symbol table entry this class generates.
        st_entry:     Option<Rc<RefCell<ClassEntry>>>,
        /// The SymbolTable that hosts the nested declarations. Is also found in the ClassEntry itself to resolve children.
        symbol_table: Rc<RefCell<SymbolTable>>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the class definition in the source text.
        range: TextRange,
    },
    /// Defines a return statement.
    Return {
        /// The expression to return.
        expr:      Option<Expr>,
        /// The expected return datatype.
        data_type: DataType,
        /// If this is a return on workflow level, also mentions a data that is returned (if any).
        output:    HashSet<Data>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the return statement in the source text.
        range: TextRange,
    },

    /// Defines an if-statement.
    If {
        /// The condition to branch on.
        cond: Expr,
        /// The block for if the condition was true.
        consequent: Box<Block>,
        /// The (optional) block for if the condition was false.
        alternative: Option<Box<Block>>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the if-statement in the source text.
        range: TextRange,
    },
    /// Defines a for-loop.
    For {
        /// The statement that is run at the start of the for-loop.
        initializer: Box<Stmt>,
        /// The expression that has to evaluate to true while running.
        condition:   Expr,
        /// The statement that is run at the end of every iteration.
        increment:   Box<Stmt>,
        /// The block to run every iteration.
        consequent:  Box<Block>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the for-loop in the source text.
        range: TextRange,
    },
    /// Defines a while-loop.
    While {
        /// The expression that has to evaluate to true while running.
        condition:  Expr,
        /// The block to run every iteration.
        consequent: Box<Block>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the while-loop in the source text.
        range: TextRange,
    },
    /// Defines a parallel block (i.e., multiple branches run in parallel).
    Parallel {
        /// The (optional) identifier to which to write the result of the parallel statement.
        result: Option<Identifier>,
        /// The code blocks to run in parallel. This may either be a Block or an On-statement.
        blocks: Vec<Block>,
        /// The merge-strategy used in the parallel statement.
        merge:  Option<Identifier>,

        /// Reference to the variable to which the Parallel writes.
        st_entry: Option<Rc<RefCell<VarEntry>>>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the parallel-statement in the source text.
        range: TextRange,
    },

    /// Defines a variable definition (i.e., `let <name> := <expr>`).
    LetAssign {
        /// The name of the variable referenced.
        name:  Identifier,
        /// The expression that gives a value to the assignment.
        value: Expr,

        /// Reference to the variable to which the let-assign writes.
        st_entry: Option<Rc<RefCell<VarEntry>>>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the let-assign statement in the source text.
        range: TextRange,
    },
    /// Defines an assignment (i.e., `<name> := <expr>`).
    Assign {
        /// The name of the variable referenced.
        name:  Identifier,
        /// The expression that gives a value to the assignment.
        value: Expr,

        /// Reference to the variable to which the assign writes.
        st_entry: Option<Rc<RefCell<VarEntry>>>,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the assignment in the source text.
        range: TextRange,
    },
    /// Defines a loose expression.
    Expr {
        /// The expression to call.
        expr:      Expr,
        /// The data type of this expression. Relevant for popping or not.
        data_type: DataType,

        /// A list of attributes attached to this statement.
        attrs: Vec<Attribute>,
        /// The range of the expression statement in the source text.
        range: TextRange,
    },

    /// A special, compile-time only statement that may be used to `mem::take` statements.
    Empty {},
}

impl Stmt {
    /// Creates a new Import node with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `name`: The name of the package to import (as an identifier).
    /// - `version`: The literal with the package version (i.e., should 'Literal::Semver'). 'latest' should be assumed if the user did not specify it.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Stmt::Import` instance.
    #[inline]
    pub fn new_import(name: Identifier, version: Literal, range: TextRange) -> Self {
        Self::Import { name, version, st_funcs: None, st_classes: None, range, attrs: Vec::new() }
    }

    /// Creates a new FuncDef node with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `ident`: The name of the function, as an identifier.
    /// - `params`: The parameters of the function, as identifiers.
    /// - `code`: The code to execute when running this function.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Stmt::FuncDef` instance.
    #[inline]
    pub fn new_funcdef(ident: Identifier, params: Vec<Identifier>, code: Box<Block>, range: TextRange) -> Self {
        Self::FuncDef { ident, params, code, st_entry: None, range, attrs: Vec::new() }
    }

    /// Creates a new ClassDef node with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `ident`: The name of the class, as an identifier.
    /// - `props`: The properties of the class, as (identifier, type) pairs.
    /// - `methods`: The methods belonging to this class, as a vector of function definitions.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Stmt::ClassDef` instance.
    #[inline]
    pub fn new_classdef(ident: Identifier, props: Vec<Property>, methods: Vec<Box<Stmt>>, range: TextRange) -> Self {
        Self::ClassDef { ident, props, methods, st_entry: None, symbol_table: SymbolTable::new(), range, attrs: Vec::new() }
    }

    /// Creates a new Return node with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `expr`: An optional expression to return from the function.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Stmt::Return` instance.
    #[inline]
    pub fn new_return(expr: Option<Expr>, range: TextRange) -> Self {
        Self::Return { expr, data_type: DataType::Any, output: HashSet::new(), range, attrs: Vec::new() }
    }

    /// Creates a new Parallel node with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `result`: An optional identifier to which this Parallel may write its result.
    /// - `blocks`: The codeblocks to run in parallel.
    /// - `merge`: The merge strategy to use for this Parallel statement.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Stmt::Parallel` instance.
    #[inline]
    pub fn new_parallel(result: Option<Identifier>, blocks: Vec<Block>, merge: Option<Identifier>, range: TextRange) -> Self {
        Self::Parallel { result, blocks, merge, st_entry: None, range, attrs: Vec::new() }
    }

    /// Creates a new LetAssign node with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `name`: The identifier of the variable to write to and initialize.
    /// - `value`: The value to write.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Stmt::LetAssign` instance.
    #[inline]
    pub fn new_letassign(name: Identifier, value: Expr, range: TextRange) -> Self {
        Self::LetAssign { name, value, st_entry: None, range, attrs: Vec::new() }
    }

    /// Creates a new Assign node with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `name`: The identifier of the variable to write to.
    /// - `value`: The value to write.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Stmt::LetAssign` instance.
    #[inline]
    pub fn new_assign(name: Identifier, value: Expr, range: TextRange) -> Self {
        Self::Assign { name, value, st_entry: None, range, attrs: Vec::new() }
    }

    /// Creates a new Expr node with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `expr`: The Expr to wrap.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Stmt::Expr` instance.
    #[inline]
    pub fn new_expr(expr: Expr, range: TextRange) -> Self { Self::Expr { expr, data_type: DataType::Any, range, attrs: Vec::new() } }
}

impl Default for Stmt {
    #[inline]
    fn default() -> Self { Self::Empty {} }
}

impl Node for Stmt {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange {
        use Stmt::*;
        match self {
            Attribute(attr) => attr.range(),
            AttributeInner(attr) => attr.range(),

            Block { block, .. } => block.range(),

            Import { range, .. } => range,
            FuncDef { range, .. } => range,
            ClassDef { range, .. } => range,
            Return { range, .. } => range,

            If { range, .. } => range,
            For { range, .. } => range,
            While { range, .. } => range,
            Parallel { range, .. } => range,

            LetAssign { range, .. } => range,
            Assign { range, .. } => range,
            Expr { range, .. } => range,

            Empty {} => &NONE_RANGE,
        }
    }
}



/// Defines a (name, type) pair in a class definition.
#[derive(Clone, Debug)]
pub struct Property {
    /// The name of the property.
    pub name:      Identifier,
    /// The type of the property.
    pub data_type: DataType,

    /// Entry that refers to this property.
    pub st_entry: Option<Rc<RefCell<VarEntry>>>,

    /// The range of the property in the source text.
    pub range: TextRange,
}

impl Property {
    /// Constructor for the Property that sets a few auxillary fields to default values.
    ///
    /// # Arguments
    /// - `name`: The name of the property (as an identifier).
    /// - `data_type`: The DataType of the property.
    /// - `range`: The TextRange that links this node back to the original source text.
    ///
    /// # Returns
    /// A new Property instance.
    #[inline]
    pub fn new(name: Identifier, data_type: DataType, range: TextRange) -> Self { Self { name, data_type, st_entry: None, range } }
}

impl Node for Property {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange { &self.range }
}



/// Defines an expression.
#[derive(Clone, Debug, EnumDebug)]
pub enum Expr {
    /// Casts between two functions types.
    Cast {
        /// The expression to cast
        expr:   Box<Expr>,
        /// The type to cast to
        target: DataType,

        /// The range of the call-expression in the source text.
        range: TextRange,
    },

    /// A function call.
    Call {
        /// The thing that we're calling - obviously, this must be something with a function type.
        expr: Box<Expr>,
        /// The list of arguments for this call.
        args: Vec<Box<Expr>>,

        /// Reference to the call's function entry.
        st_entry:  Option<Rc<RefCell<FunctionEntry>>>,
        /// The locations where this Call is allowed to run based on the location of the datasets.
        locations: AllowedLocations,
        /// If this call takes in Data or IntermediateResult, then this field will list their names. Used to only ever be the case if this call is an external call, but no more, since we're also interested in tracking this for things like `commit_result`.
        input:     HashSet<Data>,
        /// The intermediate result that this Call creates, if any. Used to only ever be the case if this call is an external call, but no more, since we're also interested in tracking this for things like `commit_result`.
        result:    HashSet<Data>,
        /// Metadata for this call. Only used for external calls.
        metadata:  HashSet<Metadata>,

        /// The range of the call-expression in the source text.
        range: TextRange,
    },
    /// An array expression.
    Array {
        /// The value in the array.
        values:    Vec<Box<Expr>>,
        /// The type of the Array.
        data_type: DataType,

        /// The range of the array-expression in the source text.
        range: TextRange,
    },
    /// An ArrayIndex expression.
    ArrayIndex {
        /// The (array) expression that is indexed.
        array:     Box<Expr>,
        /// The indexing expression.
        index:     Box<Expr>,
        /// The type of the returned value.
        data_type: DataType,

        /// The range of the index-expression in the source text.
        range: TextRange,
    },
    /// Bakery-specific Pattern expression.
    Pattern {
        /// The expressions in this pattern.
        exprs: Vec<Box<Expr>>,

        /// The range of the pattern-expression in the source text.
        range: TextRange,
    },

    /// A unary operator.
    UnaOp {
        /// The operator to execute.
        op:   UnaOp,
        /// The expression.
        expr: Box<Expr>,

        /// The range of the unary operator in the source text.
        range: TextRange,
    },
    /// A binary operator.
    BinOp {
        /// The operator to execute.
        op:  BinOp,
        /// The lefthandside expression.
        lhs: Box<Expr>,
        /// The righthandside expression.
        rhs: Box<Expr>,

        /// The range of the binary operator-expression in the source text.
        range: TextRange,
    },
    /// A special case of a binary operator that implements projection.
    Proj {
        /// The lefthandside expression.
        lhs: Box<Expr>,
        /// The righthandside expression.
        rhs: Box<Expr>,

        /// Reference to the entry that this projection points to.
        st_entry: Option<SymbolTableEntry>,

        /// The range of the projection-expression in the source text.
        range: TextRange,
    },

    /// An instance expression (i.e., `new ...`).
    Instance {
        /// The identifier of the class to instantiate.
        name: Identifier,
        /// The parameters to instantiate it with, as (parameter_name, value).
        properties: Vec<PropertyExpr>,

        /// The reference to the class we instantiate.
        st_entry: Option<Rc<RefCell<ClassEntry>>>,

        /// The range of the instance-expression in the source text.
        range: TextRange,
    },
    /// A variable reference.
    VarRef {
        /// The identifier of the referenced variable.
        name: Identifier,

        /// The entry referring to the variable referred.
        st_entry: Option<Rc<RefCell<VarEntry>>>,
    },
    /// An identifier is like a variable reference but even weaker (i.e., does not expliticly link to anything - just as a placeholder for certain functions).
    Identifier {
        /// The identifier that this expression represents.
        name: Identifier,

        /// The entry referring to the function referred. This only happens when used as identifier in a call expression.
        st_entry: Option<Rc<RefCell<FunctionEntry>>>,
    },
    /// A literal expression.
    Literal {
        /// The nested Literal.
        literal: Literal,
    },

    /// A special, compile-time only expression that may be used to `mem::take` statements.
    Empty {},
}

impl Default for Expr {
    #[inline]
    fn default() -> Self { Self::Empty {} }
}

impl Expr {
    /// Creates a new Cast expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `expr`: The expression to cast.
    /// - `target`: The target type to cast to.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Expr::Cast` instance.
    #[inline]
    pub fn new_cast(expr: Box<Expr>, target: DataType, range: TextRange) -> Self { Self::Cast { expr, target, range } }

    /// Creates a new Call expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `expr`: The expression that produces the object that we call.
    /// - `args`: The arguments to call it with.
    /// - `range`: The TextRange that relates this node to the source text.
    /// - `locations`: The list of locations (as an AllowedLocation) where the call may be executed.
    ///
    /// # Returns
    /// A new `Expr::Call` instance.
    #[inline]
    pub fn new_call(expr: Box<Expr>, args: Vec<Box<Expr>>, range: TextRange, locations: AllowedLocations) -> Self {
        Self::Call { expr, args, st_entry: None, locations, input: HashSet::new(), result: HashSet::new(), metadata: HashSet::new(), range }
    }

    /// Creates a new Array expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `values`: The list of values that make up this Array.
    /// - `range`: The TextRange that links this Array to the source text.
    #[inline]
    pub fn new_array(values: Vec<Box<Expr>>, range: TextRange) -> Self { Self::Array { values, data_type: DataType::Any, range } }

    /// Creates a new ArrayIndex expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `array`: The expression that evaluates to the Array.
    /// - `index`: The expression that evaluates to the Array's index.
    /// - `range`: The TextRange that links this Array to the source text.
    #[inline]
    pub fn new_array_index(array: Box<Expr>, index: Box<Expr>, range: TextRange) -> Self {
        Self::ArrayIndex { array, index, data_type: DataType::Any, range }
    }

    /// Creates a new UnaOp expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `op`: The unary operator that this expression operates.
    /// - `expr`: The expression to execute the unary operation on.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Expr::UnaOp` instance.
    #[inline]
    pub fn new_unaop(op: UnaOp, expr: Box<Expr>, range: TextRange) -> Self { Self::UnaOp { op, expr, range } }

    /// Creates a new BinOp expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `op`: The binary operator that this expression operates.
    /// - `lhs`: The lefthand-side expression to execute the binary operation on.
    /// - `rhs`: The righthand-side expression to execute the binary operation on.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Expr::BinOp` instance.
    #[inline]
    pub fn new_binop(op: BinOp, lhs: Box<Expr>, rhs: Box<Expr>, range: TextRange) -> Self { Self::BinOp { op, lhs, rhs, range } }

    /// Creates a new Proj expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `lhs`: The left-hand side expression containing a nested projection or an identifier.
    ///
    /// # Returns
    /// A new `Expr::Proj` instance.
    #[inline]
    pub fn new_proj(lhs: Box<Expr>, rhs: Box<Expr>, range: TextRange) -> Self { Self::Proj { lhs, rhs, st_entry: None, range } }

    /// Creates a new Instance expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `name`: The name of the class that is being instantiated.
    /// - `properties`: The properties to instantiate it with.
    /// - `range`: The TextRange that relates this node to the source text.
    ///
    /// # Returns
    /// A new `Expr::Instance` instance.
    #[inline]
    pub fn new_instance(name: Identifier, properties: Vec<PropertyExpr>, range: TextRange) -> Self {
        Self::Instance { name, properties, st_entry: None, range }
    }

    /// Creates a new VarRef expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `name`: The name of the variable that is being referenced.
    ///
    /// # Returns
    /// A new `Expr::VarRef` instance.
    #[inline]
    pub fn new_varref(name: Identifier) -> Self { Self::VarRef { name, st_entry: None } }

    /// Creates a new Identifier expression with some auxillary fields set to empty.
    ///
    /// # Arguments
    /// - `name`: The name of the identifier that is being stored here.
    ///
    /// # Returns
    /// A new `Expr::Identifier` instance.
    #[inline]
    pub fn new_identifier(name: Identifier) -> Self { Self::Identifier { name, st_entry: None } }
}

impl Node for Expr {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange {
        use Expr::*;
        match self {
            Cast { range, .. } => range,

            Call { range, .. } => range,
            Array { range, .. } => range,
            ArrayIndex { range, .. } => range,
            Pattern { range, .. } => range,

            UnaOp { range, .. } => range,
            BinOp { range, .. } => range,
            Proj { range, .. } => range,

            Instance { range, .. } => range,
            VarRef { name, .. } => name.range(),
            Identifier { name, .. } => name.range(),
            Literal { literal } => literal.range(),

            Empty {} => &NONE_RANGE,
        }
    }
}



/// Defines a simple enum that is either a Data or an IntermediateResult.
#[derive(Clone, Debug, EnumDebug, Eq, Hash, PartialEq)]
pub enum Data {
    /// It's a dataset (with the given name)
    Data(String),
    /// It's an intermediate result (with the given name)
    IntermediateResult(String),
}
impl From<Data> for specifications::data::DataName {
    #[inline]
    fn from(value: Data) -> Self {
        match value {
            Data::Data(name) => Self::Data(name),
            Data::IntermediateResult(name) => Self::IntermediateResult(name),
        }
    }
}



/// Defines a common enum for both operator types.
#[derive(Clone, Debug, EnumDebug)]
pub enum Operator {
    /// Defines a unary operator.
    Unary(UnaOp),
    /// Defines a binary operator.
    Binary(BinOp),
}

impl Operator {
    /// Returns the binding power of this operator.
    ///
    /// A higher power means that it binds stronger (i.e., has higher precedence).
    #[allow(dead_code)]
    #[inline]
    pub fn binding_power(&self) -> (u8, u8) {
        match &self {
            Operator::Unary(o) => o.binding_power(),
            Operator::Binary(o) => o.binding_power(),
        }
    }
}

impl Node for Operator {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange {
        use Operator::*;
        match self {
            Unary(u) => u.range(),
            Binary(b) => b.range(),
        }
    }
}

impl Display for Operator {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
        use Operator::*;
        match self {
            Unary(o) => write!(f, "{o}"),
            Binary(o) => write!(f, "{o}"),
        }
    }
}



/// Defines unary operators for this crate.
#[derive(Clone, Debug, EnumDebug)]
pub enum UnaOp {
    /// The '[' operator (index)
    Idx { range: TextRange },
    /// The `!` operator (logical inversion)
    Not { range: TextRange },
    /// The `-` operator (negation)
    Neg { range: TextRange },
    /// The '(' operator (prioritize)
    Prio { range: TextRange },
}

impl UnaOp {
    /// Returns the binding power of this operator.
    ///
    /// A higher power means that it binds stronger (i.e., has higher precedence).
    #[inline]
    pub fn binding_power(&self) -> (u8, u8) {
        use UnaOp::*;
        match &self {
            Not { .. } => (0, 11),
            Neg { .. } => (0, 11),
            Idx { .. } => (11, 0),
            Prio { .. } => (0, 0), // Handled seperatly by pratt parser.
        }
    }
}

impl Node for UnaOp {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange {
        use UnaOp::*;
        match self {
            Not { range } => range,
            Neg { range } => range,
            Idx { range } => range,
            Prio { range } => range,
        }
    }
}

impl Display for UnaOp {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
        use UnaOp::*;
        match self {
            Idx { .. } => write!(f, "["),
            Not { .. } => write!(f, "!"),
            Neg { .. } => write!(f, "-"),
            Prio { .. } => write!(f, "("),
        }
    }
}



/// Defines binary operators for this crate.
#[derive(Clone, Debug, EnumDebug)]
pub enum BinOp {
    /// The `&&` operator (logical and)
    And { range: TextRange },
    /// The `||` operator (logical or)
    Or { range: TextRange },

    /// The `+` operator (addition)
    Add { range: TextRange },
    /// The `-` operator (subtraction)
    Sub { range: TextRange },
    /// The `*` operator (multiplication)
    Mul { range: TextRange },
    /// The `/` operator (division)
    Div { range: TextRange },
    /// The '%' operator (modulo)
    Mod { range: TextRange },

    /// The `==` operator (equality)
    Eq { range: TextRange },
    /// The `!=` operator (not equal to)
    Ne { range: TextRange },
    /// The `<` operator (less than)
    Lt { range: TextRange },
    /// The `<=` operator (less than or equal to)
    Le { range: TextRange },
    /// The `>` operator (greater than)
    Gt { range: TextRange },
    /// The `>=` operator (greater than or equal to)
    Ge { range: TextRange },
    // /// The `.` operator (projection)
    // Proj{ range: TextRange },
}

impl BinOp {
    /// Returns the binding power of this operator.
    ///
    /// A higher power means that it binds stronger (i.e., has higher precedence).
    #[inline]
    pub fn binding_power(&self) -> (u8, u8) {
        match &self {
            BinOp::And { .. } | BinOp::Or { .. } => (1, 2),  // Conditional
            BinOp::Eq { .. } | BinOp::Ne { .. } => (3, 4),   // Equality
            BinOp::Lt { .. } | BinOp::Gt { .. } => (5, 6),   // Comparison
            BinOp::Le { .. } | BinOp::Ge { .. } => (5, 6),   // Comparison
            BinOp::Add { .. } | BinOp::Sub { .. } => (7, 8), // Terms
            BinOp::Mul { .. } | BinOp::Div { .. } | BinOp::Mod { .. } => (9, 10), // Factors
                                                              // BinOp::Proj{ .. }                                      => (13, 14), // Nesting
        }
    }
}

impl Node for BinOp {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange {
        use BinOp::*;
        match self {
            And { range } => range,
            Or { range } => range,

            Add { range } => range,
            Sub { range } => range,
            Mul { range } => range,
            Div { range } => range,
            Mod { range } => range,

            Eq { range } => range,
            Ne { range } => range,
            Lt { range } => range,
            Le { range } => range,
            Gt { range } => range,
            Ge { range } => range,
            // Proj{ range } => range,
        }
    }
}

impl Display for BinOp {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
        use BinOp::*;
        match self {
            And { .. } => write!(f, "&&"),
            Or { .. } => write!(f, "||"),

            Add { .. } => write!(f, "+"),
            Sub { .. } => write!(f, "-"),
            Mul { .. } => write!(f, "*"),
            Div { .. } => write!(f, "/"),
            Mod { .. } => write!(f, "%"),

            Eq { .. } => write!(f, "=="),
            Ne { .. } => write!(f, "!="),
            Lt { .. } => write!(f, "<"),
            Le { .. } => write!(f, "<="),
            Gt { .. } => write!(f, ">"),
            Ge { .. } => write!(f, ">="),
            // Proj{ .. } => write!(f, "."),
        }
    }
}



/// Defines an (identifier, expr) pair.
#[derive(Clone, Debug)]
pub struct PropertyExpr {
    /// The property that is referenced.
    pub name:  Identifier,
    /// The value of the referenced property.
    pub value: Box<Expr>,

    /// The range of the proprety expression in the source text.
    pub range: TextRange,
}

impl Node for PropertyExpr {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange { &self.range }
}



/// Defines an identifier.
#[derive(Clone, Debug)]
pub struct Identifier {
    /// TThe string value of this identifier.
    pub value: String,
    /// The range of the identifier in the source text.
    pub range: TextRange,
}

impl Identifier {
    /// Constructor for the Identifier that pre-initializes it with some things.
    ///
    /// # Arguments
    /// - `value`: The string value of the identifier.
    /// - `range`: The complete range of the entire identifier.
    ///
    /// # Returns
    /// A new Identifier instance with the given values.
    #[inline]
    pub fn new(value: String, range: TextRange) -> Self { Self { value, range } }
}

impl Node for Identifier {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange { &self.range }
}

// /// Defines an identifier.
// #[derive(Clone, Debug)]
// pub enum Identifier {
//     /// Defines a simple identifier of only one word.
//     Name {
//         /// The value of the identifier itself.
//         value : String,

//         /// The entry to which this variable references.
//         st_entry : Option<Rc<RefCell<STVarEntry>>>,

//         /// The range of the identifier in the source text.
//         range : TextRange,
//     },

//     /// Defines a more complex identifier that is a projection.
//     Proj {
//         /// The value of the lhs of the projection.
//         lhs : Box<Self>,
//         /// The value of the rhs of the projection.
//         rhs : Box<Self>,

//         /// The class to which the left-hand side references.
//         st_entry : Option<Rc<RefCell<STClassEntry>>>,

//         /// The range of the identifier in the source text.
//         range : TextRange,
//     }
// }

// impl Identifier {
//     /// Constructor for the Identifier that initializes some auxillary fields to empty.
//     ///
//     /// # Arguments
//     /// - `value`: The value (i.e., identifier) of the identifier.
//     /// - `range`: The range of the identifier in the source text.
//     ///
//     /// # Returns
//     /// A new Identifier instance with the given value and range.
//     #[inline]
//     pub fn new_name(value: String, range: TextRange) -> Self {
//         Self::Name {
//             value,

//             st_entry : None,

//             range,
//         }
//     }

//     /// Constructor for the Identifier that initializes it as a project operator (and sets some auxillary fields to empty).
//     ///
//     /// # Arguments
//     /// - `lhs`: The left-hand side value of the identifier.
//     /// - `rhs`: The right-hand side value of the identifier.
//     /// - `range`: The range of the identifier in the source text.
//     ///
//     /// # Returns
//     /// A new Identifier instance with the given value and range.
//     #[inline]
//     pub fn new_proj(lhs: Box<Self>, rhs: Box<Self>, range: TextRange) -> Self {
//         Self::Proj {
//             lhs,
//             rhs,

//             st_entry : None,

//             range,
//         }
//     }



//     /// Sets the st_entry of this Identifier as if this is an `Identifier::Name`.
//     ///
//     /// # Arguments
//     /// - `entry`: The entry to set.
//     ///
//     /// # Returns
//     /// Nothing, but does change the internal value.
//     ///
//     /// # Panics
//     /// This function panics if this was an `Identifier::Proj` instead of an `Identifier::Name`.
//     #[inline]
//     pub fn set_entry(&mut self, entry: Rc<RefCell<STVarEntry>>) {
//         if let Identifier::Name{ ref mut st_entry, .. } = self {
//             *st_entry = Some(entry);
//         } else {
//             panic!("Cannot set entry value of Name identifier (is Proj identifier)");
//         }
//     }

//     /// Builds a complete identifier from the parts.
//     ///
//     /// # Returns
//     /// Either the normal value if this is an `Identifier::Name`, or else a combination of all nested identifiers separated by dots if it is an `Identifier::Proj`.
//     #[inline]
//     pub fn full_value(&self) -> String {
//         match self {
//             Identifier::Name{ value, .. }    => value.clone(),
//             Identifier::Proj{ lhs, rhs, .. } => format!("{}.{}", lhs.full_value(), rhs.full_value()),
//         }
//     }

//     /// Returns the value of the identifier if this is a Name identifier.
//     ///
//     /// # Returns
//     /// A string reference to the identifier value.
//     ///
//     /// # Panics
//     /// This function panics if this was an `Identifier::Proj` instead of an `Identifier::Name`.
//     #[inline]
//     pub fn value(&self) -> &str {
//         if let Identifier::Name{ value, .. } = self {
//             value
//         } else {
//             panic!("Cannot set entry value of Name identifier (is Proj identifier)");
//         }
//     }

//     /// Returns the variable entry of the identifier if this is a Name identifier.
//     ///
//     /// # Returns
//     /// An STVarEntry that represents the referenced variable.
//     ///
//     /// # Panics
//     /// This function panics if this was an `Identifier::Proj` instead of an `Identifier::Name`.
//     #[inline]
//     pub fn st_entry(&self) -> &Option<Rc<RefCell<STVarEntry>>> {
//         if let Identifier::Name{ st_entry, .. } = self {
//             st_entry
//         } else {
//             panic!("Cannot get entry value of Name identifier (is Proj identifier)");
//         }
//     }
// }

// impl Node for Identifier {
//     /// Returns the node's source range.
//     #[inline]
//     fn range(&self) -> &TextRange {
//         use Identifier::*;
//         match self {
//             Name{ range, .. } => range,
//             Proj{ range, .. } => range,
//         }
//     }
// }



/// Defines a literal constant.
#[derive(Clone, Debug, EnumDebug)]
pub enum Literal {
    /// Defines the null literal.
    Null {
        /// The range of the boolean in the source text.
        range: TextRange,
    },

    /// Defines a boolean literal.
    Boolean {
        /// The value of the Boolean.
        value: bool,

        /// The range of the boolean in the source text.
        range: TextRange,
    },

    /// Defines an integral literal.
    Integer {
        /// The value of the Integer.
        value: i64,

        /// The range of the integer in the source text.
        range: TextRange,
    },

    /// Defines a floating-point literal.
    Real {
        /// The value of the Real.
        value: f64,

        /// The range of the real in the source text.
        range: TextRange,
    },

    /// Defines a String literal.
    String {
        /// The value of the String.
        value: String,

        /// The range of the string in the source text.
        range: TextRange,
    },

    /// Defines a SemVer literal.
    Semver {
        /// We did not parse the semver _yet_.
        value: String,

        range: TextRange,
    },

    /// Defines a Void literal (no value).
    Void {
        /// The range of the void in the source text.
        range: TextRange,
    },
}

impl Literal {
    /// Returns the value of the Literal as if it is a Boolean.
    ///
    /// # Returns
    /// The value of this Boolean literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not a Boolean.
    #[inline]
    pub fn as_bool(&self) -> bool {
        use Literal::*;
        if let Boolean { value, .. } = self {
            *value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Boolean'", self.data_type());
        }
    }

    /// Returns a reference to the value of the Literal as if it is a Boolean.
    ///
    /// # Returns
    /// A reference to the value of this Boolean literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not a Boolean.
    #[inline]
    pub fn as_bool_ref(&self) -> &bool {
        use Literal::*;
        if let Boolean { value, .. } = self {
            value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Boolean'", self.data_type());
        }
    }

    /// Returns a muteable reference to the value of the Literal as if it is a Boolean.
    ///
    /// # Returns
    /// A muteable reference to the value of this Boolean literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not a Boolean.
    #[inline]
    pub fn as_bool_mut(&mut self) -> &mut bool {
        use Literal::*;
        if let Boolean { ref mut value, .. } = self {
            value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Boolean'", self.data_type());
        }
    }

    /// Returns the value of the Literal as if it is an Integer.
    ///
    /// # Returns
    /// The value of this Integer literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not an Integer.
    #[inline]
    pub fn as_int(&self) -> i64 {
        use Literal::*;
        if let Integer { value, .. } = self {
            *value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Integer'", self.data_type());
        }
    }

    /// Returns a reference to the value of the Literal as if it is an Integer.
    ///
    /// # Returns
    /// A reference to the value of this Integer literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not an Integer.
    #[inline]
    pub fn as_int_ref(&self) -> &i64 {
        use Literal::*;
        if let Integer { value, .. } = self {
            value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Integer'", self.data_type());
        }
    }

    /// Returns a muteable reference to the value of the Literal as if it is an Integer.
    ///
    /// # Returns
    /// A muteable reference to the value of this Integer literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not an Integer.
    #[inline]
    pub fn as_int_mut(&mut self) -> &mut i64 {
        use Literal::*;
        if let Integer { ref mut value, .. } = self {
            value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Integer'", self.data_type());
        }
    }

    /// Returns the value of the Literal as if it is a Real.
    ///
    /// # Returns
    /// The value of this Real literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not a Real.
    #[inline]
    pub fn as_real(&self) -> f64 {
        use Literal::*;
        if let Real { value, .. } = self {
            *value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Real'", self.data_type());
        }
    }

    /// Returns a reference to the value of the Literal as if it is a Real.
    ///
    /// # Returns
    /// A reference to the value of this Real literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not a Real.
    #[inline]
    pub fn as_real_ref(&self) -> &f64 {
        use Literal::*;
        if let Real { value, .. } = self {
            value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Real'", self.data_type());
        }
    }

    /// Returns a muteable reference to the value of the Literal as if it is a Real.
    ///
    /// # Returns
    /// A muteable reference to the value of this Real literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not a Real.
    #[inline]
    pub fn as_real_mut(&mut self) -> &mut f64 {
        use Literal::*;
        if let Real { ref mut value, .. } = self {
            value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Real'", self.data_type());
        }
    }

    /// Returns a reference to the value of the Literal as if it is a String.
    ///
    /// # Returns
    /// A reference to the value of this String literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not a String.
    #[inline]
    pub fn as_string_ref(&self) -> &str {
        use Literal::*;
        if let String { value, .. } = self {
            value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'String'", self.data_type());
        }
    }

    /// Returns a muteable reference to the value of the Literal as if it is a String.
    ///
    /// # Returns
    /// A muteable reference to the value of this String literal.
    ///
    /// # Panics
    /// This function panics if the Literal is not a String.
    #[inline]
    pub fn as_string_mut(&mut self) -> &mut str {
        use Literal::*;
        if let String { ref mut value, .. } = self {
            value
        } else {
            panic!("Attempted to get Literal of type '{}' as 'String'", self.data_type());
        }
    }

    /// Returns a (parsed) semantic version from the Literal as if it is a Semver.
    ///
    /// # Returns
    /// A freshly parsed (i.e., non-trivial retrieval) of a Version.
    ///
    /// # Errors
    /// This function errors if we could not parse the Semver as a Version.
    ///
    /// # Panics
    /// This function panics if the Literal is not a Semver.
    #[inline]
    pub fn as_version(&self) -> Result<Version, ParseError> {
        use Literal::*;
        if let Semver { value, .. } = self {
            Version::from_str(value)
        } else {
            panic!("Attempted to get Literal of type '{}' as 'Semver'", self.data_type());
        }
    }

    /// Returns the data type of this Literal.
    #[inline]
    pub fn data_type(&self) -> DataType {
        use Literal::*;
        match self {
            Null { .. } => DataType::Any,
            Boolean { .. } => DataType::Boolean,
            Integer { .. } => DataType::Integer,
            Real { .. } => DataType::Real,
            String { .. } => DataType::String,
            Semver { .. } => DataType::Semver,
            Void { .. } => DataType::Void,
        }
    }
}

impl Node for Literal {
    /// Returns the node's source range.
    #[inline]
    fn range(&self) -> &TextRange {
        use Literal::*;
        match self {
            Null { range, .. } => range,
            Boolean { range, .. } => range,
            Integer { range, .. } => range,
            Real { range, .. } => range,
            String { range, .. } => range,
            Semver { range, .. } => range,
            Void { range, .. } => range,
        }
    }
}