-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy path_cpython.mojo
1963 lines (1589 loc) · 63.4 KB
/
_cpython.mojo
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 (c) 2025, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""
Mojo bindings functions and types from the CPython C API.
Documentation for these functions can be found online at:
<https://docs.python.org/3/c-api/stable.html#contents-of-limited-api>
"""
from collections import InlineArray, Optional
from collections.string.string_slice import get_static_string
from os import abort, getenv, setenv
from os.path import dirname
from pathlib import Path
from sys import external_call
from sys.arg import argv
from sys.ffi import (
DLHandle,
OpaquePointer,
c_char,
c_int,
c_long,
c_size_t,
c_ssize_t,
c_uint,
)
from memory import UnsafePointer
from python._bindings import PyMojoObject, Pythonable, Typed_initproc
from python.python import _get_global_python_itf
# ===-----------------------------------------------------------------------===#
# Raw Bindings
# ===-----------------------------------------------------------------------===#
# https://github.com/python/cpython/blob/d45225bd66a8123e4a30314c627f2586293ba532/Include/compile.h#L7
alias Py_single_input = 256
alias Py_file_input = 257
alias Py_eval_input = 258
alias Py_func_type_input = 345
alias Py_tp_dealloc = 52
alias Py_tp_init = 60
alias Py_tp_methods = 64
alias Py_tp_new = 65
alias Py_tp_repr = 66
alias Py_TPFLAGS_DEFAULT = 0
alias Py_ssize_t = c_ssize_t
# TODO(MOCO-1138):
# This should be a C ABI function pointer, not a Mojo ABI function.
alias PyCFunction = fn (PyObjectPtr, PyObjectPtr) -> PyObjectPtr
"""[Reference](https://docs.python.org/3/c-api/structures.html#c.PyCFunction).
"""
alias METH_VARARGS = 0x1
alias destructor = fn (PyObjectPtr) -> None
alias reprfunc = fn (PyObjectPtr) -> PyObjectPtr
alias initproc = fn (PyObjectPtr, PyObjectPtr, PyObjectPtr) -> c_int
alias newfunc = fn (PyObjectPtr, PyObjectPtr, PyObjectPtr) -> PyObjectPtr
# GIL
@value
@register_passable("trivial")
struct PyGILState_STATE:
"""Represents the state of the Python Global Interpreter Lock (GIL).
Notes:
This struct is used to store and manage the state of the GIL, which is
crucial for thread-safe operations in Python. [Reference](
https://github.com/python/cpython/blob/d45225bd66a8123e4a30314c627f2586293ba532/Include/pystate.h#L76
).
"""
var current_state: c_int
"""The current state of the GIL."""
alias PyGILState_LOCKED = c_int(0)
alias PyGILState_UNLOCKED = c_int(1)
struct PyThreadState:
"""Opaque struct."""
pass
@value
@register_passable("trivial")
struct PyKeysValuePair:
"""Represents a key-value pair in a Python dictionary iteration.
This struct is used to store the result of iterating over a Python dictionary,
containing the key, value, current position, and success status of the iteration.
"""
var key: PyObjectPtr
"""The key of the current dictionary item."""
var value: PyObjectPtr
"""The value of the current dictionary item."""
var position: c_int
"""The current position in the dictionary iteration."""
var success: Bool
"""Indicates whether the iteration was successful."""
@value
@register_passable("trivial")
struct PyObjectPtr(CollectionElement):
"""Equivalent to `PyObject*` in C.
It is crucial that this type has the same size and alignment as `PyObject*`
for FFI ABI correctness.
This struct provides methods for initialization, null checking,
equality comparison, and conversion to integer representation.
"""
# ===-------------------------------------------------------------------===#
# Fields
# ===-------------------------------------------------------------------===#
var unsized_obj_ptr: UnsafePointer[PyObject]
"""Raw pointer to the underlying PyObject struct instance.
It is not valid to read or write a `PyObject` directly from this pointer.
This is because `PyObject` is an "unsized" or "incomplete" type: typically,
any allocation containing a `PyObject` contains additional fields holding
information specific to that Python object instance, e.g. containing its
"true" value.
The value behind this pointer is only safe to interact with directly when
it has been downcasted to a concrete Python object type backing struct, in
a context where the user has ensured the object value is of that type.
"""
# ===-------------------------------------------------------------------===#
# Life cycle methods
# ===-------------------------------------------------------------------===#
@always_inline
fn __init__(out self):
"""Initialize a null PyObjectPtr."""
self.unsized_obj_ptr = UnsafePointer[PyObject]()
# ===-------------------------------------------------------------------===#
# Operator dunders
# ===-------------------------------------------------------------------===#
fn __eq__(self, rhs: PyObjectPtr) -> Bool:
"""Compare two PyObjectPtr for equality.
Args:
rhs: The right-hand side PyObjectPtr to compare.
Returns:
Bool: True if the pointers are equal, False otherwise.
"""
return Int(self.unsized_obj_ptr) == Int(rhs.unsized_obj_ptr)
fn __ne__(self, rhs: PyObjectPtr) -> Bool:
"""Compare two PyObjectPtr for inequality.
Args:
rhs: The right-hand side PyObjectPtr to compare.
Returns:
Bool: True if the pointers are not equal, False otherwise.
"""
return not (self == rhs)
# ===-------------------------------------------------------------------===#
# Methods
# ===-------------------------------------------------------------------===#
fn try_cast_to_mojo_value[
T: AnyType,
](
owned self,
# TODO: Make this part of the trait bound
expected_type_name: StringSlice,
) -> Optional[UnsafePointer[T]]:
var cpython = _get_global_python_itf().cpython()
var type = cpython.Py_TYPE(self)
var type_name = PythonObject(cpython.PyType_GetName(type))
# FIXME(MSTDL-978):
# Improve this check. We should do something conceptually equivalent
# to:
# type == T.python_type_object
# where:
# trait Pythonable:
# var python_type_object: PyTypeObject
if type_name == PythonObject(expected_type_name):
return self.unchecked_cast_to_mojo_value[T]()
else:
return None
fn unchecked_cast_to_mojo_object[
T: AnyType
](owned self) -> UnsafePointer[PyMojoObject[T]]:
"""Assume that this Python object contains a wrapped Mojo value."""
return self.unsized_obj_ptr.bitcast[PyMojoObject[T]]()
fn unchecked_cast_to_mojo_value[T: AnyType](owned self) -> UnsafePointer[T]:
var mojo_obj_ptr = self.unchecked_cast_to_mojo_object[T]()
# TODO(MSTDL-950): Should use something like `addr_of!`
return UnsafePointer[T](to=mojo_obj_ptr[].mojo_value)
fn is_null(self) -> Bool:
"""Check if the pointer is null.
Returns:
Bool: True if the pointer is null, False otherwise.
"""
return Int(self.unsized_obj_ptr) == 0
# TODO: Consider removing this and inlining Int(p.value) into callers
fn _get_ptr_as_int(self) -> Int:
"""Get the pointer value as an integer.
Returns:
Int: The integer representation of the pointer.
"""
return Int(self.unsized_obj_ptr)
@value
@register_passable
struct PythonVersion:
"""Represents a Python version with major, minor, and patch numbers."""
var major: Int
"""The major version number."""
var minor: Int
"""The minor version number."""
var patch: Int
"""The patch version number."""
@implicit
fn __init__(out self, version: StringSlice):
"""Initialize a PythonVersion object from a version string.
Args:
version: A string representing the Python version (e.g., "3.9.5").
The version string is parsed to extract major, minor, and patch numbers.
If parsing fails for any component, it defaults to -1.
"""
var version_string = String(version)
var components = InlineArray[Int, 3](-1)
var start = 0
var next_idx = 0
var i = 0
while next_idx < len(version_string) and i < 3:
if version_string[next_idx] == "." or (
version_string[next_idx] == " " and i == 2
):
var c = version_string[start:next_idx]
try:
components[i] = atol(c)
except:
components[i] = -1
i += 1
start = next_idx + 1
next_idx += 1
self = PythonVersion(components[0], components[1], components[2])
fn _py_get_version(lib: DLHandle) -> StringSlice[StaticConstantOrigin]:
return StringSlice[StaticConstantOrigin](
unsafe_from_utf8_ptr=lib.call["Py_GetVersion", UnsafePointer[c_char]]()
)
fn _py_finalize(lib: DLHandle):
lib.call["Py_Finalize"]()
@value
struct PyMethodDef(CollectionElement):
"""Represents a Python method definition. This struct is used to define
methods for Python modules or types.
Notes:
[Reference](
https://docs.python.org/3/c-api/structures.html#c.PyMethodDef
).
"""
# ===-------------------------------------------------------------------===#
# Fields
# ===-------------------------------------------------------------------===#
var method_name: UnsafePointer[c_char]
"""A pointer to the name of the method as a C string.
Notes:
called `ml_name` in CPython.
"""
# TODO(MSTDL-887): Support keyword-argument only methods
var method_impl: PyCFunction
"""A function pointer to the implementation of the method."""
var method_flags: c_int
"""Flags indicating how the method should be called. [Reference](
https://docs.python.org/3/c-api/structures.html#c.PyMethodDef)."""
var method_docstring: UnsafePointer[c_char]
"""The docstring for the method."""
# ===-------------------------------------------------------------------===#
# Life cycle methods
# ===-------------------------------------------------------------------===#
fn __init__(out self):
"""Constructs a zero initialized PyModuleDef.
This is suitable for use terminating an array of PyMethodDef values.
"""
self.method_name = UnsafePointer[c_char]()
self.method_impl = _null_fn_ptr[PyCFunction]()
self.method_flags = 0
self.method_docstring = UnsafePointer[c_char]()
fn __init__(out self, *, other: Self):
"""Explicitly construct a deep copy of the provided value.
Args:
other: The value to copy.
"""
self = other
@staticmethod
fn function[
func: fn (PyObjectPtr, PyObjectPtr) -> PyObjectPtr,
func_name: StaticString,
docstring: StaticString = StaticString(),
]() -> Self:
"""Create a PyMethodDef for a function.
Parameters:
func: The function to wrap.
func_name: The name of the function.
docstring: The docstring for the function.
"""
# TODO(MSTDL-896):
# Support a way to get the name of the function from its parameter
# type, similar to `get_linkage_name()`?
# FIXME: PyMethodDef is capturing the pointer without an origin.
# Immortalize the string so we know it is permanent, and force it to be
# nul terminated.
alias func_name_str = get_static_string[func_name]()
alias docstring_str = get_static_string[docstring]()
return PyMethodDef(
func_name_str.unsafe_ptr().bitcast[c_char](),
func,
METH_VARARGS,
docstring_str.unsafe_ptr().bitcast[c_char](),
)
fn _null_fn_ptr[T: AnyTrivialRegType]() -> T:
return __mlir_op.`pop.pointer.bitcast`[_type=T](
__mlir_attr.`#interp.pointer<0> : !kgen.pointer<none>`
)
struct PyTypeObject:
"""The opaque C structure of the objects used to describe types.
Notes:
[Reference](https://docs.python.org/3/c-api/type.html#c.PyTypeObject).
"""
# TODO(MSTDL-877):
# Fill this out based on
# https://docs.python.org/3/c-api/typeobj.html#pytypeobject-definition
pass
@value
@register_passable("trivial")
struct PyType_Spec:
"""Structure defining a type's behavior.
Notes:
[Reference](https://docs.python.org/3/c-api/type.html#c.PyType_Spec).
"""
var name: UnsafePointer[c_char]
var basicsize: c_int
var itemsize: c_int
var flags: c_uint
var slots: UnsafePointer[PyType_Slot]
@value
@register_passable("trivial")
struct PyType_Slot(CollectionElement):
"""Structure defining optional functionality of a type, containing a slot ID
and a value pointer.
Notes:
[Reference](https://docs.python.org/3/c-api/type.html#c.PyType_Slot).
"""
var slot: c_int
var pfunc: OpaquePointer
@staticmethod
fn tp_new(func: newfunc) -> Self:
return PyType_Slot(Py_tp_new, rebind[OpaquePointer](func))
@staticmethod
fn tp_init(func: Typed_initproc) -> Self:
return PyType_Slot(Py_tp_init, rebind[OpaquePointer](func))
@staticmethod
fn tp_dealloc(func: destructor) -> Self:
return PyType_Slot(Py_tp_dealloc, rebind[OpaquePointer](func))
@staticmethod
fn tp_methods(methods: UnsafePointer[PyMethodDef]) -> Self:
return PyType_Slot(Py_tp_methods, rebind[OpaquePointer](methods))
@staticmethod
fn tp_repr(func: reprfunc) -> Self:
return PyType_Slot(Py_tp_repr, rebind[OpaquePointer](func))
@staticmethod
fn null() -> Self:
return PyType_Slot(0, OpaquePointer())
@value
struct PyObject(Stringable, Representable, Writable):
"""All object types are extensions of this type. This is a type which
contains the information Python needs to treat a pointer to an object as an
object. In a normal “release” build, it contains only the object's reference
count and a pointer to the corresponding type object. Nothing is actually
declared to be a PyObject, but every pointer to a Python object can be cast
to a PyObject.
Notes:
[Reference](https://docs.python.org/3/c-api/structures.html#c.PyObject).
"""
var object_ref_count: Int
var object_type: UnsafePointer[PyTypeObject]
fn __init__(out self):
self.object_ref_count = 0
self.object_type = UnsafePointer[PyTypeObject]()
@no_inline
fn __str__(self) -> String:
"""Get the PyModuleDef_Base as a string.
Returns:
A string representation.
"""
return String.write(self)
@no_inline
fn __repr__(self) -> String:
"""Get the `PyObject` as a string. Returns the same `String` as
`__str__`.
Returns:
A string representation.
"""
return String(self)
# ===-------------------------------------------------------------------===#
# Methods
# ===-------------------------------------------------------------------===#
fn write_to[W: Writer](self, mut writer: W):
"""Formats to the provided Writer.
Parameters:
W: A type conforming to the Writable trait.
Args:
writer: The object to write to.
"""
writer.write("PyObject(")
writer.write("object_ref_count=", self.object_ref_count, ",")
writer.write("object_type=", self.object_type)
writer.write(")")
# Mojo doesn't have macros, so we define it here for ease.
struct PyModuleDef_Base(Stringable, Representable, Writable):
"""PyModuleDef_Base.
Notes:
[Reference 1](
https://github.com/python/cpython/blob/833c58b81ebec84dc24ef0507f8c75fe723d9f66/Include/moduleobject.h#L39
). [Reference 2](
https://pyo3.rs/main/doc/pyo3/ffi/struct.pymoduledef_base
). `PyModuleDef_HEAD_INIT` defaults all of its members, [Reference 3](
https://github.com/python/cpython/blob/833c58b81ebec84dc24ef0507f8c75fe723d9f66/Include/moduleobject.h#L60
).
"""
var object_base: PyObject
"""The initial segment of every `PyObject` in CPython."""
# TODO(MOCO-1138): This is a C ABI function pointer, not Mojo a function.
alias _init_fn_type = fn () -> UnsafePointer[PyObject]
"""The function used to re-initialize the module."""
var init_fn: Self._init_fn_type
var index: Py_ssize_t
"""The module's index into its interpreter's modules_by_index cache."""
var dict_copy: UnsafePointer[PyObject]
"""A copy of the module's __dict__ after the first time it was loaded."""
# ===------------------------------------------------------------------=== #
# Life cycle methods
# ===------------------------------------------------------------------=== #
fn __init__(out self):
self.object_base = PyObject()
self.init_fn = _null_fn_ptr[Self._init_fn_type]()
self.index = 0
self.dict_copy = UnsafePointer[PyObject]()
fn __moveinit__(out self, owned existing: Self):
self.object_base = existing.object_base
self.init_fn = existing.init_fn
self.index = existing.index
self.dict_copy = existing.dict_copy
# ===-------------------------------------------------------------------===#
# Trait implementations
# ===-------------------------------------------------------------------===#
@no_inline
fn __str__(self) -> String:
"""Get the PyModuleDef_Base as a string.
Returns:
A string representation.
"""
return String.write(self)
@no_inline
fn __repr__(self) -> String:
"""Get the PyMdouleDef_Base as a string. Returns the same `String` as
`__str__`.
Returns:
A string representation.
"""
return String(self)
# ===-------------------------------------------------------------------===#
# Methods
# ===-------------------------------------------------------------------===#
fn write_to[W: Writer](self, mut writer: W):
"""Formats to the provided Writer.
Parameters:
W: A type conforming to the Writable trait.
Args:
writer: The object to write to.
"""
writer.write("PyModuleDef_Base(")
writer.write("object_base=", self.object_base, ",")
writer.write("init_fn=<unprintable>", ",")
writer.write("index=", self.index, ",")
writer.write("dict_copy=", self.dict_copy)
writer.write(")")
@value
struct PyModuleDef_Slot:
"""[Reference](
https://docs.python.org/3/c-api/module.html#c.PyModuleDef_Slot).
"""
var slot: c_int
var value: OpaquePointer
struct PyModuleDef(Stringable, Representable, Writable, Movable):
"""The Python module definition structs that holds all of the information
needed to create a module.
Notes:
[Reference](https://docs.python.org/3/c-api/module.html#c.PyModuleDef).
"""
var base: PyModuleDef_Base
var name: UnsafePointer[c_char]
"""[Reference](https://docs.python.org/3/c-api/structures.html#c.PyMethodDef
)."""
var docstring: UnsafePointer[c_char]
"""Points to the contents of the docstring for the module."""
var size: Py_ssize_t
var methods: UnsafePointer[PyMethodDef]
"""A pointer to a table of module-level functions. Can be null if there
are no functions present."""
var slots: UnsafePointer[PyModuleDef_Slot]
# TODO(MOCO-1138): These are C ABI function pointers, not Mojo functions.
alias _visitproc_fn_type = fn (PyObjectPtr, OpaquePointer) -> c_int
alias _traverse_fn_type = fn (
PyObjectPtr, Self._visitproc_fn_type, OpaquePointer
) -> c_int
var traverse_fn: Self._traverse_fn_type
alias _clear_fn_type = fn (PyObjectPtr) -> c_int
var clear_fn: Self._clear_fn_type
alias _free_fn_type = fn (OpaquePointer) -> OpaquePointer
var free_fn: Self._free_fn_type
@implicit
fn __init__(out self, name: StaticString):
self.base = PyModuleDef_Base()
self.name = name.unsafe_ptr().bitcast[c_char]()
self.docstring = UnsafePointer[c_char]()
# means that the module does not support sub-interpreters
self.size = -1
self.methods = UnsafePointer[PyMethodDef]()
self.slots = UnsafePointer[PyModuleDef_Slot]()
self.slots = UnsafePointer[PyModuleDef_Slot]()
self.traverse_fn = _null_fn_ptr[Self._traverse_fn_type]()
self.clear_fn = _null_fn_ptr[Self._clear_fn_type]()
self.free_fn = _null_fn_ptr[Self._free_fn_type]()
fn __moveinit__(out self, owned existing: Self):
self.base = existing.base^
self.name = existing.name
self.docstring = existing.docstring
self.size = existing.size
self.methods = existing.methods
self.slots = existing.slots
self.traverse_fn = existing.traverse_fn
self.clear_fn = existing.clear_fn
self.free_fn = existing.free_fn
# ===-------------------------------------------------------------------===#
# Trait implementations
# ===-------------------------------------------------------------------===#
@no_inline
fn __str__(self) -> String:
"""Get the PyModuleDefe as a string.
Returns:
A string representation.
"""
return String.write(self)
@no_inline
fn __repr__(self) -> String:
"""Get the PyMdouleDef as a string. Returns the same `String` as
`__str__`.
Returns:
A string representation.
"""
return String(self)
# ===-------------------------------------------------------------------===#
# Methods
# ===-------------------------------------------------------------------===#
fn write_to[W: Writer](self, mut writer: W):
"""Formats to the provided Writer.
Parameters:
W: A type conforming to the Writable trait.
Args:
writer: The object to write to.
"""
writer.write("PyModuleDef(")
writer.write("base=", self.base, ",")
writer.write("name=", self.name, ",")
writer.write("docstring=", self.docstring, ",")
writer.write("size=", self.size, ",")
writer.write("methods=", self.methods, ",")
writer.write("slots=", self.slots, ",")
writer.write("traverse_fn=<unprintable>", ",")
writer.write("clear_fn=<unprintable>", ",")
writer.write("free_fn=<unprintable>")
writer.write(")")
@value
struct CPython:
"""Handle to the CPython interpreter present in the current process."""
# ===-------------------------------------------------------------------===#
# Fields
# ===-------------------------------------------------------------------===#
var lib: DLHandle
"""The handle to the CPython shared library."""
var logging_enabled: Bool
"""Whether logging is enabled."""
var version: PythonVersion
"""The version of the Python runtime."""
var total_ref_count: UnsafePointer[Int]
"""The total reference count of all Python objects."""
var init_error: StringSlice[StaticConstantOrigin]
"""An error message if initialization failed."""
# ===-------------------------------------------------------------------===#
# Life cycle methods
# ===-------------------------------------------------------------------===#
fn __init__(out self):
var logging_enabled = getenv("MODULAR_CPYTHON_LOGGING") == "ON"
if logging_enabled:
print("CPython init")
print("MOJO_PYTHON:", getenv("MOJO_PYTHON"))
print("MOJO_PYTHON_LIBRARY:", getenv("MOJO_PYTHON_LIBRARY"))
# Add directory of target file to top of sys.path to find python modules
var file_dir = dirname(argv()[0])
if Path(file_dir).is_dir() or file_dir == "":
var python_path = getenv("PYTHONPATH")
# A leading `:` will put the current dir at the top of sys.path.
# If we're doing `mojo run main.mojo` or `./main`, the returned
# `dirname` will be an empty string.
if file_dir == "" and not python_path:
file_dir = ":"
if python_path:
_ = setenv("PYTHONPATH", file_dir + ":" + python_path)
else:
_ = setenv("PYTHONPATH", file_dir)
# TODO(MOCO-772) Allow raises to propagate through function pointers
# and make this initialization a raising function.
self.init_error = StringSlice[StaticConstantOrigin](
unsafe_from_utf8_ptr=external_call[
"KGEN_CompilerRT_Python_SetPythonPath", UnsafePointer[c_char]
]()
)
var python_lib = getenv("MOJO_PYTHON_LIBRARY")
if logging_enabled:
print("PYTHONEXECUTABLE:", getenv("PYTHONEXECUTABLE"))
print("libpython selected:", python_lib)
self.lib = DLHandle(python_lib)
self.total_ref_count = UnsafePointer[Int].alloc(1)
self.logging_enabled = logging_enabled
if not self.init_error:
if not self.lib.check_symbol("Py_Initialize"):
self.init_error = "compatible Python library not found"
self.lib.call["Py_Initialize"]()
self.version = PythonVersion(_py_get_version(self.lib))
else:
self.version = PythonVersion(0, 0, 0)
fn __del__(owned self):
pass
@staticmethod
fn destroy(mut existing: CPython):
if existing.logging_enabled:
print("CPython destroy")
var remaining_refs = existing.total_ref_count.take_pointee()
print("Number of remaining refs:", remaining_refs)
# Technically not necessary since we're working with register
# passable types, by it's good practice to re-initialize the
# pointer after a consuming move.
existing.total_ref_count.init_pointee_move(remaining_refs)
_py_finalize(existing.lib)
existing.lib.close()
existing.total_ref_count.free()
fn check_init_error(self) raises:
"""Used for entry points that initialize Python on first use, will
raise an error if one occurred when initializing the global CPython.
"""
if self.init_error:
var error = String(self.init_error)
var mojo_python = getenv("MOJO_PYTHON")
var python_lib = getenv("MOJO_PYTHON_LIBRARY")
var python_exe = getenv("PYTHONEXECUTABLE")
if mojo_python:
error += "\nMOJO_PYTHON: " + mojo_python
if python_lib:
error += "\nMOJO_PYTHON_LIBRARY: " + python_lib
if python_exe:
error += "\npython executable: " + python_exe
error += "\n\nMojo/Python interop error, troubleshooting docs at:"
error += "\n https://modul.ar/fix-python\n"
raise error
# ===-------------------------------------------------------------------===#
# Logging
# ===-------------------------------------------------------------------===#
@always_inline
fn log[*Ts: Writable](self, *args: *Ts):
"""If logging is enabled, print the given arguments as a log message.
Parameters:
Ts: The argument types.
Arguments:
args: The arguments to log.
"""
if not self.logging_enabled:
return
# TODO(MOCO-358):
# Once Mojo argument splatting is supported, this should just
# be: `print(*args)`
@parameter
fn print_arg[T: Writable](arg: T):
print(arg, sep="", end="", flush=False)
args.each[print_arg]()
print(flush=True)
# ===-------------------------------------------------------------------===#
# Reference count management
# ===-------------------------------------------------------------------===#
fn _inc_total_rc(self):
var v = self.total_ref_count.take_pointee()
self.total_ref_count.init_pointee_move(v + 1)
fn _dec_total_rc(self):
var v = self.total_ref_count.take_pointee()
self.total_ref_count.init_pointee_move(v - 1)
fn Py_IncRef(self, ptr: PyObjectPtr):
"""[Reference](
https://docs.python.org/3/c-api/refcounting.html#c.Py_IncRef).
"""
self.log(ptr._get_ptr_as_int(), " INCREF refcnt:", self._Py_REFCNT(ptr))
self.lib.call["Py_IncRef"](ptr)
self._inc_total_rc()
fn Py_DecRef(self, ptr: PyObjectPtr):
"""[Reference](
https://docs.python.org/3/c-api/refcounting.html#c.Py_DecRef).
"""
self.log(ptr._get_ptr_as_int(), " DECREF refcnt:", self._Py_REFCNT(ptr))
self.lib.call["Py_DecRef"](ptr)
self._dec_total_rc()
# This function assumes a specific way PyObjectPtr is implemented, namely
# that the refcount has offset 0 in that structure. That generally doesn't
# have to always be the case - but often it is and it's convenient for
# debugging. We shouldn't rely on this function anywhere - its only purpose
# is debugging.
fn _Py_REFCNT(self, ptr: PyObjectPtr) -> Int:
if ptr._get_ptr_as_int() == 0:
return -1
# NOTE:
# The "obvious" way to write this would be:
# return ptr.unsized_obj_ptr[].object_ref_count
# However, that is not valid, because, as the name suggest, a PyObject
# is an "unsized" or "incomplete" type, meaning that a pointer to an
# instance of that type doesn't point at the entire allocation of the
# underlying "concrete" object instance.
#
# To avoid concerns about whether that's UB or not in Mojo, this
# this by just assumes the first field will be the ref count, and
# treats the object pointer "as if" it was a pointer to just the first
# field.
# TODO(MSTDL-950): Should use something like `addr_of!`
return ptr.unsized_obj_ptr.bitcast[Int]()[]
# ===-------------------------------------------------------------------===#
# Python GIL and threading
# ===-------------------------------------------------------------------===#
fn PyGILState_Ensure(self) -> PyGILState_STATE:
"""[Reference](
https://docs.python.org/3/c-api/init.html#c.PyGILState_Ensure).
"""
return self.lib.call["PyGILState_Ensure", PyGILState_STATE]()
fn PyGILState_Release(self, state: PyGILState_STATE):
"""[Reference](
https://docs.python.org/3/c-api/init.html#c.PyGILState_Release).
"""
self.lib.call["PyGILState_Release"](state)
fn PyEval_SaveThread(self) -> UnsafePointer[PyThreadState]:
"""[Reference](
https://docs.python.org/3/c-api/init.html#c.PyEval_SaveThread).
"""
return self.lib.call[
"PyEval_SaveThread", UnsafePointer[PyThreadState]
]()
fn PyEval_RestoreThread(self, state: UnsafePointer[PyThreadState]):
"""[Reference](
https://docs.python.org/3/c-api/init.html#c.PyEval_RestoreThread).
"""
self.lib.call["PyEval_RestoreThread"](state)
# ===-------------------------------------------------------------------===#
# Python Dict operations
# ===-------------------------------------------------------------------===#
fn PyDict_New(self) -> PyObjectPtr:
"""[Reference](
https://docs.python.org/3/c-api/dict.html#c.PyDict_New).
"""
var r = self.lib.call["PyDict_New", PyObjectPtr]()
self.log(
r._get_ptr_as_int(),
" NEWREF PyDict_New, refcnt:",
self._Py_REFCNT(r),
)
self._inc_total_rc()
return r
# int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
fn PyDict_SetItem(
self, dict_obj: PyObjectPtr, key: PyObjectPtr, value: PyObjectPtr
) -> c_int:
"""[Reference](
https://docs.python.org/3/c-api/dict.html#c.PyDict_SetItem).
"""
var r = self.lib.call["PyDict_SetItem", c_int](dict_obj, key, value)
self.log(
"PyDict_SetItem, key: ",
key._get_ptr_as_int(),
" value: ",
value._get_ptr_as_int(),
)
return r
fn PyDict_GetItemWithError(
self, dict_obj: PyObjectPtr, key: PyObjectPtr
) -> PyObjectPtr:
"""[Reference](
https://docs.python.org/3/c-api/dict.html#c.PyDict_GetItemWithError).
"""
var r = self.lib.call["PyDict_GetItemWithError", PyObjectPtr](
dict_obj, key
)
self.log("PyDict_GetItemWithError, key: ", key._get_ptr_as_int())