diff --git a/CHANGELOG.md b/CHANGELOG.md index eea2fc0..4fd49ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -156,6 +156,32 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). - Every result is lexed again and must have the same tokens and comments, or nothing changes. - Registered dynamically for Lua documents only (language `lua`, or `*.lua` in any letter case) when the client supports it, so `.menu` files have no formatter; static otherwise. +- Quick fixes (`textDocument/codeAction`) for three `.menu` diagnostics, with the remedy + [IESDP](https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm) states: + - `menu-unquoted-underscore`: *Enclose in quotes* (`My_Menu` → `"My_Menu"`; "Always quote + names"). A run without a letter (`10_0`) gets no fix: it is not a name, and quoting would + make a number a string. + - `menu-word-too-long`: *Enclose in quotes* ("Quoted strings are not limited"); the whole run + when the word is joined to `_`. + - `menu-inline-lua-last-character`: *Insert a space before the closing backtick* ("end every + inline block with a line break or a space"), so the engine drops the space instead of code. + - Each fix is preferred (`isPreferred`) and linked to its diagnostic; when the file has several + problems of the code, *Fix all `` problems* fixes them together. + - `source.fixAll.ieLua` applies every fix of the file, also from `editor.codeActionsOnSave` + (`{ "source.fixAll.ieLua": "explicit" }`) and whether or not diagnostics were published + (`ieLua.validate.mode` `manual`). The kind is stable: settings refer to it. + - No fix for `lua-syntax`, `menu-unterminated-string` or `menu-unterminated-block`: where the + text should end, or how to repair the Lua, would be a guess. + - The current text is analyzed again for every request: a diagnostic from an older version of + the file (published on save, before later edits) gets no fix rather than an edit in the wrong + place. Every set of edits is checked by lexing the result: the remaining problems must be + exactly those no fix touches, or nothing is offered (and an error is logged). + - The fixes change the Lua the engine compiles, as intended: the character it dropped before + the backtick now runs, and a quoted property value is compiled whole (`enabled "My_Var"` is + `My_Var`, not `My`). The Lua is validated as usual afterwards; it may report an error the + dropped or split text hid. + - Titles are localized like the hover labels. Advertised only to clients that accept + `CodeAction` literals (`codeActionLiteralSupport`). - 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 a19961c..bc7e914 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, semantic tokens, formatting of `.lua` files, 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, formatting of `.lua` files, `.menu` quick fixes, 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) | @@ -35,6 +35,7 @@ │ │ ├── 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) +│ │ ├── codeActions/ # Quick fixes for .menu diagnostics (pure, no LSP imports) │ │ ├── formatting/ # Layout-preserving Lua formatting edits (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) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index de7b3bd..ef3b336 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,7 @@ server (port 6009). | `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/codeActions/` | Quick fixes for `.menu` diagnostics (pure; every set of edits re-lexed and checked) | | `src/server/formatting/` | Layout-preserving formatting edits for Lua (pure; every result re-lexed and checked) | | `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) | diff --git a/README.md b/README.md index dd24993..41eaf41 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,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**, **semantic highlighting**, **formatting** (Lua files), **document symbols**, -> **workspace symbols**, **folding**, and **go to definition**, **find references** and **rename** -> within a file; cross-file navigation, formatting of `.menu` files and more are planned. +> **workspace symbols**, **folding**, **quick fixes** (`.menu` files), and **go to definition**, +> **find references** and **rename** within a file; cross-file navigation, formatting of `.menu` +> files and more are planned. ## Features @@ -70,6 +71,11 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the 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, a reserved word, or a global that is defined outside the file. +- **Quick fixes for `.menu` text the game misreads.** Put an unquoted name such as `My_Menu`, or + a word too long for the game, in quotes, or add the space the game needs before the closing + backtick of a Lua block, from the light bulb (Ctrl+.). *Fix all IE Lua auto-fixable problems* + fixes the whole file; to do it on every save, add + `"editor.codeActionsOnSave": { "source.fixAll.ieLua": "explicit" }` to your settings. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors** through the Language Server Protocol. diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index da199ec..979a7ff 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -52,6 +52,11 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea editor's tab and indentation settings, and with *Editor: Format On Type* it re-indents `end`, `else` and closing brackets as you type them. Files with syntax errors are left as they are; `.menu` files are not formatted yet. +- **Quick fixes for `.menu` text the game misreads.** Click the light bulb (or press Ctrl+.) + on a warning to put an unquoted name such as `My_Menu` or a too-long word in quotes, or to add + the space the game needs before the closing backtick of a Lua block. Fix them all at once with + *Fix all IE Lua auto-fixable problems*, or on every save with + `"editor.codeActionsOnSave": { "source.fixAll.ieLua": "explicit" }`. - **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 c9072fd..40de30a 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -72,6 +72,7 @@ node /path/to/server.js --stdio | 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. | | Formatting | `textDocument/formatting`, `/rangeFormatting`, `/onTypeFormatting` | `.lua` files only. Keeps your line breaks; uses the editor's tab size and spaces/tabs option. See below. | +| Quick fixes | `textDocument/codeAction` | `.menu` files only: kinds `quickfix` and `source.fixAll.ieLua`. Needs `codeActionLiteralSupport`. 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; @@ -117,6 +118,17 @@ turned on; see its documentation). When the editor supports dynamic registration offered for Lua documents only (language `lua`, or `*.lua` in any letter case), so `.menu` files have no formatter; other editors get no edits for `.menu` files. -Symbols, folding, hover, completion, semantic tokens, formatting and navigation always reflect the current text, whatever `validate.mode` is. +Quick fixes cover three `.menu` diagnostics, with the remedy IESDP gives: +`menu-unquoted-underscore` and `menu-word-too-long` put the text in `"…"`, and +`menu-inline-lua-last-character` inserts a space before the closing backtick. The action is +offered for a diagnostic only while its problem is still at the same place in the current text. +A fix changes the Lua the game compiles, as intended: the character it dropped before the +backtick now runs, and a quoted Lua property value is compiled whole, so validation may then +report an error the misread text hid. +The `source.fixAll.ieLua` action applies every fix of the file, whether or not diagnostics were +published; ask for that kind (or `source.fixAll`) to run it on save, if your editor can request +code actions on save. Action titles follow the editor's `locale`, like hover. + +Symbols, folding, hover, completion, semantic tokens, formatting, quick fixes 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/l10n/server/messages.cs.json b/l10n/server/messages.cs.json index fef2b14..2ba80c4 100644 --- a/l10n/server/messages.cs.json +++ b/l10n/server/messages.cs.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "parametr", "hover.kind.forVariable": "proměnná for", "hover.kind.global": "globální", - "hover.engineReplaced": "Herní engine nahrazuje {0} vlastní funkcí, takže popis v příručce Lua 5.2 neplatí. Viz {1}." + "hover.engineReplaced": "Herní engine nahrazuje {0} vlastní funkcí, takže popis v příručce Lua 5.2 neplatí. Viz {1}.", + "codeAction.quote": "Uzavřít do uvozovek", + "codeAction.insertSpace": "Vložit mezeru před uzavírací zpětný apostrof", + "codeAction.fixAllOfCode": "Opravit všechny problémy {0}", + "codeAction.fixAll": "Opravit všechny automaticky opravitelné problémy IE Lua" } diff --git a/l10n/server/messages.de.json b/l10n/server/messages.de.json index b9d35a2..8ecbd58 100644 --- a/l10n/server/messages.de.json +++ b/l10n/server/messages.de.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "Parameter", "hover.kind.forVariable": "for-Variable", "hover.kind.global": "global", - "hover.engineReplaced": "Die Spiel-Engine ersetzt {0} durch eine eigene Funktion, daher gilt die Beschreibung im Lua 5.2-Handbuch nicht. Siehe {1}." + "hover.engineReplaced": "Die Spiel-Engine ersetzt {0} durch eine eigene Funktion, daher gilt die Beschreibung im Lua 5.2-Handbuch nicht. Siehe {1}.", + "codeAction.quote": "In Anführungszeichen setzen", + "codeAction.insertSpace": "Leerzeichen vor dem schließenden Backtick einfügen", + "codeAction.fixAllOfCode": "Alle {0}-Probleme beheben", + "codeAction.fixAll": "Alle automatisch behebbaren IE Lua-Probleme beheben" } diff --git a/l10n/server/messages.es.json b/l10n/server/messages.es.json index bdf6523..7cda641 100644 --- a/l10n/server/messages.es.json +++ b/l10n/server/messages.es.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "parámetro", "hover.kind.forVariable": "variable for", "hover.kind.global": "global", - "hover.engineReplaced": "El motor del juego reemplaza {0} por una función propia, por lo que la descripción del manual de Lua 5.2 no se aplica. Consulte {1}." + "hover.engineReplaced": "El motor del juego reemplaza {0} por una función propia, por lo que la descripción del manual de Lua 5.2 no se aplica. Consulte {1}.", + "codeAction.quote": "Encerrar entre comillas", + "codeAction.insertSpace": "Insertar un espacio antes de la comilla invertida de cierre", + "codeAction.fixAllOfCode": "Corregir todos los problemas {0}", + "codeAction.fixAll": "Corregir todos los problemas de IE Lua que se pueden corregir automáticamente" } diff --git a/l10n/server/messages.fr.json b/l10n/server/messages.fr.json index 6eacce5..170bc82 100644 --- a/l10n/server/messages.fr.json +++ b/l10n/server/messages.fr.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "paramètre", "hover.kind.forVariable": "variable for", "hover.kind.global": "globale", - "hover.engineReplaced": "Le moteur du jeu remplace {0} par sa propre fonction : la description du manuel Lua 5.2 ne s'applique donc pas. Voir {1}." + "hover.engineReplaced": "Le moteur du jeu remplace {0} par sa propre fonction : la description du manuel Lua 5.2 ne s'applique donc pas. Voir {1}.", + "codeAction.quote": "Mettre entre guillemets", + "codeAction.insertSpace": "Insérer un espace avant l'accent grave fermant", + "codeAction.fixAllOfCode": "Corriger tous les problèmes {0}", + "codeAction.fixAll": "Corriger tous les problèmes IE Lua corrigibles automatiquement" } diff --git a/l10n/server/messages.hu.json b/l10n/server/messages.hu.json index 474e42c..ee10b79 100644 --- a/l10n/server/messages.hu.json +++ b/l10n/server/messages.hu.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "paraméter", "hover.kind.forVariable": "for-változó", "hover.kind.global": "globális", - "hover.engineReplaced": "A játékmotor saját függvényre cseréli a(z) {0} függvényt, ezért a Lua 5.2 kézikönyv leírása nem érvényes. Lásd: {1}." + "hover.engineReplaced": "A játékmotor saját függvényre cseréli a(z) {0} függvényt, ezért a Lua 5.2 kézikönyv leírása nem érvényes. Lásd: {1}.", + "codeAction.quote": "Idézőjelek közé tétel", + "codeAction.insertSpace": "Szóköz beszúrása a záró fordított aposztróf elé", + "codeAction.fixAllOfCode": "Az összes {0} probléma javítása", + "codeAction.fixAll": "Az összes automatikusan javítható IE Lua-probléma javítása" } diff --git a/l10n/server/messages.it.json b/l10n/server/messages.it.json index 18cd307..123246c 100644 --- a/l10n/server/messages.it.json +++ b/l10n/server/messages.it.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "parametro", "hover.kind.forVariable": "variabile for", "hover.kind.global": "globale", - "hover.engineReplaced": "Il motore di gioco sostituisce {0} con una propria funzione, quindi la descrizione del manuale di Lua 5.2 non si applica. Vedere {1}." + "hover.engineReplaced": "Il motore di gioco sostituisce {0} con una propria funzione, quindi la descrizione del manuale di Lua 5.2 non si applica. Vedere {1}.", + "codeAction.quote": "Racchiudi tra virgolette", + "codeAction.insertSpace": "Inserisci uno spazio prima dell'apice inverso di chiusura", + "codeAction.fixAllOfCode": "Correggi tutti i problemi {0}", + "codeAction.fixAll": "Correggi tutti i problemi di IE Lua correggibili automaticamente" } diff --git a/l10n/server/messages.ja.json b/l10n/server/messages.ja.json index b248938..4d21e0e 100644 --- a/l10n/server/messages.ja.json +++ b/l10n/server/messages.ja.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "パラメーター", "hover.kind.forVariable": "for 変数", "hover.kind.global": "グローバル", - "hover.engineReplaced": "ゲーム エンジンは {0} を独自の関数に置き換えるため、Lua 5.2 マニュアルの説明は当てはまりません。{1} を参照してください。" + "hover.engineReplaced": "ゲーム エンジンは {0} を独自の関数に置き換えるため、Lua 5.2 マニュアルの説明は当てはまりません。{1} を参照してください。", + "codeAction.quote": "引用符で囲む", + "codeAction.insertSpace": "閉じるバッククォートの前にスペースを挿入する", + "codeAction.fixAllOfCode": "すべての {0} の問題を修正する", + "codeAction.fixAll": "自動修正可能な IE Lua の問題をすべて修正する" } diff --git a/l10n/server/messages.json b/l10n/server/messages.json index ff04bbc..5a98f09 100644 --- a/l10n/server/messages.json +++ b/l10n/server/messages.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "parameter", "hover.kind.forVariable": "for variable", "hover.kind.global": "global", - "hover.engineReplaced": "The game engine replaces {0} with its own function, so the description in the Lua 5.2 manual does not apply. See {1}." + "hover.engineReplaced": "The game engine replaces {0} with its own function, so the description in the Lua 5.2 manual does not apply. See {1}.", + "codeAction.quote": "Enclose in quotes", + "codeAction.insertSpace": "Insert a space before the closing backtick", + "codeAction.fixAllOfCode": "Fix all {0} problems", + "codeAction.fixAll": "Fix all IE Lua auto-fixable problems" } diff --git a/l10n/server/messages.ko.json b/l10n/server/messages.ko.json index 83b0160..4f6ff2a 100644 --- a/l10n/server/messages.ko.json +++ b/l10n/server/messages.ko.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "매개 변수", "hover.kind.forVariable": "for 변수", "hover.kind.global": "전역", - "hover.engineReplaced": "게임 엔진이 {0}을(를) 자체 함수로 대체하므로 Lua 5.2 설명서의 설명은 적용되지 않습니다. {1}을(를) 참조하세요." + "hover.engineReplaced": "게임 엔진이 {0}을(를) 자체 함수로 대체하므로 Lua 5.2 설명서의 설명은 적용되지 않습니다. {1}을(를) 참조하세요.", + "codeAction.quote": "따옴표로 묶기", + "codeAction.insertSpace": "닫는 백틱 앞에 공백 삽입", + "codeAction.fixAllOfCode": "모든 {0} 문제 해결", + "codeAction.fixAll": "자동 수정 가능한 모든 IE Lua 문제 해결" } diff --git a/l10n/server/messages.pl.json b/l10n/server/messages.pl.json index 2510399..4ea55c3 100644 --- a/l10n/server/messages.pl.json +++ b/l10n/server/messages.pl.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "parametr", "hover.kind.forVariable": "zmienna for", "hover.kind.global": "globalna", - "hover.engineReplaced": "Silnik gry zastępuje {0} własną funkcją, więc opis z podręcznika Lua 5.2 nie ma zastosowania. Zobacz {1}." + "hover.engineReplaced": "Silnik gry zastępuje {0} własną funkcją, więc opis z podręcznika Lua 5.2 nie ma zastosowania. Zobacz {1}.", + "codeAction.quote": "Ujmij w cudzysłów", + "codeAction.insertSpace": "Wstaw spację przed zamykającym grawisem", + "codeAction.fixAllOfCode": "Napraw wszystkie problemy {0}", + "codeAction.fixAll": "Napraw wszystkie automatycznie naprawialne problemy IE Lua" } diff --git a/l10n/server/messages.pt-br.json b/l10n/server/messages.pt-br.json index c8d52c0..35c7c9e 100644 --- a/l10n/server/messages.pt-br.json +++ b/l10n/server/messages.pt-br.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "parâmetro", "hover.kind.forVariable": "variável for", "hover.kind.global": "global", - "hover.engineReplaced": "O mecanismo do jogo substitui {0} por uma função própria, portanto a descrição do manual do Lua 5.2 não se aplica. Consulte {1}." + "hover.engineReplaced": "O mecanismo do jogo substitui {0} por uma função própria, portanto a descrição do manual do Lua 5.2 não se aplica. Consulte {1}.", + "codeAction.quote": "Colocar entre aspas", + "codeAction.insertSpace": "Inserir um espaço antes do acento grave de fechamento", + "codeAction.fixAllOfCode": "Corrigir todos os problemas {0}", + "codeAction.fixAll": "Corrigir todos os problemas do IE Lua que podem ser corrigidos automaticamente" } diff --git a/l10n/server/messages.ru.json b/l10n/server/messages.ru.json index 29538c3..0cebda9 100644 --- a/l10n/server/messages.ru.json +++ b/l10n/server/messages.ru.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "параметр", "hover.kind.forVariable": "переменная for", "hover.kind.global": "глобальная", - "hover.engineReplaced": "Игровой движок заменяет {0} собственной функцией, поэтому описание из руководства по Lua 5.2 не применимо. См. {1}." + "hover.engineReplaced": "Игровой движок заменяет {0} собственной функцией, поэтому описание из руководства по Lua 5.2 не применимо. См. {1}.", + "codeAction.quote": "Заключить в кавычки", + "codeAction.insertSpace": "Вставить пробел перед закрывающим обратным апострофом", + "codeAction.fixAllOfCode": "Исправить все проблемы {0}", + "codeAction.fixAll": "Исправить все автоматически исправляемые проблемы IE Lua" } diff --git a/l10n/server/messages.tr.json b/l10n/server/messages.tr.json index 7c0f086..d0dc043 100644 --- a/l10n/server/messages.tr.json +++ b/l10n/server/messages.tr.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "parametre", "hover.kind.forVariable": "for değişkeni", "hover.kind.global": "global", - "hover.engineReplaced": "Oyun motoru {0} işlevini kendi işleviyle değiştirir; bu nedenle Lua 5.2 kılavuzundaki açıklama geçerli değildir. Bkz. {1}." + "hover.engineReplaced": "Oyun motoru {0} işlevini kendi işleviyle değiştirir; bu nedenle Lua 5.2 kılavuzundaki açıklama geçerli değildir. Bkz. {1}.", + "codeAction.quote": "Tırnak içine al", + "codeAction.insertSpace": "Kapanış ters tırnağından önce boşluk ekle", + "codeAction.fixAllOfCode": "Tüm {0} sorunlarını düzelt", + "codeAction.fixAll": "Otomatik olarak düzeltilebilen tüm IE Lua sorunlarını düzelt" } diff --git a/l10n/server/messages.zh-cn.json b/l10n/server/messages.zh-cn.json index 225af1c..090ca3f 100644 --- a/l10n/server/messages.zh-cn.json +++ b/l10n/server/messages.zh-cn.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "参数", "hover.kind.forVariable": "for 变量", "hover.kind.global": "全局", - "hover.engineReplaced": "游戏引擎将 {0} 替换为自己的函数,因此 Lua 5.2 手册中的说明不适用。请参阅 {1}。" + "hover.engineReplaced": "游戏引擎将 {0} 替换为自己的函数,因此 Lua 5.2 手册中的说明不适用。请参阅 {1}。", + "codeAction.quote": "用引号括起来", + "codeAction.insertSpace": "在右反引号前插入空格", + "codeAction.fixAllOfCode": "修复所有 {0} 问题", + "codeAction.fixAll": "修复所有可自动修复的 IE Lua 问题" } diff --git a/l10n/server/messages.zh-tw.json b/l10n/server/messages.zh-tw.json index 3c183af..7d99504 100644 --- a/l10n/server/messages.zh-tw.json +++ b/l10n/server/messages.zh-tw.json @@ -2,5 +2,9 @@ "hover.kind.parameter": "參數", "hover.kind.forVariable": "for 變數", "hover.kind.global": "全域", - "hover.engineReplaced": "遊戲引擎會以自己的函式取代 {0},因此 Lua 5.2 手冊中的說明不適用。請參閱 {1}。" + "hover.engineReplaced": "遊戲引擎會以自己的函式取代 {0},因此 Lua 5.2 手冊中的說明不適用。請參閱 {1}。", + "codeAction.quote": "以引號括住", + "codeAction.insertSpace": "在右反引號前插入空格", + "codeAction.fixAllOfCode": "修正所有 {0} 問題", + "codeAction.fixAll": "修正所有可自動修正的 IE Lua 問題" } diff --git a/src/server/codeActions/quickFixes.ts b/src/server/codeActions/quickFixes.ts new file mode 100644 index 0000000..8ad31d5 --- /dev/null +++ b/src/server/codeActions/quickFixes.ts @@ -0,0 +1,190 @@ +// Quick fixes for text the engine misreads in .menu files. Pure: no LSP or +// `vscode` imports. +// +// Only fixes whose remedy IESDP states are offered ("MENU file format", +// https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm): +// +// | Code | IESDP | Fix | +// | -------------------------------- | ------------------------------------------------------------------------- | ----------------------------------- | +// | `menu-unquoted-underscore` | "Underscores are not part of a word … Always quote names." | `"…"` around the run | +// | `menu-word-too-long` | "A longer unquoted word aborts the game. Quoted strings are not limited." | `"…"` around the word | +// | `menu-inline-lua-last-character` | "end every inline block with a line break or a space" | a space before the closing backtick | +// +// The fixes change the Lua the engine compiles, as intended: the character it +// dropped before a backtick now runs, and a quoted property value is compiled +// whole (`enabled "My_Var"` is `My_Var`, not `My`). The safety check covers the +// .menu lexing only; the Lua is validated as usual. +// +// The other codes have no single correct fix: where an unterminated string or +// block should end, or how to repair a Lua syntax error, would be a guess. +// +// Every set of edits is checked before it is offered (`applyChecked`): the edited +// text is lexed again, and its problems must be exactly the problems the edits do +// not touch. + +import { lexMenu } from '../validation/menuLexer.ts'; +import { DiagnosticCode, type Problem } from '../validation/types.ts'; + +/** The diagnostic codes that have a quick fix. */ +export const FIXABLE_CODES = [ + DiagnosticCode.MenuUnquotedUnderscore, + DiagnosticCode.MenuWordTooLong, + DiagnosticCode.MenuInlineLuaLastCharacter, +] as const; +export type FixableCode = (typeof FIXABLE_CODES)[number]; + +export function isFixableCode(code: unknown): code is FixableCode { + return (FIXABLE_CODES as readonly unknown[]).includes(code); +} + +/** A replacement of the half-open range `[start, end)` of the text by `newText`. */ +export interface TextChange { + readonly start: number; + readonly end: number; + readonly newText: string; +} + +/** What a fix does, for its title. */ +export type FixAction = 'quote' | 'insertSpace'; + +/** The fix of one problem. */ +export interface MenuFix { + /** The problem it fixes, with the range its diagnostic has. */ + readonly problem: Problem & { readonly code: FixableCode }; + readonly action: FixAction; + readonly change: TextChange; +} + +/** The problems of a .menu text, as `lexMenu` reports them, and the fixes of those that have one. */ +export interface MenuFixAnalysis { + readonly problems: readonly Problem[]; + readonly fixes: readonly MenuFix[]; +} + +const LETTER = /[A-Za-z]/; + +function quote(text: string, start: number, end: number): TextChange { + // A run of letters, digits and `_` never contains a quote, so `"…"` holds it as is. + return { start, end, newText: `"${text.slice(start, end)}"` }; +} + +function contains(outer: Problem, inner: Problem): boolean { + return outer.start <= inner.start && inner.end <= outer.end; +} + +/** + * The problems `lexMenu` reports for `text` (the same ones the diagnostics + * publish, at the same offsets) and a fix for each one that has one: + * + * - `menu-unquoted-underscore`: the run in `"…"`, when it has a letter. A run of + * digits and `_` (`10_0`) is not a name and gets no fix: quoting would make a + * number a string, and what was meant (`100`, `10 0`) is unknown. + * - `menu-word-too-long`: the word in `"…"`; when the word is part of a run + * with `_`, the whole run, since quoting the word alone would leave the rest + * of the run misread. + * - `menu-inline-lua-last-character`: a space inserted before the closing + * backtick, so the engine drops the space instead of code. + */ +export function analyzeMenu(text: string): MenuFixAnalysis { + const { problems } = lexMenu(text); + const runs = problems.filter((problem) => problem.code === DiagnosticCode.MenuUnquotedUnderscore); + const fixes: MenuFix[] = []; + for (const problem of problems) { + switch (problem.code) { + case DiagnosticCode.MenuUnquotedUnderscore: + if (LETTER.test(text.slice(problem.start, problem.end))) { + fixes.push({ problem: { ...problem, code: problem.code }, action: 'quote', change: quote(text, problem.start, problem.end) }); + } + break; + case DiagnosticCode.MenuWordTooLong: { + const run = runs.find((candidate) => contains(candidate, problem)) ?? problem; + fixes.push({ problem: { ...problem, code: problem.code }, action: 'quote', change: quote(text, run.start, run.end) }); + break; + } + case DiagnosticCode.MenuInlineLuaLastCharacter: + // The problem is the character before the closing backtick, which is at `end`. + fixes.push({ problem: { ...problem, code: problem.code }, action: 'insertSpace', change: { start: problem.end, end: problem.end, newText: ' ' } }); + break; + default: + break; + } + } + return { problems, fixes }; +} + +/** The part of the text a fix depends on: its problem and the range it changes. */ +function span(fix: MenuFix): { start: number; end: number } { + return { start: Math.min(fix.problem.start, fix.change.start), end: Math.max(fix.problem.end, fix.change.end) }; +} + +function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean { + return a.start < b.end && b.start < a.end; +} + +/** + * The changes of several fixes as one set: in document order, each distinct + * change once (a long word in a run with `_` has the run's change), and a change + * that overlaps one already kept is dropped, the wider one kept first. + */ +export function combineChanges(fixes: readonly MenuFix[]): TextChange[] { + const ordered = [...fixes] + .map((fix) => fix.change) + .sort((a, b) => a.start - b.start || b.end - a.end); + const kept: TextChange[] = []; + for (const change of ordered) { + const last = kept.at(-1); + if (last && last.start === change.start && last.end === change.end && last.newText === change.newText) continue; + // Insertions (empty ranges) conflict with a change that covers their position. + const reach = { start: change.start, end: Math.max(change.end, change.start + 1) }; + if (kept.some((other) => overlaps({ start: other.start, end: Math.max(other.end, other.start + 1) }, reach))) continue; + kept.push(change); + } + return kept; +} + +/** `text` with `changes` (in document order, not overlapping) applied. */ +export function applyChanges(text: string, changes: readonly TextChange[]): string { + let result = ''; + let at = 0; + for (const change of changes) { + result += text.slice(at, change.start) + change.newText; + at = change.end; + } + return result + text.slice(at); +} + +/** Where `offset` of the original text is after `changes`, for an offset outside every changed range. */ +function shifted(offset: number, changes: readonly TextChange[]): number { + let delta = 0; + for (const change of changes) { + if (change.end <= offset) delta += change.newText.length - (change.end - change.start); + } + return offset + delta; +} + +function sameProblem(a: Problem, b: Problem): boolean { + return a.start === b.start && a.end === b.end && a.code === b.code && a.message === b.message && a.severity === b.severity; +} + +/** + * The changes of `fixes` (`combineChanges`), when they are safe: the edited text + * must have exactly the problems of the original that no fix touches (its + * problem and changed range), at their shifted offsets. `undefined` otherwise, + * or when there is nothing to change. + */ +export function applyChecked(text: string, analysis: MenuFixAnalysis, fixes: readonly MenuFix[]): TextChange[] | undefined { + const changes = combineChanges(fixes); + if (changes.length === 0) return undefined; + // A fix whose change was dropped for an overlap is only fixed if a kept change covers its problem. + const applied = fixes.filter((fix) => changes.some((change) => change.start === fix.change.start && change.end === fix.change.end && change.newText === fix.change.newText)); + const touched = [...applied.map(span), ...changes.map((change) => ({ start: change.start, end: Math.max(change.end, change.start + 1) }))]; + const expected = analysis.problems + .filter((problem) => !touched.some((range) => overlaps(range, { start: problem.start, end: Math.max(problem.end, problem.start + 1) }))) + .map((problem) => ({ ...problem, start: shifted(problem.start, changes), end: shifted(problem.end, changes) })); + const actual = lexMenu(applyChanges(text, changes)).problems; + const same = actual.length === expected.length && actual.every((problem, index) => { + const wanted = expected[index]; + return wanted !== undefined && sameProblem(problem, wanted); + }); + return same ? changes : undefined; +} diff --git a/src/server/features/codeActions.ts b/src/server/features/codeActions.ts new file mode 100644 index 0000000..07138a7 --- /dev/null +++ b/src/server/features/codeActions.ts @@ -0,0 +1,206 @@ +import type { CodeAction, CodeActionClientCapabilities, CodeActionParams, Connection, Diagnostic, Range, TextDocuments } from 'vscode-languageserver/node'; +import { CodeActionKind } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import { DIAGNOSTIC_SOURCE, FIX_ALL_KIND } from '../../shared/protocol.ts'; +import { analyzeMenu, applyChecked, isFixableCode, type FixAction, type MenuFix, type MenuFixAnalysis, type TextChange } from '../codeActions/quickFixes.ts'; +import type { Messages } from '../l10n.ts'; +import { documentKind } from '../validation/validateText.ts'; +import { toWorkspaceEdit } from './rename.ts'; + +export interface CodeActionDeps { + readonly messages: Messages; + /** `workspace.workspaceEdit.documentChanges` of the client: send versioned edits. */ + readonly documentChanges: boolean; +} + +/** The kinds this server returns, as advertised in `codeActionProvider.codeActionKinds`. */ +export const CODE_ACTION_KINDS = [CodeActionKind.QuickFix, FIX_ALL_KIND] as const; + +/** + * Whether the client accepts `CodeAction` literals. Without them a server can + * only return `Command`s, which this server does not implement, so the + * capability is not advertised. + */ +export function supportsCodeActionLiterals(literalSupport: CodeActionClientCapabilities['codeActionLiteralSupport']): boolean { + return literalSupport !== undefined; +} + +/** + * Whether actions of `kind` are wanted. LSP: `only` filters by kind, and a + * requested kind includes its sub-kinds (`source` includes `source.fixAll.ieLua`). + * Without `only`, quick fixes are returned and source actions are not: clients + * ask for source actions by kind (`editor.codeActionsOnSave`, *Source Action…*). + */ +export function wanted(kind: string, only: readonly string[] | undefined): boolean { + if (only === undefined) return kind === CodeActionKind.QuickFix; + return only.some((requested) => kind === requested || kind.startsWith(`${requested}.`)); +} + +const TITLE_KEYS: Readonly> = { + quote: 'codeAction.quote', + insertSpace: 'codeAction.insertSpace', +}; + +/** + * Resolves `true` when the request should stop. Called between the diagnostics + * of a request, each of which lexes the document again for its safety check. + */ +export type Pause = () => Promise; + +/** + * The code actions for a .menu document (none for Lua files, which have no + * fixable diagnostics), or a reason they were refused, for the log. + * + * - A quick fix for each diagnostic of `context.diagnostics` from this server + * whose code has a fix and whose problem is still in the current text, at + * exactly that range: a diagnostic of an older version (published on save, + * before later edits) gets none rather than an edit at the wrong place. + * - With it, when the current text has more than one problem of that code, a + * quick fix for all of them. + * - `source.fixAll.ieLua`: every fixable problem of the current text, whether + * or not its diagnostics were published (`ieLua.validate.mode` `manual`). + * + * Every set of changes passes the safety check of `applyChecked` first, which + * lexes the edited document: `pause` is awaited before each further diagnostic, + * so that a request for a selection with many diagnostics can be cancelled. + * `undefined` when `pause` stopped the request. + */ +export async function codeActions( + document: TextDocument, + params: Pick, + deps: CodeActionDeps, + pause: Pause = () => Promise.resolve(false), +): Promise<{ actions: CodeAction[]; refused: string[] } | undefined> { + const actions: CodeAction[] = []; + const refused: string[] = []; + if (documentKind(document.uri, document.languageId) !== 'menu') return { actions, refused }; + const { only } = params.context; + const quickFixes = wanted(CodeActionKind.QuickFix, only); + const fixAll = wanted(FIX_ALL_KIND, only); + if (!quickFixes && !fixAll) return { actions, refused }; + + const text = document.getText(); + const analysis: MenuFixAnalysis = analyzeMenu(text); + const rangeOf = (start: number, end: number): Range => ({ start: document.positionAt(start), end: document.positionAt(end) }); + const edit = (changes: TextChange[]) => + toWorkspaceEdit( + document, + changes.map(({ start, end, newText }) => ({ range: rangeOf(start, end), newText })), + deps.documentChanges, + ); + const checked = (fixes: readonly MenuFix[], what: string): TextChange[] | undefined => { + const changes = applyChecked(text, analysis, fixes); + if (!changes) refused.push(what); + return changes; + }; + + if (quickFixes) { + /** The fixes by code and problem offsets, the identity of a diagnostic. */ + const byProblem = new Map(analysis.fixes.map((fix) => [problemKey(fix.problem.code, fix.problem.start, fix.problem.end), fix])); + /** The fixes of each code, for its "fix all" action. */ + const byCode = new Map(); + for (const fix of analysis.fixes) { + const group = byCode.get(fix.problem.code); + if (group) group.push(fix); + else byCode.set(fix.problem.code, [fix]); + } + /** Codes whose "fix all" action was already added. */ + const allOffered = new Set(); + let first = true; + for (const diagnostic of params.context.diagnostics) { + if (diagnostic.source !== DIAGNOSTIC_SOURCE || !isFixableCode(diagnostic.code)) continue; + const fix = byProblem.get(problemKey(diagnostic.code, ...offsetsOf(document, diagnostic.range))); + if (!fix) continue; + if (!first && (await pause())) return undefined; + first = false; + const changes = checked([fix], `the ${fix.problem.code} fix at offset ${String(fix.problem.start)}`); + if (changes) { + actions.push({ + title: deps.messages.t(TITLE_KEYS[fix.action]), + kind: CodeActionKind.QuickFix, + diagnostics: [diagnostic], + isPreferred: true, + edit: edit(changes), + }); + } + const sameCode = byCode.get(fix.problem.code) ?? []; + if (sameCode.length > 1 && !allOffered.has(fix.problem.code)) { + allOffered.add(fix.problem.code); + const all = checked(sameCode, `the fixes of every ${fix.problem.code} problem`); + if (all) { + const diagnostics: Diagnostic[] = params.context.diagnostics.filter( + (other) => other.source === DIAGNOSTIC_SOURCE && other.code === fix.problem.code, + ); + actions.push({ + title: deps.messages.t('codeAction.fixAllOfCode', fix.problem.code), + kind: CodeActionKind.QuickFix, + diagnostics, + edit: edit(all), + }); + } + } + } + } + + if (fixAll && analysis.fixes.length > 0) { + const changes = checked(analysis.fixes, 'the fixes of every fixable problem'); + if (changes) { + actions.push({ title: deps.messages.t('codeAction.fixAll'), kind: FIX_ALL_KIND, edit: edit(changes) }); + } + } + return { actions, refused }; +} + +function problemKey(code: string, start: number, end: number): string { + return `${code}:${String(start)}:${String(end)}`; +} + +/** + * The offsets of a diagnostic's range, or `[-1, -1]` (matching no problem) when + * the range is not a range of the current text, such as positions past the end + * of a line, which `offsetAt` would clamp. + */ +function offsetsOf(document: TextDocument, range: Range): [number, number] { + const start = document.offsetAt(range.start); + const end = document.offsetAt(range.end); + const exact = (offset: number, position: Range['start']) => { + const back = document.positionAt(offset); + return back.line === position.line && back.character === position.character; + }; + return exact(start, range.start) && exact(end, range.end) ? [start, end] : [-1, -1]; +} + +/** `textDocument/codeAction` (see `codeActions`). */ +export function register(connection: Connection, documents: TextDocuments, deps: CodeActionDeps): void { + connection.onCodeAction(async (params, token): Promise => { + try { + const document = documents.get(params.textDocument.uri); + if (!document || token.isCancellationRequested) { + return null; + } + // Between diagnostics, let the cancellation (and edits) arrive. `TextDocuments` + // updates a document in place, so an edit meanwhile shows as a new version, and + // the actions computed for the old text are dropped. + const { version } = document; + const stale = (): boolean => token.isCancellationRequested || documents.get(document.uri)?.version !== version; + const pause: Pause = () => + new Promise((resolve) => { + setImmediate(() => { + resolve(stale()); + }); + }); + const result = await codeActions(document, params, deps, pause); + if (!result || stale()) { + return null; + } + const { actions, refused } = result; + for (const what of refused) { + connection.console.error(`Code actions for ${params.textDocument.uri}: ${what} would change problems it does not fix; not offered.`); + } + return actions; + } catch (error) { + connection.console.error(`Code actions for ${params.textDocument.uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }); +} diff --git a/src/server/server.ts b/src/server/server.ts index d7cd6c6..c1e7b13 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -15,6 +15,7 @@ import { } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { ParsedDocumentCache } from './documentCache.ts'; +import * as codeActions from './features/codeActions.ts'; import * as completion from './features/completion.ts'; import * as definition from './features/definition.ts'; import * as diagnostics from './features/diagnostics.ts'; @@ -105,7 +106,12 @@ connection.onInitialize((params) => { }); definition.register(connection, documents, { cache: parsed }); references.register(connection, documents, { cache: parsed }); - rename.register(connection, documents, { cache: parsed, documentChanges: workspace?.workspaceEdit?.documentChanges === true }); + const documentChanges = workspace?.workspaceEdit?.documentChanges === true; + rename.register(connection, documents, { cache: parsed, documentChanges }); + const codeActionLiterals = codeActions.supportsCodeActionLiterals(params.capabilities.textDocument?.codeAction?.codeActionLiteralSupport); + if (codeActionLiterals) { + codeActions.register(connection, documents, { messages, documentChanges }); + } workspaceSymbols.register(connection, documents, { cache: parsed, index }); semanticTokens.register(connection, documents, { cache: parsed }); formatting.register(connection, documents, { cache: parsed }); @@ -145,6 +151,7 @@ connection.onInitialize((params) => { workspaceSymbolProvider: true, hoverProvider: true, completionProvider: { triggerCharacters: [...completion.TRIGGER_CHARACTERS], resolveProvider: true }, + ...(codeActionLiterals ? { codeActionProvider: { codeActionKinds: [...codeActions.CODE_ACTION_KINDS] } } : {}), semanticTokensProvider: { legend: semanticTokens.LEGEND, full: { delta: true }, range: true }, ...formatting.staticCapabilities(formattingRegistration), ...(workspaceFolderChanges ? { workspace: { workspaceFolders: { supported: true, changeNotifications: true } } } : {}), diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index 7ba280d..9485937 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -11,6 +11,13 @@ export const DOCUMENT_SCHEMES = ['file', 'untitled'] as const; /** Value of `Diagnostic.source` for every diagnostic this server publishes. */ export const DIAGNOSTIC_SOURCE = 'IE Lua'; +/** + * Code action kind of the action that applies every quick fix of a document + * (`editor.codeActionsOnSave`: `{ "source.fixAll.ieLua": "explicit" }`). Users put + * it in their settings: never rename it. + */ +export const FIX_ALL_KIND = 'source.fixAll.ieLua'; + export interface ValidateDocumentParams { readonly uri: string; } diff --git a/test/fixtures/workspace/QUICKFIX.MENU b/test/fixtures/workspace/QUICKFIX.MENU new file mode 100644 index 0000000..7c3e6bb --- /dev/null +++ b/test/fixtures/workspace/QUICKFIX.MENU @@ -0,0 +1,12 @@ +-- Original fixture: text the engine misreads, each with a quick fix. +` +fixtureFixed = true` +menu +{ + name Quick_Fix + label + { + area 0 0 10 10 + text Another_Name + } +} diff --git a/test/integration/codeActions.test.ts b/test/integration/codeActions.test.ts new file mode 100644 index 0000000..1452898 --- /dev/null +++ b/test/integration/codeActions.test.ts @@ -0,0 +1,85 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { DIAGNOSTIC_SOURCE, FIX_ALL_KIND } from '../../src/shared/protocol.ts'; +import { activateExtension, closeAllEditors, fixtureUri, openFixture, waitForDiagnostics } from './helpers.ts'; + +/** The code actions VS Code collects for `range` of `uri`, of `kind` when given. */ +async function actionsAt(uri: vscode.Uri, range: vscode.Range, kind?: string): Promise { + const found = await vscode.commands.executeCommand<(vscode.CodeAction | vscode.Command)[] | undefined>( + 'vscode.executeCodeActionProvider', + uri, + range, + kind, + ); + return (found ?? []).filter((action): action is vscode.CodeAction => 'kind' in action || 'edit' in action); +} + +/** `line:character newText` of each edit of `uri`, in document order. */ +function editsOf(edit: vscode.WorkspaceEdit | undefined, uri: vscode.Uri): string[] { + return (edit?.get(uri) ?? []).map(({ range, newText }) => `${String(range.start.line)}:${String(range.start.character)} ${newText}`); +} + +suite('Code actions', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + /** QUICKFIX.MENU, validated, with its diagnostics. */ + async function quickFixFixture(): Promise<{ uri: vscode.Uri; diagnostics: vscode.Diagnostic[] }> { + const uri = await openFixture('QUICKFIX.MENU'); + await vscode.commands.executeCommand('ieLua.validateDocument', uri); + const diagnostics = await waitForDiagnostics(uri, (found) => found.length === 3); + return { uri, diagnostics }; + } + + test('offers a preferred quick fix that quotes a name with "_", and one that quotes every such name', async () => { + const { uri, diagnostics } = await quickFixFixture(); + const underscore = diagnostics.find((d) => d.code === 'menu-unquoted-underscore' && d.range.start.line === 5); + assert.ok(underscore, 'no diagnostic for name Quick_Fix'); + assert.equal(underscore.source, DIAGNOSTIC_SOURCE); + const actions = (await actionsAt(uri, underscore.range)).filter((action) => action.kind?.value === 'quickfix'); + assert.deepEqual( + actions.map((action) => [action.title, action.isPreferred === true, editsOf(action.edit, uri)]), + [ + ['Enclose in quotes', true, ['5:6 "Quick_Fix"']], + ['Fix all menu-unquoted-underscore problems', false, ['5:6 "Quick_Fix"', '9:7 "Another_Name"']], + ], + ); + }); + + test('offers a quick fix that inserts a space before a closing backtick', async () => { + const { uri, diagnostics } = await quickFixFixture(); + const inline = diagnostics.find((d) => d.code === 'menu-inline-lua-last-character'); + assert.ok(inline, 'no diagnostic for the inline Lua block'); + const actions = (await actionsAt(uri, inline.range)).filter((action) => action.kind?.value === 'quickfix'); + assert.deepEqual( + actions.map((action) => [action.title, editsOf(action.edit, uri)]), + [['Insert a space before the closing backtick', ['2:19 ']]], + ); + }); + + test('fixes every fixable problem with source.fixAll.ieLua, without published diagnostics', async () => { + const document = await vscode.workspace.openTextDocument({ language: 'ie-menu', content: 'name My_Menu\n`x = 1`\n' }); + await vscode.window.showTextDocument(document); + const whole = new vscode.Range(0, 0, document.lineCount, 0); + const [fixAll, ...others] = await actionsAt(document.uri, whole, FIX_ALL_KIND); + assert.ok(fixAll?.edit, 'no fix-all action'); + assert.deepEqual(others, []); + assert.equal(fixAll.kind?.value, FIX_ALL_KIND); + assert.equal(fixAll.title, 'Fix all IE Lua auto-fixable problems'); + assert.ok(await vscode.workspace.applyEdit(fixAll.edit)); + assert.equal(document.getText(), 'name "My_Menu"\n`x = 1 `\n'); + await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor'); + }); + + test('offers no IE Lua code actions for Lua files', async () => { + const uri = fixtureUri('valid.lua'); + await openFixture('valid.lua'); + const actions = await actionsAt(uri, new vscode.Range(0, 0, 1, 0), 'source'); + assert.deepEqual(actions.filter((action) => action.kind?.value === FIX_ALL_KIND), []); + }); +}); diff --git a/test/unit/server/codeActions/quickFixes.test.ts b/test/unit/server/codeActions/quickFixes.test.ts new file mode 100644 index 0000000..c5190b6 --- /dev/null +++ b/test/unit/server/codeActions/quickFixes.test.ts @@ -0,0 +1,156 @@ +import assert from 'node:assert/strict'; +import { + analyzeMenu, + applyChanges, + applyChecked, + combineChanges, + FIXABLE_CODES, + isFixableCode, + type MenuFix, +} from '../../../../src/server/codeActions/quickFixes.ts'; +import { lexMenu, MAX_WORD_LENGTH } from '../../../../src/server/validation/menuLexer.ts'; +import { DiagnosticCode } from '../../../../src/server/validation/types.ts'; + +/** The text after applying every fix of `text`, or `undefined` when the safety check refuses. */ +function fixAll(text: string): string | undefined { + const analysis = analyzeMenu(text); + const changes = applyChecked(text, analysis, analysis.fixes); + return changes && applyChanges(text, changes); +} + +/** The text after applying only `fix`. */ +function fixOne(text: string, fix: MenuFix | undefined): string | undefined { + assert.ok(fix, 'no fix'); + const changes = applyChecked(text, analyzeMenu(text), [fix]); + return changes && applyChanges(text, changes); +} + +describe('server/codeActions/quickFixes', () => { + it('knows exactly the three codes IESDP states a remedy for', () => { + assert.deepEqual([...FIXABLE_CODES].sort(), ['menu-inline-lua-last-character', 'menu-unquoted-underscore', 'menu-word-too-long']); + assert.equal(isFixableCode(DiagnosticCode.LuaSyntax), false); + assert.equal(isFixableCode(DiagnosticCode.MenuUnterminatedString), false); + assert.equal(isFixableCode(DiagnosticCode.MenuUnterminatedBlock), false); + assert.equal(isFixableCode(42), false); + }); + + it('quotes a run with "_", so the engine reads it as one string', () => { + const text = 'menu { name My_Menu }'; + const { fixes } = analyzeMenu(text); + assert.equal(fixes.length, 1); + const [fix] = fixes; + assert.ok(fix); + assert.equal(fix.problem.code, DiagnosticCode.MenuUnquotedUnderscore); + assert.equal(fix.action, 'quote'); + assert.equal(fixOne(text, fix), 'menu { name "My_Menu" }'); + assert.deepEqual(lexMenu('menu { name "My_Menu" }').problems, []); + }); + + it('quotes runs that start or end with "_" as written', () => { + assert.equal(fixAll('text _a b_ __c__'), 'text "_a" "b_" "__c__"'); + }); + + it('offers no fix for a run of digits and "_", which is not a name', () => { + const text = 'area 10_0 0 1 1'; + const analysis = analyzeMenu(text); + assert.equal(analysis.problems.length, 1); + assert.deepEqual(analysis.fixes, []); + assert.equal(applyChecked(text, analysis, analysis.fixes), undefined); + }); + + it('quotes an unquoted word that is too long, as quoted strings are not limited', () => { + const word = 'a'.repeat(MAX_WORD_LENGTH); + const text = `text ${word}`; + const { fixes } = analyzeMenu(text); + assert.equal(fixes.length, 1); + assert.equal(fixes[0]?.problem.code, DiagnosticCode.MenuWordTooLong); + assert.equal(fixOne(text, fixes[0]), `text "${word}"`); + }); + + it('quotes the whole run when a long word is joined to "_", and fixes both problems with one change', () => { + const word = 'b'.repeat(MAX_WORD_LENGTH + 2); + const text = `text ${word}_x`; + const { problems, fixes } = analyzeMenu(text); + assert.deepEqual(problems.map((p) => p.code), [DiagnosticCode.MenuWordTooLong, DiagnosticCode.MenuUnquotedUnderscore]); + assert.equal(fixes.length, 2); + for (const fix of fixes) { + assert.equal(fixOne(text, fix), `text "${word}_x"`); + } + assert.equal(combineChanges(fixes).length, 1); + assert.equal(fixAll(text), `text "${word}_x"`); + }); + + it('inserts a space before a closing backtick, so the engine drops the space instead of code', () => { + const text = '`x = 1`\nmenu { name "M" }'; + const { fixes } = analyzeMenu(text); + assert.equal(fixes.length, 1); + const [fix] = fixes; + assert.ok(fix); + assert.equal(fix.problem.code, DiagnosticCode.MenuInlineLuaLastCharacter); + assert.equal(fix.action, 'insertSpace'); + assert.deepEqual(fix.change, { start: 6, end: 6, newText: ' ' }); + assert.equal(fixOne(text, fix), '`x = 1 `\nmenu { name "M" }'); + }); + + it('keeps the problem range of each fix as the diagnostic has it', () => { + const text = 'name My_Menu `a=1`'; + const { problems, fixes } = analyzeMenu(text); + assert.deepEqual( + fixes.map((fix) => [fix.problem.start, fix.problem.end]), + problems.map((problem) => [problem.start, problem.end]), + ); + }); + + it('offers no fix for unterminated strings and blocks', () => { + assert.deepEqual(analyzeMenu('name "open').fixes, []); + assert.deepEqual(analyzeMenu("name 'open").fixes, []); + assert.deepEqual(analyzeMenu('`x = 1').fixes, []); + }); + + it('fixes one problem and leaves the others reported at their shifted offsets', () => { + const text = 'a_b `x=1` c_d'; + const analysis = analyzeMenu(text); + const first = analysis.fixes[0]; + assert.equal(fixOne(text, first), '"a_b" `x=1` c_d'); + const after = lexMenu('"a_b" `x=1` c_d').problems; + assert.deepEqual(after.map((p) => p.code), [DiagnosticCode.MenuInlineLuaLastCharacter, DiagnosticCode.MenuUnquotedUnderscore]); + assert.deepEqual(after.map((p) => p.start), analysis.problems.slice(1).map((p) => p.start + 2)); + }); + + it('fixes every fixable problem at once and leaves only those without a fix', () => { + const text = 'menu {\n\tname My_Menu\n\tarea 10_0 0 1 1\n\tonOpen `x = 1`\n}\n'; + const fixed = 'menu {\n\tname "My_Menu"\n\tarea 10_0 0 1 1\n\tonOpen `x = 1 `\n}\n'; + assert.equal(fixAll(text), fixed); + assert.deepEqual(lexMenu(fixed).problems.map((p) => p.code), [DiagnosticCode.MenuUnquotedUnderscore]); + // Idempotent: the result has nothing left to fix. + assert.deepEqual(analyzeMenu(fixed).fixes, []); + }); + + it('refuses changes after which the remaining problems differ', () => { + const text = 'a_b c_d'; + const analysis = analyzeMenu(text); + const first = analysis.fixes[0]; + assert.ok(first); + // A change that does not match its problem: it would leave `a_b` reported and break `c_d`. + const bogus: MenuFix = { ...first, change: { start: 5, end: 5, newText: '"' } }; + assert.equal(applyChecked(text, analysis, [bogus]), undefined); + }); + + it('refuses when there is nothing to change', () => { + const analysis = analyzeMenu('menu { name "M" }'); + assert.equal(applyChecked('menu { name "M" }', analysis, []), undefined); + }); + + it('applies changes in document order and keeps one of overlapping changes, the wider first', () => { + assert.equal(applyChanges('abcdef', [{ start: 1, end: 2, newText: 'X' }, { start: 4, end: 4, newText: '-' }]), 'aXcd-ef'); + const fix = (start: number, end: number, newText: string): MenuFix => ({ + problem: { start, end, message: '', code: DiagnosticCode.MenuUnquotedUnderscore, severity: 'warning' }, + action: 'quote', + change: { start, end, newText }, + }); + assert.deepEqual(combineChanges([fix(2, 3, 'n'), fix(0, 5, 'w'), fix(0, 5, 'w'), fix(6, 6, 'i')]), [ + { start: 0, end: 5, newText: 'w' }, + { start: 6, end: 6, newText: 'i' }, + ]); + }); +}); diff --git a/test/unit/server/features/codeActions.test.ts b/test/unit/server/features/codeActions.test.ts new file mode 100644 index 0000000..5d2d34d --- /dev/null +++ b/test/unit/server/features/codeActions.test.ts @@ -0,0 +1,165 @@ +import assert from 'node:assert/strict'; +import { CodeActionKind, type CodeAction, type Diagnostic } from 'vscode-languageserver/node'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { codeActions as compute, CODE_ACTION_KINDS, supportsCodeActionLiterals, wanted, type CodeActionDeps, type Pause } from '../../../../src/server/features/codeActions.ts'; +import { createMessages } from '../../../../src/server/l10n.ts'; +import { DIAGNOSTIC_SOURCE, FIX_ALL_KIND } from '../../../../src/shared/protocol.ts'; + +const deps: CodeActionDeps = { messages: createMessages(undefined), documentChanges: false }; + +function menu(text: string, version = 1): TextDocument { + return TextDocument.create('file:///w/UI.MENU', 'ie-menu', version, text); +} + +/** The diagnostic the server publishes for `[start, end)` of `document`. */ +function diagnostic(document: TextDocument, start: number, end: number, code: string, source = DIAGNOSTIC_SOURCE): Diagnostic { + return { range: { start: document.positionAt(start), end: document.positionAt(end) }, code, source, message: '' }; +} + +/** The result of `codeActions`, which must not have been stopped. */ +async function codeActions( + document: TextDocument, + params: Parameters[1], + dependencies: CodeActionDeps, + pause?: Pause, +): Promise<{ actions: CodeAction[]; refused: string[] }> { + const result = await compute(document, params, dependencies, pause); + assert.ok(result, 'stopped'); + return result; +} + +/** `title → new text of each edit` of each action. */ +function summary(actions: CodeAction[]): string[] { + return actions.map((action) => { + const edits = Object.values(action.edit?.changes ?? {}).flat(); + return `${action.title} [${String(action.kind)}] ${edits.map((edit) => JSON.stringify(edit.newText)).join(' ')}`; + }); +} + +describe('server/features/codeActions', () => { + it('advertises quick fixes and the IE Lua fix-all kind, only to clients that accept CodeAction literals', () => { + assert.deepEqual([...CODE_ACTION_KINDS], ['quickfix', 'source.fixAll.ieLua']); + assert.equal(FIX_ALL_KIND, 'source.fixAll.ieLua'); + assert.equal(supportsCodeActionLiterals({ codeActionKind: { valueSet: [] } }), true); + assert.equal(supportsCodeActionLiterals(undefined), false); + }); + + it('filters by kind as LSP does: a requested kind includes its sub-kinds', () => { + assert.equal(wanted(CodeActionKind.QuickFix, undefined), true); + assert.equal(wanted(FIX_ALL_KIND, undefined), false); + for (const only of [['source'], ['source.fixAll'], [FIX_ALL_KIND]]) { + assert.equal(wanted(FIX_ALL_KIND, only), true, only.join()); + assert.equal(wanted(CodeActionKind.QuickFix, only), false, only.join()); + } + assert.equal(wanted(FIX_ALL_KIND, ['source.fix']), false); + assert.equal(wanted(FIX_ALL_KIND, ['source.organizeImports']), false); + assert.equal(wanted(CodeActionKind.QuickFix, ['quickfix']), true); + }); + + it('offers the fix of a published diagnostic, preferred and linked to it', async () => { + const document = menu('name My_Menu'); + const published = diagnostic(document, 5, 12, 'menu-unquoted-underscore'); + const { actions, refused } = await codeActions(document, { context: { diagnostics: [published] } }, deps); + assert.deepEqual(refused, []); + assert.deepEqual(summary(actions), ['Enclose in quotes [quickfix] "\\"My_Menu\\""']); + const [action] = actions; + assert.ok(action); + assert.equal(action.isPreferred, true); + assert.deepEqual(action.diagnostics, [published]); + }); + + it('inserts a space before a closing backtick', async () => { + const document = menu('`x = 1`'); + const { actions } = await codeActions(document, { context: { diagnostics: [diagnostic(document, 5, 6, 'menu-inline-lua-last-character')] } }, deps); + assert.deepEqual(summary(actions), ['Insert a space before the closing backtick [quickfix] " "']); + }); + + it('adds a fix for every problem of the code when there are several, once', async () => { + const document = menu('a_b c_d'); + const both = [diagnostic(document, 0, 3, 'menu-unquoted-underscore'), diagnostic(document, 4, 7, 'menu-unquoted-underscore')]; + const { actions } = await codeActions(document, { context: { diagnostics: both } }, deps); + assert.deepEqual(summary(actions), [ + 'Enclose in quotes [quickfix] "\\"a_b\\""', + 'Fix all menu-unquoted-underscore problems [quickfix] "\\"a_b\\"" "\\"c_d\\""', + 'Enclose in quotes [quickfix] "\\"c_d\\""', + ]); + }); + + it('ignores diagnostics that are stale, from another source or without a fix', async () => { + const document = menu(' name My_Menu "open'); + const diagnostics = [ + // Published before two spaces were typed at the start. + diagnostic(document, 5, 12, 'menu-unquoted-underscore'), + diagnostic(document, 7, 14, 'menu-unquoted-underscore', 'other linter'), + diagnostic(document, 15, 16, 'menu-unterminated-string'), + diagnostic(document, 0, 1, 'lua-syntax'), + ]; + assert.deepEqual((await codeActions(document, { context: { diagnostics } }, deps)).actions, []); + }); + + it('fixes every fixable problem with source.fixAll.ieLua, whether or not diagnostics were published', async () => { + const document = menu('name My_Menu\narea 10_0 0 1 1\n`x = 1`'); + for (const only of [['source'], ['source.fixAll'], [FIX_ALL_KIND]]) { + const { actions } = await codeActions(document, { context: { diagnostics: [], only } }, deps); + assert.deepEqual(summary(actions), ['Fix all IE Lua auto-fixable problems [source.fixAll.ieLua] "\\"My_Menu\\"" " "'], only.join()); + } + }); + + it('returns no fix-all action when nothing can be fixed', async () => { + const document = menu('area 10_0 0 1 1'); + assert.deepEqual((await codeActions(document, { context: { diagnostics: [], only: ['source'] } }, deps)).actions, []); + }); + + it('returns no quick fixes when only source actions are requested, and no source action otherwise', async () => { + const document = menu('name My_Menu'); + const published = [diagnostic(document, 5, 12, 'menu-unquoted-underscore')]; + assert.deepEqual(summary((await codeActions(document, { context: { diagnostics: published, only: ['source'] } }, deps)).actions), [ + 'Fix all IE Lua auto-fixable problems [source.fixAll.ieLua] "\\"My_Menu\\""', + ]); + assert.deepEqual(summary((await codeActions(document, { context: { diagnostics: published } }, deps)).actions), ['Enclose in quotes [quickfix] "\\"My_Menu\\""']); + }); + + it('offers nothing for Lua files', async () => { + const document = TextDocument.create('file:///w/a.lua', 'lua', 1, 'local My_Menu = 1'); + assert.deepEqual((await codeActions(document, { context: { diagnostics: [], only: ['source', 'quickfix'] } }, deps)).actions, []); + }); + + it('sends versioned edits to clients that support documentChanges', async () => { + const document = menu('name My_Menu', 7); + const { actions } = await codeActions(document, { context: { diagnostics: [], only: [FIX_ALL_KIND] } }, { ...deps, documentChanges: true }); + assert.deepEqual(actions[0]?.edit, { + documentChanges: [ + { + textDocument: { uri: 'file:///w/UI.MENU', version: 7 }, + edits: [{ range: { start: { line: 0, character: 5 }, end: { line: 0, character: 12 } }, newText: '"My_Menu"' }], + }, + ], + }); + }); + + it('ignores a stale diagnostic whose range is past the end of a line, which offsetAt would clamp', async () => { + const document = menu('name My_Menu\nx'); + const stale: Diagnostic = { range: { start: { line: 0, character: 5 }, end: { line: 0, character: 40 } }, code: 'menu-unquoted-underscore', source: DIAGNOSTIC_SOURCE, message: '' }; + assert.deepEqual((await codeActions(document, { context: { diagnostics: [stale] } }, deps)).actions, []); + }); + + it('pauses between diagnostics and stops when the pause says so', async () => { + const document = menu('a_b c_d e_f'); + const diagnostics = [0, 4, 8].map((start) => diagnostic(document, start, start + 3, 'menu-unquoted-underscore')); + let pauses = 0; + const count: Pause = () => { + pauses++; + return Promise.resolve(false); + }; + await codeActions(document, { context: { diagnostics } }, deps, count); + assert.equal(pauses, 2, 'once before each diagnostic after the first'); + assert.equal(await compute(document, { context: { diagnostics } }, deps, () => Promise.resolve(true)), undefined); + }); + + it('titles the actions in the client locale', async () => { + const document = menu('name My_Menu'); + const german = { ...deps, messages: createMessages('de') }; + const { actions } = await codeActions(document, { context: { diagnostics: [diagnostic(document, 5, 12, 'menu-unquoted-underscore')] } }, german); + assert.equal(actions[0]?.title, 'In Anführungszeichen setzen'); + }); +});