From 6cc4aba4efed6357c54cc2b26fc0a85c17ae910b Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 26 Oct 2026 10:31:33 +0000 Subject: [PATCH] Narrowing by && and ||: no else narrowing for &&, both sides of || checkSafeCast handed its one else slot to both sides of `&&`, so the else branch of `x === undefined && k` (false also when only `k` is) read x as defined: an undefined x became a number, and `x === undefined` was false there. It also stopped at a left side that is no test (`k && x !== undefined` narrowed nothing) and had no `||` case. Now `&&` narrows its then branch by both sides and its else branch by neither; `||` narrows its else branch, and what follows when its then branch exits, by both sides (a list of else cases, gathered in a temporary module so the sides' then narrowings emit nothing). The right side of `||` is narrowed by the left being false (`x === undefined || x > 1`). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenExpressions.cpp | 14 +- tslang/lib/TypeScript/MLIRGenImpl.h | 77 +++++++--- tslang/lib/TypeScript/MLIRGenStatements.cpp | 14 +- tslang/test/tester/CMakeLists.txt | 3 + .../test/tester/tests/00narrowing_and_or.ts | 138 ++++++++++++++++++ 5 files changed, 209 insertions(+), 37 deletions(-) create mode 100644 tslang/test/tester/tests/00narrowing_and_or.ts diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 3b629c18f..e7f6de2d1 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -704,14 +704,14 @@ namespace mlirgen builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); auto whenTrueExpression = conditionalExpressionAST->whenTrue; - ElseSafeCase elseSafeCase; + ElseSafeCases elseSafeCases; mlir::Value resultTrue; if (staticCondition.value_or(true)) { // check if we do safe-cast here SymbolTableScopeT varScope(symbolTable); SafeTypesMapScopeT safeTypesMapScope(safeTypesMap); - checkSafeCast(conditionalExpressionAST->condition, V(result), &elseSafeCase, genContext); + checkSafeCast(conditionalExpressionAST->condition, V(result), &elseSafeCases, genContext); auto result = mlirGen(whenTrueExpression, genContext); if (!genContext.allowPartialResolve) { @@ -735,10 +735,7 @@ namespace mlirgen { SymbolTableScopeT varScope(symbolTable); SafeTypesMapScopeT safeTypesMapScope(safeTypesMap); - if (elseSafeCase.safeType) - { - addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, genContext); - } + addElseSafeCastStatements(elseSafeCases, genContext); auto result2 = mlirGen(whenFalseExpression, genContext); if (!genContext.allowPartialResolve) @@ -751,10 +748,7 @@ namespace mlirgen else { resultFalse = mlirGenSkippedBranch(location, whenFalseExpression, [&](const GenContext &evalGenContext) { - if (elseSafeCase.safeType) - { - addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, evalGenContext); - } + addElseSafeCastStatements(elseSafeCases, evalGenContext); }, genContext); } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index b307939f1..48760fd72 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -4144,6 +4144,18 @@ class MLIRGenImpl mlir::Type safeType; }; + // what a false condition narrows: one test gives one case, `a || b` (false when both are) gives + // the cases of both + using ElseSafeCases = SmallVector; + + void addElseSafeCastStatements(const ElseSafeCases &elseSafeCases, const GenContext &genContext) + { + for (auto &elseSafeCase : elseSafeCases) + { + addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, genContext); + } + } + mlir::LogicalResult addSafeCastStatement(Expression expr, Node typeToken, bool inverse, ElseSafeCase* elseSafeCase, const GenContext &genContext) { auto safeType = getType(typeToken, genContext); @@ -4750,7 +4762,9 @@ class MLIRGenImpl return addSafeCastStatement(expr, typePredicateType.getElementType(), inverse, elseSafeCase, genContext); } - mlir::LogicalResult checkSafeCast(Expression exprIn, mlir::Value conditionValue, ElseSafeCase *elseSafeCase, const GenContext &genContext) + // Narrows the then branch of a condition here, and gathers into elseSafeCases what narrows its + // else branch (the caller adds those there). + mlir::LogicalResult checkSafeCast(Expression exprIn, mlir::Value conditionValue, ElseSafeCases *elseSafeCases, const GenContext &genContext) { auto expr = stripParentheses(exprIn); @@ -4760,25 +4774,51 @@ class MLIRGenImpl auto op = (SyntaxKind)binExpr->operatorToken; if (op == SyntaxKind::AmpersandAmpersandToken) { - auto left = binExpr->left; - auto leftResult = checkSafeCast(left, conditionValue, elseSafeCase, genContext); - if (mlir::failed(leftResult)) - { - return leftResult; - } + // `a && b` is true when both are: each side narrows the then branch, also when the other + // is no test (`k && x !== undefined` stopped at `k`). It is false when either is, so + // neither narrows the else branch: in the else of `x === undefined && k`, x was read as + // defined + auto leftResult = checkSafeCast(binExpr->left, conditionValue, nullptr, genContext); + auto rightResult = checkSafeCast(binExpr->right, conditionValue, nullptr, genContext); + return mlir::success(mlir::succeeded(leftResult) || mlir::succeeded(rightResult)); + } - auto right = binExpr->right; - auto rightResult = checkSafeCast(right, conditionValue, elseSafeCase, genContext); - if (mlir::failed(rightResult)) + if (op == SyntaxKind::BarBarToken) + { + // `a || b` is true when either is: neither narrows the then branch. It is false when both + // are, so the else branch has what each side's being false gives + if (elseSafeCases) { - return rightResult; + collectElseSafeCases(binExpr->left, conditionValue, *elseSafeCases, genContext); + collectElseSafeCases(binExpr->right, conditionValue, *elseSafeCases, genContext); } return mlir::success(); } } - return checkSafeCastOne(exprIn, conditionValue, elseSafeCase, genContext); + ElseSafeCase elseSafeCase{}; + auto result = checkSafeCastOne(exprIn, conditionValue, elseSafeCases ? &elseSafeCase : nullptr, genContext); + if (elseSafeCases && elseSafeCase.safeType) + { + elseSafeCases->push_back(elseSafeCase); + } + + return result; + } + + // What a condition's being false narrows, without narrowing anything where it is true: the casts + // checkSafeCast emits for that go to a temporary module, thrown away + void collectElseSafeCases(Expression expr, mlir::Value conditionValue, ElseSafeCases &elseSafeCases, const GenContext &genContext) + { + TempModuleScope tempModuleScope(*this); + SymbolTableScopeT varScope(symbolTable); + SafeTypesMapScopeT safeTypesMapScope(safeTypesMap); + + GenContext evalGenContext(genContext); + evalGenContext.allowPartialResolve = true; + evalGenContext.funcOp = tempFuncOp; + checkSafeCast(expr, conditionValue, &elseSafeCases, evalGenContext); } mlir::LogicalResult checkSafeCastOne(Expression exprIn, mlir::Value conditionValue, ElseSafeCase *elseSafeCase, const GenContext &genContext) @@ -5604,7 +5644,6 @@ class MLIRGenImpl builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); - ElseSafeCase elseSafeCase; mlir::Value resultTrue; { if (rightSkipped) @@ -5617,7 +5656,7 @@ class MLIRGenImpl // check if we do safe-cast here SymbolTableScopeT varScope(symbolTable); SafeTypesMapScopeT safeTypesMapScope(safeTypesMap); - checkSafeCast(leftExpression, V(result), &elseSafeCase, genContext); + checkSafeCast(leftExpression, V(result), nullptr, genContext); auto result = mlirGen(rightExpression, genContext); EXIT_IF_FAILED_OR_NO_VALUE(result) @@ -5658,10 +5697,12 @@ class MLIRGenImpl { SymbolTableScopeT varScope(symbolTable); SafeTypesMapScopeT safeTypesMapScope(safeTypesMap); - if (elseSafeCase.safeType) - { - addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, genContext); - } + + // the right side of `||` runs when the left is false: `x === undefined || x > 1` + // compares a defined x. Never gathered before, as only `&&` checked its left side + ElseSafeCases elseSafeCases; + collectElseSafeCases(leftExpression, leftExpressionValue, elseSafeCases, genContext); + addElseSafeCastStatements(elseSafeCases, genContext); auto result = mlirGen(rightExpression, genContext); EXIT_IF_FAILED_OR_NO_VALUE(result) diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 9a43d5c4f..a55bbb2a0 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -655,7 +655,7 @@ namespace mlirgen // value, and for a statically decided test that cast can be one the value cannot take - an array // narrowed to `string` by `typeof x === "string"`. Under --di the narrowed variable's debug record // keeps such a cast alive into LLVM lowering even though the branch body was skipped. - ElseSafeCase elseSafeCase{}; + ElseSafeCases elseSafeCases; // `if (x === null) return;` narrows x for the rest of the block, as an else branch would auto thenExits = !hasElse && !literalValue.has_value() && genContext.funcOp && statementAlwaysExits(ifStatementAST->thenStatement); @@ -667,7 +667,7 @@ namespace mlirgen if (processIf) { // check if we do safe-cast here - checkSafeCast(ifStatementAST->expression, V(result), hasElse || thenExits ? &elseSafeCase : nullptr, genContext); + checkSafeCast(ifStatementAST->expression, V(result), hasElse || thenExits ? &elseSafeCases : nullptr, genContext); auto result = mlirGenBranchStatement(ifStatementAST->thenStatement, genContext); EXIT_IF_FAILED(result) @@ -684,11 +684,7 @@ namespace mlirgen auto processIf = !literalValue.has_value() || !literalValue.value(); if (processIf) { - if (elseSafeCase.safeType) - { - // add case statement - addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, genContext); - } + addElseSafeCastStatements(elseSafeCases, genContext); auto result = mlirGenBranchStatement(ifStatementAST->elseStatement, genContext); EXIT_IF_FAILED(result) @@ -697,9 +693,9 @@ namespace mlirgen builder.setInsertionPointAfter(ifOp); - if (thenExits && elseSafeCase.safeType) + if (thenExits) { - addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, genContext); + addElseSafeCastStatements(elseSafeCases, genContext); } return mlir::success(); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 5e51a33f9..80714fb4d 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -285,6 +285,7 @@ tslang_add_test(NAME test-compile-00-int64-mul-literal COMMAND test-runner "${PR tslang_add_test(NAME test-compile-00-int-literal-above-s32 COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00int_literal_above_s32.ts") tslang_add_test(NAME test-compile-00-literal-union-arith COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00literal_union_arith.ts") tslang_add_test(NAME test-compile-00-literal-union-cast COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00literal_union_cast.ts") +tslang_add_test(NAME test-compile-00-narrowing-and-or COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrowing_and_or.ts") tslang_add_test(NAME test-compile-00-bool-const-array COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00bool_const_array.ts") tslang_add_test(NAME test-compile-00-mixed-type-ops COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00mixed_type_ops.ts") tslang_add_test(NAME test-compile-00-generator-manual-next COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_manual_next.ts") @@ -887,6 +888,7 @@ tslang_add_test(NAME test-jit-00-int64-mul-literal COMMAND test-runner -jit "${P tslang_add_test(NAME test-jit-00-int-literal-above-s32 COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00int_literal_above_s32.ts") tslang_add_test(NAME test-jit-00-literal-union-arith COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00literal_union_arith.ts") tslang_add_test(NAME test-jit-00-literal-union-cast COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00literal_union_cast.ts") +tslang_add_test(NAME test-jit-00-narrowing-and-or COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrowing_and_or.ts") tslang_add_test(NAME test-jit-00-bool-const-array COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00bool_const_array.ts") tslang_add_test(NAME test-jit-00-mixed-type-ops COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00mixed_type_ops.ts") tslang_add_test(NAME test-jit-00-generator-manual-next COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00generator_manual_next.ts") @@ -2117,6 +2119,7 @@ set(TSLANG_CORPUS 00int_literal_above_s32.ts 00literal_union_arith.ts 00literal_union_cast.ts + 00narrowing_and_or.ts 00bool_const_array.ts 00break_continue_scope_exit.ts 00break_continue.ts diff --git a/tslang/test/tester/tests/00narrowing_and_or.ts b/tslang/test/tester/tests/00narrowing_and_or.ts new file mode 100644 index 000000000..984a23189 --- /dev/null +++ b/tslang/test/tester/tests/00narrowing_and_or.ts @@ -0,0 +1,138 @@ +// regression test: narrowing by a condition joined with && or ||. +// +// bugs found and fixed: +// - the else branch of `x === undefined && k` read x as defined: what `x === undefined` being false +// says was taken for the whole `&&`, which is false also when only `k` is. An undefined x was read +// as a number there, and `x === undefined` was false; +// - `k && x !== undefined` didn't narrow x: the test stopped at `k`; +// - `||` narrowed nothing: not the else branch (false when both sides are), not what follows +// `if (x === undefined || k) return;`, not the right side of `x === undefined || x > 1`. + +class C { + v = 7; + get(): number { return this.v; } +} + +// the else branch of `&&` is not narrowed +function andElse(a: number | undefined, k: boolean) { + if (a === undefined && k) { + return "then"; + } else { + const e = a; + return e === undefined ? "else undefined" : "else " + e; + } +} + +function andElseExits(a: C | undefined, k: boolean) { + if (a === undefined && k) return "then"; + const e = a; + return e === undefined ? "after undefined" : "after " + e.get(); +} + +// both sides of `&&` narrow its then branch +function andRight(a: number | undefined, k: boolean) { + if (k && a !== undefined) { + const n: number = a; + return n * 2; + } + + return -1; +} + +function andBoth(a: number | undefined, b: number | undefined) { + if (a !== undefined && b !== undefined) { + return a + b; + } + + return -1; +} + +// `||`: its else branch, what follows when its then branch exits, its right side +function orElse(a: number | undefined, k: boolean) { + if (a === undefined || k) { + return -1; + } else { + const n: number = a; + return n * 2; + } +} + +function orExits(a: C | undefined, b: C | undefined) { + if (a === undefined || b === undefined) return -1; + return a.get() + b.get(); +} + +function orRight(a: number | undefined) { + return a === undefined || a > 1; +} + +function orThen(a: number | undefined, k: boolean) { + if (a !== undefined || k) { + const t = a; + return t === undefined ? "then undefined" : "then " + t; + } + + return "else"; +} + +function orNull(a: C | null, k: boolean) { + if (a === null || k) return -1; + return a.get(); +} + +function orTypeOf(a: string | number, k: boolean) { + if (typeof a === "string" || k) return -1; + const n: number = a; + return n * 2; +} + +function ternary(a: number | undefined, k: boolean) { + return a === undefined || k ? -1 : a * 2; +} + +function main() { + assert(andElse(undefined, false) == "else undefined"); + assert(andElse(3, false) == "else 3"); + assert(andElse(3, true) == "else 3"); + assert(andElse(undefined, true) == "then"); + + assert(andElseExits(undefined, false) == "after undefined"); + assert(andElseExits(new C(), false) == "after 7"); + assert(andElseExits(undefined, true) == "then"); + + assert(andRight(21, true) == 42); + assert(andRight(21, false) == -1); + assert(andRight(undefined, true) == -1); + + assert(andBoth(1, 2) == 3); + assert(andBoth(1, undefined) == -1); + + assert(orElse(21, false) == 42); + assert(orElse(21, true) == -1); + assert(orElse(undefined, false) == -1); + + assert(orExits(new C(), new C()) == 14); + assert(orExits(new C(), undefined) == -1); + assert(orExits(undefined, new C()) == -1); + + assert(orRight(undefined)); + assert(orRight(5)); + assert(!orRight(0)); + + assert(orThen(4, false) == "then 4"); + assert(orThen(undefined, true) == "then undefined"); + assert(orThen(undefined, false) == "else"); + + assert(orNull(new C(), false) == 7); + assert(orNull(null, false) == -1); + assert(orNull(new C(), true) == -1); + + assert(orTypeOf(21, false) == 42); + assert(orTypeOf("s", false) == -1); + assert(orTypeOf(21, true) == -1); + + assert(ternary(21, false) == 42); + assert(ternary(undefined, false) == -1); + + print("done."); +}