Skip to content

Instantly share code, notes, and snippets.

@nadako
Created April 21, 2016 02:35
Show Gist options
  • Select an option

  • Save nadako/8ad5f75d261fa25a7c0af56fbb0d24c1 to your computer and use it in GitHub Desktop.

Select an option

Save nadako/8ad5f75d261fa25a7c0af56fbb0d24c1 to your computer and use it in GitHub Desktop.

Revisions

  1. nadako created this gist Apr 21, 2016.
    33 changes: 33 additions & 0 deletions FunctionArgMacro.hx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    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;
    }
    }
    9 changes: 9 additions & 0 deletions Main.hx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    @:build(FunctionArgMacro.build())
    class Main {
    static function main() {
    }

    static function greet(@notNullOrEmpty who:String) {
    trace('Hi, $who!');
    }
    }
    9 changes: 9 additions & 0 deletions main.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    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 + "!");
    };