[IronPython] Using IronPython AST

Dan Eloff dan.eloff at gmail.com
Wed Oct 8 13:41:39 PDT 2008

I'm looking at the ast stuff in IronPython.Compiler.Ast and seeing how
difficult it would be to write a python 2.5 _ast (and 2.6 ast) wrapper
over it.

Jython actually supports this now, and I don't wish to see IronPython
left behind in this area.

It looks like I should be able to handle a read-only ast without much
difficulty. The trouble comes with altering the ast. It seems from
looking at the code that everything is marked readonly, the ast cannot
be modified in place?

This is not a blocker, it's possible to handle all modifications in
the wrapper, and then generate a new ast at the end that can be

For example:

node = UnaryOp()
node.op = USub()
node.operand = Num()
node.operand.n = 5

1) How would you turn this into an ast? Something like this maybe?

node = new UnaryExpression(PythonOperator.Negate, new ConstantExpression(5))

2) I assume there is a mechanism for compiling and/or executing an
ast, please could someone show how to use it (you can build off the
script below)

3) Is there a mechanism for turning an ast back into source code? This
would help me with debugging.


Thanks to Dino for showing how to get an ast:

import clr
from IronPython.Compiler import Parser

from Microsoft.Scripting import ErrorSink
from Microsoft.Scripting.Runtime import CompilerContext
from Microsoft.Scripting.Hosting.Providers import HostingHelpers
from IronPython.Hosting import Python
py = Python.CreateEngine() # beta 5 and beyond

src = HostingHelpers.GetSourceUnit(py.CreateScriptSourceFromString('print
pylc = HostingHelpers.GetLanguageContext(py)

p = Parser.CreateParser(CompilerContext(src,
pylc.GetCompilerOptions(), ErrorSink.Default), pylc.Options)
ast = p.ParseFile(True)

More information about the Users mailing list