Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
56 changes: 46 additions & 10 deletions src/selfgraph/code/_resolve.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import json
import os
import posixpath
import re
from bisect import bisect_right
Expand Down Expand Up @@ -144,6 +145,21 @@ def _fits(request: Request, method: str, template: tuple[str, ...]) -> bool:
return all(t == s or (s != "" and _SLOT.fullmatch(t) is not None) for t, s in zip(template, segs, strict=True))


def _pick(entries: list[tuple[str, Any]], types: bool) -> Any:
"""The declaration a scope binds under a name: the type in a type position, else the value, so a function or
constant wins over an interface or type alias of the same name.

@param entries (list[tuple[str, Any]]): what the scope binds under the name.
@param types (bool): whether the name is in a type position.
@return (Any): the declaration, or None.
"""
syms = [value for kind, value in entries if kind == "sym"]
for sym in syms:
if sym.kind in TYPE_KINDS if types else sym.kind not in ("interface", "type"):
return sym
return syms[0] if syms else None


class _Sym:
def __init__(self, file: _File, decl: Declaration) -> None:
self.file, self.decl, self.kind, self.name, self.id = file, decl, decl.kind, decl.name, decl.id
Expand Down Expand Up @@ -351,9 +367,9 @@ def _lookup(self, f: _File, offset: int, name: str, types: bool = False) -> tupl
while scope is not None:
private = scope is not start and scope.decl is not None and scope.decl.kind in TYPE_KINDS
entries = [] if private and f.r.get("private_class_scope") else scope.names.get(name, [])
for kind, value in entries:
if kind == "sym":
return "sym", value, "scope"
sym = _pick(entries, types)
if sym is not None:
return "sym", sym, "scope"
for kind, value in entries:
if kind == "import":
found = self._import(f, value)
Expand Down Expand Up @@ -508,9 +524,9 @@ def _top(self, m: _File, name: str) -> tuple[str, Any] | None:
@return (tuple[str, Any] | None): the binding, or None.
"""
entries = m.top.names.get(name, [])
for kind, value in entries:
if kind == "sym":
return "sym", value
sym = _pick(entries, False)
if sym is not None:
return "sym", sym
for kind, value in entries:
if kind == "import":
return self._import(m, value)
Expand Down Expand Up @@ -553,7 +569,7 @@ def _files(self, f: _File, text: str, relative: bool) -> list[_File]:
return []
bases = [(f.root, "/".join(parts[: len(parts) - dots + 1]))]
path = text[dots:].replace(sep, "/")
elif relative or text.startswith(("./", "../")):
elif relative or text.startswith(("./", "../")) or text in (".", ".."):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A bare "." (and "..", same code) becomes the folder path and then the file suffixes are tried before /index.*, so a sibling file named after the folder wins.

Repro: web/sub.ts and web/sub/index.ts both export wrong; web/sub/use.ts has import { wrong } from "."; wrong(). Both SDKs give CALLS function:web/sub/use.ts:go -> function:web/sub.ts:wrong. ts.resolveModuleName resolves it to web/sub/index.ts under Node10, Node16 and Bundler.

For . and .. only try the /index.* suffixes. Please add the sibling file to the code-self fixture so the test covers it.

bases = [(f.root, f.dir)]
elif m:
segs = [s for s in text.split(sep) if s] if sep != "/" else [text]
Expand All @@ -571,14 +587,15 @@ def _files(self, f: _File, text: str, relative: bool) -> list[_File]:
if "root" in search:
bases.extend((i, "") for i in range(len(self.roots)) if i != f.root)
candidates = [(root, _norm(f"{base}/{path}")) for root, base in bases] + self._configured(f, text)
candidates += self._own(f, text)
out: list[_File] = []
for root, full in candidates:
if full.startswith(".."):
continue
if m.get("directory"):
out = [o for o in self.files if o.root == root and o.dir == full and o.r is f.r]
else:
names = [full + s for s in m.get("suffixes", [""])]
names = [(full + s).removeprefix("/") for s in m.get("suffixes", [""])]
compiled = m.get("compiled")
if compiled and re.search(compiled, full):
stem = re.sub(compiled, "", full)
Expand All @@ -589,6 +606,22 @@ def _files(self, f: _File, text: str, relative: bool) -> list[_File]:
self.cache[key] = out
return out

def _own(self, f: _File, text: str) -> list[tuple[int, str]]:
"""The paths a module name maps to when its first segment names a root that is itself a package.

@param f (_File): the file.
@param text (str): the module name.
@return (list[tuple[int, str]]): (root index, path) pairs to try.
"""
sep = f.m.get("separator", "/")
head, _, rest = text.partition(sep)
return [
(index, rest.replace(sep, "/"))
for index, root in enumerate(self.roots)
if head == os.path.basename(os.path.normpath(root))
and any((index, marker) in self.by_path for marker in f.m.get("packages", []))
]

def _anchor(self, f: _File, anchor: str) -> str:
"""The directory a leading path segment such as crate, self, or super stands for.

