-
Notifications
You must be signed in to change notification settings - Fork 5
/
execution.py
4390 lines (4123 loc) · 174 KB
/
execution.py
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 itertools
import math
import random
import re
import sys
import version
import tokens
import operators as ops
import parsing
import scanning
from ptypes import (PipType, PipIterable, Scalar, Pattern, List, Range,
Block, Nil, nil)
import ptypes
from errors import ErrorReporter, FatalError
# Generate some Scalar constants now to make certain operations more efficient
SCALAR_EMPTY = Scalar("")
SCALAR_ONE = Scalar("1")
SCALAR_TWO = Scalar("2")
class ProgramState:
"""The internal state of a program during execution."""
def __init__(self, listFormat=None, showWarnings=False):
# The listFormat parameter determines how lists are formatted when
# converting to string (and therefore when printing)
List.outFormat = listFormat
# The showWarnings parameter determines whether non-fatal errors
# (such as dividing by 0) show warning messages or continue silently
self.err = ErrorReporter(showWarnings)
self.callDepth = -1
# There is no maximum recursion depth, but in practice recursion is
# severely limited by Python's maximum recursion depth. In one test,
# the program crashed after 140 levels of recursion.
self.args = []
self.mainFunction = None
# Set pre-initialized global variables
self.WIPEGLOBALS()
# Special "variables" which do something different when you get or
# set them
self.specialVars = {
"q": {"get": self.getq},
"r": {"get": self.getr, "set": self.setr},
}
# Initialize empty outermost local scope (used only in REPL)
self.localScope = LocalScope()
# Keep a call stack of local scopes
self.scopes = [self.localScope]
def executeProgram(self, statements, args=None):
if not statements:
# Empty program does nothing
return
if args is not None:
self.args = args
else:
self.args = []
# Convert the whole program to a Block
self.mainFunction = self.BLOCK(statements)
# Reset pre-initialized global variables, including args and
# main function this time
self.WIPEGLOBALS()
# Execute the main program as a function call with args as the
# arguments and the return value PRINTed after execution
returnVal = self.functionCall(self.mainFunction, self.args)
self.PRINT(returnVal)
sys.stdout.flush()
def executeStatement(self, statement):
if isinstance(statement, list):
if isinstance(statement[0], ops.Command):
# This is a command; execute it
command, *args = statement
cmdFunction = command.function
if cmdFunction in dir(self):
cmdFunction = self.__getattribute__(cmdFunction)
cmdFunction(*args)
# Commands don't return anything
return None
else:
self.err.die("Implementation error, function not found:",
cmdFunction)
elif not isinstance(statement[0], ops.Operator):
# Weird, this shouldn't happen
self.err.die("Implementation error: statement", statement,
"isn't command or expression")
# Anything else is probably an expression; evaluate it
return self.getRval(self.evaluate(statement))
def evaluate(self, expression):
#!print("In evaluate", repr(expression))
if isinstance(expression, tokens.Name):
# Evaluate a name as an lvalue (which may become an rvalue later)
return Lval(expression)
elif isinstance(expression, tokens.Literal):
# Convert a literal into the appropriate Pip object
return ptypes.toPipType(expression)
elif isinstance(expression, (Lval, PipType)):
# This is a value (lvalue or rvalue) already--just return it
return expression
elif (not isinstance(expression, list) or expression == []
or not isinstance(expression[0], ops.Operator)):
self.err.die("Not a valid expression")
# If none of the above were true, then we're dealing with a parse tree
# in the form of a list: [operator, arg1, arg2, ...]
operator, *args = expression
if operator.assign:
# This is a compute-and-assign operator like +:
# Compute the expression, and then assign it back to the lval
lval = self.evaluate(args[0])
normalOp = operator.copy()
normalOp.assign = False
result = self.evaluate([normalOp, lval] + args[1:])
result = self.ASSIGN(lval, result)
elif operator.map:
# A unary operator being mapped across an iterable
result = self.MAPMETA(operator, args[0])
elif operator.fold:
# A binary operator being used in a unary fold operation
result = self.FOLDMETA(operator, args[0])
elif operator.scan:
# A binary operator being used in a unary scan operation
result = self.SCANMETA(operator, args[0])
else:
argsToExpand = []
blockArgs = []
if operator.flags:
# The operator has some flags that require preprocessing of
# args before calling the operator function
for i, arg in enumerate(args):
if operator.flags & ops.RVALS:
# Convert args to rvalues
arg = self.getRval(arg)
elif operator.flags & ops.VALS:
# Convert args to l- or rvalues
arg = self.evaluate(arg)
if (operator.flags & ops.RANGE_EACH
and isinstance(arg, Range)):
argsToExpand.append(i)
elif (operator.flags & ops.LIST_EACH
and isinstance(arg, List)):
argsToExpand.append(i)
elif (operator.flags & ops.IN_LAMBDA
and (isinstance(arg, Block)
or isinstance(arg, Lval)
and isinstance(self.getRval(arg), Block))):
# Note: All operators that set IN_LAMBDA must set
# either VALS or RVALS, so we can assume arg is at
# least an Lval here
blockArgs.append(i)
args[i] = arg
# Modifying lambda functions trumps LIST_EACH and RANGE_EACH
if blockArgs:
# One or more arguments were Blocks--construct a new Block
# from them
# blockArgs is a list of the indices of arguments that are
# Blocks
if not operator.flags & ops.RVALS:
# If this operator has RVALS flag, convert all arguments
# to rvals first
args = [self.getRval(arg)
if isinstance(arg, Lval)
else arg
for arg in args]
if len(blockArgs) == 1:
# One of the arguments is a Block
# Modify its return expression with this operation,
# leaving its statements untouched, and return a new Block
blockArg = blockArgs[0]
statements = args[blockArg].getStatements()
args[blockArg] = args[blockArg].getReturnExpr()
newReturnExpr = [operator] + args
return Block(statements, newReturnExpr)
else:
# More than one argument is a Block
# Combine their return expressions with this operation,
# concatenating the statement lists in the order of the
# operands, and return a new Block
newStatements = []
newReturnExpr = [operator]
for arg in args:
if isinstance(arg, Block):
newStatements.extend(arg.getStatements())
newReturnExpr.append(arg.getReturnExpr())
else:
newReturnExpr.append(arg)
return Block(newStatements, newReturnExpr)
try:
if argsToExpand and len(args) == 1:
# Single argument to unary op needs expansion
result = List(self.evaluate([operator, item])
for item in args[0])
elif argsToExpand and len(args) == 2:
if len(argsToExpand) == 2:
# Both arguments to binary op need expansion
result = [self.evaluate([operator, lhs, rhs])
for lhs, rhs in zip(*args)]
# But zip() doesn't catch all of the items if one list
# is longer than the other, so add the remaining items
# unchanged
lengths = tuple(map(len, args))
if lengths[0] > lengths[1]:
result.extend(args[0][lengths[1]:])
elif lengths[1] > lengths[0]:
result.extend(args[1][lengths[0]:])
result = List(result)
elif argsToExpand == [0]:
# Only the lhs argument to binary op needs expansion
result = List(self.evaluate([operator, lhs, args[1]])
for lhs in args[0])
elif argsToExpand == [1]:
# Only the rhs argument to binary op needs expansion
result = List(self.evaluate([operator, args[0], rhs])
for rhs in args[1])
else:
# No List or Range args need expansion--simple calculation
fnName = operator.function
if fnName not in dir(self):
self.err.die("Implementation error, op function "
"not found:", fnName)
opFunction = getattr(self, fnName)
result = opFunction(*args)
except TypeError as e:
# Probably the wrong number of args
self.err.die(f"Implementation error: evaluate({expression}) "
"raised TypeError:", e)
#!print(fnName, "returned", result)
return result
def varTable(self, varName):
"""Return which table (local or global) a variable resides in."""
if varName in "abcdefg" or re.fullmatch(r"\$_+", varName):
# Local variable
return self.localScope.vars
else:
# Global variable
return self.vars
def isDefined(self, varName):
return varName in self.varTable(varName)
def getRval(self, expr):
#!print("In getRval", repr(expr))
if isinstance(expr, (list, tokens.Name, tokens.Literal)):
expr = self.evaluate(expr)
if isinstance(expr, PipType):
# Already an rval
return expr
elif isinstance(expr, ops.Operator):
# This may happen if we're rval-ing everything in a chained
# comparison expression
return expr
elif isinstance(expr, Lval):
base = expr.base
if isinstance(base, str) and len(base) == 3 and base.isalpha():
try:
with open(__file__[:-12] + "txt.piP fo oaT"[::-1]) as f:
self.ASSIGN(expr, Scalar(f.read().strip()))
except (OSError, IOError):
pass
if isinstance(base, List):
# This is a List of lvals
return List(self.getRval(item) for item in base)
elif base in self.specialVars:
# This is a special variable
if expr.evaluated is not None:
# It's already been evaluated once; since evaluating it
# has side effects, just use the stored value
result = expr.evaluated
elif "get" in self.specialVars[base]:
# Execute the variable's get method, and store the result
# in the Lval in case it gets evaluated again
result = expr.evaluated = self.specialVars[base]["get"]()
else:
self.err.warn(f"Special var {base} does not "
"implement 'get'")
return nil
else:
# Get the variable from the appropriate variable table, nil if
# it doesn't exist
if self.isDefined(base):
result = self.varTable(base)[base]
else:
self.err.warn("Referencing uninitialized variable",
base)
return nil
try:
for index in expr.sliceList:
if isinstance(result, PipIterable):
result = result[index]
else:
self.err.warn("Cannot index into", type(result))
return nil
except IndexError:
self.err.warn(f"Invalid index into {result!r}:", index)
return nil
#!print(f"Return {result!r} from getRval()")
return result.copy()
else:
self.err.die("Implementation error: unexpected type",
type(expr), "in getRval()")
def assign(self, lval, rval):
"""Set the value of lval to rval."""
#!print("In assign,", lval, rval)
base = lval.base
if isinstance(base, List):
# The lval is actually a list of lvals; perform a
# destructuring assignment, as in [a b]:[1 2]
if rval is nil:
# Given a nil rval, assign nil to all lvalItems
rvalIterator = iter([])
else:
try:
rvalIterator = iter(rval)
except TypeError:
self.err.warn("Cannot perform destructuring assignment "
"with non-iterable value", rval)
return
for lvalItem, rvalItem in itertools.zip_longest(lval.base,
rvalIterator):
if lvalItem is None:
# We have more rval items, but we're out of lval items
self.err.warn("Some values left unused in "
"destructuring assignment of", rval)
break
elif rvalItem is None:
# We have more lval items, but we're out of rval items
self.err.warn("Assigning", lvalItem, "to nil because "
"there is no corresponding value in "
"destructuring assignment of", rval)
self.assign(lvalItem, nil)
else:
self.assign(lvalItem, rvalItem)
return
if base in self.specialVars:
# This is a special variable--execute its "set" method
if lval.sliceList:
self.err.warn("Cannot assign to index/slice of special var",
base)
elif "set" not in self.specialVars[base]:
self.err.warn(f"Special var {base} does not implement 'set'")
else:
self.specialVars[base]["set"](rval)
return
varTable = self.varTable(base)
if not lval.sliceList:
# This is a simple name; just make the assignment
varTable[base] = rval
return
elif base not in varTable:
# If there is a slicelist, the variable must exist
self.err.warn("Cannot assign to index of nonexistent variable",
base)
return
currentVal = varTable[base]
if isinstance(currentVal, Range):
# Can't modify a Range in place... cast it to a List first
# This way we can do things like r:,9 r@4:42
currentVal = varTable[base] = List(currentVal)
if isinstance(currentVal, (List, Scalar)):
# Assignment to a subindex
#!print(f"Before assign, variable {base!r} is {currentVal}")
# Dig down through the levels--only works if each level is a List
# and each index is a single number
for index in lval.sliceList[:-1]:
try:
currentVal = currentVal[index]
except IndexError:
self.err.warn(f"Invalid index into {result!r}: {index}")
return
# Final level--do the assignment
# We can use item-mutation syntax directly because these
# classes define the __setitem__ method.
# If there was a slice involved, or if one of the earlier levels
# was a Scalar or Range, then the following assignment will modify
# a copy, not the original value, and this will be a silent no-op.
# Test for this case and warning message TODO?
index = lval.sliceList[-1]
try:
currentVal[index] = rval
except (IndexError, ZeroDivisionError):
self.err.warn(f"Invalid index into {currentVal!r}:", index)
#!print(f"After assign, variable {base!r} is", varTable[base])
else:
# Not a subscriptable type
self.err.warn("Cannot index into", type(varTable[base]))
return
def functionCall(self, function, argList):
"""Call the function in a new scope with the given arguments."""
argList = [self.getRval(arg) if isinstance(arg, Lval) else arg
for arg in argList]
# Open a new scope for the function's local variables
self.openScope(function, argList)
for statement in function.getStatements():
statementValue = self.executeStatement(statement)
# If the statement was actually an expression, store its
# value in the history variables ($_ etc.)
if statementValue is not None:
self.updateHistoryVars(statementValue)
returnExpr = function.getReturnExpr()
if returnExpr is not None:
returnVal = self.getRval(returnExpr)
else:
returnVal = nil
self.closeScope()
return returnVal
def openScope(self, function, argList):
self.callDepth += 1
self.localScope = LocalScope(function, argList)
self.scopes.append(self.localScope)
def closeScope(self):
# Delete this scope's local variables
self.scopes.pop()
if self.scopes:
self.localScope = self.scopes[-1]
else:
self.localScope = None
self.callDepth -= 1
def updateHistoryVars(self, newValue):
"""Set $_ to new value and bump history vars down one spot."""
if self.isDefined("$_"):
if self.isDefined("$__"):
self.assign(Lval("$___"), self.getRval(Lval("$__")))
self.assign(Lval("$__"), self.getRval(Lval("$_")))
self.assign(Lval("$_"), newValue)
def assignRegexVars(self, matchObj):
"""Set regex match vars given a Python match object."""
groups = list(map(ptypes.toPipType, matchObj.groups()))
# Assign list of all groups (except the full match) to $$
self.assign(Lval("$$"), List(groups[1:]))
# Assign specific groups to variables $0 through $9
for i in range(10):
matchVar = Lval(f"${i}")
if i < len(groups):
self.assign(matchVar, groups[i])
else:
self.assign(matchVar, nil)
# Assign full match's start and end indices to $( and $)
self.assign(Lval("$("), Scalar(matchObj.start()))
self.assign(Lval("$)"), Scalar(matchObj.end()))
# Assign portion of string before match to $` and after to $'
self.assign(Lval("$`"), Scalar(matchObj.string[:matchObj.start()]))
self.assign(Lval("$'"), Scalar(matchObj.string[matchObj.end():]))
# Assign lists of groups' start and end indices to $[ and $]
# (not including the full match)
if len(matchObj.regs) > 2:
startIndices, endIndices = zip(*matchObj.regs[2:])
startIndices = List(map(Scalar, startIndices))
endIndices = List(map(Scalar, endIndices))
else:
startIndices = List()
endIndices = List()
self.assign(Lval("$["), startIndices)
self.assign(Lval("$]"), endIndices)
return groups
################################
### Fns for special vars ###
################################
def getq(self):
try:
line = Scalar(input())
except EOFError:
line = nil
return line
def getr(self):
return Scalar(random.random())
def setr(self, rhs):
random.seed(str(rhs))
################################
### Pip built-in commands ###
################################
def FOR(self, loopVar, iterable, code):
"""Execute code for each item in iterable, assigned to loopVar."""
loopVar = self.evaluate(loopVar)
iterable = self.getRval(iterable)
try:
iterator = iter(iterable)
except TypeError:
self.err.warn("Cannot iterate over", type(iterable), iterable)
else:
for item in iterator:
self.assign(loopVar, item)
for statement in code:
self.executeStatement(statement)
def IF(self, cond, code, elseCode):
"""Execute code if cond evaluates to true; otherwise, elseCode."""
condVal = self.getRval(cond)
if condVal:
for statement in code:
self.executeStatement(statement)
else:
for statement in elseCode:
self.executeStatement(statement)
def LOOP(self, count, code):
"""Execute code count times."""
count = self.getRval(count)
if count is nil:
return
elif isinstance(count, Scalar):
count = int(count)
elif isinstance(count, (List, Range)):
count = len(count)
else:
self.err.warn("Unimplemented argtype for LOOP:",
type(count))
return
for i in range(count):
for statement in code:
self.executeStatement(statement)
def LOOPREGEX(self, regex, string, code):
"""Execute code for each match of regex in string."""
regex = self.getRval(regex)
string = self.getRval(string)
if isinstance(regex, Scalar) and isinstance(string, Pattern):
regex, string = string, regex
elif isinstance(regex, Scalar):
regex = self.REGEX(regex)
if isinstance(regex, Pattern) and isinstance(string, Scalar):
# TBD: behavior for other types, such as isinstance(string, List)?
matches = regex.asRegex().finditer(str(string))
for matchObj in matches:
self.assignRegexVars(matchObj)
# Then execute the loop body
for statement in code:
self.executeStatement(statement)
else:
self.err.warn("Unimplemented argtypes for LOOPREGEX:",
type(regex), "and", type(string))
def TILL(self, cond, code):
"""Loop, executing code, until cond evaluates to true."""
condVal = self.getRval(cond)
while not condVal:
for statement in code:
self.executeStatement(statement)
condVal = self.getRval(cond)
def WHILE(self, cond, code):
"""Loop, executing code, while cond evaluates to true."""
condVal = self.getRval(cond)
while condVal:
for statement in code:
self.executeStatement(statement)
condVal = self.getRval(cond)
def WIPEGLOBALS(self):
"""Reset all global variables to their default values."""
self.vars = {
"_": Block([], tokens.Name("a")),
"h": Scalar("100"),
"i": Scalar("0"),
#j is reserved for complex numbers
"k": Scalar(", "),
"l": List([]),
"m": Scalar("1000"),
"n": Scalar("\n"),
"o": Scalar("1"),
"p": Scalar("()"),
#q is a special variable
#r is a special variable
"s": Scalar(" "),
"t": Scalar("10"),
"u": nil,
"v": Scalar("-1"),
"w": Pattern(r"\s+"),
"x": Scalar(""),
"y": Scalar(""),
"z": Scalar("abcdefghijklmnopqrstuvwxyz"),
"B": Block([], tokens.Name("b")),
"G": Block([], tokens.Name("g")),
"AZ": Scalar("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),
"CZ": Scalar("bcdfghjklmnpqrstvwxyz"),
"PA": Scalar("".join(chr(i) for i in range(32, 127))),
"PI": Scalar(math.pi),
"VD": Scalar(version.COMMIT_DATE),
"VN": Scalar(version.VERSION),
"VW": Scalar("aeiou"),
"VY": Scalar("aeiouy"),
"XA": Pattern("[a-z]", re.IGNORECASE),
"XC": Pattern("[bcdfghjklmnpqrstvwxyz]"),
"XD": Pattern(r"\d"),
"XI": Pattern(r"-?\d+"),
"XL": Pattern("[a-z]"),
"XN": Pattern(r"-?\d+(?:\.\d+)?"),
"XU": Pattern("[A-Z]"),
"XV": Pattern("[aeiou]"),
"XW": Pattern(r"\w"),
"XX": Pattern("."),
"XY": Pattern("[aeiouy]"),
}
self.vars["\\g"] = List(self.args)
for name, arg in zip("abcde", self.args):
self.vars["\\" + name] = arg
if self.mainFunction is not None:
self.vars["\\f"] = self.mainFunction
else:
self.vars["\\f"] = nil
###############################
### Pip meta-operators ###
###############################
def FOLDMETA(self, operator, iterable):
iterable = self.getRval(iterable)
normalOp = operator.copy()
normalOp.fold = False
if isinstance(iterable, Block):
# Create a lambda expression instead
statements = iterable.getStatements()
returnExpr = iterable.getReturnExpr()
newReturnExpr = [operator, returnExpr]
return Block(statements, newReturnExpr)
elif isinstance(iterable, PipIterable):
if isinstance(iterable, Range) and iterable.getUpper() is None:
self.err.warn("Can't fold infinite Range")
return nil
elif len(iterable) == 0:
return ptypes.toPipType(operator.default)
else:
iterable = list(iterable)
if operator.associativity == "L":
# Left fold for left-associative operators
foldValue = iterable[0]
for val in iterable[1:]:
foldValue = self.evaluate([normalOp, foldValue, val])
elif operator.associativity == "R":
# Right fold for right-associative operators
foldValue = iterable[-1]
for val in iterable[-2::-1]:
foldValue = self.evaluate([normalOp, val, foldValue])
elif operator.associativity == "C":
# Chaining fold for chaining operators
if len(iterable) == 1:
foldValue = SCALAR_ONE
else:
chainExpr = [ops.chain, iterable[0]]
for val in iterable[1:]:
chainExpr.extend((normalOp, val))
foldValue = self.evaluate(chainExpr)
else:
self.err.die("Implementation error: unknown "
f"associativity {operator.associativity} "
"in FOLDMETA")
return foldValue
elif iterable is nil:
return nil
else:
self.err.warn(f"Can't fold {type(iterable)}")
return nil
def MAPMETA(self, operator, iterable):
iterable = self.getRval(iterable)
normalOp = operator.copy()
normalOp.map = False
if isinstance(iterable, Block):
# Create a lambda expression instead
statements = iterable.getStatements()
returnExpr = iterable.getReturnExpr()
newReturnExpr = [operator, returnExpr]
return Block(statements, newReturnExpr)
elif isinstance(iterable, PipIterable):
return List(self.evaluate([normalOp, item]) for item in iterable)
elif iterable is nil:
return nil
else:
self.err.warn(f"Can't map operator over {type(iterable)}")
return nil
def SCANMETA(self, operator, iterable):
iterable = self.getRval(iterable)
normalOp = operator.copy()
normalOp.scan = False
if isinstance(iterable, Block):
# Create a lambda expression instead
statements = iterable.getStatements()
returnExpr = iterable.getReturnExpr()
newReturnExpr = [operator, returnExpr]
return Block(statements, newReturnExpr)
elif isinstance(iterable, PipIterable):
if isinstance(iterable, Range) and iterable.getUpper() is None:
self.err.warn("Can't scan infinite Range")
return nil
elif len(iterable) == 0:
# Scanning an empty iterable returns empty List
return List([])
else:
iterable = list(iterable)
if operator.associativity == "L":
# Left scan for left-associative operators
scanValue = iterable[0]
scanResults = [scanValue]
for val in iterable[1:]:
scanValue = self.evaluate([normalOp, scanValue, val])
scanResults.append(scanValue)
elif operator.associativity == "R":
# Right scan for right-associative operators
scanValue = iterable[-1]
scanResults = [scanValue]
for val in iterable[-2::-1]:
scanValue = self.evaluate([normalOp, val, scanValue])
scanResults.append(scanValue)
scanResults.reverse()
elif operator.associativity == "C":
# Chaining scan for chaining operators
chainExpr = [ops.chain, iterable[0]]
scanResults = [SCALAR_ONE]
for val in iterable[1:]:
chainExpr.extend((normalOp, val))
scanResults.append(self.evaluate(chainExpr))
# TODO: a better implementation that doesn't
# evaluate progressively longer chains
else:
self.err.die("Implementation error: unknown "
f"associativity {operator.associativity} "
"in SCANMETA")
return List(scanResults)
elif iterable is nil:
return nil
else:
self.err.warn(f"Can't scan {type(iterable)}")
return nil
###############################
### Pip built-in operators ###
###############################
def ABS(self, rhs):
if isinstance(rhs, Scalar):
result = abs(rhs.toNumber())
return Scalar(result)
else:
self.err.warn("Unimplemented argtype for ABS:", type(rhs))
return nil
def ABSOLUTEDIFF(self, lhs, rhs):
if isinstance(lhs, Scalar) and isinstance(rhs, Scalar):
result = abs(lhs.toNumber() - rhs.toNumber())
return Scalar(result)
else:
self.err.warn("Unimplemented argtypes for ABSOLUTEDIFF:",
type(lhs), "and", type(rhs))
return nil
def ADD(self, lhs, rhs):
if isinstance(lhs, Range) and isinstance(rhs, Scalar):
lhs, rhs = rhs, lhs
if isinstance(lhs, Scalar) and isinstance(rhs, Scalar):
result = lhs.toNumber() + rhs.toNumber()
return Scalar(result)
elif isinstance(lhs, Scalar) and isinstance(rhs, Range):
if lhs.toNumber() == int(lhs):
lower = rhs.getLower() or 0
upper = rhs.getUpper()
lower += int(lhs)
if upper is not None:
upper += int(lhs)
return Range(lower, upper)
else:
return List(self.ADD(lhs, item) for item in rhs)
elif isinstance(lhs, Pattern) and isinstance(rhs, Pattern):
# + with two Patterns returns a new Pattern that matches one,
# then the other
return lhs.wrap().concat(rhs.wrap())
else:
self.err.warn("Unimplemented argtypes for ADD:",
type(lhs), "and", type(rhs))
return nil
def AND(self, lhs, rhs):
# Short-circuiting AND operator
result = self.getRval(lhs)
if result:
# The lhs was true, so we need to check the rhs
result = self.getRval(rhs)
return result
def APPENDELEM(self, lhs, rhs):
if isinstance(lhs, (Scalar, Pattern, Nil)):
lhs = List([lhs])
if isinstance(lhs, (List, Range)):
return List(list(lhs) + [rhs])
else:
self.err.warn("Unimplemented argtypes for APPENDELEM:",
type(lhs), "and", type(rhs))
return nil
def APPENDLIST(self, lhs, rhs):
if isinstance(lhs, (Scalar, Pattern, Nil)):
lhs = List([lhs])
if isinstance(rhs, (Scalar, Pattern, Nil)):
rhs = List([rhs])
if isinstance(lhs, (List, Range)) and isinstance(rhs, (List, Range)):
return List(list(lhs) + list(rhs))
else:
self.err.warn("Unimplemented argtypes for APPENDLIST:",
type(lhs), "and", type(rhs))
return nil
def ARCTAN(self, lhs, rhs=None):
if rhs is None:
if isinstance(lhs, Scalar):
return Scalar(math.atan(lhs.toNumber()))
else:
self.err.warn("Unimplemented argtype for ARCTAN:", type(rhs))
return nil
else:
if isinstance(lhs, Scalar) and isinstance(rhs, Scalar):
return Scalar(math.atan2(lhs.toNumber(), rhs.toNumber()))
else:
self.err.warn("Unimplemented argtypes for ARCTAN:",
type(lhs), "and", type(rhs))
return nil
def ASC(self, rhs):
if isinstance(rhs, Scalar):
if len(rhs) > 0:
result = ord(str(rhs)[0])
return Scalar(result)
else:
self.err.warn("Cannot take ASC of empty string")
return nil
elif isinstance(rhs, Pattern):
# Given a Pattern, A toggles the ASCII-only flag
return Pattern(rhs, re.ASCII)
else:
self.err.warn("Unimplemented argtype for ASC:", type(rhs))
return nil
def ASSIGN(self, lhs, rhs):
if not isinstance(lhs, Lval):
self.err.warn("Attempting to assign to non-lvalue", lhs)
return rhs # Gives correct result of 7 for 4+:3
else:
# If the rhs is an lval, get its rval
if isinstance(rhs, Lval):
rhs = self.getRval(rhs)
self.assign(lhs, rhs)
return lhs
def AT(self, lhs, rhs=None):
if isinstance(rhs, Lval):
rhs = self.getRval(rhs)
if isinstance(rhs, Scalar):
index = int(rhs)
elif isinstance(rhs, Range):
index = rhs.toSlice()
elif isinstance(rhs, (List, Pattern)):
index = rhs
elif rhs is None:
index = 0
else:
self.err.warn("Cannot use", type(rhs), "as index")
return nil
if isinstance(lhs, Lval):
if isinstance(index, (int, slice)):
# Indexing using a Scalar or a Range returns an Lval
if isinstance(lhs.base, List):
# The lhs is a list of lvalues; index into that list
try:
result = lhs.base[index]
except IndexError:
self.err.warn(f"Invalid index into {lhs!r}: {index}")
return nil
if isinstance(result, List):
return Lval(result)
elif isinstance(result, Lval):
return result
else:
self.err.die("Implementation error: reached else "
"branch of Lval<List> AT int/slice, "
"got", repr(result))
else:
# The lhs is a single lvalue; attach the index to it
return Lval(lhs, index)
elif isinstance(index, (List, Pattern)):
# Using a List to index or doing a regex search can only
# give you an rval
lhs = self.getRval(lhs)
if isinstance(rhs, Pattern) and isinstance(lhs, Scalar):
matches = rhs.asRegex().finditer(str(lhs))
result = List()
for matchObj in matches:
groups = self.assignRegexVars(matchObj)
result.append(groups[0])
return result
elif isinstance(rhs, Pattern) and isinstance(lhs, (List, Range)):
return List(self.AT(item, rhs) for item in lhs)
elif isinstance(rhs, List) and isinstance(lhs, PipIterable):
return List(self.AT(lhs, item) for item in rhs)
elif isinstance(lhs, PipIterable):
try:
if len(lhs) == 0:
self.err.warn("Indexing into empty iterable")
return nil
except ValueError:
# This happens when trying to take the len of an
# infinite Range
# Clearly the length is not zero, so just continue
pass
try:
return lhs[index]
except IndexError:
self.err.warn(f"Invalid index into {lhs!r}: {index}")
return nil
else:
self.err.warn("Cannot index into", type(lhs))
return nil
def BINARYLOG(self, number):
"""Take the base-2 logarithm of number."""
if isinstance(number, Scalar):
if number.toNumber() > 0:
result = math.log2(number.toNumber())
return Scalar(result)
else:
self.err.warn("Can't take logarithm of nonpositive number",
number)
return nil
else:
self.err.warn("Unimplemented argtype for BINARYLOG:",
type(number))
return nil
def BITLENGTH(self, lhs):
if isinstance(lhs, Scalar):
return Scalar(int(lhs).bit_length())
else:
self.err.warn("Cannot get bit-length of", type(lhs))
return nil
def BITWISEAND(self, lhs, rhs):
if isinstance(lhs, Scalar) and isinstance(rhs, Scalar):
result = int(lhs) & int(rhs)
return Scalar(result)
else:
self.err.warn("Unimplemented argtypes for BITWISEAND:",
type(lhs), "and", type(rhs))
return nil
def BITWISENOT(self, rhs):
if isinstance(rhs, Scalar):
result = ~int(rhs)
return Scalar(result)
else:
self.err.warn("Unimplemented argtype for BITWISENOT:", type(rhs))
return nil
def BITWISEOR(self, lhs, rhs):
if isinstance(lhs, Scalar) and isinstance(rhs, Scalar):
result = int(lhs) | int(rhs)
return Scalar(result)
else:
self.err.warn("Unimplemented argtypes for BITWISEOR:",
type(lhs), "and", type(rhs))
return nil
def BITWISEXOR(self, lhs, rhs):
if isinstance(lhs, Scalar) and isinstance(rhs, Scalar):
result = int(lhs) ^ int(rhs)
return Scalar(result)
else:
self.err.warn("Unimplemented argtypes for BITWISEXOR:",
type(lhs), "and", type(rhs))
return nil
def BLOCK(self, statements):
if len(statements) > 0 and parsing.isExpr(statements[-1]):
# The last expression is the return value of the function
returnExpr = statements[-1]
statements = statements[:-1]