Reject all expressions with __ in them.
[python-bulletml.git] / bulletml / expr.py
index a00c99e..c7d4098 100644 (file)
@@ -11,6 +11,8 @@ import re
 
 from bulletml.errors import Error
 
+__all__ = ["ExprError", "NumberDef", "INumberDef"]
+
 class ExprError(Error):
     """Raised when an invalid expression is evaluated/compiled."""
     pass
@@ -19,7 +21,6 @@ class NumberDef(object):
     """BulletML numeric expression.
 
     This translates BulletML numeric expressions into Python expressions.
-    The 
 
     Examples:
     35
@@ -37,6 +38,12 @@ class NumberDef(object):
             expr = expr.string
         except AttributeError:
             pass
+        try:
+            if "__" in expr:
+                # nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
+                raise ExprError(expr)
+        except TypeError:
+            pass
         self.string = expr = str(expr)
         repl = lambda match: "params[%d]" % (int(match.group()[1:]) - 1)
         expr = re.sub(r"\$\d+", repl, expr.lower())
@@ -75,6 +82,7 @@ class INumberDef(NumberDef):
             self._value = int(round(self._value))
 
     def __call__(self, params, rank):
+        # Avoid int(round(__call__())) overhead for constants.
         if self._value is not None:
             return self._value
         return int(round(super(INumberDef, self).__call__(params, rank)))