[IronPython] Building via AST

Dino Viehland dinov at microsoft.com
Mon Apr 12 22:33:34 CEST 2010


Nope – the DLR doesn’t have any support for building .NET types – dynamic or otherwise.  If you’d like to just build an object which behaves dynamically I’d suggest looking at DynamicObject.  You can just subclass it and override various Try* methods and you’ll have a dynamic object.

If you really do need to do ILGen into a type, and as long as you’re building only static methods, you can use expression trees via Lambda<T>.CompileToMethod (unfortunately currently instance methods are not supported).  Here’s an example of that:

using System;
using System.Linq.Expressions;
using System.Reflection;

class Foo {
    public static void Main(string[] args) {
        var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("foo"), System.Reflection.Emit.AssemblyBuilderAccess.Save);
        var module = asm.DefineDynamicModule("foo.dll");
        var type = module.DefineType("TestType");

        var param1 = Expression.Parameter(typeof(Foox), "arg1");
        var param2 = Expression.Parameter(typeof(Foox), "arg2");
        var method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Static);

        Expression.Lambda<Func<Foox, Foox, bool>>(
            Expression.Equal(param1, param2),
            new[] { param1, param2 }
        ).CompileToMethod(method);
        type.CreateType();
        asm.Save("foo.dll");
    }
}
enum Foox {
    Bar,
    Baz
}

From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Justin Chase
Sent: Monday, April 12, 2010 1:21 PM
To: users at lists.ironpython.com
Subject: [IronPython] Building via AST

Suppose I would like to build an AST programmatically and compile that into an assembly dynamically (meaning an assembly flagged with RunAndCollect) from C#. How would I do that with IronPython's help? I do not what to author Python code and compile that I would like to just deal directly with the AST.

Currently I have working code where I'm using System.Linq.Expression namespace to build statements and expressions into delegates but what I would like is to leverage the DLR to build dynamic types as well (without having to use ILGenerator preferably). Is this possible today?

--
Justin Chase
http://www.justnbusiness.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20100412/d479d9a5/attachment.html>


More information about the Ironpython-users mailing list