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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
"""Language-aware resolution of extracted references to repository files."""

from __future__ import annotations

from dataclasses import dataclass
import json
import posixpath
import re
import tomllib


@dataclass(frozen=True, slots=True)
class Resolution:
    status: str
    target: str | None = None
    candidates: tuple[str, ...] = ()
    confidence: float = 0.0
    evidence: str = ""


def _unique(values):
    return list(dict.fromkeys(value for value in values if value))


def _jsonc_loads(text: str):
    """Load the JSON-with-comments dialect used by tsconfig/jsconfig files."""
    output: list[str] = []
    index = 0
    quote: str | None = None
    while index < len(text):
        char = text[index]
        if quote:
            output.append(char)
            if char == "\\" and index + 1 < len(text):
                index += 1
                output.append(text[index])
            elif char == quote:
                quote = None
        elif char == '"':
            quote = char
            output.append(char)
        elif text.startswith("//", index):
            index = text.find("\n", index)
            if index < 0:
                break
            output.append("\n")
        elif text.startswith("/*", index):
            end = text.find("*/", index + 2)
            index = len(text) if end < 0 else end + 1
        else:
            output.append(char)
        index += 1

    cleaned = "".join(output)
    output = []
    index = 0
    quote = None
    while index < len(cleaned):
        char = cleaned[index]
        if quote:
            output.append(char)
            if char == "\\" and index + 1 < len(cleaned):
                index += 1
                output.append(cleaned[index])
            elif char == quote:
                quote = None
        elif char == '"':
            quote = char
            output.append(char)
        elif char == ",":
            lookahead = index + 1
            while lookahead < len(cleaned) and cleaned[lookahead].isspace():
                lookahead += 1
            if lookahead >= len(cleaned) or cleaned[lookahead] not in "]}":
                output.append(char)
        else:
            output.append(char)
        index += 1
    return json.loads("".join(output))


