From 8a6ba6a193fc3b77e7d09d665104a5ae1d04d65e Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 07:07:42 +0900 Subject: [PATCH 01/21] feat: resolve class-generated commands in diagnostics Collect literal class members and scoped instance declarations across project files so generated methods and accessors do not raise undefined-command warnings. Preserve body diagnostics and invalidate cached resolution when class declarations change. Refs #90. --- ls/server/src/diagnostics/calls.ts | 3 ++ ls/server/src/diagnostics/classes.ts | 70 +++++++++++++++++++++++++ ls/server/src/diagnostics/facts.ts | 20 ++++--- ls/server/src/diagnostics/snapshot.ts | 13 +++-- ls/server/test/diagnostics/main.test.ts | 70 ++++++++++++++++++++++++- 5 files changed, 162 insertions(+), 14 deletions(-) create mode 100644 ls/server/src/diagnostics/classes.ts diff --git a/ls/server/src/diagnostics/calls.ts b/ls/server/src/diagnostics/calls.ts index 6daadbd0..a547b679 100644 --- a/ls/server/src/diagnostics/calls.ts +++ b/ls/server/src/diagnostics/calls.ts @@ -19,6 +19,7 @@ import { simpleParameter } from './facts'; export type ResolutionContext = Declarations & { readonly environment: ShellEnvironment; readonly projectRoot: string; + readonly classCommands: ReadonlySet; }; function alias(name: string, word: WordNode, context: ResolutionContext): boolean { @@ -159,6 +160,8 @@ export function analyzeCalls(snapshot: FunctionSnapshot, file: ZshFileHydration, if (!options.ignores || !ignored(options.ignores, word.range.start.line, diagnostic.code)) diagnostics.push(diagnostic); } } + } else if (functionCommand(command) && context.classCommands.has(name)) { + continue; } else if (context.autoloads.has(name) && functionCommand(command)) { continue; } else if (shellKnown(name, command, context) === false && diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts new file mode 100644 index 00000000..24450f0e --- /dev/null +++ b/ls/server/src/diagnostics/classes.ts @@ -0,0 +1,70 @@ +import type { FunctionDefinitionNode, SimpleCommandNode } from '../zshParser/ast'; +import { literalWord } from '../refreshFunctions/word'; + +export type ClassDeclarations = { + readonly definitions: ReadonlyMap>; + readonly instances: ReadonlyMap>; +}; +export type ClassState = { + readonly definitions: Map>; + readonly instances: Map>; + pending?: { + readonly name: string; readonly scope: FunctionDefinitionNode | undefined; + readonly members: Set; methodDepth?: number; + }; +}; + +export function createClassState(): ClassState { + return { definitions: new Map(), instances: new Map() }; +} + +function identifier(value: string | null | undefined): value is string { + return value !== null && value !== undefined && /^[A-Za-z_][A-Za-z0-9_]*$/.test(value) && + !value.startsWith('z_cls_') && !value.startsWith('__z_cls_'); +} + +export function classDeclaration(command: SimpleCommandNode, depth: number, + scope: FunctionDefinitionNode | undefined, state: ClassState): void { + const name = command.commandName && literalWord(command.commandName.word); + const args = command.arguments.map(word => literalWord(word)); + const pending = state.pending; + if (pending?.methodDepth !== undefined) { + if (name === 'z.cls.fn.done' && scope === pending.scope && depth === pending.methodDepth) { + delete pending.methodDepth; + } + return; + } + if (name === 'z.cls.new' && identifier(args[0]) && identifier(args[1]) && args.length === 2) { + const classes = state.instances.get(args[1]) ?? new Set(); + classes.add(args[0]); + state.instances.set(args[1], classes); + } else if (name === 'z.cls.draw' && identifier(args[0]) && args.length === 1 && !pending) { + state.pending = { name: args[0], scope, members: new Set() }; + } else if (pending && scope === pending.scope) { + if (name === 'z.cls.attr' && identifier(args[0]) && args.length === 2) { + pending.members.add(args[0] + '.get'); + pending.members.add(args[0] + '.set'); + } else if (name === 'z.cls.fn' && identifier(args[0]) && args.length >= 1 && args.length <= 2) { + pending.members.add(args[0]); + if (args.length === 1) pending.methodDepth = depth; + } else if (name === 'z.cls.drew' && args.length === 0) { + state.definitions.set(pending.name, pending.members); + delete state.pending; + } else if (name === 'z.cls.abort') { + delete state.pending; + } + } +} + +export function classCommands(declarations: readonly ClassDeclarations[]): ReadonlySet { + const definitions = new Map(declarations.flatMap(file => [...file.definitions])); + const commands = new Set(); + for (const file of declarations) { + for (const [instance, classes] of file.instances) { + for (const name of classes) { + for (const member of definitions.get(name) ?? []) commands.add(instance + '.' + member); + } + } + } + return commands; +} diff --git a/ls/server/src/diagnostics/facts.ts b/ls/server/src/diagnostics/facts.ts index 528722f7..8f7a3274 100644 --- a/ls/server/src/diagnostics/facts.ts +++ b/ls/server/src/diagnostics/facts.ts @@ -8,6 +8,8 @@ import { protocolRange } from '../connection/ast/cursor'; import { literalWord } from '../refreshFunctions/word'; import { formatDiagnostics } from './format'; import { moduleBuiltins } from './modules'; +import { createClassState, classDeclaration } from './classes'; +import type { ClassDeclarations } from './classes'; export type Declarations = { readonly aliases: ReadonlySet; readonly globalAliases: ReadonlySet; @@ -16,7 +18,7 @@ export type Declarations = { }; export type FileFacts = { readonly calls: readonly SimpleCommandNode[]; readonly base: readonly Diagnostics[]; - readonly declarations: Declarations; + readonly declarations: Declarations; readonly classes: ClassDeclarations; }; type Usage = { readonly definition: FunctionDefinitionNode; readonly depth: number; @@ -91,6 +93,7 @@ function declarations(command: SimpleCommandNode, sets: { export function collectFileFacts(file: ZshFileHydration): FileFacts { const calls: SimpleCommandNode[] = []; const usages: Usage[] = []; + const classes = createClassState(); const active: Usage[] = []; const sets = { aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), autoloads: new Set(), builtins: new Set() }; @@ -105,13 +108,14 @@ export function collectFileFacts(file: ZshFileHydration): FileFacts { if (node.kind === 'simpleCommand') { if (node.commandName) calls.push(node); declarations(node, sets); - if (current && node.commandName && literalWord(node.commandName.word) === 'z.arg.named') { - const word = node.arguments[0]; - const name = word && literalWord(word); - if (name) use(current, name); - } + classDeclaration(node, depth, current?.definition, classes); + } + if (!current || classes.pending?.methodDepth !== undefined && classes.pending.scope === current.definition) return; + if (node.kind === 'simpleCommand' && node.commandName && literalWord(node.commandName.word) === 'z.arg.named') { + const word = node.arguments[0]; + const name = word && literalWord(word); + if (name) use(current, name); } - if (!current) return; if (node.kind === 'word') wordUsage(node, current); if (node.kind === 'opaqueCommand' || node.kind === 'unknown' || node.kind === 'hereDocument' && !node.quoted) current.uncertain = true; @@ -135,5 +139,5 @@ export function collectFileFacts(file: ZshFileHydration): FileFacts { code: diagnostic.kind, range: protocolRange(diagnostic.range), message: diagnostic.message, source: 'z-ls/parser' }); for (const diagnostic of file.hydrationDiagnostics) base.push({ severity: DiagnosticSeverity.Warning, code: diagnostic.kind, range: protocolRange(diagnostic.range), message: diagnostic.message, source: 'z-ls/documentation' }); - return { calls, base, declarations: sets }; + return { calls, base, declarations: sets, classes }; } diff --git a/ls/server/src/diagnostics/snapshot.ts b/ls/server/src/diagnostics/snapshot.ts index 576e3322..3339c8dc 100644 --- a/ls/server/src/diagnostics/snapshot.ts +++ b/ls/server/src/diagnostics/snapshot.ts @@ -9,6 +9,7 @@ import { collectFileFacts } from './facts'; import type { FileFacts, Declarations } from './facts'; import { embeddedCallDiagnostics } from './embedded'; import { sameCallContracts } from './contracts'; +import { classCommands } from './classes'; import type { ResolutionContext } from './calls'; import type { Diagnostics } from './type'; @@ -23,7 +24,8 @@ export type DiagnosticSnapshot = { export function createDiagnosticSnapshot(): DiagnosticSnapshot { return { revision: 0, targets: new Map(), context: { environment: emptyShellEnvironment(), projectRoot: '', - aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), autoloads: new Set(), builtins: new Set() }, files: new Map() }; + classCommands: new Set(), aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), + autoloads: new Set(), builtins: new Set() }, files: new Map() }; } function sameSet(left: ReadonlySet, right: ReadonlySet): boolean { @@ -32,6 +34,7 @@ function sameSet(left: ReadonlySet, right: ReadonlySet): boolean function resolutionContext(facts: readonly FileFacts[], environment: ShellEnvironment, projectRoot: string, previous: ResolutionContext): ResolutionContext { + const generated = classCommands(facts.map(file => file.classes)); const declarations: Declarations = { aliases: new Set(facts.flatMap(file => [...file.declarations.aliases])), globalAliases: new Set(facts.flatMap(file => [...file.declarations.globalAliases])), @@ -42,8 +45,8 @@ function resolutionContext(facts: readonly FileFacts[], environment: ShellEnviro if (environment === previous.environment && projectRoot === previous.projectRoot && sameSet(declarations.aliases, previous.aliases) && sameSet(declarations.globalAliases, previous.globalAliases) && sameSet(declarations.suffixAliases, previous.suffixAliases) && sameSet(declarations.autoloads, previous.autoloads) && - sameSet(declarations.builtins, previous.builtins)) return previous; - return { ...declarations, environment, projectRoot }; + sameSet(declarations.builtins, previous.builtins) && sameSet(generated, previous.classCommands)) return previous; + return { ...declarations, environment, projectRoot, classCommands: generated }; } function suppressed(file: ZshFileHydration, diagnostics: readonly Diagnostics[]): readonly Diagnostics[] { @@ -78,10 +81,10 @@ export function refreshDiagnosticSnapshot({ snapshot, environment, previous = cr reusableContracts && previous.context === context) { files.set(uri, cached); } else { - const local = input.project ? context : resolutionContext([current], environment, + const local = input.project ? context : resolutionContext([...projectFacts, current], environment, context.projectRoot, context); const effective = input.project ? context : { - ...context, aliases: new Set([...context.aliases, ...local.aliases]), + ...context, classCommands: local.classCommands, aliases: new Set([...context.aliases, ...local.aliases]), globalAliases: new Set([...context.globalAliases, ...local.globalAliases]), suffixAliases: new Set([...context.suffixAliases, ...local.suffixAliases]), autoloads: new Set([...context.autoloads, ...local.autoloads]), diff --git a/ls/server/test/diagnostics/main.test.ts b/ls/server/test/diagnostics/main.test.ts index e2a5e40b..99b54556 100644 --- a/ls/server/test/diagnostics/main.test.ts +++ b/ls/server/test/diagnostics/main.test.ts @@ -42,7 +42,7 @@ function fixture(content: string, definitions = definition, shell = environment) return { root, snapshot, diagnostics, document, definitionUri, items: validateTextDocument({ diagnostics, textDocument: document }) }; } -const semantic = (items: ReturnType) => +const semantic = (items: Readonly>) => items.filter(item => ['missing-positional-argument', 'missing-named-argument', 'undefined-command'].includes(item.code ?? '')); describe('call diagnostics@AST', () => { @@ -311,3 +311,71 @@ describe('hydrated controls and diagnostics cache', () => { expect(last?.range.start).toEqual({ line: 1, character: 7 }); }); }); + +const classApi = ['z.cls.draw() { : }', 'z.cls.attr() { : }', 'z.cls.fn() { : }', + 'z.cls.fn.done() { : }', 'z.cls.drew() { : }', 'z.cls.new() { : }'].join('\n') + '\n'; +const counterClass = [ + 'z.cls.draw Counter; {', + ' z.cls.attr count 0', + ' z.cls.fn increment', + ' (( ++count ))', + ' z.cls.fn.done', + ' z.cls.drew', + '}', '', +].join('\n'); + +describe('class DSL command diagnostics', () => { + test('別ファイルのクラスから生成されるメソッドと属性を認識し、タイプミスは診断する', () => { + const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.count.get\ncounter.count.set 3\ncounter.typo\n', + classApi + counterClass); + expect(semantic(f.items)).toMatchObject([{ code: 'undefined-command', + message: 'counter.typo is not defined in the project or shell environment.' }]); + expect(semantic(f.items)).toHaveLength(1); + }); + test('メソッド内の未定義コマンドを元ファイルの位置で診断する', () => { + const source = counterClass.replace('(( ++count ))', 'missing_inside_method'); + const f = fixture('', classApi + source); + expect(semantic(f.diagnostics.files.get(f.definitionUri)?.items ?? [])).toMatchObject([{ + code: 'undefined-command', range: { start: { line: 9, character: 4 } }, + }]); + }); + test('メソッドの編集で未編集の呼出元を再診断する', () => { + const f = fixture('z.cls.new Counter counter\ncounter.increment\n', classApi + counterClass); + expect(semantic(f.items)).toEqual([]); + const changed = TextDocument.create(f.definitionUri, 'shellscript', 1, + classApi + counterClass.replace('z.cls.fn increment', 'z.cls.fn reset')); + const snapshot = refreshFunctionSnapshot({ projectRoot: f.root, documents: [f.document, changed], previous: f.snapshot }); + const next = refreshDiagnosticSnapshot({ snapshot, environment, previous: f.diagnostics }); + expect(semantic(validateTextDocument({ diagnostics: next, textDocument: f.document }))) + .toMatchObject([{ code: 'undefined-command' }]); + }); + test('入れ子の関数や文字列内の終了名でメソッドを閉じない', () => { + const source = counterClass.replace('(( ++count ))', + 'helper() { z.cls.fn.done }\n print "z.cls.fn.done"\n z.cls.fn imaginary'); + const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.imaginary\n', classApi + source); + expect(semantic(f.items)).toHaveLength(1); + expect(semantic(f.items)[0]?.message).toContain('counter.imaginary'); + }); +}); + +describe('scoped class references', () => { + test('スコープによって異なるクラスを指す同名変数の呼出を認識する', () => { + const arrayClass = ['z.cls.draw ArrayBox; {', 'z.cls.fn fill', ':', 'z.cls.fn.done', 'z.cls.drew', '}', ''].join('\n'); + const source = ['z.cls.new Counter counter', 'counter.increment', 'inner() {', 'local counter', + 'z.cls.new ArrayBox counter', 'counter.fill', '}', 'counter.count.get', ''].join('\n'); + expect(semantic(fixture(source, classApi + counterClass + arrayClass).items)).toEqual([]); + }); + test('外側の関数の引数使用へメソッド内の引数を混ぜない', () => { + const source = '# $1: loader argument\nload() {\n' + + counterClass.replace('(( ++count ))', 'print "$1"') + '}\n'; + const f = fixture('', classApi + source); + expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); + }); + test('メソッドの名前付き引数取得を外側の引数使用へ混ぜない', () => { + const source = '# $option: loader option\nload() {\n' + + counterClass.replace('(( ++count ))', 'z.arg.named option "$@"') + '}\n'; + const f = fixture('', classApi + 'z.arg.named() { : }\n' + source); + expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); + }); + +}); From 3b02d802d146369f17451d2a430c46c5c04c2e70 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 08:23:00 +0900 Subject: [PATCH 02/21] refactor: make class declaration state and tests explicit Return readonly definition and method capture states without mutating prior maps. Test declaration transitions with real AST fixtures and keep class command integration in dedicated files instead of the general diagnostics suite. --- ls/server/src/diagnostics/classes.ts | 68 ++++++----- ls/server/src/diagnostics/facts.ts | 6 +- .../diagnostics/classDeclarations.test.ts | 106 +++++++++++++++++ ls/server/test/diagnostics/classes.test.ts | 109 ++++++++++++++++++ ls/server/test/diagnostics/main.test.ts | 70 +---------- 5 files changed, 255 insertions(+), 104 deletions(-) create mode 100644 ls/server/test/diagnostics/classDeclarations.test.ts create mode 100644 ls/server/test/diagnostics/classes.test.ts diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts index 24450f0e..ceaea900 100644 --- a/ls/server/src/diagnostics/classes.ts +++ b/ls/server/src/diagnostics/classes.ts @@ -5,17 +5,17 @@ export type ClassDeclarations = { readonly definitions: ReadonlyMap>; readonly instances: ReadonlyMap>; }; -export type ClassState = { - readonly definitions: Map>; - readonly instances: Map>; - pending?: { - readonly name: string; readonly scope: FunctionDefinitionNode | undefined; - readonly members: Set; methodDepth?: number; - }; +type ClassDefinition = { + readonly name: string; readonly scope: FunctionDefinitionNode | undefined; + readonly members: ReadonlySet; }; +type ClassCapture = + | { readonly kind: 'definition'; readonly definition: ClassDefinition } + | { readonly kind: 'method'; readonly definition: ClassDefinition; readonly depth: number }; +export type ClassState = ClassDeclarations & { readonly pending: ClassCapture | null }; export function createClassState(): ClassState { - return { definitions: new Map(), instances: new Map() }; + return { definitions: new Map(), instances: new Map(), pending: null }; } function identifier(value: string | null | undefined): value is string { @@ -24,36 +24,40 @@ function identifier(value: string | null | undefined): value is string { } export function classDeclaration(command: SimpleCommandNode, depth: number, - scope: FunctionDefinitionNode | undefined, state: ClassState): void { + scope: FunctionDefinitionNode | undefined, state: ClassState): ClassState { const name = command.commandName && literalWord(command.commandName.word); const args = command.arguments.map(word => literalWord(word)); const pending = state.pending; - if (pending?.methodDepth !== undefined) { - if (name === 'z.cls.fn.done' && scope === pending.scope && depth === pending.methodDepth) { - delete pending.methodDepth; - } - return; + if (pending?.kind === 'method') { + return name === 'z.cls.fn.done' && scope === pending.definition.scope && depth === pending.depth ? + { ...state, pending: { kind: 'definition', definition: pending.definition } } : state; } if (name === 'z.cls.new' && identifier(args[0]) && identifier(args[1]) && args.length === 2) { - const classes = state.instances.get(args[1]) ?? new Set(); - classes.add(args[0]); - state.instances.set(args[1], classes); - } else if (name === 'z.cls.draw' && identifier(args[0]) && args.length === 1 && !pending) { - state.pending = { name: args[0], scope, members: new Set() }; - } else if (pending && scope === pending.scope) { - if (name === 'z.cls.attr' && identifier(args[0]) && args.length === 2) { - pending.members.add(args[0] + '.get'); - pending.members.add(args[0] + '.set'); - } else if (name === 'z.cls.fn' && identifier(args[0]) && args.length >= 1 && args.length <= 2) { - pending.members.add(args[0]); - if (args.length === 1) pending.methodDepth = depth; - } else if (name === 'z.cls.drew' && args.length === 0) { - state.definitions.set(pending.name, pending.members); - delete state.pending; - } else if (name === 'z.cls.abort') { - delete state.pending; - } + const instances = new Map(state.instances); + instances.set(args[1], new Set([...(instances.get(args[1]) ?? []), args[0]])); + return { ...state, instances }; + } + if (name === 'z.cls.draw' && identifier(args[0]) && args.length === 1 && !pending) { + return { ...state, pending: { kind: 'definition', definition: { name: args[0], scope, members: new Set() } } }; + } + if (!pending || scope !== pending.definition.scope) return state; + + const definition = pending.definition; + if (name === 'z.cls.attr' && identifier(args[0]) && args.length === 2) { + const members = new Set([...definition.members, args[0] + '.get', args[0] + '.set']); + return { ...state, pending: { kind: 'definition', definition: { ...definition, members } } }; + } + if (name === 'z.cls.fn' && identifier(args[0]) && args.length >= 1 && args.length <= 2) { + const next = { ...definition, members: new Set([...definition.members, args[0]]) }; + return { ...state, pending: args.length === 1 ? + { kind: 'method', definition: next, depth } : { kind: 'definition', definition: next } }; + } + if (name === 'z.cls.drew' && args.length === 0) { + const definitions = new Map(state.definitions); + definitions.set(definition.name, definition.members); + return { ...state, definitions, pending: null }; } + return name === 'z.cls.abort' ? { ...state, pending: null } : state; } export function classCommands(declarations: readonly ClassDeclarations[]): ReadonlySet { diff --git a/ls/server/src/diagnostics/facts.ts b/ls/server/src/diagnostics/facts.ts index 8f7a3274..b78fdf93 100644 --- a/ls/server/src/diagnostics/facts.ts +++ b/ls/server/src/diagnostics/facts.ts @@ -93,7 +93,7 @@ function declarations(command: SimpleCommandNode, sets: { export function collectFileFacts(file: ZshFileHydration): FileFacts { const calls: SimpleCommandNode[] = []; const usages: Usage[] = []; - const classes = createClassState(); + let classes = createClassState(); const active: Usage[] = []; const sets = { aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), autoloads: new Set(), builtins: new Set() }; @@ -108,9 +108,9 @@ export function collectFileFacts(file: ZshFileHydration): FileFacts { if (node.kind === 'simpleCommand') { if (node.commandName) calls.push(node); declarations(node, sets); - classDeclaration(node, depth, current?.definition, classes); + classes = classDeclaration(node, depth, current?.definition, classes); } - if (!current || classes.pending?.methodDepth !== undefined && classes.pending.scope === current.definition) return; + if (!current || (classes.pending?.kind === 'method' && classes.pending.definition.scope === current.definition)) return; if (node.kind === 'simpleCommand' && node.commandName && literalWord(node.commandName.word) === 'z.arg.named') { const word = node.arguments[0]; const name = word && literalWord(word); diff --git a/ls/server/test/diagnostics/classDeclarations.test.ts b/ls/server/test/diagnostics/classDeclarations.test.ts new file mode 100644 index 00000000..7e8b1238 --- /dev/null +++ b/ls/server/test/diagnostics/classDeclarations.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, test } from 'vitest'; +import { findAll } from '../../src/zshParser/ast'; +import { createZshFileHydration } from '../../src/zshHydrator'; +import { createClassState, classDeclaration, classCommands } from '../../src/diagnostics/classes'; + +function command(content: string) { + const file = createZshFileHydration({ sourceFile: 'classes.zsh', file: 'classes.zsh', content }); + const node = findAll(file.ast, 'simpleCommand')[0]; + if (!node) throw new Error('Expected a command in the class fixture'); + return node; +} + +describe('createClassState', () => { + test('空の独立した状態を返す', () => { + const first = createClassState(); + const second = createClassState(); + expect(first.definitions.size).toBe(0); + expect(first.instances.size).toBe(0); + expect(first.pending).toBeNull(); + expect(first.definitions).not.toBe(second.definitions); + expect(first.instances).not.toBe(second.instances); + }); +}); + +describe('classDeclaration', () => { + test('入力を変更せずに定義を開始する', () => { + const before = createClassState(); + const next = classDeclaration(command('z.cls.draw Counter'), 1, undefined, before); + expect(before.pending).toBeNull(); + expect(next.pending).toMatchObject({ kind: 'definition', definition: { name: 'Counter' } }); + expect(next.definitions.size).toBe(0); + }); + + test('属性のget/setを追加し、前のメンバー集合を保持する', () => { + const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); + const next = classDeclaration(command('z.cls.attr count 0'), 1, undefined, drawing); + expect(drawing.pending?.definition.members.size).toBe(0); + expect([...next.pending?.definition.members ?? []]).toEqual(['count.get', 'count.set']); + }); + + test('同じ深さの終了マーカーで本体を閉じ、公開時だけ定義に加える', () => { + const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); + const method = classDeclaration(command('z.cls.fn increment'), 1, undefined, drawing); + expect(method.pending?.kind).toBe('method'); + expect(classDeclaration(command('z.cls.fn.done'), 2, undefined, method)).toBe(method); + const ended = classDeclaration(command('z.cls.fn.done'), 1, undefined, method); + expect(ended.pending?.kind).toBe('definition'); + expect(method.pending?.kind).toBe('method'); + const published = classDeclaration(command('z.cls.drew'), 1, undefined, ended); + expect([...published.definitions.get('Counter') ?? []]).toEqual(['increment']); + expect(published.pending).toBeNull(); + expect(ended.definitions.size).toBe(0); + }); + + test('inline本体は捕捉状態に入らず登録する', () => { + const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); + const next = classDeclaration(command("z.cls.fn value 'REPLY=$count'"), 1, undefined, drawing); + expect(next.pending?.kind).toBe('definition'); + expect([...next.pending?.definition.members ?? []]).toEqual(['value']); + }); + + test('入れ子の別関数にある終了名では本体を閉じない', () => { + const file = createZshFileHydration({ sourceFile: 'scope.zsh', file: 'scope.zsh', content: 'helper() { : }' }); + const scope = file.functions[0]?.definition; + if (!scope) throw new Error('Expected a function scope'); + const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); + const method = classDeclaration(command('z.cls.fn run'), 1, undefined, drawing); + expect(classDeclaration(command('z.cls.fn.done'), 1, scope, method)).toBe(method); + }); + + test('同名bindingの候補を入力集合を変えずに追加する', () => { + const first = classDeclaration(command('z.cls.new Counter object'), 1, undefined, createClassState()); + const next = classDeclaration(command('z.cls.new ArrayBox object'), 1, undefined, first); + expect([...first.instances.get('object') ?? []]).toEqual(['Counter']); + expect([...next.instances.get('object') ?? []]).toEqual(['Counter', 'ArrayBox']); + }); + + test.each(['z.cls.new $class object', 'z.cls.new z_cls_reserved object', 'z.cls.new Counter bad-name', + 'z.cls.new Counter', 'z.cls.draw bad-name'])('不完全・動的・予約済みの宣言を登録しない: %s', source => { + const before = createClassState(); + expect(classDeclaration(command(source), 1, undefined, before)).toBe(before); + }); + + test('abortで未公開の定義を破棄し、入力状態を保持する', () => { + const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); + const next = classDeclaration(command('z.cls.abort'), 1, undefined, drawing); + expect(next.pending).toBeNull(); + expect(drawing.pending?.definition.name).toBe('Counter'); + expect(next.definitions.size).toBe(0); + }); +}); + +describe('classCommands', () => { + test('別ファイルの定義と複数の候補を組み合わせ、入力集合を保持する', () => { + const definitions = new Map([['Counter', new Set(['increment', 'count.get'])], ['ArrayBox', new Set(['fill'])]]); + const instances = new Map([['object', new Set(['Counter', 'ArrayBox'])]]); + const result = classCommands([{ definitions, instances: new Map() }, { definitions: new Map(), instances }]); + expect([...result]).toEqual(['object.increment', 'object.count.get', 'object.fill']); + expect(definitions.size).toBe(2); + expect(instances.get('object')?.size).toBe(2); + }); + + test('未公開クラスからはコマンドを生成しない', () => { + expect([...classCommands([{ definitions: new Map(), instances: new Map([['object', new Set(['Missing'])]]) }])]).toEqual([]); + }); +}); diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts new file mode 100644 index 00000000..99adf770 --- /dev/null +++ b/ls/server/test/diagnostics/classes.test.ts @@ -0,0 +1,109 @@ +import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { refreshFunctionSnapshot } from '../../src/refreshFunctions/main'; +import { refreshDiagnosticSnapshot } from '../../src/diagnostics/snapshot'; +import { readShellEnvironment, emptyShellEnvironment } from '../../src/diagnostics/environment'; +import type { ShellEnvironment } from '../../src/diagnostics/environment'; +import { validateTextDocument } from '../../src/diagnostics/main'; + +const roots: string[] = []; +const environmentRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'z-class-diag-shell-')); +let environment: ShellEnvironment = emptyShellEnvironment(); +beforeAll(async () => { + fs.writeFileSync(path.join(environmentRoot, '.zshrc'), ''); + environment = await readShellEnvironment({ env: { ...process.env, ZDOTDIR: environmentRoot } }); + expect(environment.kind).toBe('available'); +}); +afterAll(() => fs.rmSync(environmentRoot, { recursive: true, force: true })); +afterEach(() => { + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); +function fixture(content: string, definitions: string) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'z-class-diag-')); + roots.push(root); + const definitionUri = pathToFileURL(path.join(root, 'definition.zsh')).href; + fs.writeFileSync(path.join(root, 'definition.zsh'), definitions); + const document = TextDocument.create(pathToFileURL(path.join(root, 'caller.zsh')).href, 'shellscript', 1, content); + const snapshot = refreshFunctionSnapshot({ projectRoot: root, documents: [document] }); + const diagnostics = refreshDiagnosticSnapshot({ snapshot, environment }); + return { root, snapshot, diagnostics, document, definitionUri, + items: validateTextDocument({ diagnostics, textDocument: document }) }; +} +const semantic = (items: Readonly>) => + items.filter(item => ['missing-positional-argument', 'missing-named-argument', 'undefined-command'].includes(item.code ?? '')); + +const classApi = ['z.cls.draw() { : }', 'z.cls.attr() { : }', 'z.cls.fn() { : }', + 'z.cls.fn.done() { : }', 'z.cls.drew() { : }', 'z.cls.new() { : }'].join('\n') + '\n'; +const counterClass = [ + 'z.cls.draw Counter; {', + ' z.cls.attr count 0', + ' z.cls.fn increment', + ' (( ++count ))', + ' z.cls.fn.done', + ' z.cls.drew', + '}', '', +].join('\n'); + +describe('class DSL command diagnostics', () => { + test('別ファイルのクラスから生成されるメソッドと属性を認識し、タイプミスは診断する', () => { + const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.count.get\ncounter.count.set 3\ncounter.typo\n', + classApi + counterClass); + expect(semantic(f.items)).toMatchObject([{ code: 'undefined-command', + message: 'counter.typo is not defined in the project or shell environment.' }]); + expect(semantic(f.items)).toHaveLength(1); + }); + + test('メソッド内の未定義コマンドを元ファイルの位置で診断する', () => { + const source = counterClass.replace('(( ++count ))', 'missing_inside_method'); + const f = fixture('', classApi + source); + expect(semantic(f.diagnostics.files.get(f.definitionUri)?.items ?? [])).toMatchObject([{ + code: 'undefined-command', range: { start: { line: 9, character: 4 } }, + }]); + }); + + test('メソッドの編集で未編集の呼出元を再診断する', () => { + const f = fixture('z.cls.new Counter counter\ncounter.increment\n', classApi + counterClass); + expect(semantic(f.items)).toEqual([]); + const changed = TextDocument.create(f.definitionUri, 'shellscript', 1, + classApi + counterClass.replace('z.cls.fn increment', 'z.cls.fn reset')); + const snapshot = refreshFunctionSnapshot({ projectRoot: f.root, documents: [f.document, changed], previous: f.snapshot }); + const next = refreshDiagnosticSnapshot({ snapshot, environment, previous: f.diagnostics }); + expect(semantic(validateTextDocument({ diagnostics: next, textDocument: f.document }))) + .toMatchObject([{ code: 'undefined-command' }]); + }); + + test('入れ子の関数や文字列内の終了名でメソッドを閉じない', () => { + const source = counterClass.replace('(( ++count ))', + 'helper() { z.cls.fn.done }\n print "z.cls.fn.done"\n z.cls.fn imaginary'); + const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.imaginary\n', classApi + source); + expect(semantic(f.items)).toHaveLength(1); + expect(semantic(f.items)[0]?.message).toContain('counter.imaginary'); + }); +}); + +describe('scoped class references', () => { + test('スコープによって異なるクラスを指す同名変数の呼出を認識する', () => { + const arrayClass = ['z.cls.draw ArrayBox; {', 'z.cls.fn fill', ':', 'z.cls.fn.done', 'z.cls.drew', '}', ''].join('\n'); + const source = ['z.cls.new Counter counter', 'counter.increment', 'inner() {', 'local counter', + 'z.cls.new ArrayBox counter', 'counter.fill', '}', 'counter.count.get', ''].join('\n'); + expect(semantic(fixture(source, classApi + counterClass + arrayClass).items)).toEqual([]); + }); + + test('外側の関数の引数使用へメソッド内の引数を混ぜない', () => { + const source = '# $1: loader argument\nload() {\n' + + counterClass.replace('(( ++count ))', 'print "$1"') + '}\n'; + const f = fixture('', classApi + source); + expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); + }); + + test('メソッドの名前付き引数取得を外側の引数使用へ混ぜない', () => { + const source = '# $option: loader option\nload() {\n' + + counterClass.replace('(( ++count ))', 'z.arg.named option "$@"') + '}\n'; + const f = fixture('', classApi + 'z.arg.named() { : }\n' + source); + expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); + }); +}); diff --git a/ls/server/test/diagnostics/main.test.ts b/ls/server/test/diagnostics/main.test.ts index 99b54556..e2a5e40b 100644 --- a/ls/server/test/diagnostics/main.test.ts +++ b/ls/server/test/diagnostics/main.test.ts @@ -42,7 +42,7 @@ function fixture(content: string, definitions = definition, shell = environment) return { root, snapshot, diagnostics, document, definitionUri, items: validateTextDocument({ diagnostics, textDocument: document }) }; } -const semantic = (items: Readonly>) => +const semantic = (items: ReturnType) => items.filter(item => ['missing-positional-argument', 'missing-named-argument', 'undefined-command'].includes(item.code ?? '')); describe('call diagnostics@AST', () => { @@ -311,71 +311,3 @@ describe('hydrated controls and diagnostics cache', () => { expect(last?.range.start).toEqual({ line: 1, character: 7 }); }); }); - -const classApi = ['z.cls.draw() { : }', 'z.cls.attr() { : }', 'z.cls.fn() { : }', - 'z.cls.fn.done() { : }', 'z.cls.drew() { : }', 'z.cls.new() { : }'].join('\n') + '\n'; -const counterClass = [ - 'z.cls.draw Counter; {', - ' z.cls.attr count 0', - ' z.cls.fn increment', - ' (( ++count ))', - ' z.cls.fn.done', - ' z.cls.drew', - '}', '', -].join('\n'); - -describe('class DSL command diagnostics', () => { - test('別ファイルのクラスから生成されるメソッドと属性を認識し、タイプミスは診断する', () => { - const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.count.get\ncounter.count.set 3\ncounter.typo\n', - classApi + counterClass); - expect(semantic(f.items)).toMatchObject([{ code: 'undefined-command', - message: 'counter.typo is not defined in the project or shell environment.' }]); - expect(semantic(f.items)).toHaveLength(1); - }); - test('メソッド内の未定義コマンドを元ファイルの位置で診断する', () => { - const source = counterClass.replace('(( ++count ))', 'missing_inside_method'); - const f = fixture('', classApi + source); - expect(semantic(f.diagnostics.files.get(f.definitionUri)?.items ?? [])).toMatchObject([{ - code: 'undefined-command', range: { start: { line: 9, character: 4 } }, - }]); - }); - test('メソッドの編集で未編集の呼出元を再診断する', () => { - const f = fixture('z.cls.new Counter counter\ncounter.increment\n', classApi + counterClass); - expect(semantic(f.items)).toEqual([]); - const changed = TextDocument.create(f.definitionUri, 'shellscript', 1, - classApi + counterClass.replace('z.cls.fn increment', 'z.cls.fn reset')); - const snapshot = refreshFunctionSnapshot({ projectRoot: f.root, documents: [f.document, changed], previous: f.snapshot }); - const next = refreshDiagnosticSnapshot({ snapshot, environment, previous: f.diagnostics }); - expect(semantic(validateTextDocument({ diagnostics: next, textDocument: f.document }))) - .toMatchObject([{ code: 'undefined-command' }]); - }); - test('入れ子の関数や文字列内の終了名でメソッドを閉じない', () => { - const source = counterClass.replace('(( ++count ))', - 'helper() { z.cls.fn.done }\n print "z.cls.fn.done"\n z.cls.fn imaginary'); - const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.imaginary\n', classApi + source); - expect(semantic(f.items)).toHaveLength(1); - expect(semantic(f.items)[0]?.message).toContain('counter.imaginary'); - }); -}); - -describe('scoped class references', () => { - test('スコープによって異なるクラスを指す同名変数の呼出を認識する', () => { - const arrayClass = ['z.cls.draw ArrayBox; {', 'z.cls.fn fill', ':', 'z.cls.fn.done', 'z.cls.drew', '}', ''].join('\n'); - const source = ['z.cls.new Counter counter', 'counter.increment', 'inner() {', 'local counter', - 'z.cls.new ArrayBox counter', 'counter.fill', '}', 'counter.count.get', ''].join('\n'); - expect(semantic(fixture(source, classApi + counterClass + arrayClass).items)).toEqual([]); - }); - test('外側の関数の引数使用へメソッド内の引数を混ぜない', () => { - const source = '# $1: loader argument\nload() {\n' + - counterClass.replace('(( ++count ))', 'print "$1"') + '}\n'; - const f = fixture('', classApi + source); - expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); - }); - test('メソッドの名前付き引数取得を外側の引数使用へ混ぜない', () => { - const source = '# $option: loader option\nload() {\n' + - counterClass.replace('(( ++count ))', 'z.arg.named option "$@"') + '}\n'; - const f = fixture('', classApi + 'z.arg.named() { : }\n' + source); - expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); - }); - -}); From 2ed7721be5c21191f292c0bdbc2b65d35e31ad88 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 13:10:01 +0900 Subject: [PATCH 03/21] refactor: share literal word decoding below hydration Move the existing decoder to the AST word layer so hydrators can consume it without depending on function resolution. Keep the old import as a compatibility re-export and cover literal, dynamic and prefix inputs. --- ls/server/src/refreshFunctions/word.ts | 8 +--- ls/server/src/zshParser/ast/word/literal.ts | 8 ++++ .../test/zshParser/ast/word/literal.test.ts | 41 +++++++++++++++++++ 3 files changed, 50 insertions(+), 7 deletions(-) create mode 100644 ls/server/src/zshParser/ast/word/literal.ts create mode 100644 ls/server/test/zshParser/ast/word/literal.test.ts diff --git a/ls/server/src/refreshFunctions/word.ts b/ls/server/src/refreshFunctions/word.ts index 04604529..a8e2fae1 100644 --- a/ls/server/src/refreshFunctions/word.ts +++ b/ls/server/src/refreshFunctions/word.ts @@ -1,7 +1 @@ -import type { WordNode } from '../zshParser/ast'; -import { hereDocDelimiter } from '../zshParser/lexer/delimiter'; - -export function literalWord(word: WordNode, end = word.raw.length): string | null { - if (word.parts.some(part => part.kind !== 'stringLiteral')) return null; - return hereDocDelimiter(word.raw.slice(0, end)).delimiter; -} +export { literalWord } from '../zshParser/ast/word/literal'; diff --git a/ls/server/src/zshParser/ast/word/literal.ts b/ls/server/src/zshParser/ast/word/literal.ts new file mode 100644 index 00000000..e36863c9 --- /dev/null +++ b/ls/server/src/zshParser/ast/word/literal.ts @@ -0,0 +1,8 @@ +import type { WordNode } from './word'; +import { hereDocDelimiter } from '../../lexer/delimiter'; + +/** Decode a literal word or prefix; expansions keep their dynamic meaning. */ +export function literalWord(word: WordNode, end = word.raw.length): string | null { + if (word.parts.some(part => part.kind !== 'stringLiteral')) return null; + return hereDocDelimiter(word.raw.slice(0, end)).delimiter; +} diff --git a/ls/server/test/zshParser/ast/word/literal.test.ts b/ls/server/test/zshParser/ast/word/literal.test.ts new file mode 100644 index 00000000..e6056ce1 --- /dev/null +++ b/ls/server/test/zshParser/ast/word/literal.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from 'vitest'; +import { findAll } from '../../../../src/zshParser/ast'; +import { Lexer } from '../../../../src/zshParser/lexer'; +import { Parser } from '../../../../src/zshParser/parser'; +import { literalWord } from '../../../../src/zshParser/ast/word/literal'; +import { literalWord as compatibilityLiteralWord } from '../../../../src/refreshFunctions/word'; + +function word(source: string) { + const lexed = Lexer.tokenize(source, { sourceFile: 'literal.zsh' }); + const parsed = Parser.parse(lexed.tokens, { sourceFile: 'literal.zsh', path: 'literal.zsh' }); + expect(lexed.diagnostics).toEqual([]); + expect(parsed.diagnostics).toEqual([]); + const argument = findAll(parsed.ast, 'simpleCommand')[0]?.arguments[0]; + if (!argument) throw new Error('Expected a parsed argument'); + return argument; +} + +describe('literalWord', () => { + test.each([ + ['print plain', 'plain'], + ["print 'two words'", 'two words'], + ['print "two words"', 'two words'], + ["print pre'fix'", 'prefix'], + ['print one\\ two', 'one two'], + ["print $'one\\ntwo'", 'one\ntwo'], + ["print ''", ''], + ])('literalの引用をASTから復元する: %s', (source, value) => { + expect(literalWord(word(source))).toBe(value); + }); + + test.each(['print "$value"', 'print "$(print one)"', 'print $(( 1 + 2 ))'])( + '展開を含むWordをliteralと扱わない: %s', source => { + expect(literalWord(word(source))).toBeNull(); + }); + + test('指定された終端まで復元し、既存importの互換性を保持する', () => { + const argument = word("print 'option'=value"); + expect(literalWord(argument, argument.raw.indexOf('='))).toBe('option'); + expect(compatibilityLiteralWord).toBe(literalWord); + }); +}); From 64600c9c8781ac4d9cdf4e1735eca20e29f45501 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 13:10:01 +0900 Subject: [PATCH 04/21] feat: hydrate class declarations on native syntax nodes Attach typed class, attribute, method and instance meaning while preserving syntax kinds and source positions. Build reusable indexes from the final AST so declaration, word and lexical-scope references stay current after immutable enrichment. Represent published, aborted and incomplete definitions separately. --- ls/server/src/zshHydrator/classes/collect.ts | 120 ++++++++++++++ ls/server/src/zshHydrator/classes/index.ts | 108 +++++++++++++ ls/server/src/zshHydrator/classes/types.ts | 43 +++++ ls/server/src/zshHydrator/fileHydration.ts | 5 +- ls/server/src/zshHydrator/hydrate.ts | 4 +- ls/server/src/zshHydrator/index.ts | 2 + ls/server/test/zshHydrator/classes.test.ts | 159 +++++++++++++++++++ 7 files changed, 439 insertions(+), 2 deletions(-) create mode 100644 ls/server/src/zshHydrator/classes/collect.ts create mode 100644 ls/server/src/zshHydrator/classes/index.ts create mode 100644 ls/server/src/zshHydrator/classes/types.ts create mode 100644 ls/server/test/zshHydrator/classes.test.ts diff --git a/ls/server/src/zshHydrator/classes/collect.ts b/ls/server/src/zshHydrator/classes/collect.ts new file mode 100644 index 00000000..6c20f76a --- /dev/null +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -0,0 +1,120 @@ +import type { FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../zshParser/ast'; +import { walk } from '../../zshParser/ast'; +import { literalWord } from '../../zshParser/ast/word/literal'; +import type { SourceRange } from '../../zshParser/lexer'; +import type { ClassInformation, ClassScopeLocation } from './types'; + +type Member = { readonly node: SimpleCommandNode; readonly information: ClassInformation }; +type Definition = { readonly node: SimpleCommandNode; readonly name: string; readonly members: readonly Member[] }; +type Capture = + | { readonly kind: 'definition'; readonly definition: Definition } + | { readonly kind: 'method'; readonly definition: Definition; readonly node: SimpleCommandNode; readonly name: string; readonly depth: number }; +type State = { + readonly scopes: ReadonlyMap; + readonly information: ReadonlyMap; +}; + +/** Keep runtime-reserved names outside statically declared class symbols. */ +function identifier(value: string | null | undefined): value is string { + return value !== null && value !== undefined && value.length > 0 && + [...value].every((char, index) => char === '_' || char >= 'a' && char <= 'z' || + char >= 'A' && char <= 'Z' || index > 0 && char >= '0' && char <= '9') && + !value.startsWith('z_cls_') && !value.startsWith('__z_cls_'); +} +/** Store ownership by position so syntax attachments never retain an earlier AST. */ +function scopeLocation(scope: FunctionDefinitionNode | undefined): ClassScopeLocation { + return scope ? { kind: 'function', offset: scope.range.start.offset } : { kind: 'file' }; +} +/** Replace one lexical capture without changing previous states. */ +function withCapture(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture | null): State { + const scopes = new Map(state.scopes); + if (capture) scopes.set(scope, capture); + else scopes.delete(scope); + return { ...state, scopes }; +} +/** Keep block source positions even when editing leaves its end marker absent. */ +function method(capture: Extract, end: SourceRange, closed: boolean): Member { + return { node: capture.node, information: { kind: 'classMethod', name: capture.name, + classOffset: capture.definition.node.range.start.offset, + body: { kind: 'block', range: { start: capture.node.range.end, end: end.start }, end: closed ? end : null } } }; +} +/** Publish the complete definition and member meaning together. */ +function finish(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture, + end: SourceRange, status: 'published' | 'aborted' | 'incomplete'): State { + const definition = capture.definition; + const members = capture.kind === 'method' ? [...definition.members, method(capture, end, false)] : definition.members; + const information = new Map(state.information); + information.set(definition.node.range.start.offset, { kind: 'classDefinition', name: definition.name, + scope: scopeLocation(scope), state: status, range: { start: definition.node.range.start, end: end.end } }); + for (const member of members) information.set(member.node.range.start.offset, member.information); + return { ...withCapture(state, scope, null), information }; +} +/** Interpret only literal directive commands in the current native function scope. */ +function declaration(command: SimpleCommandNode, depth: number, scope: FunctionDefinitionNode | undefined, state: State): State { + if (command.precommandModifiers.some(modifier => modifier.type === 'builtin' || modifier.type === 'command')) return state; + const name = command.commandName && literalWord(command.commandName.word); + if (!name || !name.startsWith('z.cls.')) return state; + if (!['z.cls.draw', 'z.cls.attr', 'z.cls.fn', 'z.cls.fn.done', 'z.cls.drew', 'z.cls.abort', 'z.cls.new'].includes(name)) return state; + const args = command.arguments.map(word => literalWord(word)); + const capture = state.scopes.get(scope); + if (name === 'z.cls.new' && args.length === 2 && identifier(args[0]) && identifier(args[1])) { + const information = new Map(state.information); + information.set(command.range.start.offset, { kind: 'classInstance', name: args[1], className: args[0], + scope: capture?.kind === 'method' ? { kind: 'classMethod', offset: capture.node.range.start.offset } : scopeLocation(scope) }); + return { ...state, information }; + } + if (capture?.kind === 'method') { + if (depth !== capture.depth) return state; + if (name === 'z.cls.fn.done' && args.length === 0) { + return withCapture(state, scope, { kind: 'definition', definition: { ...capture.definition, + members: [...capture.definition.members, method(capture, command.range, true)] } }); + } + return name === 'z.cls.abort' || name === 'z.cls.drew' ? finish(state, scope, capture, command.range, 'aborted') : state; + } + if (name === 'z.cls.draw' && args.length === 1 && identifier(args[0]) && !capture) { + return withCapture(state, scope, { kind: 'definition', definition: { node: command, name: args[0], members: [] } }); + } + if (!capture) return state; + const definition = capture.definition; + if (name === 'z.cls.attr' && args.length === 2 && identifier(args[0])) { + if (definition.members.some(m => m.information.kind === 'classAttribute' && m.information.name === args[0])) return state; + return withCapture(state, scope, { kind: 'definition', definition: { ...definition, + members: [...definition.members, { node: command, information: { kind: 'classAttribute', name: args[0], + classOffset: definition.node.range.start.offset } }] } }); + } + if (name === 'z.cls.fn' && args.length >= 1 && args.length <= 2 && identifier(args[0])) { + if (definition.members.some(m => m.information.kind === 'classMethod' && m.information.name === args[0])) { + return args.length === 1 ? finish(state, scope, capture, command.range, 'aborted') : state; + } + if (args.length === 1) return withCapture(state, scope, { kind: 'method', definition, node: command, name: args[0], depth }); + return withCapture(state, scope, { kind: 'definition', definition: { ...definition, + members: [...definition.members, { node: command, information: { kind: 'classMethod', name: args[0], + classOffset: definition.node.range.start.offset, + body: { kind: 'inline', range: command.arguments[1].range } } }] } }); + } + if (name === 'z.cls.drew' && args.length === 0) return finish(state, scope, capture, command.range, 'published'); + return name === 'z.cls.abort' ? finish(state, scope, capture, command.range, 'aborted') : state; +} + +/** Interpret class directives from syntax commands, independently in each native function scope. */ +export function collectClassInformation(ast: FileNode): ReadonlyMap { + let state: State = { scopes: new Map(), information: new Map() }; + const scopes: { readonly node: FunctionDefinitionNode; readonly depth: number }[] = []; + walk(ast, (node, depth) => { + while (scopes.length && scopes[scopes.length - 1].depth >= depth) scopes.pop(); + if (node.kind === 'functionDefinition') scopes.push({ node, depth }); + if (node.kind === 'simpleCommand') { + if ('hydration' in node) { + const information = new Map(state.information); + information.set(node.range.start.offset, null); + state = { ...state, information }; + } + state = declaration(node, depth, scopes.at(-1)?.node, state); + } + }); + for (const [scope, capture] of state.scopes) { + const end = scope?.range.end ?? ast.range.end; + state = finish(state, scope, capture, { start: end, end }, 'incomplete'); + } + return state.information; +} diff --git a/ls/server/src/zshHydrator/classes/index.ts b/ls/server/src/zshHydrator/classes/index.ts new file mode 100644 index 00000000..408b0a55 --- /dev/null +++ b/ls/server/src/zshHydrator/classes/index.ts @@ -0,0 +1,108 @@ +import type { AstNode, FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../zshParser/ast'; +import { findAll, mapAst } from '../../zshParser/ast'; +import { collectClassInformation } from './collect'; +import type { ClassInformation, ClassFileHydration, ClassDefinition, ClassAttribute, ClassMethod, + ClassInstance, HydratedClassCommand } from './types'; +export type * from './types'; + +/** Narrow the attachment through its class role discriminator. */ +export function isHydratedClassCommand(node: SimpleCommandNode): node is HydratedClassCommand { + if (!('hydration' in node) || typeof node.hydration !== 'object' || node.hydration === null) return false; + const information = node.hydration; + return 'kind' in information && 'name' in information && typeof information.name === 'string' && + (information.kind === 'classDefinition' || information.kind === 'classAttribute' || + information.kind === 'classMethod' || information.kind === 'classInstance'); +} +/** Expose class meaning without changing the generic syntax node types. */ +export function classInformationOf(node: SimpleCommandNode): ClassInformation | null { + return isHydratedClassCommand(node) ? node.hydration : null; +} + +/** Attach class meaning while retaining every native syntax kind, token and range. */ +export function hydrateClasses(ast: FileNode): FileNode { + const information = collectClassInformation(ast); + if (information.size === 0) return ast; + return mapAst(ast, (node: AstNode): AstNode => { + if (node.kind !== 'simpleCommand') return node; + const value = information.get(node.range.start.offset); + if (value) { + const hydrated: HydratedClassCommand = { ...node, hydration: value }; + return hydrated; + } + if (isHydratedClassCommand(node)) { + const { hydration, ...syntax } = node; + return syntax; + } + return node; + }); +} + +/** Build indexes only after enrichment, so every declaration/word/scope refers to the returned AST. */ +export function classesFromAst(ast: FileNode): ClassFileHydration { + const commands = findAll(ast, 'simpleCommand').filter(isHydratedClassCommand); + if (commands.length === 0) return { definitions: [], instances: [], methodScopes: new Map() }; + const commandByOffset = new Map(commands.map(node => [node.range.start.offset, node])); + const functions = new Map(findAll(ast, 'functionDefinition').map(node => [node.range.start.offset, node])); + const groups = new Map; + attributes: ClassAttribute[]; methods: ClassMethod[] }>(); + for (const command of commands) { + const information = classInformationOf(command); + if (information?.kind !== 'classDefinition' || !command.arguments[0]) continue; + groups.set(command.range.start.offset, { definition: { kind: 'classDefinition', name: information.name, + declaration: command, nameNode: command.arguments[0], file: ast, + scope: information.scope.kind === 'function' ? functions.get(information.scope.offset) ?? null : null, + state: information.state, range: information.range }, attributes: [], methods: [] }); + } + const instances: ClassInstance[] = []; + for (const command of commands) { + const information = classInformationOf(command); + if (!information) continue; + const [nameNode, value] = command.arguments; + if (!nameNode) continue; + if (information.kind === 'classAttribute') { + if (value) groups.get(information.classOffset)?.attributes.push({ kind: 'classAttribute', name: information.name, + declaration: command, nameNode, defaultValue: value }); + } else if (information.kind === 'classMethod') { + if (information.body.kind === 'inline' && !value) continue; + groups.get(information.classOffset)?.methods.push({ kind: 'classMethod', name: information.name, + declaration: command, nameNode, body: information.body.kind === 'inline' ? + { kind: 'inline', value } : information.body }); + } else if (information.kind === 'classInstance' && value) { + const location = information.scope; + const ownerFunction = location.kind === 'function' ? functions.get(location.offset) : null; + const ownerMethod = location.kind === 'classMethod' ? commandByOffset.get(location.offset) : null; + if (location.kind === 'function' && !ownerFunction || location.kind === 'classMethod' && !ownerMethod) continue; + const scope: ClassInstance['scope'] = ownerFunction ? { kind: 'function', declaration: ownerFunction } : + ownerMethod ? { kind: 'classMethod', declaration: ownerMethod } : { kind: 'file' }; + instances.push({ kind: 'classInstance', name: information.name, className: information.className, + declaration: command, classNameNode: nameNode, nameNode: value, scope, file: ast }); + } + } + const definitions = [...groups.values()].map(group => ({ ...group.definition, + attributes: group.attributes, methods: group.methods })); + const methodScopes = new Map(); + for (const definition of definitions) { + for (const method of definition.methods) { + if (method.body.kind !== 'block') continue; + const scopes = methodScopes.get(definition.scope) ?? []; + scopes.push({ method, range: method.body.range }); + methodScopes.set(definition.scope, scopes); + } + } + for (const scopes of methodScopes.values()) scopes.sort((left, right) => left.range.start.offset - right.range.start.offset); + return { definitions, instances, methodScopes }; +} + +/** Find method parameter ownership without interpreting class commands again during diagnostics. */ +export function classMethodAt(classes: ClassFileHydration, scope: FunctionDefinitionNode | null, offset: number): ClassMethod | null { + const methods = classes.methodScopes.get(scope) ?? []; + let low = 0, high = methods.length - 1; + while (low <= high) { + const middle = Math.floor((low + high) / 2); + const entry = methods[middle]; + if (offset < entry.range.start.offset) high = middle - 1; + else if (offset >= entry.range.end.offset) low = middle + 1; + else return entry.method; + } + return null; +} diff --git a/ls/server/src/zshHydrator/classes/types.ts b/ls/server/src/zshHydrator/classes/types.ts new file mode 100644 index 00000000..16a8f946 --- /dev/null +++ b/ls/server/src/zshHydrator/classes/types.ts @@ -0,0 +1,43 @@ +import type { FileNode, FunctionDefinitionNode, SimpleCommandNode, WordNode } from '../../zshParser/ast'; +import type { SourceRange } from '../../zshParser/lexer'; + +export type ClassScopeLocation = + | { readonly kind: 'file' } + | { readonly kind: 'function' | 'classMethod'; readonly offset: number }; +export type ClassMethodBody = + | { readonly kind: 'inline'; readonly range: SourceRange } + | { readonly kind: 'block'; readonly range: SourceRange; readonly end: SourceRange | null }; +export type ClassInformation = + | { readonly kind: 'classDefinition'; readonly name: string; readonly scope: ClassScopeLocation; + readonly state: 'published' | 'aborted' | 'incomplete'; readonly range: SourceRange } + | { readonly kind: 'classAttribute'; readonly name: string; readonly classOffset: number } + | { readonly kind: 'classMethod'; readonly name: string; readonly classOffset: number; readonly body: ClassMethodBody } + | { readonly kind: 'classInstance'; readonly name: string; readonly className: string; readonly scope: ClassScopeLocation }; +export type HydratedClassCommand = SimpleCommandNode & { readonly hydration: ClassInformation }; +export type ClassAttribute = { + readonly kind: 'classAttribute'; readonly name: string; readonly declaration: SimpleCommandNode; + readonly nameNode: WordNode; readonly defaultValue: WordNode; +}; +export type ClassMethod = { + readonly kind: 'classMethod'; readonly name: string; readonly declaration: SimpleCommandNode; + readonly nameNode: WordNode; + readonly body: { readonly kind: 'inline'; readonly value: WordNode } | + { readonly kind: 'block'; readonly range: SourceRange; readonly end: SourceRange | null }; +}; +export type ClassDefinition = { + readonly kind: 'classDefinition'; readonly name: string; readonly declaration: SimpleCommandNode; + readonly file: FileNode; readonly nameNode: WordNode; readonly scope: FunctionDefinitionNode | null; + readonly state: 'published' | 'aborted' | 'incomplete'; readonly range: SourceRange; + readonly attributes: readonly ClassAttribute[]; readonly methods: readonly ClassMethod[]; +}; +export type ClassInstance = { + readonly kind: 'classInstance'; readonly name: string; readonly className: string; + readonly declaration: SimpleCommandNode; readonly nameNode: WordNode; readonly classNameNode: WordNode; + readonly file: FileNode; readonly scope: { readonly kind: 'file' } | + { readonly kind: 'function'; readonly declaration: FunctionDefinitionNode } | + { readonly kind: 'classMethod'; readonly declaration: SimpleCommandNode }; +}; +export type ClassFileHydration = { + readonly definitions: readonly ClassDefinition[]; readonly instances: readonly ClassInstance[]; + readonly methodScopes: ReadonlyMap; +}; diff --git a/ls/server/src/zshHydrator/fileHydration.ts b/ls/server/src/zshHydrator/fileHydration.ts index f4e97988..215c1360 100644 --- a/ls/server/src/zshHydrator/fileHydration.ts +++ b/ls/server/src/zshHydrator/fileHydration.ts @@ -8,6 +8,8 @@ import type { ParserDiagnostic } from '../zshParser/parser'; import { hydrateAst, documentationOf } from './hydrate'; import type { HydrationDiagnostic } from './documentation'; import type { HydrationOptions } from './directive'; +import { classesFromAst } from './classes'; +import type { ClassFileHydration } from './classes'; export type HydratedFunction = { readonly name: string; @@ -19,6 +21,7 @@ export type ZshFileHydration = { readonly ast: FileNode; readonly tokens: readonly Token[]; readonly functions: readonly HydratedFunction[]; + readonly classes: ClassFileHydration; readonly query: QueryContext; readonly lexerDiagnostics: readonly LexerDiagnostic[]; readonly parserDiagnostics: readonly ParserDiagnostic[]; @@ -32,7 +35,7 @@ export function createZshFileHydration({ const ast = hydrateAst(parsed.ast, content, options); const definitions = findAll(ast, 'functionDefinition'); return { - sourceFile, file, ast, tokens: parsed.tokens, query: createQueryContext(ast), + sourceFile, file, ast, classes: classesFromAst(ast), tokens: parsed.tokens, query: createQueryContext(ast), functions: definitions.flatMap((definition) => definition.names.map((word) => ({ name: word.raw, definition }))), lexerDiagnostics: lexed.diagnostics, parserDiagnostics: parsed.diagnostics, diff --git a/ls/server/src/zshHydrator/hydrate.ts b/ls/server/src/zshHydrator/hydrate.ts index 9ccd375d..d5cd2c12 100644 --- a/ls/server/src/zshHydrator/hydrate.ts +++ b/ls/server/src/zshHydrator/hydrate.ts @@ -4,6 +4,7 @@ import type { FunctionDocumentation } from './documentation'; import { parseFunctionDocumentation } from './documentation'; import type { ControlComment, HydrationOptions } from './directive'; import { parseDirective } from './directive'; +import { hydrateClasses } from './classes'; export type HydratedDocBlock = DocBlockNode & { readonly hydration: FunctionDocumentation }; export type HydratedComment = CommentNode & { readonly hydration: ControlComment }; @@ -33,7 +34,7 @@ export function hydrateAst(ast: FileNode, source: string, options: HydrationOpti documents.set(definition.leadingDoc.range.start.offset, result.documentation); for (const offset of result.exampleComments) exampleComments.add(offset); } - return mapAst(ast, (node: AstNode): AstNode => { + const enriched = mapAst(ast, (node: AstNode): AstNode => { if (node.kind === 'docBlock') { const original = documents.get(node.range.start.offset); if (original) { @@ -53,4 +54,5 @@ export function hydrateAst(ast: FileNode, source: string, options: HydrationOpti } return node; }); + return hydrateClasses(enriched); } diff --git a/ls/server/src/zshHydrator/index.ts b/ls/server/src/zshHydrator/index.ts index 4902028e..a717b978 100644 --- a/ls/server/src/zshHydrator/index.ts +++ b/ls/server/src/zshHydrator/index.ts @@ -6,3 +6,5 @@ export { hydrateAst, documentationOf, directivesOf, isHydratedDocBlock, isHydrat export type { HydratedDocBlock, HydratedComment } from './hydrate'; export type * from './documentation'; export type { Directive, DirectiveArgument, ControlComment, HydrationOptions } from './directive'; +export { hydrateClasses, classesFromAst, classInformationOf, isHydratedClassCommand, classMethodAt } from './classes'; +export type { ClassInformation, HydratedClassCommand, ClassFileHydration, ClassDefinition, ClassMethod, ClassAttribute, ClassInstance } from './classes'; diff --git a/ls/server/test/zshHydrator/classes.test.ts b/ls/server/test/zshHydrator/classes.test.ts new file mode 100644 index 00000000..66529b49 --- /dev/null +++ b/ls/server/test/zshHydrator/classes.test.ts @@ -0,0 +1,159 @@ +import { describe, expect, test } from 'vitest'; +import { findAll, mapAst } from '../../src/zshParser/ast'; +import { Lexer } from '../../src/zshParser/lexer'; +import { Parser } from '../../src/zshParser/parser'; +import { createZshFileHydration, hydrateAst } from '../../src/zshHydrator'; +import { classInformationOf, classesFromAst, classMethodAt, hydrateClasses } from '../../src/zshHydrator/classes'; +import { astContractViolations } from '../zshParser/parser/contracts'; + +const source = ['z.cls.draw Counter; {', ' z.cls.attr count 0', ' z.cls.fn increment', + ' (( ++count ))', ' print "$1"', ' z.cls.fn.done', " z.cls.fn value 'REPLY=$count'", ' z.cls.drew', '}', + 'z.cls.new Counter object', ''].join('\n'); +function fixture(content = source) { + return createZshFileHydration({ sourceFile: '/project/classes.zsh', file: 'classes.zsh', content }); +} + +describe('class hydration', () => { + test('classのないASTは追加コピーせず返す', () => { + const file = fixture('print hello\n'); + expect(hydrateClasses(file.ast)).toBe(file.ast); + }); + + test('深い構文内の終了名ではメソッドを閉じない', () => { + const text = source.replace('(( ++count ))', 'if true; then z.cls.fn.done; fi\n print deeper'); + const file = fixture(text); + const method = file.classes.definitions[0].methods[0]; + expect(method.body.kind).toBe('block'); + if (method.body.kind !== 'block') throw new Error('Expected a block method'); + expect(method.body.end?.start.offset).toBe(text.lastIndexOf('z.cls.fn.done')); + expect(classMethodAt(file.classes, null, text.indexOf('print deeper'))).toBe(method); + }); + + test.each(['z.cls.new $class object', 'z.cls.new z_cls_reserved object', 'z.cls.new Counter bad-name', + 'z.cls.new Counter', 'z.cls.draw bad-name'])('動的・不完全・予約済みの名前を決め打ちしない: %s', text => { + const file = fixture(text + '\n'); + expect(file.classes.definitions).toEqual([]); + expect(file.classes.instances).toEqual([]); + }); + + test('同名instanceのnative function scopeを返却ASTに結び付ける', () => { + const file = fixture('z.cls.new Counter object\nload() { local object; z.cls.new Other object; }\n'); + expect(file.classes.instances[0].scope.kind).toBe('file'); + const local = file.classes.instances[1]; + expect(local.scope.kind).toBe('function'); + if (local.scope.kind !== 'function') throw new Error('Expected function ownership'); + expect(local.scope.declaration).toBe(file.functions[0].definition); + }); + + test('子のcommandを付加情報で更新してもdefaultのWord参照が古くならない', () => { + const file = fixture('z.cls.draw Holder\nz.cls.attr value "$(z.cls.new Other inside)"\nz.cls.drew\n'); + const attribute = file.classes.definitions[0].attributes[0]; + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); + const binding = file.classes.instances.find(item => item.name === 'inside'); + expect(binding).toBeDefined(); + expect(findAll(attribute.defaultValue, 'simpleCommand')).toContain(binding?.declaration); + expect(file.classes.definitions[0].file).toBe(file.ast); + }); + + test('既存のclass付加情報が入力に残っていても現在の構文から更新する', () => { + const information = classInformationOf(fixture().classes.definitions[0].declaration); + if (!information) throw new Error('Expected class information'); + const ordinary = fixture('print hello\n'); + const stale = mapAst(ordinary.ast, node => node.kind === 'simpleCommand' ? { ...node, hydration: information } : node); + const refreshed = hydrateAst(stale, 'print hello\n'); + expect(findAll(refreshed, 'simpleCommand').map(classInformationOf)).toEqual([null]); + expect(classesFromAst(refreshed).definitions).toEqual([]); + expect(findAll(stale, 'simpleCommand').map(classInformationOf)).toEqual([information]); + }); + + test('class・属性・メソッド・instanceに意味情報を付与し、通常の構文ノードを保持する', () => { + const file = fixture(); + const definition = file.classes.definitions[0]; + expect(definition).toMatchObject({ kind: 'classDefinition', name: 'Counter', state: 'published' }); + expect(definition.declaration.kind).toBe('simpleCommand'); + expect(classInformationOf(definition.declaration)?.kind).toBe('classDefinition'); + expect(definition.attributes.map(item => item.name)).toEqual(['count']); + expect(definition.methods.map(item => item.name)).toEqual(['increment', 'value']); + expect(file.classes.instances[0]).toMatchObject({ kind: 'classInstance', className: 'Counter', name: 'object' }); + expect(astContractViolations(file.ast, file.tokens, source)).toEqual([]); + }); + + test('索引と属性値・名前が返却ASTと同じノードを参照する', () => { + const file = fixture(); + const commands = findAll(file.ast, 'simpleCommand'); + const definition = file.classes.definitions[0]; + expect(commands).toContain(definition.declaration); + expect(definition.nameNode).toBe(definition.declaration.arguments[0]); + const attribute = definition.attributes[0]; + expect(commands).toContain(attribute.declaration); + expect(attribute.nameNode).toBe(attribute.declaration.arguments[0]); + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); + expect(file.classes.instances[0].nameNode).toBe(file.classes.instances[0].declaration.arguments[1]); + expect(classesFromAst(file.ast)).toEqual(file.classes); + }); + + test('blockとinlineの本体を元の範囲またはWordとして保持する', () => { + const file = fixture(); + const [block, inline] = file.classes.definitions[0].methods; + expect(block.body.kind).toBe('block'); + if (block.body.kind !== 'block') throw new Error('Expected a block method'); + expect(source.slice(block.body.range.start.offset, block.body.range.end.offset)).toContain('(( ++count ))'); + expect(source.slice(block.body.range.start.offset, block.body.range.end.offset)).not.toContain('z.cls.fn.done'); + expect(inline.body.kind).toBe('inline'); + if (inline.body.kind !== 'inline') throw new Error('Expected an inline method'); + expect(inline.body.value).toBe(inline.declaration.arguments[1]); + expect(classMethodAt(file.classes, null, source.indexOf('print "$1"'))).toBe(block); + expect(classMethodAt(file.classes, null, source.indexOf('z.cls.fn.done'))).toBeNull(); + }); + + test('入力ASTを変更せず再hydrationしても意味情報を重複させない', () => { + const parsed = Parser.parse(Lexer.tokenize(source, { sourceFile: 'x' }).tokens, { sourceFile: 'x', path: 'x' }); + const ast = hydrateAst(parsed.ast, source); + expect(findAll(parsed.ast, 'simpleCommand').map(classInformationOf).filter(Boolean)).toEqual([]); + expect(hydrateAst(ast, source)).toEqual(ast); + expect(classesFromAst(ast).definitions).toHaveLength(1); + }); + + test('未完了とabortを公開済みclassと区別する', () => { + const incomplete = fixture('z.cls.draw Open\nz.cls.fn run\nprint "$1"\n'); + expect(incomplete.classes.definitions[0]).toMatchObject({ name: 'Open', state: 'incomplete' }); + expect(incomplete.classes.definitions[0].methods[0].body).toMatchObject({ kind: 'block', end: null }); + const aborted = fixture('z.cls.draw Discarded\nz.cls.attr count 0\nz.cls.abort\n'); + expect(aborted.classes.definitions[0]).toMatchObject({ name: 'Discarded', state: 'aborted' }); + }); + + test('文字列・コメント・非function呼出をclassと誤認しない', () => { + const file = fixture('# z.cls.draw Comment\nprint "z.cls.draw String"\ncommand z.cls.draw External\nbuiltin z.cls.new Counter object\n'); + expect(file.classes.definitions).toEqual([]); + expect(file.classes.instances).toEqual([]); + }); + + test('native関数ごとのclassを独立して解釈し、本体内の引数スコープを保持する', () => { + const text = 'load() {\n' + source.slice(0, source.indexOf('z.cls.new')) + '}\n'; + const file = fixture(text); + const owner = file.functions.find(fn => fn.name === 'load')?.definition; + expect(file.classes.definitions[0].scope).toBe(owner); + expect(owner && classMethodAt(file.classes, owner, text.indexOf('print "$1"'))?.name).toBe('increment'); + expect(classMethodAt(file.classes, null, text.indexOf('print "$1"'))).toBeNull(); + }); + + test('入れ子のnative関数にある終端名で外側のメソッドを閉じない', () => { + const file = fixture(source.replace('(( ++count ))', 'helper() { z.cls.fn.done }\n print "z.cls.fn.done"')); + expect(file.classes.definitions[0].methods.map(m => m.name)).toEqual(['increment', 'value']); + }); + + test('メソッド内のinstance宣言をclass method scopeに結び付ける', () => { + const file = fixture(source.replace('(( ++count ))', 'z.cls.new Other nested')); + const binding = file.classes.instances.find(i => i.name === 'nested'); + expect(binding?.scope.kind).toBe('classMethod'); + if (binding?.scope.kind !== 'classMethod') throw new Error('Expected a method scope'); + expect(binding.scope.declaration).toBe(file.classes.definitions[0].methods[0].declaration); + }); + + test('native関数内のclassと外側のclassを同じpending状態にしない', () => { + const text = 'z.cls.draw Outer\nhelper() { z.cls.draw Inner; z.cls.drew }\nz.cls.drew\n'; + const file = fixture(text); + expect(file.classes.definitions.map(d => d.name)).toEqual(['Outer', 'Inner']); + expect(file.classes.definitions.find(d => d.name === 'Inner')?.scope).toBe(file.functions[0].definition); + }); +}); From 8183ceab68637f6be83dab9a57af811fc2ef499c Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 13:10:01 +0900 Subject: [PATCH 05/21] feat: resolve class calls from shared hydration targets Replace diagnostic-side DSL recognition with hydrated declaration and instance indexes. Return member provenance from call analysis, refresh cached contexts when AST references change, and preserve method argument ownership. Use the shared code-argument analyzer for inline method bodies and isolate embedded class bindings. --- lib/cls/process.zsh | 2 +- ls/server/src/diagnostics/calls.ts | 14 ++- ls/server/src/diagnostics/classes.ts | 95 +++++----------- ls/server/src/diagnostics/embedded/index.ts | 4 +- ls/server/src/diagnostics/facts.ts | 12 +- ls/server/src/diagnostics/snapshot.ts | 13 ++- .../diagnostics/classDeclarations.test.ts | 106 ------------------ ls/server/test/diagnostics/classes.test.ts | 75 ++++++++++++- 8 files changed, 128 insertions(+), 193 deletions(-) delete mode 100644 ls/server/test/diagnostics/classDeclarations.test.ts diff --git a/lib/cls/process.zsh b/lib/cls/process.zsh index 513bad3a..6c7d86b8 100644 --- a/lib/cls/process.zsh +++ b/lib/cls/process.zsh @@ -62,7 +62,7 @@ z.cls.attr() { # 引用しない本体の末尾には、独立した文としてz.cls.fn.doneを置く。 # # $1: メソッド名 -# $2?: 引数で指定する本体 +# $2? [code]: 引数で指定する本体 # REPLY: null # return: 0|1 # diff --git a/ls/server/src/diagnostics/calls.ts b/ls/server/src/diagnostics/calls.ts index a547b679..1d47a5fa 100644 --- a/ls/server/src/diagnostics/calls.ts +++ b/ls/server/src/diagnostics/calls.ts @@ -16,10 +16,13 @@ import { ignored } from './controls'; import type { ShellEnvironment } from './environment'; import type { Declarations } from './facts'; import { simpleParameter } from './facts'; +import type { ClassFileHydration } from '../zshHydrator'; +import type { ClassCommandTargets, ClassCommandTarget } from './classes'; export type ResolutionContext = Declarations & { readonly environment: ShellEnvironment; readonly projectRoot: string; - readonly classCommands: ReadonlySet; + readonly classCommands: ClassCommandTargets; + readonly classFiles: readonly ClassFileHydration[]; }; function alias(name: string, word: WordNode, context: ResolutionContext): boolean { @@ -108,6 +111,7 @@ export type CallAnalysisOptions = { export type CallAnalysis = { readonly diagnostics: readonly Diagnostics[]; readonly targets: ReadonlyMap; + readonly classTargets: ReadonlyMap; }; /** 埋め込みコードやworkspace外の定義はローカルに保ち、workspaceの参照先には追加しない。 */ @@ -137,6 +141,7 @@ export function analyzeCalls(snapshot: FunctionSnapshot, file: ZshFileHydration, commands: readonly SimpleCommandNode[], context: ResolutionContext, options: CallAnalysisOptions = {}): CallAnalysis { const diagnostics: Diagnostics[] = []; const targets = new Map(); + const classTargets = new Map(); const local = localDefinitions(snapshot, file); const scopes = (options.scopes ?? []).map(scope => ({ ...scope, definitions: localDefinitions(snapshot, scope.file) })); const origin = scopes.at(-1); @@ -153,6 +158,7 @@ export function analyzeCalls(snapshot: FunctionSnapshot, file: ZshFileHydration, const inherited = scopes.map(scope => localDefinition(scope.definitions, name, scope.offset)).find(target => target !== undefined); const target = functionCommand(command) ? localDefinition(local, name, word.range.start.offset) ?? inherited ?? resolveFunction(snapshot, name, { file: origin?.file ?? file, offset: origin?.offset ?? word.range.start.offset })?.definition : null; + const generated = functionCommand(command) ? context.classCommands.get(name) : undefined; if (target) { targets.set(command, target); if (!incomplete) { @@ -160,8 +166,8 @@ export function analyzeCalls(snapshot: FunctionSnapshot, file: ZshFileHydration, if (!options.ignores || !ignored(options.ignores, word.range.start.line, diagnostic.code)) diagnostics.push(diagnostic); } } - } else if (functionCommand(command) && context.classCommands.has(name)) { - continue; + } else if (generated) { + classTargets.set(command, generated); } else if (context.autoloads.has(name) && functionCommand(command)) { continue; } else if (shellKnown(name, command, context) === false && @@ -171,7 +177,7 @@ export function analyzeCalls(snapshot: FunctionSnapshot, file: ZshFileHydration, message: name + ' is not defined in the project or shell environment.' }); } } - return { diagnostics, targets }; + return { diagnostics, targets, classTargets }; } /** 関数の参照先を必要としない呼び出し元向けに、既存の診断のみを返すAPIを保つ。 */ diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts index ceaea900..f76ed81e 100644 --- a/ls/server/src/diagnostics/classes.ts +++ b/ls/server/src/diagnostics/classes.ts @@ -1,74 +1,37 @@ -import type { FunctionDefinitionNode, SimpleCommandNode } from '../zshParser/ast'; -import { literalWord } from '../refreshFunctions/word'; +import type { ClassFileHydration, ClassDefinition, ClassInstance, ClassMethod, ClassAttribute } from '../zshHydrator/classes'; -export type ClassDeclarations = { - readonly definitions: ReadonlyMap>; - readonly instances: ReadonlyMap>; +export type ClassCommandTarget = { + readonly definition: ClassDefinition; readonly instance: ClassInstance; + readonly member: ClassMethod | ClassAttribute; readonly operation: 'method' | 'get' | 'set'; }; -type ClassDefinition = { - readonly name: string; readonly scope: FunctionDefinitionNode | undefined; - readonly members: ReadonlySet; -}; -type ClassCapture = - | { readonly kind: 'definition'; readonly definition: ClassDefinition } - | { readonly kind: 'method'; readonly definition: ClassDefinition; readonly depth: number }; -export type ClassState = ClassDeclarations & { readonly pending: ClassCapture | null }; - -export function createClassState(): ClassState { - return { definitions: new Map(), instances: new Map(), pending: null }; -} - -function identifier(value: string | null | undefined): value is string { - return value !== null && value !== undefined && /^[A-Za-z_][A-Za-z0-9_]*$/.test(value) && - !value.startsWith('z_cls_') && !value.startsWith('__z_cls_'); -} - -export function classDeclaration(command: SimpleCommandNode, depth: number, - scope: FunctionDefinitionNode | undefined, state: ClassState): ClassState { - const name = command.commandName && literalWord(command.commandName.word); - const args = command.arguments.map(word => literalWord(word)); - const pending = state.pending; - if (pending?.kind === 'method') { - return name === 'z.cls.fn.done' && scope === pending.definition.scope && depth === pending.depth ? - { ...state, pending: { kind: 'definition', definition: pending.definition } } : state; - } - if (name === 'z.cls.new' && identifier(args[0]) && identifier(args[1]) && args.length === 2) { - const instances = new Map(state.instances); - instances.set(args[1], new Set([...(instances.get(args[1]) ?? []), args[0]])); - return { ...state, instances }; - } - if (name === 'z.cls.draw' && identifier(args[0]) && args.length === 1 && !pending) { - return { ...state, pending: { kind: 'definition', definition: { name: args[0], scope, members: new Set() } } }; - } - if (!pending || scope !== pending.definition.scope) return state; - - const definition = pending.definition; - if (name === 'z.cls.attr' && identifier(args[0]) && args.length === 2) { - const members = new Set([...definition.members, args[0] + '.get', args[0] + '.set']); - return { ...state, pending: { kind: 'definition', definition: { ...definition, members } } }; - } - if (name === 'z.cls.fn' && identifier(args[0]) && args.length >= 1 && args.length <= 2) { - const next = { ...definition, members: new Set([...definition.members, args[0]]) }; - return { ...state, pending: args.length === 1 ? - { kind: 'method', definition: next, depth } : { kind: 'definition', definition: next } }; - } - if (name === 'z.cls.drew' && args.length === 0) { - const definitions = new Map(state.definitions); - definitions.set(definition.name, definition.members); - return { ...state, definitions, pending: null }; - } - return name === 'z.cls.abort' ? { ...state, pending: null } : state; -} +export type ClassCommandTargets = ReadonlyMap; -export function classCommands(declarations: readonly ClassDeclarations[]): ReadonlySet { - const definitions = new Map(declarations.flatMap(file => [...file.definitions])); - const commands = new Set(); - for (const file of declarations) { - for (const [instance, classes] of file.instances) { - for (const name of classes) { - for (const member of definitions.get(name) ?? []) commands.add(instance + '.' + member); +/** Resolve only published class symbols; targets retain declaration nodes and member provenance. */ +export function classCommands(files: readonly ClassFileHydration[]): ClassCommandTargets { + const definitions = new Map(files.flatMap(file => file.definitions.filter(d => d.state === 'published').map(d => [d.name, d]))); + const commands = new Map(); + for (const file of files) { + for (const instance of file.instances) { + const definition = definitions.get(instance.className); + if (!definition) continue; + for (const member of [...definition.methods, ...definition.attributes]) { + const operations: readonly ClassCommandTarget['operation'][] = member.kind === 'classMethod' ? ['method'] : ['get', 'set']; + for (const operation of operations) { + const name = instance.name + '.' + member.name + (operation === 'method' ? '' : '.' + operation); + const targets = commands.get(name) ?? []; + targets.push({ definition, member, instance, operation }); + commands.set(name, targets); + } } } } return commands; } + +/** Preserve cached contexts only while all class declaration and binding references are current. */ +export function sameClassFiles(left: readonly ClassFileHydration[], right: readonly ClassFileHydration[]): boolean { + const declarations = (files: readonly ClassFileHydration[]) => files.flatMap(file => + [...file.definitions.map(d => d.declaration), ...file.instances.map(i => i.declaration)]); + const previous = declarations(left), next = declarations(right); + return previous.length === next.length && previous.every((node, index) => node === next[index]); +} diff --git a/ls/server/src/diagnostics/embedded/index.ts b/ls/server/src/diagnostics/embedded/index.ts index be2253f2..e6bd7afe 100644 --- a/ls/server/src/diagnostics/embedded/index.ts +++ b/ls/server/src/diagnostics/embedded/index.ts @@ -6,6 +6,7 @@ import type { Diagnostics } from '../type'; import type { ResolutionContext, CallScope } from '../calls'; import { analyzeCalls } from '../calls'; import { collectFileFacts } from '../facts'; +import { classCommands } from '../classes'; import { DiagnosticSeverity } from '../../vscode_type'; import { protocolRange } from '../../connection/ast/cursor'; import { codeArguments } from './arguments'; @@ -69,7 +70,8 @@ export function embeddedCallDiagnostics(snapshot: FunctionSnapshot, file: ZshFil const facts = collectFileFacts(child); const declarations = facts.declarations; const inherited = program.context; - const childContext: ResolutionContext = { ...inherited, + const classFiles = [...inherited.classFiles, child.classes]; + const childContext: ResolutionContext = { ...inherited, classFiles, classCommands: classCommands(classFiles), aliases: new Set([...inherited.aliases, ...declarations.aliases]), globalAliases: new Set([...inherited.globalAliases, ...declarations.globalAliases]), suffixAliases: new Set([...inherited.suffixAliases, ...declarations.suffixAliases]), diff --git a/ls/server/src/diagnostics/facts.ts b/ls/server/src/diagnostics/facts.ts index b78fdf93..7f33f4cf 100644 --- a/ls/server/src/diagnostics/facts.ts +++ b/ls/server/src/diagnostics/facts.ts @@ -8,8 +8,8 @@ import { protocolRange } from '../connection/ast/cursor'; import { literalWord } from '../refreshFunctions/word'; import { formatDiagnostics } from './format'; import { moduleBuiltins } from './modules'; -import { createClassState, classDeclaration } from './classes'; -import type { ClassDeclarations } from './classes'; +import { classMethodAt } from '../zshHydrator'; +import type { ClassFileHydration } from '../zshHydrator'; export type Declarations = { readonly aliases: ReadonlySet; readonly globalAliases: ReadonlySet; @@ -18,7 +18,7 @@ export type Declarations = { }; export type FileFacts = { readonly calls: readonly SimpleCommandNode[]; readonly base: readonly Diagnostics[]; - readonly declarations: Declarations; readonly classes: ClassDeclarations; + readonly declarations: Declarations; readonly classes: ClassFileHydration; }; type Usage = { readonly definition: FunctionDefinitionNode; readonly depth: number; @@ -93,7 +93,6 @@ function declarations(command: SimpleCommandNode, sets: { export function collectFileFacts(file: ZshFileHydration): FileFacts { const calls: SimpleCommandNode[] = []; const usages: Usage[] = []; - let classes = createClassState(); const active: Usage[] = []; const sets = { aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), autoloads: new Set(), builtins: new Set() }; @@ -108,9 +107,8 @@ export function collectFileFacts(file: ZshFileHydration): FileFacts { if (node.kind === 'simpleCommand') { if (node.commandName) calls.push(node); declarations(node, sets); - classes = classDeclaration(node, depth, current?.definition, classes); } - if (!current || (classes.pending?.kind === 'method' && classes.pending.definition.scope === current.definition)) return; + if (!current || classMethodAt(file.classes, current.definition, node.range.start.offset)) return; if (node.kind === 'simpleCommand' && node.commandName && literalWord(node.commandName.word) === 'z.arg.named') { const word = node.arguments[0]; const name = word && literalWord(word); @@ -139,5 +137,5 @@ export function collectFileFacts(file: ZshFileHydration): FileFacts { code: diagnostic.kind, range: protocolRange(diagnostic.range), message: diagnostic.message, source: 'z-ls/parser' }); for (const diagnostic of file.hydrationDiagnostics) base.push({ severity: DiagnosticSeverity.Warning, code: diagnostic.kind, range: protocolRange(diagnostic.range), message: diagnostic.message, source: 'z-ls/documentation' }); - return { calls, base, declarations: sets, classes }; + return { calls, base, declarations: sets, classes: file.classes }; } diff --git a/ls/server/src/diagnostics/snapshot.ts b/ls/server/src/diagnostics/snapshot.ts index 3339c8dc..3feaa967 100644 --- a/ls/server/src/diagnostics/snapshot.ts +++ b/ls/server/src/diagnostics/snapshot.ts @@ -9,7 +9,7 @@ import { collectFileFacts } from './facts'; import type { FileFacts, Declarations } from './facts'; import { embeddedCallDiagnostics } from './embedded'; import { sameCallContracts } from './contracts'; -import { classCommands } from './classes'; +import { classCommands, sameClassFiles } from './classes'; import type { ResolutionContext } from './calls'; import type { Diagnostics } from './type'; @@ -24,7 +24,7 @@ export type DiagnosticSnapshot = { export function createDiagnosticSnapshot(): DiagnosticSnapshot { return { revision: 0, targets: new Map(), context: { environment: emptyShellEnvironment(), projectRoot: '', - classCommands: new Set(), aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), + classCommands: new Map(), classFiles: [], aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), autoloads: new Set(), builtins: new Set() }, files: new Map() }; } @@ -34,7 +34,8 @@ function sameSet(left: ReadonlySet, right: ReadonlySet): boolean function resolutionContext(facts: readonly FileFacts[], environment: ShellEnvironment, projectRoot: string, previous: ResolutionContext): ResolutionContext { - const generated = classCommands(facts.map(file => file.classes)); + const classFiles = facts.map(file => file.classes); + const generated = classCommands(classFiles); const declarations: Declarations = { aliases: new Set(facts.flatMap(file => [...file.declarations.aliases])), globalAliases: new Set(facts.flatMap(file => [...file.declarations.globalAliases])), @@ -45,8 +46,8 @@ function resolutionContext(facts: readonly FileFacts[], environment: ShellEnviro if (environment === previous.environment && projectRoot === previous.projectRoot && sameSet(declarations.aliases, previous.aliases) && sameSet(declarations.globalAliases, previous.globalAliases) && sameSet(declarations.suffixAliases, previous.suffixAliases) && sameSet(declarations.autoloads, previous.autoloads) && - sameSet(declarations.builtins, previous.builtins) && sameSet(generated, previous.classCommands)) return previous; - return { ...declarations, environment, projectRoot, classCommands: generated }; + sameSet(declarations.builtins, previous.builtins) && sameClassFiles(classFiles, previous.classFiles)) return previous; + return { ...declarations, environment, projectRoot, classCommands: generated, classFiles }; } function suppressed(file: ZshFileHydration, diagnostics: readonly Diagnostics[]): readonly Diagnostics[] { @@ -84,7 +85,7 @@ export function refreshDiagnosticSnapshot({ snapshot, environment, previous = cr const local = input.project ? context : resolutionContext([...projectFacts, current], environment, context.projectRoot, context); const effective = input.project ? context : { - ...context, classCommands: local.classCommands, aliases: new Set([...context.aliases, ...local.aliases]), + ...context, classCommands: local.classCommands, classFiles: local.classFiles, aliases: new Set([...context.aliases, ...local.aliases]), globalAliases: new Set([...context.globalAliases, ...local.globalAliases]), suffixAliases: new Set([...context.suffixAliases, ...local.suffixAliases]), autoloads: new Set([...context.autoloads, ...local.autoloads]), diff --git a/ls/server/test/diagnostics/classDeclarations.test.ts b/ls/server/test/diagnostics/classDeclarations.test.ts deleted file mode 100644 index 7e8b1238..00000000 --- a/ls/server/test/diagnostics/classDeclarations.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { findAll } from '../../src/zshParser/ast'; -import { createZshFileHydration } from '../../src/zshHydrator'; -import { createClassState, classDeclaration, classCommands } from '../../src/diagnostics/classes'; - -function command(content: string) { - const file = createZshFileHydration({ sourceFile: 'classes.zsh', file: 'classes.zsh', content }); - const node = findAll(file.ast, 'simpleCommand')[0]; - if (!node) throw new Error('Expected a command in the class fixture'); - return node; -} - -describe('createClassState', () => { - test('空の独立した状態を返す', () => { - const first = createClassState(); - const second = createClassState(); - expect(first.definitions.size).toBe(0); - expect(first.instances.size).toBe(0); - expect(first.pending).toBeNull(); - expect(first.definitions).not.toBe(second.definitions); - expect(first.instances).not.toBe(second.instances); - }); -}); - -describe('classDeclaration', () => { - test('入力を変更せずに定義を開始する', () => { - const before = createClassState(); - const next = classDeclaration(command('z.cls.draw Counter'), 1, undefined, before); - expect(before.pending).toBeNull(); - expect(next.pending).toMatchObject({ kind: 'definition', definition: { name: 'Counter' } }); - expect(next.definitions.size).toBe(0); - }); - - test('属性のget/setを追加し、前のメンバー集合を保持する', () => { - const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); - const next = classDeclaration(command('z.cls.attr count 0'), 1, undefined, drawing); - expect(drawing.pending?.definition.members.size).toBe(0); - expect([...next.pending?.definition.members ?? []]).toEqual(['count.get', 'count.set']); - }); - - test('同じ深さの終了マーカーで本体を閉じ、公開時だけ定義に加える', () => { - const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); - const method = classDeclaration(command('z.cls.fn increment'), 1, undefined, drawing); - expect(method.pending?.kind).toBe('method'); - expect(classDeclaration(command('z.cls.fn.done'), 2, undefined, method)).toBe(method); - const ended = classDeclaration(command('z.cls.fn.done'), 1, undefined, method); - expect(ended.pending?.kind).toBe('definition'); - expect(method.pending?.kind).toBe('method'); - const published = classDeclaration(command('z.cls.drew'), 1, undefined, ended); - expect([...published.definitions.get('Counter') ?? []]).toEqual(['increment']); - expect(published.pending).toBeNull(); - expect(ended.definitions.size).toBe(0); - }); - - test('inline本体は捕捉状態に入らず登録する', () => { - const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); - const next = classDeclaration(command("z.cls.fn value 'REPLY=$count'"), 1, undefined, drawing); - expect(next.pending?.kind).toBe('definition'); - expect([...next.pending?.definition.members ?? []]).toEqual(['value']); - }); - - test('入れ子の別関数にある終了名では本体を閉じない', () => { - const file = createZshFileHydration({ sourceFile: 'scope.zsh', file: 'scope.zsh', content: 'helper() { : }' }); - const scope = file.functions[0]?.definition; - if (!scope) throw new Error('Expected a function scope'); - const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); - const method = classDeclaration(command('z.cls.fn run'), 1, undefined, drawing); - expect(classDeclaration(command('z.cls.fn.done'), 1, scope, method)).toBe(method); - }); - - test('同名bindingの候補を入力集合を変えずに追加する', () => { - const first = classDeclaration(command('z.cls.new Counter object'), 1, undefined, createClassState()); - const next = classDeclaration(command('z.cls.new ArrayBox object'), 1, undefined, first); - expect([...first.instances.get('object') ?? []]).toEqual(['Counter']); - expect([...next.instances.get('object') ?? []]).toEqual(['Counter', 'ArrayBox']); - }); - - test.each(['z.cls.new $class object', 'z.cls.new z_cls_reserved object', 'z.cls.new Counter bad-name', - 'z.cls.new Counter', 'z.cls.draw bad-name'])('不完全・動的・予約済みの宣言を登録しない: %s', source => { - const before = createClassState(); - expect(classDeclaration(command(source), 1, undefined, before)).toBe(before); - }); - - test('abortで未公開の定義を破棄し、入力状態を保持する', () => { - const drawing = classDeclaration(command('z.cls.draw Counter'), 1, undefined, createClassState()); - const next = classDeclaration(command('z.cls.abort'), 1, undefined, drawing); - expect(next.pending).toBeNull(); - expect(drawing.pending?.definition.name).toBe('Counter'); - expect(next.definitions.size).toBe(0); - }); -}); - -describe('classCommands', () => { - test('別ファイルの定義と複数の候補を組み合わせ、入力集合を保持する', () => { - const definitions = new Map([['Counter', new Set(['increment', 'count.get'])], ['ArrayBox', new Set(['fill'])]]); - const instances = new Map([['object', new Set(['Counter', 'ArrayBox'])]]); - const result = classCommands([{ definitions, instances: new Map() }, { definitions: new Map(), instances }]); - expect([...result]).toEqual(['object.increment', 'object.count.get', 'object.fill']); - expect(definitions.size).toBe(2); - expect(instances.get('object')?.size).toBe(2); - }); - - test('未公開クラスからはコマンドを生成しない', () => { - expect([...classCommands([{ definitions: new Map(), instances: new Map([['object', new Set(['Missing'])]]) }])]).toEqual([]); - }); -}); diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index 99adf770..f468aff4 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -9,6 +9,9 @@ import { refreshDiagnosticSnapshot } from '../../src/diagnostics/snapshot'; import { readShellEnvironment, emptyShellEnvironment } from '../../src/diagnostics/environment'; import type { ShellEnvironment } from '../../src/diagnostics/environment'; import { validateTextDocument } from '../../src/diagnostics/main'; +import { createZshFileHydration } from '../../src/zshHydrator'; +import { classCommands, sameClassFiles } from '../../src/diagnostics/classes'; +import { analyzeCalls } from '../../src/diagnostics/calls'; const roots: string[] = []; const environmentRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'z-class-diag-shell-')); @@ -36,7 +39,7 @@ function fixture(content: string, definitions: string) { const semantic = (items: Readonly>) => items.filter(item => ['missing-positional-argument', 'missing-named-argument', 'undefined-command'].includes(item.code ?? '')); -const classApi = ['z.cls.draw() { : }', 'z.cls.attr() { : }', 'z.cls.fn() { : }', +const classApi = ['z.cls.draw() { : }', 'z.cls.attr() { : }', '# $1: method name', '# $2? [code]: inline body', 'z.cls.fn() { : \"$@\" }', 'z.cls.fn.done() { : }', 'z.cls.drew() { : }', 'z.cls.new() { : }'].join('\n') + '\n'; const counterClass = [ 'z.cls.draw Counter; {', @@ -49,6 +52,16 @@ const counterClass = [ ].join('\n'); describe('class DSL command diagnostics', () => { + test('inlineメソッド本体はmainのcode引数診断で元位置に報告する', () => { + const source = counterClass.replace('z.cls.fn increment\n (( ++count ))\n z.cls.fn.done', + "z.cls.fn increment 'missing_inline_method'"); + const f = fixture('', classApi + source); + const diagnostics = f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'undefined-command') ?? []; + expect(diagnostics).toHaveLength(1); + expect(diagnostics[0].message).toContain('missing_inline_method'); + expect(diagnostics[0].range.start.line).toBe(10); + }); + test('別ファイルのクラスから生成されるメソッドと属性を認識し、タイプミスは診断する', () => { const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.count.get\ncounter.count.set 3\ncounter.typo\n', classApi + counterClass); @@ -61,7 +74,7 @@ describe('class DSL command diagnostics', () => { const source = counterClass.replace('(( ++count ))', 'missing_inside_method'); const f = fixture('', classApi + source); expect(semantic(f.diagnostics.files.get(f.definitionUri)?.items ?? [])).toMatchObject([{ - code: 'undefined-command', range: { start: { line: 9, character: 4 } }, + code: 'undefined-command', range: { start: { line: 11, character: 4 } }, }]); }); @@ -107,3 +120,61 @@ describe('scoped class references', () => { expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); }); }); + +describe('hydrated class command targets', () => { + test('別ファイルのclassとinstanceを実際のメンバーノードへ結び付ける', () => { + const definitions = createZshFileHydration({ sourceFile: '/defs.zsh', file: 'defs.zsh', content: counterClass }); + const bindings = createZshFileHydration({ sourceFile: '/caller.zsh', file: 'caller.zsh', content: 'z.cls.new Counter object\n' }); + const targets = classCommands([definitions.classes, bindings.classes]); + const method = targets.get('object.increment')?.[0]; + expect(method?.definition).toBe(definitions.classes.definitions[0]); + expect(method?.member).toBe(definitions.classes.definitions[0].methods[0]); + expect(method?.instance).toBe(bindings.classes.instances[0]); + expect(method?.operation).toBe('method'); + expect(targets.get('object.count.set')?.[0].member).toBe(definitions.classes.definitions[0].attributes[0]); + }); + + test('未公開とabortのclassからはターゲットを生成しない', () => { + for (const ending of ['', 'z.cls.abort\n']) { + const file = createZshFileHydration({ sourceFile: 'x', file: 'x', + content: 'z.cls.draw Open\nz.cls.attr count 0\n' + ending + 'z.cls.new Open object\n' }); + expect(classCommands([file.classes]).size).toBe(0); + } + }); + + test('同じASTを再利用し、変更したclassの参照は古いcontextへ残さない', () => { + const file = createZshFileHydration({ sourceFile: 'x', file: 'x', content: counterClass }); + const next = createZshFileHydration({ sourceFile: 'x', file: 'x', content: counterClass.replace('increment', 'reset') }); + expect(sameClassFiles([file.classes], [file.classes])).toBe(true); + expect(sameClassFiles([file.classes], [next.classes])).toBe(false); + const empty = createZshFileHydration({ sourceFile: 'y', file: 'y', content: 'print one\n' }); + expect(sameClassFiles([empty.classes], [])).toBe(true); + }); + + test('呼出解析がclassメンバーの解決先を名前の除外だけでなく返す', () => { + const f = fixture('z.cls.new Counter object\nobject.increment\n', classApi + counterClass); + const report = f.diagnostics.files.get(f.document.uri); + if (!report) throw new Error('Expected caller diagnostics'); + const analysis = analyzeCalls(f.snapshot, report.file, report.facts.calls, f.diagnostics.context); + const targets = [...analysis.classTargets.values()].flat(); + expect(targets).toHaveLength(1); + expect(targets[0].member).toMatchObject({ kind: 'classMethod', name: 'increment' }); + expect(targets[0].member.declaration.commandName?.word.raw).toBe('z.cls.fn'); + }); + + test('code引数内のinstanceは外側のclassを使い、外側へ漏れない', () => { + const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; + const f = fixture("run 'z.cls.new Counter inside; inside.increment'\ninside.increment\n", classApi + counterClass + api); + expect(semantic(f.items)).toHaveLength(1); + expect(semantic(f.items)[0].range.start.line).toBe(1); + }); + + test('code引数内のclassはそのcode内で解決し、projectへ漏れない', () => { + const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; + const text = "run 'z.cls.draw Local; z.cls.fn value \"REPLY=1\"; z.cls.drew; z.cls.new Local local_object; local_object.value'\n" + + 'z.cls.new Local outside\noutside.value\n'; + const f = fixture(text, classApi + api); + expect(semantic(f.items)).toHaveLength(1); + expect(semantic(f.items)[0].message).toContain('outside.value'); + }); +}); From 80aafce48ca106f33e3f2ebf70cd769b49aec973 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 14:15:38 +0900 Subject: [PATCH 06/21] refactor: make class hydration types and transitions explicit Expand semantic fields and state transitions into readable steps, share the member transition, and resolve lexical owners through the final AST index. Match the runtime reserved prefix and retain source positions, readonly data and node identity. --- ls/server/src/zshHydrator/classes/collect.ts | 234 ++++++++++++++---- ls/server/src/zshHydrator/classes/index.ts | 186 +++++++++++--- ls/server/src/zshHydrator/classes/types.ts | 133 ++++++++-- ls/server/src/zshHydrator/fileHydration.ts | 7 +- ls/server/src/zshHydrator/index.ts | 18 +- ls/server/test/zshHydrator/classes.test.ts | 65 ++++- .../test/zshParser/ast/word/literal.test.ts | 2 + 7 files changed, 518 insertions(+), 127 deletions(-) diff --git a/ls/server/src/zshHydrator/classes/collect.ts b/ls/server/src/zshHydrator/classes/collect.ts index 6c20f76a..378537c7 100644 --- a/ls/server/src/zshHydrator/classes/collect.ts +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -2,13 +2,29 @@ import type { FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../ import { walk } from '../../zshParser/ast'; import { literalWord } from '../../zshParser/ast/word/literal'; import type { SourceRange } from '../../zshParser/lexer'; -import type { ClassInformation, ClassScopeLocation } from './types'; +import type { ClassDefinition, ClassInformation, ClassScopeLocation } from './types'; -type Member = { readonly node: SimpleCommandNode; readonly information: ClassInformation }; -type Definition = { readonly node: SimpleCommandNode; readonly name: string; readonly members: readonly Member[] }; +type Member = { + readonly node: SimpleCommandNode; + readonly information: ClassInformation; +}; +type Definition = { + readonly node: SimpleCommandNode; + readonly name: string; + readonly members: readonly Member[]; +}; type Capture = - | { readonly kind: 'definition'; readonly definition: Definition } - | { readonly kind: 'method'; readonly definition: Definition; readonly node: SimpleCommandNode; readonly name: string; readonly depth: number }; + | { + readonly kind: 'definition'; + readonly definition: Definition; + } + | { + readonly kind: 'method'; + readonly definition: Definition; + readonly node: SimpleCommandNode; + readonly name: string; + readonly depth: number; + }; type State = { readonly scopes: ReadonlyMap; readonly information: ReadonlyMap; @@ -16,105 +32,225 @@ type State = { /** Keep runtime-reserved names outside statically declared class symbols. */ function identifier(value: string | null | undefined): value is string { - return value !== null && value !== undefined && value.length > 0 && - [...value].every((char, index) => char === '_' || char >= 'a' && char <= 'z' || - char >= 'A' && char <= 'Z' || index > 0 && char >= '0' && char <= '9') && - !value.startsWith('z_cls_') && !value.startsWith('__z_cls_'); + if (!value || value.startsWith('z_cls_')) return false; + + return [...value].every((char, index) => { + const letter = char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z'; + const digit = index > 0 && char >= '0' && char <= '9'; + + return char === '_' || letter || digit; + }); } + /** Store ownership by position so syntax attachments never retain an earlier AST. */ function scopeLocation(scope: FunctionDefinitionNode | undefined): ClassScopeLocation { return scope ? { kind: 'function', offset: scope.range.start.offset } : { kind: 'file' }; } + /** Replace one lexical capture without changing previous states. */ function withCapture(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture | null): State { const scopes = new Map(state.scopes); - if (capture) scopes.set(scope, capture); - else scopes.delete(scope); + + if (capture) { + scopes.set(scope, capture); + } else { + scopes.delete(scope); + } + return { ...state, scopes }; } + +/** Add a member through the same immutable transition for every declaration form. */ +function withMember(state: State, scope: FunctionDefinitionNode | undefined, + definition: Definition, member: Member): State { + return withCapture(state, scope, { + kind: 'definition', + definition: { + ...definition, + members: [...definition.members, member], + }, + }); +} + /** Keep block source positions even when editing leaves its end marker absent. */ -function method(capture: Extract, end: SourceRange, closed: boolean): Member { - return { node: capture.node, information: { kind: 'classMethod', name: capture.name, - classOffset: capture.definition.node.range.start.offset, - body: { kind: 'block', range: { start: capture.node.range.end, end: end.start }, end: closed ? end : null } } }; +function blockMethod(capture: Extract, end: SourceRange, closed: boolean): Member { + return { + node: capture.node, + information: { + kind: 'classMethod', + name: capture.name, + classOffset: capture.definition.node.range.start.offset, + body: { + kind: 'block', + range: { start: capture.node.range.end, end: end.start }, + end: closed ? end : null, + }, + }, + }; } + /** Publish the complete definition and member meaning together. */ function finish(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture, - end: SourceRange, status: 'published' | 'aborted' | 'incomplete'): State { + end: SourceRange, status: ClassDefinition['state']): State { const definition = capture.definition; - const members = capture.kind === 'method' ? [...definition.members, method(capture, end, false)] : definition.members; + const members = capture.kind === 'method' + ? [...definition.members, blockMethod(capture, end, false)] + : definition.members; const information = new Map(state.information); - information.set(definition.node.range.start.offset, { kind: 'classDefinition', name: definition.name, - scope: scopeLocation(scope), state: status, range: { start: definition.node.range.start, end: end.end } }); - for (const member of members) information.set(member.node.range.start.offset, member.information); + + information.set(definition.node.range.start.offset, { + kind: 'classDefinition', + name: definition.name, + scope: scopeLocation(scope), + state: status, + range: { start: definition.node.range.start, end: end.end }, + }); + + for (const member of members) { + information.set(member.node.range.start.offset, member.information); + } + return { ...withCapture(state, scope, null), information }; } + /** Interpret only literal directive commands in the current native function scope. */ -function declaration(command: SimpleCommandNode, depth: number, scope: FunctionDefinitionNode | undefined, state: State): State { - if (command.precommandModifiers.some(modifier => modifier.type === 'builtin' || modifier.type === 'command')) return state; +function declaration(command: SimpleCommandNode, depth: number, + scope: FunctionDefinitionNode | undefined, state: State): State { + const external = command.precommandModifiers.some( + modifier => modifier.type === 'builtin' || modifier.type === 'command', + ); + if (external) return state; + const name = command.commandName && literalWord(command.commandName.word); if (!name || !name.startsWith('z.cls.')) return state; - if (!['z.cls.draw', 'z.cls.attr', 'z.cls.fn', 'z.cls.fn.done', 'z.cls.drew', 'z.cls.abort', 'z.cls.new'].includes(name)) return state; + + const directives = ['z.cls.draw', 'z.cls.attr', 'z.cls.fn', 'z.cls.fn.done', + 'z.cls.drew', 'z.cls.abort', 'z.cls.new']; + if (!directives.includes(name)) return state; + const args = command.arguments.map(word => literalWord(word)); const capture = state.scopes.get(scope); + if (name === 'z.cls.new' && args.length === 2 && identifier(args[0]) && identifier(args[1])) { const information = new Map(state.information); - information.set(command.range.start.offset, { kind: 'classInstance', name: args[1], className: args[0], - scope: capture?.kind === 'method' ? { kind: 'classMethod', offset: capture.node.range.start.offset } : scopeLocation(scope) }); + const location: ClassScopeLocation = capture?.kind === 'method' + ? { kind: 'classMethod', offset: capture.node.range.start.offset } + : scopeLocation(scope); + + information.set(command.range.start.offset, { + kind: 'classInstance', + name: args[1], + className: args[0], + scope: location, + }); + return { ...state, information }; } + if (capture?.kind === 'method') { if (depth !== capture.depth) return state; + if (name === 'z.cls.fn.done' && args.length === 0) { - return withCapture(state, scope, { kind: 'definition', definition: { ...capture.definition, - members: [...capture.definition.members, method(capture, command.range, true)] } }); + return withMember(state, scope, capture.definition, blockMethod(capture, command.range, true)); + } + + if (name === 'z.cls.abort' || name === 'z.cls.drew') { + return finish(state, scope, capture, command.range, 'aborted'); } - return name === 'z.cls.abort' || name === 'z.cls.drew' ? finish(state, scope, capture, command.range, 'aborted') : state; + + return state; } + if (name === 'z.cls.draw' && args.length === 1 && identifier(args[0]) && !capture) { - return withCapture(state, scope, { kind: 'definition', definition: { node: command, name: args[0], members: [] } }); + return withCapture(state, scope, { + kind: 'definition', + definition: { node: command, name: args[0], members: [] }, + }); } + if (!capture) return state; + const definition = capture.definition; + if (name === 'z.cls.attr' && args.length === 2 && identifier(args[0])) { - if (definition.members.some(m => m.information.kind === 'classAttribute' && m.information.name === args[0])) return state; - return withCapture(state, scope, { kind: 'definition', definition: { ...definition, - members: [...definition.members, { node: command, information: { kind: 'classAttribute', name: args[0], - classOffset: definition.node.range.start.offset } }] } }); + const duplicate = definition.members.some( + member => member.information.kind === 'classAttribute' && member.information.name === args[0], + ); + if (duplicate) return state; + + return withMember(state, scope, definition, { + node: command, + information: { + kind: 'classAttribute', + name: args[0], + classOffset: definition.node.range.start.offset, + }, + }); } + if (name === 'z.cls.fn' && args.length >= 1 && args.length <= 2 && identifier(args[0])) { - if (definition.members.some(m => m.information.kind === 'classMethod' && m.information.name === args[0])) { + const duplicate = definition.members.some( + member => member.information.kind === 'classMethod' && member.information.name === args[0], + ); + if (duplicate) { return args.length === 1 ? finish(state, scope, capture, command.range, 'aborted') : state; } - if (args.length === 1) return withCapture(state, scope, { kind: 'method', definition, node: command, name: args[0], depth }); - return withCapture(state, scope, { kind: 'definition', definition: { ...definition, - members: [...definition.members, { node: command, information: { kind: 'classMethod', name: args[0], + + if (args.length === 1) { + return withCapture(state, scope, { kind: 'method', definition, node: command, name: args[0], depth }); + } + + return withMember(state, scope, definition, { + node: command, + information: { + kind: 'classMethod', + name: args[0], classOffset: definition.node.range.start.offset, - body: { kind: 'inline', range: command.arguments[1].range } } }] } }); + body: { kind: 'inline', range: command.arguments[1].range }, + }, + }); } - if (name === 'z.cls.drew' && args.length === 0) return finish(state, scope, capture, command.range, 'published'); - return name === 'z.cls.abort' ? finish(state, scope, capture, command.range, 'aborted') : state; + + if (name === 'z.cls.drew' && args.length === 0) { + return finish(state, scope, capture, command.range, 'published'); + } + + if (name === 'z.cls.abort') { + return finish(state, scope, capture, command.range, 'aborted'); + } + + return state; } /** Interpret class directives from syntax commands, independently in each native function scope. */ export function collectClassInformation(ast: FileNode): ReadonlyMap { let state: State = { scopes: new Map(), information: new Map() }; const scopes: { readonly node: FunctionDefinitionNode; readonly depth: number }[] = []; + walk(ast, (node, depth) => { - while (scopes.length && scopes[scopes.length - 1].depth >= depth) scopes.pop(); - if (node.kind === 'functionDefinition') scopes.push({ node, depth }); - if (node.kind === 'simpleCommand') { - if ('hydration' in node) { - const information = new Map(state.information); - information.set(node.range.start.offset, null); - state = { ...state, information }; - } - state = declaration(node, depth, scopes.at(-1)?.node, state); + while (scopes.length && scopes[scopes.length - 1].depth >= depth) { + scopes.pop(); + } + + if (node.kind === 'functionDefinition') { + scopes.push({ node, depth }); + } + + if (node.kind !== 'simpleCommand') return; + + if ('hydration' in node) { + const information = new Map(state.information); + information.set(node.range.start.offset, null); + state = { ...state, information }; } + + state = declaration(node, depth, scopes.at(-1)?.node, state); }); + for (const [scope, capture] of state.scopes) { const end = scope?.range.end ?? ast.range.end; state = finish(state, scope, capture, { start: end, end }, 'incomplete'); } + return state.information; } diff --git a/ls/server/src/zshHydrator/classes/index.ts b/ls/server/src/zshHydrator/classes/index.ts index 408b0a55..896828c9 100644 --- a/ls/server/src/zshHydrator/classes/index.ts +++ b/ls/server/src/zshHydrator/classes/index.ts @@ -1,18 +1,39 @@ import type { AstNode, FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../zshParser/ast'; import { findAll, mapAst } from '../../zshParser/ast'; import { collectClassInformation } from './collect'; -import type { ClassInformation, ClassFileHydration, ClassDefinition, ClassAttribute, ClassMethod, - ClassInstance, HydratedClassCommand } from './types'; +import type { + ClassAttribute, + ClassDefinition, + ClassFileHydration, + ClassInformation, + ClassInstance, + ClassMethod, + ClassMethodScope, + ClassScopeLocation, + HydratedClassCommand, +} from './types'; + export type * from './types'; +type DefinitionGroup = { + readonly definition: Omit; + readonly attributes: ClassAttribute[]; + readonly methods: ClassMethod[]; +}; + /** Narrow the attachment through its class role discriminator. */ export function isHydratedClassCommand(node: SimpleCommandNode): node is HydratedClassCommand { - if (!('hydration' in node) || typeof node.hydration !== 'object' || node.hydration === null) return false; + if (!('hydration' in node) || typeof node.hydration !== 'object' || node.hydration === null) { + return false; + } + const information = node.hydration; + return 'kind' in information && 'name' in information && typeof information.name === 'string' && (information.kind === 'classDefinition' || information.kind === 'classAttribute' || information.kind === 'classMethod' || information.kind === 'classInstance'); } + /** Expose class meaning without changing the generic syntax node types. */ export function classInformationOf(node: SimpleCommandNode): ClassInformation | null { return isHydratedClassCommand(node) ? node.hydration : null; @@ -22,87 +43,172 @@ export function classInformationOf(node: SimpleCommandNode): ClassInformation | export function hydrateClasses(ast: FileNode): FileNode { const information = collectClassInformation(ast); if (information.size === 0) return ast; + return mapAst(ast, (node: AstNode): AstNode => { if (node.kind !== 'simpleCommand') return node; + const value = information.get(node.range.start.offset); if (value) { const hydrated: HydratedClassCommand = { ...node, hydration: value }; return hydrated; } + if (isHydratedClassCommand(node)) { const { hydration, ...syntax } = node; return syntax; } + return node; }); } -/** Build indexes only after enrichment, so every declaration/word/scope refers to the returned AST. */ +/** Resolve an attachment's lexical owner against the final enriched syntax nodes. */ +function instanceScope(location: ClassScopeLocation, + functions: ReadonlyMap, + commands: ReadonlyMap): ClassInstance['scope'] | null { + if (location.kind === 'file') return { kind: 'file' }; + + if (location.kind === 'function') { + const declaration = functions.get(location.offset); + return declaration ? { kind: 'function', declaration } : null; + } + + const declaration = commands.get(location.offset); + return declaration ? { kind: 'classMethod', declaration } : null; +} + +/** Group member indexes under definition nodes from the returned AST. */ +function definitionGroups(ast: FileNode, commands: readonly HydratedClassCommand[], + functions: ReadonlyMap): Map { + const groups = new Map(); + + for (const command of commands) { + const information = command.hydration; + const nameNode = command.arguments[0]; + if (information.kind !== 'classDefinition' || !nameNode) continue; + + const scope = information.scope.kind === 'function' + ? functions.get(information.scope.offset) ?? null + : null; + + groups.set(command.range.start.offset, { + definition: { + kind: 'classDefinition', + name: information.name, + declaration: command, + nameNode, + file: ast, + scope, + state: information.state, + range: information.range, + }, + attributes: [], + methods: [], + }); + } + + return groups; +} + +/** Build indexes only after enrichment, so declarations, words and scopes refer to the returned AST. */ export function classesFromAst(ast: FileNode): ClassFileHydration { const commands = findAll(ast, 'simpleCommand').filter(isHydratedClassCommand); - if (commands.length === 0) return { definitions: [], instances: [], methodScopes: new Map() }; + if (commands.length === 0) { + return { definitions: [], instances: [], methodScopes: new Map() }; + } + const commandByOffset = new Map(commands.map(node => [node.range.start.offset, node])); const functions = new Map(findAll(ast, 'functionDefinition').map(node => [node.range.start.offset, node])); - const groups = new Map; - attributes: ClassAttribute[]; methods: ClassMethod[] }>(); - for (const command of commands) { - const information = classInformationOf(command); - if (information?.kind !== 'classDefinition' || !command.arguments[0]) continue; - groups.set(command.range.start.offset, { definition: { kind: 'classDefinition', name: information.name, - declaration: command, nameNode: command.arguments[0], file: ast, - scope: information.scope.kind === 'function' ? functions.get(information.scope.offset) ?? null : null, - state: information.state, range: information.range }, attributes: [], methods: [] }); - } + const groups = definitionGroups(ast, commands, functions); const instances: ClassInstance[] = []; + for (const command of commands) { - const information = classInformationOf(command); - if (!information) continue; + const information = command.hydration; const [nameNode, value] = command.arguments; if (!nameNode) continue; - if (information.kind === 'classAttribute') { - if (value) groups.get(information.classOffset)?.attributes.push({ kind: 'classAttribute', name: information.name, - declaration: command, nameNode, defaultValue: value }); + + if (information.kind === 'classAttribute' && value) { + groups.get(information.classOffset)?.attributes.push({ + kind: 'classAttribute', + name: information.name, + declaration: command, + nameNode, + defaultValue: value, + }); } else if (information.kind === 'classMethod') { if (information.body.kind === 'inline' && !value) continue; - groups.get(information.classOffset)?.methods.push({ kind: 'classMethod', name: information.name, - declaration: command, nameNode, body: information.body.kind === 'inline' ? - { kind: 'inline', value } : information.body }); + + const body: ClassMethod['body'] = information.body.kind === 'inline' + ? { kind: 'inline', value } + : information.body; + + groups.get(information.classOffset)?.methods.push({ + kind: 'classMethod', + name: information.name, + declaration: command, + nameNode, + body, + }); } else if (information.kind === 'classInstance' && value) { - const location = information.scope; - const ownerFunction = location.kind === 'function' ? functions.get(location.offset) : null; - const ownerMethod = location.kind === 'classMethod' ? commandByOffset.get(location.offset) : null; - if (location.kind === 'function' && !ownerFunction || location.kind === 'classMethod' && !ownerMethod) continue; - const scope: ClassInstance['scope'] = ownerFunction ? { kind: 'function', declaration: ownerFunction } : - ownerMethod ? { kind: 'classMethod', declaration: ownerMethod } : { kind: 'file' }; - instances.push({ kind: 'classInstance', name: information.name, className: information.className, - declaration: command, classNameNode: nameNode, nameNode: value, scope, file: ast }); + const scope = instanceScope(information.scope, functions, commandByOffset); + if (!scope) continue; + + instances.push({ + kind: 'classInstance', + name: information.name, + className: information.className, + declaration: command, + classNameNode: nameNode, + nameNode: value, + scope, + file: ast, + }); } } - const definitions = [...groups.values()].map(group => ({ ...group.definition, - attributes: group.attributes, methods: group.methods })); - const methodScopes = new Map(); + + const definitions = [...groups.values()].map(group => ({ + ...group.definition, + attributes: group.attributes, + methods: group.methods, + })); + const methodScopes = new Map(); + for (const definition of definitions) { for (const method of definition.methods) { if (method.body.kind !== 'block') continue; + const scopes = methodScopes.get(definition.scope) ?? []; scopes.push({ method, range: method.body.range }); methodScopes.set(definition.scope, scopes); } } - for (const scopes of methodScopes.values()) scopes.sort((left, right) => left.range.start.offset - right.range.start.offset); + + for (const scopes of methodScopes.values()) { + scopes.sort((left, right) => left.range.start.offset - right.range.start.offset); + } + return { definitions, instances, methodScopes }; } /** Find method parameter ownership without interpreting class commands again during diagnostics. */ -export function classMethodAt(classes: ClassFileHydration, scope: FunctionDefinitionNode | null, offset: number): ClassMethod | null { +export function classMethodAt(classes: ClassFileHydration, + scope: FunctionDefinitionNode | null, offset: number): ClassMethod | null { const methods = classes.methodScopes.get(scope) ?? []; - let low = 0, high = methods.length - 1; + let low = 0; + let high = methods.length - 1; + while (low <= high) { const middle = Math.floor((low + high) / 2); const entry = methods[middle]; - if (offset < entry.range.start.offset) high = middle - 1; - else if (offset >= entry.range.end.offset) low = middle + 1; - else return entry.method; + + if (offset < entry.range.start.offset) { + high = middle - 1; + } else if (offset >= entry.range.end.offset) { + low = middle + 1; + } else { + return entry.method; + } } + return null; } diff --git a/ls/server/src/zshHydrator/classes/types.ts b/ls/server/src/zshHydrator/classes/types.ts index 16a8f946..d714f0bf 100644 --- a/ls/server/src/zshHydrator/classes/types.ts +++ b/ls/server/src/zshHydrator/classes/types.ts @@ -1,43 +1,124 @@ -import type { FileNode, FunctionDefinitionNode, SimpleCommandNode, WordNode } from '../../zshParser/ast'; +import type { + FileNode, + FunctionDefinitionNode, + SimpleCommandNode, + WordNode, +} from '../../zshParser/ast'; import type { SourceRange } from '../../zshParser/lexer'; export type ClassScopeLocation = | { readonly kind: 'file' } - | { readonly kind: 'function' | 'classMethod'; readonly offset: number }; + | { + readonly kind: 'function' | 'classMethod'; + readonly offset: number; + }; + export type ClassMethodBody = - | { readonly kind: 'inline'; readonly range: SourceRange } - | { readonly kind: 'block'; readonly range: SourceRange; readonly end: SourceRange | null }; + | { + readonly kind: 'inline'; + readonly range: SourceRange; + } + | { + readonly kind: 'block'; + readonly range: SourceRange; + readonly end: SourceRange | null; + }; + export type ClassInformation = - | { readonly kind: 'classDefinition'; readonly name: string; readonly scope: ClassScopeLocation; - readonly state: 'published' | 'aborted' | 'incomplete'; readonly range: SourceRange } - | { readonly kind: 'classAttribute'; readonly name: string; readonly classOffset: number } - | { readonly kind: 'classMethod'; readonly name: string; readonly classOffset: number; readonly body: ClassMethodBody } - | { readonly kind: 'classInstance'; readonly name: string; readonly className: string; readonly scope: ClassScopeLocation }; -export type HydratedClassCommand = SimpleCommandNode & { readonly hydration: ClassInformation }; + | { + readonly kind: 'classDefinition'; + readonly name: string; + readonly scope: ClassScopeLocation; + readonly state: 'published' | 'aborted' | 'incomplete'; + readonly range: SourceRange; + } + | { + readonly kind: 'classAttribute'; + readonly name: string; + readonly classOffset: number; + } + | { + readonly kind: 'classMethod'; + readonly name: string; + readonly classOffset: number; + readonly body: ClassMethodBody; + } + | { + readonly kind: 'classInstance'; + readonly name: string; + readonly className: string; + readonly scope: ClassScopeLocation; + }; + +export type HydratedClassCommand = SimpleCommandNode & { + readonly hydration: ClassInformation; +}; + export type ClassAttribute = { - readonly kind: 'classAttribute'; readonly name: string; readonly declaration: SimpleCommandNode; - readonly nameNode: WordNode; readonly defaultValue: WordNode; + readonly kind: 'classAttribute'; + readonly name: string; + readonly declaration: SimpleCommandNode; + readonly nameNode: WordNode; + readonly defaultValue: WordNode; }; + export type ClassMethod = { - readonly kind: 'classMethod'; readonly name: string; readonly declaration: SimpleCommandNode; + readonly kind: 'classMethod'; + readonly name: string; + readonly declaration: SimpleCommandNode; readonly nameNode: WordNode; - readonly body: { readonly kind: 'inline'; readonly value: WordNode } | - { readonly kind: 'block'; readonly range: SourceRange; readonly end: SourceRange | null }; + readonly body: + | { + readonly kind: 'inline'; + readonly value: WordNode; + } + | { + readonly kind: 'block'; + readonly range: SourceRange; + readonly end: SourceRange | null; + }; }; + export type ClassDefinition = { - readonly kind: 'classDefinition'; readonly name: string; readonly declaration: SimpleCommandNode; - readonly file: FileNode; readonly nameNode: WordNode; readonly scope: FunctionDefinitionNode | null; - readonly state: 'published' | 'aborted' | 'incomplete'; readonly range: SourceRange; - readonly attributes: readonly ClassAttribute[]; readonly methods: readonly ClassMethod[]; + readonly kind: 'classDefinition'; + readonly name: string; + readonly declaration: SimpleCommandNode; + readonly file: FileNode; + readonly nameNode: WordNode; + readonly scope: FunctionDefinitionNode | null; + readonly state: 'published' | 'aborted' | 'incomplete'; + readonly range: SourceRange; + readonly attributes: readonly ClassAttribute[]; + readonly methods: readonly ClassMethod[]; }; + export type ClassInstance = { - readonly kind: 'classInstance'; readonly name: string; readonly className: string; - readonly declaration: SimpleCommandNode; readonly nameNode: WordNode; readonly classNameNode: WordNode; - readonly file: FileNode; readonly scope: { readonly kind: 'file' } | - { readonly kind: 'function'; readonly declaration: FunctionDefinitionNode } | - { readonly kind: 'classMethod'; readonly declaration: SimpleCommandNode }; + readonly kind: 'classInstance'; + readonly name: string; + readonly className: string; + readonly declaration: SimpleCommandNode; + readonly nameNode: WordNode; + readonly classNameNode: WordNode; + readonly file: FileNode; + readonly scope: + | { readonly kind: 'file' } + | { + readonly kind: 'function'; + readonly declaration: FunctionDefinitionNode; + } + | { + readonly kind: 'classMethod'; + readonly declaration: SimpleCommandNode; + }; }; + +export type ClassMethodScope = { + readonly range: SourceRange; + readonly method: ClassMethod; +}; + export type ClassFileHydration = { - readonly definitions: readonly ClassDefinition[]; readonly instances: readonly ClassInstance[]; - readonly methodScopes: ReadonlyMap; + readonly definitions: readonly ClassDefinition[]; + readonly instances: readonly ClassInstance[]; + readonly methodScopes: ReadonlyMap; }; diff --git a/ls/server/src/zshHydrator/fileHydration.ts b/ls/server/src/zshHydrator/fileHydration.ts index 215c1360..7e3fb243 100644 --- a/ls/server/src/zshHydrator/fileHydration.ts +++ b/ls/server/src/zshHydrator/fileHydration.ts @@ -35,7 +35,12 @@ export function createZshFileHydration({ const ast = hydrateAst(parsed.ast, content, options); const definitions = findAll(ast, 'functionDefinition'); return { - sourceFile, file, ast, classes: classesFromAst(ast), tokens: parsed.tokens, query: createQueryContext(ast), + sourceFile, + file, + ast, + classes: classesFromAst(ast), + tokens: parsed.tokens, + query: createQueryContext(ast), functions: definitions.flatMap((definition) => definition.names.map((word) => ({ name: word.raw, definition }))), lexerDiagnostics: lexed.diagnostics, parserDiagnostics: parsed.diagnostics, diff --git a/ls/server/src/zshHydrator/index.ts b/ls/server/src/zshHydrator/index.ts index a717b978..3499ec33 100644 --- a/ls/server/src/zshHydrator/index.ts +++ b/ls/server/src/zshHydrator/index.ts @@ -6,5 +6,19 @@ export { hydrateAst, documentationOf, directivesOf, isHydratedDocBlock, isHydrat export type { HydratedDocBlock, HydratedComment } from './hydrate'; export type * from './documentation'; export type { Directive, DirectiveArgument, ControlComment, HydrationOptions } from './directive'; -export { hydrateClasses, classesFromAst, classInformationOf, isHydratedClassCommand, classMethodAt } from './classes'; -export type { ClassInformation, HydratedClassCommand, ClassFileHydration, ClassDefinition, ClassMethod, ClassAttribute, ClassInstance } from './classes'; +export { + hydrateClasses, + classesFromAst, + classInformationOf, + isHydratedClassCommand, + classMethodAt, +} from './classes'; +export type { + ClassInformation, + HydratedClassCommand, + ClassFileHydration, + ClassDefinition, + ClassMethod, + ClassAttribute, + ClassInstance, +} from './classes'; diff --git a/ls/server/test/zshHydrator/classes.test.ts b/ls/server/test/zshHydrator/classes.test.ts index 66529b49..7a3fc217 100644 --- a/ls/server/test/zshHydrator/classes.test.ts +++ b/ls/server/test/zshHydrator/classes.test.ts @@ -6,16 +6,39 @@ import { createZshFileHydration, hydrateAst } from '../../src/zshHydrator'; import { classInformationOf, classesFromAst, classMethodAt, hydrateClasses } from '../../src/zshHydrator/classes'; import { astContractViolations } from '../zshParser/parser/contracts'; -const source = ['z.cls.draw Counter; {', ' z.cls.attr count 0', ' z.cls.fn increment', - ' (( ++count ))', ' print "$1"', ' z.cls.fn.done', " z.cls.fn value 'REPLY=$count'", ' z.cls.drew', '}', - 'z.cls.new Counter object', ''].join('\n'); +const source = [ + 'z.cls.draw Counter; {', + ' z.cls.attr count 0', + ' z.cls.fn increment', + ' (( ++count ))', + ' print "$1"', + ' z.cls.fn.done', + " z.cls.fn value 'REPLY=$count'", + ' z.cls.drew', + '}', + 'z.cls.new Counter object', + '', +].join('\n'); + function fixture(content = source) { - return createZshFileHydration({ sourceFile: '/project/classes.zsh', file: 'classes.zsh', content }); + return createZshFileHydration({ + sourceFile: '/project/classes.zsh', + file: 'classes.zsh', + content, + }); } describe('class hydration', () => { + test('runtimeと同じ予約prefixだけを除外する', () => { + const file = fixture('z.cls.draw __z_cls_Box\nz.cls.attr __z_cls_value 0\nz.cls.drew\n'); + + expect(file.classes.definitions[0].name).toBe('__z_cls_Box'); + expect(file.classes.definitions[0].attributes[0].name).toBe('__z_cls_value'); + }); + test('classのないASTは追加コピーせず返す', () => { const file = fixture('print hello\n'); + expect(hydrateClasses(file.ast)).toBe(file.ast); }); @@ -23,8 +46,10 @@ describe('class hydration', () => { const text = source.replace('(( ++count ))', 'if true; then z.cls.fn.done; fi\n print deeper'); const file = fixture(text); const method = file.classes.definitions[0].methods[0]; + expect(method.body.kind).toBe('block'); if (method.body.kind !== 'block') throw new Error('Expected a block method'); + expect(method.body.end?.start.offset).toBe(text.lastIndexOf('z.cls.fn.done')); expect(classMethodAt(file.classes, null, text.indexOf('print deeper'))).toBe(method); }); @@ -32,24 +57,30 @@ describe('class hydration', () => { test.each(['z.cls.new $class object', 'z.cls.new z_cls_reserved object', 'z.cls.new Counter bad-name', 'z.cls.new Counter', 'z.cls.draw bad-name'])('動的・不完全・予約済みの名前を決め打ちしない: %s', text => { const file = fixture(text + '\n'); + expect(file.classes.definitions).toEqual([]); expect(file.classes.instances).toEqual([]); }); test('同名instanceのnative function scopeを返却ASTに結び付ける', () => { - const file = fixture('z.cls.new Counter object\nload() { local object; z.cls.new Other object; }\n'); + const file = fixture('z.cls.new Counter object\nload() { local object=""; z.cls.new Other object; }\n'); + expect(file.classes.instances[0].scope.kind).toBe('file'); const local = file.classes.instances[1]; + expect(local.scope.kind).toBe('function'); if (local.scope.kind !== 'function') throw new Error('Expected function ownership'); + expect(local.scope.declaration).toBe(file.functions[0].definition); }); test('子のcommandを付加情報で更新してもdefaultのWord参照が古くならない', () => { const file = fixture('z.cls.draw Holder\nz.cls.attr value "$(z.cls.new Other inside)"\nz.cls.drew\n'); const attribute = file.classes.definitions[0].attributes[0]; + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); const binding = file.classes.instances.find(item => item.name === 'inside'); + expect(binding).toBeDefined(); expect(findAll(attribute.defaultValue, 'simpleCommand')).toContain(binding?.declaration); expect(file.classes.definitions[0].file).toBe(file.ast); @@ -61,6 +92,7 @@ describe('class hydration', () => { const ordinary = fixture('print hello\n'); const stale = mapAst(ordinary.ast, node => node.kind === 'simpleCommand' ? { ...node, hydration: information } : node); const refreshed = hydrateAst(stale, 'print hello\n'); + expect(findAll(refreshed, 'simpleCommand').map(classInformationOf)).toEqual([null]); expect(classesFromAst(refreshed).definitions).toEqual([]); expect(findAll(stale, 'simpleCommand').map(classInformationOf)).toEqual([information]); @@ -69,6 +101,7 @@ describe('class hydration', () => { test('class・属性・メソッド・instanceに意味情報を付与し、通常の構文ノードを保持する', () => { const file = fixture(); const definition = file.classes.definitions[0]; + expect(definition).toMatchObject({ kind: 'classDefinition', name: 'Counter', state: 'published' }); expect(definition.declaration.kind).toBe('simpleCommand'); expect(classInformationOf(definition.declaration)?.kind).toBe('classDefinition'); @@ -82,9 +115,11 @@ describe('class hydration', () => { const file = fixture(); const commands = findAll(file.ast, 'simpleCommand'); const definition = file.classes.definitions[0]; + expect(commands).toContain(definition.declaration); expect(definition.nameNode).toBe(definition.declaration.arguments[0]); const attribute = definition.attributes[0]; + expect(commands).toContain(attribute.declaration); expect(attribute.nameNode).toBe(attribute.declaration.arguments[0]); expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); @@ -95,12 +130,15 @@ describe('class hydration', () => { test('blockとinlineの本体を元の範囲またはWordとして保持する', () => { const file = fixture(); const [block, inline] = file.classes.definitions[0].methods; + expect(block.body.kind).toBe('block'); if (block.body.kind !== 'block') throw new Error('Expected a block method'); + expect(source.slice(block.body.range.start.offset, block.body.range.end.offset)).toContain('(( ++count ))'); expect(source.slice(block.body.range.start.offset, block.body.range.end.offset)).not.toContain('z.cls.fn.done'); expect(inline.body.kind).toBe('inline'); if (inline.body.kind !== 'inline') throw new Error('Expected an inline method'); + expect(inline.body.value).toBe(inline.declaration.arguments[1]); expect(classMethodAt(file.classes, null, source.indexOf('print "$1"'))).toBe(block); expect(classMethodAt(file.classes, null, source.indexOf('z.cls.fn.done'))).toBeNull(); @@ -109,6 +147,7 @@ describe('class hydration', () => { test('入力ASTを変更せず再hydrationしても意味情報を重複させない', () => { const parsed = Parser.parse(Lexer.tokenize(source, { sourceFile: 'x' }).tokens, { sourceFile: 'x', path: 'x' }); const ast = hydrateAst(parsed.ast, source); + expect(findAll(parsed.ast, 'simpleCommand').map(classInformationOf).filter(Boolean)).toEqual([]); expect(hydrateAst(ast, source)).toEqual(ast); expect(classesFromAst(ast).definitions).toHaveLength(1); @@ -116,14 +155,17 @@ describe('class hydration', () => { test('未完了とabortを公開済みclassと区別する', () => { const incomplete = fixture('z.cls.draw Open\nz.cls.fn run\nprint "$1"\n'); + expect(incomplete.classes.definitions[0]).toMatchObject({ name: 'Open', state: 'incomplete' }); expect(incomplete.classes.definitions[0].methods[0].body).toMatchObject({ kind: 'block', end: null }); const aborted = fixture('z.cls.draw Discarded\nz.cls.attr count 0\nz.cls.abort\n'); + expect(aborted.classes.definitions[0]).toMatchObject({ name: 'Discarded', state: 'aborted' }); }); test('文字列・コメント・非function呼出をclassと誤認しない', () => { const file = fixture('# z.cls.draw Comment\nprint "z.cls.draw String"\ncommand z.cls.draw External\nbuiltin z.cls.new Counter object\n'); + expect(file.classes.definitions).toEqual([]); expect(file.classes.instances).toEqual([]); }); @@ -132,6 +174,7 @@ describe('class hydration', () => { const text = 'load() {\n' + source.slice(0, source.indexOf('z.cls.new')) + '}\n'; const file = fixture(text); const owner = file.functions.find(fn => fn.name === 'load')?.definition; + expect(file.classes.definitions[0].scope).toBe(owner); expect(owner && classMethodAt(file.classes, owner, text.indexOf('print "$1"'))?.name).toBe('increment'); expect(classMethodAt(file.classes, null, text.indexOf('print "$1"'))).toBeNull(); @@ -139,21 +182,25 @@ describe('class hydration', () => { test('入れ子のnative関数にある終端名で外側のメソッドを閉じない', () => { const file = fixture(source.replace('(( ++count ))', 'helper() { z.cls.fn.done }\n print "z.cls.fn.done"')); - expect(file.classes.definitions[0].methods.map(m => m.name)).toEqual(['increment', 'value']); + + expect(file.classes.definitions[0].methods.map(method => method.name)).toEqual(['increment', 'value']); }); test('メソッド内のinstance宣言をclass method scopeに結び付ける', () => { const file = fixture(source.replace('(( ++count ))', 'z.cls.new Other nested')); - const binding = file.classes.instances.find(i => i.name === 'nested'); + const binding = file.classes.instances.find(instance => instance.name === 'nested'); + expect(binding?.scope.kind).toBe('classMethod'); if (binding?.scope.kind !== 'classMethod') throw new Error('Expected a method scope'); + expect(binding.scope.declaration).toBe(file.classes.definitions[0].methods[0].declaration); }); test('native関数内のclassと外側のclassを同じpending状態にしない', () => { const text = 'z.cls.draw Outer\nhelper() { z.cls.draw Inner; z.cls.drew }\nz.cls.drew\n'; const file = fixture(text); - expect(file.classes.definitions.map(d => d.name)).toEqual(['Outer', 'Inner']); - expect(file.classes.definitions.find(d => d.name === 'Inner')?.scope).toBe(file.functions[0].definition); + + expect(file.classes.definitions.map(definition => definition.name)).toEqual(['Outer', 'Inner']); + expect(file.classes.definitions.find(definition => definition.name === 'Inner')?.scope).toBe(file.functions[0].definition); }); }); diff --git a/ls/server/test/zshParser/ast/word/literal.test.ts b/ls/server/test/zshParser/ast/word/literal.test.ts index e6056ce1..c52139db 100644 --- a/ls/server/test/zshParser/ast/word/literal.test.ts +++ b/ls/server/test/zshParser/ast/word/literal.test.ts @@ -8,6 +8,7 @@ import { literalWord as compatibilityLiteralWord } from '../../../../src/refresh function word(source: string) { const lexed = Lexer.tokenize(source, { sourceFile: 'literal.zsh' }); const parsed = Parser.parse(lexed.tokens, { sourceFile: 'literal.zsh', path: 'literal.zsh' }); + expect(lexed.diagnostics).toEqual([]); expect(parsed.diagnostics).toEqual([]); const argument = findAll(parsed.ast, 'simpleCommand')[0]?.arguments[0]; @@ -35,6 +36,7 @@ describe('literalWord', () => { test('指定された終端まで復元し、既存importの互換性を保持する', () => { const argument = word("print 'option'=value"); + expect(literalWord(argument, argument.raw.indexOf('='))).toBe('option'); expect(compatibilityLiteralWord).toBe(literalWord); }); From 546afc40387c729aa8278ca708b06eb97976f120 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 14:15:38 +0900 Subject: [PATCH 07/21] refactor: align class diagnostic consumers and test layout Use explicit semantic names, separate target and context construction, and make test setup, actions and assertions readable. Keep existing class, incremental and embedded-code cases and their resolution behavior. --- ls/server/src/diagnostics/calls.ts | 5 +- ls/server/src/diagnostics/classes.ts | 39 +++++-- ls/server/src/diagnostics/embedded/index.ts | 8 +- ls/server/src/diagnostics/facts.ts | 12 +- ls/server/src/diagnostics/snapshot.ts | 32 +++++- ls/server/test/diagnostics/classes.test.ts | 119 ++++++++++++++------ 6 files changed, 154 insertions(+), 61 deletions(-) diff --git a/ls/server/src/diagnostics/calls.ts b/ls/server/src/diagnostics/calls.ts index 1d47a5fa..2370d6d5 100644 --- a/ls/server/src/diagnostics/calls.ts +++ b/ls/server/src/diagnostics/calls.ts @@ -17,10 +17,11 @@ import type { ShellEnvironment } from './environment'; import type { Declarations } from './facts'; import { simpleParameter } from './facts'; import type { ClassFileHydration } from '../zshHydrator'; -import type { ClassCommandTargets, ClassCommandTarget } from './classes'; +import type { ClassCommandTarget, ClassCommandTargets } from './classes'; export type ResolutionContext = Declarations & { - readonly environment: ShellEnvironment; readonly projectRoot: string; + readonly environment: ShellEnvironment; + readonly projectRoot: string; readonly classCommands: ClassCommandTargets; readonly classFiles: readonly ClassFileHydration[]; }; diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts index f76ed81e..39231a80 100644 --- a/ls/server/src/diagnostics/classes.ts +++ b/ls/server/src/diagnostics/classes.ts @@ -1,37 +1,58 @@ -import type { ClassFileHydration, ClassDefinition, ClassInstance, ClassMethod, ClassAttribute } from '../zshHydrator/classes'; +import type { + ClassAttribute, + ClassDefinition, + ClassFileHydration, + ClassInstance, + ClassMethod, +} from '../zshHydrator/classes'; export type ClassCommandTarget = { - readonly definition: ClassDefinition; readonly instance: ClassInstance; - readonly member: ClassMethod | ClassAttribute; readonly operation: 'method' | 'get' | 'set'; + readonly definition: ClassDefinition; + readonly instance: ClassInstance; + readonly member: ClassMethod | ClassAttribute; + readonly operation: 'method' | 'get' | 'set'; }; export type ClassCommandTargets = ReadonlyMap; /** Resolve only published class symbols; targets retain declaration nodes and member provenance. */ export function classCommands(files: readonly ClassFileHydration[]): ClassCommandTargets { - const definitions = new Map(files.flatMap(file => file.definitions.filter(d => d.state === 'published').map(d => [d.name, d]))); + const definitions = new Map(files.flatMap(file => file.definitions + .filter(definition => definition.state === 'published') + .map(definition => [definition.name, definition]))); const commands = new Map(); + for (const file of files) { for (const instance of file.instances) { const definition = definitions.get(instance.className); if (!definition) continue; + for (const member of [...definition.methods, ...definition.attributes]) { - const operations: readonly ClassCommandTarget['operation'][] = member.kind === 'classMethod' ? ['method'] : ['get', 'set']; + const operations: readonly ClassCommandTarget['operation'][] = + member.kind === 'classMethod' ? ['method'] : ['get', 'set']; + for (const operation of operations) { - const name = instance.name + '.' + member.name + (operation === 'method' ? '' : '.' + operation); + const suffix = operation === 'method' ? '' : '.' + operation; + const name = instance.name + '.' + member.name + suffix; const targets = commands.get(name) ?? []; + targets.push({ definition, member, instance, operation }); commands.set(name, targets); } } } } + return commands; } /** Preserve cached contexts only while all class declaration and binding references are current. */ export function sameClassFiles(left: readonly ClassFileHydration[], right: readonly ClassFileHydration[]): boolean { - const declarations = (files: readonly ClassFileHydration[]) => files.flatMap(file => - [...file.definitions.map(d => d.declaration), ...file.instances.map(i => i.declaration)]); - const previous = declarations(left), next = declarations(right); + const declarations = (files: readonly ClassFileHydration[]) => files.flatMap(file => [ + ...file.definitions.map(definition => definition.declaration), + ...file.instances.map(instance => instance.declaration), + ]); + const previous = declarations(left); + const next = declarations(right); + return previous.length === next.length && previous.every((node, index) => node === next[index]); } diff --git a/ls/server/src/diagnostics/embedded/index.ts b/ls/server/src/diagnostics/embedded/index.ts index e6bd7afe..a7d4c53e 100644 --- a/ls/server/src/diagnostics/embedded/index.ts +++ b/ls/server/src/diagnostics/embedded/index.ts @@ -71,12 +71,16 @@ export function embeddedCallDiagnostics(snapshot: FunctionSnapshot, file: ZshFil const declarations = facts.declarations; const inherited = program.context; const classFiles = [...inherited.classFiles, child.classes]; - const childContext: ResolutionContext = { ...inherited, classFiles, classCommands: classCommands(classFiles), + const childContext: ResolutionContext = { + ...inherited, + classFiles, + classCommands: classCommands(classFiles), aliases: new Set([...inherited.aliases, ...declarations.aliases]), globalAliases: new Set([...inherited.globalAliases, ...declarations.globalAliases]), suffixAliases: new Set([...inherited.suffixAliases, ...declarations.suffixAliases]), autoloads: new Set([...inherited.autoloads, ...declarations.autoloads]), - builtins: new Set([...inherited.builtins, ...declarations.builtins]) }; + builtins: new Set([...inherited.builtins, ...declarations.builtins]), + }; pending.push({ file: child, calls: facts.calls, context: childContext, source, scopes: [{ file: program.file, offset: argument.word.range.start.offset }, ...program.scopes], depth: program.depth + 1 }); } diff --git a/ls/server/src/diagnostics/facts.ts b/ls/server/src/diagnostics/facts.ts index 7f33f4cf..8ae331c4 100644 --- a/ls/server/src/diagnostics/facts.ts +++ b/ls/server/src/diagnostics/facts.ts @@ -1,15 +1,13 @@ import type { FunctionDefinitionNode, SimpleCommandNode, WordNode } from '../zshParser/ast'; import { walk } from '../zshParser/ast'; -import type { ZshFileHydration } from '../zshHydrator'; -import { documentationOf } from '../zshHydrator'; +import type { ClassFileHydration, ZshFileHydration } from '../zshHydrator'; +import { classMethodAt, documentationOf } from '../zshHydrator'; import { DiagnosticSeverity } from '../vscode_type'; import type { Diagnostics } from './type'; import { protocolRange } from '../connection/ast/cursor'; import { literalWord } from '../refreshFunctions/word'; import { formatDiagnostics } from './format'; import { moduleBuiltins } from './modules'; -import { classMethodAt } from '../zshHydrator'; -import type { ClassFileHydration } from '../zshHydrator'; export type Declarations = { readonly aliases: ReadonlySet; readonly globalAliases: ReadonlySet; @@ -17,8 +15,10 @@ export type Declarations = { readonly builtins: ReadonlySet; }; export type FileFacts = { - readonly calls: readonly SimpleCommandNode[]; readonly base: readonly Diagnostics[]; - readonly declarations: Declarations; readonly classes: ClassFileHydration; + readonly calls: readonly SimpleCommandNode[]; + readonly base: readonly Diagnostics[]; + readonly declarations: Declarations; + readonly classes: ClassFileHydration; }; type Usage = { readonly definition: FunctionDefinitionNode; readonly depth: number; diff --git a/ls/server/src/diagnostics/snapshot.ts b/ls/server/src/diagnostics/snapshot.ts index 3feaa967..04ddea4c 100644 --- a/ls/server/src/diagnostics/snapshot.ts +++ b/ls/server/src/diagnostics/snapshot.ts @@ -23,9 +23,22 @@ export type DiagnosticSnapshot = { }; export function createDiagnosticSnapshot(): DiagnosticSnapshot { - return { revision: 0, targets: new Map(), context: { environment: emptyShellEnvironment(), projectRoot: '', - classCommands: new Map(), classFiles: [], aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), - autoloads: new Set(), builtins: new Set() }, files: new Map() }; + return { + revision: 0, + targets: new Map(), + context: { + environment: emptyShellEnvironment(), + projectRoot: '', + classCommands: new Map(), + classFiles: [], + aliases: new Set(), + globalAliases: new Set(), + suffixAliases: new Set(), + autoloads: new Set(), + builtins: new Set(), + }, + files: new Map(), + }; } function sameSet(left: ReadonlySet, right: ReadonlySet): boolean { @@ -47,7 +60,13 @@ function resolutionContext(facts: readonly FileFacts[], environment: ShellEnviro sameSet(declarations.aliases, previous.aliases) && sameSet(declarations.globalAliases, previous.globalAliases) && sameSet(declarations.suffixAliases, previous.suffixAliases) && sameSet(declarations.autoloads, previous.autoloads) && sameSet(declarations.builtins, previous.builtins) && sameClassFiles(classFiles, previous.classFiles)) return previous; - return { ...declarations, environment, projectRoot, classCommands: generated, classFiles }; + return { + ...declarations, + environment, + projectRoot, + classCommands: generated, + classFiles, + }; } function suppressed(file: ZshFileHydration, diagnostics: readonly Diagnostics[]): readonly Diagnostics[] { @@ -85,7 +104,10 @@ export function refreshDiagnosticSnapshot({ snapshot, environment, previous = cr const local = input.project ? context : resolutionContext([...projectFacts, current], environment, context.projectRoot, context); const effective = input.project ? context : { - ...context, classCommands: local.classCommands, classFiles: local.classFiles, aliases: new Set([...context.aliases, ...local.aliases]), + ...context, + classCommands: local.classCommands, + classFiles: local.classFiles, + aliases: new Set([...context.aliases, ...local.aliases]), globalAliases: new Set([...context.globalAliases, ...local.globalAliases]), suffixAliases: new Set([...context.suffixAliases, ...local.suffixAliases]), autoloads: new Set([...context.autoloads, ...local.autoloads]), diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index f468aff4..f69f3385 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -19,6 +19,7 @@ let environment: ShellEnvironment = emptyShellEnvironment(); beforeAll(async () => { fs.writeFileSync(path.join(environmentRoot, '.zshrc'), ''); environment = await readShellEnvironment({ env: { ...process.env, ZDOTDIR: environmentRoot } }); + expect(environment.kind).toBe('available'); }); afterAll(() => fs.rmSync(environmentRoot, { recursive: true, force: true })); @@ -28,19 +29,40 @@ afterEach(() => { function fixture(content: string, definitions: string) { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'z-class-diag-')); roots.push(root); + const definitionUri = pathToFileURL(path.join(root, 'definition.zsh')).href; fs.writeFileSync(path.join(root, 'definition.zsh'), definitions); - const document = TextDocument.create(pathToFileURL(path.join(root, 'caller.zsh')).href, 'shellscript', 1, content); + + const document = TextDocument.create( + pathToFileURL(path.join(root, 'caller.zsh')).href, 'shellscript', 1, content, + ); const snapshot = refreshFunctionSnapshot({ projectRoot: root, documents: [document] }); const diagnostics = refreshDiagnosticSnapshot({ snapshot, environment }); - return { root, snapshot, diagnostics, document, definitionUri, - items: validateTextDocument({ diagnostics, textDocument: document }) }; + + return { + root, + snapshot, + diagnostics, + document, + definitionUri, + items: validateTextDocument({ diagnostics, textDocument: document }), + }; } -const semantic = (items: Readonly>) => - items.filter(item => ['missing-positional-argument', 'missing-named-argument', 'undefined-command'].includes(item.code ?? '')); -const classApi = ['z.cls.draw() { : }', 'z.cls.attr() { : }', '# $1: method name', '# $2? [code]: inline body', 'z.cls.fn() { : \"$@\" }', - 'z.cls.fn.done() { : }', 'z.cls.drew() { : }', 'z.cls.new() { : }'].join('\n') + '\n'; +const semantic = (items: Readonly>) => + items.filter(item => ['missing-positional-argument', 'missing-named-argument', 'undefined-command'] + .includes(item.code ?? '')); + +const classApi = [ + 'z.cls.draw() { : }', + 'z.cls.attr() { : }', + '# $1: method name', + '# $2? [code]: inline body', + 'z.cls.fn() { : "$@" }', + 'z.cls.fn.done() { : }', + 'z.cls.drew() { : }', + 'z.cls.new() { : }', +].join('\n') + '\n'; const counterClass = [ 'z.cls.draw Counter; {', ' z.cls.attr count 0', @@ -55,69 +77,85 @@ describe('class DSL command diagnostics', () => { test('inlineメソッド本体はmainのcode引数診断で元位置に報告する', () => { const source = counterClass.replace('z.cls.fn increment\n (( ++count ))\n z.cls.fn.done', "z.cls.fn increment 'missing_inline_method'"); - const f = fixture('', classApi + source); - const diagnostics = f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'undefined-command') ?? []; + const scenario = fixture('', classApi + source); + const diagnostics = scenario.diagnostics.files.get(scenario.definitionUri)?.items.filter(item => item.code === 'undefined-command') ?? []; + expect(diagnostics).toHaveLength(1); expect(diagnostics[0].message).toContain('missing_inline_method'); expect(diagnostics[0].range.start.line).toBe(10); }); test('別ファイルのクラスから生成されるメソッドと属性を認識し、タイプミスは診断する', () => { - const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.count.get\ncounter.count.set 3\ncounter.typo\n', + const scenario = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.count.get\ncounter.count.set 3\ncounter.typo\n', classApi + counterClass); - expect(semantic(f.items)).toMatchObject([{ code: 'undefined-command', + + expect(semantic(scenario.items)).toMatchObject([{ code: 'undefined-command', message: 'counter.typo is not defined in the project or shell environment.' }]); - expect(semantic(f.items)).toHaveLength(1); + + expect(semantic(scenario.items)).toHaveLength(1); }); test('メソッド内の未定義コマンドを元ファイルの位置で診断する', () => { const source = counterClass.replace('(( ++count ))', 'missing_inside_method'); - const f = fixture('', classApi + source); - expect(semantic(f.diagnostics.files.get(f.definitionUri)?.items ?? [])).toMatchObject([{ + const scenario = fixture('', classApi + source); + + expect(semantic(scenario.diagnostics.files.get(scenario.definitionUri)?.items ?? [])).toMatchObject([{ code: 'undefined-command', range: { start: { line: 11, character: 4 } }, }]); }); test('メソッドの編集で未編集の呼出元を再診断する', () => { - const f = fixture('z.cls.new Counter counter\ncounter.increment\n', classApi + counterClass); - expect(semantic(f.items)).toEqual([]); - const changed = TextDocument.create(f.definitionUri, 'shellscript', 1, + const scenario = fixture('z.cls.new Counter counter\ncounter.increment\n', classApi + counterClass); + + expect(semantic(scenario.items)).toEqual([]); + + const changed = TextDocument.create(scenario.definitionUri, 'shellscript', 1, classApi + counterClass.replace('z.cls.fn increment', 'z.cls.fn reset')); - const snapshot = refreshFunctionSnapshot({ projectRoot: f.root, documents: [f.document, changed], previous: f.snapshot }); - const next = refreshDiagnosticSnapshot({ snapshot, environment, previous: f.diagnostics }); - expect(semantic(validateTextDocument({ diagnostics: next, textDocument: f.document }))) + + const snapshot = refreshFunctionSnapshot({ + projectRoot: scenario.root, + documents: [scenario.document, changed], + previous: scenario.snapshot, + }); + const next = refreshDiagnosticSnapshot({ snapshot, environment, previous: scenario.diagnostics }); + + expect(semantic(validateTextDocument({ diagnostics: next, textDocument: scenario.document }))) .toMatchObject([{ code: 'undefined-command' }]); }); test('入れ子の関数や文字列内の終了名でメソッドを閉じない', () => { const source = counterClass.replace('(( ++count ))', 'helper() { z.cls.fn.done }\n print "z.cls.fn.done"\n z.cls.fn imaginary'); - const f = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.imaginary\n', classApi + source); - expect(semantic(f.items)).toHaveLength(1); - expect(semantic(f.items)[0]?.message).toContain('counter.imaginary'); + const scenario = fixture('z.cls.new Counter counter\ncounter.increment\ncounter.imaginary\n', classApi + source); + + expect(semantic(scenario.items)).toHaveLength(1); + expect(semantic(scenario.items)[0]?.message).toContain('counter.imaginary'); }); }); describe('scoped class references', () => { test('スコープによって異なるクラスを指す同名変数の呼出を認識する', () => { const arrayClass = ['z.cls.draw ArrayBox; {', 'z.cls.fn fill', ':', 'z.cls.fn.done', 'z.cls.drew', '}', ''].join('\n'); - const source = ['z.cls.new Counter counter', 'counter.increment', 'inner() {', 'local counter', + const source = ['z.cls.new Counter counter', 'counter.increment', 'inner() {', 'local counter=""', 'z.cls.new ArrayBox counter', 'counter.fill', '}', 'counter.count.get', ''].join('\n'); + expect(semantic(fixture(source, classApi + counterClass + arrayClass).items)).toEqual([]); }); test('外側の関数の引数使用へメソッド内の引数を混ぜない', () => { const source = '# $1: loader argument\nload() {\n' + counterClass.replace('(( ++count ))', 'print "$1"') + '}\n'; - const f = fixture('', classApi + source); - expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); + const scenario = fixture('', classApi + source); + + expect(scenario.diagnostics.files.get(scenario.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); }); test('メソッドの名前付き引数取得を外側の引数使用へ混ぜない', () => { const source = '# $option: loader option\nload() {\n' + counterClass.replace('(( ++count ))', 'z.arg.named option "$@"') + '}\n'; - const f = fixture('', classApi + 'z.arg.named() { : }\n' + source); - expect(f.diagnostics.files.get(f.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); + const scenario = fixture('', classApi + 'z.arg.named() { : }\n' + source); + + expect(scenario.diagnostics.files.get(scenario.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); }); }); @@ -127,6 +165,7 @@ describe('hydrated class command targets', () => { const bindings = createZshFileHydration({ sourceFile: '/caller.zsh', file: 'caller.zsh', content: 'z.cls.new Counter object\n' }); const targets = classCommands([definitions.classes, bindings.classes]); const method = targets.get('object.increment')?.[0]; + expect(method?.definition).toBe(definitions.classes.definitions[0]); expect(method?.member).toBe(definitions.classes.definitions[0].methods[0]); expect(method?.instance).toBe(bindings.classes.instances[0]); @@ -138,6 +177,7 @@ describe('hydrated class command targets', () => { for (const ending of ['', 'z.cls.abort\n']) { const file = createZshFileHydration({ sourceFile: 'x', file: 'x', content: 'z.cls.draw Open\nz.cls.attr count 0\n' + ending + 'z.cls.new Open object\n' }); + expect(classCommands([file.classes]).size).toBe(0); } }); @@ -145,18 +185,21 @@ describe('hydrated class command targets', () => { test('同じASTを再利用し、変更したclassの参照は古いcontextへ残さない', () => { const file = createZshFileHydration({ sourceFile: 'x', file: 'x', content: counterClass }); const next = createZshFileHydration({ sourceFile: 'x', file: 'x', content: counterClass.replace('increment', 'reset') }); + expect(sameClassFiles([file.classes], [file.classes])).toBe(true); expect(sameClassFiles([file.classes], [next.classes])).toBe(false); const empty = createZshFileHydration({ sourceFile: 'y', file: 'y', content: 'print one\n' }); + expect(sameClassFiles([empty.classes], [])).toBe(true); }); test('呼出解析がclassメンバーの解決先を名前の除外だけでなく返す', () => { - const f = fixture('z.cls.new Counter object\nobject.increment\n', classApi + counterClass); - const report = f.diagnostics.files.get(f.document.uri); + const scenario = fixture('z.cls.new Counter object\nobject.increment\n', classApi + counterClass); + const report = scenario.diagnostics.files.get(scenario.document.uri); if (!report) throw new Error('Expected caller diagnostics'); - const analysis = analyzeCalls(f.snapshot, report.file, report.facts.calls, f.diagnostics.context); + const analysis = analyzeCalls(scenario.snapshot, report.file, report.facts.calls, scenario.diagnostics.context); const targets = [...analysis.classTargets.values()].flat(); + expect(targets).toHaveLength(1); expect(targets[0].member).toMatchObject({ kind: 'classMethod', name: 'increment' }); expect(targets[0].member.declaration.commandName?.word.raw).toBe('z.cls.fn'); @@ -164,17 +207,19 @@ describe('hydrated class command targets', () => { test('code引数内のinstanceは外側のclassを使い、外側へ漏れない', () => { const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; - const f = fixture("run 'z.cls.new Counter inside; inside.increment'\ninside.increment\n", classApi + counterClass + api); - expect(semantic(f.items)).toHaveLength(1); - expect(semantic(f.items)[0].range.start.line).toBe(1); + const scenario = fixture("run 'z.cls.new Counter inside; inside.increment'\ninside.increment\n", classApi + counterClass + api); + + expect(semantic(scenario.items)).toHaveLength(1); + expect(semantic(scenario.items)[0].range.start.line).toBe(1); }); test('code引数内のclassはそのcode内で解決し、projectへ漏れない', () => { const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; const text = "run 'z.cls.draw Local; z.cls.fn value \"REPLY=1\"; z.cls.drew; z.cls.new Local local_object; local_object.value'\n" + 'z.cls.new Local outside\noutside.value\n'; - const f = fixture(text, classApi + api); - expect(semantic(f.items)).toHaveLength(1); - expect(semantic(f.items)[0].message).toContain('outside.value'); + const scenario = fixture(text, classApi + api); + + expect(semantic(scenario.items)).toHaveLength(1); + expect(semantic(scenario.items)[0].message).toContain('outside.value'); }); }); From 2153cb4de6964f42d2571e995bdad25b7df1de19 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 14:50:24 +0900 Subject: [PATCH 08/21] refactor: split class hydration transitions and indexes Interpret bindings, attributes, method endings and publication through separate readonly transitions. Build fresh role-specific indexes without mutating input ASTs or existing indexes. Retain native declaration references and cover duplicate members and independent index reconstruction. --- ls/server/src/zshHydrator/classes/collect.ts | 200 +++++++++++-------- ls/server/src/zshHydrator/classes/index.ts | 153 ++------------ ls/server/src/zshHydrator/classes/indexes.ts | 158 +++++++++++++++ ls/server/test/zshHydrator/classes.test.ts | 41 ++++ 4 files changed, 335 insertions(+), 217 deletions(-) create mode 100644 ls/server/src/zshHydrator/classes/indexes.ts diff --git a/ls/server/src/zshHydrator/classes/collect.ts b/ls/server/src/zshHydrator/classes/collect.ts index 378537c7..6c3d682a 100644 --- a/ls/server/src/zshHydrator/classes/collect.ts +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -30,6 +30,14 @@ type State = { readonly information: ReadonlyMap; }; +type ClassDirective = { + readonly command: SimpleCommandNode; + readonly name: string; + readonly args: readonly (string | null)[]; + readonly depth: number; + readonly scope: FunctionDefinitionNode | undefined; +}; + /** Keep runtime-reserved names outside statically declared class symbols. */ function identifier(value: string | null | undefined): value is string { if (!value || value.startsWith('z_cls_')) return false; @@ -113,113 +121,149 @@ function finish(state: State, scope: FunctionDefinitionNode | undefined, capture return { ...withCapture(state, scope, null), information }; } -/** Interpret only literal directive commands in the current native function scope. */ -function declaration(command: SimpleCommandNode, depth: number, - scope: FunctionDefinitionNode | undefined, state: State): State { +/** Read one literal directive from native syntax without executing its arguments. */ +function classDirective(command: SimpleCommandNode, depth: number, + scope: FunctionDefinitionNode | undefined): ClassDirective | null { const external = command.precommandModifiers.some( modifier => modifier.type === 'builtin' || modifier.type === 'command', ); - if (external) return state; + if (external) return null; const name = command.commandName && literalWord(command.commandName.word); - if (!name || !name.startsWith('z.cls.')) return state; + if (!name || !name.startsWith('z.cls.')) return null; - const directives = ['z.cls.draw', 'z.cls.attr', 'z.cls.fn', 'z.cls.fn.done', + const names = ['z.cls.draw', 'z.cls.attr', 'z.cls.fn', 'z.cls.fn.done', 'z.cls.drew', 'z.cls.abort', 'z.cls.new']; - if (!directives.includes(name)) return state; - - const args = command.arguments.map(word => literalWord(word)); - const capture = state.scopes.get(scope); + if (!names.includes(name)) return null; - if (name === 'z.cls.new' && args.length === 2 && identifier(args[0]) && identifier(args[1])) { - const information = new Map(state.information); - const location: ClassScopeLocation = capture?.kind === 'method' - ? { kind: 'classMethod', offset: capture.node.range.start.offset } - : scopeLocation(scope); - - information.set(command.range.start.offset, { - kind: 'classInstance', - name: args[1], - className: args[0], - scope: location, - }); + return { command, name, args: command.arguments.map(word => literalWord(word)), depth, scope }; +} - return { ...state, information }; - } +/** Record a binding in its native function or captured method scope. */ +function instanceDeclaration(directive: ClassDirective, capture: Capture | undefined, state: State): State { + const [className, name] = directive.args; + if (directive.args.length !== 2 || !identifier(className) || !identifier(name)) return state; - if (capture?.kind === 'method') { - if (depth !== capture.depth) return state; + const information = new Map(state.information); + const scope: ClassScopeLocation = capture?.kind === 'method' + ? { kind: 'classMethod', offset: capture.node.range.start.offset } + : scopeLocation(directive.scope); + + information.set(directive.command.range.start.offset, { + kind: 'classInstance', + name, + className, + scope, + }); - if (name === 'z.cls.fn.done' && args.length === 0) { - return withMember(state, scope, capture.definition, blockMethod(capture, command.range, true)); - } + return { ...state, information }; +} - if (name === 'z.cls.abort' || name === 'z.cls.drew') { - return finish(state, scope, capture, command.range, 'aborted'); - } +/** Close only markers at the method's original syntax depth. */ +function methodEnd(directive: ClassDirective, capture: Extract, state: State): State { + if (directive.depth !== capture.depth) return state; - return state; + if (directive.name === 'z.cls.fn.done' && directive.args.length === 0) { + return withMember(state, directive.scope, capture.definition, blockMethod(capture, directive.command.range, true)); } - if (name === 'z.cls.draw' && args.length === 1 && identifier(args[0]) && !capture) { - return withCapture(state, scope, { - kind: 'definition', - definition: { node: command, name: args[0], members: [] }, - }); + if (directive.name === 'z.cls.abort' || directive.name === 'z.cls.drew') { + return finish(state, directive.scope, capture, directive.command.range, 'aborted'); } - if (!capture) return state; + return state; +} - const definition = capture.definition; +/** Retain the first valid attribute declaration in a definition. */ +function attributeDeclaration(directive: ClassDirective, definition: Definition, state: State): State { + const name = directive.args[0]; + if (directive.args.length !== 2 || !identifier(name)) return state; - if (name === 'z.cls.attr' && args.length === 2 && identifier(args[0])) { - const duplicate = definition.members.some( - member => member.information.kind === 'classAttribute' && member.information.name === args[0], - ); - if (duplicate) return state; - - return withMember(state, scope, definition, { - node: command, - information: { - kind: 'classAttribute', - name: args[0], - classOffset: definition.node.range.start.offset, - }, - }); - } + const duplicate = definition.members.some( + member => member.information.kind === 'classAttribute' && member.information.name === name, + ); + if (duplicate) return state; - if (name === 'z.cls.fn' && args.length >= 1 && args.length <= 2 && identifier(args[0])) { - const duplicate = definition.members.some( - member => member.information.kind === 'classMethod' && member.information.name === args[0], - ); - if (duplicate) { - return args.length === 1 ? finish(state, scope, capture, command.range, 'aborted') : state; - } + return withMember(state, directive.scope, definition, { + node: directive.command, + information: { + kind: 'classAttribute', + name, + classOffset: definition.node.range.start.offset, + }, + }); +} - if (args.length === 1) { - return withCapture(state, scope, { kind: 'method', definition, node: command, name: args[0], depth }); - } +/** Start a block capture or retain an inline body's original word range. */ +function methodDeclaration(directive: ClassDirective, capture: Capture, state: State): State { + const [name] = directive.args; + if (directive.args.length < 1 || directive.args.length > 2 || !identifier(name)) return state; - return withMember(state, scope, definition, { - node: command, - information: { - kind: 'classMethod', - name: args[0], - classOffset: definition.node.range.start.offset, - body: { kind: 'inline', range: command.arguments[1].range }, - }, + const definition = capture.definition; + const duplicate = definition.members.some( + member => member.information.kind === 'classMethod' && member.information.name === name, + ); + if (duplicate) { + return directive.args.length === 1 ? finish(state, directive.scope, capture, directive.command.range, 'aborted') : state; + } + + if (directive.args.length === 1) { + return withCapture(state, directive.scope, { + kind: 'method', + definition, + node: directive.command, + name, + depth: directive.depth, }); } - if (name === 'z.cls.drew' && args.length === 0) { - return finish(state, scope, capture, command.range, 'published'); + return withMember(state, directive.scope, definition, { + node: directive.command, + information: { + kind: 'classMethod', + name, + classOffset: definition.node.range.start.offset, + body: { kind: 'inline', range: directive.command.arguments[1].range }, + }, + }); +} + +/** Apply the member or publication transition for an open definition. */ +function definitionDeclaration(directive: ClassDirective, capture: Capture, state: State): State { + switch (directive.name) { + case 'z.cls.attr': + return attributeDeclaration(directive, capture.definition, state); + case 'z.cls.fn': + return methodDeclaration(directive, capture, state); + case 'z.cls.drew': + return directive.args.length === 0 + ? finish(state, directive.scope, capture, directive.command.range, 'published') + : state; + case 'z.cls.abort': + return finish(state, directive.scope, capture, directive.command.range, 'aborted'); + default: + return state; } +} + +/** Route a directive through its current lexical capture state. */ +function declaration(command: SimpleCommandNode, depth: number, + scope: FunctionDefinitionNode | undefined, state: State): State { + const directive = classDirective(command, depth, scope); + if (!directive) return state; - if (name === 'z.cls.abort') { - return finish(state, scope, capture, command.range, 'aborted'); + const capture = state.scopes.get(scope); + if (directive.name === 'z.cls.new') return instanceDeclaration(directive, capture, state); + if (capture?.kind === 'method') return methodEnd(directive, capture, state); + + if (directive.name === 'z.cls.draw' && directive.args.length === 1 && identifier(directive.args[0]) && !capture) { + return withCapture(state, scope, { + kind: 'definition', + definition: { node: command, name: directive.args[0], members: [] }, + }); } - return state; + return capture ? definitionDeclaration(directive, capture, state) : state; } /** Interpret class directives from syntax commands, independently in each native function scope. */ diff --git a/ls/server/src/zshHydrator/classes/index.ts b/ls/server/src/zshHydrator/classes/index.ts index 896828c9..622b576f 100644 --- a/ls/server/src/zshHydrator/classes/index.ts +++ b/ls/server/src/zshHydrator/classes/index.ts @@ -1,26 +1,13 @@ import type { AstNode, FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../zshParser/ast'; import { findAll, mapAst } from '../../zshParser/ast'; import { collectClassInformation } from './collect'; -import type { - ClassAttribute, - ClassDefinition, - ClassFileHydration, - ClassInformation, - ClassInstance, - ClassMethod, - ClassMethodScope, - ClassScopeLocation, - HydratedClassCommand, -} from './types'; +import type { ClassFileHydration, ClassInformation, ClassMethod, HydratedClassCommand } from './types'; +import { + definitionsFromCommands, instancesFromCommands, membersFromCommands, methodScopesFromDefinitions, +} from './indexes'; export type * from './types'; -type DefinitionGroup = { - readonly definition: Omit; - readonly attributes: ClassAttribute[]; - readonly methods: ClassMethod[]; -}; - /** Narrow the attachment through its class role discriminator. */ export function isHydratedClassCommand(node: SimpleCommandNode): node is HydratedClassCommand { if (!('hydration' in node) || typeof node.hydration !== 'object' || node.hydration === null) { @@ -62,132 +49,20 @@ export function hydrateClasses(ast: FileNode): FileNode { }); } -/** Resolve an attachment's lexical owner against the final enriched syntax nodes. */ -function instanceScope(location: ClassScopeLocation, - functions: ReadonlyMap, - commands: ReadonlyMap): ClassInstance['scope'] | null { - if (location.kind === 'file') return { kind: 'file' }; - - if (location.kind === 'function') { - const declaration = functions.get(location.offset); - return declaration ? { kind: 'function', declaration } : null; - } - - const declaration = commands.get(location.offset); - return declaration ? { kind: 'classMethod', declaration } : null; -} - -/** Group member indexes under definition nodes from the returned AST. */ -function definitionGroups(ast: FileNode, commands: readonly HydratedClassCommand[], - functions: ReadonlyMap): Map { - const groups = new Map(); - - for (const command of commands) { - const information = command.hydration; - const nameNode = command.arguments[0]; - if (information.kind !== 'classDefinition' || !nameNode) continue; - - const scope = information.scope.kind === 'function' - ? functions.get(information.scope.offset) ?? null - : null; - - groups.set(command.range.start.offset, { - definition: { - kind: 'classDefinition', - name: information.name, - declaration: command, - nameNode, - file: ast, - scope, - state: information.state, - range: information.range, - }, - attributes: [], - methods: [], - }); - } - - return groups; -} - -/** Build indexes only after enrichment, so declarations, words and scopes refer to the returned AST. */ +/** Compose role-specific indexes after enrichment, retaining only final AST references. */ export function classesFromAst(ast: FileNode): ClassFileHydration { const commands = findAll(ast, 'simpleCommand').filter(isHydratedClassCommand); - if (commands.length === 0) { - return { definitions: [], instances: [], methodScopes: new Map() }; - } + if (commands.length === 0) return { definitions: [], instances: [], methodScopes: new Map() }; - const commandByOffset = new Map(commands.map(node => [node.range.start.offset, node])); const functions = new Map(findAll(ast, 'functionDefinition').map(node => [node.range.start.offset, node])); - const groups = definitionGroups(ast, commands, functions); - const instances: ClassInstance[] = []; - - for (const command of commands) { - const information = command.hydration; - const [nameNode, value] = command.arguments; - if (!nameNode) continue; - - if (information.kind === 'classAttribute' && value) { - groups.get(information.classOffset)?.attributes.push({ - kind: 'classAttribute', - name: information.name, - declaration: command, - nameNode, - defaultValue: value, - }); - } else if (information.kind === 'classMethod') { - if (information.body.kind === 'inline' && !value) continue; - - const body: ClassMethod['body'] = information.body.kind === 'inline' - ? { kind: 'inline', value } - : information.body; - - groups.get(information.classOffset)?.methods.push({ - kind: 'classMethod', - name: information.name, - declaration: command, - nameNode, - body, - }); - } else if (information.kind === 'classInstance' && value) { - const scope = instanceScope(information.scope, functions, commandByOffset); - if (!scope) continue; - - instances.push({ - kind: 'classInstance', - name: information.name, - className: information.className, - declaration: command, - classNameNode: nameNode, - nameNode: value, - scope, - file: ast, - }); - } - } - - const definitions = [...groups.values()].map(group => ({ - ...group.definition, - attributes: group.attributes, - methods: group.methods, - })); - const methodScopes = new Map(); - - for (const definition of definitions) { - for (const method of definition.methods) { - if (method.body.kind !== 'block') continue; - - const scopes = methodScopes.get(definition.scope) ?? []; - scopes.push({ method, range: method.body.range }); - methodScopes.set(definition.scope, scopes); - } - } - - for (const scopes of methodScopes.values()) { - scopes.sort((left, right) => left.range.start.offset - right.range.start.offset); - } - - return { definitions, instances, methodScopes }; + const members = membersFromCommands(commands); + const definitions = definitionsFromCommands(ast, commands, functions, members); + + return { + definitions, + instances: instancesFromCommands(ast, commands, functions), + methodScopes: methodScopesFromDefinitions(definitions), + }; } /** Find method parameter ownership without interpreting class commands again during diagnostics. */ diff --git a/ls/server/src/zshHydrator/classes/indexes.ts b/ls/server/src/zshHydrator/classes/indexes.ts new file mode 100644 index 00000000..b7b36e71 --- /dev/null +++ b/ls/server/src/zshHydrator/classes/indexes.ts @@ -0,0 +1,158 @@ +import type { FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../zshParser/ast'; +import type { + ClassAttribute, ClassDefinition, ClassFileHydration, ClassInstance, + ClassMethod, ClassMethodScope, ClassScopeLocation, HydratedClassCommand, +} from './types'; + +type MemberGroup = { + readonly attributes: readonly ClassAttribute[]; + readonly methods: readonly ClassMethod[]; +}; +type LocatedMember = { + readonly classOffset: number; + readonly member: ClassAttribute | ClassMethod; +}; + +/** Retain a member's final syntax nodes without copying its body or value. */ +function memberFromCommand(command: HydratedClassCommand): LocatedMember | null { + const information = command.hydration; + const [nameNode, value] = command.arguments; + if (!nameNode) return null; + + const base = { name: information.name, declaration: command, nameNode }; + if (information.kind === 'classAttribute' && value) { + return { + classOffset: information.classOffset, + member: { ...base, kind: 'classAttribute', defaultValue: value }, + }; + } + + if (information.kind !== 'classMethod' || information.body.kind === 'inline' && !value) return null; + + const body: ClassMethod['body'] = information.body.kind === 'inline' + ? { kind: 'inline', value } + : information.body; + + return { classOffset: information.classOffset, member: { ...base, kind: 'classMethod', body } }; +} + +/** Build fresh member groups; input commands and their existing indexes stay unchanged. */ +export function membersFromCommands(commands: readonly HydratedClassCommand[]): ReadonlyMap { + const groups = new Map(); + + for (const command of commands) { + const located = memberFromCommand(command); + if (!located) continue; + + const group = groups.get(located.classOffset) ?? { attributes: [], methods: [] }; + if (located.member.kind === 'classAttribute') { + group.attributes.push(located.member); + } else { + group.methods.push(located.member); + } + groups.set(located.classOffset, group); + } + + return groups; +} + +/** Join a definition to its final native function owner and freshly built member group. */ +function definitionFromCommand(ast: FileNode, command: HydratedClassCommand, + functions: ReadonlyMap, + members: ReadonlyMap): ClassDefinition | null { + const information = command.hydration; + const nameNode = command.arguments[0]; + if (information.kind !== 'classDefinition' || !nameNode) return null; + + const scope = information.scope.kind === 'function' ? functions.get(information.scope.offset) ?? null : null; + const group = members.get(command.range.start.offset); + + return { + kind: 'classDefinition', + name: information.name, + declaration: command, + nameNode, + file: ast, + scope, + state: information.state, + range: information.range, + attributes: group?.attributes ?? [], + methods: group?.methods ?? [], + }; +} + +/** Collect definitions in native syntax order, retaining incomplete and aborted entries. */ +export function definitionsFromCommands(ast: FileNode, commands: readonly HydratedClassCommand[], + functions: ReadonlyMap, + members: ReadonlyMap): readonly ClassDefinition[] { + return commands.map(command => definitionFromCommand(ast, command, functions, members)) + .filter((definition): definition is ClassDefinition => definition !== null); +} + +/** Resolve lexical ownership only against the final enriched syntax nodes. */ +function instanceScope(location: ClassScopeLocation, + functions: ReadonlyMap, + commands: ReadonlyMap): ClassInstance['scope'] | null { + if (location.kind === 'file') return { kind: 'file' }; + + if (location.kind === 'function') { + const declaration = functions.get(location.offset); + return declaration ? { kind: 'function', declaration } : null; + } + + const declaration = commands.get(location.offset); + return declaration ? { kind: 'classMethod', declaration } : null; +} + +/** Bind an instance's class/name words to its final lexical owner. */ +function instanceFromCommand(ast: FileNode, command: HydratedClassCommand, + functions: ReadonlyMap, + commands: ReadonlyMap): ClassInstance | null { + const information = command.hydration; + const [classNameNode, nameNode] = command.arguments; + if (information.kind !== 'classInstance' || !classNameNode || !nameNode) return null; + + const scope = instanceScope(information.scope, functions, commands); + if (!scope) return null; + + return { + kind: 'classInstance', + name: information.name, + className: information.className, + declaration: command, + classNameNode, + nameNode, + scope, + file: ast, + }; +} + +/** Collect independent bindings without changing commands or other file indexes. */ +export function instancesFromCommands(ast: FileNode, commands: readonly HydratedClassCommand[], + functions: ReadonlyMap): readonly ClassInstance[] { + const commandByOffset = new Map(commands.map(node => [node.range.start.offset, node])); + + return commands.map(command => instanceFromCommand(ast, command, functions, commandByOffset)) + .filter((instance): instance is ClassInstance => instance !== null); +} + +/** Index block ranges for argument ownership without interpreting directives again. */ +export function methodScopesFromDefinitions(definitions: readonly ClassDefinition[]): ClassFileHydration['methodScopes'] { + const methodScopes = new Map(); + + for (const definition of definitions) { + for (const method of definition.methods) { + if (method.body.kind !== 'block') continue; + + const scopes = methodScopes.get(definition.scope) ?? []; + scopes.push({ method, range: method.body.range }); + methodScopes.set(definition.scope, scopes); + } + } + + for (const scopes of methodScopes.values()) { + scopes.sort((left, right) => left.range.start.offset - right.range.start.offset); + } + + return methodScopes; +} diff --git a/ls/server/test/zshHydrator/classes.test.ts b/ls/server/test/zshHydrator/classes.test.ts index 7a3fc217..62a93793 100644 --- a/ls/server/test/zshHydrator/classes.test.ts +++ b/ls/server/test/zshHydrator/classes.test.ts @@ -29,6 +29,47 @@ function fixture(content = source) { } describe('class hydration', () => { + test('重複したblockメソッドはclassを破棄する', () => { + const file = fixture("z.cls.draw Duplicate\nz.cls.fn run ':'\nz.cls.fn run\nz.cls.fn.done\nz.cls.drew\n"); + + expect(file.classes.definitions[0].state).toBe('aborted'); + expect(file.classes.definitions[0].methods).toHaveLength(1); + }); + + test('重複したinlineメソッドは元の本体を保持する', () => { + const file = fixture("z.cls.draw Duplicate\nz.cls.fn run 'print first'\nz.cls.fn run 'print second'\nz.cls.drew\n"); + const definition = file.classes.definitions[0]; + const method = definition.methods[0]; + + expect(definition.state).toBe('published'); + expect(definition.methods).toHaveLength(1); + expect(method.body.kind).toBe('inline'); + if (method.body.kind !== 'inline') throw new Error('Expected an inline method'); + + expect(method.body.value.raw).toBe("'print first'"); + }); + + test('重複した属性は元のdefaultを保持する', () => { + const file = fixture('z.cls.draw Duplicate\nz.cls.attr value first\nz.cls.attr value second\nz.cls.drew\n'); + const definition = file.classes.definitions[0]; + + expect(definition.state).toBe('published'); + expect(definition.attributes).toHaveLength(1); + expect(definition.attributes[0].defaultValue.raw).toBe('first'); + }); + + test('索引の再構築が既存索引を変更せず返却ASTの参照を保持する', () => { + const file = fixture(); + const original = file.classes; + const rebuilt = classesFromAst(file.ast); + + expect(rebuilt).toEqual(original); + expect(rebuilt.definitions).not.toBe(original.definitions); + expect(rebuilt.definitions[0].attributes).not.toBe(original.definitions[0].attributes); + expect(rebuilt.definitions[0].attributes[0].defaultValue).toBe(original.definitions[0].attributes[0].defaultValue); + expect(rebuilt.instances[0].declaration).toBe(original.instances[0].declaration); + }); + test('runtimeと同じ予約prefixだけを除外する', () => { const file = fixture('z.cls.draw __z_cls_Box\nz.cls.attr __z_cls_value 0\nz.cls.drew\n'); From 931c934cf0f6159735addfd0cbbe6f9f3c614991 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Mon, 16 Nov 2026 16:06:26 +0900 Subject: [PATCH 09/21] test: cover class API visibility in the language server Use the actual runtime declarations to verify eight default public completions, opt-in access to twenty private helpers, and private-call diagnostics and definition resolution. Keep the existing provider implementation and public DSL unchanged. --- ls/server/test/connection/classApi.test.ts | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 ls/server/test/connection/classApi.test.ts diff --git a/ls/server/test/connection/classApi.test.ts b/ls/server/test/connection/classApi.test.ts new file mode 100644 index 00000000..ec0eb155 --- /dev/null +++ b/ls/server/test/connection/classApi.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, test } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { globSync } from 'glob'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { refreshFunctionSnapshot } from '../../src/refreshFunctions/main'; +import { zCompletion } from '../../src/connection/completion'; +import { zDefinition } from '../../src/connection/definition'; +import { emptyShellEnvironment } from '../../src/diagnostics/environment'; +import { refreshDiagnosticSnapshot } from '../../src/diagnostics/snapshot'; +import { validateTextDocument } from '../../src/diagnostics/main'; + +const roots: string[] = []; +const publicCommands = [ + 'z.cls.abort', 'z.cls.attr', 'z.cls.delete', 'z.cls.draw', + 'z.cls.drew', 'z.cls.fn', 'z.cls.fn.done', 'z.cls.new', +]; + +afterEach(() => { + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); + +/** Index the actual class declarations through the ordinary provider snapshot path. */ +function fixture(content = 'z.cls.¦\n') { + const repoRoot = path.resolve(__dirname, '../../../..'); + const source = globSync('lib/cls/**/*.zsh', { cwd: repoRoot, nodir: true }).sort() + .map(file => fs.readFileSync(path.join(repoRoot, file), 'utf8')).join('\n'); + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'z-class-api-')); + roots.push(root); + const definitionPath = path.join(root, 'class.zsh'); + fs.writeFileSync(definitionPath, source); + const offset = content.indexOf('¦'); + if (offset < 0) throw new Error('Expected a cursor marker'); + + const document = TextDocument.create( + pathToFileURL(path.join(root, 'caller.zsh')).href, 'shellscript', 1, content.replace('¦', ''), + ); + const snapshot = refreshFunctionSnapshot({ projectRoot: root, documents: [document] }); + const documents = { get: (uri: string) => uri === document.uri ? document : undefined }; + const params = { textDocument: { uri: document.uri }, position: document.positionAt(offset) }; + + return { definitionUri: pathToFileURL(definitionPath).href, document, snapshot, documents, params }; +} + +describe('class API visibility', () => { + test('通常の補完は実際の公開DSLの8関数だけを返す', () => { + const scenario = fixture(); + const items = zCompletion({ ...scenario, showPrivateFunctions: false }); + + expect(items?.map(item => item.label).toSorted()).toEqual(publicCommands); + }); + + test('private表示を有効にすると内部20関数も参照できる', () => { + const scenario = fixture(); + const names = zCompletion({ ...scenario, showPrivateFunctions: true })?.map(item => item.label) ?? []; + const internal = names.filter(name => name.split('.').some(segment => segment.startsWith('_'))); + + expect(names).toHaveLength(28); + expect(internal).toHaveLength(20); + expect(internal).toContain('z.cls.instance._call'); + expect(internal).toContain('z.cls.capture._start'); + expect(names).not.toContain('z.cls.instance.call'); + }); + + test('明示した内部呼出しは補完の表示設定に関係なく解決する', () => { + const scenario = fixture('z.cls.instance._¦call reference method member\n'); + const diagnostics = refreshDiagnosticSnapshot({ snapshot: scenario.snapshot, environment: emptyShellEnvironment() }); + + expect(validateTextDocument({ diagnostics, textDocument: scenario.document })).toEqual([]); + expect(zDefinition(scenario)?.uri).toBe(scenario.definitionUri); + }); +}); From 13347046c2c264968c391fe94dcc346bbbfefa4a Mon Sep 17 00:00:00 2001 From: milkeclair Date: Tue, 17 Nov 2026 08:23:28 +0900 Subject: [PATCH 10/21] docs: describe class hydration in Japanese Retain upstream Japanese architecture guides and restore the class-specific hydration, provenance and diagnostic sections in Japanese. Preserve source tokens, semantic behavior and the code parameter marker while translating added function comments. --- lib/cls/README.md | 4 +++ ls/server/src/diagnostics/README.md | 16 ++++++++++ ls/server/src/diagnostics/classes.ts | 4 +-- ls/server/src/zshHydrator/README.md | 33 +++++++++++++++++--- ls/server/src/zshHydrator/classes/collect.ts | 28 ++++++++--------- ls/server/src/zshHydrator/classes/index.ts | 10 +++--- ls/server/src/zshHydrator/classes/indexes.ts | 16 +++++----- ls/server/src/zshParser/ast/word/literal.ts | 2 +- ls/server/test/connection/classApi.test.ts | 2 +- 9 files changed, 80 insertions(+), 35 deletions(-) diff --git a/lib/cls/README.md b/lib/cls/README.md index 47aebf12..9667c687 100644 --- a/lib/cls/README.md +++ b/lib/cls/README.md @@ -129,6 +129,10 @@ DEBUGトラップと、実行タイミング・localtrapsの設定を復元し 実行時に保存する本体には元のコメントや整形を保持しません。 定義ファイルは通常のシェル構文を保つため、シンタックスハイライトと本体の診断を利用できます。 +z-lsは通常のASTへクラス・属性・メソッド・実体の意味情報を付加し、 +共有する索引から生成済みコマンドの定義元を解決します。 +メソッド本体の診断位置を保持し、引数で渡す本体は共通の[code]解析を利用します。 +動的な名前の解決には、既存の保守的な解析を適用します。 ## 実行時の費用 diff --git a/ls/server/src/diagnostics/README.md b/ls/server/src/diagnostics/README.md index b0d5e607..15995e2f 100644 --- a/ls/server/src/diagnostics/README.md +++ b/ls/server/src/diagnostics/README.md @@ -47,3 +47,19 @@ ASTの所有関係、引数の契約、制御コメント、snapshotの再利用 外側の展開で生成後のコードが不明になる場合は、そのコードの診断を保留します。外側のASTにあるコマンド置換は通常の診断を保ち、コードを実行して評価することはありません。ファイル全体の書式規則は文字列の内容には適用しません。 明示的な処理スタックを使い、入れ子は最大32段、ファイルごとの文字列表記は合計1,048,576 UTF-16単位までとします。上限を超えると、復号後のソースや位置対応表の確保を続けず`embedded-analysis-limit`を返します。変更のない報告は既存の診断snapshotを再利用し、コード型や許可値が変わると依存する呼び出しの契約を更新します。 + +## クラス定義 + +hydratorが通常の構文コマンドへクラスの意味を付加し、 +ファイルごとのクラス・メンバー・実体の索引を提供します。 +診断はこの索引を保持し、DSLを再認識する処理を持ちません。 +公開済みの定義からメソッド・属性get/setを解決し、呼出し解析はメンバーと実体の宣言元を返します。 + +コンテキストの再利用では、クラス宣言と束縛が現在のASTを参照していることを確認します。 +同じ名前のまま変更した場合も解決先を更新し、古いASTの参照を残しません。 +引用しないメソッド本体は元の位置を保持し、hydratorの範囲索引から引数の所有関係を判定します。 +引数で渡す本体は[code]として共通の埋め込み解析へ渡し、元の位置へ診断を対応付けます。 + +コード引数は外側のクラス定義を継承しますが、そのコードでの定義・実体はそのプログラム内に保ちます。 +同じ変数名で静的に観測したクラスは候補として集め、動的な参照展開は動的コマンドとして扱います。 +ソースを実行したり、条件分岐後の変数の型を再現したりする解析は行いません。 diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts index 39231a80..4792986b 100644 --- a/ls/server/src/diagnostics/classes.ts +++ b/ls/server/src/diagnostics/classes.ts @@ -14,7 +14,7 @@ export type ClassCommandTarget = { }; export type ClassCommandTargets = ReadonlyMap; -/** Resolve only published class symbols; targets retain declaration nodes and member provenance. */ +/** 公開済みクラスだけを解決し、宣言ノードとメンバーの定義元を参照先に保持する。 */ export function classCommands(files: readonly ClassFileHydration[]): ClassCommandTargets { const definitions = new Map(files.flatMap(file => file.definitions .filter(definition => definition.state === 'published') @@ -45,7 +45,7 @@ export function classCommands(files: readonly ClassFileHydration[]): ClassComman return commands; } -/** Preserve cached contexts only while all class declaration and binding references are current. */ +/** クラス宣言と実体の束縛が同じノードを参照する間だけ、解決コンテキストを再利用する。 */ export function sameClassFiles(left: readonly ClassFileHydration[], right: readonly ClassFileHydration[]): boolean { const declarations = (files: readonly ClassFileHydration[]) => files.flatMap(file => [ ...file.definitions.map(definition => definition.declaration), diff --git a/ls/server/src/zshHydrator/README.md b/ls/server/src/zshHydrator/README.md index 207c82a3..be9ebbfa 100644 --- a/ls/server/src/zshHydrator/README.md +++ b/ls/server/src/zshHydrator/README.md @@ -1,6 +1,6 @@ # Zsh hydrator -hydratorは、汎用Zsh AST上の関数ドキュメントと、登録済みの制御コメントの名前空間を解釈します。変更時は新しい値を作り、情報を付加したASTを返します。関数エントリと位置検索は、返されたAST内のノードを参照します。元のコメント、ソース範囲、トークンも引き続き参照できます。 +hydratorは、汎用Zsh AST上の関数ドキュメント、クラス宣言、登録済みの制御コメントの名前空間を解釈します。変更時は新しい値を作り、情報を付加したASTを返します。関数エントリと位置検索は、返されたAST内のノードを参照します。元のコメント、ソース範囲、トークンも引き続き参照できます。 ## ファイルの解析と情報の付加 @@ -17,7 +17,7 @@ const documentation = documentationOf(definition); const location = locate(result.query, 3); ``` -関数エントリは、表現されたすべての関数名の接頭辞を含み、ソース上の名前の記述を保ちます。シェル構文は汎用Lexer/Parserが扱い、このモジュールはドキュメントの規約を扱います。 +関数エントリは、表現されたすべての関数名の接頭辞を含み、ソース上の名前の記述を保ちます。シェル構文は汎用Lexer/Parserが扱い、このモジュールはドキュメントの規約とクラスDSLの意味を扱います。 ## 付加するドキュメント @@ -72,8 +72,33 @@ const directives = directivesOf(result.ast.comments[0]); `refreshZshHydrator({ previous, projectRoot, documents, options })`は開いている文書を優先し、バージョンと内容が両方一致すれば文書エントリを再利用します。変更ファイルを再構築し、削除ファイルを取り除き、解釈設定が変われば付加情報を作り直します。走査中に消えたものや通常ファイルでなくなったものはsnapshotへ含めず、それ以外のI/Oエラーは呼び出し元へ返します。 -バージョン番号がリセットされて再度開かれた文書も、内容が異なれば解析し直します。比較用のコピーを作らず、既存の変更不能な文字列をfingerprintとして保持します。各snapshotは`ast`、`tokens`、`query`、`functions`、Lexer・Parser・hydratorそれぞれの診断を持つファイルエントリを含みます。 +バージョン番号がリセットされて再度開かれた文書も、内容が異なれば解析し直します。比較用のコピーを作らず、既存の変更不能な文字列をfingerprintとして保持します。各snapshotは`ast`、`tokens`、`query`、`functions`、`classes`、Lexer・Parser・hydratorそれぞれの診断を持つファイルエントリを含みます。 `documentationOf`、`directivesOf`、`isHydratedDocBlock`、`isHydratedComment`で、型を保って付加情報へアクセスできます。汎用ASTの探索は明示的な構文辺と関連辺を辿り、付加データはこれらのhydrator APIから参照します。 -LSP接続はこのAPIを通して、ドキュメントと制御コメントの情報を付加したASTを共有します。 +LSP接続はこのAPIを通して、ドキュメント・制御コメント・クラスの情報を付加したASTを共有します。 + +## クラスの意味情報と索引 + +`hydrateAst`は、通常の`simpleCommand`に`classDefinition`、`classAttribute`、 +`classMethod`、`classInstance`の意味情報を付加します。 +コマンドの単語、関数の所有関係、構文の深さから判定し、ソース文字列を正規表現で走査しません。 +通常の構文種別、範囲、トークン、コメントの参照は保持します。 + +`classInformationOf(command)`で付加情報を取得できます。 +`createZshFileHydration`の`classes`は、クラス・メンバー・実体の宣言の索引です。 +名前、属性の初期値、所有スコープは返却AST内のノードを直接参照します。 +引数で指定した本体は元のWordを、本体を直接記述した場合はソース範囲と終了マーカーを保持します。 + +公開済み・破棄済み・未完了の定義を区別し、診断のコマンド解決には公開済みの定義だけを使います。 +動的または不正な名前を推測で確定しません。 +関数・メソッドの構文スコープと静的に現れた束縛を記録し、条件分岐後の実行状態や実行順は再現しません。 + +宣言の認識、実体の束縛、メンバー登録、終了マーカー、公開は別々のreadonlyな状態遷移です。 +役割別の索引構築は新しいコレクションを返し、既存のファイル索引へ追加しません。 +情報の付加後に索引を作り、子ノードが更新された場合も最終ASTを参照します。 +再hydrationは元のASTを変えずに意味情報を作り直し、古いクラスの付加情報を取り除きます。 + +`classMethodAt`は、宣言を再解釈せず、本体の範囲から引数の所有関係を調べます。 +診断はこの共通情報を使い、名前の除外だけでなく、メンバーの宣言を解決先として返します。 +この接続で変更するconsumerは診断です。補完・hover・定義ジャンプへのクラスメンバーの接続は別の変更範囲です。 diff --git a/ls/server/src/zshHydrator/classes/collect.ts b/ls/server/src/zshHydrator/classes/collect.ts index 6c3d682a..9ad5f95d 100644 --- a/ls/server/src/zshHydrator/classes/collect.ts +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -38,7 +38,7 @@ type ClassDirective = { readonly scope: FunctionDefinitionNode | undefined; }; -/** Keep runtime-reserved names outside statically declared class symbols. */ +/** 実行時に予約した名前を、静的なクラスの識別子から除外する。 */ function identifier(value: string | null | undefined): value is string { if (!value || value.startsWith('z_cls_')) return false; @@ -50,12 +50,12 @@ function identifier(value: string | null | undefined): value is string { }); } -/** Store ownership by position so syntax attachments never retain an earlier AST. */ +/** 以前のASTを付加情報に保持しないよう、所有関係を位置で記録する。 */ function scopeLocation(scope: FunctionDefinitionNode | undefined): ClassScopeLocation { return scope ? { kind: 'function', offset: scope.range.start.offset } : { kind: 'file' }; } -/** Replace one lexical capture without changing previous states. */ +/** 以前の状態を変更せず、1つの構文スコープの収集状態を置き換える。 */ function withCapture(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture | null): State { const scopes = new Map(state.scopes); @@ -68,7 +68,7 @@ function withCapture(state: State, scope: FunctionDefinitionNode | undefined, ca return { ...state, scopes }; } -/** Add a member through the same immutable transition for every declaration form. */ +/** 宣言形式にかかわらず、元の状態を変えない共通の遷移でメンバーを追加する。 */ function withMember(state: State, scope: FunctionDefinitionNode | undefined, definition: Definition, member: Member): State { return withCapture(state, scope, { @@ -80,7 +80,7 @@ function withMember(state: State, scope: FunctionDefinitionNode | undefined, }); } -/** Keep block source positions even when editing leaves its end marker absent. */ +/** 編集中に終了マーカーが欠けた場合も、本体のソース位置を保持する。 */ function blockMethod(capture: Extract, end: SourceRange, closed: boolean): Member { return { node: capture.node, @@ -97,7 +97,7 @@ function blockMethod(capture: Extract, end: SourceR }; } -/** Publish the complete definition and member meaning together. */ +/** クラス定義とメンバーの意味情報をまとめて確定する。 */ function finish(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture, end: SourceRange, status: ClassDefinition['state']): State { const definition = capture.definition; @@ -121,7 +121,7 @@ function finish(state: State, scope: FunctionDefinitionNode | undefined, capture return { ...withCapture(state, scope, null), information }; } -/** Read one literal directive from native syntax without executing its arguments. */ +/** 引数を実行せず、通常の構文から静的な宣言を1つ読む。 */ function classDirective(command: SimpleCommandNode, depth: number, scope: FunctionDefinitionNode | undefined): ClassDirective | null { const external = command.precommandModifiers.some( @@ -139,7 +139,7 @@ function classDirective(command: SimpleCommandNode, depth: number, return { command, name, args: command.arguments.map(word => literalWord(word)), depth, scope }; } -/** Record a binding in its native function or captured method scope. */ +/** 通常の関数または収集中のメソッドのスコープに、実体の束縛を記録する。 */ function instanceDeclaration(directive: ClassDirective, capture: Capture | undefined, state: State): State { const [className, name] = directive.args; if (directive.args.length !== 2 || !identifier(className) || !identifier(name)) return state; @@ -159,7 +159,7 @@ function instanceDeclaration(directive: ClassDirective, capture: Capture | undef return { ...state, information }; } -/** Close only markers at the method's original syntax depth. */ +/** メソッド開始時と同じ構文の深さにある終了マーカーだけを処理する。 */ function methodEnd(directive: ClassDirective, capture: Extract, state: State): State { if (directive.depth !== capture.depth) return state; @@ -174,7 +174,7 @@ function methodEnd(directive: ClassDirective, capture: Extract 2 || !identifier(name)) return state; @@ -228,7 +228,7 @@ function methodDeclaration(directive: ClassDirective, capture: Capture, state: S }); } -/** Apply the member or publication transition for an open definition. */ +/** 定義中のクラスに、メンバー登録または公開の状態遷移を適用する。 */ function definitionDeclaration(directive: ClassDirective, capture: Capture, state: State): State { switch (directive.name) { case 'z.cls.attr': @@ -246,7 +246,7 @@ function definitionDeclaration(directive: ClassDirective, capture: Capture, stat } } -/** Route a directive through its current lexical capture state. */ +/** 現在の構文スコープの収集状態に応じて宣言を処理する。 */ function declaration(command: SimpleCommandNode, depth: number, scope: FunctionDefinitionNode | undefined, state: State): State { const directive = classDirective(command, depth, scope); @@ -266,7 +266,7 @@ function declaration(command: SimpleCommandNode, depth: number, return capture ? definitionDeclaration(directive, capture, state) : state; } -/** Interpret class directives from syntax commands, independently in each native function scope. */ +/** 通常の関数スコープごとに独立して、構文上のコマンドからクラス宣言を解釈する。 */ export function collectClassInformation(ast: FileNode): ReadonlyMap { let state: State = { scopes: new Map(), information: new Map() }; const scopes: { readonly node: FunctionDefinitionNode; readonly depth: number }[] = []; diff --git a/ls/server/src/zshHydrator/classes/index.ts b/ls/server/src/zshHydrator/classes/index.ts index 622b576f..bad3e230 100644 --- a/ls/server/src/zshHydrator/classes/index.ts +++ b/ls/server/src/zshHydrator/classes/index.ts @@ -8,7 +8,7 @@ import { export type * from './types'; -/** Narrow the attachment through its class role discriminator. */ +/** クラスでの役割を示す種別から、付加情報の型を絞り込む。 */ export function isHydratedClassCommand(node: SimpleCommandNode): node is HydratedClassCommand { if (!('hydration' in node) || typeof node.hydration !== 'object' || node.hydration === null) { return false; @@ -21,12 +21,12 @@ export function isHydratedClassCommand(node: SimpleCommandNode): node is Hydrate information.kind === 'classMethod' || information.kind === 'classInstance'); } -/** Expose class meaning without changing the generic syntax node types. */ +/** 汎用の構文ノード型を変えず、クラスの意味情報を取得する。 */ export function classInformationOf(node: SimpleCommandNode): ClassInformation | null { return isHydratedClassCommand(node) ? node.hydration : null; } -/** Attach class meaning while retaining every native syntax kind, token and range. */ +/** 通常の構文種別・トークン・範囲を保ったまま、クラスの意味情報を付加する。 */ export function hydrateClasses(ast: FileNode): FileNode { const information = collectClassInformation(ast); if (information.size === 0) return ast; @@ -49,7 +49,7 @@ export function hydrateClasses(ast: FileNode): FileNode { }); } -/** Compose role-specific indexes after enrichment, retaining only final AST references. */ +/** 情報の付加後に役割別の索引を組み合わせ、最終ASTの参照だけを保持する。 */ export function classesFromAst(ast: FileNode): ClassFileHydration { const commands = findAll(ast, 'simpleCommand').filter(isHydratedClassCommand); if (commands.length === 0) return { definitions: [], instances: [], methodScopes: new Map() }; @@ -65,7 +65,7 @@ export function classesFromAst(ast: FileNode): ClassFileHydration { }; } -/** Find method parameter ownership without interpreting class commands again during diagnostics. */ +/** 診断時にクラスのコマンドを再解釈せず、メソッドの引数の所有関係を調べる。 */ export function classMethodAt(classes: ClassFileHydration, scope: FunctionDefinitionNode | null, offset: number): ClassMethod | null { const methods = classes.methodScopes.get(scope) ?? []; diff --git a/ls/server/src/zshHydrator/classes/indexes.ts b/ls/server/src/zshHydrator/classes/indexes.ts index b7b36e71..a0c12844 100644 --- a/ls/server/src/zshHydrator/classes/indexes.ts +++ b/ls/server/src/zshHydrator/classes/indexes.ts @@ -13,7 +13,7 @@ type LocatedMember = { readonly member: ClassAttribute | ClassMethod; }; -/** Retain a member's final syntax nodes without copying its body or value. */ +/** 本体や値をコピーせず、最終AST内のメンバーの構文ノードを保持する。 */ function memberFromCommand(command: HydratedClassCommand): LocatedMember | null { const information = command.hydration; const [nameNode, value] = command.arguments; @@ -36,7 +36,7 @@ function memberFromCommand(command: HydratedClassCommand): LocatedMember | null return { classOffset: information.classOffset, member: { ...base, kind: 'classMethod', body } }; } -/** Build fresh member groups; input commands and their existing indexes stay unchanged. */ +/** 入力コマンドと既存の索引を変えず、新しいメンバーの組を構築する。 */ export function membersFromCommands(commands: readonly HydratedClassCommand[]): ReadonlyMap { const groups = new Map(); @@ -56,7 +56,7 @@ export function membersFromCommands(commands: readonly HydratedClassCommand[]): return groups; } -/** Join a definition to its final native function owner and freshly built member group. */ +/** 定義を、最終ASTの所有関数と新しく構築したメンバーの組へ対応付ける。 */ function definitionFromCommand(ast: FileNode, command: HydratedClassCommand, functions: ReadonlyMap, members: ReadonlyMap): ClassDefinition | null { @@ -81,7 +81,7 @@ function definitionFromCommand(ast: FileNode, command: HydratedClassCommand, }; } -/** Collect definitions in native syntax order, retaining incomplete and aborted entries. */ +/** 未完了と破棄済みの状態も含め、構文の順序で定義を集める。 */ export function definitionsFromCommands(ast: FileNode, commands: readonly HydratedClassCommand[], functions: ReadonlyMap, members: ReadonlyMap): readonly ClassDefinition[] { @@ -89,7 +89,7 @@ export function definitionsFromCommands(ast: FileNode, commands: readonly Hydrat .filter((definition): definition is ClassDefinition => definition !== null); } -/** Resolve lexical ownership only against the final enriched syntax nodes. */ +/** 情報を付加した最終構文ノードだけを使い、構文スコープの所有関係を解決する。 */ function instanceScope(location: ClassScopeLocation, functions: ReadonlyMap, commands: ReadonlyMap): ClassInstance['scope'] | null { @@ -104,7 +104,7 @@ function instanceScope(location: ClassScopeLocation, return declaration ? { kind: 'classMethod', declaration } : null; } -/** Bind an instance's class/name words to its final lexical owner. */ +/** 実体のクラス名・変数名の単語を、最終ASTの所有スコープに対応付ける。 */ function instanceFromCommand(ast: FileNode, command: HydratedClassCommand, functions: ReadonlyMap, commands: ReadonlyMap): ClassInstance | null { @@ -127,7 +127,7 @@ function instanceFromCommand(ast: FileNode, command: HydratedClassCommand, }; } -/** Collect independent bindings without changing commands or other file indexes. */ +/** コマンドや他のファイルの索引を変えず、実体の束縛を集める。 */ export function instancesFromCommands(ast: FileNode, commands: readonly HydratedClassCommand[], functions: ReadonlyMap): readonly ClassInstance[] { const commandByOffset = new Map(commands.map(node => [node.range.start.offset, node])); @@ -136,7 +136,7 @@ export function instancesFromCommands(ast: FileNode, commands: readonly Hydrated .filter((instance): instance is ClassInstance => instance !== null); } -/** Index block ranges for argument ownership without interpreting directives again. */ +/** 宣言を再解釈せずに引数の所有関係を判定できるよう、本体の範囲を索引化する。 */ export function methodScopesFromDefinitions(definitions: readonly ClassDefinition[]): ClassFileHydration['methodScopes'] { const methodScopes = new Map(); diff --git a/ls/server/src/zshParser/ast/word/literal.ts b/ls/server/src/zshParser/ast/word/literal.ts index e36863c9..15144d85 100644 --- a/ls/server/src/zshParser/ast/word/literal.ts +++ b/ls/server/src/zshParser/ast/word/literal.ts @@ -1,7 +1,7 @@ import type { WordNode } from './word'; import { hereDocDelimiter } from '../../lexer/delimiter'; -/** Decode a literal word or prefix; expansions keep their dynamic meaning. */ +/** 静的な単語または接頭辞を復号し、展開を含む値は動的なまま扱う。 */ export function literalWord(word: WordNode, end = word.raw.length): string | null { if (word.parts.some(part => part.kind !== 'stringLiteral')) return null; return hereDocDelimiter(word.raw.slice(0, end)).delimiter; diff --git a/ls/server/test/connection/classApi.test.ts b/ls/server/test/connection/classApi.test.ts index ec0eb155..e23adb67 100644 --- a/ls/server/test/connection/classApi.test.ts +++ b/ls/server/test/connection/classApi.test.ts @@ -22,7 +22,7 @@ afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); -/** Index the actual class declarations through the ordinary provider snapshot path. */ +/** 実際のクラス宣言を通常のprovider snapshot経由で索引化する。 */ function fixture(content = 'z.cls.¦\n') { const repoRoot = path.resolve(__dirname, '../../../..'); const source = globSync('lib/cls/**/*.zsh', { cwd: repoRoot, nodir: true }).sort() From 93c37495e3c8cbdeb06a29243e757306360b842c Mon Sep 17 00:00:00 2001 From: milkeclair Date: Tue, 17 Nov 2026 11:47:01 +0900 Subject: [PATCH 11/21] refactor: align class hydration contracts and descriptions Constrain class definitions to file/function ownership and member captures to actual attributes or methods, using the established discriminated-union model. Use ordinary Japanese descriptions and document current consumers without development-history wording. Keep syntax nodes, ranges and runtime behavior unchanged. --- ls/server/src/zshHydrator/README.md | 4 +- ls/server/src/zshHydrator/classes/collect.ts | 10 ++--- ls/server/src/zshHydrator/classes/types.ts | 13 ++++-- ls/server/test/diagnostics/classes.test.ts | 14 +++---- ls/server/test/zshHydrator/classes.test.ts | 42 +++++++++---------- .../test/zshParser/ast/word/literal.test.ts | 6 +-- 6 files changed, 48 insertions(+), 41 deletions(-) diff --git a/ls/server/src/zshHydrator/README.md b/ls/server/src/zshHydrator/README.md index be9ebbfa..58e83101 100644 --- a/ls/server/src/zshHydrator/README.md +++ b/ls/server/src/zshHydrator/README.md @@ -97,8 +97,8 @@ LSP接続はこのAPIを通して、ドキュメント・制御コメント・ 宣言の認識、実体の束縛、メンバー登録、終了マーカー、公開は別々のreadonlyな状態遷移です。 役割別の索引構築は新しいコレクションを返し、既存のファイル索引へ追加しません。 情報の付加後に索引を作り、子ノードが更新された場合も最終ASTを参照します。 -再hydrationは元のASTを変えずに意味情報を作り直し、古いクラスの付加情報を取り除きます。 +hydrateAstを再適用すると、元のASTを変えずに意味情報を作り直し、古いクラスの付加情報を取り除きます。 `classMethodAt`は、宣言を再解釈せず、本体の範囲から引数の所有関係を調べます。 診断はこの共通情報を使い、名前の除外だけでなく、メンバーの宣言を解決先として返します。 -この接続で変更するconsumerは診断です。補完・hover・定義ジャンプへのクラスメンバーの接続は別の変更範囲です。 +クラスの索引は診断で使用します。補完・hover・定義ジャンプは従来の関数索引を使用します。 diff --git a/ls/server/src/zshHydrator/classes/collect.ts b/ls/server/src/zshHydrator/classes/collect.ts index 9ad5f95d..aec8c3b5 100644 --- a/ls/server/src/zshHydrator/classes/collect.ts +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -2,11 +2,11 @@ import type { FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../ import { walk } from '../../zshParser/ast'; import { literalWord } from '../../zshParser/ast/word/literal'; import type { SourceRange } from '../../zshParser/lexer'; -import type { ClassDefinition, ClassInformation, ClassScopeLocation } from './types'; +import type { ClassDefinition, ClassDefinitionScopeLocation, ClassInformation, ClassScopeLocation } from './types'; type Member = { readonly node: SimpleCommandNode; - readonly information: ClassInformation; + readonly information: Extract; }; type Definition = { readonly node: SimpleCommandNode; @@ -51,7 +51,7 @@ function identifier(value: string | null | undefined): value is string { } /** 以前のASTを付加情報に保持しないよう、所有関係を位置で記録する。 */ -function scopeLocation(scope: FunctionDefinitionNode | undefined): ClassScopeLocation { +function scopeLocation(scope: FunctionDefinitionNode | undefined): ClassDefinitionScopeLocation { return scope ? { kind: 'function', offset: scope.range.start.offset } : { kind: 'file' }; } @@ -195,7 +195,7 @@ function attributeDeclaration(directive: ClassDirective, definition: Definition, } /** 本体の収集を開始するか、引数で指定した本体の元の単語範囲を保持する。 */ -function methodDeclaration(directive: ClassDirective, capture: Capture, state: State): State { +function methodDeclaration(directive: ClassDirective, capture: Extract, state: State): State { const [name] = directive.args; if (directive.args.length < 1 || directive.args.length > 2 || !identifier(name)) return state; @@ -229,7 +229,7 @@ function methodDeclaration(directive: ClassDirective, capture: Capture, state: S } /** 定義中のクラスに、メンバー登録または公開の状態遷移を適用する。 */ -function definitionDeclaration(directive: ClassDirective, capture: Capture, state: State): State { +function definitionDeclaration(directive: ClassDirective, capture: Extract, state: State): State { switch (directive.name) { case 'z.cls.attr': return attributeDeclaration(directive, capture.definition, state); diff --git a/ls/server/src/zshHydrator/classes/types.ts b/ls/server/src/zshHydrator/classes/types.ts index d714f0bf..93a0769d 100644 --- a/ls/server/src/zshHydrator/classes/types.ts +++ b/ls/server/src/zshHydrator/classes/types.ts @@ -6,10 +6,17 @@ import type { } from '../../zshParser/ast'; import type { SourceRange } from '../../zshParser/lexer'; -export type ClassScopeLocation = +export type ClassDefinitionScopeLocation = | { readonly kind: 'file' } | { - readonly kind: 'function' | 'classMethod'; + readonly kind: 'function'; + readonly offset: number; + }; + +export type ClassScopeLocation = + | ClassDefinitionScopeLocation + | { + readonly kind: 'classMethod'; readonly offset: number; }; @@ -28,7 +35,7 @@ export type ClassInformation = | { readonly kind: 'classDefinition'; readonly name: string; - readonly scope: ClassScopeLocation; + readonly scope: ClassDefinitionScopeLocation; readonly state: 'published' | 'aborted' | 'incomplete'; readonly range: SourceRange; } diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index f69f3385..18404dfc 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -74,7 +74,7 @@ const counterClass = [ ].join('\n'); describe('class DSL command diagnostics', () => { - test('inlineメソッド本体はmainのcode引数診断で元位置に報告する', () => { + test('引数形式のメソッド本体は共通のコード引数解析で元位置に診断する', () => { const source = counterClass.replace('z.cls.fn increment\n (( ++count ))\n z.cls.fn.done', "z.cls.fn increment 'missing_inline_method'"); const scenario = fixture('', classApi + source); @@ -160,7 +160,7 @@ describe('scoped class references', () => { }); describe('hydrated class command targets', () => { - test('別ファイルのclassとinstanceを実際のメンバーノードへ結び付ける', () => { + test('別ファイルのクラスと実体を実際のメンバーノードへ結び付ける', () => { const definitions = createZshFileHydration({ sourceFile: '/defs.zsh', file: 'defs.zsh', content: counterClass }); const bindings = createZshFileHydration({ sourceFile: '/caller.zsh', file: 'caller.zsh', content: 'z.cls.new Counter object\n' }); const targets = classCommands([definitions.classes, bindings.classes]); @@ -173,7 +173,7 @@ describe('hydrated class command targets', () => { expect(targets.get('object.count.set')?.[0].member).toBe(definitions.classes.definitions[0].attributes[0]); }); - test('未公開とabortのclassからはターゲットを生成しない', () => { + test('未公開と破棄済みのクラスからは解決先を生成しない', () => { for (const ending of ['', 'z.cls.abort\n']) { const file = createZshFileHydration({ sourceFile: 'x', file: 'x', content: 'z.cls.draw Open\nz.cls.attr count 0\n' + ending + 'z.cls.new Open object\n' }); @@ -182,7 +182,7 @@ describe('hydrated class command targets', () => { } }); - test('同じASTを再利用し、変更したclassの参照は古いcontextへ残さない', () => { + test('同じASTを再利用し、変更したクラスの参照を古いコンテキストへ残さない', () => { const file = createZshFileHydration({ sourceFile: 'x', file: 'x', content: counterClass }); const next = createZshFileHydration({ sourceFile: 'x', file: 'x', content: counterClass.replace('increment', 'reset') }); @@ -193,7 +193,7 @@ describe('hydrated class command targets', () => { expect(sameClassFiles([empty.classes], [])).toBe(true); }); - test('呼出解析がclassメンバーの解決先を名前の除外だけでなく返す', () => { + test('呼出し解析がクラスのメンバー宣言を解決先として返す', () => { const scenario = fixture('z.cls.new Counter object\nobject.increment\n', classApi + counterClass); const report = scenario.diagnostics.files.get(scenario.document.uri); if (!report) throw new Error('Expected caller diagnostics'); @@ -205,7 +205,7 @@ describe('hydrated class command targets', () => { expect(targets[0].member.declaration.commandName?.word.raw).toBe('z.cls.fn'); }); - test('code引数内のinstanceは外側のclassを使い、外側へ漏れない', () => { + test('コード引数内の実体は外側のクラスを使い、外側へ漏れない', () => { const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; const scenario = fixture("run 'z.cls.new Counter inside; inside.increment'\ninside.increment\n", classApi + counterClass + api); @@ -213,7 +213,7 @@ describe('hydrated class command targets', () => { expect(semantic(scenario.items)[0].range.start.line).toBe(1); }); - test('code引数内のclassはそのcode内で解決し、projectへ漏れない', () => { + test('コード引数内のクラスはそのコード内で解決し、プロジェクトへ漏れない', () => { const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; const text = "run 'z.cls.draw Local; z.cls.fn value \"REPLY=1\"; z.cls.drew; z.cls.new Local local_object; local_object.value'\n" + 'z.cls.new Local outside\noutside.value\n'; diff --git a/ls/server/test/zshHydrator/classes.test.ts b/ls/server/test/zshHydrator/classes.test.ts index 62a93793..0e20f81b 100644 --- a/ls/server/test/zshHydrator/classes.test.ts +++ b/ls/server/test/zshHydrator/classes.test.ts @@ -29,14 +29,14 @@ function fixture(content = source) { } describe('class hydration', () => { - test('重複したblockメソッドはclassを破棄する', () => { + test('重複した本体収集形式のメソッドはクラスを破棄する', () => { const file = fixture("z.cls.draw Duplicate\nz.cls.fn run ':'\nz.cls.fn run\nz.cls.fn.done\nz.cls.drew\n"); expect(file.classes.definitions[0].state).toBe('aborted'); expect(file.classes.definitions[0].methods).toHaveLength(1); }); - test('重複したinlineメソッドは元の本体を保持する', () => { + test('重複した引数形式のメソッドは元の本体を保持する', () => { const file = fixture("z.cls.draw Duplicate\nz.cls.fn run 'print first'\nz.cls.fn run 'print second'\nz.cls.drew\n"); const definition = file.classes.definitions[0]; const method = definition.methods[0]; @@ -49,7 +49,7 @@ describe('class hydration', () => { expect(method.body.value.raw).toBe("'print first'"); }); - test('重複した属性は元のdefaultを保持する', () => { + test('重複した属性は元の初期値を保持する', () => { const file = fixture('z.cls.draw Duplicate\nz.cls.attr value first\nz.cls.attr value second\nz.cls.drew\n'); const definition = file.classes.definitions[0]; @@ -70,14 +70,14 @@ describe('class hydration', () => { expect(rebuilt.instances[0].declaration).toBe(original.instances[0].declaration); }); - test('runtimeと同じ予約prefixだけを除外する', () => { + test('実行時と同じ予約接頭辞だけを除外する', () => { const file = fixture('z.cls.draw __z_cls_Box\nz.cls.attr __z_cls_value 0\nz.cls.drew\n'); expect(file.classes.definitions[0].name).toBe('__z_cls_Box'); expect(file.classes.definitions[0].attributes[0].name).toBe('__z_cls_value'); }); - test('classのないASTは追加コピーせず返す', () => { + test('クラスのないASTは追加コピーせず返す', () => { const file = fixture('print hello\n'); expect(hydrateClasses(file.ast)).toBe(file.ast); @@ -103,19 +103,19 @@ describe('class hydration', () => { expect(file.classes.instances).toEqual([]); }); - test('同名instanceのnative function scopeを返却ASTに結び付ける', () => { + test('同名の実体の関数スコープを返却ASTに結び付ける', () => { const file = fixture('z.cls.new Counter object\nload() { local object=""; z.cls.new Other object; }\n'); expect(file.classes.instances[0].scope.kind).toBe('file'); - const local = file.classes.instances[1]; + const binding = file.classes.instances[1]; - expect(local.scope.kind).toBe('function'); - if (local.scope.kind !== 'function') throw new Error('Expected function ownership'); + expect(binding.scope.kind).toBe('function'); + if (binding.scope.kind !== 'function') throw new Error('Expected function ownership'); - expect(local.scope.declaration).toBe(file.functions[0].definition); + expect(binding.scope.declaration).toBe(file.functions[0].definition); }); - test('子のcommandを付加情報で更新してもdefaultのWord参照が古くならない', () => { + test('子のコマンドに情報を付加しても初期値のWord参照が古くならない', () => { const file = fixture('z.cls.draw Holder\nz.cls.attr value "$(z.cls.new Other inside)"\nz.cls.drew\n'); const attribute = file.classes.definitions[0].attributes[0]; @@ -127,7 +127,7 @@ describe('class hydration', () => { expect(file.classes.definitions[0].file).toBe(file.ast); }); - test('既存のclass付加情報が入力に残っていても現在の構文から更新する', () => { + test('既存のクラス付加情報が入力に残っていても現在の構文から更新する', () => { const information = classInformationOf(fixture().classes.definitions[0].declaration); if (!information) throw new Error('Expected class information'); const ordinary = fixture('print hello\n'); @@ -139,7 +139,7 @@ describe('class hydration', () => { expect(findAll(stale, 'simpleCommand').map(classInformationOf)).toEqual([information]); }); - test('class・属性・メソッド・instanceに意味情報を付与し、通常の構文ノードを保持する', () => { + test('クラス・属性・メソッド・実体に意味情報を付与し、通常の構文ノードを保持する', () => { const file = fixture(); const definition = file.classes.definitions[0]; @@ -168,7 +168,7 @@ describe('class hydration', () => { expect(classesFromAst(file.ast)).toEqual(file.classes); }); - test('blockとinlineの本体を元の範囲またはWordとして保持する', () => { + test('本体を元の範囲または引数のWordとして保持する', () => { const file = fixture(); const [block, inline] = file.classes.definitions[0].methods; @@ -185,7 +185,7 @@ describe('class hydration', () => { expect(classMethodAt(file.classes, null, source.indexOf('z.cls.fn.done'))).toBeNull(); }); - test('入力ASTを変更せず再hydrationしても意味情報を重複させない', () => { + test('入力ASTへ情報を付加し直しても意味情報を重複させない', () => { const parsed = Parser.parse(Lexer.tokenize(source, { sourceFile: 'x' }).tokens, { sourceFile: 'x', path: 'x' }); const ast = hydrateAst(parsed.ast, source); @@ -194,7 +194,7 @@ describe('class hydration', () => { expect(classesFromAst(ast).definitions).toHaveLength(1); }); - test('未完了とabortを公開済みclassと区別する', () => { + test('未完了と破棄済みのクラスを公開済みのクラスと区別する', () => { const incomplete = fixture('z.cls.draw Open\nz.cls.fn run\nprint "$1"\n'); expect(incomplete.classes.definitions[0]).toMatchObject({ name: 'Open', state: 'incomplete' }); @@ -204,14 +204,14 @@ describe('class hydration', () => { expect(aborted.classes.definitions[0]).toMatchObject({ name: 'Discarded', state: 'aborted' }); }); - test('文字列・コメント・非function呼出をclassと誤認しない', () => { + test('文字列・コメント・関数以外の呼出しをクラスと誤認しない', () => { const file = fixture('# z.cls.draw Comment\nprint "z.cls.draw String"\ncommand z.cls.draw External\nbuiltin z.cls.new Counter object\n'); expect(file.classes.definitions).toEqual([]); expect(file.classes.instances).toEqual([]); }); - test('native関数ごとのclassを独立して解釈し、本体内の引数スコープを保持する', () => { + test('通常の関数ごとのクラスを独立して解釈し、本体内の引数スコープを保持する', () => { const text = 'load() {\n' + source.slice(0, source.indexOf('z.cls.new')) + '}\n'; const file = fixture(text); const owner = file.functions.find(fn => fn.name === 'load')?.definition; @@ -221,13 +221,13 @@ describe('class hydration', () => { expect(classMethodAt(file.classes, null, text.indexOf('print "$1"'))).toBeNull(); }); - test('入れ子のnative関数にある終端名で外側のメソッドを閉じない', () => { + test('入れ子の関数にある終端名で外側のメソッドを閉じない', () => { const file = fixture(source.replace('(( ++count ))', 'helper() { z.cls.fn.done }\n print "z.cls.fn.done"')); expect(file.classes.definitions[0].methods.map(method => method.name)).toEqual(['increment', 'value']); }); - test('メソッド内のinstance宣言をclass method scopeに結び付ける', () => { + test('メソッド内の実体宣言をクラスメソッドのスコープに結び付ける', () => { const file = fixture(source.replace('(( ++count ))', 'z.cls.new Other nested')); const binding = file.classes.instances.find(instance => instance.name === 'nested'); @@ -237,7 +237,7 @@ describe('class hydration', () => { expect(binding.scope.declaration).toBe(file.classes.definitions[0].methods[0].declaration); }); - test('native関数内のclassと外側のclassを同じpending状態にしない', () => { + test('関数内のクラスと外側のクラスを同じ定義中の状態にしない', () => { const text = 'z.cls.draw Outer\nhelper() { z.cls.draw Inner; z.cls.drew }\nz.cls.drew\n'; const file = fixture(text); diff --git a/ls/server/test/zshParser/ast/word/literal.test.ts b/ls/server/test/zshParser/ast/word/literal.test.ts index c52139db..ea23c386 100644 --- a/ls/server/test/zshParser/ast/word/literal.test.ts +++ b/ls/server/test/zshParser/ast/word/literal.test.ts @@ -25,16 +25,16 @@ describe('literalWord', () => { ['print one\\ two', 'one two'], ["print $'one\\ntwo'", 'one\ntwo'], ["print ''", ''], - ])('literalの引用をASTから復元する: %s', (source, value) => { + ])('静的な値の引用をASTから復元する: %s', (source, value) => { expect(literalWord(word(source))).toBe(value); }); test.each(['print "$value"', 'print "$(print one)"', 'print $(( 1 + 2 ))'])( - '展開を含むWordをliteralと扱わない: %s', source => { + '展開を含むWordを静的な値と扱わない: %s', source => { expect(literalWord(word(source))).toBeNull(); }); - test('指定された終端まで復元し、既存importの互換性を保持する', () => { + test('指定された終端まで復元し、既存のimportとの互換性を保持する', () => { const argument = word("print 'option'=value"); expect(literalWord(argument, argument.raw.indexOf('='))).toBe('option'); From 564d73b153882065d6cfd8c575ec0fc7f2214750 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Tue, 17 Nov 2026 17:32:08 +0900 Subject: [PATCH 12/21] refactor: clarify class hydration state transitions --- ls/server/src/zshHydrator/classes/collect.ts | 72 ++++++++++---------- ls/server/src/zshHydrator/classes/indexes.ts | 37 ++++++---- 2 files changed, 61 insertions(+), 48 deletions(-) diff --git a/ls/server/src/zshHydrator/classes/collect.ts b/ls/server/src/zshHydrator/classes/collect.ts index aec8c3b5..b5ec43e9 100644 --- a/ls/server/src/zshHydrator/classes/collect.ts +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -26,7 +26,7 @@ type Capture = readonly depth: number; }; type State = { - readonly scopes: ReadonlyMap; + readonly captures: ReadonlyMap; readonly information: ReadonlyMap; }; @@ -57,15 +57,15 @@ function scopeLocation(scope: FunctionDefinitionNode | undefined): ClassDefiniti /** 以前の状態を変更せず、1つの構文スコープの収集状態を置き換える。 */ function withCapture(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture | null): State { - const scopes = new Map(state.scopes); + const captures = new Map(state.captures); if (capture) { - scopes.set(scope, capture); + captures.set(scope, capture); } else { - scopes.delete(scope); + captures.delete(scope); } - return { ...state, scopes }; + return { ...state, captures }; } /** 宣言形式にかかわらず、元の状態を変えない共通の遷移でメンバーを追加する。 */ @@ -81,7 +81,7 @@ function withMember(state: State, scope: FunctionDefinitionNode | undefined, } /** 編集中に終了マーカーが欠けた場合も、本体のソース位置を保持する。 */ -function blockMethod(capture: Extract, end: SourceRange, closed: boolean): Member { +function blockMethodFromCapture(capture: Extract, end: SourceRange, closed: boolean): Member { return { node: capture.node, information: { @@ -98,11 +98,11 @@ function blockMethod(capture: Extract, end: SourceR } /** クラス定義とメンバーの意味情報をまとめて確定する。 */ -function finish(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture, +function finishDefinition(state: State, scope: FunctionDefinitionNode | undefined, capture: Capture, end: SourceRange, status: ClassDefinition['state']): State { const definition = capture.definition; const members = capture.kind === 'method' - ? [...definition.members, blockMethod(capture, end, false)] + ? [...definition.members, blockMethodFromCapture(capture, end, false)] : definition.members; const information = new Map(state.information); @@ -122,7 +122,7 @@ function finish(state: State, scope: FunctionDefinitionNode | undefined, capture } /** 引数を実行せず、通常の構文から静的な宣言を1つ読む。 */ -function classDirective(command: SimpleCommandNode, depth: number, +function readClassDirective(command: SimpleCommandNode, depth: number, scope: FunctionDefinitionNode | undefined): ClassDirective | null { const external = command.precommandModifiers.some( modifier => modifier.type === 'builtin' || modifier.type === 'command', @@ -140,7 +140,7 @@ function classDirective(command: SimpleCommandNode, depth: number, } /** 通常の関数または収集中のメソッドのスコープに、実体の束縛を記録する。 */ -function instanceDeclaration(directive: ClassDirective, capture: Capture | undefined, state: State): State { +function declareInstance(directive: ClassDirective, capture: Capture | undefined, state: State): State { const [className, name] = directive.args; if (directive.args.length !== 2 || !identifier(className) || !identifier(name)) return state; @@ -160,22 +160,22 @@ function instanceDeclaration(directive: ClassDirective, capture: Capture | undef } /** メソッド開始時と同じ構文の深さにある終了マーカーだけを処理する。 */ -function methodEnd(directive: ClassDirective, capture: Extract, state: State): State { +function applyMethodDirective(directive: ClassDirective, capture: Extract, state: State): State { if (directive.depth !== capture.depth) return state; if (directive.name === 'z.cls.fn.done' && directive.args.length === 0) { - return withMember(state, directive.scope, capture.definition, blockMethod(capture, directive.command.range, true)); + return withMember(state, directive.scope, capture.definition, blockMethodFromCapture(capture, directive.command.range, true)); } if (directive.name === 'z.cls.abort' || directive.name === 'z.cls.drew') { - return finish(state, directive.scope, capture, directive.command.range, 'aborted'); + return finishDefinition(state, directive.scope, capture, directive.command.range, 'aborted'); } return state; } /** クラス内で最初に現れた有効な属性宣言を保持する。 */ -function attributeDeclaration(directive: ClassDirective, definition: Definition, state: State): State { +function declareAttribute(directive: ClassDirective, definition: Definition, state: State): State { const name = directive.args[0]; if (directive.args.length !== 2 || !identifier(name)) return state; @@ -195,7 +195,7 @@ function attributeDeclaration(directive: ClassDirective, definition: Definition, } /** 本体の収集を開始するか、引数で指定した本体の元の単語範囲を保持する。 */ -function methodDeclaration(directive: ClassDirective, capture: Extract, state: State): State { +function declareMethod(directive: ClassDirective, capture: Extract, state: State): State { const [name] = directive.args; if (directive.args.length < 1 || directive.args.length > 2 || !identifier(name)) return state; @@ -204,7 +204,9 @@ function methodDeclaration(directive: ClassDirective, capture: Extract member.information.kind === 'classMethod' && member.information.name === name, ); if (duplicate) { - return directive.args.length === 1 ? finish(state, directive.scope, capture, directive.command.range, 'aborted') : state; + return directive.args.length === 1 + ? finishDefinition(state, directive.scope, capture, directive.command.range, 'aborted') + : state; } if (directive.args.length === 1) { @@ -229,32 +231,32 @@ function methodDeclaration(directive: ClassDirective, capture: Extract, state: State): State { +function applyDefinitionDirective(directive: ClassDirective, capture: Extract, state: State): State { switch (directive.name) { case 'z.cls.attr': - return attributeDeclaration(directive, capture.definition, state); + return declareAttribute(directive, capture.definition, state); case 'z.cls.fn': - return methodDeclaration(directive, capture, state); + return declareMethod(directive, capture, state); case 'z.cls.drew': return directive.args.length === 0 - ? finish(state, directive.scope, capture, directive.command.range, 'published') + ? finishDefinition(state, directive.scope, capture, directive.command.range, 'published') : state; case 'z.cls.abort': - return finish(state, directive.scope, capture, directive.command.range, 'aborted'); + return finishDefinition(state, directive.scope, capture, directive.command.range, 'aborted'); default: return state; } } /** 現在の構文スコープの収集状態に応じて宣言を処理する。 */ -function declaration(command: SimpleCommandNode, depth: number, +function collectCommand(command: SimpleCommandNode, depth: number, scope: FunctionDefinitionNode | undefined, state: State): State { - const directive = classDirective(command, depth, scope); + const directive = readClassDirective(command, depth, scope); if (!directive) return state; - const capture = state.scopes.get(scope); - if (directive.name === 'z.cls.new') return instanceDeclaration(directive, capture, state); - if (capture?.kind === 'method') return methodEnd(directive, capture, state); + const capture = state.captures.get(scope); + if (directive.name === 'z.cls.new') return declareInstance(directive, capture, state); + if (capture?.kind === 'method') return applyMethodDirective(directive, capture, state); if (directive.name === 'z.cls.draw' && directive.args.length === 1 && identifier(directive.args[0]) && !capture) { return withCapture(state, scope, { @@ -263,21 +265,21 @@ function declaration(command: SimpleCommandNode, depth: number, }); } - return capture ? definitionDeclaration(directive, capture, state) : state; + return capture ? applyDefinitionDirective(directive, capture, state) : state; } /** 通常の関数スコープごとに独立して、構文上のコマンドからクラス宣言を解釈する。 */ export function collectClassInformation(ast: FileNode): ReadonlyMap { - let state: State = { scopes: new Map(), information: new Map() }; - const scopes: { readonly node: FunctionDefinitionNode; readonly depth: number }[] = []; + let state: State = { captures: new Map(), information: new Map() }; + const functionScopes: { readonly node: FunctionDefinitionNode; readonly depth: number }[] = []; walk(ast, (node, depth) => { - while (scopes.length && scopes[scopes.length - 1].depth >= depth) { - scopes.pop(); + while (functionScopes.length && functionScopes[functionScopes.length - 1].depth >= depth) { + functionScopes.pop(); } if (node.kind === 'functionDefinition') { - scopes.push({ node, depth }); + functionScopes.push({ node, depth }); } if (node.kind !== 'simpleCommand') return; @@ -288,12 +290,12 @@ export function collectClassInformation(ast: FileNode): ReadonlyMap Date: Tue, 17 Nov 2026 17:32:08 +0900 Subject: [PATCH 13/21] refactor: reuse the combined class diagnostic context The context for an external document already includes project declarations and the document itself. Use that result directly and build generated class commands only after the context reuse check. Cover both project and local class resolution through an external document, including isolation from project callers. --- ls/server/src/diagnostics/snapshot.ts | 15 ++------------- ls/server/test/diagnostics/classes.test.ts | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/ls/server/src/diagnostics/snapshot.ts b/ls/server/src/diagnostics/snapshot.ts index 04ddea4c..dc9e560f 100644 --- a/ls/server/src/diagnostics/snapshot.ts +++ b/ls/server/src/diagnostics/snapshot.ts @@ -48,7 +48,6 @@ function sameSet(left: ReadonlySet, right: ReadonlySet): boolean function resolutionContext(facts: readonly FileFacts[], environment: ShellEnvironment, projectRoot: string, previous: ResolutionContext): ResolutionContext { const classFiles = facts.map(file => file.classes); - const generated = classCommands(classFiles); const declarations: Declarations = { aliases: new Set(facts.flatMap(file => [...file.declarations.aliases])), globalAliases: new Set(facts.flatMap(file => [...file.declarations.globalAliases])), @@ -64,7 +63,7 @@ function resolutionContext(facts: readonly FileFacts[], environment: ShellEnviro ...declarations, environment, projectRoot, - classCommands: generated, + classCommands: classCommands(classFiles), classFiles, }; } @@ -101,18 +100,8 @@ export function refreshDiagnosticSnapshot({ snapshot, environment, previous = cr reusableContracts && previous.context === context) { files.set(uri, cached); } else { - const local = input.project ? context : resolutionContext([...projectFacts, current], environment, + const effective = input.project ? context : resolutionContext([...projectFacts, current], environment, context.projectRoot, context); - const effective = input.project ? context : { - ...context, - classCommands: local.classCommands, - classFiles: local.classFiles, - aliases: new Set([...context.aliases, ...local.aliases]), - globalAliases: new Set([...context.globalAliases, ...local.globalAliases]), - suffixAliases: new Set([...context.suffixAliases, ...local.suffixAliases]), - autoloads: new Set([...context.autoloads, ...local.autoloads]), - builtins: new Set([...context.builtins, ...local.builtins]), - }; files.set(uri, { ...input, facts: current, resultId: String(revision), items: suppressed(input.file, [...current.base, ...embeddedCallDiagnostics(snapshot, input.file, current.calls, effective)]) .toSorted((left, right) => left.range.start.line - right.range.start.line || diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index 18404dfc..b3b2ea25 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -142,6 +142,27 @@ describe('scoped class references', () => { expect(semantic(fixture(source, classApi + counterClass + arrayClass).items)).toEqual([]); }); + test('プロジェクト外の文書はプロジェクトと文書内のクラスを使い、文書内の定義は外へ漏れない', () => { + const scenario = fixture('z.cls.new Local leaked\nleaked.value\n', classApi + counterClass); + const outside = TextDocument.create( + pathToFileURL(path.join(path.dirname(scenario.root), 'outside.zsh')).href, 'shellscript', 1, + 'z.cls.draw Local\nz.cls.fn value "REPLY=1"\nz.cls.drew\n' + + 'z.cls.new Counter counter\ncounter.increment\nz.cls.new Local local_object\nlocal_object.value\n', + ); + const snapshot = refreshFunctionSnapshot({ + projectRoot: scenario.root, + documents: [scenario.document, outside], + previous: scenario.snapshot, + }); + + const diagnostics = refreshDiagnosticSnapshot({ snapshot, environment, previous: scenario.diagnostics }); + + expect(diagnostics.files.get(outside.uri)?.project).toBe(false); + expect(semantic(validateTextDocument({ diagnostics, textDocument: outside }))).toEqual([]); + expect(semantic(validateTextDocument({ diagnostics, textDocument: scenario.document }))) + .toMatchObject([{ code: 'undefined-command', message: 'leaked.value is not defined in the project or shell environment.' }]); + }); + test('外側の関数の引数使用へメソッド内の引数を混ぜない', () => { const source = '# $1: loader argument\nload() {\n' + counterClass.replace('(( ++count ))', 'print "$1"') + '}\n'; From 3ea96d7296965daa89c7def2fab10a9a97621f5e Mon Sep 17 00:00:00 2001 From: milkeclair Date: Tue, 17 Nov 2026 19:33:43 +0900 Subject: [PATCH 14/21] test: indent class fixtures and declare LS cases explicitly --- ls/server/test/diagnostics/classes.test.ts | 81 +++++++++++-- ls/server/test/zshHydrator/classes.test.ts | 111 ++++++++++++++++-- .../test/zshParser/ast/word/literal.test.ts | 55 ++++++--- 3 files changed, 206 insertions(+), 41 deletions(-) diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index b3b2ea25..57a5dba6 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -135,9 +135,26 @@ describe('class DSL command diagnostics', () => { describe('scoped class references', () => { test('スコープによって異なるクラスを指す同名変数の呼出を認識する', () => { - const arrayClass = ['z.cls.draw ArrayBox; {', 'z.cls.fn fill', ':', 'z.cls.fn.done', 'z.cls.drew', '}', ''].join('\n'); - const source = ['z.cls.new Counter counter', 'counter.increment', 'inner() {', 'local counter=""', - 'z.cls.new ArrayBox counter', 'counter.fill', '}', 'counter.count.get', ''].join('\n'); + const arrayClass = [ + 'z.cls.draw ArrayBox; {', + ' z.cls.fn fill', + ' :', + ' z.cls.fn.done', + ' z.cls.drew', + '}', + '', + ].join('\n'); + const source = [ + 'z.cls.new Counter counter', + 'counter.increment', + 'inner() {', + ' local counter=""', + ' z.cls.new ArrayBox counter', + ' counter.fill', + '}', + 'counter.count.get', + '', + ].join('\n'); expect(semantic(fixture(source, classApi + counterClass + arrayClass).items)).toEqual([]); }); @@ -146,8 +163,16 @@ describe('scoped class references', () => { const scenario = fixture('z.cls.new Local leaked\nleaked.value\n', classApi + counterClass); const outside = TextDocument.create( pathToFileURL(path.join(path.dirname(scenario.root), 'outside.zsh')).href, 'shellscript', 1, - 'z.cls.draw Local\nz.cls.fn value "REPLY=1"\nz.cls.drew\n' + - 'z.cls.new Counter counter\ncounter.increment\nz.cls.new Local local_object\nlocal_object.value\n', + [ + 'z.cls.draw Local', + ' z.cls.fn value "REPLY=1"', + ' z.cls.drew', + 'z.cls.new Counter counter', + 'counter.increment', + 'z.cls.new Local local_object', + 'local_object.value', + '', + ].join('\n'), ); const snapshot = refreshFunctionSnapshot({ projectRoot: scenario.root, @@ -164,16 +189,38 @@ describe('scoped class references', () => { }); test('外側の関数の引数使用へメソッド内の引数を混ぜない', () => { - const source = '# $1: loader argument\nload() {\n' + - counterClass.replace('(( ++count ))', 'print "$1"') + '}\n'; + const source = [ + '# $1: loader argument', + 'load() {', + ' z.cls.draw Counter; {', + ' z.cls.attr count 0', + ' z.cls.fn increment', + ' print "$1"', + ' z.cls.fn.done', + ' z.cls.drew', + ' }', + '}', + '', + ].join('\n'); const scenario = fixture('', classApi + source); expect(scenario.diagnostics.files.get(scenario.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); }); test('メソッドの名前付き引数取得を外側の引数使用へ混ぜない', () => { - const source = '# $option: loader option\nload() {\n' + - counterClass.replace('(( ++count ))', 'z.arg.named option "$@"') + '}\n'; + const source = [ + '# $option: loader option', + 'load() {', + ' z.cls.draw Counter; {', + ' z.cls.attr count 0', + ' z.cls.fn increment', + ' z.arg.named option "$@"', + ' z.cls.fn.done', + ' z.cls.drew', + ' }', + '}', + '', + ].join('\n'); const scenario = fixture('', classApi + 'z.arg.named() { : }\n' + source); expect(scenario.diagnostics.files.get(scenario.definitionUri)?.items.filter(item => item.code === 'unused-argument')).toHaveLength(1); @@ -195,9 +242,9 @@ describe('hydrated class command targets', () => { }); test('未公開と破棄済みのクラスからは解決先を生成しない', () => { - for (const ending of ['', 'z.cls.abort\n']) { + for (const ending of ['', ' z.cls.abort\n']) { const file = createZshFileHydration({ sourceFile: 'x', file: 'x', - content: 'z.cls.draw Open\nz.cls.attr count 0\n' + ending + 'z.cls.new Open object\n' }); + content: 'z.cls.draw Open\n z.cls.attr count 0\n' + ending + 'z.cls.new Open object\n' }); expect(classCommands([file.classes]).size).toBe(0); } @@ -236,8 +283,16 @@ describe('hydrated class command targets', () => { test('コード引数内のクラスはそのコード内で解決し、プロジェクトへ漏れない', () => { const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; - const text = "run 'z.cls.draw Local; z.cls.fn value \"REPLY=1\"; z.cls.drew; z.cls.new Local local_object; local_object.value'\n" + - 'z.cls.new Local outside\noutside.value\n'; + const text = [ + "run 'z.cls.draw Local", + ' z.cls.fn value "REPLY=1"', + ' z.cls.drew', + 'z.cls.new Local local_object', + "local_object.value'", + 'z.cls.new Local outside', + 'outside.value', + '', + ].join('\n'); const scenario = fixture(text, classApi + api); expect(semantic(scenario.items)).toHaveLength(1); diff --git a/ls/server/test/zshHydrator/classes.test.ts b/ls/server/test/zshHydrator/classes.test.ts index 0e20f81b..fec137c8 100644 --- a/ls/server/test/zshHydrator/classes.test.ts +++ b/ls/server/test/zshHydrator/classes.test.ts @@ -30,14 +30,27 @@ function fixture(content = source) { describe('class hydration', () => { test('重複した本体収集形式のメソッドはクラスを破棄する', () => { - const file = fixture("z.cls.draw Duplicate\nz.cls.fn run ':'\nz.cls.fn run\nz.cls.fn.done\nz.cls.drew\n"); + const file = fixture([ + 'z.cls.draw Duplicate', + " z.cls.fn run ':'", + ' z.cls.fn run', + ' z.cls.fn.done', + ' z.cls.drew', + '', + ].join('\n')); expect(file.classes.definitions[0].state).toBe('aborted'); expect(file.classes.definitions[0].methods).toHaveLength(1); }); test('重複した引数形式のメソッドは元の本体を保持する', () => { - const file = fixture("z.cls.draw Duplicate\nz.cls.fn run 'print first'\nz.cls.fn run 'print second'\nz.cls.drew\n"); + const file = fixture([ + 'z.cls.draw Duplicate', + " z.cls.fn run 'print first'", + " z.cls.fn run 'print second'", + ' z.cls.drew', + '', + ].join('\n')); const definition = file.classes.definitions[0]; const method = definition.methods[0]; @@ -50,7 +63,13 @@ describe('class hydration', () => { }); test('重複した属性は元の初期値を保持する', () => { - const file = fixture('z.cls.draw Duplicate\nz.cls.attr value first\nz.cls.attr value second\nz.cls.drew\n'); + const file = fixture([ + 'z.cls.draw Duplicate', + ' z.cls.attr value first', + ' z.cls.attr value second', + ' z.cls.drew', + '', + ].join('\n')); const definition = file.classes.definitions[0]; expect(definition.state).toBe('published'); @@ -71,7 +90,12 @@ describe('class hydration', () => { }); test('実行時と同じ予約接頭辞だけを除外する', () => { - const file = fixture('z.cls.draw __z_cls_Box\nz.cls.attr __z_cls_value 0\nz.cls.drew\n'); + const file = fixture([ + 'z.cls.draw __z_cls_Box', + ' z.cls.attr __z_cls_value 0', + ' z.cls.drew', + '', + ].join('\n')); expect(file.classes.definitions[0].name).toBe('__z_cls_Box'); expect(file.classes.definitions[0].attributes[0].name).toBe('__z_cls_value'); @@ -95,9 +119,36 @@ describe('class hydration', () => { expect(classMethodAt(file.classes, null, text.indexOf('print deeper'))).toBe(method); }); - test.each(['z.cls.new $class object', 'z.cls.new z_cls_reserved object', 'z.cls.new Counter bad-name', - 'z.cls.new Counter', 'z.cls.draw bad-name'])('動的・不完全・予約済みの名前を決め打ちしない: %s', text => { - const file = fixture(text + '\n'); + test('変数で指定したクラス名を決め打ちしない', () => { + const file = fixture('z.cls.new $class object\n'); + + expect(file.classes.definitions).toEqual([]); + expect(file.classes.instances).toEqual([]); + }); + + test('予約済みのクラス名を登録しない', () => { + const file = fixture('z.cls.new z_cls_reserved object\n'); + + expect(file.classes.definitions).toEqual([]); + expect(file.classes.instances).toEqual([]); + }); + + test('不正な実体名を登録しない', () => { + const file = fixture('z.cls.new Counter bad-name\n'); + + expect(file.classes.definitions).toEqual([]); + expect(file.classes.instances).toEqual([]); + }); + + test('実体名のない宣言を登録しない', () => { + const file = fixture('z.cls.new Counter\n'); + + expect(file.classes.definitions).toEqual([]); + expect(file.classes.instances).toEqual([]); + }); + + test('不正なクラス名で定義を開始しない', () => { + const file = fixture('z.cls.draw bad-name\n'); expect(file.classes.definitions).toEqual([]); expect(file.classes.instances).toEqual([]); @@ -116,7 +167,12 @@ describe('class hydration', () => { }); test('子のコマンドに情報を付加しても初期値のWord参照が古くならない', () => { - const file = fixture('z.cls.draw Holder\nz.cls.attr value "$(z.cls.new Other inside)"\nz.cls.drew\n'); + const file = fixture([ + 'z.cls.draw Holder', + ' z.cls.attr value "$(z.cls.new Other inside)"', + ' z.cls.drew', + '', + ].join('\n')); const attribute = file.classes.definitions[0].attributes[0]; expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); @@ -195,11 +251,21 @@ describe('class hydration', () => { }); test('未完了と破棄済みのクラスを公開済みのクラスと区別する', () => { - const incomplete = fixture('z.cls.draw Open\nz.cls.fn run\nprint "$1"\n'); + const incomplete = fixture([ + 'z.cls.draw Open', + ' z.cls.fn run', + ' print "$1"', + '', + ].join('\n')); expect(incomplete.classes.definitions[0]).toMatchObject({ name: 'Open', state: 'incomplete' }); expect(incomplete.classes.definitions[0].methods[0].body).toMatchObject({ kind: 'block', end: null }); - const aborted = fixture('z.cls.draw Discarded\nz.cls.attr count 0\nz.cls.abort\n'); + const aborted = fixture([ + 'z.cls.draw Discarded', + ' z.cls.attr count 0', + ' z.cls.abort', + '', + ].join('\n')); expect(aborted.classes.definitions[0]).toMatchObject({ name: 'Discarded', state: 'aborted' }); }); @@ -212,7 +278,20 @@ describe('class hydration', () => { }); test('通常の関数ごとのクラスを独立して解釈し、本体内の引数スコープを保持する', () => { - const text = 'load() {\n' + source.slice(0, source.indexOf('z.cls.new')) + '}\n'; + const text = [ + 'load() {', + ' z.cls.draw Counter; {', + ' z.cls.attr count 0', + ' z.cls.fn increment', + ' (( ++count ))', + ' print "$1"', + ' z.cls.fn.done', + " z.cls.fn value 'REPLY=$count'", + ' z.cls.drew', + ' }', + '}', + '', + ].join('\n'); const file = fixture(text); const owner = file.functions.find(fn => fn.name === 'load')?.definition; @@ -238,7 +317,15 @@ describe('class hydration', () => { }); test('関数内のクラスと外側のクラスを同じ定義中の状態にしない', () => { - const text = 'z.cls.draw Outer\nhelper() { z.cls.draw Inner; z.cls.drew }\nz.cls.drew\n'; + const text = [ + 'z.cls.draw Outer', + ' helper() {', + ' z.cls.draw Inner', + ' z.cls.drew', + ' }', + ' z.cls.drew', + '', + ].join('\n'); const file = fixture(text); expect(file.classes.definitions.map(definition => definition.name)).toEqual(['Outer', 'Inner']); diff --git a/ls/server/test/zshParser/ast/word/literal.test.ts b/ls/server/test/zshParser/ast/word/literal.test.ts index ea23c386..ab57f7f2 100644 --- a/ls/server/test/zshParser/ast/word/literal.test.ts +++ b/ls/server/test/zshParser/ast/word/literal.test.ts @@ -17,22 +17,45 @@ function word(source: string) { } describe('literalWord', () => { - test.each([ - ['print plain', 'plain'], - ["print 'two words'", 'two words'], - ['print "two words"', 'two words'], - ["print pre'fix'", 'prefix'], - ['print one\\ two', 'one two'], - ["print $'one\\ntwo'", 'one\ntwo'], - ["print ''", ''], - ])('静的な値の引用をASTから復元する: %s', (source, value) => { - expect(literalWord(word(source))).toBe(value); - }); - - test.each(['print "$value"', 'print "$(print one)"', 'print $(( 1 + 2 ))'])( - '展開を含むWordを静的な値と扱わない: %s', source => { - expect(literalWord(word(source))).toBeNull(); - }); + test('引用のない静的な値をASTから復元する', () => { + expect(literalWord(word('print plain'))).toBe('plain'); + }); + + test('単一引用符で囲んだ値をASTから復元する', () => { + expect(literalWord(word("print 'two words'"))).toBe('two words'); + }); + + test('二重引用符で囲んだ値をASTから復元する', () => { + expect(literalWord(word('print "two words"'))).toBe('two words'); + }); + + test('引用部分を含む単語をASTから復元する', () => { + expect(literalWord(word("print pre'fix'"))).toBe('prefix'); + }); + + test('エスケープした空白をASTから復元する', () => { + expect(literalWord(word('print one\\ two'))).toBe('one two'); + }); + + test('ドル単一引用符の改行をASTから復元する', () => { + expect(literalWord(word("print $'one\\ntwo'"))).toBe('one\ntwo'); + }); + + test('引用した空文字列をASTから復元する', () => { + expect(literalWord(word("print ''"))).toBe(''); + }); + + test('パラメーター展開を含むWordを静的な値と扱わない', () => { + expect(literalWord(word('print "$value"'))).toBeNull(); + }); + + test('コマンド置換を含むWordを静的な値と扱わない', () => { + expect(literalWord(word('print "$(print one)"'))).toBeNull(); + }); + + test('算術展開を含むWordを静的な値と扱わない', () => { + expect(literalWord(word('print $(( 1 + 2 ))'))).toBeNull(); + }); test('指定された終端まで復元し、既存のimportとの互換性を保持する', () => { const argument = word("print 'option'=value"); From 5883e5ad06d421ef8b01630c9cb454e49072c666 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Wed, 18 Nov 2026 07:49:15 +0900 Subject: [PATCH 15/21] test: preserve class hydration in shared code programs Verify that the shared embedded-code result retains the class index and references its returned AST. Describe native-function providers and class diagnostics in terms of the common code-program analysis introduced on main. --- ls/server/src/diagnostics/README.md | 1 + ls/server/src/zshHydrator/README.md | 2 +- ls/server/test/diagnostics/classes.test.ts | 14 ++++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/ls/server/src/diagnostics/README.md b/ls/server/src/diagnostics/README.md index 42f8e713..b55f4438 100644 --- a/ls/server/src/diagnostics/README.md +++ b/ls/server/src/diagnostics/README.md @@ -66,6 +66,7 @@ hydratorが通常の構文コマンドへクラスの意味を付加し、 引用しないメソッド本体は元の位置を保持し、hydratorの範囲索引から引数の所有関係を判定します。 引数で渡す本体は[code]として共通の埋め込み解析へ渡し、元の位置へ診断を対応付けます。 +`codePrograms`の各要素の`file.classes`から、コード引数のクラス索引を参照できます。 コード引数は外側のクラス定義を継承しますが、そのコードでの定義・実体はそのプログラム内に保ちます。 同じ変数名で静的に観測したクラスは候補として集め、動的な参照展開は動的コマンドとして扱います。 ソースを実行したり、条件分岐後の変数の型を再現したりする解析は行いません。 diff --git a/ls/server/src/zshHydrator/README.md b/ls/server/src/zshHydrator/README.md index ed9b5510..4e783bec 100644 --- a/ls/server/src/zshHydrator/README.md +++ b/ls/server/src/zshHydrator/README.md @@ -109,4 +109,4 @@ hydrateAstを再適用すると、元のASTを変えずに意味情報を作り `classMethodAt`は、宣言を再解釈せず、本体の範囲から引数の所有関係を調べます。 診断はこの共通情報を使い、名前の除外だけでなく、メンバーの宣言を解決先として返します。 -クラスの索引は診断で使用します。補完・hover・定義ジャンプは従来の関数索引を使用します。 +クラスの索引は診断の呼出し解決で使用します。通常の関数の補完・hover・定義ジャンプは、関数索引とコード引数の共通解析結果を使用します。 diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index 1673bed7..3b0bedb7 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -386,5 +386,19 @@ describe('hydrated class command targets', () => { expect(semantic(scenario.items)).toHaveLength(1); expect(semantic(scenario.items)[0].message).toContain('outside.value'); + + const report = scenario.diagnostics.files.get(scenario.document.uri); + const program = report?.codePrograms.find((entry) => + entry.file.classes.definitions.some((definition) => definition.name === 'Local'), + ); + const definition = program?.file.classes.definitions[0]; + + expect(definition?.name).toBe('Local'); + expect(definition?.file).toBe(program?.file.ast); + expect(definition?.methods.map((method) => method.name)).toEqual(['value']); + expect(program?.file.classes.instances.map((instance) => instance.name)).toEqual([ + 'local_object', + ]); + expect(program?.root).toBe(report?.file); }); }); From d8e881a207b291fbf4c95c4b86bdb759271f11ba Mon Sep 17 00:00:00 2001 From: milkeclair Date: Wed, 18 Nov 2026 09:58:14 +0900 Subject: [PATCH 16/21] feat: hydrate named defaults and flat class boundaries --- ls/server/src/diagnostics/README.md | 3 + ls/server/src/zshHydrator/README.md | 10 + .../src/zshHydrator/classes/attribute.ts | 53 +++ ls/server/src/zshHydrator/classes/collect.ts | 187 +++++++++-- ls/server/src/zshHydrator/classes/indexes.ts | 15 +- ls/server/src/zshHydrator/classes/types.ts | 1 + ls/server/test/connection/classApi.test.ts | 23 +- ls/server/test/diagnostics/classes.test.ts | 69 +++- ls/server/test/zshHydrator/classes.test.ts | 315 +++++++++++++++++- 9 files changed, 610 insertions(+), 66 deletions(-) create mode 100644 ls/server/src/zshHydrator/classes/attribute.ts diff --git a/ls/server/src/diagnostics/README.md b/ls/server/src/diagnostics/README.md index b55f4438..3e188e09 100644 --- a/ls/server/src/diagnostics/README.md +++ b/ls/server/src/diagnostics/README.md @@ -70,3 +70,6 @@ hydratorが通常の構文コマンドへクラスの意味を付加し、 コード引数は外側のクラス定義を継承しますが、そのコードでの定義・実体はそのプログラム内に保ちます。 同じ変数名で静的に観測したクラスは候補として集め、動的な参照展開は動的コマンドとして扱います。 ソースを実行したり、条件分岐後の変数の型を再現したりする解析は行いません。 + +属性の初期値は必須の名前付き引数`default=`で指定し、省略は通常の関数引数の診断で報告します。 +不正な属性を含むクラスと、入れ子や同じ構文スコープでの重複によって拒否した定義からは、生成コマンドを作りません。 diff --git a/ls/server/src/zshHydrator/README.md b/ls/server/src/zshHydrator/README.md index 4e783bec..6cfacac9 100644 --- a/ls/server/src/zshHydrator/README.md +++ b/ls/server/src/zshHydrator/README.md @@ -110,3 +110,13 @@ hydrateAstを再適用すると、元のASTを変えずに意味情報を作り `classMethodAt`は、宣言を再解釈せず、本体の範囲から引数の所有関係を調べます。 診断はこの共通情報を使い、名前の除外だけでなく、メンバーの宣言を解決先として返します。 クラスの索引は診断の呼出し解決で使用します。通常の関数の補完・hover・定義ジャンプは、関数索引とコード引数の共通解析結果を使用します。 + +属性は名前と必須の名前付き引数`default=`で宣言します。`default=`や`default=""`で空の初期値も指定できます。 +`z.cls.attr default default=0`のように、`default`という属性名も利用できます。 +`ClassAttribute.defaultValue`は名前付き引数全体の元のWordを参照し、 +`defaultValueRange`は`default=`と引用を除いた値の物理位置を示します。空値は単語の末尾の長さ0の範囲です。 +名前付き初期値の省略、余分な引数、属性の重複などがある定義は、`drew`で公開せず破棄済みとして保持します。 + +定義中のクラスへの入れ子や、同じ構文スコープで公開済みの名前による`draw`は拒否した範囲として分離します。 +拒否した範囲のメンバーと終端を外側へ混ぜず、対応する`drew`の後に外側の収集を続けます。 +メソッド本体は同じ深さの独立した`fn.done`まで保持し、本体内の`draw`や`drew`、論理演算・パイプ・非同期実行中の`fn.done`で収集を終了しません。 diff --git a/ls/server/src/zshHydrator/classes/attribute.ts b/ls/server/src/zshHydrator/classes/attribute.ts new file mode 100644 index 00000000..9b203ba2 --- /dev/null +++ b/ls/server/src/zshHydrator/classes/attribute.ts @@ -0,0 +1,53 @@ +import { decodeLiteral } from '../../embeddedCode/literal'; +import { createCodeSourceMap, sourcePosition } from '../../embeddedCode/sourceMap'; +import type { SimpleCommandNode, WordNode } from '../../zshParser/ast'; +import { literalWord } from '../../zshParser/ast/word/literal'; +import type { SourceRange } from '../../zshParser/lexer'; + +function isDefaultArgument(word: WordNode): boolean { + const prefix = word.parts[0]; + if (prefix?.kind !== 'stringLiteral') return false; + + const value = literalWord({ ...word, raw: prefix.value, parts: [prefix] }); + return value?.startsWith('default=') ?? false; +} + +/** 属性名と必須のdefault引数を、元の単語の参照を保って読み取る。 */ +export function attributeArguments(command: SimpleCommandNode): { + readonly nameNode: WordNode; + readonly defaultValue: WordNode; +} | null { + if (command.arguments.length !== 2) return null; + + const index = command.arguments.findIndex(isDefaultArgument); + if (index < 0) return null; + + const nameNode = command.arguments[1 - index]; + return isDefaultArgument(nameNode) ? null : { nameNode, defaultValue: command.arguments[index] }; +} + +/** 引用と展開の構文を保ちながら、default=を除いた値の物理位置を返す。 */ +export function attributeValueRange(word: WordNode): SourceRange { + const ranges = word.parts.flatMap((part, index): readonly SourceRange[] => { + if (part.kind !== 'stringLiteral') return [part.range]; + + const segment: WordNode = { ...word, range: part.range, raw: part.value, parts: [part] }; + const decoded = decodeLiteral(segment, true); + if (!decoded) return []; + + const spans = decoded.spans.slice(index === 0 ? 'default='.length : 0); + if (spans.length === 0) return []; + + const source = createCodeSourceMap(segment, decoded); + return [ + { + start: sourcePosition(source, spans[0].start), + end: sourcePosition(source, spans[spans.length - 1].end), + }, + ]; + }); + + return ranges.length + ? { start: ranges[0].start, end: ranges[ranges.length - 1].end } + : { start: word.range.end, end: word.range.end }; +} diff --git a/ls/server/src/zshHydrator/classes/collect.ts b/ls/server/src/zshHydrator/classes/collect.ts index f87f9f6d..224fe8a6 100644 --- a/ls/server/src/zshHydrator/classes/collect.ts +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -1,11 +1,17 @@ import { castDraft } from 'immer'; -import { appendItems, makeMap, produce, setEntry } from '../../util/collections'; +import { addValue, appendItems, makeMap, makeSet, produce, setEntry } from '../../util/collections'; import { again, done, loop } from '../../util/loop'; import { pushStack, type Stack } from '../../util/stack'; -import type { FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../zshParser/ast'; +import type { + FileNode, + FunctionDefinitionNode, + ListItemNode, + SimpleCommandNode, +} from '../../zshParser/ast'; import { foldAst } from '../../zshParser/ast'; import { literalWord } from '../../zshParser/ast/word/literal'; import type { SourceRange } from '../../zshParser/lexer'; +import { attributeArguments } from './attribute'; import type { ClassDefinition, ClassDefinitionScopeLocation, @@ -21,6 +27,7 @@ type Definition = { readonly node: SimpleCommandNode; readonly name: string; readonly members: readonly Member[]; + readonly failed: boolean; }; type Capture = | { @@ -33,10 +40,16 @@ type Capture = readonly node: SimpleCommandNode; readonly name: string; readonly depth: number; + } + | { + readonly kind: 'rejected'; + readonly outer: Capture | undefined; + readonly methodDepth: number | null; }; type State = { readonly captures: ReadonlyMap; readonly information: ReadonlyMap; + readonly published: ReadonlyMap>; }; type ClassDirective = { @@ -45,6 +58,7 @@ type ClassDirective = { readonly args: readonly (string | null)[]; readonly depth: number; readonly scope: FunctionDefinitionNode | undefined; + readonly standalone: boolean; }; /** 実行時に予約した名前を、静的なクラスの識別子から除外する。 */ @@ -122,7 +136,7 @@ function blockMethodFromCapture( function finishDefinition( state: State, scope: FunctionDefinitionNode | undefined, - capture: Capture, + capture: Extract, end: SourceRange, status: ClassDefinition['state'], ): State { @@ -145,7 +159,16 @@ function finishDefinition( } }); - return { ...withCapture(state, scope, null), information }; + const published = + status === 'published' + ? setEntry( + state.published, + scope, + addValue(state.published.get(scope) ?? makeSet(), definition.name), + ) + : state.published; + + return { ...withCapture(state, scope, null), information, published }; } /** 引数を実行せず、通常の構文から静的な宣言を1つ読む。 */ @@ -153,6 +176,7 @@ function readClassDirective( command: SimpleCommandNode, depth: number, scope: FunctionDefinitionNode | undefined, + standalone: boolean, ): ClassDirective | null { const external = command.precommandModifiers.some( (modifier) => modifier.type === 'builtin' || modifier.type === 'command', @@ -173,7 +197,14 @@ function readClassDirective( ]; if (!names.includes(name)) return null; - return { command, name, args: command.arguments.map((word) => literalWord(word)), depth, scope }; + return { + command, + name, + args: command.arguments.map((word) => literalWord(word)), + depth, + scope, + standalone, + }; } /** 通常の関数または収集中のメソッドのスコープに、実体の束縛を記録する。 */ @@ -207,7 +238,7 @@ function applyMethodDirective( capture: Extract, state: State, ): State { - if (directive.depth !== capture.depth) return state; + if (directive.depth !== capture.depth || !directive.standalone) return state; if (directive.name === 'z.cls.fn.done' && directive.args.length === 0) { return withMember( @@ -218,22 +249,22 @@ function applyMethodDirective( ); } - if (directive.name === 'z.cls.abort' || directive.name === 'z.cls.drew') { - return finishDefinition(state, directive.scope, capture, directive.command.range, 'aborted'); - } - return state; } /** クラス内で最初に現れた有効な属性宣言を保持する。 */ function declareAttribute(directive: ClassDirective, definition: Definition, state: State): State { - const name = directive.args[0]; - if (directive.args.length !== 2 || !identifier(name)) return state; - + const attribute = attributeArguments(directive.command); + const name = attribute && literalWord(attribute.nameNode); const duplicate = definition.members.some( (member) => member.information.kind === 'classAttribute' && member.information.name === name, ); - if (duplicate) return state; + if (!attribute || !identifier(name) || duplicate) { + return withCapture(state, directive.scope, { + kind: 'definition', + definition: { ...definition, failed: true }, + }); + } return withMember(state, directive.scope, definition, { node: directive.command, @@ -298,7 +329,13 @@ function applyDefinitionDirective( return declareMethod(directive, capture, state); case 'z.cls.drew': return directive.args.length === 0 - ? finishDefinition(state, directive.scope, capture, directive.command.range, 'published') + ? finishDefinition( + state, + directive.scope, + capture, + directive.command.range, + capture.definition.failed ? 'aborted' : 'published', + ) : state; case 'z.cls.abort': return finishDefinition(state, directive.scope, capture, directive.command.range, 'aborted'); @@ -307,30 +344,69 @@ function applyDefinitionDirective( } } +/** 拒否した定義のメンバーや終端を、外側で収集中のクラスへ混ぜない。 */ +function applyRejectedDirective( + directive: ClassDirective, + capture: Extract, + state: State, +): State { + if (!directive.standalone) return state; + + if (capture.methodDepth !== null) { + return directive.name === 'z.cls.fn.done' && + directive.args.length === 0 && + directive.depth === capture.methodDepth + ? withCapture(state, directive.scope, { ...capture, methodDepth: null }) + : state; + } + + if (directive.name === 'z.cls.draw') { + return withCapture(state, directive.scope, { + kind: 'rejected', + outer: capture, + methodDepth: null, + }); + } + + if (directive.name === 'z.cls.drew' && directive.args.length === 0) { + return withCapture(state, directive.scope, capture.outer ?? null); + } + + return directive.name === 'z.cls.fn' && directive.args.length === 1 + ? withCapture(state, directive.scope, { ...capture, methodDepth: directive.depth }) + : state; +} + /** 現在の構文スコープの収集状態に応じて宣言を処理する。 */ function collectCommand( command: SimpleCommandNode, depth: number, scope: FunctionDefinitionNode | undefined, + standalone: boolean, state: State, ): State { - const directive = readClassDirective(command, depth, scope); + const directive = readClassDirective(command, depth, scope, standalone); if (!directive) return state; const capture = state.captures.get(scope); + if (capture?.kind === 'rejected') return applyRejectedDirective(directive, capture, state); if (directive.name === 'z.cls.new') return declareInstance(directive, capture, state); if (capture?.kind === 'method') return applyMethodDirective(directive, capture, state); - if ( - directive.name === 'z.cls.draw' && - directive.args.length === 1 && - identifier(directive.args[0]) && - !capture - ) { - return withCapture(state, scope, { - kind: 'definition', - definition: { node: command, name: directive.args[0], members: [] }, - }); + if (directive.name === 'z.cls.draw') { + if ( + directive.args.length === 1 && + identifier(directive.args[0]) && + !capture && + !state.published.get(scope)?.has(directive.args[0]) + ) { + return withCapture(state, scope, { + kind: 'definition', + definition: { node: command, name: directive.args[0], members: [], failed: false }, + }); + } + + return withCapture(state, scope, { kind: 'rejected', outer: capture, methodDepth: null }); } return capture ? applyDefinitionDirective(directive, capture, state) : state; @@ -343,26 +419,63 @@ type FunctionScope = { type CollectionProgress = { readonly collected: State; readonly functionScopes: Stack | null; + readonly standaloneCommand: SimpleCommandNode | null; }; +function standaloneCommand(item: ListItemNode): SimpleCommandNode | null { + if (item.sublist.kind !== 'sublist') return null; + + const pipeline = item.sublist.first; + const command = pipeline.first; + const foreground = + !item.terminator || item.terminator.type === 'newline' || item.terminator.type === 'semicolon'; + + return foreground && + item.sublist.rest.length === 0 && + pipeline.rest.length === 0 && + !pipeline.timing && + !pipeline.modifier && + command.kind === 'simpleCommand' && + command.precommandModifiers.length === 0 + ? command + : null; +} + /** 通常の関数スコープごとに独立して、構文上のコマンドからクラス宣言を解釈する。 */ export function collectClassInformation( ast: FileNode, ): ReadonlyMap { const initial: CollectionProgress = { - collected: { captures: makeMap(), information: makeMap() }, + collected: { captures: makeMap(), information: makeMap(), published: makeMap() }, functionScopes: null, + standaloneCommand: null, }; const progress = foldAst(ast, initial, (previous, node, depth) => { const active = loop | null, Stack | null>( previous.functionScopes, (scopes) => (scopes && scopes.value.depth >= depth ? again(scopes.next) : done(scopes)), ); + const rejected = previous.collected.captures.get(active?.value.node)?.kind === 'rejected'; + if ( + rejected && + (node.kind === 'functionDefinition' || + node.kind === 'commandSubstitution' || + node.kind === 'processSubstitution' || + node.kind === 'subshellCommand') + ) { + return { + state: { ...previous, functionScopes: active }, + control: 'skip', + }; + } + const functionScopes = node.kind === 'functionDefinition' ? pushStack({ node, depth }, active) : active; + const standalone = + node.kind === 'listItem' ? standaloneCommand(node) : previous.standaloneCommand; if (node.kind !== 'simpleCommand') { - return { state: { ...previous, functionScopes } }; + return { state: { ...previous, functionScopes, standaloneCommand: standalone } }; } const collected = @@ -375,15 +488,27 @@ export function collectClassInformation( return { state: { - collected: collectCommand(node, depth, functionScopes?.value.node, collected), + collected: collectCommand( + node, + depth, + functionScopes?.value.node, + standalone === node, + collected, + ), functionScopes, + standaloneCommand: standalone, }, }; }); return [...progress.collected.captures].reduce((state, [scope, capture]) => { - const end = scope?.range.end ?? ast.range.end; + const active = loop< + Capture | undefined, + Extract | undefined + >(capture, (current) => (current?.kind === 'rejected' ? again(current.outer) : done(current))); + if (!active) return state; - return finishDefinition(state, scope, capture, { start: end, end }, 'incomplete'); + const end = scope?.range.end ?? ast.range.end; + return finishDefinition(state, scope, active, { start: end, end }, 'incomplete'); }, progress.collected).information; } diff --git a/ls/server/src/zshHydrator/classes/indexes.ts b/ls/server/src/zshHydrator/classes/indexes.ts index 3b6f7fbf..75be5cd8 100644 --- a/ls/server/src/zshHydrator/classes/indexes.ts +++ b/ls/server/src/zshHydrator/classes/indexes.ts @@ -1,5 +1,6 @@ import { castDraft } from 'immer'; import { makeMap, produce } from '../../util/collections'; +import { attributeArguments, attributeValueRange } from './attribute'; import type { FileNode, FunctionDefinitionNode, SimpleCommandNode } from '../../zshParser/ast'; import type { ClassAttribute, @@ -29,13 +30,21 @@ function memberFromCommand(command: HydratedClassCommand): LocatedMember | null const base = { name: information.name, declaration: command, nameNode }; switch (information.kind) { - case 'classAttribute': - if (!value) return null; + case 'classAttribute': { + const attribute = attributeArguments(command); + if (!attribute) return null; return { classOffset: information.classOffset, - member: { ...base, kind: 'classAttribute', defaultValue: value }, + member: { + ...base, + nameNode: attribute.nameNode, + kind: 'classAttribute', + defaultValue: attribute.defaultValue, + defaultValueRange: attributeValueRange(attribute.defaultValue), + }, }; + } case 'classMethod': if (information.body.kind === 'inline') { if (!value) return null; diff --git a/ls/server/src/zshHydrator/classes/types.ts b/ls/server/src/zshHydrator/classes/types.ts index 93a0769d..e14339bf 100644 --- a/ls/server/src/zshHydrator/classes/types.ts +++ b/ls/server/src/zshHydrator/classes/types.ts @@ -67,6 +67,7 @@ export type ClassAttribute = { readonly declaration: SimpleCommandNode; readonly nameNode: WordNode; readonly defaultValue: WordNode; + readonly defaultValueRange: SourceRange; }; export type ClassMethod = { diff --git a/ls/server/test/connection/classApi.test.ts b/ls/server/test/connection/classApi.test.ts index 1831c101..f14cd532 100644 --- a/ls/server/test/connection/classApi.test.ts +++ b/ls/server/test/connection/classApi.test.ts @@ -69,7 +69,7 @@ describe('class API visibility', () => { expect(items?.map((item) => item.label).toSorted()).toEqual(publicCommands); }); - test('private表示を有効にすると内部20関数も参照できる', () => { + test('private表示を有効にすると内部24関数も参照できる', () => { const scenario = fixture(); const names = zCompletion({ ...scenario, showPrivateFunctions: true })?.map((item) => item.label) ?? []; @@ -77,8 +77,8 @@ describe('class API visibility', () => { name.split('.').some((segment) => segment.startsWith('_')), ); - expect(names).toHaveLength(28); - expect(internal).toHaveLength(20); + expect(names).toHaveLength(32); + expect(internal).toHaveLength(24); expect(internal).toContain('z.cls.instance._call'); expect(internal).toContain('z.cls.capture._start'); expect(names).not.toContain('z.cls.instance.call'); @@ -94,4 +94,21 @@ describe('class API visibility', () => { expect(validateTextDocument({ diagnostics, textDocument: scenario.document })).toEqual([]); expect(zDefinition(scenario)?.uri).toBe(scenario.definitionUri); }); + test('実際の属性APIがdefaultの省略を必須引数として診断する', () => { + const scenario = fixture( + ['z.cls.draw MissingDefault', ' z.cls.attr price¦', ' z.cls.drew', ''].join('\n'), + ); + const diagnostics = refreshDiagnosticSnapshot({ + snapshot: scenario.snapshot, + environment: emptyShellEnvironment(), + }); + const items = validateTextDocument({ diagnostics, textDocument: scenario.document }); + + expect(items.filter((item) => item.code === 'missing-named-argument')).toMatchObject([ + { + code: 'missing-named-argument', + message: 'Missing required named argument: default', + }, + ]); + }); }); diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index 3b0bedb7..b95f5960 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -62,7 +62,9 @@ const semantic = (items: Readonly>) => const classApi = [ 'z.cls.draw() { : }', - 'z.cls.attr() { : }', + '# $1: attribute name', + '# $default: initial value', + 'z.cls.attr() { : "$@" }', '# $1: method name', '# $2? [code]: inline body', 'z.cls.fn() { : "$@" }', @@ -71,13 +73,12 @@ const classApi = 'z.cls.new() { : }', ].join('\n') + '\n'; const counterClass = [ - 'z.cls.draw Counter; {', - ' z.cls.attr count 0', + 'z.cls.draw Counter', + ' z.cls.attr count default=0', ' z.cls.fn increment', ' (( ++count ))', ' z.cls.fn.done', ' z.cls.drew', - '}', '', ].join('\n'); @@ -95,7 +96,7 @@ describe('class DSL command diagnostics', () => { expect(diagnostics).toHaveLength(1); expect(diagnostics[0].message).toContain('missing_inline_method'); - expect(diagnostics[0].range.start.line).toBe(10); + expect(diagnostics[0].range.start.line).toBe(12); }); test('別ファイルのクラスから生成されるメソッドと属性を認識し、タイプミスは診断する', () => { @@ -123,7 +124,7 @@ describe('class DSL command diagnostics', () => { ).toMatchObject([ { code: 'undefined-command', - range: { start: { line: 11, character: 4 } }, + range: { start: { line: 13, character: 4 } }, }, ]); }); @@ -177,12 +178,11 @@ describe('class DSL command diagnostics', () => { describe('scoped class references', () => { test('スコープによって異なるクラスを指す同名変数の呼出を認識する', () => { const arrayClass = [ - 'z.cls.draw ArrayBox; {', + 'z.cls.draw ArrayBox', ' z.cls.fn fill', ' :', ' z.cls.fn.done', ' z.cls.drew', - '}', '', ].join('\n'); const source = [ @@ -245,13 +245,12 @@ describe('scoped class references', () => { const source = [ '# $1: loader argument', 'load() {', - ' z.cls.draw Counter; {', - ' z.cls.attr count 0', + ' z.cls.draw Counter', + ' z.cls.attr count default=0', ' z.cls.fn increment', ' print "$1"', ' z.cls.fn.done', ' z.cls.drew', - ' }', '}', '', ].join('\n'); @@ -268,13 +267,12 @@ describe('scoped class references', () => { const source = [ '# $option: loader option', 'load() {', - ' z.cls.draw Counter; {', - ' z.cls.attr count 0', + ' z.cls.draw Counter', + ' z.cls.attr count default=0', ' z.cls.fn increment', ' z.arg.named option "$@"', ' z.cls.fn.done', ' z.cls.drew', - ' }', '}', '', ].join('\n'); @@ -317,7 +315,8 @@ describe('hydrated class command targets', () => { const file = createZshFileHydration({ sourceFile: 'x', file: 'x', - content: 'z.cls.draw Open\n z.cls.attr count 0\n' + ending + 'z.cls.new Open object\n', + content: + 'z.cls.draw Open\n z.cls.attr count default=0\n' + ending + 'z.cls.new Open object\n', }); expect(classCommands([file.classes]).size).toBe(0); @@ -401,4 +400,44 @@ describe('hydrated class command targets', () => { ]); expect(program?.root).toBe(report?.file); }); + test('defaultを省略した属性を通常の必須引数診断で報告する', () => { + const scenario = fixture( + '', + classApi + ['z.cls.draw MissingDefault', ' z.cls.attr price', ' z.cls.drew', ''].join('\n'), + ); + const items = scenario.diagnostics.files.get(scenario.definitionUri)?.items ?? []; + + expect(semantic(items)).toMatchObject([ + { + code: 'missing-named-argument', + message: 'Missing required named argument: default', + }, + ]); + expect( + scenario.snapshot.hydrator.files.get('definition.zsh')?.classes.definitions[0].state, + ).toBe('aborted'); + }); + + test('拒否した定義の属性コマンドを生成せず外側の属性を解決する', () => { + const definitions = [ + 'z.cls.draw Outer', + ' z.cls.draw Rejected', + ' z.cls.attr leaked default=0', + ' z.cls.drew', + ' z.cls.attr kept default=1', + ' z.cls.drew', + '', + ].join('\n'); + const scenario = fixture( + ['z.cls.new Outer object', 'object.kept.get', 'object.leaked.get', ''].join('\n'), + classApi + definitions, + ); + + expect(semantic(scenario.items)).toMatchObject([ + { + code: 'undefined-command', + message: 'object.leaked.get is not defined in the project or shell environment.', + }, + ]); + }); }); diff --git a/ls/server/test/zshHydrator/classes.test.ts b/ls/server/test/zshHydrator/classes.test.ts index 0fd4e034..ce32f9f7 100644 --- a/ls/server/test/zshHydrator/classes.test.ts +++ b/ls/server/test/zshHydrator/classes.test.ts @@ -12,15 +12,14 @@ import { import { astContractViolations } from '../zshParser/parser/contracts'; const source = [ - 'z.cls.draw Counter; {', - ' z.cls.attr count 0', + 'z.cls.draw Counter', + ' z.cls.attr count default=0', ' z.cls.fn increment', ' (( ++count ))', ' print "$1"', ' z.cls.fn.done', " z.cls.fn value 'REPLY=$count'", ' z.cls.drew', - '}', 'z.cls.new Counter object', '', ].join('\n'); @@ -71,21 +70,21 @@ describe('class hydration', () => { expect(method.body.value.raw).toBe("'print first'"); }); - test('重複した属性は元の初期値を保持する', () => { + test('重複した属性は元の初期値を保持しクラスを破棄する', () => { const file = fixture( [ 'z.cls.draw Duplicate', - ' z.cls.attr value first', - ' z.cls.attr value second', + ' z.cls.attr value default=first', + ' z.cls.attr value default=second', ' z.cls.drew', '', ].join('\n'), ); const definition = file.classes.definitions[0]; - expect(definition.state).toBe('published'); + expect(definition.state).toBe('aborted'); expect(definition.attributes).toHaveLength(1); - expect(definition.attributes[0].defaultValue.raw).toBe('first'); + expect(definition.attributes[0].defaultValue.raw).toBe('default=first'); }); test('索引の再構築が既存索引を変更せず返却ASTの参照を保持する', () => { @@ -104,7 +103,9 @@ describe('class hydration', () => { test('実行時と同じ予約接頭辞だけを除外する', () => { const file = fixture( - ['z.cls.draw __z_cls_Box', ' z.cls.attr __z_cls_value 0', ' z.cls.drew', ''].join('\n'), + ['z.cls.draw __z_cls_Box', ' z.cls.attr __z_cls_value default=0', ' z.cls.drew', ''].join( + '\n', + ), ); expect(file.classes.definitions[0].name).toBe('__z_cls_Box'); @@ -185,7 +186,7 @@ describe('class hydration', () => { const file = fixture( [ 'z.cls.draw Holder', - ' z.cls.attr value "$(z.cls.new Other inside)"', + ' z.cls.attr value default="$(z.cls.new Other inside)"', ' z.cls.drew', '', ].join('\n'), @@ -299,7 +300,7 @@ describe('class hydration', () => { end: null, }); const aborted = fixture( - ['z.cls.draw Discarded', ' z.cls.attr count 0', ' z.cls.abort', ''].join('\n'), + ['z.cls.draw Discarded', ' z.cls.attr count default=0', ' z.cls.abort', ''].join('\n'), ); expect(aborted.classes.definitions[0]).toMatchObject({ name: 'Discarded', state: 'aborted' }); @@ -317,15 +318,14 @@ describe('class hydration', () => { test('通常の関数ごとのクラスを独立して解釈し、本体内の引数スコープを保持する', () => { const text = [ 'load() {', - ' z.cls.draw Counter; {', - ' z.cls.attr count 0', + ' z.cls.draw Counter', + ' z.cls.attr count default=0', ' z.cls.fn increment', ' (( ++count ))', ' print "$1"', ' z.cls.fn.done', " z.cls.fn value 'REPLY=$count'", ' z.cls.drew', - ' }', '}', '', ].join('\n'); @@ -380,4 +380,291 @@ describe('class hydration', () => { file.functions[0].definition, ); }); + test('defaultという属性名と名前付き初期値を区別する', () => { + const text = [ + 'z.cls.draw BusinessValue', + ' z.cls.attr default default=0', + ' z.cls.drew', + '', + ].join('\n'); + const file = fixture(text); + const attribute = file.classes.definitions[0].attributes[0]; + + expect(attribute.name).toBe('default'); + expect(attribute.nameNode).toBe(attribute.declaration.arguments[0]); + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); + expect( + text.slice(attribute.defaultValueRange.start.offset, attribute.defaultValueRange.end.offset), + ).toBe('0'); + }); + + test('先に指定したdefault引数も元の単語へ結び付ける', () => { + const file = fixture( + ['z.cls.draw Reversed', ' z.cls.attr default=0 price', ' z.cls.drew', ''].join('\n'), + ); + const attribute = file.classes.definitions[0].attributes[0]; + + expect(attribute.name).toBe('price'); + expect(attribute.nameNode).toBe(attribute.declaration.arguments[1]); + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[0]); + expect(attribute.defaultValueRange.start.offset).toBe( + attribute.defaultValue.range.start.offset + 'default='.length, + ); + }); + + test('明示した空のdefault値を長さ0の範囲で保持する', () => { + const file = fixture( + ['z.cls.draw EmptyDefault', ' z.cls.attr value default=', ' z.cls.drew', ''].join('\n'), + ); + const attribute = file.classes.definitions[0].attributes[0]; + + expect(file.classes.definitions[0].state).toBe('published'); + expect(attribute.defaultValue.raw).toBe('default='); + expect(attribute.defaultValueRange).toEqual({ + start: attribute.defaultValue.range.end, + end: attribute.defaultValue.range.end, + }); + }); + + test('引用した空のdefault値も長さ0の範囲で保持する', () => { + const file = fixture( + ['z.cls.draw QuotedEmpty', ' z.cls.attr value default=""', ' z.cls.drew', ''].join('\n'), + ); + const attribute = file.classes.definitions[0].attributes[0]; + + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); + expect(attribute.defaultValueRange).toEqual({ + start: attribute.defaultValue.range.end, + end: attribute.defaultValue.range.end, + }); + }); + + test('引用した日本語の初期値を元ソースの値の位置へ結び付ける', () => { + const text = [ + 'z.cls.draw QuotedDefault', + ' z.cls.attr label default="日本語の値"', + ' z.cls.drew', + '', + ].join('\n'); + const file = fixture(text); + const attribute = file.classes.definitions[0].attributes[0]; + + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); + expect(attribute.defaultValueRange.start).toEqual({ + offset: text.indexOf('日本語の値'), + line: 1, + character: ' z.cls.attr label default="'.length, + }); + expect( + text.slice(attribute.defaultValueRange.start.offset, attribute.defaultValueRange.end.offset), + ).toBe('日本語の値'); + }); + + test('引用内に名前付き引数を記述しても値の範囲を保持する', () => { + const text = [ + 'z.cls.draw QuotedArgument', + " z.cls.attr value 'default=two words'", + ' z.cls.drew', + '', + ].join('\n'); + const file = fixture(text); + const attribute = file.classes.definitions[0].attributes[0]; + + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); + expect( + text.slice(attribute.defaultValueRange.start.offset, attribute.defaultValueRange.end.offset), + ).toBe('two words'); + }); + + test('展開を含むdefault値の構文と値の位置を保持する', () => { + const text = [ + 'z.cls.draw DynamicDefault', + ' z.cls.attr value default="$(print text)"', + ' z.cls.drew', + '', + ].join('\n'); + const file = fixture(text); + const attribute = file.classes.definitions[0].attributes[0]; + + expect(attribute.defaultValue).toBe(attribute.declaration.arguments[1]); + expect(findAll(attribute.defaultValue, 'commandSubstitution')).toHaveLength(1); + expect( + text.slice(attribute.defaultValueRange.start.offset, attribute.defaultValueRange.end.offset), + ).toBe('$(print text)'); + }); + + test('defaultを省略した属性があるクラスを公開しない', () => { + const file = fixture( + ['z.cls.draw MissingDefault', ' z.cls.attr price', ' z.cls.drew', ''].join('\n'), + ); + + expect(file.classes.definitions[0].state).toBe('aborted'); + expect(file.classes.definitions[0].attributes).toEqual([]); + }); + + test('位置引数の初期値を名前付きdefaultとして扱わない', () => { + const file = fixture( + ['z.cls.draw PositionalDefault', ' z.cls.attr price 0', ' z.cls.drew', ''].join('\n'), + ); + + expect(file.classes.definitions[0].state).toBe('aborted'); + expect(file.classes.definitions[0].attributes).toEqual([]); + }); + + test('defaultを重複指定したクラスを公開しない', () => { + const file = fixture( + [ + 'z.cls.draw DuplicateDefault', + ' z.cls.attr price default=0 default=1', + ' z.cls.drew', + '', + ].join('\n'), + ); + + expect(file.classes.definitions[0].state).toBe('aborted'); + expect(file.classes.definitions[0].attributes).toEqual([]); + }); + + test('拒否した入れ子のクラスのメンバーと終端を外側へ混ぜない', () => { + const file = fixture( + [ + 'z.cls.draw Outer', + ' z.cls.attr kept default=0', + ' z.cls.draw Inner', + ' z.cls.attr leaked default=1', + ' z.cls.drew', + ' z.cls.attr tail default=2', + ' z.cls.drew', + '', + ].join('\n'), + ); + + expect(file.classes.definitions.map((definition) => definition.name)).toEqual(['Outer']); + expect(file.classes.definitions[0].state).toBe('published'); + expect(file.classes.definitions[0].attributes.map((attribute) => attribute.name)).toEqual([ + 'kept', + 'tail', + ]); + }); + + test('拒否した定義のメソッド内のマーカーで外側を閉じない', () => { + const file = fixture( + [ + 'z.cls.draw Outer', + ' z.cls.draw Rejected', + ' z.cls.fn run', + ' z.cls.draw Business', + ' z.cls.drew', + ' z.cls.abort', + ' z.cls.fn.done', + ' z.cls.abort', + ' z.cls.drew', + ' z.cls.attr kept default=0', + ' z.cls.drew', + '', + ].join('\n'), + ); + + expect(file.classes.definitions.map((definition) => definition.name)).toEqual(['Outer']); + expect(file.classes.definitions[0].state).toBe('published'); + expect(file.classes.definitions[0].attributes.map((attribute) => attribute.name)).toEqual([ + 'kept', + ]); + }); + + test('拒否した定義内の関数と置換のクラスを外へ混ぜない', () => { + const file = fixture( + [ + 'z.cls.draw Outer', + ' z.cls.draw Rejected', + ' helper() { z.cls.draw Hidden; z.cls.drew }', + ' z.cls.attr ignored default="$(z.cls.drew)"', + ' z.cls.drew', + ' z.cls.attr kept default=0', + ' z.cls.drew', + '', + ].join('\n'), + ); + + expect(file.classes.definitions.map((definition) => definition.name)).toEqual(['Outer']); + expect(file.classes.definitions[0].attributes.map((attribute) => attribute.name)).toEqual([ + 'kept', + ]); + expect(file.functions.map((fn) => fn.name)).toContain('helper'); + }); + + test('同じスコープで公開済みのクラス名を上書きしない', () => { + const file = fixture( + [ + 'z.cls.draw Duplicate', + ' z.cls.attr first default=0', + ' z.cls.drew', + 'z.cls.draw Duplicate', + ' z.cls.attr leaked default=1', + ' z.cls.drew', + '', + ].join('\n'), + ); + + expect(file.classes.definitions).toHaveLength(1); + expect(file.classes.definitions[0].attributes.map((attribute) => attribute.name)).toEqual([ + 'first', + ]); + }); + + test('メソッド本体のdrawとdrewを終了マーカーとして扱わない', () => { + const text = [ + 'z.cls.draw MethodMarkers', + ' z.cls.fn run', + ' z.cls.draw Business', + ' z.cls.drew', + ' z.cls.fn.done', + ' z.cls.drew', + '', + ].join('\n'); + const file = fixture(text); + const method = file.classes.definitions[0].methods[0]; + + expect(file.classes.definitions[0].state).toBe('published'); + expect(method.body.kind).toBe('block'); + if (method.body.kind !== 'block') throw new Error('Expected a block method'); + + expect(text.slice(method.body.range.start.offset, method.body.range.end.offset)).toContain( + 'z.cls.drew', + ); + expect(method.body.end?.start.offset).toBe(text.indexOf('z.cls.fn.done')); + }); + + test('論理演算・パイプ・非同期実行中のfn.doneでメソッドを閉じない', () => { + const text = [ + 'z.cls.draw MethodBoundary', + ' z.cls.fn run', + ' true && z.cls.fn.done', + ' print value | z.cls.fn.done', + ' z.cls.fn.done &', + ' print tail', + ' z.cls.fn.done', + ' z.cls.drew', + '', + ].join('\n'); + const file = fixture(text); + const method = file.classes.definitions[0].methods[0]; + + expect(method.body.kind).toBe('block'); + if (method.body.kind !== 'block') throw new Error('Expected a block method'); + + expect(method.body.end?.start.offset).toBe(text.lastIndexOf('z.cls.fn.done')); + expect(classMethodAt(file.classes, null, text.indexOf('print tail'))).toBe(method); + }); + + test('通常のZshグループ内でもクラスを定義できる', () => { + const file = fixture( + ['z.cls.draw Grouped; {', ' z.cls.attr price default=0', ' z.cls.drew', '}', ''].join('\n'), + ); + + expect(file.classes.definitions[0].state).toBe('published'); + expect(file.classes.definitions[0].attributes.map((attribute) => attribute.name)).toEqual([ + 'price', + ]); + }); }); From 8804e839979105d7ef0591caae6e68c805089e82 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Wed, 18 Nov 2026 12:37:22 +0900 Subject: [PATCH 17/21] feat: resolve self calls in class method scopes --- ls/server/src/diagnostics/README.md | 5 + ls/server/src/diagnostics/calls.ts | 37 ++- ls/server/src/diagnostics/classes.ts | 3 +- ls/server/src/diagnostics/self.ts | 168 ++++++++++ ls/server/src/zshHydrator/README.md | 25 ++ ls/server/test/diagnostics/self.test.ts | 343 +++++++++++++++++++++ ls/server/test/zshHydrator/classes.test.ts | 4 +- 7 files changed, 575 insertions(+), 10 deletions(-) create mode 100644 ls/server/src/diagnostics/self.ts create mode 100644 ls/server/test/diagnostics/self.test.ts diff --git a/ls/server/src/diagnostics/README.md b/ls/server/src/diagnostics/README.md index 3e188e09..58a497d5 100644 --- a/ls/server/src/diagnostics/README.md +++ b/ls/server/src/diagnostics/README.md @@ -73,3 +73,8 @@ hydratorが通常の構文コマンドへクラスの意味を付加し、 属性の初期値は必須の名前付き引数`default=`で指定し、省略は通常の関数引数の診断で報告します。 不正な属性を含むクラスと、入れ子や同じ構文スコープでの重複によって拒否した定義からは、生成コマンドを作りません。 + +`$self`によるメソッドと属性の呼出しは、実際の所有メソッドからクラスを確定できる場合に共有の解決先へ結び付けます。 +未定義のメンバーは`undefined-command`として、元のWordまたはコード引数内の位置へ診断します。 +`ClassCommandTarget.instance`は、具体的な実体が実行時に決まるself参照ではnullです。 +通常の実体変数名から解決した場合は、従来どおり実体宣言を参照します。 diff --git a/ls/server/src/diagnostics/calls.ts b/ls/server/src/diagnostics/calls.ts index 319f538e..334842b5 100644 --- a/ls/server/src/diagnostics/calls.ts +++ b/ls/server/src/diagnostics/calls.ts @@ -22,6 +22,7 @@ import { isAliasReference, isKnownShellCommand, type ResolutionContext } from '. import type { IgnoreControls } from './controls'; import { ignored } from './controls'; import { simpleParameter } from './facts'; +import { resolveSelfCommand } from './self'; import type { Diagnostics } from './type'; export type { ResolutionContext } from './commandResolution'; @@ -203,14 +204,36 @@ export function analyzeCalls( }; const result = commands.reduce((previous, command) => { const word = command.commandName?.word; - const name = word && literalWord(word); + if (!word) return previous; - if ( - !word || - !name || - (!word.quoted && word.raw.startsWith('=')) || - uncertainWord(word, context) - ) { + const self = functionCommand(command) + ? resolveSelfCommand(file, word, options.scopes ?? []) + : null; + if (self) { + if (self.target) { + return { + ...previous, + classTargets: setEntry(previous.classTargets, command, [self.target]), + }; + } + + return options.ignores && ignored(options.ignores, word.range.start.line, 'undefined-command') + ? previous + : { + ...previous, + diagnostics: appendItems(previous.diagnostics, { + severity: DiagnosticSeverity.Error, + code: 'undefined-command', + range: protocolRange(mapRange(word.range)), + source: 'z-ls', + message: self.name + ' is not defined in class ' + self.definition.name + '.', + }), + }; + } + + const name = literalWord(word); + + if (!name || (!word.quoted && word.raw.startsWith('=')) || uncertainWord(word, context)) { return previous; } diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts index 404ca968..4a1d93ba 100644 --- a/ls/server/src/diagnostics/classes.ts +++ b/ls/server/src/diagnostics/classes.ts @@ -10,7 +10,8 @@ import type { export type ClassCommandTarget = { readonly definition: ClassDefinition; - readonly instance: ClassInstance; + // selfは所有クラスを確定できても、呼び出す実体は実行時に決まる。 + readonly instance: ClassInstance | null; readonly member: ClassMethod | ClassAttribute; readonly operation: 'method' | 'get' | 'set'; }; diff --git a/ls/server/src/diagnostics/self.ts b/ls/server/src/diagnostics/self.ts new file mode 100644 index 00000000..75b705f2 --- /dev/null +++ b/ls/server/src/diagnostics/self.ts @@ -0,0 +1,168 @@ +import { decodeLiteral } from '../embeddedCode/literal'; +import type { ClassDefinition, ZshFileHydration } from '../zshHydrator'; +import { classMethodAt } from '../zshHydrator'; +import type { AstNode, FunctionDefinitionNode, WordNode, WordPartNode } from '../zshParser/ast'; +import { locate } from '../zshParser/ast'; +import type { CallScope } from './calls'; +import type { ClassCommandTarget } from './classes'; + +function staticText(word: WordNode, parts: readonly WordPartNode[]): string | null { + return parts.reduce((text, part) => { + if (text === null || part.kind !== 'stringLiteral') return null; + + const segment: WordNode = { ...word, range: part.range, raw: part.value, parts: [part] }; + const value = decodeLiteral(segment, true)?.text; + return value === undefined ? null : text + value; + }, ''); +} + +function selfMemberName(word: WordNode): string | null { + const index = word.parts.findIndex( + (part) => + (part.kind === 'variableReference' && part.name.value === 'self') || + (part.kind === 'parameterExpansion' && part.raw === '${self}'), + ); + if (index < 0 || staticText(word, word.parts.slice(0, index)) !== '') return null; + + const suffix = staticText(word, word.parts.slice(index + 1)); + if (!suffix?.startsWith('.') || suffix.length === 1) return null; + + const staticName = [...suffix].every( + (char) => + char === '.' || + char === '_' || + (char >= 'a' && char <= 'z') || + (char >= 'A' && char <= 'Z') || + (char >= '0' && char <= '9'), + ); + return staticName ? suffix.slice(1) : null; +} + +function shadowsSelf(path: readonly AstNode[], offset: number, start: number): boolean { + return path.some( + (node) => + node.kind === 'list' && + node.items.some((item) => { + if (item.sublist.kind !== 'sublist') return false; + + const command = item.sublist.first.first; + if ( + command.kind !== 'simpleCommand' || + command.range.start.offset < start || + command.range.start.offset >= offset || + command.semantic.role !== 'declaration' + ) + return false; + + const declaration = command.semantic.declaration; + if ( + declaration.kind === 'export' || + declaration.options.some((option) => option.name.includes('g')) + ) { + return false; + } + + return ( + declaration.names.some((name) => name.value === 'self') || + declaration.assignments.some((assignment) => assignment.name.value === 'self') + ); + }), + ); +} + +function ownerAt( + file: ZshFileHydration, + offset: number, +): { + readonly definition: ClassDefinition | null; + readonly blocked: boolean; +} { + const location = locate(file.query, offset); + const scope = + location?.kind === 'syntax' + ? (location.path + .toReversed() + .find((node): node is FunctionDefinitionNode => node.kind === 'functionDefinition') ?? + null) + : null; + const block = classMethodAt(file.classes, scope, offset); + const definition = file.classes.definitions.find( + (candidate) => + candidate.state === 'published' && + candidate.scope === scope && + candidate.methods.some( + (method) => + method === block || + (method.body.kind === 'inline' && + method.body.value.range.start.offset <= offset && + offset < method.body.value.range.end.offset), + ), + ); + + const method = definition?.methods.find( + (candidate) => + candidate === block || + (candidate.body.kind === 'inline' && + candidate.body.value.range.start.offset <= offset && + offset < candidate.body.value.range.end.offset), + ); + const start = method + ? method.body.kind === 'block' + ? method.body.range.start.offset + : method.body.value.range.start.offset + : 0; + const shadowed = location?.kind === 'syntax' && shadowsSelf(location.path, offset, start); + + return { + definition: shadowed ? null : (definition ?? null), + blocked: scope !== null || shadowed, + }; +} + +/** 文字列のコードも元の所有関係から調べ、通常の関数を越えてselfの所属を推測しない。 */ +function owningClass( + file: ZshFileHydration, + word: WordNode, + scopes: readonly CallScope[], +): ClassDefinition | null { + const current = ownerAt(file, word.range.start.offset); + if (current.definition || current.blocked) return current.definition; + + for (const scope of scopes) { + const owner = ownerAt(scope.file, scope.offset); + if (owner.definition || owner.blocked) return owner.definition; + } + + return null; +} + +function memberTarget(definition: ClassDefinition, name: string): ClassCommandTarget | null { + const method = definition.methods.find((candidate) => candidate.name === name); + if (method) return { definition, instance: null, member: method, operation: 'method' }; + + const operation = name.endsWith('.get') ? 'get' : name.endsWith('.set') ? 'set' : null; + if (!operation) return null; + + const attributeName = name.slice(0, -operation.length - 1); + const attribute = definition.attributes.find((candidate) => candidate.name === attributeName); + return attribute ? { definition, instance: null, member: attribute, operation } : null; +} + +/** 実際の所有メソッドが分かるself参照だけを、共有するメンバー宣言へ結び付ける。 */ +export function resolveSelfCommand( + file: ZshFileHydration, + word: WordNode, + scopes: readonly CallScope[], +): { + readonly definition: ClassDefinition; + readonly name: string; + readonly target: ClassCommandTarget | null; +} | null { + const name = selfMemberName(word); + if (!name) return null; + + const definition = owningClass(file, word, scopes); + return definition + ? { definition, name: '$self.' + name, target: memberTarget(definition, name) } + : null; +} diff --git a/ls/server/src/zshHydrator/README.md b/ls/server/src/zshHydrator/README.md index 6cfacac9..3267d605 100644 --- a/ls/server/src/zshHydrator/README.md +++ b/ls/server/src/zshHydrator/README.md @@ -120,3 +120,28 @@ hydrateAstを再適用すると、元のASTを変えずに意味情報を作り 定義中のクラスへの入れ子や、同じ構文スコープで公開済みの名前による`draw`は拒否した範囲として分離します。 拒否した範囲のメンバーと終端を外側へ混ぜず、対応する`drew`の後に外側の収集を続けます。 メソッド本体は同じ深さの独立した`fn.done`まで保持し、本体内の`draw`や`drew`、論理演算・パイプ・非同期実行中の`fn.done`で収集を終了しません。 + +## メソッド内のself参照 + +メソッドの実行時には、現在の実体参照を持つreadonly変数`self`を使えます。 +`"$self.increment"`、`"$self.count.get"`、`"$self.count.set" 3`は、 +付加済みASTの所有メソッドと通常の関数スコープから、そのクラスのメンバー宣言へ解決します。 +`self`という属性名も利用でき、`"$self.self.get"`でその値を取得します。 + +引数で渡す本体も共通のコード解析結果と元の単語の位置から所有関係を調べます。 +通常の関数を越える所属や、別の`self`の宣言、変動するメンバー名、メソッド外の`$self`は推測で確定しません。 +実行時の本体を書き換えず、通常の構文と元の範囲を保持します。 + +```zsh +z.cls.draw Counter + z.cls.attr count default=0 + z.cls.fn increment + "$self.count.get" + local next=$(( REPLY + 1 )) + "$self.count.set" "$next" + REPLY=$next + z.cls.fn.done + z.cls.drew +``` + +この定義は、countを1増やして結果を返すCounter.incrementを公開します。 diff --git a/ls/server/test/diagnostics/self.test.ts b/ls/server/test/diagnostics/self.test.ts new file mode 100644 index 00000000..1df1c7fc --- /dev/null +++ b/ls/server/test/diagnostics/self.test.ts @@ -0,0 +1,343 @@ +import { afterEach, describe, expect, test } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { refreshFunctionSnapshot } from '../../src/refreshFunctions/main'; +import { analyzeCalls } from '../../src/diagnostics/calls'; +import { refreshDiagnosticSnapshot } from '../../src/diagnostics/snapshot'; +import { emptyShellEnvironment } from '../../src/diagnostics/environment'; +import { findAll } from '../../src/zshParser/ast'; + +const roots: string[] = []; +afterEach(() => { + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); + +const classApi = [ + 'z.cls.draw() { : }', + '# $1: attribute name', + '# $default: initial value', + 'z.cls.attr() { : "$@" }', + '# $1: method name', + '# $2? [code]: inline body', + 'z.cls.fn() { : "$@" }', + 'z.cls.fn.done() { : }', + 'z.cls.drew() { : }', + 'z.cls.new() { : }', + '# $1 [code]: body', + 'run_code() { eval "$1" }', + '', +].join('\n'); + +const counter = [ + 'z.cls.draw Counter', + ' z.cls.attr count default=0', + ' z.cls.attr self default=business', + ' z.cls.fn increment', + ' "$self.count.get"', + ' "$self.count.set" 1', + ' z.cls.fn.done', + ' z.cls.fn twice', + ' "$self.increment"', + ' z.cls.fn.done', + ' z.cls.drew', + '', +].join('\n'); + +function fixture(source = counter) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'z-self-diag-')); + roots.push(root); + const document = TextDocument.create( + pathToFileURL(path.join(root, 'class.zsh')).href, + 'shellscript', + 1, + classApi + source, + ); + const snapshot = refreshFunctionSnapshot({ projectRoot: root, documents: [document] }); + const diagnostics = refreshDiagnosticSnapshot({ snapshot, environment: emptyShellEnvironment() }); + const report = diagnostics.files.get(document.uri); + if (!report) throw new Error('Expected class diagnostics'); + const analysis = analyzeCalls(snapshot, report.file, report.facts.calls, diagnostics.context); + return { snapshot, diagnostics, document, report, analysis }; +} + +describe('selfのクラス参照', () => { + test('所有メソッドのクラスからメソッドと属性を実際の宣言へ解決する', () => { + const scenario = fixture(); + const targets = [...scenario.analysis.classTargets.values()].flat(); + const definition = scenario.report.file.classes.definitions[0]; + + expect(targets.map((target) => target.operation)).toEqual(['get', 'set', 'method']); + expect(targets.map((target) => target.member.name)).toEqual(['count', 'count', 'increment']); + expect(targets.every((target) => target.definition === definition)).toBe(true); + expect(targets.every((target) => target.instance === null)).toBe(true); + expect(targets[0].member).toBe(definition.attributes[0]); + expect(targets[2].member).toBe(definition.methods[0]); + }); + + test('既知のselfのメンバーのタイプミスを元の位置へ診断する', () => { + const scenario = fixture(counter.replace('"$self.increment"', '"$self.typo"')); + const items = scenario.report.items.filter((item) => item.code === 'undefined-command'); + const offset = scenario.document.getText().indexOf('"$self.typo"'); + + expect(items).toHaveLength(1); + expect(items[0]).toMatchObject({ + message: '$self.typo is not defined in class Counter.', + range: { start: scenario.document.positionAt(offset) }, + }); + }); + test('引用しないselfと波括弧で囲んだselfも同じ所有クラスへ解決する', () => { + const scenario = fixture( + counter.replace( + '"$self.increment"', + '$self.increment\n ${self}.count.get\n "${self}.count.set" 2', + ), + ); + const targets = [...scenario.analysis.classTargets.values()].flat(); + + expect(targets.map((target) => target.operation)).toEqual([ + 'get', + 'set', + 'method', + 'get', + 'set', + ]); + expect( + targets.every((target) => target.definition === scenario.report.file.classes.definitions[0]), + ).toBe(true); + }); + + test('selfという属性名を実体参照のselfと区別する', () => { + const scenario = fixture(counter.replace('"$self.increment"', '"$self.self.get"')); + const targets = [...scenario.analysis.classTargets.values()].flat(); + const definition = scenario.report.file.classes.definitions[0]; + + expect(targets[2].operation).toBe('get'); + expect(targets[2].member).toBe(definition.attributes[1]); + expect(targets[2].member.name).toBe('self'); + expect(targets[2].instance).toBeNull(); + }); + + test('メソッド外のself参照をクラスへ結び付けない', () => { + const scenario = fixture(counter + '"$self.typo"\n'); + const targets = [...scenario.analysis.classTargets.keys()]; + + expect(targets).toHaveLength(3); + expect(targets.some((command) => command.commandName?.word.raw === '"$self.typo"')).toBe(false); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); + + test('入れ子の通常の関数で宣言したselfを外側のクラスへ結び付けない', () => { + const scenario = fixture( + counter.replace( + '"$self.increment"', + 'helper() {\n local self=other\n "$self.typo"\n }\n "$self.increment"', + ), + ); + + expect([...scenario.analysis.classTargets.values()].flat()).toHaveLength(3); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); + + test('selfを明示的に宣言しない通常の関数でも所属を推測しない', () => { + const scenario = fixture( + counter.replace('"$self.increment"', 'helper() { "$self.typo" }\n "$self.increment"'), + ); + + expect([...scenario.analysis.classTargets.values()].flat()).toHaveLength(3); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); + + test('匿名関数で新しいselfを宣言したスコープへ外側の所属を持ち込まない', () => { + const scenario = fixture( + counter.replace( + '"$self.increment"', + '() {\n local self=other\n "$self.typo"\n }\n "$self.increment"', + ), + ); + + expect( + findAll(scenario.report.file.ast, 'simpleCommand').some( + (command) => + command.semantic.role === 'declaration' && + command.semantic.declaration.kind === 'local' && + command.semantic.declaration.assignments.some( + (assignment) => assignment.name.value === 'self', + ), + ), + ).toBe(true); + expect([...scenario.analysis.classTargets.values()].flat()).toHaveLength(3); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); + + test('通常の関数内で定義したクラスのメソッドへselfを結び付ける', () => { + const scenario = fixture( + [ + 'load() {', + ' z.cls.draw LocalCounter', + ' z.cls.attr count default=0', + ' z.cls.fn value', + ' "$self.count.get"', + ' z.cls.fn.done', + ' z.cls.drew', + '}', + '', + ].join('\n'), + ); + const target = [...scenario.analysis.classTargets.values()].flat()[0]; + const definition = scenario.report.file.classes.definitions[0]; + const owner = scenario.report.file.functions.find((fn) => fn.name === 'load'); + + expect(target.definition).toBe(definition); + expect(definition.scope).toBe(owner?.definition); + expect(target.member).toBe(definition.attributes[0]); + }); + + test('別のクラスに同名メソッドがあっても実際の所有クラスだけを使う', () => { + const scenario = fixture( + counter + + [ + 'z.cls.draw Other', + ' z.cls.attr label default=other', + ' z.cls.fn twice', + ' "$self.label.get"', + ' "$self.count.get"', + ' z.cls.fn.done', + ' z.cls.drew', + '', + ].join('\n'), + ); + const targets = [...scenario.analysis.classTargets.values()].flat(); + const other = scenario.report.file.classes.definitions[1]; + + expect(targets[3].definition).toBe(other); + expect(targets[3].member).toBe(other.attributes[0]); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toMatchObject( + [{ message: '$self.count.get is not defined in class Other.' }], + ); + }); + + test('引数で渡す本体のselfを元のメソッドとクラスへ結び付ける', () => { + const scenario = fixture( + [ + 'z.cls.draw Inline', + ' z.cls.attr count default=0', + ' z.cls.fn value \'"$self.count.get"\'', + ' z.cls.drew', + '', + ].join('\n'), + ); + const program = scenario.report.codePrograms[0]; + if (!program) throw new Error('Expected an inline code program'); + + const analysis = analyzeCalls( + scenario.snapshot, + program.file, + findAll(program.file.ast, 'simpleCommand'), + scenario.diagnostics.context, + { scopes: [{ file: scenario.report.file, offset: program.word.range.start.offset }] }, + ); + const target = [...analysis.classTargets.values()].flat()[0]; + const definition = scenario.report.file.classes.definitions[0]; + const method = definition.methods[0]; + + expect(method.body.kind).toBe('inline'); + if (method.body.kind !== 'inline') throw new Error('Expected an inline method'); + + expect(program.word).toBe(method.body.value); + expect(program.root).toBe(scenario.report.file); + expect(target.definition).toBe(definition); + expect(target.member).toBe(definition.attributes[0]); + expect(target.operation).toBe('get'); + expect(target.instance).toBeNull(); + }); + + test('引数形式の本体のselfの診断を元の引用内へ対応付ける', () => { + const scenario = fixture( + ['z.cls.draw Inline', ' z.cls.fn value \'"$self.typo"\'', ' z.cls.drew', ''].join('\n'), + ); + const items = scenario.report.items.filter((item) => item.code === 'undefined-command'); + const offset = scenario.document.getText().indexOf('"$self.typo"'); + + expect(items).toHaveLength(1); + expect(items[0]).toMatchObject({ + message: '$self.typo is not defined in class Inline.', + range: { start: scenario.document.positionAt(offset) }, + }); + }); + + test('入れ子のコード引数でも既知のselfと平坦化した元位置を保持する', () => { + const scenario = fixture( + [ + 'z.cls.draw InlineNested', + ' z.cls.fn value \'run_code "\\$self.typo"\'', + ' z.cls.drew', + '', + ].join('\n'), + ); + const items = scenario.report.items.filter((item) => item.code === 'undefined-command'); + const offset = scenario.document.getText().indexOf('\\$self.typo'); + + expect(scenario.report.codePrograms).toHaveLength(2); + expect(items).toHaveLength(1); + expect(items[0]).toMatchObject({ + message: '$self.typo is not defined in class InlineNested.', + range: { start: scenario.document.positionAt(offset) }, + }); + }); + + test('コード引数内の通常の関数を越えてselfを推測しない', () => { + const scenario = fixture( + [ + 'z.cls.draw InlineHelper', + ' z.cls.fn value \'helper() { "$self.typo" }; helper\'', + ' z.cls.drew', + '', + ].join('\n'), + ); + + expect(scenario.report.codePrograms).toHaveLength(1); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); + + test('変動する実体やメンバー名を静的なself呼出しと扱わない', () => { + const scenario = fixture( + counter.replace( + '"$self.increment"', + '"$self.$member"\n "$other.increment"\n prefix$self.increment\n "${self:-other}.increment"', + ), + ); + + expect([...scenario.analysis.classTargets.values()].flat()).toHaveLength(2); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); + + test('selfの診断にも既存の制御コメントを適用する', () => { + const scenario = fixture( + counter.replace('"$self.increment"', '"$self.typo" # zls: ignore undefined-command'), + ); + + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); + test('コード引数で宣言したselfを外側のメソッドへ結び付けない', () => { + const scenario = fixture( + counter.replace('"$self.increment"', 'run_code \'local self=other; "$self.typo"\''), + ); + + expect(scenario.report.codePrograms).toHaveLength(1); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); + test('新しいスコープのtypesetによるself宣言も外側へ結び付けない', () => { + const scenario = fixture( + counter.replace( + '"$self.increment"', + '() {\n typeset self=other\n "$self.typo"\n }\n "$self.increment"', + ), + ); + + expect([...scenario.analysis.classTargets.values()].flat()).toHaveLength(3); + expect(scenario.report.items.filter((item) => item.code === 'undefined-command')).toEqual([]); + }); +}); diff --git a/ls/server/test/zshHydrator/classes.test.ts b/ls/server/test/zshHydrator/classes.test.ts index ce32f9f7..bad57a3c 100644 --- a/ls/server/test/zshHydrator/classes.test.ts +++ b/ls/server/test/zshHydrator/classes.test.ts @@ -18,7 +18,7 @@ const source = [ ' (( ++count ))', ' print "$1"', ' z.cls.fn.done', - " z.cls.fn value 'REPLY=$count'", + ' z.cls.fn value \'"$self.count.get"\'', ' z.cls.drew', 'z.cls.new Counter object', '', @@ -324,7 +324,7 @@ describe('class hydration', () => { ' (( ++count ))', ' print "$1"', ' z.cls.fn.done', - " z.cls.fn value 'REPLY=$count'", + ' z.cls.fn value \'"$self.count.get"\'', ' z.cls.drew', '}', '', From 790f376de343760e5f7b66681ae590192981878b Mon Sep 17 00:00:00 2001 From: milkeclair Date: Wed, 18 Nov 2026 13:09:11 +0900 Subject: [PATCH 18/21] refactor: separate class collection and self resolution stages --- ls/server/src/diagnostics/calls.ts | 4 +- ls/server/src/diagnostics/self.ts | 82 +++++----- ls/server/src/embeddedCode/index.ts | 7 +- ls/server/src/zshHydrator/classes/collect.ts | 160 ++++++++++--------- ls/server/test/connection/classApi.test.ts | 6 +- 5 files changed, 141 insertions(+), 118 deletions(-) diff --git a/ls/server/src/diagnostics/calls.ts b/ls/server/src/diagnostics/calls.ts index 334842b5..502ae7bb 100644 --- a/ls/server/src/diagnostics/calls.ts +++ b/ls/server/src/diagnostics/calls.ts @@ -206,9 +206,7 @@ export function analyzeCalls( const word = command.commandName?.word; if (!word) return previous; - const self = functionCommand(command) - ? resolveSelfCommand(file, word, options.scopes ?? []) - : null; + const self = functionCommand(command) ? resolveSelfCommand(file, word, scopes) : null; if (self) { if (self.target) { return { diff --git a/ls/server/src/diagnostics/self.ts b/ls/server/src/diagnostics/self.ts index 75b705f2..0d2542ea 100644 --- a/ls/server/src/diagnostics/self.ts +++ b/ls/server/src/diagnostics/self.ts @@ -1,5 +1,10 @@ import { decodeLiteral } from '../embeddedCode/literal'; -import type { ClassDefinition, ZshFileHydration } from '../zshHydrator'; +import type { + ClassDefinition, + ClassFileHydration, + ClassMethod, + ZshFileHydration, +} from '../zshHydrator'; import { classMethodAt } from '../zshHydrator'; import type { AstNode, FunctionDefinitionNode, WordNode, WordPartNode } from '../zshParser/ast'; import { locate } from '../zshParser/ast'; @@ -70,7 +75,33 @@ function shadowsSelf(path: readonly AstNode[], offset: number, start: number): b ); } -function ownerAt( +function methodOwnerAt( + classes: ClassFileHydration, + scope: FunctionDefinitionNode | null, + offset: number, +): { + readonly definition: ClassDefinition; + readonly method: ClassMethod; +} | null { + const block = classMethodAt(classes, scope, offset); + + for (const definition of classes.definitions) { + if (definition.state !== 'published' || definition.scope !== scope) continue; + + const method = definition.methods.find( + (candidate) => + candidate === block || + (candidate.body.kind === 'inline' && + candidate.body.value.range.start.offset <= offset && + offset < candidate.body.value.range.end.offset), + ); + if (method) return { definition, method }; + } + + return null; +} + +function selfScopeAt( file: ZshFileHydration, offset: number, ): { @@ -78,43 +109,18 @@ function ownerAt( readonly blocked: boolean; } { const location = locate(file.query, offset); + const path = location?.kind === 'syntax' ? location.path : []; const scope = - location?.kind === 'syntax' - ? (location.path - .toReversed() - .find((node): node is FunctionDefinitionNode => node.kind === 'functionDefinition') ?? - null) - : null; - const block = classMethodAt(file.classes, scope, offset); - const definition = file.classes.definitions.find( - (candidate) => - candidate.state === 'published' && - candidate.scope === scope && - candidate.methods.some( - (method) => - method === block || - (method.body.kind === 'inline' && - method.body.value.range.start.offset <= offset && - offset < method.body.value.range.end.offset), - ), - ); - - const method = definition?.methods.find( - (candidate) => - candidate === block || - (candidate.body.kind === 'inline' && - candidate.body.value.range.start.offset <= offset && - offset < candidate.body.value.range.end.offset), - ); - const start = method - ? method.body.kind === 'block' - ? method.body.range.start.offset - : method.body.value.range.start.offset - : 0; - const shadowed = location?.kind === 'syntax' && shadowsSelf(location.path, offset, start); + path + .toReversed() + .find((node): node is FunctionDefinitionNode => node.kind === 'functionDefinition') ?? null; + const owner = methodOwnerAt(file.classes, scope, offset); + const body = owner?.method.body; + const start = body ? (body.kind === 'block' ? body.range : body.value.range).start.offset : 0; + const shadowed = shadowsSelf(path, offset, start); return { - definition: shadowed ? null : (definition ?? null), + definition: shadowed ? null : (owner?.definition ?? null), blocked: scope !== null || shadowed, }; } @@ -125,11 +131,11 @@ function owningClass( word: WordNode, scopes: readonly CallScope[], ): ClassDefinition | null { - const current = ownerAt(file, word.range.start.offset); + const current = selfScopeAt(file, word.range.start.offset); if (current.definition || current.blocked) return current.definition; for (const scope of scopes) { - const owner = ownerAt(scope.file, scope.offset); + const owner = selfScopeAt(scope.file, scope.offset); if (owner.definition || owner.blocked) return owner.definition; } diff --git a/ls/server/src/embeddedCode/index.ts b/ls/server/src/embeddedCode/index.ts index 2e4cf608..a19934df 100644 --- a/ls/server/src/embeddedCode/index.ts +++ b/ls/server/src/embeddedCode/index.ts @@ -123,12 +123,15 @@ function inheritedContext( declarations: Declarations, classes: ClassFileHydration, ): ResolutionContext { - const classFiles = [...parent.classFiles, classes]; + const hasClassDeclarations = classes.definitions.length > 0 || classes.instances.length > 0; + const classFiles = hasClassDeclarations + ? appendItems(parent.classFiles, classes) + : parent.classFiles; return { ...parent, classFiles, - classCommands: classCommands(classFiles), + classCommands: hasClassDeclarations ? classCommands(classFiles) : parent.classCommands, aliases: declarations.aliases.size ? new Set([...parent.aliases, ...declarations.aliases]) : parent.aliases, diff --git a/ls/server/src/zshHydrator/classes/collect.ts b/ls/server/src/zshHydrator/classes/collect.ts index 224fe8a6..558c43ca 100644 --- a/ls/server/src/zshHydrator/classes/collect.ts +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -3,12 +3,14 @@ import { addValue, appendItems, makeMap, makeSet, produce, setEntry } from '../. import { again, done, loop } from '../../util/loop'; import { pushStack, type Stack } from '../../util/stack'; import type { + AstNode, FileNode, FunctionDefinitionNode, ListItemNode, SimpleCommandNode, } from '../../zshParser/ast'; import { foldAst } from '../../zshParser/ast'; +import type { FoldStep } from '../../zshParser/ast/traversal/walk'; import { literalWord } from '../../zshParser/ast/word/literal'; import type { SourceRange } from '../../zshParser/lexer'; import { attributeArguments } from './attribute'; @@ -232,24 +234,29 @@ function declareInstance( }; } +function isMethodEnd(directive: ClassDirective, depth: number): boolean { + return ( + directive.depth === depth && + directive.standalone && + directive.name === 'z.cls.fn.done' && + directive.args.length === 0 + ); +} + /** メソッド開始時と同じ構文の深さにある終了マーカーだけを処理する。 */ function applyMethodDirective( directive: ClassDirective, capture: Extract, state: State, ): State { - if (directive.depth !== capture.depth || !directive.standalone) return state; - - if (directive.name === 'z.cls.fn.done' && directive.args.length === 0) { - return withMember( - state, - directive.scope, - capture.definition, - blockMethodFromCapture(capture, directive.command.range, true), - ); - } - - return state; + return isMethodEnd(directive, capture.depth) + ? withMember( + state, + directive.scope, + capture.definition, + blockMethodFromCapture(capture, directive.command.range, true), + ) + : state; } /** クラス内で最初に現れた有効な属性宣言を保持する。 */ @@ -353,9 +360,7 @@ function applyRejectedDirective( if (!directive.standalone) return state; if (capture.methodDepth !== null) { - return directive.name === 'z.cls.fn.done' && - directive.args.length === 0 && - directive.depth === capture.methodDepth + return isMethodEnd(directive, capture.methodDepth) ? withCapture(state, directive.scope, { ...capture, methodDepth: null }) : state; } @@ -441,67 +446,65 @@ function standaloneCommand(item: ListItemNode): SimpleCommandNode | null { : null; } -/** 通常の関数スコープごとに独立して、構文上のコマンドからクラス宣言を解釈する。 */ -export function collectClassInformation( - ast: FileNode, -): ReadonlyMap { - const initial: CollectionProgress = { - collected: { captures: makeMap(), information: makeMap(), published: makeMap() }, - functionScopes: null, - standaloneCommand: null, - }; - const progress = foldAst(ast, initial, (previous, node, depth) => { - const active = loop | null, Stack | null>( - previous.functionScopes, - (scopes) => (scopes && scopes.value.depth >= depth ? again(scopes.next) : done(scopes)), - ); - const rejected = previous.collected.captures.get(active?.value.node)?.kind === 'rejected'; - if ( - rejected && - (node.kind === 'functionDefinition' || - node.kind === 'commandSubstitution' || - node.kind === 'processSubstitution' || - node.kind === 'subshellCommand') - ) { - return { - state: { ...previous, functionScopes: active }, - control: 'skip', - }; - } +/** 構文スコープを進め、1ノード分の収集状態と探索制御を返す。 */ +function collectNode( + previous: CollectionProgress, + node: AstNode, + depth: number, +): FoldStep { + const active = loop | null, Stack | null>( + previous.functionScopes, + (scopes) => (scopes && scopes.value.depth >= depth ? again(scopes.next) : done(scopes)), + ); + const rejected = previous.collected.captures.get(active?.value.node)?.kind === 'rejected'; + if ( + rejected && + (node.kind === 'functionDefinition' || + node.kind === 'commandSubstitution' || + node.kind === 'processSubstitution' || + node.kind === 'subshellCommand') + ) { + return { + state: { ...previous, functionScopes: active }, + control: 'skip', + }; + } - const functionScopes = - node.kind === 'functionDefinition' ? pushStack({ node, depth }, active) : active; - const standalone = - node.kind === 'listItem' ? standaloneCommand(node) : previous.standaloneCommand; + const functionScopes = + node.kind === 'functionDefinition' ? pushStack({ node, depth }, active) : active; + const standalone = + node.kind === 'listItem' ? standaloneCommand(node) : previous.standaloneCommand; - if (node.kind !== 'simpleCommand') { - return { state: { ...previous, functionScopes, standaloneCommand: standalone } }; - } + if (node.kind !== 'simpleCommand') { + return { state: { ...previous, functionScopes, standaloneCommand: standalone } }; + } - const collected = - 'hydration' in node - ? { - ...previous.collected, - information: setEntry(previous.collected.information, node.range.start.offset, null), - } - : previous.collected; + const collected = + 'hydration' in node + ? { + ...previous.collected, + information: setEntry(previous.collected.information, node.range.start.offset, null), + } + : previous.collected; - return { - state: { - collected: collectCommand( - node, - depth, - functionScopes?.value.node, - standalone === node, - collected, - ), - functionScopes, - standaloneCommand: standalone, - }, - }; - }); + return { + state: { + collected: collectCommand( + node, + depth, + functionScopes?.value.node, + standalone === node, + collected, + ), + functionScopes, + standaloneCommand: standalone, + }, + }; +} - return [...progress.collected.captures].reduce((state, [scope, capture]) => { +/** 終端のない定義を、それぞれの所有スコープの末尾で確定する。 */ +function finishOpenDefinitions(ast: FileNode, collected: State): State { + return [...collected.captures].reduce((state, [scope, capture]) => { const active = loop< Capture | undefined, Extract | undefined @@ -510,5 +513,18 @@ export function collectClassInformation( const end = scope?.range.end ?? ast.range.end; return finishDefinition(state, scope, active, { start: end, end }, 'incomplete'); - }, progress.collected).information; + }, collected); +} + +/** 通常の関数スコープごとに独立して、構文上のコマンドからクラス宣言を解釈する。 */ +export function collectClassInformation( + ast: FileNode, +): ReadonlyMap { + const initial: CollectionProgress = { + collected: { captures: makeMap(), information: makeMap(), published: makeMap() }, + functionScopes: null, + standaloneCommand: null, + }; + const progress = foldAst(ast, initial, collectNode); + return finishOpenDefinitions(ast, progress.collected).information; } diff --git a/ls/server/test/connection/classApi.test.ts b/ls/server/test/connection/classApi.test.ts index f14cd532..da4c6ede 100644 --- a/ls/server/test/connection/classApi.test.ts +++ b/ls/server/test/connection/classApi.test.ts @@ -69,7 +69,7 @@ describe('class API visibility', () => { expect(items?.map((item) => item.label).toSorted()).toEqual(publicCommands); }); - test('private表示を有効にすると内部24関数も参照できる', () => { + test('private表示を有効にすると内部27関数も参照できる', () => { const scenario = fixture(); const names = zCompletion({ ...scenario, showPrivateFunctions: true })?.map((item) => item.label) ?? []; @@ -77,8 +77,8 @@ describe('class API visibility', () => { name.split('.').some((segment) => segment.startsWith('_')), ); - expect(names).toHaveLength(32); - expect(internal).toHaveLength(24); + expect(names).toHaveLength(35); + expect(internal).toHaveLength(27); expect(internal).toContain('z.cls.instance._call'); expect(internal).toContain('z.cls.capture._start'); expect(names).not.toContain('z.cls.instance.call'); From 25ef70e2cdaa0995dd5ed5f5a73591ab0e59eff0 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Wed, 18 Nov 2026 15:27:47 +0900 Subject: [PATCH 19/21] fix: resolve expanded class instance member commands --- ls/server/src/diagnostics/calls.ts | 18 ++-- ls/server/src/diagnostics/classes.ts | 105 +++++++++++++++++++++ ls/server/src/diagnostics/self.ts | 55 +---------- ls/server/test/diagnostics/classes.test.ts | 59 +++++++++++- 4 files changed, 179 insertions(+), 58 deletions(-) diff --git a/ls/server/src/diagnostics/calls.ts b/ls/server/src/diagnostics/calls.ts index 502ae7bb..c88b37ed 100644 --- a/ls/server/src/diagnostics/calls.ts +++ b/ls/server/src/diagnostics/calls.ts @@ -17,7 +17,7 @@ import type { ZshFileHydration } from '../zshHydrator'; import { documentationOf } from '../zshHydrator'; import type { FunctionDefinitionNode, SimpleCommandNode, WordNode } from '../zshParser/ast'; import type { SourceRange } from '../zshParser/lexer'; -import type { ClassCommandTarget } from './classes'; +import { classMemberReference, resolveInstanceCommand, type ClassCommandTarget } from './classes'; import { isAliasReference, isKnownShellCommand, type ResolutionContext } from './commandResolution'; import type { IgnoreControls } from './controls'; import { ignored } from './controls'; @@ -206,12 +206,18 @@ export function analyzeCalls( const word = command.commandName?.word; if (!word) return previous; - const self = functionCommand(command) ? resolveSelfCommand(file, word, scopes) : null; - if (self) { - if (self.target) { + const reference = functionCommand(command) ? classMemberReference(word) : null; + const member = reference + ? (resolveInstanceCommand(file, word, reference, context.classFiles) ?? + (reference.binding === 'self' + ? resolveSelfCommand(file, word, reference.member, scopes) + : null)) + : null; + if (member) { + if (member.target) { return { ...previous, - classTargets: setEntry(previous.classTargets, command, [self.target]), + classTargets: setEntry(previous.classTargets, command, [member.target]), }; } @@ -224,7 +230,7 @@ export function analyzeCalls( code: 'undefined-command', range: protocolRange(mapRange(word.range)), source: 'z-ls', - message: self.name + ' is not defined in class ' + self.definition.name + '.', + message: member.name + ' is not defined in class ' + member.definition.name + '.', }), }; } diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts index 4a1d93ba..8e40bebf 100644 --- a/ls/server/src/diagnostics/classes.ts +++ b/ls/server/src/diagnostics/classes.ts @@ -1,4 +1,7 @@ import { castDraft } from 'immer'; +import { decodeLiteral } from '../embeddedCode/literal'; +import { classMethodAt, type ZshFileHydration } from '../zshHydrator'; +import { locate, type WordNode, type WordPartNode } from '../zshParser/ast'; import { makeMap, produce } from '../util/collections'; import type { ClassAttribute, @@ -50,6 +53,108 @@ export function classCommands(files: readonly ClassFileHydration[]): ClassComman }); } +function staticText(word: WordNode, parts: readonly WordPartNode[]): string | null { + return parts.reduce((text, part) => { + if (text === null || part.kind !== 'stringLiteral') return null; + + const segment: WordNode = { ...word, range: part.range, raw: part.value, parts: [part] }; + const value = decodeLiteral(segment, true)?.text; + return value === undefined ? null : text + value; + }, ''); +} + +/** 実体IDを展開する変数と、リテラルで書かれたメンバー名を取得する。 */ +export function classMemberReference( + word: WordNode, +): { readonly binding: string; readonly member: string } | null { + const index = word.parts.findIndex((part) => part.kind !== 'stringLiteral'); + const part = word.parts[index]; + if (!part || staticText(word, word.parts.slice(0, index)) !== '') return null; + + const binding = + part.kind === 'variableReference' + ? part.name.value + : part.kind === 'parameterExpansion' + ? /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(part.raw)?.[1] + : undefined; + if (!binding) return null; + + const suffix = staticText(word, word.parts.slice(index + 1)); + return suffix && /^\.[A-Za-z0-9_.]+$/.test(suffix) ? { binding, member: suffix.slice(1) } : null; +} + +export function memberTarget( + definition: ClassDefinition, + name: string, + instance: ClassInstance | null, +): ClassCommandTarget | null { + const method = definition.methods.find((candidate) => candidate.name === name); + if (method) return { definition, instance, member: method, operation: 'method' }; + + const operation = name.endsWith('.get') ? 'get' : name.endsWith('.set') ? 'set' : null; + if (!operation) return null; + + const attributeName = name.slice(0, -operation.length - 1); + const attribute = definition.attributes.find((candidate) => candidate.name === attributeName); + return attribute ? { definition, instance, member: attribute, operation } : null; +} + +/** 呼び出しに先行する同一スコープの束縛を解決する。 */ +export function resolveInstanceCommand( + file: ZshFileHydration, + word: WordNode, + reference: NonNullable>, + files: readonly ClassFileHydration[], +): { + readonly definition: ClassDefinition; + readonly name: string; + readonly target: ClassCommandTarget | null; +} | null { + const offset = word.range.start.offset; + const candidates = file.classes.instances.filter( + (instance) => + instance.name === reference.binding && instance.declaration.range.end.offset <= offset, + ); + if (candidates.length === 0) return null; + + const location = locate(file.query, offset); + if (location?.kind !== 'syntax') return null; + + const scope = location.path.findLast((node) => node.kind === 'functionDefinition') ?? null; + const method = classMethodAt(file.classes, scope, offset); + const scoped = candidates.filter(({ scope: instanceScope }) => { + if (method) + return ( + instanceScope.kind === 'classMethod' && instanceScope.declaration === method.declaration + ); + if (scope) return instanceScope.kind === 'function' && instanceScope.declaration === scope; + return instanceScope.kind === 'file'; + }); + if (scoped.length !== 1) return null; + + const [instance] = scoped; + const declaration = locate(file.query, instance.declaration.range.start.offset); + if (declaration?.kind !== 'syntax') return null; + + const list = declaration.path.findLast((node) => node.kind === 'list'); + if (!list || !location.path.includes(list)) return null; + + for (let index = files.length - 1; index >= 0; index--) { + const definition = files[index].definitions.findLast( + (candidate) => candidate.name === instance.className && candidate.state === 'published', + ); + if (definition) { + return { + definition, + name: '$' + reference.binding + '.' + reference.member, + target: memberTarget(definition, reference.member, instance), + }; + } + } + + return null; +} + /** クラス宣言と実体の束縛が同じノードを参照する間だけ、解決コンテキストを再利用する。 */ export function sameClassFiles( left: readonly ClassFileHydration[], diff --git a/ls/server/src/diagnostics/self.ts b/ls/server/src/diagnostics/self.ts index 0d2542ea..ad1fe413 100644 --- a/ls/server/src/diagnostics/self.ts +++ b/ls/server/src/diagnostics/self.ts @@ -1,4 +1,3 @@ -import { decodeLiteral } from '../embeddedCode/literal'; import type { ClassDefinition, ClassFileHydration, @@ -6,42 +5,10 @@ import type { ZshFileHydration, } from '../zshHydrator'; import { classMethodAt } from '../zshHydrator'; -import type { AstNode, FunctionDefinitionNode, WordNode, WordPartNode } from '../zshParser/ast'; +import type { AstNode, FunctionDefinitionNode, WordNode } from '../zshParser/ast'; import { locate } from '../zshParser/ast'; import type { CallScope } from './calls'; -import type { ClassCommandTarget } from './classes'; - -function staticText(word: WordNode, parts: readonly WordPartNode[]): string | null { - return parts.reduce((text, part) => { - if (text === null || part.kind !== 'stringLiteral') return null; - - const segment: WordNode = { ...word, range: part.range, raw: part.value, parts: [part] }; - const value = decodeLiteral(segment, true)?.text; - return value === undefined ? null : text + value; - }, ''); -} - -function selfMemberName(word: WordNode): string | null { - const index = word.parts.findIndex( - (part) => - (part.kind === 'variableReference' && part.name.value === 'self') || - (part.kind === 'parameterExpansion' && part.raw === '${self}'), - ); - if (index < 0 || staticText(word, word.parts.slice(0, index)) !== '') return null; - - const suffix = staticText(word, word.parts.slice(index + 1)); - if (!suffix?.startsWith('.') || suffix.length === 1) return null; - - const staticName = [...suffix].every( - (char) => - char === '.' || - char === '_' || - (char >= 'a' && char <= 'z') || - (char >= 'A' && char <= 'Z') || - (char >= '0' && char <= '9'), - ); - return staticName ? suffix.slice(1) : null; -} +import { memberTarget, type ClassCommandTarget } from './classes'; function shadowsSelf(path: readonly AstNode[], offset: number, start: number): boolean { return path.some( @@ -142,33 +109,19 @@ function owningClass( return null; } -function memberTarget(definition: ClassDefinition, name: string): ClassCommandTarget | null { - const method = definition.methods.find((candidate) => candidate.name === name); - if (method) return { definition, instance: null, member: method, operation: 'method' }; - - const operation = name.endsWith('.get') ? 'get' : name.endsWith('.set') ? 'set' : null; - if (!operation) return null; - - const attributeName = name.slice(0, -operation.length - 1); - const attribute = definition.attributes.find((candidate) => candidate.name === attributeName); - return attribute ? { definition, instance: null, member: attribute, operation } : null; -} - /** 実際の所有メソッドが分かるself参照だけを、共有するメンバー宣言へ結び付ける。 */ export function resolveSelfCommand( file: ZshFileHydration, word: WordNode, + name: string, scopes: readonly CallScope[], ): { readonly definition: ClassDefinition; readonly name: string; readonly target: ClassCommandTarget | null; } | null { - const name = selfMemberName(word); - if (!name) return null; - const definition = owningClass(file, word, scopes); return definition - ? { definition, name: '$self.' + name, target: memberTarget(definition, name) } + ? { definition, name: '$self.' + name, target: memberTarget(definition, name, null) } : null; } diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index b95f5960..ba68bf10 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -131,7 +131,7 @@ describe('class DSL command diagnostics', () => { test('メソッドの編集で未編集の呼出元を再診断する', () => { const scenario = fixture( - 'z.cls.new Counter counter\ncounter.increment\n', + 'z.cls.new Counter counter\n$counter.increment\n', classApi + counterClass, ); @@ -358,6 +358,63 @@ describe('hydrated class command targets', () => { expect(targets[0].member.declaration.commandName?.word.raw).toBe('z.cls.fn'); }); + test('実体IDを展開する呼び出しがメソッドと属性を解決する', () => { + const scenario = fixture( + [ + 'z.cls.new Counter counter && $counter.increment', + '"$counter.increment"', + '${counter}.count.get', + '"$counter.count.set" 3', + '$counter.missing', + '$unknown.missing', + '${counter:-other}.missing', + '$counter.$member', + '', + ].join('\n'), + classApi + counterClass, + ); + const report = scenario.diagnostics.files.get(scenario.document.uri); + if (!report) throw new Error('Expected caller diagnostics'); + const analysis = analyzeCalls( + scenario.snapshot, + report.file, + report.facts.calls, + scenario.diagnostics.context, + ); + const targets = [...analysis.classTargets.values()].flat(); + + expect( + targets.map(({ instance, member, operation }) => [instance?.name, member.name, operation]), + ).toEqual([ + ['counter', 'increment', 'method'], + ['counter', 'increment', 'method'], + ['counter', 'count', 'get'], + ['counter', 'count', 'set'], + ]); + expect(semantic(scenario.items)).toMatchObject([ + { + message: '$counter.missing is not defined in class Counter.', + range: { start: { line: 4 } }, + }, + ]); + }); + + test('初期化より前や別の関数の同名変数から実体を推測しない', () => { + const scenario = fixture( + [ + '$counter.unknown', + 'z.cls.new Counter counter', + 'other() { local counter=some_command; $counter.unknown; }', + 'if false; then z.cls.new Counter conditional; fi', + '$conditional.unknown', + '', + ].join('\n'), + classApi + counterClass, + ); + + expect(semantic(scenario.items)).toEqual([]); + }); + test('コード引数内の実体は外側のクラスを使い、外側へ漏れない', () => { const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; const scenario = fixture( From 99b623ec38672582ce7ab3fb7bc0a1a659db7a83 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Wed, 18 Nov 2026 15:30:25 +0900 Subject: [PATCH 20/21] test: verify class completion without fixed API counts --- ls/server/test/connection/classApi.test.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/ls/server/test/connection/classApi.test.ts b/ls/server/test/connection/classApi.test.ts index da4c6ede..732436a6 100644 --- a/ls/server/test/connection/classApi.test.ts +++ b/ls/server/test/connection/classApi.test.ts @@ -61,24 +61,27 @@ function fixture(content = 'z.cls.¦\n') { }; } +function privateCommand(name: string): boolean { + return name.split('.').some((segment) => segment.startsWith('_')); +} + describe('class API visibility', () => { - test('通常の補完は実際の公開DSLの8関数だけを返す', () => { + test('通常の補完は公開DSLを表示し、内部関数を隠す', () => { const scenario = fixture(); const items = zCompletion({ ...scenario, showPrivateFunctions: false }); - expect(items?.map((item) => item.label).toSorted()).toEqual(publicCommands); + const names = items?.map((item) => item.label) ?? []; + expect(names).toEqual(expect.arrayContaining(publicCommands)); + expect(names.filter(privateCommand)).toEqual([]); }); - test('private表示を有効にすると内部27関数も参照できる', () => { + test('private表示を有効にすると公開DSLと内部関数を参照できる', () => { const scenario = fixture(); const names = zCompletion({ ...scenario, showPrivateFunctions: true })?.map((item) => item.label) ?? []; - const internal = names.filter((name) => - name.split('.').some((segment) => segment.startsWith('_')), - ); + const internal = names.filter(privateCommand); - expect(names).toHaveLength(35); - expect(internal).toHaveLength(27); + expect(names).toEqual(expect.arrayContaining(publicCommands)); expect(internal).toContain('z.cls.instance._call'); expect(internal).toContain('z.cls.capture._start'); expect(names).not.toContain('z.cls.instance.call'); From 58e105e528ff27b864b714097a09cb060415aa63 Mon Sep 17 00:00:00 2001 From: milkeclair Date: Wed, 18 Nov 2026 15:46:07 +0900 Subject: [PATCH 21/21] fix: resolve class members only through instance ID expansion --- ls/server/src/diagnostics/README.md | 8 +- ls/server/src/diagnostics/calls.ts | 9 - ls/server/src/diagnostics/classes.ts | 37 ---- .../src/diagnostics/commandResolution.ts | 2 - ls/server/src/diagnostics/snapshot.ts | 4 +- ls/server/src/embeddedCode/index.ts | 2 - ls/server/test/diagnostics/classes.test.ts | 182 ++++++++++++------ 7 files changed, 124 insertions(+), 120 deletions(-) diff --git a/ls/server/src/diagnostics/README.md b/ls/server/src/diagnostics/README.md index 58a497d5..5391d428 100644 --- a/ls/server/src/diagnostics/README.md +++ b/ls/server/src/diagnostics/README.md @@ -59,7 +59,7 @@ ASTの所有関係、引数の契約、制御コメント、snapshotの再利用 hydratorが通常の構文コマンドへクラスの意味を付加し、 ファイルごとのクラス・メンバー・実体の索引を提供します。 診断はこの索引を保持し、DSLを再認識する処理を持ちません。 -公開済みの定義からメソッド・属性get/setを解決し、呼出し解析はメンバーと実体の宣言元を返します。 +呼び出しが `$counter.increment` や `${counter}.count.get` の形であれば、先行する `z.cls.new` の束縛と公開済みクラスを照合します。呼び出し解析はメンバーと実体の宣言元を返します。 コンテキストの再利用では、クラス宣言と束縛が現在のASTを参照していることを確認します。 同じ名前のまま変更した場合も解決先を更新し、古いASTの参照を残しません。 @@ -68,13 +68,13 @@ hydratorが通常の構文コマンドへクラスの意味を付加し、 `codePrograms`の各要素の`file.classes`から、コード引数のクラス索引を参照できます。 コード引数は外側のクラス定義を継承しますが、そのコードでの定義・実体はそのプログラム内に保ちます。 -同じ変数名で静的に観測したクラスは候補として集め、動的な参照展開は動的コマンドとして扱います。 +同じ構文スコープで先行する束縛を一つに絞れれば、そこからクラスを特定します。束縛が不明な呼び出しは動的コマンドとして扱います。 ソースを実行したり、条件分岐後の変数の型を再現したりする解析は行いません。 属性の初期値は必須の名前付き引数`default=`で指定し、省略は通常の関数引数の診断で報告します。 -不正な属性を含むクラスと、入れ子や同じ構文スコープでの重複によって拒否した定義からは、生成コマンドを作りません。 +不正な属性を含むクラスや、入れ子や同じスコープでの重複で拒否されたクラスは、公開済みクラスの照合から除外します。 `$self`によるメソッドと属性の呼出しは、実際の所有メソッドからクラスを確定できる場合に共有の解決先へ結び付けます。 未定義のメンバーは`undefined-command`として、元のWordまたはコード引数内の位置へ診断します。 `ClassCommandTarget.instance`は、具体的な実体が実行時に決まるself参照ではnullです。 -通常の実体変数名から解決した場合は、従来どおり実体宣言を参照します。 +変数展開から実体を特定した場合は、その宣言を参照します。`counter.increment` は通常のコマンド名として解決します。 diff --git a/ls/server/src/diagnostics/calls.ts b/ls/server/src/diagnostics/calls.ts index c88b37ed..b2864d62 100644 --- a/ls/server/src/diagnostics/calls.ts +++ b/ls/server/src/diagnostics/calls.ts @@ -281,15 +281,6 @@ export function analyzeCalls( }; } - const generated = functionCommand(command) ? context.classCommands.get(name) : undefined; - - if (generated) { - return { - ...previous, - classTargets: setEntry(previous.classTargets, command, generated), - }; - } - if (context.autoloads.has(name) && functionCommand(command)) { return previous; } diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts index 8e40bebf..544a4f0b 100644 --- a/ls/server/src/diagnostics/classes.ts +++ b/ls/server/src/diagnostics/classes.ts @@ -1,8 +1,6 @@ -import { castDraft } from 'immer'; import { decodeLiteral } from '../embeddedCode/literal'; import { classMethodAt, type ZshFileHydration } from '../zshHydrator'; import { locate, type WordNode, type WordPartNode } from '../zshParser/ast'; -import { makeMap, produce } from '../util/collections'; import type { ClassAttribute, ClassDefinition, @@ -18,41 +16,6 @@ export type ClassCommandTarget = { readonly member: ClassMethod | ClassAttribute; readonly operation: 'method' | 'get' | 'set'; }; -export type ClassCommandTargets = ReadonlyMap; - -/** 公開済みクラスだけを解決し、宣言ノードとメンバーの定義元を参照先に保持する。 */ -export function classCommands(files: readonly ClassFileHydration[]): ClassCommandTargets { - const definitions = makeMap( - files.flatMap((file) => - file.definitions - .filter((definition) => definition.state === 'published') - .map((definition) => [definition.name, definition]), - ), - ); - return produce(makeMap(), (draft) => { - for (const file of files) { - for (const instance of file.instances) { - const definition = definitions.get(instance.className); - if (!definition) continue; - - for (const member of [...definition.methods, ...definition.attributes]) { - const operations: readonly ClassCommandTarget['operation'][] = - member.kind === 'classMethod' ? ['method'] : ['get', 'set']; - - for (const operation of operations) { - const suffix = operation === 'method' ? '' : '.' + operation; - const name = instance.name + '.' + member.name + suffix; - const targets = draft.get(name) ?? []; - - targets.push(castDraft({ definition, member, instance, operation })); - draft.set(name, targets); - } - } - } - } - }); -} - function staticText(word: WordNode, parts: readonly WordPartNode[]): string | null { return parts.reduce((text, part) => { if (text === null || part.kind !== 'stringLiteral') return null; diff --git a/ls/server/src/diagnostics/commandResolution.ts b/ls/server/src/diagnostics/commandResolution.ts index 948f7b51..9b0a0679 100644 --- a/ls/server/src/diagnostics/commandResolution.ts +++ b/ls/server/src/diagnostics/commandResolution.ts @@ -2,14 +2,12 @@ import fs from 'node:fs'; import path from 'node:path'; import type { ClassFileHydration } from '../zshHydrator'; import type { SimpleCommandNode, WordNode } from '../zshParser/ast'; -import type { ClassCommandTargets } from './classes'; import type { ShellEnvironment } from './environment'; import type { Declarations } from './facts'; export type ResolutionContext = Declarations & { readonly environment: ShellEnvironment; readonly projectRoot: string; - readonly classCommands: ClassCommandTargets; readonly classFiles: readonly ClassFileHydration[]; }; diff --git a/ls/server/src/diagnostics/snapshot.ts b/ls/server/src/diagnostics/snapshot.ts index a1ec51c9..d5d3c8b7 100644 --- a/ls/server/src/diagnostics/snapshot.ts +++ b/ls/server/src/diagnostics/snapshot.ts @@ -5,7 +5,7 @@ import type { FunctionSnapshot } from '../refreshFunctions/main'; import type { FunctionTargets } from '../refreshFunctions/target'; import type { ZshFileHydration } from '../zshHydrator'; import type { ResolutionContext } from './calls'; -import { classCommands, sameClassFiles } from './classes'; +import { sameClassFiles } from './classes'; import { sameCallContracts } from './contracts'; import { collectIgnoreControls, ignored } from './controls'; import type { ShellEnvironment } from './environment'; @@ -38,7 +38,6 @@ export function createDiagnosticSnapshot(): DiagnosticSnapshot { context: { environment: emptyShellEnvironment(), projectRoot: '', - classCommands: new Map(), classFiles: [], aliases: new Set(), globalAliases: new Set(), @@ -86,7 +85,6 @@ function resolutionContext( ...declarations, environment, projectRoot, - classCommands: classCommands(classFiles), classFiles, }; } diff --git a/ls/server/src/embeddedCode/index.ts b/ls/server/src/embeddedCode/index.ts index a19934df..f8734e7c 100644 --- a/ls/server/src/embeddedCode/index.ts +++ b/ls/server/src/embeddedCode/index.ts @@ -2,7 +2,6 @@ import { appendItems, collectArray } from '../util/collections'; import { protocolRange } from '../connection/ast/cursor'; import type { CallScope, ResolutionContext } from '../diagnostics/calls'; import { analyzeCalls } from '../diagnostics/calls'; -import { classCommands } from '../diagnostics/classes'; import type { IgnoreControls } from '../diagnostics/controls'; import { collectIgnoreControls, ignored } from '../diagnostics/controls'; import type { Declarations } from '../diagnostics/facts'; @@ -131,7 +130,6 @@ function inheritedContext( return { ...parent, classFiles, - classCommands: hasClassDeclarations ? classCommands(classFiles) : parent.classCommands, aliases: declarations.aliases.size ? new Set([...parent.aliases, ...declarations.aliases]) : parent.aliases, diff --git a/ls/server/test/diagnostics/classes.test.ts b/ls/server/test/diagnostics/classes.test.ts index ba68bf10..84051813 100644 --- a/ls/server/test/diagnostics/classes.test.ts +++ b/ls/server/test/diagnostics/classes.test.ts @@ -10,7 +10,7 @@ import { readShellEnvironment, emptyShellEnvironment } from '../../src/diagnosti import type { ShellEnvironment } from '../../src/diagnostics/environment'; import { validateTextDocument } from '../../src/diagnostics/main'; import { createZshFileHydration } from '../../src/zshHydrator'; -import { classCommands, sameClassFiles } from '../../src/diagnostics/classes'; +import { sameClassFiles } from '../../src/diagnostics/classes'; import { analyzeCalls } from '../../src/diagnostics/calls'; const roots: string[] = []; @@ -101,14 +101,14 @@ describe('class DSL command diagnostics', () => { test('別ファイルのクラスから生成されるメソッドと属性を認識し、タイプミスは診断する', () => { const scenario = fixture( - 'z.cls.new Counter counter\ncounter.increment\ncounter.count.get\ncounter.count.set 3\ncounter.typo\n', + 'z.cls.new Counter counter\n$counter.increment\n$counter.count.get\n$counter.count.set 3\n$counter.typo\n', classApi + counterClass, ); expect(semantic(scenario.items)).toMatchObject([ { code: 'undefined-command', - message: 'counter.typo is not defined in the project or shell environment.', + message: '$counter.typo is not defined in class Counter.', }, ]); @@ -166,7 +166,7 @@ describe('class DSL command diagnostics', () => { 'helper() { z.cls.fn.done }\n print "z.cls.fn.done"\n z.cls.fn imaginary', ); const scenario = fixture( - 'z.cls.new Counter counter\ncounter.increment\ncounter.imaginary\n', + 'z.cls.new Counter counter\n$counter.increment\n$counter.imaginary\n', classApi + source, ); @@ -187,21 +187,28 @@ describe('scoped class references', () => { ].join('\n'); const source = [ 'z.cls.new Counter counter', - 'counter.increment', + '$counter.increment', 'inner() {', ' local counter=""', ' z.cls.new ArrayBox counter', - ' counter.fill', + ' $counter.fill', + ' $counter.increment', '}', - 'counter.count.get', + '$counter.count.get', + '$counter.fill', '', ].join('\n'); - expect(semantic(fixture(source, classApi + counterClass + arrayClass).items)).toEqual([]); + const scenario = fixture(source, classApi + counterClass + arrayClass); + + expect(semantic(scenario.items).map((item) => item.message)).toEqual([ + '$counter.increment is not defined in class ArrayBox.', + '$counter.fill is not defined in class Counter.', + ]); }); test('プロジェクト外の文書はプロジェクトと文書内のクラスを使い、文書内の定義は外へ漏れない', () => { - const scenario = fixture('z.cls.new Local leaked\nleaked.value\n', classApi + counterClass); + const scenario = fixture('z.cls.new Local leaked\n$leaked.value\n', classApi + counterClass); const outside = TextDocument.create( pathToFileURL(path.join(path.dirname(scenario.root), 'outside.zsh')).href, 'shellscript', @@ -211,9 +218,11 @@ describe('scoped class references', () => { ' z.cls.fn value "REPLY=1"', ' z.cls.drew', 'z.cls.new Counter counter', - 'counter.increment', + '$counter.increment', 'z.cls.new Local local_object', - 'local_object.value', + '$local_object.value', + '$counter.value', + '$local_object.increment', '', ].join('\n'), ); @@ -230,15 +239,21 @@ describe('scoped class references', () => { }); expect(diagnostics.files.get(outside.uri)?.project).toBe(false); - expect(semantic(validateTextDocument({ diagnostics, textDocument: outside }))).toEqual([]); expect( - semantic(validateTextDocument({ diagnostics, textDocument: scenario.document })), - ).toMatchObject([ - { - code: 'undefined-command', - message: 'leaked.value is not defined in the project or shell environment.', - }, + semantic(validateTextDocument({ diagnostics, textDocument: outside })).map( + (item) => item.message, + ), + ).toEqual([ + '$counter.value is not defined in class Counter.', + '$local_object.increment is not defined in class Local.', ]); + + const report = diagnostics.files.get(scenario.document.uri); + if (!report) throw new Error('Expected caller diagnostics'); + const analysis = analyzeCalls(snapshot, report.file, report.facts.calls, diagnostics.context); + + expect(semantic(report.items)).toEqual([]); + expect(analysis.classTargets.size).toBe(0); }); test('外側の関数の引数使用へメソッド内の引数を混ぜない', () => { @@ -287,39 +302,22 @@ describe('scoped class references', () => { }); describe('hydrated class command targets', () => { - test('別ファイルのクラスと実体を実際のメンバーノードへ結び付ける', () => { - const definitions = createZshFileHydration({ - sourceFile: '/defs.zsh', - file: 'defs.zsh', - content: counterClass, - }); - const bindings = createZshFileHydration({ - sourceFile: '/caller.zsh', - file: 'caller.zsh', - content: 'z.cls.new Counter object\n', - }); - const targets = classCommands([definitions.classes, bindings.classes]); - const method = targets.get('object.increment')?.[0]; - - expect(method?.definition).toBe(definitions.classes.definitions[0]); - expect(method?.member).toBe(definitions.classes.definitions[0].methods[0]); - expect(method?.instance).toBe(bindings.classes.instances[0]); - expect(method?.operation).toBe('method'); - expect(targets.get('object.count.set')?.[0].member).toBe( - definitions.classes.definitions[0].attributes[0], - ); - }); - - test('未公開と破棄済みのクラスからは解決先を生成しない', () => { + test('未公開と破棄済みのクラスからは解決先を取得しない', () => { for (const ending of ['', ' z.cls.abort\n']) { - const file = createZshFileHydration({ - sourceFile: 'x', - file: 'x', - content: - 'z.cls.draw Open\n z.cls.attr count default=0\n' + ending + 'z.cls.new Open object\n', - }); - - expect(classCommands([file.classes]).size).toBe(0); + const scenario = fixture( + 'z.cls.new Open object\n$object.count.get\n', + classApi + 'z.cls.draw Open\n z.cls.attr count default=0\n' + ending, + ); + const report = scenario.diagnostics.files.get(scenario.document.uri); + if (!report) throw new Error('Expected caller diagnostics'); + const analysis = analyzeCalls( + scenario.snapshot, + report.file, + report.facts.calls, + scenario.diagnostics.context, + ); + + expect(analysis.classTargets.size).toBe(0); } }); @@ -338,9 +336,9 @@ describe('hydrated class command targets', () => { expect(sameClassFiles([empty.classes], [])).toBe(true); }); - test('呼出し解析がクラスのメンバー宣言を解決先として返す', () => { + test('呼出し解析が別ファイルのメソッドと属性の宣言を解決先として返す', () => { const scenario = fixture( - 'z.cls.new Counter object\nobject.increment\n', + 'z.cls.new Counter object\n$object.increment\n$object.count.set 1\n', classApi + counterClass, ); const report = scenario.diagnostics.files.get(scenario.document.uri); @@ -353,9 +351,62 @@ describe('hydrated class command targets', () => { ); const targets = [...analysis.classTargets.values()].flat(); - expect(targets).toHaveLength(1); - expect(targets[0].member).toMatchObject({ kind: 'classMethod', name: 'increment' }); - expect(targets[0].member.declaration.commandName?.word.raw).toBe('z.cls.fn'); + const definition = + scenario.snapshot.hydrator.files.get('definition.zsh')?.classes.definitions[0]; + if (!definition) throw new Error('Expected class definition'); + const instance = report.file.classes.instances[0]; + + expect(targets).toHaveLength(2); + expect(targets[0].definition).toBe(definition); + expect(targets[0].instance).toBe(instance); + expect(targets[0].member).toBe(definition.methods[0]); + expect(targets[1].definition).toBe(definition); + expect(targets[1].instance).toBe(instance); + expect(targets[1].member).toBe(definition.attributes[0]); + }); + + test('実体の変数名をそのまま使った呼び出しを未定義コマンドとして報告する', () => { + const scenario = fixture( + [ + 'typeset counter', + 'z.cls.new Counter counter', + '$counter.increment', + 'counter.increment', + '', + ].join('\n'), + classApi + counterClass, + ); + + expect(semantic(scenario.items)).toMatchObject([ + { + code: 'undefined-command', + message: 'counter.increment is not defined in the project or shell environment.', + range: { start: { line: 3, character: 0 } }, + }, + ]); + }); + + test('同名の通常関数が宣言されていれば通常の関数として解決する', () => { + const scenario = fixture( + ['typeset counter', 'z.cls.new Counter counter', 'counter.increment', ''].join('\n'), + classApi + counterClass + 'counter.increment() { :; }\n', + ); + const report = scenario.diagnostics.files.get(scenario.document.uri); + if (!report) throw new Error('Expected caller diagnostics'); + const analysis = analyzeCalls( + scenario.snapshot, + report.file, + report.facts.calls, + scenario.diagnostics.context, + ); + const command = report.facts.calls.find( + (call) => call.commandName?.word.raw === 'counter.increment', + ); + if (!command) throw new Error('Expected dotted command'); + + expect(semantic(scenario.items)).toEqual([]); + expect(analysis.targets.has(command)).toBe(true); + expect(analysis.classTargets.has(command)).toBe(false); }); test('実体IDを展開する呼び出しがメソッドと属性を解決する', () => { @@ -418,12 +469,15 @@ describe('hydrated class command targets', () => { test('コード引数内の実体は外側のクラスを使い、外側へ漏れない', () => { const api = '# $1 [code]: body\nrun() { eval "$1" }\n'; const scenario = fixture( - "run 'z.cls.new Counter inside; inside.increment'\ninside.increment\n", + "run 'z.cls.new Counter inside; $inside.missing'\n$inside.missing\n", classApi + counterClass + api, ); expect(semantic(scenario.items)).toHaveLength(1); - expect(semantic(scenario.items)[0].range.start.line).toBe(1); + expect(semantic(scenario.items)[0]).toMatchObject({ + message: '$inside.missing is not defined in class Counter.', + range: { start: { line: 0 } }, + }); }); test('コード引数内のクラスはそのコード内で解決し、プロジェクトへ漏れない', () => { @@ -433,15 +487,17 @@ describe('hydrated class command targets', () => { ' z.cls.fn value "REPLY=1"', ' z.cls.drew', 'z.cls.new Local local_object', - "local_object.value'", + "$local_object.missing'", 'z.cls.new Local outside', - 'outside.value', + '$outside.missing', '', ].join('\n'); const scenario = fixture(text, classApi + api); expect(semantic(scenario.items)).toHaveLength(1); - expect(semantic(scenario.items)[0].message).toContain('outside.value'); + expect(semantic(scenario.items)[0].message).toBe( + '$local_object.missing is not defined in class Local.', + ); const report = scenario.diagnostics.files.get(scenario.document.uri); const program = report?.codePrograms.find((entry) => @@ -475,7 +531,7 @@ describe('hydrated class command targets', () => { ).toBe('aborted'); }); - test('拒否した定義の属性コマンドを生成せず外側の属性を解決する', () => { + test('公開済みクラスの属性を解決し、拒否されたクラスの属性を報告する', () => { const definitions = [ 'z.cls.draw Outer', ' z.cls.draw Rejected', @@ -486,14 +542,14 @@ describe('hydrated class command targets', () => { '', ].join('\n'); const scenario = fixture( - ['z.cls.new Outer object', 'object.kept.get', 'object.leaked.get', ''].join('\n'), + ['z.cls.new Outer object', '$object.kept.get', '$object.leaked.get', ''].join('\n'), classApi + definitions, ); expect(semantic(scenario.items)).toMatchObject([ { code: 'undefined-command', - message: 'object.leaked.get is not defined in the project or shell environment.', + message: '$object.leaked.get is not defined in class Outer.', }, ]); });