luaut-parser 2.1.0 → 3.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
@@ -45,24 +45,32 @@ annotation resolves to, and `expectedTypeOf` what each call argument should
45
45
  be, so a tool never has to re-derive a type from text.
46
46
 
47
47
  `parseWithRecovery(source)` returns `{ program, errors }` instead of throwing —
48
- use it for editors, where the text is usually mid-edit.
48
+ use it for editors, where the text is usually mid-edit. An error costs as
49
+ little of the tree as it can: a broken value becomes an `ErrorExpression`
50
+ (typed `any`) in its place, a broken field or argument is skipped to the next
51
+ `,`, a missing comma between fields on separate lines, or a missing `)`, `}`,
52
+ `then`, `do` or `end`, is recorded and read past — a missing `end` is placed
53
+ by indentation — and an unclosed string ends at its line. Skipping never lets
54
+ an `end` or `}` inside a skipped function or object close the block around
55
+ it. Valid code parses to exactly the same tree as `parse`.
49
56
 
50
57
  Neither analysis mutates the AST; both return side tables.
51
58
 
52
59
  ## Projects
53
60
 
54
- **No types are built in** — not `print`, not `string`, not `game`. A project
55
- lists the type libraries it uses in `luaut.config.json`, the way TypeScript
56
- uses `@types/*`:
61
+ **No globals are built in** — not `print`, not `string`, not `game`. Only the
62
+ language's own utility types are (`Partial`, `Pick`, `Omit`, `Record`,
63
+ `ReturnType`, `Truthy`, ...; see `PRELUDE_SOURCE`). A project lists the type
64
+ libraries it uses in `luaut.config.json`, the way TypeScript uses `@types/*`:
57
65
 
58
66
  ```bash
59
- npm i -D @luaut/roblox # or just @luaut/luau
67
+ npm i -D @luaut/roblox # Luau + Roblox; or @luaut/lua on its own
60
68
  ```
61
69
 
62
70
  ```jsonc
63
71
  // luaut.config.json
64
72
  {
65
- "types": ["roblox"], // @luaut/roblox, which brings @luaut/luau
73
+ "types": ["roblox"], // and what it depends on: @luaut/lua
66
74
  "paths": { "@shared/*": ["src/shared/*"] }, // import aliases, as in tsconfig
67
75
  "sourceMap": "sourcemap.json" // a Rojo sourcemap, or null
68
76
  }
@@ -71,10 +79,10 @@ npm i -D @luaut/roblox # or just @luaut/luau
71
79
  - **Which config applies** — the nearest one in the file's folder or above.
72
80
  `luaut.config.json` and `luaut.config.jsonc` in the same folder is an error.
73
81
  Both forms accept comments and trailing commas.
74
- - **`types`** — `"luau"` is looked up as `@luaut/luau`, then as a package named
75
- `luau`, in `node_modules` from the config upward. A full package name or a
76
- relative path (`"./types"`, `"./defs.d.luaut"`) works too. A type library's
77
- own type-library dependencies load first.
82
+ - **`types`** — any name, looked up as the package `@luaut/<name>` in
83
+ `node_modules` from the config upward; one that is not installed is an
84
+ error. A relative path (`"./types"`, `"./defs.d.luaut"`) loads the project's
85
+ own definitions. A type library's own type-library dependencies load first.
78
86
  - **`paths`** — tsconfig rules: an exact pattern wins, then the `*` pattern
79
87
  with the longest prefix; targets resolve from `baseUrl` (default: the
80
88
  config's folder).
@@ -96,8 +104,13 @@ the config (or sourcemap) it is about. `host` reads files — pass your own to
96
104
  read unsaved editor buffers or to record what was read.
97
105
 
98
106
  `type` / `typeof` are **not** special-cased in the analyzer either: they are
99
- overload sets in `@luaut/luau`, and narrowing is derived from them. Without a
100
- library that declares them, they narrow nothing.
107
+ overload sets in `@luaut/lua` and `@luaut/roblox`, and narrowing is derived
108
+ from them. Without a library that declares them, they narrow nothing.
109
+
110
+ Libraries stack: a name declared again *adds* to what an earlier library gave
111
+ it — overloads of a function accumulate, and the members of a declared table
112
+ merge. That is how `@luaut/roblox` extends Lua's `table` and `type` without
113
+ restating them.
101
114
 
102
115
  ## The language, in brief
103
116
 
@@ -106,8 +119,50 @@ must.
106
119
 
107
120
  **Declarations** — `const` and `let` only; Lua's `local` is gone.
108
121
 
122
+ **Functions** — `function name() ... end` declares `name` in the enclosing
123
+ scope; like a TypeScript function declaration it cannot be reassigned.
124
+ `const` and `let` do not apply to functions. `function T.name()` and
125
+ `function T:name()` define a member.
126
+
127
+ **Hoisting** — a function declaration is visible to its whole block, above
128
+ itself too, so `let r: ReturnType<typeof load>` may come before `function
129
+ load()`. A closure reads the name its own value is bound to, as in JavaScript
130
+ (`let m = { clear: function() m.items = {} end }`), and a later name in the
131
+ same block; the compiler declares such a name before the statement that fills
132
+ it. A module's top-level names are visible to code that runs later —
133
+ function bodies and `typeof` — wherever that code is written, since a bundle
134
+ declares them all before the module runs. At the top level the whole function
135
+ is hoisted, and can be called above its declaration. Inside a function only
136
+ the name is: other functions can call it, but a call straight in the block
137
+ above the declaration is an error, because nothing is there yet.
138
+
139
+ **Returns** — a declared return type is checked: what a `return` gives must
140
+ fit it, and a function that declared one must return a value (a guard or an
141
+ `asserts` function needs none). The declared type also types what is written
142
+ there, so a returned callback takes its parameters from it.
143
+
144
+ **Overloads** — a `function name(...)` with no body is a signature for the
145
+ declaration that follows it, as in TypeScript: the signatures are what a call
146
+ sees, and the last one, with the body, is the implementation. `export` goes on
147
+ every line of the set or none of them. A parameter of the implementation that
148
+ carries no annotation holds what the signatures allow there — under
149
+ `get(stat: "hp")` and `get(stat: "name")`, the implementation's `stat` is
150
+ `"hp" | "name"` rather than `any`.
151
+
152
+ **Modules** — `import { a, b as c } from "./m"`, `import D from "./m"` and
153
+ `import * as M from "./m"`; `export const`, `export function`, `export default`,
154
+ `export { a as b }`, `export { a } from "./m"` and `export * from "./m"`.
155
+ Imports are read-only: assigning to an imported name, or to a member of a
156
+ namespace (`M.x = 1`), is an error.
157
+
158
+ `import type { A } from "./m"` (also `import type D` and `import type * as M`)
159
+ brings in names that are types and nothing else: unlike TypeScript, using one
160
+ as a value is an error, and only type positions — `typeof A` included — may
161
+ name it. Compiled code keeps no trace of it.
162
+
109
163
  **Optionality** — there is no `T?` shorthand. `?` in type position always
110
- belongs to a conditional type, and in expression position to a ternary.
164
+ belongs to a conditional type, and in expression position to a ternary or an
165
+ optional chain.
111
166
 
112
167
  ```luau
