385b31b5ab1d8fc1122d1f903f076a938876ba69
[python-bulletml.git] / bulletml / expr.py
1 """BulletML expression evaluator.
2
3 http://www.asahi-net.or.jp/~cs8k-cyu/bulletml/index_e.html
4 """
5
6 # BulletML assumes 1/2 = 0.5.
7 from __future__ import division
8
9 import random
10 import re
11
12 from bulletml.errors import Error
13
14 __all__ = ["ExprError", "NumberDef", "INumberDef"]
15
16 class ExprError(Error):
17 """Raised when an invalid expression is evaluated/compiled."""
18 pass
19
20 class NumberDef(object):
21 """BulletML numeric expression.
22
23 This translates BulletML numeric expressions into Python expressions.
24
25 Examples:
26 35
27 360/16
28 0.7 + 0.9*$rand
29 180-$rank*20
30 (2+$1)*0.3
31
32 """
33
34 GLOBALS = dict(random=random.random, __builtins__={})
35
36 def __init__(self, expr):
37 try:
38 expr = expr.string
39 except AttributeError:
40 pass
41 self.string = expr = str(expr)
42 repl = lambda match: "params[%d]" % (int(match.group()[1:]) - 1)
43 expr = re.sub(r"\$\d+", repl, expr.lower())
44 self.__expr = expr.replace("$rand", "random()").replace("$rank", "rank")
45 try:
46 try:
47 self._value = eval(self.__expr, dict(__builtins__={}))
48 except NameError:
49 variables = dict(rank=1, params=[0] * 99)
50 value = eval(self.__expr, self.GLOBALS, variables)
51 if not isinstance(value, (int, float)):
52 raise TypeError(expr)
53 self._value = None
54 self.expr = self.string
55 else:
56 self.expr = self._value
57 except Exception:
58 raise ExprError(expr)
59 self.__expr = compile(self.__expr, __file__, "eval")
60
61 def __call__(self, params, rank):
62 """Evaluate the expression and return its value."""
63 if self._value is not None:
64 return self._value
65 variables = { 'rank': rank, 'params': params }
66 return eval(self.__expr, self.GLOBALS, variables)
67
68 def __repr__(self):
69 return "%s(%r)" % (type(self).__name__, self.expr)
70
71 class INumberDef(NumberDef):
72 """A NumberDef, but returns rounded integer results."""
73 def __init__(self, expr):
74 super(INumberDef, self).__init__(expr)
75 if self._value is not None:
76 self._value = int(round(self._value))
77
78 def __call__(self, params, rank):
79 # Avoid int(round(__call__())) overhead for constants.
80 if self._value is not None:
81 return self._value
82 return int(round(super(INumberDef, self).__call__(params, rank)))