[Bf-committers] parsing Blender and math expressions?
Toni Alatalo
antont at kyperjokki.fi
Fri Apr 30 08:58:43 CEST 2010
Triggered by the crazily exploded security/sandboxing talk, I looked a
bit into what kind of mathematical expression parsers etc. there are for
Python -- and sure enough there are plenty, e.g. the examples at the
yacc-style Ply and in Pyparsing. They can securely eval things like 1+1
=> 2, and there was also examples with linear algebra etc. I was curious
how easy it would be to add Blender specific functionality in such a
parser (new commands), and found an example where it was easy so made a
little proof of concept that can do stuff like this:
1 + 1
sin(curframe()) #inspired by the
http://wiki.blender.org/index.php/Dev:2.4/Source/Animation/PyDrivers
The quick test implementation is at http://an.org/blender/blendexp.py -
can be used as a lib that provides a func that evals expressions, and
run as a standlone file that runs tests and prints the results. Examples
of both usage are in the docstrings in the file. Requires pyparsing.
That uses a mock Blender module but it would work against the actual
Blender too inside the app. I just added two simple things that saw in
driver examples:
blender_fn = {
"curframe" : Blender.curframe,
"noise" : Blender.noise
}
.. so that those functions can be used in the expressions, calling
Blender, but the expressions are not Python, there are no python objects
accessible there, it is sandboxed. In this version it seems to accept
only numbers as input for the functions, so no clever paramater attack
seems possible.
I don't know if something like this could be actually useful -- my guess
is not, except perhaps for simple drivers. Caveats: all kinds of Blender
scene data is probably easy enough to make accessible this way. Perhaps
with some clever trick reading data from scene could be added though?
For more complex things like constraints you probably need a programming
language, where can do if/else etc. So if continued along this route,
would end up reimplementing PyPy, which already is an implementation of
py in py :)
This example doesn't have interactive mode nor named vars, but e.g. this
Ply one does: http://www.dabeaz.com/ply/example.html (an interactive
calculator with named args implemented in one not big py file). It
seemed that some constraints that I found on the net might be nice to
implement with this kind of a domain specific lang in a namespace with
prepopulated values -- in that example there is just a dict of known names.
Am curious to learn more about why this is not feasible. Had never had a
need for yacc or pyparsing earlier, so was fun to finally learn a bit
about what those are about :)
~Toni
More information about the Bf-committers
mailing list