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."); +}