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
use std::{
collections::BTreeMap,
fmt::{Display, Error, Formatter},
fs::read_to_string,
path::PathBuf,
process::exit,
};
use crate::{
mir::{
MirDeclaration, MirExpression, MirFunction, MirProgram, MirStatement, MirStructure, MirType,
},
parse, Identifier, StringLiteral, Target,
};
#[derive(Clone, Debug)]
pub struct HirProgram(Vec<HirDeclaration>, i32);
impl HirProgram {
pub const MINIMUM_MEMORY_SIZE: i32 = 128;
pub fn new(decls: Vec<HirDeclaration>, memory_size: i32) -> Self {
Self(decls, memory_size)
}
pub fn get_declarations(&self) -> &Vec<HirDeclaration> {
let Self(decls, _) = self;
decls
}
pub fn extend_declarations(&mut self, decls: &Vec<HirDeclaration>) {
self.0.extend(decls.clone())
}
fn get_memory_size(&self) -> i32 {
let Self(_, memory_size) = self;
*memory_size
}
pub fn use_std(&self) -> bool {
for decl in self.get_declarations() {
match decl {
HirDeclaration::NoStd => return false,
HirDeclaration::RequireStd => return true,
_ => {}
}
}
false
}
pub fn generate_docs(
&self,
filename: String,
target: &impl Target,
constants: &mut BTreeMap<String, HirConstant>,
ignore_header: bool,
) -> String {
let mut header = String::new();
if !ignore_header {
header = format!("# {}\n", filename.trim())
}
let mut content = String::new();
for decl in self.get_declarations() {
match decl {
HirDeclaration::DocumentHeader(s) => {
if !ignore_header {
header += s;
header += "\n";
}
continue;
}
HirDeclaration::Structure(structure) => content += &structure.generate_docs(),
HirDeclaration::Function(function) => content += &function.generate_docs(false),
HirDeclaration::Constant(doc, name, constant) => {
content += &format!("### *const* **{}** = {}\n---", name, constant);
if let Some(s) = doc {
content += "\n";
content += &s.trim();
}
}
HirDeclaration::If(cond, code) => {
if let Ok(val) = cond.to_value(self.get_declarations(), constants, target) {
if val != 0.0 {
content +=
&code.generate_docs(filename.clone(), target, constants, true);
}
}
}
HirDeclaration::IfElse(cond, then_code, else_code) => {
if let Ok(val) = cond.to_value(self.get_declarations(), constants, target) {
if val != 0.0 {
content +=
&then_code.generate_docs(filename.clone(), target, constants, true);
} else {
content +=
&else_code.generate_docs(filename.clone(), target, constants, true);
}
}
}
_ => continue,
}
content += "\n";
}
header + &content
}
pub fn compile(
&mut self,
cwd: &PathBuf,
target: &impl Target,
constants: &mut BTreeMap<String, HirConstant>,
) -> Result<MirProgram, HirError> {
let mut mir_decls = Vec::new();
let mut memory_size = self.get_memory_size();
let mut std_required = None;
// Iterate over the declarations and retreive the constants
for decl in self.get_declarations() {
if let HirDeclaration::Constant(_, name, constant) = decl {
constants.insert(name.clone(), constant.clone());
}
}
for decl in self.get_declarations() {
/// The reason we don't handle conditional compilation here
/// is because it does not allow constants to be defined in
/// the `if` statements' body.
match decl {
HirDeclaration::Function(func) => mir_decls.push(MirDeclaration::Function(
func.to_mir_fn(self.get_declarations(), &constants, target)?,
)),
HirDeclaration::Structure(structure) => mir_decls.push(MirDeclaration::Structure(
structure.to_mir_struct(self.get_declarations(), &constants, target)?,
)),
HirDeclaration::RequireStd => {
if let Some(false) = std_required {
return Err(HirError::ConflictingStdReqs);
} else {
std_required = Some(true)
}
}
HirDeclaration::NoStd => {
if let Some(true) = std_required {
return Err(HirError::ConflictingStdReqs);
} else {
std_required = Some(false)
}
}
HirDeclaration::Assert(constant) => {
if constant.to_value(self.get_declarations(), constants, target)? == 0.0 {
return Err(HirError::FailedAssertion(constant.clone()));
}
}
HirDeclaration::Extern(filename) => {
let file_path = cwd.join(filename.clone());
mir_decls.push(MirDeclaration::Extern(file_path))
}
HirDeclaration::Error(err) => return Err(HirError::UserError(err.clone())),
HirDeclaration::If(cond, code) => {
if cond.to_value(self.get_declarations(), constants, target)? != 0.0 {
mir_decls.extend(
code.clone()
.compile(cwd, target, constants)?
.get_declarations(),
);
}
}
HirDeclaration::IfElse(cond, then_code, else_code) => {
if cond.to_value(self.get_declarations(), constants, target)? != 0.0 {
mir_decls.extend(
then_code
.clone()
.compile(cwd, target, constants)?
.get_declarations(),
);
} else {
mir_decls.extend(
else_code
.clone()
.compile(cwd, target, constants)?
.get_declarations(),
);
}
}
HirDeclaration::Memory(size) => {
if *size >= Self::MINIMUM_MEMORY_SIZE {
memory_size = *size;
} else {
return Err(HirError::MemorySizeTooSmall(*size));
}
}
_ => {}
}
}
Ok(MirProgram::new(mir_decls, memory_size))
}
}
#[derive(Clone, Debug)]
pub enum HirError {
/// There are some programs that can't possibly
/// run on a minimum amount of memory. To reduce
/// the incidence of this happening, we check against
/// a minimum memory size.
MemorySizeTooSmall(i32),
/// If a constant is used without it being defined,
/// then throw this error.
ConstantNotDefined(Identifier),
/// If BOTH the `std` and `no_std` flags are used
/// in a program, then there are conflicting requirements
/// for including the standard library. Throw this error
/// if that is the case.
ConflictingStdReqs,
/// If a compile time assertion fails, throw an error
FailedAssertion(HirConstant),
/// This is a user defined error using the `error` flag
UserError(String),
/// This returns an error if a type is not defined. This was
/// specifically implemented for defining the `sizeof` operator.
TypeNotDefined(String),
/// This occurs when a literal expression is cast as a pointer.
/// This isn't ACTUALLY bad, but it's intended to promote type correctness.
CastLiteralAsPointer(HirType),
}
impl Display for HirError {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
Self::MemorySizeTooSmall(n) => write!(
f,
"specified stack + heap memory size '{}' is too small. use '{}' or greater",
n,
HirProgram::MINIMUM_MEMORY_SIZE
),
Self::ConstantNotDefined(name) => write!(f, "constant '{}' is not defined", name),
Self::UserError(err) => write!(f, "{}", err),
Self::ConflictingStdReqs => {
write!(f, "conflicting 'require_std' and 'no_std' flags present")
}
Self::FailedAssertion(assertion) => write!(f, "failed assertion '{}'", assertion),
Self::TypeNotDefined(type_name) => write!(f, "type not defined '{}'", type_name),
Self::CastLiteralAsPointer(t) => write!(f, "cannot cast literal to type '{}'", t),
}
}
}
/// This enum represents a type name in an expression.
/// Take for example the declaration `fn test(x: num) -> &void`.
/// `num` and `&void` are both `HirType` instances.
#[derive(Clone, Debug, PartialEq)]
pub enum HirType {
/// A pointer to another type
Pointer(Box<Self>),
/// The unit type, or the type that represents no
/// return value.
Void,
/// The floating point number type
Float,
/// The boolean type
Boolean,
/// The character type
Character,
/// A user defined type
Structure(Identifier),
}
impl HirType {
/// Get the size of the type on the stack.
/// For primitive types, this is straight forward. For
/// user types, though, we have to search for the structure
/// in the list of declarations and find its type.
pub fn get_size(
&self,
decls: &Vec<HirDeclaration>,
constants: &BTreeMap<Identifier, HirConstant>,
target: &impl Target,
) -> Result<i32, HirError> {
Ok(match self {
// A void type has size zero
Self::Void => 0,
// A pointer, a number, a boolean, and a character
// all have a size of 1 on the stack
Self::Pointer(_) | Self::Float | Self::Boolean | Self::Character => 1,
Self::Structure(name) => {
for decl in decls {
if let HirDeclaration::Structure(structure) = decl {
if name == structure.get_name() {
// Get the size of the structure with the type's name
return structure.get_size(decls, constants, target);
}
}
}
return Err(HirError::TypeNotDefined(name.clone()));
}
})
}
/// Is this type a pointer type?
pub fn is_pointer(&self) -> bool {
match self {
Self::Pointer(_) => true,
_ => false,
}
}
/// Lower this type to the MIR type representation
pub fn to_mir_type(&self) -> MirType {
match self {
Self::Pointer(inner) => inner.to_mir_type().refer(),
Self::Void => MirType::void(),
Self::Float => MirType::float(),
Self::Boolean => MirType::boolean(),
Self::Character => MirType::character(),
Self::Structure(name) => MirType::structure(name.clone()),
}
}
}
impl Display for HirType {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
Self::Pointer(t) => write!(f, "&{}", t),
Self::Void => write!(f, "{}", MirType::VOID),
Self::Float => write!(f, "{}", MirType::FLOAT),
Self::Boolean => write!(f, "{}", MirType::BOOLEAN),
Self::Character => write!(f, "{}", MirType::CHAR),
Self::Structure(name) => write!(f, "{}", name),
}
}
}
/// This type represents all the different flags
/// and definitions that the user has access to,
/// such as fn, const, and struct definitions,
/// and conditional compilation statements.
///
/// All constants are compiled to type float, even
/// characters and other literals.
#[derive(Clone, Debug)]
pub enum HirDeclaration {
/// This adds a docstring to the head of the document
/// that is displayed with the `doc` subcommand.
DocumentHeader(String),
/// Define a constant with an optional docstring.
Constant(Option<String>, Identifier, HirConstant),
/// Define a function
Function(HirFunction),
/// Define a structure
Structure(HirStructure),
/// Use the `assert` compiler flag
Assert(HirConstant),
/// Use the `if` compiler flag to use
/// conditional compilation.
If(HirConstant, HirProgram),
/// Use the `if` compiler flag with an `else` branch
/// to use conditional compilation.
IfElse(HirConstant, HirProgram, HirProgram),
/// Allow the user to throw their own custom errors
Error(String),
/// Include a foreign file using the `extern` flag.
Extern(String),
/// Set the memory used for the stack and heap.
Memory(i32),
/// Mark that the standard library is required for the program
RequireStd,
/// Mark that the standard library is not allowed for the program
NoStd,
/// Do nothing
Pass
}
/// This type represents a user defined structure.
#[derive(Clone, Debug)]
pub struct HirStructure {
/// The optional docstring for the structure
doc: Option<String>,
/// The name of the structure
name: Identifier,
/// The size of the structure on the stack
size: HirConstant,
/// The list of methods for the structure.
methods: Vec<HirFunction>,
/// This represents whether or not the type is
/// movable: if the type requires the copy and
/// drop methods to be called. This allows
/// users to write code with less restrictions
/// for types that don't need to be dropped.
is_movable: bool,
}
impl HirStructure {
pub fn new(
doc: Option<String>,
name: Identifier,
size: HirConstant,
methods: Vec<HirFunction>,
is_movable: bool,
) -> Self {
Self {
doc,
name,
size,
methods,
is_movable,
}
}
/// Get the structure definition's name
fn get_name(&self) -> &Identifier {
&self.name
}
/// Get the size that the structure consumes on the stack
fn get_size(
&self,
decls: &Vec<HirDeclaration>,
constants: &BTreeMap<Identifier, HirConstant>,
target: &impl Target,
) -> Result<i32, HirError> {
// Convert the `size` constant into an integeral value
self.size
.to_value(decls, constants, target)
.and_then(|n| Ok(n as i32))
}
/// Generate the documentation for the structure using the
/// docstring and the docstrings of each method.
fn generate_docs(&self) -> String {
// Add a header for the output markdown
let mut result = format!(
"## *type* **{}**\n",
self.name
);
// If a docstring is defined, then
// add it to the output
if let Some(doc) = &self.doc {
result += &(doc.trim().to_string() + "\n");
}
// Add documentation for each member function
// as a method
for method in &self.methods {
result += &method.generate_docs(true)
}
result
}
/// Convert the HIR structure into its MIR
/// structure representation.
fn to_mir_struct(
&self,
decls: &Vec<HirDeclaration>,
constants: &BTreeMap<Identifier, HirConstant>,
target: &impl Target,
) -> Result<MirStructure, HirError> {
// Convert each method into an MIR function
let mut mir_methods = Vec::new();
for method in &self.methods {
mir_methods.push(method.to_mir_fn(decls, constants, target)?);
}
// Create an MIR structure with this structure's
// name, size, methods, and movability.
Ok(MirStructure::new(
self.name.clone(),
self.size.to_value(decls, constants, target)? as i32,
mir_methods,
self.is_movable,
))
}
}
/// This type represents a user defined function.
#[derive(Clone, Debug, PartialEq)]
pub struct HirFunction {
/// The optional docstring for the function
doc: Option<String>,
/// The name of the function
name: Identifier,
/// The parameters of the function
args: Vec<(Identifier, HirType)>,
/// The functions return type
return_type: HirType,
/// The body of the function
body: Vec<HirStatement>,
}
impl HirFunction {
pub fn new(
doc: Option<String>,
name: Identifier,
args: Vec<(Identifier, HirType)>,
return_type: HirType,
body: Vec<HirStatement>,
) -> Self {
Self {
doc,
name,
args,
return_type,
body,
}
}
/// Generate the documentation for the function.
fn generate_docs(&self, is_method: bool) -> String {
let mut result = if is_method {
// If the function is a method, display the
// function under a bullet point
format!("* *fn* **{}**(", self.name)
} else {
// If the function is not a method, display
// the function under its own header
format!("### *fn* **{}**(", self.name)
};
// For each argument, display its name and type
for (i, (arg_name, arg_type)) in self.args.iter().enumerate() {
result += &format!("*{}*: {}, ", arg_name, arg_type)
}
// Remove the last space and comma from the last argument
if !self.args.is_empty() {
result.pop();
result.pop();
}
// Add the close parantheses
result += ")";
if self.return_type != HirType::Void {
// If the function is a non-void function, add the return type
result += " *->* ";
result += &self.return_type.to_string();
}
result += "\n";
if let Some(doc) = &self.doc {
result += if is_method { " - " } else { "---\n" };
result += &(doc.trim().to_string() + "\n");
}
result
}
/// Convert the HIR function into its MIR equivalent
fn to_mir_fn(
&self,
decls: &Vec<HirDeclaration>,
constants: &BTreeMap<Identifier, HirConstant>,
target: &impl Target,
) -> Result<MirFunction, HirError> {
// Convert each of the argument type to MIR types
let mut mir_args = Vec::new();
for (arg_name, arg_type) in self.args.clone() {
mir_args.push((arg_name.clone(), arg_type.to_mir_type()));
}
// For each statement in the functions body,
// convert it to an MIR statement.
let mut mir_body = Vec::new();
for stmt in self.body.clone() {
mir_body.push(stmt.to_mir_stmt(decls, constants, target)?);
}
Ok(MirFunction::new(
self.name.clone(),
mir_args,
self.return_type.to_mir_type(),
mir_body,
))
}
}
/// This type represents all constant expressions.
#[derive(Clone, Debug, PartialEq)]
pub enum HirConstant {
/// A constant Float
Float(f64),
/// A constant Character
Character(char),
/// A constant Boolean
True,
False,
/// Add two constants
Add(Box<Self>, Box<Self>),
/// Subtract two constants
Subtract(Box<Self>, Box<Self>),
/// Multiply two constants
Multiply(Box<Self>, Box<Self>),
/// Divide two constants
Divide(Box<Self>, Box<Self>),
/// Boolean And two constants
And(Box<Self>, Box<Self>),
/// Boolean Or two constants
Or(Box<Self>, Box<Self>),
/// Boolean Not a constant
Not(Box<Self>),
/// Compare two constants
Greater(Box<Self>, Box<Self>),
Less(Box<Self>, Box<Self>),
GreaterEqual(Box<Self>, Box<Self>),
LessEqual(Box<Self>, Box<Self>),
Equal(Box<Self>, Box<Self>),
NotEqual(Box<Self>, Box<Self>),
/// A named constant
Constant(Identifier),
/// Determines whether a constant is defined
IsDefined(String),
/// The size of a constant
SizeOf(HirType),
/// A constant expression that is contingent on another constant expression
Conditional(Box<Self>, Box<Self>, Box<Self>)
}
impl Display for HirConstant {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
Self::Conditional(cond, then, otherwise) => write!(f, "{} ? {} : {}", cond, then, otherwise),
Self::True => write!(f, "true"),
Self::False => write!(f, "false"),
Self::Float(n) => write!(f, "{}", n),
Self::Character(ch) => write!(f, "'{}'", ch),
Self::Add(l, r) => write!(f, "{}+{}", l, r),
Self::Subtract(l, r) => write!(f, "{}-{}", l, r),
Self::Multiply(l, r) => write!(f, "{}*{}", l, r),
Self::Divide(l, r) => write!(f, "{}/{}", l, r),
Self::And(l, r) => write!(f, "{}&&{}", l, r),
Self::Or(l, r) => write!(f, "{}||{}", l, r),
Self::Greater(l, r) => write!(f, "{}>{}", l, r),
Self::Less(l, r) => write!(f, "{}<{}", l, r),
Self::GreaterEqual(l, r) => write!(f, "{}>={}", l, r),
Self::LessEqual(l, r) => write!(f, "{}<={}", l, r),
Self::Equal(l, r) => write!(f, "{}=={}", l, r),
Self::NotEqual(l, r) => write!(f, "{}!={}", l, r),
Self::Constant(name) => write!(f, "{}", name),
Self::SizeOf(name) => write!(f, "sizeof(\"{}\")", name),
Self::IsDefined(name) => write!(f, "isdef(\"{}\")", name),
Self::Not(expr) => write!(f, "!{}", expr),
}
}
}
impl HirConstant {
/// Find a constants floating point value.
fn to_value(
&self,
decls: &Vec<HirDeclaration>,
constants: &BTreeMap<Identifier, Self>,
target: &impl Target,
) -> Result<f64, HirError> {
Ok(match self {
Self::Conditional(cond, then, otherwise) => if cond.to_value(decls, constants, target)? != 0.0 {
// If the constant condition is true, then use
// the first constant branch
then.to_value(decls, constants, target)?
} else {
// If the constant condition is false, then use
// the second constant branch
otherwise.to_value(decls, constants, target)?
},
Self::True => 1.0,
Self::False => 0.0,
Self::Float(n) => *n,
Self::Character(ch) => *ch as u8 as f64,
Self::And(l, r) => {
if l.to_value(decls, constants, target)? != 0.0
&& r.to_value(decls, constants, target)? != 0.0
{
1.0
} else {
0.0
}
}
Self::Or(l, r) => {
if l.to_value(decls, constants, target)? != 0.0
|| r.to_value(decls, constants, target)? != 0.0
{
1.0
} else {
0.0
}
}
Self::Equal(l, r) => {
if l.to_value(decls, constants, target)? == r.to_value(decls, constants, target)? {
1.0
} else {
0.0
}
}
Self::NotEqual(l, r) => {
if l.to_value(decls, constants, target)? != r.to_value(decls, constants, target)? {
1.0
} else {
0.0
}
}
Self::Greater(l, r) => {
if l.to_value(decls, constants, target)? > r.to_value(decls, constants, target)? {
1.0
} else {
0.0
}
}
Self::Less(l, r) => {
if l.to_value(decls, constants, target)? < r.to_value(decls, constants, target)? {
1.0
} else {
0.0
}
}
Self::GreaterEqual(l, r) => {
if l.to_value(decls, constants, target)? >= r.to_value(decls, constants, target)? {
1.0
} else {
0.0
}
}
Self::LessEqual(l, r) => {
if l.to_value(decls, constants, target)? <= r.to_value(decls, constants, target)? {
1.0
} else {
0.0
}
}
Self::Add(l, r) => {
l.to_value(decls, constants, target)? + r.to_value(decls, constants, target)?
}
Self::Subtract(l, r) => {
l.to_value(decls, constants, target)? - r.to_value(decls, constants, target)?
}
Self::Multiply(l, r) => {
l.to_value(decls, constants, target)? * r.to_value(decls, constants, target)?
}
Self::Divide(l, r) => {
l.to_value(decls, constants, target)? / r.to_value(decls, constants, target)?
}
Self::Constant(name) => match name.as_str() {
"TARGET" => target.get_name() as u8 as f64,
_ => {
if let Some(value) = constants.get(name) {
value.to_value(decls, constants, target)?
} else {
return Err(HirError::ConstantNotDefined(name.clone()));
}
}
},
Self::SizeOf(t) => t.get_size(decls, constants, target)? as f64,
Self::IsDefined(name) => {
if let Some(value) = constants.get(name) {
1.0
} else {
0.0
}
}
Self::Not(constant) => {
if constant.to_value(decls, constants, target)? != 0.0 {
0.0
} else {
1.0
}
}
})
}
}
/// This type represents a statement used in a function body.
/// This includes loops, conditional statements, assignments,
/// and void expressions.
#[derive(Clone, Debug, PartialEq)]
pub enum HirStatement {
/// An HIR let expression with a manually assigned type
Define(Identifier, HirType, HirExpression),
/// An HIR let expression with type inference
AutoDefine(Identifier, HirExpression),
/// A variable assignment
AssignVariable(Identifier, HirExpression),
/// An assignment to a dereferenced address
AssignAddress(HirExpression, HirExpression),
/// An HIR for loop
For(Box<Self>, HirExpression, Box<Self>, Vec<Self>),
/// An HIR while loop
While(HirExpression, Vec<Self>),
/// An HIR if statement
If(HirExpression, Vec<Self>),
/// An HIR if statement with an else clause
IfElse(HirExpression, Vec<Self>, Vec<Self>),
/// An HIR free statement to deallocate memory
Free(HirExpression, HirExpression),
/// Return one or more values at the end of a function
Return(Vec<HirExpression>),
/// Any expression
Expression(HirExpression),
}
impl HirStatement {
/// Lower an HIR statement into an equivalent MIR statement
fn to_mir_stmt(
&self,
decls: &Vec<HirDeclaration>,
constants: &BTreeMap<Identifier, HirConstant>,
target: &impl Target,
) -> Result<MirStatement, HirError> {
Ok(match self {
Self::Define(name, data_type, expr) => MirStatement::Define(
name.clone(),
data_type.to_mir_type(),
expr.to_mir_expr(decls, constants, target)?,
),
Self::AutoDefine(name, expr) => {
MirStatement::AutoDefine(name.clone(), expr.to_mir_expr(decls, constants, target)?)
}
Self::AssignVariable(name, expr) => MirStatement::AssignVariable(
name.clone(),
expr.to_mir_expr(decls, constants, target)?,
),
Self::AssignAddress(addr, expr) => MirStatement::AssignAddress(
addr.to_mir_expr(decls, constants, target)?,
expr.to_mir_expr(decls, constants, target)?,
),
Self::For(pre, cond, post, body) => {
let mut mir_body = Vec::new();
for stmt in body {
mir_body.push(stmt.to_mir_stmt(decls, constants, target)?);
}
MirStatement::For(
Box::new(pre.to_mir_stmt(decls, constants, target)?),
cond.to_mir_expr(decls, constants, target)?,
Box::new(post.to_mir_stmt(decls, constants, target)?),
mir_body,
)
}
Self::While(cond, body) => {
let mut mir_body = Vec::new();
for stmt in body {
mir_body.push(stmt.to_mir_stmt(decls, constants, target)?);
}
MirStatement::While(cond.to_mir_expr(decls, constants, target)?, mir_body)
}
Self::If(cond, body) => {
let mut mir_body = Vec::new();
for stmt in body {
mir_body.push(stmt.to_mir_stmt(decls, constants, target)?);
}
MirStatement::If(cond.to_mir_expr(decls, constants, target)?, mir_body)
}
Self::IfElse(cond, then_body, else_body) => {
// Convert the `then` case to MIR
let mut mir_then_body = Vec::new();
for stmt in then_body {
mir_then_body.push(stmt.to_mir_stmt(decls, constants, target)?);
}
// Convert the `else` case to MIR
let mut mir_else_body = Vec::new();
for stmt in else_body {
mir_else_body.push(stmt.to_mir_stmt(decls, constants, target)?);
}
MirStatement::IfElse(
cond.to_mir_expr(decls, constants, target)?,
mir_then_body,
mir_else_body,
)
}
Self::Return(exprs) => {
let mut mir_exprs = Vec::new();
for expr in exprs {
mir_exprs.push(expr.to_mir_expr(decls, constants, target)?)
}
MirStatement::Return(mir_exprs)
}
Self::Free(addr, size) => MirStatement::Free(
addr.to_mir_expr(decls, constants, target)?,
size.to_mir_expr(decls, constants, target)?,
),
Self::Expression(expr) => {
MirStatement::Expression(expr.to_mir_expr(decls, constants, target)?)
}
})
}
}
/// This type represents an expression that is used as
/// a value in a statement or in another expression.
#[derive(Clone, Debug, PartialEq)]
pub enum HirExpression {
/// The size of a type as a number
SizeOf(HirType),
/// A constant expression
Constant(HirConstant),
/// The addition of two expressions
Add(Box<Self>, Box<Self>),
/// The subtraction of two expressions
Subtract(Box<Self>, Box<Self>),
/// The multiplication of two expressions
Multiply(Box<Self>, Box<Self>),
/// The division of two expressions
Divide(Box<Self>, Box<Self>),
/// Boolean not of an expression
Not(Box<Self>),
/// Boolean and of two expressions
And(Box<Self>, Box<Self>),
/// Boolean or of two expressions
Or(Box<Self>, Box<Self>),
/// Compare two expressions with the `>` operator
Greater(Box<Self>, Box<Self>),
/// Compare two expressions with the `<` operator
Less(Box<Self>, Box<Self>),
/// Compare two expressions with the `>=` operator
GreaterEqual(Box<Self>, Box<Self>),
/// Compare two expressions with the `<=` operator
LessEqual(Box<Self>, Box<Self>),
/// Compare two expressions with the `==` operator
Equal(Box<Self>, Box<Self>),
/// Compare two expressions with the `!=` operator
NotEqual(Box<Self>, Box<Self>),
/// Get the address of a variable
Refer(Identifier),
/// Dereference a pointer variable
Deref(Box<Self>),
/// The Unit expression
Void,
/// Boolean True
True,
/// Boolean False
False,
/// A character literal. This is expressed as an expression
/// instead of a constant because constants are all of type float.
Character(char),
/// A stack allocated character array literal
String(StringLiteral),
/// A variable expression
Variable(Identifier),
/// Cast an expression's type to another type.
TypeCast(Box<Self>, HirType),
/// Mark an expression as moved. This means that the
/// inner expression will not be copied or dropped.
Move(Box<Self>),
/// The address of N number of free
/// memory cells on the stack.
Alloc(Box<Self>),
/// A function call
Call(Identifier, Vec<Self>),
/// A foreign function call
ForeignCall(Identifier, Vec<Self>),
/// A method call on an object
Method(Box<Self>, Identifier, Vec<Self>),
/// An index of a pointer value
Index(Box<Self>, Box<Self>),
/// A conditional expression
Conditional(Box<Self>, Box<Self>, Box<Self>),
}
impl HirExpression {
fn is_literal(&self) -> bool {
match self {
Self::Void
| Self::True
| Self::False
| Self::Character(_)
| Self::String(_)
| Self::Constant(_) => true,
_ => false,
}
}
fn to_mir_expr(
&self,
decls: &Vec<HirDeclaration>,
constants: &BTreeMap<Identifier, HirConstant>,
target: &impl Target,
) -> Result<MirExpression, HirError> {
Ok(match self {
Self::Move(expr) => {
MirExpression::Move(Box::new(expr.to_mir_expr(decls, constants, target)?))
}
/// Get the size of a type and replace this expression
/// with its float value.
Self::SizeOf(t) => MirExpression::Float(t.get_size(decls, constants, target)? as f64),
/// Convert a constant expression into a float literal
Self::Constant(constant) => {
MirExpression::Float(constant.to_value(decls, constants, target)?)
}
Self::Add(l, r) => MirExpression::Add(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::True => MirExpression::True,
Self::False => MirExpression::False,
Self::Not(expr) => {
MirExpression::Not(Box::new(expr.to_mir_expr(decls, constants, target)?))
}
Self::And(l, r) => MirExpression::And(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::Or(l, r) => MirExpression::Or(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::Greater(l, r) => MirExpression::Greater(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::GreaterEqual(l, r) => MirExpression::GreaterEqual(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::Less(l, r) => MirExpression::Less(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::LessEqual(l, r) => MirExpression::LessEqual(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::Equal(l, r) => MirExpression::Equal(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::NotEqual(l, r) => MirExpression::NotEqual(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::Subtract(l, r) => MirExpression::Subtract(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::Multiply(l, r) => MirExpression::Multiply(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::Divide(l, r) => MirExpression::Divide(
Box::new(l.to_mir_expr(decls, constants, target)?),
Box::new(r.to_mir_expr(decls, constants, target)?),
),
Self::Refer(var_name) => MirExpression::Refer(var_name.clone()),
Self::Deref(value) => {
MirExpression::Deref(Box::new(value.to_mir_expr(decls, constants, target)?))
}
Self::Void => MirExpression::Void,
Self::Character(ch) => MirExpression::Character(*ch),
Self::String(string) => MirExpression::String(string.clone()),
/// If a variable is actually a constant,
/// replace it with its constant value
Self::Variable(name) => {
if let Some(val) = constants.get(name) {
MirExpression::Float(val.to_value(decls, constants, target)?)
} else {
MirExpression::Variable(name.clone())
}
}
Self::Alloc(value) => {
MirExpression::Alloc(Box::new(value.to_mir_expr(decls, constants, target)?))
}
Self::TypeCast(expr, t) if expr.is_literal() && t.is_pointer() => {
return Err(HirError::CastLiteralAsPointer(t.clone()))
}
Self::TypeCast(expr, t) => MirExpression::TypeCast(
Box::new(expr.to_mir_expr(decls, constants, target)?),
t.to_mir_type(),
),
Self::Call(name, arguments) => MirExpression::Call(name.clone(), {
let mut result = Vec::new();
for arg in arguments {
result.push(arg.to_mir_expr(decls, constants, target)?);
}
result
}),
Self::ForeignCall(name, arguments) => MirExpression::ForeignCall(name.clone(), {
let mut result = Vec::new();
for arg in arguments {
result.push(arg.to_mir_expr(decls, constants, target)?);
}
result
}),
Self::Method(instance, name, arguments) => MirExpression::Method(
Box::new(instance.to_mir_expr(decls, constants, target)?),
name.clone(),
{
let mut result = Vec::new();
for arg in arguments {
result.push(arg.to_mir_expr(decls, constants, target)?);
}
result
},
),
Self::Index(ptr, idx) => MirExpression::Index(
Box::new(ptr.to_mir_expr(decls, constants, target)?),
Box::new(idx.to_mir_expr(decls, constants, target)?),
),
Self::Conditional(cond, then, otherwise) => MirExpression::Conditional(
Box::new(cond.to_mir_expr(decls, constants, target)?),
Box::new(then.to_mir_expr(decls, constants, target)?),
Box::new(otherwise.to_mir_expr(decls, constants, target)?),
),
})
}
}