@overmvp/kumi 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/animation/color-transition.ts +196 -0
- package/animation/cycle.ts +151 -0
- package/animation/ease.ts +29 -0
- package/animation/index.ts +13 -0
- package/animation/package.json +12 -0
- package/animation/presets.ts +376 -0
- package/animation/spec.ts +197 -0
- package/builder/Cargo.lock +192 -0
- package/builder/Cargo.toml +7 -0
- package/builder/css-v1.mjs +387 -0
- package/builder/css-v1.test.mjs +361 -0
- package/builder/generated-output.mjs +61 -0
- package/builder/generated-output.test.mjs +132 -0
- package/builder/jsx-form.mjs +93 -0
- package/builder/jsx-form.test.mjs +48 -0
- package/builder/jsx-lists.mjs +209 -0
- package/builder/link-addon-package.mjs +127 -0
- package/builder/lua-assets.mjs +74 -0
- package/builder/lua-builtin-values.mjs +57 -0
- package/builder/lua-builtin-values.test.mjs +155 -0
- package/builder/lua-loop-closures.mjs +183 -0
- package/builder/lua-loop-closures.test.mjs +89 -0
- package/builder/lua-truthiness.mjs +61 -0
- package/builder/lua-truthiness.test.mjs +113 -0
- package/builder/module-declarations.mjs +594 -0
- package/builder/module-declarations.test.mjs +435 -0
- package/builder/native-kernels.mjs +60 -0
- package/builder/native-lua.d.ts +57 -0
- package/builder/native-routes.mjs +51 -0
- package/builder/no-static-ref-read.mjs +93 -0
- package/builder/no-static-ref-read.test.mjs +181 -0
- package/builder/secure-snippet.mjs +317 -0
- package/builder/secure-snippet.test.mjs +101 -0
- package/builder/shared-lua-runtime.mjs +150 -0
- package/builder/src/addon-link.lua +29 -0
- package/builder/src/arrays.lua +260 -0
- package/builder/src/assets.rs +177 -0
- package/builder/src/classes.lua +75 -0
- package/builder/src/collections.lua +190 -0
- package/builder/src/compiler.rs +2336 -0
- package/builder/src/config.rs +42 -0
- package/builder/src/entries.rs +166 -0
- package/builder/src/errors.lua +15 -0
- package/builder/src/lua_data.rs +231 -0
- package/builder/src/main.rs +381 -0
- package/builder/src/native_ir.rs +65 -0
- package/builder/src/native_signal.rs +83 -0
- package/builder/src/numbers.lua +76 -0
- package/builder/src/project-front.mjs +3682 -0
- package/builder/src/records.lua +75 -0
- package/builder/src/routes.rs +124 -0
- package/builder/src/setup-store.lua +18 -0
- package/builder/src/signal-kernel.fingerprint +1 -0
- package/builder/src/strings.lua +103 -0
- package/builder/src/ts-lower.mjs +68 -0
- package/builder/src/wow-reads.lua +22 -0
- package/builder/src/wow_client.rs +253 -0
- package/builder/src/wow_types.rs +564 -0
- package/builder/style-modules.mjs +93 -0
- package/builder/style-states.mjs +100 -0
- package/builder/style-states.test.mjs +103 -0
- package/builder/vite-assets.mjs +53 -0
- package/builder/vite-project.mjs +10 -0
- package/config.ts +59 -0
- package/eslint.mjs +74 -0
- package/form/index.ts +526 -0
- package/form/package.json +13 -0
- package/motion/index.ts +2 -0
- package/motion/package.json +10 -0
- package/package.json +26 -4
- package/router/index.ts +50 -0
- package/router/navigation.ts +22 -0
- package/router/package.json +12 -0
- package/router/router-view.ts +134 -0
- package/router/routes.ts +64 -0
- package/scripts/addon-build.mjs +364 -0
- package/scripts/addon-project.mjs +78 -0
- package/scripts/kumi-cli.mjs +105 -0
- package/scripts/link-addons.mjs +61 -0
- package/src/bindings.ts +35 -0
- package/src/context.ts +15 -0
- package/src/css-tokens.ts +239 -0
- package/src/css-v1.ts +68 -0
- package/src/cvars.ts +91 -0
- package/src/element-node.ts +32 -0
- package/src/elements.ts +505 -0
- package/src/feature-scope.ts +82 -0
- package/src/flex-layout.ts +807 -0
- package/src/frame-scheduler.ts +336 -0
- package/src/grid-tracks.ts +165 -0
- package/src/image-imports.d.ts +24 -0
- package/src/images.ts +79 -0
- package/src/index.ts +29 -0
- package/src/jsx-dev-runtime.ts +2 -0
- package/src/jsx-runtime.ts +29 -0
- package/src/jsx.d.ts +12 -0
- package/src/keyed-list.ts +366 -0
- package/src/media-query.ts +144 -0
- package/src/module-ui.ts +147 -0
- package/src/module.ts +311 -0
- package/src/node-selectors.ts +114 -0
- package/src/owned-collections.ts +52 -0
- package/src/providers.ts +241 -0
- package/src/reactive-scope.ts +34 -0
- package/src/reactivity.ts +275 -0
- package/src/result.ts +64 -0
- package/src/runtime.ts +52 -0
- package/src/scheduler.ts +185 -0
- package/src/signal-kernel.ts +63 -0
- package/src/style-classes.ts +51 -0
- package/src/style-states.ts +134 -0
- package/src/style-variables.ts +53 -0
- package/src/text-children.ts +42 -0
- package/src/theme.ts +50 -0
- package/src/transition.ts +18 -0
- package/state/index.ts +9 -0
- package/state/package.json +12 -0
- package/state/setup-store-persistence.ts +206 -0
- package/state/setup-store-view.ts +10 -0
- package/state/setup-store.ts +342 -0
- package/state/store-bindings.ts +25 -0
- package/state/store.ts +84 -0
- package/styles/_layers.scss +14 -0
- package/templates/addon/.agents/skills/kumi-build-debug/SKILL.md +36 -0
- package/templates/addon/.agents/skills/kumi-feature/SKILL.md +50 -0
- package/templates/addon/.agents/skills/kumi-plugin/SKILL.md +36 -0
- package/templates/addon/.agents/skills/kumi-store/SKILL.md +47 -0
- package/templates/addon/.agents/skills/kumi-ui/SKILL.md +73 -0
- package/templates/addon/.agents/skills/kumi-wow-api/SKILL.md +30 -0
- package/templates/addon/.claude/skills/kumi-build-debug/SKILL.md +36 -0
- package/templates/addon/.claude/skills/kumi-feature/SKILL.md +50 -0
- package/templates/addon/.claude/skills/kumi-plugin/SKILL.md +36 -0
- package/templates/addon/.claude/skills/kumi-store/SKILL.md +47 -0
- package/templates/addon/.claude/skills/kumi-ui/SKILL.md +73 -0
- package/templates/addon/.claude/skills/kumi-wow-api/SKILL.md +30 -0
- package/templates/addon/AGENTS.md +34 -0
- package/templates/addon/Assets/Art/Corner10.tga +0 -0
- package/templates/addon/Assets/Art/Corner11.tga +0 -0
- package/templates/addon/Assets/Art/Corner12.tga +0 -0
- package/templates/addon/Assets/Art/Corner13.tga +0 -0
- package/templates/addon/Assets/Art/Corner14.tga +0 -0
- package/templates/addon/Assets/Art/Corner15.tga +0 -0
- package/templates/addon/Assets/Art/Corner16.tga +0 -0
- package/templates/addon/Assets/Art/Corner2.tga +0 -0
- package/templates/addon/Assets/Art/Corner3.tga +0 -0
- package/templates/addon/Assets/Art/Corner4.tga +0 -0
- package/templates/addon/Assets/Art/Corner5.tga +0 -0
- package/templates/addon/Assets/Art/Corner6.tga +0 -0
- package/templates/addon/Assets/Art/Corner7.tga +0 -0
- package/templates/addon/Assets/Art/Corner8.tga +0 -0
- package/templates/addon/Assets/Art/Corner9.tga +0 -0
- package/templates/addon/Assets/Art/Dot.tga +0 -0
- package/templates/addon/Assets/Art/Gear.tga +0 -0
- package/templates/addon/Assets/Art/Grip.tga +0 -0
- package/templates/addon/Assets/Art/Outline10.tga +0 -0
- package/templates/addon/Assets/Art/Outline12.tga +0 -0
- package/templates/addon/Assets/Art/Outline13.tga +0 -0
- package/templates/addon/Assets/Art/Outline14.tga +0 -0
- package/templates/addon/Assets/Art/Outline15.tga +0 -0
- package/templates/addon/Assets/Art/Outline2.tga +0 -0
- package/templates/addon/Assets/Art/Outline3.tga +0 -0
- package/templates/addon/Assets/Art/Outline5.tga +0 -0
- package/templates/addon/Assets/Art/Outline7.tga +0 -0
- package/templates/addon/Assets/Art/Outline9.tga +0 -0
- package/templates/addon/Assets/Art/Round11.tga +0 -0
- package/templates/addon/Assets/Art/Round11Border.tga +0 -0
- package/templates/addon/Assets/Art/Round4.tga +0 -0
- package/templates/addon/Assets/Art/Round4Border.tga +0 -0
- package/templates/addon/Assets/Art/Round6.tga +0 -0
- package/templates/addon/Assets/Art/Round6Border.tga +0 -0
- package/templates/addon/Assets/Art/Round8.tga +0 -0
- package/templates/addon/Assets/Art/Round8Border.tga +0 -0
- package/templates/addon/Assets/Art/Search.tga +0 -0
- package/templates/addon/CLAUDE.md +1 -0
- package/templates/addon/README.md +49 -0
- package/templates/addon/eslint.config.mjs +6 -0
- package/templates/addon/gitignore +9 -0
- package/templates/addon/kumi.config.ts +17 -0
- package/templates/addon/package.json +20 -0
- package/templates/addon/src/app/app.module.ts +18 -0
- package/templates/addon/src/app/commands.store.ts +11 -0
- package/templates/addon/src/app/layout/AppWindow.module.scss +92 -0
- package/templates/addon/src/app/layout/AppWindow.tsx +32 -0
- package/templates/addon/src/app/main.ts +5 -0
- package/templates/addon/src/app/routes/(window)/home/page.tsx +8 -0
- package/templates/addon/src/app/routes/(window)/plugins/page.tsx +38 -0
- package/templates/addon/src/app/routes/(window)/settings/page.tsx +8 -0
- package/templates/addon/src/app/theme.ts +6 -0
- package/templates/addon/src/modules/greeting/api/player.api.ts +29 -0
- package/templates/addon/src/modules/greeting/greeting.module.ts +18 -0
- package/templates/addon/src/modules/greeting/model/greeting.store.ts +81 -0
- package/templates/addon/src/modules/greeting/services/greeting.service.ts +38 -0
- package/templates/addon/src/modules/greeting/ui/Greeting.module.scss +105 -0
- package/templates/addon/src/modules/greeting/ui/GreetingCard.tsx +29 -0
- package/templates/addon/src/modules/greeting/widgets/GreetingHud.tsx +54 -0
- package/templates/addon/src/modules/greeting/widgets/GreetingOverview.tsx +18 -0
- package/templates/addon/src/modules/greeting/widgets/GreetingSettings.tsx +56 -0
- package/templates/addon/src/modules/playtime/api/clock.api.ts +6 -0
- package/templates/addon/src/modules/playtime/model/playtime.store.ts +19 -0
- package/templates/addon/src/modules/playtime/playtime.module.ts +18 -0
- package/templates/addon/src/modules/playtime/services/playtime.service.ts +18 -0
- package/templates/addon/src/modules/playtime/ui/Playtime.module.scss +25 -0
- package/templates/addon/src/modules/playtime/ui/PlaytimeBadge.tsx +10 -0
- package/templates/addon/src/modules/playtime/widgets/PlaytimePage.tsx +16 -0
- package/templates/addon/src/shared/api/native-art.ts +28 -0
- package/templates/addon/src/shared/assets/close.png +0 -0
- package/templates/addon/src/shared/lib/format.ts +20 -0
- package/templates/addon/src/shared/styles/_tokens.scss +12 -0
- package/templates/addon/src/shared/ui/Button.tsx +29 -0
- package/templates/addon/src/shared/ui/Choice.tsx +34 -0
- package/templates/addon/src/shared/ui/Controls.module.scss +93 -0
- package/templates/addon/src/shared/ui/Glyph.tsx +18 -0
- package/templates/addon/src/shared/ui/Slider.tsx +25 -0
- package/templates/addon/src/shared/ui/Toggle.tsx +29 -0
- package/templates/addon/src/shared/ui/focus-ref.ts +7 -0
- package/templates/addon/src/shared/ui/range-skin.tsx +15 -0
- package/templates/addon/tsconfig.json +63 -0
- package/translate/index.ts +14 -0
- package/translate/package.json +9 -0
- package/utils/colors.ts +76 -0
- package/utils/format.ts +37 -0
- package/utils/index.ts +4 -0
- package/utils/number.ts +17 -0
- package/utils/package.json +7 -0
- package/utils/text.ts +6 -0
- package/validate/index.ts +119 -0
- package/validate/package.json +9 -0
- package/wow/absolute-position.ts +142 -0
- package/wow/action-bar-layout.ts +108 -0
- package/wow/action-button.ts +219 -0
- package/wow/action-catalog.ts +98 -0
- package/wow/addon-manifest.ts +36 -0
- package/wow/animation.ts +428 -0
- package/wow/app-ui.ts +221 -0
- package/wow/aura-button.ts +76 -0
- package/wow/aura-container.ts +591 -0
- package/wow/aura-countdown.ts +201 -0
- package/wow/aura-slot.ts +153 -0
- package/wow/bar-shade.ts +93 -0
- package/wow/borrowed-slot.ts +216 -0
- package/wow/button-drag.ts +48 -0
- package/wow/cast-clock.ts +153 -0
- package/wow/cast-text.ts +83 -0
- package/wow/class-colors.ts +126 -0
- package/wow/clock.ts +7 -0
- package/wow/color-picker.ts +128 -0
- package/wow/commands.ts +17 -0
- package/wow/contained-frame.ts +128 -0
- package/wow/contract.ts +42 -0
- package/wow/cooldown-timing.ts +24 -0
- package/wow/css-box.ts +144 -0
- package/wow/css-color.ts +12 -0
- package/wow/css-style.ts +109 -0
- package/wow/css-surfaces.ts +603 -0
- package/wow/css-text.ts +399 -0
- package/wow/cursor.ts +45 -0
- package/wow/cvar-schema.ts +32 -0
- package/wow/cvars.ts +98 -0
- package/wow/dropdown-art.ts +39 -0
- package/wow/element-click.ts +20 -0
- package/wow/element-event-coordinator.ts +219 -0
- package/wow/element-events.ts +317 -0
- package/wow/event-dispatcher.ts +151 -0
- package/wow/events.ts +50 -0
- package/wow/font-cache.ts +92 -0
- package/wow/frame-access.ts +53 -0
- package/wow/frame-layer.ts +5 -0
- package/wow/frame-timing.ts +13 -0
- package/wow/frames.ts +236 -0
- package/wow/heal-prediction.ts +305 -0
- package/wow/hooks.ts +133 -0
- package/wow/image-layers.ts +55 -0
- package/wow/index.ts +111 -0
- package/wow/layout-view.ts +663 -0
- package/wow/locale-font.ts +15 -0
- package/wow/lua-string.ts +18 -0
- package/wow/lua-table.ts +18 -0
- package/wow/macro-book.ts +84 -0
- package/wow/map-position.ts +27 -0
- package/wow/media-query.ts +65 -0
- package/wow/module-events.ts +11 -0
- package/wow/native-hooks.ts +168 -0
- package/wow/native-placement.ts +88 -0
- package/wow/native.ts +153 -0
- package/wow/number-format.ts +8 -0
- package/wow/number-input.ts +10 -0
- package/wow/panel-host.ts +97 -0
- package/wow/pixel.ts +35 -0
- package/wow/plugins.ts +246 -0
- package/wow/protect.ts +48 -0
- package/wow/protected-layout.ts +133 -0
- package/wow/protected-view.ts +103 -0
- package/wow/range-art.ts +81 -0
- package/wow/readable-api.ts +120 -0
- package/wow/reparent-frame.ts +99 -0
- package/wow/rounded-texture.ts +183 -0
- package/wow/saved-variables.ts +109 -0
- package/wow/scroll-view.ts +64 -0
- package/wow/secret-ref.ts +14 -0
- package/wow/secure-bindings.ts +89 -0
- package/wow/secure-clicks.ts +432 -0
- package/wow/secure-snippet.ts +235 -0
- package/wow/secure-state.ts +130 -0
- package/wow/secure-target-visibility.ts +89 -0
- package/wow/secure-transaction.ts +331 -0
- package/wow/special-window.ts +269 -0
- package/wow/spell-cooldown.ts +36 -0
- package/wow/start-addon.ts +122 -0
- package/wow/state-paint.ts +256 -0
- package/wow/transition.ts +86 -0
- package/wow/unit-button.ts +39 -0
- package/wow/unit-cast.ts +92 -0
- package/wow/unit-health-text.ts +47 -0
- package/wow/view-nodes.ts +304 -0
- package/wow/view.ts +1864 -0
- package/wow/visible-frame-job.ts +34 -0
- package/wow/width-reserve.ts +108 -0
|
@@ -0,0 +1,3682 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
5
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
|
|
8
|
+
const require = createRequire(resolve("package.json"));
|
|
9
|
+
const ts = require("typescript");
|
|
10
|
+
const [entry, workspace, sdk, tsconfig, mode, link, assets, pack, checkAssets, fragments] = process.argv.slice(2);
|
|
11
|
+
const workspaceRoot = realpathSync(workspace);
|
|
12
|
+
const sdkRoot = realpathSync(sdk);
|
|
13
|
+
const entryPath = realpathSync(entry);
|
|
14
|
+
// SDK fixtures compile like an addon. Their ambient `declare` mocks bind to Lua globals.
|
|
15
|
+
const testMode = mode === "test";
|
|
16
|
+
const addon = mode === "addon" || testMode;
|
|
17
|
+
const rootSources = resolve(workspaceRoot, "src");
|
|
18
|
+
const rootEntry = relative(resolve(rootSources, "app"), entryPath);
|
|
19
|
+
const generatedLazyEntry = relative(resolve(workspaceRoot, "build/kumi/plugins"), entryPath);
|
|
20
|
+
const usesRootSources = [rootEntry, generatedLazyEntry].some(path => path !== "" && !isAbsolute(path)
|
|
21
|
+
&& path.split(/[\\/]/)[0] !== "..");
|
|
22
|
+
const addonSources = usesRootSources ? rootSources : resolve(workspaceRoot, "dev/uikit/src");
|
|
23
|
+
const addonPlatform = resolve(addonSources, "platform/ui-globals.d.ts");
|
|
24
|
+
const options = { strict: true, noEmit: true, target: ts.ScriptTarget.ES2020, types: [] };
|
|
25
|
+
const display = {
|
|
26
|
+
getCurrentDirectory: ts.sys.getCurrentDirectory, getCanonicalFileName: name => name, getNewLine: () => "\n",
|
|
27
|
+
};
|
|
28
|
+
let declarations = [];
|
|
29
|
+
|
|
30
|
+
function diagnostics(errors) {
|
|
31
|
+
if (errors.length) throw new Error(ts.formatDiagnosticsWithColorAndContext(errors, display).trimEnd());
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (tsconfig) {
|
|
35
|
+
const config = ts.getParsedCommandLineOfConfigFile(tsconfig, {}, {
|
|
36
|
+
...ts.sys, onUnRecoverableConfigFileDiagnostic: diagnostic => diagnostics([diagnostic]),
|
|
37
|
+
});
|
|
38
|
+
diagnostics(config.errors);
|
|
39
|
+
Object.assign(options, config.options, { noEmit: true });
|
|
40
|
+
declarations = config.fileNames.filter(file => file.endsWith(".d.ts"));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const moduleMarkers = new Set(["Module", "ModuleType", "Injectable", "Inject"]);
|
|
44
|
+
|
|
45
|
+
function moduleMarker(symbol, name = symbol?.name) {
|
|
46
|
+
const declaration = symbol?.valueDeclaration;
|
|
47
|
+
const expected = moduleMarkers.has(name) ? "src/module.ts" : name === "OnEvent" ? "wow/module-events.ts" : undefined;
|
|
48
|
+
return expected !== undefined && symbol?.name === name && declaration
|
|
49
|
+
&& relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === expected;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const kumiJsxFactories = new Map();
|
|
53
|
+
|
|
54
|
+
function jsxPragma(file, key, argument) {
|
|
55
|
+
const found = file.pragmas.get(key);
|
|
56
|
+
return (Array.isArray(found) ? found[0] : found)?.arguments[argument];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function withKumiJsx(file, source) {
|
|
60
|
+
if (options.jsx !== ts.JsxEmit.ReactJSX || !file.fileName.endsWith(".tsx")) return source;
|
|
61
|
+
const runtime = jsxPragma(file, "jsxruntime", "runtime");
|
|
62
|
+
const importSource = jsxPragma(file, "jsximportsource", "factory") ?? options.jsxImportSource;
|
|
63
|
+
if (runtime === "classic" || importSource !== "@kumi/core") return source;
|
|
64
|
+
function hasJsx(node) {
|
|
65
|
+
return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node)
|
|
66
|
+
|| ts.forEachChild(node, hasJsx);
|
|
67
|
+
}
|
|
68
|
+
if (!hasJsx(file)) return source;
|
|
69
|
+
let suffix = 0;
|
|
70
|
+
while (source.includes("__kumiCreateElement" + suffix) || source.includes("__kumiFragment" + suffix)) suffix += 1;
|
|
71
|
+
const factory = "__kumiCreateElement" + suffix;
|
|
72
|
+
const fragment = "__kumiFragment" + suffix;
|
|
73
|
+
kumiJsxFactories.set(file.fileName, { factory, fragment });
|
|
74
|
+
// Imports are hoisted. Append the aliases to preserve source diagnostic positions.
|
|
75
|
+
return source + `\nimport { createElement as ${factory}, Fragment as ${fragment} } from "@kumi/core";\n`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function checkedProgram() {
|
|
79
|
+
const paths = [entry, ...declarations];
|
|
80
|
+
const host = ts.createCompilerHost(options);
|
|
81
|
+
const frontend = name => import(pathToFileURL(resolve(sdkRoot, `builder/${name}.mjs`)).href);
|
|
82
|
+
if (addon) {
|
|
83
|
+
const { useNativeRoutes } = await frontend("native-routes");
|
|
84
|
+
useNativeRoutes(ts, host, resolve(addonSources, "app/routes"));
|
|
85
|
+
}
|
|
86
|
+
const original = ts.createProgram(paths, options, host);
|
|
87
|
+
diagnostics(ts.getPreEmitDiagnostics(original));
|
|
88
|
+
const candidates = original.getSourceFiles().filter(file => !file.isDeclarationFile && compilerOwnsPath(file.fileName)
|
|
89
|
+
&& (file.text.includes("@") || file.text.includes("secureSnippet") || file.fileName.endsWith(".tsx"))).map(file => file.fileName);
|
|
90
|
+
if (!candidates.length) return original;
|
|
91
|
+
const [{ transformSecureSnippets }, { transformModuleDeclarations }, { transformJsx }] = await Promise.all([
|
|
92
|
+
frontend("secure-snippet"), frontend("module-declarations"), frontend("jsx-lists"),
|
|
93
|
+
]);
|
|
94
|
+
const canonical = path => host.getCanonicalFileName(resolve(path));
|
|
95
|
+
const changes = new Map();
|
|
96
|
+
const read = host.readFile;
|
|
97
|
+
host.readFile = file => changes.get(canonical(file)) ?? read(file);
|
|
98
|
+
for (const path of candidates) {
|
|
99
|
+
const file = original.getSourceFile(path);
|
|
100
|
+
const source = transformSecureSnippets(ts, path, file.text, { program: original, isMarkerSymbol: secureSnippetMarker });
|
|
101
|
+
if (source !== undefined) changes.set(canonical(path), source);
|
|
102
|
+
}
|
|
103
|
+
const secured = changes.size ? ts.createProgram(paths, options, host) : original;
|
|
104
|
+
let rewritten = false;
|
|
105
|
+
for (const path of candidates) {
|
|
106
|
+
const file = secured.getSourceFile(path);
|
|
107
|
+
if (file === undefined) continue;
|
|
108
|
+
const declared = transformModuleDeclarations(ts, path, file.text, {
|
|
109
|
+
program: secured, rejectUnknown: true, isMarkerSymbol: moduleMarker,
|
|
110
|
+
}) ?? file.text;
|
|
111
|
+
const source = withKumiJsx(file, transformJsx(ts, path, declared) ?? declared);
|
|
112
|
+
if (source === file.text) continue;
|
|
113
|
+
rewritten = true;
|
|
114
|
+
changes.set(canonical(path), source);
|
|
115
|
+
}
|
|
116
|
+
const lowered = rewritten ? ts.createProgram(paths, options, host) : secured;
|
|
117
|
+
if (lowered !== original) diagnostics(ts.getPreEmitDiagnostics(lowered));
|
|
118
|
+
return lowered;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function secureSnippetMarker(symbol) {
|
|
122
|
+
const declaration = symbol?.valueDeclaration;
|
|
123
|
+
return symbol?.name === "secureSnippet" && declaration && ts.isFunctionDeclaration(declaration)
|
|
124
|
+
&& relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "wow/secure-snippet.ts";
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const program = await checkedProgram();
|
|
128
|
+
const checker = program.getTypeChecker();
|
|
129
|
+
const { SyntaxKind: K, TypeFlags: T } = ts;
|
|
130
|
+
const records = ["kumi-project-1"];
|
|
131
|
+
const emit = (...parts) => records.push(parts.join("\t"));
|
|
132
|
+
const text = value => Buffer.from(value, "utf8").toString("hex");
|
|
133
|
+
const ids = new Map();
|
|
134
|
+
const textureIds = new Map();
|
|
135
|
+
const stack = [];
|
|
136
|
+
const bindings = new Map();
|
|
137
|
+
const forwardedRest = new WeakSet();
|
|
138
|
+
const delayedReferences = new WeakSet();
|
|
139
|
+
const capturedVariables = new WeakSet();
|
|
140
|
+
const patternParameters = new WeakMap();
|
|
141
|
+
const addonSourceFiles = new WeakMap();
|
|
142
|
+
let unique = 0;
|
|
143
|
+
|
|
144
|
+
function unsupported(node, message = `${K[node.kind]} is outside the Kumi compiler subset`) {
|
|
145
|
+
const file = node.getSourceFile();
|
|
146
|
+
const { line, character } = file.getLineAndCharacterOfPosition(node.getStart(file));
|
|
147
|
+
throw new Error(`${file.fileName}:${line + 1}:${character + 1}: ${message}`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function propertyName(node) {
|
|
151
|
+
if (!ts.isIdentifier(node) && !ts.isStringLiteral(node)) unsupported(node, "Expected a literal property name");
|
|
152
|
+
return node.text;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function binding(symbol, node) {
|
|
156
|
+
if (symbol === undefined) unsupported(node, "Unresolved value symbol");
|
|
157
|
+
const declaration = symbol.valueDeclaration;
|
|
158
|
+
// The checker exposes distinct symbols for the field and the lexical binding of a parameter property.
|
|
159
|
+
const key = declaration && ts.isParameter(declaration) && ts.isIdentifier(declaration.name) ? declaration : symbol;
|
|
160
|
+
if (!bindings.has(key)) bindings.set(key, `b${++unique}`);
|
|
161
|
+
return bindings.get(key);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function identifier(node) {
|
|
165
|
+
if (!ts.isIdentifier(node)) unsupported(node, "Expected an identifier");
|
|
166
|
+
const symbol = checker.getSymbolAtLocation(node);
|
|
167
|
+
if (!symbol?.declarations?.some(declaration => declaration.getSourceFile() === node.getSourceFile())) {
|
|
168
|
+
unsupported(node, "Expected a local value symbol");
|
|
169
|
+
}
|
|
170
|
+
return binding(symbol, node);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const hostGlobals = new Map([
|
|
174
|
+
["pcall", ["wow/protect.ts"]],
|
|
175
|
+
["xpcall", ["wow/protect.ts"]],
|
|
176
|
+
["_G", ["wow/native.ts"]],
|
|
177
|
+
["issecretvalue", ["wow/native.ts"]],
|
|
178
|
+
["rawget", ["wow/lua-table.ts", "wow/frames.ts", "wow/native-hooks.ts", "wow/secure-transaction.ts", "wow/aura-container.ts"]],
|
|
179
|
+
["rawset", ["wow/lua-table.ts", "wow/frames.ts", "wow/native-hooks.ts", "wow/secure-transaction.ts", "wow/aura-container.ts"]],
|
|
180
|
+
["getmetatable", ["wow/native-placement.ts"]],
|
|
181
|
+
["setmetatable", ["wow/lua-table.ts", "wow/native-hooks.ts", "wow/readable-api.ts"]],
|
|
182
|
+
["error", ["wow/readable-api.ts"]],
|
|
183
|
+
["string", ["wow/lua-string.ts"]],
|
|
184
|
+
["CreateFrame", ["wow/frames.ts"]],
|
|
185
|
+
["GameFontNormal", ["wow/view.ts"]],
|
|
186
|
+
["rawequal", ["wow/view.ts"]],
|
|
187
|
+
["DoReadyCheck", ["wow/index.ts"]],
|
|
188
|
+
["pairs", ["wow/special-window.ts"]],
|
|
189
|
+
["table", ["wow/special-window.ts"]],
|
|
190
|
+
["type", ["wow/special-window.ts"]],
|
|
191
|
+
["tonumber", ["wow/aura-countdown.ts", "wow/number-input.ts"]],
|
|
192
|
+
]);
|
|
193
|
+
|
|
194
|
+
const addonHostGlobals = new Set([
|
|
195
|
+
"_G", "assert", "collectgarbage", "coroutine", "date", "error", "getmetatable", "ipairs", "loadstring", "math", "next", "pairs", "pcall",
|
|
196
|
+
"print", "rawequal", "rawget", "rawset", "select", "setfenv", "setmetatable", "string", "table", "time", "tonumber", "tostring", "type", "unpack", "xpcall",
|
|
197
|
+
"C_AddOns", "C_ChallengeMode", "C_Timer", "ChatFrame1", "ChatTypeInfo", "CreateFont", "DEFAULT_CHAT_FRAME", "EnumerateFrames", "GetAddOnMetadata",
|
|
198
|
+
"GetInstanceInfo", "GetLocale", "GetNormalizedRealmName", "GetPlayerInfoByGUID", "GetRealmName", "InCombatLockdown", "IsInGroup",
|
|
199
|
+
"LibStub", "ReloadUI", "STANDARD_TEXT_FONT", "UIParent", "UNKNOWN", "UNKNOWNOBJECT", "UnitClass", "UnitExists", "UnitFullName",
|
|
200
|
+
"UnitGUID", "UnitGroupRolesAssigned", "UnitIsUnit", "UnitName", "UnitNameFromGUID", "debugstack", "geterrorhandler", "hooksecurefunc",
|
|
201
|
+
"issecretvalue", "strsplit", "wipe",
|
|
202
|
+
]);
|
|
203
|
+
|
|
204
|
+
function hostGlobal(symbol) {
|
|
205
|
+
const sources = hostGlobals.get(symbol?.name);
|
|
206
|
+
const addonHost = addon && (addonHostGlobals.has(symbol?.name) || testMode && symbol?.name !== undefined);
|
|
207
|
+
if (!sources && !addonHost) return false;
|
|
208
|
+
const declarations = symbol.declarations?.filter(declaration => !ts.isTypeAliasDeclaration(declaration) && !ts.isInterfaceDeclaration(declaration));
|
|
209
|
+
return declarations?.length && declarations.every(declaration => {
|
|
210
|
+
const externalFunction = ts.isFunctionDeclaration(declaration) && !declaration.body;
|
|
211
|
+
if (!externalFunction && !ambientVariable(declaration)) return false;
|
|
212
|
+
const path = realpathSync(declaration.getSourceFile().fileName);
|
|
213
|
+
if (sources?.includes(relative(sdkRoot, path).replaceAll("\\", "/"))) return true;
|
|
214
|
+
if (!addonHost || !addonOwnsPath(path)) return false;
|
|
215
|
+
if (!externalFunction) return true;
|
|
216
|
+
const [receiver] = declaration.parameters;
|
|
217
|
+
return receiver && ts.isIdentifier(receiver.name) && receiver.name.text === "this" && receiver.type?.kind === K.VoidKeyword;
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function ambientVariable(declaration) {
|
|
222
|
+
return declaration && ts.isVariableDeclaration(declaration)
|
|
223
|
+
&& ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Ambient;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function addonBinding(symbol) {
|
|
227
|
+
const declaration = symbol?.valueDeclaration;
|
|
228
|
+
if (!ambientVariable(declaration)) return;
|
|
229
|
+
const path = realpathSync(declaration.getSourceFile().fileName);
|
|
230
|
+
if (symbol.name === "kumiAddonTable" && relative(sdkRoot, path).replaceAll("\\", "/") === "wow/addon-manifest.ts") {
|
|
231
|
+
return addon ? "addonApp" : "nil";
|
|
232
|
+
}
|
|
233
|
+
if (!addon) return;
|
|
234
|
+
if (path === entryPath) {
|
|
235
|
+
if (symbol.name === "addonName") return "addonName";
|
|
236
|
+
if (symbol.name === "addonTable") return "addonTable";
|
|
237
|
+
}
|
|
238
|
+
if (symbol.name === "KumiUI" && addonOwnsPath(path)) return "addonApp";
|
|
239
|
+
if (relative(addonPlatform, path) === "") {
|
|
240
|
+
if (symbol.name === "t") return "addonLocale";
|
|
241
|
+
if (symbol.name === "UI") return "addonUi";
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function nativeLuaDeclaration(declaration) {
|
|
246
|
+
const file = declaration?.getSourceFile();
|
|
247
|
+
return file?.isDeclarationFile && /(?:^|[/\\])native-lua\.d\.ts$/.test(file.fileName)
|
|
248
|
+
&& relative(sdkRoot, realpathSync(file.fileName)).replaceAll("\\", "/")
|
|
249
|
+
=== "builder/native-lua.d.ts";
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function nativeMultiFunction(symbol) {
|
|
253
|
+
const declaration = symbol?.valueDeclaration;
|
|
254
|
+
if (symbol?.name !== "$multi" || !declaration || !ts.isVariableDeclaration(declaration)
|
|
255
|
+
|| !(ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Ambient)) return false;
|
|
256
|
+
if (nativeLuaDeclaration(declaration)) return true;
|
|
257
|
+
const file = relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/");
|
|
258
|
+
if (!["wow/class-colors.ts", "wow/cursor.ts", "wow/map-position.ts", "wow/readable-api.ts"].includes(file)) return false;
|
|
259
|
+
const marker = checker.getTypeOfSymbolAtLocation(symbol, declaration).getProperty("__tstlExtension");
|
|
260
|
+
return marker && checker.getTypeOfSymbolAtLocation(marker, declaration).value === "MultiFunction";
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function variableDeclaration(symbol) {
|
|
264
|
+
let node = symbol?.valueDeclaration;
|
|
265
|
+
while (node && ts.isBindingElement(node)) node = node.parent.parent;
|
|
266
|
+
if (node && ts.isVariableDeclaration(node) && node.parent.flags & ts.NodeFlags.BlockScoped) return node;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function rememberCapturedVariables(file) {
|
|
270
|
+
function inspect(node, owner) {
|
|
271
|
+
if (ts.isTypeNode(node)) return;
|
|
272
|
+
if (ts.isFunctionLike(node)) owner = node;
|
|
273
|
+
if (owner && ts.isIdentifier(node)) {
|
|
274
|
+
const symbol = ts.isShorthandPropertyAssignment(node.parent)
|
|
275
|
+
? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
276
|
+
const declaration = variableDeclaration(symbol);
|
|
277
|
+
if (declaration && declaration.getSourceFile() === file && owner.end <= declaration.getStart(file)) {
|
|
278
|
+
capturedVariables.add(declaration);
|
|
279
|
+
delayedReferences.add(node);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
ts.forEachChild(node, child => { inspect(child, owner); });
|
|
283
|
+
}
|
|
284
|
+
inspect(file);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function reference(symbol, node) {
|
|
288
|
+
if (symbol?.name === "Infinity" && symbol.declarations?.some(declaration =>
|
|
289
|
+
program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) return emit("global", "math.huge");
|
|
290
|
+
if (symbol?.name === "NaN" && symbol.declarations?.some(declaration =>
|
|
291
|
+
program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) return emit("literal", "nan");
|
|
292
|
+
if (symbol?.name === "String" && symbol.declarations?.some(declaration =>
|
|
293
|
+
program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) {
|
|
294
|
+
return emit("global", "tostring");
|
|
295
|
+
}
|
|
296
|
+
if (symbol?.name === "Number" && symbol.declarations?.some(declaration =>
|
|
297
|
+
program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) return emit("global", "numberValue");
|
|
298
|
+
if (hostGlobal(symbol)) return emit("host-global", symbol.name);
|
|
299
|
+
const addonGlobal = addonBinding(symbol);
|
|
300
|
+
if (addonGlobal === "nil") return emit("literal", "nil");
|
|
301
|
+
if (addonGlobal) return emit("addon-global", addonGlobal);
|
|
302
|
+
if (addon && symbol?.name === "$vararg" && nativeLuaDeclaration(symbol.valueDeclaration) && realpathSync(node.getSourceFile().fileName) === entryPath) {
|
|
303
|
+
return emit("addon-global", "addonArgs");
|
|
304
|
+
}
|
|
305
|
+
if (symbol?.declarations?.some(declaration => ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Ambient)) {
|
|
306
|
+
unsupported(node, "Ambient value has no native host binding");
|
|
307
|
+
}
|
|
308
|
+
const file = node.getSourceFile();
|
|
309
|
+
if (!symbol?.declarations?.some(declaration => declaration.getSourceFile() === file)) {
|
|
310
|
+
unsupported(node, "Value requires a local declaration or named import");
|
|
311
|
+
}
|
|
312
|
+
if (symbol.flags & ts.SymbolFlags.Alias && !bindings.has(symbol)) {
|
|
313
|
+
unsupported(node, "Value requires a runtime import");
|
|
314
|
+
}
|
|
315
|
+
if (moduleMarker(symbol)) unsupported(node, "Kumi module declaration must be lowered before linking");
|
|
316
|
+
const declaration = variableDeclaration(symbol);
|
|
317
|
+
if (declaration && declaration.getStart(file) > node.getStart(file) && !delayedReferences.has(node)) {
|
|
318
|
+
unsupported(node, "Local binding must be declared before it is referenced");
|
|
319
|
+
}
|
|
320
|
+
emit("ref", binding(symbol, node));
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// True when every value of the type is truthy in Lua: never nil or false. Lua treats 0 and "" as true.
|
|
324
|
+
function luaAlwaysTruthy(input) {
|
|
325
|
+
const type = nativeBase(input);
|
|
326
|
+
if (type.isUnion()) return type.types.every(luaAlwaysTruthy);
|
|
327
|
+
if (type.isIntersection()) return type.types.some(luaAlwaysTruthy);
|
|
328
|
+
if (type.flags & (T.Any | T.Unknown | T.Null | T.Undefined | T.Void | T.Never | T.BooleanLike | T.TypeParameter)) return false;
|
|
329
|
+
return Boolean(type.flags & (T.NumberLike | T.StringLike | T.BigIntLike | T.ESSymbolLike | T.Object | T.NonPrimitive))
|
|
330
|
+
|| type.getCallSignatures().length > 0;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function luaTruthValue(input) {
|
|
334
|
+
const type = nativeBase(input);
|
|
335
|
+
if (type.isUnionOrIntersection()) return type.types.every(luaTruthValue);
|
|
336
|
+
return Boolean(type.flags & (T.BooleanLike | T.Undefined | T.Null | T.Void | T.Never | T.Object | T.NonPrimitive)
|
|
337
|
+
|| type.isStringLiteral() && type.value !== "" || type.isNumberLiteral() && type.value !== 0
|
|
338
|
+
|| type.getCallSignatures().length > 0);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function booleanCondition(node) {
|
|
342
|
+
const type = checker.getTypeAtLocation(node);
|
|
343
|
+
if (!addonSource(node) && !luaTruthValue(type)) {
|
|
344
|
+
unsupported(node, "Use an explicit comparison in a condition");
|
|
345
|
+
}
|
|
346
|
+
expression(node);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function body(node, params = []) {
|
|
350
|
+
statements(ts.isBlock(node) ? node.statements : [node], parameterPrelude(params));
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function canonicalReveal(declaration, guard) {
|
|
354
|
+
if (!declaration || !ts.isFunctionDeclaration(declaration) || declaration.name?.text !== "reveal"
|
|
355
|
+
|| !declaration.body || declaration.parameters.length !== 1) return false;
|
|
356
|
+
const file = declaration.getSourceFile();
|
|
357
|
+
if (relative(sdkRoot, realpathSync(file.fileName)).replaceAll("\\", "/") !== "wow/native.ts"
|
|
358
|
+
|| !guard?.body || !ts.isFunctionDeclaration(guard) || guard.getSourceFile() !== file) return false;
|
|
359
|
+
|
|
360
|
+
// The Rust lowering inlines this exact pair, including its single read of the host predicate.
|
|
361
|
+
// A changed SDK body uses ordinary function emission.
|
|
362
|
+
const printer = ts.createPrinter({ removeComments: true, newLine: ts.NewLineKind.LineFeed });
|
|
363
|
+
const source = [guard, declaration].map(node => printer.printNode(ts.EmitHint.Unspecified, node, file)).join("\n");
|
|
364
|
+
if (createHash("sha256").update(source).digest("hex") !== "b37a4d648682becadede60fa3a88813830eb3c65cac2a1d2acc23d1a320fdd1b") return false;
|
|
365
|
+
const callee = declaration.body.statements[0].expression.condition.expression;
|
|
366
|
+
const predicate = guard.body.statements[0].declarationList.declarations[0].initializer;
|
|
367
|
+
return checker.getSymbolAtLocation(callee)?.valueDeclaration === guard
|
|
368
|
+
&& hostGlobal(checker.getSymbolAtLocation(predicate));
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function emitCanonicalReveal(declaration, exports, params) {
|
|
372
|
+
if (params.length !== 1 || exports.get("reveal")?.valueDeclaration !== declaration
|
|
373
|
+
|| !canonicalReveal(declaration, exports.get("isSecret")?.valueDeclaration)) return false;
|
|
374
|
+
|
|
375
|
+
emit("block", 1);
|
|
376
|
+
emit("return-wow-reveal", params[0]);
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function parameters(nodes, usesSelf = false) {
|
|
381
|
+
const names = [];
|
|
382
|
+
for (const param of nodes) {
|
|
383
|
+
if (ts.isIdentifier(param.name) && param.name.text === "this") {
|
|
384
|
+
if (!usesSelf && !(checker.getTypeAtLocation(param).flags & T.Void)) unsupported(param, "A declared function must use this: void");
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
const name = parameterName(param);
|
|
388
|
+
names.push(param.dotDotDotToken ? `${forwardedRest.has(param) ? "forwarded-rest" : "rest"}:${name}` : name);
|
|
389
|
+
}
|
|
390
|
+
return names;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function parameterName(param) {
|
|
394
|
+
if (ts.isIdentifier(param.name)) return identifier(param.name);
|
|
395
|
+
if (!patternParameters.has(param)) patternParameters.set(param, `b${++unique}`);
|
|
396
|
+
return patternParameters.get(param);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function parameterPrelude(params) {
|
|
400
|
+
const steps = [];
|
|
401
|
+
for (const param of params) {
|
|
402
|
+
if (param.initializer) steps.push(() => {
|
|
403
|
+
emit("nil-assign", parameterName(param));
|
|
404
|
+
expression(param.initializer);
|
|
405
|
+
});
|
|
406
|
+
if (ts.isIdentifier(param.name)) continue;
|
|
407
|
+
const read = () => emit("ref", parameterName(param));
|
|
408
|
+
if (ts.isObjectBindingPattern(param.name)) {
|
|
409
|
+
steps.push(() => bindObject(param.name, read, () => isOwnedRecord(checker.getTypeAtLocation(param))));
|
|
410
|
+
} else {
|
|
411
|
+
if (!nativeArrayReference(param.name) && !knownTuple(checker.getTypeAtLocation(param)) && !param.dotDotDotToken) {
|
|
412
|
+
unsupported(param, "A destructured parameter requires a native tuple or record");
|
|
413
|
+
}
|
|
414
|
+
steps.push(() => bindTuple(param.name, read));
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return steps;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function valueSymbol(node) {
|
|
421
|
+
const symbol = checker.getSymbolAtLocation(node);
|
|
422
|
+
return symbol?.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const readableOverrides = new WeakMap();
|
|
426
|
+
|
|
427
|
+
function sdkVariable(symbol, name, path) {
|
|
428
|
+
const declaration = symbol?.valueDeclaration;
|
|
429
|
+
return symbol?.name === name && declaration && ts.isVariableDeclaration(declaration)
|
|
430
|
+
&& relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === path
|
|
431
|
+
&& (declaration.parent.flags & ts.NodeFlags.Const) !== 0 ? declaration : undefined;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function readableMetatable(init, fieldCount) {
|
|
435
|
+
if (!init || !ts.isCallExpression(init) || init.arguments.length !== 2
|
|
436
|
+
|| !ts.isIdentifier(init.expression) || init.expression.text !== "setmetatable"
|
|
437
|
+
|| !hostGlobal(valueSymbol(init.expression))) return;
|
|
438
|
+
const [table, meta] = init.arguments;
|
|
439
|
+
if (!ts.isObjectLiteralExpression(table) || !ts.isObjectLiteralExpression(meta)
|
|
440
|
+
|| meta.properties.length !== fieldCount
|
|
441
|
+
|| !meta.properties.every(field => ts.isPropertyAssignment(field) && ts.isIdentifier(field.name))) return;
|
|
442
|
+
const fields = new Map(meta.properties.map(field => [field.name.text, field.initializer]));
|
|
443
|
+
return { table, fields };
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function readOnlyApiMetatable(initializer) {
|
|
447
|
+
const view = readableMetatable(initializer, 3);
|
|
448
|
+
if (!view || view.table.properties.length !== 0) return;
|
|
449
|
+
const index = view.fields.get("__index");
|
|
450
|
+
const write = view.fields.get("__newindex");
|
|
451
|
+
if (!index || !ts.isIdentifier(index) || !write || !ts.isIdentifier(write)
|
|
452
|
+
|| view.fields.get("__metatable")?.kind !== K.FalseKeyword) return;
|
|
453
|
+
return { index, reject: valueSymbol(write)?.valueDeclaration };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function readReadableNamespace(initializer, name, host, reject) {
|
|
457
|
+
if (!ts.isIdentifier(initializer)) return;
|
|
458
|
+
const symbol = valueSymbol(initializer);
|
|
459
|
+
const declaration = sdkVariable(symbol, symbol?.name, "wow/readable-api.ts");
|
|
460
|
+
const view = readOnlyApiMetatable(declaration?.initializer);
|
|
461
|
+
if (!view || view.reject !== reject) return;
|
|
462
|
+
const lookup = valueSymbol(view.index)?.valueDeclaration;
|
|
463
|
+
if (!lookup || !ts.isFunctionDeclaration(lookup) || lookup.getSourceFile() !== declaration.getSourceFile()
|
|
464
|
+
|| !lookup.body || lookup.parameters.length !== 3) return;
|
|
465
|
+
const [receiver, , key] = lookup.parameters;
|
|
466
|
+
if (!ts.isIdentifier(receiver.name) || receiver.name.text !== "this"
|
|
467
|
+
|| !(checker.getTypeAtLocation(receiver).flags & T.Void) || !ts.isIdentifier(key.name)) return;
|
|
468
|
+
|
|
469
|
+
const keySymbol = valueSymbol(key.name);
|
|
470
|
+
const statements = lookup.body.statements;
|
|
471
|
+
const exit = statements.at(-1);
|
|
472
|
+
if (!exit || !ts.isReturnStatement(exit) || !exit.expression || !ts.isElementAccessExpression(exit.expression)) return;
|
|
473
|
+
const nativeLookup = exit.expression;
|
|
474
|
+
const target = nativeLookup.expression;
|
|
475
|
+
if (!ts.isPropertyAccessExpression(target) || target.name.text !== name || !ts.isIdentifier(target.expression)
|
|
476
|
+
|| valueSymbol(target.expression) !== host || !ts.isIdentifier(nativeLookup.argumentExpression)
|
|
477
|
+
|| valueSymbol(nativeLookup.argumentExpression) !== keySymbol) return;
|
|
478
|
+
|
|
479
|
+
const keys = new Set();
|
|
480
|
+
for (const statement of statements.slice(0, -1)) {
|
|
481
|
+
if (!ts.isIfStatement(statement) || statement.elseStatement || !ts.isReturnStatement(statement.thenStatement)
|
|
482
|
+
|| !statement.thenStatement.expression || !ts.isBinaryExpression(statement.expression)) return;
|
|
483
|
+
const { left, operatorToken, right } = statement.expression;
|
|
484
|
+
if (operatorToken.kind !== K.EqualsEqualsEqualsToken || !ts.isIdentifier(left)
|
|
485
|
+
|| valueSymbol(left) !== keySymbol || !ts.isStringLiteralLike(right)) return;
|
|
486
|
+
keys.add(right.text);
|
|
487
|
+
}
|
|
488
|
+
return keys;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function readReadableOverrides(symbol) {
|
|
492
|
+
const declaration = sdkVariable(symbol, "readableApi", "wow/readable-api.ts");
|
|
493
|
+
const view = readOnlyApiMetatable(declaration?.initializer);
|
|
494
|
+
if (!view) return;
|
|
495
|
+
const { index, reject } = view;
|
|
496
|
+
if (!reject || !ts.isFunctionDeclaration(reject) || reject.getSourceFile() !== declaration.getSourceFile()
|
|
497
|
+
|| reject.body?.statements.length !== 1) return;
|
|
498
|
+
const [exit] = reject.body.statements;
|
|
499
|
+
if (!ts.isReturnStatement(exit) || !exit.expression || !ts.isCallExpression(exit.expression)
|
|
500
|
+
|| !ts.isIdentifier(exit.expression.expression) || exit.expression.expression.text !== "error"
|
|
501
|
+
|| !hostGlobal(valueSymbol(exit.expression.expression))) return;
|
|
502
|
+
const methods = sdkVariable(valueSymbol(index), "readableMethods", "wow/readable-api.ts");
|
|
503
|
+
const lookup = readableMetatable(methods?.initializer, 1);
|
|
504
|
+
const raw = lookup?.fields.get("__index");
|
|
505
|
+
if (!raw || !ts.isIdentifier(raw)) return;
|
|
506
|
+
const hostSymbol = valueSymbol(raw);
|
|
507
|
+
const host = sdkVariable(hostSymbol, "api", "wow/native.ts")?.initializer;
|
|
508
|
+
if (!host || !ts.isIdentifier(host) || host.text !== "_G" || !hostGlobal(valueSymbol(host))) return;
|
|
509
|
+
const keys = new Set();
|
|
510
|
+
const guardedReads = new Map();
|
|
511
|
+
const guardedTuples = new Map();
|
|
512
|
+
const namespaces = new Map();
|
|
513
|
+
for (const field of lookup.table.properties) {
|
|
514
|
+
if ((!ts.isMethodDeclaration(field) && !ts.isPropertyAssignment(field)) || !ts.isIdentifier(field.name)) return;
|
|
515
|
+
const name = field.name.text;
|
|
516
|
+
keys.add(name);
|
|
517
|
+
if (ts.isMethodDeclaration(field)) {
|
|
518
|
+
const forwarding = readableHostForwarding(field, hostSymbol, name);
|
|
519
|
+
if (forwarding) guardedReads.set(name, forwarding);
|
|
520
|
+
else {
|
|
521
|
+
const tuple = readableHostTupleForwarding(field, hostSymbol, name);
|
|
522
|
+
if (tuple) guardedTuples.set(name, tuple);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
if (ts.isPropertyAssignment(field)) {
|
|
526
|
+
const nested = readReadableNamespace(field.initializer, name, hostSymbol, reject);
|
|
527
|
+
if (nested) namespaces.set(name, nested);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
return { keys, guardedReads, guardedTuples, namespaces };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function readableHostForwarding(field, host, name) {
|
|
534
|
+
if (field.parameters.length !== 2 || field.body?.statements.length !== 1) return false;
|
|
535
|
+
const [receiver, rest] = field.parameters;
|
|
536
|
+
if (!ts.isIdentifier(receiver.name) || receiver.name.text !== "this"
|
|
537
|
+
|| !(checker.getTypeAtLocation(receiver).flags & T.Void)
|
|
538
|
+
|| !rest.dotDotDotToken || !ts.isIdentifier(rest.name)) return false;
|
|
539
|
+
const [exit] = field.body.statements;
|
|
540
|
+
if (!ts.isReturnStatement(exit) || !exit.expression || !ts.isCallExpression(exit.expression)
|
|
541
|
+
|| exit.expression.arguments.length !== 1 || !ts.isIdentifier(exit.expression.expression)) return false;
|
|
542
|
+
if (!canonicalRevealCall(exit.expression)) return false;
|
|
543
|
+
|
|
544
|
+
const [raw] = exit.expression.arguments;
|
|
545
|
+
if (!ts.isCallExpression(raw) || !ts.isPropertyAccessExpression(raw.expression)
|
|
546
|
+
|| raw.expression.name.text !== name || !ts.isIdentifier(raw.expression.expression)
|
|
547
|
+
|| valueSymbol(raw.expression.expression) !== host || raw.arguments.length !== 1) return false;
|
|
548
|
+
const [arg] = raw.arguments;
|
|
549
|
+
if (!ts.isSpreadElement(arg) || !ts.isIdentifier(arg.expression)
|
|
550
|
+
|| valueSymbol(arg.expression)?.valueDeclaration !== rest || raw.expression.questionDotToken) return false;
|
|
551
|
+
return raw.questionDotToken ? "optional" : "required";
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function canonicalRevealCall(node) {
|
|
555
|
+
if (!ts.isCallExpression(node) || node.flags & ts.NodeFlags.OptionalChain || node.arguments.length !== 1
|
|
556
|
+
|| !ts.isIdentifier(node.expression)) return false;
|
|
557
|
+
const reveal = valueSymbol(node.expression)?.valueDeclaration;
|
|
558
|
+
const guard = reveal && checker.resolveName("isSecret", reveal, ts.SymbolFlags.Value, false)?.valueDeclaration;
|
|
559
|
+
return canonicalReveal(reveal, guard);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function readableHostTupleForwarding(field, host, name) {
|
|
563
|
+
if (field.parameters.length < 1 || field.parameters.length > 2 || field.body?.statements.length !== 2) return;
|
|
564
|
+
const [receiver, input] = field.parameters;
|
|
565
|
+
if (!ts.isIdentifier(receiver.name) || receiver.name.text !== "this"
|
|
566
|
+
|| !(checker.getTypeAtLocation(receiver).flags & T.Void)
|
|
567
|
+
|| input && (!ts.isIdentifier(input.name) || input.dotDotDotToken || input.initializer)) return;
|
|
568
|
+
const [assignment, exit] = field.body.statements;
|
|
569
|
+
if (!ts.isVariableStatement(assignment) || !(assignment.declarationList.flags & ts.NodeFlags.Const)
|
|
570
|
+
|| assignment.declarationList.declarations.length !== 1
|
|
571
|
+
|| !ts.isReturnStatement(exit) || !exit.expression || !ts.isCallExpression(exit.expression)
|
|
572
|
+
|| !ts.isIdentifier(exit.expression.expression) || !nativeMultiFunction(valueSymbol(exit.expression.expression))) return;
|
|
573
|
+
const { name: pattern, initializer: raw } = assignment.declarationList.declarations[0];
|
|
574
|
+
if (!ts.isArrayBindingPattern(pattern) || !raw || !nativeMultiCall(raw) || !ts.isPropertyAccessExpression(raw.expression)
|
|
575
|
+
|| raw.expression.name.text !== name || valueSymbol(raw.expression.expression) !== host
|
|
576
|
+
|| raw.arguments.length !== field.parameters.length - 1
|
|
577
|
+
|| input && (!ts.isIdentifier(raw.arguments[0]) || valueSymbol(raw.arguments[0])?.valueDeclaration !== input)) return;
|
|
578
|
+
|
|
579
|
+
const guards = exit.expression.arguments;
|
|
580
|
+
if (pattern.elements.length === 0 || guards.length !== pattern.elements.length) return;
|
|
581
|
+
for (const [index, slot] of pattern.elements.entries()) {
|
|
582
|
+
const guard = guards[index];
|
|
583
|
+
if (!ts.isBindingElement(slot) || slot.initializer || slot.dotDotDotToken || !ts.isIdentifier(slot.name)
|
|
584
|
+
|| !canonicalRevealCall(guard) || !ts.isIdentifier(guard.arguments[0])
|
|
585
|
+
|| valueSymbol(guard.arguments[0])?.valueDeclaration !== slot) return;
|
|
586
|
+
}
|
|
587
|
+
return { count: guards.length, arity: raw.arguments.length };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function readableHostOverrides(source) {
|
|
591
|
+
const symbol = valueSymbol(ts.isPropertyAccessExpression(source) ? source.name : source);
|
|
592
|
+
if (symbol?.name !== "readableApi") return;
|
|
593
|
+
let overrides = readableOverrides.get(symbol);
|
|
594
|
+
if (overrides === undefined) {
|
|
595
|
+
overrides = readReadableOverrides(symbol) ?? false;
|
|
596
|
+
readableOverrides.set(symbol, overrides);
|
|
597
|
+
}
|
|
598
|
+
return overrides || undefined;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function staticMemberName(node) {
|
|
602
|
+
if (node.flags & ts.NodeFlags.OptionalChain) return;
|
|
603
|
+
if (ts.isPropertyAccessExpression(node)) return node.name.text;
|
|
604
|
+
if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression)) {
|
|
605
|
+
return node.argumentExpression.text;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function emitReadableHostProperty(source, name) {
|
|
610
|
+
const overrides = readableHostOverrides(source);
|
|
611
|
+
if (overrides && !overrides.keys.has(name)) {
|
|
612
|
+
emit("property", text(name));
|
|
613
|
+
emit("host-global", "_G");
|
|
614
|
+
return true;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
const namespace = staticMemberName(source);
|
|
618
|
+
if (namespace === undefined) return false;
|
|
619
|
+
const nested = readableHostOverrides(source.expression)?.namespaces.get(namespace);
|
|
620
|
+
if (!nested || nested.has(name)) return false;
|
|
621
|
+
|
|
622
|
+
// Keep an escaping namespace as the facade. A direct unguarded lookup has
|
|
623
|
+
// the same host receiver and key as the proven __index fallback.
|
|
624
|
+
emit("property", text(name));
|
|
625
|
+
emit("property", text(namespace));
|
|
626
|
+
emit("host-global", "_G");
|
|
627
|
+
return true;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function stableReadableArgument(node) {
|
|
631
|
+
return ts.isIdentifier(node) || ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)
|
|
632
|
+
|| node.kind === K.TrueKeyword || node.kind === K.FalseKeyword || node.kind === K.NullKeyword;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function emitReadableHostCall(node) {
|
|
636
|
+
const callee = node.expression;
|
|
637
|
+
const name = staticMemberName(callee);
|
|
638
|
+
if (name === undefined) return false;
|
|
639
|
+
const forwarding = readableHostOverrides(callee.expression)?.guardedReads.get(name);
|
|
640
|
+
if (!forwarding || !node.arguments.every(stableReadableArgument)) return false;
|
|
641
|
+
|
|
642
|
+
// The facade reads the host member after evaluating the caller's arguments.
|
|
643
|
+
// Use the ordinary dispatch for arguments that can change that member.
|
|
644
|
+
if (forwarding === "optional") {
|
|
645
|
+
emit("call", node.arguments.length + 1);
|
|
646
|
+
emit("global", "wowOptionalReadable");
|
|
647
|
+
} else {
|
|
648
|
+
emit("call", 1);
|
|
649
|
+
emit("global", "wowReadable");
|
|
650
|
+
emit("call", node.arguments.length);
|
|
651
|
+
}
|
|
652
|
+
emit("property", text(name));
|
|
653
|
+
emit("host-global", "_G");
|
|
654
|
+
callArguments(node.arguments);
|
|
655
|
+
return true;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function readableHostTuple(node) {
|
|
659
|
+
const callee = node.expression;
|
|
660
|
+
const name = staticMemberName(callee);
|
|
661
|
+
if (name === undefined || !node.arguments.every(stableReadableArgument)) return;
|
|
662
|
+
const read = readableHostOverrides(callee.expression)?.guardedTuples.get(name);
|
|
663
|
+
if (read && node.arguments.length === read.arity) return { name, count: read.count };
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function emitReadableTupleRead(node, name) {
|
|
667
|
+
emit("call", node.arguments.length);
|
|
668
|
+
emit("property", text(name));
|
|
669
|
+
emit("host-global", "_G");
|
|
670
|
+
callArguments(node.arguments);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function bindNativeTuple(names, node, predeclared) {
|
|
674
|
+
const readable = readableHostTuple(node);
|
|
675
|
+
if (readable && names.length <= readable.count) {
|
|
676
|
+
emit(predeclared ? "readable-multi-binding" : "readable-multi-local", ...names);
|
|
677
|
+
return emitReadableTupleRead(node, readable.name);
|
|
678
|
+
}
|
|
679
|
+
emit(predeclared ? "multi-binding" : "multi-local", ...names);
|
|
680
|
+
return call(node, "multi");
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function nativeClass(node) {
|
|
684
|
+
const declaration = valueSymbol(ts.isPropertyAccessExpression(node) ? node.name : node)?.valueDeclaration;
|
|
685
|
+
return declaration && ts.isClassDeclaration(declaration) && ts.isSourceFile(declaration.parent)
|
|
686
|
+
&& !declaration.getSourceFile().isDeclarationFile;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function classMethodUsesSelf(declaration) {
|
|
690
|
+
if (!declaration || !ts.isMethodDeclaration(declaration) || !ts.isClassDeclaration(declaration.parent)) return false;
|
|
691
|
+
const receiver = checker.getSignatureFromDeclaration(declaration)?.thisParameter;
|
|
692
|
+
if (receiver) return !(checker.getTypeOfSymbolAtLocation(receiver, declaration).flags & T.Void);
|
|
693
|
+
return addonMethodUsesSelf(declaration, declaration) !== false;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function nativeLuaStringCall(node, method) {
|
|
697
|
+
if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)
|
|
698
|
+
|| node.expression.name.text !== method) return false;
|
|
699
|
+
const declaration = valueSymbol(node.expression.expression)?.valueDeclaration;
|
|
700
|
+
return declaration && ts.isVariableDeclaration(declaration) && declaration.name.getText() === "luaString"
|
|
701
|
+
&& relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "wow/lua-string.ts";
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const classModifiers = [K.PublicKeyword, K.PrivateKeyword, K.ProtectedKeyword, K.ReadonlyKeyword];
|
|
705
|
+
|
|
706
|
+
function classBody(node) {
|
|
707
|
+
const fields = [];
|
|
708
|
+
const methods = [];
|
|
709
|
+
let constructor;
|
|
710
|
+
const base = node.heritageClauses?.find(clause => clause.token === K.ExtendsKeyword)?.types[0]?.expression;
|
|
711
|
+
if (base && !nativeClass(base)) unsupported(node, "Class inheritance requires a declared native base class");
|
|
712
|
+
for (const member of node.members) {
|
|
713
|
+
if (ts.isSemicolonClassElement(member)) continue;
|
|
714
|
+
if (member.modifiers?.some(modifier => !classModifiers.includes(modifier.kind)
|
|
715
|
+
&& !(modifier.kind === K.StaticKeyword && ts.isMethodDeclaration(member)))) unsupported(member);
|
|
716
|
+
if (ts.isConstructorDeclaration(member) && member.body && !constructor) constructor = member;
|
|
717
|
+
else if (ts.isPropertyDeclaration(member)) fields.push(member);
|
|
718
|
+
else if ((ts.isMethodDeclaration(member) || ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member))
|
|
719
|
+
&& member.body && !member.asteriskToken) methods.push(member);
|
|
720
|
+
else unsupported(member);
|
|
721
|
+
}
|
|
722
|
+
emit("class-body", text(node.name.text), methods.length, base ? 1 : 0);
|
|
723
|
+
if (base) expression(base);
|
|
724
|
+
for (const member of methods) {
|
|
725
|
+
const method = ts.isGetAccessorDeclaration(member) ? "getter"
|
|
726
|
+
: ts.isSetAccessorDeclaration(member) ? "setter"
|
|
727
|
+
: member.modifiers?.some(modifier => modifier.kind === K.StaticKeyword) ? "static-method" : "method";
|
|
728
|
+
const receiver = member.parameters[0];
|
|
729
|
+
const explicit = receiver && ts.isIdentifier(receiver.name) && receiver.name.text === "this";
|
|
730
|
+
const params = explicit ? member.parameters.slice(1) : member.parameters;
|
|
731
|
+
const free = ts.isMethodDeclaration(member) ? !classMethodUsesSelf(member) : explicit && receiver.type?.kind === K.VoidKeyword;
|
|
732
|
+
if (free && (method === "getter" || method === "setter")) unsupported(receiver, "A native accessor requires a receiver");
|
|
733
|
+
emit(free ? `free-${method}` : method, text(propertyName(member.name)), ...parameters(params));
|
|
734
|
+
body(member.body, params);
|
|
735
|
+
}
|
|
736
|
+
const params = constructor?.parameters ?? [];
|
|
737
|
+
const parameterFields = params.filter(param => param.modifiers?.some(modifier => classModifiers.includes(modifier.kind)));
|
|
738
|
+
const constructorParameters = base && !constructor ? [`forwarded-rest:b${++unique}`] : parameters(params);
|
|
739
|
+
emit("constructor", fields.length + parameterFields.length, ...constructorParameters);
|
|
740
|
+
statements([], parameterPrelude(params));
|
|
741
|
+
let constructorBody = constructor?.body.statements ?? [];
|
|
742
|
+
if (base) {
|
|
743
|
+
if (constructor) {
|
|
744
|
+
const first = constructorBody[0];
|
|
745
|
+
const call = first && ts.isExpressionStatement(first) && first.expression;
|
|
746
|
+
if (!call || !ts.isCallExpression(call) || call.expression.kind !== K.SuperKeyword) {
|
|
747
|
+
unsupported(constructor, "A derived constructor must start with its super call");
|
|
748
|
+
}
|
|
749
|
+
emit("super-init", call.arguments.length);
|
|
750
|
+
callArguments(call.arguments);
|
|
751
|
+
constructorBody = constructorBody.slice(1);
|
|
752
|
+
} else emit("super-forward");
|
|
753
|
+
}
|
|
754
|
+
const defineFields = options.useDefineForClassFields ?? (options.target >= ts.ScriptTarget.ES2022);
|
|
755
|
+
const fieldOperation = defineFields && base ? "define-class-field" : "class-field";
|
|
756
|
+
const parameterInitializers = () => {
|
|
757
|
+
for (const param of parameterFields) {
|
|
758
|
+
emit(fieldOperation, text(propertyName(param.name)));
|
|
759
|
+
emit("ref", identifier(param.name));
|
|
760
|
+
}
|
|
761
|
+
};
|
|
762
|
+
if (!defineFields) parameterInitializers();
|
|
763
|
+
for (const field of fields) {
|
|
764
|
+
emit(fieldOperation, text(propertyName(field.name)));
|
|
765
|
+
if (field.initializer) expression(field.initializer);
|
|
766
|
+
else emit("literal", "nil");
|
|
767
|
+
}
|
|
768
|
+
if (defineFields) parameterInitializers();
|
|
769
|
+
statements(constructorBody);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function collectionConstructor(node) {
|
|
773
|
+
if (!ts.isNewExpression(node) || !ts.isIdentifier(node.expression)) return;
|
|
774
|
+
const symbol = checker.getSymbolAtLocation(node.expression);
|
|
775
|
+
if (["Map", "Set", "WeakMap"].includes(symbol?.name) && symbol.declarations?.some(declaration =>
|
|
776
|
+
program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) return symbol.name.toLowerCase();
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function rawTableConstruction(node) {
|
|
780
|
+
if (!ts.isNewExpression(node) || !ts.isIdentifier(node.expression)) return false;
|
|
781
|
+
const symbol = valueSymbol(node.expression);
|
|
782
|
+
return ["LuaMap", "LuaSet", "LuaTable"].includes(symbol?.name) && nativeLuaDeclaration(symbol.valueDeclaration);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
const rawTableArity = { get: 1, has: 1, set: 2, add: 1, delete: 1, length: 0, isEmpty: 0 };
|
|
786
|
+
|
|
787
|
+
function rawTableMember(declaration) {
|
|
788
|
+
if (!declaration || !ts.isMethodSignature(declaration) || !nativeLuaDeclaration(declaration)) return;
|
|
789
|
+
const name = propertyName(declaration.name);
|
|
790
|
+
if (Object.hasOwn(rawTableArity, name)) return name;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
function rawTableOperation(node, declaration, discard) {
|
|
794
|
+
const operation = rawTableMember(declaration);
|
|
795
|
+
if (!operation) return false;
|
|
796
|
+
const member = node.expression;
|
|
797
|
+
const optional = ts.isPropertyAccessExpression(member) && member.questionDotToken && !node.questionDotToken
|
|
798
|
+
&& !(member.expression.flags & ts.NodeFlags.OptionalChain);
|
|
799
|
+
if (!ts.isPropertyAccessExpression(member) || !optional && node.flags & ts.NodeFlags.OptionalChain
|
|
800
|
+
|| node.arguments.length !== rawTableArity[operation] || node.arguments.some(ts.isSpreadElement)) {
|
|
801
|
+
unsupported(node, "Lua table operations require a direct call with an explicit receiver");
|
|
802
|
+
}
|
|
803
|
+
if (!optional && discard && ["set", "add", "delete"].includes(operation)) {
|
|
804
|
+
emit("table-write");
|
|
805
|
+
expression(member.expression);
|
|
806
|
+
expression(node.arguments[0]);
|
|
807
|
+
if (operation === "set") expression(node.arguments[1]);
|
|
808
|
+
else emit("literal", operation === "add" ? "true" : "nil");
|
|
809
|
+
return true;
|
|
810
|
+
}
|
|
811
|
+
if (discard) emit("effect-value");
|
|
812
|
+
emit(optional ? "optional-raw-table" : "raw-table", operation);
|
|
813
|
+
expression(member.expression);
|
|
814
|
+
for (const arg of node.arguments) expression(arg);
|
|
815
|
+
return true;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function nativeLuaIteration(node) {
|
|
819
|
+
const brand = checker.getTypeAtLocation(node).getProperty("__kumiLuaIteration");
|
|
820
|
+
if (!brand?.declarations?.length || !brand.declarations.every(nativeLuaDeclaration)) return;
|
|
821
|
+
const type = checker.getTypeOfSymbolAtLocation(brand, node);
|
|
822
|
+
if (type.isStringLiteral()) return type.value;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
function nativeMatchIterator(node) {
|
|
826
|
+
const brand = checker.getTypeAtLocation(node).getProperty("__tstlIterable");
|
|
827
|
+
return brand?.declarations?.some(declaration =>
|
|
828
|
+
relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "wow/lua-string.ts");
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function collectionReference(node) {
|
|
832
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)) {
|
|
833
|
+
const inner = collectionReference(node.expression);
|
|
834
|
+
if (inner) return inner;
|
|
835
|
+
}
|
|
836
|
+
const constructed = collectionConstructor(node);
|
|
837
|
+
if (constructed) return constructed;
|
|
838
|
+
const type = checker.getNonNullableType(checker.getTypeAtLocation(node));
|
|
839
|
+
const symbol = type.getSymbol();
|
|
840
|
+
if (["OwnedMap", "OwnedReadonlyMap", "OwnedSet", "OwnedWeakMap"].includes(symbol?.name) && symbol.declarations?.some(declaration =>
|
|
841
|
+
relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "src/owned-collections.ts")) {
|
|
842
|
+
if (symbol.name === "OwnedWeakMap") return "weakmap";
|
|
843
|
+
return symbol.name === "OwnedSet" ? "set" : "map";
|
|
844
|
+
}
|
|
845
|
+
const field = privateReadonlyInitializer(node);
|
|
846
|
+
if (field) return collectionConstructor(field);
|
|
847
|
+
if (!ts.isIdentifier(node)) return;
|
|
848
|
+
const declaration = checker.getSymbolAtLocation(node)?.valueDeclaration;
|
|
849
|
+
if (declaration && ts.isVariableDeclaration(declaration) && declaration.initializer
|
|
850
|
+
&& declaration.getSourceFile() === node.getSourceFile() && declaration.getStart() < node.getStart()
|
|
851
|
+
&& ts.isVariableDeclarationList(declaration.parent) && declaration.parent.flags & ts.NodeFlags.Const) {
|
|
852
|
+
return collectionConstructor(declaration.initializer) ?? collectionReference(declaration.initializer);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
function privateReadonlyInitializer(node) {
|
|
857
|
+
if (!ts.isPropertyAccessExpression(node) || node.flags & ts.NodeFlags.OptionalChain) return;
|
|
858
|
+
const declaration = valueSymbol(node.name)?.valueDeclaration;
|
|
859
|
+
if (declaration && ts.isPropertyDeclaration(declaration) && declaration.initializer
|
|
860
|
+
&& declaration.modifiers?.some(modifier => modifier.kind === K.PrivateKeyword)
|
|
861
|
+
&& declaration.modifiers.some(modifier => modifier.kind === K.ReadonlyKeyword)) return declaration.initializer;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
function arrayMethod(declaration) {
|
|
865
|
+
if (declaration && ts.isMethodSignature(declaration) && ts.isInterfaceDeclaration(declaration.parent)
|
|
866
|
+
&& ["Array", "ReadonlyArray"].includes(declaration.parent.name.text)
|
|
867
|
+
&& program.isSourceFileDefaultLibrary(declaration.getSourceFile())) return propertyName(declaration.name);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
function denseArrayReference(node) {
|
|
871
|
+
const type = checker.getNonNullableType(checker.getTypeAtLocation(node));
|
|
872
|
+
const item = knownTuple(type) && checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
873
|
+
if (item && knownPresent(item)) return true;
|
|
874
|
+
const field = privateReadonlyInitializer(node);
|
|
875
|
+
if (field && ts.isArrayLiteralExpression(field)) {
|
|
876
|
+
const element = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
877
|
+
if (element && knownPresent(element) && denseArrayReference(field)) return true;
|
|
878
|
+
}
|
|
879
|
+
const symbol = type.getSymbol();
|
|
880
|
+
if (["OwnedArray", "OwnedReadonlyArray", "OwnedLuaArray"].includes(symbol?.name) && symbol.declarations?.some(declaration =>
|
|
881
|
+
relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "src/owned-collections.ts")) {
|
|
882
|
+
return symbol.name !== "OwnedLuaArray";
|
|
883
|
+
}
|
|
884
|
+
if (ts.isAsExpression(node) || ts.isParenthesizedExpression(node) || ts.isSatisfiesExpression(node)) {
|
|
885
|
+
return denseArrayReference(node.expression);
|
|
886
|
+
}
|
|
887
|
+
if (ts.isBinaryExpression(node) && node.operatorToken.kind === K.QuestionQuestionToken) {
|
|
888
|
+
return denseArrayReference(node.left) && denseArrayReference(node.right);
|
|
889
|
+
}
|
|
890
|
+
if (ts.isConditionalExpression(node)) return denseArrayReference(node.whenTrue) && denseArrayReference(node.whenFalse);
|
|
891
|
+
if (collectionSnapshot(node)) return true;
|
|
892
|
+
if (ts.isArrayLiteralExpression(node)) return node.elements.every(element => {
|
|
893
|
+
if (ts.isOmittedExpression(element)) return false;
|
|
894
|
+
if (!ts.isSpreadElement(element)) return knownPresent(checker.getTypeAtLocation(element));
|
|
895
|
+
return denseMultiCall(element.expression) || denseArrayReference(element.expression);
|
|
896
|
+
});
|
|
897
|
+
if (ts.isCallExpression(node) && ["keys", "entries", "values"].some(name => standardMember(node.expression, "Object", name))) return true;
|
|
898
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "split"
|
|
899
|
+
&& stringDeclaration(checker.getResolvedSignature(node)?.getDeclaration())) return true;
|
|
900
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && !(node.flags & ts.NodeFlags.OptionalChain)
|
|
901
|
+
&& ["slice", "filter", "sort", "map"].includes(node.expression.name.text)
|
|
902
|
+
&& arrayMethod(checker.getResolvedSignature(node)?.getDeclaration()) === node.expression.name.text) {
|
|
903
|
+
const output = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
904
|
+
return (node.expression.name.text !== "map" || output && knownPresent(output)) && denseArrayReference(node.expression.expression);
|
|
905
|
+
}
|
|
906
|
+
if (!ts.isIdentifier(node)) return false;
|
|
907
|
+
const declaration = checker.getSymbolAtLocation(node)?.valueDeclaration;
|
|
908
|
+
const element = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
909
|
+
if (addonSource(node) && element?.isUnion() && element.types.some(item => item.flags & (T.Null | T.Undefined))) return false;
|
|
910
|
+
return declaration && ts.isVariableDeclaration(declaration) && declaration.initializer
|
|
911
|
+
&& declaration.getStart() < node.getStart() && declaration.parent.flags & ts.NodeFlags.Const
|
|
912
|
+
&& (denseMultiCall(declaration.initializer) || denseArrayReference(declaration.initializer));
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function nativeArrayReference(node) {
|
|
916
|
+
if (denseArrayReference(node) || nativeRest(node)) return true;
|
|
917
|
+
if (luaArrayAbiReference(node)) return true;
|
|
918
|
+
const symbol = checker.getNonNullableType(checker.getTypeAtLocation(node)).getSymbol();
|
|
919
|
+
return symbol?.name === "OwnedLuaArray" && symbol.declarations?.some(declaration =>
|
|
920
|
+
relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "src/owned-collections.ts");
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function luaArrayAbiReference(node) {
|
|
924
|
+
if (!usesLuaTableAbi(node)) return false;
|
|
925
|
+
function arrayStorage(value) {
|
|
926
|
+
const type = nativeBase(value);
|
|
927
|
+
if (type.isUnion()) return type.types.every(arrayStorage);
|
|
928
|
+
if (type.isIntersection()) return type.types.some(arrayStorage);
|
|
929
|
+
return checker.isArrayType(type) || checker.isTupleType(type);
|
|
930
|
+
}
|
|
931
|
+
return arrayStorage(checker.getNonNullableType(checker.getTypeAtLocation(node)));
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function arrayOrSetReference(node) {
|
|
935
|
+
const declaration = ts.isIdentifier(node) && valueSymbol(node)?.valueDeclaration;
|
|
936
|
+
if (!declaration || !ts.isVariableDeclaration(declaration) || declaration.getSourceFile() !== node.getSourceFile()
|
|
937
|
+
|| !(declaration.parent.flags & ts.NodeFlags.Const) || !declaration.initializer
|
|
938
|
+
|| !ts.isConditionalExpression(declaration.initializer)) return false;
|
|
939
|
+
const { whenTrue, whenFalse } = declaration.initializer;
|
|
940
|
+
return collectionReference(whenTrue) === "set" && denseArrayReference(whenFalse)
|
|
941
|
+
|| denseArrayReference(whenTrue) && collectionReference(whenFalse) === "set";
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function nativeRest(node) {
|
|
945
|
+
if (ts.isAsExpression(node) || ts.isParenthesizedExpression(node) || ts.isSatisfiesExpression(node)) {
|
|
946
|
+
return nativeRest(node.expression);
|
|
947
|
+
}
|
|
948
|
+
const declaration = ts.isIdentifier(node) && valueSymbol(node)?.valueDeclaration;
|
|
949
|
+
return declaration && ts.isParameter(declaration) && declaration.dotDotDotToken ? declaration : undefined;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function rememberForwardedRest(node) {
|
|
953
|
+
if (ts.isSpreadElement(node) && (ts.isCallExpression(node.parent) || ts.isNewExpression(node.parent))) {
|
|
954
|
+
const parameter = nativeRest(node.expression);
|
|
955
|
+
if (parameter) forwardedRest.add(parameter);
|
|
956
|
+
}
|
|
957
|
+
ts.forEachChild(node, rememberForwardedRest);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function outerExpression(node) {
|
|
961
|
+
let enclosing = node;
|
|
962
|
+
while (ts.isAsExpression(enclosing.parent) || ts.isParenthesizedExpression(enclosing.parent)
|
|
963
|
+
|| ts.isSatisfiesExpression(enclosing.parent) || ts.isNonNullExpression(enclosing.parent)) enclosing = enclosing.parent;
|
|
964
|
+
return enclosing;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
function validateForwardedRest(node) {
|
|
968
|
+
if (ts.isTypeNode(node)) return;
|
|
969
|
+
if (ts.isIdentifier(node) && forwardedRest.has(nativeRest(node))) {
|
|
970
|
+
const use = outerExpression(node);
|
|
971
|
+
const parent = use.parent;
|
|
972
|
+
if (ts.isParameter(parent) && parent.name === node || ts.isSpreadElement(parent)
|
|
973
|
+
|| ts.isForOfStatement(parent) && parent.expression === use) return;
|
|
974
|
+
if (ts.isCallExpression(parent) && parent.arguments[0] === use && ts.isIdentifier(parent.expression)
|
|
975
|
+
&& parent.expression.text === "unpack" && hostGlobal(valueSymbol(parent.expression))) return;
|
|
976
|
+
if ((ts.isElementAccessExpression(parent) || ts.isPropertyAccessExpression(parent) && parent.name.text === "length")
|
|
977
|
+
&& parent.expression === use) {
|
|
978
|
+
const access = outerExpression(parent);
|
|
979
|
+
const operation = access.parent;
|
|
980
|
+
const write = ts.isBinaryExpression(operation) && operation.left === access
|
|
981
|
+
&& operation.operatorToken.kind >= K.FirstAssignment && operation.operatorToken.kind <= K.LastAssignment
|
|
982
|
+
|| ts.isDeleteExpression(operation)
|
|
983
|
+
|| (ts.isPrefixUnaryExpression(operation) || ts.isPostfixUnaryExpression(operation))
|
|
984
|
+
&& (operation.operator === K.PlusPlusToken || operation.operator === K.MinusMinusToken);
|
|
985
|
+
if (!write) return;
|
|
986
|
+
}
|
|
987
|
+
unsupported(node, "A forwarded rest sequence may only be read or spread");
|
|
988
|
+
}
|
|
989
|
+
ts.forEachChild(node, validateForwardedRest);
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function collectionSnapshot(node) {
|
|
993
|
+
if (!ts.isArrayLiteralExpression(node) || node.elements.length !== 1 || !ts.isSpreadElement(node.elements[0])) return;
|
|
994
|
+
return spreadCollection(node.elements[0].expression);
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
function spreadCollection(source) {
|
|
998
|
+
const kind = collectionReference(source);
|
|
999
|
+
if (kind === "set" || kind === "map") return { source, field: kind === "set" ? "key" : "entry" };
|
|
1000
|
+
return collectionProjection(source, true);
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
function collectionProjection(node, includeEntries = false) {
|
|
1004
|
+
if (!ts.isCallExpression(node) || node.arguments.length || node.flags & ts.NodeFlags.OptionalChain
|
|
1005
|
+
|| !ts.isPropertyAccessExpression(node.expression)) return;
|
|
1006
|
+
const { expression: owner, name } = node.expression;
|
|
1007
|
+
if (name.text !== "keys" && name.text !== "values" && !(includeEntries && name.text === "entries")
|
|
1008
|
+
|| collectionReference(owner) !== "map") return;
|
|
1009
|
+
const declaration = checker.getResolvedSignature(node)?.getDeclaration();
|
|
1010
|
+
if (declaration && ts.isMethodSignature(declaration) && ts.isInterfaceDeclaration(declaration.parent)
|
|
1011
|
+
&& ["Map", "ReadonlyMap"].includes(declaration.parent.name.text) && program.isSourceFileDefaultLibrary(declaration.getSourceFile())) {
|
|
1012
|
+
return { source: owner, field: name.text === "keys" ? "key" : name.text === "values" ? "value" : "entry" };
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
function nativeRouterEntries(node) {
|
|
1017
|
+
if (ts.isIdentifier(node)) {
|
|
1018
|
+
const declaration = valueSymbol(node)?.valueDeclaration;
|
|
1019
|
+
return declaration && ts.isVariableDeclaration(declaration) && declaration.initializer
|
|
1020
|
+
&& declaration.getStart() < node.getStart() && declaration.parent.flags & ts.NodeFlags.Const
|
|
1021
|
+
&& nativeRouterEntries(declaration.initializer);
|
|
1022
|
+
}
|
|
1023
|
+
if (!ts.isCallExpression(node) || node.arguments.length || node.flags & ts.NodeFlags.OptionalChain) return false;
|
|
1024
|
+
const declaration = checker.getResolvedSignature(node)?.getDeclaration();
|
|
1025
|
+
return declaration && ts.isArrowFunction(declaration) && ts.isPropertyAssignment(declaration.parent)
|
|
1026
|
+
&& ts.isIdentifier(declaration.parent.name) && declaration.parent.name.text === "entries"
|
|
1027
|
+
&& relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "router/index.ts";
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
function denseValue(node) {
|
|
1031
|
+
denseType(node, checker.getTypeAtLocation(node));
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
function denseType(node, type) {
|
|
1035
|
+
if (!knownPresent(type)) unsupported(node, "A dense array value must be known to be present");
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
function knownPresent(type) {
|
|
1039
|
+
if (type.flags & T.TypeParameter) {
|
|
1040
|
+
const constraint = checker.getBaseConstraintOfType(type);
|
|
1041
|
+
if (constraint && constraint !== type) return knownPresent(constraint);
|
|
1042
|
+
}
|
|
1043
|
+
const alternatives = type.isUnion() ? type.types : [type];
|
|
1044
|
+
return alternatives.every(value => !(value.flags & (T.Null | T.Undefined | T.Any | T.Unknown | T.TypeParameter | T.Void)));
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
function nativeMultiCall(node) {
|
|
1048
|
+
return ts.isCallExpression(node) && !(node.flags & ts.NodeFlags.OptionalChain)
|
|
1049
|
+
&& hasNativeMultiReturn(node, checker.getTypeAtLocation(node));
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
function denseMultiCall(node) {
|
|
1053
|
+
if (!nativeMultiCall(node)) return false;
|
|
1054
|
+
const type = checker.getTypeAtLocation(node);
|
|
1055
|
+
const item = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
1056
|
+
return item !== undefined && knownPresent(item);
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
function numericIndex(node) {
|
|
1060
|
+
numberOperand(node, "Dense array indices must be numeric");
|
|
1061
|
+
expression(node);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
function nativeBase(type) {
|
|
1065
|
+
return checker.getBaseConstraintOfType(type) ?? type;
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
function knownTuple(value) {
|
|
1069
|
+
const type = nativeBase(value);
|
|
1070
|
+
if (type.isUnion()) return type.types.every(knownTuple);
|
|
1071
|
+
if (type.isIntersection()) return type.types.some(knownTuple);
|
|
1072
|
+
return checker.isTupleType(type);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
function knownString(value) {
|
|
1076
|
+
const type = nativeBase(value);
|
|
1077
|
+
if (type.isUnion()) return type.types.every(knownString);
|
|
1078
|
+
if (type.isIntersection()) return type.types.some(knownString);
|
|
1079
|
+
return Boolean(type.flags & T.StringLike);
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
function knownNumber(value) {
|
|
1083
|
+
const type = nativeBase(value);
|
|
1084
|
+
if (type.isUnion()) return type.types.every(knownNumber);
|
|
1085
|
+
if (type.isIntersection()) return type.types.some(knownNumber);
|
|
1086
|
+
return Boolean(type.flags & T.NumberLike);
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
function stringOrNumber(value) {
|
|
1090
|
+
const type = nativeBase(value);
|
|
1091
|
+
return type.isUnion() ? type.types.every(stringOrNumber) : knownString(type) || knownNumber(type);
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
function recordKey(value) {
|
|
1095
|
+
const type = nativeBase(value);
|
|
1096
|
+
if (type.isUnion()) return type.types.every(recordKey);
|
|
1097
|
+
if (type.isIntersection()) return type.types.some(recordKey);
|
|
1098
|
+
return Boolean(type.flags & (T.StringLike | T.NumberLike) || value.flags & T.TypeParameter
|
|
1099
|
+
&& (checker.isTypeAssignableTo(value, checker.getStringType()) || checker.isTypeAssignableTo(value, checker.getNumberType())));
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
function recordType(value) {
|
|
1103
|
+
const type = nativeBase(value);
|
|
1104
|
+
if (type.isUnionOrIntersection()) return type.types.every(recordType);
|
|
1105
|
+
return Boolean(type.flags & (T.Object | T.NonPrimitive)) && !checker.isArrayType(type) && !checker.isTupleType(type);
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function tableType(value) {
|
|
1109
|
+
const type = nativeBase(value);
|
|
1110
|
+
if (type.isUnionOrIntersection()) return type.types.every(tableType);
|
|
1111
|
+
return Boolean(type.flags & (T.Object | T.NonPrimitive)) && type.getCallSignatures().length === 0;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
function addonSource(node) {
|
|
1115
|
+
if (!addon) return false;
|
|
1116
|
+
const source = node.getSourceFile();
|
|
1117
|
+
if (!addonSourceFiles.has(source)) addonSourceFiles.set(source, addonOwnsPath(source.fileName));
|
|
1118
|
+
return addonSourceFiles.get(source);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
function addonOwnsPath(path) {
|
|
1122
|
+
const nestedWorkspace = workspaceRoot !== sdkRoot && inRoot(sdkRoot, workspaceRoot);
|
|
1123
|
+
return inRoot(workspaceRoot, path) && (nestedWorkspace || !inRoot(sdkRoot, path));
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
function usesLuaTableAbi(node) {
|
|
1127
|
+
const path = relative(sdkRoot, node.getSourceFile().fileName).replaceAll("\\", "/");
|
|
1128
|
+
return addonSource(node) || path === "form/index.ts" || addon && (
|
|
1129
|
+
path === "animation/presets.ts" || path === "validate/index.ts" || path === "router/routes.ts" || path === "router/index.ts"
|
|
1130
|
+
|| path === "wow/secure-target-visibility.ts");
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
function structuralLuaTable(node) {
|
|
1134
|
+
return usesLuaTableAbi(node) && tableType(checker.getNonNullableType(checker.getTypeAtLocation(node)));
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
function addonAny(node, type = checker.getTypeAtLocation(node)) {
|
|
1138
|
+
return addonSource(node) && Boolean(type.flags & T.Any);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
function tableIndex(node, optional = false) {
|
|
1142
|
+
let target = checker.getTypeAtLocation(node.expression);
|
|
1143
|
+
if (optional) target = checker.getNonNullableType(target);
|
|
1144
|
+
if ((!recordType(target) && !addonAny(node.expression, target)) || collectionReference(node.expression)
|
|
1145
|
+
|| !recordKey(checker.getTypeAtLocation(node.argumentExpression))) {
|
|
1146
|
+
unsupported(node, "Table indexing requires an object with known string or number keys");
|
|
1147
|
+
}
|
|
1148
|
+
expression(node.expression);
|
|
1149
|
+
expression(node.argumentExpression);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
function numberOperand(node, message) {
|
|
1153
|
+
if (!knownNumber(checker.getTypeAtLocation(node))) unsupported(node, message);
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
function update(node) {
|
|
1157
|
+
const operand = node.operand;
|
|
1158
|
+
numberOperand(operand, "An increment or decrement requires a known number");
|
|
1159
|
+
const operator = node.operator === K.PlusPlusToken ? "+" : "-";
|
|
1160
|
+
const result = ts.isPrefixUnaryExpression(node) ? "new" : "old";
|
|
1161
|
+
if (ts.isIdentifier(operand)) {
|
|
1162
|
+
return emit("update-local", operator, result, identifier(operand));
|
|
1163
|
+
}
|
|
1164
|
+
if (ts.isPropertyAccessExpression(operand) && !(operand.flags & ts.NodeFlags.OptionalChain)) {
|
|
1165
|
+
if (operand.name.text === "length" && nativeArrayReference(operand.expression)) {
|
|
1166
|
+
unsupported(operand, "Change dense array lengths explicitly");
|
|
1167
|
+
}
|
|
1168
|
+
emit("update-property", operator, result, text(operand.name.text));
|
|
1169
|
+
return expression(operand.expression);
|
|
1170
|
+
}
|
|
1171
|
+
if (ts.isElementAccessExpression(operand) && !(operand.flags & ts.NodeFlags.OptionalChain)) {
|
|
1172
|
+
emit("update-index", operator, result);
|
|
1173
|
+
return tableIndex(operand);
|
|
1174
|
+
}
|
|
1175
|
+
unsupported(operand, "An update requires a local variable or table field");
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
function assignable(node) {
|
|
1179
|
+
if (ts.isIdentifier(node)) return emit("target-local", identifier(node));
|
|
1180
|
+
if (ts.isPropertyAccessExpression(node) && !(node.flags & ts.NodeFlags.OptionalChain)) {
|
|
1181
|
+
if (collectionReference(node.expression) || node.name.text === "length" && nativeArrayReference(node.expression)) {
|
|
1182
|
+
unsupported(node, "Collection operations require an explicit write");
|
|
1183
|
+
}
|
|
1184
|
+
emit("target-property", text(node.name.text));
|
|
1185
|
+
return expression(node.expression);
|
|
1186
|
+
}
|
|
1187
|
+
if (ts.isElementAccessExpression(node) && !(node.flags & ts.NodeFlags.OptionalChain)) {
|
|
1188
|
+
if (nativeArrayReference(node.expression)) {
|
|
1189
|
+
emit("target-array-index");
|
|
1190
|
+
expression(node.expression);
|
|
1191
|
+
return numericIndex(node.argumentExpression);
|
|
1192
|
+
}
|
|
1193
|
+
emit("target-index");
|
|
1194
|
+
return tableIndex(node);
|
|
1195
|
+
}
|
|
1196
|
+
unsupported(node, "Assignment expression requires a local or property");
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
const compoundOperators = new Map([
|
|
1200
|
+
[K.PlusEqualsToken, "+"], [K.MinusEqualsToken, "-"], [K.AsteriskEqualsToken, "*"],
|
|
1201
|
+
[K.SlashEqualsToken, "/"], [K.AsteriskAsteriskEqualsToken, "^"],
|
|
1202
|
+
]);
|
|
1203
|
+
|
|
1204
|
+
function compoundAssignment(node) {
|
|
1205
|
+
const left = checker.getTypeAtLocation(node.left);
|
|
1206
|
+
const right = checker.getTypeAtLocation(node.right);
|
|
1207
|
+
let operator = compoundOperators.get(node.operatorToken.kind);
|
|
1208
|
+
if (operator === "+" && knownString(left) && knownString(right)) operator = "..";
|
|
1209
|
+
else if (!operator || !knownNumber(left) || !knownNumber(right)) {
|
|
1210
|
+
unsupported(node, "Compound assignment requires matching numeric or string operands");
|
|
1211
|
+
}
|
|
1212
|
+
emit("compound", operator);
|
|
1213
|
+
assignable(node.left);
|
|
1214
|
+
return expression(node.right);
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
function collectionMember(declaration, receiver) {
|
|
1218
|
+
if (!declaration || !ts.isMethodSignature(declaration) || !ts.isInterfaceDeclaration(declaration.parent)
|
|
1219
|
+
|| !program.isSourceFileDefaultLibrary(declaration.getSourceFile())) return false;
|
|
1220
|
+
const kind = declaration.parent.name.text.replace(/^Readonly/, "");
|
|
1221
|
+
if (kind !== "Map" && kind !== "Set" && kind !== "WeakMap") return false;
|
|
1222
|
+
const name = propertyName(declaration.name);
|
|
1223
|
+
const owned = collectionReference(receiver) === kind.toLowerCase();
|
|
1224
|
+
if (!owned && (!addonSource(receiver) || name === "entries")) {
|
|
1225
|
+
unsupported(receiver, "Collection receiver has no proven native representation");
|
|
1226
|
+
}
|
|
1227
|
+
const methods = kind === "WeakMap" ? ["get", "has", "set", "delete"]
|
|
1228
|
+
: kind === "Map" ? ["get", "has", "set", "delete", "clear", "entries"] : ["has", "add", "delete", "clear"];
|
|
1229
|
+
if (!methods.includes(name)) unsupported(receiver, `Unsupported ${kind} method: ${name}`);
|
|
1230
|
+
return true;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
const numericMembers = {
|
|
1234
|
+
Math: { floor: "math.floor", ceil: "math.ceil", abs: "math.abs", sqrt: "math.sqrt", atan2: "math.atan2",
|
|
1235
|
+
sin: "math.sin", cos: "math.cos", tan: "math.tan", atan: "math.atan", random: "math.random",
|
|
1236
|
+
exp: "math.exp", log: "math.log", pow: "math.pow",
|
|
1237
|
+
min: "numberMin", max: "numberMax", round: "numberRound" },
|
|
1238
|
+
Number: { isFinite: "numberFinite", isNaN: "numberNaN", isInteger: "numberInteger" },
|
|
1239
|
+
};
|
|
1240
|
+
|
|
1241
|
+
const arrayCallbacks = { every: "arrayEvery", some: "arraySome", forEach: "arrayForEach", map: "arrayMap",
|
|
1242
|
+
filter: "arrayFilter", find: "arrayFind", findIndex: "arrayFindIndex", flatMap: "arrayFlatMap" };
|
|
1243
|
+
|
|
1244
|
+
function arrayCallbackTarget(node, method) {
|
|
1245
|
+
if (!Object.hasOwn(arrayCallbacks, method) || node.arguments.length !== 1) return;
|
|
1246
|
+
if (!addonSource(node) && ["every", "some", "filter", "find", "findIndex"].includes(method)) {
|
|
1247
|
+
const signatures = checker.getTypeAtLocation(node.arguments[0]).getCallSignatures();
|
|
1248
|
+
if (!signatures.length || signatures.some(signature => !luaTruthValue(checker.getReturnTypeOfSignature(signature)))) {
|
|
1249
|
+
unsupported(node.arguments[0], "Array predicate must have a Lua-compatible truth value");
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
return arrayCallbacks[method];
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
function arrayChainTarget(node, declaration) {
|
|
1256
|
+
const method = arrayMethod(declaration);
|
|
1257
|
+
const count = node.arguments.length;
|
|
1258
|
+
if (method === "push" && node.arguments.every(argument => !ts.isSpreadElement(argument))) {
|
|
1259
|
+
if (addonSource(node) && luaArrayAbiReference(node.expression.expression)
|
|
1260
|
+
&& node.arguments.some(argument => !knownPresent(checker.getTypeAtLocation(argument)))) return "arrayPushSlots";
|
|
1261
|
+
for (const argument of node.arguments) denseValue(argument);
|
|
1262
|
+
return "arrayPushValues";
|
|
1263
|
+
}
|
|
1264
|
+
if (method === "includes" && count >= 1 && count <= 2) return "arrayIncludes";
|
|
1265
|
+
if (method === "indexOf" && count >= 1 && count <= 2) return "arrayIndexOf";
|
|
1266
|
+
if (method === "join" && count <= 1) return "arrayJoin";
|
|
1267
|
+
if (method === "slice" && count <= 2) return "arraySlice";
|
|
1268
|
+
if (method === "splice" && count === 1) return "arrayTakeTail";
|
|
1269
|
+
if (method === "splice" && count === 2) return "arraySplice";
|
|
1270
|
+
if (method === "reduce" && count === 2) return "arrayReduce";
|
|
1271
|
+
if (method === "pop" && count === 0) return "arrayPop";
|
|
1272
|
+
if (method === "shift" && count === 0) return "arrayShift";
|
|
1273
|
+
if (method === "reverse" && count === 0) return "arrayReverse";
|
|
1274
|
+
return arrayCallbackTarget(node, method);
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
// A namespace holding only types, such as the JSX namespace, has no runtime value.
|
|
1278
|
+
function typeOnlyNamespace(node) {
|
|
1279
|
+
if (!ts.isModuleDeclaration(node) || !node.body) return false;
|
|
1280
|
+
if (ts.isModuleDeclaration(node.body)) return typeOnlyNamespace(node.body);
|
|
1281
|
+
return ts.isModuleBlock(node.body) && node.body.statements.every(statement => ts.isInterfaceDeclaration(statement)
|
|
1282
|
+
|| ts.isTypeAliasDeclaration(statement) || typeOnlyNamespace(statement));
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
function standardMember(node, ownerName, key) {
|
|
1286
|
+
if (!ts.isPropertyAccessExpression(node) || !ts.isIdentifier(node.expression) || node.name.text !== key) return false;
|
|
1287
|
+
const owner = checker.getSymbolAtLocation(node.expression);
|
|
1288
|
+
const member = checker.getSymbolAtLocation(node.name);
|
|
1289
|
+
return owner?.name === ownerName && owner.declarations?.some(declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()))
|
|
1290
|
+
&& member?.declarations?.some(declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()));
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
const stringMethods = {
|
|
1294
|
+
charAt: ["byteCharAt", 1, 1], charCodeAt: ["byteCharCodeAt", 1, 1],
|
|
1295
|
+
endsWith: ["byteEndsWith", 1, 2], startsWith: ["byteStartsWith", 1, 2],
|
|
1296
|
+
indexOf: ["byteIndexOf", 1, 2], includes: ["byteIncludes", 1, 2],
|
|
1297
|
+
slice: ["byteSlice", 0, 2], split: ["byteSplit", 0, 1], trim: ["byteTrim", 0, 0],
|
|
1298
|
+
substring: ["byteSubstring", 1, 2], replace: ["byteReplace", 2, 2],
|
|
1299
|
+
repeat: ["byteRepeat", 1, 1], trimEnd: ["byteTrimEnd", 0, 0],
|
|
1300
|
+
toLowerCase: ["string.lower", 0, 0], toUpperCase: ["string.upper", 0, 0],
|
|
1301
|
+
};
|
|
1302
|
+
|
|
1303
|
+
function stringDeclaration(declaration) {
|
|
1304
|
+
return declaration && ts.isMethodSignature(declaration) && ts.isInterfaceDeclaration(declaration.parent)
|
|
1305
|
+
&& declaration.parent.name.text === "String" && program.isSourceFileDefaultLibrary(declaration.getSourceFile());
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
function nativeStringTarget(node, declaration, optional) {
|
|
1309
|
+
if (!ts.isPropertyAccessExpression(node.expression) || !stringDeclaration(declaration)) return;
|
|
1310
|
+
const type = checker.getTypeAtLocation(node.expression.expression);
|
|
1311
|
+
if (!knownString(optional ? checker.getNonNullableType(type) : type)) unsupported(node, "String operation requires a primitive string");
|
|
1312
|
+
const name = propertyName(declaration.name);
|
|
1313
|
+
if (!Object.hasOwn(stringMethods, name)) unsupported(node, "String method is outside the native string subset");
|
|
1314
|
+
const [target, minimum, maximum] = stringMethods[name];
|
|
1315
|
+
if (node.arguments.length < minimum || node.arguments.length > maximum) unsupported(node);
|
|
1316
|
+
if (name === "split" && node.arguments.length && !knownString(checker.getTypeAtLocation(node.arguments[0]))) {
|
|
1317
|
+
unsupported(node, "String split requires a literal-string separator");
|
|
1318
|
+
}
|
|
1319
|
+
if (name === "replace" && !node.arguments.every(arg => knownString(checker.getTypeAtLocation(arg)))) {
|
|
1320
|
+
unsupported(node, "String replace requires a plain search string and replacement");
|
|
1321
|
+
}
|
|
1322
|
+
return target;
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
function nativeStringCall(node, declaration, optional = false) {
|
|
1326
|
+
const target = nativeStringTarget(node, declaration, optional);
|
|
1327
|
+
if (!target) return false;
|
|
1328
|
+
if (!optional && fixedByteStringCall(node, target)) return true;
|
|
1329
|
+
emit(optional ? "optional-intrinsic" : "call", node.arguments.length + Number(!optional));
|
|
1330
|
+
emit("global", target);
|
|
1331
|
+
expression(node.expression.expression);
|
|
1332
|
+
for (const arg of node.arguments) expression(arg);
|
|
1333
|
+
return true;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
function literalByteOffset(node) {
|
|
1337
|
+
const negative = ts.isPrefixUnaryExpression(node) && node.operator === K.MinusToken;
|
|
1338
|
+
const number = negative ? node.operand : node;
|
|
1339
|
+
if (!ts.isNumericLiteral(number)) return;
|
|
1340
|
+
const value = Number(number.text) * (negative ? -1 : 1);
|
|
1341
|
+
// Keep converted indices inside the integer range of Lua 5.1's string API.
|
|
1342
|
+
if (Number.isInteger(value) && Math.abs(value) <= 0x7ffe) return value;
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
function fixedByteStringCall(node, target) {
|
|
1346
|
+
const receiver = node.expression.expression;
|
|
1347
|
+
if (target === "byteSlice") {
|
|
1348
|
+
const offsets = node.arguments.map(literalByteOffset);
|
|
1349
|
+
if (offsets.some(value => value === undefined)) return false;
|
|
1350
|
+
const [first = 0, last] = offsets;
|
|
1351
|
+
const start = first < 0 ? first : first + 1;
|
|
1352
|
+
if (last === undefined) emit("byte-substring", start);
|
|
1353
|
+
else emit("byte-substring", start, last < 0 ? last - 1 : last);
|
|
1354
|
+
expression(receiver);
|
|
1355
|
+
return true;
|
|
1356
|
+
}
|
|
1357
|
+
if (target !== "byteStartsWith" && target !== "byteEndsWith") return false;
|
|
1358
|
+
const [match] = node.arguments;
|
|
1359
|
+
if (node.arguments.length !== 1 || !ts.isStringLiteralLike(match)) return false;
|
|
1360
|
+
const bytes = Buffer.byteLength(match.text);
|
|
1361
|
+
if (bytes > 0x7ffe) return false;
|
|
1362
|
+
emit("binary", "==");
|
|
1363
|
+
if (target === "byteStartsWith" || bytes === 0) emit("byte-substring", 1, bytes);
|
|
1364
|
+
else emit("byte-substring", -bytes);
|
|
1365
|
+
expression(receiver);
|
|
1366
|
+
expression(match);
|
|
1367
|
+
return true;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
function nativeFixedNumber(node, declaration) {
|
|
1371
|
+
if (!ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "toFixed"
|
|
1372
|
+
|| !declaration || !ts.isMethodSignature(declaration) || !ts.isInterfaceDeclaration(declaration.parent)
|
|
1373
|
+
|| declaration.parent.name.text !== "Number" || !program.isSourceFileDefaultLibrary(declaration.getSourceFile())) return false;
|
|
1374
|
+
const target = node.expression.expression;
|
|
1375
|
+
if (!knownNumber(checker.getTypeAtLocation(target)) || node.arguments.length > 1 || node.arguments.some(ts.isSpreadElement)) {
|
|
1376
|
+
unsupported(node, "Number.toFixed requires a number and optional digits");
|
|
1377
|
+
}
|
|
1378
|
+
emit("call", 1 + node.arguments.length);
|
|
1379
|
+
emit("global", "numberFixed");
|
|
1380
|
+
expression(target);
|
|
1381
|
+
for (const arg of node.arguments) expression(arg);
|
|
1382
|
+
return true;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
function numericIntrinsic(node) {
|
|
1386
|
+
if (!ts.isPropertyAccessExpression(node) || !ts.isIdentifier(node.expression)) return;
|
|
1387
|
+
const owner = checker.getSymbolAtLocation(node.expression);
|
|
1388
|
+
const intrinsic = numericMembers[owner?.name];
|
|
1389
|
+
if (!intrinsic || !owner.declarations?.some(declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) return;
|
|
1390
|
+
if (!Object.hasOwn(intrinsic, node.name.text)) return;
|
|
1391
|
+
const member = checker.getSymbolAtLocation(node.name);
|
|
1392
|
+
if (!member?.declarations?.some(declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) return;
|
|
1393
|
+
return intrinsic[node.name.text];
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
function callArguments(args) {
|
|
1397
|
+
for (const arg of args) {
|
|
1398
|
+
if (!ts.isSpreadElement(arg)) {
|
|
1399
|
+
expression(arg);
|
|
1400
|
+
continue;
|
|
1401
|
+
}
|
|
1402
|
+
const parameter = nativeRest(arg.expression);
|
|
1403
|
+
if (parameter) emit("spread-rest", identifier(parameter.name));
|
|
1404
|
+
else {
|
|
1405
|
+
const source = arg.expression;
|
|
1406
|
+
const type = checker.getTypeAtLocation(source);
|
|
1407
|
+
if (ts.isCallExpression(source) && !(source.flags & ts.NodeFlags.OptionalChain) && hasNativeMultiReturn(source, type)) {
|
|
1408
|
+
emit("spread-native");
|
|
1409
|
+
call(source, "multi");
|
|
1410
|
+
continue;
|
|
1411
|
+
}
|
|
1412
|
+
if (!nativeArrayReference(source) && !knownTuple(type)) {
|
|
1413
|
+
unsupported(arg, "Argument spread requires a native tuple or dense sequence");
|
|
1414
|
+
}
|
|
1415
|
+
emit("spread-array");
|
|
1416
|
+
expression(source);
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
function optionalReceiverConvention(node, signature) {
|
|
1422
|
+
const declaration = signature.getDeclaration();
|
|
1423
|
+
if (!declaration && addonAny(node.expression)) return "free";
|
|
1424
|
+
const receiver = signature.thisParameter;
|
|
1425
|
+
const classMethod = declaration && ts.isMethodDeclaration(declaration) && ts.isClassDeclaration(declaration.parent);
|
|
1426
|
+
const collection = ts.isPropertyAccessExpression(node.expression) && collectionMember(declaration, node.expression.expression);
|
|
1427
|
+
const freeFunction = declaration && (ts.isFunctionDeclaration(declaration) && declaration.body || ts.isArrowFunction(declaration)
|
|
1428
|
+
|| ts.isFunctionExpression(declaration) || ts.isFunctionTypeNode(declaration));
|
|
1429
|
+
const addonMethod = addonMethodUsesSelf(node, declaration);
|
|
1430
|
+
if (!receiver && !classMethod && !collection && !freeFunction && addonMethod === undefined) {
|
|
1431
|
+
unsupported(node, "Optional calls require an explicit calling convention");
|
|
1432
|
+
}
|
|
1433
|
+
const usesSelf = receiver ? !(checker.getTypeOfSymbolAtLocation(receiver, node).flags & T.Void)
|
|
1434
|
+
: collection || (addonMethod ?? classMethod);
|
|
1435
|
+
return usesSelf ? "self" : "free";
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
function optionalCall(node, signature) {
|
|
1439
|
+
const callee = node.expression;
|
|
1440
|
+
const member = ts.isPropertyAccessExpression(callee);
|
|
1441
|
+
const optionalReceiver = member && callee.questionDotToken;
|
|
1442
|
+
const optionalMethod = node.questionDotToken;
|
|
1443
|
+
if (ts.isElementAccessExpression(callee)
|
|
1444
|
+
|| !optionalReceiver && !optionalMethod || !optionalReceiver && callee.flags & ts.NodeFlags.OptionalChain
|
|
1445
|
+
|| optionalReceiver && callee.expression.flags & ts.NodeFlags.OptionalChain) return optionalChain(node);
|
|
1446
|
+
const convention = optionalReceiverConvention(node, signature);
|
|
1447
|
+
if (member) {
|
|
1448
|
+
const mode = optionalReceiver && optionalMethod ? "both" : optionalReceiver ? "receiver" : "member";
|
|
1449
|
+
emit("optional-member-call", node.arguments.length, text(callee.name.text), convention, mode);
|
|
1450
|
+
expression(callee.expression);
|
|
1451
|
+
} else {
|
|
1452
|
+
if (convention === "self") unsupported(node, "An optional method call requires its receiver");
|
|
1453
|
+
emit("optional-call", node.arguments.length);
|
|
1454
|
+
expression(callee);
|
|
1455
|
+
}
|
|
1456
|
+
callArguments(node.arguments);
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
function optionalChain(node) {
|
|
1460
|
+
const steps = [];
|
|
1461
|
+
let target = node;
|
|
1462
|
+
while (target.flags & ts.NodeFlags.OptionalChain) {
|
|
1463
|
+
const step = target;
|
|
1464
|
+
const guard = step.questionDotToken ? 1 : 0;
|
|
1465
|
+
if (ts.isCallExpression(step)) {
|
|
1466
|
+
const signature = checker.getResolvedSignature(step);
|
|
1467
|
+
if (!signature || hasNativeMultiReturn(step, checker.getReturnTypeOfSignature(signature))) {
|
|
1468
|
+
unsupported(step, "Optional chains require single-result calls");
|
|
1469
|
+
}
|
|
1470
|
+
const callee = step.expression;
|
|
1471
|
+
if (!guard && ts.isPropertyAccessExpression(callee)) {
|
|
1472
|
+
const declaration = signature.getDeclaration();
|
|
1473
|
+
const intrinsic = nativeArrayReference(callee.expression) ? arrayChainTarget(step, declaration)
|
|
1474
|
+
: nativeStringTarget(step, declaration, true);
|
|
1475
|
+
if (intrinsic) {
|
|
1476
|
+
steps.push(() => {
|
|
1477
|
+
emit("chain-intrinsic", callee.questionDotToken ? 1 : 0, step.arguments.length);
|
|
1478
|
+
emit("global", intrinsic);
|
|
1479
|
+
callArguments(step.arguments);
|
|
1480
|
+
});
|
|
1481
|
+
target = callee.expression;
|
|
1482
|
+
continue;
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
const convention = optionalReceiverConvention(step, signature);
|
|
1486
|
+
if (ts.isPropertyAccessExpression(callee)) {
|
|
1487
|
+
steps.push(() => {
|
|
1488
|
+
emit("chain-member", callee.questionDotToken ? 1 : 0, guard, convention, step.arguments.length, text(callee.name.text));
|
|
1489
|
+
callArguments(step.arguments);
|
|
1490
|
+
});
|
|
1491
|
+
target = callee.expression;
|
|
1492
|
+
continue;
|
|
1493
|
+
}
|
|
1494
|
+
if (ts.isElementAccessExpression(callee)) {
|
|
1495
|
+
steps.push(() => {
|
|
1496
|
+
emit("chain-index-call", callee.questionDotToken ? 1 : 0, guard, convention, step.arguments.length,
|
|
1497
|
+
optionalIndexKind(callee));
|
|
1498
|
+
optionalIndexKey(callee);
|
|
1499
|
+
callArguments(step.arguments);
|
|
1500
|
+
});
|
|
1501
|
+
target = callee.expression;
|
|
1502
|
+
continue;
|
|
1503
|
+
}
|
|
1504
|
+
if (convention === "self") unsupported(step, "An optional method call requires its receiver");
|
|
1505
|
+
steps.push(() => { emit("chain-call", guard, step.arguments.length); callArguments(step.arguments); });
|
|
1506
|
+
} else if (ts.isPropertyAccessExpression(step)) {
|
|
1507
|
+
const member = valueSymbol(step.name)?.valueDeclaration;
|
|
1508
|
+
if (classMethodUsesSelf(member)) {
|
|
1509
|
+
unsupported(step, "A class method requires its receiver at the call site");
|
|
1510
|
+
}
|
|
1511
|
+
const type = checker.getNonNullableType(checker.getTypeAtLocation(step.expression));
|
|
1512
|
+
const length = step.name.text === "length" && (knownString(type) || nativeArrayReference(step.expression) || knownTuple(type));
|
|
1513
|
+
if (!length && (!tableType(type) || step.name.text === "length" && (checker.isArrayType(type) || checker.isTupleType(type)))) {
|
|
1514
|
+
unsupported(step, "Optional access requires a native property or length");
|
|
1515
|
+
}
|
|
1516
|
+
steps.push(() => emit(length ? "chain-length" : "chain-field", guard, ...(length ? [] : [text(step.name.text)])));
|
|
1517
|
+
} else if (ts.isElementAccessExpression(step)) {
|
|
1518
|
+
steps.push(() => { emit("chain-index", guard, optionalIndexKind(step)); optionalIndexKey(step); });
|
|
1519
|
+
} else unsupported(step, "Unsupported part of optional chain");
|
|
1520
|
+
target = step.expression;
|
|
1521
|
+
}
|
|
1522
|
+
emit("optional-chain", steps.length);
|
|
1523
|
+
expression(target);
|
|
1524
|
+
for (const step of steps.reverse()) step();
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
function optionalIndexKind(node) {
|
|
1528
|
+
const type = checker.getNonNullableType(checker.getTypeAtLocation(node.expression));
|
|
1529
|
+
if (nativeArrayReference(node.expression) || knownTuple(type)) return "array";
|
|
1530
|
+
if ((!recordType(type) && !addonAny(node.expression, type)) || collectionReference(node.expression)
|
|
1531
|
+
|| !recordKey(checker.getTypeAtLocation(node.argumentExpression))) {
|
|
1532
|
+
unsupported(node, "Table indexing requires an object with known string or number keys");
|
|
1533
|
+
}
|
|
1534
|
+
return "table";
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
function optionalIndexKey(node) {
|
|
1538
|
+
if (optionalIndexKind(node) === "array") numericIndex(node.argumentExpression);
|
|
1539
|
+
else expression(node.argumentExpression);
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
function nativeReceiverCall(node, declaration) {
|
|
1543
|
+
if (!ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "call"
|
|
1544
|
+
|| !declaration || !ts.isMethodSignature(declaration) || !ts.isInterfaceDeclaration(declaration.parent)
|
|
1545
|
+
|| !["Function", "CallableFunction"].includes(declaration.parent.name.text)
|
|
1546
|
+
|| !program.isSourceFileDefaultLibrary(declaration.getSourceFile())) return false;
|
|
1547
|
+
const callee = node.expression;
|
|
1548
|
+
const target = callee.expression;
|
|
1549
|
+
if (target.flags & ts.NodeFlags.OptionalChain) unsupported(node, "Bind the optional callback before calling it with a receiver");
|
|
1550
|
+
const optional = Boolean(callee.questionDotToken);
|
|
1551
|
+
const type = checker.getTypeAtLocation(target);
|
|
1552
|
+
const signatures = (optional ? checker.getNonNullableType(type) : type).getCallSignatures();
|
|
1553
|
+
if (!node.arguments.length || ts.isSpreadElement(node.arguments[0]) || !signatures.length
|
|
1554
|
+
|| signatures.some(signature => {
|
|
1555
|
+
if (!signature.thisParameter) return true;
|
|
1556
|
+
const receiver = checker.getTypeOfSymbolAtLocation(signature.thisParameter, target);
|
|
1557
|
+
return receiver.flags & T.Void || !addonSource(node) && !tableType(receiver);
|
|
1558
|
+
})) {
|
|
1559
|
+
unsupported(node, "Function.call requires a callable with an explicit table receiver");
|
|
1560
|
+
}
|
|
1561
|
+
emit(optional ? "optional-call" : "call", node.arguments.length);
|
|
1562
|
+
expression(target);
|
|
1563
|
+
callArguments(node.arguments);
|
|
1564
|
+
return true;
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
function hasNativeMultiReturn(node, type) {
|
|
1568
|
+
const brand = type.getProperty("__tstlMultiReturn");
|
|
1569
|
+
if (!brand) return false;
|
|
1570
|
+
if (brand.declarations?.length && brand.declarations.every(nativeLuaDeclaration)) return true;
|
|
1571
|
+
const generated = ts.resolveModuleName("@kumi/wow-generated", node.getSourceFile().fileName, options, ts.sys)
|
|
1572
|
+
.resolvedModule?.resolvedFileName;
|
|
1573
|
+
const generatedPath = generated && realpathSync(generated);
|
|
1574
|
+
if (!brand.declarations?.length || !brand.declarations.every(declaration =>
|
|
1575
|
+
nativeLuaDeclaration(declaration) || generatedPath && realpathSync(declaration.getSourceFile().fileName) === generatedPath)) {
|
|
1576
|
+
unsupported(node, "Lua multiple returns require the SDK generated ABI declaration");
|
|
1577
|
+
}
|
|
1578
|
+
return true;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
function returnValue(node, owner) {
|
|
1582
|
+
if (node && owner) {
|
|
1583
|
+
const signature = checker.getSignatureFromDeclaration(owner);
|
|
1584
|
+
if (signature && hasNativeMultiReturn(node, checker.getReturnTypeOfSignature(signature))) {
|
|
1585
|
+
while (ts.isParenthesizedExpression(node)) node = node.expression;
|
|
1586
|
+
if (ts.isConditionalExpression(node)) {
|
|
1587
|
+
emit("if", 1);
|
|
1588
|
+
booleanCondition(node.condition);
|
|
1589
|
+
emit("block", 1);
|
|
1590
|
+
returnValue(node.whenTrue, owner);
|
|
1591
|
+
emit("block", 1);
|
|
1592
|
+
return returnValue(node.whenFalse, owner);
|
|
1593
|
+
}
|
|
1594
|
+
if (!ts.isCallExpression(node) || node.flags & ts.NodeFlags.OptionalChain) {
|
|
1595
|
+
unsupported(node, "Return a native multiple result directly");
|
|
1596
|
+
}
|
|
1597
|
+
if (ts.isIdentifier(node.expression) && nativeMultiFunction(valueSymbol(node.expression))) {
|
|
1598
|
+
emit("return-multi", node.arguments.length);
|
|
1599
|
+
return callArguments(node.arguments);
|
|
1600
|
+
}
|
|
1601
|
+
emit("return-native");
|
|
1602
|
+
return call(node, "multi");
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
emit("return");
|
|
1606
|
+
if (node) return expression(node);
|
|
1607
|
+
emit("literal", "nil");
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
function call(node, mode = "scalar") {
|
|
1611
|
+
const signature = checker.getResolvedSignature(node);
|
|
1612
|
+
if (!signature) unsupported(node, "Call has no resolved signature");
|
|
1613
|
+
const brand = hasNativeMultiReturn(node, checker.getReturnTypeOfSignature(signature));
|
|
1614
|
+
if (mode === "multi" && !brand) unsupported(node, "Array assignment requires a declared Lua multiple return");
|
|
1615
|
+
if (mode === "scalar" && brand) unsupported(node, "Destructure a Lua multiple return in a single declaration");
|
|
1616
|
+
const receiver = signature.thisParameter;
|
|
1617
|
+
const declaration = signature.getDeclaration();
|
|
1618
|
+
if (rawTableOperation(node, declaration, false)) return;
|
|
1619
|
+
if (nativeReceiverCall(node, declaration)) return;
|
|
1620
|
+
if (standardMember(node.expression, "Array", "from")) {
|
|
1621
|
+
const [source, map] = node.arguments;
|
|
1622
|
+
if (node.arguments.length === 1) {
|
|
1623
|
+
const projection = collectionProjection(source);
|
|
1624
|
+
if (projection) {
|
|
1625
|
+
emit("collection-snapshot", projection.field);
|
|
1626
|
+
return expression(projection.source);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
if (node.arguments.length === 2 && ts.isObjectLiteralExpression(source) && source.properties.length === 1) {
|
|
1630
|
+
const [length] = source.properties;
|
|
1631
|
+
if (ts.isPropertyAssignment(length) && (ts.isIdentifier(length.name) || ts.isStringLiteral(length.name))
|
|
1632
|
+
&& length.name.text === "length" && knownNumber(checker.getTypeAtLocation(length.initializer)) && !ts.isSpreadElement(map)) {
|
|
1633
|
+
emit("call", 2);
|
|
1634
|
+
emit("global", "arrayFromLength");
|
|
1635
|
+
expression(length.initializer);
|
|
1636
|
+
return expression(map);
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
if (node.arguments.length === 2 && !ts.isSpreadElement(source) && !ts.isSpreadElement(map)) {
|
|
1640
|
+
const collection = collectionReference(source);
|
|
1641
|
+
if (collection === "map" || collection === "set") {
|
|
1642
|
+
emit("map-collection", collection);
|
|
1643
|
+
expression(source);
|
|
1644
|
+
return expression(map);
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
if (node.flags & ts.NodeFlags.OptionalChain) {
|
|
1649
|
+
if (ts.isPropertyAccessExpression(node.expression) && node.expression.questionDotToken && !node.questionDotToken
|
|
1650
|
+
&& !(node.expression.expression.flags & ts.NodeFlags.OptionalChain)) {
|
|
1651
|
+
if (nativeStringCall(node, declaration, true)) return;
|
|
1652
|
+
const target = node.expression.expression;
|
|
1653
|
+
if (nativeArrayReference(target)) {
|
|
1654
|
+
const intrinsic = arrayChainTarget(node, declaration);
|
|
1655
|
+
if (intrinsic) {
|
|
1656
|
+
emit("optional-intrinsic", node.arguments.length);
|
|
1657
|
+
emit("global", intrinsic);
|
|
1658
|
+
expression(target);
|
|
1659
|
+
return callArguments(node.arguments);
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
return optionalCall(node, signature);
|
|
1664
|
+
}
|
|
1665
|
+
if (mode === "scalar" && emitReadableHostCall(node)) return;
|
|
1666
|
+
if (standardMember(node.expression, "Object", "defineProperties") && node.arguments.length === 2
|
|
1667
|
+
&& relative(sdkRoot, realpathSync(node.getSourceFile().fileName)).replaceAll("\\", "/") === "state/setup-store-view.ts") {
|
|
1668
|
+
emit("call", 2);
|
|
1669
|
+
emit("global", "setupStoreView");
|
|
1670
|
+
return callArguments(node.arguments);
|
|
1671
|
+
}
|
|
1672
|
+
if (nativeStringCall(node, declaration)) return;
|
|
1673
|
+
if (nativeFixedNumber(node, declaration)) return;
|
|
1674
|
+
if (standardMember(node.expression, "Array", "isArray") && node.arguments.length === 1) {
|
|
1675
|
+
emit("call", 1);
|
|
1676
|
+
emit("global", "isLuaArray");
|
|
1677
|
+
return expression(node.arguments[0]);
|
|
1678
|
+
}
|
|
1679
|
+
if (["keys", "entries", "values"].some(name => standardMember(node.expression, "Object", name)) && node.arguments.length === 1) {
|
|
1680
|
+
const target = node.arguments[0];
|
|
1681
|
+
const iteration = nativeLuaIteration(target);
|
|
1682
|
+
const rawTable = iteration === "pairs" || iteration === "keys" && node.expression.name.text === "keys";
|
|
1683
|
+
if (!rawTable && (!(recordType(checker.getTypeAtLocation(target)) || nativeArrayReference(target)) || collectionReference(target))) {
|
|
1684
|
+
unsupported(target, "Own key enumeration requires a record or proven native sequence");
|
|
1685
|
+
}
|
|
1686
|
+
emit(`object-${node.expression.name.text}`);
|
|
1687
|
+
return expression(target);
|
|
1688
|
+
}
|
|
1689
|
+
if (standardMember(node.expression, "Object", "fromEntries") && node.arguments.length === 1) {
|
|
1690
|
+
const [source] = node.arguments;
|
|
1691
|
+
const item = checker.getIndexTypeOfType(checker.getTypeAtLocation(source), ts.IndexKind.Number);
|
|
1692
|
+
if (!nativeArrayReference(source) || !item || !knownTuple(item)) {
|
|
1693
|
+
unsupported(source, "Object.fromEntries requires native pairs");
|
|
1694
|
+
}
|
|
1695
|
+
emit("call", 1);
|
|
1696
|
+
emit("global", "objectFromEntries");
|
|
1697
|
+
return expression(source);
|
|
1698
|
+
}
|
|
1699
|
+
if (standardMember(node.expression, "Object", "getOwnPropertyDescriptor") && node.arguments.length === 2) {
|
|
1700
|
+
const [target, key] = node.arguments;
|
|
1701
|
+
if (!tableType(checker.getTypeAtLocation(target)) || !knownString(checker.getTypeAtLocation(key))) {
|
|
1702
|
+
unsupported(node, "Own descriptor lookup requires a table and a string key");
|
|
1703
|
+
}
|
|
1704
|
+
emit("object-descriptor");
|
|
1705
|
+
expression(target);
|
|
1706
|
+
return expression(key);
|
|
1707
|
+
}
|
|
1708
|
+
if (standardMember(node.expression, "Object", "assign") && node.arguments.length >= 2) {
|
|
1709
|
+
const [target, ...sources] = node.arguments;
|
|
1710
|
+
const proven = sources.every(nativeRecord);
|
|
1711
|
+
if ((!tableType(checker.getTypeAtLocation(target)) && !addonAny(target))
|
|
1712
|
+
|| !proven && !sources.every(value => nativeRecord(value) || structuralLuaTable(value) || addonAny(value))) {
|
|
1713
|
+
unsupported(node, "Object.assign requires a table target and proven native source records");
|
|
1714
|
+
}
|
|
1715
|
+
emit("call", node.arguments.length);
|
|
1716
|
+
emit("global", !proven ? "copyStructuralSources" : node.arguments.length === 2 ? "copyFields" : "copyAllFields");
|
|
1717
|
+
for (const arg of node.arguments) expression(arg);
|
|
1718
|
+
return;
|
|
1719
|
+
}
|
|
1720
|
+
const number = numericIntrinsic(node.expression);
|
|
1721
|
+
if (number) {
|
|
1722
|
+
const numericPair = (number === "numberMin" || number === "numberMax") && node.arguments.length === 2
|
|
1723
|
+
&& node.arguments.every(argument => !ts.isSpreadElement(argument) && knownNumber(checker.getTypeAtLocation(argument)));
|
|
1724
|
+
emit("call", node.arguments.length);
|
|
1725
|
+
emit("global", numericPair ? number + "2" : number);
|
|
1726
|
+
callArguments(node.arguments);
|
|
1727
|
+
return;
|
|
1728
|
+
}
|
|
1729
|
+
const method = arrayMethod(declaration);
|
|
1730
|
+
if (ts.isPropertyAccessExpression(node.expression) && method !== undefined) {
|
|
1731
|
+
const target = node.expression.expression;
|
|
1732
|
+
if (!denseArrayReference(target) && !luaArrayAbiReference(target)) {
|
|
1733
|
+
const type = checker.getTypeAtLocation(target);
|
|
1734
|
+
const item = knownTuple(type) && checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
1735
|
+
if (!item || !knownPresent(item)) unsupported(target, "Array operation requires a proven dense representation");
|
|
1736
|
+
}
|
|
1737
|
+
if (method === "push" && addonSource(node) && luaArrayAbiReference(target)
|
|
1738
|
+
&& node.arguments.every(argument => !ts.isSpreadElement(argument))
|
|
1739
|
+
&& node.arguments.some(argument => !knownPresent(checker.getTypeAtLocation(argument)))) {
|
|
1740
|
+
emit("call", node.arguments.length + 1);
|
|
1741
|
+
emit("global", "arrayPushSlots");
|
|
1742
|
+
expression(target);
|
|
1743
|
+
return callArguments(node.arguments);
|
|
1744
|
+
}
|
|
1745
|
+
if (method === "push" && node.arguments.length === 1) {
|
|
1746
|
+
if (ts.isSpreadElement(node.arguments[0])) {
|
|
1747
|
+
const source = node.arguments[0].expression;
|
|
1748
|
+
if (!nativeArrayReference(source)) unsupported(source, "Array push spread requires a native sequence");
|
|
1749
|
+
emit("call", 2);
|
|
1750
|
+
emit("global", "arrayPushAll");
|
|
1751
|
+
expression(target);
|
|
1752
|
+
return expression(source);
|
|
1753
|
+
}
|
|
1754
|
+
denseValue(node.arguments[0]);
|
|
1755
|
+
emit("array-push");
|
|
1756
|
+
expression(target);
|
|
1757
|
+
return expression(node.arguments[0]);
|
|
1758
|
+
}
|
|
1759
|
+
if (method === "push" && node.arguments.every(argument => !ts.isSpreadElement(argument))) {
|
|
1760
|
+
for (const argument of node.arguments) denseValue(argument);
|
|
1761
|
+
emit("call", node.arguments.length + 1);
|
|
1762
|
+
emit("global", "arrayPushValues");
|
|
1763
|
+
expression(target);
|
|
1764
|
+
return callArguments(node.arguments);
|
|
1765
|
+
}
|
|
1766
|
+
if (method === "pop" && node.arguments.length === 0) {
|
|
1767
|
+
emit("array-pop");
|
|
1768
|
+
return expression(target);
|
|
1769
|
+
}
|
|
1770
|
+
if ((method === "shift" || method === "reverse") && node.arguments.length === 0) {
|
|
1771
|
+
emit("call", 1);
|
|
1772
|
+
emit("global", method === "shift" ? "arrayShift" : "arrayReverse");
|
|
1773
|
+
return expression(target);
|
|
1774
|
+
}
|
|
1775
|
+
if (method === "concat" && node.arguments.every(argument => !ts.isSpreadElement(argument) && nativeArrayReference(argument))) {
|
|
1776
|
+
emit("call", node.arguments.length + 1);
|
|
1777
|
+
emit("global", "arrayConcat");
|
|
1778
|
+
expression(target);
|
|
1779
|
+
return callArguments(node.arguments);
|
|
1780
|
+
}
|
|
1781
|
+
if (method === "unshift" && node.arguments.every(argument => !ts.isSpreadElement(argument))) {
|
|
1782
|
+
for (const argument of node.arguments) denseValue(argument);
|
|
1783
|
+
emit("call", node.arguments.length + 1);
|
|
1784
|
+
emit("global", "arrayUnshift");
|
|
1785
|
+
expression(target);
|
|
1786
|
+
return callArguments(node.arguments);
|
|
1787
|
+
}
|
|
1788
|
+
if (method === "reduce" && node.arguments.length === 2) {
|
|
1789
|
+
emit("call", 3);
|
|
1790
|
+
emit("global", "arrayReduce");
|
|
1791
|
+
expression(target);
|
|
1792
|
+
return callArguments(node.arguments);
|
|
1793
|
+
}
|
|
1794
|
+
if (method === "includes" && (node.arguments.length === 1 || node.arguments.length === 2)
|
|
1795
|
+
|| method === "join" && node.arguments.length <= 1) {
|
|
1796
|
+
emit("call", node.arguments.length + 1);
|
|
1797
|
+
emit("global", method === "includes" ? "arrayIncludes" : "arrayJoin");
|
|
1798
|
+
expression(target);
|
|
1799
|
+
for (const argument of node.arguments) expression(argument);
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
if (method === "indexOf" && (node.arguments.length === 1 || node.arguments.length === 2)
|
|
1803
|
+
|| method === "slice" && node.arguments.length <= 2) {
|
|
1804
|
+
emit("call", node.arguments.length + 1);
|
|
1805
|
+
emit("global", method === "indexOf" ? "arrayIndexOf" : "arraySlice");
|
|
1806
|
+
expression(target);
|
|
1807
|
+
for (const argument of node.arguments) expression(argument);
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
1810
|
+
if (method === "splice" && node.arguments.length > 0
|
|
1811
|
+
|| method === "sort" && node.arguments.length <= 1) {
|
|
1812
|
+
if (method === "sort" && (!node.arguments.length || !checker.getTypeAtLocation(node.arguments[0]).getCallSignatures().length)) {
|
|
1813
|
+
const item = checker.getIndexTypeOfType(checker.getTypeAtLocation(target), ts.IndexKind.Number);
|
|
1814
|
+
if (!item || !knownString(item)) unsupported(target, "Default sorting requires a dense string sequence");
|
|
1815
|
+
}
|
|
1816
|
+
if (method === "splice") for (const value of node.arguments.slice(2)) denseValue(value);
|
|
1817
|
+
let compareUsesSelf = false;
|
|
1818
|
+
const [comparator] = node.arguments;
|
|
1819
|
+
if (method === "sort" && comparator) {
|
|
1820
|
+
const conventions = checker.getTypeAtLocation(comparator).getCallSignatures().map(signature => signature.thisParameter
|
|
1821
|
+
&& !(checker.getTypeOfSymbolAtLocation(signature.thisParameter, comparator).flags & T.Void));
|
|
1822
|
+
compareUsesSelf = Boolean(conventions[0]);
|
|
1823
|
+
if (conventions.some(convention => Boolean(convention) !== compareUsesSelf)) {
|
|
1824
|
+
unsupported(comparator, "Array sorting requires one comparator calling convention");
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
emit("call", node.arguments.length + 1 + Number(compareUsesSelf));
|
|
1828
|
+
emit("global", method === "sort" ? "arraySort" : node.arguments.length === 1 ? "arrayTakeTail"
|
|
1829
|
+
: node.arguments.length === 2 ? "arraySplice" : "arraySpliceInsert");
|
|
1830
|
+
expression(target);
|
|
1831
|
+
for (const argument of node.arguments) expression(argument);
|
|
1832
|
+
if (compareUsesSelf) emit("literal", "true");
|
|
1833
|
+
return;
|
|
1834
|
+
}
|
|
1835
|
+
const callback = arrayCallbackTarget(node, method);
|
|
1836
|
+
if (callback) {
|
|
1837
|
+
emit("call", 2);
|
|
1838
|
+
emit("global", callback);
|
|
1839
|
+
expression(target);
|
|
1840
|
+
return expression(node.arguments[0]);
|
|
1841
|
+
}
|
|
1842
|
+
unsupported(node, "Array method is outside the native dense subset");
|
|
1843
|
+
}
|
|
1844
|
+
let callee = node.expression;
|
|
1845
|
+
while (ts.isNonNullExpression(callee)) callee = callee.expression;
|
|
1846
|
+
if (ts.isPropertyAccessExpression(callee) && callee.name.text === "next" && !node.arguments.length
|
|
1847
|
+
&& nativeRouterEntries(callee.expression)) {
|
|
1848
|
+
emit("method", 0, text("next"));
|
|
1849
|
+
return expression(callee.expression);
|
|
1850
|
+
}
|
|
1851
|
+
const member = ts.isPropertyAccessExpression(callee) && collectionMember(declaration, callee.expression);
|
|
1852
|
+
const classMethod = declaration && ts.isMethodDeclaration(declaration) && ts.isClassDeclaration(declaration.parent);
|
|
1853
|
+
const addonMethod = addonMethodUsesSelf(node, declaration);
|
|
1854
|
+
if (member && callee.name.text === "entries" && node.arguments.length === 0) {
|
|
1855
|
+
emit("map-entry-iterator");
|
|
1856
|
+
return expression(callee.expression);
|
|
1857
|
+
}
|
|
1858
|
+
if (!receiver && !member && !classMethod && addonMethod === undefined && declaration
|
|
1859
|
+
&& (ts.isMethodSignature(declaration) || ts.isMethodDeclaration(declaration))) {
|
|
1860
|
+
unsupported(node, "Method signatures require an explicit this type");
|
|
1861
|
+
}
|
|
1862
|
+
const usesSelf = receiver ? !(checker.getTypeOfSymbolAtLocation(receiver, node).flags & T.Void)
|
|
1863
|
+
: member || (addonMethod ?? classMethod);
|
|
1864
|
+
if (usesSelf) {
|
|
1865
|
+
if (ts.isElementAccessExpression(callee) && !(callee.flags & ts.NodeFlags.OptionalChain)) {
|
|
1866
|
+
emit("method-index", node.arguments.length);
|
|
1867
|
+
tableIndex(callee);
|
|
1868
|
+
return callArguments(node.arguments);
|
|
1869
|
+
}
|
|
1870
|
+
if (!ts.isPropertyAccessExpression(callee) || callee.flags & ts.NodeFlags.OptionalChain) {
|
|
1871
|
+
unsupported(node, "A native method call requires its explicit receiver");
|
|
1872
|
+
}
|
|
1873
|
+
emit("method", node.arguments.length, text(callee.name.text));
|
|
1874
|
+
expression(callee.expression);
|
|
1875
|
+
} else {
|
|
1876
|
+
emit("call", node.arguments.length);
|
|
1877
|
+
expression(node.expression);
|
|
1878
|
+
}
|
|
1879
|
+
callArguments(node.arguments);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
function addonMethodUsesSelf(use, declaration) {
|
|
1883
|
+
if (!declaration || !addonSource(use)
|
|
1884
|
+
|| !ts.isMethodSignature(declaration) && !ts.isMethodDeclaration(declaration)) return;
|
|
1885
|
+
if (!addonSource(declaration) && !inRoot(sdkRoot, declaration.getSourceFile().fileName)) return;
|
|
1886
|
+
if (ts.getJSDocTags(declaration).some(tag => tag.tagName.text === "noSelf")) return false;
|
|
1887
|
+
let owner = declaration.parent;
|
|
1888
|
+
while (owner && !ts.isSourceFile(owner)) {
|
|
1889
|
+
if (ts.isClassDeclaration(owner) || ts.isClassExpression(owner) || ts.isInterfaceDeclaration(owner)) {
|
|
1890
|
+
return !ts.getJSDocTags(owner).some(tag => tag.tagName.text === "noSelf");
|
|
1891
|
+
}
|
|
1892
|
+
owner = owner.parent;
|
|
1893
|
+
}
|
|
1894
|
+
return true;
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
function objectMethodHasSelf(node) {
|
|
1898
|
+
const key = propertyName(node.name);
|
|
1899
|
+
const method = checker.getSignatureFromDeclaration(node);
|
|
1900
|
+
const context = checker.getContextualType(node.parent);
|
|
1901
|
+
const contextual = (context && checker.getTypeOfPropertyOfType(context, key))
|
|
1902
|
+
?? (addonSource(node) ? checker.getContextualTypeForObjectLiteralElement(node) : undefined);
|
|
1903
|
+
const candidates = method?.thisParameter ? [method] : contextual?.getCallSignatures();
|
|
1904
|
+
if (addonSource(node)) {
|
|
1905
|
+
const signatures = candidates?.length ? candidates : [method];
|
|
1906
|
+
const conventions = signatures.map(signature => {
|
|
1907
|
+
if (signature?.thisParameter) {
|
|
1908
|
+
const receiver = checker.getTypeOfSymbolAtLocation(signature.thisParameter, node);
|
|
1909
|
+
return receiver.flags & T.Void ? false : tableType(receiver) ? true : undefined;
|
|
1910
|
+
}
|
|
1911
|
+
const declaration = signature?.getDeclaration();
|
|
1912
|
+
return addonMethodUsesSelf(node, declaration);
|
|
1913
|
+
});
|
|
1914
|
+
const [convention] = conventions;
|
|
1915
|
+
if (convention !== undefined && conventions.every(value => value === convention)) return convention;
|
|
1916
|
+
}
|
|
1917
|
+
if (!candidates?.length || candidates.some(signature => !signature.thisParameter)) {
|
|
1918
|
+
unsupported(node, "Object method requires a declared or contextual this type");
|
|
1919
|
+
}
|
|
1920
|
+
const receivers = candidates.map(signature => checker.getTypeOfSymbolAtLocation(signature.thisParameter, node));
|
|
1921
|
+
if (receivers.every(type => type.flags & T.Void)) return false;
|
|
1922
|
+
if (receivers.every(tableType)) return true;
|
|
1923
|
+
unsupported(node, "Object method requires one calling convention and a known table receiver");
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
function objectMethod(node) {
|
|
1927
|
+
if (!node.body || node.asteriskToken || node.modifiers?.length) unsupported(node);
|
|
1928
|
+
const usesSelf = objectMethodHasSelf(node);
|
|
1929
|
+
emit("field", text(propertyName(node.name)));
|
|
1930
|
+
emit(usesSelf ? "object-method" : "arrow", ...parameters(node.parameters, usesSelf));
|
|
1931
|
+
body(node.body, node.parameters);
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
function functionHasSelf(node) {
|
|
1935
|
+
const [receiver] = node.parameters;
|
|
1936
|
+
if (receiver && ts.isIdentifier(receiver.name) && receiver.name.text === "this") {
|
|
1937
|
+
const type = checker.getTypeAtLocation(receiver);
|
|
1938
|
+
return !(type.flags & T.Void) && (addonSource(node) || tableType(type));
|
|
1939
|
+
}
|
|
1940
|
+
if (!ts.isFunctionExpression(node)) return false;
|
|
1941
|
+
const type = checker.getContextualType(node);
|
|
1942
|
+
const signatures = type && checker.getNonNullableType(type).getCallSignatures();
|
|
1943
|
+
return signatures?.length && signatures.every(signature => signature.thisParameter
|
|
1944
|
+
&& tableType(checker.getTypeOfSymbolAtLocation(signature.thisParameter, node)));
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
function arrowReceivesSelf(node) {
|
|
1948
|
+
const assigned = outerExpression(node);
|
|
1949
|
+
const assignment = assigned.parent;
|
|
1950
|
+
if (!ts.isBinaryExpression(assignment) || assignment.operatorToken.kind !== K.EqualsToken || assignment.right !== assigned
|
|
1951
|
+
|| !ts.isPropertyAccessExpression(assignment.left) && !ts.isElementAccessExpression(assignment.left)) return false;
|
|
1952
|
+
const type = checker.getContextualType(node);
|
|
1953
|
+
const signatures = type && checker.getNonNullableType(type).getCallSignatures();
|
|
1954
|
+
if (!signatures?.length) return false;
|
|
1955
|
+
const conventions = signatures.map(signature => {
|
|
1956
|
+
if (!signature.thisParameter) return false;
|
|
1957
|
+
const receiver = checker.getTypeOfSymbolAtLocation(signature.thisParameter, node);
|
|
1958
|
+
return !(receiver.flags & T.Void);
|
|
1959
|
+
});
|
|
1960
|
+
if (conventions.some(self => self !== conventions[0])) unsupported(node, "An arrow requires one receiver convention");
|
|
1961
|
+
return conventions[0];
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
function isOwnedRecord(type) {
|
|
1965
|
+
const alias = type.aliasSymbol;
|
|
1966
|
+
return alias?.name === "OwnedRecord" && alias.declarations?.some(declaration =>
|
|
1967
|
+
relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "src/owned-collections.ts");
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
function nativeRecord(node) {
|
|
1971
|
+
if (isOwnedRecord(checker.getTypeAtLocation(node))) return true;
|
|
1972
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
|
|
1973
|
+
return nativeRecord(node.expression);
|
|
1974
|
+
}
|
|
1975
|
+
if (ts.isObjectLiteralExpression(node)) return true;
|
|
1976
|
+
if (ts.isCallExpression(node) && standardMember(node.expression, "Object", "assign")) {
|
|
1977
|
+
return node.arguments.length >= 2 && node.arguments.every(nativeRecord);
|
|
1978
|
+
}
|
|
1979
|
+
if (ts.isCallExpression(node) && standardMember(node.expression, "Object", "fromEntries")) return node.arguments.length === 1;
|
|
1980
|
+
if (ts.isIdentifier(node)) {
|
|
1981
|
+
const declaration = checker.getSymbolAtLocation(node)?.valueDeclaration;
|
|
1982
|
+
if (declaration && ts.isBindingElement(declaration) && declaration.dotDotDotToken
|
|
1983
|
+
&& ts.isObjectBindingPattern(declaration.parent) && ts.isVariableDeclaration(declaration.parent.parent)
|
|
1984
|
+
&& declaration.parent.parent.parent.flags & ts.NodeFlags.Const) return true;
|
|
1985
|
+
return declaration && ts.isVariableDeclaration(declaration) && declaration.initializer
|
|
1986
|
+
&& declaration.getStart() < node.getStart() && declaration.parent.flags & ts.NodeFlags.Const
|
|
1987
|
+
&& nativeRecord(declaration.initializer);
|
|
1988
|
+
}
|
|
1989
|
+
if (!ts.isCallExpression(node) || node.flags & ts.NodeFlags.OptionalChain) return false;
|
|
1990
|
+
let declaration = checker.getResolvedSignature(node)?.getDeclaration();
|
|
1991
|
+
if (!declaration?.body && ts.isIdentifier(node.expression)) declaration = valueSymbol(node.expression)?.valueDeclaration;
|
|
1992
|
+
if (declaration && ts.isVariableDeclaration(declaration) && declaration.parent.flags & ts.NodeFlags.Const) {
|
|
1993
|
+
declaration = declaration.initializer;
|
|
1994
|
+
}
|
|
1995
|
+
if (!declaration || (!ts.isFunctionDeclaration(declaration) && !ts.isArrowFunction(declaration)) || !declaration.body) return false;
|
|
1996
|
+
let body = declaration.body;
|
|
1997
|
+
while (ts.isParenthesizedExpression(body)) body = body.expression;
|
|
1998
|
+
if (!ts.isBlock(body)) return ts.isObjectLiteralExpression(body);
|
|
1999
|
+
const tail = body.statements.at(-1);
|
|
2000
|
+
if (!tail || !ts.isReturnStatement(tail)) return false;
|
|
2001
|
+
const returns = [];
|
|
2002
|
+
function inspect(part) {
|
|
2003
|
+
if (ts.isReturnStatement(part)) returns.push(part.expression);
|
|
2004
|
+
else if (!ts.isFunctionLike(part)) ts.forEachChild(part, inspect);
|
|
2005
|
+
}
|
|
2006
|
+
inspect(body);
|
|
2007
|
+
return returns.length > 0 && returns.every(value => value && ts.isObjectLiteralExpression(value));
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
function nativeSpreadMode(node) {
|
|
2011
|
+
const type = checker.getTypeAtLocation(node);
|
|
2012
|
+
const source = checker.getNonNullableType(type);
|
|
2013
|
+
if (nativeRecord(node) || isOwnedRecord(source) || source.flags & T.Never) return knownPresent(type) ? "present" : "nullable";
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
const parameterRecord = new WeakMap();
|
|
2017
|
+
|
|
2018
|
+
function privateRecordParameter(parameter) {
|
|
2019
|
+
if (!parameter || !ts.isParameter(parameter) || !ts.isIdentifier(parameter.name) || parameter.dotDotDotToken) return false;
|
|
2020
|
+
if (parameterRecord.has(parameter)) return parameterRecord.get(parameter);
|
|
2021
|
+
const owner = parameter.parent;
|
|
2022
|
+
if (!ts.isFunctionDeclaration(owner) || !owner.name || !owner.body) return false;
|
|
2023
|
+
const file = owner.getSourceFile();
|
|
2024
|
+
const symbol = checker.getSymbolAtLocation(owner.name);
|
|
2025
|
+
const binding = checker.getSymbolAtLocation(parameter.name);
|
|
2026
|
+
if (!symbol || [...exportSymbols(file).values()].some(value => runtimeTarget(value) === symbol)) return false;
|
|
2027
|
+
const index = owner.parameters.filter(current => !ts.isIdentifier(current.name) || current.name.text !== "this").indexOf(parameter);
|
|
2028
|
+
if (index < 0) return false;
|
|
2029
|
+
parameterRecord.set(parameter, false);
|
|
2030
|
+
let called = false;
|
|
2031
|
+
function rejects(node) {
|
|
2032
|
+
if (ts.isTypeNode(node)) return;
|
|
2033
|
+
if (ts.isIdentifier(node) && node !== owner.name) {
|
|
2034
|
+
const value = ts.isShorthandPropertyAssignment(node.parent)
|
|
2035
|
+
? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
2036
|
+
if (value === binding && ts.isAssignmentTarget(node)) return true;
|
|
2037
|
+
if (value === symbol) {
|
|
2038
|
+
const call = node.parent;
|
|
2039
|
+
if (!ts.isCallExpression(call) || call.expression !== node || call.arguments.some(ts.isSpreadElement)) return true;
|
|
2040
|
+
called = true;
|
|
2041
|
+
const argument = call.arguments[index];
|
|
2042
|
+
const mode = argument === undefined ? "nullable" : nativeSpreadMode(argument);
|
|
2043
|
+
return mode === undefined || mode === "nullable" && parameter.initializer !== undefined
|
|
2044
|
+
&& nativeSpreadMode(parameter.initializer) === undefined;
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
return ts.forEachChild(node, child => rejects(child) || undefined);
|
|
2048
|
+
}
|
|
2049
|
+
const proven = !rejects(file) && called;
|
|
2050
|
+
parameterRecord.set(parameter, proven);
|
|
2051
|
+
return proven;
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
function nativeSpread(node) {
|
|
2055
|
+
const mode = nativeSpreadMode(node);
|
|
2056
|
+
if (mode !== undefined) return mode;
|
|
2057
|
+
if (ts.isIdentifier(node) && privateRecordParameter(valueSymbol(node)?.valueDeclaration)) {
|
|
2058
|
+
return knownPresent(checker.getTypeAtLocation(node)) ? "present" : "nullable";
|
|
2059
|
+
}
|
|
2060
|
+
if (structuralLuaTable(node)) return "structural";
|
|
2061
|
+
unsupported(node, "Object spread requires a proven native record");
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
const jsxEntities = { amp: "&", apos: "'", gt: ">", lt: "<", nbsp: "\u00a0", quot: '"' };
|
|
2065
|
+
|
|
2066
|
+
function jsxString(node, value) {
|
|
2067
|
+
return value.replace(/&(#x[\da-fA-F]+|#\d+|\w+);/g, (entity, word) => {
|
|
2068
|
+
if (word.startsWith("#")) {
|
|
2069
|
+
const hexadecimal = word.startsWith("#x");
|
|
2070
|
+
const code = Number.parseInt(word.slice(hexadecimal ? 2 : 1), hexadecimal ? 16 : 10);
|
|
2071
|
+
if (code > 0x10ffff || code >= 0xd800 && code <= 0xdfff) unsupported(node, "JSX text has an invalid code point");
|
|
2072
|
+
return String.fromCodePoint(code);
|
|
2073
|
+
}
|
|
2074
|
+
if (Object.hasOwn(jsxEntities, word)) return jsxEntities[word];
|
|
2075
|
+
unsupported(node, `JSX entity ${entity} is outside the native subset`);
|
|
2076
|
+
});
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
function jsxText(node) {
|
|
2080
|
+
const lines = node.text.split(/\r\n|[\r\n\u2028\u2029]/);
|
|
2081
|
+
if (lines.length === 1) return jsxString(node, lines[0]);
|
|
2082
|
+
const parts = [];
|
|
2083
|
+
for (let index = 0; index < lines.length; index++) {
|
|
2084
|
+
let line = lines[index];
|
|
2085
|
+
if (index > 0) line = line.trimStart();
|
|
2086
|
+
if (index < lines.length - 1) line = line.trimEnd();
|
|
2087
|
+
if (line) parts.push(jsxString(node, line));
|
|
2088
|
+
}
|
|
2089
|
+
return parts.length ? parts.join(" ") : undefined;
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
function jsxFactory(name, node, invoke = false) {
|
|
2093
|
+
const [root, ...members] = name?.split(".") ?? [];
|
|
2094
|
+
if (!root || ![root, ...members].every(part => /^[$A-Z_a-z][$\w]*$/.test(part))) {
|
|
2095
|
+
unsupported(node, "Classic JSX requires a named factory");
|
|
2096
|
+
}
|
|
2097
|
+
const symbol = checker.resolveName(root, node, ts.SymbolFlags.Value, false);
|
|
2098
|
+
if (members.length && symbol) {
|
|
2099
|
+
let type = checker.getTypeOfSymbolAtLocation(symbol, node);
|
|
2100
|
+
for (const key of members) {
|
|
2101
|
+
const member = checker.getPropertyOfType(type, key);
|
|
2102
|
+
if (!member) unsupported(node, `JSX factory member '${key}' cannot be resolved`);
|
|
2103
|
+
type = checker.getTypeOfSymbolAtLocation(member, node);
|
|
2104
|
+
}
|
|
2105
|
+
if (invoke && type.getCallSignatures().some(signature => {
|
|
2106
|
+
const declaration = signature.getDeclaration();
|
|
2107
|
+
return signature.thisParameter && !(checker.getTypeOfSymbolAtLocation(signature.thisParameter, node).flags & T.Void)
|
|
2108
|
+
|| !signature.thisParameter && declaration && (ts.isMethodSignature(declaration) || ts.isMethodDeclaration(declaration));
|
|
2109
|
+
})) unsupported(node, "A qualified JSX factory must have a free calling convention");
|
|
2110
|
+
}
|
|
2111
|
+
for (const member of members.reverse()) emit("property", text(member));
|
|
2112
|
+
reference(symbol, node);
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
function jsxProps(attributes) {
|
|
2116
|
+
if (!attributes?.length) return emit("literal", "nil");
|
|
2117
|
+
emit("object", attributes.length);
|
|
2118
|
+
for (const attr of attributes) {
|
|
2119
|
+
if (ts.isJsxSpreadAttribute(attr)) {
|
|
2120
|
+
emit("spread-fields", nativeSpread(attr.expression));
|
|
2121
|
+
expression(attr.expression);
|
|
2122
|
+
continue;
|
|
2123
|
+
}
|
|
2124
|
+
emit("field", text(propertyName(attr.name)));
|
|
2125
|
+
if (!attr.initializer) emit("literal", "true");
|
|
2126
|
+
else if (ts.isStringLiteral(attr.initializer)) emit("string", text(jsxString(attr, attr.initializer.text)));
|
|
2127
|
+
else if (ts.isJsxExpression(attr.initializer) && attr.initializer.expression) expression(attr.initializer.expression);
|
|
2128
|
+
else unsupported(attr, "Unsupported JSX property value");
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
function jsx(node) {
|
|
2133
|
+
const pragma = (key, argument) => jsxPragma(node.getSourceFile(), key, argument);
|
|
2134
|
+
const automatic = kumiJsxFactories.get(node.getSourceFile().fileName);
|
|
2135
|
+
if (!automatic && (options.jsx !== ts.JsxEmit.React || pragma("jsxruntime", "runtime") === "automatic")) {
|
|
2136
|
+
unsupported(node, "The native compiler requires classic JSX or Kumi's automatic JSX runtime");
|
|
2137
|
+
}
|
|
2138
|
+
const fragment = ts.isJsxFragment(node);
|
|
2139
|
+
const opening = ts.isJsxElement(node) ? node.openingElement : node;
|
|
2140
|
+
const children = [];
|
|
2141
|
+
for (const child of node.children ?? []) {
|
|
2142
|
+
if (ts.isJsxText(child)) {
|
|
2143
|
+
const value = jsxText(child);
|
|
2144
|
+
if (value !== undefined) children.push(value);
|
|
2145
|
+
} else if (ts.isJsxExpression(child)) {
|
|
2146
|
+
if (child.dotDotDotToken) unsupported(child, "JSX spread children are unsupported");
|
|
2147
|
+
if (child.expression) children.push(child.expression);
|
|
2148
|
+
} else children.push(child);
|
|
2149
|
+
}
|
|
2150
|
+
emit("call", 2 + children.length);
|
|
2151
|
+
jsxFactory(automatic?.factory ?? pragma("jsx", "factory") ?? options.jsxFactory, node, true);
|
|
2152
|
+
if (fragment) jsxFactory(automatic?.fragment ?? pragma("jsxfrag", "factory") ?? options.jsxFragmentFactory, node);
|
|
2153
|
+
else if (ts.isIdentifier(opening.tagName) && ts.isIntrinsicJsxName(opening.tagName.text)) emit("string", text(opening.tagName.text));
|
|
2154
|
+
else expression(opening.tagName);
|
|
2155
|
+
jsxProps(opening.attributes?.properties);
|
|
2156
|
+
for (const child of children) {
|
|
2157
|
+
if (typeof child === "string") emit("string", text(child));
|
|
2158
|
+
else expression(child);
|
|
2159
|
+
}
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
function expression(node) {
|
|
2163
|
+
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node)) return jsx(node);
|
|
2164
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isNonNullExpression(node)
|
|
2165
|
+
|| ts.isSatisfiesExpression(node)) return expression(node.expression);
|
|
2166
|
+
if (node.kind === K.TrueKeyword || node.kind === K.FalseKeyword) {
|
|
2167
|
+
return emit("literal", node.kind === K.TrueKeyword ? "true" : "false");
|
|
2168
|
+
}
|
|
2169
|
+
if (node.kind === K.NullKeyword) return emit("literal", "nil");
|
|
2170
|
+
if (ts.isNumericLiteral(node)) return emit("number", Number(node.text));
|
|
2171
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return emit("string", text(node.text));
|
|
2172
|
+
if (ts.isTemplateExpression(node)) {
|
|
2173
|
+
emit("template", node.templateSpans.length, text(node.head.text));
|
|
2174
|
+
for (const span of node.templateSpans) {
|
|
2175
|
+
const type = nativeBase(checker.getTypeAtLocation(span.expression));
|
|
2176
|
+
const alternatives = type.isUnion() ? type.types : [type];
|
|
2177
|
+
if (!alternatives.every(value => value.flags & (T.StringLike | T.NumberLike | T.BooleanLike))) {
|
|
2178
|
+
unsupported(span.expression, "Template substitutions require a known string, number or boolean");
|
|
2179
|
+
}
|
|
2180
|
+
emit("template-part", knownString(type) ? "string" : "scalar", text(span.literal.text));
|
|
2181
|
+
expression(span.expression);
|
|
2182
|
+
}
|
|
2183
|
+
return;
|
|
2184
|
+
}
|
|
2185
|
+
if (node.kind === K.ThisKeyword) {
|
|
2186
|
+
let parent = node.parent;
|
|
2187
|
+
while (parent && !ts.isSourceFile(parent)) {
|
|
2188
|
+
if (ts.isClassElement(parent) && ts.isClassDeclaration(parent.parent)) {
|
|
2189
|
+
const receiver = parent.parameters?.[0];
|
|
2190
|
+
const explicit = receiver && ts.isIdentifier(receiver.name) && receiver.name.text === "this";
|
|
2191
|
+
if (explicit ? receiver.type?.kind === K.VoidKeyword : addonMethodUsesSelf(parent, parent) === false) {
|
|
2192
|
+
return emit("literal", "nil");
|
|
2193
|
+
}
|
|
2194
|
+
return emit("self");
|
|
2195
|
+
}
|
|
2196
|
+
if (ts.isMethodDeclaration(parent) && ts.isObjectLiteralExpression(parent.parent) && objectMethodHasSelf(parent)) {
|
|
2197
|
+
return emit("self");
|
|
2198
|
+
}
|
|
2199
|
+
if ((ts.isFunctionExpression(parent) || ts.isFunctionDeclaration(parent)) && functionHasSelf(parent)) return emit("self");
|
|
2200
|
+
if (ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent) || ts.isMethodDeclaration(parent)) break;
|
|
2201
|
+
parent = parent.parent;
|
|
2202
|
+
}
|
|
2203
|
+
unsupported(node, "This expression requires a native receiver");
|
|
2204
|
+
}
|
|
2205
|
+
if (ts.isIdentifier(node)) {
|
|
2206
|
+
const symbol = checker.getSymbolAtLocation(node);
|
|
2207
|
+
if (node.text === "undefined" && !symbol?.declarations?.length) return emit("literal", "nil");
|
|
2208
|
+
return reference(symbol, node);
|
|
2209
|
+
}
|
|
2210
|
+
if (ts.isPropertyAccessExpression(node)) {
|
|
2211
|
+
if (standardMember(node, "Math", "PI")) return emit("global", "math.pi");
|
|
2212
|
+
if (standardMember(node, "Number", "NaN")) return emit("literal", "nan");
|
|
2213
|
+
if (standardMember(node, "Number", "POSITIVE_INFINITY")) return emit("global", "math.huge");
|
|
2214
|
+
if (standardMember(node, "Number", "NEGATIVE_INFINITY")) return emit("literal", "-inf");
|
|
2215
|
+
for (const name of ["MAX_SAFE_INTEGER", "MIN_SAFE_INTEGER", "EPSILON", "MAX_VALUE", "MIN_VALUE"]) {
|
|
2216
|
+
if (standardMember(node, "Number", name)) return emit("number", String(Number[name]));
|
|
2217
|
+
}
|
|
2218
|
+
if (node.flags & ts.NodeFlags.OptionalChain && (!node.questionDotToken || node.expression.flags & ts.NodeFlags.OptionalChain)) {
|
|
2219
|
+
return optionalChain(node);
|
|
2220
|
+
}
|
|
2221
|
+
const symbol = valueSymbol(node.name);
|
|
2222
|
+
if (moduleMarker(symbol)) unsupported(node, "Kumi module declaration must be lowered before linking");
|
|
2223
|
+
const member = symbol?.valueDeclaration;
|
|
2224
|
+
if (rawTableMember(member)) unsupported(node, "A Lua table operation requires its receiver at the call site");
|
|
2225
|
+
if (classMethodUsesSelf(member)) {
|
|
2226
|
+
unsupported(node, "A class method requires its receiver at the call site");
|
|
2227
|
+
}
|
|
2228
|
+
if (node.name.text === "length") {
|
|
2229
|
+
const type = checker.getTypeAtLocation(node.expression);
|
|
2230
|
+
if (knownString(type) && !(node.flags & ts.NodeFlags.OptionalChain)) {
|
|
2231
|
+
emit("string-length");
|
|
2232
|
+
return expression(node.expression);
|
|
2233
|
+
}
|
|
2234
|
+
if (nativeArrayReference(node.expression)) {
|
|
2235
|
+
if (node.flags & ts.NodeFlags.OptionalChain && !node.questionDotToken) unsupported(node);
|
|
2236
|
+
emit(node.questionDotToken ? "optional-length" : "array-length");
|
|
2237
|
+
return expression(node.expression);
|
|
2238
|
+
}
|
|
2239
|
+
if (checker.isArrayType(type) || checker.isTupleType(type)) unsupported(node, "Array length requires a proven dense representation");
|
|
2240
|
+
}
|
|
2241
|
+
if (node.flags & ts.NodeFlags.OptionalChain) {
|
|
2242
|
+
const type = checker.getNonNullableType(checker.getTypeAtLocation(node.expression));
|
|
2243
|
+
if (!node.questionDotToken || !tableType(type)) {
|
|
2244
|
+
unsupported(node, "Optional access requires a table or undefined");
|
|
2245
|
+
}
|
|
2246
|
+
emit("optional-property", text(node.name.text));
|
|
2247
|
+
} else {
|
|
2248
|
+
if (emitReadableHostProperty(node.expression, node.name.text)) return;
|
|
2249
|
+
emit("property", text(node.name.text));
|
|
2250
|
+
}
|
|
2251
|
+
return expression(node.expression);
|
|
2252
|
+
}
|
|
2253
|
+
if (ts.isElementAccessExpression(node) && node.flags & ts.NodeFlags.OptionalChain
|
|
2254
|
+
&& (!node.questionDotToken || node.expression.flags & ts.NodeFlags.OptionalChain)) return optionalChain(node);
|
|
2255
|
+
if (ts.isElementAccessExpression(node) && node.questionDotToken) {
|
|
2256
|
+
if (nativeArrayReference(node.expression) || knownTuple(checker.getNonNullableType(checker.getTypeAtLocation(node.expression)))) {
|
|
2257
|
+
emit("optional-array-index");
|
|
2258
|
+
expression(node.expression);
|
|
2259
|
+
return numericIndex(node.argumentExpression);
|
|
2260
|
+
}
|
|
2261
|
+
emit("optional-index");
|
|
2262
|
+
return tableIndex(node, true);
|
|
2263
|
+
}
|
|
2264
|
+
if (ts.isElementAccessExpression(node) && !(node.flags & ts.NodeFlags.OptionalChain)) {
|
|
2265
|
+
const source = node.expression;
|
|
2266
|
+
if (ts.isStringLiteralLike(node.argumentExpression) && emitReadableHostProperty(source, node.argumentExpression.text)) return;
|
|
2267
|
+
if (knownString(checker.getTypeAtLocation(source))) {
|
|
2268
|
+
emit("call", 2);
|
|
2269
|
+
emit("global", "byteAt");
|
|
2270
|
+
expression(source);
|
|
2271
|
+
return numericIndex(node.argumentExpression);
|
|
2272
|
+
}
|
|
2273
|
+
if (nativeMultiCall(source)) {
|
|
2274
|
+
const index = node.argumentExpression;
|
|
2275
|
+
if (ts.isNumericLiteral(index) && Number.isSafeInteger(Number(index.text)) && Number(index.text) < 1000) {
|
|
2276
|
+
const offset = Number(index.text) + 1;
|
|
2277
|
+
const readable = readableHostTuple(source);
|
|
2278
|
+
const guard = ["wowReadable", "wowReadableSecond", "wowReadableThird"][offset - 1];
|
|
2279
|
+
if (readable && offset <= readable.count && guard !== undefined) {
|
|
2280
|
+
emit("call", 1);
|
|
2281
|
+
emit("global", guard);
|
|
2282
|
+
emit("spread-native");
|
|
2283
|
+
return emitReadableTupleRead(source, readable.name);
|
|
2284
|
+
}
|
|
2285
|
+
emit("multi-slot", offset);
|
|
2286
|
+
return call(source, "multi");
|
|
2287
|
+
}
|
|
2288
|
+
emit("array-index");
|
|
2289
|
+
emit("multi-array");
|
|
2290
|
+
call(source, "multi");
|
|
2291
|
+
return numericIndex(index);
|
|
2292
|
+
}
|
|
2293
|
+
if (nativeArrayReference(node.expression) || knownTuple(checker.getTypeAtLocation(node.expression))) {
|
|
2294
|
+
emit("array-index");
|
|
2295
|
+
expression(node.expression);
|
|
2296
|
+
return numericIndex(node.argumentExpression);
|
|
2297
|
+
}
|
|
2298
|
+
emit("table-index");
|
|
2299
|
+
return tableIndex(node);
|
|
2300
|
+
}
|
|
2301
|
+
if (ts.isCallExpression(node)) {
|
|
2302
|
+
if (addonSource(node) && nativeMultiCall(node)) {
|
|
2303
|
+
emit("multi-array");
|
|
2304
|
+
return call(node, "multi");
|
|
2305
|
+
}
|
|
2306
|
+
return call(node);
|
|
2307
|
+
}
|
|
2308
|
+
if (ts.isNewExpression(node)) {
|
|
2309
|
+
if (ts.isIdentifier(node.expression)) {
|
|
2310
|
+
const symbol = valueSymbol(node.expression);
|
|
2311
|
+
if (symbol?.name === "Error" && symbol.declarations?.some(declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) {
|
|
2312
|
+
const args = node.arguments ?? [];
|
|
2313
|
+
if (args.length > 1 || args.some(ts.isSpreadElement)) unsupported(node, "Error construction accepts one message");
|
|
2314
|
+
emit("error-value");
|
|
2315
|
+
if (args.length) expression(args[0]);
|
|
2316
|
+
else emit("literal", "nil");
|
|
2317
|
+
return;
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
if (rawTableConstruction(node)) {
|
|
2321
|
+
if (node.arguments?.length) unsupported(node, "Lua tables only support empty construction");
|
|
2322
|
+
return emit("object", 0);
|
|
2323
|
+
}
|
|
2324
|
+
const collection = collectionConstructor(node);
|
|
2325
|
+
if (collection && !node.arguments?.length) return emit("collection", collection);
|
|
2326
|
+
if (collection && node.arguments?.length === 1) {
|
|
2327
|
+
const [source] = node.arguments;
|
|
2328
|
+
const type = checker.getTypeAtLocation(source);
|
|
2329
|
+
if ((collection === "map" || collection === "set") && collectionReference(source) === collection) {
|
|
2330
|
+
emit("collection-init", collection === "map" ? "copyMap" : "copySet");
|
|
2331
|
+
return expression(source);
|
|
2332
|
+
}
|
|
2333
|
+
if (collection === "map" && nativeArrayReference(source)) {
|
|
2334
|
+
const item = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
2335
|
+
if (!item || !knownTuple(item)) unsupported(source, "A native Map initializer requires key and value tuples");
|
|
2336
|
+
denseType(source, item);
|
|
2337
|
+
emit("collection-init", "mapFromArray");
|
|
2338
|
+
return expression(source);
|
|
2339
|
+
}
|
|
2340
|
+
if (collection === "set" && (denseArrayReference(source) || luaArrayAbiReference(source) || knownTuple(type))) {
|
|
2341
|
+
const item = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
2342
|
+
if (!item) unsupported(source, "A native Set initializer requires a known element type");
|
|
2343
|
+
if (!knownPresent(item) && addonSource(node) && luaArrayAbiReference(source)) {
|
|
2344
|
+
emit("collection-init", "setFromLuaArray");
|
|
2345
|
+
return expression(source);
|
|
2346
|
+
}
|
|
2347
|
+
if (!ts.isCallExpression(source) || !standardMember(source.expression, "Object", "values")) denseType(source, item);
|
|
2348
|
+
emit("collection-init", "setFromArray");
|
|
2349
|
+
return expression(source);
|
|
2350
|
+
}
|
|
2351
|
+
unsupported(source, "Collection initialization requires a proven native collection or dense sequence");
|
|
2352
|
+
}
|
|
2353
|
+
if (nativeClass(node.expression)) {
|
|
2354
|
+
emit("call", node.arguments?.length ?? 0);
|
|
2355
|
+
expression(node.expression);
|
|
2356
|
+
callArguments(node.arguments ?? []);
|
|
2357
|
+
return;
|
|
2358
|
+
}
|
|
2359
|
+
const declaration = checker.getResolvedSignature(node)?.getDeclaration();
|
|
2360
|
+
if (!collection && declaration && !declaration.getSourceFile().isDeclarationFile
|
|
2361
|
+
&& checker.getSignaturesOfType(checker.getTypeAtLocation(node.expression), ts.SignatureKind.Construct).length) {
|
|
2362
|
+
emit("call", 1 + (node.arguments?.length ?? 0));
|
|
2363
|
+
emit("global", "constructClass");
|
|
2364
|
+
expression(node.expression);
|
|
2365
|
+
callArguments(node.arguments ?? []);
|
|
2366
|
+
return;
|
|
2367
|
+
}
|
|
2368
|
+
unsupported(node, "Construction requires a declared class or an empty native collection");
|
|
2369
|
+
}
|
|
2370
|
+
if (ts.isArrayLiteralExpression(node)) {
|
|
2371
|
+
const snapshot = collectionSnapshot(node);
|
|
2372
|
+
if (snapshot) {
|
|
2373
|
+
const element = checker.getIndexTypeOfType(checker.getTypeAtLocation(node), ts.IndexKind.Number);
|
|
2374
|
+
if (!element) unsupported(node, "A collection snapshot requires a known element type");
|
|
2375
|
+
denseType(node, element);
|
|
2376
|
+
emit("collection-snapshot", snapshot.field);
|
|
2377
|
+
return expression(snapshot.source);
|
|
2378
|
+
}
|
|
2379
|
+
if (node.elements.length === 1 && ts.isSpreadElement(node.elements[0])) {
|
|
2380
|
+
const source = node.elements[0].expression;
|
|
2381
|
+
if (nativeMultiCall(source)) {
|
|
2382
|
+
emit("multi-array");
|
|
2383
|
+
return call(source, "multi");
|
|
2384
|
+
}
|
|
2385
|
+
if (nativeArrayReference(source) || knownTuple(checker.getTypeAtLocation(source))) {
|
|
2386
|
+
emit("array-copy");
|
|
2387
|
+
return expression(source);
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
const contextual = checker.getContextualType(node);
|
|
2391
|
+
const tuple = knownTuple(checker.getTypeAtLocation(node)) || contextual && knownTuple(contextual);
|
|
2392
|
+
const luaSlots = tuple || luaArrayAbiReference(node);
|
|
2393
|
+
emit("array", node.elements.length);
|
|
2394
|
+
for (const element of node.elements) {
|
|
2395
|
+
if (ts.isSpreadElement(element)) {
|
|
2396
|
+
const source = element.expression;
|
|
2397
|
+
const collection = spreadCollection(source);
|
|
2398
|
+
if (collection) {
|
|
2399
|
+
emit("spread-array");
|
|
2400
|
+
emit("collection-snapshot", collection.field);
|
|
2401
|
+
expression(collection.source);
|
|
2402
|
+
continue;
|
|
2403
|
+
}
|
|
2404
|
+
if (denseMultiCall(source)) {
|
|
2405
|
+
emit("spread-array");
|
|
2406
|
+
emit("multi-array");
|
|
2407
|
+
call(source, "multi");
|
|
2408
|
+
continue;
|
|
2409
|
+
}
|
|
2410
|
+
const type = checker.getTypeAtLocation(source);
|
|
2411
|
+
const item = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
2412
|
+
const luaSequence = luaArrayAbiReference(source);
|
|
2413
|
+
if (!item || !(denseArrayReference(source) || knownTuple(type) || luaSequence)) unsupported(element, "Array spread requires a proven sequence");
|
|
2414
|
+
if (!luaSequence) denseType(element, item);
|
|
2415
|
+
emit("spread-array");
|
|
2416
|
+
expression(source);
|
|
2417
|
+
continue;
|
|
2418
|
+
}
|
|
2419
|
+
if (!luaSlots) denseValue(element);
|
|
2420
|
+
if (luaSlots && ts.isOmittedExpression(element)) emit("literal", "nil");
|
|
2421
|
+
else expression(element);
|
|
2422
|
+
}
|
|
2423
|
+
return;
|
|
2424
|
+
}
|
|
2425
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
2426
|
+
emit("object", node.properties.length);
|
|
2427
|
+
for (const property of node.properties) {
|
|
2428
|
+
if (ts.isShorthandPropertyAssignment(property) && !property.objectAssignmentInitializer) {
|
|
2429
|
+
emit("field", text(property.name.text));
|
|
2430
|
+
reference(checker.getShorthandAssignmentValueSymbol(property), property.name);
|
|
2431
|
+
} else if (ts.isPropertyAssignment(property)) {
|
|
2432
|
+
if (ts.isNumericLiteral(property.name) || ts.isComputedPropertyName(property.name)) {
|
|
2433
|
+
const key = ts.isNumericLiteral(property.name) ? property.name : property.name.expression;
|
|
2434
|
+
if (!ts.isNumericLiteral(key) && !recordKey(checker.getTypeAtLocation(key))) {
|
|
2435
|
+
unsupported(property.name, "Computed record fields require string or numeric keys");
|
|
2436
|
+
}
|
|
2437
|
+
emit("computed-field");
|
|
2438
|
+
expression(key);
|
|
2439
|
+
} else emit("field", text(propertyName(property.name)));
|
|
2440
|
+
expression(property.initializer);
|
|
2441
|
+
} else if (ts.isSpreadAssignment(property)) {
|
|
2442
|
+
emit("spread-fields", nativeSpread(property.expression));
|
|
2443
|
+
expression(property.expression);
|
|
2444
|
+
} else if (ts.isMethodDeclaration(property)) objectMethod(property);
|
|
2445
|
+
else unsupported(property);
|
|
2446
|
+
}
|
|
2447
|
+
return;
|
|
2448
|
+
}
|
|
2449
|
+
if (ts.isFunctionExpression(node) && !node.asteriskToken && !node.modifiers?.length) {
|
|
2450
|
+
const usesSelf = functionHasSelf(node);
|
|
2451
|
+
const opcode = usesSelf ? "object-method" : "arrow";
|
|
2452
|
+
const params = parameters(node.parameters, usesSelf);
|
|
2453
|
+
const symbol = node.name && checker.getSymbolAtLocation(node.name);
|
|
2454
|
+
if (symbol && (referencesBinding(node.body, symbol) || node.parameters.some(param => referencesBinding(param, symbol)))) {
|
|
2455
|
+
emit(`named-${opcode}`, binding(symbol, node.name), ...params);
|
|
2456
|
+
} else emit(opcode, ...params);
|
|
2457
|
+
return body(node.body, node.parameters);
|
|
2458
|
+
}
|
|
2459
|
+
if (ts.isArrowFunction(node) && !node.modifiers?.length) {
|
|
2460
|
+
emit(arrowReceivesSelf(node) ? "arrow-receiver" : "arrow", ...parameters(node.parameters));
|
|
2461
|
+
if (ts.isBlock(node.body)) body(node.body, node.parameters);
|
|
2462
|
+
else {
|
|
2463
|
+
const prelude = parameterPrelude(node.parameters);
|
|
2464
|
+
emit("block", 1 + prelude.length);
|
|
2465
|
+
for (const step of prelude) step();
|
|
2466
|
+
returnValue(node.body, node);
|
|
2467
|
+
}
|
|
2468
|
+
return;
|
|
2469
|
+
}
|
|
2470
|
+
if (ts.isTypeOfExpression(node)) {
|
|
2471
|
+
emit("type-of");
|
|
2472
|
+
return expression(node.expression);
|
|
2473
|
+
}
|
|
2474
|
+
if (ts.isConditionalExpression(node)) {
|
|
2475
|
+
emit(luaAlwaysTruthy(checker.getTypeAtLocation(node.whenTrue)) ? "select-truthy" : "select");
|
|
2476
|
+
booleanCondition(node.condition);
|
|
2477
|
+
expression(node.whenTrue);
|
|
2478
|
+
expression(node.whenFalse);
|
|
2479
|
+
return;
|
|
2480
|
+
}
|
|
2481
|
+
if (ts.isBinaryExpression(node)) {
|
|
2482
|
+
const op = node.operatorToken.kind;
|
|
2483
|
+
if (op === K.InstanceOfKeyword) {
|
|
2484
|
+
if (!nativeClass(node.right)) unsupported(node.right, "Instance tests require a declared native class");
|
|
2485
|
+
emit("instance-of");
|
|
2486
|
+
expression(node.left);
|
|
2487
|
+
return expression(node.right);
|
|
2488
|
+
}
|
|
2489
|
+
if (op === K.InKeyword) {
|
|
2490
|
+
if (!recordKey(checker.getTypeAtLocation(node.left)) || !tableType(checker.getTypeAtLocation(node.right))
|
|
2491
|
+
|| nativeArrayReference(node.right) || collectionReference(node.right)) {
|
|
2492
|
+
unsupported(node, "Membership tests require a string or number key and a record");
|
|
2493
|
+
}
|
|
2494
|
+
if (ts.isStringLiteral(node.left)) {
|
|
2495
|
+
emit("has-property", text(node.left.text));
|
|
2496
|
+
return expression(node.right);
|
|
2497
|
+
}
|
|
2498
|
+
emit("call", 2);
|
|
2499
|
+
emit("global", "tableHas");
|
|
2500
|
+
expression(node.left);
|
|
2501
|
+
return expression(node.right);
|
|
2502
|
+
}
|
|
2503
|
+
if (op === K.EqualsToken) {
|
|
2504
|
+
emit("assignment");
|
|
2505
|
+
assignable(node.left);
|
|
2506
|
+
return expression(node.right);
|
|
2507
|
+
}
|
|
2508
|
+
if (op === K.QuestionQuestionEqualsToken) {
|
|
2509
|
+
emit("nullish-assignment");
|
|
2510
|
+
assignable(node.left);
|
|
2511
|
+
return expression(node.right);
|
|
2512
|
+
}
|
|
2513
|
+
if (op === K.BarBarEqualsToken || op === K.AmpersandAmpersandEqualsToken) {
|
|
2514
|
+
if (!addonSource(node) && !luaTruthValue(checker.getTypeAtLocation(node.left))) {
|
|
2515
|
+
unsupported(node.left, "Logical assignment requires a Lua-compatible condition");
|
|
2516
|
+
}
|
|
2517
|
+
emit("logical-assignment", op === K.BarBarEqualsToken ? "or" : "and");
|
|
2518
|
+
assignable(node.left);
|
|
2519
|
+
return expression(node.right);
|
|
2520
|
+
}
|
|
2521
|
+
if (compoundOperators.has(op)) return compoundAssignment(node);
|
|
2522
|
+
if (op === K.EqualsEqualsToken || op === K.ExclamationEqualsToken) {
|
|
2523
|
+
if (node.left.kind !== K.NullKeyword && node.right.kind !== K.NullKeyword) {
|
|
2524
|
+
unsupported(node, "Loose equality is only supported for testing null or undefined together");
|
|
2525
|
+
}
|
|
2526
|
+
const value = node.right.kind === K.NullKeyword ? node.left : node.right;
|
|
2527
|
+
emit("binary", op === K.EqualsEqualsToken ? "==" : "~=");
|
|
2528
|
+
if (value.kind === K.NullKeyword) emit("literal", "nil");
|
|
2529
|
+
else expression(value);
|
|
2530
|
+
return emit("literal", "nil");
|
|
2531
|
+
}
|
|
2532
|
+
if (op === K.QuestionQuestionToken) {
|
|
2533
|
+
emit("nullish");
|
|
2534
|
+
expression(node.left);
|
|
2535
|
+
return expression(node.right);
|
|
2536
|
+
}
|
|
2537
|
+
if (op === K.AmpersandAmpersandToken || op === K.BarBarToken) {
|
|
2538
|
+
emit("binary", op === K.AmpersandAmpersandToken ? "and" : "or");
|
|
2539
|
+
booleanCondition(node.left);
|
|
2540
|
+
return expression(node.right);
|
|
2541
|
+
}
|
|
2542
|
+
if (op === K.EqualsEqualsEqualsToken || op === K.ExclamationEqualsEqualsToken) {
|
|
2543
|
+
const comparison = op === K.EqualsEqualsEqualsToken ? "==" : "~=";
|
|
2544
|
+
const typeOf = ts.isTypeOfExpression(node.left) ? node.left : node.right;
|
|
2545
|
+
const name = typeOf === node.left ? node.right : node.left;
|
|
2546
|
+
if (ts.isTypeOfExpression(typeOf) && ts.isStringLiteralLike(name)
|
|
2547
|
+
&& ["boolean", "number", "string", "undefined"].includes(name.text)) {
|
|
2548
|
+
emit("primitive-type-test", comparison, name.text === "undefined" ? "nil" : name.text);
|
|
2549
|
+
return expression(typeOf.expression);
|
|
2550
|
+
}
|
|
2551
|
+
emit("binary", comparison);
|
|
2552
|
+
} else if ([K.MinusToken, K.AsteriskToken, K.AsteriskAsteriskToken, K.SlashToken, K.PercentToken, K.LessThanToken,
|
|
2553
|
+
K.LessThanEqualsToken, K.GreaterThanToken, K.GreaterThanEqualsToken].includes(op)) {
|
|
2554
|
+
const comparison = [K.LessThanToken, K.LessThanEqualsToken, K.GreaterThanToken, K.GreaterThanEqualsToken].includes(op);
|
|
2555
|
+
if (!comparison || !knownString(checker.getTypeAtLocation(node.left)) || !knownString(checker.getTypeAtLocation(node.right))) {
|
|
2556
|
+
numberOperand(node.left, "Numeric operator requires a number on the left");
|
|
2557
|
+
numberOperand(node.right, "Numeric operator requires a number on the right");
|
|
2558
|
+
}
|
|
2559
|
+
if (op === K.PercentToken && addon) emit("lua-modulo");
|
|
2560
|
+
else emit("binary", op === K.AsteriskAsteriskToken ? "^" : node.operatorToken.getText());
|
|
2561
|
+
} else if (op === K.PlusToken) {
|
|
2562
|
+
const left = checker.getTypeAtLocation(node.left);
|
|
2563
|
+
const right = checker.getTypeAtLocation(node.right);
|
|
2564
|
+
if (knownNumber(left) && knownNumber(right)) emit("binary", "+");
|
|
2565
|
+
else if (knownString(left) && stringOrNumber(right)
|
|
2566
|
+
|| stringOrNumber(left) && knownString(right)) emit("binary", "..");
|
|
2567
|
+
else if (addonSource(node) && (knownString(left) || knownString(right))) {
|
|
2568
|
+
emit("binary", "..");
|
|
2569
|
+
if (!stringOrNumber(left)) { emit("call", 1); emit("global", "tostring"); }
|
|
2570
|
+
expression(node.left);
|
|
2571
|
+
if (!stringOrNumber(right)) { emit("call", 1); emit("global", "tostring"); }
|
|
2572
|
+
return expression(node.right);
|
|
2573
|
+
}
|
|
2574
|
+
else unsupported(node, "Plus requires numeric addition or known string concatenation");
|
|
2575
|
+
} else unsupported(node.operatorToken);
|
|
2576
|
+
expression(node.left);
|
|
2577
|
+
expression(node.right);
|
|
2578
|
+
return;
|
|
2579
|
+
}
|
|
2580
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === K.ExclamationToken) {
|
|
2581
|
+
emit("not");
|
|
2582
|
+
return booleanCondition(node.operand);
|
|
2583
|
+
}
|
|
2584
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === K.MinusToken) {
|
|
2585
|
+
numberOperand(node.operand, "Negation requires a known number");
|
|
2586
|
+
emit("negate");
|
|
2587
|
+
return expression(node.operand);
|
|
2588
|
+
}
|
|
2589
|
+
if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))
|
|
2590
|
+
&& (node.operator === K.PlusPlusToken || node.operator === K.MinusMinusToken)) return update(node);
|
|
2591
|
+
unsupported(node);
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
function statements(nodes, prelude = []) {
|
|
2595
|
+
const executable = nodes.filter(node => !ts.isTypeAliasDeclaration(node) && !ts.isInterfaceDeclaration(node)
|
|
2596
|
+
&& !(ts.isFunctionDeclaration(node) && !node.body));
|
|
2597
|
+
const functions = executable.filter(node => ts.isFunctionDeclaration(node) && node.name && node.body && !node.asteriskToken && !node.modifiers?.length);
|
|
2598
|
+
const variables = executable.filter(ts.isVariableStatement).flatMap(node =>
|
|
2599
|
+
[...node.declarationList.declarations].filter(declaration => functions.length || capturedVariables.has(declaration)));
|
|
2600
|
+
const hoisted = functions.length > 0 || variables.length > 0;
|
|
2601
|
+
const count = executable.reduce((total, node) => total + (ts.isVariableStatement(node) ? node.declarationList.declarations.length : 1),
|
|
2602
|
+
prelude.length + (hoisted ? 1 : 0));
|
|
2603
|
+
emit("block", count);
|
|
2604
|
+
for (const step of prelude) step();
|
|
2605
|
+
if (hoisted) {
|
|
2606
|
+
emit("predeclare-locals", ...functions.map(node => identifier(node.name)), ...variables.flatMap(declaration => bindingNames(declaration.name)));
|
|
2607
|
+
for (const node of functions) {
|
|
2608
|
+
const usesSelf = functionHasSelf(node);
|
|
2609
|
+
emit(usesSelf ? "local-function-self" : "local-function", identifier(node.name), ...parameters(node.parameters, usesSelf));
|
|
2610
|
+
body(node.body, node.parameters);
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
2613
|
+
for (const node of executable) if (!functions.includes(node)) statement(node, variables);
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
function boundIdentifiers(name) {
|
|
2617
|
+
if (ts.isIdentifier(name)) return [name];
|
|
2618
|
+
return name.elements.flatMap(element => ts.isBindingElement(element) ? boundIdentifiers(element.name) : []);
|
|
2619
|
+
}
|
|
2620
|
+
|
|
2621
|
+
function bindingNames(name) {
|
|
2622
|
+
return boundIdentifiers(name).map(identifier);
|
|
2623
|
+
}
|
|
2624
|
+
|
|
2625
|
+
function emitBindingPattern(pattern) {
|
|
2626
|
+
const tuple = ts.isArrayBindingPattern(pattern);
|
|
2627
|
+
emit("pattern-fields", pattern.elements.filter(ts.isBindingElement).length);
|
|
2628
|
+
for (const [index, element] of pattern.elements.entries()) {
|
|
2629
|
+
if (!ts.isBindingElement(element)) continue;
|
|
2630
|
+
if (element.dotDotDotToken) {
|
|
2631
|
+
if (!tuple || !ts.isIdentifier(element.name)) unsupported(element, "Nested rest requires a named array binding");
|
|
2632
|
+
emit("tuple-rest", index, identifier(element.name));
|
|
2633
|
+
continue;
|
|
2634
|
+
}
|
|
2635
|
+
const key = tuple ? index + 1 : text(propertyName(element.propertyName ?? element.name));
|
|
2636
|
+
const nested = !ts.isIdentifier(element.name);
|
|
2637
|
+
emit(tuple ? "tuple-field" : "object-field", key, nested ? "-" : identifier(element.name), element.initializer ? 1 : 0);
|
|
2638
|
+
if (element.initializer) expression(element.initializer);
|
|
2639
|
+
if (nested) emitBindingPattern(element.name);
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2643
|
+
function bindObject(pattern, read, own, predeclared = false) {
|
|
2644
|
+
if (!pattern.elements.length) unsupported(pattern, "Expected at least one object binding");
|
|
2645
|
+
if (pattern.elements.some(element => !ts.isIdentifier(element.name))) {
|
|
2646
|
+
const locals = bindingNames(pattern);
|
|
2647
|
+
if (!locals.length) unsupported(pattern, "Expected an object result binding");
|
|
2648
|
+
emit(predeclared ? "pattern-binding" : "pattern-local", ...locals);
|
|
2649
|
+
read();
|
|
2650
|
+
emitBindingPattern(pattern);
|
|
2651
|
+
return;
|
|
2652
|
+
}
|
|
2653
|
+
let rest = "-";
|
|
2654
|
+
const bindings = pattern.elements.flatMap(element => {
|
|
2655
|
+
if (element.dotDotDotToken) {
|
|
2656
|
+
const proven = own();
|
|
2657
|
+
if (!proven && !structuralLuaTable(pattern)) unsupported(element, "Object rest requires a proven native record");
|
|
2658
|
+
rest = identifier(element.name) + (proven ? "" : ":structural");
|
|
2659
|
+
return [];
|
|
2660
|
+
}
|
|
2661
|
+
const name = identifier(element.name);
|
|
2662
|
+
return [element.initializer ? `${name}:default` : name, text(propertyName(element.propertyName ?? element.name))];
|
|
2663
|
+
});
|
|
2664
|
+
emit(predeclared ? "object-binding" : "object-local", rest, ...bindings);
|
|
2665
|
+
read();
|
|
2666
|
+
for (const element of pattern.elements) if (element.initializer) expression(element.initializer);
|
|
2667
|
+
}
|
|
2668
|
+
|
|
2669
|
+
function tupleLocals(pattern) {
|
|
2670
|
+
const locals = pattern.elements.map(element => {
|
|
2671
|
+
if (ts.isOmittedExpression(element)) return "-";
|
|
2672
|
+
if (!ts.isBindingElement(element) || element.dotDotDotToken) unsupported(element);
|
|
2673
|
+
return identifier(element.name);
|
|
2674
|
+
});
|
|
2675
|
+
if (!locals.some(name => name !== "-")) unsupported(pattern, "Expected at least one result binding");
|
|
2676
|
+
return locals;
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
function compoundTuple(pattern) {
|
|
2680
|
+
return pattern.elements.some(element => ts.isBindingElement(element) && (element.dotDotDotToken || !ts.isIdentifier(element.name)));
|
|
2681
|
+
}
|
|
2682
|
+
|
|
2683
|
+
function bindTuple(pattern, read, predeclared = false) {
|
|
2684
|
+
if (compoundTuple(pattern)) {
|
|
2685
|
+
const locals = bindingNames(pattern);
|
|
2686
|
+
if (!locals.length) unsupported(pattern, "Expected a tuple result binding");
|
|
2687
|
+
emit(predeclared ? "pattern-binding" : "pattern-local", ...locals);
|
|
2688
|
+
read();
|
|
2689
|
+
emitBindingPattern(pattern);
|
|
2690
|
+
return;
|
|
2691
|
+
}
|
|
2692
|
+
const locals = tupleLocals(pattern);
|
|
2693
|
+
const bindings = pattern.elements;
|
|
2694
|
+
emit(predeclared ? "tuple-binding" : "tuple-local", ...locals.map((name, index) => bindings[index].initializer ? `${name}:default` : name));
|
|
2695
|
+
read();
|
|
2696
|
+
for (const element of bindings) if (element.initializer) expression(element.initializer);
|
|
2697
|
+
}
|
|
2698
|
+
|
|
2699
|
+
function referencesBinding(node, symbol) {
|
|
2700
|
+
if (ts.isTypeNode(node)) return;
|
|
2701
|
+
if (ts.isIdentifier(node)) {
|
|
2702
|
+
const found = ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node
|
|
2703
|
+
? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
2704
|
+
if (found === symbol) return node;
|
|
2705
|
+
}
|
|
2706
|
+
return ts.forEachChild(node, child => referencesBinding(child, symbol));
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
function multiArrayValue(node) {
|
|
2710
|
+
while (ts.isParenthesizedExpression(node)) node = node.expression;
|
|
2711
|
+
if (ts.isConditionalExpression(node)) {
|
|
2712
|
+
emit("select");
|
|
2713
|
+
booleanCondition(node.condition);
|
|
2714
|
+
multiArrayValue(node.whenTrue);
|
|
2715
|
+
return multiArrayValue(node.whenFalse);
|
|
2716
|
+
}
|
|
2717
|
+
if (!nativeMultiCall(node)) unsupported(node, "Destructure native multiple results from calls");
|
|
2718
|
+
emit("multi-array");
|
|
2719
|
+
return call(node, "multi");
|
|
2720
|
+
}
|
|
2721
|
+
|
|
2722
|
+
function localDeclaration(declaration, predeclared) {
|
|
2723
|
+
const initializer = declaration.initializer;
|
|
2724
|
+
if (ts.isObjectBindingPattern(declaration.name)) {
|
|
2725
|
+
if (!initializer) unsupported(declaration, "Expected an initialized object binding");
|
|
2726
|
+
return bindObject(declaration.name, () => expression(initializer), () => nativeRecord(initializer), predeclared);
|
|
2727
|
+
}
|
|
2728
|
+
if (ts.isArrayBindingPattern(declaration.name)) {
|
|
2729
|
+
if (!initializer) unsupported(declaration, "Array destructuring requires an initializer");
|
|
2730
|
+
const bindings = declaration.name.elements;
|
|
2731
|
+
const type = checker.getTypeAtLocation(initializer);
|
|
2732
|
+
if (type.getProperty("__tstlMultiReturn")) {
|
|
2733
|
+
if (!nativeMultiCall(initializer) || compoundTuple(declaration.name) || bindings.some(element => element.initializer)) {
|
|
2734
|
+
return bindTuple(declaration.name, () => multiArrayValue(initializer), predeclared);
|
|
2735
|
+
}
|
|
2736
|
+
return bindNativeTuple(tupleLocals(declaration.name), initializer, predeclared);
|
|
2737
|
+
}
|
|
2738
|
+
if (!knownTuple(type) && !nativeArrayReference(initializer)) unsupported(declaration, "Array destructuring requires a native tuple or sequence");
|
|
2739
|
+
return bindTuple(declaration.name, () => expression(initializer), predeclared);
|
|
2740
|
+
}
|
|
2741
|
+
const name = identifier(declaration.name);
|
|
2742
|
+
const capturesSelf = !predeclared && initializer && referencesBinding(initializer, checker.getSymbolAtLocation(declaration.name));
|
|
2743
|
+
emit(predeclared ? "assign" : capturesSelf ? "local-initializer" : "local", name);
|
|
2744
|
+
if (initializer && declaration.parent.flags & ts.NodeFlags.Const && denseMultiCall(initializer)) {
|
|
2745
|
+
emit("multi-array");
|
|
2746
|
+
return call(initializer, "multi");
|
|
2747
|
+
}
|
|
2748
|
+
if (initializer) return expression(initializer);
|
|
2749
|
+
emit("literal", "nil");
|
|
2750
|
+
}
|
|
2751
|
+
|
|
2752
|
+
function assignTuple(node) {
|
|
2753
|
+
const source = node.right;
|
|
2754
|
+
const type = checker.getTypeAtLocation(source);
|
|
2755
|
+
const nativeCall = ts.isCallExpression(source) && !(source.flags & ts.NodeFlags.OptionalChain)
|
|
2756
|
+
&& hasNativeMultiReturn(source, type);
|
|
2757
|
+
const targets = node.left.elements;
|
|
2758
|
+
const marker = nativeCall && ts.isIdentifier(source.expression) && nativeMultiFunction(valueSymbol(source.expression));
|
|
2759
|
+
if (targets.some(element => !ts.isOmittedExpression(element) && !ts.isIdentifier(element))) {
|
|
2760
|
+
const values = targets.map(target => ts.isOmittedExpression(target) ? "-" : `b${++unique}`);
|
|
2761
|
+
emit("scoped-block");
|
|
2762
|
+
emit("block", 1 + values.filter(name => name !== "-").length);
|
|
2763
|
+
const tuple = nativeCall ? undefined : `b${++unique}`;
|
|
2764
|
+
if (nativeCall) {
|
|
2765
|
+
emit("multi-local", ...values);
|
|
2766
|
+
if (marker) {
|
|
2767
|
+
emit("multi-list", source.arguments.length);
|
|
2768
|
+
callArguments(source.arguments);
|
|
2769
|
+
} else call(source, "multi");
|
|
2770
|
+
} else {
|
|
2771
|
+
if (!knownTuple(type) && !nativeArrayReference(source)) unsupported(source, "Tuple assignment requires a native tuple or sequence");
|
|
2772
|
+
emit("local", tuple);
|
|
2773
|
+
expression(source);
|
|
2774
|
+
}
|
|
2775
|
+
for (const [index, target] of targets.entries()) {
|
|
2776
|
+
if (ts.isOmittedExpression(target)) continue;
|
|
2777
|
+
if (ts.isIdentifier(target)) emit("assign", identifier(target));
|
|
2778
|
+
else if (ts.isPropertyAccessExpression(target) && !(target.flags & ts.NodeFlags.OptionalChain)) {
|
|
2779
|
+
emit("write", text(target.name.text));
|
|
2780
|
+
expression(target.expression);
|
|
2781
|
+
} else if (ts.isElementAccessExpression(target) && !(target.flags & ts.NodeFlags.OptionalChain)) {
|
|
2782
|
+
if (nativeArrayReference(target.expression)) {
|
|
2783
|
+
emit("lua-array-write");
|
|
2784
|
+
expression(target.expression);
|
|
2785
|
+
numericIndex(target.argumentExpression);
|
|
2786
|
+
} else {
|
|
2787
|
+
emit("table-write");
|
|
2788
|
+
tableIndex(target);
|
|
2789
|
+
}
|
|
2790
|
+
} else unsupported(target, "Expected a local or table field in a tuple assignment");
|
|
2791
|
+
if (nativeCall) emit("ref", values[index]);
|
|
2792
|
+
else {
|
|
2793
|
+
emit("array-index");
|
|
2794
|
+
emit("ref", tuple);
|
|
2795
|
+
emit("number", index);
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
return;
|
|
2799
|
+
}
|
|
2800
|
+
const names = targets.map(element => ts.isOmittedExpression(element) ? "-" : identifier(element));
|
|
2801
|
+
const locals = names.filter(name => name !== "-");
|
|
2802
|
+
if (!locals.length || new Set(locals).size !== locals.length) {
|
|
2803
|
+
unsupported(node.left, "Tuple assignment requires distinct local targets");
|
|
2804
|
+
}
|
|
2805
|
+
if (nativeCall && !marker) {
|
|
2806
|
+
return bindNativeTuple(names, source, true);
|
|
2807
|
+
}
|
|
2808
|
+
if (nativeCall || ts.isArrayLiteralExpression(source) && source.elements.every(element => !ts.isSpreadElement(element))) {
|
|
2809
|
+
const values = nativeCall ? source.arguments : source.elements;
|
|
2810
|
+
emit("multi-binding", ...names);
|
|
2811
|
+
emit("multi-list", values.length);
|
|
2812
|
+
for (const value of values) {
|
|
2813
|
+
if (ts.isOmittedExpression(value)) emit("literal", "nil");
|
|
2814
|
+
else expression(value);
|
|
2815
|
+
}
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
if (!knownTuple(type) && !nativeArrayReference(source)) unsupported(source, "Tuple assignment requires a native tuple or sequence");
|
|
2819
|
+
emit("tuple-binding", ...names);
|
|
2820
|
+
return expression(source);
|
|
2821
|
+
}
|
|
2822
|
+
|
|
2823
|
+
function assignObject(node) {
|
|
2824
|
+
if (!tableType(checker.getTypeAtLocation(node.right))) unsupported(node.right, "Object assignment requires a table");
|
|
2825
|
+
const source = `b${++unique}`;
|
|
2826
|
+
emit("scoped-block");
|
|
2827
|
+
emit("block", node.left.properties.length + 1);
|
|
2828
|
+
emit("local", source);
|
|
2829
|
+
expression(node.right);
|
|
2830
|
+
for (const property of node.left.properties) {
|
|
2831
|
+
const target = ts.isPropertyAssignment(property) ? property.initializer
|
|
2832
|
+
: ts.isShorthandPropertyAssignment(property) && !property.objectAssignmentInitializer ? property.name : undefined;
|
|
2833
|
+
if (!target) unsupported(property, "Object assignment requires a named field and an assignable target");
|
|
2834
|
+
emit("effect-value");
|
|
2835
|
+
emit("assignment");
|
|
2836
|
+
if (ts.isShorthandPropertyAssignment(property)) {
|
|
2837
|
+
emit("target-local", binding(checker.getShorthandAssignmentValueSymbol(property), target));
|
|
2838
|
+
} else assignable(target);
|
|
2839
|
+
emit("property", text(propertyName(property.name)));
|
|
2840
|
+
emit("ref", source);
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
|
|
2844
|
+
function protectedAncestor(node) {
|
|
2845
|
+
for (let child = node, parent = node.parent; parent && !ts.isFunctionLike(parent); child = parent, parent = parent.parent) {
|
|
2846
|
+
if (ts.isTryStatement(parent) && (child === parent.tryBlock || child === parent.catchClause)) return parent;
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
|
|
2850
|
+
function protectedBlockControl(block) {
|
|
2851
|
+
let returns = 0;
|
|
2852
|
+
function inspect(node) {
|
|
2853
|
+
if (ts.isFunctionLike(node)) return;
|
|
2854
|
+
if (ts.isReturnStatement(node)) {
|
|
2855
|
+
returns = Math.max(returns, node.expression ? 2 : 1);
|
|
2856
|
+
return;
|
|
2857
|
+
}
|
|
2858
|
+
if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) {
|
|
2859
|
+
if (node.label) return node;
|
|
2860
|
+
for (let parent = node.parent; parent !== block; parent = parent.parent) {
|
|
2861
|
+
if (ts.isIterationStatement(parent, false) || ts.isBreakStatement(node) && ts.isSwitchStatement(parent)) return;
|
|
2862
|
+
}
|
|
2863
|
+
return node;
|
|
2864
|
+
}
|
|
2865
|
+
return ts.forEachChild(node, inspect);
|
|
2866
|
+
}
|
|
2867
|
+
const invalid = inspect(block);
|
|
2868
|
+
return { returns, invalid };
|
|
2869
|
+
}
|
|
2870
|
+
|
|
2871
|
+
function nativeIteratorBindings(pattern, prelude) {
|
|
2872
|
+
return pattern.elements.map(element => {
|
|
2873
|
+
if (ts.isOmittedExpression(element)) return "-";
|
|
2874
|
+
if (element.dotDotDotToken || element.initializer) unsupported(element, "Native iterator bindings require fixed slots");
|
|
2875
|
+
const { name } = element;
|
|
2876
|
+
if (ts.isIdentifier(name)) return identifier(name);
|
|
2877
|
+
const type = checker.getTypeAtLocation(name);
|
|
2878
|
+
const temporary = `b${++unique}`;
|
|
2879
|
+
const read = () => emit("ref", temporary);
|
|
2880
|
+
if (ts.isArrayBindingPattern(name) && (knownTuple(type) || nativeArrayReference(name))) prelude.push(() => bindTuple(name, read));
|
|
2881
|
+
else if (ts.isObjectBindingPattern(name) && tableType(type)) prelude.push(() => bindObject(name, read, () => isOwnedRecord(type)));
|
|
2882
|
+
else unsupported(name, "A nested iterator binding requires a native tuple or table");
|
|
2883
|
+
return temporary;
|
|
2884
|
+
});
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
function forOf(node) {
|
|
2888
|
+
const kind = collectionReference(node.expression);
|
|
2889
|
+
const multiItems = denseMultiCall(node.expression);
|
|
2890
|
+
const array = multiItems || nativeArrayReference(node.expression) || knownTuple(checker.getTypeAtLocation(node.expression));
|
|
2891
|
+
const arrayOrSet = arrayOrSetReference(node.expression);
|
|
2892
|
+
const iterator = nativeLuaStringCall(node.expression, "gmatch") || nativeMatchIterator(node.expression);
|
|
2893
|
+
const rawPairs = ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression)
|
|
2894
|
+
&& node.expression.expression.text === "pairs" && hostGlobal(valueSymbol(node.expression.expression));
|
|
2895
|
+
const projection = collectionProjection(node.expression);
|
|
2896
|
+
const routerEntries = nativeRouterEntries(node.expression);
|
|
2897
|
+
const rawIteration = nativeLuaIteration(node.expression);
|
|
2898
|
+
const arrayEntries = ts.isCallExpression(node.expression) && ts.isPropertyAccessExpression(node.expression.expression)
|
|
2899
|
+
&& !node.expression.arguments.length && !(node.expression.flags & ts.NodeFlags.OptionalChain)
|
|
2900
|
+
&& arrayMethod(checker.getResolvedSignature(node.expression)?.getDeclaration()) === "entries"
|
|
2901
|
+
&& (denseArrayReference(node.expression.expression.expression) || luaArrayAbiReference(node.expression.expression.expression))
|
|
2902
|
+
? node.expression.expression.expression : undefined;
|
|
2903
|
+
if ((!kind && !array && !arrayOrSet && !iterator && !rawPairs && !projection && !rawIteration && !arrayEntries && !routerEntries)
|
|
2904
|
+
|| kind === "weakmap"
|
|
2905
|
+
|| node.awaitModifier || !ts.isVariableDeclarationList(node.initializer)
|
|
2906
|
+
|| !(node.initializer.flags & ts.NodeFlags.Const) || node.initializer.declarations.length !== 1) {
|
|
2907
|
+
unsupported(node, "Iteration currently requires a native collection and a const binding");
|
|
2908
|
+
}
|
|
2909
|
+
const [{ name }] = node.initializer.declarations;
|
|
2910
|
+
const continued = hasContinue(node.statement) ? 1 : 0;
|
|
2911
|
+
let prelude = [];
|
|
2912
|
+
if (iterator) {
|
|
2913
|
+
if (ts.isIdentifier(name)) emit("for-native-values", continued, identifier(name));
|
|
2914
|
+
else if (ts.isArrayBindingPattern(name) && name.elements.length && hasNativeMultiReturn(name, checker.getTypeAtLocation(name))) {
|
|
2915
|
+
emit("for-native-values", continued, ...nativeIteratorBindings(name, prelude));
|
|
2916
|
+
} else unsupported(name, "String captures require a direct iterator binding");
|
|
2917
|
+
} else if (rawPairs) {
|
|
2918
|
+
if (!ts.isArrayBindingPattern(name) || name.elements.length > 2 || name.elements.some(element => element.initializer)) {
|
|
2919
|
+
unsupported(name, "Native pairs require direct key and value bindings");
|
|
2920
|
+
}
|
|
2921
|
+
const bindings = nativeIteratorBindings(name, prelude);
|
|
2922
|
+
emit("for-native-values", continued, ...(bindings.length ? bindings : ["-"]));
|
|
2923
|
+
} else if (rawIteration === "iterator") {
|
|
2924
|
+
if (ts.isArrayBindingPattern(name)) {
|
|
2925
|
+
if (!name.elements.length || name.elements.some(element => element.initializer)
|
|
2926
|
+
|| !hasNativeMultiReturn(name, checker.getTypeAtLocation(name))) {
|
|
2927
|
+
unsupported(name, "A Lua iterator requires direct multiple-result bindings");
|
|
2928
|
+
}
|
|
2929
|
+
emit("for-native-values", continued, ...nativeIteratorBindings(name, prelude));
|
|
2930
|
+
} else if (ts.isIdentifier(name) && !hasNativeMultiReturn(name, checker.getTypeAtLocation(name))) {
|
|
2931
|
+
emit("for-native-values", continued, identifier(name));
|
|
2932
|
+
} else unsupported(name, "Bind the native iterator result directly");
|
|
2933
|
+
} else if (rawIteration === "pairs" || rawIteration === "keys") {
|
|
2934
|
+
if (rawIteration === "keys" && ts.isIdentifier(name)) emit("for-raw-table", continued, identifier(name));
|
|
2935
|
+
else if (rawIteration === "pairs" && ts.isArrayBindingPattern(name) && name.elements.length > 0 && name.elements.length <= 2
|
|
2936
|
+
&& !name.elements.some(element => element.initializer)) {
|
|
2937
|
+
emit("for-raw-table", continued, ...nativeIteratorBindings(name, prelude));
|
|
2938
|
+
}
|
|
2939
|
+
else unsupported(name, "Lua table iteration requires direct key and value bindings");
|
|
2940
|
+
} else if (routerEntries) {
|
|
2941
|
+
if (ts.isIdentifier(name)) emit("for-map-entry-record", continued, identifier(name));
|
|
2942
|
+
else if (ts.isArrayBindingPattern(name) && name.elements.length > 0 && name.elements.length <= 2) {
|
|
2943
|
+
emit("for-map-entries", continued, ...nativeIteratorBindings(name, prelude));
|
|
2944
|
+
} else unsupported(name, "Router entry iteration requires a tuple or named binding");
|
|
2945
|
+
} else if (projection) {
|
|
2946
|
+
if (ts.isIdentifier(name)) {
|
|
2947
|
+
if (projection.field === "key") emit("for-collection", continued, identifier(name));
|
|
2948
|
+
else emit("for-collection", continued, "-", identifier(name));
|
|
2949
|
+
} else if (ts.isObjectBindingPattern(name) && tableType(checker.getTypeAtLocation(name))) {
|
|
2950
|
+
const item = `b${++unique}`;
|
|
2951
|
+
if (projection.field === "key") emit("for-collection", continued, item);
|
|
2952
|
+
else emit("for-collection", continued, "-", item);
|
|
2953
|
+
prelude = [() => bindObject(name, () => emit("ref", item), () => isOwnedRecord(checker.getTypeAtLocation(name)))];
|
|
2954
|
+
} else unsupported(name, "Expected an identifier or object binding for a Map key or value");
|
|
2955
|
+
} else if (arrayEntries) {
|
|
2956
|
+
if (!ts.isArrayBindingPattern(name) || !name.elements.length || name.elements.length > 2 || name.elements.some(element => element.initializer)) {
|
|
2957
|
+
unsupported(name, "Array entries require direct index and item bindings");
|
|
2958
|
+
}
|
|
2959
|
+
const [index, item = "-"] = nativeIteratorBindings(name, prelude);
|
|
2960
|
+
emit("for-array-entries", continued, index, item);
|
|
2961
|
+
} else if (arrayOrSet) {
|
|
2962
|
+
emit("for-array-or-set", continued, identifier(name));
|
|
2963
|
+
} else if (array) {
|
|
2964
|
+
if (ts.isIdentifier(name)) emit("for-array", continued, identifier(name));
|
|
2965
|
+
else if (ts.isObjectBindingPattern(name)) {
|
|
2966
|
+
const element = checker.getIndexTypeOfType(checker.getTypeAtLocation(node.expression), ts.IndexKind.Number);
|
|
2967
|
+
if (!element || !tableType(element)) unsupported(name, "Array object bindings require table items");
|
|
2968
|
+
const item = `b${++unique}`;
|
|
2969
|
+
emit("for-array", continued, item);
|
|
2970
|
+
prelude = [() => bindObject(name, () => emit("ref", item), () => isOwnedRecord(element))];
|
|
2971
|
+
}
|
|
2972
|
+
else if ((denseArrayReference(node.expression) || luaArrayAbiReference(node.expression)) && ts.isArrayBindingPattern(name)) {
|
|
2973
|
+
const element = checker.getIndexTypeOfType(checker.getTypeAtLocation(node.expression), ts.IndexKind.Number);
|
|
2974
|
+
if (!element || !knownTuple(element)) unsupported(name, "Array loop destructuring requires tuple items");
|
|
2975
|
+
if (compoundTuple(name) || name.elements.some(binding => binding.initializer)) {
|
|
2976
|
+
const item = `b${++unique}`;
|
|
2977
|
+
emit("for-array", continued, item);
|
|
2978
|
+
prelude = [() => bindTuple(name, () => emit("ref", item))];
|
|
2979
|
+
} else emit("for-array-tuple", continued, ...tupleLocals(name));
|
|
2980
|
+
} else unsupported(name);
|
|
2981
|
+
} else if (kind === "set") emit("for-collection", continued, identifier(name));
|
|
2982
|
+
else {
|
|
2983
|
+
if (!ts.isArrayBindingPattern(name) || !name.elements.length || name.elements.length > 2) {
|
|
2984
|
+
unsupported(name, "A Map loop requires a key binding or key and value bindings");
|
|
2985
|
+
}
|
|
2986
|
+
emit("for-collection", continued, ...nativeIteratorBindings(name, prelude));
|
|
2987
|
+
}
|
|
2988
|
+
if (rawPairs || rawIteration === "iterator" && ts.isCallExpression(node.expression)) {
|
|
2989
|
+
emit("iterator-call");
|
|
2990
|
+
call(node.expression, "iterator");
|
|
2991
|
+
} else if (multiItems) {
|
|
2992
|
+
emit("multi-array");
|
|
2993
|
+
call(node.expression, "multi");
|
|
2994
|
+
} else expression(projection?.source ?? arrayEntries ?? node.expression);
|
|
2995
|
+
const block = node.statement;
|
|
2996
|
+
statements(ts.isBlock(block) ? block.statements : [block], prelude);
|
|
2997
|
+
}
|
|
2998
|
+
|
|
2999
|
+
function hasContinue(node) {
|
|
3000
|
+
if (ts.isContinueStatement(node)) return !node.label;
|
|
3001
|
+
if (ts.isFunctionLike(node) || ts.isIterationStatement(node, false)) return false;
|
|
3002
|
+
return ts.forEachChild(node, child => hasContinue(child) || undefined) === true;
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
function forIn(node) {
|
|
3006
|
+
const [binding] = ts.isVariableDeclarationList(node.initializer) ? node.initializer.declarations : [];
|
|
3007
|
+
if (!binding || node.initializer.declarations.length !== 1 || !(node.initializer.flags & ts.NodeFlags.BlockScoped)
|
|
3008
|
+
|| !ts.isIdentifier(binding.name) || !structuralLuaTable(node.expression) || collectionReference(node.expression)) {
|
|
3009
|
+
unsupported(node, "Key iteration requires a Lua table and a local identifier");
|
|
3010
|
+
}
|
|
3011
|
+
emit("for-raw-table", hasContinue(node.statement) ? 1 : 0, identifier(binding.name));
|
|
3012
|
+
expression(node.expression);
|
|
3013
|
+
body(node.statement);
|
|
3014
|
+
}
|
|
3015
|
+
|
|
3016
|
+
function nativeSwitch(node) {
|
|
3017
|
+
function breaksSwitch(child) {
|
|
3018
|
+
if (ts.isBreakStatement(child)) return child.label === undefined;
|
|
3019
|
+
if (ts.isFunctionLike(child) || ts.isIterationStatement(child, false) || ts.isSwitchStatement(child)) return false;
|
|
3020
|
+
return ts.forEachChild(child, nested => breaksSwitch(nested) || undefined) === true;
|
|
3021
|
+
}
|
|
3022
|
+
function switchArm(arm) {
|
|
3023
|
+
if (arm.breakable) {
|
|
3024
|
+
emit("block", 1);
|
|
3025
|
+
emit("breakable-block");
|
|
3026
|
+
}
|
|
3027
|
+
statements(arm.body);
|
|
3028
|
+
}
|
|
3029
|
+
const arms = node.caseBlock.clauses;
|
|
3030
|
+
let fallback;
|
|
3031
|
+
const cases = [];
|
|
3032
|
+
let labels = [];
|
|
3033
|
+
for (const arm of arms) {
|
|
3034
|
+
if (ts.isCaseClause(arm)) {
|
|
3035
|
+
labels.push(arm.expression);
|
|
3036
|
+
if (arm.statements.length === 0) continue;
|
|
3037
|
+
} else if (labels.length) {
|
|
3038
|
+
unsupported(arm, "A grouped native switch case cannot fall through to default");
|
|
3039
|
+
}
|
|
3040
|
+
const last = arm.statements.at(-1);
|
|
3041
|
+
const terminal = last && (ts.isBlock(last) ? last.statements.at(-1) : last);
|
|
3042
|
+
const endsInBreak = last && ts.isBreakStatement(last) && !last.label;
|
|
3043
|
+
const body = endsInBreak ? arm.statements.slice(0, -1) : arm.statements;
|
|
3044
|
+
const terminates = terminal && (ts.isReturnStatement(terminal) || ts.isBreakStatement(terminal) && !terminal.label);
|
|
3045
|
+
const breakable = body.some(breaksSwitch);
|
|
3046
|
+
if ((!terminates && arm !== arms.at(-1)) || breakable && body.some(hasContinue)
|
|
3047
|
+
|| body.some(child => ts.isVariableStatement(child) || ts.isFunctionDeclaration(child) || ts.isClassDeclaration(child))) {
|
|
3048
|
+
unsupported(arm, "Native switch requires terminal arms with block-scoped declarations");
|
|
3049
|
+
}
|
|
3050
|
+
if (ts.isCaseClause(arm)) {
|
|
3051
|
+
cases.push({ labels, body, breakable });
|
|
3052
|
+
labels = [];
|
|
3053
|
+
} else fallback = { body, breakable };
|
|
3054
|
+
}
|
|
3055
|
+
if (labels.length) cases.push({ labels, body: [] });
|
|
3056
|
+
emit("switch", cases.length, fallback === undefined ? 0 : 1);
|
|
3057
|
+
expression(node.expression);
|
|
3058
|
+
for (const arm of cases) {
|
|
3059
|
+
emit("case", ...arm.labels.map(label => {
|
|
3060
|
+
const type = checker.getTypeAtLocation(label);
|
|
3061
|
+
const alternatives = type.isUnion() ? type.types : [type];
|
|
3062
|
+
const scalars = T.StringLike | T.NumberLike | T.BooleanLike | T.Undefined | T.Null;
|
|
3063
|
+
return alternatives.every(value => value.flags & scalars) ? "value" : "identity";
|
|
3064
|
+
}));
|
|
3065
|
+
for (const label of arm.labels) expression(label);
|
|
3066
|
+
switchArm(arm);
|
|
3067
|
+
}
|
|
3068
|
+
if (fallback) switchArm(fallback);
|
|
3069
|
+
}
|
|
3070
|
+
|
|
3071
|
+
function forClassic(node) {
|
|
3072
|
+
const declarations = node.initializer;
|
|
3073
|
+
const continued = hasContinue(node.statement) ? 1 : 0;
|
|
3074
|
+
if (!declarations) {
|
|
3075
|
+
emit(node.incrementor ? "for-existing" : "while", continued);
|
|
3076
|
+
} else {
|
|
3077
|
+
if (!ts.isVariableDeclarationList(declarations) || !(declarations.flags & ts.NodeFlags.Let)
|
|
3078
|
+
|| declarations.declarations.length !== 1 || !declarations.declarations[0].initializer) {
|
|
3079
|
+
unsupported(node, "A classic for loop requires one initialized let binding");
|
|
3080
|
+
}
|
|
3081
|
+
const [{ name, initializer }] = declarations.declarations;
|
|
3082
|
+
emit("for-classic", continued, identifier(name));
|
|
3083
|
+
expression(initializer);
|
|
3084
|
+
}
|
|
3085
|
+
if (node.condition) booleanCondition(node.condition);
|
|
3086
|
+
else emit("literal", "true");
|
|
3087
|
+
body(node.statement);
|
|
3088
|
+
if (!declarations && !node.incrementor) return;
|
|
3089
|
+
emit("block", node.incrementor ? 1 : 0);
|
|
3090
|
+
if (node.incrementor) {
|
|
3091
|
+
emit("effect-value");
|
|
3092
|
+
expression(node.incrementor);
|
|
3093
|
+
}
|
|
3094
|
+
}
|
|
3095
|
+
|
|
3096
|
+
function statement(node, predeclared = []) {
|
|
3097
|
+
if (ts.isBlock(node)) {
|
|
3098
|
+
emit("scoped-block");
|
|
3099
|
+
return body(node);
|
|
3100
|
+
}
|
|
3101
|
+
if (ts.isReturnStatement(node)) {
|
|
3102
|
+
let parent = node.parent;
|
|
3103
|
+
while (parent && !ts.isFunctionLike(parent)) parent = parent.parent;
|
|
3104
|
+
if (protectedAncestor(node)) {
|
|
3105
|
+
if (parent && ts.isConstructorDeclaration(parent)) unsupported(node, "Protected constructor returns are unsupported");
|
|
3106
|
+
if (!node.expression) return emit("try-exit");
|
|
3107
|
+
if (hasNativeMultiReturn(node.expression, checker.getTypeAtLocation(node.expression))) {
|
|
3108
|
+
unsupported(node, "Protected multiple-result returns are unsupported");
|
|
3109
|
+
}
|
|
3110
|
+
emit("try-return");
|
|
3111
|
+
return expression(node.expression);
|
|
3112
|
+
}
|
|
3113
|
+
if (parent && ts.isConstructorDeclaration(parent)) {
|
|
3114
|
+
if (node.expression) unsupported(node, "Constructors returning a replacement instance are unsupported");
|
|
3115
|
+
emit("return");
|
|
3116
|
+
return emit("self");
|
|
3117
|
+
}
|
|
3118
|
+
return returnValue(node.expression, parent);
|
|
3119
|
+
}
|
|
3120
|
+
if (ts.isThrowStatement(node)) {
|
|
3121
|
+
emit("raise");
|
|
3122
|
+
return expression(node.expression);
|
|
3123
|
+
}
|
|
3124
|
+
if (ts.isTryStatement(node)) {
|
|
3125
|
+
const { tryBlock, catchClause, finallyBlock } = node;
|
|
3126
|
+
const attempted = protectedBlockControl(tryBlock);
|
|
3127
|
+
const caught = catchClause && protectedBlockControl(catchClause.block);
|
|
3128
|
+
const invalid = attempted.invalid ?? caught?.invalid;
|
|
3129
|
+
if (invalid) unsupported(invalid, "Protected blocks require local loop control");
|
|
3130
|
+
const catchName = catchClause?.variableDeclaration?.name;
|
|
3131
|
+
emit("try", catchClause ? 1 : 0, catchName ? identifier(catchName) : "-", finallyBlock ? 1 : 0,
|
|
3132
|
+
Math.max(attempted.returns, caught?.returns ?? 0), protectedAncestor(node) ? 1 : 0);
|
|
3133
|
+
body(tryBlock);
|
|
3134
|
+
if (catchClause) body(catchClause.block);
|
|
3135
|
+
if (finallyBlock) body(finallyBlock);
|
|
3136
|
+
return;
|
|
3137
|
+
}
|
|
3138
|
+
if (ts.isIfStatement(node)) {
|
|
3139
|
+
emit("if", node.elseStatement ? 1 : 0);
|
|
3140
|
+
booleanCondition(node.expression);
|
|
3141
|
+
body(node.thenStatement);
|
|
3142
|
+
if (node.elseStatement) body(node.elseStatement);
|
|
3143
|
+
return;
|
|
3144
|
+
}
|
|
3145
|
+
if (ts.isVariableStatement(node) && !node.modifiers?.length && node.declarationList.flags & ts.NodeFlags.BlockScoped) {
|
|
3146
|
+
for (const declaration of node.declarationList.declarations) localDeclaration(declaration, predeclared.includes(declaration));
|
|
3147
|
+
return;
|
|
3148
|
+
}
|
|
3149
|
+
if (ts.isForOfStatement(node)) return forOf(node);
|
|
3150
|
+
if (ts.isForInStatement(node)) return forIn(node);
|
|
3151
|
+
if (ts.isForStatement(node)) return forClassic(node);
|
|
3152
|
+
if (ts.isWhileStatement(node)) {
|
|
3153
|
+
emit("while", hasContinue(node.statement) ? 1 : 0);
|
|
3154
|
+
booleanCondition(node.expression);
|
|
3155
|
+
return body(node.statement);
|
|
3156
|
+
}
|
|
3157
|
+
if (ts.isDoStatement(node)) {
|
|
3158
|
+
emit("do-while", hasContinue(node.statement) ? 1 : 0);
|
|
3159
|
+
body(node.statement);
|
|
3160
|
+
return booleanCondition(node.expression);
|
|
3161
|
+
}
|
|
3162
|
+
if (ts.isBreakStatement(node) && !node.label) return emit("break");
|
|
3163
|
+
if (ts.isContinueStatement(node) && !node.label) return emit("continue");
|
|
3164
|
+
if (ts.isSwitchStatement(node)) return nativeSwitch(node);
|
|
3165
|
+
if (ts.isExpressionStatement(node)) {
|
|
3166
|
+
let value = node.expression;
|
|
3167
|
+
while (ts.isParenthesizedExpression(value)) value = value.expression;
|
|
3168
|
+
if (ts.isVoidExpression(value) || ts.isPropertyAccessExpression(value) || ts.isElementAccessExpression(value)) {
|
|
3169
|
+
emit("effect-value");
|
|
3170
|
+
return expression(ts.isVoidExpression(value) ? value.expression : value);
|
|
3171
|
+
}
|
|
3172
|
+
if (ts.isDeleteExpression(value)) {
|
|
3173
|
+
const target = value.expression;
|
|
3174
|
+
if (ts.isPropertyAccessExpression(target) && !(target.flags & ts.NodeFlags.OptionalChain)
|
|
3175
|
+
&& tableType(checker.getTypeAtLocation(target.expression)) && !collectionReference(target.expression)
|
|
3176
|
+
&& !nativeArrayReference(target.expression)) {
|
|
3177
|
+
emit("write", text(target.name.text));
|
|
3178
|
+
expression(target.expression);
|
|
3179
|
+
return emit("literal", "nil");
|
|
3180
|
+
}
|
|
3181
|
+
if (!ts.isElementAccessExpression(target) || target.flags & ts.NodeFlags.OptionalChain) {
|
|
3182
|
+
unsupported(value, "Delete requires a direct Lua table or array slot");
|
|
3183
|
+
}
|
|
3184
|
+
if (nativeArrayReference(target.expression)) {
|
|
3185
|
+
emit("lua-array-write");
|
|
3186
|
+
expression(target.expression);
|
|
3187
|
+
numericIndex(target.argumentExpression);
|
|
3188
|
+
} else {
|
|
3189
|
+
emit("table-write");
|
|
3190
|
+
tableIndex(target);
|
|
3191
|
+
}
|
|
3192
|
+
return emit("literal", "nil");
|
|
3193
|
+
}
|
|
3194
|
+
if ((ts.isPrefixUnaryExpression(value) || ts.isPostfixUnaryExpression(value))
|
|
3195
|
+
&& (value.operator === K.PlusPlusToken || value.operator === K.MinusMinusToken)) {
|
|
3196
|
+
emit("effect-value");
|
|
3197
|
+
return update(value);
|
|
3198
|
+
}
|
|
3199
|
+
if (ts.isCallExpression(value)) {
|
|
3200
|
+
if (rawTableOperation(value, checker.getResolvedSignature(value)?.getDeclaration(), true)) return;
|
|
3201
|
+
emit("effect");
|
|
3202
|
+
return call(value, "discard");
|
|
3203
|
+
}
|
|
3204
|
+
if (ts.isBinaryExpression(value) && compoundOperators.has(value.operatorToken.kind)) {
|
|
3205
|
+
emit("effect-value");
|
|
3206
|
+
return compoundAssignment(value);
|
|
3207
|
+
}
|
|
3208
|
+
if (ts.isBinaryExpression(value) && value.operatorToken.kind === K.QuestionQuestionEqualsToken && ts.isIdentifier(value.left)) {
|
|
3209
|
+
emit("nil-assign", identifier(value.left));
|
|
3210
|
+
return expression(value.right);
|
|
3211
|
+
}
|
|
3212
|
+
if (ts.isBinaryExpression(value) && [K.QuestionQuestionEqualsToken, K.BarBarEqualsToken, K.AmpersandAmpersandEqualsToken]
|
|
3213
|
+
.includes(value.operatorToken.kind)) {
|
|
3214
|
+
emit("effect-value");
|
|
3215
|
+
return expression(value);
|
|
3216
|
+
}
|
|
3217
|
+
if (ts.isBinaryExpression(value) && value.operatorToken.kind === K.EqualsToken) {
|
|
3218
|
+
if (ts.isArrayLiteralExpression(value.left)) return assignTuple(value);
|
|
3219
|
+
if (ts.isObjectLiteralExpression(value.left)) return assignObject(value);
|
|
3220
|
+
if (ts.isPropertyAccessExpression(value.left) && value.left.name.text === "length"
|
|
3221
|
+
&& !(value.left.flags & ts.NodeFlags.OptionalChain)
|
|
3222
|
+
&& (denseArrayReference(value.left.expression) || addonSource(node) && ts.isNumericLiteral(value.right)
|
|
3223
|
+
&& Number(value.right.text) === 0 && luaArrayAbiReference(value.left.expression))) {
|
|
3224
|
+
emit("array-trim");
|
|
3225
|
+
expression(value.left.expression);
|
|
3226
|
+
return numericIndex(value.right);
|
|
3227
|
+
}
|
|
3228
|
+
if (ts.isElementAccessExpression(value.left) && !(value.left.flags & ts.NodeFlags.OptionalChain)
|
|
3229
|
+
&& denseArrayReference(value.left.expression)) {
|
|
3230
|
+
denseValue(value.right);
|
|
3231
|
+
emit("array-write");
|
|
3232
|
+
expression(value.left.expression);
|
|
3233
|
+
numericIndex(value.left.argumentExpression);
|
|
3234
|
+
return expression(value.right);
|
|
3235
|
+
}
|
|
3236
|
+
if (ts.isElementAccessExpression(value.left) && !(value.left.flags & ts.NodeFlags.OptionalChain)
|
|
3237
|
+
&& (nativeArrayReference(value.left.expression) || knownTuple(checker.getTypeAtLocation(value.left.expression)))) {
|
|
3238
|
+
emit("lua-array-write");
|
|
3239
|
+
expression(value.left.expression);
|
|
3240
|
+
numericIndex(value.left.argumentExpression);
|
|
3241
|
+
return expression(value.right);
|
|
3242
|
+
}
|
|
3243
|
+
if (ts.isElementAccessExpression(value.left) && !(value.left.flags & ts.NodeFlags.OptionalChain)) {
|
|
3244
|
+
emit("table-write");
|
|
3245
|
+
tableIndex(value.left);
|
|
3246
|
+
return expression(value.right);
|
|
3247
|
+
}
|
|
3248
|
+
if (ts.isIdentifier(value.left)) emit("assign", identifier(value.left));
|
|
3249
|
+
else if (ts.isPropertyAccessExpression(value.left) && !(value.left.flags & ts.NodeFlags.OptionalChain)) {
|
|
3250
|
+
if (collectionReference(value.left.expression)) unsupported(value.left, "Native collections do not accept property writes");
|
|
3251
|
+
if (value.left.name.text === "length" && nativeArrayReference(value.left.expression)) unsupported(value.left, "Only dense arrays can change length");
|
|
3252
|
+
emit("write", text(value.left.name.text));
|
|
3253
|
+
expression(value.left.expression);
|
|
3254
|
+
} else unsupported(value.left, "Assignment requires a local variable or a named property");
|
|
3255
|
+
return expression(value.right);
|
|
3256
|
+
}
|
|
3257
|
+
}
|
|
3258
|
+
unsupported(node);
|
|
3259
|
+
}
|
|
3260
|
+
|
|
3261
|
+
function moduleOf(node) {
|
|
3262
|
+
const symbol = checker.getSymbolAtLocation(node.moduleSpecifier);
|
|
3263
|
+
const file = symbol?.declarations?.find(ts.isSourceFile);
|
|
3264
|
+
if (!file || file.isDeclarationFile || !/\.tsx?$/.test(file.fileName)) {
|
|
3265
|
+
unsupported(node, "Runtime imports must resolve to a TypeScript implementation");
|
|
3266
|
+
}
|
|
3267
|
+
return file;
|
|
3268
|
+
}
|
|
3269
|
+
|
|
3270
|
+
function inRoot(root, file) {
|
|
3271
|
+
const path = relative(root, file);
|
|
3272
|
+
return !isAbsolute(path) && path.split(/[\\/]/)[0] !== "..";
|
|
3273
|
+
}
|
|
3274
|
+
|
|
3275
|
+
function compilerOwnsPath(path) {
|
|
3276
|
+
const root = inRoot(sdkRoot, path) ? sdkRoot : workspaceRoot;
|
|
3277
|
+
return inRoot(root, path) && !relative(root, path).split(/[\\/]/).some(part => part.toLowerCase() === "node_modules");
|
|
3278
|
+
}
|
|
3279
|
+
|
|
3280
|
+
function usesAddonUi(file, symbol) {
|
|
3281
|
+
const jsx = file.fileName.endsWith(".tsx") && [options.jsxFactory, options.jsxFragmentFactory]
|
|
3282
|
+
.some(factory => factory?.startsWith("UI."));
|
|
3283
|
+
if (!jsx && !file.text.includes("UI")) return false;
|
|
3284
|
+
function inspect(node) {
|
|
3285
|
+
if (ts.isTypeNode(node)) return;
|
|
3286
|
+
if (ts.isIdentifier(node) && node.text === "UI" && checker.getSymbolAtLocation(node) === symbol) return true;
|
|
3287
|
+
if (jsx && (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node))
|
|
3288
|
+
&& checker.resolveName("UI", node, ts.SymbolFlags.Value, false) === symbol) return true;
|
|
3289
|
+
return ts.forEachChild(node, inspect);
|
|
3290
|
+
}
|
|
3291
|
+
return inspect(file) === true;
|
|
3292
|
+
}
|
|
3293
|
+
|
|
3294
|
+
function moduleIdentity(path, source) {
|
|
3295
|
+
if (!link) return;
|
|
3296
|
+
const sdkFile = inRoot(sdkRoot, path) && !addonOwnsPath(path);
|
|
3297
|
+
const name = relative(sdkFile ? sdkRoot : workspaceRoot, path).replaceAll("\\", "/");
|
|
3298
|
+
const key = `${sdkFile ? "sdk" : "addon"}/${name}`;
|
|
3299
|
+
emit("linked-module", text(key), createHash("sha256").update(source).digest("hex"));
|
|
3300
|
+
}
|
|
3301
|
+
|
|
3302
|
+
function nativeImageDeclaration(declaration) {
|
|
3303
|
+
return declaration && relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "src/image-imports.d.ts";
|
|
3304
|
+
}
|
|
3305
|
+
|
|
3306
|
+
function addonTexture(node) {
|
|
3307
|
+
const specifier = node.moduleSpecifier;
|
|
3308
|
+
if (!addon || !ts.isStringLiteral(specifier)) return;
|
|
3309
|
+
const extension = /\.(tga|png|jpe?g|webp)$/iu.exec(specifier.text)?.[1]?.toLowerCase();
|
|
3310
|
+
if (!extension) return;
|
|
3311
|
+
const declaration = checker.getSymbolAtLocation(specifier)?.declarations;
|
|
3312
|
+
if (!declaration?.some(value => ts.isModuleDeclaration(value) && ts.isStringLiteral(value.name)
|
|
3313
|
+
&& value.name.text === `*.${extension}` && nativeImageDeclaration(value))) return;
|
|
3314
|
+
if (!node.importClause?.name || node.importClause.namedBindings) unsupported(node, "An addon texture requires one default import");
|
|
3315
|
+
if (!/^\.{1,2}[/\\]/u.test(specifier.text)) unsupported(node, "Addon textures require relative imports");
|
|
3316
|
+
const requested = resolve(node.getSourceFile().fileName, "..", specifier.text);
|
|
3317
|
+
if (!inRoot(workspaceRoot, requested) || !ts.sys.fileExists(requested)) unsupported(node, "An addon texture must exist inside the workspace");
|
|
3318
|
+
const source = realpathSync(requested);
|
|
3319
|
+
if (!inRoot(workspaceRoot, source)) unsupported(node, "An addon texture must resolve inside the workspace");
|
|
3320
|
+
const root = resolve(workspaceRoot, "Assets");
|
|
3321
|
+
const direct = extension === "tga" && inRoot(root, requested) && inRoot(realpathSync(root), source);
|
|
3322
|
+
if (!direct && !assets) unsupported(node, "A converted addon texture requires --addon-assets-dir");
|
|
3323
|
+
const data = readFileSync(source);
|
|
3324
|
+
const hash = createHash("sha256").update(data).digest("hex");
|
|
3325
|
+
const path = direct ? relative(workspaceRoot, requested).replaceAll("\\", "/") : `KumiGenerated/Assets/${hash}.tga`;
|
|
3326
|
+
if (!textureIds.has(path)) {
|
|
3327
|
+
const id = ids.size + textureIds.size + 1;
|
|
3328
|
+
textureIds.set(path, id);
|
|
3329
|
+
if (link) emit("linked-module", text(`asset/${path}`), hash);
|
|
3330
|
+
if (direct) emit("direct-tga", id, text(path));
|
|
3331
|
+
else {
|
|
3332
|
+
const args = ["image", "-", "--image-output", resolve(assets, path)];
|
|
3333
|
+
if (extension === "tga") args.push("--image-input-tga");
|
|
3334
|
+
if (checkAssets) args.push("--check");
|
|
3335
|
+
const converted = execFileSync(pack, args, { input: data, encoding: "utf8", windowsHide: true });
|
|
3336
|
+
emit("addon-texture", id, text(path), ...converted.trim().split(/\s+/u));
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
3339
|
+
return textureIds.get(path);
|
|
3340
|
+
}
|
|
3341
|
+
|
|
3342
|
+
function runtimeExport(element) {
|
|
3343
|
+
const symbol = checker.getExportSpecifierLocalTargetSymbol(element) ?? checker.getSymbolAtLocation(element.name);
|
|
3344
|
+
const target = runtimeTarget(symbol);
|
|
3345
|
+
if (!target) return;
|
|
3346
|
+
const declaration = target.valueDeclaration;
|
|
3347
|
+
if (declaration && ts.isVariableDeclaration(declaration) && !(declaration.parent.flags & ts.NodeFlags.Const)) {
|
|
3348
|
+
unsupported(element, "Exported mutable bindings require a live module export");
|
|
3349
|
+
}
|
|
3350
|
+
return symbol;
|
|
3351
|
+
}
|
|
3352
|
+
|
|
3353
|
+
function runtimeTarget(symbol) {
|
|
3354
|
+
if (!symbol) return;
|
|
3355
|
+
if (symbol.flags & ts.SymbolFlags.Alias) {
|
|
3356
|
+
if (checker.getTypeOnlyAliasDeclaration(symbol)) return;
|
|
3357
|
+
symbol = checker.getAliasedSymbol(symbol);
|
|
3358
|
+
}
|
|
3359
|
+
if (symbol.flags & ts.SymbolFlags.Value && !moduleMarker(symbol)) return symbol;
|
|
3360
|
+
}
|
|
3361
|
+
|
|
3362
|
+
function exportSymbols(file) {
|
|
3363
|
+
const symbol = checker.getSymbolAtLocation(file);
|
|
3364
|
+
return new Map(symbol ? checker.getExportsOfModule(symbol).map(value => [value.getName(), value]) : []);
|
|
3365
|
+
}
|
|
3366
|
+
|
|
3367
|
+
function staticData(node) {
|
|
3368
|
+
if (ts.isStringLiteralLike(node) || ts.isNumericLiteral(node) || [K.TrueKeyword, K.FalseKeyword, K.NullKeyword].includes(node.kind)) return true;
|
|
3369
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) return staticData(node.expression);
|
|
3370
|
+
if (ts.isPrefixUnaryExpression(node)) return node.operator === K.MinusToken && ts.isNumericLiteral(node.operand);
|
|
3371
|
+
if (ts.isIdentifier(node)) return node.text === "undefined" && !checker.getSymbolAtLocation(node)?.declarations?.length;
|
|
3372
|
+
if (ts.isArrayLiteralExpression(node)) return node.elements.every(staticData);
|
|
3373
|
+
return ts.isObjectLiteralExpression(node) && node.properties.every(property => ts.isPropertyAssignment(property)
|
|
3374
|
+
&& (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) || ts.isNumericLiteral(property.name))
|
|
3375
|
+
&& staticData(property.initializer));
|
|
3376
|
+
}
|
|
3377
|
+
|
|
3378
|
+
const startupFactories = new Map([
|
|
3379
|
+
["defineCVars", ["src/cvars.ts", 1]],
|
|
3380
|
+
["integer", ["src/cvars.ts", "literals"]],
|
|
3381
|
+
["oneOf", ["src/cvars.ts", "literals"]],
|
|
3382
|
+
["createWoWCVars", ["wow/cvars.ts", 1]],
|
|
3383
|
+
["createMacroBook", ["wow/macro-book.ts", 0]],
|
|
3384
|
+
["rawField", ["wow/lua-table.ts", 2]],
|
|
3385
|
+
["createFrameDriver", ["src/frame-scheduler.ts", 2]],
|
|
3386
|
+
]);
|
|
3387
|
+
|
|
3388
|
+
function initializedFactory(node) {
|
|
3389
|
+
const declaration = checker.getResolvedSignature(node)?.getDeclaration();
|
|
3390
|
+
const factory = declaration && ts.isFunctionDeclaration(declaration) && startupFactories.get(declaration.name?.text);
|
|
3391
|
+
if (!factory) return false;
|
|
3392
|
+
const [expected, argumentsRule] = factory;
|
|
3393
|
+
const source = relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/");
|
|
3394
|
+
return source === expected && (argumentsRule === "literals" ? node.arguments.every(staticData) : node.arguments.length === argumentsRule);
|
|
3395
|
+
}
|
|
3396
|
+
|
|
3397
|
+
function moduleInitializer(node) {
|
|
3398
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
|
|
3399
|
+
return moduleInitializer(node.expression);
|
|
3400
|
+
}
|
|
3401
|
+
if (ts.isIdentifier(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || staticData(node)) return;
|
|
3402
|
+
if (ts.isTemplateExpression(node)) {
|
|
3403
|
+
for (const span of node.templateSpans) moduleInitializer(span.expression);
|
|
3404
|
+
return;
|
|
3405
|
+
}
|
|
3406
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === K.MinusToken && ts.isNumericLiteral(node.operand)) return;
|
|
3407
|
+
if (collectionConstructor(node) || rawTableConstruction(node)) {
|
|
3408
|
+
for (const argument of node.arguments ?? []) moduleInitializer(argument);
|
|
3409
|
+
return;
|
|
3410
|
+
}
|
|
3411
|
+
const luaStringChar = ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)
|
|
3412
|
+
&& node.expression.name.text === "char" && ts.isIdentifier(node.expression.expression)
|
|
3413
|
+
&& hostGlobal(valueSymbol(node.expression.expression)) && node.expression.expression.text === "string";
|
|
3414
|
+
if ((nativeLuaStringCall(node, "char") || luaStringChar) && node.arguments.every(ts.isNumericLiteral)) return;
|
|
3415
|
+
if (ts.isBinaryExpression(node) && [K.PlusToken, K.MinusToken, K.AsteriskToken, K.AsteriskAsteriskToken, K.SlashToken, K.PercentToken]
|
|
3416
|
+
.includes(node.operatorToken.kind)) {
|
|
3417
|
+
moduleInitializer(node.left);
|
|
3418
|
+
return moduleInitializer(node.right);
|
|
3419
|
+
}
|
|
3420
|
+
if (ts.isPropertyAccessExpression(node)) return moduleInitializer(node.expression);
|
|
3421
|
+
if (ts.isElementAccessExpression(node)) {
|
|
3422
|
+
moduleInitializer(node.expression);
|
|
3423
|
+
return moduleInitializer(node.argumentExpression);
|
|
3424
|
+
}
|
|
3425
|
+
if (ts.isArrayLiteralExpression(node)) {
|
|
3426
|
+
for (const element of node.elements) moduleInitializer(ts.isSpreadElement(element) ? element.expression : element);
|
|
3427
|
+
return;
|
|
3428
|
+
}
|
|
3429
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
3430
|
+
for (const property of node.properties) {
|
|
3431
|
+
if (ts.isPropertyAssignment(property)) {
|
|
3432
|
+
if (ts.isComputedPropertyName(property.name)) moduleInitializer(property.name.expression);
|
|
3433
|
+
moduleInitializer(property.initializer);
|
|
3434
|
+
}
|
|
3435
|
+
else if (ts.isSpreadAssignment(property)) moduleInitializer(property.expression);
|
|
3436
|
+
else if (!ts.isShorthandPropertyAssignment(property) && !ts.isMethodDeclaration(property)) unsupported(property);
|
|
3437
|
+
}
|
|
3438
|
+
return;
|
|
3439
|
+
}
|
|
3440
|
+
if (ts.isCallExpression(node) && node.arguments.length === 1
|
|
3441
|
+
&& ["keys", "entries", "values"].some(name => standardMember(node.expression, "Object", name))) return moduleInitializer(node.arguments[0]);
|
|
3442
|
+
if (ts.isCallExpression(node) && !(node.flags & ts.NodeFlags.OptionalChain) && initializedFactory(node)) {
|
|
3443
|
+
for (const argument of node.arguments) moduleInitializer(argument);
|
|
3444
|
+
return;
|
|
3445
|
+
}
|
|
3446
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && !node.questionDotToken) {
|
|
3447
|
+
const symbol = checker.getSymbolAtLocation(node.expression);
|
|
3448
|
+
const staticArguments = node.arguments.every(staticData);
|
|
3449
|
+
const local = symbol?.valueDeclaration;
|
|
3450
|
+
if (staticArguments && local && local.getSourceFile() === node.getSourceFile() && ts.isFunctionDeclaration(local)
|
|
3451
|
+
&& ts.isSourceFile(local.parent) && local.parameters.every(param => ts.isIdentifier(param.name) && !param.initializer)
|
|
3452
|
+
&& local.body?.statements.length === 1) {
|
|
3453
|
+
const [statement] = local.body.statements;
|
|
3454
|
+
if (ts.isReturnStatement(statement) && statement.expression && ts.isArrowFunction(statement.expression)) return;
|
|
3455
|
+
}
|
|
3456
|
+
if (symbol?.flags & ts.SymbolFlags.Alias && bindings.has(symbol)) {
|
|
3457
|
+
// Imported modules are initialized. Static data cannot run
|
|
3458
|
+
// code in this module before its remaining bindings are initialized.
|
|
3459
|
+
if (staticArguments) return;
|
|
3460
|
+
if (node.arguments.every(arg => {
|
|
3461
|
+
const type = checker.getTypeAtLocation(arg);
|
|
3462
|
+
return knownString(type) || knownNumber(type) || Boolean(type.flags & (T.BooleanLike | T.Undefined | T.Null));
|
|
3463
|
+
})) {
|
|
3464
|
+
for (const argument of node.arguments) moduleInitializer(argument);
|
|
3465
|
+
return;
|
|
3466
|
+
}
|
|
3467
|
+
const target = checker.getAliasedSymbol(symbol);
|
|
3468
|
+
const declaration = target.valueDeclaration;
|
|
3469
|
+
if (target.name === "defineModule" && declaration && node.arguments.length === 1
|
|
3470
|
+
&& relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "src/module.ts") {
|
|
3471
|
+
let argument = node.arguments[0];
|
|
3472
|
+
if (ts.isIdentifier(argument)) {
|
|
3473
|
+
const metadata = checker.getSymbolAtLocation(argument)?.valueDeclaration;
|
|
3474
|
+
if (metadata && ts.isVariableDeclaration(metadata) && metadata.getSourceFile() === node.getSourceFile()
|
|
3475
|
+
&& metadata.parent.flags & ts.NodeFlags.Const) argument = metadata.initializer;
|
|
3476
|
+
}
|
|
3477
|
+
while (argument && (ts.isAsExpression(argument) || ts.isParenthesizedExpression(argument)
|
|
3478
|
+
|| ts.isSatisfiesExpression(argument))) argument = argument.expression;
|
|
3479
|
+
if (argument && ts.isObjectLiteralExpression(argument) && argument.properties.some(property =>
|
|
3480
|
+
ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))
|
|
3481
|
+
&& property.name.text === "providers")) return moduleInitializer(node.arguments[0]);
|
|
3482
|
+
}
|
|
3483
|
+
if (target.name === "defineStore" && declaration && (node.arguments.length === 2 || node.arguments.length === 3)
|
|
3484
|
+
&& relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "state/setup-store.ts") {
|
|
3485
|
+
for (const argument of node.arguments) moduleInitializer(argument);
|
|
3486
|
+
return;
|
|
3487
|
+
}
|
|
3488
|
+
if (target.name === "createSignalFactory" && declaration &&
|
|
3489
|
+
relative(sdkRoot, realpathSync(declaration.getSourceFile().fileName)).replaceAll("\\", "/") === "src/signal-kernel.ts"
|
|
3490
|
+
&& node.arguments.every(arg => ts.isIdentifier(arg) || ts.isArrowFunction(arg))) return;
|
|
3491
|
+
}
|
|
3492
|
+
}
|
|
3493
|
+
unsupported(node, "Module initialization requires static data or an initialized import with safe arguments");
|
|
3494
|
+
}
|
|
3495
|
+
|
|
3496
|
+
async function visit(file, origin) {
|
|
3497
|
+
const path = realpathSync(file.fileName);
|
|
3498
|
+
if (ids.has(path)) return ids.get(path);
|
|
3499
|
+
if (!compilerOwnsPath(path)) {
|
|
3500
|
+
unsupported(origin, "Runtime module outside project or SDK");
|
|
3501
|
+
}
|
|
3502
|
+
const active = stack.indexOf(path);
|
|
3503
|
+
if (active >= 0) {
|
|
3504
|
+
const cycle = [...stack.slice(active), path].map(name => relative(workspaceRoot, name));
|
|
3505
|
+
unsupported(origin, `Circular runtime import: ${cycle.join(" -> ")}`);
|
|
3506
|
+
}
|
|
3507
|
+
stack.push(path);
|
|
3508
|
+
if (uiCore && file !== uiCore && !uiLinked && usesAddonUi(file, ui)) {
|
|
3509
|
+
const id = await visit(uiCore, file);
|
|
3510
|
+
emit("addon-core", id);
|
|
3511
|
+
uiLinked = true;
|
|
3512
|
+
}
|
|
3513
|
+
|
|
3514
|
+
if (relative(sdkRoot, path).replaceAll("\\", "/") === "src/signal-kernel.ts") {
|
|
3515
|
+
const frontend = await import(pathToFileURL(resolve(sdkRoot, "builder/src/ts-lower.mjs")).href);
|
|
3516
|
+
const lowered = frontend.lowerSignalFactory(ts, program, sdkRoot, file.fileName);
|
|
3517
|
+
moduleIdentity(path, file.text);
|
|
3518
|
+
emit("native-signal", ids.size + textureIds.size + 1, lowered.source, lowered.fingerprint);
|
|
3519
|
+
} else {
|
|
3520
|
+
rememberForwardedRest(file);
|
|
3521
|
+
rememberCapturedVariables(file);
|
|
3522
|
+
validateForwardedRest(file);
|
|
3523
|
+
const imports = [];
|
|
3524
|
+
const forwarded = new Map();
|
|
3525
|
+
const exports = exportSymbols(file);
|
|
3526
|
+
for (const node of file.statements) {
|
|
3527
|
+
if (ts.isExportDeclaration(node) && node.moduleSpecifier && !node.isTypeOnly) {
|
|
3528
|
+
const dependency = moduleOf(node);
|
|
3529
|
+
if (!node.exportClause) {
|
|
3530
|
+
const id = await visit(dependency, node);
|
|
3531
|
+
for (const [name, candidate] of exportSymbols(dependency)) {
|
|
3532
|
+
if (name === "default" || forwarded.has(name)) continue;
|
|
3533
|
+
const selected = exports.get(name);
|
|
3534
|
+
const target = runtimeTarget(selected);
|
|
3535
|
+
if (target && target === runtimeTarget(candidate)
|
|
3536
|
+
&& !selected.declarations?.some(declaration => declaration.getSourceFile() === file)) {
|
|
3537
|
+
forwarded.set(name, [id, text(name)]);
|
|
3538
|
+
}
|
|
3539
|
+
}
|
|
3540
|
+
continue;
|
|
3541
|
+
}
|
|
3542
|
+
if (!ts.isNamedExports(node.exportClause)) unsupported(node, "Namespace re-exports are unsupported");
|
|
3543
|
+
const elements = node.exportClause.elements.filter(element => !element.isTypeOnly && runtimeExport(element));
|
|
3544
|
+
if (!elements.length && node.exportClause.elements.length > 0) continue;
|
|
3545
|
+
const id = await visit(dependency, node);
|
|
3546
|
+
for (const element of elements) {
|
|
3547
|
+
forwarded.set(element.name.text, [id, text((element.propertyName ?? element.name).text)]);
|
|
3548
|
+
}
|
|
3549
|
+
continue;
|
|
3550
|
+
}
|
|
3551
|
+
if (!ts.isImportDeclaration(node) || node.importClause?.isTypeOnly) continue;
|
|
3552
|
+
const clause = node.importClause;
|
|
3553
|
+
const named = clause?.namedBindings;
|
|
3554
|
+
const elements = named && ts.isNamedImports(named) ? named.elements.filter(element => !element.isTypeOnly) : [];
|
|
3555
|
+
if (!clause?.name && named && ts.isNamedImports(named) && elements.length === 0 && named.elements.length > 0) continue;
|
|
3556
|
+
const id = addonTexture(node) ?? await visit(moduleOf(node), node);
|
|
3557
|
+
const importName = node => fragments ? node : identifier(node);
|
|
3558
|
+
if (clause?.name) imports.push(["import", importName(clause.name), id, text("default")]);
|
|
3559
|
+
if (named && ts.isNamespaceImport(named)) imports.push(["import-module", importName(named.name), id]);
|
|
3560
|
+
for (const element of elements ?? []) {
|
|
3561
|
+
const symbol = checker.getSymbolAtLocation(element.name);
|
|
3562
|
+
const target = checker.getAliasedSymbol(symbol);
|
|
3563
|
+
if (moduleMarker(target)) unsupported(element, "Kumi module declaration must be lowered before linking");
|
|
3564
|
+
if (!target.valueDeclaration || target.valueDeclaration.getSourceFile().isDeclarationFile
|
|
3565
|
+
&& !(addon && nativeImageDeclaration(target.valueDeclaration))) {
|
|
3566
|
+
unsupported(element, "Runtime import must name a compiled value export");
|
|
3567
|
+
}
|
|
3568
|
+
imports.push(["import", importName(element.name), id, text((element.propertyName ?? element.name).text)]);
|
|
3569
|
+
}
|
|
3570
|
+
}
|
|
3571
|
+
moduleIdentity(path, file.text);
|
|
3572
|
+
emit("module", ids.size + textureIds.size + 1);
|
|
3573
|
+
if (fragments) {
|
|
3574
|
+
// Module locals have no cross-file identity. Start at the same slot in every entry graph.
|
|
3575
|
+
bindings.clear();
|
|
3576
|
+
unique = 0;
|
|
3577
|
+
}
|
|
3578
|
+
for (const [operation, name, ...operands] of imports) {
|
|
3579
|
+
emit(operation, fragments ? identifier(name) : name, ...operands);
|
|
3580
|
+
}
|
|
3581
|
+
for (const [name, forward] of forwarded) emit("re-export", text(name), ...forward);
|
|
3582
|
+
for (const node of file.statements) {
|
|
3583
|
+
if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isImportDeclaration(node)) continue;
|
|
3584
|
+
if (ts.isClassDeclaration(node) && node.name && moduleMarker(checker.getSymbolAtLocation(node.name))) continue;
|
|
3585
|
+
if (ts.isModuleDeclaration(node) && ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Ambient) continue;
|
|
3586
|
+
if (typeOnlyNamespace(node)) continue;
|
|
3587
|
+
if (ts.isExportDeclaration(node)) {
|
|
3588
|
+
if (node.isTypeOnly || node.moduleSpecifier) continue;
|
|
3589
|
+
if (!node.exportClause || !ts.isNamedExports(node.exportClause)) unsupported(node);
|
|
3590
|
+
for (const element of node.exportClause.elements) {
|
|
3591
|
+
if (element.isTypeOnly) continue;
|
|
3592
|
+
const symbol = runtimeExport(element);
|
|
3593
|
+
if (symbol) emit("export-binding", text(element.name.text), binding(symbol, element));
|
|
3594
|
+
}
|
|
3595
|
+
continue;
|
|
3596
|
+
}
|
|
3597
|
+
if (ts.isExportAssignment(node) && !node.isExportEquals) {
|
|
3598
|
+
emit("binding", text("default"), `b${++unique}`);
|
|
3599
|
+
if (!addon) moduleInitializer(node.expression);
|
|
3600
|
+
expression(node.expression);
|
|
3601
|
+
continue;
|
|
3602
|
+
}
|
|
3603
|
+
if (ts.isVariableStatement(node) && ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Ambient
|
|
3604
|
+
&& node.declarationList.declarations.every(({ name, type }) =>
|
|
3605
|
+
type && ts.isTypeOperatorNode(type) && type.operator === K.UniqueKeyword
|
|
3606
|
+
|| hostGlobal(checker.getSymbolAtLocation(name)) || nativeMultiFunction(checker.getSymbolAtLocation(name))
|
|
3607
|
+
|| addonBinding(checker.getSymbolAtLocation(name)))) continue;
|
|
3608
|
+
if (ts.isVariableStatement(node) && node.declarationList.flags & ts.NodeFlags.BlockScoped
|
|
3609
|
+
&& !node.modifiers?.some(modifier => modifier.kind !== K.ExportKeyword)) {
|
|
3610
|
+
const exported = node.modifiers?.some(modifier => modifier.kind === K.ExportKeyword);
|
|
3611
|
+
if (exported && !(node.declarationList.flags & ts.NodeFlags.Const)) {
|
|
3612
|
+
unsupported(node, "Exported mutable bindings require a live module export");
|
|
3613
|
+
}
|
|
3614
|
+
for (const declaration of node.declarationList.declarations) {
|
|
3615
|
+
if (!ts.isIdentifier(declaration.name)) {
|
|
3616
|
+
if (!declaration.initializer) unsupported(declaration, "Module bindings require an initializer");
|
|
3617
|
+
if (!addon) moduleInitializer(declaration.initializer);
|
|
3618
|
+
const names = boundIdentifiers(declaration.name);
|
|
3619
|
+
emit("module-locals", ...names.map(identifier));
|
|
3620
|
+
if (exported) for (const name of names) emit("export-binding", text(name.text), identifier(name));
|
|
3621
|
+
emit("module-init");
|
|
3622
|
+
emit("block", 1);
|
|
3623
|
+
localDeclaration(declaration, true);
|
|
3624
|
+
continue;
|
|
3625
|
+
}
|
|
3626
|
+
emit("binding", exported ? text(propertyName(declaration.name)) : "-", identifier(declaration.name));
|
|
3627
|
+
if (declaration.initializer) {
|
|
3628
|
+
if (!addon) moduleInitializer(declaration.initializer);
|
|
3629
|
+
expression(declaration.initializer);
|
|
3630
|
+
} else emit("literal", "nil");
|
|
3631
|
+
}
|
|
3632
|
+
continue;
|
|
3633
|
+
}
|
|
3634
|
+
if (ts.isClassDeclaration(node) && node.name && !node.modifiers?.some(modifier => modifier.kind !== K.ExportKeyword)) {
|
|
3635
|
+
const exported = node.modifiers?.some(modifier => modifier.kind === K.ExportKeyword);
|
|
3636
|
+
emit("class", exported ? text(node.name.text) : "-", identifier(node.name));
|
|
3637
|
+
classBody(node);
|
|
3638
|
+
continue;
|
|
3639
|
+
}
|
|
3640
|
+
if (addon && (ts.isExpressionStatement(node) || ts.isIfStatement(node) || ts.isBlock(node)
|
|
3641
|
+
|| ts.isIterationStatement(node, false) || ts.isSwitchStatement(node) || ts.isThrowStatement(node) || ts.isTryStatement(node))) {
|
|
3642
|
+
emit("module-init");
|
|
3643
|
+
emit("block", 1);
|
|
3644
|
+
statement(node);
|
|
3645
|
+
continue;
|
|
3646
|
+
}
|
|
3647
|
+
if (!ts.isFunctionDeclaration(node)) unsupported(node, "Module scope accepts imports, types and declarations with native lowering");
|
|
3648
|
+
if (!node.body) continue;
|
|
3649
|
+
const defaultExport = node.modifiers?.some(modifier => modifier.kind === K.DefaultKeyword);
|
|
3650
|
+
if ((!node.name && !defaultExport) || node.asteriskToken || node.modifiers?.some(modifier =>
|
|
3651
|
+
modifier.kind !== K.ExportKeyword && modifier.kind !== K.DefaultKeyword)) unsupported(node);
|
|
3652
|
+
const exported = node.modifiers?.some(modifier => modifier.kind === K.ExportKeyword);
|
|
3653
|
+
const usesSelf = functionHasSelf(node);
|
|
3654
|
+
const key = defaultExport ? "default" : exported ? node.name.text : undefined;
|
|
3655
|
+
const name = node.name ? identifier(node.name) : `b${++unique}`;
|
|
3656
|
+
const params = parameters(node.parameters, usesSelf);
|
|
3657
|
+
emit(usesSelf ? "function-self" : "function", key === undefined ? "-" : text(key),
|
|
3658
|
+
name, ...params);
|
|
3659
|
+
if (!emitCanonicalReveal(node, exports, params)) body(node.body, node.parameters);
|
|
3660
|
+
}
|
|
3661
|
+
emit("end-module");
|
|
3662
|
+
}
|
|
3663
|
+
stack.pop();
|
|
3664
|
+
const id = ids.size + textureIds.size + 1;
|
|
3665
|
+
ids.set(path, id);
|
|
3666
|
+
return id;
|
|
3667
|
+
}
|
|
3668
|
+
|
|
3669
|
+
const file = program.getSourceFile(entry);
|
|
3670
|
+
const platform = addon && program.getSourceFile(addonPlatform);
|
|
3671
|
+
const ui = platform && checker.resolveName("UI", platform, ts.SymbolFlags.Value, false);
|
|
3672
|
+
let uiCore;
|
|
3673
|
+
let uiLinked = false;
|
|
3674
|
+
if (addonBinding(ui) === "addonUi") {
|
|
3675
|
+
const path = realpathSync(resolve(sdkRoot, "src/index.ts"));
|
|
3676
|
+
uiCore = checker.getTypeOfSymbolAtLocation(ui, ui.valueDeclaration).getSymbol()?.declarations?.find(ts.isSourceFile);
|
|
3677
|
+
if (!uiCore || uiCore.isDeclarationFile || realpathSync(uiCore.fileName) !== path) {
|
|
3678
|
+
unsupported(ui.valueDeclaration, "The addon UI global must use @kumi/core from the selected SDK");
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
emit("entry", await visit(file, file));
|
|
3682
|
+
process.stdout.write(records.join("\n") + "\n");
|