-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrfexproto.py
More file actions
1695 lines (1610 loc) · 63.9 KB
/
Copy pathrfexproto.py
File metadata and controls
1695 lines (1610 loc) · 63.9 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
#
# Copyright (C) 2024-2026 George Zhang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Optional RPython imports
try:
from rpython.rlib.rsre import rsre_re as re
from rpython.rlib import rweakref
from rpython.rlib import jit
from rpython.rlib import objectmodel
from rpython.rlib import rfile
except ImportError:
import re
class rweakref(object):
class RWeakKeyDictionary(object):
def __init__(self, *args):
import weakref
self._data = weakref.WeakKeyDictionary()
def get(self, key): return self._data.get(key, None)
def set(self, key, value): self._data[key] = value
class jit(object):
class JitDriver(object):
def __init__(self, **kwargs): pass
def jit_merge_point(self, **kwargs): pass
def can_enter_jit(self, **kwargs): pass
@staticmethod
def set_param(*args): pass
@staticmethod
def set_user_param(*args): pass
@staticmethod
def promote(arg): return arg
@staticmethod
def promote_string(arg): return arg
@staticmethod
def elidable(func): return func
@staticmethod
def unroll_safe(func): return func
@staticmethod
def isvirtual(arg): return False
@staticmethod
def isconstant(arg): return False
@staticmethod
def we_are_jitted(): return False
class objectmodel(object):
class specialize(object):
@staticmethod
def call_location(): return lambda func: func
class rfile(object):
@staticmethod
def create_file(filename):
return open(filename, "rb")
if b"" == "": # Python 2
@staticmethod
def create_stdio():
import sys, os
# TODO: is this the correct way to reopen files in binary mode?
return (
os.fdopen(sys.stdin.fileno(), "rb", 0),
os.fdopen(sys.stdout.fileno(), "wb", 0),
os.fdopen(sys.stderr.fileno(), "wb", 0),
)
else:
@staticmethod
def create_stdio():
import sys
return sys.stdin.buffer, sys.stdout.buffer, sys.stderr.buffer
# == Interpreter types and logic
class Object(object):
_attrs_ = _immutable_fields_ = ()
class Nil(Object):
_attrs_ = _immutable_fields_ = ()
class Ignore(Object):
_attrs_ = _immutable_fields_ = ()
class Inert(Object):
_attrs_ = _immutable_fields_ = ()
class Boolean(Object):
_attrs_ = _immutable_fields_ = ("value",)
def __init__(self, value):
assert isinstance(value, bool)
self.value = value
class Pair(Object):
_attrs_ = _immutable_fields_ = ("car", "cdr")
def __init__(self, car, cdr):
assert isinstance(car, Object)
assert isinstance(cdr, Object)
self.car = car
self.cdr = cdr
ImmutablePair = Pair
class MutablePair(Pair):
_attrs_ = ("car", "cdr")
_immutable_fields_ = ()
class Int(Object):
_attrs_ = _immutable_fields_ = ("value",)
def __init__(self, value):
assert isinstance(value, int)
self.value = value
class String(Object):
_attrs_ = _immutable_fields_ = ("value",)
def __init__(self, value):
assert isinstance(value, bytes)
self.value = value
class Symbol(Object):
_attrs_ = _immutable_fields_ = ("name",)
def __init__(self, name):
assert isinstance(name, bytes)
self.name = name
class Environment(Object):
_immutable_fields_ = ("storage", "parent")
def __init__(self, bindings, parent):
assert parent is None or isinstance(parent, Environment)
storage, localmap = _environment_tostoragemap(bindings)
self.storage = storage
self.parent = parent
self.localmap = localmap
class Continuation(Object):
_immutable_fields_ = ("env", "operative", "parent")
_attrs_ = _immutable_fields_ + ("_should_enter", "_call_info")
def __init__(self, env, operative, parent):
assert env is None or isinstance(env, Environment)
assert isinstance(operative, Operative)
assert parent is None or isinstance(parent, Continuation)
self.env = env
self.operative = operative
self.parent = parent
self._should_enter = False
self._call_info = None
class Combiner(Object):
_immutable_fields_ = ("num_wraps", "operative")
def __init__(self, num_wraps, operative):
self.num_wraps = num_wraps
self.operative = operative
NIL = Nil()
IGNORE = Ignore()
INERT = Inert()
TRUE = Boolean(True)
FALSE = Boolean(False)
class Operative(object):
_immutable_ = True
def call(self, env, value, parent): assert False
class PrimitiveOperative(Operative):
_immutable_ = True
def __init__(self, func):
self.func = func
def call(self, env, value, parent):
try:
return self.func(env, value, parent)
except RuntimeError as e:
return f_error(parent, MutablePair(String(_c_str_to_bytes(e.message)), NIL))
class ContinuationOperative(Operative):
_immutable_ = True
def __init__(self, continuation):
self.continuation = continuation
def call(self, env, value, parent):
# TODO: replace with abnormal pass when guarded continuations implemented
return f_return(self.continuation, value)
class UserDefinedOperative(Operative):
_immutable_ = True
def __init__(self, env, envname, name, body):
assert env is None or isinstance(env, Environment)
self.env = env
assert isinstance(envname, Symbol) or isinstance(envname, Ignore)
self.envname = envname
assert not isinstance(name, MutablePair)
self.name = name
assert not isinstance(body, MutablePair)
self.body = body
def call(self, env, value, parent):
call_env = Environment({}, self.env)
envname = self.envname
if isinstance(envname, Symbol):
_environment_update(call_env, envname, env)
name = self.name
try:
_define(call_env, name, value)
except RuntimeError as e:
return f_error(parent, MutablePair(String(_c_str_to_bytes(e.message)), NIL))
return f_eval(call_env, self.body, parent)
def _f_noop(env, expr, parent):
return f_return(parent, expr)
NOOP = PrimitiveOperative(_f_noop)
# Interpreter-wide mapping from pair to location info
class Location(object):
def __init__(self, filename, start_line_no, start_char_no, end_line_no, end_char_no):
assert isinstance(filename, bytes)
self.filename = filename
assert isinstance(start_line_no, int)
self.start_line_no = start_line_no
assert isinstance(start_char_no, int)
self.start_char_no = start_char_no
assert isinstance(end_line_no, int)
self.end_line_no = end_line_no
assert isinstance(end_char_no, int)
self.end_char_no = end_char_no
LOCATIONS = rweakref.RWeakKeyDictionary(Object, Location)
def _copy_immutable_recursively_set(expr, visited):
if not isinstance(expr, MutablePair):
return expr
if expr in visited:
return visited[expr]
pair = ImmutablePair(NIL, NIL)
visited[expr] = pair
pair.car = _copy_immutable_recursively_set(expr.car, visited)
pair.cdr = _copy_immutable_recursively_set(expr.cdr, visited)
return pair
@jit.unroll_safe
def _copy_immutable_recursively_list(expr, visited):
if not isinstance(expr, MutablePair):
return expr
for before, after in visited:
if expr is before:
return after
pair = ImmutablePair(NIL, NIL)
visited.append((expr, pair))
pair.car = _copy_immutable_recursively_list(expr.car, visited)
pair.cdr = _copy_immutable_recursively_list(expr.cdr, visited)
return pair
def _f_copy_immutable(expr):
if not jit.we_are_jitted():
return _copy_immutable_recursively_set(expr, {})
else:
return _copy_immutable_recursively_list(expr, [])
# Exceptions
class ParsingError(Exception):
def __init__(self, message, line_no, char_no):
self.message = message
# Note that line_no and char_no must be on the exception instance since
# unlike internal errors, there is no "source expression" to locate.
self.line_no = line_no
self.char_no = char_no
OldRuntimeError = RuntimeError
class RuntimeError(OldRuntimeError):
def __init__(self, message):
# RPython exception instances don't have .message
self.message = message
class EvaluationError(Exception):
def __init__(self, value, parent=None):
# Actual exception which stops the evaluation loop
self.value = value
self.parent = parent
class EvaluationDone(Exception):
def __init__(self, value):
# Resolved value which stops the evaluation loop
self.value = value
class EvaluationStop(Exception):
def __init__(self, value):
# Exception which stops evalulation of the current file or REPL
self.value = value
def _f_evaluation_stop(env, expr, parent):
raise EvaluationStop(expr)
ROOT_CONT = Continuation(None, PrimitiveOperative(_f_evaluation_stop), None)
def _f_error_cont(env, expr, parent):
if isinstance(expr, Pair):
original_parent = expr.car
if isinstance(original_parent, Continuation):
raise EvaluationError(expr.cdr, original_parent)
raise EvaluationError(expr)
ERROR_CONT = Continuation(None, PrimitiveOperative(_f_error_cont), ROOT_CONT)
def _f_evaluation_done(env, expr, parent):
raise EvaluationDone(expr)
EVALUATION_DONE = PrimitiveOperative(_f_evaluation_done)
# Variable lookup and environment versioning
# We assume that most environments assign the same variables in the same order.
# This lets us optimize local variable lookups to be just an array access. See
# https://pypy.org/posts/2011/03/controlling-tracing-of-interpreter-with_21-6524148550848694588.html
# Also note that we are using symbols themselves as keys, not the name. The
# idea is that different functions which happen to share the same variable
# names shouldn't be handled the same.
# These are placeholder values for a binding's known value.
_INITIAL = Object() # Just initialized
_MUTATED = Object() # Symbol gets assigned different values
class LocalMap(object):
_immutable_fields_ = ("transitions", "symbol", "index", "parent", "known_value?", "cached_attrs")
def __init__(self, symbol, index, parent):
self.transitions = {} # Symbol -> LocalMap
assert symbol is None or isinstance(symbol, Symbol)
self.symbol = symbol
assert isinstance(index, int)
self.index = index
assert parent is None or isinstance(parent, LocalMap)
self.parent = parent
self.known_value = _INITIAL
self.cached_attrs = {}
@jit.elidable
def find(self, name):
assert isinstance(name, bytes)
if name in self.cached_attrs:
return self.cached_attrs[name]
attr = self._find(name)
self.cached_attrs[name] = attr
return attr
def _find(self, name):
if self.symbol is None:
return None
if self.symbol.name == name:
return self
return self.parent._find(name)
@jit.elidable
def new_localmap_with(self, name):
assert isinstance(name, Symbol)
if name not in self.transitions:
new = LocalMap(name, self.index + 1, self)
self.transitions[name] = new
return self.transitions[name]
_ROOT_LOCALMAP = LocalMap(None, -1, None)
@jit.unroll_safe
def _environment_tostoragemap(bindings):
storage = []
localmap = _ROOT_LOCALMAP
if bindings is not None and len(bindings) > 0:
for key, value in bindings.items(): # TODO: should we sort?
# TODO: How to ensure same logic as in _environment_update?
localmap = localmap.new_localmap_with(Symbol(key))
if localmap.known_value is _INITIAL:
localmap.known_value = value
elif localmap.known_value is _MUTATED:
pass
elif localmap.known_value is not value:
localmap.known_value = _MUTATED
storage.append(value)
return storage, localmap
@jit.unroll_safe
def _environment_lookup(env, name):
if not jit.isvirtual(name):
jit.promote(name)
name_name = name.name
if not jit.isvirtual(name_name):
jit.promote_string(name_name)
while env is not None:
# Promote the local map since the combiner calls should be the same,
# hence variable lookups should be on the same lexical environments.
jit.promote(env.localmap)
attr = env.localmap.find(name_name)
if attr is not None:
# If the binding is a constant, return the known value
if attr.known_value is not _INITIAL and attr.known_value is not _MUTATED:
return attr.known_value
return env.storage[attr.index]
env = env.parent
return None
def _environment_update(env, name, value):
if not jit.isvirtual(name):
jit.promote(name)
name_name = name.name
if not jit.isvirtual(name_name):
jit.promote_string(name_name)
attr = env.localmap.find(name_name)
if attr is not None:
# Invalidate traces if the binding differs from the previous constant
if attr.known_value is not _MUTATED and attr.known_value is not value:
attr.known_value = _MUTATED
env.storage[attr.index] = value
else:
attr = env.localmap = env.localmap.new_localmap_with(name)
# Initialize binding's known value, otherwise invalidate if different
if attr.known_value is _INITIAL:
attr.known_value = value
elif attr.known_value is _MUTATED:
pass
elif attr.known_value is not value:
attr.known_value = _MUTATED
env.storage.append(value)
# Specialized environments
class StepWrappedEnvironment(Environment):
_immutable_fields_ = Environment._immutable_fields_ + ("env", "args")
def __init__(self, env, args):
Environment.__init__(self, None, None)
self.env = env
self.args = args
class StepEvCarEnvironment(Environment):
_immutable_fields_ = Environment._immutable_fields_ + ("env", "operative", "num_wraps", "todo", "p", "c", "i", "res")
def __init__(self, env, operative, num_wraps, todo, p, c, i, res):
Environment.__init__(self, None, None)
self.env = env
self.operative = operative
self.num_wraps = num_wraps
self.todo = todo
self.p = p
self.c = c
self.i = i
self.res = res
class FRemoteEvalEnvironment(Environment):
_immutable_fields_ = Environment._immutable_fields_ + ("expression",)
def __init__(self, expression):
Environment.__init__(self, None, None)
self.expression = expression
class FIfEnvironment(Environment):
_immutable_fields_ = Environment._immutable_fields_ + ("env", "then", "orelse")
def __init__(self, env, then, orelse):
Environment.__init__(self, None, None)
self.env = env
self.then = then
self.orelse = orelse
class FDefineEnvironment(Environment):
_immutable_fields_ = Environment._immutable_fields_ + ("env", "name")
def __init__(self, env, name):
Environment.__init__(self, None, None)
self.env = env
self.name = name
class FBindsEnvironment(Environment):
_immutable_fields_ = Environment._immutable_fields_ + ("name",)
def __init__(self, name):
Environment.__init__(self, None, None)
self.name = name
# Core interpreter logic
def _f_toplevel_eval(env, expr):
parent = Continuation(None, EVALUATION_DONE, ROOT_CONT)
parent._call_info = expr
return f_eval(env, expr, parent)
def f_return(parent, obj):
return None, obj, parent
def f_return_loop_constant(parent, obj):
return obj, None, parent
def f_error(parent, value):
# TODO: replace with abnormal pass when guarded continuations implemented
return f_return(ERROR_CONT, MutablePair(parent, value))
def f_eval(env, obj, parent=None):
# Don't let the JIT driver promote virtuals (such as mutable pairs
# constructed at runtime)
if not jit.isconstant(obj):
next_continuation = Continuation(env, _STEP_EVAL, parent)
return f_return(next_continuation, obj)
return obj, env, parent
def _step_eval(env, obj, parent):
return step_evaluate((obj, env, parent))
_STEP_EVAL = PrimitiveOperative(_step_eval)
def step_evaluate(state):
obj, env, parent = state
# Return values should usually not be promoted (red variables) unless they
# are loop constants (green variables).
if obj is None: # normal return
assert env is not None
return parent.operative.call(parent.env, env, parent.parent)
if env is None: # loop constant
assert obj is not None
return parent.operative.call(parent.env, obj, parent.parent)
if isinstance(obj, Symbol):
assert isinstance(env, Environment)
value = _environment_lookup(env, obj)
if value is None:
return f_error(parent, MutablePair(String(b"binding not found"), MutablePair(obj, NIL)))
return f_return(parent, value)
elif isinstance(obj, Pair):
next_env = StepWrappedEnvironment(env, obj.cdr)
next_continuation = Continuation(next_env, _STEP_CALL_WRAPPED, parent)
next_continuation._call_info = obj.car
return f_eval(env, obj.car, next_continuation)
else:
return f_return(parent, obj)
jitdriver = jit.JitDriver(
greens=["expr"],
reds=["env", "continuation"],
is_recursive=True,
)
def fully_evaluate(state):
expr, env, continuation = state
try:
while True:
jitdriver.jit_merge_point(expr=expr, env=env, continuation=continuation)
expr, env, continuation = step_evaluate((expr, env, continuation))
if continuation._should_enter:
jitdriver.can_enter_jit(expr=expr, env=env, continuation=continuation)
except EvaluationDone as e:
return e.value
# TODO: Look into how Pycket does runtime call-graph construction to
# automatically infer loops. See https://doi.org/10.1145/2858949.2784740
def _f_loop_constant(env, expr, parent):
return f_return(parent, INERT)
def _f_loop_head(env, expr, parent):
next_continuation = Continuation(None, _F_LOOP_CONSTANT, parent)
next_continuation._should_enter = True
return f_return_loop_constant(next_continuation, expr)
_F_LOOP_CONSTANT = PrimitiveOperative(_f_loop_constant)
_F_LOOP_HEAD = PrimitiveOperative(_f_loop_head)
@jit.unroll_safe
def _step_call_wrapped(static, combiner, parent):
assert isinstance(static, StepWrappedEnvironment)
env = static.env
args = static.args
if not isinstance(combiner, Combiner):
raise RuntimeError("combiner call car must be combiner")
# Promoting combiners should work in loops since otherwise the loop logic
# would be different each iteration.
if not jit.isvirtual(combiner):
jit.promote(combiner)
jit.promote(combiner.num_wraps)
if not jit.isvirtual(combiner.operative):
jit.promote(combiner.operative)
if combiner.num_wraps == 0 or isinstance(args, Nil):
return f_return(Continuation(env, combiner.operative, parent), args)
# Brent's cycle finding algorithm
x = y = args
step = 1
c = a = 0
while isinstance(x, Pair):
x = x.cdr
c += 1
if x == y: # cycle of length c found
x = y = args
for _ in range(c):
assert isinstance(x, Pair)
x = x.cdr
a = 0
while x != y:
assert isinstance(x, Pair)
assert isinstance(y, Pair)
x = x.cdr
y = y.cdr
a += 1
p = a + c
n = 0
break
if c == step:
step *= 2
y = x
a += c
c = 0
else: # acyclic args
a += c
p = a
c = 0
n = 1 if isinstance(x, Nil) else 0
if c == 0 and n == 0:
raise RuntimeError("applicative call args must be proper list")
assert isinstance(args, Pair)
next_expr = args.car
next_env = StepEvCarEnvironment(env, combiner.operative, combiner.num_wraps, args.cdr, p, c, 0, NIL)
next_continuation = Continuation(next_env, _STEP_CALL_EVCAR, parent)
next_continuation._call_info = next_expr
return f_eval(env, next_expr, next_continuation)
_STEP_CALL_WRAPPED = PrimitiveOperative(_step_call_wrapped)
@jit.unroll_safe
def _step_call_evcar(static, value, parent):
assert isinstance(static, StepEvCarEnvironment)
env = static.env
assert isinstance(env, Environment)
operative = static.operative
assert isinstance(operative, Operative)
num_wraps = static.num_wraps
assert isinstance(num_wraps, int)
todo = static.todo
assert isinstance(todo, Nil) or isinstance(todo, Pair)
p = static.p
assert isinstance(p, int)
c = static.c
assert isinstance(c, int)
i = static.i
assert isinstance(i, int)
res = static.res
assert isinstance(res, Nil) or isinstance(res, Pair)
res = MutablePair(value, res)
i = i + 1
if i == p:
i = 0
num_wraps = num_wraps - 1
if c == 0:
assert isinstance(todo, Nil)
else:
up = todo = MutablePair(NIL, NIL)
for _ in range(c-1): assert isinstance(res, Pair); todo = MutablePair(res.car, todo); res = res.cdr
assert isinstance(res, Pair)
up.car = res.car
up.cdr = todo
res = res.cdr
todo = up
p -= c
for _ in range(p): assert isinstance(res, Pair); todo = MutablePair(res.car, todo); res = res.cdr
assert isinstance(todo, Pair)
if num_wraps == 0:
continuation = Continuation(env, operative, parent)
return f_return(continuation, todo)
assert isinstance(todo, Pair)
next_env = StepEvCarEnvironment(env, operative, num_wraps, todo.cdr, p, c, i, res)
next_expr = todo.car
next_continuation = Continuation(next_env, _STEP_CALL_EVCAR, parent)
next_continuation._call_info = next_expr
return f_eval(env, next_expr, next_continuation)
_STEP_CALL_EVCAR = PrimitiveOperative(_step_call_evcar)
# == Lexing, parsing, and writing logic
if b"" == "": # Python 2
def _c_char_to_len1(char): return char
def _c_len1_to_char(len1): return len1
def _c_char_to_int(char): return ord(char)
def _c_int_to_char(code): return chr(code)
def _c_join_chars(chars): return b"".join(chars)
else: # Python 3+
def _c_char_to_len1(char): return chr(char)
def _c_len1_to_char(len1): return ord(len1)
def _c_char_to_int(char): return char
def _c_int_to_char(code): return code
def _c_join_chars(chars): return bytes(chars)
def _c_str_to_bytes(string): return _c_join_chars([_c_len1_to_char(len1) for len1 in string])
def _c_bytes_to_str(bytes_): return "".join([_c_char_to_len1(char) for char in bytes_])
_TOKEN_PATTERN = re.compile(b"|".join([
br'[()]', # open and close brackets
br'[^ \t\r\n();"]+', # symbol-like tokens
br'"(?:[^"\\\r\n]|\\[^\r\n])*"', # single-line strings
br'[ \t\r]+', # horizontal whitespace
br'\n', # newline (parsed separately to count lines)
br';[^\r\n]*', # single-line comments
]))
def tokenize(text, offsets=None, init_line_no=0, init_char_no=0):
result = []
i = 0
len_text = len(text)
line_no = init_line_no
line_start_i = -init_char_no
while i < len_text:
match = _TOKEN_PATTERN.match(text, i)
if match is None:
raise ParsingError("unknown syntax", line_no, i - line_start_i)
token = match.group()
if token == b"\n":
line_no += 1
line_start_i = i + 1
elif token[0] not in b" \t\r;":
result.append(token)
if offsets is not None:
offsets.append(line_no)
offsets.append(i - line_start_i)
i = match.end()
return result
_STRING_PATTERN = re.compile(b"|".join([
br'[^\\]', # normal characters
br'\\x[a-fA-F0-9][a-fA-F0-9]', # hex escape sequence
br'\\[abtnr"\\]', # common escape sequences
]))
def parse(tokens, offsets=None, locations=None, depth=0, upcons=None):
token = tokens.pop()
assert isinstance(token, bytes)
line_no = offsets.pop() if offsets is not None else -1
char_no = offsets.pop() if offsets is not None else -1
if token == b")":
raise ParsingError("unmatched close bracket", line_no, char_no)
if token == b"(":
expr, _, _ = _parse_elements(
tokens,
offsets=offsets, locations=locations,
depth=depth, upcons=upcons,
line_no=line_no, char_no=char_no,
first_line_no=line_no, first_char_no=char_no,
)
return expr
if token == b".":
raise ParsingError("unexpected dot", line_no, char_no)
if token == b"#t" or token == b"#T":
return TRUE
if token == b"#f" or token == b"#F":
return FALSE
if token.lower() == b"#ignore":
return IGNORE
if token.lower() == b"#inert":
return INERT
if upcons is not None and token.lower()[:4] == b"#up<" and token[-1] == b">"[0]:
try:
j = len(token)-1
assert j >= 4
up = int(token[4:j])
if not 1 <= up <= depth:
raise ValueError
except ValueError:
raise ParsingError("invalid up-reference amount", line_no, char_no)
for i in range(depth-1, -1, -1):
if i in upcons:
break
upcons[i] = MutablePair(NIL, NIL)
return upcons[depth-up]
if token[0] == b'"'[0]:
i = 1
len_token = len(token) - 1
chars = []
while i < len_token:
match = _STRING_PATTERN.match(token, i)
if match is None:
raise ParsingError("unknown string escape", line_no, char_no + i)
part = match.group()
if part[0] != b"\\"[0]:
chars.append(part[0])
elif part[1] == b"x"[0]:
chars.append(_c_int_to_char(int(part[2:4], 16)))
else:
chars.append(b'\a\b\t\n\r"\\'[b'abtnr"\\'.find(part[1])])
i = match.end()
return String(_c_join_chars(chars))
if _c_char_to_len1(token[0]).isdigit() or token[0] in b"+-" and len(token) > 1 and _c_char_to_len1(token[1]).isdigit():
try:
return Int(int(token))
except ValueError:
raise ParsingError("unknown number", line_no, char_no)
if token[0] != b"#"[0]:
symbol = Symbol(token.lower())
if locations is not None:
locations.append((symbol, line_no, char_no, line_no, char_no + len(token)))
return symbol
raise ParsingError("unknown token", line_no, char_no)
def _parse_elements(
tokens,
offsets=None, locations=None,
depth=0, upcons=None,
line_no=-1, char_no=-1,
first_line_no=-1, first_char_no=-1,
):
if not tokens:
raise ParsingError("unmatched open bracket", first_line_no, first_char_no)
token = tokens[-1]
if token == b")":
tokens.pop()
end_line_no = offsets.pop() if offsets is not None else -1
end_char_no = offsets.pop() if offsets is not None else -1
return NIL, end_line_no, end_char_no
if token == b".":
if line_no == first_line_no and char_no == first_char_no:
line_no = offsets[-1] if offsets is not None else -1
char_no = offsets[-2] if offsets is not None else -1
raise ParsingError("missing car element", line_no, char_no)
tokens.pop()
if offsets is not None:
offsets.pop()
offsets.pop()
if not tokens:
raise ParsingError("unmatched open bracket and missing cdr element", first_line_no, first_char_no)
if tokens[-1] == b")":
line_no = offsets[-1] if offsets is not None else -1
char_no = offsets[-2] if offsets is not None else -1
raise ParsingError("unexpected close bracket", line_no, char_no)
element = parse(tokens, offsets=offsets, locations=locations, depth=depth, upcons=upcons)
if not tokens:
raise ParsingError("unmatched open bracket", first_line_no, first_char_no)
end_line_no = offsets.pop() if offsets is not None else -1
end_char_no = offsets.pop() if offsets is not None else -1
if tokens.pop() != b")":
raise ParsingError("expected close bracket", end_line_no, end_char_no)
return element, end_line_no, end_char_no
element = parse(tokens, offsets=offsets, locations=locations, depth=depth+1, upcons=upcons)
if not tokens:
raise ParsingError("unmatched open bracket", first_line_no, first_char_no)
next_line_no = offsets[-1] if offsets is not None else -1
next_char_no = offsets[-2] if offsets is not None else -1
rest, end_line_no, end_char_no = _parse_elements(
tokens,
offsets=offsets, locations=locations,
depth=depth+1, upcons=upcons,
line_no=next_line_no, char_no=next_char_no,
first_line_no=first_line_no, first_char_no=first_char_no,
)
if depth not in upcons:
pair = MutablePair(element, rest)
else:
pair = upcons.pop(depth)
pair.car = element
pair.cdr = rest
if locations is not None:
locations.append((pair, line_no, char_no, end_line_no, end_char_no + 1))
return pair, end_line_no, end_char_no
# Helper class to handle REPL input state
class _InteractiveParser:
def __init__(self):
self.curr_lines = []
self.curr_tokens = []
self.curr_offsets = []
self.curr_exprs = []
self.curr_locations = []
self.last_lines = None
@staticmethod
@objectmodel.specialize.call_location()
def extendleft(a, b):
a.reverse()
a.extend(b)
a.reverse()
def handle(self, line, lines=None, locations=None): # returns done, exprs
if lines is None: lines = []
if locations is None: locations = []
# Add line to history
if line and line[-1] == b"\n"[0]:
self.curr_lines.append(line[:-1])
else:
self.curr_lines.append(line)
try:
# Try to tokenize the line
temp_offsets = []
temp_tokens = tokenize(
line, offsets=temp_offsets,
init_line_no=len(lines)+len(self.curr_lines)-1,
init_char_no=0,
)
self.extendleft(self.curr_tokens, temp_tokens)
self.extendleft(self.curr_offsets, temp_offsets)
# Try to parse the tokens
copy_tokens = self.curr_tokens[:]
copy_offsets = self.curr_offsets[:]
while copy_tokens:
assert copy_offsets
temp_locations = []
temp_expr = parse(
copy_tokens,
offsets=copy_offsets,
locations=temp_locations,
upcons={},
)
self.curr_exprs.append(temp_expr)
self.curr_locations.extend(temp_locations)
del self.curr_tokens[len(copy_tokens):]
del self.curr_offsets[len(copy_offsets):]
except ParsingError as e:
if e.message.startswith("unmatched open bracket"):
# More input is needed
return False, []
# Save lines (for later printing) and clear state
self.last_lines = self.curr_lines[:]
del self.curr_lines[:]
del self.curr_tokens[:]
del self.curr_offsets[:]
del self.curr_exprs[:]
del self.curr_locations[:]
raise
# All tokens were parsed, return expressions
lines.extend(self.curr_lines)
locations.extend(self.curr_locations)
copy_exprs = self.curr_exprs[:]
del self.curr_lines[:]
del self.curr_locations[:]
del self.curr_exprs[:]
return True, copy_exprs
def _prompt_lines(stdin, stdout, prompt_list):
leftover = []
while True:
# Output the prompt if at the start of a line
if not leftover:
stdout.write(prompt_list[0])
stdout.flush()
# Read a chunk of data, usually ends with a newline
part = stdin.readline()
if not part:
if leftover:
yield "".join(leftover)
return
# Split on newlines and yield each line
i = part.find(b"\n")
if i < 0:
leftover.append(part)
else:
leftover.append(part[:i+1])
yield b"".join(leftover)
del leftover[:]
while True:
j = part.find(b"\n", i+1)
if j < 0:
if i+1 < len(part):
leftover.append(part[i+1:])
break
else:
yield part[i+1:j+1]
i = j
def _f_write(file, obj):
_write(file, obj, 0, {})
def _write(file, obj, depth, upcons):
if isinstance(obj, Nil):
file.write(b"()")
elif isinstance(obj, Int):
file.write(b"%d" % (obj.value,))
elif isinstance(obj, String):
file.write(b'"')
for char in obj.value:
code = _c_char_to_int(char)
if char in b'\a\b\t\n\r"\\': # escape sequences
file.write(b"\\")
file.write(_c_join_chars([b'abtnr"\\'[b'\a\b\t\n\r"\\'.find(char)]]))
elif not 32 <= code < 128: # unprintable codes
file.write(b"\\x")
file.write(_c_join_chars([b"0123456789abcdef"[code//16]]))
file.write(_c_join_chars([b"0123456789abcdef"[code%16]]))
else:
file.write(_c_join_chars([char]))
file.write(b'"')
elif isinstance(obj, Symbol):
file.write(obj.name)
elif isinstance(obj, Ignore):
file.write(b"#ignore")
elif isinstance(obj, Inert):
file.write(b"#inert")
elif isinstance(obj, Boolean):
if obj.value:
file.write(b"#t")
else:
file.write(b"#f")
elif isinstance(obj, Pair):
if obj in upcons:
file.write(b"#up<")
file.write(b"%d" % (depth - upcons[obj],))
file.write(b">")
return
stack = []
file.write(b"(")
stack.append(obj)
upcons[obj] = depth
depth += 1
_write(file, obj.car, depth, upcons)
obj_cdr = obj.cdr
while isinstance(obj_cdr, Pair):
if obj_cdr in upcons:
break
obj = obj_cdr
file.write(b" ")
stack.append(obj)
upcons[obj] = depth
depth += 1
_write(file, obj.car, depth, upcons)
obj_cdr = obj.cdr
if not isinstance(obj_cdr, Nil):
file.write(b" . ")
_write(file, obj_cdr, depth, upcons)
while stack:
upcons.pop(stack.pop())
file.write(b")")
elif isinstance(obj, Environment):
file.write(b"#environment")
elif isinstance(obj, Continuation):
file.write(b"#continuation")
elif isinstance(obj, Combiner):
file.write(b"#combiner")
else:
file.write(b"#unknown")
def _f_print_trace(file, continuation):
assert isinstance(continuation, Continuation)
# Output stack trace in reverse order, with recent calls last
frames = []
while continuation is not None:
frames.append(continuation)
continuation = continuation.parent
while frames:
continuation = frames.pop()
# Skip helper frames (part of argument evaluation)
if continuation._call_info is None:
continue
expr = continuation._call_info
loc = LOCATIONS.get(expr)
if loc is None:
# Non-source expressions can be evaluated, usually from eval
file.write(b" in unknown\n")
file.write(b" ")
_f_write(file, expr)
file.write(b"\n")
continue
# Get source location of expression
if loc.start_line_no == loc.end_line_no:
line_info = b"%d" % (loc.start_line_no+1,)
else:
line_info = b"%d:%d" % (loc.start_line_no+1, loc.end_line_no+1)
file.write(b" in %s at %s [%d:%d]\n" % (loc.filename, line_info, loc.start_char_no+1, loc.end_char_no+1))
# TODO: output the actual content of the lines the expression is from