waneck / testrepo

0 stars 0 forks source link

Issue 1783 - EnumValue.match - haxe #1783

Open waneck opened 11 years ago

waneck commented 11 years ago

[Google Issue #1783 : http://code.google.com/haxe/issues/detail?id=1783] by ncanna...@gmail.com, at 2013-05-07T05:56:00.000Z Add the ability to do e.match(pattern) on any EnumValue that compiles to :

switch( e ) { case pattern: true; default: false; }

No variable capturing is allowed in this pattern.

This can be used to quickly check for a pattern, such as :

if( expr.match(EConst(_)) ) compileAsConst(expr);

waneck commented 11 years ago

[comment from si...@haxe.org, published at 2013-05-07T07:10:30.000Z] There's a macro for that! ;)

using Main; import haxe.macro.Context; import haxe.macro.Expr;

class Main { static function main() { var e = macro 99; trace(e.expr.match(EConst())); // true trace(e.expr.match(EBinop())); // false }

macro static public function match(e:ExprOf<EnumValue>, pattern:Expr) {
    var locals:Map<String,Type> = neko.Lib.load("macro", "pattern_locals", 2)(pattern, Context.typeof(e));
    for (k in locals) {
        Context.error("Capture variables are not allowed", pattern.pos);
    }
    return macro switch($e) {
        case $pattern: true;
        case _: false;
    }
}   

}

waneck commented 11 years ago

[comment from ncanna...@gmail.com, published at 2013-05-07T07:24:13.000Z] Of course, but I meant to have it as a default in the language, without relying on macro code ;)

waneck commented 11 years ago

[comment from si...@haxe.org, published at 2013-05-07T08:36:53.000Z]