-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
codegen.rs
3175 lines (3034 loc) · 117 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
//! generates `CodeObj` (equivalent to PyCodeObject of CPython) from `AST`.
//!
//! ASTからPythonバイトコード(コードオブジェクト)を生成する
use std::fmt;
use std::process;
use crate::ty::codeobj::MakeFunctionFlags;
use crate::ty::codeobj::{CodeObj, CodeObjFlags};
use crate::ty::value::GenTypeObj;
use erg_common::cache::CacheSet;
use erg_common::config::{ErgConfig, Input};
use erg_common::env::erg_std_path;
use erg_common::error::{ErrorDisplay, Location};
use erg_common::opcode::{CommonOpcode, CompareOp};
use erg_common::opcode308::Opcode308;
use erg_common::opcode310::Opcode310;
use erg_common::opcode311::{BinOpCode, Opcode311};
use erg_common::option_enum_unwrap;
use erg_common::python_util::{env_python_version, PythonVersion};
use erg_common::traits::{Locational, Stream};
use erg_common::vis::Visibility;
use erg_common::Str;
use erg_common::{
debug_power_assert, enum_unwrap, fn_name, fn_name_full, impl_stream_for_wrapper, log,
switch_unreachable,
};
use erg_parser::ast::{DefId, DefKind};
use CommonOpcode::*;
use erg_parser::ast::PreDeclTypeSpec;
use erg_parser::ast::TypeSpec;
use erg_parser::ast::{NonDefaultParamSignature, ParamPattern, VarName};
use erg_parser::token::DOT;
use erg_parser::token::EQUAL;
use erg_parser::token::{Token, TokenKind};
use crate::compile::{AccessKind, Name, StoreLoadKind};
use crate::error::CompileError;
use crate::hir::{
Accessor, Args, Array, BinOp, Block, Call, ClassDef, Def, DefBody, Expr, Identifier, Lambda,
Literal, Params, PatchDef, PosArg, ReDef, Record, Signature, SubrSignature, Tuple, UnaryOp,
VarSignature, HIR,
};
use crate::ty::value::ValueObj;
use crate::ty::{HasType, Type, TypeCode, TypePair};
use erg_common::fresh::fresh_varname;
use AccessKind::*;
/// patch method -> function
/// patch attr -> variable
fn debind(ident: &Identifier) -> Option<Str> {
match ident.vi.py_name.as_ref().map(|s| &s[..]) {
Some(name) if name.starts_with("Function::") => {
Some(Str::from(name.replace("Function::", "")))
}
Some(patch_method) if patch_method.contains("::") || patch_method.contains('.') => {
Some(Str::rc(patch_method))
}
_ => None,
}
}
fn escape_name(name: &str, vis: Visibility) -> Str {
let name = name.replace('!', "__erg_proc__");
let name = name.replace('$', "__erg_shared__");
if vis.is_private() {
Str::from("::".to_string() + &name)
} else {
Str::from(name)
}
}
fn escape_ident(ident: Identifier) -> Str {
let vis = ident.vis();
if let Some(py_name) = ident.vi.py_name {
py_name
} else {
escape_name(ident.inspect(), vis)
}
}
#[derive(Debug, Clone)]
pub struct PyCodeGenUnit {
pub(crate) id: usize,
pub(crate) py_version: PythonVersion,
pub(crate) codeobj: CodeObj,
pub(crate) stack_len: u32, // the maximum stack size
pub(crate) prev_lineno: u32,
pub(crate) lasti: usize,
pub(crate) prev_lasti: usize,
pub(crate) _refs: Vec<ValueObj>, // ref-counted objects
}
impl PartialEq for PyCodeGenUnit {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl fmt::Display for PyCodeGenUnit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"CompilerUnit{{\nid: {}\ncode:\n{}\n}}",
self.id,
self.codeobj.code_info(Some(self.py_version))
)
}
}
impl PyCodeGenUnit {
pub fn new<S: Into<Str>, T: Into<Str>>(
id: usize,
py_version: PythonVersion,
params: Vec<Str>,
filename: S,
name: T,
firstlineno: u32,
) -> Self {
Self {
id,
py_version,
codeobj: CodeObj::empty(params, filename, name, firstlineno),
stack_len: 0,
prev_lineno: firstlineno,
lasti: 0,
prev_lasti: 0,
_refs: vec![],
}
}
}
#[derive(Debug, Clone)]
pub struct PyCodeGenStack(Vec<PyCodeGenUnit>);
impl_stream_for_wrapper!(PyCodeGenStack, PyCodeGenUnit);
#[derive(Debug, Default)]
pub struct PyCodeGenerator {
cfg: ErgConfig,
pub(crate) py_version: PythonVersion,
str_cache: CacheSet<str>,
prelude_loaded: bool,
mutate_op_loaded: bool,
in_op_loaded: bool,
record_type_loaded: bool,
module_type_loaded: bool,
control_loaded: bool,
convertors_loaded: bool,
abc_loaded: bool,
unit_size: usize,
units: PyCodeGenStack,
}
impl PyCodeGenerator {
pub fn new(cfg: ErgConfig) -> Self {
Self {
py_version: cfg.target_version.unwrap_or_else(env_python_version),
cfg,
str_cache: CacheSet::new(),
prelude_loaded: false,
mutate_op_loaded: false,
in_op_loaded: false,
record_type_loaded: false,
module_type_loaded: false,
control_loaded: false,
convertors_loaded: false,
abc_loaded: false,
unit_size: 0,
units: PyCodeGenStack::empty(),
}
}
pub fn clear(&mut self) {
self.units.clear();
}
#[inline]
fn input(&self) -> &Input {
&self.cfg.input
}
fn get_cached(&self, s: &str) -> Str {
self.str_cache.get(s)
}
#[inline]
fn toplevel_block(&self) -> &PyCodeGenUnit {
self.units.first().unwrap()
}
#[inline]
fn cur_block(&self) -> &PyCodeGenUnit {
self.units.last().unwrap()
}
#[inline]
fn mut_cur_block(&mut self) -> &mut PyCodeGenUnit {
self.units.last_mut().unwrap()
}
#[inline]
fn cur_block_codeobj(&self) -> &CodeObj {
&self.cur_block().codeobj
}
#[inline]
fn mut_cur_block_codeobj(&mut self) -> &mut CodeObj {
&mut self.mut_cur_block().codeobj
}
#[inline]
fn toplevel_block_codeobj(&self) -> &CodeObj {
&self.toplevel_block().codeobj
}
#[inline]
fn stack_len(&self) -> u32 {
self.cur_block().stack_len
}
#[inline]
fn lasti(&self) -> usize {
self.cur_block().lasti
}
#[inline]
#[allow(dead_code)]
fn emit_print_expr(&mut self) {
self.write_instr(Opcode311::PRINT_EXPR);
self.write_arg(0);
self.stack_dec();
}
fn _emit_compare_op(&mut self, op: CompareOp) {
self.write_instr(Opcode311::COMPARE_OP);
self.write_arg(op as usize);
self.stack_dec();
if self.py_version.minor >= Some(11) {
self.write_bytes(&[0; 4]);
}
}
/// shut down the interpreter
#[allow(dead_code)]
fn terminate(&mut self) {
self.emit_push_null();
self.emit_load_name_instr(Identifier::public("exit"));
self.emit_load_const(1);
if self.py_version.minor >= Some(11) {
self.emit_precall_and_call(1);
} else {
self.write_instr(Opcode310::CALL_FUNCTION);
self.write_arg(1);
}
self.stack_dec();
}
/// swap TOS and TOS1
fn rot2(&mut self) {
if self.py_version.minor >= Some(11) {
self.write_instr(Opcode311::SWAP);
self.write_arg(2);
} else {
self.write_instr(Opcode310::ROT_TWO);
self.write_arg(0);
}
}
fn dup_top(&mut self) {
if self.py_version.minor >= Some(11) {
self.write_instr(Opcode311::COPY);
self.write_arg(1);
} else {
self.write_instr(Opcode310::DUP_TOP);
self.write_arg(0);
}
self.stack_inc();
}
/// COPY(1) == DUP_TOP
fn copy(&mut self, i: usize) {
debug_power_assert!(i, >, 0);
if self.py_version.minor >= Some(11) {
self.write_instr(Opcode311::COPY);
self.write_arg(i);
} else {
todo!()
}
self.stack_inc();
}
/// 0 origin
#[allow(dead_code)]
fn peek_stack(&mut self, i: usize) {
self.copy(i + 1);
self.emit_print_expr();
}
#[inline]
fn jump_delta(&self, jump_to: usize) -> usize {
if self.py_version.minor >= Some(10) {
if self.lasti() <= jump_to * 2 {
3
} else {
0
}
} else if self.lasti() <= jump_to {
6
} else {
0
}
}
fn calc_edit_jump(&mut self, idx: usize, jump_to: usize) {
let arg = if self.py_version.minor >= Some(10) {
jump_to / 2
} else {
jump_to
};
if !CommonOpcode::is_jump_op(*self.cur_block_codeobj().code.get(idx - 1).unwrap()) {
self.crash(&format!("calc_edit_jump: not jump op: {idx} {jump_to}"));
}
self.edit_code(idx, arg);
}
#[inline]
fn edit_code(&mut self, idx: usize, arg: usize) {
log!(err "editing: {idx} {arg}");
match u8::try_from(arg) {
Ok(u8code) => {
*self.mut_cur_block_codeobj().code.get_mut(idx).unwrap() = u8code;
}
Err(_e) => {
// TODO: use u16 as long as possible
// see write_arg's comment
let delta = self.jump_delta(arg);
let bytes = u32::try_from(arg + delta).unwrap().to_be_bytes();
let before_instr = idx.saturating_sub(1);
*self.mut_cur_block_codeobj().code.get_mut(idx).unwrap() = bytes[3];
self.extend_arg(before_instr, &bytes);
}
}
}
// e.g. JUMP_ABSOLUTE 264, lasti: 100
// 6 more instructions will be added after this, so 264 + 6 => 270
// this is greater than u8::MAX, so we need to extend the arg
// first, split `code + delta` into 4 u8s (as __Big__ endian)
// 270.to_be_bytes() == [0, 0, 1, 14]
// then, write the bytes in reverse order
// [..., EXTENDED_ARG 0, EXTENDED_ARG 0, EXTENDED_ARG 1, JUMP_ABSOLUTE 14]
#[inline]
fn extend_arg(&mut self, before_instr: usize, bytes: &[u8]) {
for byte in bytes.iter().rev().skip(1) {
self.mut_cur_block_codeobj()
.code
.insert(before_instr, *byte);
self.mut_cur_block_codeobj()
.code
.insert(before_instr, CommonOpcode::EXTENDED_ARG as u8);
self.mut_cur_block().lasti += 2;
}
}
fn write_instr<C: Into<u8>>(&mut self, code: C) {
self.mut_cur_block_codeobj().code.push(code.into());
self.mut_cur_block().lasti += 1;
// log!(info "wrote: {}", code);
}
fn write_arg(&mut self, code: usize) {
match u8::try_from(code) {
Ok(u8code) => {
self.mut_cur_block_codeobj().code.push(u8code);
self.mut_cur_block().lasti += 1;
// log!(info "wrote: {}", code);
}
Err(_) => match u16::try_from(code) {
Ok(_) => {
let delta =
if CommonOpcode::is_jump_op(*self.cur_block_codeobj().code.last().unwrap())
{
let shift_bytes = 2;
self.jump_delta(code) + shift_bytes
} else {
0
};
let arg = code + delta;
let bytes = u16::try_from(arg).unwrap().to_be_bytes(); // [u8; 2]
let before_instr = self.lasti().saturating_sub(1);
self.mut_cur_block_codeobj().code.push(bytes[1]);
self.mut_cur_block().lasti += 1;
self.extend_arg(before_instr, &bytes);
}
Err(_) => {
let delta =
if CommonOpcode::is_jump_op(*self.cur_block_codeobj().code.last().unwrap())
{
let shift_bytes = 6;
self.jump_delta(code) + shift_bytes
} else {
0
};
let arg = code + delta;
let bytes = u32::try_from(arg).unwrap().to_be_bytes(); // [u8; 4]
let before_instr = self.lasti().saturating_sub(1);
self.mut_cur_block_codeobj().code.push(bytes[3]);
self.mut_cur_block().lasti += 1;
self.extend_arg(before_instr, &bytes);
}
},
}
}
fn write_bytes(&mut self, bytes: &[u8]) {
self.mut_cur_block_codeobj().code.extend_from_slice(bytes);
self.mut_cur_block().lasti += bytes.len();
}
fn stack_inc(&mut self) {
self.mut_cur_block().stack_len += 1;
if self.stack_len() > self.cur_block_codeobj().stacksize {
self.mut_cur_block_codeobj().stacksize = self.stack_len();
}
}
fn stack_dec(&mut self) {
if self.stack_len() == 0 {
let lasti = self.lasti();
let last = self.cur_block_codeobj().code.last().unwrap();
self.crash(&format!(
"the stack size becomes -1\nlasti: {lasti}\nlast code: {last}"
));
} else {
self.mut_cur_block().stack_len -= 1;
}
}
/// NOTE: For example, an operation that increases the stack by 2 and decreases it by 1 should be `stack_inc_n(2); stack_dec();` not `stack_inc(1);`.
/// This is because the stack size will not increase correctly.
fn stack_inc_n(&mut self, n: usize) {
self.mut_cur_block().stack_len += n as u32;
if self.stack_len() > self.cur_block_codeobj().stacksize {
self.mut_cur_block_codeobj().stacksize = self.stack_len();
}
}
fn stack_dec_n(&mut self, n: usize) {
if n > 0 && self.stack_len() == 0 {
let lasti = self.lasti();
let last = self.cur_block_codeobj().code.last().unwrap();
self.crash(&format!(
"the stack size becomes -1\nlasti: {lasti}\nlast code: {last}"
));
} else {
self.mut_cur_block().stack_len -= n as u32;
}
}
fn emit_load_const<C: Into<ValueObj>>(&mut self, cons: C) {
let value: ValueObj = cons.into();
let is_str = value.is_str();
let is_int = value.is_int();
let is_nat = value.is_nat();
let is_bool = value.is_bool();
if !self.cfg.no_std {
if is_bool {
self.emit_push_null();
self.emit_load_name_instr(Identifier::public("Bool"));
} else if is_nat {
self.emit_push_null();
self.emit_load_name_instr(Identifier::public("Nat"));
} else if is_int {
self.emit_push_null();
self.emit_load_name_instr(Identifier::public("Int"));
} else if is_str {
self.emit_push_null();
self.emit_load_name_instr(Identifier::public("Str"));
}
}
let wrapped = is_str || is_int; // is_int => is_nat and is_bool
let idx = self
.mut_cur_block_codeobj()
.consts
.iter()
.position(|c| c == &value)
.unwrap_or_else(|| {
self.mut_cur_block_codeobj().consts.push(value);
self.mut_cur_block_codeobj().consts.len() - 1
});
self.write_instr(LOAD_CONST);
self.write_arg(idx);
self.stack_inc();
if !self.cfg.no_std && wrapped {
self.emit_call_instr(1, Name);
self.stack_dec();
}
}
fn register_const<C: Into<ValueObj>>(&mut self, cons: C) -> usize {
let value = cons.into();
self.mut_cur_block_codeobj()
.consts
.iter()
.position(|c| c == &value)
.unwrap_or_else(|| {
self.mut_cur_block_codeobj().consts.push(value);
self.mut_cur_block_codeobj().consts.len() - 1
})
}
fn local_search(&self, name: &str, _acc_kind: AccessKind) -> Option<Name> {
let current_is_toplevel = self.cur_block() == self.toplevel_block();
if let Some(idx) = self
.cur_block_codeobj()
.names
.iter()
.position(|n| &**n == name)
{
Some(Name::local(idx))
} else if let Some(idx) = self
.cur_block_codeobj()
.varnames
.iter()
.position(|v| &**v == name)
{
if current_is_toplevel {
Some(Name::local(idx))
} else {
Some(Name::fast(idx))
}
} else {
self.cur_block_codeobj()
.freevars
.iter()
.position(|f| &**f == name)
.map(Name::deref)
}
}
// local_searchで見つからなかった変数を探索する
fn rec_search(&mut self, name: &str) -> Option<StoreLoadKind> {
// search_name()を実行した後なのでcur_blockはskipする
for (nth_from_toplevel, block) in self.units.iter_mut().enumerate().rev().skip(1) {
let block_is_toplevel = nth_from_toplevel == 0;
if block.codeobj.cellvars.iter().any(|c| &**c == name) {
return Some(StoreLoadKind::Deref);
} else if let Some(idx) = block.codeobj.varnames.iter().position(|v| &**v == name) {
if block_is_toplevel {
return Some(StoreLoadKind::Global);
} else {
// the outer scope variable
let cellvar_name = block.codeobj.varnames.get(idx).unwrap().clone();
block.codeobj.cellvars.push(cellvar_name);
return Some(StoreLoadKind::Deref);
}
}
if block_is_toplevel && block.codeobj.names.iter().any(|n| &**n == name) {
return Some(StoreLoadKind::Global);
}
}
// 見つからなかった変数(前方参照変数など)はグローバル
Some(StoreLoadKind::Global)
}
fn register_name(&mut self, name: Str) -> Name {
let current_is_toplevel = self.cur_block() == self.toplevel_block();
match self.rec_search(&name) {
Some(st @ (StoreLoadKind::Local | StoreLoadKind::Global)) => {
let st = if current_is_toplevel {
StoreLoadKind::Local
} else {
st
};
self.mut_cur_block_codeobj().names.push(name);
Name::new(st, self.cur_block_codeobj().names.len() - 1)
}
Some(StoreLoadKind::Deref) => {
self.mut_cur_block_codeobj().freevars.push(name.clone());
if self.py_version.minor >= Some(11) {
// in 3.11 freevars are unified with varnames
self.mut_cur_block_codeobj().varnames.push(name);
Name::deref(self.cur_block_codeobj().varnames.len() - 1)
} else {
// cellvarsのpushはrec_search()で行われる
Name::deref(self.cur_block_codeobj().freevars.len() - 1)
}
}
None => {
// new variable
if current_is_toplevel {
self.mut_cur_block_codeobj().names.push(name);
Name::local(self.cur_block_codeobj().names.len() - 1)
} else {
self.mut_cur_block_codeobj().varnames.push(name);
Name::fast(self.cur_block_codeobj().varnames.len() - 1)
}
}
Some(_) => {
switch_unreachable!()
}
}
}
fn register_attr(&mut self, name: Str) -> Name {
self.mut_cur_block_codeobj().names.push(name);
Name::local(self.cur_block_codeobj().names.len() - 1)
}
fn register_method(&mut self, name: Str) -> Name {
self.mut_cur_block_codeobj().names.push(name);
Name::local(self.cur_block_codeobj().names.len() - 1)
}
fn select_load_instr(&self, kind: StoreLoadKind, acc_kind: AccessKind) -> u8 {
match kind {
StoreLoadKind::Fast | StoreLoadKind::FastConst => LOAD_FAST as u8,
StoreLoadKind::Global | StoreLoadKind::GlobalConst => LOAD_NAME as u8, //LOAD_GLOBAL as u8,
StoreLoadKind::Deref | StoreLoadKind::DerefConst => {
if self.py_version.minor >= Some(11) {
Opcode311::LOAD_DEREF as u8
} else {
Opcode310::LOAD_DEREF as u8
}
}
StoreLoadKind::Local | StoreLoadKind::LocalConst => match acc_kind {
Name => LOAD_NAME as u8,
Attr => LOAD_ATTR as u8,
Method => LOAD_METHOD as u8,
},
}
}
fn select_store_instr(&self, kind: StoreLoadKind, acc_kind: AccessKind) -> u8 {
match kind {
StoreLoadKind::Fast => STORE_FAST as u8,
StoreLoadKind::FastConst => STORE_FAST as u8, // ERG_STORE_FAST_IMMUT,
// NOTE: First-time variables are treated as GLOBAL, but they are always first-time variables when assigned, so they are just NAME
// NOTE: 初見の変数はGLOBAL扱いになるが、代入時は必ず初見であるので単なるNAME
StoreLoadKind::Global | StoreLoadKind::GlobalConst => STORE_NAME as u8,
StoreLoadKind::Deref | StoreLoadKind::DerefConst => {
if self.py_version.minor >= Some(11) {
Opcode311::STORE_DEREF as u8
} else {
Opcode310::STORE_DEREF as u8
}
}
StoreLoadKind::Local | StoreLoadKind::LocalConst => {
match acc_kind {
Name => STORE_NAME as u8,
Attr => STORE_ATTR as u8,
// cannot overwrite methods directly
Method => STORE_ATTR as u8,
}
}
}
}
fn emit_load_name_instr(&mut self, ident: Identifier) {
log!(info "entered {}({ident})", fn_name!());
let escaped = escape_ident(ident);
match &escaped[..] {
"if__" | "for__" | "while__" | "with__" | "discard__" => {
self.load_control();
}
"int__" | "nat__" => {
self.load_convertors();
}
_ => {}
}
let name = self
.local_search(&escaped, Name)
.unwrap_or_else(|| self.register_name(escaped));
let instr = self.select_load_instr(name.kind, Name);
self.write_instr(instr);
self.write_arg(name.idx);
self.stack_inc();
if instr == LOAD_GLOBAL as u8 && self.py_version.minor >= Some(11) {
self.write_bytes(&[0; 2]);
self.write_bytes(&[0; 8]);
}
}
fn emit_load_global_instr(&mut self, ident: Identifier) {
log!(info "entered {} ({ident})", fn_name!());
let escaped = escape_ident(ident);
let name = self
.local_search(&escaped, Name)
.unwrap_or_else(|| self.register_name(escaped));
let instr = LOAD_GLOBAL;
self.write_instr(instr);
self.write_arg(name.idx);
self.stack_inc();
}
fn emit_import_name_instr(&mut self, ident: Identifier, items_len: usize) {
log!(info "entered {}({ident})", fn_name!());
let escaped = escape_ident(ident);
let name = self
.local_search(&escaped, Name)
.unwrap_or_else(|| self.register_name(escaped));
self.write_instr(IMPORT_NAME);
self.write_arg(name.idx);
self.stack_inc_n(items_len);
self.stack_dec(); // (level + from_list) -> module object
}
fn emit_import_from_instr(&mut self, ident: Identifier) {
log!(info "entered {}", fn_name!());
let escaped = escape_ident(ident);
let name = self
.local_search(&escaped, Name)
.unwrap_or_else(|| self.register_name(escaped));
self.write_instr(IMPORT_FROM);
self.write_arg(name.idx);
// self.stack_inc(); (module object) -> attribute
}
fn emit_import_all_instr(&mut self, ident: Identifier) {
log!(info "entered {}", fn_name!());
self.emit_load_const(0i32); // escaping to call access `Nat` before importing `Nat`
self.emit_load_const([Str::ever("*")]);
let escaped = escape_ident(ident);
let name = self
.local_search(&escaped, Name)
.unwrap_or_else(|| self.register_name(escaped));
self.write_instr(IMPORT_NAME);
self.write_arg(name.idx);
self.stack_inc();
self.write_instr(IMPORT_STAR);
self.write_arg(0);
self.stack_dec_n(3);
}
/// item: (name, renamed)
fn emit_global_import_items(
&mut self,
module: Identifier,
items: Vec<(Identifier, Option<Identifier>)>,
) {
self.emit_load_const(0);
let item_name_tuple = items
.iter()
.map(|ident| ValueObj::Str(ident.0.inspect().clone()))
.collect::<Vec<_>>();
let items_len = item_name_tuple.len();
self.emit_load_const(item_name_tuple);
self.emit_import_name_instr(module, items_len);
for (item, renamed) in items.into_iter() {
if let Some(renamed) = renamed {
self.emit_import_from_instr(item);
self.emit_store_global_instr(renamed);
} else {
self.emit_import_from_instr(item.clone());
self.emit_store_global_instr(item);
}
}
self.emit_pop_top(); // discard IMPORT_FROM object
}
fn emit_load_attr_instr(&mut self, ident: Identifier) {
log!(info "entered {} ({ident})", fn_name!());
let escaped = escape_ident(ident);
let name = self
.local_search(&escaped, Attr)
.unwrap_or_else(|| self.register_attr(escaped));
let instr = self.select_load_instr(name.kind, Attr);
self.write_instr(instr);
self.write_arg(name.idx);
if self.py_version.minor >= Some(11) {
self.write_bytes(&[0; 8]);
}
}
fn emit_load_method_instr(&mut self, ident: Identifier) {
log!(info "entered {} ({ident})", fn_name!());
if &ident.inspect()[..] == "__new__" {
log!("{:?}", ident.vi);
}
let escaped = escape_ident(ident);
let name = self
.local_search(&escaped, Method)
.unwrap_or_else(|| self.register_method(escaped));
let instr = self.select_load_instr(name.kind, Method);
self.write_instr(instr);
self.write_arg(name.idx);
if self.py_version.minor >= Some(11) {
self.stack_inc(); // instead of PUSH_NULL
self.write_bytes(&[0; 20]);
}
}
fn emit_store_instr(&mut self, ident: Identifier, acc_kind: AccessKind) {
log!(info "entered {} ({ident})", fn_name!());
let escaped = escape_ident(ident);
let name = self.local_search(&escaped, acc_kind).unwrap_or_else(|| {
if acc_kind.is_local() {
self.register_name(escaped)
} else {
self.register_attr(escaped)
}
});
let instr = self.select_store_instr(name.kind, acc_kind);
self.write_instr(instr);
self.write_arg(name.idx);
self.stack_dec();
if instr == STORE_ATTR as u8 {
if self.py_version.minor >= Some(11) {
self.write_bytes(&[0; 8]);
}
self.stack_dec();
}
}
/// used for importing Erg builtin objects, etc. normally, this is not used
// Ergの組み込みオブジェクトをimportするときなどに使う、通常は使わない
fn emit_store_global_instr(&mut self, ident: Identifier) {
log!(info "entered {} ({ident})", fn_name!());
let escaped = escape_ident(ident);
let name = self
.local_search(&escaped, Name)
.unwrap_or_else(|| self.register_name(escaped));
let instr = STORE_GLOBAL;
self.write_instr(instr);
self.write_arg(name.idx);
self.stack_dec();
}
/// Ergの文法として、属性への代入は存在しない(必ずオブジェクトはすべての属性を初期化しなくてはならないため)
/// この関数はPythonへ落とし込むときに使う
fn store_acc(&mut self, acc: Accessor) {
log!(info "entered {} ({acc})", fn_name!());
match acc {
Accessor::Ident(ident) => {
self.emit_store_instr(ident, Name);
}
Accessor::Attr(attr) => {
self.emit_expr(*attr.obj);
self.emit_store_instr(attr.ident, Attr);
}
}
}
fn emit_pop_top(&mut self) {
self.write_instr(POP_TOP);
self.write_arg(0);
self.stack_dec();
}
fn cancel_if_pop_top(&mut self) {
if self.cur_block_codeobj().code.len() < 2 {
return;
}
let lasop_t_idx = self.cur_block_codeobj().code.len() - 2;
if self.cur_block_codeobj().code.get(lasop_t_idx) == Some(&(POP_TOP as u8)) {
self.mut_cur_block_codeobj().code.pop();
self.mut_cur_block_codeobj().code.pop();
self.mut_cur_block().lasti -= 2;
self.stack_inc();
}
}
/// Compileが継続不能になった際呼び出す
/// 極力使わないこと
fn crash(&mut self, description: &str) -> ! {
if cfg!(feature = "debug") {
println!("current block: {}", self.cur_block());
panic!("internal error: {description}");
} else {
process::exit(1);
}
}
fn gen_param_names(&self, params: &Params) -> Vec<Str> {
params
.non_defaults
.iter()
.map(|p| p.inspect().map(|s| &s[..]).unwrap_or("_"))
.chain(if let Some(var_args) = ¶ms.var_args {
vec![var_args.inspect().map(|s| &s[..]).unwrap_or("_")]
} else {
vec![]
})
.chain(
params
.defaults
.iter()
.map(|p| p.inspect().map(|s| &s[..]).unwrap_or("_")),
)
.enumerate()
.map(|(i, s)| {
if s == "_" {
format!("_{i}")
} else {
escape_name(s, Visibility::Private).to_string()
}
})
.map(|s| self.get_cached(&s))
.collect()
}
fn emit_acc(&mut self, acc: Accessor) {
log!(info "entered {} ({acc})", fn_name!());
match acc {
Accessor::Ident(ident) => {
if &ident.inspect()[..] == "#ModuleType" && !self.module_type_loaded {
self.load_module_type();
self.module_type_loaded = true;
}
self.emit_load_name_instr(ident);
}
Accessor::Attr(mut a) => {
// Python's namedtuple, a representation of Record, does not allow attribute names such as `::x`.
// Since Erg does not allow the coexistence of private and public variables with the same name, there is no problem in this trick.
let is_record = a.obj.ref_t().is_record();
if is_record {
a.ident.dot = Some(DOT);
}
if let Some(varname) = debind(&a.ident) {
a.ident.dot = None;
a.ident.name = VarName::from_str(varname);
self.emit_load_name_instr(a.ident);
} else {
self.emit_expr(*a.obj);
self.emit_load_attr_instr(a.ident);
}
}
}
}
fn emit_def(&mut self, def: Def) {
log!(info "entered {} ({})", fn_name!(), def.sig);
if def.def_kind().is_trait() {
return self.emit_trait_def(def);
}
match def.sig {
Signature::Subr(sig) => self.emit_subr_def(None, sig, def.body),
Signature::Var(sig) => self.emit_var_def(sig, def.body),
}
}
fn emit_push_null(&mut self) {
if self.py_version.minor >= Some(11) {
self.write_instr(Opcode311::PUSH_NULL);
self.write_arg(0);
self.stack_inc();
}
}
fn emit_precall_and_call(&mut self, argc: usize) {
self.write_instr(Opcode311::PRECALL);
self.write_arg(argc);
self.write_arg(0);
self.write_arg(0);
self.write_instr(Opcode311::CALL);
self.write_arg(argc);
self.write_bytes(&[0; 8]);
self.stack_dec();
}
fn emit_call_instr(&mut self, argc: usize, kind: AccessKind) {
if self.py_version.minor >= Some(11) {
self.emit_precall_and_call(argc);
} else {
match kind {
AccessKind::Method => self.write_instr(Opcode310::CALL_METHOD),
_ => self.write_instr(Opcode310::CALL_FUNCTION),
}
self.write_arg(argc);
}
}
fn emit_call_kw_instr(&mut self, argc: usize, kws: Vec<ValueObj>) {
if self.py_version.minor >= Some(11) {
let idx = self.register_const(kws);
self.write_instr(Opcode311::KW_NAMES);
self.write_arg(idx);
self.emit_precall_and_call(argc);
} else {
self.emit_load_const(kws);
self.write_instr(Opcode310::CALL_FUNCTION_KW);
self.write_arg(argc);
}
}
fn emit_trait_def(&mut self, def: Def) {
if !self.abc_loaded {
self.load_abc();
self.abc_loaded = true;
}
self.emit_push_null();
self.write_instr(LOAD_BUILD_CLASS);
self.write_arg(0);
self.stack_inc();
let code = self.emit_trait_block(def.def_kind(), &def.sig, def.body.block);
self.emit_load_const(code);
if self.py_version.minor < Some(11) {
self.emit_load_const(def.sig.ident().inspect().clone());