-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode2.rs
More file actions
3075 lines (2735 loc) · 96.9 KB
/
code2.rs
File metadata and controls
3075 lines (2735 loc) · 96.9 KB
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
// --- moc-common/src/ast.rs ---
use crate::decl::Decl;
pub type Ast = Vec<Decl>;
// --- moc-common/src/debug_utils.rs ---
use crate::token::{Token};
pub fn print_tokens(tokens: &[Token]) {
for token in tokens {
println!("{}", token);
}
}
pub const INDENT: &str = " ";
pub fn create_indent(depth: usize) -> String {
format!("\n{}", INDENT.repeat(depth))
}
// --- moc-common/src/decl.rs ---
use serde::Serialize;
use crate::{
CodeBlock, CodeSpan, TypedVar, expr::{Expr, GenericParam, Ident, TraitBound, TypeExpr}
};
#[derive(Debug, Clone, Serialize)]
pub struct FnSignature {
pub ident: String,
pub generics: Vec<GenericParam>, // Using the struct from our last step!
pub params: Vec<TypedVar>,
pub return_type: Option<TypeExpr>,
}
#[derive(Debug, Clone, Serialize)]
pub enum DeclKind {
Fn {
// function declaration
signature: FnSignature,
body: CodeBlock,
},
Use {
path: Ident,
alias: Option<String>,
},
Struct {
ident: String,
fields: Vec<TypedVar>,
generics: Vec<GenericParam>, // e.g., ["T", "U"]
impl_traits: Vec<TraitBound>, // NEW: e.g., [PartialOrd]
},
Sum {
ident: String,
generics: Vec<GenericParam>,
impl_traits: Vec<TraitBound>,
variants: Vec<Variant>,
},
Trait {
ident: String,
generics: Vec<GenericParam>, // Traits can be generic too!
methods: Vec<FnSignature>,
},
// global variable/constant?
// Only for debugging stuff! If I want to just test parsing expressions without all the other shebang.
LooseExpr(Expr),
}
#[derive(Debug, Clone, Serialize)]
pub struct Decl {
pub span: CodeSpan,
pub kind: DeclKind,
}
impl Decl {
pub fn new(kind: DeclKind, span: CodeSpan) -> Self {
Self { kind, span }
}
}
// sum type variant stuff
#[derive(Debug, Clone, Serialize)]
pub enum VariantData {
Unit,
Tuple(Vec<TypeExpr>),
Struct(Vec<TypedVar>),
}
#[derive(Debug, Clone, Serialize)]
pub struct Variant {
pub ident: String,
pub data: VariantData,
}
// --- moc-common/src/error.rs ---
use std::io;
use thiserror::Error;
use crate::{CodeSpan, ast::Ast, expr::Expr, token::Token};
#[derive(Debug, Error)]
pub enum CompilerError {
#[error(transparent)]
ParserError(#[from] ParserError),
#[error(transparent)]
LexerError(#[from] LexerError),
#[error("File operation failed")]
FileNotFound(#[from] io::Error)
}
#[derive(Debug, Clone, Error)]
pub enum LexerError {
#[error("Unterminated string literal")]
UnterminatedStringLiteral(CodeSpan),
#[error("Invalid character '{0}'")]
InvalidCharacter(char, CodeSpan),
#[error("Unknown escape character")]
UnknownEscapeCharacter(CodeSpan),
#[error("Multiple decimal points in number literal")]
MultiDecimalPointInNumberLiteral(CodeSpan),
#[error("Unexpected character while lexing non-decimal number literal")]
UnexpectedCharacterLexingNonDecimalNumberLiteral(CodeSpan),
#[error("Unknown token encountered")]
UnknownToken(CodeSpan),
}
#[derive(Debug, Clone, Error)]
pub enum ParserError {
#[error("{msg}")]
UnexpectedToken {
msg: String,
peeking: Option<Token>,
span: CodeSpan,
},
}
impl ParserError {
pub fn unexpected_token(msg: &str, peeking: Option<Token>, span: CodeSpan) -> Self {
Self::UnexpectedToken { msg: msg.into(), peeking, span }
}
pub fn wrap<T>(self) -> Result<T, ParserError> {
Err(self)
}
}
pub type LexerResult = Result<Token, LexerError>;
pub type ParseResult = Result<Ast, ParserError>;
pub type ExprParseResult = Result<Expr, ParserError>;
// --- moc-common/src/lib.rs ---
pub mod ast;
pub mod debug_utils;
pub mod decl;
pub mod error;
pub mod expr;
pub mod op;
pub mod stmt;
pub mod token;
use std::{
collections::VecDeque,
fmt::{Debug, Display},
};
use derive_more::Display;
use serde::Serialize;
use crate::{
expr::TypeExpr,
stmt::Stmt,
};
#[derive(Debug, Clone, Copy, Serialize)]
pub struct CodeLocation {
pub line: usize,
pub column: usize,
}
impl CodeLocation {
pub fn is_in_same_line(&self, other: &Self) -> bool {
self.line == other.line
}
}
impl Default for CodeLocation {
fn default() -> Self {
Self { line: 1, column: 1 }
}
}
impl Display for CodeLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{}:{}", self.line, self.column))
}
}
#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct CodeSpan {
pub start: CodeLocation,
pub end: CodeLocation,
}
#[derive(Debug, Display)]
pub struct ExpandCodeSpanError;
impl std::error::Error for ExpandCodeSpanError {}
impl CodeSpan {
pub fn is_single_line(&self) -> bool {
self.start.line == self.end.line
}
pub fn length(&self) -> usize {
self.end.column - self.start.column
}
pub fn try_extend_left(&mut self, chars: usize) -> Result<(), ExpandCodeSpanError> {
if self.start.column - chars > 0 {
self.start.column -= chars;
Ok(())
} else {
Err(ExpandCodeSpanError)
}
}
pub fn extend_right(&mut self, chars: usize) {
self.start.column += chars;
}
pub fn try_extend_both_sides(&mut self, chars: usize) -> Result<(), ExpandCodeSpanError> {
self.try_extend_left(chars)?;
self.extend_right(chars);
Ok(())
}
/// Creates a new span that encompasses both `self` and `other`
pub fn merge(self, other: Self) -> Self {
Self {
start: self.start,
end: other.end,
}
}
}
impl From<(CodeLocation, CodeLocation)> for CodeSpan {
fn from(value: (CodeLocation, CodeLocation)) -> Self {
Self {
start: value.0,
end: value.1,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CodeBlock {
pub stmts: Vec<Stmt>,
}
impl CodeBlock {
pub fn new() -> Self {
Self { stmts: Vec::new() }
}
}
#[derive(Clone, Debug, Serialize)]
pub struct ModulePath {
pub path: VecDeque<String>,
}
impl ModulePath {
pub fn new(module_path: VecDeque<String>) -> Self {
ModulePath { path: module_path }
}
pub fn from_slice(module_path: &[String]) -> Self {
ModulePath {
path: module_path.iter().cloned().collect(),
}
}
/// Like for example: The string "mod:submod:my_function" will yield a ModuleIdentifier with dirs: mod:submod
pub fn from_qualified_item_identifier(ident: &str) -> Self {
let mut path: VecDeque<String> = ident
.split_terminator(":")
.map(|path_dir| path_dir.to_string())
.collect();
path.pop_back();
ModulePath { path }
}
pub fn from_string(ident: &str) -> Self {
let path = ident
.split_terminator(":")
.map(|path_dir| path_dir.to_string())
.collect();
ModulePath { path }
}
pub fn remove_and_get_last_path(&mut self) -> String {
let suffix = self
.path
.pop_back()
.expect("ModulePath should not be empty.");
suffix
}
}
impl Display for ModulePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ModuleIdentifier")?;
self.path.fmt(f)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct TypedVar {
/// the variable's identifier
ident: String,
/// the type identifier
type_expr: TypeExpr,
}
impl TypedVar {
pub fn new(ident: String, type_expr: TypeExpr) -> Self {
Self { ident, type_expr }
}
}
// --- moc-common/src/stmt.rs ---
use serde::Serialize;
use crate::{CodeBlock, CodeSpan, expr::{Expr, TypeExpr}, op::BinaryOp};
#[derive(Clone, Debug, Serialize)]
pub enum StmtKind {
Print(Expr), // probably dont wanna have this as inbuilt function
// a i32 (declaring variable)
LocalVarDecl {
ident: String,
type_expr: TypeExpr
},
// <expr> = <expr> (updating value)
Assignmt {
assignee: Expr,
new_value: Expr
},
// a += 10, a -= 10 etc. (operating and assigning)
VarOperatorAssign {
assignee: Expr,
operator: BinaryOp,
value: Expr,
},
// a i32 := 10 OR a := 10 (infers type)
LocalVarDeclAssign {
ident: String,
type_expr: Option<TypeExpr>,
value: Expr,
},
Break {
value: Option<Expr>
},
Defer(Box<Stmt>),
Expr(Expr), // expression statement (like function call)
Ret(Option<Expr>), // return statement
CodeBlock(CodeBlock),
Next,
}
#[derive(Clone, Debug, Serialize)]
pub struct Stmt {
span: CodeSpan,
kind: StmtKind,
}
impl Stmt {
pub fn new(kind: StmtKind, span: CodeSpan) -> Self {
Self { kind, span }
}
}
// --- moc-common/src/token.rs ---
use std::fmt::Display;
use derive_more::Display;
use serde::Serialize;
use crate::{
CodeSpan,
op::{BinaryOp, UnaryOp},
};
#[macro_export]
macro_rules! token {
($token_kind:ident, $start:expr, $end:expr) => {
$crate::token::Token::new(
$crate::token::TokenKind::$token_kind,
CodeSpan::from(($start, $end)),
)
};
}
#[derive(Debug, Clone, Serialize)]
pub struct Token {
pub kind: TokenKind,
pub value: Option<String>,
pub span: CodeSpan,
}
impl Display for Token {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(value) = self.value() {
write!(
f,
"{} from {} to {}, value: \"{}\"",
self.kind,
self.span.start,
self.span.end,
value.escape_default()
)
} else {
write!(
f,
"{} from {} to {}",
self.kind, self.span.start, self.span.end
)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display, Serialize)]
pub enum TokenKind {
AddAssign, // +=
Ampersand, // &
Equals, // =
At, // @
BitAndAssign, // &=
BitOrAssign, // |=
BitXorAssign, // ^=
BitNotAssign, // ~=
BitShiftLeft, // <<
BitShiftRight, // >>
BitShiftLeftAssign, // <<=
BitShiftRightAssign, // >>=
Break, // keyword
Caret, // ^
CloseBrace,
CloseParen,
OpenBrack,
CloseBrack,
Colon,
Comma,
DeclareAssign, // :=
Defer,
DivAssign, // /=
Dot,
DoubleEquals,
Excl, // !
Else,
EndOfFile,
False,
Fn,
For,
Greater,
GreaterOrEqual,
Ident,
If,
In,
Impl,
Is,
Less,
LessOrEqual,
LineBreak, // encompassing CRLF and LF in one token.
Loop,
Minus,
Percent,
Pipe,
ModAssign,
MultAssign,
Next, // keyword, like 'continue' in other languages
ExclEquals,
DecimalIntegerNumberLiteral,
DecimalPointNumberLiteral,
HexadecimalIntegerNumberLiteral,
OctalIntegerNumberLiteral,
BinaryIntegerNumberLiteral,
ScientificDecimalNumberLiteral, // 1e9 = 1,000,000,000 | 1e-9 = 0.000000001 | 0.1e9 = 100,000,000 | 0.1e-9 = 0.0000000001
ScientificHexNumberLiteral, // 0x10p10 = 0x10 * 2^10 | 0x10p-10 = 0x10 * 2^-10
OpenBrace,
OpenParen,
Plus,
Ret,
Semicolon,
Slash,
StringLiteral,
Star,
Struct,
SubAssign,
Sum,
Tilde, // ~
Trait,
True,
Use,
}
#[derive(Debug, Clone, Copy, Display, Serialize, Eq, PartialEq)]
pub enum NumberLiteralKind {
DecimalInteger,
DecimalPoint, // like floating point
BinaryInteger,
OctalInteger,
HexadecimalInteger,
ScientificDecimal, // 1e9 = 1,000,000,000 | 1e-9 = 0.000000001 | 0.1e9 = 100,000,000 | 0.1e-9 = 0.0000000001
ScientificHex, // 0x10p10 = 0x10 * 2^10 | 0x10p-10 = 0x10 * 2^-10
}
impl NumberLiteralKind {
pub fn get_radix(&self) -> u32 {
match self {
NumberLiteralKind::DecimalInteger
| NumberLiteralKind::ScientificDecimal
| NumberLiteralKind::DecimalPoint => 10,
NumberLiteralKind::BinaryInteger => 2,
NumberLiteralKind::OctalInteger => 8,
NumberLiteralKind::HexadecimalInteger | NumberLiteralKind::ScientificHex => 16,
}
}
pub fn get_token_type(&self) -> TokenKind {
match self {
NumberLiteralKind::DecimalInteger => TokenKind::DecimalIntegerNumberLiteral,
NumberLiteralKind::DecimalPoint => TokenKind::DecimalPointNumberLiteral,
NumberLiteralKind::BinaryInteger => TokenKind::BinaryIntegerNumberLiteral,
NumberLiteralKind::OctalInteger => TokenKind::OctalIntegerNumberLiteral,
NumberLiteralKind::HexadecimalInteger => TokenKind::HexadecimalIntegerNumberLiteral,
NumberLiteralKind::ScientificDecimal => TokenKind::ScientificDecimalNumberLiteral,
NumberLiteralKind::ScientificHex => TokenKind::ScientificHexNumberLiteral,
}
}
}
impl Token {
pub fn string_literal(literal: String, span: CodeSpan) -> Self {
Self {
kind: TokenKind::StringLiteral,
value: Some(literal.into()),
span,
}
}
pub fn ident(ident: String, span: CodeSpan) -> Self {
Self {
kind: TokenKind::Ident,
value: Some(ident.into()),
span,
}
}
pub fn integer(value: String, span: CodeSpan) -> Self {
Self {
kind: TokenKind::DecimalIntegerNumberLiteral,
value: Some(value),
span,
}
}
pub fn number_literal(
value: String,
number_literal_type: NumberLiteralKind,
span: CodeSpan,
) -> Self {
Self {
kind: number_literal_type.get_token_type(),
value: Some(value),
span,
}
}
pub fn new(kind: TokenKind, span: CodeSpan) -> Self {
Self {
kind,
value: None,
span,
}
}
pub fn with_value(r#type: TokenKind, value: String, span: CodeSpan) -> Self {
Self {
kind: r#type,
value: Some(value),
span,
}
}
pub fn value(&self) -> Option<&String> {
self.value.as_ref()
}
/// # Panics
/// Panics if no value is present
pub fn unwrap_value(&self) -> String {
self.value.as_ref().expect("Expected value").clone()
}
pub fn is_assignment_operator(&self) -> bool {
use TokenKind::*;
matches!(
self.kind,
Equals
| DeclareAssign
| AddAssign
| SubAssign
| MultAssign
| ModAssign
| DivAssign
| BitAndAssign
| BitXorAssign
| BitNotAssign
| BitOrAssign
| BitShiftLeftAssign
| BitShiftRightAssign
)
}
pub fn is_binary_op(&self) -> bool {
BinaryOp::try_from(self.kind).is_ok()
}
pub fn is_unary_op(&self) -> bool {
UnaryOp::try_from(self.kind).is_ok()
}
pub fn is_of_kind(&self, kind: TokenKind) -> bool {
self.kind == kind
}
pub fn is_of_any_kinds(&self, types: &[TokenKind]) -> bool {
for r#type in types {
if self.is_of_kind(*r#type) {
return true;
}
}
false
}
pub fn is_number_literal(&self) -> bool {
TryInto::<NumberLiteralKind>::try_into(self.kind).is_ok()
}
pub fn infix_binding_power(&self) -> Option<(u8, u8)> {
if let Some(binary_op) = BinaryOp::try_from(self.kind).ok() {
return Some(binary_op.infix_binding_power());
}
use TokenKind::*;
match self.kind {
OpenParen => Some((110, 0)), // 0 on the right because it's postfix/special
Dot => Some((120, 0)),
OpenBrack => Some((110, 0)),
TokenKind::Colon => Some((9, 10)),
DeclareAssign | Equals | AddAssign | SubAssign | MultAssign | DivAssign | ModAssign
| BitAndAssign | BitOrAssign | BitNotAssign | BitXorAssign | BitShiftLeftAssign
| BitShiftRightAssign => Some((10, 9)), // Right-associative assignment
_ => None,
}
}
}
impl From<TokenKind> for Token {
fn from(r#type: TokenKind) -> Self {
Self {
kind: r#type,
value: None,
span: CodeSpan::default(),
}
}
}
impl From<NumberLiteralKind> for TokenKind {
fn from(value: NumberLiteralKind) -> Self {
value.get_token_type()
}
}
#[derive(Debug)]
pub struct NonNumberLiteralTokenTypeError;
impl TryFrom<TokenKind> for NumberLiteralKind {
type Error = NonNumberLiteralTokenTypeError;
fn try_from(value: TokenKind) -> Result<Self, Self::Error> {
match value {
TokenKind::DecimalIntegerNumberLiteral => Ok(NumberLiteralKind::DecimalInteger),
TokenKind::DecimalPointNumberLiteral => Ok(NumberLiteralKind::DecimalPoint),
TokenKind::BinaryIntegerNumberLiteral => Ok(NumberLiteralKind::BinaryInteger),
TokenKind::OctalIntegerNumberLiteral => Ok(NumberLiteralKind::OctalInteger),
TokenKind::HexadecimalIntegerNumberLiteral => Ok(NumberLiteralKind::HexadecimalInteger),
TokenKind::ScientificDecimalNumberLiteral => Ok(NumberLiteralKind::ScientificDecimal),
TokenKind::ScientificHexNumberLiteral => Ok(NumberLiteralKind::ScientificHex),
_ => Err(NonNumberLiteralTokenTypeError),
}
}
}
#[cfg(test)]
mod tests {
use crate::CodeLocation;
use super::*;
#[test]
fn is_of_type_s() {
let token = token!(Plus, CodeLocation::default(), CodeLocation::default());
assert!(token.is_of_kind(TokenKind::Plus));
assert!(token.is_of_any_kinds(&[TokenKind::Plus, TokenKind::Minus]));
assert!(token.is_of_any_kinds(&[TokenKind::Minus, TokenKind::Plus]));
}
}
// --- moc-common/src/expr.rs ---
use serde::Serialize;
use crate::{
CodeBlock, CodeLocation, CodeSpan, ModulePath, op::{BinaryOp, UnaryOp}, token::{NumberLiteralKind, TokenKind}
};
#[derive(Debug, Clone, Serialize)]
pub enum ExprKind {
// Expressions
Assign {
assignee: Box<Expr>,
operator: TokenKind, // TODO: maybe make this use it's own enum type like AssignmentOp?
value: Box<Expr>,
},
Binary {
left_expr: Box<Expr>,
operator: BinaryOp,
right_expr: Box<Expr>,
},
FieldAccess {
called_on: Box<Expr>,
member_ident: Ident,
},
ArrayLiteral {
elements: Vec<Expr>,
},
ArrayAccessor {
array: Box<Expr>,
index: Box<Expr>,
},
ForLoop {
condition: Option<Box<Expr>>, // if None, is infinite loop
code_block: CodeBlock,
},
If {
condition: Box<Expr>,
if_block: CodeBlock,
else_block: Option<CodeBlock>,
},
BoolLiteral(bool),
Grouping(Box<Expr>),
FnCall {
callee: Box<Expr>, // callee / what value, what expression the function is being called on.
args: Vec<Expr>,
},
// this is only part. A full generic FnCall consists of FnCall with callee being an expr of type GenericFnCallPart.
GenericFnCallPart {
callee: Box<Expr>,
type_args: Option<Vec<TypeExpr>>,
},
Variable {
ident: Ident,
},
NumberLiteral(String, NumberLiteralKind),
StringLiteral(String),
Unary {
operator: UnaryOp,
expr: Box<Expr>,
}, // Operator followed by another expr
Empty,
}
#[derive(Clone, Debug, Serialize)]
pub struct Expr {
pub span: CodeSpan,
pub kind: ExprKind,
}
#[derive(Debug, Clone, Serialize)]
pub enum Ident {
Simple(String),
WithModulePrefix(ModulePath, String),
}
impl Ident {
/// Gets the ident if of variant Simple, else gets the suffix.
pub fn base(&self) -> &String {
match self {
Ident::Simple(ident) => &ident,
Ident::WithModulePrefix(_, suffix) => &suffix,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum TypeExpr {
Ident(Ident),
Pointer(Box<TypeExpr>),
Array {
length: Option<usize>,
type_expr: Box<TypeExpr>,
},
Generic {
ident: Ident,
params: Vec<TypeExpr>, // identifiers of generic type parameters
},
}
// used in struct/sum declarations impl items.
// struct A impl Trait[i32]
// (the [T] is optional. only for generic traits)
// maybe rename to TraitImplDecl or something. I need to sleep.
#[derive(Debug, Clone, Serialize)]
pub struct TraitBound {
pub ident: Ident,
pub args: Vec<TypeExpr>,
}
#[derive(Debug, Clone, Serialize)]
pub struct GenericParam {
pub ident: String,
pub bounds: Option<Vec<Ident>>,
}
impl TypeExpr {
pub fn pointer(type_expr: Self) -> Self {
Self::Pointer(Box::new(type_expr))
}
}
impl Expr {
pub fn new(kind: ExprKind, span: CodeSpan) -> Self {
Self { kind, span }
}
pub fn binary(left: Self, operator: BinaryOp, right: Self) -> Self {
let span = left.span.merge(right.span);
Self::new(
ExprKind::Binary {
left_expr: Box::new(left),
operator,
right_expr: Box::new(right),
},
span,
)
}
pub fn unary(start: CodeLocation, operator: UnaryOp, right: Self) -> Self {
let span = (start, (&right.span).end).into();
Expr::new(ExprKind::Unary {
operator,
expr: Box::new(right),
}, span)
}
pub fn boxed(self) -> Box<Self> {
Box::new(self)
}
}
// --- moc-common/src/op.rs ---
//! An operator is something that can form an expression together with other expressions.
//! Unary operators create unary expressions while binary operators create binary expressions.
use derive_more::Display;
use serde::Serialize;
use crate::token::TokenKind;
#[derive(Clone, Copy, Debug, Display, Serialize)]
pub enum UnaryOp {
Negative, // -
Not, // ! Logical NOT
BitNot, // ~ Bitwise NOT
Deref, // * Postfix deref (pointee = pointer.*)
AddressOf,// &
}
#[derive(Debug)]
pub struct TokenNotAUnaryOpError;
impl TryFrom<TokenKind> for UnaryOp {
type Error = TokenNotAUnaryOpError;
fn try_from(value: TokenKind) -> Result<Self, Self::Error> {
match value {
TokenKind::Minus => Ok(UnaryOp::Negative),
TokenKind::Excl => Ok(UnaryOp::Not),
TokenKind::Tilde => Ok(UnaryOp::BitNot),
TokenKind::Ampersand => Ok(UnaryOp::AddressOf),
_ => Err(TokenNotAUnaryOpError),
}
}
}
impl UnaryOp {
/// Returns the binding power for prefix operators.
/// Higher than most binary operators so that `-a.b` is `-(a.b)`
/// but lower than primary expressions.
pub fn prefix_binding_power(&self) -> u8 {
// We use 17 here because our highest binary (Mult/Div) is 15/16.
17
}
}
#[derive(Clone, Copy, Debug, Display, Serialize)]
pub enum BinaryOp {
Add,
Sub, // Subtract
Mult, // Multiply
Div, // Divide
Mod, // Modulo
BitShiftLeft, // Bitshift left
BitShiftRight, // Bitshift right
BitOr, // Bitwise OR
BitAnd, // Bitwise AND
BitXor, // Bitwise XOR
Greater,
Less,
Equal,
NotEqual,
GreaterOrEqual,
LessOrEqual,
}
impl BinaryOp {
// lower binding power means lower precedence.
// Operators with higher precedence are evaluated before those with lower precedence in an expression.
// For example, multiplication has higher precedence than addition, so in 3 + 4 * 5, the multiplication is performed first.
pub fn infix_binding_power(&self) -> (u8, u8) {
use BinaryOp::*;
match self {
// Priority 1: Equality
Equal | NotEqual => (1, 2), // Equality makes sense to be evaluated after the two sides have already been evaluated, therefore low precedence
// Priority 2: Comparisons
Greater | Less | GreaterOrEqual | LessOrEqual => (3, 4),
// Priority 3: Bitwise Logic
BitOr => (5, 6),
BitXor => (7, 8),
BitAnd => (9, 10),
// Priority 4: Shifts
BitShiftLeft | BitShiftRight => (11, 12),
// Priority 5: Sums
Add | Sub => (13, 14),
// Priority 6: Products
Mult | Div | Mod => (15, 16),
}
}
}
#[derive(Debug)]
pub struct TokenNotABinaryOpError;
impl TryFrom<TokenKind> for BinaryOp {
type Error = TokenNotABinaryOpError;
fn try_from(value: TokenKind) -> Result<Self, Self::Error> {
use BinaryOp::*;
match value {
TokenKind::Plus => Ok(Add),
TokenKind::Minus => Ok(Sub), // Subtract
TokenKind::Star => Ok(Mult), // Multiply
TokenKind::Slash => Ok(Div), // Divide
TokenKind::Percent => Ok(Mod), // Modulo
TokenKind::BitShiftLeft => Ok(BitShiftLeft), // Bitshift left
TokenKind::BitShiftRight => Ok(BitShiftRight), // Bitshift right
TokenKind::Pipe => Ok(BitOr), // Bitwise OR
TokenKind::Ampersand => Ok(BitAnd), // Bitwise AND
TokenKind::Caret => Ok(BitXor), // Bitwise XOR
TokenKind::DoubleEquals => Ok(Equal), // ==
TokenKind::ExclEquals => Ok(NotEqual), // !=
TokenKind::Greater => Ok(Greater), // >
TokenKind::Less => Ok(Less), // <
TokenKind::GreaterOrEqual => Ok(GreaterOrEqual), // >=
TokenKind::LessOrEqual => Ok(LessOrEqual), // <=
_ => Err(TokenNotABinaryOpError),
}
}
}
// --- moc-cli/src/main.rs ---
use clap::Parser;
use moc_common::debug_utils;
use moc_main::CompilerOptions;