diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 38b01782d..b03056929 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -48,6 +48,8 @@ // the call returns what the adapter returns, owned when every adapter here returns owned (OwnedReturnConsumptionPass) #define ANY_CALL_ADAPTER_ATTR_NAME "__any_call_adapter" #define ANY_CALL_ADAPTER_CALL_ATTR_NAME "__any_call_adapter_call" +// the call reading `x[k]` of `x: any` (MLIRGenImpl::mlirGenAnyKey): a value, not a place to write +#define ANY_KEY_READ_ATTR_NAME "__any_key_read" // On a `ts.ValueOrDefault`: an explicit cast in the source (`data` of a `T | undefined`) made // it, so its lowering does not warn that an optional value is read as it is. @@ -313,6 +315,9 @@ // module attribute: the adapter made for each function type boxed in the module, by the type's // MLIRHelper::hashOfType (TYPE_DESCR_CALL) #define ANY_CALL_ADAPTERS_ATTR_NAME "ts.any_call_adapters" +// module attribute: the adapter made for each tuple, class, interface or array type boxed in the module, +// by the type's MLIRHelper::hashOfType (TYPE_DESCR_KEYS) +#define ANY_KEYS_ADAPTERS_ATTR_NAME "ts.any_keys_adapters" #define NEW_METHOD_NAME ".new" #define NEW_CTOR_METHOD_NAME ".new_ctor" // the fields of a class value's storage tuple (ClassValueType), beside NEW_METHOD_NAME @@ -678,12 +683,20 @@ // `any` - `(box: any, args: any[]) => any`, made when the function is boxed (user ruling 11-18, // MLIRGenImpl::ensureAnyCallAdapter) - and null for any other type, or when none was made. #define TYPE_DESCR_CALL 5 +// 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. +#define TYPE_DESCR_KEYS 6 +#define ANY_KEYS_OP_GET 0 +#define ANY_KEYS_OP_HAS 1 // 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 // string literal does, on top of being a name preceded by a descriptor. Both reads work off // the same pointer: `tag - sizeof(header)` is the marker, `tag - sizeof(record)` the record. -#define TYPE_DESCR_BLOCK_HEADER 6 +#define TYPE_DESCR_BLOCK_HEADER 7 // Coarse category of the described type. These correspond one-to-one with the names // TypeOfOpHelper::typeOfAsString reports, and are derived from that name so the two cannot diff --git a/tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h b/tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h index 27b3632c4..79a1bfa06 100644 --- a/tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h +++ b/tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h @@ -358,7 +358,7 @@ class LLVMCodeHelper : public LLVMCodeHelperBase mlir::Value getOrCreateTypeDescriptorName(mlir::Type type, std::string name, int kind, StringRef releaseRoutineName, StringRef retainRoutineName, StringRef shareRoutineName, StringRef variant = "", uint32_t layout = 0, - StringRef callRoutineName = "") + StringRef callRoutineName = "", StringRef keysRoutineName = "") { auto loc = op->getLoc(); auto parentModule = op->getParentOfType(); @@ -419,6 +419,11 @@ class LLVMCodeHelper : public LLVMCodeHelperBase ? (mlir::Value)rewriter.create(loc, th.getPtrType()) : (mlir::Value)rewriter.create(loc, th.getPtrType(), callRoutineName); setStructValue(loc, recordValue, callValue, TYPE_DESCR_CALL); + mlir::Value keysValue = + keysRoutineName.empty() + ? (mlir::Value)rewriter.create(loc, th.getPtrType()) + : (mlir::Value)rewriter.create(loc, th.getPtrType(), keysRoutineName); + setStructValue(loc, recordValue, keysValue, TYPE_DESCR_KEYS); // a tag doubles as a string payload, so what precedes the name has to read as an // immortal block header - see TYPE_DESCR_BLOCK_HEADER setStructValue(loc, recordValue, diff --git a/tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h b/tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h index 62ac95c7c..f744ca0d3 100644 --- a/tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h +++ b/tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h @@ -34,13 +34,14 @@ class TypeDescriptorLogic { } - // { i32 kind, i32 layout, ptr release, ptr retain, ptr share, ptr call, blockHeader }: the block header - // an integer of CompileOptions::heapBlockHeaderBytes, the index width but 8 bytes on wasm32 + // { i32 kind, i32 layout, ptr release, ptr retain, ptr share, ptr call, ptr keys, blockHeader }: the block + // header an integer of CompileOptions::heapBlockHeaderBytes, the index width but 8 bytes on wasm32 static LLVM::LLVMStructType getRecordType(mlir::OpBuilder &builder, mlir::Type blockWordType) { auto i32Ty = builder.getI32Type(); auto ptrTy = LLVM::LLVMPointerType::get(builder.getContext()); - return LLVM::LLVMStructType::getLiteral(builder.getContext(), {i32Ty, i32Ty, ptrTy, ptrTy, ptrTy, ptrTy, blockWordType}, false); + return LLVM::LLVMStructType::getLiteral(builder.getContext(), + {i32Ty, i32Ty, ptrTy, ptrTy, ptrTy, ptrTy, ptrTy, blockWordType}, false); } LLVM::LLVMStructType getRecordType() @@ -99,6 +100,15 @@ class TypeDescriptorLogic return rewriter.create(loc, th.getPtrType(), callPtr); } + // TYPE_DESCR_KEYS of the type this tag names: the adapter that reads a key of a boxed value, or null + mlir::Value getKeysFromTag(mlir::Value tagValue) + { + auto recordPtr = getRecordPtrFromTag(tagValue); + auto keysPtr = rewriter.create(loc, th.getPtrType(), getRecordType(), recordPtr, + ArrayRef{0, TYPE_DESCR_KEYS}); + return rewriter.create(loc, th.getPtrType(), keysPtr); + } + mlir::Value isKind(mlir::Value tagValue, int kind) { auto kindValue = getKindFromTag(tagValue); diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h index 8d5a2b040..b55dc455b 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h @@ -193,6 +193,9 @@ struct GenContext // storage declared in the body does not dominate it; hoisting is what lets the unwind leg // dispose and release what the body's scope owes. bool allocateScopeOwnedVarsOutsideOfOperation = false; + // a catch clause's variable is being declared: the landing pad writes it, not an initializer, so it + // starts with nothing in it (MLIRGenImpl::adjustLocalVariableType) + bool declaringCatchVariable = false; bool forceDiscover = false; bool discoverParamsOnly = false; bool insertIntoParentScope = false; diff --git a/tslang/include/TypeScript/TypeScriptOps.td b/tslang/include/TypeScript/TypeScriptOps.td index f4281ba54..9539ae8b1 100644 --- a/tslang/include/TypeScript/TypeScriptOps.td +++ b/tslang/include/TypeScript/TypeScriptOps.td @@ -513,6 +513,18 @@ def TypeScript_IsTupleOfLayoutOp : TypeScript_Op<"IsTupleOfLayout", [Pure]> { let results = (outs TypeScript_Boolean:$res); } +def TypeScript_AnyKeysAdapterOp : TypeScript_Op<"AnyKeysAdapter", [Pure]> { + let summary = "the adapter that reads a key of the value an any holds"; + let description = [{ + The TYPE_DESCR_KEYS of the tag of the box $value: `(box: any, op: number, key: any, value: any) => any`, + made for the type of the value (a tuple, class, interface or array) when it was boxed + (MLIRGenImpl::ensureAnyKeysAdapter), or null when none was made for it. + }]; + + let arguments = (ins TypeScript_Any:$value); + let results = (outs TypeScript_Opaque:$res); +} + def TypeScript_AnyCallAdapterOp : TypeScript_Op<"AnyCallAdapter", [Pure]> { let summary = "the adapter that calls the function an any holds"; let description = [{ diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index ccc2c5a15..3000d09b2 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -3316,7 +3316,7 @@ void AddTsAffineLegalOps(ConversionTarget &target) mlir_ts::EndCatchOp, mlir_ts::TryEntryOp, mlir_ts::BeginCleanupOp, mlir_ts::EndCleanupOp, mlir_ts::ThrowUnwindOp, mlir_ts::ThrowCallOp, mlir_ts::SymbolCallInternalOp, mlir_ts::CallInternalOp, mlir_ts::ReturnInternalOp, mlir_ts::NoOp, mlir_ts::SwitchStateInternalOp, mlir_ts::UnreachableOp, mlir_ts::GlobalConstructorOp, mlir_ts::AppendToUsedOp, - mlir_ts::CreateBoundFunctionOp, mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::AnyCallAdapterOp, mlir_ts::IsTypeTagOfOp, mlir_ts::BoxOp, mlir_ts::UnboxOp, + mlir_ts::CreateBoundFunctionOp, mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::AnyCallAdapterOp, mlir_ts::AnyKeysAdapterOp, mlir_ts::IsTypeTagOfOp, mlir_ts::BoxOp, mlir_ts::UnboxOp, mlir_ts::CreateUnionInstanceOp, mlir_ts::GetValueFromUnionOp, mlir_ts::GetTypeInfoFromUnionOp, mlir_ts::OptionalOp, mlir_ts::OptionalValueOp, mlir_ts::OptionalUndefOp, mlir_ts::LoadLibraryPermanentlyOp, mlir_ts::SearchForAddressOfSymbolOp, diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 83c93a9b5..f00c6db81 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -495,12 +495,26 @@ class TypeDescriptorOpLowering : public TsLlvmPattern } } + // ...and the adapter reading its keys through `any` (TYPE_DESCR_KEYS), on the same terms + std::string keysRoutineName; + if (auto parentModule = op->getParentOfType()) + { + if (auto adapters = parentModule->getAttrOfType(ANY_KEYS_ADAPTERS_ATTR_NAME)) + { + if (auto adapterName = adapters.getAs(std::to_string(MLIRHelper::hashOfType(descriptorType))); + adapterName && parentModule.lookupSymbol(adapterName.getValue())) + { + keysRoutineName = adapterName.getValue().str(); + } + } + } + rewriter.replaceOp(op, ch.getOrCreateTypeDescriptorName(descriptorType, name, TypeOfOpHelper::typeKindFromName(name), releaseRoutineName, retainRoutineName, shareRoutineName, variant, TypeOfOpHelper::layoutIdOf(descriptorType), - callRoutineName)); + callRoutineName, keysRoutineName)); return success(); } @@ -8535,6 +8549,25 @@ struct AnyCallAdapterOpLowering : public TsLlvmPattern +{ + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::AnyKeysAdapterOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + auto loc = op.getLoc(); + + TypeConverterHelper tch(getTypeConverter()); + + AnyLogic al(op, rewriter, tch, loc, tsLlvmContext->compileOptions); + TypeDescriptorLogic tdl(rewriter, tch, loc, tsLlvmContext->compileOptions); + rewriter.replaceOp(op, tdl.getKeysFromTag(al.getTypeOfAny(transformed.getValue()))); + return success(); + } +}; + struct IsTypeTagOfOpLowering : public TsLlvmPattern { using TsLlvmPattern::TsLlvmPattern; @@ -10383,7 +10416,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation() LoadSaveValueLowering, ThrowUnwindOpLowering, ThrowCallOpLowering, TryEntryOpLowering,VariableOpLowering, DebugVariableOpLowering, AllocaOpLowering, InvokeOpLowering, AccessorUnwindEdgeOpLowering, InvokeHybridOpLowering, VirtualSymbolRefOpLowering, ThisVirtualSymbolRefOpLowering, ThisSymbolRefOpLowering, InterfaceSymbolRefOpLowering, NewInterfaceOpLowering, VTableOffsetRefOpLowering, LoadBoundRefOpLowering, StoreBoundRefOpLowering, CreateBoundRefOpLowering, - CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, IsTupleOfLayoutOpLowering, AnyCallAdapterOpLowering, IsTypeTagOfOpLowering, DebuggerOpLowering, + CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, IsTupleOfLayoutOpLowering, AnyCallAdapterOpLowering, AnyKeysAdapterOpLowering, IsTypeTagOfOpLowering, DebuggerOpLowering, UnreachableOpLowering, SymbolCallInternalOpLowering, CallInternalOpLowering, CallHybridInternalOpLowering, ReturnInternalOpLowering, NoOpLowering, GlobalConstructorOpLowering, AppendToUsedOpLowering, ExtractInterfaceThisOpLowering, ExtractInterfaceVTableOpLowering, BoxOpLowering, UnboxOpLowering, DialectCastOpLowering, CreateUnionInstanceOpLowering, diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 08b9d56e7..414609387 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -1683,9 +1683,9 @@ namespace mlirgen } else if (auto anyType = dyn_cast(arrayType)) { - emitError(location, "element access of a value of type 'any' ('x[k]') is not supported: cast it to its type first"); - return mlir::failure(); - } + // looked up at run time (user ruling 11-19) + return mlirGenAnyKey(location, expression, argumentExpression, ANY_KEYS_OP_GET, genContext); + } else { LLVM_DEBUG(llvm::dbgs() << "\n!! ElementAccessExpression: " << arrayType diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index b6eaccbc4..45d3d8af1 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -1354,6 +1354,15 @@ namespace mlirgen return mlir::failure(); } + // a constant array (`const a: any = [1, 2]`) is boxed as the array it makes: `a`, and its keys read + // through `any`, read the box as an array, and a constant array's is not one (a crash) + if (auto constArrayType = dyn_cast(valueType); constArrayType && isa(type)) + { + auto arrayType = mlir_ts::ArrayType::get(mth.wideStorageType(constArrayType.getElementType())); + CAST_A(arrayValue, location, arrayType, value, genContext); + return cast(location, type, arrayValue, genContext, disableStrictNullCheck); + } + // Boxing into `any` makes the box an owner of what it now holds, and it has to take a // reference to say so: an `any` releases its payload through the type tag beside it when // the box dies (`buildBody`, AnyType). Nothing took one. The payload was copied in, and @@ -1371,6 +1380,29 @@ namespace mlirgen { ensureAnyCallAdapter(location, valueType, genContext); } + + // ...and a key of a tuple, class, interface or array boxed in one read through it (user ruling 11-19): + // its keys adapter, for each of a union's members it may hold + auto ensureKeys = [&](mlir::Type boxedType) { + boxedType = TypeOfOpHelper::typeOfBaseType(boxedType); + if (isa(boxedType)) + { + ensureAnyKeysAdapter(location, boxedType, genContext); + } + }; + + if (auto unionType = dyn_cast(valueType)) + { + for (auto member : unionType.getTypes()) + { + ensureKeys(member); + } + } + else + { + ensureKeys(valueType); + } } auto castResult = builder.create(location, type, value); @@ -4608,5 +4640,460 @@ namespace mlirgen return result; } + // a number key, boxed as a number or as an integer (a literal given as `any`: "s32"), by its `typeof` in + // `kt` - not `typeof key` itself, which narrows `key` to a number whose box an s32 is not + static const std::string anyKeyIsNumberSource = + "kt == \"number\" || kt == \"s32\" || kt == \"s64\" || kt == \"u32\" || kt == \"u64\""; + + bool MLIRGenImpl::anyKeysOfType(mlir::Type type, SmallVector &values, SmallVector &methods, + llvm::StringSet<> *optionals) + { + llvm::StringSet<> seen; + auto addKey = [&](SmallVector &keys, StringRef name) { + // the compiler's own fields (`.vtbl`, `.rtti`, a base), a private name, and a constructor are no keys + if (name.empty() || name.starts_with(".") || name.starts_with("#") || name == "constructor") + { + return; + } + + if (seen.insert(name).second) + { + keys.push_back(name.str()); + } + }; + + if (auto classType = dyn_cast(type)) + { + auto classInfo = getClassInfoByFullName(classType.getName().getValue()); + if (!classInfo) + { + return false; + } + + // its public members: the adapter reads them as any code outside the class would + std::function walk = [&](ClassInfo::TypePtr info) { + auto storageType = mlir::cast(info->classType.getStorageType()); + for (auto &field : storageType.getFields()) + { + if (auto name = dyn_cast_or_null(field.id); + name && field.accessLevel == mlir_ts::AccessLevel::Public) + { + addKey(values, name.getValue()); + } + } + + for (auto &accessor : info->accessors) + { + if (!accessor.isStatic && accessor.get && accessor.getAccessLevel == mlir_ts::AccessLevel::Public) + { + addKey(values, accessor.name); + } + } + + for (auto &method : info->methods) + { + if (!method.isStatic && method.accessLevel == mlir_ts::AccessLevel::Public) + { + addKey(methods, method.name); + } + } + + for (auto &baseClass : info->baseClasses) + { + walk(baseClass); + } + }; + + walk(classInfo); + return true; + } + + if (auto interfaceType = dyn_cast(type)) + { + auto interfaceInfo = getInterfaceInfoByFullName(interfaceType.getName().getValue()); + if (!interfaceInfo) + { + return false; + } + + std::function walk = [&](InterfaceInfo::TypePtr info) { + for (auto &field : info->fields) + { + if (auto name = dyn_cast_or_null(field.id)) + { + addKey(values, name.getValue()); + if (field.isConditional && optionals) + { + optionals->insert(name.getValue()); + } + } + } + + for (auto &accessor : info->accessors) + { + addKey(values, accessor.name); + } + + for (auto &method : info->methods) + { + addKey(methods, method.name); + } + + for (auto &extend : info->extends) + { + if (extend.second) + { + walk(extend.second); + } + } + }; + + walk(interfaceInfo); + return true; + } + + if (isa(type)) + { + SmallVector keys; + if (!forInFieldKeys(type, keys)) + { + return false; + } + + for (auto &key : keys) + { + addKey(values, key); + } + + return true; + } + + return false; + } + + // The adapter of a tuple, class or interface type T whose keys are a, b, ... and methods m, ...: + // + // function __any_keys_(box: any, op: number, key: any, value: any): any { + // const k = the key's text (a string, or a number's: a tuple's position), else + // return op == HAS ? false : undefined; + // const o = box; + // if (k == "a") return op == HAS ? true : o["a"]; + // ... + // if (k == "m") { if (op == HAS) return true; throw new TypeError(...); } + // return op == HAS ? false : undefined; + // } + // + // and of an array type A, one generic for every array: + // + // function __any_keys_array(box: any, op: number, key: any, value: any): any { + // a number key in range its element, "length" its length, anything else undefined + // } + // + // 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. + void MLIRGenImpl::ensureAnyKeysAdapter(mlir::Location location, mlir::Type type, const GenContext &genContext) + { + if (compileOptions.memoryModel == MemoryModelOwn || genContext.allowPartialResolve || mth.isGenericType(type)) + { + return; + } + + // made once the module's statements are (makePendingAnyKeysAdapters), not here: here is the middle of + // whatever boxed it - an arrow function, a generic instantiated while its arguments are inferred, another + // adapter - and an adapter made inside one was made twice, or used a value of the function around it + anyKeysAdaptersPending.push_back({location, type}); + } + + void MLIRGenImpl::makePendingAnyKeysAdapters(const GenContext &genContext) + { + // an adapter boxes what it reads, which may add more + while (!anyKeysAdaptersPending.empty()) + { + auto [location, type] = anyKeysAdaptersPending.pop_back_val(); + makeAnyKeysAdapter(location, type, genContext); + } + } + + void MLIRGenImpl::makeAnyKeysAdapter(mlir::Location location, mlir::Type type, const GenContext &genContext) + { + type = TypeOfOpHelper::typeOfBaseType(type); + + auto isArray = isa(type); + SmallVector values; + SmallVector methods; + llvm::StringSet<> optionals; + if (!isArray && !anyKeysOfType(type, values, methods, &optionals)) + { + return; + } + + auto hash = MLIRHelper::hashOfType(type); + if (anyKeysAdaptersInProgress.contains(hash)) + { + return; + } + + if (auto existing = theModule->getAttrOfType(ANY_KEYS_ADAPTERS_ATTR_NAME); + existing && existing.get(std::to_string(hash))) + { + return; + } + + anyKeysAdaptersInProgress.insert(hash); + 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"; + + std::string name; + std::string src; + if (isArray) + { + name = "__any_keys_array"; + 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 == " + 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" + + notThere + + "}\n"; + } + else + { + auto quote = [](StringRef text) { + std::string quoted = "\""; + for (auto c : text) + { + if (c == '"' || c == '\\') + { + quoted += '\\'; + } + + quoted += c; + } + + return quoted + "\""; + }; + + auto isIndex = [](StringRef text) { + return !text.empty() && llvm::all_of(text, [](char c) { return c >= '0' && c <= '9'; }); + }; + + name = "__any_keys_" + std::to_string(hash); + // a number key is its text, as a tuple's position is + src = "function " + name + "(box: any, op: number, key: any, value: any): any {\n" + "const kt = typeof key;\n" + "let k = \"\";\n" + "if (kt == \"string\") k = key;\n" + "else if (" + anyKeyIsNumberSource + ") k = \"\" + key;\n" + "else " + notThere + + "const o = box;\n"; + for (auto &key : values) + { + // a tuple's unnamed field is read by its position + auto read = isIndex(key) ? "o[" + key + "]" : "o[" + quote(key) + "]"; + 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"; + continue; + } + + src += "if (k == " + quote(key) + ") return op == " + has + " ? true : " + read + ";\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") + + " }\n"; + } + + src += notThere + "}\n"; + } + + // nothing said while it is made reaches the program: what fails only leaves the type without one + mlir::ScopedDiagnosticHandler diagHandler(builder.getContext(), [&](mlir::Diagnostic &) {}); + mlir::SmallVector> postponedMessages; + GenContext adapterGenContext(genContext); + adapterGenContext.postponedMessages = &postponedMessages; + mlir::OpBuilder::InsertionGuard insertionGuard(builder); + + // info, we add "_" extra as scanner append "_" in front of "__"; + auto funcName = "_" + name; + auto funcRef = resolveIdentifier(location, funcName, adapterGenContext); + if (!funcRef) + { + MLIRLocationGuard vgLoc(overwriteLoc); + overwriteLoc = location; + if (mlir::failed(parsePartialStatements(stows(src)))) + { + return; + } + + funcRef = resolveIdentifier(location, funcName, adapterGenContext); + if (!funcRef) + { + return; + } + } + + NodeFactory nf(NodeFactoryFlags::None); + NodeArray typeArguments; + adapterGenContext.typeAliasMap.insert({".ANY_KEYS_T", type}); + typeArguments.push_back(nf.createTypeReferenceNode(nf.createIdentifier(S(".ANY_KEYS_T")).as())); + + SmallVector noOperands; + auto instance = mlirGenSpecialized(location, funcRef, typeArguments, noOperands, adapterGenContext); + if (instance.failed_or_no_value()) + { + return; + } + + auto symbolRefOp = V(instance).getDefiningOp(); + if (!symbolRefOp || !postponedMessages.empty()) + { + return; + } + + // nothing calls it by name - the descriptor takes its address in TypeDescriptorOpLowering - so it is + // public: private, SymbolDCE erased it before then (the JIT's pipeline) + auto adapterName = symbolRefOp.getIdentifierAttr().getValue(); + if (auto adapterOp = theModule.lookupSymbol(adapterName)) + { + mlir::SymbolTable::setSymbolVisibility(adapterOp, mlir::SymbolTable::Visibility::Public); + // its call in `__any_key` returns what it returns (OwnedReturnConsumptionPass), as a call adapter's + adapterOp->setAttr(ANY_CALL_ADAPTER_ATTR_NAME, builder.getUnitAttr()); + } + + // for the type's descriptor (TypeDescriptorOpLowering): TYPE_DESCR_KEYS + mlir::NamedAttrList adapters; + if (auto existing = theModule->getAttrOfType(ANY_KEYS_ADAPTERS_ATTR_NAME)) + { + adapters.append(existing.getValue()); + } + + adapters.set(std::to_string(hash), builder.getStringAttr(adapterName)); + theModule->setAttr(ANY_KEYS_ADAPTERS_ATTR_NAME, adapters.getDictionary(builder.getContext())); + } + + ValueOrLogicalResult MLIRGenImpl::mlirGenAnyKey(mlir::Location location, mlir::Value box, mlir::Value key, int op, + const GenContext &genContext) + { + 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)) + { + CAST(key, location, getNumberType(), key, genContext); + } + else if (isa(keyType) && key.getType() != keyType) + { + CAST(key, location, getStringType(), key, genContext); + } + + CAST_A(keyValue, location, getAnyType(), key, genContext); + + // info, we add "_" extra as scanner append "_" in front of "__"; + auto funcName = "___any_key"; + auto funcRef = resolveIdentifier(location, funcName, genContext); + if (!funcRef) + { + auto has = std::to_string(ANY_KEYS_OP_HAS); + // `b`: `box` before `typeof` narrowed it + std::string src = + "function __any_key(box: any, op: number, key: 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 == \"string\") {\n" + "if (op == " + has + ") " + throwTypeErrorSource("'k in x' of a string is not allowed") + "\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" + "return undefined;\n" + "}\n" + "if (kt == \"string\" && key == \"length\") return s.length;\n" + "return undefined;\n" + "}\n" + "const keys = __any_keys_adapter(b);\n" + "if (keys == null) {\n" + "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" + "return undefined;\n" + "}\n" + "return (<(box: any, op: number, key: any, value: any) => any>keys)(b, op, key, undefined);\n" + "}\n"; + + MLIRLocationGuard vgLoc(overwriteLoc); + overwriteLoc = location; + if (mlir::failed(parsePartialStatements(stows(src)))) + { + return mlir::failure(); + } + + funcRef = resolveIdentifier(location, funcName, genContext); + if (!funcRef) + { + return mlir::failure(); + } + } + + NodeFactory nf(NodeFactoryFlags::None); + GenContext keyGenContext(genContext); + keyGenContext.typeAliasMap.insert({".ANY_KEY_T", getAnyType()}); + + SmallVector operands; + operands.push_back(box); + operands.push_back(builder.create(location, getNumberType(), builder.getF64FloatAttr(op))); + operands.push_back(keyValue); + + auto result = mlirGenCallExpression(location, funcRef, + {nf.createTypeReferenceNode(nf.createIdentifier(S(".ANY_KEY_T")).as())}, + operands, keyGenContext); + EXIT_IF_FAILED_OR_NO_VALUE(result) + + // the one call through a value in `__any_key` is the adapter's: it returns what the adapter returns, a box + // its caller owns (OwnedReturnConsumptionPass) + theModule.walk([&](mlir_ts::FuncOp funcOp) { + if (funcOp.getName().starts_with("___any_key<")) + { + funcOp.walk([&](mlir_ts::CallIndirectOp callOp) { + callOp->setAttr(ANY_CALL_ADAPTER_CALL_ATTR_NAME, builder.getUnitAttr()); + }); + } + }); + + if (op == ANY_KEYS_OP_HAS) + { + return cast(location, getBooleanType(), V(result), genContext); + } + + if (auto definingOp = V(result).getDefiningOp()) + { + definingOp->setAttr(ANY_KEY_READ_ATTR_NAME, builder.getUnitAttr()); + } + + return result; + } + } // namespace mlirgen } // namespace typescript diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 1a9bb1552..9e177772e 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -1751,6 +1751,16 @@ namespace mlirgen return V(builder.create(location, getOpaqueType(), boxValue)); } + // `__any_keys_adapter(box)` of `__any_key` (mlirGenAnyKey): the keys adapter of the type of the value the box holds + if (callExpr == SyntaxKind::Identifier && MLIRHelper::getName(callExpr.as()) == "___any_keys_adapter" + && callExpression->arguments.size() == 1) + { + auto box = mlirGen(callExpression->arguments.front(), genContext); + EXIT_IF_FAILED_OR_NO_VALUE(box) + CAST_A(boxValue, location, getAnyType(), V(box), genContext); + return V(builder.create(location, getOpaqueType(), boxValue)); + } + // `Shared.count(s)` (own spec 23.1), unless the program declares its own `Shared`, which // wins as it does in type position and in `new`. if (callExpr == SyntaxKind::PropertyAccessExpression) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index de64501e2..cc09151ab 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -2627,11 +2627,22 @@ class MLIRGenImpl // if it is Optional type, we need to set to undefined if (isa(type) && !variableDeclarationInfo.initial) - { + { CAST_A(castedValue, location, type, getUndefined(location), genContext); variableDeclarationInfo.setInitial(castedValue); } + // -mm=rc: `let failure: any;` of a heap type starts empty, so that it owns what it is given like any other + // local (takeOwnershipOfLocal). With no initializer it borrowed: `failure = e` in a catch clause took no + // reference, the clause gave the caught value back, and `throw failure` after it threw freed memory. + // Not a catch clause's variable, which the landing pad writes. + if (!variableDeclarationInfo.initial && compileOptions.memoryModel == MemoryModelRC && !variableDeclarationInfo.isConst && + !variableDeclarationInfo.isGlobal && !genContext.declaringCatchVariable && genContext.ownedVars != nullptr && + !isa(type) && mth.ownsHeapMemory(location, mth.wideStorageType(type))) + { + variableDeclarationInfo.setInitial(builder.create(location, mth.wideStorageType(type))); + } + if (variableDeclarationInfo.isConst) { // A const array literal (`!ts.const_array`) that was routed into real @@ -7272,16 +7283,32 @@ class MLIRGenImpl EXIT_IF_FAILED_OR_NO_VALUE(resultLeft) auto leftExpressionValue = V(resultLeft); + auto resultRight = mlirGen(binaryExpressionAST->right, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(resultRight) + auto rightExpressionValue = V(resultRight); + + // `k in x` of `x: any`: asked of the keys of the value it holds, at run time (user ruling 11-19) + if (isa(rightExpressionValue.getType())) + { + return mlirGenAnyKey(location, rightExpressionValue, leftExpressionValue, ANY_KEYS_OP_HAS, genContext); + } + if (!isConstValue(leftExpressionValue)) { + // ...and a key known only at run time, of a value whose keys its type knows: asked of them the same way + SmallVector values; + SmallVector methods; + auto rightType = TypeOfOpHelper::typeOfBaseType(rightExpressionValue.getType()); + 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); + } + emitError(loc(binaryExpressionAST->left), "'k in obj' with a key known only at run time is not supported here: the key must be a constant"); return mlir::failure(); } - auto resultRight = mlirGen(binaryExpressionAST->right, genContext); - EXIT_IF_FAILED_OR_NO_VALUE(resultRight) - auto rightExpressionValue = V(resultRight); - // a number, a boolean or a bigint has no fields to look up (a string's `length` is an // extension: tests/00in_method_names.ts) auto rightBaseType = mth.getBaseType(rightExpressionValue.getType()); @@ -8187,6 +8214,13 @@ 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)) + { + emitError(location, "writing 'x[k]' of a value of type 'any' is not supported: cast it to its type first"); + return mlir::failure(); + } + auto leftExpressionValueBeforeCast = leftExpressionValue; // the type the place takes: a variable a test narrowed takes any its declaration allows, a field @@ -12707,6 +12741,34 @@ class MLIRGenImpl // function types an adapter is being made for: a function returning one of its own type is not made twice llvm::DenseSet anyCallAdaptersInProgress; + + // `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` + ValueOrLogicalResult mlirGenAnyKey(mlir::Location location, mlir::Value box, mlir::Value key, int op, + const GenContext &genContext); + + // 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) + void ensureAnyKeysAdapter(mlir::Location location, mlir::Type type, const GenContext &genContext); + + // The keys of a value of `type` an adapter reads (fields and accessors, `values`) and those it only says + // 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); + + // the adapter itself, made once the module's statements are (makePendingAnyKeysAdapters) + void makeAnyKeysAdapter(mlir::Location location, mlir::Type type, const GenContext &genContext); + + // the adapters of the types boxed while the module's statements were made + void makePendingAnyKeysAdapters(const GenContext &genContext); + + // types a keys adapter is being made for: a class with a field of its own type is not made twice + llvm::DenseSet anyKeysAdaptersInProgress; + + // types boxed whose keys adapters are still to be made + SmallVector> anyKeysAdaptersPending; ValueOrLogicalResult mlirGenObjectBuiltin(mlir::Location location, StringRef method, Expression argument, const GenContext &genContext); ValueOrLogicalResult mlirGenSharedShare(mlir::Location location, CallExpression callExpression, const GenContext &genContext); diff --git a/tslang/lib/TypeScript/MLIRGenModule.cpp b/tslang/lib/TypeScript/MLIRGenModule.cpp index 4dab440cd..4b8f93541 100644 --- a/tslang/lib/TypeScript/MLIRGenModule.cpp +++ b/tslang/lib/TypeScript/MLIRGenModule.cpp @@ -1496,6 +1496,12 @@ namespace mlirgen notResolved = 1; } + // the keys adapters of what the statements boxed into `any` (MLIRGenImpl::ensureAnyKeysAdapter) + if (notResolved == 0) + { + makePendingAnyKeysAdapters(genContext); + } + notResolved += takeExcessiveInstantiationError(); if (failed(outputDiagnostics(postponedMessages, notResolved))) @@ -1548,6 +1554,10 @@ namespace mlirgen } } + // ...and of what the entry code boxed: made here, inside the module's own generation (after it, they + // missed what it does next and left references unlowered) + makePendingAnyKeysAdapters(genContext); + clearTempModule(); eraseUnusedWeakFieldReads(); diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 132878f5f..365c11810 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -2369,12 +2369,14 @@ namespace mlirgen caughtName = varDecl ? MLIRHelper::getName(varDecl->name) : std::string(".caught.value"); caughtType = varDecl && varDecl->type ? getType(varDecl->type, genContext) : getAnyType(); varName = ".caught"; + GenContext catchVariableGenContext(genContext); + catchVariableGenContext.declaringCatchVariable = true; auto declaredType = registerVariable( location, varName, false, VariableType::Let, [&](mlir::Location, const GenContext &) -> TypeValueInitType { return {caughtType, mlir::Value(), TypeProvided::Yes}; }, - genContext); + catchVariableGenContext); if (!declaredType) { return mlir::failure(); @@ -2386,7 +2388,9 @@ namespace mlirgen if (varDecl) { varName = MLIRHelper::getName(varDecl->name); - if (mlir::failed(mlirGen(varDecl, VariableType::Let, genContext))) + GenContext catchVariableGenContext(genContext); + catchVariableGenContext.declaringCatchVariable = true; + if (mlir::failed(mlirGen(varDecl, VariableType::Let, catchVariableGenContext))) { return mlir::failure(); } diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 08982812f..c41d459e9 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -812,7 +812,7 @@ namespace own_inference } uses.push_back(user); - if (mlir::isa(user)) + if (mlir::isa(user)) { continue; } diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index ff1d67938..d6e9e5044 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -748,7 +748,7 @@ namespace own_inference // a test - `if (d)`, `d?.x`, `typeof u` - asks about the value, and keeps nothing if (mlir::isa(user)) + mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::AnyCallAdapterOp, mlir_ts::AnyKeysAdapterOp, mlir_ts::IsTypeTagOfOp>(user)) { return true; } diff --git a/tslang/test/android/android_skips.txt b/tslang/test/android/android_skips.txt index e9f72e78c..f078b2ec1 100644 --- a/tslang/test/android/android_skips.txt +++ b/tslang/test/android/android_skips.txt @@ -12,3 +12,4 @@ json.ts none # (default library) builds a 100000-character st # refused by design under the model, as in ctest (which registers them under the other models only) 00weak_field.ts rc # '@weak' is not supported under -mm=rc (own spec 93): ctest runs it under gc, none and own +00let_without_initializer_owns.ts own # copies an `any` holding an object, which -mm=own refuses at run time: ctest runs it under gc, rc and none diff --git a/tslang/test/suites.mjs b/tslang/test/suites.mjs index cbdcca64c..2d149dd49 100644 --- a/tslang/test/suites.mjs +++ b/tslang/test/suites.mjs @@ -54,6 +54,8 @@ export const makeSuites = (defaultLibRepo) => ({ if (first.startsWith("// gc only") && leg.mm !== "gc") return "marked '// gc only'"; if (first.startsWith("// linux only") && !leg.linux) return "marked '// linux only'"; if (first.startsWith("// not own") && leg.mm === "own") return "marked '// not own'"; + // what -mm=rc does not have (WeakRef, so FinalizationRegistry), as the default library's tests.ps1 skips it + if (first.startsWith("// not rc") && leg.mm === "rc") return "marked '// not rc'"; return null; }, passed: (run) => run.code !== 0 ? `exit code ${run.code}` diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index f1d2f6f11..1238a2e34 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -341,6 +341,8 @@ tslang_add_test(NAME test-compile-00-never-type COMMAND test-runner "${PROJECT_S tslang_add_test(NAME test-compile-00-cast-any-literal-field COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00cast_any_literal_field.ts") 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-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") tslang_add_test(NAME test-compile-00-const-array-to-array-elements COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00const_array_to_array_elements.ts") @@ -1055,6 +1057,8 @@ tslang_add_test(NAME test-jit-00-never-type COMMAND test-runner -jit "${PROJECT_ tslang_add_test(NAME test-jit-00-cast-any-literal-field COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00cast_any_literal_field.ts") 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-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") tslang_add_test(NAME test-jit-00-const-array-to-array-elements COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00const_array_to_array_elements.ts") @@ -3153,6 +3157,8 @@ set(TSLANG_CORPUS 00cast_any_literal_field.ts 00symbol_unique_key.ts 00any_call.ts + 00any_keys.ts + 00let_without_initializer_owns.ts 00call_signature_type.ts 00f_bounded_generic.ts 00types_indexedaccesstype.ts @@ -4065,6 +4071,33 @@ 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() +# ...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/conditional-named-const-release.cmake b/tslang/test/tester/conditional-named-const-release.cmake index 5fb93e69a..50c9e3ccf 100644 --- a/tslang/test/tester/conditional-named-const-release.cmake +++ b/tslang/test/tester/conditional-named-const-release.cmake @@ -44,7 +44,7 @@ set(expected "nestedChosen:1:1" "chosenInLoop:1:1" "returnChosen:1:1" - "assignedOutside:1:0") + "assignedOutside:1:1") foreach(entry IN LISTS expected) string(REPLACE ":" ";" entry "${entry}") list(POP_FRONT entry function) 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/any_key_assign.ts b/tslang/test/tester/crash-errors/any_key_assign.ts new file mode 100644 index 000000000..45003d77a --- /dev/null +++ b/tslang/test/tester/crash-errors/any_key_assign.ts @@ -0,0 +1,3 @@ +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 new file mode 100644 index 000000000..dc6ce4cc3 --- /dev/null +++ b/tslang/test/tester/crash-errors/any_key_compound.ts @@ -0,0 +1,3 @@ +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 new file mode 100644 index 000000000..3a2a86ae8 --- /dev/null +++ b/tslang/test/tester/crash-errors/any_key_increment.ts @@ -0,0 +1,3 @@ +function f(a: any, k: string) { + 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.ts b/tslang/test/tester/tests/00any_keys.ts new file mode 100644 index 000000000..99ceedb8d --- /dev/null +++ b/tslang/test/tester/tests/00any_keys.ts @@ -0,0 +1,139 @@ +// `x[k]` and `k in x` of a value of type `any` (user ruling 11-19): looked up at run time through the +// adapter made for the type of the value when it was boxed (TYPE_DESCR_KEYS). A key the value does not +// have reads undefined; a method is in it, but reading one is a TypeError. +class Point { + constructor(public x: number, protected y: number) { + } + + get sum() { return this.x + this.y; } + + norm() { return this.x * this.x + this.y * this.y; } +} + +class Point3 extends Point { + constructor(x: number, y: number, public z: number) { + super(x, y); + } +} + +interface Named { + name: string; + title?: string; +} + +class Tagged { + constructor(public tags: string[]) { + } +} + +class Node1 { + next: Node1 | null = null; + constructor(public value: number) { + } +} + +function get(o: any, k: any): any { + return o[k]; +} + +function has(o: any, k: any): boolean { + return k in o; +} + +function main() { + // an object literal + const o: any = { a: 1, b: "two" }; + assert(o["a"] == 1); + assert(o["b"] == "two"); + assert(typeof o["c"] == "undefined"); + const ka = "a"; + assert(get(o, ka) == 1); + assert(has(o, "b")); + assert(!has(o, "c")); + assert("a" in o); + + // a tuple: its positions + const t: any = <[number, string]>[5, "five"]; + assert(t[0] == 5); + assert(get(t, 1) == "five"); + assert(has(t, 0)); + assert(!has(t, 2)); + + // a class: its public fields and accessors, a base's too, and methods only for `in`; a protected field is + // not read from outside the class, through `any` either + const p: any = new Point3(3, 4, 5); + assert(p["x"] == 3); + assert(typeof get(p, "y") == "undefined"); + assert(!has(p, "y")); + assert(get(p, "z") == 5); + assert(get(p, "sum") == 7); + assert(has(p, "norm")); + assert(!has(p, "w")); + assert(typeof get(p, "w") == "undefined"); + let threw = false; + try { + get(p, "norm"); + } catch (e) { + threw = true; + } + assert(threw); + + // a class with a field of its own type + const n = new Node1(1); + n.next = new Node1(2); + const an: any = n; + const next: Node1 | null = an["next"]; + assert(next != null && next.value == 2); + + // a field boxed by the class's adapter: an array whose keys are read in turn + const tagged: any = new Tagged(["p", "q"]); + const tags: any = tagged["tags"]; + assert(tags[1] == "q"); + + // an interface: an optional field not set is not there, and reads undefined + const named: Named = { name: "n" }; + const ai: any = named; + assert(ai["name"] == "n"); + assert(!has(ai, "title")); + assert(typeof get(ai, "title") == "undefined"); + + // an array (a constant one, boxed as the array it makes): its elements in range, and its length + const a: any = [10, 20, 30]; + assert(a[1] == 20); + assert(get(a, "length") == 3); + assert(typeof get(a, 3) == "undefined"); + assert(has(a, 2)); + assert(!has(a, 3)); + const nums: number[] = [1.5, 2.5]; + const an2: any = nums; + assert(an2[1] == 2.5); + const back = an2; + assert(back.length == 2 && back[0] == 1.5); + + // a string: its characters and its length + const s: any = "abc"; + assert(s[1] == "b"); + assert(get(s, "length") == 3); + + // a number has no keys: undefined, and `in` of it a TypeError + const num: any = 5; + assert(typeof get(num, "x") == "undefined"); + + // null: a TypeError + let nullThrew = false; + try { + get(null, "x"); + } catch (e) { + nullThrew = true; + } + assert(nullThrew); + + // a key known only at run time, of a value whose type knows its keys + const plain = { u: 1, v: 2 }; + let key = "v"; + assert(key in plain); + key = "w"; + assert(!(key in plain)); + + print("done."); +} diff --git a/tslang/test/tester/tests/00conditional_named_const_release.ts b/tslang/test/tester/tests/00conditional_named_const_release.ts index f789eb6d9..6ef4e908b 100644 --- a/tslang/test/tester/tests/00conditional_named_const_release.ts +++ b/tslang/test/tester/tests/00conditional_named_const_release.ts @@ -68,8 +68,8 @@ function returnChosen(b: boolean) { return b ? h : h2; } -// the local declared without a value owns nothing, so `h` is what keeps the value it is given -// alive after the `if`: it is not released at the end of the `if` +// the local declared without a value starts empty and owns what it is given (rc), so `h` is released +// at the end of the `if` like any other: `n` holds a reference of its own to the value chosen function assignedOutside(b: boolean) { const h2 = new C(30); let n: C; diff --git a/tslang/test/tester/tests/00let_without_initializer_owns.ts b/tslang/test/tester/tests/00let_without_initializer_owns.ts new file mode 100644 index 000000000..50697fa1d --- /dev/null +++ b/tslang/test/tester/tests/00let_without_initializer_owns.ts @@ -0,0 +1,46 @@ +// A `let` of a heap type declared without an initializer owns what it is given, as one declared with +// a value does. Under -mm=rc it borrowed: `failure = e` in a catch clause took no reference, the clause +// gave the caught value back as it ended, and `throw failure` after it threw a freed block (the default +// library's DisposableStack.dispose; the wasm host's heap check found the second free). +class Failure { + constructor(public name: string) { + } +} + +function run(f: () => void) { + let failure: any; + let failed = false; + try { + f(); + } catch (e) { + failure = e; + failed = true; + } + + if (failed) throw failure; +} + +function keep(n: number): string { + let kept: string; + { + const made = "v" + n; + kept = made; + } + + return kept + "!"; +} + +function main() { + let caught = ""; + for (let i = 0; i < 3; i++) { + try { + run(() => { throw new Failure("f" + i); }); + } catch (e) { + caught += (e).name; + } + } + + assert(caught == "f0f1f2", "thrown again after the catch clause"); + assert(keep(7) == "v7!", "kept past the block that made it"); + print("done."); +} diff --git a/tslang/test/wasm/host.mjs b/tslang/test/wasm/host.mjs index d70a2029a..2c4f6193e 100644 --- a/tslang/test/wasm/host.mjs +++ b/tslang/test/wasm/host.mjs @@ -1127,6 +1127,10 @@ export function createHost(options = {}) // C's round: halves away from zero (Math.round takes them up) round: (x) => (x < 0 ? -Math.round(-x) : Math.round(x)), fmod: (x, y) => x % y, + // x * 2^e, which LLVM makes of `pow(2, e)` (the default library's float16 code): in two steps, so that + // a scale 2^e alone would overflow or underflow (e beyond -1022..1023) still gives the product + ldexp: (x, e) => { const h = e >> 1; return x * Math.pow(2, h) * Math.pow(2, e - h); }, + ldexpf: (x, e) => { const h = e >> 1; return Math.fround(x * Math.pow(2, h) * Math.pow(2, e - h)); }, fmin: Math.min, fmax: Math.max, abs: (x) => (x < 0 ? -x | 0 : x), labs: (x) => (typeof x === "bigint" ? (x < 0n ? -x : x) : (x < 0 ? -x | 0 : x)), diff --git a/tslang/test/wasm/wasm_skips.txt b/tslang/test/wasm/wasm_skips.txt index d42cd1c04..f67ff03c5 100644 --- a/tslang/test/wasm/wasm_skips.txt +++ b/tslang/test/wasm/wasm_skips.txt @@ -16,3 +16,4 @@ json.ts none # (default library) builds a 100000-character st # fails natively under the same model too (not run natively under it by ctest) 01tuple.ts own # frees a block it does not own (native own: the program does not finish either) 00global_interface_initializer.ts own # asserts "a field read" (native own: the same assert) +00let_without_initializer_owns.ts own # copies an `any` holding an object, which -mm=own refuses at run time by design (native own: the same assert)