113
168
  name?: T -- may be absent; its type is `T | nil`
@@ -117,6 +172,13 @@ name: T | nil -- must be written, but may be nil
117
172
  Omitting an argument requires `?` (or a default), as in TypeScript — a
118
173
  parameter typed `T | nil` still has to be passed something.
119
174
 
175
+ **Optional chaining** — `a?.b` and `a?:m(x)` are nil when `a` is, and then
176
+ nothing further along the chain runs, arguments included: `folder?:FindFirstChild("A")?.Name`
177
+ is a `string | nil`. The `?` must touch the `.` or `:`; `c ? a : b` stays a
178
+ ternary. Parentheses end a chain. A chain cannot be assigned to (`a?.b = 1` is
179
+ an error). A chain that got through narrows what it tested: inside
180
+ `if part?.Parent then`, and `if part?.Name == "Door" then`, `part` is not nil.
181
+
120
182
  **Classes** — types are structural, except for classes. A definitions file
121
183
  declares one with `declare class`, and it is nominal, as Roblox's classes are:
122
184
 
@@ -150,15 +212,38 @@ operand and then the right one, as Luau does. So `Vector3 + Vector3` and
150
212
  (`declare class Enum.Material extends EnumItem {}`), and code writes it the
151
213
  same way.
152
214
 
215
+ **Contextual typing** — an expression takes its type from where it is
216
+ written, as in TypeScript: `let queue: thread[] = []` is a `thread[]`, and so
217
+ is `[]` passed where one is expected, including inside an object literal.
218
+
153
219
  **Calls** — every argument is checked against its parameter, and a generic
154
220
  parameter against its constraint (`GetService<K extends keyof Services>`
155
- rejects `""`).
221
+ rejects `""`). Arguments are checked again once the call's own type arguments
222
+ are known, so `pick("Bones", "Blast1")` is caught where `pick`'s second
223
+ parameter reads `Extract<Rows, { Page: P }>["Skills"][number]`. A type that
224
+ waits on a type parameter — a conditional, an index, `T[K]` — is worked out
225
+ where that parameter is.
226
+
227
+ **Trailing commas** are allowed wherever TypeScript allows them: parameter
228
+ lists, call arguments, generic parameters and type arguments, tables, arrays,
229
+ tuples, imports and exports.
230
+
231
+ A value read by a key narrows the key: after `const path = paths[stat]`, the
232
+ `else` of `if path then` leaves `stat` as exactly the keys `paths` does not
233
+ have — the same correlation `pairs` over a record and a destructured union
234
+ already get.
156
235
 
