-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmod.rs
More file actions
1301 lines (1121 loc) · 39.9 KB
/
Copy pathmod.rs
File metadata and controls
1301 lines (1121 loc) · 39.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
pub mod file_cache;
pub mod span;
use crate::mir::{
MIRConstant, MIRContext, MIRDeclaration, MIRExpression, MIRExpressionInner, MIRFnCall,
MIRFnSource, MIRFunction, MIRFunctionArgs, MIRFunctionType, MIRMarker, MIRRaw, MIRStatement,
MIRStatic, MIRType, MIRTypeInner, MIRVariable,
};
use crate::parser::file_cache::file_cache;
use pest::Parser;
use pest::iterators::Pair;
use pest_derive::Parser;
use span::to_span;
use std::borrow::Cow;
use std::path::{Path, PathBuf};
#[derive(Parser)]
#[grammar = "parser/program.pest"]
struct InsertParser;
/// Parses a file into MIR,
/// returning whether it was successful.
pub fn parse_file<'a>(location: &'a Path, ctx: &mut MIRContext<'a>) -> bool {
let data = file_cache().get(location).unwrap();
let Some(decls) = parse_data(location, data, ctx) else {
return false;
};
for decl in decls {
let Some(key) = ctx.register(decl) else {
// Registration failed (duplicate identifier).
// Any error was already printed.
return false;
};
ctx.push_decl(key);
}
true
}
/// Parses some data file into MIR,
/// returning whether it was successful.
fn parse_data<'a>(
location: &'a Path,
data: &'a str,
ctx: &mut MIRContext<'a>,
) -> Option<Vec<MIRDeclaration<'a>>> {
let ast = match InsertParser::parse(Rule::program, data) {
Ok(ast) => ast,
Err(err) => {
eprintln!("{err}");
return None;
}
};
for pair in ast {
match pair.as_rule() {
Rule::declarations => {
return parse_declarations(location, pair, ctx);
}
Rule::EOI => {}
_ => unreachable!(),
}
}
unreachable!("No declarations found!");
}
fn parse_declarations<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Option<Vec<MIRDeclaration<'a>>> {
assert_eq!(value.as_rule(), Rule::declarations);
let mut res = vec![];
for pair in value.into_inner() {
match pair.as_rule() {
Rule::constDeclaration => {
res.push(MIRDeclaration::Constant(parse_constant(
location, pair, ctx,
)));
}
Rule::staticDeclaration => {
res.push(MIRDeclaration::Static(parse_static(location, pair, ctx)));
}
Rule::functionDeclaration => {
res.push(MIRDeclaration::Function(parse_function(
location, pair, ctx,
)?));
}
Rule::externFunctionDeclaration => {
res.push(MIRDeclaration::Function(parse_extern_function(
location, pair,
)));
}
Rule::importDeclaration => {
res.extend(parse_import(location, pair, ctx)?);
}
Rule::targetDeclaration => {
res.extend(parse_target(location, pair, ctx)?);
}
Rule::markerStatement => {
res.push(MIRDeclaration::Marker(parse_marker(location, pair)));
}
Rule::rawStatement => {
res.push(MIRDeclaration::Raw(parse_raw(location, pair)));
}
_ => unreachable!(),
}
}
Some(res)
}
fn parse_static<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRStatic<'a> {
assert_eq!(value.as_rule(), Rule::staticDeclaration);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let identifier = data.next().unwrap().as_str();
let ty = parse_type(location, data.next().unwrap());
let expr = parse_expression(location, data.next().unwrap(), ctx);
MIRStatic {
name: Cow::Borrowed(identifier),
ty,
value: expr,
span,
}
}
fn parse_marker<'a>(location: &'a Path, value: Pair<'a, Rule>) -> MIRMarker<'a> {
assert_eq!(value.as_rule(), Rule::markerStatement);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let identifier = data.next().unwrap().as_str();
MIRMarker {
name: Cow::Borrowed(identifier),
span,
}
}
fn parse_raw<'a>(location: &'a Path, value: Pair<'a, Rule>) -> MIRRaw<'a> {
assert_eq!(value.as_rule(), Rule::rawStatement);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let text = parse_string(data.next().unwrap()).into();
MIRRaw { text, span }
}
fn parse_constant<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRConstant<'a> {
assert_eq!(value.as_rule(), Rule::constDeclaration);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let identifier = data.next().unwrap().as_str();
let ty = parse_type(location, data.next().unwrap());
let expr = parse_expression(location, data.next().unwrap(), ctx);
MIRConstant {
name: Cow::Borrowed(identifier),
ty,
value: expr,
span,
}
}
fn parse_function<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Option<MIRFunction<'a>> {
assert_eq!(value.as_rule(), Rule::functionDeclaration);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let fn_type;
let identifier;
let first_pair = data.next().unwrap();
if first_pair.as_rule() == Rule::identifier {
fn_type = MIRFunctionType::Export;
identifier = first_pair.as_str();
} else {
fn_type = match first_pair.as_rule() {
Rule::inlineOut => MIRFunctionType::Inline,
Rule::helperOut => MIRFunctionType::Helper,
_ => unreachable!(),
};
identifier = data.next().unwrap().as_str();
}
let mut args = vec![];
let mut ret = MIRType {
ty: MIRTypeInner::Unit,
span: None,
};
for pair in data {
match pair.as_rule() {
Rule::functionArgs => {
args = parse_function_args(location, pair, ctx);
}
Rule::functionReturn => {
// functionReturn([type])
ret = parse_type(location, pair.into_inner().next().unwrap());
}
Rule::functionBody => {
// Function body is the last item.
return Some(MIRFunction {
name: Cow::Borrowed(identifier),
fn_type,
args_ty: MIRFunctionArgs {
args: args.iter().map(|v| v.ty.ty.clone()).collect(),
variadic: false,
},
args,
ret_ty: ret,
body: parse_function_body(location, pair, ctx)?,
span,
extern_import: None,
});
}
_ => unreachable!(),
}
}
// No function body.
unreachable!();
}
fn parse_extern_function<'a>(location: &'a Path, value: Pair<'a, Rule>) -> MIRFunction<'a> {
assert_eq!(value.as_rule(), Rule::externFunctionDeclaration);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let identifier = data.next().unwrap().as_str();
let mut args = vec![];
let mut variadic = false;
let mut ret = MIRType {
ty: MIRTypeInner::Unit,
span: None,
};
for pair in data {
match pair.as_rule() {
Rule::externFunctionArgs => {
(args, variadic) = parse_extern_function_args(location, pair);
}
Rule::functionReturn => {
ret = parse_type(location, pair.into_inner().next().unwrap());
}
Rule::string => {
// Import path is the last item.
let import = parse_string(pair);
return MIRFunction {
name: Cow::Borrowed(identifier),
fn_type: MIRFunctionType::Extern,
args_ty: MIRFunctionArgs {
args: args.iter().map(|v| v.ty.ty.clone()).collect(),
variadic,
},
args,
ret_ty: ret,
body: vec![],
span,
extern_import: Some(Cow::Owned(import)),
};
}
_ => unreachable!(),
}
}
unreachable!();
}
fn parse_extern_function_args<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
) -> (Vec<MIRVariable<'a>>, bool) {
assert_eq!(value.as_rule(), Rule::externFunctionArgs);
let mut args = vec![];
let mut variadic = false;
for pair in value.into_inner() {
match pair.as_rule() {
Rule::functionArg => {
let span = to_span(location, pair.as_span());
let mut data = pair.into_inner();
let identifier = data.next().unwrap().as_str();
let ty = parse_type(location, data.next().unwrap());
args.push(MIRVariable {
name: Cow::Borrowed(identifier),
ty,
span,
var_idx: None,
arg: true,
});
}
Rule::variadic => {
variadic = true;
}
_ => {}
}
}
(args, variadic)
}
fn parse_import<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Option<Vec<MIRDeclaration<'a>>> {
assert_eq!(value.as_rule(), Rule::importDeclaration);
let value = PathBuf::from(parse_string(value.into_inner().next().unwrap()));
let import_path = if value.starts_with("./") || value.starts_with("../") || value.is_absolute()
{
// Relative or absolute path.
// These are standard fs path imports, and should be imported relative to the
// current file.
location
.parent()
.expect("File path had no parent!")
.join(value)
} else {
// Module import path.
value
};
// Normalize the import, since join won't resolve "../" etc, and this
// could create duplicate declarations.
// We can't canonicalize the path, since we want to preserve "std/..." paths.
let import_path = import_path
.normalize_lexically()
.expect("Failed to normalize import path!");
if file_cache().exists(&import_path) {
// We already imported this file, so return
// nothing here to avoid duplicating declarations.
return Some(vec![]);
}
let data = file_cache().get(&import_path).unwrap();
// Leaking is okay here, since we only do it once per file.
parse_data(import_path.leak(), data, ctx)
}
fn parse_target<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Option<Vec<MIRDeclaration<'a>>> {
assert_eq!(value.as_rule(), Rule::targetDeclaration);
let mut values = value.into_inner();
let name = parse_string(values.next().unwrap());
if name != ctx.target.name() {
// Not the right target.
return Some(vec![]);
}
parse_declarations(location, values.next().unwrap(), ctx)
}
fn parse_function_body<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Option<Vec<MIRStatement<'a>>> {
assert_eq!(value.as_rule(), Rule::functionBody);
let mut body = vec![];
for pair in value.into_inner() {
body.push(parse_statement(location, pair, ctx)?);
}
Some(body)
}
fn parse_statement<'a>(
location: &'a Path,
pair: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Option<MIRStatement<'a>> {
let span = to_span(location, pair.as_span());
match pair.as_rule() {
Rule::createVariable => {
let mut data = pair.into_inner();
let identifier = data.next().unwrap().as_str();
let ty = parse_type(location, data.next().unwrap());
Some(MIRStatement::CreateVariable {
var: MIRVariable {
name: Cow::Borrowed(identifier),
ty,
span: span.clone(),
var_idx: None,
arg: false,
},
value: None,
span,
})
}
Rule::createSetVariable => {
let mut data = pair.into_inner();
let identifier = data.next().unwrap().as_str();
let ty = parse_type(location, data.next().unwrap());
let value = parse_expression(location, data.next().unwrap(), ctx);
Some(MIRStatement::CreateVariable {
var: MIRVariable {
name: Cow::Borrowed(identifier),
ty,
span: span.clone(),
var_idx: None,
arg: false,
},
value: Some(value),
span: span.clone(),
})
}
Rule::setVariable => {
let mut data = pair.into_inner();
let place = parse_place_expr(location, data.next().unwrap(), ctx);
let value = parse_expression(location, data.next().unwrap(), ctx);
Some(MIRStatement::SetVariable { place, value, span })
}
// These get converted to SetVariable to make future analysis easier,
// but will get re-compacted later in the compilation process.
Rule::addAssign => {
let mut data = pair.into_inner();
let place = parse_place_expr(location, data.next().unwrap(), ctx);
let value = parse_expression(location, data.next().unwrap(), ctx);
Some(MIRStatement::SetVariable {
place: place.clone(),
value: MIRExpression {
inner: MIRExpressionInner::Add(Box::new(place), Box::new(value)),
ty: None,
span: span.clone(),
},
span,
})
}
Rule::subAssign => {
let mut data = pair.into_inner();
let place = parse_place_expr(location, data.next().unwrap(), ctx);
let value = parse_expression(location, data.next().unwrap(), ctx);
Some(MIRStatement::SetVariable {
place: place.clone(),
value: MIRExpression {
inner: MIRExpressionInner::Sub(Box::new(place), Box::new(value)),
ty: None,
span: span.clone(),
},
span,
})
}
Rule::mulAssign => {
let mut data = pair.into_inner();
let place = parse_place_expr(location, data.next().unwrap(), ctx);
let value = parse_expression(location, data.next().unwrap(), ctx);
Some(MIRStatement::SetVariable {
place: place.clone(),
value: MIRExpression {
inner: MIRExpressionInner::Mul(Box::new(place), Box::new(value)),
ty: None,
span: span.clone(),
},
span,
})
}
Rule::divAssign => {
let mut data = pair.into_inner();
let place = parse_place_expr(location, data.next().unwrap(), ctx);
let value = parse_expression(location, data.next().unwrap(), ctx);
Some(MIRStatement::SetVariable {
place: place.clone(),
value: MIRExpression {
inner: MIRExpressionInner::Div(Box::new(place), Box::new(value)),
ty: None,
span: span.clone(),
},
span,
})
}
Rule::functionCallDirect => {
let mut data = pair.into_inner();
let name_data = data.next().unwrap();
let name = name_data.as_str();
let args = data
.next()
.map_or(vec![], |args| parse_function_call_args(location, args, ctx));
Some(MIRStatement::FunctionCall(MIRFnCall {
source: MIRFnSource::Direct(
Cow::Borrowed(name),
to_span(location, name_data.as_span()),
),
args,
args_ty: None,
ret_ty: None,
span,
}))
}
Rule::functionCallIndirect => {
let mut data = pair.into_inner();
let ptr = parse_expression(location, data.next().unwrap(), ctx);
let args = data
.next()
.map_or(vec![], |args| parse_function_call_args(location, args, ctx));
Some(MIRStatement::FunctionCall(MIRFnCall {
source: MIRFnSource::Indirect(ptr),
args,
args_ty: None,
ret_ty: None,
span,
}))
}
Rule::returnStmt => Some(MIRStatement::Return {
expr: pair
.into_inner()
.next()
.map(|v| parse_expression(location, v, ctx)),
span,
}),
Rule::ifStatement => parse_if_statement(location, pair, ctx),
Rule::continueStatement => Some(MIRStatement::ContinueStatement { span }),
Rule::breakStatement => Some(MIRStatement::BreakStatement { span }),
Rule::loopStatement => {
let mut data = pair.into_inner();
let loop_body = parse_function_body(location, data.next().unwrap(), ctx)?;
Some(MIRStatement::LoopStatement {
condition: None,
body: loop_body,
iterate: vec![],
span,
})
}
Rule::whileStatement => {
let mut data = pair.into_inner();
let condition = parse_expression(location, data.next().unwrap(), ctx);
let loop_body = parse_function_body(location, data.next().unwrap(), ctx)?;
Some(MIRStatement::LoopStatement {
condition: Some(condition),
body: loop_body,
iterate: vec![],
span,
})
}
Rule::forStatement => {
let mut data = pair.into_inner();
let init_pair = data.next().unwrap();
let cond_pair = data.next().unwrap();
let iterate_pair = data.next().unwrap();
let body_pair = data.next().unwrap();
let init_stmt = match init_pair.as_rule() {
Rule::forLoopEmpty => None,
_ => Some(parse_statement(location, init_pair, ctx)?),
};
let condition = match cond_pair.as_rule() {
Rule::forLoopEmpty => None,
Rule::expression => Some(parse_expression(location, cond_pair, ctx)),
_ => unreachable!(),
};
let iterate_stmt = match iterate_pair.as_rule() {
Rule::forLoopEmpty => None,
_ => Some(parse_statement(location, iterate_pair, ctx)?),
};
let loop_body = parse_function_body(location, body_pair, ctx)?;
// For loops are desugared to a scope containing their initializer
// and a while loop.
// This makes MIR much simpler, with a small cost during codegen
// to get it properly optimized.
//
// for let i: u32 = 0; i < 10; i = i + 1 {
// i = i + 2;
// }
//
// Desugars to
//
// scope {
// let i: u32 = 0;
// while i < 10 {
// i = i + 2;
// } iterate { i = i + 1 }
// }
let mut scope_body = vec![];
if let Some(init) = init_stmt {
scope_body.push(init);
}
scope_body.push(MIRStatement::LoopStatement {
condition,
body: loop_body,
iterate: iterate_stmt.into_iter().collect(),
span: span.clone(),
});
Some(MIRStatement::ScopeStatement {
body: scope_body,
span,
})
}
Rule::markerStatement => {
let marker = parse_marker(location, pair);
// Even though markers can live inside functions, they're
// always global/unique.
//
// We need to manually register it here, since only
// global/outer declarations are automatically registered.
ctx.register(MIRDeclaration::Marker(marker.clone()))?;
Some(MIRStatement::MarkerStatement {
name: marker.name,
span: marker.span,
})
}
Rule::rawStatement => {
let raw = parse_raw(location, pair);
Some(MIRStatement::RawStatement {
text: raw.text,
span: raw.span,
})
}
_ => unreachable!(),
}
}
fn parse_if_statement<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Option<MIRStatement<'a>> {
assert_eq!(value.as_rule(), Rule::ifStatement);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let condition = parse_expression(location, data.next().unwrap(), ctx);
let on_true = parse_function_body(location, data.next().unwrap(), ctx)?;
let on_false = data
.next()
.and_then(|v| parse_if_else(location, v, ctx))
.unwrap_or(vec![]);
Some(MIRStatement::IfStatement {
condition,
on_true,
on_false,
span,
})
}
fn parse_if_else<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Option<Vec<MIRStatement<'a>>> {
assert_eq!(value.as_rule(), Rule::ifElse);
let data = value.into_inner().next().unwrap();
match data.as_rule() {
Rule::ifStatement => Some(vec![parse_if_statement(location, data, ctx)?]),
Rule::functionBody => parse_function_body(location, data, ctx),
_ => unreachable!(),
}
}
fn parse_function_args<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
_ctx: &mut MIRContext<'a>,
) -> Vec<MIRVariable<'a>> {
assert_eq!(value.as_rule(), Rule::functionArgs);
let mut args = vec![];
for pair in value.into_inner() {
let span = to_span(location, pair.as_span());
match pair.as_rule() {
Rule::functionArg => {
let mut data = pair.into_inner();
let identifier = data.next().unwrap().as_str();
let ty = parse_type(location, data.next().unwrap());
args.push(MIRVariable {
name: Cow::Borrowed(identifier),
ty,
span,
var_idx: None,
arg: true,
});
}
_ => unreachable!(),
}
}
args
}
fn parse_function_call_args<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> Vec<MIRExpression<'a>> {
assert_eq!(value.as_rule(), Rule::functionCallArgs);
let mut exprs = vec![];
for pair in value.into_inner() {
let _span = to_span(location, pair.as_span());
match pair.as_rule() {
Rule::expression => {
exprs.push(parse_expression(location, pair, ctx));
}
_ => unreachable!(),
}
}
exprs
}
fn parse_expression<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRExpression<'a> {
assert_eq!(value.as_rule(), Rule::expression);
parse_ternary(location, value.into_inner().next().unwrap(), ctx)
}
fn parse_ternary<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRExpression<'a> {
assert_eq!(value.as_rule(), Rule::ternary);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
// This is either a ternary or just a normal expression.
let condition = parse_logical(location, data.next().unwrap(), ctx);
if let Some(on_true_pair) = data.next() {
let on_true = parse_expression(location, on_true_pair, ctx);
let on_false = parse_expression(location, data.next().unwrap(), ctx);
MIRExpression {
inner: MIRExpressionInner::Ternary(
Box::new(condition),
Box::new(on_true),
Box::new(on_false),
),
ty: None,
span,
}
} else {
condition
}
}
fn parse_logical<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRExpression<'a> {
assert_eq!(value.as_rule(), Rule::logical);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let mut lhs = parse_comparison(location, data.next().unwrap(), ctx);
while let Some(op) = data.next() {
let rhs = parse_comparison(location, data.next().unwrap(), ctx);
let expr = match op.as_str() {
"&&" => MIRExpressionInner::BoolAnd(Box::new(lhs), Box::new(rhs)),
"||" => MIRExpressionInner::BoolOr(Box::new(lhs), Box::new(rhs)),
_ => unreachable!(),
};
lhs = MIRExpression {
inner: expr,
ty: None,
span: span.clone(),
};
}
lhs
}
fn parse_comparison<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRExpression<'a> {
assert_eq!(value.as_rule(), Rule::comparison);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let mut lhs = parse_addition(location, data.next().unwrap(), ctx);
while let Some(op) = data.next() {
let rhs = parse_addition(location, data.next().unwrap(), ctx);
let expr = match op.as_str() {
"==" => MIRExpressionInner::Equal(Box::new(lhs), Box::new(rhs)),
"!=" => MIRExpressionInner::NotEqual(Box::new(lhs), Box::new(rhs)),
">" => MIRExpressionInner::Greater(Box::new(lhs), Box::new(rhs)),
"<" => MIRExpressionInner::Less(Box::new(lhs), Box::new(rhs)),
">=" => MIRExpressionInner::GreaterEq(Box::new(lhs), Box::new(rhs)),
"<=" => MIRExpressionInner::LessEq(Box::new(lhs), Box::new(rhs)),
_ => unreachable!(),
};
lhs = MIRExpression {
inner: expr,
ty: None,
span: span.clone(),
};
}
lhs
}
fn parse_addition<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRExpression<'a> {
assert_eq!(value.as_rule(), Rule::addition);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let mut lhs = parse_multiplication(location, data.next().unwrap(), ctx);
while let Some(op) = data.next() {
let rhs = parse_multiplication(location, data.next().unwrap(), ctx);
let expr = match op.as_str() {
"+" => MIRExpressionInner::Add(Box::new(lhs), Box::new(rhs)),
"-" => MIRExpressionInner::Sub(Box::new(lhs), Box::new(rhs)),
_ => unreachable!(),
};
lhs = MIRExpression {
inner: expr,
ty: None,
span: span.clone(),
};
}
lhs
}
fn parse_multiplication<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRExpression<'a> {
assert_eq!(value.as_rule(), Rule::multiplication);
let span = to_span(location, value.as_span());
let mut data = value.into_inner();
let mut lhs = parse_primary(location, data.next().unwrap(), ctx);
while let Some(op) = data.next() {
let rhs = parse_primary(location, data.next().unwrap(), ctx);
let expr = match op.as_str() {
"*" => MIRExpressionInner::Mul(Box::new(lhs), Box::new(rhs)),
"/" => MIRExpressionInner::Div(Box::new(lhs), Box::new(rhs)),
_ => unreachable!(),
};
lhs = MIRExpression {
inner: expr,
ty: None,
span: span.clone(),
};
}
lhs
}
fn parse_primary<'a>(
location: &'a Path,
value: Pair<'a, Rule>,
ctx: &mut MIRContext<'a>,
) -> MIRExpression<'a> {
assert_eq!(value.as_rule(), Rule::primary);
let span = to_span(location, value.as_span());
let data = value.into_inner().next().unwrap();
let mut ty = None;
let expr = match data.as_rule() {
Rule::number => {
let res = parse_number(data);
// Type ascription from the number literal.
ty = res.1;
MIRExpressionInner::Number(res.0)
}
Rule::string => MIRExpressionInner::String(Cow::Owned(parse_string(data))),
Rule::char => MIRExpressionInner::Char(parse_char(data)),
Rule::functionCallDirect => {
let mut data = data.into_inner();
let name_data = data.next().unwrap();
let name = name_data.as_str();
let args = data
.next()
.map_or(vec![], |args| parse_function_call_args(location, args, ctx));
MIRExpressionInner::FunctionCall(Box::new(MIRFnCall {
source: MIRFnSource::Direct(
Cow::Borrowed(name),
to_span(location, name_data.as_span()),
),
args,
args_ty: None,
ret_ty: None,
span: span.clone(),
}))
}
Rule::functionCallIndirect => {
let mut data = data.into_inner();
let ptr = parse_expression(location, data.next().unwrap(), ctx);
let args = data
.next()
.map_or(vec![], |args| parse_function_call_args(location, args, ctx));
MIRExpressionInner::FunctionCall(Box::new(MIRFnCall {
source: MIRFnSource::Indirect(ptr),
args,
args_ty: None,
ret_ty: None,
span: span.clone(),
}))
}
Rule::placeExpr => {
return parse_place_expr(location, data, ctx);
}
Rule::boolLiteral => MIRExpressionInner::Bool(data.as_str() == "true"),
Rule::quine => MIRExpressionInner::Quine,