diff --git a/lib/cls/README.md b/lib/cls/README.md index 5e9b71cf..6bff97c0 100644 --- a/lib/cls/README.md +++ b/lib/cls/README.md @@ -151,6 +151,10 @@ DEBUGトラップと、実行タイミング・localtrapsの設定を復元し 実行時に保存する本体には元のコメントや整形を保持しません。 定義ファイルは通常のシェル構文を保つため、シンタックスハイライトと本体の診断を利用できます。 +z-lsは通常のASTへクラス・属性・メソッド・実体の意味情報を付加し、 +共有する索引から生成済みコマンドの定義元を解決します。 +メソッド本体の診断位置を保持し、引数で渡す本体は共通の[code]解析を利用します。 +動的な名前の解決には、既存の保守的な解析を適用します。 ## 実行時の費用 diff --git a/lib/cls/process.zsh b/lib/cls/process.zsh index c93d102a..845f7930 100644 --- a/lib/cls/process.zsh +++ b/lib/cls/process.zsh @@ -84,7 +84,7 @@ z.cls.attr() { # 引用しない本体の末尾には、独立した文としてz.cls.fn.doneを置く。 # # $1: メソッド名 -# $2?: 引数で指定する本体 +# $2? [code]: 引数で指定する本体 # REPLY: null # return: 0|1 # diff --git a/ls/server/src/diagnostics/README.md b/ls/server/src/diagnostics/README.md index b9cf8809..5391d428 100644 --- a/ls/server/src/diagnostics/README.md +++ b/ls/server/src/diagnostics/README.md @@ -53,3 +53,28 @@ ASTの所有関係、引数の契約、制御コメント、snapshotの再利用 ## 実装の役割 `facts.ts`で解析事実を集め、`commandResolution.ts`でシェルの名前と実行パスを解決します。`calls.ts`は関数参照・引数契約と診断を対応付け、`snapshot.ts`がファイル単位の報告と再利用を管理します。 + +## クラス定義 + +hydratorが通常の構文コマンドへクラスの意味を付加し、 +ファイルごとのクラス・メンバー・実体の索引を提供します。 +診断はこの索引を保持し、DSLを再認識する処理を持ちません。 +呼び出しが `$counter.increment` や `${counter}.count.get` の形であれば、先行する `z.cls.new` の束縛と公開済みクラスを照合します。呼び出し解析はメンバーと実体の宣言元を返します。 + +コンテキストの再利用では、クラス宣言と束縛が現在のASTを参照していることを確認します。 +同じ名前のまま変更した場合も解決先を更新し、古いASTの参照を残しません。 +引用しないメソッド本体は元の位置を保持し、hydratorの範囲索引から引数の所有関係を判定します。 +引数で渡す本体は[code]として共通の埋め込み解析へ渡し、元の位置へ診断を対応付けます。 + +`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 c66669c5..b2864d62 100644 --- a/ls/server/src/diagnostics/calls.ts +++ b/ls/server/src/diagnostics/calls.ts @@ -17,10 +17,12 @@ import type { ZshFileHydration } from '../zshHydrator'; import { documentationOf } from '../zshHydrator'; import type { FunctionDefinitionNode, SimpleCommandNode, WordNode } from '../zshParser/ast'; import type { SourceRange } from '../zshParser/lexer'; +import { classMemberReference, resolveInstanceCommand, type ClassCommandTarget } from './classes'; import { isAliasReference, isKnownShellCommand, type ResolutionContext } from './commandResolution'; 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'; @@ -135,6 +137,7 @@ export type CallAnalysisOptions = { export type CallAnalysis = { readonly diagnostics: readonly Diagnostics[]; readonly targets: ReadonlyMap; + readonly classTargets: ReadonlyMap; }; /** 埋め込みコードやworkspace外の定義はローカルに保ち、workspaceの参照先には追加しない。 */ @@ -197,17 +200,44 @@ export function analyzeCalls( const initial = { diagnostics: collectArray(), targets: makeMap(), + classTargets: makeMap(), }; const result = commands.reduce((previous, command) => { const word = command.commandName?.word; - const name = word && literalWord(word); + if (!word) return previous; + + 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, [member.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: member.name + ' is not defined in class ' + member.definition.name + '.', + }), + }; + } - if ( - !word || - !name || - (!word.quoted && word.raw.startsWith('=')) || - uncertainWord(word, context) - ) { + const name = literalWord(word); + + if (!name || (!word.quoted && word.raw.startsWith('=')) || uncertainWord(word, context)) { return previous; } @@ -244,7 +274,11 @@ export function analyzeCalls( ), ); - return { diagnostics, targets: setEntry(previous.targets, command, target) }; + return { + ...previous, + diagnostics, + targets: setEntry(previous.targets, command, target), + }; } if (context.autoloads.has(name) && functionCommand(command)) { @@ -269,7 +303,11 @@ export function analyzeCalls( : previous; }, initial); - return { diagnostics: result.diagnostics, targets: new Map(result.targets) }; + return { + diagnostics: result.diagnostics, + targets: new Map(result.targets), + classTargets: new Map(result.classTargets), + }; } /** 関数の参照先を必要としない呼び出し元向けに、既存の診断のみを返すAPIを保つ。 */ diff --git a/ls/server/src/diagnostics/classes.ts b/ls/server/src/diagnostics/classes.ts new file mode 100644 index 00000000..544a4f0b --- /dev/null +++ b/ls/server/src/diagnostics/classes.ts @@ -0,0 +1,135 @@ +import { decodeLiteral } from '../embeddedCode/literal'; +import { classMethodAt, type ZshFileHydration } from '../zshHydrator'; +import { locate, type WordNode, type WordPartNode } from '../zshParser/ast'; +import type { + ClassAttribute, + ClassDefinition, + ClassFileHydration, + ClassInstance, + ClassMethod, +} from '../zshHydrator/classes'; + +export type ClassCommandTarget = { + readonly definition: ClassDefinition; + // selfは所有クラスを確定できても、呼び出す実体は実行時に決まる。 + readonly instance: ClassInstance | null; + readonly member: ClassMethod | ClassAttribute; + readonly operation: 'method' | 'get' | 'set'; +}; +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[], + right: readonly ClassFileHydration[], +): boolean { + 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/commandResolution.ts b/ls/server/src/diagnostics/commandResolution.ts index 29d289f6..9b0a0679 100644 --- a/ls/server/src/diagnostics/commandResolution.ts +++ b/ls/server/src/diagnostics/commandResolution.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; +import type { ClassFileHydration } from '../zshHydrator'; import type { SimpleCommandNode, WordNode } from '../zshParser/ast'; import type { ShellEnvironment } from './environment'; import type { Declarations } from './facts'; @@ -7,6 +8,7 @@ import type { Declarations } from './facts'; export type ResolutionContext = Declarations & { readonly environment: ShellEnvironment; readonly projectRoot: string; + readonly classFiles: readonly ClassFileHydration[]; }; export function isAliasReference( diff --git a/ls/server/src/diagnostics/facts.ts b/ls/server/src/diagnostics/facts.ts index 9bf5fb5b..6d9ca1e0 100644 --- a/ls/server/src/diagnostics/facts.ts +++ b/ls/server/src/diagnostics/facts.ts @@ -11,8 +11,8 @@ import { protocolRange } from '../connection/ast/cursor'; import { literalWord } from '../refreshFunctions/word'; import { again, done, loop } from '../util/loop'; import { DiagnosticSeverity } from '../vscode_type'; -import type { ZshFileHydration } from '../zshHydrator'; -import { documentationOf } from '../zshHydrator'; +import type { ClassFileHydration, ZshFileHydration } from '../zshHydrator'; +import { classMethodAt, documentationOf } from '../zshHydrator'; import type { AstNode, FunctionDefinitionNode, @@ -36,6 +36,7 @@ export type FileFacts = { readonly calls: readonly SimpleCommandNode[]; readonly base: readonly Diagnostics[]; readonly declarations: Declarations; + readonly classes: ClassFileHydration; }; type DeclarationSets = { @@ -312,7 +313,9 @@ function collectNodeFacts( : scoped; const usage = current && declared.usages.get(current.definition); - if (!usage) return declared; + if (!usage || classMethodAt(file.classes, usage.definition, node.range.start.offset)) { + return declared; + } return { ...declared, @@ -375,6 +378,7 @@ export function collectFileFacts(file: ZshFileHydration): FileFacts { return { calls: facts.calls, base, + classes: file.classes, declarations: { aliases: new Set(sets.aliases), globalAliases: new Set(sets.globalAliases), diff --git a/ls/server/src/diagnostics/self.ts b/ls/server/src/diagnostics/self.ts new file mode 100644 index 00000000..ad1fe413 --- /dev/null +++ b/ls/server/src/diagnostics/self.ts @@ -0,0 +1,127 @@ +import type { + ClassDefinition, + ClassFileHydration, + ClassMethod, + ZshFileHydration, +} from '../zshHydrator'; +import { classMethodAt } from '../zshHydrator'; +import type { AstNode, FunctionDefinitionNode, WordNode } from '../zshParser/ast'; +import { locate } from '../zshParser/ast'; +import type { CallScope } from './calls'; +import { memberTarget, type ClassCommandTarget } from './classes'; + +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 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, +): { + readonly definition: ClassDefinition | null; + readonly blocked: boolean; +} { + const location = locate(file.query, offset); + const path = location?.kind === 'syntax' ? location.path : []; + const scope = + 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 : (owner?.definition ?? null), + blocked: scope !== null || shadowed, + }; +} + +/** 文字列のコードも元の所有関係から調べ、通常の関数を越えてselfの所属を推測しない。 */ +function owningClass( + file: ZshFileHydration, + word: WordNode, + scopes: readonly CallScope[], +): ClassDefinition | null { + const current = selfScopeAt(file, word.range.start.offset); + if (current.definition || current.blocked) return current.definition; + + for (const scope of scopes) { + const owner = selfScopeAt(scope.file, scope.offset); + if (owner.definition || owner.blocked) return owner.definition; + } + + return 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 definition = owningClass(file, word, scopes); + return definition + ? { definition, name: '$self.' + name, target: memberTarget(definition, name, null) } + : null; +} diff --git a/ls/server/src/diagnostics/snapshot.ts b/ls/server/src/diagnostics/snapshot.ts index 148b53e5..d5d3c8b7 100644 --- a/ls/server/src/diagnostics/snapshot.ts +++ b/ls/server/src/diagnostics/snapshot.ts @@ -5,6 +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 { sameClassFiles } from './classes'; import { sameCallContracts } from './contracts'; import { collectIgnoreControls, ignored } from './controls'; import type { ShellEnvironment } from './environment'; @@ -37,6 +38,7 @@ export function createDiagnosticSnapshot(): DiagnosticSnapshot { context: { environment: emptyShellEnvironment(), projectRoot: '', + classFiles: [], aliases: new Set(), globalAliases: new Set(), suffixAliases: new Set(), @@ -57,6 +59,7 @@ function resolutionContext( projectRoot: string, previous: ResolutionContext, ): ResolutionContext { + const classFiles = 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])), @@ -72,12 +75,18 @@ function resolutionContext( sameSet(declarations.globalAliases, previous.globalAliases) && sameSet(declarations.suffixAliases, previous.suffixAliases) && sameSet(declarations.autoloads, previous.autoloads) && - sameSet(declarations.builtins, previous.builtins) + sameSet(declarations.builtins, previous.builtins) && + sameClassFiles(classFiles, previous.classFiles) ) { return previous; } - return { ...declarations, environment, projectRoot }; + return { + ...declarations, + environment, + projectRoot, + classFiles, + }; } function suppressed( @@ -119,22 +128,18 @@ function diagnoseFile( snapshot: FunctionSnapshot, input: DiagnosticInput, facts: FileFacts, + projectFacts: readonly FileFacts[], context: ResolutionContext, revision: number, ): FileDiagnostics { - const local = input.project - ? context - : resolutionContext([facts], context.environment, context.projectRoot, context); const effective = input.project ? context - : { - ...context, - 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]), - }; + : resolutionContext( + [...projectFacts, facts], + context.environment, + context.projectRoot, + context, + ); const embedded = analyzeEmbeddedCode(snapshot, input.file, facts.calls, effective); return { @@ -197,7 +202,7 @@ export function refreshDiagnosticSnapshot({ return [[uri, cached]]; } - return [[uri, diagnoseFile(snapshot, input, current, context, revision)]]; + return [[uri, diagnoseFile(snapshot, input, current, projectFacts, context, revision)]]; }, ); const files: ReadonlyMap = new Map(entries); diff --git a/ls/server/src/embeddedCode/index.ts b/ls/server/src/embeddedCode/index.ts index b312b38d..f8734e7c 100644 --- a/ls/server/src/embeddedCode/index.ts +++ b/ls/server/src/embeddedCode/index.ts @@ -12,7 +12,7 @@ import { projectFileFunctions } from '../refreshFunctions/projection'; import type { FunctionTargets } from '../refreshFunctions/target'; import { again, done, loop } from '../util/loop'; import { DiagnosticSeverity } from '../vscode_type'; -import type { ZshFileHydration } from '../zshHydrator'; +import type { ClassFileHydration, ZshFileHydration } from '../zshHydrator'; import { createZshFileHydration } from '../zshHydrator'; import type { SimpleCommandNode, WordNode } from '../zshParser/ast'; import type { CodeArgument } from './arguments'; @@ -120,9 +120,16 @@ function embeddedSyntax(program: CodeProgram): readonly Diagnostics[] { function inheritedContext( parent: ResolutionContext, declarations: Declarations, + classes: ClassFileHydration, ): ResolutionContext { + const hasClassDeclarations = classes.definitions.length > 0 || classes.instances.length > 0; + const classFiles = hasClassDeclarations + ? appendItems(parent.classFiles, classes) + : parent.classFiles; + return { ...parent, + classFiles, aliases: declarations.aliases.size ? new Set([...parent.aliases, ...declarations.aliases]) : parent.aliases, @@ -195,7 +202,7 @@ function expandArgument( const pending: Pending = { file: child, calls: facts.calls, - context: inheritedContext(current.context, facts.declarations), + context: inheritedContext(current.context, facts.declarations, child.classes), program, scopes: [{ file: current.file, offset: argument.word.range.start.offset }, ...current.scopes], depth: current.depth + 1, diff --git a/ls/server/src/refreshFunctions/word.ts b/ls/server/src/refreshFunctions/word.ts index f2142f64..a8e2fae1 100644 --- a/ls/server/src/refreshFunctions/word.ts +++ b/ls/server/src/refreshFunctions/word.ts @@ -1,10 +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/zshHydrator/README.md b/ls/server/src/zshHydrator/README.md index 0b0a2502..3267d605 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,7 +72,7 @@ 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から参照します。 @@ -84,3 +84,64 @@ LSP接続はこのAPIを通して、ドキュメントと制御コメントの - `inputs.ts`: 開いた文書の選択とプロジェクト内のパス判定。 - `entry.ts`: ディスク・バッファの読込とfingerprint照合。 - `documentation`と`directive.ts`: ドキュメントと制御コメントの解釈。 +- `classes`: クラス宣言の意味情報と、最終ASTを参照するクラス索引。 + +## クラスの意味情報と索引 + +`hydrateAst`は、通常の`simpleCommand`に`classDefinition`、`classAttribute`、 +`classMethod`、`classInstance`の意味情報を付加します。 +コマンドの単語、関数の所有関係、構文の深さから判定し、ソース文字列を正規表現で走査しません。 +通常の構文種別、範囲、トークン、コメントの参照は保持します。 + +`classInformationOf(command)`で付加情報を取得できます。 +`createZshFileHydration`の`classes`は、クラス・メンバー・実体の宣言の索引です。 +名前、属性の初期値、所有スコープは返却AST内のノードを直接参照します。 +引数で指定した本体は元のWordを、本体を直接記述した場合はソース範囲と終了マーカーを保持します。 + +公開済み・破棄済み・未完了の定義を区別し、診断のコマンド解決には公開済みの定義だけを使います。 +動的または不正な名前を推測で確定しません。 +関数・メソッドの構文スコープと静的に現れた束縛を記録し、条件分岐後の実行状態や実行順は再現しません。 + +宣言の認識、実体の束縛、メンバー登録、終了マーカー、公開は別々のreadonlyな状態遷移です。 +役割別の索引構築は新しいコレクションを返し、既存のファイル索引へ追加しません。 +情報の付加後に索引を作り、子ノードが更新された場合も最終ASTを参照します。 +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`で収集を終了しません。 + +## メソッド内の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/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 new file mode 100644 index 00000000..558c43ca --- /dev/null +++ b/ls/server/src/zshHydrator/classes/collect.ts @@ -0,0 +1,530 @@ +import { castDraft } from 'immer'; +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 { + 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'; +import type { + ClassDefinition, + ClassDefinitionScopeLocation, + ClassInformation, + ClassScopeLocation, +} from './types'; + +type Member = { + readonly node: SimpleCommandNode; + readonly information: Extract; +}; +type Definition = { + readonly node: SimpleCommandNode; + readonly name: string; + readonly members: readonly Member[]; + readonly failed: boolean; +}; +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: 'rejected'; + readonly outer: Capture | undefined; + readonly methodDepth: number | null; + }; +type State = { + readonly captures: ReadonlyMap; + readonly information: ReadonlyMap; + readonly published: ReadonlyMap>; +}; + +type ClassDirective = { + readonly command: SimpleCommandNode; + readonly name: string; + readonly args: readonly (string | null)[]; + readonly depth: number; + readonly scope: FunctionDefinitionNode | undefined; + readonly standalone: boolean; +}; + +/** 実行時に予約した名前を、静的なクラスの識別子から除外する。 */ +function identifier(value: string | null | undefined): value is string { + 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; + }); +} + +/** 以前のASTを付加情報に保持しないよう、所有関係を位置で記録する。 */ +function scopeLocation(scope: FunctionDefinitionNode | undefined): ClassDefinitionScopeLocation { + return scope ? { kind: 'function', offset: scope.range.start.offset } : { kind: 'file' }; +} + +/** 以前の状態を変更せず、1つの構文スコープの収集状態を置き換える。 */ +function withCapture( + state: State, + scope: FunctionDefinitionNode | undefined, + capture: Capture | null, +): State { + const captures = produce(state.captures, (draft) => { + if (capture) { + draft.set(castDraft(scope), castDraft(capture)); + } else { + draft.delete(castDraft(scope)); + } + }); + + return { ...state, captures }; +} + +/** 宣言形式にかかわらず、元の状態を変えない共通の遷移でメンバーを追加する。 */ +function withMember( + state: State, + scope: FunctionDefinitionNode | undefined, + definition: Definition, + member: Member, +): State { + return withCapture(state, scope, { + kind: 'definition', + definition: { + ...definition, + members: appendItems(definition.members, member), + }, + }); +} + +/** 編集中に終了マーカーが欠けた場合も、本体のソース位置を保持する。 */ +function blockMethodFromCapture( + 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 finishDefinition( + state: State, + scope: FunctionDefinitionNode | undefined, + capture: Extract, + end: SourceRange, + status: ClassDefinition['state'], +): State { + const definition = capture.definition; + const members = + capture.kind === 'method' + ? appendItems(definition.members, blockMethodFromCapture(capture, end, false)) + : definition.members; + const information = produce(state.information, (draft) => { + draft.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) { + draft.set(member.node.range.start.offset, member.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つ読む。 */ +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', + ); + if (external) return null; + + const name = command.commandName && literalWord(command.commandName.word); + if (!name || !name.startsWith('z.cls.')) return null; + + 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 (!names.includes(name)) return null; + + return { + command, + name, + args: command.arguments.map((word) => literalWord(word)), + depth, + scope, + standalone, + }; +} + +/** 通常の関数または収集中のメソッドのスコープに、実体の束縛を記録する。 */ +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; + + const scope: ClassScopeLocation = + capture?.kind === 'method' + ? { kind: 'classMethod', offset: capture.node.range.start.offset } + : scopeLocation(directive.scope); + + return { + ...state, + information: setEntry(state.information, directive.command.range.start.offset, { + kind: 'classInstance', + name, + className, + scope, + }), + }; +} + +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 { + return isMethodEnd(directive, capture.depth) + ? withMember( + state, + directive.scope, + capture.definition, + blockMethodFromCapture(capture, directive.command.range, true), + ) + : state; +} + +/** クラス内で最初に現れた有効な属性宣言を保持する。 */ +function declareAttribute(directive: ClassDirective, definition: Definition, state: State): 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 (!attribute || !identifier(name) || duplicate) { + return withCapture(state, directive.scope, { + kind: 'definition', + definition: { ...definition, failed: true }, + }); + } + + return withMember(state, directive.scope, definition, { + node: directive.command, + information: { + kind: 'classAttribute', + name, + classOffset: definition.node.range.start.offset, + }, + }); +} + +/** 本体の収集を開始するか、引数で指定した本体の元の単語範囲を保持する。 */ +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; + + 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 + ? finishDefinition(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, + }); + } + + 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 }, + }, + }); +} + +/** 定義中のクラスに、メンバー登録または公開の状態遷移を適用する。 */ +function applyDefinitionDirective( + directive: ClassDirective, + capture: Extract, + state: State, +): State { + switch (directive.name) { + case 'z.cls.attr': + return declareAttribute(directive, capture.definition, state); + case 'z.cls.fn': + return declareMethod(directive, capture, state); + case 'z.cls.drew': + return directive.args.length === 0 + ? 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'); + default: + return state; + } +} + +/** 拒否した定義のメンバーや終端を、外側で収集中のクラスへ混ぜない。 */ +function applyRejectedDirective( + directive: ClassDirective, + capture: Extract, + state: State, +): State { + if (!directive.standalone) return state; + + if (capture.methodDepth !== null) { + return isMethodEnd(directive, 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, 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') { + 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; +} + +type FunctionScope = { + readonly node: FunctionDefinitionNode; + readonly depth: number; +}; +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; +} + +/** 構文スコープを進め、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; + + 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; + + return { + state: { + collected: collectCommand( + node, + depth, + functionScopes?.value.node, + standalone === node, + collected, + ), + functionScopes, + standaloneCommand: standalone, + }, + }; +} + +/** 終端のない定義を、それぞれの所有スコープの末尾で確定する。 */ +function finishOpenDefinitions(ast: FileNode, collected: State): State { + return [...collected.captures].reduce((state, [scope, capture]) => { + const active = loop< + Capture | undefined, + Extract | undefined + >(capture, (current) => (current?.kind === 'rejected' ? again(current.outer) : done(current))); + if (!active) return state; + + const end = scope?.range.end ?? ast.range.end; + return finishDefinition(state, scope, active, { start: end, end }, 'incomplete'); + }, 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/src/zshHydrator/classes/index.ts b/ls/server/src/zshHydrator/classes/index.ts new file mode 100644 index 00000000..78ddc0e3 --- /dev/null +++ b/ls/server/src/zshHydrator/classes/index.ts @@ -0,0 +1,122 @@ +import { makeMap } from '../../util/collections'; +import { again, done, loop } from '../../util/loop'; +import type { + AstNode, + FileNode, + FunctionDefinitionNode, + SimpleCommandNode, +} from '../../zshParser/ast'; +import { findAll, mapAst } from '../../zshParser/ast'; +import { collectClassInformation } from './collect'; +import type { + ClassFileHydration, + ClassInformation, + ClassMethod, + HydratedClassCommand, +} from './types'; +import { + definitionsFromCommands, + instancesFromCommands, + membersFromCommands, + methodScopesFromDefinitions, +} from './indexes'; + +export type * from './types'; + +/** クラスでの役割を示す種別から、付加情報の型を絞り込む。 */ +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') + ); +} + +/** 汎用の構文ノード型を変えず、クラスの意味情報を取得する。 */ +export function classInformationOf(node: SimpleCommandNode): ClassInformation | null { + return isHydratedClassCommand(node) ? node.hydration : null; +} + +/** 通常の構文種別・トークン・範囲を保ったまま、クラスの意味情報を付加する。 */ +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: _hydration, ...syntax } = node; + return syntax; + } + + return node; + }); +} + +/** 情報の付加後に役割別の索引を組み合わせ、最終ASTの参照だけを保持する。 */ +export function classesFromAst( + ast: FileNode, + functionDefinitions?: readonly FunctionDefinitionNode[], +): ClassFileHydration { + const commands = findAll(ast, 'simpleCommand').filter(isHydratedClassCommand); + if (commands.length === 0) return { definitions: [], instances: [], methodScopes: makeMap() }; + + const functions = makeMap( + (functionDefinitions ?? findAll(ast, 'functionDefinition')).map((node) => [ + node.range.start.offset, + node, + ]), + ); + const members = membersFromCommands(commands); + const definitions = definitionsFromCommands(ast, commands, functions, members); + + return { + definitions, + instances: instancesFromCommands(ast, commands, functions), + methodScopes: methodScopesFromDefinitions(definitions), + }; +} + +/** 診断時にクラスのコマンドを再解釈せず、メソッドの引数の所有関係を調べる。 */ +export function classMethodAt( + classes: ClassFileHydration, + scope: FunctionDefinitionNode | null, + offset: number, +): ClassMethod | null { + const methods = classes.methodScopes.get(scope) ?? []; + + return loop<{ readonly low: number; readonly high: number }, ClassMethod | null>( + { low: 0, high: methods.length - 1 }, + ({ low, high }) => { + if (low > high) return done(null); + + const middle = Math.floor((low + high) / 2); + const entry = methods[middle]; + + if (offset < entry.range.start.offset) { + return again({ low, high: middle - 1 }); + } + + return offset >= entry.range.end.offset + ? again({ low: middle + 1, high }) + : done(entry.method); + }, + ); +} diff --git a/ls/server/src/zshHydrator/classes/indexes.ts b/ls/server/src/zshHydrator/classes/indexes.ts new file mode 100644 index 00000000..75be5cd8 --- /dev/null +++ b/ls/server/src/zshHydrator/classes/indexes.ts @@ -0,0 +1,206 @@ +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, + 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; +}; + +/** 本体や値をコピーせず、最終AST内のメンバーの構文ノードを保持する。 */ +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 }; + switch (information.kind) { + case 'classAttribute': { + const attribute = attributeArguments(command); + if (!attribute) return null; + + return { + classOffset: information.classOffset, + 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; + + return { + classOffset: information.classOffset, + member: { ...base, kind: 'classMethod', body: { kind: 'inline', value } }, + }; + } + + return { + classOffset: information.classOffset, + member: { ...base, kind: 'classMethod', body: information.body }, + }; + default: + return null; + } +} + +/** 入力コマンドと既存の索引を変えず、新しいメンバーの組を構築する。 */ +export function membersFromCommands( + commands: readonly HydratedClassCommand[], +): ReadonlyMap { + return produce(makeMap(), (draft) => { + for (const command of commands) { + const located = memberFromCommand(command); + if (!located) continue; + + const group = draft.get(located.classOffset) ?? { attributes: [], methods: [] }; + if (located.member.kind === 'classAttribute') { + group.attributes.push(castDraft(located.member)); + } else { + group.methods.push(castDraft(located.member)); + } + draft.set(located.classOffset, group); + } + }); +} + +/** 定義を、最終ASTの所有関数と新しく構築したメンバーの組へ対応付ける。 */ +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 ?? [], + }; +} + +/** 未完了と破棄済みの状態も含め、構文の順序で定義を集める。 */ +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); +} + +/** 情報を付加した最終構文ノードだけを使い、構文スコープの所有関係を解決する。 */ +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; +} + +/** 実体のクラス名・変数名の単語を、最終ASTの所有スコープに対応付ける。 */ +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, + }; +} + +/** コマンドや他のファイルの索引を変えず、実体の束縛を集める。 */ +export function instancesFromCommands( + ast: FileNode, + commands: readonly HydratedClassCommand[], + functions: ReadonlyMap, +): readonly ClassInstance[] { + const commandByOffset = makeMap(commands.map((node) => [node.range.start.offset, node])); + + return commands + .map((command) => instanceFromCommand(ast, command, functions, commandByOffset)) + .filter((instance): instance is ClassInstance => instance !== null); +} + +/** 宣言を再解釈せずに引数の所有関係を判定できるよう、本体の範囲を索引化する。 */ +export function methodScopesFromDefinitions( + definitions: readonly ClassDefinition[], +): ClassFileHydration['methodScopes'] { + return produce(makeMap(), (draft) => { + for (const definition of definitions) { + for (const method of definition.methods) { + if (method.body.kind !== 'block') continue; + + const key = castDraft(definition.scope); + const scopes = draft.get(key) ?? []; + scopes.push(castDraft({ method, range: method.body.range })); + draft.set(key, scopes); + } + } + + for (const scopes of draft.values()) { + scopes.sort((left, right) => left.range.start.offset - right.range.start.offset); + } + }); +} diff --git a/ls/server/src/zshHydrator/classes/types.ts b/ls/server/src/zshHydrator/classes/types.ts new file mode 100644 index 00000000..e14339bf --- /dev/null +++ b/ls/server/src/zshHydrator/classes/types.ts @@ -0,0 +1,132 @@ +import type { + FileNode, + FunctionDefinitionNode, + SimpleCommandNode, + WordNode, +} from '../../zshParser/ast'; +import type { SourceRange } from '../../zshParser/lexer'; + +export type ClassDefinitionScopeLocation = + | { readonly kind: 'file' } + | { + readonly kind: 'function'; + readonly offset: number; + }; + +export type ClassScopeLocation = + | ClassDefinitionScopeLocation + | { + readonly kind: '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: ClassDefinitionScopeLocation; + 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 defaultValueRange: SourceRange; +}; + +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 ClassMethodScope = { + readonly range: SourceRange; + readonly method: ClassMethod; +}; + +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 b292aefb..9d6c067c 100644 --- a/ls/server/src/zshHydrator/fileHydration.ts +++ b/ls/server/src/zshHydrator/fileHydration.ts @@ -1,3 +1,4 @@ +import { classesFromAst, type ClassFileHydration } from './classes'; import type { FileNode, FunctionDefinitionNode, QueryContext } from '../zshParser/ast'; import { createQueryContext, findAll } from '../zshParser/ast'; import type { LexerDiagnostic, Token } from '../zshParser/lexer'; @@ -19,6 +20,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[]; @@ -47,6 +49,7 @@ export function createZshFileHydration({ file, ast, tokens: parsed.tokens, + classes: classesFromAst(ast, definitions), query: createQueryContext(ast, definitions), functions: definitions.flatMap((definition) => definition.names.map((word) => ({ name: word.raw, definition })), diff --git a/ls/server/src/zshHydrator/hydrate.ts b/ls/server/src/zshHydrator/hydrate.ts index c4988564..39bb1b3b 100644 --- a/ls/server/src/zshHydrator/hydrate.ts +++ b/ls/server/src/zshHydrator/hydrate.ts @@ -1,3 +1,4 @@ +import { hydrateClasses } from './classes'; import { lowerBound } from '../util/search'; import type { AstNode, @@ -72,7 +73,7 @@ export function hydrateAst( documents.size === 0 && !ast.comments.some((comment) => isHydratedComment(comment) || parseDirective(comment, options)) ) { - return ast; + return hydrateClasses(ast); } // 先行コメントの位置ではなく、構文の範囲に含まれる関数定義の位置で絞り込む。 @@ -80,7 +81,7 @@ export function hydrateAst( .map(({ definition }) => definition.range.start.offset) .toSorted((left, right) => left - right); - return mapAst( + const documentedAst = mapAst( ast, (node: AstNode): AstNode => { if (node.kind === 'docBlock') { @@ -125,4 +126,6 @@ export function hydrateAst( return first < offsets.length && offsets[first] < end.offset; }, ); + + return hydrateClasses(documentedAst); } diff --git a/ls/server/src/zshHydrator/index.ts b/ls/server/src/zshHydrator/index.ts index 5e0776ee..912b6d42 100644 --- a/ls/server/src/zshHydrator/index.ts +++ b/ls/server/src/zshHydrator/index.ts @@ -17,3 +17,19 @@ export { refreshZshHydrator, } from './hydrator'; export type { ZshHydrator } from './hydrator'; +export { + hydrateClasses, + classesFromAst, + classInformationOf, + isHydratedClassCommand, + classMethodAt, +} from './classes'; +export type { + ClassInformation, + HydratedClassCommand, + ClassFileHydration, + ClassDefinition, + ClassMethod, + ClassAttribute, + ClassInstance, +} from './classes'; 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..043f0e80 --- /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'; + +/** 静的な単語または接頭辞を復号し、展開を含む値は動的なまま扱う。 */ +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 new file mode 100644 index 00000000..732436a6 --- /dev/null +++ b/ls/server/test/connection/classApi.test.ts @@ -0,0 +1,117 @@ +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 }); +}); + +/** 実際のクラス宣言を通常のprovider snapshot経由で索引化する。 */ +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, + }; +} + +function privateCommand(name: string): boolean { + return name.split('.').some((segment) => segment.startsWith('_')); +} + +describe('class API visibility', () => { + test('通常の補完は公開DSLを表示し、内部関数を隠す', () => { + const scenario = fixture(); + const items = zCompletion({ ...scenario, showPrivateFunctions: false }); + + const names = items?.map((item) => item.label) ?? []; + expect(names).toEqual(expect.arrayContaining(publicCommands)); + expect(names.filter(privateCommand)).toEqual([]); + }); + + test('private表示を有効にすると公開DSLと内部関数を参照できる', () => { + const scenario = fixture(); + const names = + zCompletion({ ...scenario, showPrivateFunctions: true })?.map((item) => item.label) ?? []; + const internal = names.filter(privateCommand); + + 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'); + }); + + 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); + }); + 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 new file mode 100644 index 00000000..84051813 --- /dev/null +++ b/ls/server/test/diagnostics/classes.test.ts @@ -0,0 +1,556 @@ +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'; +import { createZshFileHydration } from '../../src/zshHydrator'; +import { 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-')); +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() { : }', + '# $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() { : }', + ].join('\n') + '\n'; +const counterClass = [ + 'z.cls.draw Counter', + ' z.cls.attr count default=0', + ' z.cls.fn increment', + ' (( ++count ))', + ' z.cls.fn.done', + ' z.cls.drew', + '', +].join('\n'); + +describe('class DSL command diagnostics', () => { + 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); + 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(12); + }); + + test('別ファイルのクラスから生成されるメソッドと属性を認識し、タイプミスは診断する', () => { + const scenario = fixture( + '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 class Counter.', + }, + ]); + + expect(semantic(scenario.items)).toHaveLength(1); + }); + + test('メソッド内の未定義コマンドを元ファイルの位置で診断する', () => { + const source = counterClass.replace('(( ++count ))', 'missing_inside_method'); + const scenario = fixture('', classApi + source); + + expect( + semantic(scenario.diagnostics.files.get(scenario.definitionUri)?.items ?? []), + ).toMatchObject([ + { + code: 'undefined-command', + range: { start: { line: 13, character: 4 } }, + }, + ]); + }); + + test('メソッドの編集で未編集の呼出元を再診断する', () => { + const scenario = fixture( + 'z.cls.new Counter counter\n$counter.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: 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 scenario = fixture( + 'z.cls.new Counter counter\n$counter.increment\n$counter.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=""', + ' z.cls.new ArrayBox counter', + ' $counter.fill', + ' $counter.increment', + '}', + '$counter.count.get', + '$counter.fill', + '', + ].join('\n'); + + 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\n$leaked.value\n', classApi + counterClass); + const outside = TextDocument.create( + pathToFileURL(path.join(path.dirname(scenario.root), 'outside.zsh')).href, + 'shellscript', + 1, + [ + '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', + '$counter.value', + '$local_object.increment', + '', + ].join('\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 })).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('外側の関数の引数使用へメソッド内の引数を混ぜない', () => { + const source = [ + '# $1: loader argument', + 'load() {', + ' 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'); + 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', + 'load() {', + ' 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'); + 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); + }); +}); + +describe('hydrated class command targets', () => { + test('未公開と破棄済みのクラスからは解決先を取得しない', () => { + for (const ending of ['', ' z.cls.abort\n']) { + 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); + } + }); + + test('同じASTを再利用し、変更したクラスの参照を古いコンテキストへ残さない', () => { + 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('呼出し解析が別ファイルのメソッドと属性の宣言を解決先として返す', () => { + const scenario = fixture( + '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); + 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(); + + 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を展開する呼び出しがメソッドと属性を解決する', () => { + 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( + "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]).toMatchObject({ + message: '$inside.missing is not defined in class Counter.', + range: { start: { line: 0 } }, + }); + }); + + 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.missing'", + 'z.cls.new Local outside', + '$outside.missing', + '', + ].join('\n'); + const scenario = fixture(text, classApi + api); + + expect(semantic(scenario.items)).toHaveLength(1); + 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) => + 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); + }); + 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 class Outer.', + }, + ]); + }); +}); 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 new file mode 100644 index 00000000..bad57a3c --- /dev/null +++ b/ls/server/test/zshHydrator/classes.test.ts @@ -0,0 +1,670 @@ +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 default=0', + ' z.cls.fn increment', + ' (( ++count ))', + ' print "$1"', + ' z.cls.fn.done', + ' z.cls.fn value \'"$self.count.get"\'', + ' 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('重複した本体収集形式のメソッドはクラスを破棄する', () => { + 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', + " 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]; + + 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('重複した属性は元の初期値を保持しクラスを破棄する', () => { + const file = fixture( + [ + 'z.cls.draw Duplicate', + ' 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('aborted'); + expect(definition.attributes).toHaveLength(1); + expect(definition.attributes[0].defaultValue.raw).toBe('default=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('実行時と同じ予約接頭辞だけを除外する', () => { + const file = fixture( + ['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'); + expect(file.classes.definitions[0].attributes[0].name).toBe('__z_cls_value'); + }); + + test('クラスのない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('変数で指定したクラス名を決め打ちしない', () => { + 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([]); + }); + + 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 binding = file.classes.instances[1]; + + expect(binding.scope.kind).toBe('function'); + if (binding.scope.kind !== 'function') throw new Error('Expected function ownership'); + + expect(binding.scope.declaration).toBe(file.functions[0].definition); + }); + + test('子のコマンドに情報を付加しても初期値のWord参照が古くならない', () => { + const file = fixture( + [ + 'z.cls.draw Holder', + ' z.cls.attr value default="$(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]); + 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('既存のクラス付加情報が入力に残っていても現在の構文から更新する', () => { + 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('クラス・属性・メソッド・実体に意味情報を付与し、通常の構文ノードを保持する', () => { + 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('本体を元の範囲または引数の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へ情報を付加し直しても意味情報を重複させない', () => { + 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('未完了と破棄済みのクラスを公開済みのクラスと区別する', () => { + 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', ' z.cls.attr count default=0', ' z.cls.abort', ''].join('\n'), + ); + + expect(aborted.classes.definitions[0]).toMatchObject({ name: 'Discarded', state: 'aborted' }); + }); + + 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('通常の関数ごとのクラスを独立して解釈し、本体内の引数スコープを保持する', () => { + const text = [ + 'load() {', + ' 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 \'"$self.count.get"\'', + ' z.cls.drew', + '}', + '', + ].join('\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('入れ子の関数にある終端名で外側のメソッドを閉じない', () => { + 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('メソッド内の実体宣言をクラスメソッドのスコープに結び付ける', () => { + const file = fixture(source.replace('(( ++count ))', 'z.cls.new Other 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('関数内のクラスと外側のクラスを同じ定義中の状態にしない', () => { + 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', + ]); + expect(file.classes.definitions.find((definition) => definition.name === 'Inner')?.scope).toBe( + 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', + ]); + }); +}); 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..ab57f7f2 --- /dev/null +++ b/ls/server/test/zshParser/ast/word/literal.test.ts @@ -0,0 +1,66 @@ +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('引用のない静的な値を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"); + + expect(literalWord(argument, argument.raw.indexOf('='))).toBe('option'); + expect(compatibilityLiteralWord).toBe(literalWord); + }); +});