@gwigz/slua-tstl-plugin 1.0.0 → 1.1.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/README.md CHANGED
@@ -2,6 +2,50 @@
2
2
 
3
3
  [TypeScriptToLua](https://typescripttolua.github.io) plugin to provide better DX with SLua types.
4
4
 
5
+ ## Usage
6
+
7
+ Add the plugin to `tstl.luaPlugins` in your `tsconfig.json`:
8
+
9
+ ```jsonc
10
+ {
11
+ "tstl": {
12
+ "luaTarget": "Luau",
13
+ "luaPlugins": [{ "name": "@gwigz/slua-tstl-plugin" }],
14
+ },
15
+ }
16
+ ```
17
+
18
+ To enable output optimizations, pass `optimize: true` for all flags, or pick individual ones:
19
+
20
+ ```jsonc
21
+ {
22
+ "tstl": {
23
+ "luaPlugins": [
24
+ // all optimizations
25
+ { "name": "@gwigz/slua-tstl-plugin", "optimize": true },
26
+ ],
27
+ },
28
+ }
29
+ ```
30
+
31
+ ```jsonc
32
+ {
33
+ "tstl": {
34
+ "luaPlugins": [
35
+ // pick individual optimizations
36
+ {
37
+ "name": "@gwigz/slua-tstl-plugin",
38
+ "optimize": {
39
+ "compoundAssignment": true,
40
+ "shortenTemps": true,
41
+ "inlineLocals": true,
42
+ },
43
+ },
44
+ ],
45
+ },
46
+ }
47
+ ```
48
+
5
49
  ## What it does
6
50
 
7
51
  - Translates TypeScript patterns to native Luau/LSL equivalents (see below)
@@ -34,24 +78,26 @@ For SL-typed JSON (preserving vector/quaternion/uuid), use `lljson.slencode`/`ll
34
78
 
35
79
  String methods are translated to LSL `ll.*` functions or Luau `string.*` stdlib calls:
36
80
 
37
- | TypeScript | Lua output |
38
- | ---------------------- | ----------------------------------------- |
39
- | `str.toUpperCase()` | `ll.ToUpper(str)` |
40
- | `str.toLowerCase()` | `ll.ToLower(str)` |
41
- | `str.trim()` | `ll.StringTrim(str, STRING_TRIM)` |
42
- | `str.trimStart()` | `ll.StringTrim(str, STRING_TRIM_HEAD)` |
43
- | `str.trimEnd()` | `ll.StringTrim(str, STRING_TRIM_TAIL)` |
44
- | `str.indexOf(x)` | `(string.find(str, x, 1, true) or 0) - 1` |
45
- | `str.includes(x)` | `string.find(str, x, 1, true) ~= nil` |
46
- | `str.startsWith(x)` | `string.find(str, x, 1, true) == 1` |
47
- | `str.split(sep)` | `string.split(str, sep)` |
48
- | `str.repeat(n)` | `string.rep(str, n)` |
49
- | `str.substring(start)` | `string.sub(str, start + 1)` |
50
- | `str.substring(s, e)` | `string.sub(str, s + 1, e)` |
51
- | `str.replaceAll(a, b)` | `ll.ReplaceSubString(str, a, b, 0)` |
81
+ | TypeScript | Lua output |
82
+ | ---------------------- | ------------------------------------------------ |
83
+ | `str.toUpperCase()` | `ll.ToUpper(str)` |
84
+ | `str.toLowerCase()` | `ll.ToLower(str)` |
85
+ | `str.trim()` | `ll.StringTrim(str, STRING_TRIM)` |
86
+ | `str.trimStart()` | `ll.StringTrim(str, STRING_TRIM_HEAD)` |
87
+ | `str.trimEnd()` | `ll.StringTrim(str, STRING_TRIM_TAIL)` |
88
+ | `str.indexOf(x)` | `(string.find(str, x, 1, true) or 0) - 1` |
89
+ | `str.indexOf(x, from)` | `(string.find(str, x, from + 1, true) or 0) - 1` |
90
+ | `str.includes(x)` | `string.find(str, x, 1, true) ~= nil` |
91
+ | `str.startsWith(x)` | `string.find(str, x, 1, true) == 1` |
92
+ | `str.split(sep)` | `string.split(str, sep)` |
93
+ | `str.repeat(n)` | `string.rep(str, n)` |
94
+ | `str.substring(start)` | `string.sub(str, start + 1)` |
95
+ | `str.substring(s, e)` | `string.sub(str, s + 1, e)` |
96
+ | `str.replace(a, b)` | `ll.ReplaceSubString(str, a, b, 1)` |
97
+ | `str.replaceAll(a, b)` | `ll.ReplaceSubString(str, a, b, 0)` |
52
98
 
53
99
  > [!NOTE]
54
- > `str.indexOf(x, fromIndex)` and `str.startsWith(x, position)` with a second argument fall through to TSTL's default handling. Similarly, `str.split()` with no separator is not transformed.
100
+ > `str.indexOf(x, fromIndex)` adjusts the `fromIndex` to 1-based (constant-folded for literals). `str.startsWith(x, position)` with a second argument falls through to TSTL's default handling. Similarly, `str.split()` with no separator is not transformed.
55
101
 
56
102
  ### Array methods
57
103
 
@@ -134,6 +180,132 @@ This only applies when the argument is directly a `/` expression. `Math.floor(x)
134
180
  > [!WARNING]
135
181
  > JavaScript integer truncation idioms `~~x` and `x | 0` do **not** map cleanly to Luau. `~~x` emits `bit32.bnot(bit32.bnot(x))` and `x | 0` emits `bit32.bor(x, 0)`, neither of which preserves correct semantics for negative numbers (the `bit32` library operates on unsigned 32-bit integers). Use `math.floor(x)` for floor truncation instead.
136
182
 
183
+ ## Optimizations
184
+
185
+ Pass `optimize: true` to enable all optimizations, or pass an object to pick individual flags. All flags default to `false` when not specified.
186
+
187
+ ### `filter`
188
+
189
+ Inlines `arr.filter(cb)` as an `ipairs` loop instead of pulling in `__TS__ArrayFilter`.
190
+
191
+ Automatically disabled for files with more than one `.filter()` call, where the shared helper is results in a smaller script.
192
+
193
+ ```typescript
194
+ const result = arr.filter((x) => x > 0)
195
+ ```
196
+
197
+ ```lua
198
+ local function ____opt_fn_0(x)
199
+ return x > 0
200
+ end
201
+ local ____opt_0 = {}
202
+ for _, ____opt_v_0 in ipairs(arr) do
203
+ if ____opt_fn_0(____opt_v_0) then
204
+ ____opt_0[#____opt_0 + 1] = ____opt_v_0
205
+ end
206
+ end
207
+ local result = ____opt_0
208
+ ```
209
+
210
+ ### `compoundAssignment`
211
+
212
+ Rewrites self-reassignment arithmetic to Luau compound assignment operators.
213
+
214
+ | TypeScript | Lua output |
215
+ | ------------ | ---------- |
216
+ | `x = x + n` | `x += n` |
217
+ | `x = x - 1` | `x -= 1` |
218
+ | `x = x .. s` | `x ..= s` |
219
+
220
+ Only currently only applies to simple identifiers.
221
+
222
+ ### `floorMultiply`
223
+
224
+ Reorders `Math.floor((a / b) * c)` to use the floor division operator, avoiding a `math.floor` call.
225
+
226
+ | TypeScript | Lua output |
227
+ | ---------------------------------- | --------------------- |
228
+ | `Math.floor((used / limit) * 100)` | `used * 100 // limit` |
229
+
230
+ Plain `Math.floor(a / b)` is **always** optimized to `a // b` regardless of this flag.
231
+
232
+ ### `indexOf`
233
+
234
+ Emits bare `string.find` / `table.find` for `indexOf` _presence checks_ instead of the full `(find or 0) - 1` pattern.
235
+
236
+ | TypeScript | Lua output |
237
+ | ----------------------- | -------------------------------- |
238
+ | `s.indexOf(x) >= 0` | `string.find(s, x, 1, true)` |
239
+ | `s.indexOf(x) !== -1` | `string.find(s, x, 1, true)` |
240
+ | `s.indexOf(x) === -1` | `not string.find(s, x, 1, true)` |
241
+ | `arr.indexOf(x) >= 0` | `table.find(arr, x)` |
242
+ | `arr.indexOf(x) === -1` | `not table.find(arr, x)` |
243
+
244
+ Bare `indexOf` calls without a comparison will still emit `(find or 0) - 1` to retain 0-index style responses.
245
+
246
+ ### `shortenTemps`
247
+
248
+ Shortens TSTL's destructuring temp names and collapses consecutive field accesses into multi-assignment.
249
+
250
+ ```typescript
251
+ const { a, b } = fn()
252
+ ```
253
+
254
+ Default output:
255
+
256
+ ```lua
257
+ local ____fn_result_0 = fn()
258
+ local a = ____fn_result_0.a
259
+ local b = ____fn_result_0.b
260
+ ```
261
+
262
+ Optimized output:
263
+
264
+ ```lua
265
+ local _r0 = fn()
266
+ local a, b = _r0.a, _r0.b
267
+ ```
268
+
269
+ ### `inlineLocals`
270
+
271
+ Merges forward-declared `local x` with its first `x = value` assignment when there are no references to `x` in between.
272
+
273
+ Default output:
274
+
275
+ ```lua
276
+ local x
277
+ x = 5
278
+ ```
279
+
280
+ Optimized output:
281
+
282
+ ```lua
283
+ local x = 5
284
+ ```
285
+
286
+ ### `numericConcat`
287
+
288
+ Strips `tostring()` from number-typed (and string-typed) template literal interpolations, since Luau's `..` operator handles numeric concatenation natively.
289
+
290
+ ```typescript
291
+ // count is number
292
+ const msg = `items: ${count}`
293
+ ```
294
+
295
+ Default output:
296
+
297
+ ```lua
298
+ local msg = "items: " .. tostring(count)
299
+ ```
300
+
301
+ Optimized output:
302
+
303
+ ```lua
304
+ local msg = "items: " .. count
305
+ ```
306
+
307
+ Non-numeric types (booleans, `any`, etc.) still get wrapped in `tostring()`.
308
+
137
309
  ## Keeping output small
138
310
 
139
311
  Some TypeScript patterns pull in large TSTL runtime helpers. Here are recommendations for keeping output lean:
@@ -0,0 +1,25 @@
1
+ import * as ts from "typescript";
2
+ /**
3
+ * PascalCase class names that map to lowercase Lua globals.
4
+ * `new Vector(...)` is handled by @customConstructor, but static access
5
+ * like `Vector.zero` emits `Vector.zero` in Lua -- which doesn't exist.
6
+ * The PropertyAccessExpression visitor rewrites the Lua identifier to lowercase.
7
+ */
8
+ export declare const PASCAL_TO_LOWER: Record<string, string>;
9
+ /**
10
+ * TSTL treats "bit32" as a Lua keyword and renames it to "____bit32" in output.
11
+ * This is incorrect for Luau where bit32 is a valid global library.
12
+ * The visitor rewrites the mangled name back; the diagnostic is suppressed
13
+ * separately in consumers (e.g. the playground transpiler worker).
14
+ */
15
+ export declare const TSTL_KEYWORD_FIXUPS: Record<string, string>;
16
+ export declare const BINARY_BITWISE_OPS: Record<number, string>;
17
+ /**
18
+ * Compound bitwise assignment tokens (`&=`, `|=`, etc.) map to the same
19
+ * `bit32.*` functions as their non-compound counterparts. We handle
20
+ * these at the TypeScript AST level rather than patching the Lua AST,
21
+ * because TSTL's desugaring loses the distinction between `>>=`
22
+ * (arshift) and `>>>=` (rshift) -- both lower to the same Lua operator.
23
+ */
24
+ export declare const COMPOUND_BITWISE_OPS: Record<number, string>;
25
+ export declare const EQUALITY_OPS: Set<ts.SyntaxKind>;
@@ -0,0 +1,50 @@
1
+ import * as ts from "typescript";
2
+ /**
3
+ * PascalCase class names that map to lowercase Lua globals.
4
+ * `new Vector(...)` is handled by @customConstructor, but static access
5
+ * like `Vector.zero` emits `Vector.zero` in Lua -- which doesn't exist.
6
+ * The PropertyAccessExpression visitor rewrites the Lua identifier to lowercase.
7
+ */
8
+ export const PASCAL_TO_LOWER = {
9
+ Vector: "vector",
10
+ Quaternion: "quaternion",
11
+ UUID: "uuid",
12
+ };
13
+ /**
14
+ * TSTL treats "bit32" as a Lua keyword and renames it to "____bit32" in output.
15
+ * This is incorrect for Luau where bit32 is a valid global library.
16
+ * The visitor rewrites the mangled name back; the diagnostic is suppressed
17
+ * separately in consumers (e.g. the playground transpiler worker).
18
+ */
19
+ export const TSTL_KEYWORD_FIXUPS = {
20
+ ____bit32: "bit32",
21
+ };
22
+ export const BINARY_BITWISE_OPS = {
23
+ [ts.SyntaxKind.AmpersandToken]: "band",
24
+ [ts.SyntaxKind.BarToken]: "bor",
25
+ [ts.SyntaxKind.CaretToken]: "bxor",
26
+ [ts.SyntaxKind.LessThanLessThanToken]: "lshift",
27
+ [ts.SyntaxKind.GreaterThanGreaterThanToken]: "arshift",
28
+ [ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken]: "rshift",
29
+ };
30
+ /**
31
+ * Compound bitwise assignment tokens (`&=`, `|=`, etc.) map to the same
32
+ * `bit32.*` functions as their non-compound counterparts. We handle
33
+ * these at the TypeScript AST level rather than patching the Lua AST,
34
+ * because TSTL's desugaring loses the distinction between `>>=`
35
+ * (arshift) and `>>>=` (rshift) -- both lower to the same Lua operator.
36
+ */
37
+ export const COMPOUND_BITWISE_OPS = {
38
+ [ts.SyntaxKind.AmpersandEqualsToken]: "band",
39
+ [ts.SyntaxKind.BarEqualsToken]: "bor",
40
+ [ts.SyntaxKind.CaretEqualsToken]: "bxor",
41
+ [ts.SyntaxKind.LessThanLessThanEqualsToken]: "lshift",
42
+ [ts.SyntaxKind.GreaterThanGreaterThanEqualsToken]: "arshift",
43
+ [ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken]: "rshift",
44
+ };
45
+ export const EQUALITY_OPS = new Set([
46
+ ts.SyntaxKind.EqualsEqualsToken,
47
+ ts.SyntaxKind.EqualsEqualsEqualsToken,
48
+ ts.SyntaxKind.ExclamationEqualsToken,
49
+ ts.SyntaxKind.ExclamationEqualsEqualsToken,
50
+ ]);
package/dist/index.d.ts CHANGED
@@ -1,3 +1,11 @@
1
1
  import * as tstl from "typescript-to-lua";
2
- declare const plugin: tstl.Plugin;
3
- export default plugin;
2
+ import type { CallTransform } from "./transforms.js";
3
+ import type { OptimizeFlags } from "./optimize.js";
4
+ export type { CallTransform, OptimizeFlags };
5
+ export interface SluaPluginOptions {
6
+ /** Enable per-transform output optimizations. Pass `true` to enable all. */
7
+ optimize?: boolean | OptimizeFlags;
8
+ [key: string]: any;
9
+ }
10
+ declare function createPlugin(options?: SluaPluginOptions): tstl.Plugin;
11
+ export default createPlugin;