157
236
  **Narrowing** follows TypeScript's model: references (`x`, `x.a.b`, `x["k"]`)
158
237
  rather than just variables, discriminated unions at any depth, `and`/`or`,
159
238
  early return, `break`/`continue`, `error()` (declared `-> never`), user type
160
239
  guards (`v is T`), and assertion signatures (`asserts v`).
161
240
 
241
+ Reading a member of, indexing or calling a value that may be nil is an error
242
+ until a check narrows the nil away, as with TypeScript's `strictNullChecks`:
243
+ `FindFirstChild("A"):FindFirstChild("B")` reports that the first call is
244
+ possibly nil. Use `?.` / `?:`, or check first. The read is still typed from the
245
+ non-nil part.
246
+
162
247
  Only `nil` and `false` are falsy — `0` and `""` are truthy, unlike JavaScript.
163
248
 
164
249
  **Types** — unions, intersections, tuples `[A, B]`, type packs `(A, B)` (the
@@ -166,7 +251,14 @@ several values a function returns), `keyof`, `T[K]`, conditional types with
166
251
  `infer`, mapped types with `as` remapping, template literal types
167
252
  (`` `on${Event}` ``), and set difference `A - B`. The utility types
168
253
  (`Partial`, `Pick`, `Omit`, `ReturnType`, `Parameters`, `Exclude`, …) are
169
- written in luaut on top of those, not built in.
254
+ built in, and written in luaut on top of those rather than special-cased in
255
+ the analyzer. A type library or a file may declare one again; the later
256
+ declaration wins.
257
+
258
+ A call may write its type arguments out — `find<Folder>("Remotes")`,
259
+ `inst:WaitForChild<Folder>("Remotes")` — and a type parameter may have a
260
+ default (`<T = Instance>`) for the calls that do not. `a < b > (c)` is still
261
+ three operators: only a call after the `>` makes it type arguments.
170
262
 
171
263
  `<const T>` infers an argument at its narrowest, as in TypeScript 5.
172
264
 
@@ -177,6 +269,47 @@ written in luaut on top of those, not built in.
177
269
 
178
270
  **Modules** — `import` / `export`, export lists, re-exports and `export *`.
179
271
 
272
+ **`satisfies`** — checks a value against a type without giving it that type,
273
+ as in TypeScript 4.9:
274
+
275
+ ```luau
276
+ type Shape = { kind: "circle" | "rect", size: number }
277
+ const circle = { kind: "circle", size: 2 } satisfies Shape -- { kind: "circle", size: number }
278
+ const handlers = {
279
+ Click: function(x) return x + 1 end, -- x: number, from the contract
280
+ } satisfies { [string]: (x: number) -> number }
281
+ ```
282
+
283
+ The contract types callbacks and empty arrays, and a literal stays a literal
284
+ where the contract asks for literals (`kind: "circle"`, not `string`). A value
285
+ that does not fit is an error. So is a property the contract does not know —
286
+ TypeScript's excess property check, which applies to an object literal written
287
+ straight into an annotation (`const s: Shape = { ..., typo: 1 }`) too. A value
288
+ that already has a type of its own keeps it exactly: `{ ... } as const
289
+ satisfies T` stays readonly and literal. `as` reinterprets instead of
290
+ checking, and compiled code keeps neither.
291
+
292
+ **Undeclared names** — `analyzeScopes(program, { builtinGlobals, reportUndeclared: true })`
293
+ reports each read of a name nothing declares: "Cannot find name 'x'". A global
294
+ assigned in the file (`x = 1`) and a `declare` count as declarations.
295
+ `analyzeTypes(program, scopes, { reportUnknownTypes: true })` does the same for
296
+ type names. Both are off by default, since they are only right when the type
297
+ libraries the file names are loaded.
298
+
299
+ **Directives** — comments that switch checking off, as TypeScript's
300
+ `// @ts-...` do. They silence scope and type errors, never syntax errors:
301
+
302
+ ```luau
303
+ --@luaut-nocheck -- before the first line of code: the whole file
304
+ --@luaut-ignore -- the next line of code
305
+ --@luaut-expect-error -- the next line of code, which must have an error
306
+ ```
307
+
308
+ `parseWithRecovery` returns them as `directives`; `directivesOf(source)` reads
309
+ them for a caller that parsed some other way, and
310
+ `applyDirectives(directives, diagnostics, lineOf)` filters a list and names
311
+ each `expect-error` that had nothing to suppress.
312
+
180
313
  ## Options
181
314
 
182
315
  ```ts