forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.rs
More file actions
1451 lines (1301 loc) · 50.1 KB
/
code.rs
File metadata and controls
1451 lines (1301 loc) · 50.1 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
//! Infamous code object. The python class `code`
use super::{PyBytesRef, PyStrRef, PyTupleRef, PyType};
use crate::common::lock::PyMutex;
use crate::{
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::PyStrInterned,
bytecode::{self, AsBag, BorrowedConstant, CodeFlags, Constant, ConstantBag, Instruction},
class::{PyClassImpl, StaticType},
convert::{ToPyException, ToPyObject},
frozen,
function::OptionalArg,
types::{Comparable, Constructor, Hashable, Representable},
};
use alloc::fmt;
use core::{
borrow::Borrow,
ops::Deref,
sync::atomic::{AtomicPtr, AtomicU64, Ordering},
};
use malachite_bigint::BigInt;
use num_traits::Zero;
use rustpython_compiler_core::{OneIndexed, bytecode::CodeUnits, bytecode::PyCodeLocationInfoKind};
/// State for iterating through code address ranges
struct PyCodeAddressRange<'a> {
ar_start: i32,
ar_end: i32,
ar_line: i32,
computed_line: i32,
reader: LineTableReader<'a>,
}
impl<'a> PyCodeAddressRange<'a> {
fn new(linetable: &'a [u8], first_line: i32) -> Self {
PyCodeAddressRange {
ar_start: 0,
ar_end: 0,
ar_line: -1,
computed_line: first_line,
reader: LineTableReader::new(linetable),
}
}
/// Check if this is a NO_LINE marker (code 15)
fn is_no_line_marker(byte: u8) -> bool {
(byte >> 3) == 0x1f
}
/// Advance to next address range
fn advance(&mut self) -> bool {
if self.reader.at_end() {
return false;
}
let first_byte = match self.reader.read_byte() {
Some(b) => b,
None => return false,
};
if (first_byte & 0x80) == 0 {
return false; // Invalid linetable
}
let code = (first_byte >> 3) & 0x0f;
let length = ((first_byte & 0x07) + 1) as i32;
// Get line delta for this entry
let line_delta = self.get_line_delta(code);
// Update computed line
self.computed_line += line_delta;
// Check for NO_LINE marker
if Self::is_no_line_marker(first_byte) {
self.ar_line = -1;
} else {
self.ar_line = self.computed_line;
}
// Update address range
self.ar_start = self.ar_end;
self.ar_end += length * 2; // sizeof(_Py_CODEUNIT) = 2
// Skip remaining bytes for this entry
while !self.reader.at_end() {
if let Some(b) = self.reader.peek_byte() {
if (b & 0x80) != 0 {
break;
}
self.reader.read_byte();
} else {
break;
}
}
true
}
fn get_line_delta(&mut self, code: u8) -> i32 {
let kind = match PyCodeLocationInfoKind::from_code(code) {
Some(k) => k,
None => return 0,
};
match kind {
PyCodeLocationInfoKind::None => 0, // NO_LINE marker
PyCodeLocationInfoKind::Long => {
let delta = self.reader.read_signed_varint();
// Skip end_line, col, end_col
self.reader.read_varint();
self.reader.read_varint();
self.reader.read_varint();
delta
}
PyCodeLocationInfoKind::NoColumns => self.reader.read_signed_varint(),
PyCodeLocationInfoKind::OneLine0 => {
self.reader.read_byte(); // Skip column
self.reader.read_byte(); // Skip end column
0
}
PyCodeLocationInfoKind::OneLine1 => {
self.reader.read_byte(); // Skip column
self.reader.read_byte(); // Skip end column
1
}
PyCodeLocationInfoKind::OneLine2 => {
self.reader.read_byte(); // Skip column
self.reader.read_byte(); // Skip end column
2
}
_ if kind.is_short() => {
self.reader.read_byte(); // Skip column byte
0
}
_ => 0,
}
}
}
#[derive(FromArgs)]
pub struct ReplaceArgs {
#[pyarg(named, optional)]
co_posonlyargcount: OptionalArg<u32>,
#[pyarg(named, optional)]
co_argcount: OptionalArg<u32>,
#[pyarg(named, optional)]
co_kwonlyargcount: OptionalArg<u32>,
#[pyarg(named, optional)]
co_filename: OptionalArg<PyStrRef>,
#[pyarg(named, optional)]
co_firstlineno: OptionalArg<u32>,
#[pyarg(named, optional)]
co_consts: OptionalArg<Vec<PyObjectRef>>,
#[pyarg(named, optional)]
co_name: OptionalArg<PyStrRef>,
#[pyarg(named, optional)]
co_names: OptionalArg<Vec<PyObjectRef>>,
#[pyarg(named, optional)]
co_flags: OptionalArg<u32>,
#[pyarg(named, optional)]
co_varnames: OptionalArg<Vec<PyObjectRef>>,
#[pyarg(named, optional)]
co_nlocals: OptionalArg<u32>,
#[pyarg(named, optional)]
co_stacksize: OptionalArg<u32>,
#[pyarg(named, optional)]
co_code: OptionalArg<crate::builtins::PyBytesRef>,
#[pyarg(named, optional)]
co_linetable: OptionalArg<crate::builtins::PyBytesRef>,
#[pyarg(named, optional)]
co_exceptiontable: OptionalArg<crate::builtins::PyBytesRef>,
#[pyarg(named, optional)]
co_freevars: OptionalArg<Vec<PyObjectRef>>,
#[pyarg(named, optional)]
co_cellvars: OptionalArg<Vec<PyObjectRef>>,
#[pyarg(named, optional)]
co_qualname: OptionalArg<PyStrRef>,
}
#[derive(Clone)]
#[repr(transparent)]
pub struct Literal(PyObjectRef);
impl Borrow<PyObject> for Literal {
fn borrow(&self) -> &PyObject {
&self.0
}
}
impl From<Literal> for PyObjectRef {
fn from(obj: Literal) -> Self {
obj.0
}
}
impl From<PyObjectRef> for Literal {
fn from(obj: PyObjectRef) -> Self {
Literal(obj)
}
}
fn borrow_obj_constant(obj: &PyObject) -> BorrowedConstant<'_, Literal> {
match_class!(match obj {
ref i @ super::int::PyInt => {
let value = i.as_bigint();
if obj.class().is(super::bool_::PyBool::static_type()) {
BorrowedConstant::Boolean {
value: !value.is_zero(),
}
} else {
BorrowedConstant::Integer { value }
}
}
ref f @ super::float::PyFloat => BorrowedConstant::Float { value: f.to_f64() },
ref c @ super::complex::PyComplex => BorrowedConstant::Complex {
value: c.to_complex()
},
ref s @ super::pystr::PyStr => BorrowedConstant::Str { value: s.as_wtf8() },
ref b @ super::bytes::PyBytes => BorrowedConstant::Bytes {
value: b.as_bytes()
},
ref c @ PyCode => {
BorrowedConstant::Code { code: &c.code }
}
ref t @ super::tuple::PyTuple => {
let elements = t.as_slice();
// SAFETY: Literal is repr(transparent) over PyObjectRef, and a Literal tuple only ever
// has other literals as elements
let elements = unsafe { &*(elements as *const [PyObjectRef] as *const [Literal]) };
BorrowedConstant::Tuple { elements }
}
super::singletons::PyNone => BorrowedConstant::None,
super::slice::PyEllipsis => BorrowedConstant::Ellipsis,
ref s @ super::slice::PySlice => {
// Constant pool slices always store Some() for start/step (even for None).
// Box::leak the array so it outlives the borrow. Leak is acceptable since
// constant pool objects live for the program's lifetime.
let start = s.start.clone().unwrap();
let stop = s.stop.clone();
let step = s.step.clone().unwrap();
let arr = Box::leak(Box::new([Literal(start), Literal(stop), Literal(step)]));
BorrowedConstant::Slice { elements: arr }
}
ref fs @ super::set::PyFrozenSet => {
// Box::leak the elements so they outlive the borrow. Leak is acceptable since
// constant pool objects live for the program's lifetime.
let elems: Vec<Literal> = fs.elements().into_iter().map(Literal).collect();
let elements = Box::leak(elems.into_boxed_slice());
BorrowedConstant::Frozenset { elements }
}
_ => panic!("unexpected payload for constant python value"),
})
}
impl Constant for Literal {
type Name = &'static PyStrInterned;
fn borrow_constant(&self) -> BorrowedConstant<'_, Self> {
borrow_obj_constant(&self.0)
}
}
impl<'a> AsBag for &'a Context {
type Bag = PyObjBag<'a>;
fn as_bag(self) -> PyObjBag<'a> {
PyObjBag(self)
}
}
impl<'a> AsBag for &'a VirtualMachine {
type Bag = PyObjBag<'a>;
fn as_bag(self) -> PyObjBag<'a> {
PyObjBag(&self.ctx)
}
}
#[derive(Clone, Copy)]
pub struct PyObjBag<'a>(pub &'a Context);
impl ConstantBag for PyObjBag<'_> {
type Constant = Literal;
fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant {
let ctx = self.0;
let obj = match constant {
BorrowedConstant::Integer { value } => ctx.new_bigint(value).into(),
BorrowedConstant::Float { value } => ctx.new_float(value).into(),
BorrowedConstant::Complex { value } => ctx.new_complex(value).into(),
BorrowedConstant::Str { value } if value.len() <= 20 => {
ctx.intern_str(value).to_object()
}
BorrowedConstant::Str { value } => ctx.new_str(value).into(),
BorrowedConstant::Bytes { value } => ctx.new_bytes(value.to_vec()).into(),
BorrowedConstant::Boolean { value } => ctx.new_bool(value).into(),
BorrowedConstant::Code { code } => ctx.new_code(code.map_clone_bag(self)).into(),
BorrowedConstant::Tuple { elements } => {
let elements = elements
.iter()
.map(|constant| self.make_constant(constant.borrow_constant()).0)
.collect();
ctx.new_tuple(elements).into()
}
BorrowedConstant::Slice { elements } => {
let [start, stop, step] = elements;
let start_obj = self.make_constant(start.borrow_constant()).0;
let stop_obj = self.make_constant(stop.borrow_constant()).0;
let step_obj = self.make_constant(step.borrow_constant()).0;
// Store as PySlice with Some() for all fields (even None values)
// so borrow_obj_constant can reference them.
use crate::builtins::PySlice;
PySlice {
start: Some(start_obj),
stop: stop_obj,
step: Some(step_obj),
}
.into_ref(ctx)
.into()
}
BorrowedConstant::Frozenset { elements: _ } => {
// Creating a frozenset requires VirtualMachine for element hashing.
// PyObjBag only has Context, so we cannot construct PyFrozenSet here.
// Frozenset constants from .pyc are handled by PyMarshalBag which has VM access.
unimplemented!(
"frozenset constant in PyObjBag::make_constant requires VirtualMachine"
)
}
BorrowedConstant::None => ctx.none(),
BorrowedConstant::Ellipsis => ctx.ellipsis.clone().into(),
};
Literal(obj)
}
fn make_name(&self, name: &str) -> &'static PyStrInterned {
self.0.intern_str(name)
}
fn make_int(&self, value: BigInt) -> Self::Constant {
Literal(self.0.new_int(value).into())
}
fn make_tuple(&self, elements: impl Iterator<Item = Self::Constant>) -> Self::Constant {
Literal(self.0.new_tuple(elements.map(|lit| lit.0).collect()).into())
}
fn make_code(&self, code: CodeObject) -> Self::Constant {
Literal(self.0.new_code(code).into())
}
}
pub type CodeObject = bytecode::CodeObject<Literal>;
pub trait IntoCodeObject {
fn into_code_object(self, ctx: &Context) -> CodeObject;
}
impl IntoCodeObject for CodeObject {
fn into_code_object(self, _ctx: &Context) -> Self {
self
}
}
impl IntoCodeObject for bytecode::CodeObject {
fn into_code_object(self, ctx: &Context) -> CodeObject {
self.map_bag(PyObjBag(ctx))
}
}
impl<B: AsRef<[u8]>> IntoCodeObject for frozen::FrozenCodeObject<B> {
fn into_code_object(self, ctx: &Context) -> CodeObject {
self.decode(ctx)
}
}
/// Per-code-object monitoring data (_PyCoMonitoringData).
/// Stores original opcodes displaced by INSTRUMENTED_LINE / INSTRUMENTED_INSTRUCTION.
pub struct CoMonitoringData {
/// Original opcodes at positions with INSTRUMENTED_LINE.
/// Indexed by instruction index. 0 = not instrumented for LINE.
pub line_opcodes: Vec<u8>,
/// Original opcodes at positions with INSTRUMENTED_INSTRUCTION.
/// Indexed by instruction index. 0 = not instrumented for INSTRUCTION.
pub per_instruction_opcodes: Vec<u8>,
}
#[pyclass(module = false, name = "code")]
pub struct PyCode {
pub code: CodeObject,
source_path: AtomicPtr<PyStrInterned>,
/// Version counter for lazy re-instrumentation.
/// Compared against `PyGlobalState::instrumentation_version` at RESUME.
pub instrumentation_version: AtomicU64,
/// Side-table for INSTRUMENTED_LINE / INSTRUMENTED_INSTRUCTION.
pub monitoring_data: PyMutex<Option<CoMonitoringData>>,
/// Whether adaptive counters have been initialized (lazy quickening).
pub quickened: core::sync::atomic::AtomicBool,
}
impl Deref for PyCode {
type Target = CodeObject;
fn deref(&self) -> &Self::Target {
&self.code
}
}
impl PyCode {
pub fn new(code: CodeObject) -> Self {
let sp = code.source_path as *const PyStrInterned as *mut PyStrInterned;
Self {
code,
source_path: AtomicPtr::new(sp),
instrumentation_version: AtomicU64::new(0),
monitoring_data: PyMutex::new(None),
quickened: core::sync::atomic::AtomicBool::new(false),
}
}
pub fn source_path(&self) -> &'static PyStrInterned {
// SAFETY: always points to a valid &'static PyStrInterned (interned strings are never deallocated)
unsafe { &*self.source_path.load(Ordering::Relaxed) }
}
pub fn set_source_path(&self, new: &'static PyStrInterned) {
self.source_path.store(
new as *const PyStrInterned as *mut PyStrInterned,
Ordering::Relaxed,
);
}
pub fn from_pyc_path(path: &std::path::Path, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
let name = match path.file_stem() {
Some(stem) => stem.display().to_string(),
None => "".to_owned(),
};
let content = std::fs::read(path).map_err(|e| e.to_pyexception(vm))?;
Self::from_pyc(
&content,
Some(&name),
Some(&path.display().to_string()),
Some("<source>"),
vm,
)
}
pub fn from_pyc(
pyc_bytes: &[u8],
name: Option<&str>,
bytecode_path: Option<&str>,
source_path: Option<&str>,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
if !crate::import::check_pyc_magic_number_bytes(pyc_bytes) {
return Err(vm.new_value_error("pyc bytes has wrong MAGIC"));
}
let bootstrap_external = vm.import("_frozen_importlib_external", 0)?;
let compile_bytecode = bootstrap_external.get_attr("_compile_bytecode", vm)?;
// 16 is the pyc header length
let Some((_, code_bytes)) = pyc_bytes.split_at_checked(16) else {
return Err(vm.new_value_error(format!(
"pyc_bytes header is broken. 16 bytes expected but {} bytes given.",
pyc_bytes.len()
)));
};
let code_bytes_obj = vm.ctx.new_bytes(code_bytes.to_vec());
let compiled =
compile_bytecode.call((code_bytes_obj, name, bytecode_path, source_path), vm)?;
compiled.try_downcast(vm)
}
}
impl fmt::Debug for PyCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "code: {:?}", self.code)
}
}
impl PyPayload for PyCode {
#[inline]
fn class(ctx: &Context) -> &'static Py<PyType> {
ctx.types.code_type
}
}
impl Representable for PyCode {
#[inline]
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
let code = &zelf.code;
Ok(format!(
"<code object {} at {:#x} file {:?}, line {}>",
code.obj_name,
zelf.get_id(),
zelf.source_path().as_str(),
code.first_line_number.map_or(-1, |n| n.get() as i32)
))
}
}
impl Comparable for PyCode {
fn cmp(
zelf: &Py<Self>,
other: &PyObject,
op: crate::types::PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<crate::function::PyComparisonValue> {
op.eq_only(|| {
let other = class_or_notimplemented!(Self, other);
let a = &zelf.code;
let b = &other.code;
let eq = a.obj_name == b.obj_name
&& a.arg_count == b.arg_count
&& a.posonlyarg_count == b.posonlyarg_count
&& a.kwonlyarg_count == b.kwonlyarg_count
&& a.flags == b.flags
&& a.first_line_number == b.first_line_number
&& a.instructions.original_bytes() == b.instructions.original_bytes()
&& a.linetable == b.linetable
&& a.exceptiontable == b.exceptiontable
&& a.names == b.names
&& a.varnames == b.varnames
&& a.freevars == b.freevars
&& a.cellvars == b.cellvars
&& {
let a_consts: Vec<_> = a.constants.iter().map(|c| c.0.clone()).collect();
let b_consts: Vec<_> = b.constants.iter().map(|c| c.0.clone()).collect();
if a_consts.len() != b_consts.len() {
false
} else {
let mut eq = true;
for (ac, bc) in a_consts.iter().zip(b_consts.iter()) {
if !vm.bool_eq(ac, bc)? {
eq = false;
break;
}
}
eq
}
};
Ok(eq.into())
})
}
}
impl Hashable for PyCode {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<crate::common::hash::PyHash> {
let code = &zelf.code;
// Hash a tuple of key attributes, matching CPython's code_hash
let tuple = vm.ctx.new_tuple(vec![
vm.ctx.new_str(code.obj_name.as_str()).into(),
vm.ctx.new_int(code.arg_count).into(),
vm.ctx.new_int(code.posonlyarg_count).into(),
vm.ctx.new_int(code.kwonlyarg_count).into(),
vm.ctx.new_int(code.varnames.len()).into(),
vm.ctx.new_int(code.flags.bits()).into(),
vm.ctx
.new_int(code.first_line_number.map_or(0, |n| n.get()) as i64)
.into(),
vm.ctx.new_bytes(code.instructions.original_bytes()).into(),
{
let consts: Vec<_> = code.constants.iter().map(|c| c.0.clone()).collect();
vm.ctx.new_tuple(consts).into()
},
]);
tuple.as_object().hash(vm)
}
}
// Arguments for code object constructor
#[derive(FromArgs)]
pub struct PyCodeNewArgs {
argcount: u32,
posonlyargcount: u32,
kwonlyargcount: u32,
nlocals: u32,
stacksize: u32,
flags: u32,
co_code: PyBytesRef,
consts: PyTupleRef,
names: PyTupleRef,
varnames: PyTupleRef,
filename: PyStrRef,
name: PyStrRef,
qualname: PyStrRef,
firstlineno: i32,
linetable: PyBytesRef,
exceptiontable: PyBytesRef,
freevars: PyTupleRef,
cellvars: PyTupleRef,
}
impl Constructor for PyCode {
type Args = PyCodeNewArgs;
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
// Convert names tuple to vector of interned strings
let names: Box<[&'static PyStrInterned]> = args
.names
.iter()
.map(|obj| {
let s = obj
.downcast_ref::<super::pystr::PyStr>()
.ok_or_else(|| vm.new_type_error("names must be tuple of strings"))?;
Ok(vm.ctx.intern_str(s.as_wtf8()))
})
.collect::<PyResult<Vec<_>>>()?
.into_boxed_slice();
let varnames: Box<[&'static PyStrInterned]> = args
.varnames
.iter()
.map(|obj| {
let s = obj
.downcast_ref::<super::pystr::PyStr>()
.ok_or_else(|| vm.new_type_error("varnames must be tuple of strings"))?;
Ok(vm.ctx.intern_str(s.as_wtf8()))
})
.collect::<PyResult<Vec<_>>>()?
.into_boxed_slice();
let cellvars: Box<[&'static PyStrInterned]> = args
.cellvars
.iter()
.map(|obj| {
let s = obj
.downcast_ref::<super::pystr::PyStr>()
.ok_or_else(|| vm.new_type_error("cellvars must be tuple of strings"))?;
Ok(vm.ctx.intern_str(s.as_wtf8()))
})
.collect::<PyResult<Vec<_>>>()?
.into_boxed_slice();
let freevars: Box<[&'static PyStrInterned]> = args
.freevars
.iter()
.map(|obj| {
let s = obj
.downcast_ref::<super::pystr::PyStr>()
.ok_or_else(|| vm.new_type_error("freevars must be tuple of strings"))?;
Ok(vm.ctx.intern_str(s.as_wtf8()))
})
.collect::<PyResult<Vec<_>>>()?
.into_boxed_slice();
// Check nlocals matches varnames length
if args.nlocals as usize != varnames.len() {
return Err(vm.new_value_error(format!(
"nlocals ({}) != len(varnames) ({})",
args.nlocals,
varnames.len()
)));
}
// Parse and validate bytecode from bytes
let bytecode_bytes = args.co_code.as_bytes();
let instructions = CodeUnits::try_from(bytecode_bytes)
.map_err(|e| vm.new_value_error(format!("invalid bytecode: {}", e)))?;
// Convert constants
let constants = args
.consts
.iter()
.map(|obj| {
// Convert PyObject to Literal constant. For now, just wrap it
Literal(obj.clone())
})
.collect();
// Create locations (start and end pairs)
let row = if args.firstlineno > 0 {
OneIndexed::new(args.firstlineno as usize).unwrap_or(OneIndexed::MIN)
} else {
OneIndexed::MIN
};
let loc = rustpython_compiler_core::SourceLocation {
line: row,
character_offset: OneIndexed::from_zero_indexed(0),
};
let locations: Box<
[(
rustpython_compiler_core::SourceLocation,
rustpython_compiler_core::SourceLocation,
)],
> = vec![(loc, loc); instructions.len()].into_boxed_slice();
// Build localspluskinds with cell-local merging
let localspluskinds = {
use rustpython_compiler_core::bytecode::*;
let nlocals = varnames.len();
let ncells = cellvars.len();
let nfrees = freevars.len();
let numdropped = cellvars
.iter()
.filter(|cv| varnames.iter().any(|v| *v == **cv))
.count();
let nlocalsplus = nlocals + ncells - numdropped + nfrees;
let mut kinds = vec![0u8; nlocalsplus];
for kind in kinds.iter_mut().take(nlocals) {
*kind = CO_FAST_LOCAL;
}
let mut cell_numdropped = 0usize;
for (i, cv) in cellvars.iter().enumerate() {
let merged_idx = varnames.iter().position(|v| **v == **cv);
if let Some(local_idx) = merged_idx {
kinds[local_idx] |= CO_FAST_CELL;
cell_numdropped += 1;
} else {
kinds[nlocals + i - cell_numdropped] = CO_FAST_CELL;
}
}
let free_start = nlocals + ncells - numdropped;
for i in 0..nfrees {
kinds[free_start + i] = CO_FAST_FREE;
}
kinds.into_boxed_slice()
};
// Build the CodeObject
let code = CodeObject {
instructions,
locations,
flags: CodeFlags::from_bits_truncate(args.flags),
posonlyarg_count: args.posonlyargcount,
arg_count: args.argcount,
kwonlyarg_count: args.kwonlyargcount,
source_path: vm.ctx.intern_str(args.filename.as_wtf8()),
first_line_number: if args.firstlineno > 0 {
OneIndexed::new(args.firstlineno as usize)
} else {
None
},
max_stackdepth: args.stacksize,
obj_name: vm.ctx.intern_str(args.name.as_wtf8()),
qualname: vm.ctx.intern_str(args.qualname.as_wtf8()),
constants,
names,
varnames,
cellvars,
freevars,
localspluskinds,
linetable: args.linetable.as_bytes().to_vec().into_boxed_slice(),
exceptiontable: args.exceptiontable.as_bytes().to_vec().into_boxed_slice(),
};
Ok(PyCode::new(code))
}
}
#[pyclass(
with(Representable, Constructor, Comparable, Hashable),
flags(HAS_WEAKREF)
)]
impl PyCode {
#[pygetset]
const fn co_posonlyargcount(&self) -> usize {
self.code.posonlyarg_count as usize
}
#[pygetset]
const fn co_argcount(&self) -> usize {
self.code.arg_count as usize
}
#[pygetset]
const fn co_stacksize(&self) -> u32 {
self.code.max_stackdepth
}
#[pygetset]
pub fn co_filename(&self) -> PyStrRef {
self.source_path().to_owned()
}
#[pygetset]
pub fn co_cellvars(&self, vm: &VirtualMachine) -> PyTupleRef {
let cellvars = self
.cellvars
.iter()
.map(|name| name.to_pyobject(vm))
.collect();
vm.ctx.new_tuple(cellvars)
}
#[pygetset]
fn co_nlocals(&self) -> usize {
self.code.varnames.len()
}
#[pygetset]
fn co_firstlineno(&self) -> u32 {
self.code.first_line_number.map_or(0, |n| n.get() as _)
}
#[pygetset]
const fn co_kwonlyargcount(&self) -> usize {
self.code.kwonlyarg_count as usize
}
#[pygetset]
fn co_consts(&self, vm: &VirtualMachine) -> PyTupleRef {
let consts = self.code.constants.iter().map(|x| x.0.clone()).collect();
vm.ctx.new_tuple(consts)
}
#[pygetset]
fn co_name(&self) -> PyStrRef {
self.code.obj_name.to_owned()
}
#[pygetset]
fn co_qualname(&self) -> PyStrRef {
self.code.qualname.to_owned()
}
#[pygetset]
fn co_names(&self, vm: &VirtualMachine) -> PyTupleRef {
let names = self
.code
.names
.deref()
.iter()
.map(|name| name.to_pyobject(vm))
.collect();
vm.ctx.new_tuple(names)
}
#[pygetset]
const fn co_flags(&self) -> u32 {
self.code.flags.bits()
}
#[pygetset]
pub fn co_varnames(&self, vm: &VirtualMachine) -> PyTupleRef {
let varnames = self.code.varnames.iter().map(|s| s.to_object()).collect();
vm.ctx.new_tuple(varnames)
}
#[pygetset]
pub fn co_code(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef {
vm.ctx.new_bytes(self.code.instructions.original_bytes())
}
#[pygetset]
pub fn _co_code_adaptive(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef {
// Return current (possibly quickened/specialized) bytecode
let bytes = unsafe {
core::slice::from_raw_parts(
self.code.instructions.as_ptr() as *const u8,
self.code.instructions.len() * 2,
)
};
vm.ctx.new_bytes(bytes.to_vec())
}
#[pygetset]
pub fn co_freevars(&self, vm: &VirtualMachine) -> PyTupleRef {
let names = self
.code
.freevars
.deref()
.iter()
.map(|name| name.to_pyobject(vm))
.collect();
vm.ctx.new_tuple(names)
}
#[pygetset]
pub fn co_linetable(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef {
// Return the actual linetable from the code object
vm.ctx.new_bytes(self.code.linetable.to_vec())
}
#[pygetset]
pub fn co_exceptiontable(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef {
// Return the actual exception table from the code object
vm.ctx.new_bytes(self.code.exceptiontable.to_vec())
}
// spell-checker: ignore lnotab
// co_lnotab is intentionally not implemented.
// It was deprecated since 3.12 and scheduled for removal in 3.14.
// Use co_lines() or co_linetable instead.
#[pymethod]
pub fn co_lines(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
// TODO: Implement lazy iterator (lineiterator) like CPython for better performance
// Currently returns eager list for simplicity
// Return an iterator over (start_offset, end_offset, lineno) tuples
let linetable = self.code.linetable.as_ref();
let mut lines = Vec::new();
if !linetable.is_empty() {
let first_line = self.code.first_line_number.map_or(0, |n| n.get() as i32);
let mut range = PyCodeAddressRange::new(linetable, first_line);
// Process all address ranges and merge consecutive entries with same line
let mut pending_entry: Option<(i32, i32, i32)> = None;
while range.advance() {
let start = range.ar_start;
let end = range.ar_end;
let line = range.ar_line;
if let Some((prev_start, _, prev_line)) = pending_entry {
if prev_line == line {
// Same line, extend the range
pending_entry = Some((prev_start, end, prev_line));
} else {
// Different line, emit the previous entry
let tuple = if prev_line == -1 {
vm.ctx.new_tuple(vec![
vm.ctx.new_int(prev_start).into(),
vm.ctx.new_int(start).into(),
vm.ctx.none(),
])
} else {
vm.ctx.new_tuple(vec![
vm.ctx.new_int(prev_start).into(),
vm.ctx.new_int(start).into(),
vm.ctx.new_int(prev_line).into(),
])
};
lines.push(tuple.into());
pending_entry = Some((start, end, line));
}
} else {
// First entry
pending_entry = Some((start, end, line));
}
}
// Emit the last pending entry
if let Some((start, end, line)) = pending_entry {
let tuple = if line == -1 {
vm.ctx.new_tuple(vec![
vm.ctx.new_int(start).into(),
vm.ctx.new_int(end).into(),
vm.ctx.none(),
])
} else {
vm.ctx.new_tuple(vec![
vm.ctx.new_int(start).into(),
vm.ctx.new_int(end).into(),
vm.ctx.new_int(line).into(),
])
};
lines.push(tuple.into());
}
}
let list = vm.ctx.new_list(lines);
vm.call_method(list.as_object(), "__iter__", ())
}
#[pymethod]
pub fn co_positions(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
// Return an iterator over (line, end_line, column, end_column) tuples for each instruction
let linetable = self.code.linetable.as_ref();
let mut positions = Vec::new();
if !linetable.is_empty() {
let mut reader = LineTableReader::new(linetable);
let mut line = self.code.first_line_number.map_or(0, |n| n.get() as i32);
while !reader.at_end() {
let first_byte = match reader.read_byte() {
Some(b) => b,
None => break,
};
if (first_byte & 0x80) == 0 {
break; // Invalid linetable
}
let code = (first_byte >> 3) & 0x0f;
let length = ((first_byte & 0x07) + 1) as i32;
let kind = match PyCodeLocationInfoKind::from_code(code) {
Some(k) => k,
None => break, // Invalid code
};
let (line_delta, end_line_delta, column, end_column): (
i32,
i32,
Option<i32>,
Option<i32>,
) = match kind {
PyCodeLocationInfoKind::None => {
// No location - all values are None
(0, 0, None, None)
}
PyCodeLocationInfoKind::Long => {
// Long form
let delta = reader.read_signed_varint();
let end_line_delta = reader.read_varint() as i32;
let col = reader.read_varint();
let column = if col == 0 {
None
} else {
Some((col - 1) as i32)
};