Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
node_modules/
*.vsix
dist/
/core.[0-9]*
+13
View File
@@ -0,0 +1,13 @@
**/*
!package.json
!README.md
!language-configuration.json
!syntaxes/**
!extension.cjs
!graph.cjs
!workflow.cjs
!inspection.cjs
!navigation.cjs
!reading.cjs
!hover.cjs
!dist/**
+15
View File
@@ -0,0 +1,15 @@
# Dever 源码与流程阅读
插件使用项目编译器的 inspect,提供定义、引用、双向调用层级、CodeLens、诊断、悬浮说明和可点击流程。Dever: Show Calls 显示当前能力的流程及调用关系,子调用可以原地展开、折叠。流程页先显示业务说明和流程图;入口未单独写说明时,使用它绑定的处理函数说明。展开「实现细节」可查看签名、调用关系与长节点原文。Dever: Open Domain Links 打开由 inspect --links 生成且仍有效的领域文档。
在 VS Code 设置 dever.command 为编译器的绝对路径数组;远程工作区使用远程主机可执行的路径。检查命令不经过 shell,不会自动安装或替换编译器。未信任工作区不能启动源码检查。
导航依据磁盘已保存内容及 SHA-256;未保存修改显示状态提示并拒绝旧位置跳转。局部错误时仍可导航独立有效定义。当前支持普通函数、rule、flow、loop、CMD、HTTP、Job 与具名 SQL;步骤种类、守卫失败出口和具体调用均来自已检查程序。loop 展示来源、take/累积状态初始化、过滤、排序键、每行短路、循环回边、稳定排序后截取及 index 重复键失败;foldUntil 先更新状态再判断 stop,结束本行后仍走向下一输出行。同步 walk 展示 Next/Done、状态推进和停止拉取;Bytes 来源沿用逐元素循环图。随包标准库函数可以按真实调用展开并跳转源码。并发任务和流展示实际分支、汇合、取消与资源释放路径。HTTP 入口展示站点、认证、可信租户选库、实时权限和事务成功/失败出口;Job 入队是单独的队列边,不画成同步调用。
在既有 dev 容器的 editor/vscode 目录中执行 npm run build。依赖由 package-lock.json 固定,构建产物位于 dist;不手工修改产物。测试命令为 npm test、npm run test:navigation、npm run test:flows。
高亮测试额外传入 --markdown-grammar <现有 VS Code Markdown grammar>;导航和流程测试设置 DEVER_TEST_BIN 为本次编译器。浏览器测试设置 DEVER_BROWSER_TOOLS 为已有 playwright-core、@sparticuz/chromium 的依赖目录,并加载该浏览器的动态库及字体配置。共享 dev 当前使用 /cache/node/manage-browser/native/lib 和 /tmp/fonts,对应 LD_LIBRARY_PATH、FONTCONFIG_PATH。测试调用真实编译器,并在真实浏览器中核对渲染、源码点击及子流程展开;VS Code API 边界使用替身。
插件没有第二套语言解析器、后台编译服务或拖拽改源码能力。流程图描述静态调用关系;实际请求的执行顺序需通过运行日志或追踪确认。
静态 handler 的阅读名称包含具体绑定,不显示编译器的生成摘要。相同源码的不同绑定分别展开实际目标;文档仍绑定原始完整函数名,只写一份。未绑定模板可导航到声明,不生成执行图。
+12
View File
@@ -0,0 +1,12 @@
const esbuild = require('esbuild');
const fs = require('node:fs/promises');
async function build() {
await fs.mkdir('dist', { recursive: true });
await Promise.all([
fs.copyFile(require.resolve('@mermaid-js/tiny'), 'dist/mermaid.js'),
fs.copyFile('flow-browser.js', 'dist/flow-browser.js'),
esbuild.build({ entryPoints: ['flow-preview.cjs'], bundle: true, outfile: 'dist/flow-preview.cjs', minify: true, legalComments: 'eof', platform: 'node', external: ['vscode'] })
]);
}
build().catch(error => { console.error(error); process.exitCode = 1; });
+7
View File
@@ -0,0 +1,7 @@
const { registerNavigation } = require('./navigation.cjs');
function activate(context) {
registerNavigation(context);
}
module.exports = { activate };
+67
View File
@@ -0,0 +1,67 @@
(() => {
const mermaid = globalThis.mermaid;
const vscode = acquireVsCodeApi();
mermaid.initialize({ startOnLoad: false, securityLevel: 'loose', theme: document.body.classList.contains('vscode-dark') ? 'dark' : 'default', flowchart: { htmlLabels: false } });
let sequence = 0;
let request = 0;
const pending = new Map();
// Mermaid 维护全局图状态;串行渲染,避免展开多个调用时争用临时节点。
let rendering = Promise.resolve();
function render(root) {
rendering = rendering.then(async () => {
for (const code of root.querySelectorAll('pre > code.language-mermaid')) {
try {
const { svg } = await mermaid.render('dever-flow-' + sequence++, code.textContent);
const container = document.createElement('div');
container.className = 'dever-flow';
container.innerHTML = svg;
code.parentElement.replaceWith(container);
} catch (error) {
const message = document.createElement('p');
message.className = 'dever-flow-error';
message.textContent = '流程图渲染失败:' + error.message;
code.parentElement.before(message);
}
await new Promise(resolve => setTimeout(resolve, 0));
}
});
return rendering;
}
window.addEventListener('message', event => {
const message = event.data;
const target = pending.get(message.request);
if (!target) return;
if (message.type === 'expanded') {
target.innerHTML = message.html;
pending.delete(message.request);
render(target);
} else if (message.type === 'expandError') {
target.textContent = message.message;
pending.delete(message.request);
}
});
document.addEventListener('click', event => {
const link = event.target.closest('a');
if (!link) return;
const href = link.getAttribute('href') || link.getAttribute('xlink:href');
if (!href) return;
event.preventDefault();
if (href.startsWith('#')) document.getElementById(decodeURIComponent(href.slice(1)))?.scrollIntoView();
else if (href.startsWith('command:dever.expandFlow?')) {
const details = document.createElement('details');
details.open = true;
const summary = document.createElement('summary');
summary.textContent = link.textContent;
const body = document.createElement('div');
body.textContent = '正在读取已检查的子流程…';
details.append(summary, body);
link.replaceWith(details);
pending.set(++request, body);
vscode.postMessage({ type: 'expand', href, request });
} else vscode.postMessage({ type: 'open', href });
});
render(document).then(() => {
document.getElementById(document.body.dataset.anchor)?.scrollIntoView();
document.body.dataset.rendered = 'true';
});
})();
+102
View File
@@ -0,0 +1,102 @@
const vscode = require('vscode');
const fs = require('node:fs/promises');
const path = require('node:path');
const { randomBytes } = require('node:crypto');
const { pathToFileURL, fileURLToPath } = require('node:url');
const markdown = require('markdown-it')({ html: true });
// 只渲染预览使用的锚点和折叠标签;业务文档里的其他 HTML 按文本显示。
markdown.renderer.rules.html_inline = (tokens, i) => /^(?:<a id="flow-[a-zA-Z0-9_-]+">|<\/a>)$/.test(tokens[i].content) ? tokens[i].content : markdown.utils.escapeHtml(tokens[i].content);
markdown.renderer.rules.html_block = (tokens, i) => /^(?:<a id="flow-[a-zA-Z0-9_-]+"><\/a>|<details><summary>实现细节<\/summary>|<\/details>)\s*$/.test(tokens[i].content) ? tokens[i].content : tokens[i].content.startsWith('<!--') ? '' : markdown.utils.escapeHtml(tokens[i].content);
const validateLink = markdown.validateLink;
markdown.validateLink = href => href.startsWith('file:') || validateLink(href);
// 流程图与调用表共用阅读面板;链接打开真实源码或当前索引。
async function openFlowPreview(context, target, root, calls, verifyTarget = calls?.verify) {
const panel = vscode.window.createWebviewPanel('dever.links', 'Dever 调用流程', vscode.ViewColumn.Beside, {
enableScripts: true,
localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'dist')]
});
let current = target.fsPath;
let revision = 0;
async function render(filename, anchor = '') {
const generation = ++revision;
let text;
try {
text = calls ? await calls.read(filename) : await fs.readFile(filename, 'utf8');
} catch (error) {
// 保存触发的新一轮读取已经接管面板,旧读取失效时让新一轮继续。
if (generation !== revision) return;
throw error;
}
if (!calls && !text.startsWith('<!-- Generated by dever inspect --links. Do not edit. -->')) {
throw new Error('此文件不是生成的领域索引,请运行 dever inspect . --links。');
}
if (generation !== revision) return;
current = filename;
panel.title = calls ? `Dever · ${filename}` : `Dever · ${path.basename(path.dirname(filename))}`;
const script = panel.webview.asWebviewUri(vscode.Uri.joinPath(context.extensionUri, 'dist', 'flow-browser.js'));
const mermaid = panel.webview.asWebviewUri(vscode.Uri.joinPath(context.extensionUri, 'dist', 'mermaid.js'));
const nonce = randomBytes(16).toString('hex');
panel.webview.html = `<!DOCTYPE html><html><head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-${nonce}'; style-src ${panel.webview.cspSource} 'unsafe-inline'; img-src ${panel.webview.cspSource} data:; font-src ${panel.webview.cspSource} data:;">
<style>body{max-width:1100px;margin:24px auto;padding:0 24px;font:var(--vscode-font-size) var(--vscode-font-family);color:var(--vscode-editor-foreground);background:var(--vscode-editor-background)}a{color:var(--vscode-textLink-foreground)}table{border-collapse:collapse}td,th{padding:6px 12px;border:1px solid var(--vscode-panel-border)}pre{overflow:auto}details{margin:16px 0}.dever-flow{overflow:auto;margin:20px 0}.dever-flow svg{max-width:none!important}.dever-flow-error{color:var(--vscode-errorForeground)}</style>
</head><body data-anchor="${markdown.utils.escapeHtml(anchor)}">${markdown.render(text)}
<script nonce="${nonce}" src="${mermaid}"></script><script nonce="${nonce}" src="${script}"></script></body></html>`;
}
const messages = panel.webview.onDidReceiveMessage(async message => {
if (typeof message.href !== 'string') return;
if (message.type === 'expand' && calls) {
const generation = revision;
try {
if (!message.href.startsWith('command:dever.expandFlow?')) throw new Error('无效的子流程链接。');
const [requestedRoot, name] = JSON.parse(decodeURIComponent(message.href.split('?')[1]));
if (requestedRoot !== root) throw new Error('链接超出当前项目。');
const text = await calls.read(name);
if (generation === revision) await panel.webview.postMessage({ type: 'expanded', request: message.request, html: markdown.render(text) });
} catch (error) {
await panel.webview.postMessage({ type: 'expandError', request: message.request, message: error.message });
}
return;
}
if (message.type !== 'open') return;
try {
if (calls && message.href.startsWith('command:dever.showCalls?')) {
const [requestedRoot, name] = JSON.parse(decodeURIComponent(message.href.split('?')[1]));
if (requestedRoot !== root) throw new Error('链接超出当前项目。');
await render(name);
return;
}
const destination = new URL(message.href, pathToFileURL(calls ? root + path.sep : current));
if (destination.protocol !== 'file:') throw new Error('流程阅读页只打开项目源码、说明和领域索引。');
const filename = fileURLToPath(destination);
const relative = path.relative(root, filename);
const outside = relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative);
if (outside && !verifyTarget) throw new Error('链接超出当前项目。');
if (!outside && !calls && path.basename(filename) === 'link.md') {
await render(filename, decodeURIComponent(destination.hash.slice(1)));
} else {
const location = /^#L(\d+)(?:,(\d+))?$/.exec(destination.hash);
const line = location ? Number(location[1]) - 1 : 0;
const column = location?.[2] ? Number(location[2]) - 1 : 0;
const document = verifyTarget
? await verifyTarget(filename)
: await vscode.workspace.openTextDocument(vscode.Uri.file(filename));
await vscode.window.showTextDocument(document, { viewColumn: vscode.ViewColumn.One, selection: new vscode.Range(line, column, line, column) });
}
} catch (error) { vscode.window.showErrorMessage(error.message); }
});
panel.onDidDispose(() => { revision++; messages.dispose(); });
if (calls) {
const changed = calls.changed.event(() => render(current).catch(error => {
panel.dispose();
vscode.window.showErrorMessage(error.message);
}));
panel.onDidDispose(() => changed.dispose());
}
context.subscriptions.push(panel);
try { await render(calls ? calls.name : current); } catch (error) { panel.dispose(); throw error; }
return panel;
}
module.exports = { openFlowPreview };
+46
View File
@@ -0,0 +1,46 @@
// 编译器结果按身份建立邻接索引;每个 CodeLens 不再扫描整张调用图。
const indices = new WeakMap();
function graph(index) {
if (indices.has(index)) return indices.get(index);
const symbols = new Map(index.symbols.map(symbol => [symbol.id, symbol]));
const names = new Map(index.symbols.map(symbol => [symbol.name, symbol]));
const incoming = new Map(), outgoing = new Map(), sites = new Map(), declarations = new Map();
for (const call of index.calls) {
for (const [map, key] of [[incoming, call.callee], [outgoing, call.caller], [sites, call.site.file]]) {
if (!map.has(key)) map.set(key, []);
map.get(key).push(call);
}
}
for (const symbol of index.symbols) for (const site of symbol.declarations) {
if (!declarations.has(site.file)) declarations.set(site.file, []);
declarations.get(site.file).push(symbol);
}
const result = { symbols, names, incoming, outgoing, sites, declarations };
indices.set(index, result);
return result;
}
function compare(left, right) { return left.line - right.line || left.character - right.character; }
function contains(range, position) { return compare(range.start, position) <= 0 && compare(position, range.end) < 0; }
function at(index, file, position) {
const edges = graph(index).sites.get(file) || [];
const calls = edges.filter(call => contains(call.site, position));
// 嵌套调用点击优先采用最小范围,不把外层调用也当成定义目标。
calls.sort((a, b) => compare(b.site.start, a.site.start) || compare(a.site.end, b.site.end));
if (calls.length) {
const first = calls[0].site;
return [...new Set(calls.filter(call => compare(call.site.start, first.start) === 0
&& compare(call.site.end, first.end) === 0).map(call => call.callee))].map(id => graph(index).symbols.get(id));
}
return (graph(index).declarations.get(file) || []).filter(symbol => symbol.declarations.some(site => contains(site, position)));
}
function relations(index, id, incoming) {
const adjacency = incoming ? graph(index).incoming : graph(index).outgoing;
const grouped = new Map();
for (const call of adjacency.get(id) || []) {
const target = incoming ? call.caller : call.callee;
if (!grouped.has(target)) grouped.set(target, []);
grouped.get(target).push(call);
}
return [...grouped].map(([id, calls]) => ({ symbol: graph(index).symbols.get(id), calls }));
}
module.exports = { graph, at, relations, contains };
+65
View File
@@ -0,0 +1,65 @@
const vscode = require('vscode');
const { relations } = require('./graph.cjs');
const { uri } = require('./inspection.cjs');
function command(name, args) {
return `command:${name}?${encodeURIComponent(JSON.stringify(args))}`;
}
async function description(inspection, index, symbol, root) {
const find = target => index.documentation.find(item => item.symbol === target.source_name);
let value = find(symbol);
if (!value) {
const binding = relations(index, symbol.id, false).find(item => item.calls.some(call => call.kind === 'entry'));
if (binding) value = find(binding.symbol);
}
if (!value) return undefined;
const documentIndex = { files: [index.documentation_files[value.file]] };
await inspection.verify(documentIndex, 0, root);
return { ...value, uri: uri(documentIndex, 0, root) };
}
function registerHover(context, selector, inspection, lookup) {
context.subscriptions.push(vscode.languages.registerHoverProvider(selector, {
async provideHover(document, position) {
const state = await lookup(document, position);
if (!state?.symbols.length) return undefined;
const contents = [];
for (const symbol of state.symbols) {
const page = new vscode.MarkdownString();
page.isTrusted = { enabledCommands: ['dever.showCalls', 'dever.openDomainLinks', 'dever.previewDocumentation'] };
page.appendMarkdown(`**${symbol.name}**\n\n`);
if (state.index.documentation_errors.length) {
page.appendMarkdown('**说明校验未通过。** 失效或重复的标题详见“Dever”输出;签名和调用关系仍来自源码。\n\n');
}
for (const signature of symbol.signatures) page.appendCodeblock(signature, 'dever');
const detail = await description(inspection, state.index, symbol, state.root);
if (detail) {
page.baseUri = detail.uri;
page.appendMarkdown(`${detail.markdown}\n\n`);
} else {
page.appendMarkdown('尚未提供领域说明;签名和关系来自已保存源码。\n\n');
}
for (const incoming of [true, false]) {
const related = relations(state.index, symbol.id, incoming);
const label = incoming ? '调用方' : '调用目标';
const names = related.slice(0, 4).map(item => `\`${item.symbol.name}\``).join('、');
page.appendMarkdown(`${label}:${names || '当前静态索引中无记录'}${related.length > 4 ? `,共 ${related.length} 个` : ''}。\n\n`);
}
const links = [];
for (const site of symbol.declarations.slice(0, 1)) {
const target = uri(state.index, site.file, state.root).with({ fragment: `L${site.start.line + 1},${site.start.character + 1}` });
links.push(`[源码](${target.toString()})`);
}
if (detail) links.push(`[说明](${command('dever.previewDocumentation', [state.root, symbol.name])})`);
links.push(`[调用详情](${command('dever.showCalls', [state.root, symbol.name])})`);
links.push(`[领域流程](${command('dever.openDomainLinks', [state.root, symbol.name])})`);
page.appendMarkdown(links.join(' · '));
contents.push(page);
}
return new vscode.Hover(contents);
}
}));
}
module.exports = { registerHover, description, command };
+176
View File
@@ -0,0 +1,176 @@
const vscode = require('vscode');
const path = require('node:path');
const fs = require('node:fs/promises');
const { createHash } = require('node:crypto');
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
const execute = promisify(execFile);
function isSource(document) {
return document.languageId === 'dever';
}
async function projectRoot(document) {
const folder = vscode.workspace.getWorkspaceFolder(document.uri)?.uri.fsPath;
for (let directory = path.dirname(document.uri.fsPath); ; directory = path.dirname(directory)) {
try {
await fs.stat(path.join(directory, 'module'));
return directory;
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
if (directory === folder || directory === path.dirname(directory)) break;
}
return folder || document.uri.fsPath;
}
function uri(index, file) { return vscode.Uri.file(index.files[file].path); }
function range(location) {
return new vscode.Range(location.start.line, location.start.character, location.end.line, location.end.character);
}
function expandIndex(index) {
const location = ([file, line, character, endLine, endCharacter]) => ({
file, start: { line, character }, end: { line: endLine, character: endCharacter }
});
const symbols = new Map(index.symbols.map(symbol => [symbol.id, symbol]));
for (const symbol of index.symbols) {
if (symbol.template === undefined) {
symbol.source_name ??= symbol.name;
symbol.declarations = symbol.declarations.map(location);
}
}
for (const symbol of index.symbols) {
if (symbol.template !== undefined) {
const template = symbols.get(symbol.template);
symbol.source_name = template.name;
symbol.declarations = template.declarations;
symbol.signatures = template.signatures.map(signature => signature.replace(template.name, () => symbol.name));
delete symbol.template;
}
}
for (const call of index.calls) call.site = location(call.site);
for (const issue of index.diagnostics) {
issue.location = location(issue.location);
issue.related = issue.related.map(([site, reason]) => [location(site), reason]);
}
for (const flow of index.flows || []) {
for (const node of flow.nodes) if (node.site) node.site = location(node.site);
}
return index;
}
function createInspection(context) {
const cache = new Map();
// 随包源码沿用最近一次实际索引它的项目,打开库文件后仍能继续读调用链。
const sourceOwners = new Map();
const changed = new vscode.EventEmitter();
const output = vscode.window.createOutputChannel('Dever');
const diagnostics = vscode.languages.createDiagnosticCollection('dever');
const status = vscode.window.createStatusBarItem();
status.text = 'Dever:有未保存修改,导航和流程暂不可用';
const savedState = () => {
if (vscode.workspace.textDocuments.some(document => document.isDirty && isSource(document))) status.show();
else status.hide();
};
context.subscriptions.push(changed, output, diagnostics, status);
const invalidate = () => { cache.clear(); diagnostics.clear(); savedState(); changed.fire(); };
context.subscriptions.push(vscode.workspace.onDidChangeTextDocument(event => {
if (isSource(event.document)) { diagnostics.clear(); savedState(); changed.fire(); }
}));
context.subscriptions.push(vscode.workspace.onDidCloseTextDocument(savedState));
const watcher = vscode.workspace.createFileSystemWatcher('**/{*.dv,*.dever,README.md,doc/*.md,dever.lock,dever.api,setting.json}');
context.subscriptions.push(watcher, watcher.onDidChange(invalidate), watcher.onDidCreate(invalidate), watcher.onDidDelete(invalidate));
context.subscriptions.push(vscode.workspace.onDidSaveTextDocument(document => {
if (isSource(document) || /[/\\]doc[/\\][^/\\]+\.md$/.test(document.uri.fsPath)) invalidate();
}));
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(event => {
if (event.affectsConfiguration('dever.command')) invalidate();
}));
async function load(root, symbol) {
const key = JSON.stringify([root, symbol]);
if (!vscode.workspace.isTrusted) throw new Error('请信任工作区后再运行 Dever 源码检查。');
if (!cache.has(key)) {
const command = vscode.workspace.getConfiguration('dever', vscode.Uri.file(root)).get('command');
const arguments_ = [...command.slice(1), 'inspect', root, '--json'];
if (symbol) arguments_.push('--symbol', symbol, '--depth', '0');
const promise = execute(command[0], arguments_, {
maxBuffer: 32 * 1024 * 1024, windowsHide: true
}).then(({ stdout }) => {
if (cache.get(key) !== promise) throw new Error('检查期间源码已变化,请重新查询调用关系。');
const index = expandIndex(JSON.parse(stdout));
for (const file of index.files) sourceOwners.set(file.path, root);
for (const error of index.documentation_errors) output.appendLine(error);
if (!symbol) {
const byFile = new Map(index.files.map((file, id) => [id, []]));
for (const issue of index.diagnostics) {
const diagnostic = new vscode.Diagnostic(range(issue.location), issue.message, vscode.DiagnosticSeverity.Error);
diagnostic.code = issue.code;
diagnostic.relatedInformation = issue.related.map(([site, reason]) => new vscode.DiagnosticRelatedInformation(
new vscode.Location(uri(index, site.file, root), range(site)), reason));
byFile.get(issue.location.file).push(diagnostic);
}
for (const [file, issues] of byFile) diagnostics.set(uri(index, file, root), issues);
}
return index;
}).catch(error => {
if (cache.get(key) === promise) cache.delete(key);
const message = error.stderr?.trim() || error.message;
output.appendLine(message);
throw new Error(message);
});
cache.set(key, promise);
}
const pending = cache.get(key);
const index = await pending;
if (cache.get(key) !== pending) throw new Error('检查期间源码已变化,请重新查询调用关系。');
return index;
}
async function verify(index, file, root) {
const document = await vscode.workspace.openTextDocument(uri(index, file, root));
if (document.isDirty) throw new Error('调用关系基于已保存源码,请先保存文件。');
const digest = createHash('sha256').update(document.getText()).digest('hex');
if (digest !== index.files[file].sha256) {
invalidate();
throw new Error('源码已变化,请刷新调用关系。');
}
return document;
}
async function current(document) {
if (document.isDirty) return undefined;
const root = sourceOwners.get(document.uri.fsPath) || await projectRoot(document);
if (vscode.workspace.textDocuments.some(value => value.isDirty && isSource(value)
&& (value.uri.fsPath === root || value.uri.fsPath.startsWith(`${root}${path.sep}`)))) return undefined;
const index = await load(root);
const sourcePath = document.uri.fsPath;
const file = index.files.findIndex(source => source.path === sourcePath);
if (file < 0) return undefined;
await verify(index, file, root);
return { root, index, file };
}
async function location(index, site, root) {
await verify(index, site.file, root);
return new vscode.Location(uri(index, site.file, root), range(site));
}
async function checkLinks(root) {
if (!vscode.workspace.isTrusted) throw new Error('请信任工作区后再检查领域流程。');
if (vscode.workspace.textDocuments.some(document => document.isDirty && isSource(document)
&& document.uri.fsPath.startsWith(`${root}${path.sep}`))) throw new Error('请先保存源码,再查看领域流程。');
const command = vscode.workspace.getConfiguration('dever', vscode.Uri.file(root)).get('command');
try {
await execute(command[0], [...command.slice(1), 'inspect', root, '--links', '--check'], { windowsHide: true });
} catch (error) {
throw new Error(error.stderr?.trim() || error.stdout?.trim() || error.message);
}
}
return { load, current, verify, location, checkLinks, invalidate, changed };
}
module.exports = { createInspection, expandIndex, range, uri, isSource, projectRoot };
+73
View File
@@ -0,0 +1,73 @@
{
"comments": {
"lineComment": "#",
"blockComment": ["/*", "*/"]
},
"brackets": [
[
"{",
"}"
],
[
"[",
"]"
],
[
"(",
")"
]
],
"autoClosingPairs": [
{
"open": "{",
"close": "}",
"notIn": [
"string", "comment"
]
},
{
"open": "[",
"close": "]",
"notIn": [
"string", "comment"
]
},
{
"open": "(",
"close": ")",
"notIn": [
"string", "comment"
]
},
{
"open": "\"",
"close": "\"",
"notIn": [
"string", "comment"
]
}
],
"surroundingPairs": [
[
"{",
"}"
],
[
"[",
"]"
],
[
"(",
")"
],
[
"\"",
"\""
]
],
"wordPattern": "[A-Za-z_][A-Za-z0-9_]*",
"indentationRules": {
"increaseIndentPattern": "^\\s*(?:[^\"]|\"(?:\\\\.|[^\"\\\\])*\")*[({\\[]\\s*$",
"decreaseIndentPattern": "^\\s*[})\\]]"
}
}
+98
View File
@@ -0,0 +1,98 @@
const vscode = require('vscode');
const { createInspection, range, uri } = require('./inspection.cjs');
const { at, relations } = require('./graph.cjs');
const { registerReading } = require('./reading.cjs');
const { registerHover } = require('./hover.cjs');
function registerNavigation(context) {
const inspection = createInspection(context);
const selector = { language: 'dever', scheme: 'file' };
async function item(index, symbol, root) {
const first = symbol.declarations[0];
await inspection.verify(index, first.file, root);
const end = symbol.declarations.at(-1).end;
const span = range({ start: first.start, end });
const selected = new vscode.Range(span.start, span.start);
const value = new vscode.CallHierarchyItem(vscode.SymbolKind.Function, symbol.name, symbol.kind,
uri(index, first.file, root), span, selected);
return value;
}
async function lookup(document, position) {
const state = await inspection.current(document);
return state ? { ...state, symbols: at(state.index, state.file, position) } : undefined;
}
context.subscriptions.push(vscode.languages.registerDefinitionProvider(selector, {
async provideDefinition(document, position) {
const state = await lookup(document, position);
if (!state) return [];
return Promise.all(state.symbols.flatMap(symbol => symbol.declarations)
.map(site => inspection.location(state.index, site, state.root)));
}
}));
context.subscriptions.push(vscode.languages.registerReferenceProvider(selector, {
async provideReferences(document, position, options) {
const state = await lookup(document, position);
if (!state) return [];
const ids = new Set(state.symbols.map(symbol => symbol.id));
const sites = state.index.calls.filter(call => ids.has(call.callee)).map(call => call.site);
if (options.includeDeclaration) sites.push(...state.symbols.flatMap(symbol => symbol.declarations));
const unique = [...new Map(sites.map(site => [JSON.stringify(site), site])).values()]
.sort((a, b) => a.file - b.file || a.start.line - b.start.line || a.start.character - b.start.character);
return Promise.all(unique.map(site => inspection.location(state.index, site, state.root)));
}
}));
async function hierarchy(value, incoming) {
const document = await vscode.workspace.openTextDocument(value.uri);
const state = await inspection.current(document);
if (!state) throw new Error('请保存源码后重新打开调用层级。');
const { root, index, file } = state;
const start = value.selectionRange.start;
const symbol = index.symbols.find(symbol => symbol.name === value.name && symbol.declarations.some(site =>
site.file === file && site.start.line === start.line && site.start.character === start.character));
if (!symbol) throw new Error('函数位置已变化,请重新打开调用层级。');
await inspection.verify(index, symbol.declarations[0].file, root);
const result = [];
for (const relation of relations(index, symbol.id, incoming)) {
const target = await item(index, relation.symbol, root);
for (const call of relation.calls) await inspection.verify(index, call.site.file, root);
const ranges = relation.calls.map(call => range(call.site));
result.push(incoming ? new vscode.CallHierarchyIncomingCall(target, ranges)
: new vscode.CallHierarchyOutgoingCall(target, ranges));
}
return result;
}
context.subscriptions.push(vscode.languages.registerCallHierarchyProvider(selector, {
async prepareCallHierarchy(document, position) {
const state = await lookup(document, position);
if (!state) return [];
return (await Promise.all(state.symbols.map(symbol => item(state.index, symbol, state.root)))).filter(Boolean);
},
provideCallHierarchyIncomingCalls(value) { return hierarchy(value, true); },
provideCallHierarchyOutgoingCalls(value) { return hierarchy(value, false); }
}));
context.subscriptions.push(vscode.languages.registerCodeLensProvider(selector, {
onDidChangeCodeLenses: inspection.changed.event,
async provideCodeLenses(document) {
const state = await inspection.current(document);
if (!state) return [];
return state.index.symbols.filter(symbol => symbol.declarations[0].file === state.file).map(symbol => {
const incoming = relations(state.index, symbol.id, true);
const count = incoming.reduce((total, relation) => total + relation.calls.length, 0);
const start = range(symbol.declarations[0]).start;
return new vscode.CodeLens(new vscode.Range(start, start), {
title: `${incoming.length} 个调用方 · ${count} 处调用 · 查看调用关系`,
command: 'dever.showCalls', arguments: [state.root, symbol.name]
});
});
}
}));
registerReading(context, inspection, lookup);
registerHover(context, selector, inspection, lookup);
}
module.exports = { registerNavigation };
+2458
View File
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
{
"name": "dever-language",
"displayName": "Dever Language",
"description": "Dever source navigation, domain documentation, hover and call flows.",
"version": "0.0.2",
"main": "./extension.cjs",
"activationEvents": [
"onLanguage:dever"
],
"publisher": "shemic",
"private": true,
"license": "UNLICENSED",
"engines": {
"vscode": "^1.85.0"
},
"categories": [
"Programming Languages"
],
"keywords": [
"dever",
"markdown",
"syntax highlighting"
],
"repository": {
"type": "git",
"url": "ssh://git@git.dever.cc:2222/dever/core.git",
"directory": "editor/vscode"
},
"contributes": {
"commands": [
{
"command": "dever.previewDocumentation",
"title": "Dever: Preview Documentation"
},
{
"command": "dever.showCalls",
"title": "Dever: Show Calls"
},
{
"command": "dever.openDomainLinks",
"title": "Dever: Open Domain Links"
}
],
"configuration": {
"title": "Dever",
"properties": {
"dever.command": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"default": [
"dever"
],
"description": "Compiler executable followed by fixed arguments; inspect is appended without a shell."
}
}
},
"languages": [
{
"id": "dever",
"aliases": [
"Dever",
"dever"
],
"extensions": [
".dv",
".dever"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "dever",
"scopeName": "source.dever",
"path": "./syntaxes/dever.tmLanguage.json"
},
{
"scopeName": "markdown.dever.codeblock",
"path": "./syntaxes/dever-markdown.tmLanguage.json",
"injectTo": [
"text.html.markdown"
],
"embeddedLanguages": {
"meta.embedded.block.dever": "dever"
},
"tokenTypes": {
"meta.embedded.block.dever": "other"
}
}
]
},
"scripts": {
"build": "node build.cjs",
"vscode:prepublish": "npm run build",
"test": "node ../../test/editor-vscode/highlight.test.cjs",
"test:navigation": "node --test ../../test/editor-vscode/navigation.test.cjs",
"test:flows": "node --test ../../test/editor-vscode/flows.test.cjs",
"package": "vsce package --no-dependencies --skip-license"
},
"devDependencies": {
"@mermaid-js/tiny": "12.2.0",
"@vscode/vsce": "4.0.0",
"esbuild": "0.28.2",
"markdown-it": "15.0.3",
"vscode-oniguruma": "2.0.1",
"vscode-textmate": "9.2.0"
}
}
+141
View File
@@ -0,0 +1,141 @@
const vscode = require('vscode');
const path = require('node:path');
const { relations } = require('./graph.cjs');
const { uri, projectRoot } = require('./inspection.cjs');
const { openFlowPreview } = require('./dist/flow-preview.cjs');
const { description, command } = require('./hover.cjs');
const { workflow } = require('./workflow.cjs');
function registerReading(context, inspection, lookup) {
const changed = new vscode.EventEmitter();
const previews = new Map();
async function verifyTarget(root, filename) {
const index = await inspection.load(root);
const file = index.files.find(file => file.path === filename)
?? index.documentation_files.find(file => file.path === filename);
if (!file) throw new Error('目标不在当前源码或说明索引中。');
return inspection.verify({ files: [file] }, 0, root);
}
context.subscriptions.push(changed, inspection.changed.event(() => {
for (const uri of previews.values()) changed.fire(uri);
}));
context.subscriptions.push(vscode.workspace.onDidCloseTextDocument(document => {
previews.delete(document.uri.toString());
}));
const provider = {
onDidChange: changed.event,
async provideTextDocumentContent(documentUri) {
previews.set(documentUri.toString(), documentUri);
const { root, name } = JSON.parse(documentUri.query);
const index = await inspection.load(root);
const symbols = index.symbols.filter(symbol => symbol.name === name || symbol.source_name === name);
if (!symbols.length) throw new Error(`函数已不存在:${name}`);
const lines = [`# ${name}`, ''];
const details = [index.coverage, ''];
const described = new Set();
if (index.documentation_errors.length) lines.push('**说明校验未通过。** 详见“Dever”输出。', '');
function link(site) {
const file = index.files[site.file];
const target = uri(index, site.file, root).with({ fragment: `L${site.start.line + 1},${site.start.character + 1}` });
return `[${file.path}:${site.start.line + 1}](${target.toString()})`;
}
for (const symbol of symbols) {
const detail = await description(inspection, index, symbol, root);
if (detail && !described.has(detail.symbol)) {
described.add(detail.symbol);
const topic = detail.uri.with({ fragment: `L${detail.line + 1}` });
lines.push(detail.markdown, '', `[主题说明](${topic.toString()})`, '');
}
for (const signature of symbol.signatures) details.push('```dever', signature, '```', '');
for (const site of symbol.declarations) {
await inspection.verify(index, site.file, root);
details.push('## 定义', '', link(site), '');
}
for (const incoming of [true, false]) {
details.push(incoming ? '## 谁调用它' : '## 它调用谁', '');
const related = relations(index, symbol.id, incoming);
if (!related.length) details.push('当前已检查源码中没有此类关系。', '');
else details.push('| 函数 | 领域 | 关系 | 调用位置 | 定义 / 上下游 |', '| --- | --- | --- | --- | --- |');
for (const relation of related) {
for (const call of relation.calls) {
await inspection.verify(index, call.site.file, root);
const definitions = relation.symbol.declarations.map(link).join('、') || '内建操作';
const chain = command('dever.showCalls', [root, relation.symbol.name]);
details.push(`| ${relation.symbol.name} | ${relation.symbol.name.split('.').slice(0, 2).join('.')} | ${call.kind} | ${link(call.site)} | ${definitions} · [上下游](${chain}) |`);
}
}
details.push('');
}
}
if (!described.size) lines.push('尚未提供业务说明。', '');
const selected = await inspection.load(root, name);
for (const symbol of selected.symbols) for (const site of symbol.declarations) await inspection.verify(selected, site.file, root);
const { diagram, labels } = workflow(selected, root);
lines.push(diagram, '', '<details><summary>实现细节</summary>', '');
if (labels.length) lines.push('## 节点原文', '', ...labels);
lines.push(...details, '</details>', '');
return lines.join('\n');
}
};
context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider('dever-calls', provider));
context.subscriptions.push(vscode.commands.registerCommand('dever.showCalls', async (root, name) => {
try {
if (!root || !name) {
const editor = vscode.window.activeTextEditor;
if (!editor) return;
const state = await lookup(editor.document, editor.selection.active);
if (!state) throw new Error('请先保存源码,再查看调用关系。');
if (!state.symbols.length) throw new Error('请把光标放在函数或调用位置。');
root = state.root;
name = state.symbols[0].name;
}
const target = vscode.Uri.from({ scheme: 'dever-calls', path: '/calls.md', query: JSON.stringify({ root, name }) });
await openFlowPreview(context, target, root, {
name,
changed: inspection.changed,
verify: filename => verifyTarget(root, filename),
read: name => provider.provideTextDocumentContent(target.with({ query: JSON.stringify({ root, name }) }))
});
} catch (error) { vscode.window.showErrorMessage(error.message); }
}));
context.subscriptions.push(vscode.commands.registerCommand('dever.previewDocumentation', async (root, name) => {
try {
const document = vscode.window.activeTextEditor?.document;
if (!root || !name) {
if (!document) return;
const state = await lookup(document, vscode.window.activeTextEditor.selection.active);
root = state?.root || await projectRoot(document);
name = state?.symbols[0]?.name;
}
const index = await inspection.load(root);
const symbol = index.symbols.find(value => value.name === name);
const detail = symbol && await description(inspection, index, symbol, root);
if (!detail) throw new Error('该符号尚未提供 doc/ 说明。');
await vscode.commands.executeCommand('markdown.showPreviewToSide', detail.uri.with({ fragment: `L${detail.line + 1}` }));
} catch (error) { vscode.window.showErrorMessage(error.message); }
}));
context.subscriptions.push(vscode.commands.registerCommand('dever.openDomainLinks', async (root, name) => {
try {
const document = vscode.window.activeTextEditor?.document;
if (!root && !document) return;
root ||= await projectRoot(document);
const index = await inspection.load(root);
const symbol = index.symbols.find(value => value.name === name);
const source = symbol?.declarations[0];
const filename = source ? index.files[source.file].path : document.uri.fsPath;
const relative = path.relative(path.join(root, 'module'), filename).split(path.sep);
if (relative.length < 3 || relative[0] === '..') {
throw new Error('请在 module/<组件>/<领域>/ 内的源码中执行此命令。');
}
const target = vscode.Uri.file(path.join(root, 'module', ...relative.slice(0, 2), 'link.md'));
await inspection.checkLinks(root);
const panel = await openFlowPreview(context, target, root, undefined, filename => verifyTarget(root, filename));
const changed = inspection.changed.event(() => panel.dispose());
panel.onDidDispose(() => changed.dispose());
} catch (error) {
vscode.window.showErrorMessage(`${error.message} 可在项目根运行 dever inspect . --links 生成索引。`);
}
}));
}
module.exports = { registerReading };
@@ -0,0 +1,31 @@
{
"name": "Dever Markdown blocks",
"scopeName": "markdown.dever.codeblock",
"injectionSelector": "L:text.html.markdown -markup.fenced_code.block -markup.raw.block -markup.quote -markup.list -meta.embedded.block -comment",
"patterns": [
{
"name": "markup.fenced_code.block.markdown",
"contentName": "meta.embedded.block.dever source.dever",
"begin": "^ {0,3}(`{3,})[ \\t]*(dever)[ \\t]*$",
"end": "^ {0,3}\\1`* *$",
"beginCaptures": {
"1": { "name": "punctuation.definition.markdown.dever" },
"2": { "name": "fenced_code.block.language.markdown" }
},
"endCaptures": { "0": { "name": "punctuation.definition.markdown.dever" } },
"patterns": [{ "include": "source.dever" }]
},
{
"name": "markup.fenced_code.block.markdown",
"contentName": "meta.embedded.block.dever source.dever",
"begin": "^ {0,3}(~{3,})[ \\t]*(dever)[ \\t]*$",
"end": "^ {0,3}\\1~* *$",
"beginCaptures": {
"1": { "name": "punctuation.definition.markdown.dever" },
"2": { "name": "fenced_code.block.language.markdown" }
},
"endCaptures": { "0": { "name": "punctuation.definition.markdown.dever" } },
"patterns": [{ "include": "source.dever" }]
}
]
}
@@ -0,0 +1,197 @@
{
"name": "Dever",
"scopeName": "source.dever",
"patterns": [
{
"include": "#strings"
},
{
"include": "#comments"
},
{
"include": "#unsupported"
},
{
"include": "#declarations"
},
{
"include": "#constants"
},
{
"include": "#numbers"
},
{
"include": "#names"
},
{
"include": "#keywords"
},
{
"include": "#operators"
}
],
"repository": {
"comments": {
"patterns": [
{
"name": "comment.line.number-sign.dever",
"match": "(#).*$",
"captures": { "1": { "name": "punctuation.definition.comment.dever" } }
},
{
"name": "comment.block.dever",
"begin": "/\\*",
"end": "\\*/",
"beginCaptures": { "0": { "name": "punctuation.definition.comment.begin.dever" } },
"endCaptures": { "0": { "name": "punctuation.definition.comment.end.dever" } }
}
]
},
"strings": {
"name": "string.quoted.double.dever",
"begin": "\"",
"end": "\"|$",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.dever"
}
},
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.dever"
}
},
"patterns": [
{
"name": "constant.character.escape.dever",
"match": "\\\\(?:[\"\\\\nrt]|u\\{[0-9A-Fa-f]{1,6}\\})"
},
{
"name": "invalid.illegal.escape.dever",
"match": "\\\\."
}
]
},
"declarations": {
"patterns": [
{
"match": "\\b(type)\\s+([A-Z][A-Za-z0-9_]*)",
"captures": {
"1": {
"name": "storage.type.dever"
},
"2": {
"name": "entity.name.type.dever"
}
}
},
{
"match": "^\\s*(?:(public)\\s+)?(get|post|put|delete|cmd|rest)\\b",
"captures": {
"1": {
"name": "storage.modifier.dever"
},
"2": {
"name": "keyword.control.api.dever"
}
}
},
{
"match": "^\\s*(external)\\s+(command|exec|pip|npm|go)\\b",
"captures": {
"1": {
"name": "storage.modifier.external.dever"
},
"2": {
"name": "keyword.other.external.dever"
}
}
},
{
"name": "keyword.other.declaration.dever",
"match": "^\\s*(database|relation|seed|migrate|sql|index|unique|schedule)\\b"
}
]
},
"constants": {
"name": "constant.language.dever",
"match": "\\b(true|false|null|other)\\b"
},
"unsupported": {
"name": "invalid.illegal.keyword.dever",
"match": "\\b(package|exposes|pure|if|switch|match|when|by|for|while|break|continue|iterate|recur|repeat|return|function|throw|catch|try|import|use|class|interface|unsafe|macro)\\b"
},
"numbers": {
"name": "constant.numeric.dever",
"match": "(?<![A-Za-z0-9_])[0-9](?:_?[0-9])*(?:\\.[0-9](?:_?[0-9])*)?(?:[eE][+-]?[0-9](?:_?[0-9])*)?(?![A-Za-z0-9_])"
},
"names": {
"patterns": [
{
"name": "variable.other.member.dever",
"match": "\\b[a-z_][A-Za-z0-9_]*(?=\\s*:)"
},
{
"name": "entity.name.function.dever",
"match": "\\b[a-z_][A-Za-z0-9_]*(?=\\s*\\()"
},
{
"name": "support.type.dever",
"match": "\\b(Int|Float|Decimal|Bool|Text|Bytes|Secret|List|Map|Stream|AsyncStream|Channel|Task|Group|Json|Date|Time|DateTime|Duration|Id|Uuid|Upload)\\b"
},
{
"name": "entity.name.type.dever",
"match": "\\b[A-Z][A-Za-z0-9_]*\\b"
},
{
"name": "entity.name.namespace.dever",
"match": "\\b(dever|app|domain|data|port|adapter)(?=\\.)"
}
]
},
"keywords": {
"patterns": [
{
"name": "keyword.operator.logical.dever",
"match": "\\b(and|or|not)\\b"
},
{
"name": "storage.modifier.dever",
"match": "\\b(public|authenticated|long|global|transaction|job|recover|fails|private|owner)\\b"
},
{
"name": "keyword.other.data.dever",
"match": "\\b(default|unique|index|raw|lower|upper|before|after|drop)\\b"
},
{
"name": "keyword.other.adapter.dever",
"match": "\\b(setting|lib|file|allow)\\b"
},
{
"name": "keyword.control.dever",
"match": "\\b(rule|flow|loop|each|in|skip|check|else|parallel|const)\\b"
}
]
},
"operators": {
"patterns": [
{
"name": "punctuation.separator.table.dever",
"match": "\\|"
},
{
"name": "keyword.operator.dever",
"match": "//|=>|==|!=|<=|>=|[=+*/%<>?-]"
},
{
"name": "punctuation.section.dever",
"match": "[{}()\\[\\]]"
},
{
"name": "punctuation.separator.dever",
"match": "[,:.]"
}
]
}
}
}
+45
View File
@@ -0,0 +1,45 @@
// 只呈现编译器已经确定的控制边、失败出口与调用位置,不按名字猜业务流程。
const { pathToFileURL } = require('node:url');
function escape(value) {
return value.replaceAll('&', '#38;').replaceAll('"', '#34;').replaceAll('<', '#60;')
.replaceAll('>', '#62;').replaceAll('|', '#124;').replaceAll('\n', ' ').replaceAll(String.fromCharCode(96), '#96;');
}
function workflow(index, root) {
const labels = [];
const diagram = (index.flows || []).map(flow => render(flow, index, root, labels)).join('\n');
return { diagram, labels };
}
function render(flow, index, root, labels) {
const fence = String.fromCharCode(96).repeat(3);
const lines = ['## 执行流程', '', '图显示可能的执行路径。点击节点打开源码,展开调用查看子流程。', '', fence + 'mermaid', 'flowchart TD'];
const full = [];
for (const [id, node] of flow.nodes.entries()) {
const [left, right] = node.kind === 'branch' ? ['{', '}'] : node.kind === 'end' ? ['([', '])'] : ['[', ']'];
const characters = [...node.label];
let label = node.label;
if (characters.length > 48) {
const prefix = characters.slice(0, 42).join('');
const args = node.kind === 'branch' ? -1 : prefix.indexOf('(');
label = (args > 0 ? prefix.slice(0, args) + '(…)' : prefix + '…') + ' [' + (id + 1) + ']';
full.push(`节点 ${id + 1}`, '', ...node.label.split('\n').map(line => ' ' + line), '');
}
lines.push(' n' + id + left + '"' + escape(label) + '"' + right);
if (node.site) {
const target = pathToFileURL(index.files[node.site.file].path);
target.hash = 'L' + (node.site.start.line + 1) + ',' + (node.site.start.character + 1);
lines.push(' click n' + id + ' href "' + target.href + '" "打开源码"');
}
}
for (const edge of flow.edges) lines.push(' n' + edge.from + ' -->' + (edge.label ? '|"' + escape(edge.label) + '"|' : '') + ' n' + edge.to);
lines.push(fence, '');
if (full.length) {
lines.push('带编号节点的原文见「实现细节」。', '');
labels.push('### ' + index.symbols.find(symbol => symbol.id === flow.symbol).name, '', ...full);
}
for (const node of flow.nodes) if (node.target) {
const target = 'command:dever.expandFlow?' + encodeURIComponent(JSON.stringify([root, node.target]));
lines.push('[展开 ' + node.target + '](' + target + ')', '');
}
return lines.join('\n');
}
module.exports = { workflow };