-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathbuiltin.go
750 lines (646 loc) · 23.8 KB
/
builtin.go
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
// Copyright 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Built-in functions
package builtin
import (
"fmt"
"unicode/utf8"
"github.com/go-python/gpython/compile"
"github.com/go-python/gpython/py"
)
const builtin_doc = `Built-in functions, exceptions, and other objects.
Noteworthy: None is the 'nil' object; Ellipsis represents '...' in slices.`
// Initialise the module
func init() {
methods := []*py.Method{
py.MustNewMethod("__build_class__", builtin___build_class__, 0, build_class_doc),
py.MustNewMethod("__import__", py.InternalMethodImport, 0, import_doc),
py.MustNewMethod("abs", builtin_abs, 0, abs_doc),
py.MustNewMethod("all", builtin_all, 0, all_doc),
py.MustNewMethod("any", builtin_any, 0, any_doc),
// py.MustNewMethod("ascii", builtin_ascii, 0, ascii_doc),
// py.MustNewMethod("bin", builtin_bin, 0, bin_doc),
// py.MustNewMethod("callable", builtin_callable, 0, callable_doc),
py.MustNewMethod("chr", builtin_chr, 0, chr_doc),
py.MustNewMethod("compile", builtin_compile, 0, compile_doc),
// py.MustNewMethod("delattr", builtin_delattr, 0, delattr_doc),
py.MustNewMethod("dir", builtin_dir, 0, dir_doc),
py.MustNewMethod("divmod", builtin_divmod, 0, divmod_doc),
py.MustNewMethod("eval", py.InternalMethodEval, 0, eval_doc),
py.MustNewMethod("exec", py.InternalMethodExec, 0, exec_doc),
// py.MustNewMethod("format", builtin_format, 0, format_doc),
py.MustNewMethod("getattr", builtin_getattr, 0, getattr_doc),
py.MustNewMethod("globals", py.InternalMethodGlobals, 0, globals_doc),
py.MustNewMethod("hasattr", builtin_hasattr, 0, hasattr_doc),
// py.MustNewMethod("hash", builtin_hash, 0, hash_doc),
// py.MustNewMethod("hex", builtin_hex, 0, hex_doc),
// py.MustNewMethod("id", builtin_id, 0, id_doc),
// py.MustNewMethod("input", builtin_input, 0, input_doc),
// py.MustNewMethod("isinstance", builtin_isinstance, 0, isinstance_doc),
// py.MustNewMethod("issubclass", builtin_issubclass, 0, issubclass_doc),
// py.MustNewMethod("iter", builtin_iter, 0, iter_doc),
py.MustNewMethod("len", builtin_len, 0, len_doc),
py.MustNewMethod("locals", py.InternalMethodLocals, 0, locals_doc),
// py.MustNewMethod("max", builtin_max, 0, max_doc),
// py.MustNewMethod("min", builtin_min, 0, min_doc),
py.MustNewMethod("next", builtin_next, 0, next_doc),
// py.MustNewMethod("oct", builtin_oct, 0, oct_doc),
py.MustNewMethod("ord", builtin_ord, 0, ord_doc),
py.MustNewMethod("pow", builtin_pow, 0, pow_doc),
py.MustNewMethod("print", builtin_print, 0, print_doc),
py.MustNewMethod("repr", builtin_repr, 0, repr_doc),
py.MustNewMethod("round", builtin_round, 0, round_doc),
py.MustNewMethod("setattr", builtin_setattr, 0, setattr_doc),
// py.MustNewMethod("sorted", builtin_sorted, 0, sorted_doc),
// py.MustNewMethod("sum", builtin_sum, 0, sum_doc),
// py.MustNewMethod("vars", builtin_vars, 0, vars_doc),
}
globals := py.StringDict{
"None": py.None,
"Ellipsis": py.Ellipsis,
"False": py.False,
"True": py.True,
"bool": py.BoolType,
// "memoryview": py.MemoryViewType,
// "bytearray": py.ByteArrayType,
"bytes": py.BytesType,
"classmethod": py.ClassMethodType,
"complex": py.ComplexType,
"dict": py.StringDictType, // FIXME
// "enumerate": py.EnumType,
// "filter": py.FilterType,
"float": py.FloatType,
"frozenset": py.FrozenSetType,
// "property": py.PropertyType,
"int": py.IntType, // FIXME LongType?
"list": py.ListType,
// "map": py.MapType,
"object": py.ObjectType,
"range": py.RangeType,
// "reversed": py.ReversedType,
"set": py.SetType,
// "slice": py.SliceType,
"staticmethod": py.StaticMethodType,
"str": py.StringType,
// "super": py.SuperType,
"tuple": py.TupleType,
"type": py.TypeType,
// "zip": py.ZipType,
// Exceptions
"ArithmeticError": py.ArithmeticError,
"AssertionError": py.AssertionError,
"AttributeError": py.AttributeError,
"BaseException": py.BaseException,
"BlockingIOError": py.BlockingIOError,
"BrokenPipeError": py.BrokenPipeError,
"BufferError": py.BufferError,
"BytesWarning": py.BytesWarning,
"ChildProcessError": py.ChildProcessError,
"ConnectionAbortedError": py.ConnectionAbortedError,
"ConnectionError": py.ConnectionError,
"ConnectionRefusedError": py.ConnectionRefusedError,
"ConnectionResetError": py.ConnectionResetError,
"DeprecationWarning": py.DeprecationWarning,
"EOFError": py.EOFError,
"EnvironmentError": py.OSError,
"Exception": py.ExceptionType,
"FileExistsError": py.FileExistsError,
"FileNotFoundError": py.FileNotFoundError,
"FloatingPointError": py.FloatingPointError,
"FutureWarning": py.FutureWarning,
"GeneratorExit": py.GeneratorExit,
"IOError": py.OSError,
"ImportError": py.ImportError,
"ImportWarning": py.ImportWarning,
"IndentationError": py.IndentationError,
"IndexError": py.IndexError,
"InterruptedError": py.InterruptedError,
"IsADirectoryError": py.IsADirectoryError,
"KeyError": py.KeyError,
"KeyboardInterrupt": py.KeyboardInterrupt,
"LookupError": py.LookupError,
"MemoryError": py.MemoryError,
"NameError": py.NameError,
"NotADirectoryError": py.NotADirectoryError,
"NotImplemented": py.NotImplemented,
"NotImplementedError": py.NotImplementedError,
"OSError": py.OSError,
"OverflowError": py.OverflowError,
"PendingDeprecationWarning": py.PendingDeprecationWarning,
"PermissionError": py.PermissionError,
"ProcessLookupError": py.ProcessLookupError,
"ReferenceError": py.ReferenceError,
"ResourceWarning": py.ResourceWarning,
"RuntimeError": py.RuntimeError,
"RuntimeWarning": py.RuntimeWarning,
"StopIteration": py.StopIteration,
"SyntaxError": py.SyntaxError,
"SyntaxWarning": py.SyntaxWarning,
"SystemError": py.SystemError,
"SystemExit": py.SystemExit,
"TabError": py.TabError,
"TimeoutError": py.TimeoutError,
"TypeError": py.TypeError,
"UnboundLocalError": py.UnboundLocalError,
"UnicodeDecodeError": py.UnicodeDecodeError,
"UnicodeEncodeError": py.UnicodeEncodeError,
"UnicodeError": py.UnicodeError,
"UnicodeTranslateError": py.UnicodeTranslateError,
"UnicodeWarning": py.UnicodeWarning,
"UserWarning": py.UserWarning,
"ValueError": py.ValueError,
"Warning": py.Warning,
"ZeroDivisionError": py.ZeroDivisionError,
}
py.NewModule("builtins", builtin_doc, methods, globals)
}
const print_doc = `print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.`
func builtin_print(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Object, error) {
var (
sepObj py.Object = py.String(" ")
endObj py.Object = py.String("\n")
file py.Object
flush py.Object
)
kwlist := []string{"sep", "end", "file", "flush"}
err := py.ParseTupleAndKeywords(nil, kwargs, "|ssOO:print", kwlist, &sepObj, &endObj, &file, &flush)
if err != nil {
return nil, err
}
sep := sepObj.(py.String)
end := endObj.(py.String)
// FIXME ignoring file and flush
for i, v := range args {
fmt.Printf("%v", v)
if i != len(args)-1 {
fmt.Print(sep)
}
}
fmt.Print(end)
return py.None, nil
}
const repr_doc = `repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.`
func builtin_repr(self py.Object, obj py.Object) (py.Object, error) {
return py.Repr(obj)
}
const pow_doc = `pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for ints).`
func builtin_pow(self py.Object, args py.Tuple) (py.Object, error) {
var v, w, z py.Object
z = py.None
err := py.UnpackTuple(args, nil, "pow", 2, 3, &v, &w, &z)
if err != nil {
return nil, err
}
return py.Pow(v, w, z)
}
const abs_doc = `"abs(number) -> number
Return the absolute value of the argument.`
func builtin_abs(self, v py.Object) (py.Object, error) {
return py.Abs(v)
}
const all_doc = `all(iterable) -> bool
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
`
func builtin_all(self, seq py.Object) (py.Object, error) {
iter, err := py.Iter(seq)
res := false
if err != nil {
return nil, err
}
for {
item, err := py.Next(iter)
if err != nil {
if py.IsException(py.StopIteration, err) {
break
}
return nil, err
}
if py.ObjectIsTrue(item) {
res = true
} else {
res = false
break
}
}
return py.NewBool(res), nil
}
const any_doc = `any(iterable) -> bool
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, Py_RETURN_FALSE."`
func builtin_any(self, seq py.Object) (py.Object, error) {
iter, err := py.Iter(seq)
res := false
if err != nil {
return nil, err
}
for {
item, err := py.Next(iter)
if err != nil {
if py.IsException(py.StopIteration, err) {
break
}
return nil, err
}
if py.ObjectIsTrue(item) {
res = true
break
}
}
return py.NewBool(res), nil
}
const round_doc = `round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.`
func builtin_round(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Object, error) {
var number, ndigits py.Object
ndigits = py.Int(0)
// var kwlist = []string{"number", "ndigits"}
// FIXME py.ParseTupleAndKeywords(args, kwargs, "O|O:round", kwlist, &number, &ndigits)
err := py.UnpackTuple(args, nil, "round", 1, 2, &number, &ndigits)
if err != nil {
return nil, err
}
numberRounder, ok := number.(py.I__round__)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "type %s doesn't define __round__ method", number.Type().Name)
}
return numberRounder.M__round__(ndigits)
}
const build_class_doc = `__build_class__(func, name, *bases, metaclass=None, **kwds) -> class
Internal helper function used by the class statement.`
func builtin___build_class__(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Object, error) {
// fmt.Printf("__build_class__(self=%#v, args=%#v, kwargs=%#v\n", self, args, kwargs)
var prep, cell, cls py.Object
var mkw, ns py.StringDict
var meta, winner *py.Type
var isclass bool
var err error
if len(args) < 2 {
return nil, py.ExceptionNewf(py.TypeError, "__build_class__: not enough arguments")
}
// Better be callable
fn, ok := args[0].(*py.Function)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "__build__class__: func must be a function")
}
name := args[1].(py.String)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "__build_class__: name is not a string")
}
bases := args[2:]
if kwargs != nil {
mkw = kwargs.Copy() // Don't modify kwds passed in!
meta := mkw["metaclass"] // _PyDict_GetItemId(mkw, &PyId_metaclass)
if meta != nil {
delete(mkw, "metaclass")
// metaclass is explicitly given, check if it's indeed a class
_, isclass = meta.(*py.Type)
}
}
if meta == nil {
// if there are no bases, use type:
if len(bases) == 0 {
meta = py.TypeType
} else {
// else get the type of the first base
meta = bases[0].Type()
}
isclass = true // meta is really a class
}
if isclass {
// meta is really a class, so check for a more derived
// metaclass, or possible metaclass conflicts:
winner, err = meta.CalculateMetaclass(bases)
if err != nil {
return nil, err
}
if winner != meta {
meta = winner
}
}
// else: meta is not a class, so we cannot do the metaclass
// calculation, so we will use the explicitly given object as it is
prep = meta.Type().Dict["___prepare__"] // FIXME should be using _PyObject_GetAttr
if prep == nil {
ns = py.NewStringDict()
} else {
nsObj, err := py.Call(prep, py.Tuple{name, bases}, mkw)
if err != nil {
return nil, err
}
ns = nsObj.(py.StringDict)
}
// fmt.Printf("Calling %v with %v and %v\n", fn.Name, fn.Globals, ns)
// fmt.Printf("Code = %#v\n", fn.Code)
cell, err = py.VmRun(fn.Globals, ns, fn.Code, fn.Closure)
if err != nil {
return nil, err
}
// fmt.Printf("result = %#v err = %s\n", cell, err)
// fmt.Printf("locals = %#v\n", locals)
// fmt.Printf("ns = %#v\n", ns)
if cell != nil {
// fmt.Printf("Calling %v\n", meta)
cls, err = py.Call(meta, py.Tuple{name, bases, ns}, mkw)
if err != nil {
return nil, err
}
if c, ok := cell.(*py.Cell); ok {
c.Set(cls)
}
}
// fmt.Printf("Globals = %v, Locals = %v\n", fn.Globals, ns)
return cls, nil
}
const next_doc = `next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.`
func builtin_next(self py.Object, args py.Tuple) (res py.Object, err error) {
var it, def py.Object
err = py.UnpackTuple(args, nil, "next", 1, 2, &it, &def)
if err != nil {
return nil, err
}
res, err = py.Next(it)
if err != nil && def != nil && py.IsException(py.StopIteration, err) {
// Return defult on StopIteration
res = def
err = nil
}
return res, err
}
const import_doc = `__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
Import a module. Because this function is meant for use by the Python
interpreter and not for general use it is better to use
importlib.import_module() to programmatically import a module.
The globals argument is only used to determine the context;
they are not modified. The locals argument is unused. The fromlist
should be a list of names to emulate ''from name import ...'', or an
empty list to emulate ''import name''.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty. Level is used to determine whether to perform
absolute or relative imports. 0 is absolute while a positive number
is the number of parent directories to search relative to the current module.`
const ord_doc = `ord(c) -> integer
Return the integer ordinal of a one-character string.`
func builtin_ord(self, obj py.Object) (py.Object, error) {
var size int
switch x := obj.(type) {
case py.Bytes:
size = len(x)
if size == 1 {
return py.Int(x[0]), nil
}
case py.String:
size = len(x)
rune, runeSize := utf8.DecodeRuneInString(string(x))
if size == runeSize && rune != utf8.RuneError {
return py.Int(rune), nil
}
//case py.ByteArray:
// XXX Hopefully this is temporary
// FIXME implement
// size = PyByteArray_GET_SIZE(obj)
// if size == 1 {
// ord = (long)((char) * PyByteArray_AS_STRING(obj))
// return PyLong_FromLong(ord)
// }
default:
return nil, py.ExceptionNewf(py.TypeError, "ord() expected string of length 1, but %s found", obj.Type().Name)
}
return nil, py.ExceptionNewf(py.TypeError, "ord() expected a character, but string of length %d found", size)
}
const getattr_doc = `getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.`
func builtin_getattr(self py.Object, args py.Tuple) (py.Object, error) {
var v, result, dflt py.Object
var name py.Object
err := py.UnpackTuple(args, nil, "getattr", 2, 3, &v, &name, &dflt)
if err != nil {
return nil, err
}
result, err = py.GetAttr(v, name)
if err != nil {
if dflt == nil {
return nil, err
}
result = dflt
}
return result, nil
}
const hasattr_doc = `hasattr(object, name) -> bool
Return whether the object has an attribute with the given name.
(This is done by calling getattr(object, name) and catching AttributeError.)`
func builtin_hasattr(self py.Object, args py.Tuple) (py.Object, error) {
var v py.Object
var name py.Object
err := py.UnpackTuple(args, nil, "hasattr", 2, 2, &v, &name)
if err != nil {
return nil, err
}
_, err = py.GetAttr(v, name)
return py.NewBool(err == nil), nil
}
const setattr_doc = `setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
"x.y = v".`
func builtin_setattr(self py.Object, args py.Tuple) (py.Object, error) {
var v py.Object
var name py.Object
var value py.Object
err := py.UnpackTuple(args, nil, "setattr", 3, 3, &v, &name, &value)
if err != nil {
return nil, err
}
return py.SetAttr(v, name, value)
}
// Reads the source as a string
func source_as_string(cmd py.Object, funcname, what string /*, PyCompilerFlags *cf */) (string, error) {
// FIXME only understands strings, not bytes etc at the moment
if str, ok := cmd.(py.String); ok {
// FIXME cf->cf_flags |= PyCF_IGNORE_COOKIE;
return string(str), nil
}
// } else if (!PyObject_CheckReadBuffer(cmd)) {
return "", py.ExceptionNewf(py.TypeError, "%s() arg 1 must be a %s object", funcname, what)
// } else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
// return nil;
}
const compile_doc = `compile(source, filename, mode[, flags[, dont_inherit]]) -> code object
Compile the source string (a Python module, statement or expression)
into a code object that can be executed by exec() or eval().
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if non-zero, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or zero these statements do influence the compilation,
in addition to any features explicitly specified.`
func builtin_compile(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Object, error) {
// FIXME lots of unsupported stuff here!
var filename py.Object
var startstr py.Object
// var mode = -1
var dont_inherit py.Object = py.Int(0)
var supplied_flags py.Object = py.Int(0)
var optimizeInt py.Object = py.Int(-1)
//is_ast := false
// var cf PyCompilerFlags
var cmd py.Object
kwlist := []string{"source", "filename", "mode", "flags", "dont_inherit", "optimize"}
// start := []int{Py_file_input, Py_eval_input, Py_single_input}
var result py.Object
err := py.ParseTupleAndKeywords(args, kwargs, "Oss|iii:compile", kwlist,
&cmd,
&filename,
&startstr,
&supplied_flags,
&dont_inherit,
&optimizeInt)
if err != nil {
return nil, err
}
// cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8
// if supplied_flags&^(PyCF_MASK|PyCF_MASK_OBSOLETE|PyCF_DONT_IMPLY_DEDENT|PyCF_ONLY_AST) != 0 {
// return nil, py.ExceptionNewf(py.ValueError, "compile(): unrecognised flags")
// }
// XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0?
optimize := int(optimizeInt.(py.Int))
if optimize < -1 || optimize > 2 {
return nil, py.ExceptionNewf(py.ValueError, "compile(): invalid optimize value")
}
if dont_inherit.(py.Int) != 0 {
// PyEval_MergeCompilerFlags(&cf)
}
// switch string(startstr.(py.String)) {
// case "exec":
// mode = 0
// case "eval":
// mode = 1
// case "single":
// mode = 2
// default:
// return nil, py.ExceptionNewf(py.ValueError, "compile() arg 3 must be 'exec', 'eval' or 'single'")
// }
// is_ast = PyAST_Check(cmd)
// if is_ast {
// if supplied_flags & PyCF_ONLY_AST {
// result = cmd
// } else {
// arena := PyArena_New()
// mod := PyAST_obj2mod(cmd, arena, mode)
// PyAST_Validate(mod)
// result = PyAST_CompileObject(mod, filename, &cf, optimize, arena)
// PyArena_Free(arena)
// }
// } else {
str, err := source_as_string(cmd, "compile", "string, bytes or AST" /*, &cf*/)
if err != nil {
return nil, err
}
// result = py.CompileStringExFlags(str, filename, start[mode], &cf, optimize)
result, err = compile.Compile(str, string(filename.(py.String)), string(startstr.(py.String)), int(supplied_flags.(py.Int)), dont_inherit.(py.Int) != 0)
if err != nil {
return nil, err
}
// }
return result, nil
}
const dir_doc = `dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
`
func builtin_dir(self py.Object, args py.Tuple) (py.Object, error) {
n, err := args.M__len__()
if err != nil {
return nil, err
}
nn := n.(py.Int)
if nn == 0 {
// list current scope.
panic("dir() not implemented")
}
if nn > 1 {
return nil, py.ExceptionNewf(py.TypeError, "dir expected at most 1 arguments, got %d", nn)
}
panic("dir(n) not implemented")
}
const divmod_doc = `divmod(x, y) -> (quotient, remainder)
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.`
func builtin_divmod(self py.Object, args py.Tuple) (py.Object, error) {
var x, y py.Object
err := py.UnpackTuple(args, nil, "divmod", 2, 2, &x, &y)
if err != nil {
return nil, err
}
q, r, err := py.DivMod(x, y)
if err != nil {
return nil, err
}
return py.Tuple{q, r}, nil
}
const eval_doc = `"eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.`
// For code see vm/builtin.go
const exec_doc = `exec(object[, globals[, locals]])
Read and execute code from an object, which can be a string or a code
object.
The globals and locals are dictionaries, defaulting to the current
globals and locals. If only globals is given, locals defaults to it.`
// For code see vm/builtin.go
const len_doc = `len(object) -> integer
Return the number of items of a sequence or mapping.`
func builtin_len(self, v py.Object) (py.Object, error) {
return py.Len(v)
}
const chr_doc = `chr(i) -> Unicode character
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.`
func builtin_chr(self py.Object, args py.Tuple) (py.Object, error) {
var xObj py.Object
err := py.ParseTuple(args, "i:chr", &xObj)
if err != nil {
return nil, err
}
x := xObj.(py.Int)
if x < 0 || x >= 0x110000 {
return nil, py.ExceptionNewf(py.ValueError, "chr() arg not in range(0x110000)")
}
buf := make([]byte, 8)
n := utf8.EncodeRune(buf, rune(x))
return py.String(buf[:n]), nil
}
const locals_doc = `locals() -> dictionary
Update and return a dictionary containing the current scope's local variables.`
const globals_doc = `globals() -> dictionary
Return the dictionary containing the current scope's global variables.`