From ce99baa9959d994b63a544a8c2234a16d0a0a1b4 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 3 Dec 2026 18:17:20 +0000 Subject: [PATCH] JSX: `h` is the default factory, the default library's where the program has none; no "failed statement" after an error - With no factory named (@jsx, --jsx-factory, "jsxFactory"), an element calls `h` and a fragment's tag is `Fragment` (user ruling; tsc's React.createElement / React.Fragment only when named). Where the program declares no `h` / `Fragment`, they are the default library's __jsx_h / __jsx_Fragment, asked again on every pass so a program's `h` declared after the element still wins. So `tslang file.tsx` runs, and `--jsx-factory=h` with no `h` declared too - -mm=own: the library's factory is one clear error at the element (an element keeps its children) - The "factory can't be found" error is shorter, and still names `h` when there is no library - MLIRGenModule: "failed statement" is reported only when the statement failed without an error of its own (it followed every error, saying nothing more) - Tests: jsx-options (the default `h`/`Fragment`, one error with no "failed statement"), 00jsx_default_factory uses the program's own `h`, crash-errors name `h`, and defaultlib/jsx_default_factory.tsx runs against the real default library (gc, rc; jit and exe) - docs/jsx.md: the library's `h`, components, what an element prints Co-Authored-By: Claude Opus 5.5 --- docs/jsx.md | 51 ++++++++++--- docs/whats-new.md | 1 + tslang/include/TypeScript/DataStructs.h | 4 +- tslang/lib/TypeScript/MLIRGenImpl.h | 13 +++- tslang/lib/TypeScript/MLIRGenJsx.cpp | 75 +++++++++++++------ tslang/lib/TypeScript/MLIRGenModule.cpp | 26 ++++++- tslang/test/tester/CMakeLists.txt | 30 +++++++- .../tester/defaultlib/jsx_default_factory.tsx | 48 ++++++++++++ tslang/test/tester/jsx-options.cmake | 23 +++++- .../tester/tests/00jsx_default_factory.tsx | 38 +++++----- tslang/tslang/tslang.cpp | 4 +- 11 files changed, 249 insertions(+), 64 deletions(-) create mode 100644 tslang/test/tester/defaultlib/jsx_default_factory.tsx diff --git a/docs/jsx.md b/docs/jsx.md index b0991ddb5..c95bf40c1 100644 --- a/docs/jsx.md +++ b/docs/jsx.md @@ -1,12 +1,25 @@ # JSX -A `.tsx` file can use JSX. An element is a call of a function you name, the *JSX factory*, as tsc -compiles it for `"jsx": "react"` (the classic runtime). There is no DOM and no React: the factory is -yours, and what an element produces is whatever it returns: an HTML string, a tree of your own nodes, -widgets of a native UI library. +A `.tsx` file can use JSX. An element is a call of a function, the *JSX factory*, as tsc compiles it +for `"jsx": "react"` (the classic runtime). There is no DOM and no React. With nothing named, the factory +is `h`, and the default library has one: an element is a `JsxElement` that prints as HTML. + +```tsx +function Item(props: { name: string }) { + return
  • {props.name}
  • ; +} + +function main() { + const names = ["one", "two & three"]; + print(); + // +} +``` + +Or the factory is yours, and what an element produces is whatever it returns: an HTML string, a tree of +your own nodes, widgets of a native UI library. A program's own `h` takes the place of the library's: ```tsx -/** @jsx h */ function h(tag: string, props: { id: string } | null, ...children: string[]): string { let s = ""; for (const c of children) { @@ -58,10 +71,29 @@ The factory and the fragment's tag are, first found first: | A comment at the top of the file | `/** @jsx h */` | `/** @jsxFrag Fragment */` | | The command line | `--jsx-factory=h` | `--jsx-fragment-factory=Fragment` | | `tsconfig.json`, `compilerOptions` | `"jsxFactory": "h"` | `"jsxFragmentFactory": "Fragment"` | -| Otherwise | `React.createElement` | `React.Fragment` | +| Otherwise | `h` | `Fragment` | + +tsc's default is `React.createElement` and `React.Fragment`: name them to use them. A name may be dotted +(`UI.h`). When the factory's first name is not declared where an element is, the error says so. + +`h` and `Fragment` are the program's own where it declares them (wherever in the file), else the default +library's. So `--jsx-factory=h` with no `h` declared is the library's too. + +## The default library's `h` + +An element is a `JsxElement`: its `tag`, its attributes as written (`props`, `null` when there are none) +and its `children`. `print(e)`, `String(e)` and `` `${e}` `` give it as HTML: -A name may be dotted (`UI.h`). When the factory's first name is not declared where an element is, -the error says so and lists these ways to name it. +- Text and attribute values are escaped (`&`, `<`, `>`, and `"` in a value). An attribute that is `true` is + its name alone (``); `false`, `null` and `undefined` leave it out. `className` and + `htmlFor` are written `class` and `for`. +- The children are flattened (an array, as `{items.map(...)}` gives, is its items), and `null`, + `undefined` and booleans are left out, as React does (`{shown && }`). +- `br`, `hr`, `img`, `input`, `meta`, `link` and HTML's other void elements have no end tag. +- A tag that is a function is a component, called with what its parameters take: none, the attributes, + or the attributes and the children (`function Card(props: { title: string }, children: any[])`). Its + element is the component's; anything else it returns (a string, a number) becomes a fragment of it. +- `<>...` is a fragment: its children alone, with no tag around them. `--jsx` (`"jsx"` in `tsconfig.json`) takes tsc's values: `react`, `preserve` and `react-native` are all the factory call above. `react-jsx` and `react-jsxdev`, the automatic runtime that imports @@ -70,7 +102,8 @@ all the factory call above. `react-jsx` and `react-jsxdev`, the automatic runtim ## Memory models -Under `gc`, `rc` and `none` an element is an ordinary call. A factory that takes its props as `any` and +Under `gc`, `rc` and `none` an element is an ordinary call. Under `-mm=own` the default library's `h` is +refused, an error at the element (its element keeps its children): declare a typed factory of your own. A factory that takes its props as `any` and reads their keys works there. Under `-mm=own` it does not, because own refuses the keys of an `any`. A typed factory (props of one shape, children of one type, as above) compiles under every model, `-mm=own` included; what it keeps of its arguments follows own's rules for any call. diff --git a/docs/whats-new.md b/docs/whats-new.md index 7d911aea7..b8085ac44 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,6 @@ # What's new +- **JSX** runs as it is: with no factory named, an element is a call of the default library's `h`, which makes a `JsxElement` (its tag, attributes and children) that prints and turns into a string as HTML (`print(

    a < b

    )` prints `

    a < b

    `). A tag that is a function is a component, called with the attributes and the children; `<>...` is a `Fragment`. tsc's default, `React.createElement`, is used only when named. When a statement fails with an error of its own, the "failed statement" error that followed it is no longer printed, and the error of a JSX factory that can't be found is shorter. Needs the default library of the same release - A mixed array literal is typed as tsc types it: an array of the union of its elements' types, `[1, "a"]` a `(s32 | string)[]` and `[3, { a: 4 }]` a `(s32 | { a: s32 })[]` (they were tuples), so it can grow and takes either member. It stays a tuple where the context asks for one: destructured (`const [n, s] = [1, "a"]`, `[x, y] = [y, x]`), given to a tuple parameter or a generic one inferred as a tuple, or pushed into an array of tuples. Code that indexes such a literal as a tuple (`[1, [2, 2]][1][1]`, which tsc refuses too) needs a tuple type (`const t: [number, number[]] = ...`). A union of primitives and object shapes (`number | { a: number }`) can be cast and printed: each member is told apart by its tag, and `print([3, { a: 4 }])` prints `[ 3, { a: 4 } ]` - An array literal of arrays with different element types is an array of their union: `[[...t], [3]]` is a `(number[] | s32[])[]` and `[[1, 2], ["x"]]` a `(s32[] | string[])[]` (they were tuples, `[number[], s32[]]`). An element read out of one (`a[0][1]`) is the element of the array the union holds, told apart by its element type - -mm=own accepts three shapes it refused: the rest of a string array destructured (`const [w0, ...ws] = words`), a literal with a spread in it as an element of another (`[[...xs]]`), and a getter's string used after another getter or method is called (`this.name + " " + this.sides`, `` `${this.color} area=${this.area()}` ``: the string is copied, as a `let` holding it is). -mm=rc: a getter of a member some class declares `abstract` gives back the string it returns; the abstract member's empty getter made every override's result look borrowed diff --git a/tslang/include/TypeScript/DataStructs.h b/tslang/include/TypeScript/DataStructs.h index 5ded7612b..8e42be00f 100644 --- a/tslang/include/TypeScript/DataStructs.h +++ b/tslang/include/TypeScript/DataStructs.h @@ -78,8 +78,8 @@ struct CompileOptions // --sanitize=address: the program is instrumented with AddressSanitizer and linked with its runtime // (transform.cpp, exe.cpp); Linux executables only bool sanitizeAddress = false; - // JSX (.tsx), as tsc's "jsx", "jsxFactory" and "jsxFragmentFactory": empty = the default (react; - // React.createElement; React.Fragment). A file's @jsx / @jsxFrag / @jsxRuntime comment wins (MLIRGenJsx.cpp). + // JSX (.tsx), as tsc's "jsx", "jsxFactory" and "jsxFragmentFactory": empty = the default (react; the + // default library's h; Fragment). A file's @jsx / @jsxFrag / @jsxRuntime comment wins (MLIRGenJsx.cpp). std::string jsxMode; std::string jsxFactory; std::string jsxFragmentFactory; diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 5c7baf258..bce0a7f8c 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -2071,7 +2071,8 @@ class MLIRGenImpl // JSX (.tsx): an element, a self-closing element or a fragment is a call of the JSX factory (MLIRGenJsx.cpp) ValueOrLogicalResult mlirGenJsx(Expression jsxAST, const GenContext &genContext); - Expression lowerJsx(Node jsxNode, const GenContext &genContext, bool &failed); + Expression lowerJsx(Node jsxNode, const GenContext &genContext, bool &failed, + std::vector> &libraryNames); // inferType helpers; return true when the template kind matched and inference was handled @@ -25118,7 +25119,15 @@ class MLIRGenImpl // a JSX node's call of the factory, made once: every pass (discovery, dummy runs, the real one) generates // the same nodes, and the JSX node is held beside it so that its address is not reused for another while // it is a key (made anew each time, a cache keyed by a node's address could match a freed one) - std::map> jsxLowered; + struct JsxLowered + { + Node node; + Expression call; + // the names `h` and `Fragment` it calls, with the default library's for them (`__jsx_h`): each pass + // names the program's own where it declares one, else the library's + std::vector> libraryNames; + }; + std::map jsxLowered; // of a `let v: T;` declared without a value (keyed by its node, held beside it): the reads of `v` before it is // definitely assigned (noteUnassignedLetReads), and whether a `for (v of xs)` or `for (v in o)` gives it its values diff --git a/tslang/lib/TypeScript/MLIRGenJsx.cpp b/tslang/lib/TypeScript/MLIRGenJsx.cpp index 1d9f2ed8a..7af30f2c4 100644 --- a/tslang/lib/TypeScript/MLIRGenJsx.cpp +++ b/tslang/lib/TypeScript/MLIRGenJsx.cpp @@ -4,12 +4,13 @@ // TypeScript's transformers/jsx.ts, ported from its Go port jsxtransforms/jsx.go): // //
    hi {name}
    -// => React.createElement("div", { id: "a", ...p, on: f }, "hi ", name, React.createElement(Item, { n: 1 })) +// => h("div", { id: "a", ...p, on: f }, "hi ", name, h(Item, { n: 1 })) // <>a -// => React.createElement(React.Fragment, null, "a") +// => h(Fragment, null, "a") // -// - The factory is the file's `/** @jsx h */` comment, else --jsx-factory ("jsxFactory" in tsconfig.json), -// else React.createElement; a fragment's tag likewise `@jsxFrag`, --jsx-fragment-factory, React.Fragment. +// - The factory is the file's `/** @jsx f */` comment, else --jsx-factory ("jsxFactory" in tsconfig.json), +// else the default library's `h`; a fragment's tag likewise `@jsxFrag`, --jsx-fragment-factory, `Fragment`. +// (tsc's default is React.createElement / React.Fragment.) // - A tag that is a lowercase name or has a `-` is a string ("div"), `a:b` is "a:b"; any other name or a // dotted name is the value it names (a component). // - No attributes: null. An attribute with no value is `true`; a string's entities (&) are decoded. @@ -383,41 +384,60 @@ namespace { auto key = static_cast(jsxAST.instance.get()); auto found = jsxLowered.find(key); - Expression lowered; - if (found != jsxLowered.end()) - { - lowered = found->second.second; - } - else + if (found == jsxLowered.end()) { auto failed = false; - lowered = lowerJsx(jsxAST, genContext, failed); - if (failed || !lowered) + std::vector> libraryNames; + auto call = lowerJsx(jsxAST, genContext, failed, libraryNames); + if (failed || !call) { return mlir::failure(); } - jsxLowered[key] = {jsxAST, lowered}; + found = jsxLowered.insert({key, JsxLowered{jsxAST, call, std::move(libraryNames)}}).first; + } + + auto lowered = found->second.call; + auto location = loc(jsxAST); + + // `h` and `Fragment`: the program's own where it declares them, else the default library's (user ruling: + // the library's `h` is the default factory; under its own name it would take the place of a program's `h`). + // Asked again on each pass, as a program's `h` may be declared after the element + auto usesLibrary = false; + for (auto &[identifier, libraryName] : found->second.libraryNames) + { + auto name = libraryName == S("__jsx_h") ? string(S("h")) : string(S("Fragment")); + identifier->escapedText = name; + if (!resolveIdentifier(location, wstos(name), genContext) && resolveIdentifier(location, wstos(libraryName), genContext)) + { + identifier->escapedText = libraryName; + usesLibrary = true; + } + } + + if (usesLibrary && compileOptions.memoryModel == MemoryModelOwn) + { + emitError(location) << "JSX with the default library's factory is not supported under -mm=own (an element keeps " + "its children): declare a typed factory of your own, `function h(...)`"; + return mlir::failure(); } - // the factory's first name is to be found where the element is: a clear error when it is not, as - // `React` not declared is the first thing a program written for React meets + // the factory's first name is to be found where the element is: a clear error when it is not (`React` + // named as the factory and not declared, or `h` without the default library) auto callee = lowered.as()->expression; while ((SyntaxKind)callee == SyntaxKind::PropertyAccessExpression) { callee = callee.as()->expression; } - auto location = loc(jsxAST); if ((SyntaxKind)callee == SyntaxKind::Identifier) { auto rootName = MLIRHelper::getName(callee.as()); if (!resolveIdentifier(location, rootName, genContext)) { emitError(location) << "the JSX factory '" << rootName - << "' can't be found: declare it, or name the factory with a `/** @jsx h */` comment, " - "\"jsxFactory\" in tsconfig.json or --jsx-factory (a fragment: `@jsxFrag`, " - "\"jsxFragmentFactory\", --jsx-fragment-factory)"; + << "' can't be found: declare it, or name another with `/** @jsx name */`, " + "\"jsxFactory\" or --jsx-factory"; return mlir::failure(); } } @@ -425,7 +445,8 @@ namespace return mlirGen(lowered, genContext); } - Expression MLIRGenImpl::lowerJsx(Node jsxNode, const GenContext &genContext, bool &failed) + Expression MLIRGenImpl::lowerJsx(Node jsxNode, const GenContext &genContext, bool &failed, + std::vector> &libraryNames) { NodeFactory nf(NodeFactoryFlags::None); @@ -435,7 +456,7 @@ namespace return made; }; - // the factory (`React.createElement`) and the fragment's tag (`React.Fragment`) of this file + // the factory (`h`) and the fragment's tag (`Fragment`) of this file auto mode = compileOptions.jsxMode; auto automatic = mode == "react-jsx" || mode == "react-jsxdev"; if (auto runtime = jsxPragma(sourceFile, S("jsxruntime"))) @@ -451,13 +472,15 @@ namespace return undefined; } - auto factoryName = !compileOptions.jsxFactory.empty() ? stows(compileOptions.jsxFactory) : string(S("React.createElement")); + // the default library's `h` and `Fragment` unless the file names others (user ruling: not tsc's + // React.createElement and React.Fragment, so a .tsx file runs as it is) + auto factoryName = !compileOptions.jsxFactory.empty() ? stows(compileOptions.jsxFactory) : string(S("h")); if (auto pragma = jsxPragma(sourceFile, S("jsx"))) { factoryName = *pragma; } - auto fragmentName = !compileOptions.jsxFragmentFactory.empty() ? stows(compileOptions.jsxFragmentFactory) : string(S("React.Fragment")); + auto fragmentName = !compileOptions.jsxFragmentFactory.empty() ? stows(compileOptions.jsxFragmentFactory) : string(S("Fragment")); if (auto pragma = jsxPragma(sourceFile, S("jsxfrag"))) { fragmentName = *pragma; @@ -479,6 +502,12 @@ namespace } auto identifier = at(nf.createIdentifier(part), source); + // `h` and `Fragment` alone may be the default library's (mlirGenJsx) + if (!expression && dot == string::npos && (part == S("h") || part == S("Fragment"))) + { + libraryNames.push_back({identifier.as(), part == S("h") ? string(S("__jsx_h")) : string(S("__jsx_Fragment"))}); + } + expression = expression ? at(nf.createPropertyAccessExpression(expression, identifier), source) : identifier; if (dot == string::npos) { diff --git a/tslang/lib/TypeScript/MLIRGenModule.cpp b/tslang/lib/TypeScript/MLIRGenModule.cpp index 55e3c39e2..e02310219 100644 --- a/tslang/lib/TypeScript/MLIRGenModule.cpp +++ b/tslang/lib/TypeScript/MLIRGenModule.cpp @@ -33,6 +33,19 @@ namespace typescript namespace mlirgen { + // the errors said so far: a statement that failed with one of its own needs no "failed statement" after it + static size_t errorCount(const mlir::SmallVector> *messages) + { + if (!messages) + { + return 0; + } + + return llvm::count_if(*messages, [](const std::unique_ptr &diag) { + return diag->getSeverity() == mlir::DiagnosticSeverity::Error; + }); + } + mlir::LogicalResult MLIRGenImpl::report(SourceFile module, const std::vector &includeFiles) { // output diag info @@ -1931,10 +1944,14 @@ namespace mlirgen // with C not an A: the next try inserted through that dangling position). Where it was before // the statement is still good. auto insertionPointBefore = builder.saveInsertionPoint(); + auto errorsBefore = errorCount(genContext.postponedMessages); if (failed(mlirGen(statement, genContext))) { builder.restoreInsertionPoint(insertionPointBefore); - emitError(loc(statement), "failed statement"); + if (errorCount(genContext.postponedMessages) == errorsBefore) + { + emitError(loc(statement), "failed statement"); + } notResolved++; if (noErrorLocation) @@ -2208,9 +2225,14 @@ namespace mlirgen isVariableStatement && (statement.as()->declarationList->flags & NodeFlags::Const) == NodeFlags::Const; statementGenContext.rootStatementWasConst = wasConst; + auto errorsBefore = errorCount(statementGenContext.postponedMessages); if (failed(mlirGen(statement, statementGenContext))) { - emitError(loc(statement), "failed statement"); + if (errorCount(statementGenContext.postponedMessages) == errorsBefore) + { + emitError(loc(statement), "failed statement"); + } + return mlir::failure(); } } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index e1a8172bf..77bdc3c34 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4842,6 +4842,29 @@ foreach(array_from_mm gc own) endforeach() endforeach() +# JSX with no factory named, against the real default library: elements are calls of the library's `h` +# (__jsx_h), components, fragments and the HTML an element prints. Skipped when that model's default library +# has not been built. (-mm=own refuses the library's factory: 00jsx_typed_factory.tsx is own's.) +foreach(jsx_default_mm gc rc) + foreach(jsx_default_mode jit compile) + add_test(NAME test-${jsx_default_mode}-${jsx_default_mm}-defaultlib-jsx-default-factory + COMMAND ${CMAKE_COMMAND} + "-DMODE=${jsx_default_mode}" + "-DMM=${jsx_default_mm}" + "-DTSLANG=$" + "-DTSLANG_BIN=${CMAKE_BINARY_DIR}/bin" + "-DTEST=${CMAKE_CURRENT_SOURCE_DIR}/defaultlib/jsx_default_factory.tsx" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/jsx-default-factory-${jsx_default_mm}-${jsx_default_mode}" + "-DGC_LIB=${TEST_GC_LIBDIR}" + "-DLLVM_LIB=${defaultlib_collector_llvm_lib}" + "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" + "-DOPT=${defaultlib_collector_opt}" + "-DDEFAULT_LIB_CANDIDATES=${PROJECT_SOURCE_DIR}/../TypeScriptCompilerDefaultLib/__build;${PROJECT_SOURCE_DIR}/../../TypeScriptCompilerDefaultLib/__build" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-defaultlib-facts.cmake") + set_tests_properties(test-${jsx_default_mode}-${jsx_default_mm}-defaultlib-jsx-default-factory PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:") + endforeach() +endforeach() + # An Error's `stack` under the JIT (-mm=own, the driver's), against the real default library: named by tslang (jit.cpp # __tslang_stack_text), found by the library's DLL. Skipped when no default library has been built. add_test(NAME test-jit-own-defaultlib-error-stack-names @@ -5269,9 +5292,10 @@ endforeach() # Each file in crash-errors/ is one of them; the test passes when the compiler reports the error. set(crash_error_cases "jsx_mismatched_closing_tag.tsx|jsx_mismatched_closing_tag\\.tsx:1:16: error: Expected corresponding JSX closing tag for 'div'" - # an element is a call of the JSX factory (React.createElement by default), which these files do not declare - "jsx_no_children.tsx|jsx_no_children\\.tsx:1:9: error: the JSX factory 'React' can't be found" - "jsx_namespaced_tag.tsx|jsx_namespaced_tag\\.tsx:1:9: error: the JSX factory 'React' can't be found" + # an element is a call of the JSX factory (`h` by default, the default library's where the program has none), + # which these files do not declare and --no-default-lib leaves out + "jsx_no_children.tsx|jsx_no_children\\.tsx:1:9: error: the JSX factory 'h' can't be found" + "jsx_namespaced_tag.tsx|jsx_namespaced_tag\\.tsx:1:9: error: the JSX factory 'h' can't be found" "jsx_automatic_runtime.tsx|jsx_automatic_runtime\\.tsx:2:11: error: the automatic JSX runtime .* is not supported" "jsx_bad_factory_name.tsx|jsx_bad_factory_name\\.tsx:2:11: error: the JSX factory 'h\\.\\.x' is not a name or a dotted name" # a file's `export default ` is an exported constant (export-default.cmake); one in a `declare module` block is not diff --git a/tslang/test/tester/defaultlib/jsx_default_factory.tsx b/tslang/test/tester/defaultlib/jsx_default_factory.tsx new file mode 100644 index 000000000..8f6633e77 --- /dev/null +++ b/tslang/test/tester/defaultlib/jsx_default_factory.tsx @@ -0,0 +1,48 @@ +// JSX with no factory named and none declared: an element is a call of the default library's `h` (__jsx_h), +// which makes a JsxElement that prints as HTML. A tag that is a function is a component, called with what its +// parameters take (none, the attributes, the attributes and the children); what it returns that is no element +// is a fragment of it. Arrays among the children are flattened; null, undefined and booleans left out; text +// and attribute values escaped. + +function Item(props: { name: string }) { + return
  • {props.name}
  • ; +} + +function Card(props: { title: string }, children: any[]) { + return

    {props.title}

    {children}
    ; +} + +function Rule() { + return
    ; +} + +function Count(props: { n: int }) { + return "n=" + props.n; +} + +function check(actual: string, expected: string) { + print(actual); + assert(actual == expected, "expected " + expected); +} + +function main() { + check(String(
    ), "
    "); + + const names = ["a", "b + + {shown && never}{null} + + <>x{1}y + + ; + + check(`${page}`, "

    T & U

    • a
    • " + + "
    • b<c

    n=7x1y
    "); + + // the component's element itself, its children as given + assert(page.tag == "section", "the component's element"); + assert(page.children.length == 6, "six children"); + print("done."); +} diff --git a/tslang/test/tester/jsx-options.cmake b/tslang/test/tester/jsx-options.cmake index c33223e11..0d7c1a863 100644 --- a/tslang/test/tester/jsx-options.cmake +++ b/tslang/test/tester/jsx-options.cmake @@ -131,7 +131,28 @@ function main() { check("

    home

    " "${WORK_DIR}" --emit=jit --no-default-lib app.ts) check("

    home

    " "${WORK_DIR}" --emit=jit --no-default-lib --jit-cache=false app.ts) +# --- nothing named: the factory is `h` and the fragment's tag `Fragment`, here the program's own ------- +file(WRITE "${WORK_DIR}/default.tsx" "${factory}" [=[ +const Fragment = "frag"; + +function main() { + print(

    x

    ); + print(<>y); +} +]=]) +check("

    x

    \ny" "${WORK_DIR}" --emit=jit --no-default-lib default.tsx) + # --- the errors ---------------------------------------------------------------------------------- -fails("the JSX factory 'React' can't be found" "${WORK_DIR}" --emit=jit --no-default-lib plain.tsx) +# a factory named and not declared; `h` too, with the default library (which has one) left out: one error, +# and no "failed statement" after it +file(WRITE "${WORK_DIR}/bare.tsx" [=[ +const e =
    ; +]=]) +fails("the JSX factory 'React' can't be found" "${WORK_DIR}" --emit=jit --no-default-lib --jsx-factory=React.createElement plain.tsx) +fails("the JSX factory 'h' can't be found" "${WORK_DIR}" --emit=jit --no-default-lib bare.tsx) +string(FIND "${err}" "failed statement" at) +if(NOT at EQUAL -1) + message(FATAL_ERROR "a \"failed statement\" error after the factory's:\n${err}") +endif() fails("the automatic JSX runtime" "${WORK_DIR}" --emit=jit --no-default-lib --jsx=react-jsx --jsx-factory=h plain.tsx) fails("the JSX factory 'h.' is not a name or a dotted name" "${WORK_DIR}" --emit=jit --no-default-lib --jsx-factory=h. plain.tsx) diff --git a/tslang/test/tester/tests/00jsx_default_factory.tsx b/tslang/test/tester/tests/00jsx_default_factory.tsx index 7cb8ad712..85e4a29bc 100644 --- a/tslang/test/tester/tests/00jsx_default_factory.tsx +++ b/tslang/test/tester/tests/00jsx_default_factory.tsx @@ -1,29 +1,27 @@ -// JSX with no `@jsx` comment and no option: the factory is React.createElement and a fragment's tag -// React.Fragment, as tsc's "jsx": "react" has them. Here `React` is a namespace of the program's own -// whose factory renders HTML text: children are strings. +// JSX with no `@jsx` comment and no option: the factory is `h` and a fragment's tag `Fragment` (tsc's are +// React.createElement and React.Fragment). Here they are the program's own, which take the place of the +// default library's: a factory that renders HTML text, children are strings. // JSX inside an async function (an `await` in it), a generator (a `yield` around it) and a generic. -namespace React { - export const Fragment = ""; +const Fragment = ""; - export function createElement(tag: string, props: any, ...children: string[]): string { - let s = ""; - for (const c of children) { - s += c; - } +function h(tag: string, props: any, ...children: string[]): string { + let s = ""; + for (const c of children) { + s += c; + } - if (tag == Fragment) { - return s; - } + if (tag == Fragment) { + return s; + } - let attrs = ""; - if (props != null) { - for (const k in props) { - attrs += " " + k + "=\"" + (props[k] as string) + "\""; - } + let attrs = ""; + if (props != null) { + for (const k in props) { + attrs += " " + k + "=\"" + (props[k] as string) + "\""; } - - return "<" + tag + attrs + ">" + s + ""; } + + return "<" + tag + attrs + ">" + s + ""; } async function load(name: string) { diff --git a/tslang/tslang/tslang.cpp b/tslang/tslang/tslang.cpp index abc460282..f529c6675 100644 --- a/tslang/tslang/tslang.cpp +++ b/tslang/tslang/tslang.cpp @@ -235,8 +235,8 @@ cl::opt strictNullChecks("strict-null-checks", cl::desc("Strict Null Check // JSX (.tsx): an element is a call of the factory, as tsc's "jsx": "react" emits it (docs/jsx.md) cl::opt jsxMode("jsx", cl::desc("How JSX is compiled, as tsc's \"jsx\" option: react (the default), preserve and react-native are a call of the --jsx-factory; react-jsx and react-jsxdev (the automatic runtime) are not supported"), cl::init(""), cl::cat(TypeScriptCompilerCategory)); -cl::opt jsxFactory("jsx-factory", cl::desc("The function a JSX element calls, as tsc's \"jsxFactory\": a name or a dotted name (default React.createElement). A file's /** @jsx name */ comment wins"), cl::init(""), cl::cat(TypeScriptCompilerCategory)); -cl::opt jsxFragmentFactory("jsx-fragment-factory", cl::desc("What a JSX fragment <>... passes as its tag, as tsc's \"jsxFragmentFactory\" (default React.Fragment). A file's /** @jsxFrag name */ comment wins"), cl::init(""), cl::cat(TypeScriptCompilerCategory)); +cl::opt jsxFactory("jsx-factory", cl::desc("The function a JSX element calls, as tsc's \"jsxFactory\": a name or a dotted name (default h, the default library's). A file's /** @jsx name */ comment wins"), cl::init(""), cl::cat(TypeScriptCompilerCategory)); +cl::opt jsxFragmentFactory("jsx-fragment-factory", cl::desc("What a JSX fragment <>... passes as its tag, as tsc's \"jsxFragmentFactory\" (default Fragment, the default library's). A file's /** @jsxFrag name */ comment wins"), cl::init(""), cl::cat(TypeScriptCompilerCategory)); cl::opt sanitize("sanitize", cl::desc("Build the executable with a sanitizer: 'address' (AddressSanitizer: use after free, double free, " "out-of-bounds reads and writes of the heap, the stack and globals). Linux executables (--emit=exe) only; "