const assert = require('node:assert/strict'); const test = require('node:test'); const fs = require('node:fs/promises'); const os = require('node:os'); const path = require('node:path'); const Module = require('node:module'); const { pathToFileURL, fileURLToPath } = require('node:url'); // VS Code 是外部边界;源码关系由真实候选编译器生成,不在测试中伪造索引。 class Uri { constructor(url) { this.url = url; } static file(value) { return new Uri(pathToFileURL(value)); } static parse(value) { return new Uri(new URL(value)); } static joinPath(base, ...segments) { return Uri.file(path.join(base.fsPath, ...segments)); } static from(value) { const url = new URL(`${value.scheme}:/`); url.pathname = value.path; if (value.query) url.search = value.query; return new Uri(url); } get scheme() { return this.url.protocol.slice(0, -1); } get fsPath() { return this.scheme === 'file' ? fileURLToPath(this.url) : this.url.pathname; } get query() { return decodeURIComponent(this.url.search.slice(1)); } with(value) { const url = new URL(this.url); if (value.fragment !== undefined) url.hash = value.fragment; if (value.query !== undefined) url.search = value.query; return new Uri(url); } toString() { return this.url.toString(); } } class Range { constructor(first, second, third, fourth) { this.start = typeof first === 'number' ? { line: first, character: second } : first; this.end = typeof first === 'number' ? { line: third, character: fourth } : second; } } class EventEmitter { callbacks = new Set(); event = callback => { this.callbacks.add(callback); return { dispose: () => this.callbacks.delete(callback) }; }; fire(value) { for (const callback of this.callbacks) callback(value); } dispose() { this.callbacks.clear(); } } test('real compiler powers navigation, documentation hover and saved-source refresh', async () => { assert.ok(process.env.DEVER_TEST_BIN, 'set DEVER_TEST_BIN to the built candidate compiler'); const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dever editor ')); const sourcePath = path.join(root, 'main.dever'); const code = 'label(name: Text) (text: Text) {\n text = name\n}\nflow first(name: Text) (text: Text)\n| step | kind | do |\n| text | calc | "😀" + label(name) + label("另") |\nsecond(name: Text) (text: Text) {\n text = label(name)\n}\n'; const source = code + 'const suffix = "😀"\nsuffixSize() (size: Int) { size = length(suffix) }\ndecodeBytes(value: Text) (out: Text) { out = dever.bytes.toText(dever.bytes.fromText(value)) }\n' + [ 'identity(value: Int) (out: Int) { out = value }', 'double(value: Int) (out: Int) { out = value * 2 }', 'apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(value) }', 'bound(value: Int) (out: Int) { out = apply(value, identity) + apply(value, double) }', 'flow applyFlow(value: Int, transform: handler(value: Int) (out: Int)) (out: Int)', '| step | kind | do |', '| out | calc | transform(value) |', 'rule applyRule(value: Int, transform: handler(value: Int) (out: Int)) (out: Int)', '| value | transform | out |', '| - | - | transform(value) |', 'loop applyLoop(values: List, transform: handler(value: Int) (out: Int)) (out: Int)', '| each value in values | result |', '| out | sum transform(value) |', 'boundTables(value: Int) (out: Int) { out = applyFlow(value, identity) + applyRule(value, identity) + applyLoop([value], identity) }', '' ].join('\n'); await fs.writeFile(sourcePath, source); const providers = {}; const commands = {}; const executed = []; const panels = []; const opened = []; const documents = new Map(); const saved = new EventEmitter(); const disposable = () => ({ dispose() {} }); const context = { subscriptions: [], extensionUri: Uri.file(path.resolve(__dirname, '../../editor/vscode')) }; function document(uri, text) { return { uri, languageId: uri.fsPath.endsWith('.md') ? 'markdown' : 'dever', isDirty: false, text, offsetAt(position) { return this.text.split('\n').slice(0, position.line).reduce((offset, line) => offset + line.length + 1, 0) + position.character; }, getText(range) { return range ? this.text.slice(this.offsetAt(range.start), this.offsetAt(range.end)) : this.text; } }; } const vscode = { Uri, Range, EventEmitter, DiagnosticSeverity: { Error: 0 }, Diagnostic: class { constructor(range, message, severity) { Object.assign(this, {range, message, severity}); } }, DiagnosticRelatedInformation: class { constructor(location, message) { Object.assign(this, {location, message}); } }, MarkdownString: class { value = ''; appendMarkdown(text) { this.value += text; return this; } appendCodeblock(text, language) { this.value += '```' + language + '\n' + text + '\n```\n'; return this; } }, Hover: class { constructor(contents) { this.contents = contents; } }, Location: class { constructor(uri, range) { Object.assign(this, { uri, range }); } }, CodeLens: class { constructor(range, command) { Object.assign(this, { range, command }); } }, CallHierarchyItem: class { constructor(kind, name, detail, uri, range, selectionRange) { Object.assign(this, { kind, name, detail, uri, range, selectionRange }); } }, CallHierarchyIncomingCall: class { constructor(from, fromRanges) { Object.assign(this, { from, fromRanges }); } }, CallHierarchyOutgoingCall: class { constructor(to, fromRanges) { Object.assign(this, { to, fromRanges }); } }, SymbolKind: { Function: 11 }, ViewColumn: { One: 1, Beside: 2 }, window: { createOutputChannel: () => ({ appendLine() {}, dispose() {} }), createStatusBarItem: () => ({ show() {}, hide() {}, dispose() {} }), showErrorMessage(message) { throw new Error(message); }, async showTextDocument(document, options) { opened.push({ document, options }); }, createWebviewPanel(type, title, column, options) { const disposed = new EventEmitter(); const panel = { type, title, column, options, dispose() { disposed.fire(); }, onDidDispose: disposed.event, webview: { cspSource: 'https://webview.test', asWebviewUri: uri => uri, onDidReceiveMessage(callback) { panel.message = callback; return disposable(); } } }; panels.push(panel); return panel; } }, commands: { registerCommand(name, callback) { commands[name] = callback; return disposable(); }, executeCommand: async (...values) => { executed.push(values); } }, languages: { createDiagnosticCollection: () => ({ clear() {}, set() {}, dispose() {} }) }, workspace: { isTrusted: true, get textDocuments() { return [...documents.values()]; }, getWorkspaceFolder: uri => uri.fsPath.startsWith(root + path.sep) ? { uri: Uri.file(root) } : undefined, getConfiguration: () => ({ get: () => [process.env.DEVER_TEST_BIN] }), onDidChangeTextDocument: disposable, onDidSaveTextDocument: saved.event, onDidChangeConfiguration: disposable, onDidCloseTextDocument: disposable, createFileSystemWatcher: () => ({ onDidChange: disposable, onDidCreate: disposable, onDidDelete: disposable, dispose() {} }), registerTextDocumentContentProvider(scheme, provider) { providers[scheme] = provider; return disposable(); }, async openTextDocument(uri) { const key = uri.toString(); if (!documents.has(key)) { const text = uri.scheme === 'file' ? await fs.readFile(uri.fsPath, 'utf8') : await providers[uri.scheme].provideTextDocumentContent(uri); documents.set(key, document(uri, text)); } return documents.get(key); } } }; for (const name of ['Definition', 'Reference', 'CallHierarchy', 'CodeLens', 'Hover']) { vscode.languages[`register${name}Provider`] = (_, provider) => { providers[name] = provider; return disposable(); }; } const originalLoad = Module._load; Module._load = function(request, ...rest) { return request === 'vscode' ? vscode : originalLoad.call(this, request, ...rest); }; try { const { registerNavigation } = require('../../editor/vscode/navigation.cjs'); registerNavigation(context); Module._load = originalLoad; const doc = await vscode.workspace.openTextDocument(Uri.file(sourcePath)); const callLine = source.split('\n').findIndex(line => line.includes('"😀"')); const position = { line: callLine, character: source.split('\n')[callLine].indexOf('label') + 1 }; const definitions = await providers.Definition.provideDefinition(doc, position); assert.equal(definitions.length, 1); assert.equal(definitions[0].uri.fsPath, sourcePath); assert.equal(definitions[0].range.start.line, source.split('\n').findIndex(line => line.startsWith('label('))); const constantLine = source.split('\n').findIndex(line => line.startsWith('suffixSize')); const constantPosition = { line: constantLine, character: source.split('\n')[constantLine].indexOf('(suffix)') + 2 }; const constantDefinition = await providers.Definition.provideDefinition(doc, constantPosition); assert.equal(constantDefinition.length, 1); assert.equal(constantDefinition[0].range.start.line, constantLine - 1); const constantReferences = await providers.Reference.provideReferences(doc, constantPosition, { includeDeclaration: false }); assert.equal(constantReferences.length, 1); assert.equal(constantReferences[0].range.start.line, constantLine); const constantHover = await providers.Hover.provideHover(doc, constantPosition); assert.match(constantHover.contents[0].value, /const main\.main\.app\.suffix = "😀"/); const references = await providers.Reference.provideReferences(doc, position, { includeDeclaration: false }); assert.equal(references.length, 3); assert.equal(references[0].range.start.character, source.split('\n')[callLine].indexOf('label')); const [target] = await providers.CallHierarchy.prepareCallHierarchy(doc, position); const incoming = await providers.CallHierarchy.provideCallHierarchyIncomingCalls(target); assert.equal(incoming.length, 2); assert.deepEqual(incoming.map(call => call.fromRanges.length).sort(), [1, 2]); const outgoing = await providers.CallHierarchy.provideCallHierarchyOutgoingCalls(incoming[0].from); assert.equal(outgoing[0].to.name, 'main.main.app.label'); const lenses = await providers.CodeLens.provideCodeLenses(doc); assert.match(lenses[0].command.title, /2 个调用方 · 3 处调用/); const boundLine = source.split('\n').findIndex(line => line.startsWith('bound(')); const [bound] = await providers.CallHierarchy.prepareCallHierarchy(doc, { line: boundLine, character: 1 }); const bindings = await providers.CallHierarchy.provideCallHierarchyOutgoingCalls(bound); assert.equal(bindings.length, 2); assert.deepEqual(bindings.map(call => call.to.name).sort(), [ 'main.main.app.apply [transform = main.main.app.double]', 'main.main.app.apply [transform = main.main.app.identity]' ]); assert.ok(bindings.every(call => call.to.range.start.line === boundLine - 1)); const boundHover = await providers.Hover.provideHover(doc, { line: boundLine, character: source.split('\n')[boundLine].indexOf('apply') + 1 }); assert.match(boundHover.contents[0].value, /apply \[transform = main\.main\.app\.identity\]\(value: Int/); const tablesLine = source.split('\n').findIndex(line => line.startsWith('boundTables(')); for (const [name, prefix] of [['applyFlow', 'flow'], ['applyRule', 'rule'], ['applyLoop', 'loop']]) { const hover = await providers.Hover.provideHover(doc, { line: tablesLine, character: source.split('\n')[tablesLine].indexOf(name) + 1 }); assert.ok(hover.contents[0].value.includes(`${prefix} main.main.app.${name} [transform = main.main.app.identity](`), hover.contents[0].value); } const preview = Uri.from({ scheme: 'dever-calls', path: '/calls.md', query: JSON.stringify({ root, name: 'main.main.app.label' }) }); const markdown = await providers['dever-calls'].provideTextDocumentContent(preview); assert.match(markdown, /## 定义/); assert.ok(markdown.includes('```dever')); assert.match(markdown, /\| 函数 \| 领域/); assert.match(markdown, /main.main.app.first/); assert.match(markdown, /main.main.app.second/); assert.ok(markdown.includes(`#L${callLine + 1}`)); await commands['dever.showCalls'](root, 'main.main.app.label'); const callsPanel = panels.at(-1); assert.match(callsPanel.webview.html, //); assert.match(callsPanel.webview.html, /main.main.app.first<\/h1>/); assert.match(callsPanel.webview.html, /执行流程/); const reply = []; callsPanel.webview.postMessage = async message => reply.push(message); await callsPanel.message({ type: 'expand', href: 'command:dever.expandFlow?' + encodeURIComponent(JSON.stringify([root, 'main.main.app.label'])), request: 1 }); assert.equal(reply[0].type, 'expanded'); assert.match(reply[0].html, /flowchart TD/); doc.isDirty = true; await assert.rejects(callsPanel.message({ type: 'open', href: sourceHref }), /保存/); doc.isDirty = false; callsPanel.dispose(); doc.isDirty = true; assert.deepEqual(await providers.Definition.provideDefinition(doc, position), []); doc.isDirty = false; doc.text = source.replace('text = label(name)', 'text = name'); await fs.writeFile(sourcePath, doc.text); saved.fire(doc); assert.equal((await providers.Reference.provideReferences(doc, position, { includeDeclaration: false })).length, 2); doc.text = source.replace('label(name)', 'missing(name)'); await fs.writeFile(sourcePath, doc.text); saved.fire(doc); assert.deepEqual(await providers.Definition.provideDefinition(doc, position), []); const valid = await providers.Definition.provideDefinition(doc, { line: 0, character: 1 }); assert.equal(valid.length, 1, 'unrelated valid definitions remain navigable'); const libraryLine = source.split('\n').findIndex(line => line.startsWith('decodeBytes')); const libraryPosition = { line: libraryLine, character: source.split('\n')[libraryLine].indexOf('dever.bytes.toText') + 1 }; const [librarySite] = await providers.Definition.provideDefinition(doc, libraryPosition); const libraryPath = path.resolve(__dirname, '../../lib/dever/bytes.dv'); assert.equal(librarySite.uri.fsPath, libraryPath); const [libraryItem] = await providers.CallHierarchy.prepareCallHierarchy(doc, libraryPosition); const libraryIncoming = await providers.CallHierarchy.provideCallHierarchyIncomingCalls(libraryItem); assert.ok(libraryIncoming.some(call => call.from.name === 'main.main.app.decodeBytes')); await commands['dever.showCalls'](root, 'dever.bytes.app.toText'); const libraryPanel = panels.at(-1); const libraryHref = pathToFileURL(libraryPath).href + '#L15,1'; await libraryPanel.message({ type: 'open', href: libraryHref }); assert.equal(opened.at(-1).document.uri.fsPath, libraryPath); await assert.rejects(libraryPanel.message({ type: 'open', href: pathToFileURL(path.join(root, '../outside.dever')).href }), /当前源码或说明索引/); const libraryDoc = opened.at(-1).document; libraryDoc.isDirty = true; await assert.rejects(libraryPanel.message({ type: 'open', href: libraryHref }), /保存/); libraryDoc.isDirty = false; libraryPanel.dispose(); const cms = path.resolve(__dirname, '../../examples/next/cms'); await commands['dever.showCalls'](cms, 'POST /content/article/admin/manage/publish'); const entryPanel = panels.at(-1); const entryHtml = entryPanel.webview.html; assert.match(entryHtml, /只有草稿可以发布。.*

