-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython.go
More file actions
772 lines (706 loc) · 22.5 KB
/
Copy pathpython.go
File metadata and controls
772 lines (706 loc) · 22.5 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
// Code generated by protoc-gen-wasmify-go. DO NOT EDIT.
package python
import (
"encoding/binary"
"errors"
"fmt"
"math"
"os"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"github.com/goccy/pythonwasm2go"
"github.com/goccy/pythonwasm2go/base"
)
var (
_ = binary.LittleEndian
_ = errors.New
_ = fmt.Errorf
_ = math.Float32bits
_ = os.Stderr
_ = runtime.SetFinalizer
_ = sort.Search
_ = strconv.Itoa
_ = strings.TrimSpace
_ = sync.Once{}
_ = wasm2go.Memory
_ *base.Module
)
// pbAppendVarint appends a varint-encoded uint64.
func pbAppendVarint(buf []byte, v uint64) []byte {
for v >= 0x80 {
buf = append(buf, byte(v)|0x80)
v >>= 7
}
return append(buf, byte(v))
}
// pbAppendTag appends a field tag.
func pbAppendTag(buf []byte, field, wireType uint32) []byte {
return pbAppendVarint(buf, uint64(field<<3|wireType))
}
func pbAppendUint64(buf []byte, field uint32, v uint64) []byte {
buf = pbAppendTag(buf, field, 0)
return pbAppendVarint(buf, v)
}
func pbAppendInt32(buf []byte, field uint32, v int32) []byte {
buf = pbAppendTag(buf, field, 0)
return pbAppendVarint(buf, uint64(v))
}
func pbAppendInt64(buf []byte, field uint32, v int64) []byte {
buf = pbAppendTag(buf, field, 0)
return pbAppendVarint(buf, uint64(v))
}
func pbAppendBool(buf []byte, field uint32, v bool) []byte {
buf = pbAppendTag(buf, field, 0)
if v {
return append(buf, 1)
}
return append(buf, 0)
}
func pbAppendString(buf []byte, field uint32, s string) []byte {
buf = pbAppendTag(buf, field, 2)
buf = pbAppendVarint(buf, uint64(len(s)))
return append(buf, s...)
}
func pbAppendBytes(buf []byte, field uint32, data []byte) []byte {
buf = pbAppendTag(buf, field, 2)
buf = pbAppendVarint(buf, uint64(len(data)))
return append(buf, data...)
}
func pbAppendFloat(buf []byte, field uint32, v float32) []byte {
buf = pbAppendTag(buf, field, 5)
var tmp [4]byte
binary.LittleEndian.PutUint32(tmp[:], math.Float32bits(v))
return append(buf, tmp[:]...)
}
func pbAppendDouble(buf []byte, field uint32, v float64) []byte {
buf = pbAppendTag(buf, field, 1)
var tmp [8]byte
binary.LittleEndian.PutUint64(tmp[:], math.Float64bits(v))
return append(buf, tmp[:]...)
}
func pbAppendSubmessage(buf []byte, field uint32, sub []byte) []byte {
buf = pbAppendTag(buf, field, 2)
buf = pbAppendVarint(buf, uint64(len(sub)))
return append(buf, sub...)
}
func pbAppendHandle(buf []byte, field uint32, ptr uint64) []byte {
sub := pbAppendUint64(nil, 1, ptr)
return pbAppendSubmessage(buf, field, sub)
}
// pbAppendHandlePtr is the nil-safe one-line wrapper around
// pbAppendHandle. Generic + comparable lets it accept any
// pointer-typed wrapper that provides rawPtr() and short-circuit
// when the pointer is nil. The caller writes
//
// buf = pbAppendHandlePtr(buf, N, v.X)
//
// which gofmt keeps as one line; the alternative
//
// if v.X != nil { buf = pbAppendHandle(buf, N, v.X.rawPtr()) }
//
// is gofmt-expanded to three lines per occurrence and accounts
// for several hundred KB of bloat across the binding.
func pbAppendHandlePtr[T interface {
comparable
rawPtr() uint64
}](buf []byte, field uint32, v T) []byte {
var zero T
if v == zero {
return buf
}
return pbAppendHandle(buf, field, v.rawPtr())
}
// pbAppendSubmessagePtr is the value-type-message counterpart of
// pbAppendHandlePtr: nil-safe, gofmt-friendly one-liner around
// pbAppendSubmessage + the type's marshal() helper.
func pbAppendSubmessagePtr[T interface {
comparable
marshal() []byte
}](buf []byte, field uint32, v T) []byte {
var zero T
if v == zero {
return buf
}
return pbAppendSubmessage(buf, field, v.marshal())
}
// clearPtrAny is the gofmt-friendly nil-safe ownership-transfer
// helper for handle parameters. Replaces the inline expansion
//
// if c, ok := v.(interface{ clearPtr() }); ok { c.clearPtr() }
//
// (3 lines after gofmt) plus its surrounding nil-guard with a
// single function call. Handles both interface values
// (CatalogNode et al) and concrete pointers; the type assertion
// short-circuits when v is a true-nil interface, and the wrapped
// clearPtr() is itself nil-receiver-safe so a typed-nil pointer
// passed through the interface no-ops cleanly.
func clearPtrAny(v any) {
if c, ok := v.(interface{ clearPtr() }); ok {
c.clearPtr()
}
}
// clearPtrAll is the slice variant of clearPtrAny. Used when the
// proto-field's wire shape is repeated-handle and the C++ side
// adopts ownership of every element. Each element runs through
// the same type-assertion shortcut so the helper handles
// concrete-pointer slices, interface slices, and slices that mix
// nil and non-nil entries uniformly.
func clearPtrAll[T any](items []T) {
for _, item := range items {
clearPtrAny(item)
}
}
// pbReader is a streaming protobuf decoder.
type pbReader struct {
data []byte
pos int
}
func (r *pbReader) hasData() bool { return r.pos < len(r.data) }
func (r *pbReader) readVarint() uint64 {
var v uint64
var shift uint
for r.pos < len(r.data) {
b := r.data[r.pos]
r.pos++
v |= uint64(b&0x7f) << shift
if b < 0x80 {
return v
}
shift += 7
}
return v
}
func (r *pbReader) next() (field, wireType uint32, ok bool) {
if !r.hasData() {
return 0, 0, false
}
tag := r.readVarint()
return uint32(tag >> 3), uint32(tag & 7), true
}
func (r *pbReader) readString() string {
n := int(r.readVarint())
if r.pos+n > len(r.data) {
n = len(r.data) - r.pos
}
s := string(r.data[r.pos : r.pos+n])
r.pos += n
return s
}
func (r *pbReader) readBytes() []byte {
n := int(r.readVarint())
if r.pos+n > len(r.data) {
n = len(r.data) - r.pos
}
b := make([]byte, n)
copy(b, r.data[r.pos:r.pos+n])
r.pos += n
return b
}
func (r *pbReader) readBool() bool {
return r.readVarint() != 0
}
func (r *pbReader) readInt32() int32 {
return int32(r.readVarint())
}
func (r *pbReader) readInt64() int64 {
return int64(r.readVarint())
}
func (r *pbReader) readUint32() uint32 {
return uint32(r.readVarint())
}
func (r *pbReader) readUint64() uint64 {
return r.readVarint()
}
func (r *pbReader) readFloat() float32 {
if r.pos+4 > len(r.data) {
r.pos = len(r.data)
return 0
}
v := binary.LittleEndian.Uint32(r.data[r.pos : r.pos+4])
r.pos += 4
return math.Float32frombits(v)
}
func (r *pbReader) readDouble() float64 {
if r.pos+8 > len(r.data) {
r.pos = len(r.data)
return 0
}
v := binary.LittleEndian.Uint64(r.data[r.pos : r.pos+8])
r.pos += 8
return math.Float64frombits(v)
}
func (r *pbReader) readSubmessage() *pbReader {
n := int(r.readVarint())
if r.pos+n > len(r.data) {
n = len(r.data) - r.pos
}
sub := &pbReader{data: r.data[r.pos : r.pos+n]}
r.pos += n
return sub
}
func (r *pbReader) skip(wireType uint32) {
switch wireType {
case 0: // varint
r.readVarint()
case 1: // 64-bit
r.pos += 8
case 2: // length-delimited
n := int(r.readVarint())
r.pos += n
case 5: // 32-bit
r.pos += 4
}
if r.pos > len(r.data) {
r.pos = len(r.data)
}
}
// pbExtractError scans a response for field 15 (error string).
func pbExtractError(resp []byte) error {
r := &pbReader{data: resp}
for f, w, ok := r.next(); ok; f, w, ok = r.next() {
if f == 15 {
return errors.New(r.readString())
}
r.skip(w)
}
return nil
}
// readHandlePtr reads the ptr from a response. Handles two patterns:
// 1. Direct varint: field 1, wireType 0 → read varint directly
// 2. Submessage: field 1, wireType 2 → read submessage, then field 1 varint inside
func readHandlePtr(data []byte) uint64 {
r := &pbReader{data: data}
for f, w, ok := r.next(); ok; f, w, ok = r.next() {
if f == 1 {
if w == 0 {
// Direct varint (constructor pattern)
return r.readVarint()
}
if w == 2 {
// Submessage (write_handle pattern)
sub := r.readSubmessage()
for sf, sw, sok := sub.next(); sok; sf, sw, sok = sub.next() {
if sf == 1 && sw == 0 {
return sub.readVarint()
}
sub.skip(sw)
}
}
return 0
}
r.skip(w)
}
return 0
}
// readPtrAtField returns the handle pointer encoded at response field f.
// f == 1 takes the fast path via readHandlePtr (which already handles
// both the direct-varint constructor shape and the submessage write_handle
// shape); other fields are walked once to find the correct submessage.
// Returns 0 if the field is not present, which is the standard "absent
// handle" sentinel — callers translate that to (nil, nil).
func readPtrAtField(resp []byte, f uint32) uint64 {
if f == 1 {
return readHandlePtr(resp)
}
pr := &pbReader{data: resp}
for ff, w, ok := pr.next(); ok; ff, w, ok = pr.next() {
if ff == f {
if w == 2 {
sub := pr.readSubmessage()
return readHandlePtr(sub.data)
}
return 0
}
pr.skip(w)
}
return 0
}
// decodeChildHandle is the standard accessor-return shape. It reads
// the handle pointer at field f, returns nil for missing/zero, and
// otherwise constructs the child via ctor and pins the parent (owner)
// onto it via setKeepAlive when owner is non-nil. Constructor-style
// callers (free functions) pass owner=nil; accessors pass the
// receiver. The child must already implement the unexported keepAlive
// interface, which every generated handle struct does.
func decodeChildHandle[T any](resp []byte, field uint32, owner any, ctor func(uint64) *T) *T {
ptr := readPtrAtField(resp, field)
if ptr == 0 {
return nil
}
child := ctor(ptr)
if owner != nil {
if ka, ok := any(child).(interface{ setKeepAlive(any) }); ok {
ka.setKeepAlive(owner)
}
}
return child
}
// decodeAbstractAs is the abstract-return counterpart of
// decodeChildHandle: read field f, look up the runtime concrete type
// via resolveAbstractHandle, type-assert to I, attach keepAlive when
// owner is non-nil. ifaceName is only used in the error message when
// the runtime type does not satisfy I (which is a real bug, not a
// "missing field" condition).
func decodeAbstractAs[I any](resp []byte, field uint32, owner any, ifaceName string) (I, error) {
var z I
ptr := readPtrAtField(resp, field)
if ptr == 0 {
return z, nil
}
resolved, err := resolveAbstractHandle(ptr)
if err != nil {
return z, err
}
if v, ok := resolved.(I); ok {
if owner != nil {
if ka, okKA := any(v).(interface{ setKeepAlive(any) }); okKA {
ka.setKeepAlive(owner)
}
}
return v, nil
}
return z, fmt.Errorf("resolved type %T does not implement %s", resolved, ifaceName)
}
// readScalarAtField walks resp once for field f and reads the value via
// the read closure. Missing field returns the zero value. The closure is
// always one of (*pbReader).readBool / readInt32 / readInt64 / readUint32
// / readUint64 / readFloat / readDouble / readString / readBytes - small
// values, but they fold the per-method scan-and-read loop into one call
// site.
func readScalarAtField[T any](resp []byte, f uint32, read func(*pbReader) T) T {
var z T
pr := &pbReader{data: resp}
for ff, w, ok := pr.next(); ok; ff, w, ok = pr.next() {
if ff == f {
return read(pr)
}
pr.skip(w)
}
return z
}
// factoryFor curries a typed constructor (newXNoFinalizer) into the
// untyped factory shape stored in cppTypeFactories. Without it the
// generated cppTypeToGoType map had to repeat
//
// "googlesql::Foo": func(ptr uint64) any { return newFooNoFinalizer(ptr) }
//
// per concrete type — ~1,400 structurally-identical closures.
func factoryFor[T any](ctor func(uint64) *T) func(uint64) any {
return func(ptr uint64) any { return ctor(ptr) }
}
// enumString backs the per-enum String() methods. Generated code emits
// parallel _vals_<E> []int32 and _names_<E> []string slices keyed in
// canonical order; this helper does a linear scan and falls back to
// the decimal form for values that aren't in the table (forward
// compatibility when new values land before regeneration).
func enumString(v int32, vals []int32, names []string) string {
for i, x := range vals {
if x == v {
return names[i]
}
}
return strconv.Itoa(int(v))
}
var _ = errors.New
var _ = binary.LittleEndian
var _ = fmt.Errorf
var _ = math.Float32bits
var _ = strconv.Itoa
// Module is the bridge handle. It wraps the wasm2go-transpiled module
// (*base.Module) and serialises every entry on m.mu.
//
// Reentrant callbacks — a host-import callback whose handler needs
// to make further calls back into the transpiled module — are
// supported by releasing m.mu around the user handler in
// handleCallback.
//
// Safety rests on a single structural property: every path that
// touches transpiled module state goes through m.invoke, and
// m.invoke holds m.mu for the entire duration of its call. The
// release window in handleCallback simply lets another m.invoke
// grab the mutex and run as a fully nested top-level call — same
// goroutine via the user handler, different goroutine via an
// unrelated caller, it doesn't matter. Either way the nested call
// enters, balances its own state changes, and exits before the
// outer call resumes, so the outer call never observes a mid-flight
// inner call.
type Module struct {
// mu serialises every entry into the transpiled module (invoke +
// nested re-entry from inside a callback handler).
mu sync.Mutex
g *base.Module
// cbMu guards callbacks and nextCBID. RWMutex because lookup in
// handleCallback is hot (every host-import dispatch) while
// Register/Unregister are rare (typically once per lifetime of a
// registered Go-side handler). Held only for the brief map op;
// never held while running user code or the transpiled module,
// so it never participates in the m.mu -> transpiled-module ->
// handleCallback chain and cannot deadlock against it.
cbMu sync.RWMutex
callbacks map[int32]CallbackHandler
nextCBID int32
}
var (
globalModule *Module
initOnce sync.Once
initErr error
)
// CallbackHandler is implemented by Go types that need to be called from C++.
// The type is always defined (the Module struct references it); the
// registration/dispatch machinery is only emitted when the wasm imports
// wasmify.callback_invoke.
type CallbackHandler interface {
HandleCallback(methodID int32, req []byte) ([]byte, error)
}
// Init initializes the global module. Must be called before any API
// use. Safe to call multiple times (uses sync.Once).
func Init() error {
initOnce.Do(func() {
initErr = initModule()
})
return initErr
}
// module returns the initialized global module. Panics if Init was not
// called.
func module() *Module {
if globalModule == nil {
panic("wasmify: Init() must be called before using any API")
}
return globalModule
}
func initModule() (retErr error) {
m := &Module{}
env := envStubs{m: m}
m.g = wasm2go.New(env)
// Set globalModule eagerly so the rest of the API can run even if
// _initialize panics partway through C++ static-initializer code.
globalModule = m
defer func() {
if r := recover(); r != nil {
retErr = fmt.Errorf("init panicked: %v", r)
}
}()
wasm2go.Initialize(m.g)
_ = wasm2go.WasmInit(m.g)
return nil
}
// invoke serializes req into wasm memory, runs the per-export caller
// (wasm2go.Inv_<svc>_<mt>), and unpacks the (ptr<<32 | len) response.
// call is the trap-safe per-export entry point: it snapshots and
// restores the mutable wasm globals so a mid-call panic does not leak
// an abandoned C++ activation frame.
func (m *Module) invoke(serviceID, methodID int32, req []byte, call func(*base.Module, int32, int32) (int64, error)) ([]byte, error) {
m.mu.Lock()
defer m.mu.Unlock()
var reqPtr, reqLen int32
if len(req) > 0 {
reqPtr = wasm2go.WasmAlloc(m.g, int32(len(req)))
reqLen = int32(len(req))
// Free reqPtr unconditionally on return so the request
// buffer never lingers in wasm memory when the call traps
// or the early-exit branches below fire. Guard against
// the WasmAlloc-returned-zero case: free(NULL) is a
// dlmalloc no-op but C++ allocators are less consistent.
if reqPtr != 0 {
defer wasm2go.WasmFree(m.g, reqPtr)
}
copy(wasm2go.Memory(m.g)[reqPtr:], req)
}
packed, err := call(m.g, reqPtr, reqLen)
if err != nil {
return nil, err
}
respPtr := uint32(packed >> 32)
respLen := uint32(packed & 0xFFFFFFFF)
if respLen == 0 {
return nil, nil
}
mem := wasm2go.Memory(m.g)
out := make([]byte, respLen)
copy(out, mem[respPtr:respPtr+respLen])
wasm2go.WasmFree(m.g, int32(respPtr))
return out, nil
}
// resolveTypeName calls the C++ bridge to get the runtime type name of
// the object at ptr. Returns a fully qualified C++ class name.
func (m *Module) resolveTypeName(ptr uint64) (string, error) {
buf := pbAppendUint64(nil, 1, ptr)
m.mu.Lock()
defer m.mu.Unlock()
reqPtr := wasm2go.WasmAlloc(m.g, int32(len(buf)))
copy(wasm2go.Memory(m.g)[reqPtr:], buf)
packed := wasm2go.WasmifyGetTypeName(m.g, reqPtr, int32(len(buf)))
respPtr := uint32(packed >> 32)
respLen := uint32(packed & 0xFFFFFFFF)
defer wasm2go.WasmFree(m.g, reqPtr)
if respLen == 0 {
return "", nil
}
resp := make([]byte, respLen)
copy(resp, wasm2go.Memory(m.g)[respPtr:respPtr+respLen])
defer wasm2go.WasmFree(m.g, int32(respPtr))
if e := pbExtractError(resp); e != nil {
return "", e
}
r := &pbReader{data: resp}
for f, w, ok := r.next(); ok; f, w, ok = r.next() {
if f == 1 {
return r.readString(), nil
}
r.skip(w)
}
return "", nil
}
// invokeMethod fans the wasm call out into the runtime, then folds in
// the (very common) pbExtractError check on the response. call is the
// per-export wasm2go.Inv_<svc>_<mt> entry point.
func invokeMethod(svc, mid int32, req []byte, call func(*base.Module, int32, int32) (int64, error)) ([]byte, error) {
resp, err := module().invoke(svc, mid, req, call)
if err != nil {
return nil, err
}
if e := pbExtractError(resp); e != nil {
return nil, e
}
return resp, nil
}
// envStubs implements wasm2go/base.EnvImports — the host side of the
// wasm "env" imports. The per-method definitions are emitted by the
// generator (generateEnvStubs) since the import set is module-specific.
type envStubs struct{ m *Module }
func (h envStubs) Dlerror(m *base.Module) int32 { return 0 }
func (h envStubs) Dlopen(m *base.Module, l0 int32, l1 int32) int32 { return 0 }
func (h envStubs) Dlsym(m *base.Module, l0 int32, l1 int32) int32 { return 0 }
func (h envStubs) Getpid(m *base.Module) int32 { return 0 }
var _ = fmt.Errorf
var _ = sort.Search
// cppTypeNames / cppTypeFactories: parallel sorted slices replacing
// the old cppTypeToGoType map literal. Looked up via sort.Search.
var cppTypeNames = []string{}
var cppTypeFactories = []func(uint64) any{}
// resolveAbstractHandle queries the C++ runtime for the actual type of the
// object at ptr and returns the appropriate concrete Go handle type.
func resolveAbstractHandle(ptr uint64) (any, error) {
typeName, err := module().resolveTypeName(ptr)
if err != nil {
return nil, fmt.Errorf("resolveTypeName: %w", err)
}
i := sort.SearchStrings(cppTypeNames, typeName)
if i < len(cppTypeNames) && cppTypeNames[i] == typeName {
return cppTypeFactories[i](ptr), nil
}
return nil, fmt.Errorf("unknown C++ type %q for ptr 0x%x", typeName, ptr)
}
var _ = errors.New
var _ = fmt.Errorf
var _ = runtime.SetFinalizer
func PyAsyncExcAddr(h uint64) (uint32, error) {
var buf []byte
buf = pbAppendUint64(buf, 1, h)
resp, err := invokeMethod(0, 0, buf, wasm2go.Inv_0_0)
if err != nil {
return 0, err
}
return readScalarAtField(resp, 1, (*pbReader).readUint32), nil
}
// Destroy the interpreter and finalize the runtime.
func PyClose(h uint64) error {
var buf []byte
buf = pbAppendUint64(buf, 1, h)
_, err := invokeMethod(0, 1, buf, wasm2go.Inv_0_1)
return err
}
// Evaluate `src` and return the result as a JSON object string:
//
// {"ok":
//
// <bool
// >,"repr":
// <string
// >,"stdout":
// <string
// >,"stderr":
// <string
// >,
//
// "error":
//
// <string
// >}
//
// If `src` parses as a single expression, "repr" holds repr() of its value
// (empty for statements / None). "stdout"/"stderr" hold anything written to
// sys.stdout/sys.stderr during execution. On an uncaught exception, "ok" is
// false and "error" holds the formatted traceback. Globals persist across
// calls on the same handle (REPL-like).
//
// A single JSON string return is used because the bridge generator surfaces
// only one response value to Go; bundling the outputs keeps one round-trip
// and one atomic result. The Go wrapper unmarshals it.
func PyEval(h uint64, src string) (string, error) {
var buf []byte
buf = pbAppendUint64(buf, 1, h)
buf = pbAppendString(buf, 2, src)
resp, err := invokeMethod(0, 2, buf, wasm2go.Inv_0_2)
if err != nil {
return "", err
}
return readScalarAtField(resp, 1, (*pbReader).readString), nil
}
// ---- Interruption support ------------------------------------------------
//
// Mirrors PyThreadState_SetAsyncExc() done as plain memory writes, so a host
// watchdog goroutine can raise KeyboardInterrupt in a running interpreter
// WITHOUT executing any wasm/C code on that instance (which would corrupt the
// shared linear-memory C stack). To interrupt, the host performs:
//
// *(uint32_t *)py_async_exc_addr(h) = py_keyboard_interrupt_obj(h);
// atomic_or((uint32_t *)py_eval_breaker_addr(h), 8); // _PY_ASYNC_EXCEPTION_BIT
//
// CPython checks eval_breaker on every bytecode backward edge (3.9+), so it
// raises KeyboardInterrupt at the next loop iteration — including a pure
// `while True: pass`. PyExc_KeyboardInterrupt is immortal in 3.14, so storing
// it needs no refcount bookkeeping. Addresses are 32-bit linear-memory
// offsets (wasm32). The async-exception bit is the constant 8 (1u
// <
// <
// 3).
func PyEvalBreakerAddr(h uint64) (uint32, error) {
var buf []byte
buf = pbAppendUint64(buf, 1, h)
resp, err := invokeMethod(0, 3, buf, wasm2go.Inv_0_3)
if err != nil {
return 0, err
}
return readScalarAtField(resp, 1, (*pbReader).readUint32), nil
}
func PyKeyboardInterruptObj(h uint64) (uint32, error) {
var buf []byte
buf = pbAppendUint64(buf, 1, h)
resp, err := invokeMethod(0, 4, buf, wasm2go.Inv_0_4)
if err != nil {
return 0, err
}
return readScalarAtField(resp, 1, (*pbReader).readUint32), nil
}
// Initialize the CPython runtime (isolated config) and return an opaque
// interpreter handle (0 on failure). Call once per wasm instance.
//
// `stdlib_dir` is the directory holding the Python standard library (the
// `Lib/` tree: encodings/, io.py, codecs.py, ...). It becomes the sole
// module search path. The isolated config ignores PYTHONPATH, so the host
// MUST pass this (the dir is reached through the runtime's WASI filesystem
// mount). Pass NULL/empty to fall back to CPython's default path discovery
// (usually fails in the sandbox — provide the path).
func PyNew(stdlibDir string) (uint64, error) {
var buf []byte
buf = pbAppendString(buf, 1, stdlibDir)
resp, err := invokeMethod(0, 5, buf, wasm2go.Inv_0_5)
if err != nil {
return 0, err
}
return readScalarAtField(resp, 1, (*pbReader).readUint64), nil
}