Repository navigation
Expand file tree
/
Copy patheobjects.py
More file actions
1371 lines (1122 loc) · 45.6 KB
/
Copy patheobjects.py
File metadata and controls
1371 lines (1122 loc) · 45.6 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
import builtins
import collections
import os
import sys
import types
from typing import (
Text, Any, Dict, Tuple, Optional, Callable, Union, Type,
Deque, List
)
import weakref
from echo.enative_fn import ENativeFn
from echo.epy_object import (
EPyObject, AttrWhere, EPyType, try_invoke,
)
from echo.elog import log, debugged
from echo.interp_context import ICtx
from echo.code_attributes import CodeAttributes
from echo.interp_result import Result, ExceptionData, check_result
from echo.common import memoize
E_PREFIX = 'e' if 'E_PREFIX' not in os.environ else os.environ['E_PREFIX']
class EFunction(EPyObject):
def __init__(self,
code: types.CodeType,
globals_: Dict[Text, Any],
name: Text,
*,
defaults=None,
kwarg_defaults: Optional[Dict[Text, Any]] = None,
closure=None):
self.code = code
self._code_attrs = CodeAttributes.from_code(code, name=name)
self.globals_ = globals_
self.name = name
self.defaults = defaults
self.kwarg_defaults = kwarg_defaults
self.closure = closure
self.dict_ = {
'__code__': code,
'__module__': None,
'__doc__': None,
'__qualname__': None,
'__name__': name,
}
def get_type(self) -> EPyType:
return EFunctionType.get_singleton()
def __repr__(self):
return '<{}function {} at {:#x}>'.format(E_PREFIX, self.name, id(self))
@check_result
def invoke(self,
args: Tuple[Any, ...],
kwargs: Dict[Text, Any],
locals_dict: Dict[Text, Any],
ictx: ICtx,
globals_: Optional[Dict[Text, Any]] = None) -> Result[Any]:
assert isinstance(ictx, ICtx), ictx
if self._code_attrs.coroutine:
return Result(GuestCoroutine(self))
return ictx.interp_callback(
self.code, globals_=self.globals_, args=args, kwargs=kwargs,
defaults=self.defaults, locals_dict=locals_dict, name=self.name,
kwarg_defaults=self.kwarg_defaults, closure=self.closure,
ictx=ictx)
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
if name in self.dict_:
return AttrWhere.SELF_DICT
if name in ('__class__', '__dict__',):
return AttrWhere.SELF_SPECIAL
if name in ('__get__',):
return AttrWhere.CLS
return None
def _get(self,
args: Tuple[Any, ...],
kwargs: Dict[Text, Any],
locals_dict: Dict[Text, Any],
ictx: ICtx,
globals_: Optional[Dict[Text, Any]] = None) -> Result[Any]:
assert len(args) == 3, args
_self, obj, objtype = args
assert self is _self
if obj is None:
return Result(_self)
return Result(EMethod(f=_self, bound_self=obj))
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
if name == '__class__':
return Result(EFunctionType.get_singleton())
if name == '__dict__':
return Result(self.dict_)
if name == '__closure__':
return Result(self.closure)
if name == '__defaults__':
return Result(self.defaults)
if name == '__get__':
return Result(EMethod(ENativeFn(
self._get, 'efunction.__get__'), bound_self=self))
if name == '__call__':
return Result(self)
try:
return Result(self.dict_[name])
except KeyError:
msg = f'Cannot find attribute {name} on {self}'
return Result(ExceptionData(None, name, AttributeError(msg)))
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Result[None]:
self.dict_[name] = value
return Result(None)
class GuestCoroutine(EPyObject):
def __init__(self, f: EFunction):
self.f = f
def get_type(self) -> EPyType:
return GuestCoroutineType_singleton
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
if name == 'close':
return AttrWhere.CLS
return None
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
if name == 'close':
def fake(x): pass
guest_f = EFunction(
getattr(fake, '__code__'), {}, 'coroutine.close')
guest_m = EMethod(guest_f, self)
return Result(guest_m)
raise NotImplementedError
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Any:
raise NotImplementedError
class EAsyncGeneratorType(EPyType):
def __init__(self):
self._dict = {}
def __repr__(self) -> Text:
return "<eclass 'async_generator'>"
def get_name(self) -> str:
return 'async_generator'
def get_bases(self): raise NotImplementedError
def get_dict(self): raise NotImplementedError
def get_mro(self): raise NotImplementedError
def get_type(self) -> EPyType:
return get_guest_builtin('type')
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
if name == '__mro__':
return Result((self, get_guest_builtin('type')))
if name == '__dict__':
return Result(self._dict)
raise NotImplementedError(self, name)
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Any:
raise NotImplementedError
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
if name in ('__mro__', '__dict__'):
return AttrWhere.SELF_SPECIAL
return None
EAsyncGeneratorType_singleton = EAsyncGeneratorType()
class EAsyncGenerator(EPyObject):
def __init__(self, f):
self.f = f
def get_type(self) -> EPyType:
return EAsyncGeneratorType_singleton
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
return None
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
raise NotImplementedError
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Any:
raise NotImplementedError
class EMethodType(EPyType):
def __repr__(self) -> Text:
return "<{}class 'method'>".format(E_PREFIX)
def get_name(self) -> str:
return 'method'
def get_bases(self): raise NotImplementedError
def get_dict(self): raise NotImplementedError
def get_mro(self): raise NotImplementedError
def get_type(self) -> EPyType:
return get_guest_builtin('type')
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
raise NotImplementedError
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Any:
raise NotImplementedError
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
return None
EMethodType_singleton = EMethodType()
class EMethod(EPyObject):
def __init__(self, f: EPyObject, bound_self: EPyObject):
self.f = f
self.bound_self = bound_self
def __repr__(self) -> str:
name_str = ''
if isinstance(self.f, EFunction):
name_str = ' ' + self.f.name
return f'<{E_PREFIX}bound method{name_str} of {self.bound_self!r}>'
def get_type(self) -> EPyType:
return EMethodType_singleton
@property
def code(self): return self.f.code
@property
def globals_(self): return self.f.globals_
@property
def name(self): return self.f.name
@property
def defaults(self): return self.f.defaults
@property
def kwarg_defaults(self): return self.f.kwarg_defaults
@property
def closure(self): return self.f.closure
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
if name in ('__self__', '__func__'):
return AttrWhere.SELF_SPECIAL
if name == '__get__':
return None
return None
def getattr(self, name: Text, *args, **kwargs) -> Result[Any]:
if name == '__self__':
return Result(self.bound_self)
if name == '__func__':
return Result(self.f)
return self.f.getattr(name, *args, **kwargs)
def setattr(self, *args, **kwargs):
return self.f.setattr(*args, **kwargs)
@check_result
def invoke(self,
args: Tuple[Any, ...],
kwargs: Dict[Text, Any],
locals_dict: Dict[Text, Any],
ictx: ICtx,
globals_: Optional[Dict[Text, Any]] = None) -> Result[Any]:
assert isinstance(args, tuple), args
return self.f.invoke(
(self.bound_self,) + args,
kwargs, locals_dict, ictx, globals_=globals_)
class NotFoundSentinel:
pass
NotFoundSentinel_singleton = NotFoundSentinel()
def _find_name_in_mro(type_: EPyType, name: Text, ictx: ICtx) -> Any:
mro = type_.get_mro()
log('eo:fnim', f'searching for {name} in {mro}')
for cls in mro:
if isinstance(cls, EBuiltin):
if cls.hasattr(name):
return cls.getattr(name, ictx).get_value()
elif isinstance(cls, EPyType):
d = cls.get_dict()
assert isinstance(d, dict), (cls, d)
if name in d:
return d[name]
else:
assert isinstance(cls, type), cls
if hasattr(cls, name):
return getattr(cls, name)
return NotFoundSentinel_singleton
def _type_getattro(
type_: 'EClass', name: Text, ictx: ICtx,
do_invoke_desc: bool = True) -> Union[Result[Any], Tuple[bool, Any]]:
assert isinstance(type_, EClass), type_
if name == '__dict__':
return Result(type_.dict_)
if name == '__mro__':
return Result(type_.get_mro())
if name == '__class__':
return Result(type_.metaclass or get_guest_builtin('type'))
if name == '__bases__':
return Result(type_.bases)
if name == '__base__':
return Result(type_.get_base())
if name == '__name__':
return Result(type_.name)
metatype = type_.get_type()
meta_attr = _find_name_in_mro(metatype, name, ictx)
log('eo:ec:ga', f'type_: {type_} name: {name!r} metaclass: {metatype} '
f'meta_attr: {meta_attr}')
if meta_attr is not NotFoundSentinel_singleton:
if (isinstance(meta_attr, EPyObject)
and meta_attr.hasattr('__get__')
and meta_attr.hasattr('__set__')):
if not do_invoke_desc:
return (True, meta_attr)
log('gi:ga', f'overriding descriptor: {meta_attr}')
f = meta_attr.getattr('__get__', ictx)
if f.is_exception():
return f
v = f.get_value()
return try_invoke(v, (type_, metatype), {}, {}, ictx)
attr = _find_name_in_mro(type_, name, ictx)
if attr is not NotFoundSentinel_singleton:
log('eo:ec:ga', f'dict attr {name!r} on {type_}: {attr}')
if isinstance(attr, EPyObject) and attr.hasattr('__get__'):
if not do_invoke_desc:
return (True, attr)
f_result = attr.getattr('__get__', ictx)
if f_result.is_exception():
return Result(f_result.get_exception())
v = f_result.get_value()
res = try_invoke(v, (None, type_), {}, {}, ictx)
log('eo:ec:ga', f'invoked descriptor getter {v} => {res}')
return res
return Result(attr)
if meta_attr is not NotFoundSentinel_singleton:
if (isinstance(meta_attr, EPyObject)
and meta_attr.hasattr('__get__')):
log('gi:ga', f'non-overriding descriptor: {meta_attr}')
if not do_invoke_desc:
return (True, meta_attr)
f = meta_attr.getattr('__get__', ictx)
if f.is_exception():
return f
v = f.get_value()
return try_invoke(v, (type_, metatype), {}, {}, ictx)
if not do_invoke_desc:
return (False, meta_attr)
return Result(meta_attr)
if metatype.hasattr('__getattr__'):
meta_ga_ = metatype.getattr('__getattr__', ictx)
if meta_ga_.is_exception():
return meta_ga_
meta_ga = meta_ga_.get_value()
if meta_ga.hasattr('__get__'):
if not do_invoke_desc:
return meta_ga
meta_ga = invoke_desc(type_, meta_ga, ictx)
if meta_ga.is_exception():
return meta_ga
meta_ga = meta_ga.get_value()
return try_invoke(meta_ga, (name,), {}, {}, ictx)
if not do_invoke_desc:
return (False, None)
msg = f'Class {type_.name} does not have attribute {name!r}'
return Result(ExceptionData(
None,
None,
AttributeError(msg)))
class EInstance(EPyObject):
def __init__(self, cls: Union['EClass', 'EBuiltin']):
assert isinstance(cls, (EClass, EBuiltin)), cls
self.cls = cls
self.dict_: Dict[str, Any] = {}
self.builtin_storage: Dict[type, Any] = {}
def __repr__(self) -> Text:
return '<{} eobject>'.format(self.cls.name)
def __len__(self):
raise NotImplementedError
def get_type(self) -> Union['EClass', 'EBuiltin']:
return self.cls
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
if name in self.dict_:
return AttrWhere.SELF_DICT
# Special members.
if name in ('__class__', '__dict__'):
return AttrWhere.SELF_SPECIAL
cls_hasattr = self.cls.hasattr(name)
assert isinstance(cls_hasattr, bool), (self.cls, cls_hasattr)
return AttrWhere.CLS if cls_hasattr else None
@check_result
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
"""Looks up an attribute on this object instance."""
cls_attr = _find_name_in_mro(self.get_type(), name, ictx)
log('gi:ga', f'self: {self} name: {name} cls_attr: {cls_attr}')
if (isinstance(cls_attr, EInstance)
and cls_attr.hasattr('__get__')
and cls_attr.hasattr('__set__')):
log('gi:ga', f'overriding descriptor: {cls_attr}')
# Overriding descriptor.
return invoke_desc(self, cls_attr, ictx)
try:
return Result(self.dict_[name])
except KeyError:
if name == '__class__':
return Result(self.cls)
if name == '__dict__':
return Result(self.dict_)
log('eo:ei', f'cls_attr: {cls_attr}')
if isinstance(cls_attr, EPyObject) and cls_attr.hasattr('__get__'):
log('gi:ga', f'non-overriding descriptor: {cls_attr}')
return invoke_desc(self, cls_attr, ictx)
if cls_attr is not NotFoundSentinel_singleton:
return Result(cls_attr)
dunder_getattr = _find_name_in_mro(self.get_type(), '__getattr__',
ictx)
if dunder_getattr is not NotFoundSentinel_singleton:
log('eo:ei:ga', f'__getattr__: {dunder_getattr}')
if (isinstance(dunder_getattr, EPyObject)
and dunder_getattr.hasattr('__get__')):
dunder_getattr = invoke_desc(self, dunder_getattr, ictx)
if dunder_getattr.is_exception():
return dunder_getattr
dunder_getattr = dunder_getattr.get_value()
return dunder_getattr.invoke((name,), {}, {}, ictx)
msg = f"'{self.cls.name}' object does not have attribute {name!r}"
return Result(ExceptionData(None, None, AttributeError(msg)))
@check_result
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Result[None]:
cls_attr: Optional[Any] = None
if name in self.cls.dict_:
cls_attr = self.cls.dict_[name]
log('eo:ei:sa', f'cls_attr {cls_attr!r}')
if (isinstance(cls_attr, EPyObject)
and cls_attr.hasattr('__set__')):
f_result = cls_attr.getattr('__set__', ictx)
if f_result.is_exception():
return Result(f_result.get_exception())
return f_result.get_value().invoke((self, value), {}, {}, ictx)
self.dict_[name] = value
return Result(None)
@check_result
def invoke(self,
args: Tuple[Any, ...],
kwargs: Dict[Text, Any],
locals_dict: Dict[Text, Any],
ictx: ICtx,
globals_: Optional[Dict[Text, Any]] = None) -> Result[Any]:
assert isinstance(ictx, ICtx), ictx
call_res = self.getattr('__call__', ictx)
if call_res.is_exception():
return call_res
call = call_res.get_value()
return call.invoke(args, kwargs, locals_dict, ictx, globals_=globals_)
def _maybe_builtin(b: Type) -> Union['EBuiltin', Type]:
if b is Exception:
return get_guest_builtin('Exception')
if b is BaseException:
return get_guest_builtin('BaseException')
return b
def _get_bases(c: Union[EPyType, Type]) -> Tuple[Union[EPyType, Type], ...]:
if isinstance(c, type):
return tuple(_maybe_builtin(b) for b in c.__bases__)
assert isinstance(c, EPyType), c
return c.get_bases()
class EClass(EPyType):
"""Represents a user-defined class."""
def __init__(self, name: Text, dict_: Dict[Text, Any], *,
bases: Optional[Tuple[EPyType, ...]] = None,
metaclass: Optional[EPyType] = None, kwargs=None):
self.name = name
self.dict_ = dict_
self.bases: Tuple[EPyType, ...] = \
bases or (get_guest_builtin('object'),)
self.metaclass: Optional[EPyType] = metaclass
self.kwargs = kwargs
self.subclasses: weakref.WeakSet = weakref.WeakSet()
for base in self.bases:
if isinstance(base, (EBuiltin, EClass)):
base.note_subclass(self)
def get_bases(self) -> Tuple[EPyType, ...]:
return self.bases
def get_name(self) -> str:
return self.name
def get_dict(self) -> Dict[Text, Any]:
return self.dict_
def note_subclass(self, derived: 'EClass') -> None:
self.subclasses.add(derived)
def __repr__(self) -> Text:
if isinstance(self.dict_, dict) and '__module__' in self.dict_:
return '<{}class \'{}.{}\'>'.format(
E_PREFIX, self.dict_['__module__'], self.name)
return '<{}class \'{}\">'.format(E_PREFIX, self.name)
def get_type(self) -> 'EPyType':
return self.metaclass or get_guest_builtin('type')
def get_mro(self) -> Tuple[Union[EPyType, Type], ...]:
"""The MRO is a preorder DFS of the 'derives from' relation."""
derives_from = [] # (cls, base)
frontier: Deque[Union[EPyType, Type]] = collections.deque([self])
while frontier:
cls = frontier.popleft()
bases = _get_bases(cls)
for base in bases:
derives_from.append((cls, base))
frontier.append(base)
cls_to_subclasses_ = collections.defaultdict(list)
for cls, base in derives_from:
cls_to_subclasses_[base].append(cls)
cls_to_subclasses = dict(cls_to_subclasses_)
ready: Deque[Union[EPyType, Type]] = collections.deque([self])
order: List[Union[EPyType, Type]] = []
def is_ready(c) -> bool:
return all(sc in order for sc in cls_to_subclasses.get(c, []))
assert is_ready(self)
while ready:
c = ready.popleft()
order.append(c)
for b in reversed(_get_bases(c)):
if is_ready(b):
ready.appendleft(b)
eobject = get_guest_builtin('object')
if eobject not in order:
order.append(eobject)
return tuple(order)
def get_base(self) -> EPyType:
if len(self.bases) != 1:
raise NotImplementedError(self, self.bases)
return self.bases[0]
@check_result
def invoke(self,
args: Tuple[Any, ...],
kwargs: Dict[Text, Any],
locals_dict: Dict[Text, Any],
ictx: ICtx,
globals_: Optional[Dict[Text, Any]] = None) -> Result[Any]:
assert isinstance(ictx, ICtx), ictx
call_res = self.get_type().getattr('__call__', ictx)
if call_res.is_exception():
return call_res
call = call_res.get_value()
return call.invoke((self,) + args, kwargs, locals_dict, ictx,
globals_=globals_)
def instantiate(self,
args: Tuple[Any, ...],
kwargs: Dict[Text, Any],
globals_: Dict[Text, Any],
ictx: ICtx) -> Result[EInstance]:
"""Creates an instance of this user-defined class."""
log('eo:ec',
lambda: f'instantiate self: {self} args: {args} kwargs: {kwargs}')
guest_instance: Optional[EInstance] = None
if self.hasattr('__new__'):
new_f = self.getattr('__new__', ictx).get_value()
log('eo:ec:new', f'new_f {new_f}')
result = ictx.call(new_f, (self,) + args, kwargs, locals_dict={},
globals_=globals_)
if result.is_exception():
return Result(result.get_exception())
new_guest_instance = result.get_value()
do_isinstance = get_guest_builtin('isinstance')
ii_result = do_isinstance.invoke(
(new_guest_instance, self), {}, {}, ictx)
if ii_result.is_exception():
return ii_result
assert isinstance(ii_result.get_value(), bool), \
ii_result.get_value()
if not ii_result.get_value():
return Result(new_guest_instance)
guest_instance = new_guest_instance
guest_instance = (EInstance(self) if guest_instance is None
else guest_instance)
if self.hasattr('__init__'):
init_f = self.getattr('__init__', ictx).get_value()
# TODO(cdleary, 2019-01-26) What does Python do when you return
# something non-None from initializer? Ignore?
assert isinstance(guest_instance, EPyObject), guest_instance
init_res = ictx.call(
init_f, (guest_instance,) + args, kwargs, {},
globals_=globals_)
if init_res.is_exception():
return Result(init_res.get_exception())
return Result(guest_instance)
@debugged('eo:ec:hasattr_where()')
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
if name in self.dict_:
return AttrWhere.SELF_DICT
if name in ('__class__', '__bases__', '__base__', '__mro__',
'__dict__', '__name__'):
return AttrWhere.SELF_SPECIAL
if self.get_type().hasattr(name):
return AttrWhere.CLS
for base in self.get_mro()[1:]:
assert isinstance(base, EPyObject)
haw = base.hasattr_where(name)
if haw:
return haw
return None
@debugged('eo:ec:ga')
@check_result
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
"""Looks up an attribute on this class object.
This should effectively correspond to type_getattro.
"""
r = _type_getattro(self, name, ictx)
assert isinstance(r, Result)
return r
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Result[None]:
sa = _find_name_in_mro(self.get_type(), '__setattr__', ictx)
if (sa is NotFoundSentinel_singleton
or sa is get_guest_builtin('object.__setattr__')):
self.dict_[name] = value
log('eo:ec:setattr',
f'updated self.dict_ {self.dict_} name {name} value {value}')
return Result(None)
log('eo:ec:setattr',
f'self {self} name {name} value {value} => invoking {sa}')
return sa.invoke((self, name, value), {}, {}, ictx)
class EFunctionType(EPyType):
_singleton: Optional[EPyType] = None
@classmethod
def get_singleton(cls) -> EPyType:
if cls._singleton is None:
cls._singleton = EFunctionType()
return cls._singleton
def __repr__(self) -> Text:
return "<{}class 'function'>".format(E_PREFIX)
def get_name(self) -> str: return 'function'
def get_type(self) -> EPyType:
return get_guest_builtin('type')
def get_bases(self):
raise NotImplementedError
def get_dict(self):
# TODO: return mapping proxy
return {}
def get_mro(self) -> Tuple[EPyType, ...]:
return (self,)
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
if name in ('__code__', '__globals__', '__get__'):
return AttrWhere.SELF_SPECIAL
return None
def _get_desc(self, args, kwargs: Dict[Text, Any],
locals_dict: Dict[Text, Any],
ictx: ICtx,
globals_: Optional[Dict[Text, Any]] = None) -> Result[Any]:
assert not kwargs, kwargs
assert len(args) == 3, args
eself, obj, objtype = args
if obj is None:
return Result(eself)
return Result(EMethod(eself, bound_self=obj))
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
if name in ('__code__', '__globals__'):
return Result(None)
if name == '__get__':
return Result(ENativeFn(self._get_desc, 'efunction.__get__'))
raise NotImplementedError
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Any:
raise NotImplementedError
EFunctionType_singleton = EFunctionType()
class GuestCoroutineType(EPyType):
def __init__(self):
self.dict_ = {}
def get_name(self) -> str:
return 'coroutine'
def __repr__(self) -> Text:
return "<eclass 'coroutine'>"
def get_bases(self):
raise NotImplementedError
def get_dict(self):
raise NotImplementedError
def get_mro(self) -> Tuple[EPyType, ...]:
return (self, get_guest_builtin('type'))
def get_type(self) -> EPyType:
return get_guest_builtin('type')
def hasattr_where(self, name: Text) -> Optional[AttrWhere]:
if name in ('__mro__', '__dict__'):
return AttrWhere.SELF_SPECIAL
return None
def getattr(self, name: Text, ictx: ICtx) -> Result[Any]:
if name == '__mro__':
return Result(self.get_mro())
if name == '__dict__':
return Result(self.dict_)
raise NotImplementedError(name)
def setattr(self, name: Text, value: Any, ictx: ICtx) -> Any:
raise NotImplementedError(name, value)
GuestCoroutineType_singleton = GuestCoroutineType()
def _is_type_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'type'
def _is_dict_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'dict'
def _is_int_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'int'
def _is_bool_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'bool'
def is_list_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'list'
def _is_object_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'object'
def _is_exception_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'Exception'
def _is_base_exception_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'BaseException'
def _is_str_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'str'
def is_tuple_builtin(x) -> bool:
return isinstance(x, EBuiltin) and x.name == 'tuple'
@check_result
def _do_len(
args: Tuple[Any, ...],
ictx: ICtx) -> Result[Any]:
assert len(args) == 1
if not isinstance(args[0], EPyObject):
return Result(len(args[0]))
do_len_ = args[0].getattr('__len__', ictx)
if do_len_.is_exception():
return do_len_
do_len = do_len_.get_value()
res: Result[Any] = do_len.invoke((), {}, {}, ictx)
if res.is_exception():
return res
v = res.get_value()
assert isinstance(v, int) # For now.
if v < 0:
return Result(ExceptionData(
None, None, ValueError('__len__() should return >= 0')))
return Result(v)
class EBuiltin(EPyType):
"""A builtin function/type in the echo VM."""
BUILTIN_TYPES = (
'object', 'type', 'classmethod', 'bytearray', 'bytes',
'staticmethod', 'property', 'Exception', 'super', 'enumerate', 'map',
'str', 'dict', 'tuple', 'list', 'int', 'bool', 'BaseException',
)
BUILTIN_FNS = (
'len', '__build_class__', 'getattr', 'setattr', 'iter', 'reversed',
'zip', 'next', 'repr', 'exec', 'hash', 'vars', 'dir', 'sum',
'isinstance', 'issubclass', 'hasattr', 'any', 'min', 'max', 'callable',
# object
'object.__new__', 'object.__init__',
'object.__str__',
'object.__repr__',
'object.__setattr__',
'object.__format__', 'object.__reduce_ex__',
'object.__ne__', 'object.__eq__',
'object.__subclasshook__',
# type
'type.__new__', 'type.__init__',
'type.__str__', 'type.__repr__',
'type.__subclasses__',
'type.mro', 'type.__call__',
# str
'str.maketrans', 'str.join', 'str.__repr__',
# dict
'dict.__eq__', 'dict.__init__', 'dict.__repr__',
'dict.__setitem__', 'dict.__getitem__', 'dict.__delitem__',
'dict.__contains__',
'dict.fromkeys', 'dict.update', 'dict.setdefault',
'dict.pop', 'dict.get',
# int
'int.__new__', 'int.__init__',
'int.__add__', 'int.__radd__',
'int.__sub__', 'int.__rsub__',
'int.__and__', 'int.__rand__',
'int.__mul__', 'int.__rmul__',
'int.__bool__', 'int.__repr__', 'int.__str__', 'int.__int__',
# int cmp
'int.__eq__', 'int.__ne__', 'int.__lt__', 'int.__ge__', 'int.__le__',
'int.__gt__',
# list
'list.__new__', 'list.__init__',
'list.__eq__', 'list.__repr__',
'list.append', 'list.extend', 'list.clear', 'list.remove',
'list.__contains__', 'list.__iter__', 'list.__getitem__',
'list.__setitem__',
# tuple
'tuple.__new__', 'tuple.__init__',
'tuple.__eq__', 'tuple.__lt__',
'tuple.__getitem__', 'tuple.__repr__',
# bytearray
'bytearray.__setitem__', 'bytearray.__repr__',
)
_registry: Dict[Text, Tuple[Callable, Optional[type]]] = {}
def __init__(self, name: Text, bound_self: Any, singleton_ok: bool = True):
self.name = name
self.bound_self = bound_self
self.dict_: Dict[Text, Any] = {}
self.globals_: Dict[Text, Any] = {}
def get_name(self) -> str:
return 'builtin_type'
def has_standard_getattr(self) -> bool:
if self.name in ('super',):
return False
return True
@classmethod
def is_ebuiltin(cls, o: Any) -> bool:
if isinstance(o, EBuiltin):
return True
return o in cls._registry.values()
@classmethod
def get_ebuiltin_type(cls, name: Text) -> type:
t = cls._registry[name][1]
assert t is not None
return t
@classmethod
def register(cls, name: Text, f: Callable, t: Optional[type]) -> None:
cls._registry[name] = (f, t)
def __repr__(self) -> Text:
if self.name in self.BUILTIN_TYPES:
return "<{}class '{}'>".format(E_PREFIX, self.name)
if self.name in self.BUILTIN_FNS and not self.bound_self:
return f'<{E_PREFIX}built-in function {self.name}>'
return 'EBuiltin(name={!r}, bound_self={!r}, ...)'.format(
self.name, self.bound_self)
def get_dict(self):
raise NotImplementedError
def get_bases(self):
if self.name == 'object':
return ()
eobject = get_guest_builtin('object')
if self.name == 'Exception':
return (get_guest_builtin('BaseException'),)
return (eobject,)
def get_type(self) -> EPyType:
if self.name in self.BUILTIN_FNS:
if self.bound_self:
return EMethodType_singleton
else:
return EFunctionType_singleton
if self.name in self.BUILTIN_TYPES:
return get_guest_builtin('type')
raise NotImplementedError(self)
def get_mro(self) -> Tuple[EPyType, ...]:
if self.name == 'object':
return (get_guest_builtin('object'),)
elif self.name in self.BUILTIN_TYPES:
return (get_guest_builtin(self.name), get_guest_builtin('object'))
else:
raise NotImplementedError(self)
def note_subclass(self, cls: 'EClass') -> None:
pass
def is_subtype_of(self, other: EPyType) -> bool:
if _is_type_builtin(self) and _is_object_builtin(other):
return True
if self is other:
return True
return False
@check_result
def invoke(self,
args: Tuple[Any, ...],