1 """BulletML expression evaluator.
3 http://www.asahi-net.or.jp/~cs8k-cyu/bulletml/index_e.html
6 # BulletML assumes 1/2 = 0.5.
7 from __future__
import division
12 from bulletml
.errors
import Error
14 class ExprError(Error
):
15 """Raised when an invalid expression is evaluated/compiled."""
18 class NumberDef(object):
19 """BulletML numeric expression.
21 This translates BulletML numeric expressions into Python expressions.
32 def __init__(self
, expr
):
34 expr
= expr
.__original
35 except AttributeError:
37 self
.__original
= expr
38 repl
= lambda match
: "params[%d]" % (int(match
.group()[1:]) - 1)
39 expr
= re
.sub(r
"\$\d+", repl
, expr
.lower())
40 self
.__expr
= expr
.replace("$rand", "rand").replace("$rank", "rank")
43 self
.__value
= eval(self
.__expr
, dict(__builtins__
={}))
46 variables
= dict(rand
=1, rank
=1, params
=fake
, __builtins__
={})
47 value
= eval(self
.__expr
, variables
)
48 if not isinstance(value
, (int, float)):
53 self
.__expr
= compile(self
.__expr
, __file__
, "eval")
55 def __call__(self
, params
, rank
):
56 """Evaluate the expression and return its value."""
57 if self
.__value
is not None:
59 rand
= random
.random()
60 variables
= dict(rand
=rand
, rank
=rank
, params
=params
)
61 return eval(self
.__expr
, variables
)
64 return "%s(%r)" % (type(self
).__name
__, self
.__original
)