diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fb1236..1180641 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -111,6 +111,25 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). (`completionItem.documentationFormat`). The edit range is the name around the cursor, sent once per list when the client supports `itemDefaults.editRange`, as an insert/replace edit when it supports `insertReplaceSupport`. +- Semantic tokens (`textDocument/semanticTokens/full`, `/full/delta` and `/range`) for the names + in the Lua of `.lua` and `.menu` files, classified by the rules of hover so that a name is + colored as it hovers. Keywords, literals, comments and `.menu` syntax are left to the TextMate + grammars. + - Types (all standard): `namespace`, `function`, `method`, `variable`, `parameter`, `property`, + `label`. Modifiers: `declaration`, `modification`, `defaultLibrary`, and `global`, declared + in the manifest (`contributes.semanticTokenModifiers`) so that themes can style `*.global`. + No TextMate fallback scope is contributed: there is no conventional scope for globals, and + the predefined fallbacks of the token types still apply. + - Locals: parameters and the implicit `self` are `parameter`; `local function f`, and a local + declared with a function expression and never assigned again, are `function`. + - Globals have `global`. A global the document assigns is a `function` or `variable` from its + first assignment; otherwise it takes its kind from the Lua 5.2 manual (`namespace` for the + module tables) or EEex-Docs. `defaultLibrary` marks the manual's names, the engine's `print` + and the *EE Game Lua Functions*, not EEex functions. `_ENV`, and names resolved through a + local `_ENV`, are not globals. + - Fields are `property`, or `method` after `:`; library and EEex-Docs members (`string.format`, + `C:AddGold`) as documented. Assignment targets have `modification`, declared names + `declaration`, labels are `label`. - Error-tolerant Lua 5.2 parser and scope analysis (`src/server/syntax/`), checked against the official compiler by a differential test; it publishes no diagnostics of its own. - Localization of the manifest, UI strings and the language server's hover labels into all 14 VS diff --git a/CLAUDE.md b/CLAUDE.md index 6f00916..9fe4a0c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ |---|---| | Name | `IE Lua Language Server` | | Publisher | `infinity-engine-tools` | -| Purpose | Lua 5.2 language support (diagnostics, hover, completion, document and workspace symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | +| Purpose | Lua 5.2 language support (diagnostics, hover, completion, semantic tokens, document and workspace symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | | Language | TypeScript (strict) | | Bundler | esbuild (two bundles: client + language server) | | Minimum VS Code | `^1.91.0` (see `engines.vscode` in `package.json`; required by `vscode-languageclient` ≥ 10) | @@ -34,6 +34,7 @@ │ │ ├── features/ # completion.ts, diagnostics.ts, hover.ts, ... │ │ ├── hover/ # Hover targets, library knowledge and rendering (pure, no LSP imports) │ │ ├── completion/ # Completion candidates (pure, no LSP imports) +│ │ ├── semanticTokens/ # Name classification for semantic tokens (pure, no LSP imports) │ │ ├── l10n.ts # Server messages in the client's locale (tables in l10n/server/) │ │ ├── syntax/ # Lua 5.2 lexer, parser, scopes, symbols, folding (pure, no LSP imports) │ │ ├── validation/ # Pure analysis logic (no LSP imports) — unit-tested directly diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e533b1d..e4f6288 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,6 +31,7 @@ server (port 6009). | `src/server/validation/` | Pure validation logic, unit-tested without LSP or VS Code | | `src/server/hover/` | What a hover describes and its text (pure; library data from `data/lua52/` and `data/eeex/`) | | `src/server/completion/` | What completion offers at the cursor (pure; reuses the hover's knowledge and text) | +| `src/server/semanticTokens/` | What each name is, for semantic highlighting (pure; follows the hover's rules) | | `src/server/syntax/` | Error-tolerant Lua 5.2 parser, scope analysis, document symbols and folding (pure; checked against the official compiler by `test/unit/server/syntax/differential.test.ts`) | | `src/server/workspace/` | Index of the workspace's Lua and `.menu` files, and `files.exclude` matching as VS Code applies it (file system injected, unit-tested with an in-memory one) | | `src/shared/` | Types and constants used by both sides | diff --git a/README.md b/README.md index 20a9a1f..3881efb 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,9 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the > [!NOTE] > This is an early version. It currently provides **syntax diagnostics**, **hover**, -> **completion**, **document symbols**, **workspace symbols**, **folding**, and **go to definition**, -> **find references** and **rename** within a file; cross-file navigation, formatting and more are -> planned. +> **completion**, **semantic highlighting**, **document symbols**, **workspace symbols**, **folding**, +> and **go to definition**, **find references** and **rename** within a file; cross-file navigation, +> formatting and more are planned. ## Features @@ -49,6 +49,17 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the (`Infinity_…`, `EEex_…`, and methods after `C:`), with the same documentation as on hover. Nothing the game lacks is suggested (`io`, `os`, `require`, coroutines). In `.menu` files, completion works inside the Lua only. +- **Colors that show what each name is.** Parameters, local and global variables, functions, + table fields and the functions the game provides can each have their own color: the extension + tells VS Code what every name in the Lua is, by the same rules as hover. This needs a theme + that uses semantic highlighting, such as VS Code's default theme. Globals carry a `global` + modifier that you can style yourself, for example in `settings.json`: + + ```json + "editor.semanticTokenColorCustomizations": { + "rules": { "*.global": { "bold": true } } + } + ``` - **Go to Definition, Find All References and Rename Symbol** for variables within a file. Locals follow Lua's scoping rules; globals are followed across all the Lua of a `.menu` file. Rename refuses, and says why, when it could change what the code does: a name already in use nearby, diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 1904da7..75bd715 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -43,6 +43,10 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea game functions such as `Infinity_DisplayString`, or methods after `C:`. Lua functions show their description from the Lua 5.2 manual, EEex and game functions a link to their documentation. In `.menu` files, completion works inside the Lua. +- **Colors that show what each name is.** With a theme that uses semantic highlighting, such as + VS Code's default theme, parameters, local and global variables, functions, table fields and + the functions the game provides can be colored differently, in Lua files and the Lua of `.menu` + files. Themes can style globals with the `global` modifier. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors too**: setup guides for Sublime Text, Neovim, Emacs, JetBrains IDEs, Helix, Zed, Kate, Notepad++ and Geany are on the project page. diff --git a/docs/editors/README.md b/docs/editors/README.md index 590bf36..97c9f47 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -70,6 +70,7 @@ node /path/to/server.js --stdio | Rename | `textDocument/prepareRename`, `textDocument/rename` | Same file only; refused, with the reason as the error message, when the rename could change what the code does. | | Hover | `textDocument/hover` | Markdown or plain text, whichever the editor prefers (`hover.contentFormat`); the server's own words follow the editor's `locale`. See below. | | Completion | `textDocument/completion`, `completionItem/resolve` | Triggered by `.` and `:`. Documentation is sent on resolve, in the editor's preferred `completionItem.documentationFormat`. See below. | +| Semantic tokens | `textDocument/semanticTokens/full`, `/full/delta`, `/range` | Names only (keywords, strings and comments are left to the editor's highlighting). See below. | | Workspace symbols | `workspace/symbol` | Every `*.lua` and `*.menu` file under the workspace folders, plus open files. See below. | Workspace symbols need an editor that sends **workspace folders** when it starts the server; @@ -96,6 +97,13 @@ detail and its documentation on resolve. Members are offered after `.` and `:` o Each item replaces the name around the cursor (`insertReplaceSupport` and `completionList.itemDefaults` are used when the editor has them). -Symbols, folding, hover, completion and navigation always reflect the current text, whatever `validate.mode` is. +Semantic tokens classify every name in the Lua with standard token types (`namespace`, +`function`, `method`, `variable`, `parameter`, `property`, `label`) and modifiers +(`declaration`, `modification`, `defaultLibrary`), plus a `global` modifier for global variables. +`defaultLibrary` marks the Lua 5.2 library and the game's own functions (`Infinity_…`), not EEex +functions. How the names are colored depends on the editor and its color scheme; an editor that +ignores the `global` modifier still gets the token type. + +Symbols, folding, hover, completion, semantic tokens and navigation always reflect the current text, whatever `validate.mode` is. Navigation works on variables: table fields (`t.x`) and `goto` labels are not followed, and in a `.menu` file globals are shared by all its Lua, while locals stay in their own block or script. diff --git a/package.json b/package.json index 93e72c8..f2aa6f6 100644 --- a/package.json +++ b/package.json @@ -65,6 +65,12 @@ } } ], + "semanticTokenModifiers": [ + { + "id": "global", + "description": "%semanticTokenModifiers.global.description%" + } + ], "commands": [ { "command": "ieLua.validateDocument", diff --git a/package.nls.cs.json b/package.nls.cs.json index e3848c6..a60e120 100644 --- a/package.nls.cs.json +++ b/package.nls.cs.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Ověřovat při uložení souboru.", "configuration.validate.mode.type": "Ověřovat během psaní, po `#ieLua.validate.debounce#` ms bez změn.", "configuration.validate.mode.saveAndType": "Ověřovat během psaní a při uložení souboru.", - "configuration.validate.debounce.description": "Prodleva v milisekundách od poslední změny do ověření, když má `#ieLua.validate.mode#` hodnotu `type` nebo `saveAndType`." + "configuration.validate.debounce.description": "Prodleva v milisekundách od poslední změny do ověření, když má `#ieLua.validate.mode#` hodnotu `type` nebo `saveAndType`.", + "semanticTokenModifiers.global.description": "Globální proměnná (pole globálního prostředí), na rozdíl od místní proměnné." } diff --git a/package.nls.de.json b/package.nls.de.json index 7f159fe..f0afd18 100644 --- a/package.nls.de.json +++ b/package.nls.de.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Beim Speichern einer Datei überprüfen.", "configuration.validate.mode.type": "Während der Eingabe überprüfen, nachdem `#ieLua.validate.debounce#` Millisekunden lang keine Änderungen erfolgt sind.", "configuration.validate.mode.saveAndType": "Während der Eingabe und beim Speichern einer Datei überprüfen.", - "configuration.validate.debounce.description": "Verzögerung in Millisekunden nach der letzten Änderung vor der Überprüfung, wenn `#ieLua.validate.mode#` auf `type` oder `saveAndType` festgelegt ist." + "configuration.validate.debounce.description": "Verzögerung in Millisekunden nach der letzten Änderung vor der Überprüfung, wenn `#ieLua.validate.mode#` auf `type` oder `saveAndType` festgelegt ist.", + "semanticTokenModifiers.global.description": "Eine globale Variable (ein Feld der globalen Umgebung), im Gegensatz zu einer lokalen Variable." } diff --git a/package.nls.es.json b/package.nls.es.json index 7118db1..a9c3ee3 100644 --- a/package.nls.es.json +++ b/package.nls.es.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Validar al guardar un archivo.", "configuration.validate.mode.type": "Validar mientras se escribe, tras `#ieLua.validate.debounce#` milisegundos sin cambios.", "configuration.validate.mode.saveAndType": "Validar mientras se escribe y al guardar un archivo.", - "configuration.validate.debounce.description": "Retraso en milisegundos tras el último cambio antes de validar, cuando `#ieLua.validate.mode#` es `type` o `saveAndType`." + "configuration.validate.debounce.description": "Retraso en milisegundos tras el último cambio antes de validar, cuando `#ieLua.validate.mode#` es `type` o `saveAndType`.", + "semanticTokenModifiers.global.description": "Una variable global (un campo del entorno global), a diferencia de una variable local." } diff --git a/package.nls.fr.json b/package.nls.fr.json index aa9f5ad..f9bb8a7 100644 --- a/package.nls.fr.json +++ b/package.nls.fr.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Valider lors de l'enregistrement d'un fichier.", "configuration.validate.mode.type": "Valider pendant la saisie, après `#ieLua.validate.debounce#` millisecondes sans modification.", "configuration.validate.mode.saveAndType": "Valider pendant la saisie et lors de l'enregistrement d'un fichier.", - "configuration.validate.debounce.description": "Délai en millisecondes après la dernière modification avant la validation, quand `#ieLua.validate.mode#` a la valeur `type` ou `saveAndType`." + "configuration.validate.debounce.description": "Délai en millisecondes après la dernière modification avant la validation, quand `#ieLua.validate.mode#` a la valeur `type` ou `saveAndType`.", + "semanticTokenModifiers.global.description": "Une variable globale (un champ de l'environnement global), par opposition à une variable locale." } diff --git a/package.nls.hu.json b/package.nls.hu.json index ebe4752..88269ad 100644 --- a/package.nls.hu.json +++ b/package.nls.hu.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Ellenőrzés fájl mentésekor.", "configuration.validate.mode.type": "Ellenőrzés gépelés közben, ha `#ieLua.validate.debounce#` ezredmásodpercig nem történt módosítás.", "configuration.validate.mode.saveAndType": "Ellenőrzés gépelés közben és fájl mentésekor.", - "configuration.validate.debounce.description": "Késleltetés ezredmásodpercben az utolsó módosítás és az ellenőrzés között, ha az `#ieLua.validate.mode#` értéke `type` vagy `saveAndType`." + "configuration.validate.debounce.description": "Késleltetés ezredmásodpercben az utolsó módosítás és az ellenőrzés között, ha az `#ieLua.validate.mode#` értéke `type` vagy `saveAndType`.", + "semanticTokenModifiers.global.description": "Globális változó (a globális környezet egy mezője), szemben a helyi változóval." } diff --git a/package.nls.it.json b/package.nls.it.json index 09160c5..33cdec4 100644 --- a/package.nls.it.json +++ b/package.nls.it.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Convalida al salvataggio di un file.", "configuration.validate.mode.type": "Convalida durante la digitazione, dopo `#ieLua.validate.debounce#` millisecondi senza modifiche.", "configuration.validate.mode.saveAndType": "Convalida durante la digitazione e al salvataggio di un file.", - "configuration.validate.debounce.description": "Ritardo in millisecondi dopo l'ultima modifica prima della convalida, quando `#ieLua.validate.mode#` è `type` o `saveAndType`." + "configuration.validate.debounce.description": "Ritardo in millisecondi dopo l'ultima modifica prima della convalida, quando `#ieLua.validate.mode#` è `type` o `saveAndType`.", + "semanticTokenModifiers.global.description": "Una variabile globale (un campo dell'ambiente globale), a differenza di una variabile locale." } diff --git a/package.nls.ja.json b/package.nls.ja.json index 493130e..b642028 100644 --- a/package.nls.ja.json +++ b/package.nls.ja.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "ファイルの保存時に検証します。", "configuration.validate.mode.type": "入力中に、変更がない状態が `#ieLua.validate.debounce#` ミリ秒続いた後で検証します。", "configuration.validate.mode.saveAndType": "入力中およびファイルの保存時に検証します。", - "configuration.validate.debounce.description": "`#ieLua.validate.mode#` が `type` または `saveAndType` の場合に、最後の変更から検証までの遅延時間 (ミリ秒)。" + "configuration.validate.debounce.description": "`#ieLua.validate.mode#` が `type` または `saveAndType` の場合に、最後の変更から検証までの遅延時間 (ミリ秒)。", + "semanticTokenModifiers.global.description": "グローバル変数 (グローバル環境のフィールド)。ローカル変数とは異なります。" } diff --git a/package.nls.json b/package.nls.json index b0e767d..e1c7817 100644 --- a/package.nls.json +++ b/package.nls.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Validate when a file is saved.", "configuration.validate.mode.type": "Validate while typing, after `#ieLua.validate.debounce#` milliseconds without changes.", "configuration.validate.mode.saveAndType": "Validate while typing and when a file is saved.", - "configuration.validate.debounce.description": "Delay in milliseconds after the last change before validating, when `#ieLua.validate.mode#` is `type` or `saveAndType`." + "configuration.validate.debounce.description": "Delay in milliseconds after the last change before validating, when `#ieLua.validate.mode#` is `type` or `saveAndType`.", + "semanticTokenModifiers.global.description": "A global variable (a field of the global environment), as opposed to a local." } diff --git a/package.nls.ko.json b/package.nls.ko.json index 400fa4d..92b2ced 100644 --- a/package.nls.ko.json +++ b/package.nls.ko.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "파일을 저장할 때 유효성을 검사합니다.", "configuration.validate.mode.type": "입력하는 동안 `#ieLua.validate.debounce#`밀리초 동안 변경이 없으면 유효성을 검사합니다.", "configuration.validate.mode.saveAndType": "입력하는 동안과 파일을 저장할 때 유효성을 검사합니다.", - "configuration.validate.debounce.description": "`#ieLua.validate.mode#`이(가) `type` 또는 `saveAndType`인 경우 마지막 변경 후 유효성 검사까지의 지연 시간(밀리초)입니다." + "configuration.validate.debounce.description": "`#ieLua.validate.mode#`이(가) `type` 또는 `saveAndType`인 경우 마지막 변경 후 유효성 검사까지의 지연 시간(밀리초)입니다.", + "semanticTokenModifiers.global.description": "전역 변수(전역 환경의 필드)로, 로컬 변수와 구별됩니다." } diff --git a/package.nls.pl.json b/package.nls.pl.json index c3ccb34..1713be7 100644 --- a/package.nls.pl.json +++ b/package.nls.pl.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Sprawdzaj poprawność podczas zapisywania pliku.", "configuration.validate.mode.type": "Sprawdzaj poprawność podczas pisania, po `#ieLua.validate.debounce#` ms bez zmian.", "configuration.validate.mode.saveAndType": "Sprawdzaj poprawność podczas pisania i zapisywania pliku.", - "configuration.validate.debounce.description": "Opóźnienie w milisekundach od ostatniej zmiany do sprawdzenia poprawności, gdy ustawienie `#ieLua.validate.mode#` ma wartość `type` lub `saveAndType`." + "configuration.validate.debounce.description": "Opóźnienie w milisekundach od ostatniej zmiany do sprawdzenia poprawności, gdy ustawienie `#ieLua.validate.mode#` ma wartość `type` lub `saveAndType`.", + "semanticTokenModifiers.global.description": "Zmienna globalna (pole środowiska globalnego), w odróżnieniu od zmiennej lokalnej." } diff --git a/package.nls.pt-br.json b/package.nls.pt-br.json index 98fb7f8..dca88b8 100644 --- a/package.nls.pt-br.json +++ b/package.nls.pt-br.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Validar quando um arquivo for salvo.", "configuration.validate.mode.type": "Validar durante a digitação, após `#ieLua.validate.debounce#` milissegundos sem alterações.", "configuration.validate.mode.saveAndType": "Validar durante a digitação e quando um arquivo for salvo.", - "configuration.validate.debounce.description": "Atraso em milissegundos após a última alteração antes da validação, quando `#ieLua.validate.mode#` for `type` ou `saveAndType`." + "configuration.validate.debounce.description": "Atraso em milissegundos após a última alteração antes da validação, quando `#ieLua.validate.mode#` for `type` ou `saveAndType`.", + "semanticTokenModifiers.global.description": "Uma variável global (um campo do ambiente global), ao contrário de uma variável local." } diff --git a/package.nls.ru.json b/package.nls.ru.json index eb4f941..cd730af 100644 --- a/package.nls.ru.json +++ b/package.nls.ru.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Выполнять проверку при сохранении файла.", "configuration.validate.mode.type": "Выполнять проверку во время ввода, если изменений не было в течение `#ieLua.validate.debounce#` мс.", "configuration.validate.mode.saveAndType": "Выполнять проверку во время ввода и при сохранении файла.", - "configuration.validate.debounce.description": "Задержка в миллисекундах после последнего изменения перед проверкой, если для `#ieLua.validate.mode#` задано значение `type` или `saveAndType`." + "configuration.validate.debounce.description": "Задержка в миллисекундах после последнего изменения перед проверкой, если для `#ieLua.validate.mode#` задано значение `type` или `saveAndType`.", + "semanticTokenModifiers.global.description": "Глобальная переменная (поле глобального окружения), в отличие от локальной." } diff --git a/package.nls.tr.json b/package.nls.tr.json index fe08e10..c173a63 100644 --- a/package.nls.tr.json +++ b/package.nls.tr.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "Dosya kaydedildiğinde doğrula.", "configuration.validate.mode.type": "Yazarken, `#ieLua.validate.debounce#` milisaniye boyunca değişiklik olmadığında doğrula.", "configuration.validate.mode.saveAndType": "Yazarken ve dosya kaydedildiğinde doğrula.", - "configuration.validate.debounce.description": "`#ieLua.validate.mode#` ayarı `type` veya `saveAndType` olduğunda, son değişiklikten doğrulamaya kadar geçen milisaniye cinsinden gecikme." + "configuration.validate.debounce.description": "`#ieLua.validate.mode#` ayarı `type` veya `saveAndType` olduğunda, son değişiklikten doğrulamaya kadar geçen milisaniye cinsinden gecikme.", + "semanticTokenModifiers.global.description": "Yerel değişkenin aksine, genel bir değişken (genel ortamın bir alanı)." } diff --git a/package.nls.zh-cn.json b/package.nls.zh-cn.json index ee67a2e..4449ff7 100644 --- a/package.nls.zh-cn.json +++ b/package.nls.zh-cn.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "在保存文件时验证。", "configuration.validate.mode.type": "在键入时验证,在 `#ieLua.validate.debounce#` 毫秒内无更改后进行。", "configuration.validate.mode.saveAndType": "在键入时和保存文件时验证。", - "configuration.validate.debounce.description": "当 `#ieLua.validate.mode#` 为 `type` 或 `saveAndType` 时,最后一次更改后到开始验证前的延迟时间(毫秒)。" + "configuration.validate.debounce.description": "当 `#ieLua.validate.mode#` 为 `type` 或 `saveAndType` 时,最后一次更改后到开始验证前的延迟时间(毫秒)。", + "semanticTokenModifiers.global.description": "全局变量(全局环境中的字段),与局部变量相对。" } diff --git a/package.nls.zh-tw.json b/package.nls.zh-tw.json index 6c80097..89887f0 100644 --- a/package.nls.zh-tw.json +++ b/package.nls.zh-tw.json @@ -9,5 +9,6 @@ "configuration.validate.mode.save": "在儲存檔案時驗證。", "configuration.validate.mode.type": "在輸入時驗證,於 `#ieLua.validate.debounce#` 毫秒內沒有變更後進行。", "configuration.validate.mode.saveAndType": "在輸入時及儲存檔案時驗證。", - "configuration.validate.debounce.description": "當 `#ieLua.validate.mode#` 為 `type` 或 `saveAndType` 時,最後一次變更到開始驗證之間的延遲時間 (毫秒)。" + "configuration.validate.debounce.description": "當 `#ieLua.validate.mode#` 為 `type` 或 `saveAndType` 時,最後一次變更到開始驗證之間的延遲時間 (毫秒)。", + "semanticTokenModifiers.global.description": "全域變數(全域環境中的欄位),與區域變數相對。" } diff --git a/src/server/features/semanticTokens.ts b/src/server/features/semanticTokens.ts new file mode 100644 index 0000000..b0a86cf --- /dev/null +++ b/src/server/features/semanticTokens.ts @@ -0,0 +1,125 @@ +import type { Connection, Range, SemanticTokens, SemanticTokensDelta, SemanticTokensLegend, TextDocuments } from 'vscode-languageserver/node'; +import { SemanticTokensBuilder } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { classifyNames, TOKEN_MODIFIERS, TOKEN_TYPES, type NameToken, type TokenModifier, type TokenType } from '../semanticTokens/classify.ts'; + +export interface SemanticTokensDeps { + readonly cache: ParsedDocumentCache; +} + +/** Token types and modifiers by index, as advertised in `semanticTokensProvider.legend`. */ +export const LEGEND: SemanticTokensLegend = { tokenTypes: [...TOKEN_TYPES], tokenModifiers: [...TOKEN_MODIFIERS] }; + +/** Index of each type, and bit of each modifier, in the legend. */ +const TYPE_INDEX = Object.fromEntries(TOKEN_TYPES.map((type, i) => [type, i])) as Readonly>; +const MODIFIER_BIT = Object.fromEntries(TOKEN_MODIFIERS.map((modifier, i) => [modifier, 1 << i])) as Readonly>; + +/** Where tokens are pushed: `SemanticTokensBuilder.push`, which delta-encodes them. */ +export interface TokenSink { + push(line: number, char: number, length: number, tokenType: number, tokenModifiers: number): void; +} + +/** + * Pushes the tokens that overlap `range` (`[start, end)` offsets; all when + * omitted) in the relative format of LSP: line and UTF-16 character of the + * start, length, legend index of the type and bit set of the modifiers. + * Tokens never span lines (see classify.ts), so `multilineTokenSupport` is not needed. + */ +export function pushTokens(sink: TokenSink, tokens: readonly NameToken[], positionAt: (offset: number) => { line: number; character: number }, range?: { start: number; end: number }): void { + for (const token of tokens) { + if (range && (token.end <= range.start || token.start >= range.end)) continue; + const { line, character } = positionAt(token.start); + let modifiers = 0; + for (const modifier of token.modifiers) modifiers |= MODIFIER_BIT[modifier]; + sink.push(line, character, token.end - token.start, TYPE_INDEX[token.type], modifiers); + } +} + +/** + * The last full result of each document, so that `/full/delta` can answer + * with edits against it. `fill` pushes the document's current tokens. + */ +export class TokenResults { + private readonly builders = new Map(); + + /** A full result, remembered for later deltas. */ + full(uri: string, fill: (sink: TokenSink) => void): SemanticTokens { + const builder = new SemanticTokensBuilder(); + this.builders.set(uri, builder); + fill(builder); + return builder.build(); + } + + /** + * Edits against `previousResultId` when it is the last result of the + * document; otherwise (unknown id, unseen or closed document) a full result. + */ + delta(uri: string, previousResultId: string, fill: (sink: TokenSink) => void): SemanticTokens | SemanticTokensDelta { + const builder = this.builders.get(uri); + if (!builder) return this.full(uri, fill); + // Keeps the previous data only when its id matches; buildEdits() then diffs, or else returns a full result. + builder.previousResult(previousResultId); + fill(builder); + return builder.buildEdits(); + } + + delete(uri: string): void { + this.builders.delete(uri); + } +} + +/** + * `textDocument/semanticTokens/full`, `/full/delta` and `/range` (see + * src/server/semanticTokens/classify.ts). + */ +export function register(connection: Connection, documents: TextDocuments, deps: SemanticTokensDeps): void { + const results = new TokenResults(); + documents.onDidClose(({ document }) => { + results.delete(document.uri); + }); + const failed = (uri: string, error: unknown): SemanticTokens => { + // A failed request may have left a builder half filled: the next delta starts over. + results.delete(uri); + connection.console.error(`Semantic tokens for ${uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return { data: [] }; + }; + /** Pushes the tokens of `document`; synchronous, so a cancellation can only arrive after the response. */ + const filler = (document: TextDocument, range?: Range) => (sink: TokenSink): void => { + const offsets = range && { start: document.offsetAt(range.start), end: document.offsetAt(range.end) }; + pushTokens(sink, classifyNames(deps.cache.get(document)), (offset) => document.positionAt(offset), offsets); + }; + + connection.languages.semanticTokens.on(({ textDocument }, token): SemanticTokens => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) return { data: [] }; + return results.full(document.uri, filler(document)); + } catch (error) { + return failed(textDocument.uri, error); + } + }); + + connection.languages.semanticTokens.onDelta(({ textDocument, previousResultId }, token): SemanticTokens | SemanticTokensDelta => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) return { data: [] }; + return results.delta(document.uri, previousResultId, filler(document)); + } catch (error) { + return failed(textDocument.uri, error); + } + }); + + connection.languages.semanticTokens.onRange(({ textDocument, range }, token): SemanticTokens => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) return { data: [] }; + // A range result is never diffed against: it does not touch the document's last result. + const builder = new SemanticTokensBuilder(); + filler(document, range)(builder); + return builder.build(); + } catch (error) { + return failed(textDocument.uri, error); + } + }); +} diff --git a/src/server/hover/resolve.ts b/src/server/hover/resolve.ts index f7d22e8..6aa1b46 100644 --- a/src/server/hover/resolve.ts +++ b/src/server/hover/resolve.ts @@ -24,7 +24,7 @@ import type * as Ast from '../syntax/ast.ts'; import type { ParsedDocument } from '../syntax/document.ts'; import { fieldWrites, globalPath, withoutG } from '../syntax/globalPaths.ts'; import { memberAt, type MemberOccurrence } from '../syntax/members.ts'; -import { definitions, targetAt, type TargetHit } from '../syntax/navigation.ts'; +import { targetAt, type TargetHit } from '../syntax/navigation.ts'; import type { Declaration } from '../syntax/scope.ts'; import { declarationSite, type DeclarationSite } from '../syntax/signatures.ts'; import { engineReplacement, externalEntry, manualEntry, type EngineReplacement, type ExternalEntry, type ManualEntry } from './knowledge.ts'; @@ -43,9 +43,29 @@ export interface HoverHit { readonly identifier: Ast.Identifier; } -/** The first assignment to the global `name` in the document, if any. */ +/** The first assignment to each global of each document, by name; dropped with the document. */ +const firstWriteIndexes = new WeakMap>(); + +/** + * The first assignment to the global `name` in the document, if any: the + * first of `definitions` (syntax/navigation.ts), which is in document order. Indexed once per + * document, as a .menu file has thousands of chunks to search. + */ function firstWrite(document: ParsedDocument, name: string): Ast.Identifier | undefined { - return definitions(document, { kind: 'global', name })[0]; + let index = firstWriteIndexes.get(document); + if (!index) { + const first = new Map(); + for (const { scopes } of document.chunks) { + for (const identifier of scopes.writes) { + const earlier = first.get(identifier.name); + // Chunks are in document order and never overlap, so the lowest offset comes first. + if (!scopes.resolved.has(identifier) && (!earlier || identifier.start < earlier.start)) first.set(identifier.name, identifier); + } + } + index = first; + firstWriteIndexes.set(document, index); + } + return index.get(name); } /** A global that is not assigned in the document, looked up in what the server knows. */ @@ -66,7 +86,8 @@ function globalTarget(document: ParsedDocument, name: string): HoverTarget { return knownGlobal(name) ?? { kind: 'global', name, site: undefined, link: undefined }; } -function variableTarget(document: ParsedDocument, { target, identifier, chunkIndex }: TargetHit): HoverTarget | undefined { +/** What to describe for a variable occurrence (see `targetAt`), or `undefined` when there is nothing to say. */ +export function variableTarget(document: ParsedDocument, { target, identifier, chunkIndex }: TargetHit): HoverTarget | undefined { if (target.kind === 'local') { const declaring = target.declaration.identifier; return { kind: 'local', declaration: target.declaration, site: declaring && declarationSite(document, declaring) }; @@ -87,7 +108,8 @@ function libraryMember(document: ParsedDocument, dotted: string): ManualEntry | const isStringLiteral = (expression: Ast.Expression): boolean => expression.kind === 'StringLiteral' || (expression.kind === 'ParenthesizedExpression' && isStringLiteral(expression.expression)); -function memberTarget(document: ParsedDocument, { node, chunkIndex }: MemberOccurrence): HoverTarget | undefined { +/** What to describe for a field or method name (see `memberIndex`), or `undefined` when there is nothing to say. */ +export function memberTarget(document: ParsedDocument, { node, chunkIndex }: MemberOccurrence): HoverTarget | undefined { if (node.kind === 'MethodCallExpression') { // Strings have the string table as their metatable's __index (manual §6.4). if (isStringLiteral(node.base)) { diff --git a/src/server/semanticTokens/classify.ts b/src/server/semanticTokens/classify.ts new file mode 100644 index 0000000..3bd59f3 --- /dev/null +++ b/src/server/semanticTokens/classify.ts @@ -0,0 +1,202 @@ +// What each name of a document is, for semantic highlighting. Pure: no LSP or +// `vscode` imports. +// +// Only names are classified; keywords, literals, comments and .menu syntax are +// left to the TextMate grammars. Names follow the rules of hover +// (hover/resolve.ts), so a name is colored as it hovers: +// +// - Locals: `parameter` for parameters and the implicit `self` (manual +// §3.4.10, "an extra parameter called self"); `function` for `local function +// f` and for a local declared with a function expression and never assigned +// again; `variable` otherwise. The declaring name has `declaration`. +// - Globals have `global`. A global the document assigns is a `function` when +// its first assignment gives it a function, a `variable` otherwise. Other +// globals take their kind from the Lua 5.2 manual (`namespace` for module +// tables) or EEex-Docs (`function`), with `defaultLibrary` for the manual's +// names, the engine's `print` and the EE Game Lua Functions; EEex functions +// are a separate mod and do not get it. +// - `_ENV`, and names resolved through a local `_ENV`, are fields of a table +// (manual §2.2): `variable` without `global`. +// - Field names: `property`, `method` after `:`; a library or EEex-Docs +// member takes its kind from the documentation, as in hover. The names after +// the first in `function a.b:m()` are a `property` path ending in a +// `function` or `method`; named keys of table constructors are a declared +// `property`. +// - Labels (`::name::`, `goto name`): `label`. +// - Assignment targets have `modification`. + +import type * as Ast from '../syntax/ast.ts'; +import type { ParsedDocument } from '../syntax/document.ts'; +import type { ExternalEntry, ManualEntry } from '../hover/knowledge.ts'; +import { memberTarget, variableTarget, type HoverTarget } from '../hover/resolve.ts'; +import { globalPath, withoutG } from '../syntax/globalPaths.ts'; +import { memberIndex } from '../syntax/members.ts'; +import { variableIndex } from '../syntax/navigation.ts'; +import type { Declaration } from '../syntax/scope.ts'; +import { declarationSite } from '../syntax/signatures.ts'; +import { walk } from '../syntax/walk.ts'; + +export const TOKEN_TYPES = ['namespace', 'function', 'method', 'variable', 'parameter', 'property', 'label'] as const; +export type TokenType = (typeof TOKEN_TYPES)[number]; + +/** `global` is not a standard modifier: the extension manifest declares it (`semanticTokenModifiers`). */ +export const TOKEN_MODIFIERS = ['declaration', 'modification', 'defaultLibrary', 'global'] as const; +export type TokenModifier = (typeof TOKEN_MODIFIERS)[number]; + +/** A classified name: `[start, end)` document offsets, never spanning lines. */ +export interface NameToken { + readonly start: number; + readonly end: number; + readonly type: TokenType; + readonly modifiers: readonly TokenModifier[]; +} + +/** EEex-Docs section whose functions the engine itself provides (see hover/knowledge.ts). */ +const ENGINE_SOURCE = 'EE Game Lua Functions'; + +type Kind = Pick; + +function manualKind(entry: ManualEntry): Kind { + const type: TokenType = entry.kind === 'module' ? 'namespace' : entry.kind === 'function' ? 'function' : 'variable'; + return { type, modifiers: ['defaultLibrary'] }; +} + +function externalKind(entry: ExternalEntry): Kind { + return { type: 'function', modifiers: entry.sourceTitle === ENGINE_SOURCE ? ['defaultLibrary'] : [] }; +} + +const isFunction = (expression: Ast.Expression | undefined): boolean => expression?.kind === 'FunctionExpression'; + +function localKind(document: ParsedDocument, declaration: Declaration, writes: ReadonlySet): TokenType { + switch (declaration.kind) { + case 'parameter': + case 'self': + return 'parameter'; + case 'localFunction': + return 'function'; + case 'forVariable': + return 'variable'; + case 'local': { + const site = declaration.identifier && declarationSite(document, declaration.identifier); + const constant = !declaration.references.some((reference) => writes.has(reference)); + return site?.kind === 'local' && isFunction(site.value) && constant ? 'function' : 'variable'; + } + } +} + +/** The kind of a name hover describes as `target` (not a local). */ +function documentedKind(target: HoverTarget): Kind | undefined { + switch (target.kind) { + case 'global': { + const site = target.site; + const assignsFunction = site?.kind === 'functionDeclaration' || (site?.kind === 'assignment' && isFunction(site.value)); + return { type: assignsFunction ? 'function' : 'variable', modifiers: [] }; + } + case 'library': + return manualKind(target.entry); + case 'engineReplaced': + return { type: 'function', modifiers: ['defaultLibrary'] }; + case 'external': + return externalKind(target.entry); + case 'local': + return undefined; + } +} + +/** Classified names of each document; dropped with the document. */ +const caches = new WeakMap(); + +/** Every name of the document with its classification, sorted by offset. Never throws. */ +export function classifyNames(document: ParsedDocument): readonly NameToken[] { + let tokens = caches.get(document); + if (!tokens) { + tokens = classify(document); + caches.set(document, tokens); + } + return tokens; +} + +function classify(document: ParsedDocument): NameToken[] { + const tokens: NameToken[] = []; + const add = (identifier: Ast.Identifier, type: TokenType, ...modifiers: (TokenModifier | false)[]): void => { + tokens.push({ start: identifier.start, end: identifier.end, type, modifiers: modifiers.filter((modifier) => modifier !== false) }); + }; + /** A global's classification depends only on its name; resolving it scans every chunk, so once per name. */ + const globals = new Map(); + + for (const hit of variableIndex(document)) { + const { identifier, chunkIndex } = hit; + const scopes = document.chunks[chunkIndex]?.scopes; + if (!scopes) continue; + const modification = scopes.writes.has(identifier) && 'modification'; + const declaration = scopes.resolved.get(identifier); + if (declaration) { + add(identifier, localKind(document, declaration, scopes.writes), declaration.identifier === identifier && 'declaration', modification); + continue; + } + if (scopes.environmentFields.has(identifier) || identifier.name === '_ENV') { + add(identifier, 'variable', modification); + continue; + } + let kind = globals.get(identifier.name); + if (!kind) { + const target = variableTarget(document, { identifier, chunkIndex, target: { kind: 'global', name: identifier.name } }); + kind = (target && documentedKind(target)) ?? { type: 'variable', modifiers: [] }; + globals.set(identifier.name, kind); + } + add(identifier, kind.type, ...kind.modifiers, modification, 'global'); + } + + /** Field names that `t.x = …` assigns. */ + const assigned = new Set(); + document.chunks.forEach(({ tree }) => { + walk(tree.body, (node) => { + switch (node.kind) { + case 'AssignmentStatement': + for (const target of node.targets) if (target.kind === 'MemberExpression') assigned.add(target.member); + break; + case 'FunctionDeclaration': { + // The first name is a variable (above); the rest name fields. + const fields = node.path.slice(1); + fields.forEach((field, i) => { + const last = i === fields.length - 1 && !node.method; + add(field, last ? 'function' : 'property', last && 'modification'); + }); + if (node.method) add(node.method, 'method', 'modification'); + break; + } + case 'LabelStatement': + add(node.label, 'label', 'declaration'); + break; + case 'GotoStatement': + add(node.label, 'label'); + break; + case 'TableConstructor': + for (const field of node.fields) { + if (field.form === 'named' && field.key?.kind === 'Identifier') add(field.key, 'property', 'declaration'); + } + break; + default: + break; + } + }); + }); + + for (const occurrence of memberIndex(document)) { + const { identifier, node, chunkIndex } = occurrence; + const target = memberTarget(document, occurrence); + const modification = assigned.has(identifier) && 'modification'; + // Only library and EEex-Docs members, and globals named through `_G.x`, are documented. + const documented = target && documentedKind(target); + const isMethod = node.kind === 'MethodCallExpression'; + if (!documented) { + add(identifier, isMethod ? 'method' : 'property', modification); + continue; + } + const path = isMethod ? undefined : globalPath(document, chunkIndex, node); + const isGlobal = path !== undefined && withoutG(path).length === 1; + add(identifier, isMethod ? 'method' : documented.type, ...documented.modifiers, modification, isGlobal && 'global'); + } + + return tokens.sort((a, b) => a.start - b.start); +} diff --git a/src/server/server.ts b/src/server/server.ts index 7508ea2..fdb30fa 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -24,6 +24,7 @@ import * as hover from './features/hover.ts'; import { markupFormat } from './features/markup.ts'; import * as references from './features/references.ts'; import * as rename from './features/rename.ts'; +import * as semanticTokens from './features/semanticTokens.ts'; import * as workspaceSymbols from './features/workspaceSymbols.ts'; import { createMessages } from './l10n.ts'; import { SettingsStore } from './settingsStore.ts'; @@ -103,6 +104,7 @@ connection.onInitialize((params) => { references.register(connection, documents, { cache: parsed }); rename.register(connection, documents, { cache: parsed, documentChanges: workspace?.workspaceEdit?.documentChanges === true }); workspaceSymbols.register(connection, documents, { cache: parsed, index }); + semanticTokens.register(connection, documents, { cache: parsed }); hover.register(connection, documents, { cache: parsed, format: markupFormat(params.capabilities.textDocument?.hover?.contentFormat), @@ -138,6 +140,7 @@ connection.onInitialize((params) => { workspaceSymbolProvider: true, hoverProvider: true, completionProvider: { triggerCharacters: [...completion.TRIGGER_CHARACTERS], resolveProvider: true }, + semanticTokensProvider: { legend: semanticTokens.LEGEND, full: { delta: true }, range: true }, ...(workspaceFolderChanges ? { workspace: { workspaceFolders: { supported: true, changeNotifications: true } } } : {}), }, serverInfo: { name: 'IE Lua Language Server' }, diff --git a/test/fixtures/workspace/SEMANTIC.MENU b/test/fixtures/workspace/SEMANTIC.MENU new file mode 100644 index 0000000..3407cf1 --- /dev/null +++ b/test/fixtures/workspace/SEMANTIC.MENU @@ -0,0 +1,11 @@ +-- Original fixture: semantic tokens in the Lua of a .menu file. +` +function SemanticShow(count) + return count + 1 +end +` +menu +{ + name 'SEMANTIC_MAIN' + onOpen "SemanticShow(2)" +} diff --git a/test/fixtures/workspace/semantic.lua b/test/fixtures/workspace/semantic.lua new file mode 100644 index 0000000..a2b73d7 --- /dev/null +++ b/test/fixtures/workspace/semantic.lua @@ -0,0 +1,9 @@ +-- Original fixture: semantic tokens. +local function scale(value, factor) + local result = value * factor + return result +end + +SemanticTotal = scale(2, 3) +local label = string.format("%d", SemanticTotal) +Infinity_DisplayString(label) diff --git a/test/integration/semanticTokens.test.ts b/test/integration/semanticTokens.test.ts new file mode 100644 index 0000000..ae1e506 --- /dev/null +++ b/test/integration/semanticTokens.test.ts @@ -0,0 +1,86 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, openFixture } from './helpers.ts'; + +/** Decodes LSP-encoded tokens into `text type modifier,modifier` entries, in order. */ +function decode(document: vscode.TextDocument, legend: vscode.SemanticTokensLegend, tokens: vscode.SemanticTokens): string[] { + const out: string[] = []; + const data = tokens.data; + let line = 0; + let character = 0; + for (let i = 0; i + 4 < data.length; i += 5) { + const deltaLine = data[i] ?? 0; + line += deltaLine; + character = deltaLine === 0 ? character + (data[i + 1] ?? 0) : (data[i + 1] ?? 0); + const start = new vscode.Position(line, character); + const text = document.getText(new vscode.Range(start, start.translate(0, data[i + 2] ?? 0))); + const bits = data[i + 4] ?? 0; + const modifiers = legend.tokenModifiers.filter((_, bit) => (bits & (1 << bit)) !== 0); + out.push(`${text} ${legend.tokenTypes[data[i + 3] ?? -1] ?? '?'} ${modifiers.join(',')}`.trimEnd()); + } + return out; +} + +async function tokensOf(file: string, range?: (document: vscode.TextDocument) => vscode.Range): Promise { + const uri = await openFixture(file); + const document = await vscode.workspace.openTextDocument(uri); + const legend = await vscode.commands.executeCommand( + range ? 'vscode.provideDocumentRangeSemanticTokensLegend' : 'vscode.provideDocumentSemanticTokensLegend', + uri, + ); + assert.ok(legend, 'no semantic tokens legend'); + const tokens = range + ? await vscode.commands.executeCommand('vscode.provideDocumentRangeSemanticTokens', uri, range(document)) + : await vscode.commands.executeCommand('vscode.provideDocumentSemanticTokens', uri); + assert.ok(tokens, 'no semantic tokens provider answered'); + return decode(document, legend, tokens); +} + +suite('Semantic tokens', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('classifies the names of a Lua file', async () => { + assert.deepEqual(await tokensOf('semantic.lua'), [ + 'scale function declaration', + 'value parameter declaration', + 'factor parameter declaration', + 'result variable declaration', + 'value parameter', + 'factor parameter', + 'result variable', + 'SemanticTotal variable modification,global', + 'scale function', + 'label variable declaration', + 'string namespace defaultLibrary,global', + 'format function defaultLibrary', + 'SemanticTotal variable global', + 'Infinity_DisplayString function defaultLibrary,global', + 'label variable', + ]); + }); + + test('classifies only the Lua of a .menu file, with its globals shared across chunks', async () => { + assert.deepEqual(await tokensOf('SEMANTIC.MENU'), [ + 'SemanticShow function modification,global', + 'count parameter declaration', + 'count parameter', + 'SemanticShow function global', + ]); + }); + + test('returns the tokens of a range', async () => { + const tokens = await tokensOf('semantic.lua', (document) => document.lineAt(7).range); + assert.deepEqual(tokens, [ + 'label variable declaration', + 'string namespace defaultLibrary,global', + 'format function defaultLibrary', + 'SemanticTotal variable global', + ]); + }); +}); diff --git a/test/unit/server/features/semanticTokens.test.ts b/test/unit/server/features/semanticTokens.test.ts new file mode 100644 index 0000000..47f589d --- /dev/null +++ b/test/unit/server/features/semanticTokens.test.ts @@ -0,0 +1,94 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { SemanticTokenModifiers, SemanticTokenTypes } from 'vscode-languageserver/node'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { LEGEND, pushTokens, TokenResults, type TokenSink } from '../../../../src/server/features/semanticTokens.ts'; +import { classifyNames } from '../../../../src/server/semanticTokens/classify.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; + +/** The pushes for `text`: `[line, character, length, type, modifiers]`, decoded to names. */ +function pushes(text: string, range?: { start: number; end: number }): string[] { + const document = TextDocument.create('file:///t.lua', 'lua', 1, text); + const out: string[] = []; + pushTokens( + { + push: (line, character, length, type, modifiers) => { + const names = LEGEND.tokenModifiers.filter((_, i) => (modifiers & (1 << i)) !== 0); + out.push(`${String(line)}:${String(character)}+${String(length)} ${LEGEND.tokenTypes[type] ?? '?'} ${names.join(',')}`.trimEnd()); + }, + }, + classifyNames(parseDocument(text, 'lua')), + (offset) => document.positionAt(offset), + range, + ); + return out; +} + +describe('server/features/semanticTokens', () => { + it('uses only standard token types, and standard modifiers plus the declared "global"', () => { + const standardTypes: readonly string[] = Object.values(SemanticTokenTypes); + const standardModifiers: readonly string[] = Object.values(SemanticTokenModifiers); + for (const type of LEGEND.tokenTypes) assert.ok(standardTypes.includes(type), type); + const custom = LEGEND.tokenModifiers.filter((modifier) => !standardModifiers.includes(modifier)); + assert.deepEqual(custom, ['global']); + }); + + it('declares every custom modifier in the extension manifest', () => { + const manifest = JSON.parse(readFileSync(new URL('../../../../package.json', import.meta.url), 'utf8')) as { contributes: { semanticTokenModifiers?: { id: string }[] } }; + assert.deepEqual(manifest.contributes.semanticTokenModifiers?.map((modifier) => modifier.id), ['global']); + }); + + it('pushes line, UTF-16 character, length, legend type and modifier bits', () => { + assert.deepEqual(pushes('local x = 1\n print(x)'), ['0:6+1 variable declaration', '1:2+5 function defaultLibrary,global', '1:8+1 variable']); + }); + + it('counts characters in UTF-16 code units', () => { + // `é` is one UTF-16 code unit, `😀` two: the last `s` is at character 23 (22 in code points). + assert.deepEqual(pushes('local s = "é😀" return s'), ['0:6+1 variable declaration', '0:23+1 variable']); + }); + + it('keeps only the tokens that overlap the range', () => { + const text = 'local a = 1\nlocal b = a\nlocal c = b'; + const start = text.indexOf('local b'); + assert.deepEqual(pushes(text, { start, end: start + 'local b = a'.length }), ['1:6+1 variable declaration', '1:10+1 variable']); + assert.deepEqual(pushes(text, { start: 0, end: 0 }), []); + }); + + describe('TokenResults', () => { + /** A `fill` for `text`, as the handlers make one for a document. */ + const fill = (text: string) => (sink: TokenSink): void => { + const document = TextDocument.create('file:///t.lua', 'lua', 1, text); + pushTokens(sink, classifyNames(parseDocument(text, 'lua')), (offset) => document.positionAt(offset)); + }; + + it('answers a delta request with edits against the last full result', () => { + const results = new TokenResults(); + const first = results.full('file:///a.lua', fill('local a = 1')); + assert.ok(first.resultId); + const delta = results.delta('file:///a.lua', first.resultId, fill('local a = 1 return a')); + assert.ok('edits' in delta, 'edits'); + // One token appended after the first five numbers: `a` (variable, index 3) 13 characters after the declaration at 6. + assert.deepEqual(delta.edits, [{ start: 5, deleteCount: 0, data: [0, 13, 1, 3, 0] }]); + }); + + it('answers with a full result when the previous result is unknown, unseen or closed', () => { + const results = new TokenResults(); + const first = results.full('file:///a.lua', fill('local a')); + assert.ok('data' in results.delta('file:///a.lua', 'not-a-result', fill('local b')), 'unknown id'); + assert.ok('data' in results.delta('file:///b.lua', first.resultId ?? '', fill('local b')), 'unseen document'); + const again = results.full('file:///a.lua', fill('local a')); + results.delete('file:///a.lua'); + assert.ok('data' in results.delta('file:///a.lua', again.resultId ?? '', fill('local a')), 'closed document'); + }); + + it('chains deltas: each delta becomes the result the next one is diffed against', () => { + const results = new TokenResults(); + const first = results.full('file:///a.lua', fill('local a')); + const second = results.delta('file:///a.lua', first.resultId ?? '', fill('local a local b')); + assert.ok('edits' in second && second.resultId); + const third = results.delta('file:///a.lua', second.resultId, fill('local a local b')); + assert.ok('edits' in third, 'edits'); + assert.deepEqual(third.edits, []); + }); + }); +}); diff --git a/test/unit/server/hover/resolve.test.ts b/test/unit/server/hover/resolve.test.ts index b066e95..e594c21 100644 --- a/test/unit/server/hover/resolve.test.ts +++ b/test/unit/server/hover/resolve.test.ts @@ -50,6 +50,11 @@ describe('server/hover/resolve', () => { assert.equal(hover(menu, 'Total', { occurrence: 2, kind: 'menu' }), 'Total -> global Total assignment -'); }); + it('describes a global by its own first assignment, not by an earlier assignment to a local of the same name', () => { + const text = 'do local G function G() end end G = 2 function G() end return G'; + assert.equal(hover(text, 'return G', { offset: 7 }), 'G -> global G assignment -'); + }); + it('lets the document\'s own definition win over the libraries, keeping EEex-Docs links', () => { assert.equal(hover('function print() end print()', 'print', { occurrence: 1 }), 'print -> global print functionDeclaration -'); assert.equal(hover('string = {} string.format()', 'format'), undefined); diff --git a/test/unit/server/semanticTokens/classify.test.ts b/test/unit/server/semanticTokens/classify.test.ts new file mode 100644 index 0000000..782bf88 --- /dev/null +++ b/test/unit/server/semanticTokens/classify.test.ts @@ -0,0 +1,175 @@ +import assert from 'node:assert/strict'; +import { classifyNames, TOKEN_MODIFIERS, TOKEN_TYPES } from '../../../../src/server/semanticTokens/classify.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { lex } from '../../../../src/server/syntax/lexer.ts'; + +/** `name type modifier,modifier` for every classified name of `text`, in order. */ +function tokens(text: string, kind: 'lua' | 'menu' = 'lua'): string[] { + return classifyNames(parseDocument(text, kind)).map((token) => `${text.slice(token.start, token.end)} ${token.type} ${[...token.modifiers].sort().join(',')}`.trimEnd()); +} + +/** The classification of the `occurrence`-th name `name` in `text`. */ +function token(text: string, name: string, occurrence = 0, kind: 'lua' | 'menu' = 'lua'): string | undefined { + return tokens(text, kind).filter((entry) => entry.split(' ')[0] === name)[occurrence]; +} + +describe('server/semanticTokens/classify', () => { + describe('locals', () => { + it('classifies locals and for variables as variables, declared where they are declared', () => { + const text = 'local x = 1 for i = 1, x do end for k, v in pairs(x) do end return x'; + assert.equal(token(text, 'x'), 'x variable declaration'); + assert.equal(token(text, 'x', 1), 'x variable'); + assert.equal(token(text, 'i'), 'i variable declaration'); + assert.equal(token(text, 'v'), 'v variable declaration'); + }); + + it('classifies local functions, and locals declared with a function that is never reassigned, as functions', () => { + const text = 'local function f() end local g = function() end local h = function() end h = 1 return f, g, h'; + assert.equal(token(text, 'f'), 'f function declaration'); + assert.equal(token(text, 'f', 1), 'f function'); + assert.equal(token(text, 'g', 1), 'g function'); + assert.equal(token(text, 'h'), 'h variable declaration'); + assert.equal(token(text, 'h', 1), 'h variable modification'); + }); + + it('classifies parameters and the implicit self as parameters', () => { + const text = 'function T:m(a, b) return self, a end'; + assert.equal(token(text, 'a'), 'a parameter declaration'); + assert.equal(token(text, 'a', 1), 'a parameter'); + assert.equal(token(text, 'self'), 'self parameter'); + }); + + it('marks assignments to locals as modifications', () => { + assert.equal(token('local x x = 2', 'x', 1), 'x variable modification'); + }); + + it('lets a local shadow a library name', () => { + assert.equal(token('local string = {} return string', 'string', 1), 'string variable'); + }); + }); + + describe('globals', () => { + it('classifies globals the document assigns by their first assignment, without library modifiers', () => { + const text = 'function G() end V = 1 F = function() end print = nil return G, V, F, print'; + assert.equal(token(text, 'G'), 'G function global,modification'); + assert.equal(token(text, 'G', 1), 'G function global'); + assert.equal(token(text, 'V', 1), 'V variable global'); + assert.equal(token(text, 'F', 1), 'F function global'); + assert.equal(token(text, 'print', 1), 'print variable global'); + }); + + it('classifies Lua 5.2 library globals by their manual entry, as default library', () => { + const text = 'return string, pairs, _VERSION, print'; + assert.equal(token(text, 'string'), 'string namespace defaultLibrary,global'); + assert.equal(token(text, 'pairs'), 'pairs function defaultLibrary,global'); + assert.equal(token(text, '_VERSION'), '_VERSION variable defaultLibrary,global'); + assert.equal(token(text, 'print'), 'print function defaultLibrary,global'); + }); + + it('gives EE game functions the default library modifier, and EEex functions not', () => { + assert.equal(token('Infinity_DisplayString("x")', 'Infinity_DisplayString'), 'Infinity_DisplayString function defaultLibrary,global'); + assert.equal(token('EEex_Sprite_GetName(nil)', 'EEex_Sprite_GetName'), 'EEex_Sprite_GetName function global'); + }); + + it('does not offer libraries the engine lacks, and classifies other globals as variables', () => { + assert.equal(token('return io, require, unknown', 'io'), 'io variable global'); + assert.equal(token('return io, require, unknown', 'require'), 'require variable global'); + assert.equal(token('return io, require, unknown', 'unknown'), 'unknown variable global'); + }); + + it('shares the globals of a .menu file across its Lua chunks', () => { + const menu = 'menu { onOpen "function Show() end" } menu { onOpen "Show()" }'; + assert.equal(token(menu, 'Show', 1, 'menu'), 'Show function global'); + }); + + it('does not classify _ENV or names resolved through a local _ENV as globals', () => { + const text = 'local x = _ENV.print local _ENV = {} y = 1 return print'; + assert.equal(token(text, '_ENV'), '_ENV variable'); + assert.equal(token(text, 'y'), 'y variable modification'); + assert.equal(token(text, 'print', 1), 'print variable'); + }); + }); + + describe('fields', () => { + it('classifies library members by their manual entry, as default library but not global', () => { + const text = 'string.format("") _G.string.rep("x", 2); ("x"):upper() return _G.print'; + assert.equal(token(text, 'format'), 'format function defaultLibrary'); + assert.equal(token(text, 'string', 1), 'string namespace defaultLibrary,global'); + assert.equal(token(text, 'rep'), 'rep function defaultLibrary'); + assert.equal(token(text, 'upper'), 'upper method defaultLibrary'); + assert.equal(token(text, 'print'), 'print function defaultLibrary,global'); + }); + + it('classifies EEex-Docs members after the operator they are used with', () => { + assert.equal(token('C:AddGold(1) return C.AddGold', 'AddGold'), 'AddGold method defaultLibrary'); + assert.equal(token('C:AddGold(1) return C.AddGold', 'AddGold', 1), 'AddGold function defaultLibrary'); + }); + + it('classifies other fields as properties and method calls as methods', () => { + const text = 'local t = {} t.x = t.y t:m()'; + assert.equal(token(text, 'x'), 'x property modification'); + assert.equal(token(text, 'y'), 'y property'); + assert.equal(token(text, 'm'), 'm method'); + }); + + it('does not describe library members the document defines itself', () => { + assert.equal(token('function string.trim() end string.trim()', 'trim', 1), 'trim property'); + assert.equal(token('string = {} string.format()', 'format'), 'format property'); + assert.equal(token('string.format = nil string.format()', 'format', 1), 'format property'); + }); + + it('classifies the names of function declarations after the first', () => { + const text = 'function a.b.c() end function a.b:m() end'; + assert.equal(token(text, 'a'), 'a variable global'); + assert.equal(token(text, 'b'), 'b property'); + assert.equal(token(text, 'c'), 'c function modification'); + assert.equal(token(text, 'm'), 'm method modification'); + }); + + it('declares the named keys of table constructors as properties', () => { + const text = 'return { x = 1, [y] = 2, 3 }'; + assert.equal(token(text, 'x'), 'x property declaration'); + assert.equal(token(text, 'y'), 'y variable global'); + }); + }); + + it('classifies labels', () => { + const text = 'goto done ::done::'; + assert.deepEqual(tokens(text), ['done label', 'done label declaration']); + }); + + it('classifies the code of a file with syntax errors as far as it was parsed', () => { + assert.deepEqual(tokens('local x = 1\nif x then = 2\nprint(x)'), ['x variable declaration', 'x variable', 'print function defaultLibrary,global', 'x variable']); + }); + + it('classifies only the Lua of a .menu file', () => { + const menu = 'menu { name "M" button { text "T" action "local n = 1" } }'; + assert.deepEqual(tokens(menu, 'menu'), ['n variable declaration']); + }); + + it('gives each name of the code exactly one single-line token, sorted, using the legend', () => { + const text = [ + 'local function f(a, ...) return a end', + 'function M.x.y:z(b) self.k = { n = b } end', + 'for i, v in pairs(_G) do ::top:: goto top end', + 'string.format("%d", #arg) ; ("s"):rep(2) C:AddGold(1)', + ].join('\n'); + const names = lex(text, 0, text.length).tokens.filter((t) => t.type === 'name'); + const classified = classifyNames(parseDocument(text, 'lua')); + assert.deepEqual( + classified.map((t) => [t.start, t.end]), + names.map((t) => [t.start, t.end]), + ); + for (const t of classified) { + assert.ok(!text.slice(t.start, t.end).includes('\n')); + assert.ok(TOKEN_TYPES.includes(t.type)); + for (const modifier of t.modifiers) assert.ok(TOKEN_MODIFIERS.includes(modifier)); + assert.equal(new Set(t.modifiers).size, t.modifiers.length, 'no duplicate modifiers'); + } + }); + + it('classifies a document version once', () => { + const document = parseDocument('local x = 1', 'lua'); + assert.equal(classifyNames(document), classifyNames(document)); + }); +});