Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 42 additions & 9 deletions docs/jsx.md
Original file line number Diff line number Diff line change
@@ -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 <li class="item">{props.name}</li>;
}

function main() {
const names = ["one", "two & three"];
print(<ul id="list">{names.map(n => <Item name={n} />)}</ul>);
// <ul id="list"><li class="item">one</li><li class="item">two &amp; three</li></ul>
}
```

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) {
Expand Down Expand Up @@ -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 (`<input disabled>`); `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 && <b />}`).
- `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
Expand All @@ -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.
1 change: 1 addition & 0 deletions docs/whats-new.md
Original file line number Diff line number Diff line change
@@ -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(<p class="x">a &lt; b</p>)` prints `<p class="x">a &lt; b</p>`). 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
Expand Down
4 changes: 2 additions & 2 deletions tslang/include/TypeScript/DataStructs.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
13 changes: 11 additions & 2 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::pair<Identifier, string>> &libraryNames);

// inferType helpers; return true when the template kind matched and inference was handled

Expand Down Expand Up @@ -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<void *, std::pair<Node, Expression>> 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<std::pair<Identifier, string>> libraryNames;
};
std::map<void *, JsxLowered> 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
Expand Down
75 changes: 52 additions & 23 deletions tslang/lib/TypeScript/MLIRGenJsx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
// TypeScript's transformers/jsx.ts, ported from its Go port jsxtransforms/jsx.go):
//
// <div id="a" {...p} on={f}>hi {name}<Item n={1}/></div>
// => 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 (&amp;) are decoded.
Expand Down Expand Up @@ -383,49 +384,69 @@ namespace
{
auto key = static_cast<void *>(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<std::pair<Identifier, string>> 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<CallExpression>()->expression;
while ((SyntaxKind)callee == SyntaxKind::PropertyAccessExpression)
{
callee = callee.as<PropertyAccessExpression>()->expression;
}

auto location = loc(jsxAST);
if ((SyntaxKind)callee == SyntaxKind::Identifier)
{
auto rootName = MLIRHelper::getName(callee.as<Identifier>());
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();
}
}

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<std::pair<Identifier, string>> &libraryNames)
{
NodeFactory nf(NodeFactoryFlags::None);

Expand All @@ -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")))
Expand All @@ -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;
Expand All @@ -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<Identifier>(), part == S("h") ? string(S("__jsx_h")) : string(S("__jsx_Fragment"))});
}

expression = expression ? at(nf.createPropertyAccessExpression(expression, identifier), source) : identifier;
if (dot == string::npos)
{
Expand Down
26 changes: 24 additions & 2 deletions tslang/lib/TypeScript/MLIRGenModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::unique_ptr<mlir::Diagnostic>> *messages)
{
if (!messages)
{
return 0;
}

return llvm::count_if(*messages, [](const std::unique_ptr<mlir::Diagnostic> &diag) {
return diag->getSeverity() == mlir::DiagnosticSeverity::Error;
});
}

mlir::LogicalResult MLIRGenImpl::report(SourceFile module, const std::vector<SourceFile> &includeFiles)
{
// output diag info
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -2208,9 +2225,14 @@ namespace mlirgen
isVariableStatement
&& (statement.as<VariableStatement>()->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();
}
}
Expand Down
Loading
Loading