[IronPython] Determine used SymbolIds in an expression
Christian Schmidt
christian2.schmidt at gmx.de
Mon Sep 8 19:37:48 CEST 2008
Hi,
I found some answers to my own questions. But I'm stuck again...
> how can I determine the Symbols or SymbolIds that are used in an
> (IP2-)expression?
> Obviously I need to parse the expression. Where can I find a small
> sample or tutorial on parsing in IP2?
http://www.ironpython.info/index.php/The_IronPython_2_Parser
Seems that the example is outdated. Here's my try, which compiles, but
produces NullReferenceException when calling CreateParser and seems very
complicated to me.
Thanks for any help.
class SymbolWalker : IronPython.Compiler.Ast.PythonWalker
{
public Dictionary<SymbolId, int> symbols =
new Dictionary<SymbolId, int>();
public override bool Walk(NameExpression node) {
symbols[node.Name] = 1;
return true;
}
}
IEnumerable<SymbolId> GetSymbols(string pyExpression)
{
Microsoft.Scripting.Hosting.ScriptRuntime runtime =
ScriptRuntime.Create();
Microsoft.Scripting.Hosting.ScriptEngine scriptEngine =
runtime.GetEngine("py");
Microsoft.Scripting.Hosting.ScriptSource src =
engine.CreateScriptSourceFromString(expression);
System.Scripting.SourceUnit code =
Microsoft.Scripting.Hosting.HostingHelpers.GetSourceUnit(src);
System.Scripting.CompilerOptions opts =
new System.Scripting.CompilerOptions();
System.Scripting.ErrorSink sink =
System.Scripting.ErrorSink.Default;
Microsoft.Scripting.Compilers.CompilerContext context =
new Microsoft.Scripting.Compilers.CompilerContext(code, opts, sink);
IronPython.PythonEngineOptions engineOptions =
new IronPython.PythonEngineOptions();
IronPython.Compiler.Parser parser =
IronPython.Compiler.Parser.CreateParser(context, engineOptions);
IronPython.Compiler.Ast.Statement stmt
= parser.ParseTopExpression();
SymbolWalker walker =
new SymbolWalker();
stmt.Walk(walker);
return walker.symbols.Keys;
}
More information about the Ironpython-users
mailing list