class Resolver:
    """Resolve references against an immutable repository path index."""

    def __init__(self, files: dict[str, str]):
        self.files = files
        self.paths = set(files)
        self.suffix_paths = self._suffix_paths()
        self.python_roots = self._python_roots()
        self.js_base_urls, self.js_aliases, self.js_package = self._js_config()
        self.go_module = self._go_module()
        self.rust_packages = self._rust_packages()
        self.elixir_modules = self._elixir_modules()
        self.csharp_namespaces = self._csharp_namespaces()
        self.swift_external_modules = self._swift_external_modules()

    def _suffix_paths(self) -> dict[str, tuple[str, ...]]:
        suffixes: dict[str, list[str]] = {}
        for path in sorted(self.paths):
            parts = path.split("/")
            for index in range(len(parts)):
                suffixes.setdefault("/".join(parts[index:]), []).append(path)
        return {suffix: tuple(paths) for suffix, paths in suffixes.items()}

    def _python_roots(self) -> tuple[str, ...]:
        roots = [""]
        if any(path.startswith("src/") for path in self.paths):
            roots.append("src")
        for path, text in self.files.items():
            if path != "pyproject.toml":
                continue
            try:
                config = tomllib.loads(text)
                package_dir = config.get("tool", {}).get("setuptools", {}).get("package-dir", {})
                roots.extend(value.strip("./") for value in package_dir.values() if isinstance(value, str))
                where = config.get("tool", {}).get("setuptools", {}).get("packages", {}).get("find", {}).get("where", [])
                roots.extend(value.strip("./") for value in where if isinstance(value, str))
            except (tomllib.TOMLDecodeError, AttributeError):
                pass
        return tuple(dict.fromkeys(roots))

    def _js_config(self) -> tuple[tuple[str, ...], tuple[tuple[str, tuple[str, ...]], ...], str | None]:
        bases = [""]
        aliases: list[tuple[str, tuple[str, ...]]] = []
        package = None
        for path in ("package.json", "tsconfig.json", "jsconfig.json"):
            text = self.files.get(path)
            if not text:
                continue
            try:
                data = _jsonc_loads(text)
            except json.JSONDecodeError:
                continue
            if path == "package.json":
                package = data.get("name") if isinstance(data.get("name"), str) else None
                continue
            options = data.get("compilerOptions", {})
            base = options.get("baseUrl")
            if isinstance(base, str):
                bases.append(base.strip("./"))
            for pattern, targets in options.get("paths", {}).items():
                if isinstance(pattern, str) and isinstance(targets, list):
                    aliases.append((pattern, tuple(target for target in targets if isinstance(target, str))))
        return tuple(dict.fromkeys(bases)), tuple(aliases), package

    def _go_module(self) -> str | None:
        text = self.files.get("go.mod", "")
        match = re.search(r"^\s*module\s+(\S+)", text, re.M)
        return match.group(1) if match else None

    def _rust_packages(self) -> tuple[tuple[str, str], ...]:
        packages = []
        for path, text in self.files.items():
            if path != "Cargo.toml" and not path.endswith("/Cargo.toml"):
                continue
            try:
                name = tomllib.loads(text).get("package", {}).get("name")
            except (tomllib.TOMLDecodeError, AttributeError):
                continue
            if isinstance(name, str):
                packages.append((posixpath.dirname(path), name.replace("-", "_")))
        return tuple(packages)

    def _elixir_modules(self) -> dict[str, tuple[str, ...]]:
        modules: dict[str, list[str]] = {}
        pattern = re.compile(r"^\s*defmodule\s+([A-Z][\w.]*)\s+do\b", re.M)
        for path, text in self.files.items():
            if not path.endswith((".ex", ".exs")):
                continue
            for module in pattern.findall(text):
                modules.setdefault(module, []).append(path)
        return {module: tuple(paths) for module, paths in modules.items()}

    def _csharp_namespaces(self) -> dict[str, tuple[str, ...]]:
        namespaces: dict[str, list[str]] = {}
        pattern = re.compile(r"^\s*namespace\s+([A-Za-z_][\w.]*)", re.M)
        for path, text in self.files.items():
            for namespace in pattern.findall(text):
                namespaces.setdefault(namespace, []).append(path)
        return {namespace: tuple(paths) for namespace, paths in namespaces.items()}

    def _swift_external_modules(self) -> frozenset[str]:
        modules = {
            "AppKit", "AVFoundation", "Combine", "Compression", "CoreData",
            "CoreFoundation", "CoreGraphics", "CoreImage", "CoreLocation",
            "CoreText", "CryptoKit", "Darwin", "Dispatch", "Foundation",
            "FoundationNetworking", "FoundationXML", "ImageIO", "IOKit", "MapKit",
            "Metal", "Network", "ObjectiveC", "Observation", "OSLog",
            "PackageDescription", "Security", "StoreKit", "SwiftUI", "SystemConfiguration",
            "UIKit", "UniformTypeIdentifiers", "Vision", "WebKit", "XCTest",
        }
        for path, text in self.files.items():
            if posixpath.basename(path) != "Package.swift":
                continue
            modules.update(re.findall(r"\.product\s*\(\s*name\s*:\s*\"([^\"]+)\"", text))
        return frozenset(modules)

    @staticmethod
    def _variants(base: str, language: str | None) -> list[str]:
        extensions = {
            "python": (".py",),
            "javascript": (".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".json", ".vue"),
            "typescript": (".ts", ".tsx", ".js", ".jsx", ".d.ts", ".json", ".vue"),
            "go": (".go",), "java": (".java",), "c": (".h", ".c"),
            "cpp": (".h", ".hpp", ".hh", ".cpp", ".cc", ".cxx"),
            "csharp": (".cs",), "rust": (".rs",),
            "vue": (".vue", ".js", ".ts"),
            "elixir": (".ex", ".exs"), "ruby": (".rb",),
            "kotlin": (".kt", ".kts"), "swift": (".swift",),
        }.get(language or "", ("",))
        values = [base]
        values.extend(base + extension for extension in extensions)
        indexes = {
            "python": ("__init__.py",),
            "javascript": ("index.js", "index.jsx", "index.ts", "index.tsx", "index.vue"),
            "typescript": ("index.ts", "index.tsx", "index.js", "index.jsx", "index.vue"),
            "vue": ("index.vue", "index.js", "index.ts"),
            "rust": ("mod.rs",),
        }.get(language or "", ())
        values.extend(posixpath.join(base, index) for index in indexes)
        return _unique(values)

    def _match_bases(self, bases: list[str], language: str | None) -> list[str]:
        variants = _unique(variant for base in bases
                           for variant in self._variants(base.strip("/"), language))
        exact = [path for path in variants if path in self.paths]
        if exact:
            return _unique(exact)
        # Covers conventional roots such as src/main/java and packages nested
        # in a monorepo. Multiple suffix matches remain ambiguous.
        return _unique(path for variant in variants if variant
                       for path in self.suffix_paths.get(variant, ()))

    def _match_exact_bases(self, bases: list[str], language: str | None) -> list[str]:
        variants = _unique(variant for base in bases
                           for variant in self._variants(base.strip("/"), language))
        return [path for path in variants if path in self.paths]

    def _python(self, source: str, name: str) -> tuple[list[str], bool, str]:
        leading = len(name) - len(name.lstrip("."))
        module = name.lstrip(".").replace(".", "/")
        if leading:
            directory = posixpath.dirname(source)
            for _ in range(max(0, leading - 1)):
                directory = posixpath.dirname(directory)
            bases = [posixpath.normpath(posixpath.join(directory, module))]
            matches = self._match_exact_bases(bases, "python")
            while not matches and "/" in module:
                module = module.rsplit("/", 1)[0]
                bases = [posixpath.normpath(posixpath.join(directory, module))]
                matches = self._match_exact_bases(bases, "python")
            return matches, False, "python-relative"
        roots = list(self.python_roots)
        source_directory = posixpath.dirname(source)
        if source_directory:
            roots.append(source_directory)
        bases = [posixpath.join(root, module) if root else module for root in roots]
        matches = self._match_exact_bases(bases, "python")
        # ``from pkg.module import Symbol`` and ``from pkg import module`` have
        # the same syntax. Prefer the fully qualified path, then progressively
        # fall back to the containing module.
        while not matches and "/" in module:
            module = module.rsplit("/", 1)[0]
            bases = [posixpath.join(root, module) if root else module for root in roots]
            matches = self._match_exact_bases(bases, "python")
        return matches, not matches, "python-module"

    def _go(self, name: str) -> tuple[list[str], bool, str]:
        if not self.go_module or not (name == self.go_module or name.startswith(self.go_module + "/")):
            return [], True, "go-external-package"
        package = name[len(self.go_module):].strip("/")
        matches = sorted(path for path in self.paths
                         if posixpath.dirname(path) == package
                         and path.endswith(".go") and not path.endswith("_test.go"))
        return matches, False, "go-package"

    def _js(self, source: str, name: str, language: str) -> tuple[list[str], bool, str]:
        if name.startswith("."):
            base = posixpath.normpath(posixpath.join(posixpath.dirname(source), name))
            return self._match_bases([base], language), False, "js-relative"
        bases: list[str] = []
        for pattern, targets in self.js_aliases:
            if "*" in pattern and name.startswith(pattern.split("*", 1)[0]):
                wildcard = name[len(pattern.split("*", 1)[0]):]
                bases.extend(target.replace("*", wildcard).strip("./") for target in targets)
            elif name == pattern:
                bases.extend(target.strip("./") for target in targets)
        if self.js_package and (name == self.js_package or name.startswith(self.js_package + "/")):
            name = name[len(self.js_package):].lstrip("/")
            bases.extend(posixpath.join(root, name) if root else name for root in self.js_base_urls)
        if bases:
            return self._match_bases(bases, language), False, "js-alias"
        return [], True, "js-package"

    def _rust(self, source: str, name: str) -> tuple[list[str], bool, str]:
        clean = name.rstrip(":")
        source_directory = posixpath.dirname(source)
        if "::" not in clean:
            local = self._match_exact_bases(
                [posixpath.join(source_directory, clean)], "rust"
            )
            if local:
                return local, False, "rust-local-module"
        if clean.split("::", 1)[0] in {"std", "core", "alloc", "proc_macro"}:
            return [], True, "rust-standard-crate"
        if not clean.startswith(("crate::", "self::", "super::", "::")):
            root_parts = [part for part in clean.split("::") if part]
            while root_parts:
                root_module = self._match_exact_bases(
                    [posixpath.join("src", *root_parts)], "rust"
                )
                if root_module:
                    return root_module, False, "rust-root-module"
                root_parts.pop()
        cargo_directory = ""
        package_name = None
        for directory, package in sorted(self.rust_packages, key=lambda item: len(item[0]), reverse=True):
            if not directory or source == directory or source.startswith(directory + "/"):
                cargo_directory, package_name = directory, package
                break
        source_root = posixpath.join(cargo_directory, "src") if cargo_directory else "src"
        relative = source[len(source_root):].lstrip("/") if source.startswith(source_root + "/") else source
        if posixpath.basename(relative) in {"lib.rs", "main.rs", "mod.rs"}:
            module_parts = posixpath.dirname(relative).split("/") if posixpath.dirname(relative) else []
        else:
            module_parts = relative.rsplit(".", 1)[0].split("/")

        parts = [part for part in clean.split("::") if part]
        external = False
        referenced_package = next(
            ((directory, package) for directory, package in self.rust_packages
             if parts and parts[0] == package),
            None,
        )
        if referenced_package is not None:
            target_directory, _ = referenced_package
            parts.pop(0)
            target_root = posixpath.join(target_directory, "src") if target_directory else "src"
            combined = list(parts)
            while combined:
                matches = self._match_exact_bases(
                    [posixpath.join(target_root, *combined)], "rust"
                )
                if matches:
                    return matches, False, "rust-workspace-crate"
                combined.pop()
            matches = self._match_exact_bases([posixpath.join(target_root, "lib")], "rust")
            return matches, False, "rust-workspace-crate-root"
        if parts and parts[0] == "crate":
            parts.pop(0)
            base_parts: list[str] = []
        elif parts and parts[0] == "self":
            parts.pop(0)
            base_parts = module_parts
        elif parts and parts[0] == "super":
            base_parts = module_parts
            while parts and parts[0] == "super":
                parts.pop(0)
                if base_parts:
                    base_parts.pop()
        else:
            # Bare names are also used by ``mod child``. Try a child of the
            # current module before classifying the first segment as a crate.
            local = self._match_bases(
                [posixpath.join(source_root, *(module_parts + parts))], "rust"
            )
            if local:
                return local, False, "rust-child-module"
            return [], True, "rust-external-crate"

        combined = base_parts + parts
        while combined:
            base = posixpath.join(source_root, *combined)
            matches = self._match_bases([base], "rust")
            if matches:
                return matches, False, "rust-module"
            combined.pop()
        if package_name and not base_parts:
            matches = self._match_bases([posixpath.join(source_root, "lib")], "rust")
            if matches:
                return matches, False, "rust-crate-root"
        # ``use super::Type`` can refer to an item declared in the parent
        # module file rather than to a child module named Type.
        parent = posixpath.join(source_root, *base_parts)
        matches = self._match_bases([parent], "rust") if base_parts else []
        return matches, external, "rust-parent-module"

    def _elixir(self, name: str) -> tuple[list[str], bool, str]:
        matches = list(self.elixir_modules.get(name, ()))
        return matches, not matches, "elixir-defmodule"

    def _csharp(self, name: str) -> tuple[list[str], bool, str]:
        # ``using System...`` and common framework namespaces are external;
        # repository declarations are resolved conservatively by namespace.
        if name == "System" or name.startswith(("System.", "Microsoft.Extensions.", "Microsoft.AspNetCore.")):
            return [], True, "csharp-external-namespace"
        matches = list(self.csharp_namespaces.get(name, ()))
        if matches:
            return matches, False, "csharp-namespace"
        return [], False, "csharp-namespace"

    def _swift(self, source: str, name: str) -> tuple[list[str], bool, str]:
        root = name.split(".", 1)[0]
        if root in self.swift_external_modules:
            return [], True, "swift-external-module"
        return self._generic(source, name, "swift")

    def _generic(self, source: str, name: str, language: str | None) -> tuple[list[str], bool, str]:
        clean = name.strip("'\";")
        if language == "java" and clean.endswith("."):
            package = clean.rstrip(".").replace(".", "/") + "/"
            matches = sorted(path for path in self.paths
                             if path.endswith(".java")
                             and (path.startswith(package) or f"/{package}" in path))
            return matches, False, "java-wildcard-package"
        if language == "go" and self.go_module and clean.startswith(self.go_module):
            clean = clean[len(self.go_module):].lstrip("/")
        elif language == "rust":
            clean = clean.replace("crate::", "").replace("self::", "").replace("::", "/")
        elif language in {"c", "cpp"}:
            pass
        else:
            clean = clean.replace(".", "/") if "/" not in clean else clean
        bases = [clean, posixpath.normpath(posixpath.join(posixpath.dirname(source), clean))]
        matches = self._match_bases(bases, language)
        go_package = False
        if language == "go" and not matches:
            package_dir = clean.rstrip("/") + "/"
            matches = sorted(path for path in self.paths
                             if path.startswith(package_dir) and path.endswith(".go") and not path.endswith("_test.go"))
            go_package = bool(matches)
        if language in {"java", "rust"}:
            # Imports often end in a class, method or symbol. Walk toward the
            # containing class/module until a repository path is found.
            separator = "/"
            while not matches and separator in clean:
                clean = clean.rsplit(separator, 1)[0]
                matches = self._match_bases(
                    [clean, posixpath.normpath(posixpath.join(posixpath.dirname(source), clean))],
                    language,
                )
        external = not matches and (
            (language == "go" and (not self.go_module or not name.startswith(self.go_module))) or
            (language == "java" and name.startswith(("java.", "javax.", "jakarta."))) or
            (language in {"c", "cpp"} and not name.startswith(".")) or
            (language == "rust" and not name.startswith(("crate::", "self::", "super::")))
        )
        evidence = ("go-package" if go_package else
                    "c-include-candidates" if language in {"c", "cpp"} else
                    "path-match")
        return matches, external, evidence

    def resolve(self, source: str, name: str, language: str | None) -> Resolution:
        if language == "python":
            matches, external, evidence = self._python(source, name)
        elif language in {"javascript", "typescript"}:
            matches, external, evidence = self._js(source, name, language)
        elif language == "rust":
            matches, external, evidence = self._rust(source, name)
        elif language == "elixir":
            matches, external, evidence = self._elixir(name)
        elif language == "csharp":
            matches, external, evidence = self._csharp(name)
        elif language == "swift":
            matches, external, evidence = self._swift(source, name)
        elif language == "go":
            matches, external, evidence = self._go(name)
        else:
            matches, external, evidence = self._generic(source, name, language)
        matches = [path for path in matches if path != source]
        if len(matches) == 1:
            return Resolution("internal", matches[0], tuple(matches), .98, evidence)
        if len(matches) > 1:
            candidates = (matches if evidence in {"java-wildcard-package", "go-package",
                                                   "c-include-candidates"}
                          else matches[:16])
            return Resolution("ambiguous", None, tuple(candidates), .45, evidence)
        if external:
            return Resolution("external", None, (), .95, evidence)
        return Resolution("unresolved", None, (), 0.0, evidence)