【问题标题】:Get abstract underlying type in a build macro?在构建宏中获取抽象基础类型?
【发布时间】:2015-07-20 13:38:08
【问题描述】:

例如,我有一个 Bool 抽象类型

abstract ABool(Bool) from Bool to Bool {}

我有一个这种类型的字段

var abool:ABool;

我需要在我的构建宏中了解 ABool 底层类型(Bool)。

【问题讨论】:

    标签: macros haxe


    【解决方案1】:
    #if macro
    import haxe.macro.Expr;
    import haxe.macro.*;
    #end
    
    class Builder {
        macro static public function build():Array<Field> {
            var fields = Context.getBuildFields();
            for (f in fields) {
                switch (f.kind) {
                    // looks at class variables and properties
                    case FVar(t, e) | FProp(_, _, t, e):
                        // t is a haxe.macro.ComplexType,
                        // lets convert it to a haxe.macro.Type,
                        // such that we can check if it is an abstract type or not
                        var type = Context.typeof(macro {var a:$t; a;});
                        switch (type) {
                            case TAbstract(t, params):
                                var underlyingType = t.get().type;
                                trace(underlyingType); //TAbstract(Bool,[])
                            case _:
                                // ignore things that are not of abstract type
                        }
                    case _:
                        // ignore methods
                }
            }
            return fields;
        }
    }
    
    abstract ABool(Bool) from Bool to Bool {}
    
    #if !macro
    @:build(Builder.build())
    #end
    class Test {
        var abool:ABool;
    
        static function main() {
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 2013-10-21
      • 2011-05-12
      • 2011-12-16
      相关资源
      最近更新 更多