Expand Down Expand Up @@ -676,8 +709,11 @@ def _type(self, f: _File, offset: int, text: str) -> tuple[_Sym, str] | None:
result = (cls, "member") if cls is not None else None
else:
found = self._path(f, offset, segs, types=True)
if found is not None and found[0][0] == "sym" and found[0][1].kind in TYPE_KINDS:
result = (found[0][1], found[1])
sym = found[0][1] if found is not None and found[0][0] == "sym" else None
if sym is not None and sym.parent is None and sym.kind not in TYPE_KINDS:
sym = _pick(sym.file.top.names.get(sym.name, []), True)
if sym is not None and sym.kind in TYPE_KINDS:
result = (sym, found[1])
self.active.discard(key)
self.cache[key] = result
return result
Expand Down
6 changes: 3 additions & 3 deletions src/selfgraph/code/languages.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"calls": {"call_expression": null, "new_expression": {"field": "constructor"}},
"imports": {"import_statement": {"steps": [{"field": "source"}]}, "export_statement": {"steps": [{"field": "source"}]}},
"require": {"callees": {"require": false, "import": false}, "argument": "arguments", "types": ["string"]},
"relative": "^['\"`]\\.\\.?/",
"relative": "^['\"`]\\.\\.?(?:/|['\"`])",
"modules": "javascript"
},
{
Expand All @@ -78,15 +78,15 @@
"calls": {"call_expression": null, "new_expression": {"field": "constructor"}},
"imports": {"import_statement": {"steps": [{"field": "source"}]}, "export_statement": {"steps": [{"field": "source"}]}},
"require": {"callees": {"require": false, "import": false}, "argument": "arguments", "types": ["string"]},
"relative": "^['\"`]\\.\\.?/",
"relative": "^['\"`]\\.\\.?(?:/|['\"`])",
"modules": "javascript"
},
{
"id": "python",
"name": "Python",
"extensions": [".py", ".pyi"],
"grammar": {"pypi": "tree-sitter-python", "module": "tree_sitter_python", "function": "language", "npm": "tree-sitter-python", "wasm": "tree-sitter-python.wasm", "version": "0.25.0"},
"resolve": {"queries": ["python"], "self": ["self", "cls"], "split": "\\.", "private_class_scope": true, "modules": {"separator": ".", "relative": "dots", "suffixes": ["/__init__.py", "/__init__.pyi", ".py", ".pyi"], "search": ["ancestors", "root"], "local": "first"}},
"resolve": {"queries": ["python"], "self": ["self", "cls"], "split": "\\.", "private_class_scope": true, "modules": {"separator": ".", "relative": "dots", "suffixes": ["/__init__.py", "/__init__.pyi", ".py", ".pyi"], "search": ["ancestors", "root"], "local": "first", "packages": ["__init__.py", "__init__.pyi"]}},
"declarations": {"function_definition": "function", "class_definition": "class"},
"calls": {"call": null},
"imports": {
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/code-self/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Sources for the self-import and directory-import tests in `tests/test_code_resolve.py` and
`typescript/test/codeResolve.test.ts`, and for the conformance case that compares the graphs both SDKs
build from them. `pkg` is a package root that imports itself by name; `web` imports folders by their index.
Nothing here is run or built.
Empty file.
Empty file.
7 changes: 7 additions & 0 deletions tests/fixtures/code-self/pkg/cli/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class App:
def run(self):
return 1


def helper():
return 2
7 changes: 7 additions & 0 deletions tests/fixtures/code-self/pkg/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import pkg.cli.app
from pkg.cli.app import App


def go():
App()
return pkg.cli.app.helper()
7 changes: 7 additions & 0 deletions tests/fixtures/code-self/web/core.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface Ok {
v: number;
}

export function Ok(): Ok {
return { v: 1 };
}
3 changes: 3 additions & 0 deletions tests/fixtures/code-self/web/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function hello(): number {
return 1;
}
3 changes: 3 additions & 0 deletions tests/fixtures/code-self/web/sub/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function local(): number {
return 2;
}
7 changes: 7 additions & 0 deletions tests/fixtures/code-self/web/sub/use.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { hello } from "..";
import { local } from ".";
import * as core from "../core";

export function go(): number {
return hello() + local() + core.Ok().v;
}
18 changes: 18 additions & 0 deletions tests/test_code_resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
pytest.importorskip("tree_sitter_typescript")

RESOLVE = Path(__file__).parent / "fixtures" / "code-resolve"
SELF = Path(__file__).parent / "fixtures" / "code-self"
NESTED = (
"def helper():\n return 1\n\n\ndef outer():\n def helper():\n return 2\n\n return helper()\n\n\n"
"def run(helper, service):\n service.save()\n return helper()\n"
Expand Down Expand Up @@ -234,6 +235,23 @@ def test_package_names_tsconfig_paths_and_lua_tables_resolve_across_files(tmp_pa
} <= resolved(g)


def test_a_package_root_imports_itself_by_name_and_a_directory_import_reaches_its_index():
g = fresh_graph("code-self-package")
run(g.code.index([str(SELF / "pkg"), str(SELF / "web")]))
assert resolved(g) == {
"IMPORTS file:pkg/main.py file:pkg/__init__.py path",
"IMPORTS file:pkg/main.py file:pkg/cli/app.py path",
"CONSTRUCTS function:pkg/main.py:go class:pkg/cli/app.py:app import",
"CALLS function:pkg/main.py:go function:pkg/cli/app.py:helper import",
"IMPORTS file:web/sub/use.ts file:web/index.ts path",
"IMPORTS file:web/sub/use.ts file:web/sub/index.ts path",
"IMPORTS file:web/sub/use.ts file:web/core.ts path",
"CALLS function:web/sub/use.ts:go function:web/index.ts:hello import",
"CALLS function:web/sub/use.ts:go function:web/sub/index.ts:local import",
"CALLS function:web/sub/use.ts:go function:web/core.ts:ok import",
}


def test_receivers_resolve_through_the_types_variables_fields_and_returns_hold():
g = fresh_graph("code-flow")
run(g.code.index(str(RESOLVE)))
Expand Down
1 change: 1 addition & 0 deletions typescript/src/code/languages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export interface ModuleSpec {
configs?: string[];
anchors?: Record<string, string>;
markers?: string[];
packages?: string[];
index?: string[];
transitive?: boolean;
}
Expand Down
54 changes: 49 additions & 5 deletions typescript/src/code/resolve.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { basename, normalize } from "node:path";
import { comparePy, cpLen, isPlainObject, PY_WS_CLASS, pyStrip } from "../internal/py.js";
import { type ModuleSpec, type ResolveSpec, tables } from "./languages.js";
import type { Binding, Declaration, FileModel, ProjectModel, Request, ResolvedEdge } from "./model.js";
Expand Down Expand Up @@ -208,6 +209,22 @@ function fits(request: Request, method: string, template: string[]): boolean {
return template.every((t, i) => t === segs[i] || (segs[i] !== "" && SLOT.test(t)));
}

/**
* The declaration a scope binds under a name: the type in a type position, else the value, so a function or
* constant wins over an interface or type alias of the same name.
*
* @param entries (Entry[]): what the scope binds under the name.
* @param types (boolean): whether the name is in a type position.
* @return (Sym | null): the declaration, or null.
*/
function pick(entries: Entry[], types: boolean): Sym | null {
const syms = entries.filter((entry) => entry[0] === "sym").map(([, value]) => value as Sym);
const wanted = syms.find((sym) =>
types ? TYPE_KINDS.has(sym.kind) : sym.kind !== "interface" && sym.kind !== "type",
);
return wanted ?? syms[0] ?? null;
}

class Sym {
readonly id: string;
readonly kind: string;
Expand Down Expand Up @@ -503,7 +520,8 @@ class Resolver {
while (scope !== null) {
const hidden = scope !== start && scope.decl !== null && TYPE_KINDS.has(scope.decl.kind);
const entries = hidden && f.r.private_class_scope ? [] : (scope.names.get(name) ?? []);
for (const [kind, value] of entries) if (kind === "sym") return ["sym", value, "scope"];
const sym = pick(entries, types);
if (sym !== null) return ["sym", sym, "scope"];
for (const [kind, value] of entries) {
if (kind !== "import") continue;
const found = this.importOf(f, value);
Expand Down Expand Up @@ -675,7 +693,8 @@ class Resolver {
*/
top(m: File, name: string): Value | null {
const entries = m.top.names.get(name) ?? [];
for (const [kind, value] of entries) if (kind === "sym") return ["sym", value];
const sym = pick(entries, false);
if (sym !== null) return ["sym", sym];
for (const [kind, value] of entries) if (kind === "import") return this.importOf(m, value);
const held = entries.filter(([kind]) => kind === "var").map(([, value]) => value as Binding);
if (held.length) return ["var", [m, held]];
Expand Down Expand Up @@ -718,7 +737,7 @@ class Resolver {
}
bases = [[f.root, parts.slice(0, parts.length - dots + 1).join("/")]];
path = text.slice(dots).split(sep).join("/");
} else if (relative || text.startsWith("./") || text.startsWith("../")) {
} else if (relative || text.startsWith("./") || text.startsWith("../") || text === "." || text === "..") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same fix needed here for . and ...

bases = [[f.root, f.dir]];
} else if (Object.keys(m).length) {
let segs = sep !== "/" ? text.split(sep).filter((s) => s) : [text];
Expand All @@ -745,6 +764,7 @@ class Resolver {
const candidates: [number, string][] = [
...bases.map(([root, base]): [number, string] => [root, norm(`${base}/${path}`)]),
...this.configured(f, text),
...this.own(f, text),
];
let out: File[] = [];
for (const [root, full] of candidates) {
Expand All @@ -753,7 +773,7 @@ class Resolver {
out = this.files.filter((o) => o.root === root && o.dir === full && o.r === f.r);
} else {
const suffixes = m.suffixes ?? [""];
let names = suffixes.map((s) => full + s);
let names = suffixes.map((s) => (full + s).replace(/^[/]/, ""));
if (m.compiled && new RegExp(m.compiled).test(full)) {
const base = full.replace(new RegExp(m.compiled), "");
names = [...suffixes.filter((s) => s && !s.includes("/")).map((s) => base + s), ...names];
Expand All @@ -769,6 +789,26 @@ class Resolver {
return out;
}

/**
* The paths a module name maps to when its first segment names a root that is itself a package.
*
* @param f (File): the file.
* @param text (string): the module name.
* @return ([number, string][]): (root index, path) pairs to try.
*/
own(f: File, text: string): [number, string][] {
const sep = f.m.separator ?? "/";
const [head, , rest] = partition(text, sep);
const out: [number, string][] = [];
this.roots.forEach((root, index) => {
if (head !== basename(normalize(root))) return;
if ((f.m.packages ?? []).some((marker) => this.byPath.has(`${index}\0${marker}`))) {
out.push([index, rest.split(sep).join("/")]);
}
});
return out;
}

/**
* The directory a leading path segment such as crate, self, or super stands for.
*
Expand Down Expand Up @@ -867,7 +907,11 @@ class Resolver {
result = cls !== null ? [cls, "member"] : null;
} else {
const found = this.path(f, offset, segs, true);
if (found !== null && found[0][0] === "sym" && TYPE_KINDS.has(found[0][1].kind)) result = [found[0][1], found[1]];
let sym = found !== null && found[0][0] === "sym" ? found[0][1] : null;
if (sym !== null && sym.parent === null && !TYPE_KINDS.has(sym.kind)) {
sym = pick(sym.file.top.names.get(sym.name) ?? [], true);
}
if (found !== null && sym !== null && TYPE_KINDS.has(sym.kind)) result = [sym, found[1]];
}
this.active.delete(key);
this.cache.set(key, result);
Expand Down
18 changes: 18 additions & 0 deletions typescript/test/codeResolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { Relation, SelfGraph } from "../src/index.js";
import { freshGraphs, KUZU_SPEC, tempDir } from "./helpers.js";

const RESOLVE = fileURLToPath(new URL("../../tests/fixtures/code-resolve", import.meta.url));
const SELF = fileURLToPath(new URL("../../tests/fixtures/code-self", import.meta.url));
const NESTED =
"def helper():\n return 1\n\n\ndef outer():\n def helper():\n return 2\n\n return helper()\n\n\n" +
"def run(helper, service):\n service.save()\n return helper()\n";
Expand Down Expand Up @@ -249,6 +250,23 @@ describe.skipIf(!available("python") || !available("typescript"))("code call res
);
});

it("resolves a package root's imports of itself by name and directory imports to their index", async () => {
const g = open();
await g.code.index([join(SELF, "pkg"), join(SELF, "web")]);
expect((await resolved(g)).sort()).toEqual([
"CALLS function:pkg/main.py:go function:pkg/cli/app.py:helper import",
"CALLS function:web/sub/use.ts:go function:web/core.ts:ok import",
"CALLS function:web/sub/use.ts:go function:web/index.ts:hello import",
"CALLS function:web/sub/use.ts:go function:web/sub/index.ts:local import",
"CONSTRUCTS function:pkg/main.py:go class:pkg/cli/app.py:app import",
"IMPORTS file:pkg/main.py file:pkg/__init__.py path",
"IMPORTS file:pkg/main.py file:pkg/cli/app.py path",
"IMPORTS file:web/sub/use.ts file:web/core.ts path",
"IMPORTS file:web/sub/use.ts file:web/index.ts path",
"IMPORTS file:web/sub/use.ts file:web/sub/index.ts path",
]);
});

it("resolves receivers through the types that variables, fields, and returns hold", async () => {
const g = open();
await g.code.index(RESOLVE);
Expand Down
1 change: 1 addition & 0 deletions typescript/test/conformance/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function py(
| "code_resolve"
| "code_remote"
| "code_endpoints"
| "code_self"
| "pinned_unicode"
| "kuzu_statements"
| "kuzu_cut_update"
Expand Down
Loading
Loading