Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(graph): bind C# new X() to a type another namespace declares (#4822)

Swati Ahuja277abbebe8d3
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
index 8b5ec269d..78beb3a15 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -18,9 +18,11 @@ from .call_receiver_typing import (
_store_capped,
)
from .lang_helpers.kotlin_lambdas import in_lambda
+from .languages.csharp_same_namespace import _BCL_COMMON_TYPES, _USING_ALIAS_RE, _USING_NS_RE
from .languages.receiver_types import dart_named_constructors
from .models import CallSite, ParsedFile, Symbol
from .resolved_call import ResolvedCall
+from .resolvers.dotnet.namespace_map import declared_namespaces, scan_type_declarations
from .resolvers.jvm_gradle import (
SourceSetGraph,
build_source_set_graph,
@@ -40,7 +42,9 @@ class _LanguageCallStrategies:
after all of them, so a strategy there only ever sees a call nothing else
claimed and can only add an edge. ``constructor`` runs ahead of ``member``,
even for a name no symbol carries, since a named constructor is no symbol.
- All four stop at the first hit.
+ ``free_fallback`` runs after the import and inherited tiers and before the
+ global one, so it sees only a bare call nothing grounded claimed.
+ All five stop at the first hit.
Strategies are named rather than bound so a probe can substitute one.
``member_bare_fallback`` lets a member or chained call nothing claimed fall
@@ -52,6 +56,7 @@ class _LanguageCallStrategies:
"""
free: tuple[str, ...] = ()
+ free_fallback: tuple[str, ...] = ()
constructor: tuple[str, ...] = ()
member: tuple[str, ...] = ()
member_fallback: tuple[str, ...] = ()
@@ -121,7 +126,9 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
"kotlin": replace(
_JVM_STRATEGIES, member_fallback=_TYPED_RECEIVER, chain_bare_fallback=False
),
- "csharp": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
+ "csharp": _LanguageCallStrategies(
+ free_fallback=("_resolve_csharp_constructed_type",), member_fallback=_TYPED_RECEIVER
+ ),
"python": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
# Swift and Dart register the fallback: neither has a package tier of its
# own, so a typed receiver is looked for in the caller's file, in what the
@@ -153,6 +160,44 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
}
+def _csharp_lookup_levels(
+ text: str, project_usings: frozenset[str]
+) -> tuple[tuple[frozenset[str], str, float], ...]:
+ """Where C# looks for a bare type name in *text*, as ``(namespaces, origin, confidence)``.
+
+ Each namespace the file declares and each one around it, innermost first,
+ then the global namespace with every ``using`` as one level: two types the
+ usings bring in are ambiguous to the compiler too. Ceiling: the text is
+ read as one scope, so a ``using`` inside a namespace block counts at file
+ level and a file declaring two namespaces sees both chains.
+ """
+ chain = {
+ ns.rsplit(".", depth)[0]
+ for ns in declared_namespaces(text)
+ for depth in range(ns.count(".") + 1)
+ }
+ innermost_first = sorted(chain, key=lambda ns: -ns.count("."))
+ # ``using static`` names a type, whose members are not types in scope.
+ usings = {m.group(1) for m in _USING_NS_RE.finditer(text) if "static" not in m.group(0)}
+ return (
+ *((frozenset({ns}), "same_package", 0.90) for ns in innermost_first),
+ (frozenset({"", *usings, *project_usings}), "import_merged", 0.85),
+ )
+
+
+def _type_argument_count(line: str, at: int) -> int:
+ """The type arguments a ``<..>`` at *at* in *line* lists, 0 when none opens there."""
+ if line[at : at + 1] != "<":
+ return 0
+ depth, count = 0, 1
+ for char in line[at:]:
+ depth += (char == "<") - (char == ">")
+ if depth == 0:
+ return count
+ count += char == "," and depth == 1
+ return count
+
+
class LanguageStrategiesMixin:
"""Language-specific strategies and the lazy workspace indexes they read."""
@@ -188,6 +233,13 @@ class LanguageStrategiesMixin:
self._cpp_index: Any = None
self._cpp_index_built = False
+ # {C# file: {top-level type name: namespace}}, read off its source, and
+ # {C# file: where a bare type name in it is looked up}.
+ self._csharp_type_namespaces: dict[str, dict[str, str]] = {}
+ self._csharp_lookups: dict[
+ str, tuple[frozenset[str], tuple[tuple[frozenset[str], str, float], ...]]
+ ] = {}
+
# Independent builds in the repo (lazy BuildRoots), and the build roots
# each file's imports land in.
self._build_roots: Any = None
@@ -788,6 +840,135 @@ class LanguageStrategiesMixin:
type_name, _, _ = self._receiver_type_and_scope(file_path, caller_id, "apex", head)
return type_name is not None
+ def _resolve_csharp_constructed_type(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """``new Foo(..)`` that no import tier reached: the one type of that name in scope.
+
+ C# finds a bare type name in the caller's namespace, then in each one
+ around it, then in the namespaces a ``using`` brings in: the file's
+ own, every ``global using`` in its project and the project's MSBuild
+ ``<Using>`` items. Two types at the first level holding one refuse.
+ With none visible, a name the repository declares once is taken, as
+ the global tier would were the constructor not a second symbol of
+ that name.
+ """
+ name = call.target_name
+ if call.receiver_name or name not in self._csharp_type_names:
+ return None
+ arity = self._constructed_arity(file_path, call)
+ found = None if arity is None else self._csharp_type_in_scope(file_path, name, arity)
+ if found is None:
+ return None
+ type_id, origin, confidence = found
+ return self._csharp_type_call(type_id, caller_id, call, origin, confidence)
+
+ def _constructed_arity(self, file_path: str, call: CallSite) -> int | None:
+ """How many type arguments *call*'s line writes after ``new Name``, None for no ``new``.
+
+ A site records neither ``new`` nor its type arguments, and a bare
+ ``Foo()`` may be a local function or a ``using static`` method no
+ tier indexed.
+ """
+ lines = self._lines_of(file_path)
+ line = lines[call.line - 1] if 0 < call.line <= len(lines) else ""
+ match = re.search(rf"\bnew\s+{re.escape(call.target_name)}\b\s*", line)
+ if match is None:
+ return None
+ return _type_argument_count(line, match.end())
+
+ def _csharp_type_in_scope(
+ self, file_path: str, name: str, arity: int
+ ) -> tuple[str, str, float] | None:
+ """``(type id, origin, confidence)`` of the one type *name* with *arity* means here."""
+ types = [
+ (ns, type_id) for ns, type_id, n in self._csharp_constructible_types(name) if n == arity
+ ]
+ aliases, levels = self._csharp_lookup(file_path)
+ if not types or name in aliases: # ``using Foo = X.Bar;`` shadows every type Foo
+ return None
+ for level, origin, confidence in levels:
+ visible = [type_id for namespace, type_id in types if namespace in level]
+ if visible:
+ return (visible[0], origin, confidence) if len(visible) == 1 else None
+ if len(types) > 1 or name in _BCL_COMMON_TYPES:
+ return None
+ return types[0][1], "global_unique", 0.50
+
+ def _csharp_lookup(
+ self, file_path: str
+ ) -> tuple[frozenset[str], tuple[tuple[frozenset[str], str, float], ...]]:
+ """*file_path*'s ``using`` aliases and the levels a bare type name is looked up in."""
+ found = self._csharp_lookups.get(file_path)
+ if found is None:
+ text = self._text_of(file_path)
+ found = (
+ frozenset(m.group(1) for m in _USING_ALIAS_RE.finditer(text)),
+ _csharp_lookup_levels(
+ text, self._csharp_project_usings.get(file_path, frozenset())
+ ),
+ )
+ self._csharp_lookups[file_path] = found
+ return found
+
+ def _csharp_constructible_types(self, name: str) -> list[tuple[str, str, int]]:
+ """``(namespace, type id, arity)`` for each top-level C# class or struct named *name*.
+
+ The fragments of one ``partial`` type count once, under the first;
+ ``Box`` and ``Box<T>`` are two types.
+ """
+ found: dict[tuple[str, tuple[str, ...], int], str] = {}
+ for sym_id in self._global_symbols.get(name, ()):
+ symbol = self._symbols_by_id[sym_id]
+ if symbol.language != "csharp" or symbol.kind not in ("class", "struct"):
+ continue
+ path = self._symbol_paths_by_id[sym_id]
+ namespace = self._csharp_top_level_types(path).get(name)
+ if namespace is None: # nested: visible by bare name only inside its outer type
+ continue
+ fragments = self._partial_fragments.get((path, name)) or (path,)
+ found.setdefault((namespace, fragments, symbol.type_parameter_count or 0), sym_id)
+ return [(namespace, sym_id, arity) for (namespace, _, arity), sym_id in found.items()]
+
+ def _csharp_top_level_types(self, path: str) -> dict[str, str]:
+ """``{type name: namespace}`` for the top-level types *path* declares."""
+ types = self._csharp_type_namespaces.get(path)
+ if types is None:
+ types = {
+ decl.name: decl.namespace
+ for decl in scan_type_declarations(self._text_of(path))
+ if decl.qualified == decl.name
+ }
+ self._csharp_type_namespaces[path] = types
+ return types
+
+ def _csharp_type_call(
+ self, type_id: str, caller_id: str, call: CallSite, origin: str, confidence: float
+ ) -> ResolvedCall | None:
+ """``new T(..)``: *type_id*'s constructor, else the type.
+
+ Also the type when ``partial`` fragments each declare constructors:
+ an overload set is chosen within one file, so it could not pick
+ among them.
+ """
+ name = call.target_name
+ path = self._symbol_paths_by_id[type_id]
+ # A generic type beside a same-named plain one owns its members as ``Box`1``.
+ arity = self._symbols_by_id[type_id].type_parameter_count or 0
+ owner = f"{name}`{arity}" if arity and type_id.endswith(f"`{arity}") else name
+ ctors = [
+ ctor
+ for fragment in self._partial_fragments.get((path, name)) or (path,)
+ if (ctor := self._file_methods.get(fragment, {}).get((owner, name))) is not None
+ ]
+ target = ctors[0] if len(ctors) == 1 else type_id
+ if target == caller_id:
+ return None
+ return ResolvedCall(caller_id, target, confidence, call.line, origin)
+
def _resolve_dart_named_constructor(
self,
file_path: str,
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 4f82259b0..2253a11c8 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -316,6 +316,7 @@ class CallResolver(
heritage_parents: dict[str, set[str]] | None = None,
return_type_chain_languages: frozenset[str] | None = None,
partial_fragments: dict[tuple[str, str], tuple[str, ...]] | None = None,
+ csharp_project_usings: dict[str, frozenset[str]] | None = None,
) -> None:
# {type symbol id: parent type symbol ids}, from the caller's already
# resolved heritage. Absent when the resolver is built standalone, in
@@ -324,6 +325,9 @@ class CallResolver(
# {(file, partial type name): files declaring a fragment of it}, from
# the builder's C#/VB.NET partial pass. Empty in every other language.
self._partial_fragments = partial_fragments or {}
+ # {C# file: the namespaces its project's global usings and MSBuild
+ # ``<Using>`` items bring in}, from the builder's .NET project index.
+ self._csharp_project_usings = csharp_project_usings or {}
self._return_type_chain_languages = (
PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES
if return_type_chain_languages is None
@@ -1646,6 +1650,11 @@ class CallResolver(
inherited = self._implicit_inherited_call(file_path, call, caller_id)
if inherited is not None:
return inherited
+ hit = self._first_strategy_hit(
+ self._strategies_for(file_path).free_fallback, file_path, call, caller_id
+ )
+ if hit is not None:
+ return hit
# Tier 3: global unique match, only within the same language.
# Uniqueness is judged before filtering data members, on purpose: filtering
# them out first would re-uniquify a name a field and a method share. A
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 9e9638d45..4c4e7c719 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -7,6 +7,7 @@ emitting EXTENDS/IMPLEMENTS, ``reads``, and ``calls`` edges respectively.
from __future__ import annotations
from collections import defaultdict
+from collections.abc import Iterable
from typing import Any
import structlog
@@ -209,6 +210,8 @@ class ResolveMixin:
added = resolve_csharp_same_namespace_refs(
self._graph, index, cs_texts, repo
)
+ if index is not None:
+ self._csharp_project_usings = _project_usings_by_file(index, cs_texts)
log.info("same_namespace_edges", language="csharp", added=added)
if "vbnet" in languages:
vb_texts = collect_source_texts(
@@ -626,6 +629,7 @@ class ResolveMixin:
import_maps=self._shared_import_maps(),
heritage_parents=self._heritage_parents(),
partial_fragments=self._partial_fragments,
+ csharp_project_usings=self._csharp_project_usings,
)
# Record which C/C++ declarations were paired with a definition. The
@@ -849,3 +853,17 @@ def _decorator_sites(parsed: ParsedFile, registrar_names: set[str]) -> list[Call
)
)
return sites
+
+
+def _project_usings_by_file(index: Any, paths: Iterable[str]) -> dict[str, frozenset[str]]:
+ """``{C# file: what its project's global usings bring in}``, one set per project."""
+ per_project: dict[Any, frozenset[str]] = {}
+ out: dict[str, frozenset[str]] = {}
+ for path in paths:
+ csproj = index.file_to_project.get((index.repo_path / path).resolve())
+ if csproj is None:
+ continue
+ if csproj not in per_project:
+ per_project[csproj] = frozenset(index.globals_for_project(csproj))
+ out[path] = per_project[csproj]
+ return out
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index a9699c39b..e6bb12844 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -111,6 +111,9 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
# of that type}, filled by ``_resolve_dotnet_partials`` so the call
# resolver can treat the fragments as the one class scope they are.
self._partial_fragments: dict[tuple[str, str], tuple[str, ...]] = {}
+ # {C# file: namespaces its project's global usings bring in}, filled by
+ # ``_resolve_dotnet_same_namespace`` for the call resolver.
+ self._csharp_project_usings: dict[str, frozenset[str]] = {}
# ``TraversalStats`` for the walk that produced this graph, stashed by
# the caller. Carried here rather than widened into the return tuples
# of ``build_repo_graph``/``rebuild_graph_and_git`` (ten unpack sites
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
index 5b0f05ad6..7ffe37358 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
@@ -14,10 +14,12 @@ from repowise.core.ingestion.source_text import source_text
from .global_usings import collect_project_global_usings
from .msbuild import (
MSBuildProject,
+ SharedUsings,
find_csproj_files,
find_vbproj_files,
parse_csproj,
path_has_dotnet_scan_skip_dir,
+ shared_build_usings,
)
from .namespace_map import build_namespace_map, build_vb_namespace_map
from .solution import find_sln_files, parse_sln
@@ -379,6 +381,7 @@ def build_index(
continue
texts_by_proj.setdefault(csproj, {})[f] = text
+ shared_usings: SharedUsings = {}
for proj in index.projects.values():
# Heuristic: presence of any AspNetCore PackageReference flags the
# web SDK's expanded implicit-using set.
@@ -393,6 +396,7 @@ def build_index(
)
# Honour <Using Include="X"/> ItemGroup entries on top of file scans.
globals_set.update(proj.project_usings)
+ globals_set.update(shared_build_usings(proj, repo_path, shared_usings))
index.project_globals[proj.project_dir] = globals_set
log.info(
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
index e42a7ba33..1430dba0b 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
@@ -10,6 +10,7 @@ tolerates both SDK-style and legacy XML (``<Project ToolsVersion="...">``).
from __future__ import annotations
+import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -75,6 +76,9 @@ class MSBuildProject:
#: build file that adds test packages only ``Condition="'$(IsTestProject)'
#: == 'true'"`` does not make every project below it a test project.
unconditional_package_references: set[str] = field(default_factory=set)
+ #: Literal ``<PropertyGroup>`` values outside any ``Condition``, keyed
+ #: lowercase as MSBuild compares them, for a shared build file's conditions.
+ properties: dict[str, str] = field(default_factory=dict)
@property
def name(self) -> str:
@@ -191,10 +195,97 @@ def parse_csproj(csproj_path: Path) -> MSBuildProject | None:
ns = elem.get("Include")
if ns:
project.project_usings.add(ns.strip())
+ elif tag == "PropertyGroup" and id(elem) not in conditioned:
+ for prop in elem:
+ if prop.text and id(prop) not in conditioned:
+ project.properties[_local(prop.tag).lower()] = prop.text.strip()
return project
+_SHARED_BUILD_FILES = ("Directory.Build.props", "Directory.Build.targets")
+
+# ``'$(Name)' == 'value'``, the one condition shape read; any other is unknown.
+_PROPERTY_CONDITION_RE = re.compile(r"^\s*'\$\((\w+)\)'\s*(==|!=)\s*'([^'$]*)'\s*$")
+
+
+def _condition_holds(condition: str, properties: dict[str, str]) -> bool:
+ """Whether *condition* holds for *properties*; False when that is unknown.
+
+ Unknown is any shape but a literal comparison, or a property the project
+ file does not set: it may come from the SDK or another imported file.
+ """
+ match = _PROPERTY_CONDITION_RE.match(condition)
+ if match is None or match.group(1).lower() not in properties:
+ return False
+ name, op, value = match.groups()
+ equal = properties[name.lower()].lower() == value.lower()
+ return equal if op == "==" else not equal
+
+
+# {shared build file: each ``<Using Include>`` item with the conditions over it}
+SharedUsings = dict[Path, tuple[tuple[str, tuple[str, ...]], ...]]
+
+
+def shared_build_usings(project: MSBuildProject, repo_root: Path, cache: SharedUsings) -> set[str]:
+ """``<Using Include>`` items the nearest ``Directory.Build.props`` and
+ ``.targets`` above *project* give it, each file read once per *cache*.
+
+ MSBuild imports only the nearest of each name. An item under a condition
+ counts when the condition compares a property the project file sets
+ literally (``'$(IncludeUsings)' == 'true'``); any other condition drops it.
+ Ceiling: a ``<Using Remove>`` and a nearest file importing its parent are
+ not read.
+ """
+ usings: set[str] = set()
+ for name in _SHARED_BUILD_FILES:
+ path = _nearest_above(project.project_dir, repo_root, name)
+ if path is None:
+ continue
+ if path not in cache:
+ cache[path] = _using_items(path)
+ for ns, conditions in cache[path]:
+ if all(_condition_holds(c, project.properties) for c in conditions):
+ usings.add(ns)
+ return usings
+
+
+def _using_items(path: Path) -> tuple[tuple[str, tuple[str, ...]], ...]:
+ """Each ``<Using Include>`` (C#) or ``<Import Include>`` (VB) item in *path*,
+ with the ``Condition`` on it and on each element around it."""
+ try:
+ root = ET.parse(path).getroot()
+ except (ET.ParseError, OSError):
+ return ()
+ parents = {child: parent for parent in root.iter() for child in parent}
+ items = []
+ for elem in root.iter():
+ ns = elem.get("Include") if _local(elem.tag) in ("Using", "Import") else None
+ if not ns:
+ continue
+ conditions = []
+ node: ET.Element | None = elem
+ while node is not None:
+ if node.get("Condition") is not None:
+ conditions.append(node.get("Condition"))
+ node = parents.get(node)
+ items.append((ns.strip(), tuple(conditions)))
+ return tuple(items)
+
+
+def _nearest_above(start: Path, repo_root: Path, name: str) -> Path | None:
+ """The first *name* in *start* or a directory above it, up to *repo_root*."""
+ if not start.is_relative_to(repo_root):
+ return None
+ for directory in (start, *start.parents):
+ candidate = directory / name
+ if candidate.is_file():
+ return candidate
+ if directory == repo_root:
+ return None
+ return None
+
+
def _find_project_files(
repo_path: Path,
pattern: str,
diff --git a/tests/unit/ingestion/test_csharp_constructed_types.py b/tests/unit/ingestion/test_csharp_constructed_types.py
new file mode 100644
index 000000000..401104f95
--- /dev/null
+++ b/tests/unit/ingestion/test_csharp_constructed_types.py
@@ -0,0 +1,168 @@
+"""``new R(..)`` of a C# type in another namespace, reached with no import tier.
+
+C# sees a bare type name in the caller's namespace and the ones around it, then
+through the file's ``using`` directives, every ``global using`` in the project
+and the project's MSBuild ``<Using>`` items. Before this a constructor with no
+``using`` behind it got no edge at all: the class and its constructor are two
+symbols of one name, so the repo-wide tier read the name as ambiguous.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+R_IN_AB = "namespace A.B;\npublic class R\n{\n public R(int n) { }\n}\n"
+R_IN_AD = "namespace A.D;\npublic class R\n{\n public R(int n) { }\n}\n"
+CALLER = "namespace A;\nclass C\n{\n void M()\n {\n var r = new R(1);\n }\n}\n"
+USES_AB = '<Project Sdk="Microsoft.NET.Sdk">\n <ItemGroup>\n <Using Include="A.B" />\n </ItemGroup>\n</Project>\n'
+
+
+def _calls_from_m(
+ tmp_path: Path, files: dict[str, str], caller: str = "C.cs::C::M"
+) -> set[tuple[str, str]]:
+ """``(callee, origin)`` of every call edge *caller* gets in a graph of *files*."""
+ for rel, text in files.items():
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=tmp_path)
+ for fi in FileTraverser(tmp_path).traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ graph = builder.build()
+ return {
+ (callee, data.get("resolution_origin"))
+ for _, callee, data in graph.out_edges(caller, data=True)
+ if data.get("edge_type") == "calls"
+ }
+
+
+class TestOneVisibleType:
+ def test_a_parent_namespace_sees_its_child_s_type_unique_in_the_repo(
+ self, tmp_path: Path
+ ) -> None:
+ """The issue's repro: no ``using``, one ``R`` in the repository."""
+ assert _calls_from_m(tmp_path, {"R.cs": R_IN_AB, "C.cs": CALLER}) == {
+ ("R.cs::R::R", "global_unique")
+ }
+
+ def test_the_caller_s_own_namespace(self, tmp_path: Path) -> None:
+ files = {"R.cs": R_IN_AB.replace("A.B", "A"), "R2.cs": R_IN_AD, "C.cs": CALLER}
+ assert _calls_from_m(tmp_path, files) == {("R.cs::R::R", "same_package")}
+
+ def test_a_namespace_around_the_caller_s(self, tmp_path: Path) -> None:
+ files = {
+ "R.cs": R_IN_AB.replace("A.B", "A"),
+ "R2.cs": R_IN_AD,
+ "C.cs": CALLER.replace("namespace A;", "namespace A.X.Y;"),
+ }
+ assert _calls_from_m(tmp_path, files) == {("R.cs::R::R", "same_package")}
+
+ def test_a_csproj_using_item(self, tmp_path: Path) -> None:
+ files = {"P.csproj": USES_AB, "R.cs": R_IN_AB, "R2.cs": R_IN_AD, "C.cs": CALLER}
+ assert _calls_from_m(tmp_path, files) == {("R.cs::R::R", "import_merged")}
+
+ def test_a_global_using_in_another_file_of_the_project(self, tmp_path: Path) -> None:
+ files = {
+ "P.csproj": '<Project Sdk="Microsoft.NET.Sdk" />\n',
+ "Usings.cs": "global using A.B;\n",
+ "R.cs": R_IN_AB,
+ "R2.cs": R_IN_AD,
+ "C.cs": CALLER,
+ }
+ assert _calls_from_m(tmp_path, files) == {("R.cs::R::R", "import_merged")}
+
+ @pytest.mark.parametrize(
+ ("value", "expected"), [("true", {("R.cs::R::R", "import_merged")}), ("false", set())]
+ )
+ def test_a_directory_build_using_under_a_property_condition(
+ self, tmp_path: Path, value: str, expected: set[tuple[str, str]]
+ ) -> None:
+ files = {
+ "Directory.Build.targets": (
+ "<Project>\n <ItemGroup Condition=\"'$(IncludeAb)' == 'true'\">\n"
+ ' <Using Include="A.B" />\n </ItemGroup>\n</Project>\n'
+ ),
+ "src/P.csproj": (
+ '<Project Sdk="Microsoft.NET.Sdk">\n <PropertyGroup>\n'
+ f" <IncludeAb>{value}</IncludeAb>\n </PropertyGroup>\n</Project>\n"
+ ),
+ "R.cs": R_IN_AB,
+ "R2.cs": R_IN_AD,
+ "src/C.cs": CALLER,
+ }
+ assert _calls_from_m(tmp_path, files, "src/C.cs::C::M") == expected
+
+ def test_constructors_split_across_partial_fragments_answer_with_the_type(
+ self, tmp_path: Path
+ ) -> None:
+ """Overloads are chosen within one file, so two fragments' constructors are left alone."""
+ part = "namespace A.B;\npublic partial class R\n{{\n public R({0} n) {{ }}\n}}\n"
+ files = {"R1.cs": part.format("int"), "R2.cs": part.format("string"), "C.cs": CALLER}
+ calls = _calls_from_m(tmp_path, files)
+ assert calls in ({("R1.cs::R", "global_unique")}, {("R2.cs::R", "global_unique")})
+
+ @pytest.mark.parametrize(
+ ("written", "expected"), [("new R(1)", "R.cs::R::R"), ("new R<int>(1)", "R.cs::R`1::R")]
+ )
+ def test_the_type_arguments_written_pick_plain_or_generic(
+ self, tmp_path: Path, written: str, expected: str
+ ) -> None:
+ both = (
+ "namespace A.B;\npublic class R\n{\n public R(int n) { }\n}\n"
+ "public class R<T>\n{\n public R(T n) { }\n}\n"
+ )
+ files = {"R.cs": both, "C.cs": CALLER.replace("new R(1)", written)}
+ assert _calls_from_m(tmp_path, files) == {(expected, "global_unique")}
+
+
+class TestRefusals:
+ def test_two_types_of_the_name_and_no_using(self, tmp_path: Path) -> None:
+ files = {"R.cs": R_IN_AB, "R2.cs": R_IN_AD, "C.cs": CALLER}
+ assert _calls_from_m(tmp_path, files) == set()
+
+ def test_two_types_the_project_usings_bring_in(self, tmp_path: Path) -> None:
+ files = {
+ "P.csproj": USES_AB.replace("</ItemGroup>", ' <Using Include="A.D" />\n </ItemGroup>'),
+ "R.cs": R_IN_AB,
+ "R2.cs": R_IN_AD,
+ "C.cs": CALLER,
+ }
+ assert _calls_from_m(tmp_path, files) == set()
+
+ def test_a_bare_call_that_is_not_a_construction(self, tmp_path: Path) -> None:
+ """``R(1)`` with no ``new`` is a local function or a ``using static`` method."""
+ files = {"R.cs": R_IN_AB, "C.cs": CALLER.replace("var r = new R(1);", "R(1);")}
+ assert _calls_from_m(tmp_path, files) == set()
+
+ def test_a_nested_type_is_not_visible_by_its_bare_name(self, tmp_path: Path) -> None:
+ nested = (
+ "namespace A.B;\npublic class Outer\n{\n"
+ " public class R\n {\n public R(int n) { }\n }\n}\n"
+ )
+ assert _calls_from_m(tmp_path, {"Outer.cs": nested, "C.cs": CALLER}) == set()
+
+ def test_a_using_alias_of_the_name_shadows_the_repo_type(self, tmp_path: Path) -> None:
+ caller = "using Widget = X.Other;\n" + CALLER.replace("new R(1)", "new Widget(1)")
+ widget = R_IN_AB.replace("class R", "class Widget").replace("public R(", "public Widget(")
+ assert _calls_from_m(tmp_path, {"Impl.cs": widget, "C.cs": caller}) == set()
+
+ def test_a_bcl_name_with_one_repo_declaration_is_not_taken(self, tmp_path: Path) -> None:
+ """``new List(1)`` with no ``using`` of the repo's namespace may mean the BCL type."""
+ repo_list = R_IN_AB.replace("class R", "class List").replace("public R(", "public List(")
+ caller = CALLER.replace("new R(1)", "new List(1)")
+ assert _calls_from_m(tmp_path, {"List.cs": repo_list, "C.cs": caller}) == set()
+
+ def test_commas_inside_nested_type_arguments_are_not_counted(self, tmp_path: Path) -> None:
+ pair = (
+ "namespace A.B;\npublic class Pair<K, V>\n{\n public Pair(K k) { }\n}\n"
+ "public class Pair<K, V, W>\n{\n public Pair(K k) { }\n}\n"
+ )
+ caller = CALLER.replace("new R(1)", "new Pair<Dictionary<string, int>, string>(1)")
+ assert _calls_from_m(tmp_path, {"Pair.cs": pair, "C.cs": caller}) == {
+ ("Pair.cs::Pair`2::Pair", "global_unique")
+ }