From 523039a43d733df00804b05a948db6521c959237 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 21:25:29 +0000 Subject: [PATCH 1/3] x.name and x[k] = v of a value of type any, through the keys adapter (ANY_KEYS_OP_SET); a write of an optional interface field an object has no place for throws - `x.name` of `x: any` is `x["name"]`, read at run time; the member probe (evaluatePropertyValue) still finds none on `any`, as `i in a` asks it of `length` - `x[k] = v`, `x.name = v`, `+=` and `++` write through the adapter: a plain `=` makes no read (a getter does not run); a key the type has not got, a method, an accessor with no setter, a tuple's key (the `any` holds a copy) and a value not of a number, string or boolean key's kind are TypeErrors; an array is written in range or one past its end - `s[i]` of a string in an `any` is a string, as in JavaScript (it was a char) - `i.o = v` of an interface whose object was made without the optional field `o` stored through a null address: it throws Co-Authored-By: Claude Opus 5.5 --- tslang/include/TypeScript/Defines.h | 6 +- tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 7 + tslang/lib/TypeScript/MLIRGenCast.cpp | 164 ++++++++++++++++-- tslang/lib/TypeScript/MLIRGenImpl.h | 73 +++++++- tslang/test/tester/CMakeLists.txt | 14 +- .../tester/crash-errors/any_key_assign.ts | 3 - .../tester/crash-errors/any_key_compound.ts | 3 - .../tester/crash-errors/any_key_increment.ts | 3 - tslang/test/tester/tests/00any_keys_write.ts | 139 +++++++++++++++ 9 files changed, 368 insertions(+), 44 deletions(-) delete mode 100644 tslang/test/tester/crash-errors/any_key_assign.ts delete mode 100644 tslang/test/tester/crash-errors/any_key_compound.ts delete mode 100644 tslang/test/tester/crash-errors/any_key_increment.ts create mode 100644 tslang/test/tester/tests/00any_keys_write.ts diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index b03056929..292a0fb11 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -686,11 +686,13 @@ // For a tuple, class, interface or array type, the address of the adapter that reads a key of a value of // the type held in an `any` - `(box: any, op: number, key: any, value: any) => any`, made when the value // is boxed (user ruling 11-19, MLIRGenImpl::ensureAnyKeysAdapter): op ANY_KEYS_OP_GET is `box[key]`, -// undefined for a key the type does not have, and ANY_KEYS_OP_HAS is `key in box`, a boolean. `value` is -// for an op that writes, none yet. Null for any other type, or when none was made. +// undefined for a key the type does not have, ANY_KEYS_OP_HAS is `key in box`, a boolean, and +// ANY_KEYS_OP_SET is `box[key] = value`, `value` (a TypeError for a key the type has not got, a method, or +// an accessor with no setter: no key is added). Null for any other type, or when none was made. #define TYPE_DESCR_KEYS 6 #define ANY_KEYS_OP_GET 0 #define ANY_KEYS_OP_HAS 1 +#define ANY_KEYS_OP_SET 2 // The block header, last so that it sits immediately in front of the name bytes. A tag is a // `typeof` result, and `typeof x` can be assigned to a `string` and released like any other // string - so a tag has to look like a payload with an immortal block header, exactly as a diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 414609387..bb1f326fe 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -583,6 +583,13 @@ namespace mlirgen } } + // `x.name` of `x: any` is `x["name"]`, looked up at run time (mlirGenAnyKey) + if (!value && isa(objectValue.getType())) + { + auto key = builder.create(location, getStringType(), builder.getStringAttr(name)); + return mlirGenAnyKey(location, objectValue, key, ANY_KEYS_OP_GET, genContext); + } + // an integer (`1..toString()`: an integer literal is an s32) has the members a number has: the default // library declares them on `number`. A member `number` has not got either is reported for the integer. if (!value && isa(objectValue.getType())) diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 45d3d8af1..859203252 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -4645,8 +4645,54 @@ namespace mlirgen static const std::string anyKeyIsNumberSource = "kt == \"number\" || kt == \"s32\" || kt == \"s64\" || kt == \"u32\" || kt == \"u64\""; + // what a write through `any` checks of the value first: a number, a string or a boolean key (or element) takes + // a value of its kind - the conversion `any` makes (a string read as a number is 0) would write what was not + // given. Objects are checked as they are unboxed. Empty for any other type. + static std::string anyKeyValueKind(mlir::Type type) + { + if (auto optionalType = dyn_cast_or_null(type)) + { + auto kind = anyKeyValueKind(optionalType.getElementType()); + return kind.empty() ? kind : kind + " || vt == \"undefined\""; + } + + if (type && (isa(type) || isa(type))) + { + return "vt == \"number\" || vt == \"s32\" || vt == \"s64\" || vt == \"u32\" || vt == \"u64\""; + } + + if (type && isa(type)) + { + return "vt == \"string\""; + } + + if (type && isa(type)) + { + return "vt == \"boolean\""; + } + + return ""; + } + + static std::string anyKeyValueKindCheck(mlir::Type type, bool optional, const std::string &throwWrongKind) + { + auto kind = anyKeyValueKind(type); + if (kind.empty()) + { + return kind; + } + + if (optional) + { + kind += " || vt == \"undefined\""; + } + + return "const vt = typeof value; if (!(" + kind + ")) " + throwWrongKind + " "; + } + bool MLIRGenImpl::anyKeysOfType(mlir::Type type, SmallVector &values, SmallVector &methods, - llvm::StringSet<> *optionals) + llvm::StringSet<> *optionals, llvm::StringSet<> *readOnly, + llvm::StringMap *types) { llvm::StringSet<> seen; auto addKey = [&](SmallVector &keys, StringRef name) { @@ -4679,6 +4725,10 @@ namespace mlirgen name && field.accessLevel == mlir_ts::AccessLevel::Public) { addKey(values, name.getValue()); + if (types) + { + types->try_emplace(name.getValue(), field.type); + } } } @@ -4687,6 +4737,11 @@ namespace mlirgen if (!accessor.isStatic && accessor.get && accessor.getAccessLevel == mlir_ts::AccessLevel::Public) { addKey(values, accessor.name); + // a getter with no public setter: a write through `any` is a TypeError + if (readOnly && !(accessor.set && accessor.setAccessLevel == mlir_ts::AccessLevel::Public)) + { + readOnly->insert(accessor.name); + } } } @@ -4722,6 +4777,11 @@ namespace mlirgen if (auto name = dyn_cast_or_null(field.id)) { addKey(values, name.getValue()); + if (types) + { + types->try_emplace(name.getValue(), field.type); + } + if (field.isConditional && optionals) { optionals->insert(name.getValue()); @@ -4732,6 +4792,10 @@ namespace mlirgen for (auto &accessor : info->accessors) { addKey(values, accessor.name); + if (readOnly && accessor.setMethod.empty()) + { + readOnly->insert(accessor.name); + } } for (auto &method : info->methods) @@ -4824,7 +4888,9 @@ namespace mlirgen SmallVector values; SmallVector methods; llvm::StringSet<> optionals; - if (!isArray && !anyKeysOfType(type, values, methods, &optionals)) + llvm::StringSet<> readOnly; + llvm::StringMap types; + if (!isArray && !anyKeysOfType(type, values, methods, &optionals, &readOnly, &types)) { return; } @@ -4845,24 +4911,49 @@ namespace mlirgen auto inProgress = llvm::make_scope_exit([&]() { anyKeysAdaptersInProgress.erase(hash); }); auto has = std::to_string(ANY_KEYS_OP_HAS); - auto notThere = "return op == " + has + " ? false : undefined;\n"; + auto set = std::to_string(ANY_KEYS_OP_SET); + // a write of a key the type has not got: a value's keys are its type's, none is added + auto noNewKey = "if (op == " + set + ") " + + throwTypeErrorSource("a key the type of the value in the value of type any has not got can't be written") + "\n"; + auto notThere = noNewKey + "return op == " + has + " ? false : undefined;\n"; + auto throwWrongKind = throwTypeErrorSource("the value written through a value of type any is not of the key's type"); std::string name; std::string src; if (isArray) { - name = "__any_keys_array"; + // a write of an element in range, or one past the end (it grows by one). One function for each kind + // of element a write checks (anyKeyValueKind): `_n` numbers, `_s` strings, `_b` booleans. + auto elementType = isa(type) ? mlir::cast(type).getElementType() + : mlir::cast(type).getElementType(); + elementType = mth.stripLiteralType(elementType); + // (an element that may be undefined is not checked: one function per name) + auto kindCheck = isa(elementType) ? std::string() + : anyKeyValueKindCheck(elementType, false, throwWrongKind); + auto suffix = kindCheck.empty() ? "" + : isa(elementType) ? "_s" + : isa(elementType) ? "_b" + : "_n"; + name = "__any_keys_array" + std::string(suffix); src = "function " + name + "(box: any, op: number, key: any, value: any): any {\n" "const kt = typeof key;\n" "const a = box;\n" "if (" + anyKeyIsNumberSource + ") {\n" "const i = key;\n" "const inside = i >= 0 && i < a.length && i % 1 == 0;\n" + "if (op == " + set + ") {\n" + kindCheck + "\n" + "if (inside) { a[i] = value; return undefined; }\n" + "if (i == a.length) { a.push(value); return undefined; }\n" + + throwTypeErrorSource("an element of an array can only be written in its range or just past its end") + "\n" + "}\n" "if (op == " + has + ") return inside;\n" "if (inside) return a[i];\n" "return undefined;\n" "}\n" - "if (kt == \"string\" && key == \"length\") return op == " + has + " ? true : a.length;\n" + + "if (kt == \"string\" && key == \"length\") {\n" + "if (op == " + set + ") " + throwTypeErrorSource("the length of an array can't be written through a value of type any") + "\n" + "return op == " + has + " ? true : a.length;\n" + "}\n" + notThere + "}\n"; } @@ -4894,27 +4985,48 @@ namespace mlirgen "let k = \"\";\n" "if (kt == \"string\") k = key;\n" "else if (" + anyKeyIsNumberSource + ") k = \"\" + key;\n" - "else " + notThere + + "else {\n" + notThere + "}\n" "const o = box;\n"; + + // a tuple is a value: the `any` holds a copy of it, which a write would change and nothing else + auto tuple = isa(type); + auto writeOf = [&](StringRef key, const std::string &place) -> std::string { + if (tuple) + { + return "if (op == " + set + ") " + + throwTypeErrorSource("a key of a tuple can't be written through a value of type any: it holds a copy") + "\n"; + } + + if (readOnly.contains(key)) + { + return "if (op == " + set + ") " + + throwTypeErrorSource("an accessor with no setter can't be written through a value of type any") + "\n"; + } + + return "if (op == " + set + ") { " + anyKeyValueKindCheck(types.lookup(key), optionals.contains(key), throwWrongKind) + + place + " = value; return undefined; }\n"; + }; + for (auto &key : values) { // a tuple's unnamed field is read by its position auto read = isIndex(key) ? "o[" + key + "]" : "o[" + quote(key) + "]"; + src += "if (k == " + quote(key) + ") {\n" + writeOf(key, read); if (optionals.contains(key)) { // an optional field not set is not there: its `typeof` says so, not the value it reads as - src += "if (k == " + quote(key) + ") { const v = " + read + "; const set = typeof v != \"undefined\"; " - "if (op == " + has + ") return set; return set ? v : undefined; }\n"; + src += "const v = " + read + "; const isSet = typeof v != \"undefined\"; " + "if (op == " + has + ") return isSet; return isSet ? v : undefined; }\n"; continue; } - src += "if (k == " + quote(key) + ") return op == " + has + " ? true : " + read + ";\n"; + src += "return op == " + has + " ? true : " + read + ";\n}\n"; } for (auto &key : methods) { src += "if (k == " + quote(key) + ") { if (op == " + has + ") return true; " + - throwTypeErrorSource("a method read through a value of type any is not supported: cast the value to its type") + + throwTypeErrorSource("a method read or written through a value of type any is not supported: cast the value to its type") + " }\n"; } @@ -4987,7 +5099,7 @@ namespace mlirgen } ValueOrLogicalResult MLIRGenImpl::mlirGenAnyKey(mlir::Location location, mlir::Value box, mlir::Value key, int op, - const GenContext &genContext) + const GenContext &genContext, mlir::Value value) { if (compileOptions.memoryModel == MemoryModelOwn) { @@ -5015,19 +5127,21 @@ namespace mlirgen if (!funcRef) { auto has = std::to_string(ANY_KEYS_OP_HAS); + auto set = std::to_string(ANY_KEYS_OP_SET); // `b`: `box` before `typeof` narrowed it std::string src = - "function __any_key(box: any, op: number, key: any): T {\n" + "function __any_key(box: any, op: number, key: any, value: any): T {\n" "const kt = typeof key;\n" "const b = box;\n" "const t = typeof b;\n" - "if (t == \"null\" || t == \"undefined\") " + throwTypeErrorSource("a key of null or undefined can't be read") + "\n" + "if (t == \"null\" || t == \"undefined\") " + throwTypeErrorSource("a key of null or undefined can't be read or written") + "\n" "if (t == \"string\") {\n" "if (op == " + has + ") " + throwTypeErrorSource("'k in x' of a string is not allowed") + "\n" + "if (op == " + set + ") " + throwTypeErrorSource("a string can't be changed") + "\n" "const s = b;\n" "if (" + anyKeyIsNumberSource + ") {\n" "const i = key;\n" - "if (i >= 0 && i < s.length && i % 1 == 0) return s[i];\n" + "if (i >= 0 && i < s.length && i % 1 == 0) return s[i];\n" "return undefined;\n" "}\n" "if (kt == \"string\" && key == \"length\") return s.length;\n" @@ -5038,9 +5152,10 @@ namespace mlirgen "if (t == \"class\" || t == \"tuple\" || t == \"interface\" || t == \"array\" || t == \"object\") " + throwTypeErrorSource("the keys of the value in the value of type any are not known: it was boxed where they were not") + "\n" "if (op == " + has + ") " + throwTypeErrorSource("'k in x' of a value that is not an object is not allowed") + "\n" + "if (op == " + set + ") " + throwTypeErrorSource("a key of a value that is not an object can't be written") + "\n" "return undefined;\n" "}\n" - "return (<(box: any, op: number, key: any, value: any) => any>keys)(b, op, key, undefined);\n" + "return (<(box: any, op: number, key: any, value: any) => any>keys)(b, op, key, value);\n" "}\n"; MLIRLocationGuard vgLoc(overwriteLoc); @@ -5061,10 +5176,22 @@ namespace mlirgen GenContext keyGenContext(genContext); keyGenContext.typeAliasMap.insert({".ANY_KEY_T", getAnyType()}); + mlir::Value valueValue; + if (value) + { + CAST(valueValue, location, getAnyType(), value, genContext); + } + else + { + CAST(valueValue, location, getAnyType(), + builder.create(location, getUndefinedType()), genContext); + } + SmallVector operands; operands.push_back(box); operands.push_back(builder.create(location, getNumberType(), builder.getF64FloatAttr(op))); operands.push_back(keyValue); + operands.push_back(valueValue); auto result = mlirGenCallExpression(location, funcRef, {nf.createTypeReferenceNode(nf.createIdentifier(S(".ANY_KEY_T")).as())}, @@ -5087,11 +5214,18 @@ namespace mlirgen return cast(location, getBooleanType(), V(result), genContext); } + if (op == ANY_KEYS_OP_SET) + { + // `x[k] = v` is `v` + return value; + } + if (auto definingOp = V(result).getDefiningOp()) { definingOp->setAttr(ANY_KEY_READ_ATTR_NAME, builder.getUnitAttr()); } + anyKeyReads[V(result)] = {box, keyValue}; return result; } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index cc09151ab..a4221a153 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -8214,11 +8214,21 @@ class MLIRGenImpl return mlir::failure(); } - // `x[k] = v` (and `+=`, `++`) of `x: any`: a key is only read through `any` (mlirGenAnyKey) - if (auto definingOp = leftExpressionValue.getDefiningOp(); definingOp && definingOp->hasAttr(ANY_KEY_READ_ATTR_NAME)) + // `x[k] = v` (and `+=`, `++`) of `x: any`: written through the adapter of the type of the value it holds, + // as it was read (mlirGenAnyKey). The read a plain `=` made is not needed. + auto leftDefiningOp = leftExpressionValue.getDefiningOp(); + if (auto anyKeyRead = anyKeyReads.find(leftExpressionValue); + anyKeyRead != anyKeyReads.end() && leftDefiningOp && leftDefiningOp->hasAttr(ANY_KEY_READ_ATTR_NAME)) { - emitError(location, "writing 'x[k]' of a value of type 'any' is not supported: cast it to its type first"); - return mlir::failure(); + auto [box, key] = anyKeyRead->second; + anyKeyReads.erase(anyKeyRead); + auto written = mlirGenAnyKey(location, box, key, ANY_KEYS_OP_SET, genContext, rightExpressionValue); + if (leftDefiningOp->getNumResults() == 1 && leftDefiningOp->use_empty()) + { + leftDefiningOp->erase(); + } + + return written; } auto leftExpressionValueBeforeCast = leftExpressionValue; @@ -8352,6 +8362,13 @@ class MLIRGenImpl auto writeOp = mlir::cast(builder.clone(*interfaceSymbolRefOp)); writeOp->setAttr(INTERFACE_OPTIONAL_WRITE_ATTR, builder.getBoolAttr(!storesUndefined)); storeReference = writeOp.getResult(); + + // an object with no place for the field (`const i: I = { n: 1 }`, `I` with `o?: string`): + // its slot gives no address, and the write throws rather than store through none + if (mlir::failed(mlirGenThrowIfNoPlace(location, storeReference, genContext))) + { + return mlir::failure(); + } } } @@ -11043,6 +11060,36 @@ class MLIRGenImpl // holds null or undefined the read throws, as a member of a null interface does: through a stub // made as that one's methods are (mlirGenThrowingMethodStub). The check is a branch with no result, // so nothing is merged. + // throws when `reference` (an optional interface field's place) is null: the object has no place for it + mlir::LogicalResult mlirGenThrowIfNoPlace(mlir::Location location, mlir::Value reference, const GenContext &genContext) + { + auto address = builder.create(location, getOpaqueType(), reference); + auto nullValue = builder.create(location, getNullType()); + auto missing = mlirGenBinaryValues(location, SyntaxKind::EqualsEqualsToken, address, nullValue, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(missing) + + auto stubName = ".optional_field.no_place"; + auto stubType = getFunctionType({getOpaqueType()}, {}, false); + if (mlir::failed(mlirGenThrowingMethodStub(location, ".no_place", stubName, stubType, genContext, + "the object has no place for the optional field written: " + "it was made without it"))) + { + return mlir::failure(); + } + + auto ifOp = builder.create(location, V(missing), false); + mlir::OpBuilder::InsertionGuard guard(builder); + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + + auto stubRef = builder.create( + location, stubType, mlir::FlatSymbolRefAttr::get(builder.getContext(), stubName)); + auto nullThis = builder.create(location, getOpaqueType(), + builder.create(location, getNullType())); + builder.create(MLIRHelper::getCallSiteLocation(stubRef, location), stubRef, + mlir::ValueRange{nullThis}); + return mlir::success(); + } + ValueOrLogicalResult mlirGenPresentValue(mlir::Location location, mlir::Value value, const GenContext &genContext) { auto valueType = MLIRTypeHelper::getMissingValueElement(value.getType()); @@ -12744,9 +12791,13 @@ class MLIRGenImpl // `box[key]` (ANY_KEYS_OP_GET, the value or undefined) or `key in box` (ANY_KEYS_OP_HAS, a boolean) of a // value of type `any` (user ruling 11-19): through the adapter made for the type of the value it holds when - // it was boxed (TYPE_DESCR_KEYS); a string's keys are its characters and `length` + // it was boxed (TYPE_DESCR_KEYS); a string's keys are its characters and `length`. ANY_KEYS_OP_SET writes + // `value` (`box[key] = value`) and gives `value`. ValueOrLogicalResult mlirGenAnyKey(mlir::Location location, mlir::Value box, mlir::Value key, int op, - const GenContext &genContext); + const GenContext &genContext, mlir::Value value = mlir::Value()); + // `x[k]` / `x.name` of `x: any` read (mlirGenAnyKey): the box and the key (as `any`), so that an assignment + // to it writes the key (mlirGenSaveLogicOneItem) + llvm::DenseMap> anyKeyReads; // The adapter `(box: any, op: number, key: any, value: any) => any` for a tuple, class, interface or array // type boxed in an `any`, recorded for its type descriptor (ANY_KEYS_ADAPTERS_ATTR_NAME) @@ -12756,7 +12807,8 @@ class MLIRGenImpl // are there (methods, `methods`), and of the values those that may not be set (`optionals`, an optional field); // false for a type whose keys it does not know bool anyKeysOfType(mlir::Type type, SmallVector &values, SmallVector &methods, - llvm::StringSet<> *optionals = nullptr); + llvm::StringSet<> *optionals = nullptr, llvm::StringSet<> *readOnly = nullptr, + llvm::StringMap *types = nullptr); // the adapter itself, made once the module's statements are (makePendingAnyKeysAdapters) void makeAnyKeysAdapter(mlir::Location location, mlir::Type type, const GenContext &genContext); @@ -17527,6 +17579,13 @@ class MLIRGenImpl mlir::Value evaluatePropertyValue(mlir::Location location, mlir::Value exprValue, const std::string &propertyName, const GenContext &genContext) { + // a value of type `any` has every name to an access (looked up at run time, mlirGenAnyKey), but none to + // the question asked here, whether a type has a member: `i in a` asks it of `length` + if (isa(exprValue.getType())) + { + return mlir::Value(); + } + // we need to ignore errors; mlir::ScopedDiagnosticHandler diagHandler(builder.getContext(), [&](mlir::Diagnostic &diag) { }); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 1238a2e34..583417091 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -342,6 +342,7 @@ tslang_add_test(NAME test-compile-00-cast-any-literal-field COMMAND test-runner tslang_add_test(NAME test-compile-00-symbol-unique-key COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00symbol_unique_key.ts") tslang_add_test(NAME test-compile-00-any-call COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_call.ts") tslang_add_test(NAME test-compile-00-any-keys COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_keys.ts") +tslang_add_test(NAME test-compile-00-any-keys-write COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_keys_write.ts") tslang_add_test(NAME test-compile-00-let-without-initializer-owns COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00let_without_initializer_owns.ts") tslang_add_test(NAME test-compile-00-call-signature-type COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00call_signature_type.ts") tslang_add_test(NAME test-compile-00-f-bounded-generic COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00f_bounded_generic.ts") @@ -1058,6 +1059,7 @@ tslang_add_test(NAME test-jit-00-cast-any-literal-field COMMAND test-runner -jit tslang_add_test(NAME test-jit-00-symbol-unique-key COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00symbol_unique_key.ts") tslang_add_test(NAME test-jit-00-any-call COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_call.ts") tslang_add_test(NAME test-jit-00-any-keys COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_keys.ts") +tslang_add_test(NAME test-jit-00-any-keys-write COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_keys_write.ts") tslang_add_test(NAME test-jit-00-let-without-initializer-owns COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00let_without_initializer_owns.ts") tslang_add_test(NAME test-jit-00-call-signature-type COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00call_signature_type.ts") tslang_add_test(NAME test-jit-00-f-bounded-generic COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00f_bounded_generic.ts") @@ -3158,6 +3160,7 @@ set(TSLANG_CORPUS 00symbol_unique_key.ts 00any_call.ts 00any_keys.ts + 00any_keys_write.ts 00let_without_initializer_owns.ts 00call_signature_type.ts 00f_bounded_generic.ts @@ -4087,17 +4090,6 @@ foreach(any_key_own_case "any_key|2:12|element access of a value of type 'any' \ PROPERTIES PASS_REGULAR_EXPRESSION "${any_key_own_name}\\.ts:${any_key_own_position}: error: ${any_key_own_message} is not supported under -mm=own" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed|PLEASE submit a bug report") endforeach() -# ...and a key is only read through `any`: writing one is an error that says so -foreach(any_key_write_name any_key_assign any_key_compound any_key_increment) - string(REPLACE "_" "-" any_key_write_slug "${any_key_write_name}") - add_test(NAME test-compile-crash-errors-${any_key_write_slug} - COMMAND $ --emit=obj --no-default-lib -mm=none - "${PROJECT_SOURCE_DIR}/test/tester/crash-errors/${any_key_write_name}.ts" - -o "${CMAKE_CURRENT_BINARY_DIR}/crash-errors-${any_key_write_slug}.obj") - set_tests_properties(test-compile-crash-errors-${any_key_write_slug} - PROPERTIES PASS_REGULAR_EXPRESSION "${any_key_write_name}\\.ts:2:5: error: writing 'x\\[k\\]' of a value of type 'any' is not supported" - FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed|PLEASE submit a bug report") -endforeach() # a file name outside the ANSI code page: argv turned it into '?'s ("Could not open input file") set(crash_ok_unicode_file "${CMAKE_CURRENT_BINARY_DIR}/crash-errors-①Ⅻㄨ.ts") file(WRITE "${crash_ok_unicode_file}" "let x = 1;\n") diff --git a/tslang/test/tester/crash-errors/any_key_assign.ts b/tslang/test/tester/crash-errors/any_key_assign.ts deleted file mode 100644 index 45003d77a..000000000 --- a/tslang/test/tester/crash-errors/any_key_assign.ts +++ /dev/null @@ -1,3 +0,0 @@ -function f(a: any, k: string) { - a[k] = 1; -} diff --git a/tslang/test/tester/crash-errors/any_key_compound.ts b/tslang/test/tester/crash-errors/any_key_compound.ts deleted file mode 100644 index dc6ce4cc3..000000000 --- a/tslang/test/tester/crash-errors/any_key_compound.ts +++ /dev/null @@ -1,3 +0,0 @@ -function f(a: any, k: string) { - a[k] += 1; -} diff --git a/tslang/test/tester/crash-errors/any_key_increment.ts b/tslang/test/tester/crash-errors/any_key_increment.ts deleted file mode 100644 index 3a2a86ae8..000000000 --- a/tslang/test/tester/crash-errors/any_key_increment.ts +++ /dev/null @@ -1,3 +0,0 @@ -function f(a: any, k: string) { - a[k]++; -} diff --git a/tslang/test/tester/tests/00any_keys_write.ts b/tslang/test/tester/tests/00any_keys_write.ts new file mode 100644 index 000000000..89844888e --- /dev/null +++ b/tslang/test/tester/tests/00any_keys_write.ts @@ -0,0 +1,139 @@ +// `x.name`, and `x[k] = v` (`+=`, `++`) of a value of type `any`: read and written at run time through the +// adapter made for the type of the value when it was boxed (TYPE_DESCR_KEYS, ANY_KEYS_OP_SET). A write is +// a TypeError for a key the type has not got (none is added), a method, an accessor with no setter, a +// tuple's key (the `any` holds a copy), and a value not of a number, string or boolean key's kind. +let gets = 0; + +class P { + constructor(public v: number) { + } +} + +class Q { + constructor(public w: string) { + } +} + +class C { + a = 1; + s = "x"; + b = true; + p = new P(4); + + get g() { return this.a * 10; } + + get h() { gets++; return this.a; } + set h(v: number) { this.a = v; } + + m() { return 1; } +} + +interface I { + n: number; + o?: string; +} + +function throws(f: () => void) { + try { + f(); + } catch (e) { + return true; + } + + return false; +} + +function main() { + const c = new C(); + const x: any = c; + + // reads by name + assert(x.a == 1 && x.s == "x" && x.g == 10 && x.b, "read by name"); + assert(typeof x.zz == "undefined", "a key it has not got"); + + // writes, by name and by key + x.a = 5; + x["s"] = "y" + c.a; + assert(c.a == 5 && c.s == "y5" && x.g == 50, "written"); + + // a setter, which a plain write runs without the getter + x.h = 7; + x["h"] = 8; + assert(c.a == 8 && gets == 0, "setter only"); + x.h += 1; + assert(c.a == 9 && gets == 1, "compound: one read, one write"); + + x.a += 2; + x.a++; + assert(c.a == 12, "compound and increment"); + + const r = (x.s = "z"); + assert(r == "z" && c.s == "z", "an assignment is its value"); + + x.p = new P(8); + assert(c.p.v == 8, "an object"); + + // what is refused + assert(throws(() => { x.g = 1; }), "no setter"); + assert(throws(() => { x.m = 1; }), "a method"); + assert(throws(() => { x.zz = 1; }), "a key it has not got"); + assert(throws(() => { x.a = "hi"; }), "a string for a number"); + assert(throws(() => { x.s = 5; }), "a number for a string"); + assert(throws(() => { x.b = 1; }), "a number for a boolean"); + assert(throws(() => { x.p = 5; }), "a number for an object"); + assert(throws(() => { x.p = new Q("q"); }), "another class"); + assert(c.a == 12 && c.s == "z" && c.b && c.p.v == 8, "unchanged by what was refused"); + + // an interface + const i: I = { n: 1, o: "a" }; + const y: any = i; + y.o = "set"; + y.n = 9; + assert(i.n == 9 && i.o == "set" && "o" in y, "an interface"); + + // an object made without an optional field has no place for it + const j: I = { n: 1 }; + assert(throws(() => { j.o = "a"; }), "no place, typed"); + const yj: any = j; + assert(throws(() => { yj.o = "a"; }), "no place, through any"); + + // an array: in range, or one past its end + const arr = [1, 2, 3]; + const z: any = arr; + z[1] = 20; + z[3] = 40; + assert(arr.length == 4 && arr[1] == 20 && arr[3] == 40 && z.length == 4, "an array"); + assert(throws(() => { z.length = 1; }), "length"); + assert(throws(() => { z[10] = 1; }), "far past its end"); + assert(throws(() => { z[0] = "a"; }), "a string for a number element"); + + const strs: any = ["a"]; + strs[1] = "b" + arr.length; + assert(strs.length == 2 && strs[1] == "b4", "a string array"); + + // a tuple and an object literal are values: the `any` holds a copy + const t: [number, string] = [1, "a"]; + const w: any = t; + assert(throws(() => { w[0] = 11; }), "a tuple"); + const lit: any = { a: 1 }; + assert(lit.a == 1, "an object literal's key"); + assert(throws(() => { lit.a = 2; }), "an object literal"); + + // a string, null + const s: any = "str"; + assert(s.length == 3 && s[1] == "t", "a string"); + assert(throws(() => { s[0] = "q"; }), "a string can't be changed"); + const nl: any = null; + assert(throws(() => { nl.a = 1; }), "null"); + + // in a loop, with values made at run time + for (let k = 0; k < 100; k++) { + x.s = "s" + k; + x["p"] = new P(k); + strs[0] = "v" + k; + } + + assert(c.s == "s99" && c.p.v == 99 && strs[0] == "v99", "in a loop"); + + print("done."); +} From b57b5b07346456f947602b0b5797d6f05a380274 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 21:41:30 +0000 Subject: [PATCH 2/3] -mm=own: x.name, x[k], x[k] = v and k in x of a value of type any, for a key whose value copies Under own a key's value is read as a copy in a box of its own and written as a copy of the value, so a key holding a number, a boolean, a string or an `any` is read and written through `any`; one holding an object is a TypeError on read and write (it would be a second owner), as is a write through an interface and an array grown through `any` (own can't prove the unboxed value alive across them). `in` asks of every key. The adapters unbox where they use the value under own. Test 00any_keys_models.ts runs under every model; the own compile errors for x[k] and k in x are gone. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenCast.cpp | 129 ++++++++++++++---- tslang/lib/TypeScript/MLIRGenImpl.h | 2 +- tslang/test/tester/CMakeLists.txt | 22 +-- tslang/test/tester/crash-errors/any_key.ts | 3 - tslang/test/tester/crash-errors/in_any.ts | 3 - tslang/test/tester/tests/00any_keys_models.ts | 60 ++++++++ 6 files changed, 173 insertions(+), 46 deletions(-) delete mode 100644 tslang/test/tester/crash-errors/any_key.ts delete mode 100644 tslang/test/tester/crash-errors/in_any.ts create mode 100644 tslang/test/tester/tests/00any_keys_models.ts diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 859203252..e46bc3ce0 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -4737,6 +4737,11 @@ namespace mlirgen if (!accessor.isStatic && accessor.get && accessor.getAccessLevel == mlir_ts::AccessLevel::Public) { addKey(values, accessor.name); + if (types && accessor.get.funcType.getNumResults() == 1) + { + types->try_emplace(accessor.name, accessor.get.funcType.getResult(0)); + } + // a getter with no public setter: a write through `any` is a TypeError if (readOnly && !(accessor.set && accessor.setAccessLevel == mlir_ts::AccessLevel::Public)) { @@ -4792,6 +4797,11 @@ namespace mlirgen for (auto &accessor : info->accessors) { addKey(values, accessor.name); + if (types && accessor.type) + { + types->try_emplace(accessor.name, accessor.type); + } + if (readOnly && accessor.setMethod.empty()) { readOnly->insert(accessor.name); @@ -4829,6 +4839,33 @@ namespace mlirgen addKey(values, key); } + // the types of its value fields, by name or position (an accessor's is not known here) + if (types) + { + auto fields = isa(type) ? mlir::cast(type).getFields() + : mlir::cast(type).getFields(); + for (auto [index, field] : llvm::enumerate(fields)) + { + if (isa(field.type)) + { + continue; + } + + if (auto name = dyn_cast_or_null(field.id)) + { + types->try_emplace(name.getValue(), field.type); + } + else if (auto position = dyn_cast_or_null(field.id)) + { + types->try_emplace(std::to_string(position.getValue().getSExtValue()), field.type); + } + else if (!field.id) + { + types->try_emplace(std::to_string(index), field.type); + } + } + } + return true; } @@ -4855,11 +4892,12 @@ namespace mlirgen // // instantiated for T: what a key reads is boxed as any value is. The keys are those of the type the value // had when it was boxed (a Derived boxed as a Base has a Base's), and a class's public ones only. A method is there for `in`, but reading one - // is a TypeError (a method read off its object is not a value here). Not for -mm=own, as calls of `any` are - // not. Whatever fails leaves the type without one, and a key read through it a TypeError. + // is a TypeError (a method read off its object is not a value here). Under -mm=own only a key whose value + // copies is read or written (ownCopies in makeAnyKeysAdapter). Whatever fails leaves the type without one, + // and a key read through it a TypeError. void MLIRGenImpl::ensureAnyKeysAdapter(mlir::Location location, mlir::Type type, const GenContext &genContext) { - if (compileOptions.memoryModel == MemoryModelOwn || genContext.allowPartialResolve || mth.isGenericType(type)) + if (genContext.allowPartialResolve || mth.isGenericType(type)) { return; } @@ -4918,6 +4956,28 @@ namespace mlirgen auto notThere = noNewKey + "return op == " + has + " ? false : undefined;\n"; auto throwWrongKind = throwTypeErrorSource("the value written through a value of type any is not of the key's type"); + // -mm=own: what a key reads is a copy in a box of its own, and what it is given a copy of the value, so only + // a key whose value copies - one owning no heap memory, a string, an `any` (one holding an object stops, + // as any copy of it does) - is read or written through `any`. Another is a TypeError: it would be a second + // owner of what the object owns. `in` asks of every key. + auto own = compileOptions.memoryModel == MemoryModelOwn; + auto ownCopies = [&](mlir::Type keyType) { + if (!keyType) + { + return false; + } + + if (auto optionalType = dyn_cast(keyType)) + { + keyType = optionalType.getElementType(); + } + + keyType = mth.stripLiteralType(keyType); + return isa(keyType) || !mth.ownsHeapMemory(location, keyType); + }; + auto throwOwnObject = throwTypeErrorSource( + "under -mm=own a key holding an object can't be read or written through a value of type any: cast the value to its type"); + std::string name; std::string src; if (isArray) @@ -4934,25 +4994,39 @@ namespace mlirgen : isa(elementType) ? "_s" : isa(elementType) ? "_b" : "_n"; + // under -mm=own the array is unboxed where it is used: a local borrowing the box, written through, + // is one own can't prove stays alive + std::string a = own ? "(box)" : "a"; + // under -mm=own an element that does not copy (ownCopies) is not read or written: `_o` + // (under -mm=own in its range only: `push` takes the array in a variable, which own can't prove) + auto elements = "if (inside) { " + a + "[i] = value; return undefined; }\n" + + (own ? std::string() : "if (i == a.length) { a.push(value); return undefined; }\n") + + throwTypeErrorSource(own ? "under -mm=own an element of an array can only be written in its range through a value of type any" + : "an element of an array can only be written in its range or just past its end") + "\n"; + auto elementRead = "if (inside) return " + a + "[i];\n"; + if (own && !ownCopies(elementType)) + { + suffix = "_o"; + kindCheck = ""; + elements = throwOwnObject + "\n"; + elementRead = "if (inside) " + throwOwnObject + "\n"; + } + name = "__any_keys_array" + std::string(suffix); src = "function " + name + "(box: any, op: number, key: any, value: any): any {\n" - "const kt = typeof key;\n" - "const a = box;\n" + "const kt = typeof key;\n" + + (own ? "" : "const a = box;\n") + "if (" + anyKeyIsNumberSource + ") {\n" "const i = key;\n" - "const inside = i >= 0 && i < a.length && i % 1 == 0;\n" - "if (op == " + set + ") {\n" + kindCheck + "\n" - "if (inside) { a[i] = value; return undefined; }\n" - "if (i == a.length) { a.push(value); return undefined; }\n" + - throwTypeErrorSource("an element of an array can only be written in its range or just past its end") + "\n" + "const inside = i >= 0 && i < " + a + ".length && i % 1 == 0;\n" + "if (op == " + set + ") {\n" + kindCheck + "\n" + elements + "}\n" - "if (op == " + has + ") return inside;\n" - "if (inside) return a[i];\n" + "if (op == " + has + ") return inside;\n" + elementRead + "return undefined;\n" "}\n" "if (kt == \"string\" && key == \"length\") {\n" "if (op == " + set + ") " + throwTypeErrorSource("the length of an array can't be written through a value of type any") + "\n" - "return op == " + has + " ? true : a.length;\n" + "return op == " + has + " ? true : " + a + ".length;\n" "}\n" + notThere + "}\n"; @@ -4985,8 +5059,10 @@ namespace mlirgen "let k = \"\";\n" "if (kt == \"string\") k = key;\n" "else if (" + anyKeyIsNumberSource + ") k = \"\" + key;\n" - "else {\n" + notThere + "}\n" - "const o = box;\n"; + "else {\n" + notThere + "}\n" + + (own ? "" : "const o = box;\n"); + // under -mm=own the value is unboxed where it is used (see the array's) + std::string o = own ? "(box)" : "o"; // a tuple is a value: the `any` holds a copy of it, which a write would change and nothing else auto tuple = isa(type); @@ -5003,6 +5079,14 @@ namespace mlirgen throwTypeErrorSource("an accessor with no setter can't be written through a value of type any") + "\n"; } + // under -mm=own a store through an interface unboxed from `any` is one own can't prove leaves the + // object alive: read only + if (own && isa(type)) + { + return "if (op == " + set + ") " + + throwTypeErrorSource("under -mm=own a key of an interface can't be written through a value of type any: cast the value to its type") + "\n"; + } + return "if (op == " + set + ") { " + anyKeyValueKindCheck(types.lookup(key), optionals.contains(key), throwWrongKind) + place + " = value; return undefined; }\n"; }; @@ -5010,7 +5094,13 @@ namespace mlirgen for (auto &key : values) { // a tuple's unnamed field is read by its position - auto read = isIndex(key) ? "o[" + key + "]" : "o[" + quote(key) + "]"; + auto read = isIndex(key) ? o + "[" + key + "]" : o + "[" + quote(key) + "]"; + if (own && !ownCopies(types.lookup(key))) + { + src += "if (k == " + quote(key) + ") { if (op == " + has + ") return true; " + throwOwnObject + " }\n"; + continue; + } + src += "if (k == " + quote(key) + ") {\n" + writeOf(key, read); if (optionals.contains(key)) { @@ -5101,13 +5191,6 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::mlirGenAnyKey(mlir::Location location, mlir::Value box, mlir::Value key, int op, const GenContext &genContext, mlir::Value value) { - if (compileOptions.memoryModel == MemoryModelOwn) - { - emitError(location) << (op == ANY_KEYS_OP_HAS ? "'k in x' of a value of type 'any'" : "element access of a value of type 'any' ('x[k]')") - << " is not supported under -mm=own: cast it to its type first"; - return mlir::failure(); - } - // a key is a number or a string to the adapters: an integer or a literal is made one before it is boxed auto keyType = mth.stripLiteralType(mth.getBaseType(key.getType())); if (mth.isNumericType(keyType) && !isa(keyType)) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index a4221a153..9c5b798e6 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -7299,7 +7299,7 @@ class MLIRGenImpl SmallVector values; SmallVector methods; auto rightType = TypeOfOpHelper::typeOfBaseType(rightExpressionValue.getType()); - if (compileOptions.memoryModel != MemoryModelOwn && anyKeysOfType(rightType, values, methods)) + if (anyKeysOfType(rightType, values, methods)) { CAST_A(boxed, location, getAnyType(), rightExpressionValue, genContext); return mlirGenAnyKey(location, boxed, leftExpressionValue, ANY_KEYS_OP_HAS, genContext); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 583417091..96147f5cb 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1953,6 +1953,12 @@ foreach(tuple_array_mm gc rc none own) tslang_add_test(NAME test-jit-00-tuple-array-methods-${tuple_array_mm} COMMAND test-runner -jit -mm=${tuple_array_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tuple_array_methods.ts") endforeach() tslang_add_test(NAME test-compile-00-tuple-array-methods COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00tuple_array_methods.ts") +# `x.name`, `x[k]`, `x[k] = v` and `k in x` of a value of type `any` under every memory model (user ruling 11-19): +# under -mm=own a key whose value copies is read and written, another is a TypeError +foreach(any_keys_mm gc rc none own) + tslang_add_test(NAME test-jit-00-any-keys-models-${any_keys_mm} COMMAND test-runner -jit -mm=${any_keys_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_keys_models.ts") +endforeach() +tslang_add_test(NAME test-compile-00-any-keys-models-own COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_keys_models.ts") # map and filter of a `(number | string)[]`: own copies a string element of the union, as of a string[] foreach(string_union_mm gc rc none own) tslang_add_test(NAME test-jit-00-string-union-elements-${string_union_mm} COMMAND test-runner -jit -mm=${string_union_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00string_union_elements.ts") @@ -4074,22 +4080,6 @@ foreach(any_call_own_case "call_any|3:5" "call_untyped_parameter|3:16") PROPERTIES PASS_REGULAR_EXPRESSION "${any_call_own_name}\\.ts:${any_call_own_position}: error: a value of type 'any' can't be called under -mm=own" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed|PLEASE submit a bug report") endforeach() -# `x[k]` and `k in x` of a value of type `any` are looked up at run time (user ruling 11-19), but not under -# -mm=own yet, as calls of `any` are not -foreach(any_key_own_case "any_key|2:12|element access of a value of type 'any' \\('x\\[k\\]'\\)" "in_any|2:12|'k in x' of a value of type 'any'") - string(REPLACE "|" ";" any_key_own_parts "${any_key_own_case}") - list(GET any_key_own_parts 0 any_key_own_name) - list(GET any_key_own_parts 1 any_key_own_position) - list(GET any_key_own_parts 2 any_key_own_message) - string(REPLACE "_" "-" any_key_own_slug "${any_key_own_name}") - add_test(NAME test-compile-crash-errors-${any_key_own_slug}-own - COMMAND $ --emit=obj --no-default-lib -mm=own - "${PROJECT_SOURCE_DIR}/test/tester/crash-errors/${any_key_own_name}.ts" - -o "${CMAKE_CURRENT_BINARY_DIR}/crash-errors-${any_key_own_slug}-own.obj") - set_tests_properties(test-compile-crash-errors-${any_key_own_slug}-own - PROPERTIES PASS_REGULAR_EXPRESSION "${any_key_own_name}\\.ts:${any_key_own_position}: error: ${any_key_own_message} is not supported under -mm=own" - FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed|PLEASE submit a bug report") -endforeach() # a file name outside the ANSI code page: argv turned it into '?'s ("Could not open input file") set(crash_ok_unicode_file "${CMAKE_CURRENT_BINARY_DIR}/crash-errors-①Ⅻㄨ.ts") file(WRITE "${crash_ok_unicode_file}" "let x = 1;\n") diff --git a/tslang/test/tester/crash-errors/any_key.ts b/tslang/test/tester/crash-errors/any_key.ts deleted file mode 100644 index ab88680e4..000000000 --- a/tslang/test/tester/crash-errors/any_key.ts +++ /dev/null @@ -1,3 +0,0 @@ -function f(a: any, k: string) { - return a[k]; -} diff --git a/tslang/test/tester/crash-errors/in_any.ts b/tslang/test/tester/crash-errors/in_any.ts deleted file mode 100644 index 5c026ebbf..000000000 --- a/tslang/test/tester/crash-errors/in_any.ts +++ /dev/null @@ -1,3 +0,0 @@ -function f(a: any) { - return "x" in a; -} diff --git a/tslang/test/tester/tests/00any_keys_models.ts b/tslang/test/tester/tests/00any_keys_models.ts new file mode 100644 index 000000000..11c4b6dea --- /dev/null +++ b/tslang/test/tester/tests/00any_keys_models.ts @@ -0,0 +1,60 @@ +// `x.name`, `x[k]`, `x[k] = v` and `k in x` of a value of type `any` under every memory model, -mm=own +// too: a key whose value copies (a number, a boolean, a string) is read and written; under -mm=own a key +// holding an object, a write through an interface, and an array grown through `any` are TypeErrors. +class C { + a = 1; + s = "x"; + b = true; + + get g() { return this.a * 10; } + + m() { return 1; } +} + +interface I { + n: number; + o?: string; +} + +function main() { + const x: any = new C(); + assert(x.a == 1 && x.s == "x" && x.b && x.g == 10, "read by name"); + assert("a" in x && "m" in x && !("zz" in x), "in"); + + x.a = 5; + x["s"] = "y" + x.a; + x.b = false; + assert(x.a == 5 && x.s == "y5" && !x.b && x.g == 50, "written"); + + x.a += 2; + x.a++; + assert(x.a == 8, "compound and increment"); + + let refused = 0; + try { x.g = 1; } catch (e) { refused++; } + try { x.zz = 1; } catch (e) { refused++; } + try { x.a = "a string"; } catch (e) { refused++; } + assert(refused == 3 && x.a == 8, "what is refused"); + + for (let k = 0; k < 50; k++) { + x.s = "s" + k; + } + + assert(x.s == "s49", "in a loop"); + + const y: any = { n: 1, o: "a" }; + assert(y.n == 1 && y.o == "a" && "o" in y, "an interface"); + + const z: any = [1, 2, 3]; + z[1] = 20; + assert(z.length == 3 && z[1] == 20 && z[0] == 1 && typeof z[5] == "undefined", "an array"); + + const strs: any = ["a", "b"]; + strs[0] = "c" + z.length; + assert(strs[0] == "c3", "a string array"); + + const s: any = "str"; + assert(s.length == 3 && s[1] == "t", "a string"); + + print("done."); +} From 6f1a45ba50c1094ea4f39102403159aabc1d40f4 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 19 Nov 2026 21:56:16 +0000 Subject: [PATCH 3/3] Revert -mm=own support of x[k] through any: the adapters made under own failed own's checks in the default library (Error classes, an interface holding a method) and in 00any_to_interface.ts, where they reached programs that never read a key; own keeps its clear error This reverts commit b57b5b07. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenCast.cpp | 129 ++++-------------- tslang/lib/TypeScript/MLIRGenImpl.h | 2 +- tslang/test/tester/CMakeLists.txt | 22 ++- tslang/test/tester/crash-errors/any_key.ts | 3 + tslang/test/tester/crash-errors/in_any.ts | 3 + tslang/test/tester/tests/00any_keys_models.ts | 60 -------- 6 files changed, 46 insertions(+), 173 deletions(-) create mode 100644 tslang/test/tester/crash-errors/any_key.ts create mode 100644 tslang/test/tester/crash-errors/in_any.ts delete mode 100644 tslang/test/tester/tests/00any_keys_models.ts diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index e46bc3ce0..859203252 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -4737,11 +4737,6 @@ namespace mlirgen if (!accessor.isStatic && accessor.get && accessor.getAccessLevel == mlir_ts::AccessLevel::Public) { addKey(values, accessor.name); - if (types && accessor.get.funcType.getNumResults() == 1) - { - types->try_emplace(accessor.name, accessor.get.funcType.getResult(0)); - } - // a getter with no public setter: a write through `any` is a TypeError if (readOnly && !(accessor.set && accessor.setAccessLevel == mlir_ts::AccessLevel::Public)) { @@ -4797,11 +4792,6 @@ namespace mlirgen for (auto &accessor : info->accessors) { addKey(values, accessor.name); - if (types && accessor.type) - { - types->try_emplace(accessor.name, accessor.type); - } - if (readOnly && accessor.setMethod.empty()) { readOnly->insert(accessor.name); @@ -4839,33 +4829,6 @@ namespace mlirgen addKey(values, key); } - // the types of its value fields, by name or position (an accessor's is not known here) - if (types) - { - auto fields = isa(type) ? mlir::cast(type).getFields() - : mlir::cast(type).getFields(); - for (auto [index, field] : llvm::enumerate(fields)) - { - if (isa(field.type)) - { - continue; - } - - if (auto name = dyn_cast_or_null(field.id)) - { - types->try_emplace(name.getValue(), field.type); - } - else if (auto position = dyn_cast_or_null(field.id)) - { - types->try_emplace(std::to_string(position.getValue().getSExtValue()), field.type); - } - else if (!field.id) - { - types->try_emplace(std::to_string(index), field.type); - } - } - } - return true; } @@ -4892,12 +4855,11 @@ namespace mlirgen // // instantiated for T: what a key reads is boxed as any value is. The keys are those of the type the value // had when it was boxed (a Derived boxed as a Base has a Base's), and a class's public ones only. A method is there for `in`, but reading one - // is a TypeError (a method read off its object is not a value here). Under -mm=own only a key whose value - // copies is read or written (ownCopies in makeAnyKeysAdapter). Whatever fails leaves the type without one, - // and a key read through it a TypeError. + // is a TypeError (a method read off its object is not a value here). Not for -mm=own, as calls of `any` are + // not. Whatever fails leaves the type without one, and a key read through it a TypeError. void MLIRGenImpl::ensureAnyKeysAdapter(mlir::Location location, mlir::Type type, const GenContext &genContext) { - if (genContext.allowPartialResolve || mth.isGenericType(type)) + if (compileOptions.memoryModel == MemoryModelOwn || genContext.allowPartialResolve || mth.isGenericType(type)) { return; } @@ -4956,28 +4918,6 @@ namespace mlirgen auto notThere = noNewKey + "return op == " + has + " ? false : undefined;\n"; auto throwWrongKind = throwTypeErrorSource("the value written through a value of type any is not of the key's type"); - // -mm=own: what a key reads is a copy in a box of its own, and what it is given a copy of the value, so only - // a key whose value copies - one owning no heap memory, a string, an `any` (one holding an object stops, - // as any copy of it does) - is read or written through `any`. Another is a TypeError: it would be a second - // owner of what the object owns. `in` asks of every key. - auto own = compileOptions.memoryModel == MemoryModelOwn; - auto ownCopies = [&](mlir::Type keyType) { - if (!keyType) - { - return false; - } - - if (auto optionalType = dyn_cast(keyType)) - { - keyType = optionalType.getElementType(); - } - - keyType = mth.stripLiteralType(keyType); - return isa(keyType) || !mth.ownsHeapMemory(location, keyType); - }; - auto throwOwnObject = throwTypeErrorSource( - "under -mm=own a key holding an object can't be read or written through a value of type any: cast the value to its type"); - std::string name; std::string src; if (isArray) @@ -4994,39 +4934,25 @@ namespace mlirgen : isa(elementType) ? "_s" : isa(elementType) ? "_b" : "_n"; - // under -mm=own the array is unboxed where it is used: a local borrowing the box, written through, - // is one own can't prove stays alive - std::string a = own ? "(box)" : "a"; - // under -mm=own an element that does not copy (ownCopies) is not read or written: `_o` - // (under -mm=own in its range only: `push` takes the array in a variable, which own can't prove) - auto elements = "if (inside) { " + a + "[i] = value; return undefined; }\n" + - (own ? std::string() : "if (i == a.length) { a.push(value); return undefined; }\n") + - throwTypeErrorSource(own ? "under -mm=own an element of an array can only be written in its range through a value of type any" - : "an element of an array can only be written in its range or just past its end") + "\n"; - auto elementRead = "if (inside) return " + a + "[i];\n"; - if (own && !ownCopies(elementType)) - { - suffix = "_o"; - kindCheck = ""; - elements = throwOwnObject + "\n"; - elementRead = "if (inside) " + throwOwnObject + "\n"; - } - name = "__any_keys_array" + std::string(suffix); src = "function " + name + "(box: any, op: number, key: any, value: any): any {\n" - "const kt = typeof key;\n" + - (own ? "" : "const a = box;\n") + + "const kt = typeof key;\n" + "const a = box;\n" "if (" + anyKeyIsNumberSource + ") {\n" "const i = key;\n" - "const inside = i >= 0 && i < " + a + ".length && i % 1 == 0;\n" - "if (op == " + set + ") {\n" + kindCheck + "\n" + elements + + "const inside = i >= 0 && i < a.length && i % 1 == 0;\n" + "if (op == " + set + ") {\n" + kindCheck + "\n" + "if (inside) { a[i] = value; return undefined; }\n" + "if (i == a.length) { a.push(value); return undefined; }\n" + + throwTypeErrorSource("an element of an array can only be written in its range or just past its end") + "\n" "}\n" - "if (op == " + has + ") return inside;\n" + elementRead + + "if (op == " + has + ") return inside;\n" + "if (inside) return a[i];\n" "return undefined;\n" "}\n" "if (kt == \"string\" && key == \"length\") {\n" "if (op == " + set + ") " + throwTypeErrorSource("the length of an array can't be written through a value of type any") + "\n" - "return op == " + has + " ? true : " + a + ".length;\n" + "return op == " + has + " ? true : a.length;\n" "}\n" + notThere + "}\n"; @@ -5059,10 +4985,8 @@ namespace mlirgen "let k = \"\";\n" "if (kt == \"string\") k = key;\n" "else if (" + anyKeyIsNumberSource + ") k = \"\" + key;\n" - "else {\n" + notThere + "}\n" + - (own ? "" : "const o = box;\n"); - // under -mm=own the value is unboxed where it is used (see the array's) - std::string o = own ? "(box)" : "o"; + "else {\n" + notThere + "}\n" + "const o = box;\n"; // a tuple is a value: the `any` holds a copy of it, which a write would change and nothing else auto tuple = isa(type); @@ -5079,14 +5003,6 @@ namespace mlirgen throwTypeErrorSource("an accessor with no setter can't be written through a value of type any") + "\n"; } - // under -mm=own a store through an interface unboxed from `any` is one own can't prove leaves the - // object alive: read only - if (own && isa(type)) - { - return "if (op == " + set + ") " + - throwTypeErrorSource("under -mm=own a key of an interface can't be written through a value of type any: cast the value to its type") + "\n"; - } - return "if (op == " + set + ") { " + anyKeyValueKindCheck(types.lookup(key), optionals.contains(key), throwWrongKind) + place + " = value; return undefined; }\n"; }; @@ -5094,13 +5010,7 @@ namespace mlirgen for (auto &key : values) { // a tuple's unnamed field is read by its position - auto read = isIndex(key) ? o + "[" + key + "]" : o + "[" + quote(key) + "]"; - if (own && !ownCopies(types.lookup(key))) - { - src += "if (k == " + quote(key) + ") { if (op == " + has + ") return true; " + throwOwnObject + " }\n"; - continue; - } - + auto read = isIndex(key) ? "o[" + key + "]" : "o[" + quote(key) + "]"; src += "if (k == " + quote(key) + ") {\n" + writeOf(key, read); if (optionals.contains(key)) { @@ -5191,6 +5101,13 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::mlirGenAnyKey(mlir::Location location, mlir::Value box, mlir::Value key, int op, const GenContext &genContext, mlir::Value value) { + if (compileOptions.memoryModel == MemoryModelOwn) + { + emitError(location) << (op == ANY_KEYS_OP_HAS ? "'k in x' of a value of type 'any'" : "element access of a value of type 'any' ('x[k]')") + << " is not supported under -mm=own: cast it to its type first"; + return mlir::failure(); + } + // a key is a number or a string to the adapters: an integer or a literal is made one before it is boxed auto keyType = mth.stripLiteralType(mth.getBaseType(key.getType())); if (mth.isNumericType(keyType) && !isa(keyType)) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 9c5b798e6..a4221a153 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -7299,7 +7299,7 @@ class MLIRGenImpl SmallVector values; SmallVector methods; auto rightType = TypeOfOpHelper::typeOfBaseType(rightExpressionValue.getType()); - if (anyKeysOfType(rightType, values, methods)) + if (compileOptions.memoryModel != MemoryModelOwn && anyKeysOfType(rightType, values, methods)) { CAST_A(boxed, location, getAnyType(), rightExpressionValue, genContext); return mlirGenAnyKey(location, boxed, leftExpressionValue, ANY_KEYS_OP_HAS, genContext); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 96147f5cb..583417091 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1953,12 +1953,6 @@ foreach(tuple_array_mm gc rc none own) tslang_add_test(NAME test-jit-00-tuple-array-methods-${tuple_array_mm} COMMAND test-runner -jit -mm=${tuple_array_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tuple_array_methods.ts") endforeach() tslang_add_test(NAME test-compile-00-tuple-array-methods COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00tuple_array_methods.ts") -# `x.name`, `x[k]`, `x[k] = v` and `k in x` of a value of type `any` under every memory model (user ruling 11-19): -# under -mm=own a key whose value copies is read and written, another is a TypeError -foreach(any_keys_mm gc rc none own) - tslang_add_test(NAME test-jit-00-any-keys-models-${any_keys_mm} COMMAND test-runner -jit -mm=${any_keys_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_keys_models.ts") -endforeach() -tslang_add_test(NAME test-compile-00-any-keys-models-own COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_keys_models.ts") # map and filter of a `(number | string)[]`: own copies a string element of the union, as of a string[] foreach(string_union_mm gc rc none own) tslang_add_test(NAME test-jit-00-string-union-elements-${string_union_mm} COMMAND test-runner -jit -mm=${string_union_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00string_union_elements.ts") @@ -4080,6 +4074,22 @@ foreach(any_call_own_case "call_any|3:5" "call_untyped_parameter|3:16") PROPERTIES PASS_REGULAR_EXPRESSION "${any_call_own_name}\\.ts:${any_call_own_position}: error: a value of type 'any' can't be called under -mm=own" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed|PLEASE submit a bug report") endforeach() +# `x[k]` and `k in x` of a value of type `any` are looked up at run time (user ruling 11-19), but not under +# -mm=own yet, as calls of `any` are not +foreach(any_key_own_case "any_key|2:12|element access of a value of type 'any' \\('x\\[k\\]'\\)" "in_any|2:12|'k in x' of a value of type 'any'") + string(REPLACE "|" ";" any_key_own_parts "${any_key_own_case}") + list(GET any_key_own_parts 0 any_key_own_name) + list(GET any_key_own_parts 1 any_key_own_position) + list(GET any_key_own_parts 2 any_key_own_message) + string(REPLACE "_" "-" any_key_own_slug "${any_key_own_name}") + add_test(NAME test-compile-crash-errors-${any_key_own_slug}-own + COMMAND $ --emit=obj --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/crash-errors/${any_key_own_name}.ts" + -o "${CMAKE_CURRENT_BINARY_DIR}/crash-errors-${any_key_own_slug}-own.obj") + set_tests_properties(test-compile-crash-errors-${any_key_own_slug}-own + PROPERTIES PASS_REGULAR_EXPRESSION "${any_key_own_name}\\.ts:${any_key_own_position}: error: ${any_key_own_message} is not supported under -mm=own" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed|PLEASE submit a bug report") +endforeach() # a file name outside the ANSI code page: argv turned it into '?'s ("Could not open input file") set(crash_ok_unicode_file "${CMAKE_CURRENT_BINARY_DIR}/crash-errors-①Ⅻㄨ.ts") file(WRITE "${crash_ok_unicode_file}" "let x = 1;\n") diff --git a/tslang/test/tester/crash-errors/any_key.ts b/tslang/test/tester/crash-errors/any_key.ts new file mode 100644 index 000000000..ab88680e4 --- /dev/null +++ b/tslang/test/tester/crash-errors/any_key.ts @@ -0,0 +1,3 @@ +function f(a: any, k: string) { + return a[k]; +} diff --git a/tslang/test/tester/crash-errors/in_any.ts b/tslang/test/tester/crash-errors/in_any.ts new file mode 100644 index 000000000..5c026ebbf --- /dev/null +++ b/tslang/test/tester/crash-errors/in_any.ts @@ -0,0 +1,3 @@ +function f(a: any) { + return "x" in a; +} diff --git a/tslang/test/tester/tests/00any_keys_models.ts b/tslang/test/tester/tests/00any_keys_models.ts deleted file mode 100644 index 11c4b6dea..000000000 --- a/tslang/test/tester/tests/00any_keys_models.ts +++ /dev/null @@ -1,60 +0,0 @@ -// `x.name`, `x[k]`, `x[k] = v` and `k in x` of a value of type `any` under every memory model, -mm=own -// too: a key whose value copies (a number, a boolean, a string) is read and written; under -mm=own a key -// holding an object, a write through an interface, and an array grown through `any` are TypeErrors. -class C { - a = 1; - s = "x"; - b = true; - - get g() { return this.a * 10; } - - m() { return 1; } -} - -interface I { - n: number; - o?: string; -} - -function main() { - const x: any = new C(); - assert(x.a == 1 && x.s == "x" && x.b && x.g == 10, "read by name"); - assert("a" in x && "m" in x && !("zz" in x), "in"); - - x.a = 5; - x["s"] = "y" + x.a; - x.b = false; - assert(x.a == 5 && x.s == "y5" && !x.b && x.g == 50, "written"); - - x.a += 2; - x.a++; - assert(x.a == 8, "compound and increment"); - - let refused = 0; - try { x.g = 1; } catch (e) { refused++; } - try { x.zz = 1; } catch (e) { refused++; } - try { x.a = "a string"; } catch (e) { refused++; } - assert(refused == 3 && x.a == 8, "what is refused"); - - for (let k = 0; k < 50; k++) { - x.s = "s" + k; - } - - assert(x.s == "s49", "in a loop"); - - const y: any = { n: 1, o: "a" }; - assert(y.n == 1 && y.o == "a" && "o" in y, "an interface"); - - const z: any = [1, 2, 3]; - z[1] = 20; - assert(z.length == 3 && z[1] == 20 && z[0] == 1 && typeof z[5] == "undefined", "an array"); - - const strs: any = ["a", "b"]; - strs[0] = "c" + z.length; - assert(strs[0] == "c3", "a string array"); - - const s: any = "str"; - assert(s.length == 3 && s[1] == "t", "a string"); - - print("done."); -}