[IronPython] Determine used SymbolIds in an expression

Christian Schmidt christian2.schmidt at gmx.de
Mon Sep 8 19:37:48 CEST 2008


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?


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 =
   Microsoft.Scripting.Hosting.ScriptEngine scriptEngine =
   Microsoft.Scripting.Hosting.ScriptSource src =
   System.Scripting.SourceUnit code =
   System.Scripting.CompilerOptions opts =
     new System.Scripting.CompilerOptions();
   System.Scripting.ErrorSink sink =
   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();
   return walker.symbols.Keys;

More information about the Ironpython-users mailing list