From 411da7e83283b891e422dd663a409fedf182771e Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:40:04 +0100 Subject: [PATCH 1/8] feat(server): parse LuaCATS doc comments and find their problems Add src/server/docComments/, pure modules for the doc comments of the LuaCATS annotation reference (https://luals.github.io/wiki/annotations/): - parse.ts: one block of `---` lines into a Markdown description and the @param, @return, @type, @deprecated and @see tags; types are kept as written. The other reference tags and `---|` lines are recognised but not rendered. - attach.ts: which statement a block documents (the one on the next line, with no blank line between), the documented names hover describes, and the @param entry of each parameter of a function the parser sees. - check.ts: doc-tag-malformed, doc-param-unknown and doc-param-duplicate, with localized messages in all 15 server tables. Where the reference is silent (placement, `--- @tag` with a space), the modules follow its examples; the rules are written in each module header. ParsedDocument now keeps its text, to check line boundaries. Nothing uses the modules yet. Co-Authored-By: Claude Opus 5.5 --- l10n/server/messages.cs.json | 7 +- l10n/server/messages.de.json | 7 +- l10n/server/messages.es.json | 7 +- l10n/server/messages.fr.json | 7 +- l10n/server/messages.hu.json | 7 +- l10n/server/messages.it.json | 7 +- l10n/server/messages.ja.json | 7 +- l10n/server/messages.json | 7 +- l10n/server/messages.ko.json | 7 +- l10n/server/messages.pl.json | 7 +- l10n/server/messages.pt-br.json | 7 +- l10n/server/messages.ru.json | 7 +- l10n/server/messages.tr.json | 7 +- l10n/server/messages.zh-cn.json | 7 +- l10n/server/messages.zh-tw.json | 7 +- src/server/docComments/attach.ts | 169 ++++++++++++++ src/server/docComments/check.ts | 67 ++++++ src/server/docComments/parse.ts | 242 ++++++++++++++++++++ src/server/syntax/document.ts | 6 +- src/server/validation/types.ts | 6 + test/unit/server/docComments/attach.test.ts | 103 +++++++++ test/unit/server/docComments/check.test.ts | 69 ++++++ test/unit/server/docComments/parse.test.ts | 121 ++++++++++ 23 files changed, 871 insertions(+), 17 deletions(-) create mode 100644 src/server/docComments/attach.ts create mode 100644 src/server/docComments/check.ts create mode 100644 src/server/docComments/parse.ts create mode 100644 test/unit/server/docComments/attach.test.ts create mode 100644 test/unit/server/docComments/check.test.ts create mode 100644 test/unit/server/docComments/parse.test.ts diff --git a/l10n/server/messages.cs.json b/l10n/server/messages.cs.json index 2ba80c4..f5e7768 100644 --- a/l10n/server/messages.cs.json +++ b/l10n/server/messages.cs.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Opravit všechny automaticky opravitelné problémy IE Lua", + "doc.paramNameMissing": "{0} vyžaduje název parametru a za ním typ.", + "doc.paramTypeMissing": "{0} vyžaduje typ za názvem parametru.", + "doc.typeMissing": "{0} vyžaduje typ.", + "doc.paramUnknown": "Dokumentovaná funkce nemá parametr {0}.", + "doc.paramDuplicate": "Parametr {0} je v tomto komentáři již zdokumentován." } diff --git a/l10n/server/messages.de.json b/l10n/server/messages.de.json index 8ecbd58..06f09e4 100644 --- a/l10n/server/messages.de.json +++ b/l10n/server/messages.de.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Alle automatisch behebbaren IE Lua-Probleme beheben", + "doc.paramNameMissing": "{0} benötigt einen Parameternamen, gefolgt von einem Typ.", + "doc.paramTypeMissing": "{0} benötigt einen Typ nach dem Parameternamen.", + "doc.typeMissing": "{0} benötigt einen Typ.", + "doc.paramUnknown": "Die dokumentierte Funktion hat keinen Parameter {0}.", + "doc.paramDuplicate": "Der Parameter {0} ist in diesem Kommentar bereits dokumentiert." } diff --git a/l10n/server/messages.es.json b/l10n/server/messages.es.json index 7cda641..ab9ccef 100644 --- a/l10n/server/messages.es.json +++ b/l10n/server/messages.es.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Corregir todos los problemas de IE Lua que se pueden corregir automáticamente", + "doc.paramNameMissing": "{0} necesita un nombre de parámetro seguido de un tipo.", + "doc.paramTypeMissing": "{0} necesita un tipo después del nombre del parámetro.", + "doc.typeMissing": "{0} necesita un tipo.", + "doc.paramUnknown": "La función documentada no tiene ningún parámetro {0}.", + "doc.paramDuplicate": "El parámetro {0} ya está documentado en este comentario." } diff --git a/l10n/server/messages.fr.json b/l10n/server/messages.fr.json index 170bc82..91fddfb 100644 --- a/l10n/server/messages.fr.json +++ b/l10n/server/messages.fr.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Corriger tous les problèmes IE Lua corrigibles automatiquement", + "doc.paramNameMissing": "{0} nécessite un nom de paramètre suivi d'un type.", + "doc.paramTypeMissing": "{0} nécessite un type après le nom du paramètre.", + "doc.typeMissing": "{0} nécessite un type.", + "doc.paramUnknown": "La fonction documentée n'a pas de paramètre {0}.", + "doc.paramDuplicate": "Le paramètre {0} est déjà documenté dans ce commentaire." } diff --git a/l10n/server/messages.hu.json b/l10n/server/messages.hu.json index ee10b79..0197a55 100644 --- a/l10n/server/messages.hu.json +++ b/l10n/server/messages.hu.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Az összes automatikusan javítható IE Lua-probléma javítása", + "doc.paramNameMissing": "A(z) {0} címkéhez paraméternév és utána típus szükséges.", + "doc.paramTypeMissing": "A(z) {0} címkéhez típus szükséges a paraméternév után.", + "doc.typeMissing": "A(z) {0} címkéhez típus szükséges.", + "doc.paramUnknown": "A dokumentált függvénynek nincs {0} paramétere.", + "doc.paramDuplicate": "A(z) {0} paraméter már dokumentálva van ebben a megjegyzésben." } diff --git a/l10n/server/messages.it.json b/l10n/server/messages.it.json index 123246c..93083b4 100644 --- a/l10n/server/messages.it.json +++ b/l10n/server/messages.it.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Correggi tutti i problemi di IE Lua correggibili automaticamente", + "doc.paramNameMissing": "{0} richiede un nome di parametro seguito da un tipo.", + "doc.paramTypeMissing": "{0} richiede un tipo dopo il nome del parametro.", + "doc.typeMissing": "{0} richiede un tipo.", + "doc.paramUnknown": "La funzione documentata non ha alcun parametro {0}.", + "doc.paramDuplicate": "Il parametro {0} è già documentato in questo commento." } diff --git a/l10n/server/messages.ja.json b/l10n/server/messages.ja.json index 4d21e0e..e0573e0 100644 --- a/l10n/server/messages.ja.json +++ b/l10n/server/messages.ja.json @@ -6,5 +6,10 @@ "codeAction.quote": "引用符で囲む", "codeAction.insertSpace": "閉じるバッククォートの前にスペースを挿入する", "codeAction.fixAllOfCode": "すべての {0} の問題を修正する", - "codeAction.fixAll": "自動修正可能な IE Lua の問題をすべて修正する" + "codeAction.fixAll": "自動修正可能な IE Lua の問題をすべて修正する", + "doc.paramNameMissing": "{0} には、パラメーター名とそれに続く型が必要です。", + "doc.paramTypeMissing": "{0} には、パラメーター名の後に型が必要です。", + "doc.typeMissing": "{0} には型が必要です。", + "doc.paramUnknown": "ドキュメント化された関数にはパラメーター {0} がありません。", + "doc.paramDuplicate": "パラメーター {0} はこのコメントで既にドキュメント化されています。" } diff --git a/l10n/server/messages.json b/l10n/server/messages.json index 5a98f09..7fb956a 100644 --- a/l10n/server/messages.json +++ b/l10n/server/messages.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Fix all IE Lua auto-fixable problems", + "doc.paramNameMissing": "{0} needs a parameter name followed by a type.", + "doc.paramTypeMissing": "{0} needs a type after the parameter name.", + "doc.typeMissing": "{0} needs a type.", + "doc.paramUnknown": "The documented function has no parameter {0}.", + "doc.paramDuplicate": "Parameter {0} is already documented in this comment." } diff --git a/l10n/server/messages.ko.json b/l10n/server/messages.ko.json index 4f6ff2a..aa318fe 100644 --- a/l10n/server/messages.ko.json +++ b/l10n/server/messages.ko.json @@ -6,5 +6,10 @@ "codeAction.quote": "따옴표로 묶기", "codeAction.insertSpace": "닫는 백틱 앞에 공백 삽입", "codeAction.fixAllOfCode": "모든 {0} 문제 해결", - "codeAction.fixAll": "자동 수정 가능한 모든 IE Lua 문제 해결" + "codeAction.fixAll": "자동 수정 가능한 모든 IE Lua 문제 해결", + "doc.paramNameMissing": "{0}에는 매개 변수 이름과 그 뒤에 형식이 필요합니다.", + "doc.paramTypeMissing": "{0}에는 매개 변수 이름 뒤에 형식이 필요합니다.", + "doc.typeMissing": "{0}에는 형식이 필요합니다.", + "doc.paramUnknown": "문서화된 함수에 {0} 매개 변수가 없습니다.", + "doc.paramDuplicate": "{0} 매개 변수는 이 주석에 이미 문서화되어 있습니다." } diff --git a/l10n/server/messages.pl.json b/l10n/server/messages.pl.json index 4ea55c3..bbd62b3 100644 --- a/l10n/server/messages.pl.json +++ b/l10n/server/messages.pl.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Napraw wszystkie automatycznie naprawialne problemy IE Lua", + "doc.paramNameMissing": "{0} wymaga nazwy parametru, po której następuje typ.", + "doc.paramTypeMissing": "{0} wymaga typu po nazwie parametru.", + "doc.typeMissing": "{0} wymaga typu.", + "doc.paramUnknown": "Udokumentowana funkcja nie ma parametru {0}.", + "doc.paramDuplicate": "Parametr {0} jest już udokumentowany w tym komentarzu." } diff --git a/l10n/server/messages.pt-br.json b/l10n/server/messages.pt-br.json index 35c7c9e..9c297e9 100644 --- a/l10n/server/messages.pt-br.json +++ b/l10n/server/messages.pt-br.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Corrigir todos os problemas do IE Lua que podem ser corrigidos automaticamente", + "doc.paramNameMissing": "{0} precisa de um nome de parâmetro seguido de um tipo.", + "doc.paramTypeMissing": "{0} precisa de um tipo após o nome do parâmetro.", + "doc.typeMissing": "{0} precisa de um tipo.", + "doc.paramUnknown": "A função documentada não tem o parâmetro {0}.", + "doc.paramDuplicate": "O parâmetro {0} já está documentado neste comentário." } diff --git a/l10n/server/messages.ru.json b/l10n/server/messages.ru.json index 0cebda9..928d338 100644 --- a/l10n/server/messages.ru.json +++ b/l10n/server/messages.ru.json @@ -6,5 +6,10 @@ "codeAction.quote": "Заключить в кавычки", "codeAction.insertSpace": "Вставить пробел перед закрывающим обратным апострофом", "codeAction.fixAllOfCode": "Исправить все проблемы {0}", - "codeAction.fixAll": "Исправить все автоматически исправляемые проблемы IE Lua" + "codeAction.fixAll": "Исправить все автоматически исправляемые проблемы IE Lua", + "doc.paramNameMissing": "Для {0} требуется имя параметра, за которым следует тип.", + "doc.paramTypeMissing": "Для {0} требуется тип после имени параметра.", + "doc.typeMissing": "Для {0} требуется тип.", + "doc.paramUnknown": "У документируемой функции нет параметра {0}.", + "doc.paramDuplicate": "Параметр {0} уже задокументирован в этом комментарии." } diff --git a/l10n/server/messages.tr.json b/l10n/server/messages.tr.json index d0dc043..483ff18 100644 --- a/l10n/server/messages.tr.json +++ b/l10n/server/messages.tr.json @@ -6,5 +6,10 @@ "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" + "codeAction.fixAll": "Otomatik olarak düzeltilebilen tüm IE Lua sorunlarını düzelt", + "doc.paramNameMissing": "{0} için bir parametre adı ve ardından bir tür gerekir.", + "doc.paramTypeMissing": "{0} için parametre adından sonra bir tür gerekir.", + "doc.typeMissing": "{0} için bir tür gerekir.", + "doc.paramUnknown": "Belgelenen işlevin {0} parametresi yok.", + "doc.paramDuplicate": "{0} parametresi bu açıklamada zaten belgelenmiş." } diff --git a/l10n/server/messages.zh-cn.json b/l10n/server/messages.zh-cn.json index 090ca3f..8f16300 100644 --- a/l10n/server/messages.zh-cn.json +++ b/l10n/server/messages.zh-cn.json @@ -6,5 +6,10 @@ "codeAction.quote": "用引号括起来", "codeAction.insertSpace": "在右反引号前插入空格", "codeAction.fixAllOfCode": "修复所有 {0} 问题", - "codeAction.fixAll": "修复所有可自动修复的 IE Lua 问题" + "codeAction.fixAll": "修复所有可自动修复的 IE Lua 问题", + "doc.paramNameMissing": "{0} 需要参数名称,后跟类型。", + "doc.paramTypeMissing": "{0} 需要在参数名称后指定类型。", + "doc.typeMissing": "{0} 需要类型。", + "doc.paramUnknown": "所记录的函数没有参数 {0}。", + "doc.paramDuplicate": "参数 {0} 已在此注释中记录。" } diff --git a/l10n/server/messages.zh-tw.json b/l10n/server/messages.zh-tw.json index 7d99504..54978d8 100644 --- a/l10n/server/messages.zh-tw.json +++ b/l10n/server/messages.zh-tw.json @@ -6,5 +6,10 @@ "codeAction.quote": "以引號括住", "codeAction.insertSpace": "在右反引號前插入空格", "codeAction.fixAllOfCode": "修正所有 {0} 問題", - "codeAction.fixAll": "修正所有可自動修正的 IE Lua 問題" + "codeAction.fixAll": "修正所有可自動修正的 IE Lua 問題", + "doc.paramNameMissing": "{0} 需要參數名稱,後面接著類型。", + "doc.paramTypeMissing": "{0} 需要在參數名稱後指定類型。", + "doc.typeMissing": "{0} 需要類型。", + "doc.paramUnknown": "所記錄的函式沒有參數 {0}。", + "doc.paramDuplicate": "參數 {0} 已在此註解中記錄。" } diff --git a/src/server/docComments/attach.ts b/src/server/docComments/attach.ts new file mode 100644 index 0000000..72688ae --- /dev/null +++ b/src/server/docComments/attach.ts @@ -0,0 +1,169 @@ +// Which code a LuaCATS doc block documents. Pure: no LSP or `vscode` imports. +// +// The annotation reference does not state where a doc block must be; all its +// examples put it on the lines directly above the code. That is the rule here: +// +// - A doc line is a `--` short comment that starts with exactly three dashes +// (`---`, not `----` banners) and is alone on its line (only white space +// before it). A `---` comment after code is not a doc comment. +// - A doc block is a run of doc lines on consecutive lines. +// - It documents the statement that starts on the next line (white space before +// it is fine). A blank line, or anything else, in between detaches it. +// +// Documented names are those hover describes by their declaration +// (signatures.ts): `local function f`, `local x = …` with one name, +// `function G()` with one name and `G = …` with one target. Parameters take their +// `@param` entry from a block above any statement whose function the parser +// sees, which also includes `function M.f(a)`, `function M:m(a)` and +// `M.f = function(a) … end`. + +import type * as Ast from '../syntax/ast.ts'; +import type { ParsedDocument } from '../syntax/document.ts'; +import { walk } from '../syntax/walk.ts'; +import { parseDocComment, type DocComment, type DocLine, type DocParam } from './parse.ts'; + +export interface DocBlock { + readonly doc: DocComment; + /** From the first `---` to the end of the last doc line. */ + readonly start: number; + readonly end: number; + /** The statement the block documents, if one starts on the next line. */ + readonly statement: Ast.Statement | undefined; + /** The function that statement defines, when the parser sees it. */ + readonly func: Ast.FunctionExpression | undefined; + /** The function is a method (`function M:m()`), with an implicit `self`. */ + readonly method: boolean; +} + +export interface DocumentDocs { + /** Every doc block of the document, in source order. */ + readonly blocks: readonly DocBlock[]; + /** The doc comment of each documented declaring or assigned identifier. */ + readonly names: ReadonlyMap; + /** The `@param` entry of each documented parameter (the first, when one is documented twice). */ + readonly parameters: ReadonlyMap; +} + +/** `\r\n`, `\n` or `\r` and then only white space: the next line, with no blank line in between. */ +const NEXT_LINE = /^(?:\r\n|\n|\r)[ \t\v\f]*$/; +/** The same at `lastIndex` (sticky): where the next line's first non-blank character is. */ +const NEXT_LINE_AT = /(?:\r\n|\n|\r)[ \t\v\f]*/y; +const LINE_INDENT = /(?:^|[\r\n])[ \t\v\f]*$/; + +/** Whether only white space precedes `offset` on its line. */ +const aloneOnLine = (text: string, offset: number): boolean => LINE_INDENT.test(text.slice(Math.max(0, text.lastIndexOf('\n', offset - 1), text.lastIndexOf('\r', offset - 1)), offset)); + +const isDocLine = (text: string, comment: { readonly start: number; readonly end: number; readonly long: boolean }): boolean => + !comment.long && text.startsWith('---', comment.start) && text[comment.start + 3] !== '-' && aloneOnLine(text, comment.start); + +/** The function a statement defines, if it is written there. */ +function definedFunction(statement: Ast.Statement): { readonly func: Ast.FunctionExpression | undefined; readonly method: boolean } { + switch (statement.kind) { + case 'LocalFunctionStatement': + return { func: statement.func, method: false }; + case 'FunctionDeclaration': + return { func: statement.func, method: statement.method !== undefined }; + case 'LocalStatement': + case 'AssignmentStatement': { + const [value] = statement.values; + const count = statement.kind === 'LocalStatement' ? statement.names.length : statement.targets.length; + return { func: count === 1 && statement.values.length === 1 && value?.kind === 'FunctionExpression' ? value : undefined, method: false }; + } + default: + return { func: undefined, method: false }; + } +} + +/** The identifier a statement documents for hover, if any. */ +function documentedName(statement: Ast.Statement): Ast.Identifier | undefined { + switch (statement.kind) { + case 'LocalFunctionStatement': + return statement.name; + case 'LocalStatement': + return statement.names.length === 1 ? statement.names[0] : undefined; + case 'FunctionDeclaration': + return statement.path.length === 1 && statement.method === undefined ? statement.path[0] : undefined; + case 'AssignmentStatement': { + const [target] = statement.targets; + return statement.targets.length === 1 && target?.kind === 'Identifier' ? target : undefined; + } + default: + return undefined; + } +} + +function analyze(document: ParsedDocument): DocumentDocs { + const { text } = document; + const blocks: DocBlock[] = []; + const names = new Map(); + const parameters = new Map(); + for (const { tree } of document.chunks) { + // Runs of doc lines on consecutive lines. + const runs: { start: number; end: number; lines: DocLine[] }[] = []; + for (const comment of tree.comments) { + if (!isDocLine(text, comment)) continue; + const line: DocLine = { text: text.slice(comment.start + 3, comment.end), start: comment.start + 3 }; + const last = runs[runs.length - 1]; + if (last && NEXT_LINE.test(text.slice(last.end, comment.start))) { + last.lines.push(line); + last.end = comment.end; + } else { + runs.push({ start: comment.start, end: comment.end, lines: [line] }); + } + } + if (runs.length === 0) continue; + // Statements by the offset of their first token; the outermost one when several start there. + const statements = new Map(); + walk(tree.body, (node) => { + if (isStatement(node) && !statements.has(node.start)) statements.set(node.start, node); + }); + for (const run of runs) { + const doc = parseDocComment(run.lines); + // The statement after one line break and indentation, if one starts there. + NEXT_LINE_AT.lastIndex = run.end; + const next = NEXT_LINE_AT.exec(text); + const statement = next ? statements.get(NEXT_LINE_AT.lastIndex) : undefined; + const { func, method } = statement ? definedFunction(statement) : { func: undefined, method: false }; + blocks.push({ doc, start: run.start, end: run.end, statement, func, method }); + if (!statement) continue; + const name = documentedName(statement); + if (name) names.set(name, doc); + for (const parameter of func?.parameters ?? []) { + const entry = doc.params.find((param) => param.name === parameter.name); + if (entry) parameters.set(parameter, entry); + } + } + } + return { blocks, names, parameters }; +} + +const STATEMENT_KINDS: ReadonlySet = new Set([ + 'LocalStatement', 'AssignmentStatement', 'CallStatement', 'DoStatement', 'WhileStatement', 'RepeatStatement', + 'IfStatement', 'NumericForStatement', 'GenericForStatement', 'FunctionDeclaration', 'LocalFunctionStatement', + 'ReturnStatement', 'BreakStatement', 'GotoStatement', 'LabelStatement', +]); + +const isStatement = (node: Ast.Statement | Ast.Expression): node is Ast.Statement => STATEMENT_KINDS.has(node.kind); + +/** Doc blocks of each document; dropped with the document. */ +const indexes = new WeakMap(); + +/** The doc blocks of `document` and what they document, computed once per parsed document. */ +export function documentDocs(document: ParsedDocument): DocumentDocs { + let docs = indexes.get(document); + if (!docs) { + docs = analyze(document); + indexes.set(document, docs); + } + return docs; +} + +/** The doc comment of a declaring or assigned identifier (`local function f`, `G = …`), if it has one. */ +export function docCommentFor(document: ParsedDocument, identifier: Ast.Identifier): DocComment | undefined { + return documentDocs(document).names.get(identifier); +} + +/** The `@param` entry of a declared parameter, if its function's doc block has one. */ +export function parameterDoc(document: ParsedDocument, parameter: Ast.Identifier): DocParam | undefined { + return documentDocs(document).parameters.get(parameter); +} diff --git a/src/server/docComments/check.ts b/src/server/docComments/check.ts new file mode 100644 index 0000000..b2cfeeb --- /dev/null +++ b/src/server/docComments/check.ts @@ -0,0 +1,67 @@ +// Problems in LuaCATS doc comments. Pure: no LSP or `vscode` imports. +// +// Only what can be told from the text, never from types (which are shown as +// written and never checked): +// +// - `doc-tag-malformed`: `---@param` without a name or type, `---@return` or +// `---@type` without a type (the annotation reference requires them). In any +// doc block. +// - `doc-param-unknown`: `---@param x` above a function the parser sees +// (attach.ts) that has no parameter `x`: `...` needs a vararg function, `self` +// is the implicit parameter of a method. A block above anything else (a call +// result could be any function) is not checked. +// - `doc-param-duplicate`: a parameter documented twice in one block. + +import type { Messages } from '../l10n.ts'; +import type { ParsedDocument } from '../syntax/document.ts'; +import { DiagnosticCode, type Problem } from '../validation/types.ts'; +import { documentDocs, type DocBlock } from './attach.ts'; +import type { MalformedTag } from './parse.ts'; + +function malformedMessage({ tag, reason }: MalformedTag, messages: Messages): string { + switch (reason) { + case 'paramName': + return messages.t('doc.paramNameMissing', tag); + case 'paramType': + return messages.t('doc.paramTypeMissing', tag); + case 'type': + return messages.t('doc.typeMissing', tag); + } +} + +/** The parameter names `block`'s function accepts, or `undefined` when it has no function. */ +function acceptedNames(block: DocBlock): ReadonlySet | undefined { + if (!block.func) return undefined; + const names = new Set(block.func.parameters.map((parameter) => parameter.name)); + if (block.func.isVararg) names.add('...'); + if (block.method) names.add('self'); + return names; +} + +/** The doc-comment problems of `document`, in source order. */ +export function checkDocComments(document: ParsedDocument, messages: Messages): Problem[] { + const problems: Problem[] = []; + for (const block of documentDocs(document).blocks) { + const found: { readonly start: number; readonly problem: Problem }[] = []; + for (const malformed of block.doc.malformed) { + found.push({ + start: malformed.span.start, + problem: { ...malformed.span, code: DiagnosticCode.DocTagMalformed, severity: 'warning', message: malformedMessage(malformed, messages) }, + }); + } + const accepted = acceptedNames(block); + const seen = new Set(); + for (const { name, nameSpan } of block.doc.params) { + const quoted = JSON.stringify(name); + if (seen.has(name)) { + found.push({ start: nameSpan.start, problem: { ...nameSpan, code: DiagnosticCode.DocParamDuplicate, severity: 'warning', message: messages.t('doc.paramDuplicate', quoted) } }); + } else if (accepted && !accepted.has(name)) { + found.push({ start: nameSpan.start, problem: { ...nameSpan, code: DiagnosticCode.DocParamUnknown, severity: 'warning', message: messages.t('doc.paramUnknown', quoted) } }); + } + seen.add(name); + } + found.sort((a, b) => a.start - b.start); + problems.push(...found.map(({ problem }) => problem)); + } + return problems; +} diff --git a/src/server/docComments/parse.ts b/src/server/docComments/parse.ts new file mode 100644 index 0000000..c456efd --- /dev/null +++ b/src/server/docComments/parse.ts @@ -0,0 +1,242 @@ +// LuaCATS doc comments (https://luals.github.io/wiki/annotations/): the lines of +// one `---` comment block, parsed into a description and tags. Pure: no LSP or +// `vscode` imports. Types are kept as written; nothing here checks them. +// +// The annotation reference fixes the syntax of each tag; where it is silent this +// module follows its examples, and says so: +// +// - A tag line is `---@ …` with no space before `@`, as in every example. +// `--- @param` stays description text. +// - Any other line is description (Markdown, "most of the markdown syntax"), +// with one leading space removed, so `--- Text` is `Text`. An empty `---` +// line is an empty line, which separates paragraphs. +// - `---|` lines continue the values of the tag above them (`---|"'immediate'"`); +// they are not description and are not rendered. + +/** One line of a doc block: the text after `---`, and the document offset of its first character. */ +export interface DocLine { + readonly text: string; + readonly start: number; +} + +/** A half-open document range `[start, end)`. */ +export interface Span { + readonly start: number; + readonly end: number; +} + +/** `---@param [description]`. */ +export interface DocParam { + /** The name as written without `?`: a Lua name or `...`. */ + readonly name: string; + readonly optional: boolean; + readonly type: string; + /** Kept verbatim (trimmed). */ + readonly description: string; + readonly nameSpan: Span; +} + +/** `---@return [ [comment] | [name] #]`. */ +export interface DocReturn { + readonly type: string; + readonly name: string | undefined; + readonly description: string; +} + +/** A tag in the order written, for rendering. */ +export type DocTag = + | { readonly tag: 'param'; readonly param: DocParam } + | { readonly tag: 'return'; readonly value: DocReturn } + | { readonly tag: 'type'; readonly type: string } + | { readonly tag: 'deprecated' } + | { readonly tag: 'see'; readonly symbol: string }; + +/** Why a tag line is incomplete. */ +export type MalformedReason = 'paramName' | 'paramType' | 'type'; + +export interface MalformedTag { + /** The tag name as written, with `@` (`@param`). */ + readonly tag: string; + readonly reason: MalformedReason; + /** From `@` to the end of the line's text, trailing white space excluded. */ + readonly span: Span; +} + +export interface DocComment { + /** The description lines joined with `\n`; empty when there are none. */ + readonly description: string; + /** The rendered tags in source order (`@param`, `@return`, `@type`, `@deprecated`, `@see`). */ + readonly tags: readonly DocTag[]; + readonly params: readonly DocParam[]; + readonly malformed: readonly MalformedTag[]; +} + +/** The tags of the annotation reference. Lines of the others are recognised, but not rendered. */ +export const LUACATS_TAGS: ReadonlySet = new Set([ + 'alias', 'as', 'async', 'cast', 'class', 'deprecated', 'diagnostic', 'enum', 'field', 'generic', 'meta', 'module', + 'nodiscard', 'operator', 'overload', 'package', 'param', 'private', 'protected', 'return', 'see', 'source', 'type', + 'vararg', 'version', +]); + +const isSpace = (c: string | undefined): boolean => c === ' ' || c === '\t'; +const NAME = /^[A-Za-z_][A-Za-z0-9_]*/; +const CLOSING: Readonly> = { '(': ')', '<': '>', '{': '}', '[': ']' }; + +function skipSpaces(text: string, i: number): number { + while (isSpace(text[i])) i++; + return i; +} + +/** + * The end of the type that starts at `from`. A type runs through balanced + * `()`, `<>`, `{}`, `[]` and quoted strings. White space outside them ends it, + * except around `|` (`string | nil`), after the `):` of a function type and + * after a `,` in its return list (`fun(a: integer): string, boolean`). + */ +export function scanType(text: string, from: number): number { + const open: string[] = []; + let functionReturns = false; + let i = from; + while (i < text.length) { + const c = text[i] ?? ''; + if (c === '"' || c === "'" || c === '`') { + const close = text.indexOf(c, i + 1); + i = close < 0 ? text.length : close + 1; + continue; + } + if (c in CLOSING) { + open.push(CLOSING[c] ?? ''); + } else if (open.length > 0 && c === open[open.length - 1]) { + open.pop(); + } else if (open.length === 0) { + if (c === ':' && text[i - 1] === ')') functionReturns = true; + if (isSpace(c)) { + const next = skipSpaces(text, i); + const previous = text[i - 1]; + const continues = next < text.length && (previous === '|' || text[next] === '|' || (functionReturns && (previous === ':' || previous === ','))); + if (!continues) break; + i = next; + continue; + } + } + i++; + } + return i; +} + +/** The type at `from` (after white space), and where it ends; an empty type when there is none. */ +function typeAt(text: string, from: number): { readonly type: string; readonly end: number } { + const start = skipSpaces(text, from); + const end = scanType(text, start); + return { type: text.slice(start, end), end }; +} + +/** `name` or `...` at `from`, with an optional `?`; `undefined` when there is none. */ +function paramName(text: string, from: number): { readonly name: string; readonly optional: boolean; readonly start: number; readonly end: number } | undefined { + const rest = text.slice(from); + const name = rest.startsWith('...') ? '...' : NAME.exec(rest)?.[0]; + if (name === undefined) return undefined; + const optional = text[from + name.length] === '?'; + return { name, optional, start: from, end: from + name.length + (optional ? 1 : 0) }; +} + +function parseReturn(text: string, from: number): DocReturn { + const { type, end } = typeAt(text, from); + let rest = text.slice(end).trim(); + let name: string | undefined; + if (!rest.startsWith('#')) { + const written = rest.startsWith('...') ? '...' : NAME.exec(rest)?.[0]; + // A name is a whole word: `boolean ok # …`, `string ...`. + if (written !== undefined && (rest.length === written.length || isSpace(rest[written.length]))) { + name = written; + rest = rest.slice(written.length).trim(); + } + } + const description = rest.startsWith('#') ? rest.slice(1).trim() : rest; + return { type, name, description }; +} + +/** Parses the lines of one doc block. */ +export function parseDocComment(lines: readonly DocLine[]): DocComment { + const description: string[] = []; + const tags: DocTag[] = []; + const params: DocParam[] = []; + const malformed: MalformedTag[] = []; + for (const { text, start } of lines) { + if (text.startsWith('|')) continue; + if (!text.startsWith('@')) { + description.push(isSpace(text[0]) ? text.slice(1) : text); + continue; + } + const tag = /^@([A-Za-z_]*)/.exec(text)?.[1] ?? ''; + const afterTag = 1 + tag.length; + const span: Span = { start, end: start + text.trimEnd().length }; + const fail = (reason: MalformedReason): void => { + malformed.push({ tag: `@${tag}`, reason, span }); + }; + switch (tag) { + case 'param': { + const nameAt = skipSpaces(text, afterTag); + const name = nameAt > afterTag ? paramName(text, nameAt) : undefined; + if (!name) { + fail('paramName'); + break; + } + const { type, end } = isSpace(text[name.end]) ? typeAt(text, name.end) : { type: '', end: name.end }; + if (!type) { + fail('paramType'); + break; + } + const param: DocParam = { + name: name.name, + optional: name.optional, + type, + description: text.slice(end).trim(), + nameSpan: { start: start + name.start, end: start + name.end - (name.optional ? 1 : 0) }, + }; + params.push(param); + tags.push({ tag: 'param', param }); + break; + } + case 'return': { + const value = isSpace(text[afterTag]) ? parseReturn(text, afterTag) : undefined; + if (!value?.type) { + fail('type'); + break; + } + tags.push({ tag: 'return', value }); + break; + } + case 'type': { + const type = isSpace(text[afterTag]) ? typeAt(text, afterTag).type : ''; + if (!type) { + fail('type'); + break; + } + tags.push({ tag: 'type', type }); + break; + } + case 'deprecated': + tags.push({ tag: 'deprecated' }); + break; + case 'see': { + const symbol = text.slice(afterTag).trim(); + if (symbol) tags.push({ tag: 'see', symbol }); + break; + } + default: + // Other LuaCATS tags, and unknown ones: not rendered, never description. + break; + } + } + return { description: trimBlankLines(description).join('\n'), tags, params, malformed }; +} + +/** `lines` without leading and trailing empty lines. */ +function trimBlankLines(lines: readonly string[]): string[] { + let first = 0; + let last = lines.length; + while (first < last && lines[first]?.trim() === '') first++; + while (last > first && lines[last - 1]?.trim() === '') last--; + return lines.slice(first, last); +} diff --git a/src/server/syntax/document.ts b/src/server/syntax/document.ts index 55b366d..513fd35 100644 --- a/src/server/syntax/document.ts +++ b/src/server/syntax/document.ts @@ -15,6 +15,8 @@ export interface ParsedChunk { export interface ParsedDocument { readonly kind: DocumentKind; + /** The text that was parsed (offsets in the trees index into it). */ + readonly text: string; /** Lua chunks in document order. */ readonly chunks: readonly ParsedChunk[]; /** `{ … }` blocks of a .menu file; empty for Lua. */ @@ -34,8 +36,8 @@ export function parseDocument(text: string, kind: DocumentKind): ParsedDocument return { chunk, tree, scopes: analyzeScopes(tree) }; }; if (kind === 'lua') { - return { kind, chunks: [parse({ kind: 'statements', origin: 'file', offset: 0, region: { start: 0, end: text.length }, text, forms: [CHUNK_FORM] })], blocks: [] }; + return { kind, text, chunks: [parse({ kind: 'statements', origin: 'file', offset: 0, region: { start: 0, end: text.length }, text, forms: [CHUNK_FORM] })], blocks: [] }; } const { chunks, blocks } = extractMenuLua(text); - return { kind, chunks: chunks.map(parse), blocks }; + return { kind, text, chunks: chunks.map(parse), blocks }; } diff --git a/src/server/validation/types.ts b/src/server/validation/types.ts index 4eac506..40b841a 100644 --- a/src/server/validation/types.ts +++ b/src/server/validation/types.ts @@ -67,6 +67,12 @@ export const DiagnosticCode = { MenuWordTooLong: 'menu-word-too-long', /** `_` joined to unquoted text in a .menu file; the engine skips it and splits the text. */ MenuUnquotedUnderscore: 'menu-unquoted-underscore', + /** A LuaCATS `---@param` names a parameter the documented function does not have. */ + DocParamUnknown: 'doc-param-unknown', + /** A LuaCATS doc block documents the same parameter twice. */ + DocParamDuplicate: 'doc-param-duplicate', + /** A LuaCATS `---@param`, `---@return` or `---@type` lacks its name or type. */ + DocTagMalformed: 'doc-tag-malformed', } as const; export type DiagnosticCode = (typeof DiagnosticCode)[keyof typeof DiagnosticCode]; diff --git a/test/unit/server/docComments/attach.test.ts b/test/unit/server/docComments/attach.test.ts new file mode 100644 index 0000000..d42df58 --- /dev/null +++ b/test/unit/server/docComments/attach.test.ts @@ -0,0 +1,103 @@ +import assert from 'node:assert/strict'; +import { docCommentFor, documentDocs, parameterDoc } from '../../../../src/server/docComments/attach.ts'; +import { parseDocument, type ParsedDocument } from '../../../../src/server/syntax/document.ts'; +import { targetAt } from '../../../../src/server/syntax/navigation.ts'; + +/** The description of the doc comment of the declaring or assigned name at the first `needle`. */ +function descriptionAt(document: ParsedDocument, needle: string): string | undefined { + const hit = targetAt(document, document.text.indexOf(needle)); + assert.ok(hit, needle); + return docCommentFor(document, hit.identifier)?.description; +} + +const lua = (...source: string[]): ParsedDocument => parseDocument(source.join('\n'), 'lua'); + +describe('server/docComments/attach', () => { + it('documents the statement on the next line, with any indentation', () => { + const document = lua('--- Adds.', 'local function add(a, b) end', ' --- Value.', ' local value = 1', '--- Global.', 'function G() end', '--- Assigned.', 'H = 2'); + assert.equal(descriptionAt(document, 'add'), 'Adds.'); + assert.equal(descriptionAt(document, 'value'), 'Value.'); + assert.equal(descriptionAt(document, 'G('), 'Global.'); + assert.equal(descriptionAt(document, 'H ='), 'Assigned.'); + }); + + it('joins doc lines on consecutive lines into one block', () => { + const document = lua('--- One.', '--- Two.', 'local x'); + assert.equal(descriptionAt(document, 'x'), 'One.\nTwo.'); + assert.equal(documentDocs(document).blocks.length, 1); + }); + + it('accepts \\r\\n and \\r line breaks', () => { + assert.equal(descriptionAt(parseDocument('--- A.\r\n--- B.\r\nlocal x', 'lua'), 'x'), 'A.\nB.'); + assert.equal(descriptionAt(parseDocument('--- A.\rlocal x', 'lua'), 'x'), 'A.'); + }); + + it('is detached by a blank line', () => { + assert.equal(descriptionAt(lua('--- Header.', '', 'local x'), 'x'), undefined); + const split = lua('--- A.', '', '--- B.', 'local x'); + assert.equal(descriptionAt(split, 'x'), 'B.'); + assert.equal(documentDocs(split).blocks.length, 2); + }); + + it('ignores -- and ---- comments, long comments, and --- after code', () => { + assert.equal(descriptionAt(lua('-- Plain.', 'local x'), 'x'), undefined); + assert.equal(descriptionAt(lua('---- Banner', 'local x'), 'x'), undefined); + assert.equal(descriptionAt(lua('--[[ Long. ]]', 'local x'), 'x'), undefined); + const trailing = lua('local y = 1 --- Not a doc.', 'local x'); + assert.equal(descriptionAt(trailing, 'x'), undefined); + assert.equal(documentDocs(trailing).blocks.length, 0); + }); + + it('does not document a statement that starts later on the next line', () => { + assert.equal(descriptionAt(lua('--- A.', 'local y = 1 local x = 2'), 'x ='), undefined); + assert.equal(descriptionAt(lua('--- A.', 'local y = 1 local x = 2'), 'y'), 'A.'); + }); + + it('documents names only where hover describes a declaration', () => { + const document = lua('--- Two names.', 'local a, b = 1, 2', '--- Field.', 'function M.f(p) end', '--- Method.', 'function M:m(q) end'); + assert.equal(descriptionAt(document, 'a,'), undefined); + assert.equal(descriptionAt(document, 'b ='), undefined); + assert.equal(documentDocs(document).names.size, 0); + }); + + it('gives each parameter of a visible function its @param entry', () => { + const document = lua( + '---@param p string The p.', + 'function M.f(p) end', + '---@param q integer', + '---@param q string', + 'function M:m(q) end', + '---@param r boolean', + 'M.g = function(r) end', + '---@param s number', + 'local h = make(function(s) end)', + ); + const paramAt = (needle: string): string | undefined => { + const hit = targetAt(document, document.text.indexOf(needle)); + assert.ok(hit?.target.kind === 'local' && hit.target.declaration.identifier, needle); + return parameterDoc(document, hit.target.declaration.identifier)?.type; + }; + assert.equal(paramAt('p) end'), 'string'); + // The first entry wins when a parameter is documented twice. + assert.equal(paramAt('q) end'), 'integer'); + assert.equal(paramAt('r) end'), 'boolean'); + // A function inside a call is not the documented statement's function. + assert.equal(paramAt('s) end'), undefined); + }); + + it('records the function of each documented statement, and methods', () => { + const [field, method, call, none] = documentDocs(lua('---', 'function M.f(p) end', '---', 'function M:m() end', '---', 'f()', '---')).blocks; + assert.ok(field && method && call && none); + assert.equal(field.func?.parameters[0]?.name, 'p'); + assert.equal(field.method, false); + assert.equal(method.method, true); + assert.equal(call.statement?.kind, 'CallStatement'); + assert.equal(call.func, undefined); + assert.equal(none.statement, undefined); + }); + + it('reads doc comments in the Lua blocks of .menu files', () => { + const document = parseDocument('menu\n{\n\tname "M"\n}\n`\n--- Opens it.\nfunction OpenIt() end\n`\n', 'menu'); + assert.equal(descriptionAt(document, 'OpenIt'), 'Opens it.'); + }); +}); diff --git a/test/unit/server/docComments/check.test.ts b/test/unit/server/docComments/check.test.ts new file mode 100644 index 0000000..1e08e21 --- /dev/null +++ b/test/unit/server/docComments/check.test.ts @@ -0,0 +1,69 @@ +import assert from 'node:assert/strict'; +import { checkDocComments } from '../../../../src/server/docComments/check.ts'; +import { createMessages } from '../../../../src/server/l10n.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; + +const english = createMessages(undefined); + +/** `[code, problem text]` for each problem of the Lua `lines`. */ +function check(...lines: string[]): [string, string][] { + const text = lines.join('\n'); + return checkDocComments(parseDocument(text, 'lua'), english).map((problem) => [problem.code, text.slice(problem.start, problem.end)]); +} + +describe('server/docComments/check', () => { + it('accepts parameters the function has, `...` of a vararg function and `self` of a method', () => { + assert.deepEqual(check('---@param a integer', '---@param ... any', 'local function f(a, ...) end', '---@param self M', 'function M:m() end'), []); + }); + + it('reports @param names the documented function does not have', () => { + assert.deepEqual(check('---@param b integer', '---@param ... any', '---@param self M', 'local function f(a) end'), [ + ['doc-param-unknown', 'b'], + ['doc-param-unknown', '...'], + ['doc-param-unknown', 'self'], + ]); + assert.deepEqual(check('---@param x? integer', 'G = function() end'), [['doc-param-unknown', 'x']]); + }); + + it('does not check parameters where the function is not written in the statement', () => { + assert.deepEqual(check('---@param x integer', 'local f = make()'), []); + assert.deepEqual(check('---@param x integer'), []); + assert.deepEqual(check('---@param x integer', '', 'local function f() end'), []); + }); + + it('reports a parameter documented twice, once for each repetition', () => { + assert.deepEqual(check('---@param a integer', '---@param a string', '---@param a nil', 'local function f(a) end'), [ + ['doc-param-duplicate', 'a'], + ['doc-param-duplicate', 'a'], + ]); + }); + + it('reports incomplete tags in any doc block, in source order', () => { + assert.deepEqual(check('---@return', '---@param', '---@type ', '---@param x', 'local y'), [ + ['doc-tag-malformed', '@return'], + ['doc-tag-malformed', '@param'], + ['doc-tag-malformed', '@type'], + ['doc-tag-malformed', '@param x'], + ]); + }); + + it('says what is wrong, naming the tag and the parameter', () => { + const messages = checkDocComments(parseDocument('---@param\n---@param x\n---@return\n---@param b integer\n---@param b integer\nlocal function f(a) end', 'lua'), english).map( + (problem) => problem.message, + ); + assert.deepEqual(messages, [ + '@param needs a parameter name followed by a type.', + '@param needs a type after the parameter name.', + '@return needs a type.', + 'The documented function has no parameter "b".', + 'Parameter "b" is already documented in this comment.', + ]); + }); + + it('localizes the messages', () => { + const [problem] = checkDocComments(parseDocument('---@return\nlocal x', 'lua'), createMessages('de')); + assert.ok(problem); + assert.equal(problem.message, '@return benötigt einen Typ.'); + assert.equal(problem.severity, 'warning'); + }); +}); diff --git a/test/unit/server/docComments/parse.test.ts b/test/unit/server/docComments/parse.test.ts new file mode 100644 index 0000000..e9ea060 --- /dev/null +++ b/test/unit/server/docComments/parse.test.ts @@ -0,0 +1,121 @@ +import assert from 'node:assert/strict'; +import { parseDocComment, scanType, type DocLine } from '../../../../src/server/docComments/parse.ts'; + +/** Doc lines from the text after each `---`, at made-up offsets 100 apart. */ +const lines = (...texts: string[]): DocLine[] => texts.map((text, i) => ({ text, start: i * 100 })); + +const typeOf = (text: string): string => text.slice(0, scanType(text, 0)); + +describe('server/docComments/parse', () => { + describe('scanType', () => { + it('ends a simple type at white space', () => { + assert.equal(typeOf('integer the count'), 'integer'); + assert.equal(typeOf('string?'), 'string?'); + assert.equal(typeOf('string[] names'), 'string[]'); + }); + + it('keeps unions together, with or without spaces around |', () => { + assert.equal(typeOf('string|nil x'), 'string|nil'); + assert.equal(typeOf('string | nil x'), 'string | nil'); + assert.equal(typeOf('"a" | "b" c'), '"a" | "b"'); + }); + + it('runs through balanced brackets and quotes', () => { + assert.equal(typeOf('table map'), 'table'); + assert.equal(typeOf('{ x: number, y: number } point'), '{ x: number, y: number }'); + assert.equal(typeOf('"a b" rest'), '"a b"'); + assert.equal(typeOf("'a b' rest"), "'a b'"); + }); + + it('keeps the return list of a function type', () => { + assert.equal(typeOf('fun(a: integer): string callback'), 'fun(a: integer): string'); + assert.equal(typeOf('fun(): string, boolean callback'), 'fun(): string, boolean'); + }); + + it('does not continue after a colon or comma that is not part of a function type', () => { + assert.equal(typeOf('integer: count'), 'integer:'); + assert.equal(typeOf('integer, count'), 'integer,'); + }); + + it('takes the rest of the line when a bracket is never closed', () => { + assert.equal(typeOf('table { + it('joins description lines, removing one leading space from each', () => { + const doc = parseDocComment(lines(' Greets someone.', '', ' Indented **Markdown**.')); + assert.equal(doc.description, 'Greets someone.\n\n Indented **Markdown**.'); + }); + + it('drops leading and trailing empty description lines', () => { + assert.equal(parseDocComment(lines('', ' Text', ' ')).description, 'Text'); + assert.equal(parseDocComment(lines('', '')).description, ''); + }); + + it('treats "--- @tag" as description text, as the reference writes tags as "---@tag"', () => { + const doc = parseDocComment(lines(' @param x integer')); + assert.equal(doc.description, '@param x integer'); + assert.deepEqual(doc.params, []); + }); + + it('parses @param with optional marker, vararg, type and description', () => { + const doc = parseDocComment(lines('@param name string The name.', '@param count? integer', '@param ... any Values.')); + assert.deepEqual( + doc.params.map(({ name, optional, type, description }) => ({ name, optional, type, description })), + [ + { name: 'name', optional: false, type: 'string', description: 'The name.' }, + { name: 'count', optional: true, type: 'integer', description: '' }, + { name: '...', optional: false, type: 'any', description: 'Values.' }, + ], + ); + // The name span excludes `?`. + assert.deepEqual(doc.params[1]?.nameSpan, { start: 107, end: 112 }); + assert.deepEqual(doc.params[0]?.nameSpan, { start: 7, end: 11 }); + }); + + it('keeps @param descriptions verbatim', () => { + assert.equal(parseDocComment(lines('@param x integer # the count')).params[0]?.description, '# the count'); + }); + + it('parses the @return forms of the reference', () => { + const returns = parseDocComment( + lines('@return boolean enabled If the item is enabled', '@return boolean # If the item is enabled', '@return boolean ok # true on success', '@return string ...', '@return integer'), + ).tags.map((tag) => (tag.tag === 'return' ? tag.value : undefined)); + assert.deepEqual(returns, [ + { type: 'boolean', name: 'enabled', description: 'If the item is enabled' }, + { type: 'boolean', name: undefined, description: 'If the item is enabled' }, + { type: 'boolean', name: 'ok', description: 'true on success' }, + { type: 'string', name: '...', description: '' }, + { type: 'integer', name: undefined, description: '' }, + ]); + }); + + it('parses @type, @deprecated and @see, in source order', () => { + const doc = parseDocComment(lines('@deprecated', '@type string | nil', '@see Other')); + assert.deepEqual(doc.tags, [{ tag: 'deprecated' }, { tag: 'type', type: 'string | nil' }, { tag: 'see', symbol: 'Other' }]); + }); + + it('recognises other tags and union continuation lines without rendering them', () => { + const doc = parseDocComment(lines(' Text.', '@class Point', '@field x number', '@nodiscard', '|"\'immediate\'" # comment', '@unknown')); + assert.equal(doc.description, 'Text.'); + assert.deepEqual(doc.tags, []); + assert.deepEqual(doc.malformed, []); + }); + + it('reports @param without a name or type, and @return or @type without a type', () => { + const doc = parseDocComment(lines('@param', '@param x', '@param 1x integer', '@return', '@type ', '@paramx integer')); + assert.deepEqual( + doc.malformed.map(({ tag, reason, span }) => ({ tag, reason, span })), + [ + { tag: '@param', reason: 'paramName', span: { start: 0, end: 6 } }, + { tag: '@param', reason: 'paramType', span: { start: 100, end: 108 } }, + { tag: '@param', reason: 'paramName', span: { start: 200, end: 217 } }, + { tag: '@return', reason: 'type', span: { start: 300, end: 307 } }, + { tag: '@type', reason: 'type', span: { start: 400, end: 405 } }, + ], + ); + assert.deepEqual(doc.params, []); + }); + }); +}); From 312914350ef52908cff5ac85d697dc35a8d3e6e9 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:42:04 +0100 Subject: [PATCH 2/8] feat(server): show LuaCATS doc comments in hover MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Locals and the globals a document assigns now show the doc comment above their declaration (a global: above its first assignment, the site its code line already describes), and a parameter its own @param entry. The text is laid out as VS Code's TypeScript extension renders JSDoc (textRendering.ts): the description, then one paragraph per tag labelled `*@tag*`, the name in a code span and ` — ` before the text. LuaCATS types follow the name in a code span wide enough for any backticks. Tag names are syntax, so they are not translated. Plain text keeps the same layout without markup. The code line of the hover does not change. Completion targets carry the doc comment too; their documentation is unchanged until the next commit. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 ++++++++ docs/CHANGELOG.vsix.md | 4 ++ src/server/completion/candidates.ts | 14 ++++-- src/server/docComments/render.ts | 60 ++++++++++++++++++++++++++ src/server/hover/render.ts | 20 ++++++--- src/server/hover/resolve.ts | 30 +++++++++---- test/unit/server/hover/render.test.ts | 52 ++++++++++++++++++++++ test/unit/server/hover/resolve.test.ts | 18 ++++++++ 8 files changed, 199 insertions(+), 16 deletions(-) create mode 100644 src/server/docComments/render.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fd49ad..d2d21e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -182,6 +182,23 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). dropped or split text hid. - Titles are localized like the hover labels. Advertised only to clients that accept `CodeAction` literals (`codeActionLiteralSupport`). +- LuaCATS doc comments ([annotation reference](https://luals.github.io/wiki/annotations/)) on the + document's own code, in hover. Types are shown as written; nothing checks or infers them. + - A doc block is a run of `---` comments, each alone on its line, on consecutive lines; it + documents the statement that starts on the next line. A blank line detaches it, and `----` + banners and `---` after code are not doc comments. The reference does not state this rule; + its examples follow it. The same applies inside the Lua of `.menu` files. + - Documented: `local function f`, `local x = …` (one name), `function G()` and `G = …` (one + name), a global by the block above its first assignment, as its hover code line already is. + Each parameter shows its own `@param` entry, also for `function M.f(a)`, `function M:m(a)` + and `M.f = function(a) … end`, whose names have no hover. + - Rendered: the description (Markdown, one leading space removed from each line), then + `@param`, `@return`, `@type`, `@deprecated` and `@see` in the order written, laid out as VS + Code's own TypeScript hovers lay out JSDoc tags (``*@param* `name` — text``), with the type in + a code span after the name. The other reference tags (`@class`, `@field`, `@overload`, …) and + `---|` lines are not rendered and never show up as description. Tags are `---@tag`, as the + reference writes them; `--- @tag` stays description text. + - The code line of the hover does not change. - 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/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 979a7ff..0e8b40c 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -57,6 +57,10 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea 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" }`. +- **Your own documentation on hover.** Write doc comments in the LuaCATS style used by other Lua + tools, `---` lines with `---@param`, `---@return`, `---@type`, `---@deprecated` and `---@see`, + right above a function or variable, and hovering it shows the description and tags. Hovering a + parameter shows its `---@param` line. - **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/src/server/completion/candidates.ts b/src/server/completion/candidates.ts index 5690fc4..7a75459 100644 --- a/src/server/completion/candidates.ts +++ b/src/server/completion/candidates.ts @@ -26,6 +26,7 @@ // The manual data covers only the libraries the engine opens, so `io`, `os`, // `require` and `coroutine` are never offered. +import { docCommentFor, parameterDoc } from '../docComments/attach.ts'; import type { HoverTarget } from '../hover/resolve.ts'; import { allExternalEntries, @@ -81,12 +82,19 @@ const isFunctionValue = (site: DeclarationSite | undefined): boolean => site?.kind === 'localFunction' || site?.kind === 'functionDeclaration' || ((site?.kind === 'local' || site?.kind === 'assignment') && site.value?.kind === 'FunctionExpression'); function localCandidate(document: ParsedDocument, declaration: Declaration): Candidate { - const site = declaration.identifier && declarationSite(document, declaration.identifier); + const { identifier } = declaration; + const site = identifier && declarationSite(document, identifier); return { label: declaration.name, kind: isFunctionValue(site) ? 'function' : 'variable', group: CandidateGroup.Local, - target: { kind: 'local', declaration, site }, + target: { + kind: 'local', + declaration, + site, + doc: identifier && docCommentFor(document, identifier), + param: identifier && declaration.kind === 'parameter' ? parameterDoc(document, identifier) : undefined, + }, }; } @@ -136,7 +144,7 @@ function documentGlobals(document: ParsedDocument): readonly Candidate[] { list = [...assigned].map((name): Candidate => { const write = firstWrites.get(name); const site = write && declarationSite(document, write); - return { label: name, kind: isFunctionValue(site) ? 'function' : 'variable', group: CandidateGroup.Document, target: { kind: 'global', name, site, link: externalEntry(name) } }; + return { label: name, kind: isFunctionValue(site) ? 'function' : 'variable', group: CandidateGroup.Document, target: { kind: 'global', name, site, doc: write && docCommentFor(document, write), link: externalEntry(name) } }; }); documentGlobalLists.set(document, list); } diff --git a/src/server/docComments/render.ts b/src/server/docComments/render.ts new file mode 100644 index 0000000..1d77fa8 --- /dev/null +++ b/src/server/docComments/render.ts @@ -0,0 +1,60 @@ +// LuaCATS doc comments as hover text. Pure: no LSP or `vscode` imports. +// +// The layout is the one VS Code's own TypeScript hovers give JSDoc +// (extensions/typescript-language-features/src/languageFeatures/util/textRendering.ts): +// the description, a blank line, then one paragraph per tag, labelled with the +// tag in italics (`*@param*`), its parameter name in a code span, and ` — ` before +// the text. Tag names are syntax, so they are not translated. LuaCATS adds types, +// which follow the name in a code span of their own. In plain text the same +// layout is written without markup. + +import type { DocComment, DocParam, DocTag } from './parse.ts'; + +export type DocFormat = 'markdown' | 'plaintext'; + +/** `text` as a Markdown code span, with enough backticks that none inside closes it. */ +export function codeSpan(text: string): string { + const longest = Math.max(0, ...[...text.matchAll(/`+/g)].map((run) => run[0].length)); + const fence = '`'.repeat(longest + 1); + // CommonMark strips one space from each end when both are spaces, and a + // backtick at either end would join the fence. + const pad = text.startsWith('`') || text.endsWith('`') || (text.startsWith(' ') && text.endsWith(' ')) ? ' ' : ''; + return `${fence}${pad}${text}${pad}${fence}`; +} + +/** A tag line: the label, its code parts, then ` — ` and the text when there is one. */ +function tagLine(tag: string, code: readonly string[], text: string, format: DocFormat): string { + const label = format === 'markdown' ? `*@${tag}*` : `@${tag}`; + const parts = [label, ...code.map((part) => (format === 'markdown' ? codeSpan(part) : part))].join(' '); + return text ? `${parts} — ${text}` : parts; +} + +/** The line of one `@param` entry. */ +export function renderParam(param: DocParam, format: DocFormat): string { + return tagLine('param', [param.optional ? `${param.name}?` : param.name, param.type], param.description, format); +} + +function renderTag(tag: DocTag, format: DocFormat): string { + switch (tag.tag) { + case 'param': + return renderParam(tag.param, format); + case 'return': { + const { type, name, description } = tag.value; + return tagLine('return', name === undefined ? [type] : [type, name], description, format); + } + case 'type': + return tagLine('type', [tag.type], '', format); + case 'deprecated': + return tagLine('deprecated', [], '', format); + case 'see': + return tagLine('see', [], tag.symbol, format); + } +} + +/** The description and tags of `doc`, or `undefined` when it has neither. */ +export function renderDocComment(doc: DocComment, format: DocFormat): string | undefined { + // VS Code ends each tag paragraph with a hard line break (` \n\n`). + const tags = doc.tags.map((tag) => renderTag(tag, format)).join(format === 'markdown' ? ' \n\n' : '\n'); + const parts = [doc.description, tags].filter((part) => part !== ''); + return parts.length > 0 ? parts.join('\n\n') : undefined; +} diff --git a/src/server/hover/render.ts b/src/server/hover/render.ts index d8d2b95..6e28787 100644 --- a/src/server/hover/render.ts +++ b/src/server/hover/render.ts @@ -4,8 +4,10 @@ // Layout: the name as Lua (a code block in Markdown), then the documentation, // then where it comes from. Documentation quoted from the Lua manual is // verbatim; only the server's own words (`parameter`, `global`, the note on -// engine replacements) are localized. +// engine replacements) are localized. The document's own LuaCATS doc comments +// are rendered by docComments/render.ts. +import { renderDocComment, renderParam } from '../docComments/render.ts'; import type { Messages } from '../l10n.ts'; import type * as Ast from '../syntax/ast.ts'; import { parameterList, type DeclarationSite } from '../syntax/signatures.ts'; @@ -59,10 +61,18 @@ interface Parts { function parts(target: HoverTarget, format: HoverFormat, messages: Messages): Parts { const linkText = (link: Link): string => (format === 'markdown' ? `[${link.text}](${link.url})` : `${link.text} (${link.url})`); switch (target.kind) { - case 'local': - return { code: localSignature(target, messages) }; - case 'global': - return { code: globalSignature(target.name, target.site, messages), ...(target.link ? { link: externalLink(target.link) } : {}) }; + case 'local': { + const documentation = target.param ? renderParam(target.param, format) : target.doc && renderDocComment(target.doc, format); + return { code: localSignature(target, messages), ...(documentation === undefined ? {} : { documentation }) }; + } + case 'global': { + const documentation = target.doc && renderDocComment(target.doc, format); + return { + code: globalSignature(target.name, target.site, messages), + ...(documentation === undefined ? {} : { documentation }), + ...(target.link ? { link: externalLink(target.link) } : {}), + }; + } case 'library': return { code: target.entry.heading, documentation: format === 'markdown' ? target.entry.markdown : target.entry.plaintext, link: manualLink(target.entry) }; case 'engineReplaced': { diff --git a/src/server/hover/resolve.ts b/src/server/hover/resolve.ts index 6aa1b46..6083781 100644 --- a/src/server/hover/resolve.ts +++ b/src/server/hover/resolve.ts @@ -1,9 +1,11 @@ // What a hover describes: the name under the cursor and what it refers to. // Pure: no LSP or `vscode` imports. // -// - A local: its declaration (`local function f(a)`, a parameter, …). +// - A local: its declaration (`local function f(a)`, a parameter, …), and its +// LuaCATS doc comment or `@param` entry (docComments/attach.ts). // - A global: shared by all chunks of a .menu file, as in navigation.ts. -// 1. Assigned in this document: described by its first assignment; the +// 1. Assigned in this document: described by its first assignment (and the +// doc comment above it); the // document's own definition wins over the libraries (an EEex-Docs link is // still given, since a link makes no claim about behaviour). // 2. Replaced by the engine (`print`): a note instead of the manual text. @@ -20,6 +22,8 @@ // Names resolved through a local `_ENV` are fields of that table, so they get // no hover. Without type inference that is the only safe answer. +import { docCommentFor, parameterDoc } from '../docComments/attach.ts'; +import type { DocComment, DocParam } from '../docComments/parse.ts'; import type * as Ast from '../syntax/ast.ts'; import type { ParsedDocument } from '../syntax/document.ts'; import { fieldWrites, globalPath, withoutG } from '../syntax/globalPaths.ts'; @@ -30,9 +34,13 @@ import { declarationSite, type DeclarationSite } from '../syntax/signatures.ts'; import { engineReplacement, externalEntry, manualEntry, type EngineReplacement, type ExternalEntry, type ManualEntry } from './knowledge.ts'; export type HoverTarget = - | { readonly kind: 'local'; readonly declaration: Declaration; readonly site: DeclarationSite | undefined } - /** A global without documentation; `site` is its first assignment in the document, if any. */ - | { readonly kind: 'global'; readonly name: string; readonly site: DeclarationSite | undefined; readonly link: ExternalEntry | undefined } + /** `doc`: the doc comment of its declaration; `param`: the `@param` entry of a parameter (docComments/attach.ts). */ + | { readonly kind: 'local'; readonly declaration: Declaration; readonly site: DeclarationSite | undefined; readonly doc: DocComment | undefined; readonly param: DocParam | undefined } + /** + * A global without library documentation; `site` is its first assignment in + * the document, if any, and `doc` the doc comment of that assignment. + */ + | { readonly kind: 'global'; readonly name: string; readonly site: DeclarationSite | undefined; readonly doc: DocComment | undefined; readonly link: ExternalEntry | undefined } | { readonly kind: 'library'; readonly entry: ManualEntry } | { readonly kind: 'engineReplaced'; readonly replacement: EngineReplacement; readonly entry: ManualEntry | undefined } | { readonly kind: 'external'; readonly entry: ExternalEntry }; @@ -81,16 +89,22 @@ function knownGlobal(name: string): HoverTarget | undefined { function globalTarget(document: ParsedDocument, name: string): HoverTarget { const write = firstWrite(document, name); if (write) { - return { kind: 'global', name, site: declarationSite(document, write), link: externalEntry(name) }; + return { kind: 'global', name, site: declarationSite(document, write), doc: docCommentFor(document, write), link: externalEntry(name) }; } - return knownGlobal(name) ?? { kind: 'global', name, site: undefined, link: undefined }; + return knownGlobal(name) ?? { kind: 'global', name, site: undefined, doc: undefined, link: 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) }; + return { + kind: 'local', + declaration: target.declaration, + site: declaring && declarationSite(document, declaring), + doc: declaring && docCommentFor(document, declaring), + param: declaring && target.declaration.kind === 'parameter' ? parameterDoc(document, declaring) : undefined, + }; } // A field of a local `_ENV` table, or `_ENV` itself (the chunk's upvalue, not a global). const scopes = document.chunks[chunkIndex]?.scopes; diff --git a/test/unit/server/hover/render.test.ts b/test/unit/server/hover/render.test.ts index 9b4830b..5c5c363 100644 --- a/test/unit/server/hover/render.test.ts +++ b/test/unit/server/hover/render.test.ts @@ -56,6 +56,58 @@ describe('server/hover/render', () => { }); }); + describe('doc comments', () => { + const text = [ + '--- Greets someone.', + '---', + '--- Uses **Markdown**.', + '---@param name string The name.', + '---@param times? integer', + '---@return string greeting # The text.', + '---@deprecated', + '---@see Other', + 'local function greet(name, times) end', + '---@type integer', + 'Count = 0', + '--- Redefined.', + 'Infinity_DisplayString = nil', + ].join('\n'); + + it('renders the description, then each tag as VS Code renders JSDoc tags', () => { + assert.equal( + render(text, 'greet('), + `${fence('local function greet(name, times)')}\n\n---\n\nGreets someone.\n\nUses **Markdown**.\n\n` + + '*@param* `name` `string` — The name. \n\n*@param* `times?` `integer` \n\n*@return* `string` `greeting` — The text. \n\n*@deprecated* \n\n*@see* — Other', + ); + }); + + it('renders plain text without markup', () => { + assert.equal( + render(text, 'greet(', 'plaintext'), + 'local function greet(name, times)\n\nGreets someone.\n\nUses **Markdown**.\n\n' + + '@param name string — The name.\n@param times? integer\n@return string greeting — The text.\n@deprecated\n@see — Other', + ); + }); + + it('shows a parameter\'s own @param entry', () => { + assert.equal(render(text, 'name, times)'), `${fence('(parameter) name')}\n\n---\n\n*@param* \`name\` \`string\` — The name.`); + assert.equal(render(text, 'times)', 'plaintext'), '(parameter) times\n\n@param times? integer'); + }); + + it('documents a global by the doc comment of its first assignment, before its EEex-Docs link', () => { + assert.equal(render(text, 'Count'), `${fence('(global) Count')}\n\n---\n\n*@type* \`integer\``); + assert.match(render(text, 'Infinity'), /^```lua\n\(global\) Infinity_DisplayString\n```\n\n---\n\nRedefined\.\n\n---\n\n\[EE Game Lua Functions\]/); + }); + + it('widens code spans around types that contain backticks', () => { + assert.match(render('---@type `a`\nX = 1', 'X'), /\*@type\* `` `a` ``$/); + }); + + it('gives no documentation for a doc block without description or rendered tags', () => { + assert.equal(render('---@class Point\nlocal p = {}', 'p ='), fence('local p')); + }); + }); + describe('libraries', () => { it('quotes the manual entry with its heading and a link to its section', () => { assert.equal( diff --git a/test/unit/server/hover/resolve.test.ts b/test/unit/server/hover/resolve.test.ts index e594c21..df2c5ff 100644 --- a/test/unit/server/hover/resolve.test.ts +++ b/test/unit/server/hover/resolve.test.ts @@ -55,6 +55,24 @@ describe('server/hover/resolve', () => { assert.equal(hover(text, 'return G', { offset: 7 }), 'G -> global G assignment -'); }); + it('attaches the doc comment of the declaration, at every use, and parameters\' @param entries', () => { + const text = '--- F.\n---@param a integer\nlocal function f(a) return a end\nreturn f'; + const at = (needle: string, from = 0): HoverTarget | undefined => hoverTargetAt(parseDocument(text, 'lua'), text.indexOf(needle, from))?.target; + const use = at('f', text.indexOf('return f')); + assert.equal(use?.kind === 'local' && use.doc?.description, 'F.'); + const parameter = at('a', text.indexOf('return a')); + assert.ok(parameter?.kind === 'local'); + assert.equal(parameter.doc, undefined); + assert.equal(parameter.param?.type, 'integer'); + }); + + it('documents a global by its first assignment only', () => { + const text = 'G = 1\n--- Later.\nG = 2\nreturn G'; + const target = hoverTargetAt(parseDocument(text, 'lua'), text.indexOf('return G') + 7)?.target; + assert.ok(target?.kind === 'global'); + assert.equal(target.doc, undefined); + }); + 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); From ec5ee7e129780f5a64f341baa829c68fac86d33b Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:43:10 +0100 Subject: [PATCH 3/8] feat(server): add doc comments to completion items A local or document global with a LuaCATS doc comment, and a parameter with a @param entry, now carries the same documentation as its hover. It is rendered when the list is built, in the client's documentation format, and the item has no `data`: `completionItem/resolve` names no document, so resolving later could look the name up in a newer version of it. Items without a doc comment are resolved as before. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++++-- docs/CHANGELOG.vsix.md | 4 ++-- src/server/features/completion.ts | 24 +++++++++++++++++--- test/unit/server/features/completion.test.ts | 23 ++++++++++++++++++- 4 files changed, 50 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2d21e0..0a3eb85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -183,7 +183,7 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). - Titles are localized like the hover labels. Advertised only to clients that accept `CodeAction` literals (`codeActionLiteralSupport`). - LuaCATS doc comments ([annotation reference](https://luals.github.io/wiki/annotations/)) on the - document's own code, in hover. Types are shown as written; nothing checks or infers them. + document's own code, in hover and completion. Types are shown as written; nothing checks or infers them. - A doc block is a run of `---` comments, each alone on its line, on consecutive lines; it documents the statement that starts on the next line. A blank line detaches it, and `----` banners and `---` after code are not doc comments. The reference does not state this rule; @@ -198,7 +198,10 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). a code span after the name. The other reference tags (`@class`, `@field`, `@overload`, …) and `---|` lines are not rendered and never show up as description. Tags are `---@tag`, as the reference writes them; `--- @tag` stays description text. - - The code line of the hover does not change. + - The code line of the hover, and the `detail` of a completion item, do not change. + - Completion items of documented names carry the same text as their hover in `documentation`, + sent with the list rather than on `completionItem/resolve`: the resolve request names no + document, so a later lookup could read a newer version of it. - 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/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 0e8b40c..30e1302 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -59,8 +59,8 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea `"editor.codeActionsOnSave": { "source.fixAll.ieLua": "explicit" }`. - **Your own documentation on hover.** Write doc comments in the LuaCATS style used by other Lua tools, `---` lines with `---@param`, `---@return`, `---@type`, `---@deprecated` and `---@see`, - right above a function or variable, and hovering it shows the description and tags. Hovering a - parameter shows its `---@param` line. + right above a function or variable, and hovering it shows the description and tags, as does + its code completion suggestion. Hovering a parameter shows its `---@param` line. - **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/src/server/features/completion.ts b/src/server/features/completion.ts index 9234dc2..8fbd233 100644 --- a/src/server/features/completion.ts +++ b/src/server/features/completion.ts @@ -1,9 +1,10 @@ -import type { CompletionItem, CompletionList, Connection, Range, TextDocuments } from 'vscode-languageserver/node'; +import type { CompletionItem, CompletionList, Connection, MarkupContent, Range, TextDocuments } from 'vscode-languageserver/node'; import { CompletionItemKind, InsertReplaceEdit, MarkupKind, TextEdit } from 'vscode-languageserver/node'; import type { TextDocument } from 'vscode-languageserver-textdocument'; import { completionCandidates, documentationSource, documentationTarget, type Candidate, type CandidateKind } from '../completion/candidates.ts'; import type { ParsedDocumentCache } from '../documentCache.ts'; import { renderDocumentation, renderSignature, type HoverFormat } from '../hover/render.ts'; +import type { HoverTarget } from '../hover/resolve.ts'; import type { Messages } from '../l10n.ts'; import { completionSiteAt } from '../syntax/completionContext.ts'; @@ -35,6 +36,20 @@ const ITEM_KINDS: Readonly> = { keyword: CompletionItemKind.Keyword, }; +const markup = (value: string, format: HoverFormat): MarkupContent => ({ kind: format === 'markdown' ? MarkupKind.Markdown : MarkupKind.PlainText, value }); + +/** + * The documentation of a target documented by a doc comment of the document + * (docComments/), rendered now: `completionItem/resolve` names no document, and + * looking the name up again later could find a newer version of it. Only names + * with a doc comment pay for this. + */ +function documentDocumentation(target: HoverTarget | undefined, format: HoverFormat, messages: Messages): MarkupContent | undefined { + const documented = (target?.kind === 'local' && (target.doc !== undefined || target.param !== undefined)) || (target?.kind === 'global' && target.doc !== undefined); + const value = documented ? renderDocumentation(target, format, messages) : undefined; + return value === undefined ? undefined : markup(value, format); +} + /** * The completion list for candidates. `insert` is the name before the cursor, * `replace` the whole name around it; clients without insert/replace support @@ -43,7 +58,9 @@ const ITEM_KINDS: Readonly> = { export function toCompletionList(candidates: readonly Candidate[], insert: Range, replace: Range, options: CompletionClientOptions, messages: Messages): CompletionList { const editRange = options.insertReplace ? { insert, replace } : insert; const items = candidates.map((candidate): CompletionItem => { - const data = documentationSource(candidate.target); + const documentation = documentDocumentation(candidate.target, options.format, messages); + // Documentation sent now needs nothing to resolve. + const data = documentation ? undefined : documentationSource(candidate.target); let textEdit: TextEdit | InsertReplaceEdit | undefined; if (!options.defaultEditRange) { textEdit = options.insertReplace ? InsertReplaceEdit.create(candidate.label, insert, replace) : TextEdit.replace(insert, candidate.label); @@ -53,6 +70,7 @@ export function toCompletionList(candidates: readonly Candidate[], insert: Range kind: ITEM_KINDS[candidate.kind], sortText: String(candidate.group), ...(candidate.target ? { detail: renderSignature(candidate.target, messages) } : {}), + ...(documentation ? { documentation } : {}), ...(data ? { data } : {}), ...(textEdit ? { textEdit } : {}), }; @@ -65,7 +83,7 @@ export function resolveCompletionItem(item: CompletionItem, format: HoverFormat, const target = documentationTarget(item.data); const documentation = target && renderDocumentation(target, format, messages); if (documentation === undefined) return item; - return { ...item, documentation: { kind: format === 'markdown' ? MarkupKind.Markdown : MarkupKind.PlainText, value: documentation } }; + return { ...item, documentation: markup(documentation, format) }; } /** `textDocument/completion` and `completionItem/resolve` (see src/server/completion/). */ diff --git a/test/unit/server/features/completion.test.ts b/test/unit/server/features/completion.test.ts index 8eba493..6233c51 100644 --- a/test/unit/server/features/completion.test.ts +++ b/test/unit/server/features/completion.test.ts @@ -1,9 +1,11 @@ import assert from 'node:assert/strict'; import { CompletionItemKind, MarkupKind, type CompletionItem, type Range } from 'vscode-languageserver/node'; -import type { Candidate } from '../../../../src/server/completion/candidates.ts'; +import { completionCandidates, type Candidate } from '../../../../src/server/completion/candidates.ts'; import { resolveCompletionItem, toCompletionList, type CompletionClientOptions } from '../../../../src/server/features/completion.ts'; import { allManualEntries, externalEntry } from '../../../../src/server/hover/knowledge.ts'; import { createMessages } from '../../../../src/server/l10n.ts'; +import { completionSiteAt } from '../../../../src/server/syntax/completionContext.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; const english = createMessages(undefined); const insert: Range = { start: { line: 1, character: 4 }, end: { line: 1, character: 6 } }; @@ -34,6 +36,25 @@ describe('server/features/completion', () => { ]); }); + it('sends the documentation of doc comments with the item, in the client format, and no data to resolve', () => { + const text = '--- Adds.\n---@param a integer\nlocal function add(a)\n return a\nend\n--- Redefined.\nInfinity_DisplayString = nil\nlocal plain\nreturn '; + const document = parseDocument(text, 'lua'); + const site = completionSiteAt(document, text, text.length); + assert.ok(site); + const found = completionCandidates(document, site).filter((candidate) => ['add', 'plain', 'Infinity_DisplayString'].includes(candidate.label)); + const items = (format: CompletionClientOptions['format']): CompletionItem[] => toCompletionList(found, insert, replace, options({ format, defaultEditRange: true }), english).items; + const [add, plain, eeex] = items('markdown'); + assert.ok(add && plain && eeex); + assert.deepEqual(add.documentation, { kind: MarkupKind.Markdown, value: 'Adds.\n\n*@param* `a` `integer`' }); + assert.equal(add.data, undefined); + assert.equal(plain.documentation, undefined); + // The doc comment and the EEex-Docs link, which needs no resolving either. + assert.ok(typeof eeex.documentation === 'object'); + assert.match(eeex.documentation.value, /^Redefined\.\n\n---\n\n\[EE Game Lua Functions\]/); + assert.equal(eeex.data, undefined); + assert.deepEqual(items('plaintext')[0]?.documentation, { kind: MarkupKind.PlainText, value: 'Adds.\n\n@param a integer' }); + }); + it('sends the edit range once when the client supports item defaults', () => { assert.deepEqual(toCompletionList(candidates, insert, replace, options({ defaultEditRange: true }), english).itemDefaults, { editRange: insert }); assert.deepEqual(toCompletionList(candidates, insert, replace, options({ defaultEditRange: true, insertReplace: true }), english).itemDefaults, { From bd0687c99e833d177d8a7969821a6b0ddd7096ab Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:43:40 +0100 Subject: [PATCH 4/8] feat(server): publish doc comment problems as diagnostics The doc-tag-malformed, doc-param-unknown and doc-param-duplicate warnings of docComments/check.ts are published with the syntax diagnostics, under the same ieLua.validate.mode rules and source, in the client's locale. The diagnostics feature now takes the shared parse cache and the server messages. None of the new codes has a quick fix: the right name or type is not known. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++++++- docs/CHANGELOG.vsix.md | 4 +++- src/server/features/diagnostics.ts | 13 +++++++++++-- src/server/server.ts | 2 ++ 4 files changed, 24 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a3eb85..751627e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -183,7 +183,7 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). - Titles are localized like the hover labels. Advertised only to clients that accept `CodeAction` literals (`codeActionLiteralSupport`). - LuaCATS doc comments ([annotation reference](https://luals.github.io/wiki/annotations/)) on the - document's own code, in hover and completion. Types are shown as written; nothing checks or infers them. + document's own code, in hover, completion and diagnostics. Types are shown as written; nothing checks or infers them. - A doc block is a run of `---` comments, each alone on its line, on consecutive lines; it documents the statement that starts on the next line. A blank line detaches it, and `----` banners and `---` after code are not doc comments. The reference does not state this rule; @@ -202,6 +202,13 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). - Completion items of documented names carry the same text as their hover in `documentation`, sent with the list rather than on `completionItem/resolve`: the resolve request names no document, so a later lookup could read a newer version of it. + - Diagnostics (warnings, published with the others under `ieLua.validate.mode`; codes are + stable): `doc-tag-malformed` for `---@param` without a name or type and `---@return` or + `---@type` without a type, in any doc block; `doc-param-unknown` for a `---@param` the + documented function does not have (`...` needs a vararg function, `self` a method), checked + only where the statement writes the function itself, never for a call result; and + `doc-param-duplicate` for a parameter documented twice. Messages are localized like the hover + labels. - 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/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 30e1302..57d5aed 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -60,7 +60,9 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea - **Your own documentation on hover.** Write doc comments in the LuaCATS style used by other Lua tools, `---` lines with `---@param`, `---@return`, `---@type`, `---@deprecated` and `---@see`, right above a function or variable, and hovering it shows the description and tags, as does - its code completion suggestion. Hovering a parameter shows its `---@param` line. + its code completion suggestion. Hovering a parameter shows its `---@param` line. A warning + tells you when a `---@param` names a parameter the function doesn't have, documents one twice, + or misses its name or type. - **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/src/server/features/diagnostics.ts b/src/server/features/diagnostics.ts index 362029b..18d268b 100644 --- a/src/server/features/diagnostics.ts +++ b/src/server/features/diagnostics.ts @@ -3,6 +3,9 @@ import { DiagnosticSeverity } from 'vscode-languageserver/node'; import type { TextDocument } from 'vscode-languageserver-textdocument'; import { DIAGNOSTIC_SOURCE, ValidateDocumentRequest, type ValidateDocumentResult } from '../../shared/protocol.ts'; import { validatesOnSave, validatesOnType } from '../../shared/settings.ts'; +import { checkDocComments } from '../docComments/check.ts'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import type { Messages } from '../l10n.ts'; import type { SettingsStore } from '../settingsStore.ts'; import { Debouncer, type Timers } from '../validation/debouncer.ts'; import type { Lua52Checker } from '../validation/lua52.ts'; @@ -10,12 +13,17 @@ import { documentKind, validateText } from '../validation/validateText.ts'; export interface DiagnosticsDeps { readonly lua: Promise; + /** Parse results, for the doc-comment checks. */ + readonly cache: ParsedDocumentCache; + /** Messages in the client's locale (doc-comment problems). */ + readonly messages: Messages; readonly settings: SettingsStore; readonly timers: Timers; } /** - * Publishes syntax diagnostics according to `ieLua.validate.mode`: + * Publishes syntax diagnostics, and the problems of LuaCATS doc comments + * (docComments/check.ts), according to `ieLua.validate.mode`: * * | mode | on open/edit (debounced) | on save | `ieLua/validateDocument` | * | ------------- | ------------------------ | ------- | ------------------------ | @@ -40,7 +48,8 @@ export function register(connection: Connection, documents: TextDocuments ({ + const problems = [...validateText(document.getText(), documentKind(uri, document.languageId), lua), ...checkDocComments(deps.cache.get(document), deps.messages)]; + const diagnostics: Diagnostic[] = problems.map((problem) => ({ range: { start: document.positionAt(problem.start), end: document.positionAt(problem.end) }, severity: problem.severity === 'warning' ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error, source: DIAGNOSTIC_SOURCE, diff --git a/src/server/server.ts b/src/server/server.ts index c1e7b13..f3f4ad5 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -91,6 +91,8 @@ connection.onInitialize((params) => { const messages = createMessages(params.locale); const diagnosticsFeature = diagnostics.register(connection, documents, { lua, + cache: parsed, + messages, settings: new SettingsStore(connection, configurationPull, params.initializationOptions), timers: { setTimeout, clearTimeout: (handle) => { clearTimeout(handle as NodeJS.Timeout); } }, }); From 6d571bf59f95a01986f56ce393aed6787823c454 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:45:32 +0100 Subject: [PATCH 5/8] test: cover doc comments in hover, completion and diagnostics in VS Code Original fixtures doccomments.lua and DOCCOMMENTS.MENU, and integration tests for the hover of a documented local function, its parameter and globals (also in a .menu block), the documentation of a completion item, and the three doc diagnostics published by ieLua.validateDocument. Co-Authored-By: Claude Opus 5.5 --- test/fixtures/workspace/DOCCOMMENTS.MENU | 13 ++++ test/fixtures/workspace/doccomments.lua | 21 ++++++ test/integration/docComments.test.ts | 84 ++++++++++++++++++++++++ 3 files changed, 118 insertions(+) create mode 100644 test/fixtures/workspace/DOCCOMMENTS.MENU create mode 100644 test/fixtures/workspace/doccomments.lua create mode 100644 test/integration/docComments.test.ts diff --git a/test/fixtures/workspace/DOCCOMMENTS.MENU b/test/fixtures/workspace/DOCCOMMENTS.MENU new file mode 100644 index 0000000..21b8e0d --- /dev/null +++ b/test/fixtures/workspace/DOCCOMMENTS.MENU @@ -0,0 +1,13 @@ +` +--- Opens the doc menu. +---@param force boolean +function DocOpen(force) + return force +end +` + +menu +{ + name "DOC_MENU" + onOpen "DocOpen(true)" +} diff --git a/test/fixtures/workspace/doccomments.lua b/test/fixtures/workspace/doccomments.lua new file mode 100644 index 0000000..bebfffc --- /dev/null +++ b/test/fixtures/workspace/doccomments.lua @@ -0,0 +1,21 @@ +-- Original fixture: LuaCATS doc comments. + +--- Builds a greeting. +---@param name string Who to greet. +---@param times? integer +---@return string greeting # The text. +local function greet(name, times) + return string.rep("Hello, " .. name .. "! ", times or 1) +end + +---@type integer +DocCounter = 0 + +---@param missing string +---@param name string +---@param name string +---@return +function DocRefresh(name) + DocCounter = DocCounter + 1 + return greet(name) +end diff --git a/test/integration/docComments.test.ts b/test/integration/docComments.test.ts new file mode 100644 index 0000000..80f8798 --- /dev/null +++ b/test/integration/docComments.test.ts @@ -0,0 +1,84 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, openFixture, waitForDiagnostics } from './helpers.ts'; + +/** The position of the `occurrence`-th (0-based) `needle` of an open document. */ +function positionOf(document: vscode.TextDocument, needle: string, occurrence = 0): vscode.Position { + const text = document.getText(); + let offset = -1; + for (let i = 0; i <= occurrence; i++) { + offset = text.indexOf(needle, offset + 1); + assert.ok(offset >= 0, `"${needle}" #${String(i)} not found`); + } + return document.positionAt(offset); +} + +/** The Markdown hover text at the `occurrence`-th `needle` of a fixture. */ +async function hoverAt(file: string, needle: string, occurrence = 0): Promise { + const uri = await openFixture(file); + const document = await vscode.workspace.openTextDocument(uri); + const hovers = await vscode.commands.executeCommand('vscode.executeHoverProvider', uri, positionOf(document, needle, occurrence)); + return hovers + .flatMap((hover) => + hover.contents.map((content) => { + assert.ok(content instanceof vscode.MarkdownString, 'expected Markdown hover content'); + return content.value; + }), + ) + .join('\n'); +} + +suite('Doc comments', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('hover shows the doc comment of a local function and the @param entry of its parameter', async () => { + assert.equal( + await hoverAt('doccomments.lua', 'greet(name, times)'), + '```lua\nlocal function greet(name, times)\n```\n\n---\n\nBuilds a greeting.\n\n' + + '*@param* `name` `string` — Who to greet. \n\n*@param* `times?` `integer` \n\n*@return* `string` `greeting` — The text.', + ); + assert.equal(await hoverAt('doccomments.lua', 'times or'), '```lua\n(parameter) times\n```\n\n---\n\n*@param* `times?` `integer`'); + }); + + test('hover documents a global by the doc comment of its first assignment, also in .menu files', async () => { + assert.equal(await hoverAt('doccomments.lua', 'DocCounter', 2), '```lua\n(global) DocCounter\n```\n\n---\n\n*@type* `integer`'); + assert.equal( + await hoverAt('DOCCOMMENTS.MENU', 'DocOpen', 1), + '```lua\n(global) function DocOpen(force)\n```\n\n---\n\nOpens the doc menu.\n\n*@param* `force` `boolean`', + ); + }); + + test('completion items of documented names carry the doc comment', async () => { + const uri = await openFixture('doccomments.lua'); + const document = await vscode.workspace.openTextDocument(uri); + // Inside `greet` in `return greet(name)`, where greet is visible. + const position = positionOf(document, 'greet(name)').translate(0, 2); + const list = await vscode.commands.executeCommand('vscode.executeCompletionItemProvider', uri, position); + const greet = list.items.find((item) => item.label === 'greet' || (typeof item.label === 'object' && item.label.label === 'greet')); + assert.ok(greet, 'no greet item'); + const documentation = greet.documentation; + assert.ok(documentation instanceof vscode.MarkdownString, 'expected Markdown documentation'); + assert.ok(documentation.value.startsWith('Builds a greeting.\n\n*@param* `name` `string` — Who to greet.'), documentation.value); + }); + + test('validation reports doc comment problems with their codes', async () => { + const uri = await openFixture('doccomments.lua'); + const document = await vscode.workspace.openTextDocument(uri); + const result = await vscode.commands.executeCommand<{ validated: boolean; diagnosticCount: number }>('ieLua.validateDocument', uri); + assert.equal(result.validated, true); + const diagnostics = await waitForDiagnostics(uri, (found) => found.length === 3); + const summary = diagnostics.map((diagnostic) => [diagnostic.code, document.getText(diagnostic.range), diagnostic.severity]); + assert.deepEqual(summary, [ + ['doc-param-unknown', 'missing', vscode.DiagnosticSeverity.Warning], + ['doc-param-duplicate', 'name', vscode.DiagnosticSeverity.Warning], + ['doc-tag-malformed', '@return', vscode.DiagnosticSeverity.Warning], + ]); + assert.ok(diagnostics.every((diagnostic) => diagnostic.source === 'IE Lua')); + }); +}); From 5114ba0afce3cd4e6195dc734bc1efcb65d2ae9d Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:46:03 +0100 Subject: [PATCH 6/8] docs: document LuaCATS doc comments README feature list and note, the editors guide (what you get, the placement rule, the rendered tags and the three warnings), the layout tables of CONTRIBUTING.md and CLAUDE.md. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 ++- CONTRIBUTING.md | 1 + README.md | 18 +++++++++++++++++- docs/editors/README.md | 16 ++++++++++++++-- 4 files changed, 34 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index bc7e914..addd8d0 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, `.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 | +| Purpose | Lua 5.2 language support (diagnostics, hover, completion, semantic tokens, formatting of `.lua` files, `.menu` quick fixes, document and workspace symbols, folding, LuaCATS doc comments in hover, completion and diagnostics, 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) | @@ -36,6 +36,7 @@ │ │ ├── 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) +│ │ ├── docComments/ # LuaCATS doc comments: parse, attach, render, check (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 ef3b336..89c97ca 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/docComments/` | LuaCATS doc comments: parsing, what each block documents, rendering and problems (pure) | | `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`) | diff --git a/README.md b/README.md index 41eaf41..2582f82 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,8 @@ 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**, **quick fixes** (`.menu` files), and **go to definition**, +> **workspace symbols**, **folding**, **quick fixes** (`.menu` files), **LuaCATS doc comments** +> in hover, completion and diagnostics, and **go to definition**, > **find references** and **rename** within a file; cross-file navigation, formatting of `.menu` > files and more are planned. @@ -76,6 +77,21 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the 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. +- **Your own documentation from doc comments.** Write [LuaCATS](https://luals.github.io/wiki/annotations/) + doc comments, the `---` style other Lua tools read, on the lines right above a function or + variable: + + ```lua + --- Builds a greeting. + ---@param name string Who to greet. + ---@return string greeting + local function greet(name) return "Hello, " .. name end + ``` + + Hover and completion then show the description and the `@param`, `@return`, `@type`, + `@deprecated` and `@see` tags, and hovering a parameter shows its `@param` line. Types are shown + as you write them; they are not checked. A warning points out a `---@param` that names a + parameter the function doesn't have, documents one twice, or misses its name or type. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors** through the Language Server Protocol. diff --git a/docs/editors/README.md b/docs/editors/README.md index 40de30a..5989705 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -62,14 +62,14 @@ node /path/to/server.js --stdio | Feature | LSP request | Notes | | --- | --- | --- | -| Syntax errors | `textDocument/publishDiagnostics` | When `validate.mode` says so (see above). In `.menu` files, also warnings for text the game misreads. | +| Syntax errors | `textDocument/publishDiagnostics` | When `validate.mode` says so (see above). In `.menu` files, also warnings for text the game misreads. Warnings for doc comments (see below). | | Document symbols (outline) | `textDocument/documentSymbol` | Nested when the editor supports it, otherwise a flat list with container names. | | Folding | `textDocument/foldingRange` | Whole lines; the closing line of each construct stays visible. | | Go to definition | `textDocument/definition` | The declaration of a local, or every assignment to a global, in the same file. | | Find references | `textDocument/references` | Every use of a local or global in the same file. | | 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. | +| Completion | `textDocument/completion`, `completionItem/resolve` | Triggered by `.` and `:`. Documentation is sent on resolve (with the item, for names with a doc comment), 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. | @@ -129,6 +129,18 @@ The `source.fixAll.ieLua` action applies every fix of the file, whether or not d 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. +Hover and completion also show [LuaCATS](https://luals.github.io/wiki/annotations/) doc comments: +a run of `---` lines, each alone on its line, directly above a `local function`, a `local` with +one name, a `function` with one name or an assignment to one global (a global uses the comment +above its first assignment). The description and the `---@param`, `---@return`, `---@type`, +`---@deprecated` and `---@see` tags are shown in the order written, as VS Code shows JSDoc tags; +a parameter shows its own `---@param` line. Types are shown as written and never checked. With +the other diagnostics, the server publishes three warnings for doc comments: +`doc-tag-malformed` (a `---@param` without a name or type, a `---@return` or `---@type` without a +type), `doc-param-unknown` (a `---@param` the function written below does not have) and +`doc-param-duplicate` (a parameter documented twice). Their messages 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. From 11f9aa341f739b985965b2945d284dbc678cf661 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:47:24 +0100 Subject: [PATCH 7/8] perf(server): find doc lines without scanning the whole text To tell whether a `---` comment is alone on its line, attach.ts searched back for the line break with lastIndexOf('\n') and lastIndexOf('\r'). LF files have no `\r`, so every doc line scanned back to the start of the text: quadratic. A generated 2.7 MB Lua file with 20,000 doc blocks took 27.4 s to analyze, which blocked the event loop on every publish. Scan back over the indentation only. The same file now takes 87 ms, and a 311 KB .menu file with 3,000 blocks 7 ms (was 122 ms). Co-Authored-By: Claude Opus 5.5 --- src/server/docComments/attach.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/server/docComments/attach.ts b/src/server/docComments/attach.ts index 72688ae..70581d5 100644 --- a/src/server/docComments/attach.ts +++ b/src/server/docComments/attach.ts @@ -48,10 +48,16 @@ export interface DocumentDocs { const NEXT_LINE = /^(?:\r\n|\n|\r)[ \t\v\f]*$/; /** The same at `lastIndex` (sticky): where the next line's first non-blank character is. */ const NEXT_LINE_AT = /(?:\r\n|\n|\r)[ \t\v\f]*/y; -const LINE_INDENT = /(?:^|[\r\n])[ \t\v\f]*$/; - -/** Whether only white space precedes `offset` on its line. */ -const aloneOnLine = (text: string, offset: number): boolean => LINE_INDENT.test(text.slice(Math.max(0, text.lastIndexOf('\n', offset - 1), text.lastIndexOf('\r', offset - 1)), offset)); +/** + * Whether only white space precedes `offset` on its line. Scans back over the + * indentation only: searching for the line break with `lastIndexOf` would scan + * the whole text for a `\r` that LF files never have. + */ +function aloneOnLine(text: string, offset: number): boolean { + let i = offset - 1; + while (i >= 0 && /[ \t\v\f]/.test(text[i] ?? '')) i--; + return i < 0 || text[i] === '\n' || text[i] === '\r'; +} const isDocLine = (text: string, comment: { readonly start: number; readonly end: number; readonly long: boolean }): boolean => !comment.long && text.startsWith('---', comment.start) && text[comment.start + 3] !== '-' && aloneOnLine(text, comment.start); From 7a24e652328ace41c738c290bc8cf6b289dd8d28 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:48:10 +0100 Subject: [PATCH 8/8] test: cover the doc comment renderer directly codeSpan (fence width, padding where a backtick or CommonMark's space stripping would change the text), blocks with only a description, only tags or nothing rendered, and @param lines with `?`, `...` and an empty description. Found missing in the project review of this branch. Co-Authored-By: Claude Opus 5.5 --- test/unit/server/docComments/render.test.ts | 45 +++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 test/unit/server/docComments/render.test.ts diff --git a/test/unit/server/docComments/render.test.ts b/test/unit/server/docComments/render.test.ts new file mode 100644 index 0000000..43d8663 --- /dev/null +++ b/test/unit/server/docComments/render.test.ts @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +import { parseDocComment, type DocLine } from '../../../../src/server/docComments/parse.ts'; +import { codeSpan, renderDocComment, renderParam } from '../../../../src/server/docComments/render.ts'; + +const lines = (...texts: string[]): DocLine[] => texts.map((text, i) => ({ text, start: i * 100 })); + +describe('server/docComments/render', () => { + describe('codeSpan', () => { + it('uses one backtick for text without any', () => { + assert.equal(codeSpan('string|nil'), '`string|nil`'); + }); + + it('uses more backticks than the longest run inside, padded where a backtick touches the fence', () => { + assert.equal(codeSpan('a`b'), '``a`b``'); + assert.equal(codeSpan('``x'), '``` ``x ```'); + assert.equal(codeSpan('x`'), '`` x` ``'); + }); + + it('pads text that starts and ends with a space, which CommonMark would strip', () => { + assert.equal(codeSpan(' x '), '` x `'); + assert.equal(codeSpan(' x'), '` x`'); + }); + }); + + describe('renderDocComment', () => { + it('gives nothing for a block without description or rendered tags', () => { + assert.equal(renderDocComment(parseDocComment(lines('@class Point', '@field x number')), 'markdown'), undefined); + }); + + it('gives the description alone, or the tags alone', () => { + assert.equal(renderDocComment(parseDocComment(lines(' Only text.')), 'markdown'), 'Only text.'); + assert.equal(renderDocComment(parseDocComment(lines('@deprecated', '@see Other')), 'markdown'), '*@deprecated* \n\n*@see* — Other'); + assert.equal(renderDocComment(parseDocComment(lines('@deprecated', '@see Other')), 'plaintext'), '@deprecated\n@see — Other'); + }); + }); + + describe('renderParam', () => { + it('marks optional parameters and leaves out an empty description', () => { + const [optional, vararg] = parseDocComment(lines('@param x? integer', '@param ... any Rest.')).params; + assert.ok(optional && vararg); + assert.equal(renderParam(optional, 'markdown'), '*@param* `x?` `integer`'); + assert.equal(renderParam(vararg, 'plaintext'), '@param ... any — Rest.'); + }); + }); +});