Skip to content

Instantly share code, notes, and snippets.

@nadako
Created April 21, 2016 02:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nadako/8ad5f75d261fa25a7c0af56fbb0d24c1 to your computer and use it in GitHub Desktop.
Save nadako/8ad5f75d261fa25a7c0af56fbb0d24c1 to your computer and use it in GitHub Desktop.
import haxe.macro.Context;
import haxe.macro.Expr;
class FunctionArgMacro {
macro static function build():Array<Field> {
var fields = Context.getBuildFields();
for (field in fields) {
switch (field.kind) {
case FFun(fun):
var checks = [];
for (arg in fun.args) {
switch (arg.type) {
case macro : String:
for (m in arg.meta) {
switch (m.name) {
case "notNullOrEmpty":
checks.push(macro if ($i{arg.name} == null) throw $v{arg.name + " is null"});
checks.push(macro if ($i{arg.name}.length == 0) throw $v{arg.name + " is empty"});
}
}
default:
}
}
fun.expr = macro {
$b{checks};
${fun.expr};
}
default:
}
}
return fields;
}
}
@:build(FunctionArgMacro.build())
class Main {
static function main() {
}
static function greet(@notNullOrEmpty who:String) {
trace('Hi, $who!');
}
}
Main.greet = function(who) {
if(who == null) {
throw new js__$Boot_HaxeError("who is null");
}
if(who.length == 0) {
throw new js__$Boot_HaxeError("who is empty");
}
console.log("Hi, " + who + "!");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment