代码编辑器:代码补全、悬停提示、参数提示、边写边检查
- 运行器新增 language-server 模式:常驻语言服务,和编译服务分开;用 Roslyn 的
CompletionService、QuickInfoService(和 VS 的 IntelliSense 同一套引擎),参数提示用语义模型实现;
每个浏览器标签页一份工程,只更新有变化的文件;去掉仿真类库的可空注解(string? → string)
- 编译和语言服务共用同一套编译选项和引用;检查结果带上禁止 API 的报错和中文提示
- 服务端 POST /api/language 转发请求(按用户区分会话,10 秒超时)
- 编辑器:补全("." 触发,选中时取说明)、悬停、参数提示("(" "," 触发);停止输入 1 秒后检查整个工程,
和"运行"时的编译结果以较新的为准
- 实测(2 核):50 个标签页同时检查 1.2 秒内完成,同时补全 0.7 秒;内存约 260 MB
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
89e9956a22
commit
302eae4f13
12 files changed
+667
-20
No files matched your search
@@ -1,8 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
// 代码编辑器:每个文件一个 Monaco 模型(各自保留撤销记录),切换标签页时换模型。
|
||||
// 编译错误以波浪线标在代码里。F5 / Shift+F5 由页面统一处理(见 App.vue),这里不再单独绑定。
|
||||
// 编译错误以波浪线标在代码里:点"运行"时的编译结果,以及停止输入一会儿后的自动检查结果,以较新的为准。
|
||||
// 代码补全、悬停提示、参数提示见 language.ts。F5 / Shift+F5 由页面统一处理,这里不再单独绑定。
|
||||
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'
|
||||
import type { Diagnostic, SourceFile } from '@iot/shared'
|
||||
import { checkProject, registerLanguageFeatures, setLanguageFiles } from './language'
|
||||
import { monaco } from './monaco'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -25,7 +27,10 @@ function modelFor(file: SourceFile) {
|
||||
let model = models.get(file.path)
|
||||
if (!model) {
|
||||
model = monaco.editor.createModel(file.content, 'csharp', monaco.Uri.file(file.path))
|
||||
model.onDidChangeContent(() => emit('change', file.path, model!.getValue()))
|
||||
model.onDidChangeContent(() => {
|
||||
emit('change', file.path, model!.getValue())
|
||||
scheduleCheck()
|
||||
})
|
||||
models.set(file.path, model)
|
||||
} else if (model.getValue() !== file.content) {
|
||||
// 外部换了内容(切换示例、恢复原始代码)
|
||||
@@ -53,9 +58,12 @@ function showActive() {
|
||||
if (editor.value.getModel() !== model) editor.value.setModel(model)
|
||||
}
|
||||
|
||||
/** 当前显示的错误:新的编译结果或自动检查结果到来时替换 */
|
||||
let shown: Diagnostic[] = props.diagnostics
|
||||
|
||||
function applyMarkers() {
|
||||
for (const [path, model] of models) {
|
||||
const markers = props.diagnostics
|
||||
const markers = shown
|
||||
.filter((d) => d.file === path)
|
||||
.map((d) => ({
|
||||
severity: d.severity === 'error' ? monaco.MarkerSeverity.Error : monaco.MarkerSeverity.Warning,
|
||||
@@ -83,7 +91,28 @@ function reveal(path: string, line: number, column: number) {
|
||||
|
||||
defineExpose({ reveal })
|
||||
|
||||
// ---------- 边写边检查:停止输入 1 秒后检查整个工程 ----------
|
||||
const CHECK_DELAY_MS = 1000
|
||||
let checkTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function scheduleCheck() {
|
||||
if (props.readOnly) return
|
||||
clearTimeout(checkTimer)
|
||||
checkTimer = setTimeout(() => void check(), CHECK_DELAY_MS)
|
||||
}
|
||||
|
||||
async function check() {
|
||||
const versions = new Map([...models].map(([path, model]) => [path, model.getVersionId()]))
|
||||
const result = await checkProject()
|
||||
// 检查期间又改了代码:这次的结果作废,等下一次
|
||||
if (!result || [...models].some(([path, model]) => versions.get(path) !== model.getVersionId())) return
|
||||
shown = result
|
||||
applyMarkers()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
registerLanguageFeatures()
|
||||
setLanguageFiles(() => props.files)
|
||||
editor.value = monaco.editor.create(container.value!, {
|
||||
language: 'csharp',
|
||||
theme: 'vs',
|
||||
@@ -111,9 +140,16 @@ watch(() => props.files, () => {
|
||||
applyMarkers()
|
||||
})
|
||||
watch(() => props.activeFile, showActive)
|
||||
watch(() => props.diagnostics, applyMarkers)
|
||||
watch(
|
||||
() => props.diagnostics,
|
||||
(diagnostics) => {
|
||||
shown = diagnostics
|
||||
applyMarkers()
|
||||
},
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearTimeout(checkTimer)
|
||||
editor.value?.dispose()
|
||||
for (const model of models.values()) model.dispose()
|
||||
models.clear()
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// C# 语言功能:代码补全、悬停提示、参数提示、边写边检查。由服务器上的 Roslyn 语言服务计算(和 VS 的 IntelliSense 同一套引擎)。
|
||||
// 请求带上整个工程的文件;服务器按浏览器标签页(session)保存工程,只更新有变化的文件。
|
||||
import type { Diagnostic, SourceFile } from '@iot/shared'
|
||||
import { api } from '../api'
|
||||
import { monaco } from './monaco'
|
||||
|
||||
/** 每个浏览器标签页一个会话 */
|
||||
const session = crypto.randomUUID()
|
||||
|
||||
/** 当前工程的文件,由代码编辑器设置 */
|
||||
let currentFiles: () => SourceFile[] = () => []
|
||||
|
||||
export function setLanguageFiles(files: () => SourceFile[]) {
|
||||
currentFiles = files
|
||||
}
|
||||
|
||||
/** 模型对应的文件路径(模型用 Uri.file(path) 创建) */
|
||||
const pathOf = (model: monaco.editor.ITextModel) => model.uri.path.replace(/^\//, '')
|
||||
|
||||
interface Range {
|
||||
startLine: number
|
||||
startColumn: number
|
||||
endLine: number
|
||||
endColumn: number
|
||||
}
|
||||
|
||||
function request<T>(body: Record<string, unknown>): Promise<T | null> {
|
||||
return api<T & { type: string }>('POST', '/api/language', { ...body, session })
|
||||
.then((r) => (r.type === 'empty' ? null : r))
|
||||
.catch(() => null)
|
||||
}
|
||||
|
||||
const toRange = (r: Range) => new monaco.Range(r.startLine, r.startColumn, r.endLine, r.endColumn)
|
||||
|
||||
const Kind = monaco.languages.CompletionItemKind
|
||||
/** Roslyn 补全项的标签(第一个标签是种类)对应 Monaco 的图标 */
|
||||
const KINDS: Record<string, monaco.languages.CompletionItemKind> = {
|
||||
Class: Kind.Class,
|
||||
Structure: Kind.Struct,
|
||||
Interface: Kind.Interface,
|
||||
Enum: Kind.Enum,
|
||||
EnumMember: Kind.EnumMember,
|
||||
Delegate: Kind.Function,
|
||||
Event: Kind.Event,
|
||||
Field: Kind.Field,
|
||||
Constant: Kind.Constant,
|
||||
Property: Kind.Property,
|
||||
Method: Kind.Method,
|
||||
ExtensionMethod: Kind.Method,
|
||||
Local: Kind.Variable,
|
||||
Parameter: Kind.Variable,
|
||||
RangeVariable: Kind.Variable,
|
||||
Namespace: Kind.Module,
|
||||
Keyword: Kind.Keyword,
|
||||
Snippet: Kind.Snippet,
|
||||
TypeParameter: Kind.TypeParameter,
|
||||
Label: Kind.Reference,
|
||||
}
|
||||
|
||||
interface Completions {
|
||||
range: Range
|
||||
items: { label: string; insert: string; filter: string; sort: string; kind: string; detail: string }[]
|
||||
}
|
||||
|
||||
type Item = monaco.languages.CompletionItem & { index: number }
|
||||
|
||||
let registered = false
|
||||
|
||||
/** 注册到 Monaco(全局只需一次) */
|
||||
export function registerLanguageFeatures() {
|
||||
if (registered) return
|
||||
registered = true
|
||||
|
||||
monaco.languages.registerCompletionItemProvider('csharp', {
|
||||
triggerCharacters: ['.'],
|
||||
async provideCompletionItems(model, position) {
|
||||
const result = await request<Completions>({
|
||||
type: 'complete',
|
||||
files: currentFiles(),
|
||||
file: pathOf(model),
|
||||
line: position.lineNumber,
|
||||
column: position.column,
|
||||
})
|
||||
if (!result) return { suggestions: [] }
|
||||
const range = toRange(result.range)
|
||||
return {
|
||||
suggestions: result.items.map(
|
||||
(item, index): Item => ({
|
||||
index,
|
||||
label: item.label,
|
||||
insertText: item.insert,
|
||||
filterText: item.filter,
|
||||
sortText: item.sort,
|
||||
kind: KINDS[item.kind] ?? Kind.Text,
|
||||
detail: item.detail || undefined,
|
||||
range,
|
||||
}),
|
||||
),
|
||||
}
|
||||
},
|
||||
// 选中某一项时再取它的签名和说明
|
||||
async resolveCompletionItem(item) {
|
||||
const result = await request<{ text: string | null }>({ type: 'completionDetail', index: (item as Item).index })
|
||||
if (result?.text) item.documentation = { value: '```csharp\n' + result.text + '\n```' }
|
||||
return item
|
||||
},
|
||||
})
|
||||
|
||||
monaco.languages.registerHoverProvider('csharp', {
|
||||
async provideHover(model, position) {
|
||||
const result = await request<{ text: string | null; range: Range }>({
|
||||
type: 'hover',
|
||||
files: currentFiles(),
|
||||
file: pathOf(model),
|
||||
line: position.lineNumber,
|
||||
column: position.column,
|
||||
})
|
||||
if (!result?.text) return null
|
||||
// 第一段是签名,用代码格式显示;后面是说明文字
|
||||
const [signature, ...rest] = result.text.split('\n\n')
|
||||
return {
|
||||
range: toRange(result.range),
|
||||
contents: [{ value: '```csharp\n' + signature + '\n```' }, ...rest.map((value) => ({ value }))],
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
monaco.languages.registerSignatureHelpProvider('csharp', {
|
||||
signatureHelpTriggerCharacters: ['(', ','],
|
||||
signatureHelpRetriggerCharacters: [','],
|
||||
async provideSignatureHelp(model, position) {
|
||||
const result = await request<{
|
||||
signatures: { label: string; parameters: [number, number][] }[]
|
||||
activeSignature: number
|
||||
activeParameter: number
|
||||
}>({ type: 'signature', files: currentFiles(), file: pathOf(model), line: position.lineNumber, column: position.column })
|
||||
if (!result || result.signatures.length === 0) return null
|
||||
return {
|
||||
value: {
|
||||
signatures: result.signatures.map((s) => ({ label: s.label, parameters: s.parameters.map((label) => ({ label })) })),
|
||||
activeSignature: result.activeSignature,
|
||||
activeParameter: result.activeParameter,
|
||||
},
|
||||
dispose() {},
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** 整个工程的编译错误和警告(不生成程序集);出错时返回 null */
|
||||
export async function checkProject(): Promise<Diagnostic[] | null> {
|
||||
const result = await request<{ diagnostics: Diagnostic[] }>({ type: 'diagnostics', files: currentFiles() })
|
||||
return result?.diagnostics ?? null
|
||||
}
|
||||
Reference in new issue
Block a user