简体   繁体   English

在构建宏中获取抽象底层类型?

[英]Get abstract underlying type in a build macro?

For example i have an abstract type of Bool 例如,我有一个抽象类型的Bool

abstract ABool(Bool) from Bool to Bool {}

And i have a field of that type 我有一个这种类型的领域

var abool:ABool;

What i need is to know ABool underlying type (Bool) in my build macro. 我需要的是在构建宏中了解ABool底层类型(Bool)。

#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() {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM