Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
8a6ba6a
feat: resolve class-generated commands in diagnostics
milkeclair Nov 15, 2026
3b02d80
refactor: make class declaration state and tests explicit
milkeclair Nov 15, 2026
2ed7721
refactor: share literal word decoding below hydration
milkeclair Nov 16, 2026
64600c9
feat: hydrate class declarations on native syntax nodes
milkeclair Nov 16, 2026
8183cea
feat: resolve class calls from shared hydration targets
milkeclair Nov 16, 2026
80aafce
refactor: make class hydration types and transitions explicit
milkeclair Nov 16, 2026
546afc4
refactor: align class diagnostic consumers and test layout
milkeclair Nov 16, 2026
2153cb4
refactor: split class hydration transitions and indexes
milkeclair Nov 16, 2026
931c934
test: cover class API visibility in the language server
milkeclair Nov 16, 2026
1334704
docs: describe class hydration in Japanese
milkeclair Nov 16, 2026
93c3749
refactor: align class hydration contracts and descriptions
milkeclair Nov 17, 2026
564d73b
refactor: clarify class hydration state transitions
milkeclair Nov 17, 2026
5f49f58
refactor: reuse the combined class diagnostic context
milkeclair Nov 17, 2026
3ea96d7
test: indent class fixtures and declare LS cases explicitly
milkeclair Nov 17, 2026
3080671
Merge main c2b2cca into class diagnostics
milkeclair Nov 17, 2026
5883e5a
test: preserve class hydration in shared code programs
milkeclair Nov 17, 2026
2c267c7
Merge branch 'feat/class-runtime' into feat/class-diagnostics
milkeclair Nov 17, 2026
6025e1c
Merge branch 'feat/class-runtime' into feat/class-diagnostics
milkeclair Nov 18, 2026
d8e881a
feat: hydrate named defaults and flat class boundaries
milkeclair Nov 18, 2026
2428f1c
Merge branch 'feat/class-runtime' into feat/class-diagnostics
milkeclair Nov 18, 2026
8804e83
feat: resolve self calls in class method scopes
milkeclair Nov 18, 2026
94e5ad5
Merge branch 'feat/class-runtime' into feat/class-diagnostics
milkeclair Nov 18, 2026
1711399
Merge branch 'feat/class-runtime' into feat/class-diagnostics
milkeclair Nov 18, 2026
790f376
refactor: separate class collection and self resolution stages
milkeclair Nov 18, 2026
6a40743
Merge branch 'feat/class-runtime' into feat/class-diagnostics
milkeclair Nov 18, 2026
25ef70e
fix: resolve expanded class instance member commands
milkeclair Nov 18, 2026
99b623e
test: verify class completion without fixed API counts
milkeclair Nov 18, 2026
58e105e
fix: resolve class members only through instance ID expansion
milkeclair Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/cls/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ DEBUGトラップと、実行タイミング・localtrapsの設定を復元し
実行時に保存する本体には元のコメントや整形を保持しません。

定義ファイルは通常のシェル構文を保つため、シンタックスハイライトと本体の診断を利用できます。
z-lsは通常のASTへクラス・属性・メソッド・実体の意味情報を付加し、
共有する索引から生成済みコマンドの定義元を解決します。
メソッド本体の診断位置を保持し、引数で渡す本体は共通の[code]解析を利用します。
動的な名前の解決には、既存の保守的な解析を適用します。

## 実行時の費用

Expand Down
2 changes: 1 addition & 1 deletion lib/cls/process.zsh
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ z.cls.attr() {
# 引用しない本体の末尾には、独立した文としてz.cls.fn.doneを置く。
#
# $1: メソッド名
# $2?: 引数で指定する本体
# $2? [code]: 引数で指定する本体
# REPLY: null
# return: 0|1
#
Expand Down
25 changes: 25 additions & 0 deletions ls/server/src/diagnostics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` は通常のコマンド名として解決します。
56 changes: 47 additions & 9 deletions ls/server/src/diagnostics/calls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -135,6 +137,7 @@ export type CallAnalysisOptions = {
export type CallAnalysis = {
readonly diagnostics: readonly Diagnostics[];
readonly targets: ReadonlyMap<SimpleCommandNode, FunctionDefinitionNode>;
readonly classTargets: ReadonlyMap<SimpleCommandNode, readonly ClassCommandTarget[]>;
};

/** 埋め込みコードやworkspace外の定義はローカルに保ち、workspaceの参照先には追加しない。 */
Expand Down Expand Up @@ -197,17 +200,44 @@ export function analyzeCalls(
const initial = {
diagnostics: collectArray<Diagnostics>(),
targets: makeMap<SimpleCommandNode, FunctionDefinitionNode>(),
classTargets: makeMap<SimpleCommandNode, readonly ClassCommandTarget[]>(),
};
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;
}

Expand Down Expand Up @@ -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)) {
Expand All @@ -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を保つ。 */
Expand Down
135 changes: 135 additions & 0 deletions ls/server/src/diagnostics/classes.ts
Original file line number Diff line number Diff line change
@@ -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<string | null>((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<ReturnType<typeof classMemberReference>>,
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]);
}
2 changes: 2 additions & 0 deletions ls/server/src/diagnostics/commandResolution.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
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';

export type ResolutionContext = Declarations & {
readonly environment: ShellEnvironment;
readonly projectRoot: string;
readonly classFiles: readonly ClassFileHydration[];
};

export function isAliasReference(
Expand Down
10 changes: 7 additions & 3 deletions ls/server/src/diagnostics/facts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -36,6 +36,7 @@ export type FileFacts = {
readonly calls: readonly SimpleCommandNode[];
readonly base: readonly Diagnostics[];
readonly declarations: Declarations;
readonly classes: ClassFileHydration;
};

type DeclarationSets = {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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),
Expand Down
Loading
Loading