Created
July 11, 2013 18:15
-
-
Save deltaluca/5977806 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package goodies; | |
#if macro | |
import haxe.macro.Context; | |
import haxe.macro.Expr; | |
import goodies.MacroUtils; | |
class BitFields { | |
public static function run(self:Expr) { | |
var self = Context.toComplexType(Context.getType(switch (self.expr) { | |
case EConst(CIdent(s)): s; | |
default: ""; | |
})); | |
var fields = Context.getBuildFields(); | |
for (f in fields) { | |
switch (f.kind) { | |
case FVar(t,e): | |
f.kind = FVar(self, macro _new($e)); | |
f.access = [AStatic,APublic,AInline]; | |
default: | |
} | |
} | |
return fields.concat((macro class { | |
public static inline function _new(x:Int):$self return untyped x; | |
@:op(A|B) public static inline function or(a:$self, b:$self):$self return _new((untyped a)|(untyped b)); | |
@:op(A&B) public static inline function and(a:$self, b:$self):$self return _new((untyped a)&(untyped b)); | |
@:op(A^B) public static inline function xor(a:$self, b:$self):$self return _new((untyped a)^(untyped b)); | |
public static inline function test(a:$self, value:$self):Bool | |
return and(a, value) == value; | |
public inline static function toString(a:$self):String { | |
var a:Int = untyped a; | |
if (a == 0) return "(None)"; | |
else { | |
var ret = ""; | |
$b{[for (f in fields) | |
macro if ((a&(untyped $p{[f.name]})) != 0) { | |
if (ret.length != 0) ret += "|"; | |
ret += $v{f.name}; | |
} | |
]}; | |
return ret; | |
} | |
} | |
}).fields); | |
} | |
} | |
#end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package; | |
@:build(goodies.BitFields.run(ABC)) abstract ABC(Int) { | |
static var A = 1; | |
static var B = 2; | |
static var C = 4; | |
} | |
class Main { | |
static function main() { | |
$type(ABC.A); | |
$type(ABC.A | ABC.B); | |
$type(ABC.test); | |
trace((ABC.A | ABC.B).test(ABC.A)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment