diff --git a/client/space_lua/ast.ts b/client/space_lua/ast.ts index f5f35784..8278a064 100644 --- a/client/space_lua/ast.ts +++ b/client/space_lua/ast.ts @@ -1,3 +1,5 @@ +import type { LuaFunctionDocumentation } from "../../plug-api/types/index.ts"; + type ASTContext = { ctx: ASTCtx; }; @@ -12,6 +14,8 @@ export type ASTCtx = { export type LuaBlock = { type: "Block"; statements: LuaStatement[]; + // Comments lexically owned by this block, in source order. + comments?: LuaComment[]; hasLabel?: boolean; hasGoto?: boolean; // the first duplicated label is recorded here for later eval @@ -26,6 +30,14 @@ export type LuaBlock = { hasFunctionDef?: boolean; } & ASTContext; +export type LuaComment = { + type: "Comment"; + /** Exact source text, including delimiters. */ + text: string; + kind: "line" | "long"; + ctx: ASTCtx; +}; + // STATEMENTS export type LuaReturnStatement = { type: "Return"; @@ -128,6 +140,7 @@ export type LuaFunctionBody = { type: "FunctionBody"; parameters: string[]; block: LuaBlock; + documentation?: LuaFunctionDocumentation; } & ASTContext; export type LuaAssignmentStatement = { diff --git a/client/space_lua/lua.grammar b/client/space_lua/lua.grammar index e0c4b9fe..add52faa 100644 --- a/client/space_lua/lua.grammar +++ b/client/space_lua/lua.grammar @@ -17,6 +17,8 @@ @top Chunk { Block } +@external tokens luaComment from "./lua_comment.js" { Comment } + kw { @specialize[@name={term}] } ckw { @extend[@name={term}] } list { term ("," term)* } @@ -202,16 +204,12 @@ TableConstructor { "{" (field (fieldsep field)* fieldsep?)? "}" } "0" $[xX] hex+ ("." hex+)? ($[pP] $[+\-]? digit+)? } - Comment { "--" ![\n\r]* } - space { ($[ \t\f] | "\\" $[\n\r])+ } newline { $[\n\r] | "\n\r" | "\r\n" } "..."[@name=Ellipsis] ".."[@name=Concat] - @precedence { Comment, minus } - minus {"-"} fieldsep { $[,;] } diff --git a/client/space_lua/lua_comment.js b/client/space_lua/lua_comment.js new file mode 100644 index 00000000..327a2dcf --- /dev/null +++ b/client/space_lua/lua_comment.js @@ -0,0 +1,59 @@ +import { ExternalTokenizer } from "@lezer/lr"; +import { Comment } from "./parse-lua.terms.js"; + +const DASH = 45; +const EQUALS = 61; +const LINE_FEED = 10; +const CARRIAGE_RETURN = 13; +const OPEN_BRACKET = 91; +const CLOSE_BRACKET = 93; + +/** Tokenizes Lua line and long comments, including arbitrary `=` depth. */ +export const luaComment = new ExternalTokenizer((input) => { + if (input.next !== DASH || input.peek(1) !== DASH) return; + + input.advance(2); + + if (input.next === OPEN_BRACKET) { + input.advance(); + let equalsCount = 0; + while (input.next === EQUALS) { + equalsCount++; + input.advance(); + } + + if (input.next === OPEN_BRACKET) { + input.advance(); + while (input.next !== -1) { + if (input.next === CLOSE_BRACKET) { + let matches = true; + for (let i = 0; i < equalsCount; i++) { + if (input.peek(i + 1) !== EQUALS) { + matches = false; + break; + } + } + if (matches && input.peek(equalsCount + 1) === CLOSE_BRACKET) { + input.advance(equalsCount + 2); + input.acceptToken(Comment); + return; + } + } + input.advance(); + } + + // An unfinished long comment is a syntax error, just like an unfinished + // long string, so deliberately do not emit a token. + return; + } + } + + while ( + input.next !== -1 && + input.next !== LINE_FEED && + input.next !== CARRIAGE_RETURN + ) { + input.advance(); + } + input.acceptToken(Comment); +}); diff --git a/client/space_lua/parse-lua.js b/client/space_lua/parse-lua.js index 71e506a6..a3dca69e 100644 --- a/client/space_lua/parse-lua.js +++ b/client/space_lua/parse-lua.js @@ -1,5 +1,6 @@ // This file was generated by lezer-generator. You probably shouldn't edit it. import { LRParser } from "@lezer/lr"; +import { luaComment } from "./lua_comment.js"; const spec_identifier = { __proto__: null, break: 16, @@ -45,9 +46,9 @@ const spec_identifier = { export const parser = LRParser.deserialize({ version: 14, states: - "LQO!ZQPOOOOQO'#Cc'#CcO!UQPO'#CaO!bQPOOOOQO'#F]'#F]O!vQQO'#CwO$]QPO'#F[OOQO'#F['#F[O$gQPO'#F[OOQO'#Eo'#EoO%vQPO'#EnOOQO'#FW'#FWOOQO'#Ev'#EvO%{QPO'#C_OOQO'#C_'#C_QOQPOOO!UQPO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Z#VQ$[#WQ$]#XQ$p#dQ$r#fQ%Q#uQ%S#yQ%U'lQ%V'nQ%W'pQ%X'rQ%Y'tQ%Z'vQ%['xQ%]'zQ%^'|S%d$R&ZW%o$f$i%x&cQ%s$gQ%v$jQ%w$kQ%y$mQ&]%gQ&b'kS&e%t(RQ&m%|Q&o&PQ&p&TQ&y(OQ&z'mQ&{'oQ&|'qQ&}'sQ'O'uQ'P'wQ'Q'yQ'R'{Q'S'}Q'X&hQ'd']Q'g(PR(U(VlRO]ac|#[#c#e#j%h%j&O&l'Z!^rTbdhlnx!O!l#P#Q#R#S#T#U#V#W#X#d#f#i#t#u$R%g%|&P&Z'](Vx!jm#y#{$g$k$m%a&T&V&h'j'l'n'p'r't'v'x'z'|w%m$f$i$j%t%x&c'k'm'o'q's'u'w'y'{'}(O(P(RfUO]ac#c#e#j%j&O&l'Z$OVTbdhlmnx!O!l#P#Q#R#S#T#U#V#W#X#d#f#i#t#u#y#{$R$f$g$i$j$k$m%a%g%t%x%|&P&T&V&Z&c&h']'j'k'l'm'n'o'p'q'r's't'u'v'w'x'y'z'{'|'}(O(P(R(VQ#_|Q$_#[R&^%hWpRr!j%mR$S!vQ!pmU%_#{%a&VU%q$f$i%xR'T&cZoRr!j!v%mW!dh!O#i#tR!tnQ%f$RR&g%tR$a#[R!XegXO]ac#c#e#j%j&O&l'ZR!`g", nodeNames: "⚠ Comment Chunk Block ; Label :: Name break Goto goto Scope do end WhileStatement while nil true false Ellipsis Number LiteralString Property . MemberExpression [ ] Parens ( ) FunctionCall : TableConstructor { FieldDynamic FieldProp FieldExp } , AggOrderBy order by OrderBy desc asc using function FuncBody ArgList nulls first last BinaryExpression or and CompareOp BitOp BitOp BitOp BitOp Concat ArithOp ArithOp ArithOp UnaryExpression not ArithOp BitOp LenOp FunctionDef Query query QueryClause FromClause from FieldList WhereClause where OrderByClause SelectClause select LimitClause limit OffsetClause offset GroupByClause group HavingClause having FilteredCall filter RepeatStatement repeat until IfStatement if then elseif else ForStatement for ForNumeric ForGeneric NameList in ExpList Function FuncName LocalFunction local Assign VarList Local AttNameList AttName Attrib ReturnStatement return", @@ -81,10 +82,10 @@ export const parser = LRParser.deserialize({ skippedNodes: [0, 1], repeatNodeCount: 12, tokenData: - "Dj~RuXY#fYZ$Q[]#f]^$_pq#fqr$grs$rst)`uv)evw)jwx)oxy.Wyz.]z{.b{|.g|}.l}!O.s!O!P/g!P!Q/|!Q!R0^!R![1u![!]3m!]!^3z!^!_4R!_!`4e!`!a4m!c!}5P!}#O5b#O#P#w#P#QCo#Q#RC|#R#S5P#T#o5P#o#pDR#p#qDW#q#rD]#r#sDb~#kS#y~XY#f[]#fpq#f#O#P#w~#zQYZ#f]^#f~$VP#x~]^$Y~$_O#x~~$dP#x~YZ$Ym$jP!_!`$mm$rO!Xmk$uXOY$rZ]$r^r$rrs%bs#O$r#O#P%g#P;'S$r;'S;=`'}<%lO$rk%gO#}kk%j]rs$rwx$r!Q![&c#O#P$r#T#U$r#U#V$r#Y#Z$r#b#c$r#f#g$r#h#i$r#i#j(T#l#m(v#n#o$rk&fZOY$rZ]$r^r$rrs%bs!Q$r!Q!['X![#O$r#O#P%g#P;'S$r;'S;=`'}<%lO$rk'[ZOY$rZ]$r^r$rrs%bs!Q$r!Q![$r![#O$r#O#P%g#P;'S$r;'S;=`'}<%lO$rk(QP;=`<%l$rk(WP#o#p(Zk(^R!Q![(g!c!i(g#T#Z(gk(jS!Q![(g!c!i(g#T#Z(g#q#r$rk(yR!Q![)S!c!i)S#T#Z)Sk)VR!Q![$r!c!i$r#T#Z$r~)eO$f~~)jO$c~~)oO$Z~k)rXOY)oZ])o^w)owx%bx#O)o#O#P*_#P;'S)o;'S;=`,u<%lO)ok*b]rs)owx)o!Q![+Z#O#P)o#T#U)o#U#V)o#Y#Z)o#b#c)o#f#g)o#h#i)o#i#j,{#l#m-n#n#o)ok+^ZOY)oZ])o^w)owx%bx!Q)o!Q![,P![#O)o#O#P*_#P;'S)o;'S;=`,u<%lO)ok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<%lO=|kATP;=`<%l=|kAZVO!_>x!_!`>f!`#P>x#P#QAW#Q;'S>x;'S;=`?[<%lO>xoAuT$gSO#PBU#P#QBh#Q;'SBU;'S;=`Bz<%lOBUkBXTO#PBU#P#QBh#Q;'SBU;'S;=`Bz<%lOBUkBkTO#PBU#P#Q%b#Q;'SBU;'S;=`Bz<%lOBUkB}P;=`<%lBUoCVPjP#P#QCYnC_O$hn~CdO$e~~CiOq~~CnO$Y~~CsOu~~CxP$[~!_!`$m", + tokenizers: [luaComment, 0, 1, 2, 3, 4], topRules: { Chunk: [0, 2] }, dynamicPrecedences: { 144: 1 }, specialized: [{ term: 135, get: (value) => spec_identifier[value] || -1 }], - tokenPrec: 4960, + tokenPrec: 0, }); diff --git a/client/space_lua/parse.test.ts b/client/space_lua/parse.test.ts index ec94f8f9..99732324 100644 --- a/client/space_lua/parse.test.ts +++ b/client/space_lua/parse.test.ts @@ -1,10 +1,6 @@ import { expect, test } from "vitest"; -import { - parseBlock, - parseExpressionString, - stripLuaComments, -} from "./parse.ts"; -import type { LuaNumberLiteral } from "./ast.ts"; +import { parseBlock, parseExpressionString, parseToAST } from "./parse.ts"; +import type { LuaFunctionStatement, LuaNumberLiteral } from "./ast.ts"; test("Test Lua parser", () => { // Basic block test @@ -110,21 +106,75 @@ test("Test Lua parser", () => { test("Test comment handling", () => { const code = ` -- Single line comment ---[[ Multi +--[====[ Multi line -comment ]] +comment ]====] f([[ hello -- yo ]])`; - const code2 = stripLuaComments(code); - expect(code2.length).toEqual(code.length); - console.log(code2); - console.log( - stripLuaComments(`e([==[ - --- Hello - ]==])`), - ); + const block = parseBlock(code); + expect(block.comments?.map((comment) => comment.text)).toEqual([ + "-- Single line comment", + "--[====[ Multi\nline\ncomment ]====]", + ]); + expect(block.comments?.map((comment) => comment.kind)).toEqual([ + "line", + "long", + ]); + expect( + parseToAST(code).children?.some((node) => node.type === "Comment"), + ).toBe(true); +}); + +test("comments can occur between expression tokens", () => { + const block = parseBlock("f(1, -- second argument\n2)"); + expect(block.comments?.[0].text).toBe("-- second argument"); + expect(block.statements).toHaveLength(1); +}); + +test("comment-only chunks parse and unfinished long comments fail", () => { + const block = parseBlock("-- nothing to execute"); + expect(block.statements).toEqual([]); + expect(block.comments?.[0].text).toBe("-- nothing to execute"); + expect(() => parseBlock("--[==[ unfinished")).toThrow(); +}); + +test("LuaLS doc comments annotate the following function", () => { + const block = parseBlock(`--- Adds two values. +---@param a number First value. +---@param b? number Optional second value. +---@return number sum +---@see API/math +function add(a, b) + return a + b +end`); + const fn = block.statements[0] as LuaFunctionStatement; + expect(fn.body.documentation).toEqual({ + description: "Adds two values.", + parameters: [ + { + name: "a", + type: "number", + description: "First value.", + optional: false, + }, + { + name: "b", + type: "number", + description: "Optional second value.", + optional: true, + }, + ], + returns: [{ type: "number", description: "sum" }], + see: "API/math", + }); +}); + +test("a blank line separates doc comments from declarations", () => { + const block = parseBlock("--- Not attached.\n\nfunction f() end"); + const fn = block.statements[0] as LuaFunctionStatement; + expect(fn.body.documentation).toBeUndefined(); }); test("Test query parsing", () => { diff --git a/client/space_lua/parse.ts b/client/space_lua/parse.ts index 48547ead..802b1240 100644 --- a/client/space_lua/parse.ts +++ b/client/space_lua/parse.ts @@ -1,8 +1,8 @@ import { lezerToParseTree } from "../../client/markdown_parser/parse_tree.ts"; import type { SyntaxNode } from "@lezer/common"; import { - cleanTree, type ParseTree, + renderToText, } from "@silverbulletmd/silverbullet/lib/tree"; // @ts-expect-error - Local generated JavaScript file without type definitions import { parser } from "./parse-lua.js"; @@ -12,6 +12,7 @@ import type { ASTCtx, LuaAttName, LuaBlock, + LuaComment, LuaExpression, LuaFunctionBody, LuaFunctionCallExpression, @@ -25,6 +26,7 @@ import type { LuaStatement, LuaTableField, } from "./ast.ts"; +import type { LuaFunctionDocumentation } from "../../plug-api/types/index.ts"; import { LuaAttribute } from "./ast.ts"; import { getBlockGotoMeta } from "./labels.ts"; import { LuaRuntimeError, LuaStackFrame } from "./runtime.ts"; @@ -67,7 +69,217 @@ function parseChunk(t: ParseTree, ctx: ASTCtx): LuaBlock { if (t.type !== "Chunk") { throw new Error(`Expected Chunk, got ${t.type}`); } - return parseBlockNode(t.children![0], ctx); + const block = t.children?.find((child) => child.type === "Block"); + if (!block) { + return { type: "Block", statements: [], ctx: context(t, ctx) }; + } + return parseBlockNode(block, ctx); +} + +function collectLuaComments(t: ParseTree, ctx: ASTCtx): LuaComment[] { + const comments: LuaComment[] = []; + const visit = (node: ParseTree) => { + if (node.type === "Comment") { + const text = renderToText(node); + comments.push({ + type: "Comment", + text, + kind: /^--\[(=*)\[/.test(text) ? "long" : "line", + ctx: context(node, ctx), + }); + return; + } + for (const child of node.children ?? []) visit(child); + }; + visit(t); + return comments.sort((a, b) => (a.ctx.from ?? 0) - (b.ctx.from ?? 0)); +} + +function withoutComments(t: ParseTree): ParseTree { + if (!t.children) return t; + return { + ...t, + children: t.children + .filter((child) => child.type !== "Comment") + .map(withoutComments), + }; +} + +function assignCommentsToBlocks( + root: LuaBlock, + comments: LuaComment[], + source: string, +): void { + const blocks: LuaBlock[] = []; + const seen = new WeakSet(); + const visit = (value: unknown, key?: string) => { + if (!value || typeof value !== "object" || key === "ctx") return; + if (seen.has(value)) return; + seen.add(value); + if ((value as { type?: string }).type === "Block") { + blocks.push(value as LuaBlock); + } + for (const [childKey, child] of Object.entries(value)) { + if ( + childKey !== "ctx" && + childKey !== "comments" && + childKey !== "documentation" + ) { + visit(child, childKey); + } + } + }; + visit(root); + + for (const comment of comments) { + const from = comment.ctx.from ?? 0; + const to = comment.ctx.to ?? from; + let owner = root; + let ownerSpan = Number.POSITIVE_INFINITY; + for (const block of blocks) { + if (block === root) continue; + const blockFrom = block.ctx.from; + const blockTo = block.ctx.to; + if (blockFrom === undefined || blockTo === undefined) continue; + const contains = blockFrom <= from && blockTo >= to; + const immediatelyBefore = + to <= blockFrom && !source.slice(to, blockFrom).trim(); + const immediatelyAfter = + blockTo <= from && !source.slice(blockTo, from).trim(); + if ( + (contains || immediatelyBefore || immediatelyAfter) && + blockTo - blockFrom < ownerSpan + ) { + owner = block; + ownerSpan = blockTo - blockFrom; + } + } + (owner.comments ??= []).push(comment); + } +} + +function parseFunctionDocumentation( + comments: LuaComment[], +): LuaFunctionDocumentation | undefined { + const description: string[] = []; + const parameters: NonNullable = []; + const returns: NonNullable = []; + let deprecated: string | boolean | undefined; + let see: string | undefined; + + for (const comment of comments) { + const line = comment.text.slice(3).replace(/^\s?/, ""); + const param = /^@param\s+(\S+)\s+(\S+)(?:\s+(.*))?$/.exec(line); + if (param) { + const optional = param[1].endsWith("?"); + parameters.push({ + name: optional ? param[1].slice(0, -1) : param[1], + type: param[2], + description: param[3] || undefined, + optional, + }); + continue; + } + const returnDoc = /^@return\s+(\S+)(?:\s+(.*))?$/.exec(line); + if (returnDoc) { + returns.push({ + type: returnDoc[1], + description: returnDoc[2] || undefined, + }); + continue; + } + const deprecatedDoc = /^@deprecated(?:\s+(.*))?$/.exec(line); + if (deprecatedDoc) { + deprecated = deprecatedDoc[1] || true; + continue; + } + const seeDoc = /^@see\s+(.+)$/.exec(line); + if (seeDoc) { + see = seeDoc[1]; + continue; + } + if (!line.startsWith("@")) description.push(line); + } + + const docs: LuaFunctionDocumentation = {}; + const descriptionText = description.join("\n").trim(); + if (descriptionText) docs.description = descriptionText; + if (parameters.length) docs.parameters = parameters; + if (returns.length) docs.returns = returns; + if (deprecated !== undefined) docs.deprecated = deprecated; + if (see) docs.see = see; + return Object.keys(docs).length ? docs : undefined; +} + +function attachFunctionDocumentation( + root: LuaBlock, + comments: LuaComment[], + source: string, +): void { + const candidates: { from: number; body: LuaFunctionBody }[] = []; + const seen = new WeakSet(); + const claimedBodies = new WeakSet(); + + const addCandidate = (from: number | undefined, body: LuaFunctionBody) => { + if (from === undefined || claimedBodies.has(body)) return; + claimedBodies.add(body); + candidates.push({ from, body }); + }; + + const visit = (value: unknown, key?: string) => { + if (!value || typeof value !== "object" || key === "ctx") return; + if (seen.has(value)) return; + seen.add(value); + const node = value as Record; + if (node.type === "Function" || node.type === "LocalFunction") { + addCandidate(node.ctx?.from, node.body); + } else if ( + (node.type === "Local" || node.type === "Assignment") && + node.expressions?.length === 1 && + node.expressions[0]?.type === "FunctionDefinition" + ) { + addCandidate(node.ctx?.from, node.expressions[0].body); + } else if (node.type === "FunctionDefinition") { + addCandidate(node.ctx?.from, node.body); + } + for (const [childKey, child] of Object.entries(node)) { + if ( + childKey !== "ctx" && + childKey !== "comments" && + childKey !== "documentation" + ) { + visit(child, childKey); + } + } + }; + visit(root); + + const docComments = comments.filter( + (comment) => comment.kind === "line" && comment.text.startsWith("---"), + ); + for (const candidate of candidates) { + const group: LuaComment[] = []; + let boundary = candidate.from; + for (let i = docComments.length - 1; i >= 0; i--) { + const comment = docComments[i]; + const from = comment.ctx.from ?? 0; + const to = comment.ctx.to ?? from; + if (to > boundary) continue; + const gap = source.slice(to, boundary); + const lineStart = source.lastIndexOf("\n", from - 1) + 1; + if ( + gap.trim() || + /\r?\n[ \t]*\r?\n/.test(gap) || + source.slice(lineStart, from).trim() + ) { + break; + } + group.unshift(comment); + boundary = from; + } + const documentation = parseFunctionDocumentation(group); + if (documentation) candidate.body.documentation = documentation; + } } function hasCloseLocal(names: LuaAttName[] | undefined): boolean { @@ -1589,112 +1801,13 @@ function parseTableField(t: ParseTree, ctx: ASTCtx): LuaTableField { } } -export function stripLuaComments(s: string): string { - let result = ""; - let i = 0; - - while (i < s.length) { - // Check for long string - if (s[i] === "[") { - let j = i + 1; - let equalsCount = 0; - while (s[j] === "=") { - equalsCount++; - j++; - } - if (s[j] === "[") { - // Found long string start - const openBracket = s.substring(i, j + 1); - const closeBracket = `]${"=".repeat(equalsCount)}]`; - result += openBracket; - i = j + 1; - - // Find matching closing bracket - const content = s.substring(i); - const closeIndex = content.indexOf(closeBracket); - if (closeIndex !== -1) { - // Copy string content verbatim, including any comment-like sequences - result += content.substring(0, closeIndex) + closeBracket; - i += closeIndex + closeBracket.length; - continue; - } - } - } - - // Check for single quoted string - if (s[i] === '"' || s[i] === "'") { - const quote = s[i]; - result += quote; - i++; - while (i < s.length && s[i] !== quote) { - if (s[i] === "\\") { - result += s[i] + s[i + 1]; - i += 2; - } else { - result += s[i]; - i++; - } - } - if (i < s.length) { - result += s[i]; // closing quote - i++; - } - continue; - } - - // Check for comments - if (s[i] === "-" && s[i + 1] === "-") { - // Replace the -- with spaces - result += " "; - i += 2; - - // Check for long comment - if (s[i] === "[") { - let j = i + 1; - let equalsCount = 0; - while (s[j] === "=") { - equalsCount++; - j++; - } - if (s[j] === "[") { - // Found long comment start - const closeBracket = `]${"=".repeat(equalsCount)}]`; - // Replace opening bracket with spaces - result += " ".repeat(j - i + 1); - i = j + 1; - - // Find matching closing bracket - const content = s.substring(i); - const closeIndex = content.indexOf(closeBracket); - if (closeIndex !== -1) { - // Replace comment content and closing bracket with spaces - result += " ".repeat(closeIndex) + " ".repeat(closeBracket.length); - i += closeIndex + closeBracket.length; - continue; - } - } - } - - // Single line comment - replace rest of line with spaces - while (i < s.length && s[i] !== "\n") { - result += " "; - i++; - } - continue; - } - - result += s[i]; - i++; - } - - return result; -} - export function parseBlock(s: string, ctx: ASTCtx = {}): LuaBlock { try { - const t = parseToAST(stripLuaComments(s)); - // console.log("Clean tree", JSON.stringify(t, null, 2)); - const result = parseChunk(t, ctx); + const concreteTree = parseToAST(s); + const comments = collectLuaComments(concreteTree, ctx); + const result = parseChunk(withoutComments(concreteTree), ctx); + assignCommentsToBlocks(result, comments, s); + attachFunctionDocumentation(result, comments, s); // console.log("Parsed AST", JSON.stringify(result, null, 2)); getBlockGotoMeta(result); return result; @@ -1720,7 +1833,25 @@ export function parseToAST(t: string): ParseTree { } const n = lezerToParseTree(t, tree.topNode); - return cleanTree(n, true); + return cleanLuaTree(n); +} + +function cleanLuaTree(tree: ParseTree): ParseTree { + if (tree.type === "⚠") { + throw new Error(`Parse error at pos ${tree.from}`); + } + if (tree.text !== undefined) return tree; + const result: ParseTree = { + type: tree.type, + children: [], + from: tree.from, + to: tree.to, + }; + for (const node of tree.children ?? []) { + if (node.type) result.children!.push(cleanLuaTree(node)); + if (node.text?.trim()) result.children!.push(node); + } + return result; } function findFirstParseError(node: SyntaxNode): SyntaxNode | null { diff --git a/client/space_lua/pretty_print.test.ts b/client/space_lua/pretty_print.test.ts index 82e4fb67..8955c7ea 100644 --- a/client/space_lua/pretty_print.test.ts +++ b/client/space_lua/pretty_print.test.ts @@ -122,6 +122,21 @@ local y = 2 return x + y`); }); +test("comments are retained", () => { + expect( + fmtBlock(`--- Documents f. +function f() + -- body comment + return 1 -- result +end`), + ).toBe(`--- Documents f. +function f() + -- body comment + return 1 + -- result +end`); +}); + test("goto, label, break", () => { expect(fmtBlock("::top::")).toBe("::top::"); expect(fmtBlock("goto done\n::done::")).toBe(`goto done diff --git a/client/space_lua/pretty_print.ts b/client/space_lua/pretty_print.ts index 3ff68d7b..fc6f0d29 100644 --- a/client/space_lua/pretty_print.ts +++ b/client/space_lua/pretty_print.ts @@ -308,16 +308,32 @@ class Printer { block(b: LuaBlock, depth: number): string { const stmts = b.statements.filter((s) => s.type !== "Semicolon"); - const isDef = (s: LuaStatement) => + const items: (LuaStatement | NonNullable[number])[] = + [...stmts, ...(b.comments ?? [])].sort( + (a, z) => (a.ctx.from ?? 0) - (z.ctx.from ?? 0), + ); + const isDef = (s: (typeof items)[number]) => s.type === "Function" || s.type === "LocalFunction"; let out = ""; - for (let i = 0; i < stmts.length; i++) { + for (let i = 0; i < items.length; i++) { if (i > 0) { out += "\n"; // blank line separating function definitions from neighbours - if (isDef(stmts[i - 1]) || isDef(stmts[i])) out += "\n"; + const previous = items[i - 1]; + const isDocumentationPair = + previous.type === "Comment" && + previous.text.startsWith("---") && + isDef(items[i]); + if (!isDocumentationPair && (isDef(previous) || isDef(items[i]))) { + out += "\n"; + } } - out += this.statement(stmts[i], depth); + const item = items[i]; + out += + item.type === "Comment" + ? this.indent(depth) + + item.text.replaceAll("\n", `\n${this.indent(depth)}`) + : this.statement(item, depth); } return out; }