-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patheval.py
More file actions
1271 lines (1143 loc) · 35.3 KB
/
eval.py
File metadata and controls
1271 lines (1143 loc) · 35.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
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 2009, 2010 Klaus Weidner <klausw@google.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import logging
import random
import re
import sys
# Expression evaluator
#
# Intent is to have intuitive behavior, and lightweight syntax that doesn't
# intrude too much on narrative text that is mixed with the expressions.
#
# Symbol names may contain whitespace and apostrophes, this makes parsing
# a bit more complicated.
#
# Expr: Object (Whitespace* '+' Whitespace* Object)*
# Object: Func '(' Expr ')' | Dice | Symbol | Number
# Func: Number 'x' | 'max'
# DieRoll: Number 'd' Number ('b' Number)?
OBJECT_RE = re.compile(ur'''
(?:
\(
(?P<parexpr> .* )
\)
) |
(?:
(?P<func>
[\w\u0080-\uffff]+
)
\(
(?P<fexpr> .* )
\)
) |
(?:
(?P<fpipe>
[\w\u0080-\uffff]+
)
\s*
\$ # func $ arg
\s*
(?P<fpinput>
.*
)
) |
(?P<dice>
(?P<num_dice> \d* )
d
(?P<sides> \d+ )
(?: b (?P<limit> \d+ ) )?
) |
(?P<symbol>
[\w\u0080-\uffff]*
[_A-Za-z\u0080-\uffff]
[\w\u0080-\uffff']*
(?:
\s+
[\w\u0080-\uffff]*
[_A-Za-z\u0080-\uffff]
[\w\u0080-\uffff']*
)*
) |
(?P<number>
-?\d+
) |
"(?P<string>
[^"]*
)"
''', re.X | re.I)
NUMBER_RE = re.compile(r'\d+')
INTERPOLATE_RE = re.compile(r'\{([^}]*)\}')
OP_RE = re.compile(r'''
\s*
( \-
| \+
| \<=
| \<
| \>=
| \>
| \!=
| ==
| \*
| \/
| ,
)? \s*
''', re.X)
OP_PRECEDENCE = {
'*': 2,
'/': 2,
'+': 1,
'-': 1,
# rest has prio zero
',': -1,
}
class SymRef(object):
def __init__(self, target):
self.target = target
def LookupSym(name, sym):
ret = sym.get(name, None)
expansions = [name]
while isinstance(ret, SymRef):
expansions.append(ret.target)
if ret.target in expansions[:-1]:
raise ParseError('Recursive symbol expansion %s' % repr(expansions))
ret = sym.get(ret.target, None)
return ret
class ParseError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
MAX_ROLLS=2000
MAX_OBJECTS = 900 # <1000, or Python breaks first on recursion
DEBUG_PARSER = False
def setDebug(flag):
global DEBUG_PARSER
DEBUG_PARSER = flag
if flag:
logging.getLogger().setLevel(logging.DEBUG)
class Result(object):
def __init__(self, value, detail, flags, is_constant=True, is_numeric=True):
self._value = value
self._detail = detail
self._is_numeric = is_numeric
self.is_constant = is_constant
self.is_list = False
self.is_multivalue = False
self.stats = None
if is_constant:
self.constant_sum = value
else:
self.constant_sum = 0
self.flags = flags
def value(self):
return self._value
def has_detail(self):
return self._detail
def detail(self, additional=''):
maybe_constant = ''
if self.constant_sum != 0:
maybe_constant = '+' + str(self.constant_sum) # digits
if not self.has_detail():
return ''
return (self._detail + additional + maybe_constant).replace('--','').replace('+-', '-')
def detailvalue(self):
maybe_detail = self.detail()
maybe_value = self.publicval()
if maybe_detail and maybe_value:
return '%s=%s' % (maybe_detail, maybe_value)
else:
return maybe_detail + maybe_value
def detail_paren(self):
if self.has_detail():
return '(%s)' % self.detail()
else:
return '%s' % self.value()
def is_numeric(self):
return self._is_numeric
def show_as_list(self):
return False
def publicval(self):
maybe_value = []
if self.is_numeric():
maybe_value = [str(self.value())]
return ':'.join(maybe_value + sorted(self.flags.keys()))
def secretval(self):
if 'Nat20' in self.flags:
return 'Nat20'
else:
return self.publicval()
def __str__(self):
return self.detail() + '=' + self.publicval()
def __repr__(self):
def notFalse(desc, x):
if x:
return ', ' + desc + repr(x)
else:
return ''
return '%s(%s%s%s%s%s%s)' % (self.__class__.__name__, self._value,
notFalse('flags=', self.flags.keys()),
notFalse('constant_sum=', self.constant_sum),
notFalse('detail=', self._detail),
{True: ", const", False: ""}[self.is_constant],
{True: ", num", False: ""}[self.is_numeric()])
class ResultDie(Result):
def __init__(self, roll, detail):
Result.__init__(self, roll, detail, {}, is_constant=False)
def detailvalue(self):
maybe_detail = self.detail()
if maybe_detail:
return maybe_detail
else:
return self.publicval()
class ResultList(Result):
def __init__(self, items, detail=''):
Result.__init__(self, 0, map(lambda x: x.detail(), items), {})
self._items = items
self._detail = detail
self._delim = ', '
self.is_list = True
def show_as_list(self):
return True
def to_scalar(self):
return Result(self.value(), self.detail(), self.flags, is_constant=False, is_numeric=True)
def items(self):
return self._items
def value(self):
return self._value + sum([x.value() for x in self._items])
def is_numeric(self):
return any([x.is_numeric() for x in self._items])
def has_detail(self):
return True
def detail(self):
return Result.detail(self, '(%s)' % self._delim.join([x.detailvalue() for x in self._items]))
def __repr__(self):
return Result.__repr__(self) + ': ' + ', '.join([x.__repr__() for x in self._items])
class ResultMultiValue(ResultList):
def __init__(self, items):
ResultList.__init__(self, items)
self.is_multivalue = True
class ResultDice(ResultList):
def __init__(self, items, detail='', flags=None):
ResultList.__init__(self, items, detail)
self.is_constant = False
self._delim = ','
if flags is not None:
self.flags = flags
def show_as_list(self):
return False
def detail_paren(self):
return self.detail()
def detail(self):
return Result.detail(self, '(%s)' % self._delim.join([x.detailvalue() for x in self._items]))
class ResultPool(ResultList):
def __init__(self, items, detail=''):
ResultList.__init__(self, items, detail)
self.is_constant = False
def show_as_list(self):
return False
def detail_paren(self):
return self.detail()
def value(self):
return 0
def is_numeric(self):
return False
def detail(self):
results = {}
for item in self._items:
val = item.value()
results[val] = results.get(val, 0)+1
out = []
for val in reversed(sorted(results.keys())):
count = results[val]
if count == 1:
out.append(str(val))
else:
out.append('%dx%d' % (count, val))
return Result.detail(self, '(%s)' % self._delim.join(out))
def never(x):
return False
def RollDice(num_dice, sides, env):
if sides <= 0:
return Result(0, '', {})
reroll_if = env.get('reroll_if', never)
result = 0
flags={}
dice = [] # results for each roll
details = [] # ascii details for each roll
for i in xrange(num_dice):
rolls = []
this_die = 0
while True:
env['stats']['rolls'] += 1
if env['stats']['rolls'] > MAX_ROLLS:
raise ParseError('Max number of die rolls exceeded')
if 'max' in env:
this_die = sides
rolls.append(this_die)
break
elif 'avg' in env:
if reroll_if != never:
total = 0.0
valid = 0
for i in xrange(1, sides+1):
if not reroll_if(i):
total += i
valid += 1
this_die = total / valid
else:
this_die = (sides + 1) / 2.0
if 'explode' in env:
if reroll_if != never:
flags['NotImplemented'] = True
this_die *= sides / (sides - 1.0)
rolls.append(this_die)
break
else:
roll = random.randint(1, sides)
rolls.append(roll)
if 'explode' in env:
this_die += roll
if roll < sides:
break
elif not(reroll_if(roll)):
this_die = roll
break
# Collect results for one component die roll
dice.append(this_die)
this_detail = ''
die_str = str(this_die)
if 'explode' in env and len(rolls) > 1:
this_detail = die_str + '!' * (len(rolls)-1)
elif len(rolls) > 1:
this_detail = '\\'.join(map(str, rolls))
if 'max' in env or 'avg' in env:
this_detail = '=' + die_str
details.append(this_detail)
else:
result = sum(dice)
# Special cases for D&D-style d20 rolls
if sides==20 and num_dice==1:
if 'opt_nat20' in env and result==20:
flags['Nat20'] = True
if 'opt_crit_notify' in env and result >= env['opt_crit_notify']:
flags['Critical'] = True
top_detail = '%sd%d' % (
{1:''}.get(num_dice, str(num_dice)),
sides)
return ResultDice([ResultDie(x, d) for x, d in zip(dice, details)], top_detail, flags)
N_TIMES_RE = re.compile(r'(\d+) x', re.X)
def DynEnv(env, key, val):
# shallow copy, so that stats remains shared
env_copy = env.copy()
env_copy[key] = val
return env_copy
def Val(expr, sym, env):
return ParseExpr(expr, sym, env).value()
def fn_repeat(sym, env, num, fexpr):
ntimes = ParseExpr(num, sym, env).value()
if ntimes <= 0:
raise ParseError("repeat: repeat count must be >0")
out = []
for i in xrange(ntimes):
new_env = {
'_': Result(0, '', {'#'+str(i+1): True}),
'_i': i,
'_n': ntimes}
out.append(eval_with(sym, env, new_env, fexpr))
return ResultList(out)
def map_setup(sym, env, fexpr, list):
if len(list) == 0:
args, unused_rest = first_paren_expr(fexpr)
if len(args) <= 2:
raise ParseError("map: need a list or multiple arguments")
fexpr = args[0]
list = args[1:]
if len(list) == 1:
val = ParseExpr(list[0], sym, env)
if val.is_list:
all = val._items
else:
all = [val]
else:
all = [ParseExpr(x, sym, env) for x in list]
return fexpr, all
def fn_map(sym, env, fexpr, *list):
fexpr, all = map_setup(sym, env, fexpr, list)
if not '_' in fexpr:
fexpr = '(%s)+_' % fexpr
out = []
for i, item in enumerate(all):
new_env = {
'_': item,
'_i': i,
'_n': len(all)}
out.append(eval_with(sym, env, new_env, fexpr))
return ResultList(out)
def fn_filter(sym, env, fexpr, *list):
fexpr, all = map_setup(sym, env, fexpr, list)
if not '_' in fexpr:
# assume it's a predicate
fexpr = '_ %s' % fexpr
out = []
for i, item in enumerate(all):
new_env = {
'_': item,
'_i': i,
'_n': len(all)}
if eval_with(sym, env, new_env, fexpr).value():
out.append(item)
return ResultList(out)
def fn_max(sym, env, *args):
if len(args) == 1:
return ParseExpr(args[0], sym, DynEnv(env, 'max', True))
else:
max = None
for arg in args:
val = ParseExpr(arg, sym, env).value()
if max is None or val > max:
max = val
return Result(max, [], {})
def fn_min(sym, env, *args):
if len(args) <= 1:
raise ParseError('min() needs at least two args.')
else:
min = None
for arg in args:
val = ParseExpr(arg, sym, env).value()
if min is None or val < min:
min = val
return Result(min, [], {})
def fn_avg(sym, env, fexpr):
return ParseExpr(fexpr, sym, DynEnv(env, 'avg', True))
def fn_mul(sym, env, mul_a, mul_b):
val_a = ParseExpr(mul_a, sym, env)
val_b = ParseExpr(mul_b, sym, env)
mul_flags = val_a.flags
mul_flags.update(val_b.flags)
mul_val = val_a.value() * val_b.value()
if val_a.is_constant and val_b.is_constant:
mul_detail = ''
else:
mul_detail = '%s*%s' % (val_a.detail_paren(), val_b.detail_paren())
return Result(mul_val, mul_detail, mul_flags,
is_constant=(val_a.is_constant and val_b.is_constant))
def fn_div(sym, env, numer, denom):
numval = ParseExpr(numer, sym, env)
denval = ParseExpr(denom, sym, env)
div_flags = numval.flags
div_flags.update(denval.flags)
if denval.value() == 0:
div_val = 0
div_flags['DivideByZero'] = True
else:
div_val = int(numval.value()) / int(denval.value())
if numval.is_constant and denval.is_constant:
div_detail = ''
else:
div_detail = '%s/%s' % (numval.detail_paren(), denval.detail_paren())
return Result(div_val, div_detail, div_flags,
is_constant=(numval.is_constant and denval.is_constant),
is_numeric=(denval.value() != 0))
def fn_bonus(sym, env, fexpr):
bonus_res = ParseExpr(fexpr, sym, env)
return Result(bonus_res.constant_sum, '', {})
def fn_d(sym, env, num_dice, sides):
return RollDice(Val(num_dice, sym, env), Val(sides, sym, env), env)
def fn_explode(sym, env, fexpr):
return ParseExpr(fexpr, sym, DynEnv(env, 'explode', True))
def details_highlight(ret, all):
for item in all._items:
if item.value() == ret.value():
item._detail = '=>' + item._detail
break
detail = '(%s)' % all.detail()
return Result(ret.value(), detail, {}, is_constant=False)
def fn_high(sym, env, fexpr):
return fn_top(sym, env, '1', fexpr)
def fn_low(sym, env, fexpr):
return fn_bottom(sym, env, '1', fexpr)
def fn_sort(sym, env, fexpr):
all = ParseExpr(fexpr, sym, env)
if not all.is_list:
raise ParseError('sort(%s): arg is not a list or dice roll' % fexpr)
all._items = sorted(all._items, key=lambda x: x.value())
return all
def fn_rsort(sym, env, fexpr):
all = ParseExpr(fexpr, sym, env)
if not all.is_list:
raise ParseError('rsort(%s): arg is not a list or dice roll' % fexpr)
all._items = sorted(all._items, key=lambda x: x.value(), reverse=True)
return all
def fn_len(sym, env, fexpr):
all = ParseExpr(fexpr, sym, env)
if not all.is_list:
raise ParseError('len(%s): arg is not a list or dice roll' % fexpr)
ret = 0
for item in all.items():
if item.is_numeric() or item.publicval():
ret += 1
return Result(ret, '', {})
def filter_list(list, pred):
all = copy.deepcopy(list)
for i, old in enumerate(all._items):
if pred(i, old):
continue
new = copy.deepcopy(RESULT_NIL)
#maybe_detail = ''
#if old.has_detail():
# maybe_detail = '%s=' % old.detail()
#new._detail = '/*%s%s*/' % (maybe_detail, old.value())
new._detail = '/*%s*/' % (old.detailvalue())
all._items[i] = new
return all
def fn_pick(sym, env, filter, fexpr):
all = ParseExpr(fexpr, sym, env)
if not all.is_list:
raise ParseError('pick(%s): arg is not a list or dice roll' % fexpr)
pred = predicate(sym, env, filter)
return filter_list(all, lambda i, item: pred(item))
def fn_slice(sym, env, fexpr, start_expr, end_expr=None):
all = ParseExpr(fexpr, sym, env)
if not all.is_list:
raise ParseError('slice(%s): arg is not a list or dice roll' % fexpr)
num = len(all._items)
start = ParseExpr(start_expr, sym, env).value()
if end_expr is None:
if start >= 0:
end = start
start = 0
else:
end = num
else:
end = ParseExpr(end_expr, sym, env).value()
if start < 0:
start = num + start
if end < 0:
end = num + end
if start < 0 or start > num or end < 0 or end > num:
raise ParseError('slice: index out of range')
return filter_list(all, lambda i, item: i>= start and i < end)
def fn_top(sym, env, num, fexpr):
all = fn_sort(sym, env, fexpr)
return fn_slice(sym, env, all, - ParseExpr(num, sym, env).value())
def fn_bottom(sym, env, num, fexpr):
all = fn_sort(sym, env, fexpr)
return fn_slice(sym, env, all, ParseExpr(num, sym, env).value())
RELOPS = {
'==': lambda x, y: x.value() == y.value() and x.publicval() == y.publicval(),
'!=': lambda x, y: x.value() != y.value() or x.publicval() != y.publicval(),
'<': lambda x, y: x.value() < y.value(),
'<=': lambda x, y: x.value() <= y.value(),
'>': lambda x, y: x.value() > y.value(),
'>=': lambda x, y: x.value() >= y.value(),
}
RELOP_RE = re.compile(r'\s* ([=<>!]+) \s*', re.X)
def relation(sym, env, expr):
m = RELOP_RE.search(expr)
if not m:
raise ParseError('"%s" is not a valid filter')
op = RELOPS.get(m.group(1))
if not op:
raise ParseError('"%s" is not a valid filter')
return expr[:m.start()].strip(), op, expr[m.end():].strip()
def predicate(sym, env, expr):
lhs, op, rhs = relation(sym, env, expr)
#logging.debug('rhs=%s', rhs)
if lhs:
raise ParseError('Bad predicate, unexpected "%s"' % lhs)
thresh = ParseExpr(rhs, sym, env)
return lambda x: op(x, thresh)
def fn_reroll_if(sym, env, filter, fexpr):
pred = predicate(sym, env, filter)
return ParseExpr(fexpr, sym, DynEnv(env, 'reroll_if', pred))
def fn_count(sym, env, filter, fexpr=None):
if fexpr is None:
pred = lambda x: x.is_numeric() or x.publicval()
fexpr = filter
else:
pred = predicate(sym, env, filter)
val = ParseExpr(fexpr, sym, env)
if not val.is_list:
raise ParseError('cannot count non-list "%s"' % fexpr)
ret = 0
for item in val.items():
if pred(item):
ret += 1
return Result(ret, val.detail(), val.flags, is_constant=False)
#return ParseExpr(fexpr, sym, DynEnv(env, 'count', pred))
RESULT_TRUE = Result(1, '', {}, is_numeric=False)
RESULT_FALSE = Result(0, '', {}, is_numeric=False)
RESULT_NIL = Result(0, '', {}, is_numeric=False)
def boolean(sym, env, cond):
return ParseExpr(cond, sym, env).value()
def fn_if(sym, env, cond, iftrue, iffalse):
if boolean(sym, env, cond):
return ParseExpr(iftrue, sym, env)
else:
return ParseExpr(iffalse, sym, env)
def fn_cond(sym, env, *args):
nargs = len(args)
for i in xrange(0, len(args), 2):
if i == nargs-1:
# lonely leftover arg, treat as default value
return ParseExpr(args[i], sym, env)
cond = args[i]
arg = args[i+1]
if boolean(sym, env, cond):
return ParseExpr(arg, sym, env)
return RESULT_NIL
def fn_and(sym, env, *args):
for arg in args:
if not boolean(sym, env, arg):
return RESULT_FALSE
return RESULT_TRUE
def fn_or(sym, env, *args):
for arg in args:
if boolean(sym, env, arg):
return RESULT_TRUE
return RESULT_FALSE
def fn_not(sym, env, arg):
if boolean(sym, env, arg):
return RESULT_FALSE
return RESULT_TRUE
BINDING_SPLIT_RE = re.compile(r'(.*?)(==|=)(.*)')
def fn_with(sym, env, *args):
if len(args) < 2:
raise ParseError('with() needs at least two arguments')
bindings = args[:-1]
expr = args[-1]
new_env = {}
for binding in bindings:
m = BINDING_SPLIT_RE.match(binding)
if m is None:
raise ParseError('Binding term "%s" in "with(%s)" does not contain "="' % (binding.strip(), ', '.join([x.strip() for x in args])))
lhs, op, rhs = m.groups()
lhs = lhs.strip()
rhs = rhs.strip()
if op == '==':
# bind symbol synonym
rhs_val = SymRef(rhs)
if not rhs_val:
raise ParseError('"%s" is not a symbol, did you mean = instead of == in "%s"?' % (rhs, binding))
else:
#symval = sym.get(rhs)
#if symval:
# if isinstance(symval, Function) or isinstance(symval, basestring):
# env['warnings'].append('use of %s to bind a symbol, did you mean == in "%s"?' % (op, binding))
rhs_val = ParseExpr(rhs, sym, env)
new_env[lhs] = rhs_val
return eval_with(sym, env, new_env, expr)
def fn_val(sym, env, expr):
return Result(ParseExpr(expr, sym, env).value(), '', {})
def fn_lval(sym, env, expr):
arg = ParseExpr(expr, sym, env)
if not arg.is_list:
raise ParseError('lval(%s): arg is not a list or dice roll' % expr)
return ResultList([x for x in arg.items() if x.is_numeric()])
def fn_sval(sym, env, expr):
arg = ParseExpr(expr, sym, env)
return Result(0, '', arg.flags, is_numeric=False)
def fn_list(sym, env, *args):
items = []
for arg in args:
items.append(ParseExpr(arg, sym, env))
return ResultList(items)
def fn_append(sym, env, listarg, *args):
list = ParseExpr(listarg, sym, env)
if not list.is_list:
raise ParseError('append(%s): first arg is not a list or dice roll' % listarg)
items = copy.deepcopy(list.items())
for arg in args:
items.append(ParseExpr(arg, sym, env))
return ResultList(items)
def fn_concat(sym, env, *args):
all_dice = True
details = []
items = []
for arg in args:
lval = ParseExpr(arg, sym, env)
if isinstance(lval, ResultDice):
details.append(lval._detail)
else:
all_dice = False
if lval.is_list:
items += lval.items()
else:
items.append(lval)
all_dice = False
if all_dice:
return ResultDice(items, ','.join(details))
else:
return ResultList(items)
def fn_pool(sym, env, *args):
ret = fn_concat(sym, env, *args)
return ResultPool(ret.items(), ret._detail)
def fn_nth(sym, env, numexpr, expr):
num = ParseExpr(numexpr, sym, env).value()
arg = ParseExpr(expr, sym, env)
if not arg.is_list:
raise ParseError('nth(%s): arg is not a list or dice roll' % expr)
try:
return arg.items()[num]
except IndexError, e:
raise ParseError("nth(%s, %s): bad index %s, must be 0..%d" %(numexpr, expr, num, len(arg.items())-1))
def fn_range(sym, env, e1, e2=None, e3=None):
args = [ParseExpr(e1, sym, env).value()]
if e2:
args.append(ParseExpr(e2, sym, env).value())
if e3:
args.append(ParseExpr(e3, sym, env).value())
rg = range(*args)
values = [Result(x, '', {}, is_constant=True) for x in rg]
return ResultList(values)
def fn_flag(sym, env, expr, name):
val = ParseExpr(expr, sym, env)
name = name.strip().replace('"', '')
if name in val.flags or '"' + name + '"' in val.flags:
return RESULT_TRUE
else:
return RESULT_FALSE
def fn_conflicttest(sym, env, expr):
return Result(42, 'builtin', {})
FUNCTIONS = {
'max': fn_max,
'min': fn_min,
'avg': fn_avg,
'mul': fn_mul,
'div': fn_div,
'bonus': fn_bonus,
'repeat': fn_repeat, # binds _ and _i
'd': fn_d,
'explode': fn_explode,
'count': fn_count,
'len': fn_len,
'slice': fn_slice,
'pick': fn_pick,
'sort': fn_sort,
'rsort': fn_rsort,
'high': fn_high,
'low': fn_low,
'top': fn_top,
'bottom': fn_bottom,
'if': fn_if,
'or': fn_or,
'and': fn_and,
'not': fn_not,
'with': fn_with,
'val': fn_val,
'cond': fn_cond,
'lval': fn_lval,
'sval': fn_sval,
'flag': fn_flag,
'nth': fn_nth,
'map': fn_map, # binds _ and _i
'filter': fn_filter, # binds _ and _i, takes a boolean expr
'list': fn_list,
'append': fn_append,
'concat': fn_concat,
'pool': fn_pool,
### undocumented
'reroll_if': fn_reroll_if,
#'range': fn_range, # needs sanity check for ranges!
### intentionally undocumented
'conflicttest': fn_conflicttest,
### new, document!
# func $ args
### planned:
# flagged
}
def eval_with(sym, env, bindings, expr):
sym_save = {}
sym_remove = {}
for key, value in bindings.iteritems():
old = sym.get(key)
if old is None:
sym_remove[key] = True
else:
sym_save[key] = old
sym[key] = value
ret = ParseExpr(expr, sym, env)
sym.update(sym_save)
for key in sym_remove:
del sym[key]
return ret
DOLLAR_RE = re.compile(r'\$')
class Function(object):
def __init__(self, proto, expansion):
self.proto = proto
self.expansion = expansion
def name(self, key):
out = []
pos = 0
for idx, item in enumerate(DOLLAR_RE.finditer(key)):
out.append(key[pos:item.start()])
out.append('(%s)' % self.proto[idx])
pos = item.end()
out.append(key[pos:])
return ''.join(out)
def eval(self, sym, env, args):
bindings = {}
for idx, item in enumerate(args):
key = self.proto[idx]
bindings[key] = ParseExpr(item, sym, env)
return eval_with(sym, env, bindings, self.expansion)
def first_paren_expr(fexpr):
args = []
argidx = 0
open_parens = 0
in_quotes = False
for idx, char in enumerate(fexpr):
if char == '(' and not in_quotes:
open_parens += 1
elif char == ')' and not in_quotes:
open_parens -= 1
if open_parens < 0:
idx -= 1 # do not want
break
elif char == '"':
in_quotes = not in_quotes
elif char == ',' and open_parens == 0 and not in_quotes:
args.append(fexpr[argidx:idx])
argidx = idx+1
if open_parens > 0:
raise ParseError('Missing closing parenthesis in "%s"' % fexpr)
args.append(fexpr[argidx:idx+1])
fexpr = fexpr[:idx+1]
return args, fexpr
def eval_fname(sym, env, fname, args, trailexpr):
logging.debug('fname=%s args=%s trailexpr=%s', repr(fname), repr(args), repr(trailexpr))
func = None
fn = None
if '$' in fname:
func = sym.get(fname)
else:
func = sym.get(fname + ('$' * len(args)))
if not func:
fn = FUNCTIONS.get(fname, None)
#args = [x.strip() for x in args]
if func and isinstance(func, Function):
# FIXME, duplication
consume = 0
if '$' in func.expansion:
func = Function(func.proto, func.expansion.replace('$', trailexpr))
#logging.debug('magic function: %s', repr(func.expansion))
consume = len(trailexpr)
return (func.eval(sym, env, args), consume)
elif fn:
try:
return (fn(sym, env, *args), 0)
except TypeError, e:
logging.info('TypeError: %s', e, exc_info=True)
raise ParseError('%s: unexpected args %s' % (fname, repr(args)))
return (None, 0)
def ParseExpr(expr, sym, parent_env):
if isinstance(expr, Result):
return expr
# ignore Nx(...) for now
result = []
ops = []
# Make a shallow copy of the environment so that changes from child calls don't
# propagate back up unintentionally.
env = parent_env.copy()
if 'stats' in env:
env['stats']['level'] += 1
else:
env['stats'] = {'rolls': 0, 'objects': 0, 'level': 1}
env['warnings'] = []
def AddOperator(op):
DEBUG('got operator %s', op)
if ops and OP_PRECEDENCE.get(ops[-1], 0) >= OP_PRECEDENCE.get(op, 0):
Reduce(result.pop(), ops.pop())
ops.append(op)
def ShiftVal(new_result):
DEBUG('ShiftVal: %s', repr(new_result))
result.append(new_result)
def Reduce(rhs, op):
# must not modify constants such as RESULT_NIL
if not result:
raise ParseError('Missing operand in expression "%s"' % expr)
lhs = copy.deepcopy(result.pop())
DEBUG('Reduce, op=%s, lhs=%s, rhs=%s', repr(op), repr(lhs), repr(rhs))
if op == ',':
if lhs.is_multivalue:
lhs._items.append(copy.deepcopy(rhs))
else:
lhs = ResultMultiValue([lhs, copy.deepcopy(rhs)])
result.append(lhs)
return
need_parens = False
lhs_detailparen = lhs.detail_paren()
rhs_detailparen = rhs.detail_paren()
if lhs.is_list:
# flatten into scalar
lhs = lhs.to_scalar()
if rhs.is_list:
rhs = rhs.to_scalar()
lval = lhs._value
rval = rhs.value()
is_relop = False
need_detail = (not rhs.is_constant)
if op == '+':
lval += rval
lhs.constant_sum += rhs.constant_sum
if need_detail and not lhs._detail: