/
passes.rs
4537 lines (3746 loc) · 149 KB
/
passes.rs
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
//! Compiler passes that operate on Inko's MIR.
use crate::diagnostics::DiagnosticId;
use crate::hir;
use crate::mir::pattern_matching as pmatch;
use crate::mir::{
Block, BlockId, CastType, Class, Constant, Goto, Instruction, LocationId,
Method, Mir, Module, RegisterId, SELF_ID,
};
use crate::state::State;
use ast::source_location::SourceLocation;
use std::collections::{HashMap, HashSet};
use std::iter::repeat_with;
use std::mem::swap;
use std::path::PathBuf;
use types::format::format_type;
use types::{
self, Block as _, ClassId, ConstantId, MethodId, ModuleId, TypeBounds,
TypeRef, EQ_METHOD, FIELDS_LIMIT, OPTION_NONE, OPTION_SOME, RESULT_CLASS,
RESULT_ERROR, RESULT_MODULE, RESULT_OK,
};
const SELF_NAME: &str = "self";
const MODULES_LIMIT: usize = u32::MAX as usize;
const CLASSES_LIMIT: usize = u32::MAX as usize;
const METHODS_LIMIT: usize = u32::MAX as usize;
fn modulo(lhs: i64, rhs: i64) -> Option<i64> {
lhs.checked_rem(rhs)
.and_then(|res| res.checked_add(rhs))
.and_then(|res| res.checked_rem(rhs))
}
/// A compiler pass that verifies various global limits, such as the number of
/// defined classes.
pub(crate) fn check_global_limits(state: &mut State) -> Result<(), String> {
let num_mods = state.db.number_of_modules();
let num_classes = state.db.number_of_classes();
let num_methods = state.db.number_of_methods();
if num_mods > MODULES_LIMIT {
return Err(format!(
"the total number of modules ({}) \
exceeds the maximum of {} modules",
num_mods, MODULES_LIMIT
));
}
if num_classes > CLASSES_LIMIT {
return Err(format!(
"the total number of classes ({}) \
exceeds the maximum of {} classes",
num_classes, CLASSES_LIMIT
));
}
if num_methods > METHODS_LIMIT {
return Err(format!(
"the total number of methods ({}) \
exceeds the maximum of {} methods",
num_methods, METHODS_LIMIT
));
}
Ok(())
}
enum Argument {
Regular(hir::Argument),
Input(hir::Expression, TypeRef),
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum RegisterState {
/// The register is available, and should be dropped at the end of its
/// surrounding scope.
Available,
/// The register has been moved, and shouldn't be dropped.
Moved,
/// The register contains a value of which one or more fields have been
/// moved, but the containing value itself hasn't been moved.
PartiallyMoved,
/// The register is moved in one branch, while remaining live when taking
/// another branch. Dropping of the register must be done conditionally.
MaybeMoved,
}
/// The states of MIR registers, grouped per basic block.
///
/// The state is grouped per block as it may change between blocks. For example,
/// given the graph `A -> B`, a register may be available in `A` while it's
/// moved in `B`.
struct RegisterStates {
mapping: HashMap<BlockId, HashMap<RegisterId, RegisterState>>,
}
impl RegisterStates {
fn new() -> Self {
Self { mapping: HashMap::new() }
}
fn set(
&mut self,
block: BlockId,
register: RegisterId,
state: RegisterState,
) {
self.mapping.entry(block).or_default().insert(register, state);
}
fn get(
&self,
block: BlockId,
register: RegisterId,
) -> Option<RegisterState> {
self.mapping.get(&block).and_then(|m| m.get(®ister)).cloned()
}
}
#[derive(Copy, Clone, Debug)]
pub(crate) enum RegisterKind {
/// A regular register to be dropped at the end of the surrounding scope.
Regular,
/// A temporary register introduced by pattern matching.
///
/// These differ from regular registers in that if they are a value type,
/// they should still be copied instead of used as-is.
MatchVariable,
/// A register introduced using a local variable.
///
/// The stored `u32` value is the scope depth in which the variable is
/// defined.
Variable(types::VariableId, u32),
/// A register introduced using a field.
///
/// We store the field ID as part of this so we can mark it as moved. Field
/// move states are stored separately, as field reads always produce new
/// registers.
Field(types::FieldId),
/// A register introduced for `self`.
///
/// These registers can't be moved if any fields have been moved.
SelfObject,
}
impl RegisterKind {
pub(crate) fn is_field(self) -> bool {
matches!(self, RegisterKind::Field(_))
}
pub(crate) fn new_reference_on_return(self) -> bool {
matches!(
self,
RegisterKind::Field(_)
| RegisterKind::SelfObject
| RegisterKind::Variable(_, _)
)
}
pub(crate) fn is_regular(self) -> bool {
matches!(self, RegisterKind::Regular)
}
fn name(self, db: &types::Database) -> Option<String> {
match self {
RegisterKind::Variable(id, _) => Some(id.name(db).clone()),
RegisterKind::Field(id) => Some(id.name(db).clone()),
RegisterKind::SelfObject => Some(SELF_NAME.to_string()),
_ => None,
}
}
}
#[derive(Debug)]
enum ScopeKind {
/// A regular scope.
Regular,
/// A scope introduced for a method call (chain).
Call,
/// The scope is created using the `loop` keyword.
///
/// The values stored are the block `next` should jump to, and the block
/// `break` should jump to.
Loop(BlockId, BlockId),
}
struct Scope {
kind: ScopeKind,
parent: Option<Box<Scope>>,
/// The registers created in this scope.
created: Vec<RegisterId>,
/// The scope depth, starting at 1.
depth: u32,
/// The depth of the surrounding loop.
///
/// This value is set to zero if there's no loop surrounding the current
/// scope.
///
/// This value equals `depth` for the loop scope itself.
loop_depth: u32,
/// Registers that must be available at the end of a loop.
///
/// This uses a HashMap as a register may be assigned a new value after it
/// has been moved, only to be moved _again_. Using a Vec would result in
/// outdated entries.
moved_in_loop: HashMap<RegisterId, LocationId>,
}
impl Scope {
fn root_scope() -> Box<Self> {
Box::new(Self {
kind: ScopeKind::Regular,
created: Vec::new(),
parent: None,
depth: 1,
loop_depth: 0,
moved_in_loop: HashMap::new(),
})
}
fn regular_scope(parent: &Scope) -> Box<Self> {
Box::new(Self {
kind: ScopeKind::Regular,
created: Vec::new(),
parent: None,
depth: parent.depth + 1,
loop_depth: parent.loop_depth,
moved_in_loop: HashMap::new(),
})
}
fn call_scope(parent: &Scope) -> Box<Self> {
Box::new(Self {
kind: ScopeKind::Call,
created: Vec::new(),
parent: None,
depth: parent.depth + 1,
loop_depth: parent.loop_depth,
moved_in_loop: HashMap::new(),
})
}
fn loop_scope(
parent: &Scope,
next_block: BlockId,
break_block: BlockId,
) -> Box<Self> {
let depth = parent.depth + 1;
Box::new(Self {
kind: ScopeKind::Loop(next_block, break_block),
created: Vec::new(),
parent: None,
depth,
loop_depth: depth,
moved_in_loop: HashMap::new(),
})
}
fn is_loop(&self) -> bool {
matches!(self.kind, ScopeKind::Loop(_, _))
}
fn is_call(&self) -> bool {
matches!(self.kind, ScopeKind::Call)
}
}
/// A type describing the action to take when destructuring an object as part of
/// a pattern.
#[derive(Copy, Clone)]
enum RegisterAction {
/// A field is to be moved into a new register.
///
/// The wrapped value is the register that owned the field.
Move(RegisterId),
/// A field is to be incremented, and the reference moved into a new
/// register.
///
/// The wrapped value is the register that owned the field.
Increment(RegisterId),
}
struct DecisionState {
/// The register to write the results of a case body to.
output: RegisterId,
/// The block to jump to at the end of a case body.
after_block: BlockId,
/// The registers for all pattern matching variables, in the same order as
/// the variables.
registers: Vec<RegisterId>,
/// The action to take per register when destructuring a value such as an
/// enum variant of class.
actions: HashMap<RegisterId, RegisterAction>,
/// The basic blocks for every case body, and the code to compile for them.
bodies: HashMap<
BlockId,
(Vec<hir::Expression>, Vec<RegisterId>, SourceLocation),
>,
/// The location of the `match` expression.
location: LocationId,
/// If the result of a match arm should be written to a register or ignored.
write_result: bool,
}
impl DecisionState {
fn new(
output: RegisterId,
after_block: BlockId,
write_result: bool,
location: LocationId,
) -> Self {
Self {
output,
after_block,
registers: Vec::new(),
actions: HashMap::new(),
bodies: HashMap::new(),
location,
write_result,
}
}
fn input_register(&self) -> RegisterId {
self.registers[0]
}
}
pub(crate) struct GenerateDropper<'a> {
pub(crate) state: &'a mut State,
pub(crate) mir: &'a mut Mir,
pub(crate) module: ModuleId,
pub(crate) class: ClassId,
pub(crate) location: LocationId,
}
impl<'a> GenerateDropper<'a> {
pub(crate) fn run(mut self) -> MethodId {
match self.class.kind(&self.state.db) {
types::ClassKind::Async => self.async_class(),
types::ClassKind::Enum => self.enum_class(),
_ => self.regular_class(),
}
}
/// Generates the dropper method for a regular class.
///
/// This version runs the destructor (if any), followed by running the
/// dropper of every field. Finally, it frees the receiver.
fn regular_class(&mut self) -> MethodId {
self.generate_dropper(
types::DROPPER_METHOD,
types::MethodKind::Mutable,
true,
false,
)
}
/// Generates the dropper methods for an async class.
///
/// Async classes are dropped asynchronously. This is achieved as follows:
/// the regular dropper simply schedules an async version of the drop glue.
/// Because this only runs when removing the last reference to the process,
/// the async dropper is the last message. When run, it cleans up the object
/// like a regular class, and the process shuts down.
fn async_class(&mut self) -> MethodId {
let loc = self.location;
let async_dropper = self.generate_dropper(
types::ASYNC_DROPPER_METHOD,
types::MethodKind::AsyncMutable,
false,
true,
);
let dropper_type =
self.method_type(types::DROPPER_METHOD, types::MethodKind::Mutable);
let mut dropper_method = Method::new(dropper_type, loc);
let mut lower = LowerMethod::new(
self.state,
self.mir,
self.module,
&mut dropper_method,
);
lower.prepare(loc);
let self_reg = lower.self_register;
let nil_reg = lower.get_nil(loc);
// We don't need to increment here, because we only reach this point
// when all references are gone and no messages are in flight any more,
// thus no new messages can be produced.
lower.current_block_mut().send(
self_reg,
async_dropper,
Vec::new(),
None,
loc,
);
lower.current_block_mut().return_value(nil_reg, loc);
assert_eq!(lower.method.arguments.len(), 1);
assert!(lower.method.id.is_instance_method(&self.state.db));
self.add_method(types::DROPPER_METHOD, dropper_type, dropper_method);
dropper_type
}
/// Generates the dropper method for an enum class.
///
/// For enums the drop logic is a bit different: based on the value of the
/// tag, certain fields may be set to NULL. As such we branch based on the
/// tag value, and only drop the fields relevant for that tag.
fn enum_class(&mut self) -> MethodId {
let loc = self.location;
let name = types::DROPPER_METHOD;
let class = self.class;
let drop_method_opt = class.method(&self.state.db, types::DROP_METHOD);
let method_type = self.method_type(name, types::MethodKind::Mutable);
let mut method = Method::new(method_type, loc);
let mut lower =
LowerMethod::new(self.state, self.mir, self.module, &mut method);
lower.prepare(loc);
let self_reg = lower.self_register;
if let Some(id) = drop_method_opt {
let typ = TypeRef::nil();
let res = lower.new_register(typ);
lower.current_block_mut().call_instance(
res,
self_reg,
id,
Vec::new(),
None,
loc,
);
}
let variants = class.variants(lower.db());
let mut blocks = Vec::new();
let before_block = lower.current_block;
let after_block = lower.add_block();
let enum_fields = class.enum_fields(lower.db());
let tag_field =
class.field_by_index(lower.db(), types::ENUM_TAG_INDEX).unwrap();
let tag_reg = lower.new_register(TypeRef::int());
for var in variants {
let block = lower.add_current_block();
lower.add_edge(before_block, block);
let members = var.members(lower.db());
let fields = &enum_fields[0..members.len()];
for (&field, typ) in fields.iter().zip(members.into_iter()) {
let reg = lower.new_register(typ);
lower
.current_block_mut()
.get_field(reg, self_reg, class, field, loc);
lower.drop_register(reg, loc);
}
lower.current_block_mut().goto(after_block, loc);
lower.add_edge(lower.current_block, after_block);
blocks.push(block);
}
lower
.block_mut(before_block)
.get_field(tag_reg, self_reg, class, tag_field, loc);
lower.block_mut(before_block).switch(tag_reg, blocks, loc);
lower.current_block = after_block;
// Destructors may introduce new references, so we have to check again.
// We do this _after_ processing fields so we can correctly drop cyclic
// types.
lower.current_block_mut().check_refs(self_reg, loc);
lower.drop_register(tag_reg, loc);
lower.current_block_mut().free(self_reg, loc);
let nil_reg = lower.get_nil(loc);
lower.current_block_mut().return_value(nil_reg, loc);
self.add_method(name, method_type, method);
method_type
}
fn generate_dropper(
&mut self,
name: &str,
kind: types::MethodKind,
free_self: bool,
terminate: bool,
) -> MethodId {
let class = self.class;
let drop_method_opt = class.method(&self.state.db, types::DROP_METHOD);
let method_type = self.method_type(name, kind);
let loc = self.location;
let mut method = Method::new(method_type, loc);
let mut lower =
LowerMethod::new(self.state, self.mir, self.module, &mut method);
lower.prepare(loc);
let self_reg = lower.self_register;
if let Some(id) = drop_method_opt {
let typ = TypeRef::nil();
let res = lower.new_register(typ);
lower.current_block_mut().call_instance(
res,
self_reg,
id,
Vec::new(),
None,
loc,
);
}
for field in class.fields(lower.db()) {
let typ = field.value_type(lower.db());
if typ.is_permanent(lower.db()) {
continue;
}
let reg = lower.new_register(typ);
lower
.current_block_mut()
.get_field(reg, self_reg, class, field, loc);
lower.drop_register(reg, loc);
}
// Destructors may introduce new references, so we have to check again.
// We do this _after_ processing fields so we can correctly drop cyclic
// types.
lower.current_block_mut().check_refs(self_reg, loc);
if free_self {
lower.current_block_mut().free(self_reg, loc);
}
if terminate {
// No need to decrement here, because we only reach this point when
// all references and pending messages are gone.
lower.current_block_mut().finish(true, loc);
} else {
let nil_reg = lower.get_nil(loc);
lower.current_block_mut().return_value(nil_reg, loc);
}
self.add_method(name, method_type, method);
method_type
}
fn method_type(&mut self, name: &str, kind: types::MethodKind) -> MethodId {
let id = types::Method::alloc(
&mut self.state.db,
self.module,
name.to_string(),
types::Visibility::TypePrivate,
kind,
);
let self_type =
types::TypeId::ClassInstance(types::ClassInstance::rigid(
&mut self.state.db,
self.class,
&types::TypeBounds::new(),
));
let receiver = TypeRef::Mut(self_type);
id.set_receiver(&mut self.state.db, receiver);
id.set_return_type(&mut self.state.db, TypeRef::nil());
id
}
fn add_method(&mut self, name: &str, id: MethodId, method: Method) {
let cid = self.class;
cid.add_method(&mut self.state.db, name.to_string(), id);
self.mir.classes.get_mut(&cid).unwrap().methods.push(id);
self.mir.methods.insert(id, method);
}
}
pub(crate) struct DefineConstants<'a> {
state: &'a mut State,
mir: &'a mut Mir,
module_id: types::ModuleId,
}
impl<'a> DefineConstants<'a> {
pub(crate) fn run_all(
state: &mut State,
mir: &mut Mir,
modules: &Vec<hir::Module>,
) -> bool {
// Literal constants are defined first, as binary constants may depend
// on their values.
for module in modules {
let module_id = module.module_id;
DefineConstants { state, mir, module_id }.define_literal(module);
}
for module in modules {
let module_id = module.module_id;
DefineConstants { state, mir, module_id }.define_binary(module);
}
!state.diagnostics.has_errors()
}
/// Defines constants who's values are literals.
fn define_literal(&mut self, module: &hir::Module) {
for expr in &module.expressions {
if let hir::TopLevelExpression::Constant(n) = expr {
let id = n.constant_id.unwrap();
let val = match n.value {
hir::ConstExpression::Int(ref n) => Constant::Int(n.value),
hir::ConstExpression::String(ref n) => {
Constant::String(n.value.clone())
}
hir::ConstExpression::Float(ref n) => {
Constant::Float(n.value)
}
_ => continue,
};
self.mir.constants.insert(id, val);
}
}
}
/// Defines constants who's values are binary expressions.
fn define_binary(&mut self, module: &hir::Module) {
for expr in &module.expressions {
if let hir::TopLevelExpression::Constant(n) = expr {
let id = n.constant_id.unwrap();
let val = self.expression(&n.value);
self.mir.constants.insert(id, val);
}
}
}
fn expression(&mut self, node: &hir::ConstExpression) -> Constant {
match node {
hir::ConstExpression::Int(ref n) => Constant::Int(n.value),
hir::ConstExpression::String(ref n) => {
Constant::String(n.value.clone())
}
hir::ConstExpression::Float(ref n) => Constant::Float(n.value),
hir::ConstExpression::Binary(ref n) => self.binary(n),
hir::ConstExpression::True(_) => Constant::Bool(true),
hir::ConstExpression::False(_) => Constant::Bool(false),
hir::ConstExpression::ConstantRef(ref n) => match n.kind {
types::ConstantKind::Constant(id) => {
self.mir.constants.get(&id).cloned().unwrap()
}
types::ConstantKind::Builtin(id) => match id {
types::BuiltinConstant::Arch => Constant::String(
self.state.config.target.arch_name().to_string(),
),
types::BuiltinConstant::Os => Constant::String(
self.state.config.target.os_name().to_string(),
),
types::BuiltinConstant::Abi => Constant::String(
self.state.config.target.abi_name().to_string(),
),
},
_ => unreachable!(),
},
hir::ConstExpression::Array(ref n) => Constant::Array(
n.values.iter().map(|n| self.expression(n)).collect(),
),
hir::ConstExpression::Invalid(_) => unreachable!(),
}
}
fn binary(&mut self, node: &hir::ConstBinary) -> Constant {
let left = self.expression(&node.left);
let right = self.expression(&node.right);
let op = node.operator;
let loc = &node.location;
match left {
Constant::Int(lhs) => {
let mut res = None;
if let Constant::Int(rhs) = right {
res = match op {
hir::Operator::Add => lhs.checked_add(rhs),
hir::Operator::BitAnd => Some(lhs & rhs),
hir::Operator::BitOr => Some(lhs | rhs),
hir::Operator::BitXor => Some(lhs ^ rhs),
hir::Operator::Div => lhs.checked_div(rhs),
hir::Operator::Mod => modulo(lhs, rhs),
hir::Operator::Mul => lhs.checked_mul(rhs),
hir::Operator::Pow => Some(lhs.pow(rhs as u32)),
hir::Operator::Shl => lhs.checked_shl(rhs as u32),
hir::Operator::Shr => lhs.checked_shr(rhs as u32),
hir::Operator::UnsignedShr => (lhs as u64)
.checked_shr(rhs as u32)
.map(|v| v as i64),
hir::Operator::Sub => lhs.checked_sub(rhs),
_ => None,
};
}
if let Some(val) = res {
Constant::Int(val)
} else {
self.const_expr_error(&left, op, &right, loc);
Constant::Int(0)
}
}
Constant::Float(lhs) => {
let mut res = None;
if let Constant::Float(rhs) = right {
res = match op {
hir::Operator::Add => Some(lhs + rhs),
hir::Operator::Div => Some(lhs / rhs),
hir::Operator::Mod => Some(((lhs % rhs) + rhs) % rhs),
hir::Operator::Mul => Some(lhs * rhs),
hir::Operator::Pow => Some(lhs.powf(rhs)),
hir::Operator::Sub => Some(lhs - rhs),
_ => None,
};
}
if let Some(val) = res {
Constant::Float(val)
} else {
self.const_expr_error(&left, op, &right, loc);
Constant::Float(0.0)
}
}
Constant::String(ref lhs) => {
let mut res = None;
if let Constant::String(ref rhs) = right {
if node.operator == hir::Operator::Add {
res = Some(format!("{}{}", lhs, rhs))
}
}
if let Some(val) = res {
Constant::String(val)
} else {
self.const_expr_error(&left, op, &right, loc);
Constant::String(String::new())
}
}
Constant::Array(_) | Constant::Bool(_) => {
self.state.diagnostics.error(
DiagnosticId::InvalidConstExpr,
"constant Array and Bool values don't support \
binary operations",
self.file(),
node.location.clone(),
);
left
}
}
}
fn db(&self) -> &types::Database {
&self.state.db
}
fn file(&self) -> PathBuf {
self.module_id.file(self.db())
}
fn const_expr_error(
&mut self,
lhs: &Constant,
operator: hir::Operator,
rhs: &Constant,
location: &SourceLocation,
) {
self.state.diagnostics.invalid_const_expression(
&lhs.to_string(),
operator.method_name(),
&rhs.to_string(),
self.file(),
location.clone(),
);
}
}
/// A compiler pass that lowers the HIR of all modules to MIR.
pub(crate) struct LowerToMir<'a> {
state: &'a mut State,
mir: &'a mut Mir,
module: ModuleId,
}
impl<'a> LowerToMir<'a> {
pub(crate) fn run_all(
state: &mut State,
mir: &mut Mir,
nodes: Vec<hir::Module>,
) -> bool {
let mut modules = Vec::new();
let mut mod_types = Vec::new();
let mut mod_nodes = Vec::new();
// Traits and classes must be lowered first, so we can process
// implementations later.
for module in nodes {
let (types, rest) = module.expressions.into_iter().partition(|v| {
matches!(
v,
hir::TopLevelExpression::Trait(_)
| hir::TopLevelExpression::Class(_)
| hir::TopLevelExpression::ExternClass(_)
)
});
let id = module.module_id;
mod_types.push(types);
mod_nodes.push(rest);
modules.push(id);
mir.modules.insert(id, Module::new(id));
}
for (&module, nodes) in modules.iter().zip(mod_types.into_iter()) {
LowerToMir { state, mir, module }.lower_types(nodes);
}
for (&module, nodes) in modules.iter().zip(mod_nodes.into_iter()) {
LowerToMir { state, mir, module }.lower_rest(nodes);
}
!state.diagnostics.has_errors()
}
fn lower_types(&mut self, nodes: Vec<hir::TopLevelExpression>) {
for expr in nodes {
match expr {
hir::TopLevelExpression::Trait(n) => {
self.define_trait(*n);
}
hir::TopLevelExpression::Class(n) => {
self.define_class(*n);
}
hir::TopLevelExpression::ExternClass(n) => {
self.define_extern_class(*n);
}
_ => {}
}
}
}
fn lower_rest(&mut self, nodes: Vec<hir::TopLevelExpression>) {
let id = self.module;
let mut mod_methods = Vec::new();
for expr in nodes {
match expr {
hir::TopLevelExpression::Constant(n) => {
let mod_id = self.module;
self.mir
.modules
.get_mut(&mod_id)
.unwrap()
.constants
.push(n.constant_id.unwrap())
}
hir::TopLevelExpression::ModuleMethod(n) => {
mod_methods.push(self.define_module_method(*n));
}
hir::TopLevelExpression::Implement(n) => {
self.implement_trait(*n);
}
hir::TopLevelExpression::Reopen(n) => {
self.reopen_class(*n);
}
_ => {}
}
}
let mod_class_id = id.class(self.db());
let mut mod_class = Class::new(mod_class_id);
mod_class.add_methods(&mod_methods);
self.mir.add_methods(mod_methods);
self.add_class(mod_class_id, mod_class);
}
fn define_trait(&mut self, node: hir::DefineTrait) {
let mut methods = Vec::new();
for expr in node.body {
if let hir::TraitExpression::InstanceMethod(n) = expr {
methods.push(self.define_instance_method(*n));
}
}
self.mir.add_methods(methods);
}
fn implement_trait(&mut self, node: hir::ImplementTrait) {
let class_id = node.class_instance.unwrap().instance_of();
let trait_id = node.trait_instance.unwrap().instance_of();
let mut methods = Vec::new();
let mut names = HashSet::new();
for expr in node.body {
let method = self.define_instance_method(expr);
names.insert(method.id.name(self.db()).clone());
methods.push(method);
}
for id in trait_id.default_methods(self.db()) {
if !names.contains(id.name(self.db())) {
let mut method = self.mir.methods.get(&id).unwrap().clone();
// We need to make sure to use the ID of the class'
// implementation of the method, rather than the ID of the
// method as defined in its source trait.
method.id =
class_id.method(self.db(), id.name(self.db())).unwrap();
methods.push(method);
}
}
self.mir.classes.get_mut(&class_id).unwrap().add_methods(&methods);
self.mir.add_methods(methods);
}
fn define_class(&mut self, node: hir::DefineClass) {
let id = node.class_id.unwrap();
let mut methods = Vec::new();
for expr in node.body {
match expr {
hir::ClassExpression::InstanceMethod(n) => {
methods.push(self.define_instance_method(*n));
}
hir::ClassExpression::StaticMethod(n) => {
self.define_static_method(*n);
}
hir::ClassExpression::AsyncMethod(n) => {
methods.push(self.define_async_method(*n));
}
hir::ClassExpression::Variant(n) => {
methods.push(self.define_variant_method(*n, id));
}
_ => {}
}
}
let mut class = Class::new(id);
let loc = self.mir.add_location(node.location);
class.add_methods(&methods);
self.mir.add_methods(methods);
self.add_class(id, class);