Sfoglia il codice sorgente

[js] don't generate HaxeError unwrapping code when not needed (closes #4736)

Dan Korostelev 9 anni fa
parent
commit
cc0a1a71b4
2 ha cambiato i file con 36 aggiunte e 2 eliminazioni
  1. 21 2
      genjs.ml
  2. 15 0
      tests/optimization/src/TestJs.hx

+ 21 - 2
genjs.ml

@@ -688,8 +688,27 @@ and gen_expr ctx e =
 		end;
 
 		if (has_feature ctx "js.Boot.HaxeError") then begin
-			newline ctx;
-			print ctx "if (%s instanceof %s) %s = %s.val" vname (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js";"_Boot"],"HaxeError" })) vname vname;
+			let catch_var_used =
+				try
+					List.iter (fun (v,e) ->
+						match follow v.v_type with
+						| TDynamic _ -> (* Dynamic catch - unrap if the catch value is used *)
+							let rec loop e = match e.eexpr with
+							| TLocal v2 when v2 == v -> raise Exit
+							| _ -> Type.iter loop e
+							in
+							loop e
+						| _ -> (* not a Dynamic catch - we need to unwrap the error for type-checking *)
+							raise Exit
+					) catchs;
+					false
+				with Exit ->
+					true
+			in
+			if catch_var_used then begin
+				newline ctx;
+				print ctx "if (%s instanceof %s) %s = %s.val" vname (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js";"_Boot"],"HaxeError" })) vname vname;
+			end;
 		end;
 
 		List.iter (fun (v,e) ->

+ 15 - 0
tests/optimization/src/TestJs.hx

@@ -146,5 +146,20 @@ class TestJs {
 		var vRand = new Inl(Math.random());
 	}
 
+	@:js("try {throw new js__$Boot_HaxeError(false);} catch( e ) {}")
+	static function testNoHaxeErrorUnwrappingWhenNotRequired() {
+		try throw false catch (e:Dynamic) {}
+	}
+
+	@:js("try {throw new js__$Boot_HaxeError(false);} catch( e ) {if (e instanceof js__$Boot_HaxeError) e = e.val;console.log(e);}")
+	static function testHaxeErrorUnwrappingWhenUsed() {
+		try throw false catch (e:Dynamic) trace(e);
+	}
+
+	@:js("try {throw new js__$Boot_HaxeError(false);} catch( e ) {if (e instanceof js__$Boot_HaxeError) e = e.val;if( js_Boot.__instanceof(e,Bool) ) {} else throw(e);}")
+	static function testHaxeErrorUnwrappingWhenTypeChecked() {
+		try throw false catch (e:Bool) {};
+	}
+
 	static function use<T>(t:T) { }
 }