-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathcodegen.rs
More file actions
2506 lines (2347 loc) · 98.6 KB
/
Copy pathcodegen.rs
File metadata and controls
2506 lines (2347 loc) · 98.6 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
// Copyright 2022 The Goscript Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use crate::branch::*;
use crate::consts::*;
use crate::context::*;
use crate::package::PkgHelper;
use crate::types::{SelectionType, TypeCache, TypeLookup};
use go_parser::ast::*;
use go_parser::visitor::{walk_decl, walk_expr, walk_stmt, ExprVisitor, StmtVisitor};
use go_parser::*;
use go_types::{
check::TypeInfo,
typ::{identical_ignore_tags, Type},
Builtin, ObjKey as TCObjKey, OperandMode, PackageKey as TCPackageKey, TCObjects,
TypeKey as TCTypeKey,
};
use go_vm::types::*;
use go_vm::*;
use std::hash::Hash;
use std::iter::FromIterator;
macro_rules! func_ctx {
($gen:ident) => {
$gen.func_ctx_stack.last_mut().unwrap()
};
}
macro_rules! expr_ctx {
($gen:ident) => {
$gen.expr_ctx_stack.last_mut().unwrap()
};
}
/// CodeGen implements the code generation logic.
pub(crate) struct CodeGen<'a, 'c> {
vmctx: &'a mut CodeGenVMCtx,
consts: &'c Consts,
ast_objs: &'a AstObjects,
tc_objs: &'a TCObjects,
t: TypeLookup<'a>,
iface_selector: &'a mut IfaceSelector,
struct_selector: &'a mut StructSelector,
branch_helper: &'a mut BranchHelper,
pkg_helper: &'a mut PkgHelper<'a>,
pkg_key: PackageKey,
blank_ident: IdentKey,
func_ctx_stack: Vec<FuncCtx<'c>>,
expr_ctx_stack: Vec<ExprCtx>,
results: Vec<FuncCtx<'c>>,
}
impl<'a, 'c> CodeGen<'a, 'c> {
pub fn new(
vmctx: &'a mut CodeGenVMCtx,
consts: &'c Consts,
ast_objs: &'a AstObjects,
tc_objs: &'a TCObjects,
ti: &'a TypeInfo,
type_cache: &'a mut TypeCache,
iface_selector: &'a mut IfaceSelector,
struct_selector: &'a mut StructSelector,
branch_helper: &'a mut BranchHelper,
pkg_helper: &'a mut PkgHelper<'a>,
pkg_key: PackageKey,
blank_ident: IdentKey,
) -> CodeGen<'a, 'c> {
CodeGen {
vmctx,
consts,
ast_objs,
tc_objs,
t: TypeLookup::new(tc_objs, ti, type_cache),
iface_selector,
struct_selector,
branch_helper,
pkg_helper,
pkg_key,
blank_ident,
func_ctx_stack: vec![],
expr_ctx_stack: vec![],
results: vec![],
}
}
fn resolve_any_ident(&mut self, ident: &IdentKey, expr: Option<&Expr>) -> VirtualAddr {
let mode = expr.map_or(&OperandMode::Value, |x| self.t.expr_mode(x));
match mode {
OperandMode::TypeExpr => {
let tctype = self.t.underlying_tc(self.t.obj_use_tc_type(*ident));
match self.t.basic_type_meta(tctype, self.vmctx.prim_meta()) {
Some(meta) => VirtualAddr::Direct(func_ctx!(self).add_metadata(meta)),
None => {
let id = &self.ast_objs.idents[*ident];
if id.name == "error" {
let m = self.t.tc_type_to_meta(tctype, self.vmctx);
VirtualAddr::Direct(func_ctx!(self).add_metadata(m))
} else {
self.resolve_var_ident(ident)
}
}
}
}
OperandMode::Value => {
let id = &self.ast_objs.idents[*ident];
match &*id.name {
"true" => VirtualAddr::Direct(func_ctx!(self).add_comparable(true.into())),
"false" => VirtualAddr::Direct(func_ctx!(self).add_comparable(false.into())),
"nil" => VirtualAddr::Direct(Addr::UntypedNil),
_ => self.resolve_var_ident(ident),
}
}
_ => self.resolve_var_ident(ident),
}
}
fn resolve_var_ident(&mut self, ident: &IdentKey) -> VirtualAddr {
let okey = self.t.object_use(*ident);
// 1. try local first
if let Some(index) = func_ctx!(self).entity_index(&okey).map(|x| *x) {
return VirtualAddr::Direct(index);
}
// 2. try upvalue
let upvalue = self
.func_ctx_stack
.iter()
.skip(1) // skip package constructor
.rev()
.skip(1) // skip itself
.find_map(|ctx| {
let index = ctx.entity_index(&okey).map(|x| *x);
if let Some(ind) = index {
let desc = ValueDesc::new(
ctx.f_key,
ind.as_var_index() as OpIndex,
self.t.obj_use_value_type(*ident),
false,
);
Some(desc)
} else {
None
}
});
if let Some(uv) = upvalue {
let ctx = func_ctx!(self);
let index = ctx.add_upvalue(&okey, uv);
return index;
}
// 3. must be package member
self.pkg_helper
.get_member_index(func_ctx!(self), okey, *ident)
}
fn add_local_or_resolve_ident(
&mut self,
ikey: &IdentKey,
is_def: bool,
) -> (VirtualAddr, Option<TCTypeKey>, usize) {
let ident = &self.ast_objs.idents[*ikey];
let pos = ident.pos;
if ident.is_blank() {
return (VirtualAddr::Blank, None, pos);
}
if is_def {
let tc_obj = self.t.object_def(*ikey);
let (index, tc_type, _) = self.add_local_var(tc_obj);
let ctx = func_ctx!(self);
if ctx.is_ctor(&self.vmctx.functions()) {
let pkg_key = self.vmctx.functions()[ctx.f_key].package;
let pkg = &mut self.vmctx.packages_mut()[pkg_key];
pkg.add_var_mapping(ident.name.clone(), index.as_var_index() as OpIndex);
}
(VirtualAddr::Direct(index), Some(tc_type), pos)
} else {
let index = self.resolve_var_ident(ikey);
let t = self.t.obj_use_tc_type(*ikey);
(index, Some(t), pos)
}
}
fn add_local_var(&mut self, okey: TCObjKey) -> (Addr, TCTypeKey, Meta) {
let tc_type = self.t.obj_tc_type(okey);
let meta = self.t.tc_type_to_meta(tc_type, self.vmctx);
let zero_val = self.vmctx.ffi_ctx().zero_val(&meta);
let ctx = func_ctx!(self);
let index = ctx.add_local(Some(okey), Some(zero_val));
(index, tc_type, meta)
}
fn gen_def_var(&mut self, vs: &ValueSpec) {
let lhs = vs
.names
.iter()
.map(|n| -> (VirtualAddr, Option<TCTypeKey>, usize) {
let (vaddr, t, pos) = self.add_local_or_resolve_ident(n, true);
(vaddr, t, pos)
})
.collect::<Vec<(VirtualAddr, Option<TCTypeKey>, usize)>>();
let rhs = if vs.values.is_empty() {
RightHandSide::Nothing
} else {
RightHandSide::Values(&vs.values)
};
self.gen_assign_def_var(&lhs, &vs.typ, &rhs);
}
fn gen_def_const(&mut self, names: &Vec<IdentKey>) {
for name in names.iter() {
let val = self.t.ident_const_value(name);
self.add_const_def(name, val);
}
}
/// entrance for all assign related stmts
/// var x
/// x := 0
/// x += 1
/// x++
/// for x := range xxx
/// recv clause of select stmt
fn gen_assign(
&mut self,
token: &Token,
lhs_exprs: &Vec<&Expr>,
rhs: RightHandSide,
) -> Option<usize> {
let lhs = lhs_exprs
.iter()
.map(|expr| match expr {
Expr::Ident(ident) => {
let is_def = self.t.ident_is_def(ident);
let (vaddr, typ, pos) = self.add_local_or_resolve_ident(ident, is_def);
(vaddr, typ, pos)
}
Expr::Index(ind_expr) => {
let obj = &ind_expr.as_ref().expr;
let obj_addr = self.load_mode_call(|g| g.gen_expr(obj));
let ind = &ind_expr.as_ref().index;
let ind_addr = match self.t.need_cast_container_index(obj, ind) {
None => self.load_mode_call(|g| g.gen_expr(ind)),
Some(t) => {
let iface_addr = expr_ctx!(self).inc_cur_reg();
self.store_mode_call(VirtualAddr::Direct(iface_addr), Some(t), |g| {
g.gen_expr(ind)
});
iface_addr
}
};
let obj_typ = self.t.expr_value_type(obj);
let typ = self.t.expr_tc_type(expr);
let pos = ind_expr.as_ref().l_brack;
let va = match obj_typ {
ValueType::Array => VirtualAddr::ArrayEntry(obj_addr, ind_addr),
ValueType::Slice => VirtualAddr::SliceEntry(obj_addr, ind_addr),
ValueType::Map => {
let zero_addr = self.add_zero_val(typ);
VirtualAddr::MapEntry(obj_addr, ind_addr, zero_addr)
}
_ => unreachable!(),
};
(va, Some(typ), pos)
}
Expr::Selector(sexpr) => {
let typ = Some(self.t.expr_tc_type(expr));
let pos = self.ast_objs.idents[sexpr.sel].pos;
match self.t.try_pkg_key(&sexpr.expr) {
Some(key) => {
let pkg = self.pkg_helper.get_runtime_key(key);
let pkg_addr = func_ctx!(self).add_comparable(FfiCtx::new_package(pkg));
let index_addr = Addr::PkgMemberIndex(pkg, sexpr.sel);
(VirtualAddr::PackageMember(pkg_addr, index_addr), typ, pos)
}
None => {
let mut struct_addr = self.load_mode_call(|g| g.gen_expr(&sexpr.expr));
let t = self.t.node_meta(sexpr.expr.id(), self.vmctx);
let name = &self.ast_objs.idents[sexpr.sel].name;
let indices: Vec<OpIndex> = t
.field_indices(name, self.vmctx.metas())
.iter()
.map(|x| *x as OpIndex)
.collect();
let (op, index) =
self.get_struct_field_op_index(indices, Opcode::LOAD_STRUCT);
if op == Opcode::LOAD_STRUCT {
if t.ptr_depth > 0 {
struct_addr = self.gen_load_pointer(struct_addr, Some(pos));
}
(
VirtualAddr::StructMember(struct_addr, Addr::Imm(index)),
typ,
pos,
)
} else {
(
VirtualAddr::StructEmbedded(struct_addr, Addr::Imm(index)),
typ,
pos,
)
}
}
}
}
Expr::Star(sexpr) => {
let typ = Some(self.t.expr_tc_type(expr));
let pos = sexpr.star;
let addr = self.load_mode_call(|g| g.gen_expr(&sexpr.expr));
(VirtualAddr::Pointee(addr), typ, pos)
}
_ => unreachable!(),
})
.collect::<Vec<(VirtualAddr, Option<TCTypeKey>, usize)>>();
match rhs {
RightHandSide::Nothing => {
let code = match token {
Token::INC => Opcode::INC,
Token::DEC => Opcode::DEC,
_ => unreachable!(),
};
let typ = self.t.expr_value_type(&lhs_exprs[0]);
self.gen_op_assign(&lhs[0].0, code, typ, None, None, lhs[0].2);
None
}
RightHandSide::Values(rhs_exprs) => {
let simple_op = match token {
Token::ADD_ASSIGN => Some(Opcode::ADD), // +=
Token::SUB_ASSIGN => Some(Opcode::SUB), // -=
Token::MUL_ASSIGN => Some(Opcode::MUL), // *=
Token::QUO_ASSIGN => Some(Opcode::QUO), // /=
Token::REM_ASSIGN => Some(Opcode::REM), // %=
Token::AND_ASSIGN => Some(Opcode::AND), // &=
Token::OR_ASSIGN => Some(Opcode::OR), // |=
Token::XOR_ASSIGN => Some(Opcode::XOR), // ^=
Token::SHL_ASSIGN => Some(Opcode::SHL), // <<=
Token::SHR_ASSIGN => Some(Opcode::SHR), // >>=
Token::AND_NOT_ASSIGN => Some(Opcode::AND_NOT), // &^=
Token::ASSIGN | Token::DEFINE => None,
_ => unreachable!(),
};
if let Some(code) = simple_op {
assert_eq!(lhs_exprs.len(), 1);
assert_eq!(rhs_exprs.len(), 1);
let ltyp = self.t.expr_value_type(&lhs_exprs[0]);
let rtyp = match code {
Opcode::SHL | Opcode::SHR => {
let t = self.t.expr_value_type(&rhs_exprs[0]);
Some(t)
}
_ => None,
};
self.gen_op_assign(&lhs[0].0, code, ltyp, Some(&rhs_exprs[0]), rtyp, lhs[0].2);
None
} else {
self.gen_assign_def_var(&lhs, &None, &rhs)
}
}
_ => self.gen_assign_def_var(&lhs, &None, &rhs),
}
}
fn gen_op_assign(
&mut self,
left: &VirtualAddr,
opcode: Opcode,
typ: ValueType,
right: Option<&Expr>,
r_type: Option<ValueType>,
p: usize,
) {
let pos = Some(p);
let rhs_addr = match right {
Some(e) => self.load_mode_call(|g| g.gen_expr(e)),
// inc/dec
None => Addr::Void,
};
func_ctx!(self).emit_assign(left.clone(), rhs_addr, Some((opcode, typ, r_type)), pos);
}
fn gen_assign_def_var(
&mut self,
lhs: &Vec<(VirtualAddr, Option<TCTypeKey>, usize)>,
typ: &Option<Expr>,
rhs: &RightHandSide,
) -> Option<usize> {
//let mut range_marker = None;
// handle the right hand side
match rhs {
RightHandSide::Nothing => {
// define without values
let t = self.t.expr_tc_type(&typ.as_ref().unwrap());
let zero_addr = self.add_zero_val(t);
let fctx = func_ctx!(self);
for (addr, _, p) in lhs {
// dont need to worry about casting to interface
fctx.emit_assign(addr.clone(), zero_addr, None, Some(*p))
}
None
}
RightHandSide::Values(values) => {
let val0 = &values[0];
let val0_mode = self.t.expr_mode(val0);
if values.len() == 1
&& (val0_mode == &OperandMode::CommaOk || val0_mode == &OperandMode::MapIndex)
{
let comma_ok = lhs.len() == 2;
let types = if comma_ok {
self.t.expr_tuple_tc_types(val0)
} else {
vec![self.t.expr_tc_type(val0)]
};
let mut cur_reg = expr_ctx!(self).cur_reg;
self.push_expr_ctx(ExprMode::Store(lhs[0].0.clone(), lhs[0].1), cur_reg);
cur_reg += 1;
let ok_ectx = comma_ok.then(|| {
let mode = ExprMode::Store(lhs[1].0.clone(), None);
ExprCtx::new(mode, cur_reg)
});
match val0 {
Expr::TypeAssert(tae) => {
self.gen_expr_type_assert(&tae.expr, &tae.typ, ok_ectx);
}
Expr::Index(ie) => {
self.gen_expr_index(&ie.expr, &ie.index, types[0], ok_ectx);
}
Expr::Unary(recv_expr) => {
assert_eq!(recv_expr.op, Token::ARROW);
self.gen_expr_recv(
&recv_expr.expr,
types[0],
ok_ectx,
Some(recv_expr.op_pos),
);
}
_ => {
unreachable!()
}
}
self.pop_expr_ctx();
} else if values.len() == lhs.len() {
if values.len() == 1 {
// define or assign with 1 value
self.store_mode_call(lhs[0].0.clone(), lhs[0].1, |g| {
g.gen_expr(&values[0])
});
} else {
// define or assign with values
// todo: we put the rhs at a temporary register to deal with cases like this: x, y = y, x+y
// but there is probably a better solution to this problem.
let rhs: Vec<(Addr, TCTypeKey)> = values
.iter()
.map(|v| {
(
self.load_mode_call(|g| g.gen_expr(v)),
self.t.expr_tc_type(v),
)
})
.collect();
for (i, l) in lhs.iter().enumerate() {
self.store_mode_call(l.0.clone(), l.1, |g| {
g.cur_expr_emit_direct_assign(rhs[i].1, rhs[i].0, Some(l.2))
});
}
}
} else {
debug_assert!(values.len() == 1);
// define or assign with function call that returns multiple value on the right
self.discard_mode_call(|g| g.gen_expr(&val0));
// now assgin the return values
let reg_begin = expr_ctx!(self).cur_reg;
let types = self.t.expr_tuple_tc_types(val0);
for (i, l) in lhs.iter().enumerate() {
self.store_mode_call(l.0.clone(), l.1, |g| {
g.cur_expr_emit_direct_assign(
types[i],
Addr::Regsiter(reg_begin + i),
Some(l.2),
);
});
}
}
None
}
RightHandSide::Range(r) => {
// the range statement
let right_addr = self.load_mode_call(|g| g.gen_expr(r));
let tkv = self.t.expr_range_tc_types(r);
let types = [
Some(self.t.tc_type_to_value_type(tkv[0])),
//Some(self.t.tc_type_to_value_type(tkv[1])),
Some(self.t.tc_type_to_value_type(tkv[2])),
];
let pos = Some(r.pos(&self.ast_objs));
let init_inst = InterInst::with_op_t_index(
Opcode::RANGE_INIT,
types[0],
types[1],
Addr::Void,
right_addr,
Addr::Void,
);
func_ctx!(self).emit_inst(init_inst, pos);
let range_marker = func_ctx!(self).next_code_index();
let mut cur_reg = expr_ctx!(self).cur_reg;
let k_mode = ExprMode::Store(lhs[0].0.clone(), lhs[0].1);
self.push_expr_ctx(k_mode, cur_reg);
cur_reg += 1;
let v_mode = ExprMode::Store(lhs[1].0.clone(), lhs[1].1);
let mut ectx_ex = ExprCtx::new(v_mode, cur_reg);
self.emit_double_store(
&mut ectx_ex,
Opcode::RANGE,
Addr::Imm(0), // the block_end address, to be set
Addr::Void,
tkv[0],
Some(tkv[2]),
types[0],
types[1],
Addr::Void,
pos,
);
self.pop_expr_ctx();
Some(range_marker)
}
// For Select, the result is already in registers
RightHandSide::SelectRecv(addr, ok) => {
let l = &lhs[0];
func_ctx!(self).emit_assign(l.0.clone(), *addr, None, Some(l.2));
if *ok {
let l = &lhs[1];
let reg = Addr::Regsiter(addr.as_reg_index() + 1);
func_ctx!(self).emit_assign(l.0.clone(), reg, None, Some(l.2));
}
None
}
}
}
fn gen_switch_body(
&mut self,
body: &BlockStmt,
tag_addr: Addr,
tag_type: ValueType,
type_switch_local_vars: Option<(Addr, Addr, Vec<Addr>, Option<Pos>)>,
) {
let mut helper = SwitchHelper::new();
let mut has_default = false;
for (i, stmt) in body.list.iter().enumerate() {
helper.add_case_clause();
let cc = SwitchHelper::to_case_clause(stmt);
match &cc.list {
Some(l) => {
for c in l.iter() {
let pos = Some(stmt.pos(&self.ast_objs));
let addr = self.load_mode_call(|g| g.gen_expr(c));
let fctx = func_ctx!(self);
helper.tags.add_case(i, fctx.next_code_index());
fctx.emit_inst(
InterInst::with_op_t_index(
Opcode::SWITCH,
Some(tag_type),
None,
Addr::Void,
tag_addr,
addr,
),
pos,
);
}
}
None => has_default = true,
}
}
let fctx = func_ctx!(self);
helper.tags.add_default(fctx.next_code_index());
fctx.emit_inst(InterInst::with_op(Opcode::JUMP), None);
for (i, stmt) in body.list.iter().enumerate() {
let cc = SwitchHelper::to_case_clause(stmt);
let fctx = func_ctx!(self);
let default = cc.list.is_none();
if default {
helper.tags.patch_default(fctx, fctx.next_code_index());
} else {
helper.tags.patch_case(fctx, i, fctx.next_code_index());
}
if let Some((val_src, iface_src, ref dsts, p)) = type_switch_local_vars {
// Specs: In clauses with a case listing exactly one type, the variable has that type; otherwise,
// the variable has the type of the expression in the TypeSwitchGuard.
let src = if default { iface_src } else { val_src };
fctx.emit_inst(
InterInst::with_op_index(Opcode::DUPLICATE, dsts[i], src, Addr::Void),
p,
);
}
for s in cc.body.iter() {
self.visit_stmt(s);
}
if !SwitchHelper::has_fall_through(stmt) {
let fctx = func_ctx!(self);
if default {
helper.ends.add_default(fctx.next_code_index());
} else {
helper.ends.add_case(i, fctx.next_code_index());
}
fctx.emit_inst(InterInst::with_op(Opcode::JUMP), None);
}
}
let end = func_ctx!(self).next_code_index();
helper.patch_ends(func_ctx!(self), end);
// jump to the end if there is no default code
if !has_default {
let func = func_ctx!(self);
helper.tags.patch_default(func, end);
}
}
fn gen_func_def(
&mut self,
tc_type: TCTypeKey, // Meta,
f_type_key: FuncTypeKey,
recv: Option<FieldList>,
body: &BlockStmt,
) -> (FunctionKey, GosValue) {
let typ = &self.ast_objs.ftypes[f_type_key];
let fmeta = self.t.tc_type_to_meta(tc_type, &mut self.vmctx);
let f = self
.vmctx
.function_with_meta(Some(self.pkg_key), fmeta, FuncFlag::Default);
let fkey = *f.as_function();
let mut fctx = FuncCtx::new(fkey, Some(tc_type), self.consts);
if let Some(fl) = &typ.results {
fctx.add_params(&fl, self.ast_objs, &self.t);
}
match recv {
Some(recv) => {
let mut fields = recv;
fields.list.append(&mut typ.params.list.clone());
fctx.add_params(&fields, self.ast_objs, &self.t)
}
None => fctx.add_params(&typ.params, self.ast_objs, &self.t),
};
self.func_ctx_stack.push(fctx);
// process function body
self.visit_stmt_block(body);
func_ctx!(self).emit_return(None, Some(body.r_brace), self.vmctx.functions());
let f = self.func_ctx_stack.pop().unwrap();
let cls = CodeGenVMCtx::new_closure_static(fkey, Some(&f.up_ptrs), fmeta);
self.results.push(f);
(fkey, cls)
}
fn gen_builtin_call(
&mut self,
func_expr: &Expr,
params: &Vec<Expr>,
builtin: &Builtin,
return_types: &[TCTypeKey],
ellipsis: bool,
pos: Option<usize>,
) {
let slice_op_types = |g: &mut CodeGen| {
let t0 = if ellipsis && g.t.expr_value_type(¶ms[1]) == ValueType::String {
ValueType::String
} else {
ValueType::Slice
};
let (_, t_elem) = g.t.sliceable_expr_value_types(¶ms[0], g.vmctx);
(t0, g.t.tc_type_to_value_type(t_elem))
};
match builtin {
Builtin::Make => {
let meta_addr = self.load_mode_call(|g| g.gen_expr(¶ms[0]));
let mut flag = ValueType::FlagA;
let mut arg1 = Addr::Void;
let mut arg2 = Addr::Void;
if params.len() >= 2 {
flag = ValueType::FlagB;
arg1 = self.load_mode_call(|g| g.gen_expr(¶ms[1]));
}
if params.len() >= 3 {
flag = ValueType::FlagC;
arg2 = self.load_mode_call(|g| g.gen_expr(¶ms[2]));
}
self.cur_expr_emit_assign(return_types[0], pos, |f, d, p| {
let inst = InterInst::with_op_t_index(
Opcode::MAKE,
Some(flag),
None,
d,
meta_addr,
arg1,
);
f.emit_inst(inst, p);
if arg2 != Addr::Void {
let inst = InterInst::with_op_index(Opcode::VOID, d, arg2, Addr::Void);
f.emit_inst(inst, p);
}
});
}
Builtin::Complex => {
let addr0 = self.load_mode_call(|g| g.gen_expr(¶ms[0]));
let addr1 = self.load_mode_call(|g| g.gen_expr(¶ms[1]));
let t = self.t.expr_value_type(¶ms[0]);
self.cur_expr_emit_assign(return_types[0], pos, |f, d, p| {
let inst =
InterInst::with_op_t_index(Opcode::COMPLEX, Some(t), None, d, addr0, addr1);
f.emit_inst(inst, p);
});
}
Builtin::New
| Builtin::Real
| Builtin::Imag
| Builtin::Len
| Builtin::Cap
| Builtin::Ffi => {
let t = self.t.expr_value_type(¶ms[0]);
let addr0 = self.load_mode_call(|g| g.gen_expr(¶ms[0]));
let addr1 = if params.len() > 1 {
self.load_mode_call(|g| g.gen_expr(¶ms[1]))
} else {
Addr::Void
};
self.cur_expr_emit_assign(return_types[0], pos, |f, d, p| {
let op = match builtin {
Builtin::New => Opcode::NEW,
Builtin::Real => Opcode::REAL,
Builtin::Imag => Opcode::IMAG,
Builtin::Len => Opcode::LEN,
Builtin::Cap => Opcode::CAP,
Builtin::Ffi => Opcode::FFI,
_ => unreachable!(),
};
let inst = InterInst::with_op_t_index(op, Some(t), None, d, addr0, addr1);
f.emit_inst(inst, p);
});
}
Builtin::Append => {
let ft = self.t.try_expr_tc_type(func_expr).unwrap();
let init_reg = expr_ctx!(self).cur_reg;
self.gen_call_params(ft, params, ellipsis);
let types = slice_op_types(self);
self.cur_expr_emit_assign(return_types[0], pos, |f, d, p| {
let inst = InterInst::with_op_t_index(
Opcode::APPEND,
Some(types.0),
Some(types.1),
d,
Addr::Regsiter(init_reg),
Addr::Regsiter(init_reg + 1),
);
f.emit_inst(inst, p);
});
expr_ctx!(self).cur_reg = init_reg;
}
Builtin::Copy => {
let addr0 = self.load_mode_call(|g| g.gen_expr(¶ms[0]));
let addr1 = self.load_mode_call(|g| g.gen_expr(¶ms[1]));
let types = slice_op_types(self);
self.cur_expr_emit_assign(return_types[0], pos, |f, d, p| {
let inst = InterInst::with_op_t_index(
Opcode::COPY,
Some(types.0),
Some(types.1),
d,
addr0,
addr1,
);
f.emit_inst(inst, p);
});
}
Builtin::Delete | Builtin::Close | Builtin::Panic | Builtin::Assert => {
let addr0 = self.load_mode_call(|g| g.gen_expr(¶ms[0]));
let addr1 = if params.len() > 1 {
self.load_mode_call(|g| g.gen_expr(¶ms[1]))
} else {
Addr::Void
};
let op = match builtin {
Builtin::Delete => Opcode::DELETE,
Builtin::Close => Opcode::CLOSE,
Builtin::Panic => Opcode::PANIC,
Builtin::Assert => Opcode::ASSERT,
_ => unreachable!(),
};
let inst = InterInst::with_op_index(op, Addr::Void, addr0, addr1);
func_ctx!(self).emit_inst(inst, pos);
}
Builtin::Recover => {
self.cur_expr_emit_assign(return_types[0], pos, |f, d, p| {
let inst = InterInst::with_op_index(Opcode::RECOVER, d, Addr::Void, Addr::Void);
f.emit_inst(inst, p);
});
}
_ => unimplemented!(),
};
}
fn gen_conversion(&mut self, to: &Expr, from: &Expr, pos: Option<usize>) {
// conversion
// from the specs:
/*
A non-constant value x can be converted to type T in any of these cases:
x is assignable to T.
+3 [struct] ignoring struct tags (see below), x's type and T have identical underlying types.
+4 [pointer] ignoring struct tags (see below), x's type and T are pointer types that are not defined types, and their pointer base types have identical underlying types.
+5 [number] x's type and T are both integer or floating point types.
+6 [number] x's type and T are both complex types.
+7 [string] x is an integer or a slice of bytes or runes and T is a string type.
+8 [slice] x is a string and T is a slice of bytes or runes.
A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:
- x's type is identical to T.
- x's type V and T have identical underlying types and at least one of V or T is not a defined type.
+1 [interface] T is an interface type and x implements T.
+2 [channel] x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a defined type.
- x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
- x is an untyped constant representable by a value of type T.
*/
let from_addr = self.load_mode_call(|g| g.gen_expr(from));
let mut converted = false;
let n_tc_to = self.t.expr_tc_type(to); // possibly named type
let tc_to = self.t.underlying_tc(n_tc_to);
let typ_to = self.t.tc_type_to_value_type(tc_to);
let n_tc_from = self.t.expr_tc_type(from); // possibly named type
let tc_from = self.t.underlying_tc(n_tc_from);
let typ_from = self.t.tc_type_to_value_type(tc_from);
if typ_from == ValueType::Void || identical_ignore_tags(tc_to, tc_from, self.tc_objs) {
// just ignore conversion if it's nil or types are identical
// or convert between Named type and underlying type,
// or both types are Named in case they are Structs
} else {
match typ_to {
ValueType::Interface => {
if typ_from != ValueType::Void {
let iface_index = self.iface_selector.add((n_tc_to, n_tc_from));
self.cur_expr_emit_assign(n_tc_to, pos, |f, d, p| {
f.emit_cast_iface(d, from_addr, iface_index, p);
});
converted = true;
}
}
ValueType::Int
| ValueType::Int8
| ValueType::Int16
| ValueType::Int32
| ValueType::Int64
| ValueType::Uint
| ValueType::UintPtr
| ValueType::Uint8
| ValueType::Uint16
| ValueType::Uint32
| ValueType::Uint64
| ValueType::Float32
| ValueType::Float64
| ValueType::Complex64
| ValueType::Complex128
| ValueType::String
| ValueType::Slice
| ValueType::UnsafePtr
| ValueType::Pointer => {
let t_extra = match typ_to {
ValueType::String => (typ_from == ValueType::Slice)
.then(|| self.tc_objs.types[tc_from].try_as_slice().unwrap().elem()),
ValueType::Slice => {
Some(self.tc_objs.types[tc_to].try_as_slice().unwrap().elem())
}
ValueType::Pointer => {
Some(self.tc_objs.types[tc_to].try_as_pointer().unwrap().base())
}
ValueType::Channel => Some(tc_to),
_ => None,
};
let t2 = t_extra.map(|x| self.t.tc_type_to_value_type(x));
self.cur_expr_emit_assign(tc_to, pos, |f, d, p| {
f.emit_cast(d, from_addr, Addr::Void, typ_to, Some(typ_from), t2, p);
});
converted = true;
}
ValueType::Channel => { /* nothing to be done */ }
_ => {
dbg!(typ_to);
unreachable!()
}
}
}
if !converted {
self.cur_expr_emit_direct_assign(n_tc_to, from_addr, pos);
}
}
fn gen_expr_call(
&mut self,
func_expr: &Expr,
params: &Vec<Expr>,
ellipsis: bool,
style: CallStyle,
) {
let pos = Some(func_expr.pos(&self.ast_objs));
let ft = self.t.expr_tc_type(func_expr);
match *self.t.expr_mode(func_expr) {
// built in function
OperandMode::Builtin(builtin) => {
let return_types = self.t.sig_returns_tc_types(ft);
self.gen_builtin_call(func_expr, params, &builtin, &return_types, ellipsis, pos);
}
// conversion
OperandMode::TypeExpr => {
assert!(params.len() == 1);
self.gen_conversion(func_expr, ¶ms[0], pos);
}
// normal goscript function
_ => {
let next_sb = expr_ctx!(self).cur_reg;
// make sure params are at the right place
let return_types = self.t.sig_returns_tc_types(ft);
let reg_usage =
return_types.len() + if self.t.is_method(func_expr) { 1 } else { 0 };
expr_ctx!(self).cur_reg = next_sb + reg_usage;
self.gen_call_params(ft, params, ellipsis);
let func_addr = self.load_mode_call(|g| g.gen_expr(func_expr));
func_ctx!(self).emit_call(func_addr, next_sb, style, pos);
if !return_types.is_empty() {
// assgin the first return value
// the cases of returning multiple values are handled elsewhere
self.cur_expr_emit_direct_assign(return_types[0], Addr::Regsiter(next_sb), pos);
}
}
}
}
fn gen_call_params(&mut self, func: TCTypeKey, params: &Vec<Expr>, ellipsis: bool) {
let (sig_params, variadic) = self.t.sig_params_tc_types(func);
let need_pack = !ellipsis && variadic.is_some();
let non_variadic_count = sig_params.len() - if need_pack { 1 } else { 0 };
let init_reg = expr_ctx!(self).cur_reg;
for (i, e) in params.iter().enumerate() {
let addr = expr_ctx!(self).inc_cur_reg();
let lhs_type = if i < non_variadic_count {
sig_params[i]
} else {
variadic.unwrap()
};
self.store_mode_call(VirtualAddr::Direct(addr), Some(lhs_type), |g| g.gen_expr(e));
}
debug_assert!(params.len() >= non_variadic_count);
if need_pack {
if let Some(t) = variadic {
let variadic_count = params.len() - non_variadic_count;
let variadic_begin_reg = init_reg + non_variadic_count;
let pos =
(!params.is_empty()).then(|| params[non_variadic_count].pos(&self.ast_objs));
let t_elem = self.t.tc_type_to_value_type(t);
let begin = Addr::Regsiter(variadic_begin_reg);
let end = Addr::Regsiter(variadic_begin_reg + variadic_count);
let inst = InterInst::with_op_t_index(
Opcode::PACK_VARIADIC,
Some(t_elem),
None,
begin,
begin,
end,
);
func_ctx!(self).emit_inst(inst, pos);
expr_ctx!(self).cur_reg = variadic_begin_reg + 1; // done with the rest registers
}
}
}
fn gen_expr_recv(
&mut self,
channel: &Expr,
val_tc_type: TCTypeKey,
ok_lhs_ectx: Option<ExprCtx>,
pos: Option<usize>,
) {
let channel_addr = self.load_mode_call(|g| g.gen_expr(channel));
match ok_lhs_ectx {
Some(mut ok_ectx) => {
self.emit_double_store(
&mut ok_ectx,
Opcode::RECV,
channel_addr,
Addr::Void,
val_tc_type,