From cc3c21b7e3c3d597fb0aa82764bfad1387aaed97 Mon Sep 17 00:00:00 2001 From: Nicolas Cannasse Date: Tue, 14 Jul 2020 12:49:24 +0200 Subject: [PATCH] fixed unop priority overriding binop one (close #94) --- Test.hx | 2 ++ hscript/Parser.hx | 25 ++++++++++++++----------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/Test.hx b/Test.hx index 749e941..0b07500 100644 --- a/Test.hx +++ b/Test.hx @@ -111,6 +111,8 @@ class Test extends TestCase { assertScript("var f:(x:Int, y:Int)->Int = (x:Int,y:Int) -> x + y; f(3,1)", 4, null, true); assertScript("var f:(x:Int)->(y:Int, z:Int)->Int = (x:Int) -> (y:Int, z:Int) -> x + y + z; f(3)(1, 2)", 6, null, true); assertScript("var f:(x:Int)->(Int, Int)->Int = (x:Int) -> (y:Int, z:Int) -> x + y + z; f(3)(1, 2)", 6, null, true); + assertScript("var a = 10; var b = 5; a - -b", 15); + assertScript("var a = 10; var b = 5; a - b / 2", 7.5); } function testMap():Void { diff --git a/hscript/Parser.hx b/hscript/Parser.hx index 991ae35..4d35c1d 100644 --- a/hscript/Parser.hx +++ b/hscript/Parser.hx @@ -139,7 +139,7 @@ class Parser { opPriority.set(x, i); if( i == 9 ) opRightAssoc.set(x, true); } - for( x in ["!", "++", "--", "-", "~"] ) + for( x in ["!", "++", "--", "~"] ) // unary "-" handled in parser directly! opPriority.set(x, x == "++" || x == "--" ? -1 : -2); } @@ -437,19 +437,22 @@ class Parser { } return mk(EBlock(a),p1); case TOp(op): - if( opPriority.get(op) < 0 ) { + if( op == "-" ) { var start = tokenMin; var e = parseExpr(); - if( op == "-" && e != null ) - switch( expr(e) ) { - case EConst(CInt(i)): - return mk(EConst(CInt(-i)), start, pmax(e)); - case EConst(CFloat(f)): - return mk(EConst(CFloat(-f)), start, pmax(e)); - default: - } - return makeUnop(op,e); + if( e == null ) + return makeUnop(op,e); + switch( expr(e) ) { + case EConst(CInt(i)): + return mk(EConst(CInt(-i)), start, pmax(e)); + case EConst(CFloat(f)): + return mk(EConst(CFloat(-f)), start, pmax(e)); + default: + return makeUnop(op,e); + } } + if( opPriority.get(op) < 0 ) + return makeUnop(op,parseExpr()); return unexpected(tk); case TBkOpen: var a = new Array();