Skip to content

Commit bbb1676

Browse files
committed
Merge pull request #114 from gasman/fix/conditionalexpression-type-checks
Conditional expression validation should consider subtypes of int/double
2 parents a183012 + 69036e6 commit bbb1676

2 files changed

Lines changed: 32 additions & 3 deletions

File tree

lib/validate.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -865,10 +865,18 @@ Vp.expression = function expression(e) {
865865
this.checkSubtype(this.expression(vars.test), ty.Int, "conditional test", vars.test.loc);
866866
var t1 = this.expression(vars.cons);
867867
var t2 = this.expression(vars.alt);
868-
if (t1 !== t2)
869-
this.fail("type mismatch between conditional branches", e.loc);
870-
if (t1 !== ty.Int && t1 !== ty.Double)
868+
869+
var t1supertype;
870+
if (t1.subtype(ty.Int)) {
871+
t1supertype = ty.Int;
872+
} else if (t1.subtype(ty.Double)) {
873+
t1supertype = ty.Double;
874+
} else {
871875
this.fail("expected int or double in conditional branch, got " + t1, vars.cons.loc);
876+
}
877+
878+
if (!t2.subtype(t1supertype))
879+
this.fail("type mismatch between conditional branches", e.loc);
872880
return t1;
873881
}, this);
874882

test/index.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,3 +301,24 @@ exports.testFunctionTables = asmAssert(
301301
var x = [f], y = [g], z = [f, g]
302302
return f;
303303
}, { pass: true });
304+
305+
exports.testConditionalExpression = asmAssert.one(
306+
"conditional expression",
307+
function f() {
308+
return (1 ? 2 : 3)|0;
309+
},
310+
{ pass: true });
311+
312+
exports.testConditionalExpressionMismatchedTypes = asmAssert.one(
313+
"conditional with consequent and alternate of differing types",
314+
function f() {
315+
return (1 ? 0.5 : 3)|0;
316+
},
317+
{ pass: false });
318+
319+
exports.testConditionalExpressionDifferentSubtypes = asmAssert.one(
320+
"conditional with different subtypes of int",
321+
function f() {
322+
return (1 ? (2 < 3) : 4)|0;
323+
},
324+
{ pass: true });

0 commit comments

Comments
 (0)