-
Notifications
You must be signed in to change notification settings - Fork 44
/
codegen.rs
2361 lines (1929 loc) · 70.4 KB
/
codegen.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
use std::collections::{HashMap, HashSet, VecDeque};
use crate::{
ast::{
Arm, Binding, Constructor, DebugKind, EnumDefinition, EnumFieldDef, Expr, File, FileId,
Function, FunctionKind, Generic, InterfaceSuperTrait, Literal, Loop, LoopFlow, Operator,
Pat, SelectArm, SelectArmPat, Span, StrType, StructDefinition, StructField, UnOp,
},
global_state::Module,
infer,
type_::{ModuleId, Symbol, Type},
};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct EmittedFile {
pub name: String,
pub source: String,
pub imports: HashMap<String, String>, // "full/path" => name
}
impl EmittedFile {
pub fn render_source(&self) -> String {
let mut out = emitter();
out.emit("package main".to_string());
out.emit("import (".to_string());
for (path, name) in &self.imports {
out.emit(format!("{name} \"{path}\""));
}
out.emit(")".to_string());
out.emit(self.source.to_string());
out.render()
}
}
struct Emitter {
output: Vec<String>,
}
impl Emitter {
pub fn render(&self) -> String {
self.output.join("\n")
}
pub fn emit(&mut self, line: String) {
self.output.push(line)
}
pub fn emit_value(&self, value: String) -> EmitResult {
EmitResult {
output: self.render(),
value: Some(value),
}
}
pub fn no_value(&self) -> EmitResult {
EmitResult {
output: self.render(),
value: None,
}
}
fn as_value(&self) -> EmitResult {
EmitResult {
output: "".to_string(),
value: Some(self.render()),
}
}
fn try_emit(&self, result: Option<String>) -> EmitResult {
match result {
Some(result) => self.emit_value(result),
None => self.no_value(),
}
}
}
#[derive(Debug)]
struct EmitResult {
output: String,
value: Option<String>,
}
impl EmitResult {
fn empty() -> EmitResult {
EmitResult {
output: "".to_string(),
value: None,
}
}
fn unit() -> EmitResult {
EmitResult {
output: "".to_string(),
value: Some(empty_struct()),
}
}
fn to_statement(&self) -> String {
let ret = self.output.clone();
format!(
"{ret} {value}",
value = self.value.to_owned().unwrap_or_default()
)
}
}
fn empty_struct() -> String {
"struct{}{}".to_string()
}
#[derive(Debug, Clone)]
enum Ctx {
Discard, // dont' care about the result
Var(String), // emit to this specific var
Arg, // emit to a new var and tell me which it is
}
impl Ctx {
fn to_mode(self) -> EmitMode {
EmitMode {
ctx: self,
should_return: false,
}
}
fn to_var(&self) -> Option<String> {
match self {
Ctx::Discard => None,
Ctx::Var(s) => Some(s.to_string()),
Ctx::Arg => None,
}
}
fn is_discard(&self) -> bool {
match self {
Ctx::Discard => true,
Ctx::Var(_) => false,
Ctx::Arg => false,
}
}
}
#[derive(Clone)]
struct EmitMode {
ctx: Ctx,
should_return: bool,
}
impl EmitMode {
fn top_level() -> EmitMode {
EmitMode {
ctx: Ctx::Discard,
should_return: false,
}
}
}
#[derive(Debug, PartialEq)]
enum CallWrapMode {
// function returns (ok, err) tuple, so needs to be wrapped in a Result
Wrapped,
// just call the function, return type doesn't need modifications
Unwrapped,
}
// A stack of IDENT => VAR bindings
struct Scope {
scopes: VecDeque<HashMap<String, String>>,
}
impl Scope {
fn new() -> Self {
Self {
scopes: Default::default(),
}
}
fn reset(&mut self) {
self.scopes = Default::default();
self.begin();
}
fn begin(&mut self) {
self.scopes.push_front(Default::default());
}
fn add_binding(&mut self, k: String, v: String) {
self.scopes.front_mut().unwrap().insert(k, v);
}
fn exit(&mut self) {
self.scopes.pop_front();
}
fn get_binding(&self, value: &str) -> Option<String> {
self.scopes
.iter()
.find_map(|scope| scope.get(value))
.cloned()
}
fn is_defined_in_current_scope(&self, value: &str) -> bool {
self.scopes.front().unwrap().get(value).is_some()
}
}
pub struct Codegen {
pub next_var: usize,
// functions used to build enum constructors, ie. make_Option_Some()
pub make_functions: HashMap<String, String>,
// resolve type aliases
pub instance: infer::Infer,
// let bindings are re-bound to temporary vars
// ie. let x = 1
// becomes `var varN any; varN = 1`
// this allows inner scopes to reference existing bindings
// IDENT => VAR
scope: Scope,
// The return type of the current function being generated
current_fn_ret_ty: Option<Type>,
// The module being emitted (this is only here to skip emitting traits in std)
current_module: ModuleId,
// Ensure these packages are imported
ensure_imported: HashSet<ModuleId>,
}
impl Codegen {
pub fn new(instance: infer::Infer) -> Self {
Self {
next_var: 0,
make_functions: Default::default(),
instance,
scope: Scope::new(),
current_fn_ret_ty: None,
current_module: ModuleId::empty(),
ensure_imported: Default::default(),
}
}
pub fn compile_module(&mut self, module: &Module) -> Vec<EmittedFile> {
self.current_module = module.id.clone();
// collect make functions first so that all enums are registered
let make_functions = self.collect_make_functions(&module.files);
module
.files
.values()
.map(|file| {
let mut source = emitter();
// A bit dumb, but std can't have dependencies for now at least
let imports = if module.id == ModuleId::from_str("std") {
self.get_std_imports()
} else {
self.collect_imports(file)
};
// emit make functions
for f in make_functions.get(&file.id).cloned().unwrap_or_default() {
source.emit(f);
}
file.decls.iter().for_each(|expr| {
self.next_var = 0;
self.scope.reset();
let value = self.emit_expr(EmitMode::top_level(), expr);
source.emit(value.to_statement())
});
// Extend imports to whatever extra packages were collected during codegen.
// This is useful if there's an indirect dependency on a package.
// For example:
// - package os: fn Open() -> Option<fs::File>
// when calling os::Open() we need to instantiate the generic for Option,
// so package "fs" also needs to be in scope.
let imports = self.extend_imports(&imports, &self.ensure_imported.clone());
self.ensure_imported = Default::default();
EmittedFile {
name: file.go_filename(),
imports,
source: source.render(),
}
})
.collect()
}
fn fresh_var(&mut self) -> String {
self.next_var += 1;
format!("var{next}", next = self.next_var)
}
// Most expressions will ignore mode and ctx
// Only if/match/block have to care about it
fn emit_expr(&mut self, mode: EmitMode, expr: &Expr) -> EmitResult {
match expr {
Expr::Closure { fun, kind, .. } => self.emit_closure(fun, kind, None),
Expr::Block { stmts, .. } => self.emit_block(mode, stmts, false),
Expr::Call { func, args, ty, .. } => {
let call_mode = if mode.ctx.is_discard() && !mode.should_return {
// if the result should be discarded, there's no point in wrapping the value.
// This is the case when the last expression in a block returns a result (ie.
// fmt.Fprintf) but the current function returns unit so the value can be
// safely dropped and the call doesn't need to be wrapped.
CallWrapMode::Unwrapped
} else {
self.call_wrap_mode(ty)
};
self.emit_call(func, args, call_mode)
}
Expr::Literal { lit, ty, .. } => self.emit_literal(lit, ty),
Expr::Debug { kind, expr, ty, .. } => self.emit_debug(kind, expr, ty),
Expr::Return { expr, .. } => self.emit_return(expr),
Expr::Var {
value,
ty,
generics_instantiated,
..
} => self.emit_var(value, ty, generics_instantiated),
Expr::Match {
subject, arms, ty, ..
} => self.emit_match(&mode.ctx, subject, arms, ty),
Expr::Let { binding, value, .. } => self.emit_let(binding, value),
Expr::Binary {
op, left, right, ..
} => self.emit_binary(op, left, right),
Expr::If {
cond, then, els, ..
} => self.emit_if(&mode.ctx, cond, then, els),
Expr::Unit { .. } => EmitResult::unit(),
Expr::EnumDef { def, .. } => self.emit_enum(def),
Expr::StructDef { def, .. } => self.emit_struct(def),
Expr::ImplBlock {
self_name,
ty,
items,
generics,
..
} => self.emit_impl(self_name, ty, generics, items),
Expr::StructCall {
fields, rest, ty, ..
} => self.emit_struct_call(fields, rest, ty),
Expr::FieldAccess { expr, field, .. } => self.emit_struct_access(expr, field),
Expr::Try { expr, .. } => self.emit_try(&mode.ctx, expr),
Expr::Unary { op, expr, .. } => self.emit_unary(op, expr),
Expr::Noop { .. } => EmitResult::unit(),
Expr::Loop { kind, body, .. } => match kind {
Loop::NoCondition => self.emit_loop(body),
Loop::WithCondition { binding, expr } => {
self.emit_loop_with_condition(binding, expr, body)
}
Loop::While { expr } => self.emit_while_loop(expr, body),
},
Expr::Flow { kind, .. } => self.emit_loop_flow(kind),
Expr::VarUpdate { value, target, .. } => self.emit_var_update(value, target),
Expr::Const { ident, expr, .. } => self.emit_const(ident, expr),
Expr::CheckType { .. } => EmitResult::empty(),
Expr::Paren { expr, .. } => self.emit_paren(expr),
Expr::Spawn { expr, .. } => self.emit_spawn(expr),
Expr::Select { arms, .. } => self.emit_select(arms),
Expr::Defer { expr, .. } => self.emit_defer(expr),
Expr::Reference { expr, .. } => self.emit_reference(expr),
Expr::Index { expr, index, .. } => self.emit_index(expr, index),
Expr::Raw { text } => self.emit_raw(text),
Expr::TypeAlias { .. } => EmitResult::empty(),
Expr::NewtypeDef { .. } => EmitResult::empty(), // TODO asdf emit "type Foo int"
Expr::UsePackage { .. } => EmitResult::empty(),
Expr::Trait {
name,
items,
supertraits,
..
} => self.emit_interface(name, items, supertraits),
Expr::Tuple { .. } => unreachable!(),
Expr::MethodCall { .. } => unreachable!(),
Expr::Todo { .. } => todo!(),
}
}
fn emit_local(&mut self, expr: &Expr, out: &mut Emitter) -> String {
let res = self.emit_expr(Ctx::Arg.to_mode(), expr);
let value = res.value.unwrap_or_default();
out.emit(res.output);
value
}
fn emit_pattern(&mut self, subject: &str, is_matching: &str, pat: &Pat) -> String {
let mut out = emitter();
// In let bindings, we still use emit_pattern to destructure the argument.
// But in that case, there's no parent matching context that we care about, as is the case
// in match expressions. So there's no point emitting all the if statements.
let cares_about_matching = is_matching != "_";
let new_is_matching = if cares_about_matching {
self.fresh_var() + "_match_pat"
} else {
is_matching.to_string()
};
match pat {
Pat::Lit { lit, ty, span } => {
let lit = Expr::Literal {
lit: lit.clone(),
ty: ty.clone(),
span: span.clone(),
};
let value = self.emit_local(&lit, &mut out);
out.emit(format!(
"
if {is_matching} != 1 && {value} == {subject} {{
{is_matching} = 2
}} else {{
{is_matching} = 1
}}"
));
}
Pat::Type { ident, .. } => {
out.emit(format!("{ident} := {subject}"));
self.scope.add_binding(ident.clone(), ident.clone());
}
Pat::Pat { ident, elems, .. } => {
// Introduce a new sentinel matching value for the nested pattern match.
//
// For example, if we're trying to match (1, "foo")
// new_is_matching will be 2 if both fields match
// And then we can forward the success value to the parent is_matching
if cares_about_matching {
out.emit(format!("{new_is_matching} := 0"));
}
let (_, con_name) = ident.split_once(".").unwrap();
elems.iter().enumerate().for_each(|(index, p)| {
let field = constructor_field_name(con_name, elems.len(), index);
let new_subject = format!("{subject}.{field}");
let pat = self.emit_pattern(&new_subject, &new_is_matching, p);
out.emit(pat);
});
let name = to_name(ident);
if cares_about_matching {
// Check against new_is_matching but override parent is_matching for final check
out.emit(format!(
"
if {new_is_matching} != 1 && {subject}.tag == {name} {{
{is_matching} = 2
}} else {{
{is_matching} = 1
}}
"
));
}
}
Pat::Struct { fields, .. } => {
if cares_about_matching {
out.emit(format!("{new_is_matching} := 0"));
}
fields.iter().for_each(|f| {
let pat = self.emit_pattern(
&format!("{subject}.{field_name}", field_name = f.name),
&new_is_matching,
&f.value,
);
out.emit(pat);
});
if cares_about_matching {
out.emit(format!(
"
if {new_is_matching} != 1 {{
{is_matching} = 2
}} else {{
{is_matching} = 1
}}
"
));
}
}
Pat::Wild { .. } => {
if cares_about_matching {
out.emit(format!(
"if {is_matching} != 1 {{ {is_matching} = 2 /* wildcard */ }}"
))
}
}
Pat::Unit { .. } => {
if cares_about_matching {
out.emit(format!(
"if {is_matching} != 1 {{ {is_matching} = 2 /* Unit */ }}"
))
}
}
};
out.render()
}
// TODO asdf add Method variant to FunctionKind and remove receiver
fn emit_closure(
&mut self,
fun: &Function,
kind: &FunctionKind,
receiver: Option<(String, Type)>,
) -> EmitResult {
let mut out = emitter();
let mut args_destructure = emitter();
if fun.is_external() {
return out.no_value();
}
let prev_ret_ty = self.current_fn_ret_ty.clone(); // nested functions, save context
self.current_fn_ret_ty = Some(fun.ret.clone());
let (fun, receiver) = change_collection_methods(fun, receiver.clone());
let args = fun
.args
.iter()
.enumerate()
.map(|(index, a)| {
let name = match &a.pat {
Pat::Type { ident, .. } => {
// a binding is still necessary for this
self.scope.add_binding(ident.clone(), ident.clone());
ident.clone()
}
Pat::Wild { .. } => "_".to_string(),
_ => {
let var = format!("arg_{index}");
let pat = self.emit_pattern(&var, "_", &a.pat);
args_destructure.emit(pat);
var
}
};
name + " " + &self.to_type(&a.ty)
})
.collect::<Vec<_>>()
.join(", ");
let stmts = wrap_block_and_get_statements(&fun.body);
let body = self
.emit_block(
EmitMode {
ctx: Ctx::Discard,
should_return: !fun.ret.is_unit(),
},
&stmts,
true,
)
.to_statement();
// There are 3 cases here:
// - Top level functions are always emitted as `func $name`
// - Lambdas are bound to an anonymous function `$name := func`
// - Inline functions may be recursive, so need a declaration first
// `var $name func(..); $name =`
let name = to_name(&fun.name);
let ret = if fun.ret.is_unit() {
"".to_string()
} else {
self.return_to_type(&fun.ret)
};
let generics = if receiver.is_none() {
generics_to_string(&fun.generics)
} else {
"".to_string()
};
let receiver_fmt = if let Some((self_name, ty)) = receiver {
format!("({self_name} {ty})", ty = self.to_type(&ty))
} else {
"".to_string()
};
let binding = match kind {
FunctionKind::TopLevel => {
format!("func {receiver_fmt} {name} {generics} ({args}) {ret}")
}
FunctionKind::Lambda => format!("func ({args}) {ret}"),
FunctionKind::Inline => {
let typed_args = fun
.args
.iter()
.map(|t| self.to_type(&t.ty))
.collect::<Vec<_>>()
.join(", ");
let mut decl = emitter();
// needs to be separate declaration to allow recursive functions.
decl.emit(format!("var {name} func ({typed_args}) {ret}"));
decl.emit(format!("{name} = func ({args}) {ret}"));
decl.render()
}
};
out.emit(format!(
"{binding} {{
{args_destructure}
{body}
}}",
args_destructure = args_destructure.render()
));
self.current_fn_ret_ty = prev_ret_ty;
out.as_value()
}
fn emit_block(&mut self, mode: EmitMode, stmts: &[Expr], skip_braces: bool) -> EmitResult {
let mut out = emitter();
let mut stmts = stmts.to_vec();
if stmts.is_empty() {
if !skip_braces {
out.emit("{}".to_string());
}
return out.no_value();
}
let unit = Expr::Unit {
ty: self.instance.type_unit(),
span: Span::dummy(),
};
let mut last = stmts.pop().unwrap_or(unit.clone());
// The logic here is a bit involved.
// We're basically trying to emit the cleanest output possible, while allowing for values
// to be discarded
if !is_standalone(&last) && !mode.should_return && !mode.ctx.is_discard() {
stmts.push(last);
last = unit;
}
if mode.should_return {
last = ensure_wrapped_in_return(&last);
}
let needs_braces = !stmts.is_empty() || mode.should_return;
if !skip_braces && needs_braces {
out.emit("{".to_string());
}
self.scope.begin();
stmts.iter().for_each(|e| {
let result = self.emit_expr(
EmitMode {
ctx: Ctx::Discard,
should_return: false,
},
e,
);
out.emit(result.to_statement());
});
let result = match mode.ctx {
Ctx::Discard => {
let value = self.emit_expr(mode, &last);
out.emit(value.to_statement());
None
}
Ctx::Var(_) => {
let result = self.emit_expr(mode.clone(), &last);
out.emit(result.output);
let assign = assign_to_result(&mode.ctx, &result.value.unwrap_or_default());
out.emit(assign);
None
}
Ctx::Arg => {
let value = self.emit_local(&last, &mut out);
Some(value)
}
};
self.scope.exit();
if !skip_braces && needs_braces {
out.emit("}".to_string());
}
out.try_emit(result)
}
fn emit_call(&mut self, func: &Expr, args: &[Expr], mode: CallWrapMode) -> EmitResult {
if let Some(res) = self.emit_collection_method(func, args, &mode) {
return res;
}
let mut out = emitter();
let new_args = args
.iter()
.map(|a| self.emit_local(a, &mut out))
.collect::<Vec<_>>()
.join(", ");
let new_func = self.emit_local(func, &mut out);
let instantiated = match func {
Expr::Var {
generics_instantiated,
..
} => self.render_generics_instantiated(generics_instantiated),
_ => "".to_string(),
};
let call = format!("{new_func}{instantiated}({new_args})");
return self.emit_wrapped_call(call, func, &mode, &mut out);
}
fn emit_wrapped_call(
&mut self,
call: String,
func: &Expr,
mode: &CallWrapMode,
out: &mut Emitter,
) -> EmitResult {
// if no wrapping needs to happen, then just return the call
if mode == &CallWrapMode::Unwrapped {
return out.emit_value(call);
}
// if the function is a call to the constructors Ok/Err or Some/None
// then we don't need to wrap and can emit the call as is
if func.as_result_constructor().is_some() || func.as_option_constructor().is_some() {
return out.emit_value(call);
}
// At this point we know that the function either needs to return (ok, err) or (ok, bool)
// The return type is either Result<T, E> or Option<T>
let ret = func.get_type().get_function_ret().unwrap();
let args = ret.get_args().unwrap();
// Instantiate generics on return type
let instantiated = self.render_generics_instantiated(&args);
// Ensure all referenced packages are imported
self.add_pkg_imports(&args);
// Handle Result<T, E>
if ret.is_result() {
let check = self.fresh_var() + "_check";
let err = self.fresh_var() + "_err";
let result = self.fresh_var() + "_result";
out.emit(format!(
"{result} := func() Result{instantiated} {{
{check}, {err} := {call}
if {err} != nil {{
return make_Result_Err{instantiated}({err})
}}
return make_Result_Ok{instantiated}({check})
}}()
"
));
return out.emit_value(result);
}
// Handle Option<T>
if ret.is_option() {
let check = self.fresh_var() + "_check";
let err = self.fresh_var() + "_err";
let result = self.fresh_var() + "_result";
out.emit(format!(
"{result} := func() Option{instantiated} {{
{check}, {err} := {call}
if {err} == false {{
return make_Option_None{instantiated}()
}}
return make_Option_Some{instantiated}({check})
}}()
"
));
return out.emit_value(result);
}
unreachable!("should be either Result or Option");
}
fn emit_literal(&mut self, lit: &Literal, ty: &Type) -> EmitResult {
let mut out = emitter();
let value = match lit {
Literal::Int(n) => n.to_string(),
Literal::Float(n) => n.to_string(),
Literal::Bool(b) => b.to_string(),
Literal::String(inner) => match inner {
StrType::Single(s) => format!("\"{}\"", s).replace('\n', "\\n"),
StrType::Multi(lines) => {
let body = lines.join("\n");
format!("`{}`", body)
}
},
Literal::Char(s) => {
format!("\'{}\'", s)
}
Literal::Slice(elems) => {
let new_elems = elems
.iter()
.map(|e| self.emit_local(e, &mut out))
.collect::<Vec<_>>()
.join(", ");
let instantiated = self.to_type(ty.get_args().unwrap().first().unwrap());
format!("[]{instantiated} {{ {new_elems} }}")
}
};
out.emit_value(value)
}
fn emit_debug(&mut self, kind: &DebugKind, expr: &Expr, ty: &Type) -> EmitResult {
let mut out = emitter();
let var = match kind {
DebugKind::Unreachable => "".to_string(),
DebugKind::Todo => "".to_string(),
DebugKind::Inspect => self.emit_local(expr, &mut out),
};
let fn_name = format!("{:#?}", kind).to_lowercase();
let instantiated = self.to_type(&ty);
out.emit_value(format!("Debug_{fn_name}[{instantiated}]({var})"))
}
fn emit_return(&mut self, expr: &Expr) -> EmitResult {
if let Some(ret) = self.return_value_is_result(expr) {
return ret;
}
if let Some(ret) = self.return_value_is_option(expr) {
return ret;
}
let mut out = emitter();
let value = if self.current_fn_ret_ty == Some(self.instance.type_unit()) {
"".to_string()
} else {
self.emit_local(expr, &mut out)
};
out.emit(format!("return {value}"));
out.no_value()
}
fn emit_match(&mut self, ctx: &Ctx, subject: &Expr, arms: &[Arm], ty: &Type) -> EmitResult {
let mut out = emitter();
let subject = self.emit_local(subject, &mut out);
let subject_var = self.fresh_var() + "_subject";
let is_matching = self.fresh_var() + "_matches";
let new_ctx = self.generate_or_reuse(ctx, ty, &mut out);
// Matching status:
// 0 -> pattern matching hasn't started
// 1 -> pattern matching failed
// 2 -> pattern matching succeeded
out.emit(format!(
" {subject_var} := {subject}
{is_matching} := 0
",
));
arms.iter().for_each(|arm| {
let if_statements = self.emit_pattern(&subject_var, &is_matching, &arm.pat);
let result = self.emit_expr(new_ctx.clone().to_mode(), &arm.expr);
let assign = assign_to_result(&new_ctx, &result.value.unwrap_or_default());
let preamble = result.output;
out.emit(format!(
"
if {is_matching} != 2 {{
{is_matching} = 0
{if_statements}
_ = {subject_var}
if {is_matching} == 2 {{
{preamble}
{assign}
}}
}}
"
))
});
out.try_emit(new_ctx.to_var())
}
fn emit_var(&mut self, value: &str, ty: &Type, generics_instantiated: &[Type]) -> EmitResult {
let name = self.scope.get_binding(value).unwrap_or_else(|| {
value.to_string()
// panic!("failed to resolve {}", value);
});
// .unwrap_or_else(|| self.gs.resolve_name(value));
let make_fn = self.make_functions.get(&name);
// Check if it's a constructor with no arguments (ie. Option::None)
// In that case, it's not sufficient to resolve it as a bare function.
// We need to actually call the function and instantiate the generics.
if matches!(ty, Type::Con { .. }) && make_fn.is_some() {
let generics = self.render_generics_instantiated(generics_instantiated);
let call = format!("{fun}{generics}()", fun = to_name(make_fn.unwrap()));
return EmitResult {
output: "".to_string(),
value: Some(call),
};
}
let name = to_name(make_fn.unwrap_or(&name));
EmitResult {
output: "".to_string(),
value: Some(name),
}
}
fn emit_let(&mut self, binding: &Binding, value: &Expr) -> EmitResult {
let mut out = emitter();
let mut needs_declaration = true;
let mut pat_output = None;
let ctx = match binding.pat {
Pat::Type { ref ident, .. } => {
if self.scope.is_defined_in_current_scope(ident) {
needs_declaration = false;
}
self.scope.add_binding(ident.clone(), ident.clone());
Ctx::Var(ident.clone())
}
Pat::Wild { .. } => Ctx::Discard,
_ => {
let var = self.fresh_var();
let pat = self.emit_pattern(&var, "_", &binding.pat);
pat_output = Some(pat);
Ctx::Var(var)
}
};
// If it's a try expression, then a declaration is never necessary because it will define