forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuiltins.rs
More file actions
857 lines (744 loc) · 27.3 KB
/
builtins.rs
File metadata and controls
857 lines (744 loc) · 27.3 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
//! Builtin function definitions.
//!
//! Implements functions listed here: https://docs.python.org/3/library/builtins.html
// use std::ops::Deref;
use std::char;
use std::io::{self, Write};
use crate::compile;
use crate::obj::objbool;
use crate::obj::objdict;
use crate::obj::objint;
use crate::obj::objiter;
use crate::obj::objstr;
use crate::obj::objtype;
use crate::frame::{Scope, ScopeRef};
use crate::pyobject::{
AttributeProtocol, IdProtocol, PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol,
};
#[cfg(not(target_arch = "wasm32"))]
use crate::stdlib::io::io_open;
use crate::vm::VirtualMachine;
use num_traits::{Signed, ToPrimitive};
fn get_locals(vm: &mut VirtualMachine) -> PyObjectRef {
let d = vm.new_dict();
// TODO: implement dict_iter_items?
let locals = vm.get_locals();
let key_value_pairs = objdict::get_key_value_pairs(&locals);
for (key, value) in key_value_pairs {
objdict::set_item(&d, vm, &key, &value);
}
d
}
fn dir_locals(vm: &mut VirtualMachine) -> PyObjectRef {
get_locals(vm)
}
fn dir_object(vm: &mut VirtualMachine, obj: &PyObjectRef) -> PyObjectRef {
// Gather all members here:
let attributes = objtype::get_attributes(obj);
let mut members: Vec<String> = attributes.into_iter().map(|(n, _o)| n).collect();
// Sort members:
members.sort();
let members_pystr = members.into_iter().map(|m| vm.ctx.new_str(m)).collect();
vm.ctx.new_list(members_pystr)
}
fn builtin_abs(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(x, None)]);
match vm.get_method(x.clone(), "__abs__") {
Ok(attrib) => vm.invoke(attrib, PyFuncArgs::new(vec![], vec![])),
Err(..) => Err(vm.new_type_error("bad operand for abs".to_string())),
}
}
fn builtin_all(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(iterable, None)]);
let items = vm.extract_elements(iterable)?;
for item in items {
let result = objbool::boolval(vm, item)?;
if !result {
return Ok(vm.new_bool(false));
}
}
Ok(vm.new_bool(true))
}
fn builtin_any(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(iterable, None)]);
let items = vm.extract_elements(iterable)?;
for item in items {
let result = objbool::boolval(vm, item)?;
if result {
return Ok(vm.new_bool(true));
}
}
Ok(vm.new_bool(false))
}
// builtin_ascii
fn builtin_bin(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(number, Some(vm.ctx.int_type()))]);
let n = objint::get_value(number);
let s = if n.is_negative() {
format!("-0b{:b}", n.abs())
} else {
format!("0b{:b}", n)
};
Ok(vm.new_str(s))
}
// builtin_breakpoint
fn builtin_callable(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, None)]);
let is_callable = obj.typ().has_attr("__call__");
Ok(vm.new_bool(is_callable))
}
fn builtin_chr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(i, Some(vm.ctx.int_type()))]);
let code_point = objint::get_value(i).to_u32().unwrap();
let txt = match char::from_u32(code_point) {
Some(value) => value.to_string(),
None => '_'.to_string(),
};
Ok(vm.new_str(txt))
}
fn builtin_compile(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [
(source, None),
(filename, Some(vm.ctx.str_type())),
(mode, Some(vm.ctx.str_type()))
]
);
let source = objstr::get_value(source);
// TODO: fix this newline bug:
let source = format!("{}\n", source);
let mode = {
let mode = objstr::get_value(mode);
if mode == "exec" {
compile::Mode::Exec
} else if mode == "eval" {
compile::Mode::Eval
} else if mode == "single" {
compile::Mode::Single
} else {
return Err(
vm.new_value_error("compile() mode must be 'exec', 'eval' or single'".to_string())
);
}
};
let filename = objstr::get_value(filename);
compile::compile(&source, &mode, filename, vm.ctx.code_type()).map_err(|err| {
let syntax_error = vm.context().exceptions.syntax_error.clone();
vm.new_exception(syntax_error, err.to_string())
})
}
fn builtin_delattr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(obj, None), (attr, Some(vm.ctx.str_type()))]
);
vm.del_attr(obj, attr.clone())
}
fn builtin_dir(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
if args.args.is_empty() {
Ok(dir_locals(vm))
} else {
let obj = args.args.into_iter().next().unwrap();
Ok(dir_object(vm, &obj))
}
}
fn builtin_divmod(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(x, None), (y, None)]);
match vm.get_method(x.clone(), "__divmod__") {
Ok(attrib) => vm.invoke(attrib, PyFuncArgs::new(vec![y.clone()], vec![])),
Err(..) => Err(vm.new_type_error("unsupported operand type(s) for divmod".to_string())),
}
}
/// Implements `eval`.
/// See also: https://docs.python.org/3/library/functions.html#eval
fn builtin_eval(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(source, None)],
optional = [(globals, None), (locals, Some(vm.ctx.dict_type()))]
);
let scope = make_scope(vm, globals, locals)?;
// Determine code object:
let code_obj = if objtype::isinstance(source, &vm.ctx.code_type()) {
source.clone()
} else if objtype::isinstance(source, &vm.ctx.str_type()) {
let mode = compile::Mode::Eval;
let source = objstr::get_value(source);
// TODO: fix this newline bug:
let source = format!("{}\n", source);
compile::compile(&source, &mode, "<string>".to_string(), vm.ctx.code_type()).map_err(
|err| {
let syntax_error = vm.context().exceptions.syntax_error.clone();
vm.new_exception(syntax_error, err.to_string())
},
)?
} else {
return Err(vm.new_type_error("code argument must be str or code object".to_string()));
};
// Run the source:
vm.run_code_obj(code_obj.clone(), scope)
}
/// Implements `exec`
/// https://docs.python.org/3/library/functions.html#exec
fn builtin_exec(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(source, None)],
optional = [(globals, None), (locals, Some(vm.ctx.dict_type()))]
);
let scope = make_scope(vm, globals, locals)?;
// Determine code object:
let code_obj = if objtype::isinstance(source, &vm.ctx.str_type()) {
let mode = compile::Mode::Exec;
let source = objstr::get_value(source);
// TODO: fix this newline bug:
let source = format!("{}\n", source);
compile::compile(&source, &mode, "<string>".to_string(), vm.ctx.code_type()).map_err(
|err| {
let syntax_error = vm.context().exceptions.syntax_error.clone();
vm.new_exception(syntax_error, err.to_string())
},
)?
} else if objtype::isinstance(source, &vm.ctx.code_type()) {
source.clone()
} else {
return Err(vm.new_type_error("source argument must be str or code object".to_string()));
};
// Run the code:
vm.run_code_obj(code_obj, scope)
}
fn make_scope(
vm: &mut VirtualMachine,
globals: Option<&PyObjectRef>,
locals: Option<&PyObjectRef>,
) -> PyResult<ScopeRef> {
let dict_type = vm.ctx.dict_type();
let globals = match globals {
Some(arg) => {
if arg.is(&vm.get_none()) {
None
} else {
if vm.isinstance(arg, &dict_type)? {
Some(arg)
} else {
let arg_typ = arg.typ();
let actual_type = vm.to_pystr(&arg_typ)?;
let expected_type_name = vm.to_pystr(&dict_type)?;
return Err(vm.new_type_error(format!(
"globals must be a {}, not {}",
expected_type_name, actual_type
)));
}
}
}
None => None,
};
let current_scope = vm.current_scope();
let parent = match globals {
Some(dict) => Some(Scope::new(dict.clone(), Some(vm.get_builtin_scope()))),
None => current_scope.parent.clone(),
};
let locals = match locals {
Some(dict) => dict.clone(),
None => current_scope.locals.clone(),
};
Ok(Scope::new(locals, parent))
}
fn builtin_format(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(obj, None)],
optional = [(format_spec, Some(vm.ctx.str_type()))]
);
let format_spec = format_spec
.cloned()
.unwrap_or_else(|| vm.new_str("".to_string()));
vm.call_method(obj, "__format__", vec![format_spec])
}
fn builtin_getattr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(obj, None), (attr, Some(vm.ctx.str_type()))]
);
vm.get_attribute(obj.clone(), attr.clone())
}
// builtin_globals
fn builtin_hasattr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(obj, None), (attr, Some(vm.ctx.str_type()))]
);
let has_attr = match vm.get_attribute(obj.clone(), attr.clone()) {
Ok(..) => true,
Err(..) => false,
};
Ok(vm.context().new_bool(has_attr))
}
fn builtin_hash(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, None)]);
vm.call_method(obj, "__hash__", vec![])
}
// builtin_help
fn builtin_hex(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(number, Some(vm.ctx.int_type()))]);
let n = objint::get_value(number);
let s = if n.is_negative() {
format!("-0x{:x}", n.abs())
} else {
format!("0x{:x}", n)
};
Ok(vm.new_str(s))
}
fn builtin_id(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, None)]);
Ok(vm.context().new_int(obj.get_id()))
}
// builtin_input
fn builtin_isinstance(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(obj, None), (typ, Some(vm.get_type()))]
);
let isinstance = vm.isinstance(obj, typ)?;
Ok(vm.new_bool(isinstance))
}
fn builtin_issubclass(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(subclass, Some(vm.get_type())), (cls, Some(vm.get_type()))]
);
let issubclass = vm.issubclass(subclass, cls)?;
Ok(vm.context().new_bool(issubclass))
}
fn builtin_iter(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(iter_target, None)]);
objiter::get_iter(vm, iter_target)
}
fn builtin_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, None)]);
let len_method_name = "__len__";
match vm.get_method(obj.clone(), len_method_name) {
Ok(value) => vm.invoke(value, PyFuncArgs::default()),
Err(..) => Err(vm.new_type_error(format!(
"object of type '{}' has no method {:?}",
objtype::get_type_name(&obj.typ()),
len_method_name
))),
}
}
fn builtin_locals(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args);
Ok(vm.get_locals())
}
fn builtin_max(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
let candidates = if args.args.len() > 1 {
args.args.clone()
} else if args.args.len() == 1 {
vm.extract_elements(&args.args[0])?
} else {
// zero arguments means type error:
return Err(vm.new_type_error("Expected 1 or more arguments".to_string()));
};
if candidates.is_empty() {
let default = args.get_optional_kwarg("default");
if default.is_none() {
return Err(vm.new_value_error("max() arg is an empty sequence".to_string()));
} else {
return Ok(default.unwrap());
}
}
let key_func = args.get_optional_kwarg("key");
// Start with first assumption:
let mut candidates_iter = candidates.into_iter();
let mut x = candidates_iter.next().unwrap();
// TODO: this key function looks pretty duplicate. Maybe we can create
// a local function?
let mut x_key = if let Some(f) = &key_func {
let args = PyFuncArgs::new(vec![x.clone()], vec![]);
vm.invoke(f.clone(), args)?
} else {
x.clone()
};
for y in candidates_iter {
let y_key = if let Some(f) = &key_func {
let args = PyFuncArgs::new(vec![y.clone()], vec![]);
vm.invoke(f.clone(), args)?
} else {
y.clone()
};
let order = vm._gt(x_key.clone(), y_key.clone())?;
if !objbool::get_value(&order) {
x = y.clone();
x_key = y_key;
}
}
Ok(x)
}
fn builtin_min(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
let candidates = if args.args.len() > 1 {
args.args.clone()
} else if args.args.len() == 1 {
vm.extract_elements(&args.args[0])?
} else {
// zero arguments means type error:
return Err(vm.new_type_error("Expected 1 or more arguments".to_string()));
};
if candidates.is_empty() {
let default = args.get_optional_kwarg("default");
if default.is_none() {
return Err(vm.new_value_error("min() arg is an empty sequence".to_string()));
} else {
return Ok(default.unwrap());
}
}
let key_func = args.get_optional_kwarg("key");
let mut candidates_iter = candidates.into_iter();
let mut x = candidates_iter.next().unwrap();
// TODO: this key function looks pretty duplicate. Maybe we can create
// a local function?
let mut x_key = if let Some(f) = &key_func {
let args = PyFuncArgs::new(vec![x.clone()], vec![]);
vm.invoke(f.clone(), args)?
} else {
x.clone()
};
for y in candidates_iter {
let y_key = if let Some(f) = &key_func {
let args = PyFuncArgs::new(vec![y.clone()], vec![]);
vm.invoke(f.clone(), args)?
} else {
y.clone()
};
let order = vm._gt(x_key.clone(), y_key.clone())?;
if objbool::get_value(&order) {
x = y.clone();
x_key = y_key;
}
}
Ok(x)
}
fn builtin_next(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(iterator, None)],
optional = [(default_value, None)]
);
match vm.call_method(iterator, "__next__", vec![]) {
Ok(value) => Ok(value),
Err(value) => {
if objtype::isinstance(&value, &vm.ctx.exceptions.stop_iteration) {
match default_value {
None => Err(value),
Some(value) => Ok(value.clone()),
}
} else {
Err(value)
}
}
}
}
fn builtin_oct(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(number, Some(vm.ctx.int_type()))]);
let n = objint::get_value(number);
let s = if n.is_negative() {
format!("-0o{:o}", n.abs())
} else {
format!("0o{:o}", n)
};
Ok(vm.new_str(s))
}
fn builtin_ord(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(string, Some(vm.ctx.str_type()))]);
let string = objstr::get_value(string);
let string_len = string.chars().count();
if string_len > 1 {
return Err(vm.new_type_error(format!(
"ord() expected a character, but string of length {} found",
string_len
)));
}
match string.chars().next() {
Some(character) => Ok(vm.context().new_int(character as i32)),
None => Err(vm.new_type_error(
"ord() could not guess the integer representing this character".to_string(),
)),
}
}
fn builtin_pow(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(x, None), (y, None)],
optional = [(mod_value, Some(vm.ctx.int_type()))]
);
let pow_method_name = "__pow__";
let result = match vm.get_method(x.clone(), pow_method_name) {
Ok(attrib) => vm.invoke(attrib, PyFuncArgs::new(vec![y.clone()], vec![])),
Err(..) => Err(vm.new_type_error("unsupported operand type(s) for pow".to_string())),
};
//Check if the 3rd argument is defined and perform modulus on the result
//this should be optimized in the future to perform a "power-mod" algorithm in
//order to improve performance
match mod_value {
Some(mod_value) => {
let mod_method_name = "__mod__";
match vm.get_method(result.expect("result not defined").clone(), mod_method_name) {
Ok(value) => vm.invoke(value, PyFuncArgs::new(vec![mod_value.clone()], vec![])),
Err(..) => {
Err(vm.new_type_error("unsupported operand type(s) for mod".to_string()))
}
}
}
None => result,
}
}
pub fn builtin_print(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
trace!("print called with {:?}", args);
// Handle 'sep' kwarg:
let sep_arg = args
.get_optional_kwarg("sep")
.filter(|obj| !obj.is(&vm.get_none()));
if let Some(ref obj) = sep_arg {
if !objtype::isinstance(obj, &vm.ctx.str_type()) {
return Err(vm.new_type_error(format!(
"sep must be None or a string, not {}",
objtype::get_type_name(&obj.typ())
)));
}
}
let sep_str = sep_arg.as_ref().map(|obj| objstr::borrow_value(obj));
// Handle 'end' kwarg:
let end_arg = args
.get_optional_kwarg("end")
.filter(|obj| !obj.is(&vm.get_none()));
if let Some(ref obj) = end_arg {
if !objtype::isinstance(obj, &vm.ctx.str_type()) {
return Err(vm.new_type_error(format!(
"end must be None or a string, not {}",
objtype::get_type_name(&obj.typ())
)));
}
}
let end_str = end_arg.as_ref().map(|obj| objstr::borrow_value(obj));
// Handle 'flush' kwarg:
let flush = if let Some(flush) = &args.get_optional_kwarg("flush") {
objbool::boolval(vm, flush.clone()).unwrap()
} else {
false
};
let stdout = io::stdout();
let mut stdout_lock = stdout.lock();
let mut first = true;
for a in &args.args {
if first {
first = false;
} else if let Some(ref sep_str) = sep_str {
write!(stdout_lock, "{}", sep_str).unwrap();
} else {
write!(stdout_lock, " ").unwrap();
}
let v = vm.to_str(&a)?;
let s = objstr::borrow_value(&v);
write!(stdout_lock, "{}", s).unwrap();
}
if let Some(end_str) = end_str {
write!(stdout_lock, "{}", end_str).unwrap();
} else {
writeln!(stdout_lock).unwrap();
}
if flush {
stdout_lock.flush().unwrap();
}
Ok(vm.get_none())
}
fn builtin_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, None)]);
vm.to_repr(obj)
}
fn builtin_reversed(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, None)]);
match vm.get_method(obj.clone(), "__reversed__") {
Ok(value) => vm.invoke(value, PyFuncArgs::default()),
// TODO: fallback to using __len__ and __getitem__, if object supports sequence protocol
Err(..) => Err(vm.new_type_error(format!(
"'{}' object is not reversible",
objtype::get_type_name(&obj.typ()),
))),
}
}
// builtin_reversed
fn builtin_round(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(number, Some(vm.ctx.object()))],
optional = [(ndigits, None)]
);
if let Some(ndigits) = ndigits {
let ndigits = vm.call_method(ndigits, "__int__", vec![])?;
let rounded = vm.call_method(number, "__round__", vec![ndigits])?;
Ok(rounded)
} else {
// without a parameter, the result type is coerced to int
let rounded = &vm.call_method(number, "__round__", vec![])?;
Ok(vm.ctx.new_int(objint::get_value(rounded)))
}
}
fn builtin_setattr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(obj, None), (attr, Some(vm.ctx.str_type())), (value, None)]
);
let name = objstr::get_value(attr);
vm.ctx.set_attr(obj, &name, value.clone());
Ok(vm.get_none())
}
// builtin_slice
fn builtin_sorted(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(iterable, None)]);
let items = vm.extract_elements(iterable)?;
let lst = vm.ctx.new_list(items);
args.shift();
vm.call_method_pyargs(&lst, "sort", args)?;
Ok(lst)
}
fn builtin_sum(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(iterable, None)]);
let items = vm.extract_elements(iterable)?;
// Start with zero and add at will:
let mut sum = vm.ctx.new_int(0);
for item in items {
sum = vm._add(sum, item)?;
}
Ok(sum)
}
// builtin_vars
// builtin___import__
pub fn make_module(ctx: &PyContext) -> PyObjectRef {
let py_mod = py_module!(ctx, "__builtins__", {
//set __name__ fixes: https://github.com/RustPython/RustPython/issues/146
"__name__" => ctx.new_str(String::from("__main__")),
"abs" => ctx.new_rustfunc(builtin_abs),
"all" => ctx.new_rustfunc(builtin_all),
"any" => ctx.new_rustfunc(builtin_any),
"bin" => ctx.new_rustfunc(builtin_bin),
"bool" => ctx.bool_type(),
"bytearray" => ctx.bytearray_type(),
"bytes" => ctx.bytes_type(),
"callable" => ctx.new_rustfunc(builtin_callable),
"chr" => ctx.new_rustfunc(builtin_chr),
"classmethod" => ctx.classmethod_type(),
"compile" => ctx.new_rustfunc(builtin_compile),
"complex" => ctx.complex_type(),
"delattr" => ctx.new_rustfunc(builtin_delattr),
"dict" => ctx.dict_type(),
"divmod" => ctx.new_rustfunc(builtin_divmod),
"dir" => ctx.new_rustfunc(builtin_dir),
"enumerate" => ctx.enumerate_type(),
"eval" => ctx.new_rustfunc(builtin_eval),
"exec" => ctx.new_rustfunc(builtin_exec),
"float" => ctx.float_type(),
"frozenset" => ctx.frozenset_type(),
"filter" => ctx.filter_type(),
"format" => ctx.new_rustfunc(builtin_format),
"getattr" => ctx.new_rustfunc(builtin_getattr),
"hasattr" => ctx.new_rustfunc(builtin_hasattr),
"hash" => ctx.new_rustfunc(builtin_hash),
"hex" => ctx.new_rustfunc(builtin_hex),
"id" => ctx.new_rustfunc(builtin_id),
"int" => ctx.int_type(),
"isinstance" => ctx.new_rustfunc(builtin_isinstance),
"issubclass" => ctx.new_rustfunc(builtin_issubclass),
"iter" => ctx.new_rustfunc(builtin_iter),
"len" => ctx.new_rustfunc(builtin_len),
"list" => ctx.list_type(),
"locals" => ctx.new_rustfunc(builtin_locals),
"map" => ctx.map_type(),
"max" => ctx.new_rustfunc(builtin_max),
"memoryview" => ctx.memoryview_type(),
"min" => ctx.new_rustfunc(builtin_min),
"object" => ctx.object(),
"oct" => ctx.new_rustfunc(builtin_oct),
"ord" => ctx.new_rustfunc(builtin_ord),
"next" => ctx.new_rustfunc(builtin_next),
"pow" => ctx.new_rustfunc(builtin_pow),
"print" => ctx.new_rustfunc(builtin_print),
"property" => ctx.property_type(),
"range" => ctx.range_type(),
"repr" => ctx.new_rustfunc(builtin_repr),
"reversed" => ctx.new_rustfunc(builtin_reversed),
"round" => ctx.new_rustfunc(builtin_round),
"set" => ctx.set_type(),
"setattr" => ctx.new_rustfunc(builtin_setattr),
"sorted" => ctx.new_rustfunc(builtin_sorted),
"slice" => ctx.slice_type(),
"staticmethod" => ctx.staticmethod_type(),
"str" => ctx.str_type(),
"sum" => ctx.new_rustfunc(builtin_sum),
"super" => ctx.super_type(),
"tuple" => ctx.tuple_type(),
"type" => ctx.type_type(),
"zip" => ctx.zip_type(),
// Constants
"NotImplemented" => ctx.not_implemented.clone(),
// Exceptions:
"BaseException" => ctx.exceptions.base_exception_type.clone(),
"Exception" => ctx.exceptions.exception_type.clone(),
"ArithmeticError" => ctx.exceptions.arithmetic_error.clone(),
"AssertionError" => ctx.exceptions.assertion_error.clone(),
"AttributeError" => ctx.exceptions.attribute_error.clone(),
"NameError" => ctx.exceptions.name_error.clone(),
"OverflowError" => ctx.exceptions.overflow_error.clone(),
"RuntimeError" => ctx.exceptions.runtime_error.clone(),
"NotImplementedError" => ctx.exceptions.not_implemented_error.clone(),
"TypeError" => ctx.exceptions.type_error.clone(),
"ValueError" => ctx.exceptions.value_error.clone(),
"IndexError" => ctx.exceptions.index_error.clone(),
"ImportError" => ctx.exceptions.import_error.clone(),
"FileNotFoundError" => ctx.exceptions.file_not_found_error.clone(),
"StopIteration" => ctx.exceptions.stop_iteration.clone(),
"ZeroDivisionError" => ctx.exceptions.zero_division_error.clone(),
"KeyError" => ctx.exceptions.key_error.clone(),
});
#[cfg(not(target_arch = "wasm32"))]
ctx.set_attr(&py_mod, "open", ctx.new_rustfunc(io_open));
py_mod
}
pub fn builtin_build_class_(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> PyResult {
let function = args.shift();
let name_arg = args.shift();
let bases = args.args.clone();
let mut metaclass = args.get_kwarg("metaclass", vm.get_type());
for base in bases.clone() {
if objtype::issubclass(&base.typ(), &metaclass) {
metaclass = base.typ();
} else if !objtype::issubclass(&metaclass, &base.typ()) {
return Err(vm.new_type_error("metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases".to_string()));
}
}
let bases = vm.context().new_tuple(bases);
// Prepare uses full __getattribute__ resolution chain.
let prepare_name = vm.new_str("__prepare__".to_string());
let prepare = vm.get_attribute(metaclass.clone(), prepare_name)?;
let namespace = vm.invoke(
prepare,
PyFuncArgs {
args: vec![name_arg.clone(), bases.clone()],
kwargs: vec![],
},
)?;
vm.invoke_with_locals(function, namespace.clone())?;
vm.call_method(&metaclass, "__call__", vec![name_arg, bases, namespace])
}