-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathBuiltinsModule.cpp
More file actions
1640 lines (1424 loc) · 52.4 KB
/
Copy pathBuiltinsModule.cpp
File metadata and controls
1640 lines (1424 loc) · 52.4 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
#include "Modules.hpp"
#include "runtime/AssertionError.hpp"
#include "runtime/AttributeError.hpp"
#include "runtime/Import.hpp"
#include "runtime/ImportError.hpp"
#include "runtime/IndexError.hpp"
#include "runtime/KeyError.hpp"
#include "runtime/LookupError.hpp"
#include "runtime/ModuleNotFoundError.hpp"
#include "runtime/NameError.hpp"
#include "runtime/NotImplementedError.hpp"
#include "runtime/OSError.hpp"
#include "runtime/PyArgParser.hpp"
#include "runtime/PyBool.hpp"
#include "runtime/PyBytes.hpp"
#include "runtime/PyCell.hpp"
#include "runtime/PyCode.hpp"
#include "runtime/PyDict.hpp"
#include "runtime/PyFrame.hpp"
#include "runtime/PyFunction.hpp"
#include "runtime/PyInteger.hpp"
#include "runtime/PyList.hpp"
#include "runtime/PyModule.hpp"
#include "runtime/PyNone.hpp"
#include "runtime/PyNumber.hpp"
#include "runtime/PyObject.hpp"
#include "runtime/PyRange.hpp"
#include "runtime/PyStaticMethod.hpp"
#include "runtime/PyString.hpp"
#include "runtime/PyTuple.hpp"
#include "runtime/PyType.hpp"
#include "runtime/RuntimeError.hpp"
#include "runtime/StopIteration.hpp"
#include "runtime/SyntaxError.hpp"
#include "runtime/TypeError.hpp"
#include "runtime/UnboundLocalError.hpp"
#include "runtime/Value.hpp"
#include "runtime/ValueError.hpp"
#include "runtime/modules/Modules.hpp"
#include "runtime/types/builtin.hpp"
#include "runtime/warnings/ImportWarning.hpp"
#include "runtime/warnings/Warning.hpp"
#include "executable/Mangler.hpp"
#include "executable/Program.hpp"
#include "executable/bytecode/Bytecode.hpp"
#include "executable/bytecode/codegen/BytecodeGenerator.hpp"
#include "executable/bytecode/instructions/FunctionCall.hpp"
#include "interpreter/Interpreter.hpp"
#include "lexer/Lexer.hpp"
#include "memory/GarbageCollector.hpp"
#include "parser/Parser.hpp"
#include "vm/VM.hpp"
#include "utilities.hpp"
#include <algorithm>
#include <variant>
using namespace py;
static PyModule *s_builtin_module = nullptr;
namespace {
PyResult<PyObject *> print(const PyTuple *args, const PyDict *kwargs, Interpreter &interpreter)
{
auto *separator = PyString::create(" ").unwrap();
auto *end = PyString::create("\n").unwrap();
// TODO: handle error case?
PyObject *file =
PyObject::from(interpreter.get_imported_module(PyString::create("sys").unwrap())
->symbol_table()
->map()
.at(String{ "stdout" }))
.unwrap();
// sys.stdout may be None when FILE* stdout isn't connected
if (!file || file == py_none()) { return Ok(py_none()); }
// TODO: flush should be false, but for now we keep it as true, since there is no flush at
// interpreter shutdown
bool flush = true;
if (kwargs) {
static const Value separator_keyword = String{ "sep" };
static const Value end_keyword = String{ "end" };
static const Value file_keyword = String{ "file" };
static const Value flush_keyword = String{ "flush" };
if (auto it = kwargs->map().find(separator_keyword); it != kwargs->map().end()) {
auto maybe_str = it->second;
if (!std::holds_alternative<String>(maybe_str)) {
auto obj =
std::visit([](const auto &value) { return PyObject::from(value); }, maybe_str);
if (obj.is_err()) return obj;
return Err(type_error(
"sep must be None or a string, not {}", obj.unwrap()->type()->name()));
}
separator = PyString::create(std::get<String>(maybe_str).s).unwrap();
}
if (auto it = kwargs->map().find(end_keyword); it != kwargs->map().end()) {
auto maybe_str = it->second;
if (!std::holds_alternative<String>(maybe_str)) {
auto obj =
std::visit([](const auto &value) { return PyObject::from(value); }, maybe_str);
if (obj.is_err()) return obj;
return Err(type_error(
"end must be None or a string, not {}", obj.unwrap()->type()->name()));
}
end = PyString::create(std::get<String>(maybe_str).s).unwrap();
}
if (auto it = kwargs->map().find(file_keyword); it != kwargs->map().end()) {
auto file_ = PyObject::from(it->second);
if (file_.is_err()) { return file_; }
file = file_.unwrap();
}
if (auto it = kwargs->map().find(flush_keyword); it != kwargs->map().end()) {
auto flush_ = PyObject::from(it->second);
if (flush_.is_err()) { return flush_; }
const auto truthy = flush_.unwrap()->true_();
if (truthy.is_err()) { return Err(truthy.unwrap_err()); }
flush = truthy.unwrap();
}
}
auto file_write_ = file->get_method(PyString::create("write").unwrap());
if (file_write_.is_err()) { return file_write_; }
auto file_write = file_write_.unwrap();
auto strfunc = [](const PyResult<PyObject *> &arg) -> PyResult<PyString *> {
if (arg.is_err()) return Err(arg.unwrap_err());
return arg.unwrap()->str();
};
auto arg_it = args->begin();
auto arg_it_end = args->end();
if (arg_it == arg_it_end) {
if (auto result =
file_write->call(PyTuple::create(PyString::create(end).unwrap()).unwrap(), nullptr);
result.is_err()) {
return result;
}
if (flush) {
auto file_flush_ = file->get_method(PyString::create("flush").unwrap());
if (file_flush_.is_err()) { return file_flush_; }
return file_flush_.unwrap()->call(nullptr, nullptr);
}
return Ok(py_none());
}
--arg_it_end;
while (arg_it != arg_it_end) {
spdlog::debug("arg function ptr: {}", static_cast<void *>((*arg_it).unwrap()));
auto reprobj_ = strfunc(*arg_it);
if (reprobj_.is_err()) { return reprobj_; }
auto reprobj = reprobj_.unwrap();
spdlog::debug("repr result: {}", reprobj->value());
if (auto result = file_write->call(PyTuple::create(reprobj).unwrap(), nullptr);
result.is_err()) {
return result;
}
if (auto result = file_write->call(PyTuple::create(separator).unwrap(), nullptr);
result.is_err()) {
return result;
}
std::advance(arg_it, 1);
}
spdlog::debug("arg function ptr: {}", static_cast<void *>((*arg_it).unwrap()));
auto reprobj_ = strfunc(*arg_it);
if (reprobj_.is_err()) { return reprobj_; }
auto reprobj = reprobj_.unwrap();
spdlog::debug("repr result: {}", reprobj->value());
if (auto result = file_write->call(PyTuple::create(reprobj).unwrap(), nullptr);
result.is_err()) {
return result;
}
if (auto result =
file_write->call(PyTuple::create(PyString::create(end).unwrap()).unwrap(), nullptr);
result.is_err()) {
return result;
}
if (flush) {
auto file_flush_ = file->get_method(PyString::create("flush").unwrap());
if (file_flush_.is_err()) { return file_flush_; }
return file_flush_.unwrap()->call(nullptr, nullptr);
}
return Ok(py_none());
}
PyResult<PyObject *> iter(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"iter",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
return std::get<0>(result.unwrap())->iter();
}
PyResult<PyObject *> hash(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"hash",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
return std::get<0>(result.unwrap())->hash().and_then([](const size_t h) {
return PyInteger::create(h);
});
}
PyResult<PyObject *> next(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"next",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
return std::get<0>(result.unwrap())->next();
}
PyResult<PyObject *>
build_class(const PyTuple *args, const PyDict *kwargs, Interpreter &interpreter)
{
if (args->size() < 2) {
return Err(type_error("__build_class__: not enough arguments, got {}", args->size()));
}
bool metaclass_is_class = false;
auto metaclass_ = [kwargs, &metaclass_is_class]() -> PyResult<PyObject *> {
if (kwargs && kwargs->map().size() > 0) {
auto it = kwargs->map().find(String{ "metaclass" });
if (it != kwargs->map().end()) {
return PyObject::from(it->second).and_then([&metaclass_is_class](PyObject *obj) {
if (obj->type()->issubclass(py::types::type())) { metaclass_is_class = true; }
return Ok(obj);
});
}
}
return Ok(py_none());
}();
if (metaclass_.is_err()) return metaclass_;
auto *metaclass = metaclass_.unwrap();
auto maybe_function_location_ = args->operator[](0);
if (maybe_function_location_.is_err()) return maybe_function_location_;
auto *maybe_function_location = maybe_function_location_.unwrap();
auto mangled_class_name_ = args->operator[](1);
if (mangled_class_name_.is_err()) return mangled_class_name_;
auto *mangled_class_name = mangled_class_name_.unwrap();
spdlog::debug("__build_class__({}, {})",
mangled_class_name->to_string(),
maybe_function_location->to_string());
if (!as<PyString>(mangled_class_name)) {
return Err(type_error("__build_class__: name is not a string"));
}
const auto mangled_class_name_as_string = as<PyString>(mangled_class_name)->value();
PyResult<PyFunction *> callable = [&]() -> PyResult<PyFunction *> {
// TODO: Remove as<PyInteger>(maybe_function_location) branch. This is deprecated
if (as<PyInteger>(maybe_function_location)) {
// auto function_id = std::get<int64_t>(pynumber->value().value);
// FIXME: what should be the global dictionary for this?
// FIXME: what should be the module for this?
auto *f = interpreter.execution_frame()->code()->make_function(
mangled_class_name_as_string, {}, {}, {});
ASSERT(as<PyFunction>(f));
return Ok(as<PyFunction>(f));
} else if (auto *pyfunc = as<PyFunction>(maybe_function_location)) {
return Ok(pyfunc);
} else {
return Err(type_error("__build_class__: func must be callable"));
}
}();
if (callable.is_err()) { TODO(); }
const std::string class_name_str =
Mangler::default_mangler().class_demangle(mangled_class_name_as_string);
auto class_name_ = PyString::create(class_name_str);
if (class_name_.is_err()) { return Err(class_name_.unwrap_err()); }
auto *class_name = class_name_.unwrap();
std::vector<Value> bases_vector;
if (args->size() > 2) {
bases_vector.reserve(args->size() - 2);
auto it = args->elements().begin() + 2;
while (it != args->elements().end()) {
bases_vector.push_back(*it);
it++;
}
}
auto bases_ = PyTuple::create(bases_vector);
if (bases_.is_err()) { return Err(bases_.unwrap_err()); }
auto *bases = bases_.unwrap();
// finalize this class' metaclass
if (metaclass == py_none()) {
if (bases->size() == 0) {
// if there are no bases, use `type`
metaclass = py::types::type();
} else {
// else get the type of the first base
metaclass = PyObject::from(bases->elements()[0]).unwrap()->type();
}
metaclass_is_class = true;
}
if (metaclass_is_class) {
std::vector<PyType *> bases_vector;
for (const auto &base : bases->elements()) {
auto base_ = PyObject::from(base);
if (base_.is_err()) { return base_; }
if (auto *b = as<PyType>(base_.unwrap())) {
bases_vector.push_back(b);
} else {
return Err(type_error("bases must be types"));
}
}
auto winner = PyType::calculate_metaclass(static_cast<PyType *>(metaclass), bases_vector);
if (winner.is_err()) { return Err(winner.unwrap_err()); }
metaclass = const_cast<PyType *>(winner.unwrap());
}
// lookup __prepare__ and instantiate namespace
auto ns_ = [metaclass, class_name, bases, kwargs]() -> PyResult<PyObject *> {
if (metaclass == types::type()) {
return PyDict::create();
} else {
auto prepare = PyString::create("__prepare__");
if (prepare.is_err()) { return prepare; }
auto new_kwargs_ = [kwargs]() {
if (kwargs && !kwargs->map().empty()) {
auto prepare_kwargs = kwargs->map();
prepare_kwargs.erase(String{ "metaclass" });
return PyDict::create(prepare_kwargs);
} else {
return PyDict::create();
}
}();
if (new_kwargs_.is_err()) { return new_kwargs_; }
auto *new_kwargs = new_kwargs_.unwrap();
auto result = metaclass->lookup_attribute(prepare.unwrap());
if (std::get<0>(result).is_ok() && std::get<1>(result) == LookupAttrResult::FOUND) {
return std::get<0>(result).and_then(
[class_name, bases, new_kwargs](PyObject *prepare) {
auto args = PyTuple::create(class_name, bases);
return prepare->call(args.unwrap(), new_kwargs);
});
} else {
return PyDict::create();
}
}
}();
if (ns_.is_err()) { return Err(ns_.unwrap_err()); }
auto *ns = ns_.unwrap();
// this calls a function that defines a class
// For example:
// class A:
// def foo(self):
// pass
//
// becomes something like this (in bytecode):
// 1 0 LOAD_NAME 0 (__name__)
// 2 STORE_NAME 1 (__module__)
// 4 LOAD_CONST 0 ('A')
// 6 STORE_NAME 2 (__qualname__)
//
// 2 8 LOAD_CONST 1 (<code object foo at 0x5557f27c0390, file
// "example.py", line 2>)
// 10 LOAD_CONST 2 ('A.foo')
// 12 MAKE_FUNCTION 0
// 14 STORE_NAME 3 (foo)
// 16 LOAD_CONST 3 (None)
// 18 RETURN_VALUE
// and calling these instructions creates the class' methods and attributes (i.e. foo)
// call with frame keeps a reference to locals in a ns
// so we have a reference to all class attributes and methods
// i.e. {__module__: __name__, __qualname__: 'A', foo: <function A.foo>}
auto args_ = PyTuple::create();
if (args_.is_err()) { return args_; }
auto *empty_args = args_.unwrap();
auto kwargs_ = PyDict::create();
if (kwargs_.is_err()) { return kwargs_; }
auto *empty_kwargs = kwargs_.unwrap();
auto classcell = callable.unwrap()->call_with_frame(ns, empty_args, empty_kwargs);
if (classcell.is_err()) { return classcell; }
auto call_args = PyTuple::create(class_name, bases, ns);
if (call_args.is_err()) { return Err(call_args.unwrap_err()); }
auto cls = metaclass->call(call_args.unwrap(), nullptr);
// FIXME: according to CPython this is *not* how you do it, but RustPython does it this way
// what are the implications? Find out how CPython sets __classcell__.
return cls.and_then([&classcell](PyObject *cls) {
if (as<PyCell>(classcell.unwrap())) { as<PyCell>(classcell.unwrap())->set_cell(cls); }
return Ok(cls);
});
}
PyResult<PyObject *> globals(const PyTuple *, const PyDict *, Interpreter &interpreter)
{
return Ok(interpreter.execution_frame()->globals());
}
PyResult<PyObject *> locals(const PyTuple *, const PyDict *, Interpreter &interpreter)
{
return Ok(interpreter.execution_frame()->locals());
}
PyResult<PyObject *> len(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"len",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
auto *o = std::get<0>(result.unwrap());
auto mapping = o->as_mapping();
if (mapping.is_err()) { return Err(mapping.unwrap_err()); }
if (auto r = mapping.unwrap().len(); r.is_ok()) {
return PyInteger::create(r.unwrap());
} else {
return Err(r.unwrap_err());
}
}
PyResult<PyObject *> id(const PyTuple *args, const PyDict *, Interpreter &)
{
ASSERT(args->size() == 1);
auto obj = args->operator[](0);
if (obj.is_err()) return obj;
return PyInteger::create(bit_cast<intptr_t>(obj.unwrap()));
}
PyResult<PyObject *> import(const PyTuple *args, const PyDict *, Interpreter &)
{
// TODO: support globals, locals, fromlist and level
ASSERT(args->size() > 0);
auto arg0 = args->operator[](0);
if (arg0.is_err()) return arg0;
auto *name = arg0.unwrap();
if (!as<PyString>(name)) {
return Err(
type_error("__import__(): name must be a string, not {}", name->type()->to_string()));
}
auto arg1 = [args]() -> PyResult<PyObject *> {
if (args->size() > 1) {
auto arg1 = args->operator[](1);
if (arg1.is_err()) return arg1;
auto *globals = arg1.unwrap();
if (!as<PyDict>(globals) && globals != py_none()) {
return Err(type_error("__import__(): globals must be a dict or None, not {}",
globals->type()->to_string()));
}
return Ok(globals);
} else {
return Ok(py_none());
}
}();
if (arg1.is_err()) return arg1;
auto *globals = arg1.unwrap();
auto arg2 = [args]() -> PyResult<PyObject *> {
if (args->size() > 2) {
auto arg2 = args->operator[](2);
if (arg2.is_err()) return arg2;
auto *locals = arg2.unwrap();
return Ok(locals);
} else {
return Ok(py_none());
}
}();
if (arg2.is_err()) return arg2;
auto *locals = arg2.unwrap();
auto arg3 = [args]() -> PyResult<PyObject *> {
if (args->size() > 3) {
auto arg3 = args->operator[](3);
if (arg3.is_err()) return arg3;
auto *fromlist = arg3.unwrap();
return Ok(fromlist);
} else {
return PyTuple::create();
}
}();
if (arg3.is_err()) return arg3;
auto *fromlist = arg3.unwrap();
auto arg4 = [args]() -> PyResult<PyObject *> {
if (args->size() > 1) {
auto arg4 = args->operator[](4);
if (arg4.is_err()) return arg4;
auto *level = arg4.unwrap();
if (!as<PyInteger>(level)) {
return Err(type_error(
"__import__(): level must be an int, not {}", level->type()->to_string()));
}
return Ok(level);
} else {
return PyInteger::create(0);
}
}();
if (arg4.is_err()) return arg4;
auto *level = arg4.unwrap();
return import_module_level_object(as<PyString>(name),
as<PyDict>(globals),
locals,
fromlist,
static_cast<uint32_t>(as<PyInteger>(level)->as_size_t()));
}
PyResult<PyObject *> hasattr(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *, PyObject *>::unpack_tuple(args,
kwargs,
"hasattr",
std::integral_constant<size_t, 2>{},
std::integral_constant<size_t, 2>{});
if (result.is_err()) return Err(result.unwrap_err());
auto [obj, name] = result.unwrap();
if (!as<PyString>(name)) { return Err(type_error("hasattr(): attribute name must be string")); }
auto [lookup_result, found_status] = obj->lookup_attribute(name);
if (found_status == LookupAttrResult::FOUND) {
return Ok(py_true());
} else if (found_status == LookupAttrResult::NOT_FOUND) {
return Ok(py_false());
} else {
return lookup_result;
}
}
PyResult<PyObject *> getattr(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *, PyObject *, PyObject *>::unpack_tuple(args,
kwargs,
"getattr",
std::integral_constant<size_t, 2>{},
std::integral_constant<size_t, 3>{},
nullptr /* default */);
if (result.is_err()) return Err(result.unwrap_err());
auto [obj, name, default_value] = result.unwrap();
if (!as<PyString>(name)) { return Err(type_error("getattr(): attribute name must be string")); }
if (!default_value) {
auto attr = obj->getattribute(name);
if (attr.is_ok()) { ASSERT(attr.unwrap()); }
return attr;
} else {
auto [attr_value, found_status] = obj->lookup_attribute(name);
if (attr_value.is_err()) { return attr_value; }
if (found_status == LookupAttrResult::FOUND) {
if (attr_value.is_ok()) { ASSERT(attr_value.unwrap()); }
return attr_value;
} else {
ASSERT(default_value);
return Ok(default_value);
}
}
}
PyResult<PyObject *> setattr(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *, PyObject *, PyObject *>::unpack_tuple(args,
kwargs,
"setattr",
std::integral_constant<size_t, 3>{},
std::integral_constant<size_t, 3>{});
if (result.is_err()) return Err(result.unwrap_err());
auto [obj, name, value] = result.unwrap();
if (!as<PyString>(name)) { return Err(type_error("setattr(): attribute name must be string")); }
if (auto set_result = obj->setattribute(name, value); set_result.is_ok()) {
return Ok(py_none());
} else {
return Err(set_result.unwrap_err());
}
}
PyResult<PyObject *> hex(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"hex",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
auto *obj = std::get<0>(result.unwrap());
if (auto pynumber = PyNumber::as_number(obj)) {
if (std::holds_alternative<BigIntType>(pynumber->value().value)) {
std::ostringstream os;
os << std::hex << std::ios::showbase << std::get<BigIntType>(pynumber->value().value);
return PyString::create(os.str());
} else {
// FIXME: when float is separated from integer fix this
return Err(type_error(
"'float' object cannot be interpreted as an integer", obj->type()->name()));
}
} else {
return Err(
type_error("'{}' object cannot be interpreted as an integer", obj->type()->name()));
}
}
PyResult<PyObject *> ord(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"ord",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
auto *obj = std::get<0>(result.unwrap());
if (auto pystr = as<PyString>(obj)) {
if (auto codepoint = pystr->codepoint()) {
return PyObject::from(Number{ static_cast<int64_t>(*codepoint) });
} else {
auto mapping = pystr->as_mapping();
if (mapping.is_err()) { return Err(mapping.unwrap_err()); }
auto size = mapping.unwrap().len();
if (size.is_err()) { return Err(size.unwrap_err()); }
return Err(type_error(
"ord() expected a character, but string of length {} found", size.unwrap()));
}
} else {
return Err(
type_error("ord() expected string of length 1, but {} found", obj->type()->name()));
}
}
PyResult<PyObject *> chr(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"chr",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
auto *obj = std::get<0>(result.unwrap());
if (auto cp = PyNumber::as_number(obj)) {
if (std::holds_alternative<double>(cp->value().value)) {
return Err(type_error("'float' object cannot be interpreted as an integer"));
}
return PyString::chr(std::get<BigIntType>(cp->value().value));
} else {
return Err(
type_error("'{}' object cannot be interpreted as an integer", obj->type()->name()));
}
}
PyResult<PyObject *> dir(const PyTuple *args, const PyDict *, Interpreter &interpreter)
{
ASSERT(args->size() < 2);
auto dir_list_ = PyList::create();
if (dir_list_.is_err()) return Err(dir_list_.unwrap_err());
auto *dir_list = dir_list_.unwrap();
if (args->size() == 0) {
ASSERT(as<PyDict>(interpreter.execution_frame()->locals()));
for (const auto &[k, _] : as<PyDict>(interpreter.execution_frame()->locals())->map()) {
auto obj_ = PyObject::from(k);
if (obj_.is_err()) return obj_;
dir_list->elements().push_back(obj_.unwrap());
}
} else {
const auto &arg = args->elements()[0];
// If the object is a module object, the list contains the names of the module’s attributes.
if (std::holds_alternative<PyObject *>(arg) && as<PyModule>(std::get<PyObject *>(arg))) {
auto *pymodule = as<PyModule>(std::get<PyObject *>(arg));
for (const auto &[k, _] : pymodule->symbol_table()->map()) {
dir_list->elements().push_back(k);
}
}
// If the object is a type or class object, the list contains the names of its attributes,
// and recursively of the attributes of its bases.
// Otherwise, the list contains the object’s attributes’ names, the names of its class’s
// attributes, and recursively of the attributes of its class’s base classes.
else {
auto object_ = PyObject::from(arg);
if (object_.is_err()) return object_;
auto *object = object_.unwrap();
for (const auto &[k, _] : object->attributes()->map()) {
dir_list->elements().push_back(k);
}
}
}
if (auto sort_result = dir_list->sort(nullptr, nullptr); sort_result.is_err()) {
return Err(sort_result.unwrap_err());
}
return Ok(static_cast<PyObject *>(dir_list_.unwrap()));
}
PyResult<PyObject *> repr(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"repr",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
return std::get<0>(result.unwrap())->repr();
}
PyResult<PyObject *> abs(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"abs",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
return std::get<0>(result.unwrap())->abs();
}
PyResult<PyObject *> max(const PyTuple *args, const PyDict *kwargs, Interpreter &interpreter)
{
if (!args || args->size() == 0) { return Err(type_error("")); }
if (kwargs && kwargs->size() > 0) { TODO(); }
if (args->size() == 1) {
auto iterable = PyObject::from(args->elements()[0]);
if (iterable.is_err()) return Err(iterable.unwrap_err());
auto iterator = iterable.unwrap()->iter();
if (iterator.is_err()) return Err(iterator.unwrap_err());
auto value = iterator.unwrap()->next();
if (value.is_err()) return value;
auto *max_value = value.unwrap();
while (value.is_ok()) {
auto cmp = value.unwrap()->richcompare(max_value, RichCompare::Py_GT);
if (cmp.is_err()) return cmp;
if (cmp.unwrap() == py_true()) { max_value = value.unwrap(); }
value = iterator.unwrap()->next();
}
if (value.unwrap_err()->type() != stop_iteration()->type()) {
return Err(value.unwrap_err());
}
return Ok(max_value);
} else {
std::optional<Value> max_value;
for (const auto &el : args->elements()) {
if (max_value.has_value()) {
auto cmp = greater_than(el, *max_value, interpreter);
if (cmp.is_err()) return Err(cmp.unwrap_err());
auto r = truthy(cmp.unwrap(), interpreter);
if (r.is_err()) return Err(r.unwrap_err());
if (r.unwrap()) { max_value = el; }
} else {
max_value = el;
}
}
ASSERT(max_value.has_value());
return PyObject::from(*max_value);
}
}
PyResult<PyObject *> min(const PyTuple *args, const PyDict *kwargs, Interpreter &interpreter)
{
if (!args || args->size() == 0) { return Err(type_error("")); }
if (kwargs && kwargs->size() > 0) { TODO(); }
if (args->size() == 1) {
auto iterable = PyObject::from(args->elements()[0]);
if (iterable.is_err()) return Err(iterable.unwrap_err());
auto iterator = iterable.unwrap()->iter();
if (iterator.is_err()) return Err(iterator.unwrap_err());
auto value = iterator.unwrap()->next();
if (value.is_err()) return value;
auto *min_value = value.unwrap();
while (value.is_ok()) {
auto cmp = value.unwrap()->richcompare(min_value, RichCompare::Py_LT);
if (cmp.is_err()) return cmp;
if (cmp.unwrap() == py_true()) { min_value = value.unwrap(); }
value = iterator.unwrap()->next();
}
if (value.unwrap_err()->type() != stop_iteration()->type()) {
return Err(value.unwrap_err());
}
return Ok(min_value);
} else {
std::optional<Value> min_value;
for (const auto &el : args->elements()) {
if (min_value.has_value()) {
auto cmp = less_than(el, *min_value, interpreter);
if (cmp.is_err()) return Err(cmp.unwrap_err());
auto r = truthy(cmp.unwrap(), interpreter);
if (r.is_err()) return Err(r.unwrap_err());
if (r.unwrap()) { min_value = el; }
} else {
min_value = el;
}
}
ASSERT(min_value.has_value());
return PyObject::from(*min_value);
}
}
PyResult<PyObject *> isinstance(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *, PyObject *>::unpack_tuple(args,
kwargs,
"isinstance",
std::integral_constant<size_t, 2>{},
std::integral_constant<size_t, 2>{});
if (result.is_err()) return Err(result.unwrap_err());
auto [object, classinfo] = result.unwrap();
std::vector<PyType *> types;
if (auto *class_info_tuple = as<PyTuple>(classinfo)) {
types.reserve(class_info_tuple->elements().size());
for (const auto &el : class_info_tuple->elements()) {
auto el_obj = PyObject::from(el);
if (el_obj.is_err()) return el_obj;
if (!as<PyType>(el_obj.unwrap())) {
return Err(type_error("isinstance() arg 2 must be a type or tuple of types"));
}
types.push_back(as<PyType>(el_obj.unwrap()));
}
} else if (auto *class_info_type = as<PyType>(classinfo)) {
types.push_back(class_info_type);
} else {
return Err(type_error("isinstance() arg 2 must be a type or tuple of types"));
}
const auto matches = std::any_of(types.begin(), types.end(), [object](PyType *const &t) {
return object->type()->issubclass(t);
});
return Ok(matches ? py_true() : py_false());
}
PyResult<PyObject *> issubclass(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *, PyObject *>::unpack_tuple(args,
kwargs,
"issubclass",
std::integral_constant<size_t, 2>{},
std::integral_constant<size_t, 2>{});
if (result.is_err()) return Err(result.unwrap_err());
auto [class_, classinfo] = result.unwrap();
auto *class_as_type = as<PyType>(class_);
if (!class_as_type) { return Err(type_error("issubclass() arg 1 must be a class")); }
if (auto *class_info_tuple = as<PyTuple>(classinfo)) {
(void)class_info_tuple;
TODO();
} else if (auto *class_info_type = as<PyType>(classinfo)) {
return Ok(class_as_type->issubclass(class_info_type) ? py_true() : py_false());
} else {
return Err(type_error("issubclass() arg 2 must be a class or tuple of classes"));
}
}
PyResult<PyObject *> all(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"all",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
auto *iterable = std::get<0>(result.unwrap());
const auto &iterator = iterable->iter();
if (iterator.is_err()) return iterator;
auto next_value = iterator.unwrap()->next();
while (!next_value.is_err()) {
const auto is_truthy = next_value.unwrap()->true_();
if (is_truthy.is_err()) return Err(is_truthy.unwrap_err());
if (!is_truthy.unwrap()) { return Ok(py_false()); }
next_value = iterator.unwrap()->next();
}
if (next_value.unwrap_err()->type()->issubclass(types::stop_iteration())) {
return Ok(py_true());
} else {
return next_value;
}
}
PyResult<PyObject *> any(PyTuple *args, PyDict *kwargs, Interpreter &)
{
auto result = PyArgsParser<PyObject *>::unpack_tuple(args,
kwargs,
"any",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 1>{});
if (result.is_err()) return Err(result.unwrap_err());
auto *iterable = std::get<0>(result.unwrap());
const auto &iterator = iterable->iter();
if (iterator.is_err()) return iterator;
auto next_value = iterator.unwrap()->next();
while (!next_value.is_err()) {
const auto is_truthy = next_value.unwrap()->true_();
if (is_truthy.is_err()) return Err(is_truthy.unwrap_err());
if (is_truthy.unwrap()) { return Ok(py_true()); }
next_value = iterator.unwrap()->next();
}
if (next_value.unwrap_err()->type()->issubclass(types::stop_iteration())) {
return Ok(py_false());
} else {
return next_value;
}
}
PyResult<PyObject *> exec(PyTuple *args, PyDict *kwargs, Interpreter &interpreter)
{
auto result = PyArgsParser<PyObject *, PyObject *, PyObject *>::unpack_tuple(args,
kwargs,
"exec",
std::integral_constant<size_t, 1>{},
std::integral_constant<size_t, 3>{},
py_none() /* globals */,
py_none() /* locals */);
if (result.is_err()) return Err(result.unwrap_err());
auto [source, globals, locals] = result.unwrap();
if (globals == py_none()) {
globals = interpreter.execution_frame()->globals();
if (locals == py_none()) { locals = interpreter.execution_frame()->locals(); }
if (!globals || !locals) { TODO(); }
} else if (locals == py_none()) {
locals = globals;
}
if (!as<PyDict>(globals)) {
return Err(type_error("exec() globals must be a dict, not {}", globals->type()->name()));
}
if (locals->as_mapping().is_err() && locals != py_none()) {
return Err(type_error("locals must be a mapping or None, not {}", locals->type()->name()));
}
if (!as<PyDict>(globals)->map().contains(String{ "__builtin__" })) {
as<PyDict>(globals)->insert(
String{ "__builtin__" }, interpreter.execution_frame()->builtins());
}
if (auto *code = as<PyCode>(source)) {
if (!as<PyDict>(locals)) { TODO(); }
return code->eval(as<PyDict>(globals),
as<PyDict>(locals),
PyTuple::create().unwrap(),
PyDict::create().unwrap(),
{},
{},
{},
PyString::create("").unwrap());
} else {
TODO();
}