通用构建添加字段

时间:2017-01-18 15:12:33

标签: macros haxe

考虑以下代码:

http://try.haxe.org/#5AD6e

class Test
{
    public static function main()
    {
        var foo = new FluentFoo(null, { bar: 1 }).hello();
    }
}

class Foo
{
    public function new(options:{ bar:Int }) {}

    public function hello()
    {
        trace("Hi there");
    }
}

class Fluent
{
    private var parent:Null<Fluent>;

    public function new(parent:Null<Fluent>)
    {
        this.parent = parent;
    }

    public function end()
    {
        if(parent != null) {
            return parent;
        }

        throw 'Top level already reached';
    }
}

class FluentFoo extends Fluent
{
    public var base:Foo;

    public function new(parent:Null<Fluent>, options:{ bar:Int })
    {
        super(parent);

        base = new Foo(options);
    }

    public function hello()
    {
        base.hello();

        return this;
    }
}

我想自动生成FluentFoo等类。

在pseudohaxe代码中:

import haxe.Constraints.Constructible;

class Test
{
    public static function main()
    {
        var foo = new Fluent<Foo>(null, { bar: 1 }).hello();
    }
}

class Foo
{
    public function new(options:{ bar:Int }) {}

    public function hello()
    {
        trace("Hi there");
    }
}

@:generic
@:genericBuild(FluentMacro.build())
class Fluent<T:Constructible<Dynamic -> Void>>
{
    private var parent:Null<Fluent>;
    private var base:T;

    public function new(parent:Null<Fluent>, options:Dynamic)
    {
        this.parent = parent;
        this.base = new T(options);
    }

    public function end()
    {
        if(parent != null) {
            return parent;
        }

        throw 'Top level already reached';
    }
}

class FluentMacro
{
    public static function build()
    {
        //Get "T" public methods
        //Add them to class calling this genericBuild method (in this example to Fluent_Foo)
        //Modify them so they return "this"
    }
}

我知道我无法使用@:build,因为我Context.getLocalType的所有内容都是TInst(Fluent,[TInst(Fluent.T,[])])

但是,我并不完全理解关于通用构建的haxe手册 - 它们属于同一部分&#34;类型构建宏&#34;正常@:build,但build方法预计会返回ComplexType,而不是字段数组。是否可以在@:genericBuild中添加字段?

谢谢

1 个答案:

答案 0 :(得分:1)

这比我预想的要复杂一点,但我做到了。供其他人使用:https://github.com/Misiur/Fluent