From 9e5cd131ff7a0dcbea1ba763bf2a5df79a327bba Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 8 Nov 2026 20:49:49 +0000 Subject: [PATCH] @cdecl C callbacks (TSLANG 29); a generic sees no local of its caller (TSLANG 30) 29: a function-typed parameter of a declared function was a TypeScript function value ({ ptr, ptr, ptr }), so a C function taking a callback got every argument after it shifted. A function declared @cdecl takes each function-typed parameter as a C function pointer; a closure or bound method passed to it is a compile error. 30: a generic body is compiled where it is first instantiated, and a name in it resolved to a local of the instantiating function (`const total = 5` in main hid the module's total() from Bag.sum()). A generic declared outside every function now sees only its own locals and those of functions generated within it. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++ TSLANG_ISSUES.md | 17 +++- docs/c-cpp-header-import.md | 2 +- tslang/include/TypeScript/Defines.h | 4 + .../TypeScript/MLIRLogic/MLIRGenStore.h | 7 ++ tslang/lib/TypeScript/MLIRGenClasses.cpp | 2 + tslang/lib/TypeScript/MLIRGenFunctions.cpp | 31 ++++++- tslang/lib/TypeScript/MLIRGenGenerics.cpp | 21 +++++ tslang/lib/TypeScript/MLIRGenImpl.h | 40 +++++++++ tslang/lib/TypeScript/MLIRGenVariables.cpp | 25 +++++- tslang/test/tester/CMakeLists.txt | 23 +++++ tslang/test/tester/tests/00tslang_issue_29.ts | 21 +++++ .../tester/tests/00tslang_issue_29_pthread.ts | 21 +++++ .../tester/tests/00tslang_issue_29_thread.ts | 22 +++++ tslang/test/tester/tests/00tslang_issue_30.ts | 89 +++++++++++++++++++ .../test/tester/tests/cdecl_closure_error.ts | 10 +++ tslang/test/tester/verify-ownership.cmake | 4 +- 17 files changed, 340 insertions(+), 5 deletions(-) create mode 100644 tslang/test/tester/tests/00tslang_issue_29.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_29_pthread.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_29_thread.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_30.ts create mode 100644 tslang/test/tester/tests/cdecl_closure_error.ts diff --git a/README.md b/README.md index 5f675cd8b..e8254547f 100644 --- a/README.md +++ b/README.md @@ -597,6 +597,12 @@ declare function dist(p: Reference | null): f64; A pointer parameter or struct field is nullable (`| null`), as C lets it be null; a C++ reference (`const Point &`) and a result aren't. +A C function taking a callback is declared `@cdecl`: its function-typed parameters are then C function pointers, given a function or an arrow that captures nothing (a closure or a bound method is a compile error): + +```typescript +@cdecl declare function qsort(base: Opaque, count: u64, size: u64, compare: (a: Opaque, b: Opaque) => s32): void; +``` + A struct is a named tuple with its fields where C puts them; tslang lays a nested tuple out in place, as C does a struct member: - **an array** `T x[N]` is a tuple of its elements, `x: [_0: T, _1: T, ...]` (tslang has no fixed-size array type; one of more than 1024 elements, or of unknown size, is skipped); diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index ed2fa0dea..6bdae4328 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -5,7 +5,7 @@ should be a complete file that was run (`tslang file.ts`, JIT, Windows x64), wit ## Open -Items 1-28 (collected 2026-10-12 to pre-alpha118) are fixed or answered; their write-ups are in this +Items 1-30 (collected 2026-10-12 to pre-alpha119) are fixed or answered; their write-ups are in this file's git history. 24-26 were fixed by #775 (regression tests `tslang/test/tester/tests/00tslang_issues_24_26.ts` and `ref_element_layout_error.ts`): 24 (an array literal holding `const X = 1 << n` widened to 64-bit elements: shifts and bitwise operators now give an @@ -20,3 +20,18 @@ Regression test `tslang/test/tester/tests/00tslang_issue_27.ts`. 28 (a `readonly` constructor parameter without `public`, `private` or `protected` made no parameter property, so `t.width` didn't resolve): `readonly` alone now makes a public one, as in TypeScript. Regression test `tslang/test/tester/tests/00tslang_issue_28.ts`. +29 (a function-typed parameter of a `declare function` was a TypeScript function value, `{ ptr, ptr, ptr }`, +so `_beginthreadex(..., entry, arg, ...)` shifted `arg` and every argument after the callback): a +function declared `@cdecl` takes each function-typed parameter as a C function pointer. A function or +an arrow that captures nothing passes; a capturing arrow or a bound method passed straight to it is a +compile error ("a closure or a bound method can't be used as a plain function pointer"). Not checked +yet: a closure already stored in a variable of function type, passed on to a `@cdecl` parameter, still +loses its captures at run time. Regression tests `tslang/test/tester/tests/00tslang_issue_29.ts`, +`00tslang_issue_29_thread.ts` (Windows), `00tslang_issue_29_pthread.ts` (Linux) and +`cdecl_closure_error.ts`. +30 (a generic's body, compiled where it is first instantiated, resolved a name to a local of the +instantiating function: `const total = 5` in `main` hid the module's `total()` from `Bag.sum()`, and +a local `values` broke the default library's `Array`): a generic declared outside every function +now sees no local of another function; one declared in a function still reads that function's locals, +and lambdas in a generic still capture the generic's own. Regression test +`tslang/test/tester/tests/00tslang_issue_30.ts`. diff --git a/docs/c-cpp-header-import.md b/docs/c-cpp-header-import.md index 8e6cfde76..d28f8707f 100644 --- a/docs/c-cpp-header-import.md +++ b/docs/c-cpp-header-import.md @@ -76,7 +76,7 @@ compiler): | `enum E { A = 1 }` | `enum E { A = 1 }` | Underlying width from clang. | | `#define NAME 42` (object-like macro, literal) | `const NAME = 42` | Via clang's preprocessing record; only literal/`constexpr`-foldable macros; skip function-like macros (report them in a comment). | | `typedef` | `type` alias | | -| Function pointers | function type `(a: T) => R` | Already representable; C callbacks into tslang functions work if the closure has no captured environment (thick-vs-thin function pointer distinction must be checked per site). | +| Function pointers | function type `(a: T) => R` on a `@cdecl declare function` | `@cdecl` makes each function-typed parameter a C function pointer. A function or an arrow capturing nothing passes; a capturing arrow or bound method is a compile error. Without `@cdecl` the parameter is a TypeScript function value (three pointers), which C can't call. | | `...` varargs | `...args` + `func.varargs` | Already supported. | | Bitfields | not representable | Emit the containing struct as opaque + generated accessor functions (phase 2), or skip with a diagnostic. | diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 8bd2e9b9c..7fbfc0229 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -337,6 +337,10 @@ // declaration can give it: never on one that may run TypeScript code (it takes a callback) or // one re-parsed from a TypeScript library, whose functions may destroy what they are given. #define NO_DROPS_DECORATOR "nodrops" +// `@cdecl declare function f(cb: (x: T) => R)`: f is a C function, so a parameter of a function type is +// a C function pointer - one code pointer, not the code-and-context a TypeScript function value is. +// Only a function that captures nothing can be passed there (TSLANG_ISSUES 29). +#define CDECL_DECORATOR "cdecl" // The memory model a module is compiled for, a string literal: `if (__MEMORY_MODEL__ === "gc")` // generates the branch taken only (MLIRGenImpl::foldLiteralCompare) #define MEMORY_MODEL_IDENTIFIER "__MEMORY_MODEL__" diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index 10303a971..00e608cb2 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -47,6 +47,10 @@ struct GenericFunctionInfo bool processing; bool processed; + // declared inside a function, whose locals its body may read; otherwise an instantiation sees no + // local of the function it is instantiated from (MLIRGenImpl::isolateGeneratedBodies) + bool declaredInFunction = false; + GenericFunctionInfo() = default; }; @@ -1301,6 +1305,9 @@ struct GenericClassInfo SourceFile sourceFile; StringRef fileName; + // see GenericFunctionInfo::declaredInFunction + bool declaredInFunction = false; + GenericClassInfo() { } diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index d2dc44104..d4e3cc20a 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -44,6 +44,8 @@ namespace mlirgen newGenericClassPtr->elementNamespace = currentNamespace; newGenericClassPtr->sourceFile = sourceFile; newGenericClassPtr->fileName = mainSourceFileName; + newGenericClassPtr->declaredInFunction = + (genContext.funcOp && genContext.funcOp != genContext.rootStatementsFuncOp) || !lexicalFuncOps.empty(); mlirGenClassType(newGenericClassPtr, genContext); diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index ced1513f0..c5859fcc3 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -254,9 +254,19 @@ namespace mlirgen if (typeParameter) { type = getType(typeParameter, genContext); + + // a C function's callback is a bare code pointer (CDECL_DECORATOR) + if (auto hybridFuncType = dyn_cast_or_null(type)) + { + if (MLIRHelper::hasDecorator(parametersContextAST, CDECL_DECORATOR)) + { + type = mlir_ts::FunctionType::get(builder.getContext(), hybridFuncType.getInputs(), + hybridFuncType.getResults(), hybridFuncType.isVarArg()); + } + } } - // special case, setup 'this' and type provided + // special case, setup 'this' and type provided if (namePtr == THIS_NAME && type) { // NOTE: upward mailbox: explicit this-parameter type must reach the prototype chain - see GenContext @@ -1928,6 +1938,25 @@ namespace mlirgen loopLabelAliases = std::move(outerLoopLabelAliases); }); + // nor are the locals of the function a generic is instantiated from this body's: it starts a new + // lexical root, and a function generated within it joins it (isolateGeneratedBodies) + auto outerLexicalFuncOps = lexicalFuncOps; + auto outerIsolateGeneratedBodies = isolateGeneratedBodies; + if (isolateGeneratedBodies) + { + lexicalFuncOps.clear(); + lexicalFuncOps.push_back(funcOp); + isolateGeneratedBodies = false; + } + else if (!lexicalFuncOps.empty()) + { + lexicalFuncOps.push_back(funcOp); + } + auto restoreLexicalRoot = llvm::make_scope_exit([&]() { + lexicalFuncOps = std::move(outerLexicalFuncOps); + isolateGeneratedBodies = outerIsolateGeneratedBodies; + }); + // nor is a @value type a body needs one the field being typed around it waits for (an // initializer's return type inferred from this body) auto outerValueLayoutFrames = std::move(valueLayoutFrames); diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index 0f4c25f73..0f2ee908b 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -559,6 +559,9 @@ namespace mlirgen currentNamespace = functionGenericTypeInfo->elementNamespace; SourceFileScope sourceFileScope(*this, functionGenericTypeInfo->sourceFile, functionGenericTypeInfo->fileName); + // the generic sees the locals of no function it is not declared in (TSLANG_ISSUES 30) + MLIRValueGuard isolateGuard(isolateGeneratedBodies); + isolateGeneratedBodies = !functionGenericTypeInfo->declaredInFunction; return instantiateSpecializedFunctionTypeHelper(location, functionGenericTypeInfo->functionDeclaration, recieverType, discoverReturnType, genContext, capturesFirst); @@ -666,6 +669,9 @@ namespace mlirgen currentNamespace = functionGenericTypeInfo->elementNamespace; SourceFileScope sourceFileScope(*this, functionGenericTypeInfo->sourceFile, functionGenericTypeInfo->fileName); + // the generic sees the locals of no function it is not declared in (TSLANG_ISSUES 30) + MLIRValueGuard isolateGuard(isolateGeneratedBodies); + isolateGeneratedBodies = !functionGenericTypeInfo->declaredInFunction; auto [result, specFuncOp, specFuncName, isGeneric] = mlirGenFunctionLikeDeclaration(functionGenericTypeInfo->functionDeclaration, funcGenContext); @@ -1037,6 +1043,9 @@ namespace mlirgen currentNamespace = functionGenericTypeInfo->elementNamespace; SourceFileScope sourceFileScope(*this, functionGenericTypeInfo->sourceFile, functionGenericTypeInfo->fileName); + // the generic sees the locals of no function it is not declared in (TSLANG_ISSUES 30) + MLIRValueGuard isolateGuard(isolateGeneratedBodies); + isolateGeneratedBodies = !functionGenericTypeInfo->declaredInFunction; GenContext genericTypeGenContext(genContext); genericTypeGenContext.specialization = true; @@ -1098,6 +1107,9 @@ namespace mlirgen currentNamespace = functionGenericTypeInfo->elementNamespace; SourceFileScope sourceFileScope(*this, functionGenericTypeInfo->sourceFile, functionGenericTypeInfo->fileName); + // the generic sees the locals of no function it is not declared in (TSLANG_ISSUES 30) + MLIRValueGuard isolateGuard(isolateGeneratedBodies); + isolateGeneratedBodies = !functionGenericTypeInfo->declaredInFunction; auto anyNamedGenericType = IsGeneric::False; @@ -1405,6 +1417,9 @@ namespace mlirgen currentNamespace = genericClassInfo->elementNamespace; SourceFileScope sourceFileScope(*this, genericClassInfo->sourceFile, genericClassInfo->fileName); + // the generic sees the locals of no function it is not declared in (TSLANG_ISSUES 30) + MLIRValueGuard isolateGuard(isolateGeneratedBodies); + isolateGeneratedBodies = !genericClassInfo->declaredInFunction; GenContext genericTypeGenContext(genContext); genericTypeGenContext.instantiateSpecializedFunction = false; @@ -1481,6 +1496,9 @@ namespace mlirgen currentNamespace = genericClassInfo->elementNamespace; SourceFileScope sourceFileScope(*this, genericClassInfo->sourceFile, genericClassInfo->fileName); + // the generic sees the locals of no function it is not declared in (TSLANG_ISSUES 30) + MLIRValueGuard isolateGuard(isolateGeneratedBodies); + isolateGeneratedBodies = !genericClassInfo->declaredInFunction; GenContext genericTypeGenContext(genContext); genericTypeGenContext.instantiateSpecializedFunction = false; @@ -1603,6 +1621,9 @@ namespace mlirgen currentNamespace = genericClassInfo->elementNamespace; SourceFileScope sourceFileScope(*this, genericClassInfo->sourceFile, genericClassInfo->fileName); + // the generic sees the locals of no function it is not declared in (TSLANG_ISSUES 30) + MLIRValueGuard isolateGuard(isolateGeneratedBodies); + isolateGeneratedBodies = !genericClassInfo->declaredInFunction; GenContext templateGenContext(genContext); for (auto &typeParam : genericClassInfo->typeParams) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 6e54a84b8..ccfd8de87 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3797,6 +3797,8 @@ class MLIRGenImpl newGenericFunctionPtr->thisClassType = genContext.thisClassType; newGenericFunctionPtr->sourceFile = sourceFile; newGenericFunctionPtr->fileName = mainSourceFileName; + newGenericFunctionPtr->declaredInFunction = + (genContext.funcOp && genContext.funcOp != genContext.rootStatementsFuncOp) || !lexicalFuncOps.empty(); // TODO: review it, ignore in case of ArrowFunction, if (!ignoreFunctionArgsDetection) @@ -10787,7 +10789,35 @@ class MLIRGenImpl if (value.getType() != argTypeDestFuncType) { + // A closure or a bound method is a function and the value it runs with (its captures, + // its `this`); a plain function type parameter - a C callback (@cdecl, TSLANG_ISSUES 29) + // - is only a code pointer, and the cast drops the value: the function would read its + // captures through whatever the caller passed first. An arrow with untyped parameters + // becomes a closure only as the cast instantiates it. + auto closureAsFunctionPointer = [&](mlir::Type valueType) { + if (isa(valueType) && isa(argTypeDestFuncType)) + { + emitError(location, "a closure or a bound method can't be used as a plain function pointer: " + "the pointer carries no captured variables and no 'this'"); + return true; + } + + return false; + }; + + if (closureAsFunctionPointer(value.getType())) + { + return mlir::failure(); + } + CAST_A(castValue, location, argTypeDestFuncType, value, genContext); + + if (auto castOp = castValue.getDefiningOp(); + castOp && closureAsFunctionPointer(castOp.getIn().getType())) + { + return mlir::failure(); + } + operands[i] = castValue; } @@ -17161,6 +17191,16 @@ class MLIRGenImpl // can't leave a function. SmallVector activeLabels; + // A generic is instantiated where it is first used, so the locals of the function using it are + // still in symbolTable while its body is generated; a name in the body resolved to a local of its + // caller (TSLANG_ISSUES 30). While a generic declared outside every function is instantiated, + // isolateGeneratedBodies is set, and each function body generated then (the generic function, or + // each method of the generic class) starts lexicalFuncOps over: that body, and the functions + // generated within it (its lambdas and nested generics, which redeclare what they capture), see + // no local of any other function (resolveIdentifierAsVariable). + bool isolateGeneratedBodies = false; + SmallVector lexicalFuncOps; + // The yields standing where nothing is computed before them, marked by the statement around // them (the AST has no parent links to look up): yield node -> its value is used. See // SupportedYieldScope. diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index c42e6429e..d9d16f262 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -1125,8 +1125,31 @@ namespace mlirgen { //LLVM_DEBUG(dbgs() << "\n!! resolveIdentifierAsVariable: " << name << " type: " << value.second->getType() << " value: " << value.first;); - // begin of logic: outer vars auto valueRegion = value.first.getParentRegion(); + + // a local of a function this one is not declared in - the caller a generic is instantiated + // from - is no name here: the name is the module's (lexicalFuncOps, TSLANG_ISSUES 30) + if (!lexicalFuncOps.empty() && valueRegion && valueRegion->getParentOp() && + (isa(valueRegion->getParentOp()) || valueRegion->getParentOp()->getParentOfType())) + { + auto inRoot = llvm::any_of(lexicalFuncOps, [&](mlir_ts::FuncOp lexicalFuncOp) { + return lexicalFuncOp.getCallableRegion() && lexicalFuncOp.getCallableRegion()->isAncestor(valueRegion); + }); + mlir_ts::FuncOp contextFuncOp = genContext.funcOp; + auto inFunction = contextFuncOp && contextFuncOp.getCallableRegion() && + contextFuncOp.getCallableRegion()->isAncestor(valueRegion); + // a module's top-level code is a function of its own (rootStatementsFuncOp), whose + // locals are the module's variables + mlir_ts::FuncOp rootStatementsFuncOp = genContext.rootStatementsFuncOp; + auto inModuleCode = rootStatementsFuncOp && rootStatementsFuncOp.getCallableRegion() && + rootStatementsFuncOp.getCallableRegion()->isAncestor(valueRegion); + if (!inRoot && !inFunction && !inModuleCode) + { + return mlir::Value(); + } + } + + // begin of logic: outer vars auto isOuterVar = false; // TODO: review code "valueRegion && valueRegion->getParentOp()" is to support async.execute if (genContext.funcOp && genContext.funcOp != tempFuncOp && valueRegion && diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index b54426a5a..a010eae88 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1796,6 +1796,29 @@ foreach(issues_mm gc rc none own) tslang_add_test(NAME test-jit-00-tslang-issue-28-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_28.ts") tslang_add_test(NAME test-compile-00-tslang-issue-28-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_28.ts") endforeach() +# TSLANG_ISSUES 30: a generic sees no local of the function it is instantiated from +foreach(issues_mm gc rc none own) + tslang_add_test(NAME test-jit-00-tslang-issue-30-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_30.ts") + tslang_add_test(NAME test-compile-00-tslang-issue-30-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_30.ts") +endforeach() +# TSLANG 29: a @cdecl function takes a callback as a C function pointer; a C function with arguments +# after the callback (a thread start) showed the three-pointer value it was given before +if(WIN32) + set(issue_29_thread_test "00tslang_issue_29_thread.ts") +else() + set(issue_29_thread_test "00tslang_issue_29_pthread.ts") +endif() +foreach(issues_mm gc rc none own) + tslang_add_test(NAME test-jit-00-tslang-issue-29-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29.ts") + tslang_add_test(NAME test-compile-00-tslang-issue-29-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29.ts") + tslang_add_test(NAME test-jit-00-tslang-issue-29-thread-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issue_29_thread_test}") + tslang_add_test(NAME test-compile-00-tslang-issue-29-thread-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issue_29_thread_test}") +endforeach() +# ...and a closure, which needs its captured variables, can't be one +add_test(NAME test-compile-cdecl-closure-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/cdecl_closure_error.ts") +set_tests_properties(test-compile-cdecl-closure-error PROPERTIES PASS_REGULAR_EXPRESSION "a closure or a bound method can't be used as a plain function pointer" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") # ...a reference to a number is no reference to an f32 add_test(NAME test-compile-ref-element-layout-error COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/ref_element_layout_error.ts") diff --git a/tslang/test/tester/tests/00tslang_issue_29.ts b/tslang/test/tester/tests/00tslang_issue_29.ts new file mode 100644 index 000000000..6c99a911c --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_29.ts @@ -0,0 +1,21 @@ +// TSLANG_ISSUES 29: a parameter of function type in a `declare function` was a TypeScript function +// value - three pointers (code, `this`, captures) - while C takes a callback as one code pointer, so a +// C function given a callback called garbage. A function declared @cdecl takes each callback +// parameter as a plain C function pointer: a function, or an arrow that captures nothing. + +@cdecl declare function qsort(base: Opaque, count: u64, size: u64, compare: (a: Opaque, b: Opaque) => s32): void; + +function ascending(a: Opaque, b: Opaque): s32 { + return Deref(>a) - Deref(>b); +} + +function main() { + const items: s32[] = [5, 3, 9, 1, 7]; + qsort(Ref(items[0]), 5, 4, ascending); + assert(items[0] == 1 && items[1] == 3 && items[2] == 5 && items[3] == 7 && items[4] == 9, "a function"); + + qsort(Ref(items[0]), 5, 4, (a: Opaque, b: Opaque) => (Deref(>b) - Deref(>a))); + assert(items[0] == 9 && items[1] == 7 && items[2] == 5 && items[3] == 3 && items[4] == 1, "an arrow capturing nothing"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_29_pthread.ts b/tslang/test/tester/tests/00tslang_issue_29_pthread.ts new file mode 100644 index 000000000..80d326d71 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_29_pthread.ts @@ -0,0 +1,21 @@ +// TSLANG_ISSUES 29 (POSIX): a thread started by pthread_create with a @cdecl callback runs the +// TypeScript function it was given, which sees the argument passed through to it. + +@cdecl declare function pthread_create(thread: Opaque, attributes: Opaque | null, start: (arg: Opaque) => Opaque, arg: Opaque): s32; +declare function pthread_join(thread: u64, result: Opaque | null): s32; + +let seen: s32 = 0; + +function entry(arg: Opaque): Opaque { + seen = Deref(>arg); + return arg; +} + +function main() { + const values: s32[] = [42]; + let thread: u64 = 0; + assert(pthread_create(Ref(thread), null, entry, Ref(values[0])) == 0, "pthread_create"); + assert(pthread_join(thread, null) == 0, "pthread_join"); + assert(seen == 42, "the thread ran the callback with its argument"); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_29_thread.ts b/tslang/test/tester/tests/00tslang_issue_29_thread.ts new file mode 100644 index 000000000..ea1894eb6 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_29_thread.ts @@ -0,0 +1,22 @@ +// TSLANG_ISSUES 29 (Windows): a thread started by the C runtime with a @cdecl callback runs the +// TypeScript function it was given, which sees the argument passed through to it. + +@cdecl declare function _beginthreadex(security: Opaque | null, stack: u32, start: (arg: Opaque) => u32, arg: Opaque, flags: u32, id: Opaque | null): Opaque; +declare function WaitForSingleObject(handle: Opaque, ms: u32): u32; +declare function CloseHandle(handle: Opaque): s32; + +let seen: s32 = 0; + +function entry(arg: Opaque): u32 { + seen = Deref(>arg); + return 0; +} + +function main() { + const values: s32[] = [42]; + const thread = _beginthreadex(null, 0, entry, Ref(values[0]), 0, null); + WaitForSingleObject(thread, 0xFFFFFFFF); + CloseHandle(thread); + assert(seen == 42, "the thread ran the callback with its argument"); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_30.ts b/tslang/test/tester/tests/00tslang_issue_30.ts new file mode 100644 index 000000000..dc701fa18 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_30.ts @@ -0,0 +1,89 @@ +// TSLANG_ISSUES 30: a generic is instantiated where it is first used, and a name in its body resolved +// to a local of the function using it ("not a function to call" for `total(...)` when the caller had +// `const total = 5`). A generic declared outside every function sees no local of another function; one +// declared inside a function still reads that function's locals, and a lambda in a generic still +// captures the generic's own. + +function total(items: number[]) { + let sum: number = 0; + for (const item of items) sum += item; + return sum; +} + +let scale = 10; + +class Bag { + constructor(public items: number[]) {} + + sum() { + return total(this.items); + } + + scaled() { + return total(this.items) * scale; + } + + // a lambda capturing a local of the generic's own method + adder() { + const offset = 100; + return (x: number) => x + offset; + } +} + +function sumOf(items: number[]) { + return total(items); +} + +function scaledBy(value: number) { + return value * scale; +} + +// a generic method of a plain class, and a generic arrow in a module const +class Plain { + sum(items: number[]) { + return total(items); + } +} + +const arrowSum = (items: number[]) => total(items); + +function main() { + // locals named like what the generics use + const total = 5; + const scale = 2; + const offset = -1; + + const bag = new Bag([1, 2, 3]); + assert(bag.sum() == 6, "a generic class method calls the module's function"); + assert(bag.scaled() == 60, "and reads the module's variable"); + assert(bag.adder()(1) == 101, "a lambda in a generic captures the generic's local"); + assert(sumOf([4, 5]) == 9, "a generic function calls the module's function"); + assert(scaledBy(3) == 30, "a generic function reads the module's variable"); + assert(new Plain().sum([5, 6]) == 11, "a generic method"); + assert(arrowSum([7, 8]) == 15, "a generic arrow"); + assert(new Late([1, 2]).sum() == 3, "a generic class declared after the caller"); + assert(lateSum([3, 4]) == 7, "a generic function declared after the caller"); + assert(total == 5 && scale == 2 && offset == -1, "the caller's locals are its own"); + + // a generic declared inside a function reads that function's locals + const factor = 7; + function times(value: number) { + return value * factor; + } + assert(times(3) == 21, "a local generic reads its function's local"); + + print("done."); +} + +// declared after main, which instantiates them +class Late { + constructor(public items: number[]) {} + + sum() { + return total(this.items); + } +} + +function lateSum(items: number[]) { + return total(items); +} diff --git a/tslang/test/tester/tests/cdecl_closure_error.ts b/tslang/test/tester/tests/cdecl_closure_error.ts new file mode 100644 index 000000000..14ce63bef --- /dev/null +++ b/tslang/test/tester/tests/cdecl_closure_error.ts @@ -0,0 +1,10 @@ +// TSLANG_ISSUES 29: a C callback is a code pointer alone, so a closure - which needs its captured +// variables - can't be one +@cdecl declare function qsort(base: Opaque, count: u64, size: u64, compare: (a: Opaque, b: Opaque) => s32): void; + +function main() { + const items: s32[] = [2, 1]; + let calls = 0; + qsort(Ref(items[0]), 2, 4, (a: Opaque, b: Opaque) => { calls++; return 0; }); + print("done."); +} diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index 2c1f9c8ec..a31c8786d 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -57,7 +57,9 @@ set(not_compilable_alone # an error by design (test-compile-mixin-runtime-base-error) mixin_runtime_base_error.ts # an error by design (test-compile-ref-element-layout-error) - ref_element_layout_error.ts) + ref_element_layout_error.ts + # an error by design (test-compile-cdecl-closure-error) + cdecl_closure_error.ts) file(GLOB corpus "${TESTS_DIR}/*.ts") list(SORT corpus)