Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(ingest): resolve PHP calls through typed receivers (#382)

Hiro-Chibab19008335a93
diff --git a/core-ingestion/src/__tests__/queries.php.test.ts b/core-ingestion/src/__tests__/queries.php.test.ts
new file mode 100644
index 00000000..468b68d4
--- /dev/null
+++ b/core-ingestion/src/__tests__/queries.php.test.ts
@@ -0,0 +1,181 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseFile } from '../index.js';
+
+describe('PHP queries', () => {
+ it('normalizes namespace imports to the imported class name', () => {
+ const result = parseFile(
+ '/repo/UseCase.php',
+ `<?php
+namespace App;
+
+use Vendor\\Contracts\\DomainService;
+ `,
+ );
+
+ expect(result).not.toBeNull();
+ expect(result!.relationships).toContainEqual({
+ srcName: 'UseCase.php',
+ dstName: 'DomainService',
+ predicate: 'IMPORTS',
+ importRaw: 'Vendor\\Contracts\\DomainService',
+ });
+ });
+
+ it('resolves calls through typed properties and method parameters', () => {
+ const result = parseFile(
+ '/repo/UseCase.php',
+ `<?php
+interface DomainService
+{
+ public function create(): void;
+}
+
+interface Repository
+{
+ public function create(): void;
+}
+
+final class UseCase
+{
+ private AuditLogger $auditLogger;
+
+ public function __construct(
+ private DomainService $domainService,
+ private Repository $repository,
+ ) {}
+
+ public function create(Logger $logger): void
+ {
+ $this->domainService->create();
+ $this->repository?->create();
+ $this->auditLogger->write();
+ $logger->write();
+ $this->finish();
+ }
+
+ private function finish(): void {}
+}
+ `,
+ );
+
+ expect(result).not.toBeNull();
+ expect(result!.relationships).toEqual(
+ expect.arrayContaining([
+ { srcName: 'UseCase.create', dstName: 'DomainService.create', predicate: 'CALLS' },
+ { srcName: 'UseCase.create', dstName: 'Repository.create', predicate: 'CALLS' },
+ { srcName: 'UseCase.create', dstName: 'AuditLogger.write', predicate: 'CALLS' },
+ { srcName: 'UseCase.create', dstName: 'Logger.write', predicate: 'CALLS' },
+ { srcName: 'UseCase.create', dstName: 'UseCase.finish', predicate: 'CALLS' },
+ ]),
+ );
+ expect(result!.relationships).not.toContainEqual({
+ srcName: 'UseCase.create',
+ dstName: 'create',
+ predicate: 'CALLS',
+ });
+ expect(result!.relationships).not.toContainEqual({
+ srcName: 'UseCase.create',
+ dstName: 'UseCase.create',
+ predicate: 'CALLS',
+ });
+ });
+
+ it('preserves bare-name fallback when the receiver type is unknown', () => {
+ const result = parseFile(
+ '/repo/Runner.php',
+ `<?php
+function run($service): void
+{
+ $service->create();
+}
+ `,
+ );
+
+ expect(result).not.toBeNull();
+ expect(result!.relationships).toContainEqual({
+ srcName: 'run',
+ dstName: 'create',
+ predicate: 'CALLS',
+ });
+ });
+
+ it('resolves nullable declared types', () => {
+ // `?Service` parses as (optional_type (named_type (name))), not named_type.
+ // Matching only the latter dropped every nullable dependency to a bare name.
+ const result = parseFile(
+ '/repo/Nullable.php',
+ `<?php
+final class Nullable
+{
+ private ?Service $service;
+
+ public function __construct(private ?Repository $repository) {}
+
+ public function run(?Logger $logger): void
+ {
+ $this->service->create();
+ $this->repository->find();
+ $logger->write();
+ }
+}
+ `,
+ );
+
+ expect(result).not.toBeNull();
+ expect(result!.relationships).toEqual(
+ expect.arrayContaining([
+ { srcName: 'Nullable.run', dstName: 'Service.create', predicate: 'CALLS' },
+ { srcName: 'Nullable.run', dstName: 'Repository.find', predicate: 'CALLS' },
+ { srcName: 'Nullable.run', dstName: 'Logger.write', predicate: 'CALLS' },
+ ]),
+ );
+ });
+
+ it('resolves typed parameters on plain functions, not just methods', () => {
+ // function_definition is a separate node from method_declaration; rooting the
+ // parameter query at the latter alone left top-level functions untyped.
+ const result = parseFile(
+ '/repo/Standalone.php',
+ `<?php
+function run(Service $service, ?Logger $logger): void
+{
+ $service->create();
+ $logger->write();
+}
+ `,
+ );
+
+ expect(result).not.toBeNull();
+ expect(result!.relationships).toEqual(
+ expect.arrayContaining([
+ { srcName: 'run', dstName: 'Service.create', predicate: 'CALLS' },
+ { srcName: 'run', dstName: 'Logger.write', predicate: 'CALLS' },
+ ]),
+ );
+ });
+
+ it('leaves union-typed receivers as bare names', () => {
+ // A union has no single receiver type to attribute the call to, so the bare
+ // name is the honest answer rather than an arbitrary pick of one member.
+ const result = parseFile(
+ '/repo/Union.php',
+ `<?php
+final class Union
+{
+ public function run(Service|Repository $either): void
+ {
+ $either->create();
+ }
+}
+ `,
+ );
+
+ expect(result).not.toBeNull();
+ expect(result!.relationships).toContainEqual({
+ srcName: 'Union.run',
+ dstName: 'create',
+ predicate: 'CALLS',
+ });
+ });
+});
diff --git a/core-ingestion/src/__tests__/resolveEdges.test.ts b/core-ingestion/src/__tests__/resolveEdges.test.ts
index 969189f6..92979463 100644
--- a/core-ingestion/src/__tests__/resolveEdges.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.test.ts
@@ -219,6 +219,43 @@ describe('resolveEdges', () => {
});
});
+ it('resolves a typed PHP receiver call when the target is outside the parse batch', () => {
+ const caller = fileResult(
+ '/repo/UseCase.php',
+ SupportedLanguages.PHP,
+ [entity('create', SupportedLanguages.PHP, 'method', 'UseCase')],
+ [
+ {
+ srcName: 'UseCase.php',
+ dstName: 'DomainService',
+ predicate: 'IMPORTS',
+ importRaw: 'App\\Contracts\\DomainService',
+ },
+ { srcName: 'UseCase.create', dstName: 'DomainService.create', predicate: 'CALLS' },
+ ],
+ );
+ const targetPath = '/repo/DomainService.php';
+ const globalIndex = buildGlobalResolutionIndex(
+ ['/repo/UseCase.php', targetPath],
+ new Map([
+ [
+ targetPath,
+ '<?php interface DomainService { public function create(): void; }',
+ ],
+ ]),
+ );
+
+ expect(resolveEdges([caller], undefined, globalIndex)).toContainEqual({
+ srcFilePath: '/repo/UseCase.php',
+ srcName: 'UseCase.create',
+ dstFilePath: targetPath,
+ dstName: 'DomainService.create',
+ dstQualifiedKey: 'DomainService.create',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
it('resolves Elixir alias-qualified calls through the implicit short alias', () => {
const caller = fileResult(
'/repo/lib/my_app/accounts.ex',
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index 63d732b9..295230b7 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -446,6 +446,11 @@ function normalizeCapturedImport(rawValue: string, language: SupportedLanguages)
return unwrapped.replace(/^\.+/, '');
}
+ if (language === SupportedLanguages.PHP) {
+ const slashed = unwrapped.replace(/\\/g, '/');
+ return slashed.split('/').filter(Boolean).pop() ?? slashed;
+ }
+
if (language === SupportedLanguages.SAS) {
// Real SAS uses single backslashes in Windows paths (libname "&P.\SASData").
// The general pre-normalization only collapses double backslashes, so do it
@@ -1936,11 +1941,11 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
const seenCalls = new Map<string, Set<string>>();
// Track seen type references per enclosing class/file to avoid duplicate REFERENCES edges
const seenRefs = new Map<string, Set<string>>();
- // Python: map function name → (param name → declared type) for typed-parameter qualifier substitution
+ // Map function name → (param name → declared type) for typed-parameter qualifier substitution
const paramTypeMap = new Map<string, Map<string, string>>();
// Python: map function name → (variable name → assigned type) for untyped-param qualifier substitution
const assignTypeMap = new Map<string, Map<string, string>>();
- // C/C++: map enclosing scope → (variable/member name → declared type)
+ // Map enclosing scope → (variable/member name → declared type)
const declaredTypeMap = new Map<string, Map<string, string>>();
// Import aliases keyed by the in-file alias name (Go explicit aliases, etc.).
const importAliases: Record<string, string> = {};
@@ -2123,6 +2128,25 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
}
}
+ // PHP typed parameters: map the receiver variable to its declared class or
+ // interface so member calls can target Class.method instead of a bare method.
+ if (language === SupportedLanguages.PHP) {
+ const typedParamScope = match.captures.find((c: any) => c.name === '_typed_param_scope');
+ const typedParamName = match.captures.find((c: any) => c.name === '_typed_param_name');
+ const typedParamType = match.captures.find((c: any) => c.name === '_typed_param_type');
+ if (typedParamScope && typedParamName && typedParamType) {
+ const line = typedParamScope.node.startPosition.row + 1;
+ const methodName = typedParamScope.node.childForFieldName?.('name')?.text as string | undefined;
+ const className = findEnclosing(classRanges, line, '');
+ const scope = methodName ? (className ? `${className}.${methodName}` : methodName) : null;
+ if (scope) {
+ if (!paramTypeMap.has(scope)) paramTypeMap.set(scope, new Map());
+ paramTypeMap.get(scope)!.set(typedParamName.node.text, typedParamType.node.text);
+ }
+ continue;
+ }
+ }
+
// Go typed parameters: build paramTypeMap so method calls on
// parameters (incl. receivers) resolve to the parameter's declared
// type. e.g. `func (s *Scheme) F(opts *Options) { opts.Run() }`
@@ -2163,18 +2187,23 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
}
}
- // C/C++ typed declarations: capture local vars, parameters, and fields so that
+ // Typed declarations: capture local vars, parameters, and fields so that
// member calls like current->Get(...) can be rewritten to Version.Get.
- if (language === SupportedLanguages.C || language === SupportedLanguages.CPlusPlus) {
+ if (
+ language === SupportedLanguages.C ||
+ language === SupportedLanguages.CPlusPlus ||
+ language === SupportedLanguages.PHP
+ ) {
const typedVarScope = match.captures.find((c: any) => c.name === '_typed_var_scope');
const typedVarName = match.captures.find((c: any) => c.name === '_typed_var_name');
const typedVarType = match.captures.find((c: any) => c.name === '_typed_var_type');
if (typedVarScope && typedVarName && typedVarType) {
const line = typedVarScope.node.startPosition.row + 1;
- const scope =
- findEnclosingFunction(entities, line)
- ?? findEnclosing(classRanges, line, '')
- ?? fileName;
+ const scope = language === SupportedLanguages.PHP
+ ? findEnclosing(classRanges, line, '') ?? fileName
+ : findEnclosingFunction(entities, line)
+ ?? findEnclosing(classRanges, line, '')
+ ?? fileName;
if (!declaredTypeMap.has(scope)) declaredTypeMap.set(scope, new Map());
declaredTypeMap.get(scope)!.set(typedVarName.node.text, typedVarType.node.text);
continue;
@@ -2369,6 +2398,24 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
return callee;
}
let qualifier = qualifierCapture.node.text;
+ let phpPropertyOnThis = false;
+ let phpReceiverIsSupported = true;
+ if (language === SupportedLanguages.PHP) {
+ const receiverNode = qualifierCapture.node;
+ if (receiverNode.type === 'variable_name') {
+ qualifier = receiverNode.firstNamedChild?.text ?? receiverNode.text.replace(/^\$/, '');
+ } else if (receiverNode.type === 'member_access_expression') {
+ qualifier = receiverNode.childForFieldName?.('name')?.text ?? receiverNode.text;
+ const objectNode = receiverNode.childForFieldName?.('object');
+ const objectName = objectNode?.type === 'variable_name'
+ ? objectNode.firstNamedChild?.text ?? objectNode.text.replace(/^\$/, '')
+ : null;
+ phpPropertyOnThis = objectName === 'this';
+ } else {
+ phpReceiverIsSupported = false;
+ }
+ }
+ if (!phpReceiverIsSupported) return callee;
// Python: 'self'/'cls' always refers to the enclosing class — substitute it
// so the edge reads 'Query.filter' instead of 'self.filter', enabling
// same-file resolution without type inference.
@@ -2376,7 +2423,7 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
const enclosingClass = findEnclosing(classRanges, callLine, '');
if (enclosingClass) qualifier = enclosingClass;
} else if (qualifier === 'this') {
- // JS/TS: 'this' inside a class method refers to the enclosing class.
+ // JS/TS and PHP: 'this' inside a class method refers to the enclosing class.
// Substitute so e.g. `this.save()` → `Document.save` instead of `this.save`.
const enclosingClass = findEnclosing(classRanges, callLine, '');
if (enclosingClass) qualifier = enclosingClass;
@@ -2402,6 +2449,14 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
const typeForParam = paramTypeMap.get(funcName)?.get(qualifier);
if (typeForParam) qualifier = typeForParam;
}
+ } else if (language === SupportedLanguages.PHP) {
+ const funcName = findEnclosingFunction(entities, callLine);
+ const className = findEnclosing(classRanges, callLine, '');
+ const typeForReceiver = phpPropertyOnThis
+ ? (className ? declaredTypeMap.get(className)?.get(qualifier) : undefined)
+ : (funcName ? paramTypeMap.get(funcName)?.get(qualifier) : undefined);
+ if (typeForReceiver) qualifier = typeForReceiver;
+ else return callee;
} else if (language === SupportedLanguages.C || language === SupportedLanguages.CPlusPlus) {
const funcName = findEnclosingFunction(entities, callLine) ?? fileName;
const className = findEnclosing(classRanges, callLine, '')
@@ -2715,6 +2770,25 @@ export function buildGlobalResolutionIndex(
}
}
+ // PHP: index definitions so an incremental batch can resolve typed receiver
+ // calls to classes and interfaces in unchanged files.
+ for (const [fp, src] of sources) {
+ if (nodePath.extname(fp).toLowerCase() !== '.php') continue;
+ const parsed = parseFile(fp, src);
+ if (!parsed) continue;
+ const qkMap = new Map<string, string[]>();
+ for (const e of parsed.entities) {
+ if (e.kind === 'file' || e.kind === 'module') continue;
+ const list = qkMap.get(e.name) ?? [];
+ list.push(qualifiedKey(e));
+ qkMap.set(e.name, list);
+ }
+ if (qkMap.size > 0) {
+ fileQKeys.set(fp, qkMap);
+ fileHasSymbol.set(fp, new Set(qkMap.keys()));
+ }
+ }
+
// SAS: index macro definitions for cross-batch Tier-3 resolution. Derive
// them from the parser's definition.macro entities (not a regex) so this
// never drifts from what the in-batch path extracts in resolveEdges — the
diff --git a/core-ingestion/src/queries.ts b/core-ingestion/src/queries.ts
index 52af40bb..ad3d95f3 100644
--- a/core-ingestion/src/queries.ts
+++ b/core-ingestion/src/queries.ts
@@ -1025,10 +1025,12 @@ export const PHP_QUERIES = `
; Method call: $obj->method()
(member_call_expression
+ object: (_) @_qualifier
name: (name) @call.name) @call
; Nullsafe method call: $obj?->method()
(nullsafe_member_call_expression
+ object: (_) @_qualifier
name: (name) @call.name) @call
; Static call: Foo::bar() (php_only uses scoped_call_expression)
@@ -1038,6 +1040,50 @@ export const PHP_QUERIES = `
; Constructor call: new User()
(object_creation_expression (name) @call.name) @call
+; Typed properties: private Service $s / private ?Service $s
+;
+; ?Service is NOT a named_type -- tree-sitter-php wraps it as
+; (optional_type (named_type (name))). Matching only named_type silently drops
+; every nullable dependency back to a bare method name, which is most of them in
+; modern PHP. Union types (Service|Repo) are deliberately left out: there is no
+; single receiver type to attribute the call to, so a bare name is the honest
+; answer there.
+(property_declaration
+ type: [(named_type (name) @_typed_var_type)
+ (optional_type (named_type (name) @_typed_var_type))]
+ (property_element
+ name: (variable_name (name) @_typed_var_name))) @_typed_var_scope
+
+; Constructor-promoted properties: private ?Service $service
+(property_promotion_parameter
+ type: [(named_type (name) @_typed_var_type)
+ (optional_type (named_type (name) @_typed_var_type))]
+ name: (variable_name (name) @_typed_var_name)) @_typed_var_scope
+
+; Typed parameters on methods AND plain functions: function run(?Service $s)
+;
+; function_definition is a separate node from method_declaration, so rooting
+; this at method_declaration alone left every top-level function's parameters
+; untyped. The handler needs no change: childForFieldName('name') works on both,
+; and with no enclosing class the scope becomes the bare function name — which is
+; exactly what findEnclosingFunction returns for a top-level function.
+[(method_declaration
+ parameters: (formal_parameters
+ [(simple_parameter
+ type: [(named_type (name) @_typed_param_type)
+ (optional_type (named_type (name) @_typed_param_type))]
+ name: (variable_name (name) @_typed_param_name))
+ (property_promotion_parameter
+ type: [(named_type (name) @_typed_param_type)
+ (optional_type (named_type (name) @_typed_param_type))]
+ name: (variable_name (name) @_typed_param_name))]))
+ (function_definition
+ parameters: (formal_parameters
+ (simple_parameter
+ type: [(named_type (name) @_typed_param_type)
+ (optional_type (named_type (name) @_typed_param_type))]
+ name: (variable_name (name) @_typed_param_name))))] @_typed_param_scope
+
; ── Heritage: extends ────────────────────────────────────────────────────────
(class_declaration
name: (name) @heritage.class
diff --git a/ix-cli/src/cli/__tests__/ingest-discovery.test.ts b/ix-cli/src/cli/__tests__/ingest-discovery.test.ts
index f1874ecc..d4bcc19a 100644
--- a/ix-cli/src/cli/__tests__/ingest-discovery.test.ts
+++ b/ix-cli/src/cli/__tests__/ingest-discovery.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { dedupeDiscoveredFilePaths, isSupportedSourceFile } from '../commands/ingest.js';
+import { dedupeDiscoveredFilePaths, isSupportedSourceFile, needsIndexPrescan } from '../commands/ingest.js';
describe('dedupeDiscoveredFilePaths', () => {
it('collapses alternate discovered paths that point at the same canonical file', () => {
@@ -54,4 +54,9 @@ describe('dedupeDiscoveredFilePaths', () => {
expect(isSupportedSourceFile(f)).toBe(true);
}
});
+
+ it('pre-scans PHP definitions for incremental call resolution', () => {
+ expect(needsIndexPrescan('src/Service.php')).toBe(true);
+ expect(needsIndexPrescan('src/service.py')).toBe(false);
+ });
});
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 20047bac..123ecefd 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -43,11 +43,11 @@ export function isSupportedSourceFile(filePath: string): boolean {
// Extensions whose source text must be pre-read so buildGlobalResolutionIndex can
// extract cross-batch symbols before the streaming parse loop. Go uses a fast
-// regex scan; SAS and R are parsed (their cross-batch indexes are derived from
-// the parser's definition entities).
-const INDEX_PRESCAN_EXTENSIONS = new Set(['.go', '.r', '.sas']);
+// regex scan; PHP, SAS, and R are parsed (their cross-batch indexes are derived
+// from the parser's definition entities).
+const INDEX_PRESCAN_EXTENSIONS = new Set(['.go', '.php', '.r', '.sas']);
-function needsIndexPrescan(filePath: string): boolean {
+export function needsIndexPrescan(filePath: string): boolean {
return INDEX_PRESCAN_EXTENSIONS.has(nodePath.extname(filePath).toLowerCase());
}