2
votes

I use this code to execute a python expression using IronPython.

    ScriptEngine engine = Python.CreateEngine();
    ScriptScope scope = engine.CreateScope();      
    scope.SetVariable("m", mobject);
    string code = "m.ID > 5 and m.ID < 10";
    ScriptSource source = 
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);
    source.Execute(scope);

Is there a way to get the produced Expression Tree as c# object, e.g. the BlockExpression ?

1
Where are you passing in the code?WombatPM
I have referenced Microsoft Scripting libraries and IronPython. Iam using .net 4.0wilsonlarg

1 Answers

6
votes

IronPython's internal ASTs also happen to be Expression trees, so you just need to get the AST for your code, which you can do using the IronPython.Compiler.Parser class. The Parser.ParseFile method will return a IronPython.Compiler.Ast.PythonAst instance representing the code.

Using the parser is a bit tricky, but you can look at the BuildAst method of the _ast module for some hints. Basically, it's:

Parser parser = Parser.CreateParser(
    new CompilerContext(sourceUnit, opts, ThrowingErrorSink.Default),
    (PythonOptions)context.LanguageContext.Options);

PythonAst ast = parser.ParseFile(true);

ThrowingErrorSink also comes from the _ast module. You can get a SourceUnit instance like so (c.f. compile builtin):

SourceUnit sourceUnit = context.LanguageContext.CreateSnippet(source, filename, SourceCodeKind.Statements);

You then have to walk the AST to get useful information out of it, but they should be similar (but not identical to) C# expression trees.