执行流程<\/h2>/s); const [, topicHref] = /主题说明<\/a>/.exec(entryHtml); await entryPanel.message({ type: 'open', href: topicHref }); const openedTopic = opened.at(-1); assert.equal(openedTopic.document.uri.fsPath, path.join(cms, 'module/content/article/doc/article.md')); assert.equal(openedTopic.document.getText().split('\n')[openedTopic.options.selection.start.line], '## content.article.app.publish'); await commands['dever.showCalls'](cms, 'content.article.app.publish'); const appHtml = panels.at(-1).webview.html; const folded = '
实现细节'; const split = appHtml.indexOf(folded); assert.ok(split > 0); assert.match(appHtml.slice(0, split), /只有草稿可以发布。.*data\.update\(…\)/s); assert.doesNotMatch(appHtml.slice(0, split), /where = id == article_id and status == Draft/); assert.match(appHtml.slice(split), /where = id == article_id and status == Draft/); const project = path.join(root, 'application'); const run = require('node:util').promisify(require('node:child_process').execFile); const domain = path.join(project, 'module/hello/greeting'); await Promise.all(['doc', 'flow', 'api'].map(dir => fs.mkdir(path.join(domain, dir), { recursive: true }))); await fs.writeFile(path.join(domain, 'flow/greeting.dv'), 'greet(name: Text) (message: Text) { message = name /* 局部实现说明 */ } # 行尾说明'); await fs.writeFile(path.join(domain, 'api/greeting.dv'), 'cmd greet = app.greet'); await fs.writeFile(path.join(domain, 'doc/greeting.md'), '## hello.greeting.app.greet\n按原样保留。'); await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--links']); const app = await vscode.workspace.openTextDocument(Uri.file(path.join(project, 'module/hello/greeting/flow/greeting.dv'))); vscode.window.activeTextEditor = { document: app, selection: { active: { line: 0, character: 1 } } }; const hover = await providers.Hover.provideHover(app, { line: 0, character: 1 }); assert.match(hover.contents[0].value, /greet\(name: Text\) \(message: Text\)/); assert.match(hover.contents[0].value, /按原样保留/); assert.doesNotMatch(hover.contents[0].value, /局部实现说明|行尾说明/); assert.match(hover.contents[0].value, /hello\.greeting\.greet/); assert.match(hover.contents[0].value, /command:dever.showCalls/); const api = await vscode.workspace.openTextDocument(Uri.file(path.join(project, 'module/hello/greeting/api/greeting.dv'))); assert.match((await providers.Hover.provideHover(api, { line: 0, character: api.getText().indexOf('app.greet') + 5 })).contents[0].value, /按原样保留/); const topic = await vscode.workspace.openTextDocument(Uri.file(path.join(project, 'module/hello/greeting/doc/greeting.md'))); topic.text = topic.text.replace('按原样保留', '输入不做改写'); topic.isDirty = true; await assert.rejects(providers.Hover.provideHover(app, { line: 0, character: 1 }), /保存/); await fs.writeFile(topic.uri.fsPath, topic.text); topic.isDirty = false; saved.fire(topic); assert.match((await providers.Hover.provideHover(app, { line: 0, character: 1 })).contents[0].value, /输入不做改写/); await commands['dever.previewDocumentation'](project, 'hello.greeting.app.greet'); assert.equal(executed.at(-1)[0], 'markdown.showPreviewToSide'); await assert.rejects(commands['dever.openDomainLinks'](), /stale/); await run(process.env.DEVER_TEST_BIN, ['inspect', project, '--links']); await commands['dever.openDomainLinks'](); const panel = panels.at(-1); assert.equal(panel.type, 'dever.links'); assert.match(panel.webview.html, /language-mermaid/); assert.match(panel.webview.html, /flowchart TD/); assert.match(panel.webview.html, /flow-browser\.js/); await panel.message({ type: 'open', href: 'flow/greeting.dv#L15,3' }); assert.equal(opened.at(-1).document.uri.fsPath, app.uri.fsPath); assert.deepEqual(opened.at(-1).options.selection.start, { line: 14, character: 2 }); const anchor = /id="(flow-[^"]+)"/.exec(panel.webview.html)[1]; await panel.message({ type: 'open', href: `link.md#${anchor}` }); assert.ok(panel.webview.html.includes(`data-anchor="${anchor}"`)); await assert.rejects(panel.message({ type: 'open', href: 'https://example.invalid/' }), /只打开项目/); await assert.rejects(panel.message({ type: 'open', href: '../../../../outside.dever' }), /当前源码或说明索引/); topic.text = topic.text.replace('## hello.greeting.app.greet', '## hello.greeting.missing'); await fs.writeFile(topic.uri.fsPath, topic.text); saved.fire(topic); const invalidDocumentation = await providers.Hover.provideHover(app, { line: 0, character: 1 }); assert.match(invalidDocumentation.contents[0].value, /说明校验未通过/); assert.match(invalidDocumentation.contents[0].value, /greet\(name: Text\)/); await assert.rejects(commands['dever.openDomainLinks'](project, 'hello.greeting.app.greet'), /unknown or invalid documentation symbol/); } finally { Module._load = originalLoad; for (const subscription of context.subscriptions) subscription.dispose(); for (const name of ['navigation', 'inspection', 'reading', 'hover']) { delete require.cache[require.resolve(`../../editor/vscode/${name}.cjs`)]; } delete require.cache[require.resolve('../../editor/vscode/dist/flow-preview.cjs')]; await fs.rm(root, { recursive: true }); } });