diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index c14318c49..22fe49401 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -7849,6 +7849,7 @@ class MLIRGenImpl llvm::SmallVector> assignedOnceInBranch(Statement branch); void mergedAfterIf(mlir::Location location, StringRef name, mlir::Type thenType, const ElseSafeCases &elseSafeCases, const GenContext &genContext); + void unnarrowWrittenInLoop(mlir::Location location, std::initializer_list loopParts, const GenContext &genContext); mlir::LogicalResult mlirGenBranchStatement(Statement statement, const GenContext &genContext); mlir::LogicalResult mlirGen(DoStatement doStatementAST, const GenContext &genContext); @@ -10515,6 +10516,18 @@ class MLIRGenImpl leftExpressionValueBeforeCast = loaded; } + // a name narrowed by a test inside another's (`x !== null`, then `typeof x === "number"`), or an optional's value + // narrowed (`x?: number | string`): the variable is read under the narrowings (narrowedVariableLoad) + if (auto safeCastOp = leftExpressionValueBeforeCast.getDefiningOp(); + safeCastOp && !safeCastOp->hasAttr(DECLARED_FIELD_VIEW_ATTR_NAME) && + !safeCastOp.getValue().getDefiningOp()) + { + if (auto loadOp = narrowedVariableLoad(leftExpressionValueBeforeCast)) + { + leftExpressionValueBeforeCast = loadOp; + } + } + // TODO: logic to support safe cast if (auto safeCastOp = leftExpressionValueBeforeCast.getDefiningOp()) { @@ -10967,7 +10980,8 @@ class MLIRGenImpl safeCastOp && !safeCastOp->hasAttr(DECLARED_FIELD_VIEW_ATTR_NAME) && !safeCastOp->hasAttr(WEAK_FIELD_VIEW_ATTR_NAME)) { - receiverType = safeCastOp.getValue().getType(); + auto loadOp = narrowedVariableLoad(leftExpressionValue); + receiverType = loadOp ? loadOp.getType() : safeCastOp.getValue().getType(); } rightExprGenContext.receiverType = receiverType; @@ -10992,16 +11006,51 @@ class MLIRGenImpl // (typeof x === "number") { x = "s" + x; print(x); }` printed the number). It is narrowed again, to the type of // what it was given when that is one of its declared union's members, else to its declared type - read again // from its place. In the scope of the assignment. + // The read of the variable a narrowed name is (addSafeCastStatement): under each narrowing - one inside another's + // (`x !== null`, then `typeof x === "number"`) - and under the value taken out of an optional (`x?: number | + // string`). None for a field's view, or a value that is not a variable's. + mlir_ts::LoadOp narrowedVariableLoad(mlir::Value value) + { + while (value) + { + if (auto loadOp = value.getDefiningOp()) + { + return loadOp; + } + + if (auto safeCastOp = value.getDefiningOp()) + { + if (safeCastOp->hasAttr(DECLARED_FIELD_VIEW_ATTR_NAME) || safeCastOp->hasAttr(WEAK_FIELD_VIEW_ATTR_NAME)) + { + return mlir_ts::LoadOp(); + } + + value = safeCastOp.getValue(); + continue; + } + + if (auto valueOp = value.getDefiningOp()) + { + value = valueOp.getIn(); + continue; + } + + break; + } + + return mlir_ts::LoadOp(); + } + void renarrowAfterAssignment(mlir::Location location, StringRef name, mlir::Value narrowedValue, mlir::Type assignedType, const GenContext &genContext) { auto safeCastOp = narrowedValue.getDefiningOp(); - if (!safeCastOp || safeCastOp->hasAttr(DECLARED_FIELD_VIEW_ATTR_NAME) || safeCastOp->hasAttr(WEAK_FIELD_VIEW_ATTR_NAME)) + if (!safeCastOp) { return; } - auto loadOp = safeCastOp.getValue().getDefiningOp(); + auto loadOp = narrowedVariableLoad(narrowedValue); if (!loadOp) { return; @@ -11020,6 +11069,13 @@ class MLIRGenImpl { narrowedType = givenType; } + // `x?: number | string` given a string: a string (addSafeCastStatement takes the union out of the optional) + else if (auto optType = dyn_cast(declaredType); + optType && isa(optType.getElementType()) && + llvm::is_contained(mlir::cast(optType.getElementType()).getTypes(), givenType)) + { + narrowedType = givenType; + } if (narrowedType != declaredType) { diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 6fe36b2c4..09cfe1d21 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -2042,6 +2042,202 @@ namespace mlirgen return mlir::success(); } + // A write of a name in a loop (unnarrowWrittenInLoop): the expression whose type is what the name holds after it - + // the value of `x = e`, the whole of `x += e` - or none: `x++` keeps a number's type, a destructuring gives one not + // looked for. + struct LoopWrite + { + Expression value; + bool keepsType = false; + }; + + // The names `node` writes: `x = e`, `x += e`, `x++`, `[x, y] = ...`, `({ x } = ...)` - in a nested loop or function + // too. A name in a destructuring target is taken whatever it is there (`{ k: x }` gives `k` as well): taking one too + // many only reads that variable again. + static void collectLoopWrites(Node node, llvm::StringMap> &writes) + { + if (!node) + { + return; + } + + auto stripped = [](Node target) { + while (target == SyntaxKind::ParenthesizedExpression) + { + target = target.as()->expression; + } + + return target; + }; + + auto addTarget = [&](Node target, LoopWrite write) { + target = stripped(target); + if (target == SyntaxKind::Identifier) + { + writes[MLIRHelper::getName(target.as())].push_back(write); + } + else if (target == SyntaxKind::ArrayLiteralExpression || target == SyntaxKind::ObjectLiteralExpression) + { + FilterVisitorAST identifiers(SyntaxKind::Identifier, [&](auto identifier) { + writes[MLIRHelper::getName(identifier.template as())].push_back(LoopWrite()); + }); + identifiers.visit(target); + } + }; + + FilterVisitorAST binaryVisitor(SyntaxKind::BinaryExpression, [&](auto binary) { + auto binExpr = binary.template as(); + auto op = (SyntaxKind)binExpr->operatorToken; + if (isAssignmentOperator(op)) + { + auto value = op == SyntaxKind::EqualsToken ? binExpr->right : Expression(binExpr); + addTarget(binExpr->left, stripped(binExpr->left) == SyntaxKind::Identifier ? LoopWrite{value} : LoopWrite()); + } + }); + binaryVisitor.visit(node); + + FilterVisitorAST prefixVisitor(SyntaxKind::PrefixUnaryExpression, [&](auto unary) { + auto unaryExpr = unary.template as(); + if (unaryExpr->_operator == SyntaxKind::PlusPlusToken || unaryExpr->_operator == SyntaxKind::MinusMinusToken) + { + addTarget(unaryExpr->operand, LoopWrite{Expression(), true}); + } + }); + prefixVisitor.visit(node); + + FilterVisitorAST postfixVisitor(SyntaxKind::PostfixUnaryExpression, [&](auto unary) { + auto unaryExpr = unary.template as(); + if (unaryExpr->_operator == SyntaxKind::PlusPlusToken || unaryExpr->_operator == SyntaxKind::MinusMinusToken) + { + addTarget(unaryExpr->operand, LoopWrite{Expression(), true}); + } + }); + postfixVisitor.visit(node); + } + + // A loop that writes a variable a test before it narrowed (addSafeCastStatement: `if (p !== null)`, the body of a + // `while (p !== null)` around it, ...): the narrowed name was the value the test read, once, before the loop, and + // the loop's next turns - its condition too - read that value again, not what the turn before left in the variable + // (`p = p.next` never moved on, TSLANG 235). In the loop and after it the name is the variable, read at each use. + // Its type is what it is narrowed to here and what the loop writes, as tsc takes it at the loop's head: `x = x + 1` + // keeps a `number` one, `p = p.next` makes `L` an `L | null`. A write whose type can't be told (a value made of + // the loop's own locals, a destructuring) leaves it the type it is declared with. Not in a generator, whose + // narrowed local is a view read at each use already. + void MLIRGenImpl::unnarrowWrittenInLoop(mlir::Location location, std::initializer_list loopParts, + const GenContext &genContext) + { + if (genContext.allocateVarsInContextThis) + { + return; + } + + llvm::StringMap> writes; + for (auto part : loopParts) + { + collectLoopWrites(part, writes); + } + + for (auto &entry : writes) + { + auto name = entry.getKey(); + if (!symbolTable.count(name)) + { + continue; + } + + auto current = symbolTable.lookup(name).first; + auto safeCastOp = current ? current.getDefiningOp() : mlir_ts::SafeCastOp(); + if (!safeCastOp) + { + continue; + } + + // (under each narrowing: one inside another's, an optional's value) + auto loadOp = narrowedVariableLoad(current); + if (!loadOp) + { + continue; + } + + auto declaredType = loadOp.getType(); + auto narrowedType = safeCastOp.getType(); + + // the members it may have at the loop's head: those it is narrowed to and those the loop writes, each a + // member of the union it is declared with + auto declaredUnion = dyn_cast(declaredType); + llvm::SmallVector members; + auto known = !!declaredUnion; + auto add = [&](mlir::Type type) { + auto typeUnion = dyn_cast(type); + auto typeMembers = typeUnion ? typeUnion.getTypes() : llvm::ArrayRef(type); + for (auto member : typeMembers) + { + if (!llvm::is_contained(declaredUnion.getTypes(), member)) + { + known = false; + return; + } + + if (!llvm::is_contained(members, member)) + { + members.push_back(member); + } + } + }; + + if (known) + { + add(narrowedType); + } + + for (auto &write : entry.getValue()) + { + if (!known) + { + break; + } + + if (write.keepsType) + { + continue; + } + + mlir::Type writtenType; + if (write.value) + { + // (a value the loop's own locals make is not resolved here: no error of it) + mlir::ScopedDiagnosticHandler diagHandler(builder.getContext(), [&](mlir::Diagnostic &) {}); + writtenType = evaluate(write.value, genContext); + } + + if (!writtenType) + { + known = false; + break; + } + + add(mth.wideStorageType(writtenType)); + } + + mlir::Type loopType = declaredType; + if (known && members.size() < declaredUnion.getTypes().size()) + { + loopType = members.size() == 1 ? members.front() : getUnionType(members); + } + + // (declared into the symbol table as it is: declare() would give the variable's op the loop's debug scope) + auto ownName = StringRef(name).copy(stringAllocator); + auto view = std::make_shared(ownName, loopType, location); + view->setReadWriteAccess(); + if (loopType != declaredType) + { + view->setNarrowedType(loopType); + } + + symbolTable.insert(ownName, {loadOp.getReference(), view}); + } + } + // A branch written without braces (`else for (const c of gen()) ...`) is a scope all the same: // what it registers to give back at the end of its block - an owned local such as a // generator's iterator, a `using` - belongs to the branch, whose region it is defined in, not @@ -2084,6 +2280,9 @@ namespace mlirgen mlir::LogicalResult MLIRGenImpl::mlirGen(DoStatement doStatementAST, const GenContext &genContext) { + // (before the loop's scope: the name is the variable after the loop too) + unnarrowWrittenInLoop(loc(doStatementAST), {doStatementAST->statement, doStatementAST->expression}, genContext); + SymbolTableScopeT varScope(symbolTable); auto location = loc(doStatementAST); @@ -2133,6 +2332,9 @@ namespace mlirgen mlir::LogicalResult MLIRGenImpl::mlirGen(WhileStatement whileStatementAST, const GenContext &genContext) { + // (before the loop's scope: the name is the variable after the loop too) + unnarrowWrittenInLoop(loc(whileStatementAST), {whileStatementAST->expression, whileStatementAST->statement}, genContext); + SymbolTableScopeT varScope(symbolTable); auto location = loc(whileStatementAST); @@ -2319,6 +2521,13 @@ namespace mlirgen mlir::LogicalResult MLIRGenImpl::mlirGen(ForStatement forStatementAST, const GenContext &genContext) { + // (before the loop's scope: the name is the variable after the loop too; again after the initializer below, + // which may narrow it again - `for (p = head; ...)`) + unnarrowWrittenInLoop(loc(forStatementAST), + {forStatementAST->initializer, forStatementAST->condition, forStatementAST->incrementor, + forStatementAST->statement}, + genContext); + SymbolTableScopeT varScope(symbolTable); auto location = loc(forStatementAST); @@ -2349,6 +2558,9 @@ namespace mlirgen } } + unnarrowWrittenInLoop(location, {forStatementAST->condition, forStatementAST->incrementor, forStatementAST->statement}, + genContext); + SmallVector types; SmallVector operands; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 7313de097..6048c0b59 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2784,6 +2784,17 @@ set_tests_properties(test-compile-own-rest-kept-through-class-value-error PROPER foreach(issue233_mm gc rc none own) tslang_add_test(NAME test-compile-import-declared-method-overloads-${issue233_mm} COMMAND test-runner -mm=${issue233_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_declared_method_overloads.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_declared_method_overloads.ts") endforeach() +# TSLANG 235: a variable narrowed before a loop and written in it is read again on each turn and after the loop +# (not -mm=own: walking a linked list by the references its links hold is a borrow own refuses to store) +foreach(issue235_mm gc rc none) + tslang_add_test(NAME test-jit-00tslang_issue_235-${issue235_mm} COMMAND test-runner -jit -mm=${issue235_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_235.ts") + tslang_add_test(NAME test-compile-00tslang_issue_235-${issue235_mm} COMMAND test-runner -mm=${issue235_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_235.ts") +endforeach() +# ...and its type in the loop: what it is narrowed to and what the loop writes +foreach(issue235_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_235_types-${issue235_mm} COMMAND test-runner -jit -mm=${issue235_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_235_types.ts") + tslang_add_test(NAME test-compile-00tslang_issue_235_types-${issue235_mm} COMMAND test-runner -mm=${issue235_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_235_types.ts") +endforeach() add_test(NAME test-compile-declared-method-overloads-warning COMMAND $ --emit=obj --no-default-lib -mm=none "${PROJECT_SOURCE_DIR}/test/tester/tests/declared_method_overloads_warning.ts" diff --git a/tslang/test/tester/tests/00tslang_issue_235.ts b/tslang/test/tester/tests/00tslang_issue_235.ts new file mode 100644 index 000000000..b7ecf57f7 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_235.ts @@ -0,0 +1,166 @@ +// TSLANG 235: a variable a test narrowed before a loop, written in the loop. The narrowed name was the value the test +// read, once: the loop's condition and its next turns read that value again, not what the loop stored (`p = p.next` +// never moved on; a linked-list merge sort pointed its links back at themselves and hung). In the loop and after it, +// the name is the variable again. + +class L { + i: int; + next: L | null = null; + constructor(i: int) { this.i = i; } +} + +function nn(n: L | null): L { return n!; } + +function list3(): L { + const a = new L(0); + const b = new L(1); + const c = new L(2); + a.next = b; + b.next = c; + return a; +} + +// narrowed by an `if`; read in the condition, on the second turn and after the loop +function afterIf(): string { + let p: L | null = list3(); + let s = ""; + if (p !== null) { + let n: int = 0; + while (n < 2) { s += `${p!.i} `; p = p!.next; n++; } + s += `after ${p === null ? -1 : nn(p).i}`; + } + + return s; +} + +// an early return narrows; `do`, `for` (condition and incrementor) and `for...of` +function afterReturn(head: L | null): string { + let p: L | null = head; + if (p === null) { + return "none"; + } + + let s = ""; + do { s += `${p!.i}`; p = p!.next; } while (p !== null); + s += "|"; + + p = head; + for (; p !== null; p = p.next) { s += `${p.i}`; } + s += "|"; + + p = head; + const xs: int[] = [1, 2]; + for (const x of xs) { s += `${nn(p).i}`; p = nn(p).next; } + s += `|${nn(p).i}`; + return s; +} + +// the narrowing of an enclosing loop's condition, read by an inner loop that writes the variable +function innerLoop(): int { + let p: L | null = list3(); + let steps: int = 0; + while (p !== null) { + let n: int = 1; + while (n > 0 || p !== null) { + const e = nn(p); + p = e.next; + n--; + if (p === null) { break; } + } + + steps++; + if (steps > 10) { break; } + } + + return steps; +} + +// the merge sort of three.js's earcut z-order pass (the program the issue was found in) +class ZN { + i: int; + z: int; + prevZ: ZN | null = null; + nextZ: ZN | null = null; + constructor(i: int, z: int) { this.i = i; this.z = z; } +} + +function zn(n: ZN | null): ZN { return n!; } + +function sortLinked(listIn: ZN) { + let list: ZN | null = listIn; + let numMerges: int = 0; + let inSize: int = 1; + do { + let p: ZN | null = list; + list = null; + let tail: ZN | null = null; + numMerges = 0; + while (p !== null) { + numMerges++; + let q: ZN | null = p; + let pSize: int = 0; + for (let i: int = 0; i < inSize; i++) { + pSize++; + q = zn(q).nextZ; + if (q === null) { break; } + } + + let qSize: int = inSize; + while (pSize > 0 || (qSize > 0 && q !== null)) { + let e: ZN = zn(p); + let takeP = false; + if (pSize != 0) { + if (qSize == 0 || q === null) { takeP = true; } else if (zn(p).z <= zn(q).z) { takeP = true; } + } + + if (takeP) { e = zn(p); p = e.nextZ; pSize--; } else { e = zn(q); q = e.nextZ; qSize--; } + if (tail !== null) { zn(tail).nextZ = e; } else { list = e; } + e.prevZ = tail; + tail = e; + } + + p = q; + } + + zn(tail).nextZ = null; + inSize *= 2; + } while (numMerges > 1); +} + +function mergeSort(): string { + const zs: int[] = [5, 3, 9, 1, 7, 2]; + const nodes: ZN[] = []; + for (let i = 0; i < zs.length; i++) { nodes.push(new ZN(i, zs[i])); } + for (let i = 0; i + 1 < nodes.length; i++) { nodes[i].nextZ = nodes[i + 1]; nodes[i + 1].prevZ = nodes[i]; } + sortLinked(nodes[0]); + let s = ""; + for (let i = 0; i < nodes.length; i++) { + const n = nodes[i]; + const pz = n.prevZ; + const nz = n.nextZ; + s += `${n.i}:${pz === null ? -1 : zn(pz).i}/${nz === null ? -1 : zn(nz).i} `; + } + + return s; +} + +function main() { + const a = afterIf(); + print(a); + assert(a == "0 1 after 2"); + + const r = afterReturn(list3()); + print(r); + assert(r == "012|012|01|2"); + assert(afterReturn(null) == "none"); + + const steps = innerLoop(); + print(steps); + assert(steps == 1); + + const m = mergeSort(); + print(m); + assert(m == "0:1/4 1:5/0 2:4/-1 3:-1/5 4:0/2 5:3/1 "); + + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_235_types.ts b/tslang/test/tester/tests/00tslang_issue_235_types.ts new file mode 100644 index 000000000..720a7f862 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_235_types.ts @@ -0,0 +1,105 @@ +// TSLANG 235 (see 00tslang_issue_235.ts): a variable narrowed before a loop and written in it, of types -mm=own takes +// too. Its type in the loop is what it is narrowed to and what the loop writes, as tsc takes it at the loop's head. + +// a `typeof` narrowing, the loop giving it a member of another type +function typeofNarrowed(): string { + let x: string | number = 1; + let t = ""; + if (typeof x === "number") { + for (let k = 0; k < 2; k++) { t += `${typeof x} `; x = "s"; } + } + + return t; +} + +// the loop writes a member of the type it is narrowed to: it stays narrowed to that (tsc's type at the loop's head) +function keepsNarrowed(x: string | number): string { + if (typeof x === "number") { + for (let k = 0; k < 3; k++) { x = x + 1; } + return `${x * 2}`; + } + + return x; +} + +function* gen() { yield 1; yield 2; } + +// `for...of` an iterator and `for...in` +function iteratorAndKeys(): string { + let x: string | number = 1; + let s = ""; + if (typeof x === "number") { + for (const v of gen()) { s += `${typeof x}${v} `; x = "s"; } + } + + let y: string | number = 1; + const o = { a: 1, b: 2 }; + if (typeof y === "number") { + for (const k in o) { s += `${typeof y}${k} `; y = "s"; } + } + + return s; +} + +// assigned under a narrowing inside another's (`x !== null`, then `typeof x`), and an optional's value narrowed: +// "can't assign to a value of type 'number | string'"; it is the variable, narrowed again to what it is given +function doubleNarrowed(x: string | number | null): string { + let s = ""; + if (x !== null) { + if (typeof x === "number") { + s += `${x} `; + x = "s"; + s += `${x} `; + x = 4.5; + s += `${x * 2} `; + } + } + + if (x !== null) { + if (typeof x === "number") { + for (let k = 0; k < 2; k++) { s += `${x} `; x = "t"; } + } + } + + return s + (x === null ? "null" : `${x}`); +} + +function optionalNarrowed(x?: number | string): string { + let s = ""; + if (typeof x === "number") { + s += `${x} `; + x = "s"; + s += `${x} `; + } + + let y: number | string | undefined = 1; + if (typeof y === "number") { + for (let k = 0; k < 2; k++) { s += `${y} `; y = "t"; } + } + + return s + `${x}${y}`; +} + +function main() { + const t = typeofNarrowed(); + print(t); + assert(t == "number string "); + + const kn = keepsNarrowed(1); + print(kn); + assert(kn == "8"); + + const ik = iteratorAndKeys(); + print(ik); + assert(ik == "number1 string2 numbera stringb "); + + const dn = doubleNarrowed(1); + print(dn); + assert(dn == "1 s 9 4.5 t t"); + + const on = optionalNarrowed(1); + print(on); + assert(on == "1 s 1 t st"); + + print("done."); +}