Created
May 5, 2014 19:12
-
-
Save nadako/d41305c4bd8b8d35f3ef to your computer and use it in GitHub Desktop.
OptionalField abstract
This file contains 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
typedef House = | |
{ | |
?numTennants:OptionalField<Int> | |
} | |
class Main | |
{ | |
static function main() | |
{ | |
var house:House = {}; | |
var numTennants = house.numTennants.or(0); | |
} | |
} | |
This file contains 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
(function () { "use strict"; | |
var Main = function() { }; | |
Main.main = function() { | |
var house = { }; | |
var numTennants; | |
if(Object.prototype.hasOwnProperty.call(house,"numTennants")) numTennants = house.numTennants; else numTennants = 0; | |
}; | |
Main.main(); | |
})(); |
This file contains 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
import haxe.macro.Context; | |
import haxe.macro.Expr; | |
abstract OptionalField<T>(T) from T | |
{ | |
@:extern | |
public inline function extract():T return this; | |
public macro function exists(ethis:Expr):ExprOf<Bool> | |
{ | |
return makeCheckExpr(ethis); | |
} | |
public macro function or(ethis:Expr, defaultValue:ExprOf<T>):ExprOf<T> | |
{ | |
var check = makeCheckExpr(ethis); | |
return macro $check ? $ethis.extract() : $defaultValue; | |
} | |
#if macro | |
static function makeCheckExpr(ethis:Expr):ExprOf<Bool> | |
{ | |
var typed = Context.typeExpr(ethis); | |
switch (typed.expr) | |
{ | |
case TField(e, FAnon(_.get() => f)) if (f.meta.has(":optional")): | |
var eobj = Context.getTypedExpr(e); | |
return macro Reflect.hasField($eobj, $v{f.name}); | |
default: | |
throw new Error("OptionalField type is only usable for optional structure fields", ethis.pos); | |
} | |
} | |
#end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment