diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 129c17372..f20f40246 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -2106,3 +2106,47 @@ What remains of the tsc-clean failures is mostly the default library's (`Object. object literal, properties added to a function, a `never` tslang computes, declared-function overloads). Tests: diagnostic-location `generic_construct_signature_type_literal.ts`. + +152 (keys known only at run time, 2026-11-21; USER DECISIONS: a string index signature is a dictionary, an absent key +reads `T | undefined`, under -mm=own the dictionary owns its values). Fixed: +- `{ [key: string]: T }`, a string index signature and nothing else, is the default library's `ObjectDictionary` + (`@dictionary`, TypeScriptCompilerDefaultLib #114): entries by key known at run time, in the order they were added. + Before, it was a record of `get`/`set` functions nothing could fill: `const d: { [k: string]: number } = { a: 1 }` + was "field "get" can't be found in tuple '{a:s32}'". +- `d[k]`, `d["name"]` and `d.name` of a dictionary, outside its own class, are its entries - never its members, so + `d.get` and `d.size` are entries too - read as `T | undefined` (undefined for a key it does not hold) and written as + T. `k in d`, `for...in`, `Object.keys(d)` and `delete d[k]` / `delete d.name` go by its entries. +- An object literal with a key known only at run time (`{ [m]: i }` with `m: string`) makes a dictionary of its values' + type, and so does one given where a dictionary is wanted (`const d: { [k: string]: T } = { a: 1 }`, an argument, a + return). A spread into one copies a record's fields, or a dictionary's entries (the library's + `objectDictionaryAssign`). Before: "a computed property name must be a constant (a literal, or a `const` holding + one), or a well-known symbol". Whether a key is a constant is decided as before: its value's constant, or its + literal type's (an imported `const`, `"a" + "b"` folded). +- A dictionary type given from elsewhere (a `return`'s receiver, a result type found in an earlier pass) is + instantiated again where the literal is made: it may have been instantiated only in an evaluation, and then its + members were generated nowhere ("'ObjectDictionary.constructor' does not reference a valid function"). +- -mm=own: a parameter moved on paths that exclude each other - `if (f) a.push(v); else a[0] = v;`, a move then + `return` and another move after it, a `T | undefined` narrowed once and moved on two paths - was "'v' is used here + after its value was moved" (only one move of a parameter was allowed). Each move empties the parameter, so the + release at the exit, kept for a path that moves nothing, frees nothing on the others; one the function keeps on + every path is reached at each exit only through one of the moves (movesOnExclusivePaths). The dictionary's `set` + needs it. Leak probes, flat at 33 MB: 20M calls moving a parameter on exclusive paths (own), 3M writes, + overwrites and deletes of a dictionary of objects (rc and own). + +- Found on the way: a module importing another and using a Map (`import "./a"; new Map()`) + failed with "'ts.Func' op symbol declaration cannot have public visibility": the keys adapter of the RangeError + the library's Map throws was made while the imported file was read as declarations, a declaration, then made + public. It is made in full there now, as a specialization is (makeAnyKeysAdapter). + +Still open, looked at: +- An interface with only a string index signature (`interface Dictionary { [x: string]: T }`) is still an + interface: the dictionary is for the type literal (and so for what is written with it). +- -mm=own: a local moved inside two `if`s one after the other (`if (a) keep(k); if (b) keep(k);`) is "moved here on + some paths only" - so the dictionary copies its keys rather than taking the caller's; a spread of a record into a + dictionary is refused (its fields would have two owners). +- A spread of a dictionary into one of another value type is an error for now: inferring `f(a: Box, b: + Box)` from `f(Box, Box)` gives T = number | string and S = any, and the call then reads the + second argument with the wrong layout (a crash) - a generic-inference bug of its own. +- `a[a.length] = x` on an array does not grow it (gc writes past the end; rc and own crash). + +Tests: `00object_dictionary.ts`, `00own_param_exclusive_moves.ts` (compile, JIT, rc, own). diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 747fde1a3..2bb7e1067 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -558,6 +558,13 @@ // a Shared handle (counted): an object, whose block has one owner, goes through Shared. // The other memory models ignore it. #define SHARED_ELEMENTS_DECORATOR "sharedElements" +// `@dictionary class ObjectDictionary`: the value of a string index signature (`{ [key: string]: T }`, +// `{ [k]: v }` with a key known only at run time). Outside the class, `d.name` and `d["name"]` are its +// entries, never its members (ClassInfo::isDictionary). +#define DICTIONARY_DECORATOR "dictionary" +#define OBJECT_DICTIONARY_CLASS_NAME "ObjectDictionary" +// the default library's function a spread of a dictionary into a new one calls +#define OBJECT_DICTIONARY_ASSIGN_NAME "objectDictionaryAssign" // On a `ts.ThisVirtualSymbolRef` (a method's) or a `ts.VirtualSymbolRef` (an accessor's): the // receiver's class is @final, but defined in another module, so the call still goes through the // vtable. The slot holds the method the reference names, which diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index c0690b752..a70b6825a 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -897,6 +897,9 @@ struct ClassInfo // else, a slot left to a declared C++ method null), may have a constructor and field // initializers, and `.new`; still no RTTI. tslang allocates its objects. bool isCppVTableImplementation = false; + // `@dictionary`: the value of a string index signature. Outside its own methods `d.name` + // and `d["name"]` read and write its entries, not its members. + bool isDictionary = false; // `@atomic`: its objects may be used by several threads at once. Under -mm=rc a new object is // marked shared, with everything it holds, once its constructor has run, and a value stored // into one of its fields is marked before the store (ts.MarkShared), so every block reachable diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 1ea68164c..3ffb52ea1 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -1710,6 +1710,12 @@ namespace mlirgen } else if (auto classType = dyn_cast(arrayType)) { + // `d[k]` of a dictionary is its entry `k`, whatever k names + if (auto entry = mlirGenDictionaryEntry(location, expression, argumentExpression, isConditionalAccess, genContext)) + { + return *entry; + } + if (auto fieldName = argumentExpression.getDefiningOp()) { auto attr = fieldName.getValue(); @@ -3738,5 +3744,537 @@ namespace mlirgen return mlirGenCallExpression(location, newCtorMethod, typeArguments, operands, genContext); } + // ---- a string index signature's value: ObjectDictionary (OBJECT_DICTIONARY_CLASS_NAME) ---- + // + // `{ [key: string]: T }` is a dictionary of T whose keys are known at run time, a class of the default + // library marked @dictionary. Outside its own methods `d.name`, `d["name"]` and `d[k]` are its + // entries - read as `T | undefined`, written as T - and never its members. An object literal + // with a key known only at run time (`{ [m]: i }`), or one given where a dictionary is wanted, + // makes one. + + ClassInfo::TypePtr MLIRGenImpl::dictionaryClassInfoOf(mlir::Type type, const GenContext &genContext) + { + auto classType = dyn_cast_or_null(type); + if (!classType) + { + return ClassInfo::TypePtr(); + } + + auto classInfo = getClassInfoByFullName(classType.getName().getValue()); + return classInfo && classInfo->isDictionary ? classInfo : ClassInfo::TypePtr(); + } + + mlir::Type MLIRGenImpl::getObjectDictionaryType(mlir::Location location, mlir::Type valueType, const GenContext &genContext) + { + auto genericClassInfo = getGenericClassInfoByFullName(OBJECT_DICTIONARY_CLASS_NAME); + if (!genericClassInfo || !valueType) + { + return mlir::Type(); + } + + SmallVector typeArguments{valueType}; + auto [result, specializedType] = + instantiateSpecializedClassType(location, genericClassInfo->classType, typeArguments, genContext, true); + if (mlir::failed(result)) + { + return mlir::Type(); + } + + return specializedType; + } + + // The dictionary type `type`, instantiated again here. A type given from elsewhere - the receiver of a + // `return`, the function's result type found in an earlier pass - may have been instantiated only where + // nothing was kept (an evaluation, a discovery pass), and then its members are generated nowhere ("'ts.Call' + // op 'ObjectDictionary.constructor' does not reference a valid function"). `new C()` always + // resolves its type here; a dictionary made for an object literal must too. + mlir::Type MLIRGenImpl::instantiatedDictionaryType(mlir::Location location, mlir::Type type, const GenContext &genContext) + { + auto classInfo = dictionaryClassInfoOf(type, genContext); + if (!classInfo || classInfo->typeParamsWithArgs.size() != 1) + { + return type; + } + + auto valueType = std::get<1>(classInfo->typeParamsWithArgs.begin()->getValue()); + auto instantiated = getObjectDictionaryType(location, valueType, genContext); + return instantiated ? instantiated : type; + } + + std::optional MLIRGenImpl::mlirGenDictionaryEntry(mlir::Location location, mlir::Value objectValue, + mlir::Value key, bool isConditional, const GenContext &genContext) + { + // inside its own methods, `this.name` is the member + if (!dictionaryClassInfoOf(objectValue.getType(), genContext) || + (genContext.thisType && genContext.thisType == objectValue.getType())) + { + return std::nullopt; + } + + if (!isa(key.getType())) + { + auto stringKey = cast(location, getStringType(), key, genContext); + if (stringKey.failed_or_no_value()) + { + return ValueOrLogicalResult(mlir::failure()); + } + + key = V(stringKey); + } + + auto indexAccessor = builder.getStringAttr(INDEX_ACCESS_FIELD_NAME); + return mlirGenPropertyAccessExpression(location, objectValue, indexAccessor, isConditional, key, genContext); + } + + std::optional MLIRGenImpl::mlirGenDictionaryEntry(mlir::Location location, mlir::Value objectValue, + StringRef name, bool isConditional, const GenContext &genContext) + { + if (!dictionaryClassInfoOf(objectValue.getType(), genContext) || + (genContext.thisType && genContext.thisType == objectValue.getType())) + { + return std::nullopt; + } + + auto key = builder.create(location, getStringType(), builder.getStringAttr(name)); + return mlirGenDictionaryEntry(location, objectValue, key, isConditional, genContext); + } + + mlir::LogicalResult MLIRGenImpl::mlirGenDictionarySet(mlir::Location location, mlir::Value dictionary, mlir::Value key, + mlir::Value value, const GenContext &genContext) + { + if (!isa(key.getType())) + { + auto stringKey = cast(location, getStringType(), key, genContext); + if (stringKey.failed_or_no_value()) + { + return mlir::failure(); + } + + key = V(stringKey); + } + + SmallVector operands{key, value}; + auto result = mlirGenDictionaryCall(location, dictionary, INDEX_ACCESS_SET_FIELD_NAME, operands, genContext); + return mlir::failed(result.result) ? mlir::failure() : mlir::success(); + } + + // a member of the dictionary itself (`has`, `keys`, `delete`, `set`): what a dictionary's name access, an + // entry, would not give + ValueOrLogicalResult MLIRGenImpl::mlirGenDictionaryCall(mlir::Location location, mlir::Value dictionary, StringRef method, + SmallVector &operands, const GenContext &genContext) + { + auto methodResult = mlirGenPropertyAccessExpression(location, dictionary, method, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(methodResult) + return mlirGenCall(location, V(methodResult), operands, genContext); + } + + // `delete d[k]` and `delete d.name` of a dictionary: its entry is deleted (not the object freed) + std::optional MLIRGenImpl::mlirGenDictionaryDelete(mlir::Location location, Expression operand, + const GenContext &genContext) + { + Expression objectExpression; + if (operand == SyntaxKind::ElementAccessExpression) + { + objectExpression = operand.as()->expression; + } + else if (operand == SyntaxKind::PropertyAccessExpression) + { + objectExpression = operand.as()->expression; + } + else + { + return std::nullopt; + } + + if (!dictionaryClassInfoOf(evaluate(objectExpression, genContext), genContext)) + { + return std::nullopt; + } + + auto objectResult = mlirGen(objectExpression, genContext); + if (objectResult.failed_or_no_value()) + { + return mlir::failure(); + } + + mlir::Value key; + if (operand == SyntaxKind::ElementAccessExpression) + { + auto keyResult = mlirGen(operand.as()->argumentExpression, genContext); + if (keyResult.failed_or_no_value()) + { + return mlir::failure(); + } + + key = V(keyResult); + if (!isa(key.getType())) + { + auto stringKey = cast(location, getStringType(), key, genContext); + if (stringKey.failed_or_no_value()) + { + return mlir::failure(); + } + + key = V(stringKey); + } + } + else + { + auto name = MLIRHelper::getName(operand.as()->name, stringAllocator); + key = builder.create(location, getStringType(), builder.getStringAttr(name)); + } + + SmallVector operands{key}; + auto result = mlirGenDictionaryCall(location, V(objectResult), "delete", operands, genContext); + return mlir::failed(result.result) ? mlir::failure() : mlir::success(); + } + + ValueOrLogicalResult MLIRGenImpl::castTupleToDictionary(mlir::Location location, mlir::Value value, mlir_ts::TupleType srcTupleType, + mlir_ts::ClassType classType, const GenContext &genContext) + { + SmallVector noOperands; + auto newResult = NewClassInstance(location, mlir::cast(instantiatedDictionaryType(location, classType, genContext)), + noOperands, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(newResult) + auto dictionary = V(newResult); + + for (auto &field : srcTupleType.getFields()) + { + auto name = dyn_cast_or_null(field.id); + if (!name) + { + emitError(location) << "a field of '" << to_print(srcTupleType) << "' has no name a dictionary can hold"; + return mlir::failure(); + } + + auto fieldResult = mlirGenPropertyAccessExpression(location, value, field.id, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(fieldResult) + auto key = builder.create(location, getStringType(), name); + if (mlir::failed(mlirGenDictionarySet(location, dictionary, key, V(fieldResult), genContext))) + { + return mlir::failure(); + } + } + + return dictionary; + } + + std::optional MLIRGenImpl::mlirGenObjectLiteralAsDictionary(mlir::Location location, + ObjectLiteralExpression objectLiteral, const GenContext &genContext) + { + auto receiverType = genContext.receiverType ? mth.stripOptionalType(genContext.receiverType) : mlir::Type(); + auto dictionaryType = dictionaryClassInfoOf(receiverType, genContext) ? receiverType : mlir::Type(); + + auto nameOf = [](Node property) -> Node { + if (property == SyntaxKind::PropertyAssignment) + { + return property.as()->name; + } + + if (property == SyntaxKind::MethodDeclaration) + { + return property.as()->name; + } + + if (property == SyntaxKind::GetAccessor) + { + return property.as()->name; + } + + if (property == SyntaxKind::SetAccessor) + { + return property.as()->name; + } + + return Node(); + }; + + // A spread of a dictionary makes one too (`{ ...m }` of `m: { [k: string]: T }`) + auto spreadsDictionary = false; + for (auto property : objectLiteral->properties) + { + if (property == SyntaxKind::SpreadAssignment && + dictionaryClassInfoOf(evaluate(property.as()->expression, genContext), genContext)) + { + spreadsDictionary = true; + } + } + + // A computed name whose key is known only at run time: a string or a number with no constant to it, + // as getNameFromComputedPropertyName finds one (its value's, or its literal type's). The keys are + // made here, in order, and kept for the dictionary: a constant one left unused is only a constant. + auto runTimeKey = false; + SmallVector computedKeys(objectLiteral->properties.size()); + auto anyComputed = llvm::any_of(objectLiteral->properties, [&](Node property) { + auto name = nameOf(property); + return name && name == SyntaxKind::ComputedPropertyName; + }); + if (anyComputed) + { + for (auto [index, property] : llvm::enumerate(objectLiteral->properties)) + { + auto name = nameOf(property); + if (!name || name != SyntaxKind::ComputedPropertyName) + { + continue; + } + + auto expression = name.as()->expression; + if (!wellKnownSymbolName(expression).empty()) + { + continue; + } + + // only a key whose type is a string or a number, not a literal, is made here; any other (one + // that does not resolve yet, a symbol) is the record's, as before + auto keyType = evaluate(expression, genContext); + if (!keyType || !(isa(keyType) || + isa(keyType))) + { + continue; + } + + auto keyResult = mlirGen(expression, genContext); + if (keyResult.failed_or_no_value()) + { + return ValueOrLogicalResult(mlir::failure()); + } + + auto value = V(keyResult); + + computedKeys[index] = value; + MLIRCodeLogic mcl(builder, compileOptions); + mlir::Attribute constant = mcl.ExtractAttr(value); + if (!constant) + { + if (auto folded = foldableConstant(value)) + { + constant = folded.getValue(); + } + else if (auto literalType = dyn_cast(value.getType())) + { + constant = literalType.getValue(); + } + } + + if (constant) + { + computedNameConstants[name.as().operator->()] = constant; + } + else + { + runTimeKey = true; + } + } + } + + if (!runTimeKey && !dictionaryType && !spreadsDictionary) + { + return std::nullopt; + } + + for (auto property : objectLiteral->properties) + { + if (property != SyntaxKind::PropertyAssignment && property != SyntaxKind::ShorthandPropertyAssignment && + property != SyntaxKind::SpreadAssignment) + { + // a dictionary wanted, but a method here: made as a record and cast, as before + if (!runTimeKey && !spreadsDictionary) + { + return std::nullopt; + } + + emitError(loc(property)) << "an object literal that makes a dictionary (a key known only at run time, or a " + "dictionary spread into it) can hold only properties and spreads"; + return ValueOrLogicalResult(mlir::failure()); + } + } + + auto valueExpressionOf = [](Node property) -> Expression { + if (property == SyntaxKind::PropertyAssignment) + { + return property.as()->initializer; + } + + return property.as()->name.as(); + }; + + if (!dictionaryType) + { + SmallVector valueTypes; + for (auto property : objectLiteral->properties) + { + if (property == SyntaxKind::SpreadAssignment) + { + auto spreadType = evaluate(property.as()->expression, genContext); + if (auto classInfo = dictionaryClassInfoOf(spreadType, genContext); classInfo && classInfo->typeParamsWithArgs.size() == 1) + { + valueTypes.push_back(std::get<1>(classInfo->typeParamsWithArgs.begin()->getValue())); + continue; + } + + llvm::SmallVector fields; + if (!spreadType || mlir::failed(mth.getFields(spreadType, fields))) + { + emitError(loc(property)) << "a spread into a dictionary of a value of type '" << to_print(spreadType) + << "' is not supported"; + return ValueOrLogicalResult(mlir::failure()); + } + + for (auto &field : fields) + { + valueTypes.push_back(mth.wideStorageType(mth.stripLiteralType(field.type))); + } + + continue; + } + + auto valueType = evaluate(valueExpressionOf(property), genContext); + if (!valueType) + { + return ValueOrLogicalResult(mlir::failure()); + } + + valueTypes.push_back(mth.wideStorageType(mth.stripLiteralType(valueType))); + } + + auto valueType = valueTypes.empty() ? mlir::Type(getAnyType()) : mth.getUnionTypeWithMerge(location, valueTypes); + dictionaryType = getObjectDictionaryType(location, valueType, genContext); + if (!dictionaryType) + { + emitError(location) << "a key known only at run time makes a dictionary, the default library's '" + << OBJECT_DICTIONARY_CLASS_NAME << "', which is not there"; + return ValueOrLogicalResult(mlir::failure()); + } + } + + SmallVector noOperands; + dictionaryType = instantiatedDictionaryType(location, dictionaryType, genContext); + auto newResult = NewClassInstance(location, mlir::cast(dictionaryType), noOperands, genContext); + if (newResult.failed_or_no_value()) + { + return ValueOrLogicalResult(mlir::failure()); + } + + auto dictionary = V(newResult); + + GenContext valueGenContext(genContext); + valueGenContext.receiverType = mlir::Type(); + for (auto [index, property] : llvm::enumerate(objectLiteral->properties)) + { + // `...s`: a record's fields, known here, each set; a dictionary's entries, copied by the default + // library's objectDictionaryAssign (a generic function: made only where it is used) + if (property == SyntaxKind::SpreadAssignment) + { + auto spreadLocation = loc(property); + auto spreadResult = mlirGen(property.as()->expression, genContext); + if (spreadResult.failed_or_no_value()) + { + return ValueOrLogicalResult(mlir::failure()); + } + + auto spreadValue = V(spreadResult); + if (dictionaryClassInfoOf(spreadValue.getType(), genContext)) + { + if (spreadValue.getType() != dictionary.getType()) + { + emitError(spreadLocation) << "a spread of '" << to_print(spreadValue.getType()) << "' into '" + << to_print(dictionary.getType()) + << "' is not supported yet: the values' types have to be the same"; + return ValueOrLogicalResult(mlir::failure()); + } + + auto assign = resolveIdentifier(spreadLocation, OBJECT_DICTIONARY_ASSIGN_NAME, genContext); + if (!assign) + { + emitError(spreadLocation) << "a spread of a dictionary needs the default library's '" + << OBJECT_DICTIONARY_ASSIGN_NAME << "', which is not there"; + return ValueOrLogicalResult(mlir::failure()); + } + + SmallVector operands{dictionary, spreadValue}; + auto assigned = mlirGenCallExpression(spreadLocation, assign, {}, operands, genContext); + if (mlir::failed(assigned.result)) + { + return ValueOrLogicalResult(mlir::failure()); + } + + continue; + } + + llvm::SmallVector fields; + if (mlir::failed(mth.getFields(spreadValue.getType(), fields))) + { + emitError(spreadLocation) << "a spread into a dictionary of a value of type '" + << to_print(spreadValue.getType()) << "' is not supported"; + return ValueOrLogicalResult(mlir::failure()); + } + + for (auto &field : fields) + { + auto name = dyn_cast_or_null(field.id); + if (!name) + { + emitError(spreadLocation) << "a field of '" << to_print(spreadValue.getType()) + << "' has no name a dictionary can hold"; + return ValueOrLogicalResult(mlir::failure()); + } + + auto fieldResult = mlirGenPropertyAccessExpression(spreadLocation, spreadValue, field.id, genContext); + if (fieldResult.failed_or_no_value()) + { + return ValueOrLogicalResult(mlir::failure()); + } + + auto fieldKey = builder.create(spreadLocation, getStringType(), name); + if (mlir::failed(mlirGenDictionarySet(spreadLocation, dictionary, fieldKey, V(fieldResult), genContext))) + { + return ValueOrLogicalResult(mlir::failure()); + } + } + + continue; + } + + mlir::Value key = computedKeys[index]; + Node name = property == SyntaxKind::PropertyAssignment ? property.as()->name + : property.as()->name.as(); + if (!key && name == SyntaxKind::ComputedPropertyName) + { + auto keyResult = mlirGen(name.as()->expression, genContext); + if (keyResult.failed_or_no_value()) + { + return ValueOrLogicalResult(mlir::failure()); + } + + key = V(keyResult); + } + else if (!key) + { + auto nameAttr = dyn_cast_or_null(TupleFieldName(name, genContext)); + if (!nameAttr) + { + emitError(loc(property)) << "a key a dictionary can't hold"; + return ValueOrLogicalResult(mlir::failure()); + } + + key = builder.create(loc(property), getStringType(), nameAttr); + } + + auto valueResult = mlirGen(valueExpressionOf(property), valueGenContext); + if (valueResult.failed_or_no_value()) + { + return ValueOrLogicalResult(mlir::failure()); + } + + if (mlir::failed(mlirGenDictionarySet(loc(property), dictionary, key, V(valueResult), genContext))) + { + return ValueOrLogicalResult(mlir::failure()); + } + } + + return ValueOrLogicalResult(dictionary); + } + } // namespace mlirgen } // namespace typescript diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index d51f4bd79..a967fe347 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -413,6 +413,12 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::castTupleToClass(mlir::Location location, mlir::Value value, mlir_ts::TupleType srcTupleType, ArrayRef fields, mlir_ts::ClassType classType, const GenContext &genContext, bool errorAsWarning) { + // `const d: { [key: string]: number } = { a: 1 }`: a dictionary holding the literal's fields + if (dictionaryClassInfoOf(classType, genContext)) + { + return castTupleToDictionary(location, value, srcTupleType, classType, genContext); + } + SmallVector values; auto result = mapTupleToFields(location, values, value, srcTupleType, fields, true, genContext, errorAsWarning); @@ -5000,6 +5006,11 @@ namespace mlirgen auto adapterName = symbolRefOp.getIdentifierAttr().getValue(); if (auto adapterOp = theModule.lookupSymbol(adapterName)) { + if (auto adapterFunc = dyn_cast(adapterOp); adapterFunc && adapterFunc.isDeclaration()) + { + return; + } + mlir::SymbolTable::setSymbolVisibility(adapterOp, mlir::SymbolTable::Visibility::Public); // its call in `__any_invoke` returns what it returns (OwnedReturnConsumptionPass) adapterOp->setAttr(ANY_CALL_ADAPTER_ATTR_NAME, builder.getUnitAttr()); @@ -5630,6 +5641,11 @@ namespace mlirgen GenContext adapterGenContext(genContext); adapterGenContext.postponedMessages = &postponedMessages; mlir::OpBuilder::InsertionGuard insertionGuard(builder); + // made in full even while an imported file is only being declared (its library's code boxed the type), + // as a specialization is: as a declaration it was made public, "'ts.Func' op symbol declaration cannot + // have public visibility", which failed every module importing another that made one + MLIRValueGuard declarationModeGuard(declarationMode); + declarationMode = false; // info, we add "_" extra as scanner append "_" in front of "__"; auto funcName = "_" + name; diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index c6caf337e..36f438952 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -458,6 +458,11 @@ namespace mlirgen newClassPtr->isExport = true; } + if (name == DICTIONARY_DECORATOR) + { + newClassPtr->isDictionary = true; + } + if (name == DLL_IMPORT) { newClassPtr->isDeclaration = true; diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index b20614960..b8bf9cbf9 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -1559,6 +1559,13 @@ namespace mlirgen return V(builder.create(location, getSymbolType(), builder.getStringAttr(wellKnown))); } + // `d.name` of a dictionary is its entry `name` + if (auto entry = mlirGenDictionaryEntry(location, expressionValue, namePtr, + !!propertyAccessExpression->questionDotToken, genContext)) + { + return *entry; + } + auto propAccessStrRef = mlir::StringRef(print(propertyAccessExpression)).copy(stringAllocator); auto fieldResult = mlirGenPropertyAccessExpression(location, expressionValue, namePtr, @@ -1592,6 +1599,12 @@ namespace mlirgen EXIT_IF_FAILED_OR_NO_VALUE(result) auto namePtr = MLIRHelper::getName(propertyAccessExpression->name, stringAllocator); + if (auto entry = mlirGenDictionaryEntry(location, V(result), namePtr, + !!propertyAccessExpression->questionDotToken, genContext)) + { + return *entry; + } + return mlirGenPropertyAccessExpression(location, V(result), namePtr, !!propertyAccessExpression->questionDotToken, genContext); } @@ -1669,6 +1682,13 @@ namespace mlirgen return mlirGenAnyKey(location, objectValue, noKey, ANY_KEYS_OP_KEYS, genContext); } + // a dictionary's keys, in the order its entries were added + if (method == "keys" && dictionaryClassInfoOf(objectValue.getType(), genContext)) + { + SmallVector noOperands; + return mlirGenDictionaryCall(location, objectValue, "keys", noOperands, genContext); + } + SmallVector keys; if (!forInFieldKeys(objectValue.getType(), keys)) { @@ -2842,6 +2862,11 @@ namespace mlirgen auto location = loc(deleteExpression); + if (auto deleted = mlirGenDictionaryDelete(location, deleteExpression->expression, genContext)) + { + return *deleted; + } + auto result = mlirGen(deleteExpression->expression, genContext); EXIT_IF_FAILED_OR_NO_VALUE(result) auto expr = V(result); @@ -3558,6 +3583,12 @@ namespace mlirgen } } + // `{ [m]: i }` with a key known only at run time: a dictionary + if (auto dictionary = mlirGenObjectLiteralAsDictionary(location, objectLiteral, genContext)) + { + return *dictionary; + } + ObjectLiteralInfo oli{}; oli.objectLiteral = objectLiteral; diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 8a57eb5fb..ead83f7c4 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -7538,6 +7538,14 @@ class MLIRGenImpl EXIT_IF_FAILED_OR_NO_VALUE(resultRight) auto rightExpressionValue = V(resultRight); + // `k in d` of a dictionary: whether it holds an entry k + if (dictionaryClassInfoOf(rightExpressionValue.getType(), genContext)) + { + CAST_A(key, location, getStringType(), leftExpressionValue, genContext); + SmallVector operands{key}; + return mlirGenDictionaryCall(location, rightExpressionValue, "has", operands, genContext); + } + // `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())) { @@ -18390,6 +18398,28 @@ class MLIRGenImpl std::optional mlirGenObjectLiteralAsClassInstance(mlir::Location location, ObjectLiteralInfo &oli, const GenContext &genContext); + // a string index signature's value (OBJECT_DICTIONARY_CLASS_NAME): see MLIRGenAccessCall.cpp + ClassInfo::TypePtr dictionaryClassInfoOf(mlir::Type type, const GenContext &genContext); + mlir::Type getObjectDictionaryType(mlir::Location location, mlir::Type valueType, const GenContext &genContext); + mlir::Type instantiatedDictionaryType(mlir::Location location, mlir::Type type, const GenContext &genContext); + // the constant key of a computed property name an object literal's check for a dictionary made already + // (mlirGenObjectLiteralAsDictionary): read again, an imported `const` declared its accessor twice + llvm::DenseMap computedNameConstants; + std::optional mlirGenDictionaryEntry(mlir::Location location, mlir::Value objectValue, + mlir::Value key, bool isConditional, const GenContext &genContext); + std::optional mlirGenDictionaryEntry(mlir::Location location, mlir::Value objectValue, + StringRef name, bool isConditional, const GenContext &genContext); + mlir::LogicalResult mlirGenDictionarySet(mlir::Location location, mlir::Value dictionary, mlir::Value key, + mlir::Value value, const GenContext &genContext); + ValueOrLogicalResult mlirGenDictionaryCall(mlir::Location location, mlir::Value dictionary, StringRef method, + SmallVector &operands, const GenContext &genContext); + std::optional mlirGenDictionaryDelete(mlir::Location location, Expression operand, + const GenContext &genContext); + ValueOrLogicalResult castTupleToDictionary(mlir::Location location, mlir::Value value, mlir_ts::TupleType srcTupleType, + mlir_ts::ClassType classType, const GenContext &genContext); + std::optional mlirGenObjectLiteralAsDictionary(mlir::Location location, + ObjectLiteralExpression objectLiteral, const GenContext &genContext); + ValueOrLogicalResult castTupleToClass(mlir::Location location, mlir::Value value, mlir_ts::TupleType srcTupleType, ArrayRef fields, mlir_ts::ClassType classType, const GenContext &genContext, bool errorAsWarning = false); diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 57266b500..437203cfb 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -1643,19 +1643,31 @@ namespace mlirgen // An `any` holds a value whose keys are known only at run time: its keys adapter lists them // (ANY_KEYS_OP_KEYS), and the loop is `for (key of ) body`. The keys are read once, before the // first turn, as JavaScript reads them; the body reads `x[key]` through the adapter too. - if (iteratedType && (isa(iteratedType) || isa(iteratedType))) + // A dictionary's keys are its entries', listed by it (`keys`), in the order they were added. + auto dictionary = iteratedType && dictionaryClassInfoOf(iteratedType, genContext); + if (iteratedType && (isa(iteratedType) || isa(iteratedType) || dictionary)) { auto iteratedLocation = loc(forInStatementAST->expression); auto iterated = mlirGen(forInStatementAST->expression, genContext); EXIT_IF_FAILED_OR_NO_VALUE(iterated) auto iteratedValue = V(iterated); - if (!isa(iteratedValue.getType())) + ValueOrLogicalResult keys(mlir::failure()); + if (dictionary) { - CAST(iteratedValue, iteratedLocation, getAnyType(), iteratedValue, genContext); + SmallVector noOperands; + keys = mlirGenDictionaryCall(iteratedLocation, iteratedValue, "keys", noOperands, genContext); + } + else + { + if (!isa(iteratedValue.getType())) + { + CAST(iteratedValue, iteratedLocation, getAnyType(), iteratedValue, genContext); + } + + auto noKey = builder.create(iteratedLocation, getUndefinedType()); + keys = mlirGenAnyKey(iteratedLocation, iteratedValue, noKey, ANY_KEYS_OP_KEYS, genContext); } - auto noKey = builder.create(iteratedLocation, getUndefinedType()); - auto keys = mlirGenAnyKey(iteratedLocation, iteratedValue, noKey, ANY_KEYS_OP_KEYS, genContext); EXIT_IF_FAILED_OR_NO_VALUE(keys) auto keysName = StringRef(".for_in_keys"); diff --git a/tslang/lib/TypeScript/MLIRGenTypes.cpp b/tslang/lib/TypeScript/MLIRGenTypes.cpp index d4b8ade0a..378a7f848 100644 --- a/tslang/lib/TypeScript/MLIRGenTypes.cpp +++ b/tslang/lib/TypeScript/MLIRGenTypes.cpp @@ -2780,6 +2780,11 @@ namespace mlirgen return {builder.getStringAttr(wellKnown), mlir::success()}; } + if (auto known = computedNameConstants.lookup(name.as().operator->())) + { + return {known, mlir::success()}; + } + MLIRCodeLogic mcl(builder, compileOptions); auto result = mlirGen(name.as(), genContext); if (result.failed_or_no_value()) @@ -3168,6 +3173,25 @@ namespace mlirgen return mlir::Type(); } + // `{ [key: string]: T }`, a string index signature and nothing else: a dictionary of T, its entries + // known at run time (ObjectDictionary in the default library). Without the library, the old + // get/set record. + if (typeLiteral->members.size() == 1 && typeLiteral->members.front() == SyntaxKind::IndexSignature && + types.size() == 2) + { + // the get function, (this, key) => value; `{ []; }` and `{ [k: any]; }` have no key or no value type + auto getType = dyn_cast_or_null(types.front().type); + auto keyType = getType && getType.getNumInputs() == 2 ? getType.getInput(1) : mlir::Type(); + auto valueType = getType && getType.getNumResults() == 1 ? getType.getResult(0) : mlir::Type(); + if (keyType && isa(keyType) && valueType) + { + if (auto dictionaryType = getObjectDictionaryType(loc(typeLiteral), valueType, genContext)) + { + return dictionaryType; + } + } + } + // `{ (n: number): string }`, one call signature and nothing else, is the function type // `(n: number) => string`, as in TypeScript: a value of it is called as that function if (types.size() == 1 && types.front().id == MLIRHelper::TupleFieldName(CALL_FIELD_NAME, builder.getContext())) diff --git a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp index 14e50d889..8956cab00 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp @@ -96,6 +96,12 @@ namespace own_inference auto *taker = takerOf(receiver.retain, receiver.value); if (receivers.size() > 1) { + // moved on paths that exclude each other (`if (f) a.push(v); else a[0] = v;`) + if (movesOnExclusivePaths(slot, receivers, isReleasedParam(slot), toErase)) + { + return; + } + auto &second = receivers[1]; auto *secondTaker = takerOf(second.retain, second.value); reportUseAfterMove(secondTaker ? secondTaker : second.retain, taker ? taker : receiver.retain, name); @@ -141,6 +147,133 @@ namespace own_inference } } + // A parameter the body releases on the paths that do not move it (released): each move empties + // its slot after its taker, so the releases at the exits free nothing on the paths that moved + // it. One the function keeps on every path: each exit is reached only through one of the moves. + // No read of the slot may follow a move, and no move may meet itself again around a loop. + bool OwnershipInferencePass::movesOnExclusivePaths(mlir::Value slot, llvm::ArrayRef receivers, bool released, + llvm::SetVector &toErase) + { + auto assignments = slotAssignments(slot); + llvm::SmallVector kills(assignments.begin(), assignments.end()); + if (auto varOp = slot.getDefiningOp()) + { + kills.push_back(varOp); + } + + // the taker of a retain: what takerOf says, or - for a read unwrapped once (`value` of + // `T | undefined`, narrowed) and moved on each path - the next op that uses what was retained + auto takerAfter = [&](const SlotReceiver &receiver) -> mlir::Operation * { + if (auto *taker = takerOf(receiver.retain, receiver.value)) + { + return taker; + } + + if (!mlir::isa(receiver.retain)) + { + return nullptr; + } + + auto retained = receiver.retain->getOperand(0); + for (auto *op = receiver.retain->getNextNode(); op; op = op->getNextNode()) + { + if (!mlir::isa(op) && llvm::is_contained(op->getOperands(), retained)) + { + return op; + } + } + + return nullptr; + }; + + // what the read returned reaches only the retains and the takers, unwrapped on the way + std::function onlyMoved = [&](mlir::Value value) { + return llvm::all_of(value.getUsers(), [&](mlir::Operation *user) { + if (mlir::isa(user)) + { + return true; + } + + if (mlir::isa(user)) + { + return onlyMoved(user->getResult(0)); + } + + return llvm::any_of(receivers, [&](const SlotReceiver &other) { + return user == other.retain || user == takerAfter(other); + }); + }); + }; + + llvm::SmallVector takers; + for (auto &receiver : receivers) + { + auto *taker = takerAfter(receiver); + auto load = receiver.load; + if (!taker || !orderedInBody(load, taker) || reachableAfter(taker, load, kills)) + { + return false; + } + + if (!onlyMoved(receiver.value)) + { + return false; + } + + for (auto *use : slot.getUsers()) + { + if (!mlir::isa(use) && use != load.getOperation() && + reachableAfter(taker, use, kills)) + { + return false; + } + } + + takers.push_back(taker); + } + + // the moves exclude each other: none is reached from another + for (auto *from : takers) + { + for (auto *to : takers) + { + if (from != to && reachableAfter(from, to, kills)) + { + return false; + } + } + } + + if (!released) + { + auto *definition = slot.getDefiningOp(); + auto everyPath = definition != nullptr; + getFunction().walk([&](mlir_ts::ReturnInternalOp returnOp) { + everyPath = everyPath && !reachableAfter(definition, returnOp, takers); + }); + if (!everyPath) + { + return false; + } + } + + for (auto [receiver, taker] : llvm::zip(receivers, takers)) + { + if (released) + { + slotClears.push_back({slot, taker}); + } + + markBoundMethodsTaking(taker, receiver.value); + if (!isCall(receiver.retain)) + { + toErase.insert(receiver.retain); + } + } + + return true; + } + bool OwnershipInferencePass::isReadOutOfException(mlir::Value value) { auto loadOp = rootOf(value).getDefiningOp(); diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index cd7878016..d5f28cb97 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -506,6 +506,8 @@ class OwnershipInferencePass // function has no release for it, so exactly one taker must move it on, on every way out of // the function, and nothing may read it after that. void decideParam(mlir::Value slot, llvm::ArrayRef receivers, llvm::SetVector &toErase); + bool movesOnExclusivePaths(mlir::Value slot, llvm::ArrayRef receivers, bool released, + llvm::SetVector &toErase); // The thrown value, read out of the exception object by a catch's copy thunk (`.eh.copy.*`, // which the C++ runtime calls to copy the exception into the catch). rc retains it for the diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index e29bb299a..93aaf7c5a 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -464,6 +464,8 @@ tslang_add_test(NAME test-compile-00-this-void-param COMMAND test-runner "${PROJ tslang_add_test(NAME test-compile-00-global-this-members COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00global_this_members.ts") tslang_add_test(NAME test-compile-00-interface-numeric-return COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_numeric_return.ts") tslang_add_test(NAME test-compile-00-interface-method-adapters COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_method_adapters.ts") +tslang_add_test(NAME test-compile-00-own-param-exclusive-moves COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_param_exclusive_moves.ts") +tslang_add_test(NAME test-compile-00-object-dictionary COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_dictionary.ts") tslang_add_test(NAME test-compile-00-constructor-type-value COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00constructor_type_value.ts") tslang_add_test(NAME test-compile-00-string-concat-chain COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00string_concat_chain.ts") tslang_add_test(NAME test-compile-00-arrays COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00array.ts") @@ -1286,6 +1288,12 @@ tslang_add_test(NAME test-jit-own-00-interface-numeric-return COMMAND test-runne tslang_add_test(NAME test-jit-00-interface-method-adapters COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_method_adapters.ts") tslang_add_test(NAME test-jit-rc-00-interface-method-adapters COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_method_adapters.ts") tslang_add_test(NAME test-jit-own-00-interface-method-adapters COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_method_adapters.ts") +tslang_add_test(NAME test-jit-00-own-param-exclusive-moves COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_param_exclusive_moves.ts") +tslang_add_test(NAME test-jit-rc-00-own-param-exclusive-moves COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_param_exclusive_moves.ts") +tslang_add_test(NAME test-jit-own-00-own-param-exclusive-moves COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_param_exclusive_moves.ts") +tslang_add_test(NAME test-jit-00-object-dictionary COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_dictionary.ts") +tslang_add_test(NAME test-jit-rc-00-object-dictionary COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_dictionary.ts") +tslang_add_test(NAME test-jit-own-00-object-dictionary COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00object_dictionary.ts") tslang_add_test(NAME test-jit-00-constructor-type-value COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00constructor_type_value.ts") tslang_add_test(NAME test-jit-rc-00-constructor-type-value COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00constructor_type_value.ts") tslang_add_test(NAME test-jit-own-00-constructor-type-value COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00constructor_type_value.ts") @@ -6812,6 +6820,10 @@ set(import_specialization_dir "${PROJECT_SOURCE_DIR}/test/tester/import-speciali # can't be found"). On Linux the name had an `@` (`@Tree`), which ld reads as a symbol version. tslang_add_import_tests(import-specialization "${import_specialization_dir}" import_specialization box_module) +# A Map in a module importing another: the keys adapter made while the import was read as declarations was +# a public declaration, and the module failed to verify. +tslang_add_import_tests(import-map "${PROJECT_SOURCE_DIR}/test/tester/import-map" import_map map_module) + # The same for a shared library: imported directly and through a source module - see # shared-import-reimport.cmake. if (WIN32) diff --git a/tslang/test/tester/import-map/import_map.ts b/tslang/test/tester/import-map/import_map.ts new file mode 100644 index 000000000..1539a604f --- /dev/null +++ b/tslang/test/tester/import-map/import_map.ts @@ -0,0 +1,94 @@ +// A dictionary in a module importing another, keyed by imported values, beside a generic class whose code +// boxes an object into `any`. (With the default library, `import` plus `new Map` failed: the keys adapter of +// the RangeError Map throws was made while the imported file was read as declarations - a declaration, +// made public - "'ts.Func' op symbol declaration cannot have public visibility". The tester compiles without +// the library, and this file does not reach that path without it.) +import { prefix, count } from "./map_module"; + +class Failure { + constructor(public message: string) {} +} + +class Store { + private values: V[] = []; + + put(value: V) { + if (this.values.length > 100) { + throw new Failure("full"); + } + + this.values.push(value); + } + + get length() { + return this.values.length; + } +} + +@dictionary +class ObjectDictionary { + private _keys: string[] = []; + private _values: T[] = []; + + private find(key: string): int { + for (let i = 0; i < this._keys.length; i++) { + if (this._keys[i] == key) { + return i; + } + } + + return -1; + } + + get(key: string): T | undefined { + const i = this.find(key); + if (i < 0) { + return undefined; + } + + return this._values[i]; + } + + set(key: string, value: T | undefined) { + if (value === undefined) { + return; + } + + const i = this.find(key); + if (i < 0) { + this._keys.push("" + key); + this._values.push(value); + return; + } + + this._values[i] = value; + } + + [key: string]: T | undefined; + + keys(): string[] { + const r: string[] = []; + for (let i = 0; i < this._keys.length; i++) { + r.push("" + this._keys[i]); + } + + return r; + } +} + +function main() { + const s = new Store(); + s.put(true); + assert(s.length == 1); + + const d: { [key: string]: number } = {}; + for (let i = 0; i < count; i++) { + d[prefix + i] = i; + } + + const e = { [prefix]: count }; + assert(d["k2"] == 2); + assert(e["k"] == 3); + assert(Object.keys(d).length == 3); + print("done."); +} diff --git a/tslang/test/tester/import-map/map_module.ts b/tslang/test/tester/import-map/map_module.ts new file mode 100644 index 000000000..a78249ee3 --- /dev/null +++ b/tslang/test/tester/import-map/map_module.ts @@ -0,0 +1,2 @@ +export const prefix = "k"; +export const count = 3; diff --git a/tslang/test/tester/tests/00object_dictionary.ts b/tslang/test/tester/tests/00object_dictionary.ts new file mode 100644 index 000000000..5f3efc9f5 --- /dev/null +++ b/tslang/test/tester/tests/00object_dictionary.ts @@ -0,0 +1,147 @@ +// A string index signature, `{ [key: string]: T }`, is a dictionary: the default library's ObjectDictionary, +// whose entries are known at run time. `d[k]`, `d["name"]` and `d.name` are its entries - never its members, so +// `d.get` and `d.size` are entries too - read as `T | undefined` (undefined for a key it does not hold) and +// written as T. An object literal with a key known only at run time (`{ [m]: i }`) makes one, and so does one +// given where a dictionary is wanted. `k in d`, `for...in`, `Object.keys` and `delete d[k]` go by its entries. +// Under -mm=own it owns its values: written in moves, read borrows, overwritten or deleted drops. +// The tests compile without the default library: its ObjectDictionary (and objectDictionaryAssign), as the +// compiler finds them by name, over two arrays. +@dictionary +class ObjectDictionary { + private _keys: string[] = []; + private _values: T[] = []; + + get size() { + return this._keys.length; + } + + private find(key: string): int { + for (let i = 0; i < this._keys.length; i++) { + if (this._keys[i] == key) { + return i; + } + } + + return -1; + } + + get(key: string): T | undefined { + const i = this.find(key); + if (i < 0) { + return undefined; + } + + return this._values[i]; + } + + set(key: string, value: T | undefined) { + if (value === undefined) { + this.delete(key); + return; + } + + const i = this.find(key); + if (i < 0) { + this._keys.push("" + key); + this._values.push(value); + return; + } + + this._values[i] = value; + } + + [key: string]: T | undefined; + + has(key: string): boolean { + return this.find(key) >= 0; + } + + delete(key: string): boolean { + const i = this.find(key); + if (i < 0) { + return false; + } + + this._keys.splice(i, 1); + this._values.splice(i, 1); + return true; + } + + keys(): string[] { + const r: string[] = []; + for (let i = 0; i < this._keys.length; i++) { + r.push("" + this._keys[i]); + } + + return r; + } +} + +function objectDictionaryAssign(target: ObjectDictionary, source: ObjectDictionary) { + for (const k in source) { + target[k] = source[k]; + } +} + +class P { + constructor(public n: string) {} +} + +function make(m: string, i: number) { + return { [m]: i, b: 2 }; +} + +function sum(d: { [key: string]: number }) { + let total: number = 0; + for (const k in d) { + total += d[k] ?? 0; + } + + return total; +} + +function main() { + const d: { [key: string]: number } = { a: 1, get: 5 }; + const k = "x" + 1; + d[k] = 2; + d.size = 9; + assert(d["a"] == 1); + assert(d[k] == 2); + assert(d.get == 5); + assert(d.size == 9); + assert(d["zz"] === undefined); + assert("a" in d); + assert(!("zz" in d)); + assert(sum(d) == 17); + + delete d["get"]; + delete d.size; + assert(!("get" in d)); + const keys = Object.keys(d); + assert(keys.length == 2 && keys[0] == "a" && keys[1] == "x1"); + + const e = make("m" + 1, 7); + assert(e["m1"] == 7); + assert(e.b == 2); + + const o: { [key: string]: P } = {}; + for (let i = 0; i < 100; i++) { + const key = "p" + (i % 10); + o[key] = new P("v" + i); + if (i % 3 == 0) { + o[key] = new P("w" + i); + } + + if (i % 7 == 0) { + delete o["p" + (i % 4)]; + } + } + + const p = o["p9"]; + assert(p !== undefined && p.n == "w99"); + // the last delete, at i = 98, is of p2 + assert(Object.keys(o).length == 9); + assert(!("p2" in o)); + + print("done."); +} diff --git a/tslang/test/tester/tests/00own_param_exclusive_moves.ts b/tslang/test/tester/tests/00own_param_exclusive_moves.ts new file mode 100644 index 000000000..2e641786e --- /dev/null +++ b/tslang/test/tester/tests/00own_param_exclusive_moves.ts @@ -0,0 +1,64 @@ +// A parameter moved on paths that exclude each other - `if (f) a.push(v); else a[0] = v;`, a move followed by +// `return` and another after it, a `T | undefined` narrowed once and moved on two paths - was "'v' is used here +// after its value was moved" under -mm=own: only one move of a parameter was allowed. Each move now empties the +// parameter, so the release at the exit, kept for a path that moves nothing, frees nothing on the others. +class P { + constructor(public n: string) {} +} + +function put(a: P[], f: number, v: P) { + if (f == 0) { + a.push(v); + } else if (f == 1) { + a[0] = v; + } else { + assert(v.n.length > 0); + } +} + +function keep(a: P[], first: boolean, v: P) { + if (first) { + a[0] = v; + return; + } + + a[1] = v; +} + +function store(a: P[], v: P | undefined) { + if (v === undefined) { + return; + } + + if (a.length == 0) { + a.push(v); + return; + } + + a[0] = v; +} + +function main() { + const a: P[] = []; + put(a, 0, new P("a")); + put(a, 0, new P("b")); + for (let i = 0; i < 1000; i++) { + put(a, i % 3, new P("x" + (i % 10))); + keep(a, i % 2 == 0, new P("y" + (i % 7))); + if (a.length > 4) { + a.length = 2; + } + } + + assert(a.length == 3); + assert(a[0].n == "y4"); + assert(a[1].n == "y5"); + + const b: P[] = []; + store(b, undefined); + store(b, new P("s1")); + store(b, new P("s2")); + assert(b.length == 1 && b[0].n == "s2"); + + print("done."); +}