Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ingestion): index Razor/Blazor markup (.razor, .cshtml) into the graph (#1962)
Nehal kanak kuniyil thottathilbeebcd6a038d
diff --git a/README.md b/README.mdindex 81c4a1393..33918dfcb 100644--- a/README.md+++ b/README.md@@ -473,7 +473,7 @@ the orchestrators. Full matrix and the contributor recipe:## Supported languages-**19 languages parsed to AST · 35 on a five-rung ladder · framework-aware across+**20 languages parsed to AST · 36 on a five-rung ladder · framework-aware acrossall of them.**"Do you support X" has five useful answers, not two, so languages land on a@@ -507,6 +507,7 @@ ladder and every rung says what it buys you.<img src="https://img.shields.io/badge/Delphi-EE1F35?style=flat-square&logo=delphi&logoColor=white" alt="Object Pascal / Delphi" /> <strong>· Partial </strong><img src="https://img.shields.io/badge/Luau-00A2FF?style=flat-square&logo=lua&logoColor=white" alt="Luau" />+ <img src="https://img.shields.io/badge/Razor-512BD4?style=flat-square&logo=blazor&logoColor=white" alt="Razor / Blazor" /></p>Below those two rungs the ladder keeps going, and a language on a lower rung is@@ -516,7 +517,7 @@ still doing real work rather than being ignored:|---|---|---|| **Full** (13) | Python · TypeScript · JavaScript · Svelte · Vue · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges, **and code-health markers** || **Good** (5) | C · Swift · PHP · Dart · Object Pascal | All of the above except the full health suite |-| **Partial** (1) | Luau / Roblox | AST symbols and `require()` resolution, Rojo and `.luaurc` aware |+| **Partial** (2) | Luau / Roblox · Razor / Blazor | Luau: AST symbols and `require()` resolution, Rojo and `.luaurc` aware. Razor: component symbols, `@code` and component-tag call edges, C# health markers; no import resolution yet || | | ⎯⎯ *tree-sitter parsing stops here; the rungs below come from git and imports* ⎯⎯ || **Lightweight** (7) | Elixir · Clojure · Haskell · Lean 4 · Erlang · F# · HTML | A real file-to-file import graph, and no symbol-level claims || **Structural** (9) | Objective-C · R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history: blame, hotspots, co-change, ownership, bug history |diff --git a/ROADMAP.md b/ROADMAP.mdindex c1287e635..52559be3f 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -34,7 +34,7 @@ Languages land on a five-rung ladder rather than a yes/no list, because "do yousupport X" has five different useful answers. Each rung is defined, with what itbuys you, in[docs/layers/LANGUAGE_SUPPORT.md](docs/layers/LANGUAGE_SUPPORT.md). Today that-ladder covers **35 languages, 19 of them parsed to a full AST**.+ladder covers **36 languages, 20 of them parsed to a full AST**.### New languages@@ -62,6 +62,7 @@ ladder covers **35 languages, 19 of them parsed to a full AST**.| C | Planned | It shares the C++ grammar for parsing but reaches no health walker map, so it gets graph coverage without markers || SQL / dbt | Planned | Column-level blast radius || Object Pascal | Planned | Assertion and performance markers, a dedicated `uses` resolver |+| Razor / Blazor | Planned | `@using` and `@inject` edges so component tags resolve through imports, `@code` members as symbols rather than call edges only |### Need a language that is not herediff --git a/docs/README.md b/docs/README.mdindex 6ab9cb6d8..db7116195 100644--- a/docs/README.md+++ b/docs/README.md@@ -59,7 +59,7 @@ your agent in under five minutes, with no API key.| [layers/DECISIONS.md](layers/DECISIONS.md) | Architectural decisions mined from your repo and from your own agent sessions || [layers/DEAD_CODE.md](layers/DEAD_CODE.md) | Unreachable files, unused exports, and zombie packages by confidence tier || [layers/SECURITY.md](layers/SECURITY.md) | The local pattern scan: what the sixteen patterns catch, what they do not, and how far to trust the result |-| [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 19 parsed to a full AST, 35 on the five-rung ladder |+| [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 20 parsed to a full AST, 36 on the five-rung ladder || [layers/WIKI.md](layers/WIKI.md) | The generated wiki: page types, what `update` re-renders, styles, output language |## Scale itdiff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex f6ded9161..875f82a07 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -608,17 +608,19 @@ same clean projection the ingestion parser does.### The locator registryOnly step 1 differs per language, so it lives behind `_LOCATORS`, a dict of-`Locator(grammar_module, visit, component_name)`. The blanking, fencing, caching+`Locator(grammar_module, visit, component_name)` for a grammar-backed markup+language, or `Locator(byte_scan, component_name)` when no grammar exists and+the regions are found by walking the bytes. The blanking, fencing, cachingand offset invariants are shared; adding a markup language means adding a`Locator`, not a second copy of the walker.-| | Svelte | Vue |-|---|---|---|-| Grammar | `tree-sitter-svelte` | `tree-sitter-html` |-| Expression nodes | `svelte_raw_text` under `expression` / `if_start` / `key_start` / `html_tag` | `attribute_value` inside `quoted_attribute_value`; `{{ … }}` scanned inside `text` |-| Fence bytes | the surrounding `{` `}` | the surrounding `"` or `'` |-| Skipped binding forms | `{#each}`, `{#await}` heads | `v-for`, `v-slot` / `#default` |-| Non-component tags | the `svelte:*` namespace | `<KeepAlive>`, `<Transition>`, `<RouterView>`, … in either spelling |+| | Svelte | Vue | Razor |+|---|---|---|---|+| Grammar | `tree-sitter-svelte` | `tree-sitter-html` | none; byte scan, projected to C# |+| Expression nodes | `svelte_raw_text` under `expression` / `if_start` / `key_start` / `html_tag` | `attribute_value` inside `quoted_attribute_value`; `{{ … }}` scanned inside `text` | brace-matched `@code { }`, `@functions { }`, `@{ }` interiors |+| Fence bytes | the surrounding `{` `}` | the surrounding `"` or `'` | the surrounding `{` `}` |+| Skipped binding forms | `{#each}`, `{#await}` heads | `v-for`, `v-slot` / `#default` | `@using`, `@inject`, `@bind`, `@on*`, `@model`, inline `@expr` |+| Non-component tags | the `svelte:*` namespace | `<KeepAlive>`, `<Transition>`, `<RouterView>`, … in either spelling | lowercase elements; anything inside `@* *@` or `<!-- -->` |There is no `tree-sitter-vue` on PyPI. The HTML grammar parses a Vue SFC cleanlyanyway, because `<template>`, `<script>` and `<style>` are ordinary elements todiff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.mdindex 08f35885e..19cfda01e 100644--- a/docs/business/COMMERCIAL.md+++ b/docs/business/COMMERCIAL.md@@ -42,7 +42,7 @@ scale, in a regulated or security-sensitive environment**:All of the following ship in `pip install repowise` today, free for internal use.- **[Five intelligence layers](../layers/INTELLIGENCE_LAYERS.md)**: Graph- (tree-sitter AST across 19 languages, two-tier dependency graph, call+ (tree-sitter AST across 20 languages, two-tier dependency graph, callresolution, heritage extraction, Leiden communities, PageRank / betweenness /SCC), Git (hotspots, ownership, co-change pairs, bus factor, significantcommits, contributor profiles, module health), Documentation (a wiki page per@@ -99,17 +99,17 @@ All of the following ship in `pip install repowise` today, free for internal use## 3. First-class language coverage-Repowise parses **19 languages to a full AST** and places **35 on a five-rung+Repowise parses **20 languages to a full AST** and places **36 on a five-rungladder**, so "do you support X" gets the rung as its answer rather than a yes or ano. Both numbers matter and neither is worth quoting alone.-The 19 are the top three rungs. At **Full tier sit 13** (Python, TypeScript,+The 20 are the top three rungs. At **Full tier sit 13** (Python, TypeScript,JavaScript, Svelte, Vue, Java, Kotlin, Go, Rust, C++, **C#**, Scala, and Ruby) withAST parsing, import resolution, named bindings, call resolution, heritageextraction, multi-project workspace resolvers, framework-aware edges, per-languagedynamic-hint extractors, and code-health markers. A further **5 at Good tier** (C,Swift, PHP, Dart, Object Pascal/Delphi) get all of that except the full health-suite, and Luau is partial. SQL/dbt, shell, HTML, and the config formats are+suite, and Luau and Razor/Blazor are partial. SQL/dbt, shell, HTML, and the config formats arehandled by dedicated extractors on top of that.Below the AST line the ladder continues rather than stopping: **7 at Lightweight**diff --git a/docs/layers/GRAPH.md b/docs/layers/GRAPH.mdindex 92d962cb7..587059565 100644--- a/docs/layers/GRAPH.md+++ b/docs/layers/GRAPH.md@@ -11,7 +11,7 @@ that **every edge carries its own evidence**.<p><img src="https://img.shields.io/badge/17-edge_types-3178C6?style=flat-square&labelColor=0A0A0A" alt="17 edge types" /><img src="https://img.shields.io/badge/29-resolution_origins-059669?style=flat-square&labelColor=0A0A0A" alt="29 resolution origins" />- <img src="https://img.shields.io/badge/19-languages-F59520?style=flat-square&labelColor=0A0A0A" alt="19 languages" />+ <img src="https://img.shields.io/badge/20-languages-F59520?style=flat-square&labelColor=0A0A0A" alt="20 languages" /><img src="https://img.shields.io/badge/22-framework_detectors-7F52FF?style=flat-square&labelColor=0A0A0A" alt="22 framework detectors" /><img src="https://img.shields.io/badge/0-LLM_calls-1E293B?style=flat-square&labelColor=0A0A0A" alt="zero LLM calls" /><img src="https://img.shields.io/badge/compiler_graded-7_of_7_cells_undominated-DC2626?style=flat-square&labelColor=0A0A0A" alt="no tool is both more precise and more complete, in 7 of 7 compiler-graded cells" />diff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.mdindex 004968ad8..445bd12c7 100644--- a/docs/layers/INTELLIGENCE_LAYERS.md+++ b/docs/layers/INTELLIGENCE_LAYERS.md@@ -43,7 +43,7 @@ requirement for the index.## Graph Intelligencetree-sitter parses your source into a **two-tier dependency graph**: file nodes-and symbol nodes (functions, classes, methods). 19 languages parse to a full+and symbol nodes (functions, classes, methods). 20 languages parse to a fullAST; see [`LANGUAGE_SUPPORT.md`](LANGUAGE_SUPPORT.md) for per-language tiers.A **confidence-scored call resolver** handles import aliases, barreldiff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 008ddf8c6..ec839ab53 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -1,6 +1,6 @@# Language Support-**19 languages parsed to a full AST · 35 on the five-rung ladder ·+**20 languages parsed to a full AST · 36 on the five-rung ladder ·framework-aware across all of them.** "Do you support X" has five useful answersrather than two, so every language lands on a rung and the rung says what itbuys you. Everything else in your repo still appears in the wiki and is tracked@@ -32,6 +32,7 @@ reference.<img src="https://img.shields.io/badge/Delphi-EE1F35?style=flat-square&logo=delphi&logoColor=white" alt="Object Pascal / Delphi" /> <strong>· Partial </strong><img src="https://img.shields.io/badge/Luau-00A2FF?style=flat-square&logo=lua&logoColor=white" alt="Luau" />+ <img src="https://img.shields.io/badge/Razor-512BD4?style=flat-square&logo=blazor&logoColor=white" alt="Razor / Blazor" /></p>**Contents:** [Tiers](#tiers) ·@@ -53,13 +54,13 @@ produce meaningful output.|------|-----------|--------------|| **Full** (13) | Python · TypeScript · JavaScript · Svelte · Vue · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges, **and code-health markers** || **Good** (5) | C · Swift · PHP · Dart · Object Pascal | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift and PHP don't yet |-| **Partial** (1) | Luau / Roblox | AST symbols and `require()` resolution (Rojo / `.luaurc` aware). No health markers yet |+| **Partial** (2) | Luau / Roblox · Razor / Blazor | Luau: AST symbols and `require()` resolution (Rojo / `.luaurc` aware), no health markers yet. Razor: a component symbol per file, call edges from `@code` blocks and component tags, C# health markers; no import resolution yet || | | ⎯⎯ *tree-sitter parsing stops here. The rungs below are derived from git and imports, not from an AST.* ⎯⎯ || **Lightweight** (7) | Elixir · Clojure · Haskell · Lean 4 · Erlang · F# · HTML | A real file-to-file import graph, no symbol-level claims || **Structural** (9) | Objective-C · R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history only: blame, hotspots, co-change. No AST parsing |-The first three rungs are the **19 languages parsed to a full AST**; all five are-the **35** on the ladder. Both numbers are worth stating and neither is worth+The first three rungs are the **20 languages parsed to a full AST**; all five are+the **36** on the ladder. Both numbers are worth stating and neither is worthstating alone, so if you only take one thing from this page, take the rung yourlanguage sits on rather than either count.@@ -78,17 +79,19 @@ meaningless for a script invoked by name. See|-------|:----:|:----:|:-------:|:-----------:|:----------:|| File discovery & git history | ✅ | ✅ | ✅ | ✅ | ✅ || AST symbol extraction | ✅ | ✅ | ✅ | — | — |-| Import resolution | ✅ | ✅ | ✅ | file-level | — |+| Import resolution | ✅ | ✅ | Luau | file-level | — || Call graph edges | ✅ | ✅ | ✅ | — | — || Heritage (extends / implements) | ✅ | ✅ | — | — | — || Named bindings | ✅ | ✅ | — | — | — |-| Code-health markers | ✅ | Dart, Pascal | — | — | — |+| Code-health markers | ✅ | Dart, Pascal | Razor | — | — || Dead code detection | ✅ | ✅ | ✅ | ✅ | ✅ || Semantic search & wiki pages | ✅ | ✅ | ✅ | ✅ | ✅ |Scala's import resolution is partial: it shares the JVM index with Java andKotlin and falls back to parsing SBT / Mill build files. Every other Full and-Good language resolves imports outright.+Good language resolves imports outright. On the Partial rung the two languages+split: Luau resolves `require()` and has no health markers, Razor has C#+health markers and no import edges yet.---@@ -228,6 +231,31 @@ what a parent actually writes), `<Foo />` in markup mints a call edge, and ahandler referenced only from `on:click={inc}` or `@click="inc"` carries an edgeinstead of reading as dead code.+### Razor / Blazor markup (`.razor`, `.cshtml`)++Razor is the same one-file-two-languages shape, with one difference: there is+no usable `tree-sitter-razor` on PyPI, and an HTML grammar actively mis-parses+it (`List<Order>` reads as an HTML element). So the locator in+`sfc_source.py` **byte-scans** instead: `@code { }`, `@functions { }` and+`@{ }` interiors are brace-matched and projected into a C# buffer at+byte-identical offsets, PascalCase markup tags (`<RadzenDataGrid />`) mint+component call edges, and the file itself becomes a symbol named after the+filename. The C# queries, `LanguageConfig`, complexity map and perf dialect+all apply verbatim. Razor comments (`@* *@`) and HTML comments are skipped, so+commented-out code and tags mint nothing.++Razor sits on the **Partial** rung, not with Svelte and Vue, because two rows+of the tier table are still open. The C# body is projected at top level, so+`@code` members land as call edges but not as symbols, and a top-level+`[Parameter]` property is a recoverable parse error rather than a member.+`@using`, `@inject`, `@bind`, `@model` and the `@Html.Partial` family are+blanked, so a Razor file has no import edges and its calls resolve through the+repo-wide tiers only. Attribute-bound handlers (`Click="@Save"`) carry no edge+yet, the same binding-form ceiling Svelte's `{#each}` heads and Vue's `v-for`+get. Component tags resolve when the name is unique in the repo, and `@inject`+receivers resolve when the property is named after its implementation, which+is the Blazor convention.+---## Good tier@@ -331,12 +359,15 @@ map before markers fire. This table is why a language is Full rather than Good.| Ruby | ✅ | ✅ | ✅ | later | ✅ || Dart | ✅ | n/a | ✅ | later | ✅ || Object Pascal | ✅ | n/a | later | later | n/a |+| Razor | ✅ | n/a | n/a | later | ✅ || Shell | ✅ | n/a | n/a | n/a | n/a |Every cell is a deliberate call, not an oversight. Go and Object Pascal have noclass metrics because neither language nests a type's method *bodies* inside thetype; mapping them anyway would emit a class with `method_count == 0` for every-class in the repo. Kotlin's Extract Method is **blocked on the grammar**, not+class in the repo. Razor has none either: its `@code` members are projected at+C# top level with no enclosing class, and its test files are `.cs`, so the+assertion smells never apply. Kotlin's Extract Method is **blocked on the grammar**, notunscheduled: tree-sitter-kotlin parses a bare `break` as a plain identifier, anda slicer that cannot see a jump would propose an extraction that silently changescontrol flow. Rust and C++ omit `string_concat_in_loop` because both append indiff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex cb55f33b2..eb94b0b8b 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -788,6 +788,10 @@ LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {# ingestion/sfc_source.py), so the TS node map applies verbatim."svelte": _TS,"vue": _TS,+ # Razor reaches the walker as a C# buffer (its ``@code`` / ``@{ }``+ # regions projected by the same sfc_source seam), so the C# node map+ # applies verbatim.+ "razor": _CSHARP,"javascript": _JS,"jsx": _JS,"go": _GO,diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.pyindex 1a77f6428..f088f07af 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py@@ -42,6 +42,9 @@ _REGISTER: tuple[tuple[str, BasePerfDialect], ...] = (("java", _java.DIALECT),("go", _go.DIALECT),("csharp", _csharp.DIALECT),+ # Razor/Blazor reaches the pass as a C# buffer (its C# regions+ # projected by sfc_source), so the C# dialect applies verbatim.+ ("razor", _csharp.DIALECT),("rust", _rust.DIALECT),("dart", _dart.DIALECT),("scala", _scala.DIALECT),diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.pyindex b89f9284f..f39bd9c4e 100644--- a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py@@ -54,6 +54,9 @@ _SYNTHETIC_PROVIDERS: dict[str, list[_Provider]] = {"c": [cpp_macro_synthetic_symbols],"svelte": [sfc_component_symbols],"vue": [sfc_component_symbols],+ # A .razor/.cshtml file *is* the component: the name comes from the+ # filename (PascalCase by convention), same as Svelte/Vue.+ "razor": [sfc_component_symbols],}diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/sfc_component.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/sfc_component.pyindex 0a6ff2f9e..19ff1e9e4 100644--- a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/sfc_component.py+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/sfc_component.py@@ -42,11 +42,18 @@ def _vue_name(path: PurePosixPath) -> str:return vue_component_name_from_stem(path.stem, path.parent.name)-_NAMERS = {"svelte": _svelte_name, "vue": _vue_name}+def _razor_name(path: PurePosixPath) -> str:+ # Razor components are PascalCase by convention and the file *is* the+ # component, so the stem is the name; no kebab- or sigil-normalisation+ # needed (unlike SvelteKit's ``+page`` or Vue's ``back-to-top``).+ return path.stem+++_NAMERS = {"svelte": _svelte_name, "vue": _vue_name, "razor": _razor_name}def sfc_component_symbols(root: Node, src: str, file_info: FileInfo) -> list[Symbol]:- """Return the single component symbol for a ``.svelte`` / ``.vue`` file."""+ """Return the single component symbol for a ``.svelte`` / ``.vue`` / ``.razor`` file."""path = PurePosixPath(file_info.path)if not path.stem:return []diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.pyindex 439c28e6d..cc8ae013e 100644--- a/packages/core/src/repowise/core/ingestion/language_configs.py+++ b/packages/core/src/repowise/core/ingestion/language_configs.py@@ -430,3 +430,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {# copying keeps them from drifting apart.LANGUAGE_CONFIGS["svelte"] = LANGUAGE_CONFIGS["typescript"]LANGUAGE_CONFIGS["vue"] = LANGUAGE_CONFIGS["typescript"]+# Razor projects its C# regions (``@code`` / ``@{ }`` blocks) into a C#+# buffer through the same sfc_source seam, so the C# config applies verbatim.+LANGUAGE_CONFIGS["razor"] = LANGUAGE_CONFIGS["csharp"]diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.pyindex 59ea863f2..d45c986f9 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py@@ -46,6 +46,7 @@ from .php import SPEC as _PHPfrom .proto import SPEC as _PROTOfrom .python import SPEC as _PYTHONfrom .r import SPEC as _R+from .razor import SPEC as _RAZORfrom .ruby import SPEC as _RUBYfrom .rust import SPEC as _RUSTfrom .scala import SPEC as _SCALA@@ -88,6 +89,12 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (_KOTLIN,_RUBY,_CSHARP,+ # Must follow _CSHARP: shares_grammar_with resolves against the registry+ # built so far, so csharp's grammar has to be loaded first. Razor/Blazor+ # markup (.razor, .cshtml) projects its C# regions (``@code`` / ``@{ }``+ # blocks) into a C# buffer via ``sfc_source``, exactly as svelte/vue+ # project into TypeScript.+ _RAZOR,_PHP,_SWIFT,_SCALA,diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/razor.py b/packages/core/src/repowise/core/ingestion/languages/specs/razor.pynew file mode 100644index 000000000..ba10f2b94--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/specs/razor.py@@ -0,0 +1,46 @@+"""LanguageSpec for razor.++A ``.razor`` or ``.cshtml`` file is two languages in one file: C# regions+(``@code`` / ``@functions`` / ``@{ }`` blocks) plus Razor markup. There is no+``tree-sitter-razor`` on PyPI, so ``sfc_source`` byte-scans the file for the+C#-bearing regions, blanks everything else to spaces at byte-identical+offsets, and the result is parsed with the ordinary C# grammar. Hence+``shares_grammar_with`` and ``scm_file`` both point at csharp, mirroring how+``specs/svelte.py`` projects to TypeScript.++The C# builtin / heritage surfaces are copied from the csharp spec so the+projection is filtered exactly like a real ``.cs`` file would be.+"""++from __future__ import annotations++from ..spec import LanguageSpec+from .csharp import SPEC as _CSHARP++SPEC = LanguageSpec(+ tag="razor",+ display_name="Razor",+ # Razor's own using directives (``@using X``) are not projected yet, so+ # no import edges are emitted from these files today and the resolver+ # tier stays at the honest default rather than claiming C#'s full+ # resolution for edges that never exist.+ import_support="none",+ extensions=frozenset({".razor", ".cshtml"}),+ shares_grammar_with="csharp",+ scm_file="csharp.scm",+ # ``@inherits`` is blanked and the projected C# holds no type+ # declarations, so there is nothing for a heritage extractor to read.+ heritage_node_types=frozenset(),+ manifest_files=_CSHARP.manifest_files,+ # None of these declare a package; the .csproj does. Copied from the+ # csharp spec so a solution dir holding only MSBuild/NuGet settings is+ # not mistaken for a package root.+ build_config_manifests=_CSHARP.build_config_manifests,+ lock_files=_CSHARP.lock_files,+ generated_suffixes=_CSHARP.generated_suffixes,+ blocked_dirs=_CSHARP.blocked_dirs,+ builtin_calls=_CSHARP.builtin_calls,+ builtin_parents=_CSHARP.builtin_parents,+ builtin_types=_CSHARP.builtin_types,+ color_hex="#512BD4",+)diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 3a0018282..a17888b2e 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -31,6 +31,8 @@ LanguageTag = Literal["cpp","c","csharp",+ # Razor / Blazor markup, projected to C# via sfc_source (byte-scan).+ "razor","ruby","php","swift",diff --git a/packages/core/src/repowise/core/ingestion/sfc_source.py b/packages/core/src/repowise/core/ingestion/sfc_source.pyindex 55582478f..14e9886c0 100644--- a/packages/core/src/repowise/core/ingestion/sfc_source.py+++ b/packages/core/src/repowise/core/ingestion/sfc_source.py@@ -1,12 +1,13 @@"""Single-file-component source preparation.-A ``.svelte`` or ``.vue`` file is three languages in one file: ``<script>``-blocks hold TS/JS, the markup is a framework-flavoured HTML, and ``<style>`` is-CSS. The markup grammars parse the file but hand each ``<script>`` body back as-one opaque ``raw_text`` node — a ``.scm`` query run against them captures no-symbol, no import and no call.+A ``.svelte``, ``.vue`` or ``.razor`` file is more than one language in one+file: ``<script>`` blocks hold TS/JS, the markup is a framework-flavoured+HTML, and ``@code`` / ``@{ }`` regions hold C#. The markup grammars parse+the file but hand each ``<script>`` body back as one opaque ``raw_text``+node, so a ``.scm`` query run against them captures no symbol, no import and+no call.-So a markup grammar is used here only to *locate* the JS-bearing regions:+So a markup grammar is used here only to *locate* the code-bearing regions:* every ``<script>`` body,* every markup expression — Svelte's ``{expr}`` and ``on:click={inc}``, Vue's@@ -27,7 +28,8 @@ the markup would make the dead-code pass wrong on nearly every component.Only the *region-location* step differs per language, so it lives behind:data:`_LOCATORS`; the blanking, fencing, caching and offset invariants areshared. Adding a markup language means adding a :class:`Locator`, not a second-copy of the walker.+copy of the walker: grammar-backed for Svelte and Vue, byte-scanned for+Razor, which has no usable tree-sitter grammar (see the ``razor`` locator).Binding forms are deliberately skipped rather than kept: Svelte's``{#each items as item}`` and ``{#await}`` heads, and Vue's ``v-for="item in@@ -138,15 +140,29 @@ _EMPTY_SCAN = SfcScan(js_spans=(), terminators=(), component_tags=(), has_error=class Locator(NamedTuple):- """How one markup language exposes its JS regions and component tags."""+ """How one markup language exposes its code regions and component tags.++ Two shapes are supported. A **grammar-backed** locator (Svelte, Vue)+ parses the file with a tree-sitter markup grammar and ``visit`` walks+ every node. A **byte-scanned** locator (Razor) has ``grammar_module`` /+ ``visit`` left as None and ``byte_scan`` instead walks the raw bytes;+ there is no usable ``tree-sitter-razor`` on PyPI, and an HTML grammar+ actively mis-parses Razor (``List<Order>`` reads as an HTML element).+ Both shapes append to the same ``state`` dict and produce the same+ :class:`SfcScan`.+ """- # Importable module exposing a ``language()`` capsule.- grammar_module: str- # Called for every node; appends to ``state`` (spans/terminators/tags).- visit: Callable[[Node, dict], None]+ # Importable module exposing a ``language()`` capsule (None = byte-scan).+ grammar_module: str | None = None+ # Called for every node (grammar-backed locators); appends to ``state``.+ visit: Callable[[Node, dict], None] | None = None# Maps a raw markup tag name to the component name it instantiates, or# None when the tag is not a user component.- component_name: Callable[[str], str | None]+ component_name: Callable[[str], str | None] | None = None+ # Byte-scanned locators (Razor): called once with the raw source bytes;+ # appends ``(start, end)`` spans / terminator offsets / ``(name, line)``+ # component tags to ``state`` exactly like a grammar walk would.+ byte_scan: Callable[[bytes, dict], None] | None = None# ---------------------------------------------------------------------------@@ -350,6 +366,242 @@ def vue_component_name_from_stem(stem: str, parent_dir: str = "") -> str:return stem[:1].upper() + stem[1:]+# ---------------------------------------------------------------------------+# Razor / Blazor+# ---------------------------------------------------------------------------++# Razor's C#-bearing constructs, without the leading ``@`` sigil (the scan+# compares against ``source[at + 1:]``). ``@code`` / ``@functions`` / ``@{ }``+# hold class-body or statement content.+_RAZOR_BLOCK_OPENERS = (b"code", b"functions", b"{")++# Razor comments hide both markup and C#. HTML comments only hide markup: a+# Razor expression inside ``<!-- -->`` still runs, so only the tag pass skips+# them.+_RAZOR_COMMENT_CLOSE = b"*@"+_HTML_COMMENT_OPEN = b"<!--"+_HTML_COMMENT_CLOSE = b"-->"+++def _csharp_literal_end(source: bytes, index: int) -> int | None:+ """Index just past the C# literal or comment starting at ``index``.++ The brace-depth walk must not count braces inside these: a ``{`` in a+ string would leave the block unclosed or swallow the markup after it.+ """+ two = source[index : index + 2]+ if two == b"//":+ newline = source.find(b"\n", index + 2)+ return len(source) if newline < 0 else newline+ if two == b"/*":+ close = source.find(b"*/", index + 2)+ return len(source) if close < 0 else close + 2++ cursor = index+ verbatim = False+ # ``$`` and ``@`` may appear in either order. An interpolated literal's+ # braces are balanced by construction, so skipping the whole literal is+ # right for it too.+ while source[cursor : cursor + 1] in (b"@", b"$"):+ verbatim = verbatim or source[cursor : cursor + 1] == b"@"+ cursor += 1+ quote = source[cursor : cursor + 1]++ if quote == b'"':+ cursor += 1+ while cursor < len(source):+ byte = source[cursor : cursor + 1]+ if verbatim:+ if byte == b'"':+ if source[cursor + 1 : cursor + 2] == b'"':+ cursor += 2+ continue+ return cursor + 1+ cursor += 1+ continue+ if byte == b"\\":+ cursor += 2+ continue+ if byte == b'"':+ return cursor + 1+ cursor += 1+ return len(source)++ if quote == b"'" and cursor == index:+ # A char literal is at most a few bytes (``'\u0041'``); an apostrophe+ # in markup inside ``@{ }`` must not swallow the rest of the block.+ probe = cursor + 1+ while probe < len(source) and probe <= cursor + 8:+ byte = source[probe : probe + 1]+ if byte == b"\\":+ probe += 2+ continue+ if byte == b"'":+ return probe + 1+ probe += 1+ return None+++def _razor_byte_scan(source: bytes, state: dict) -> None:+ """Locate C# regions and component tags in ``.razor`` / ``.cshtml`` bytes.++ The scanner walks the raw bytes with no grammar: ``@code { ... }`` /+ ``@functions { ... }`` / ``@{ ... }`` interiors are projected as C#+ (brace-depth matched so nested object initialisers survive), and+ PascalCase tags (``<RadzenDataGrid>``) are recorded as component+ instantiations. Everything else (directives, markup, attributes) is+ blanked by :func:`_blank`.++ Deliberate exclusions, mirroring the Svelte/Vue ceilings:++ * ``@@`` is the Razor escape for a literal ``@`` (``@@code`` renders+ ``@code``), skipped so an escaped sigil never opens a false block.+ * A ``@`` that is part of a longer identifier token (``email@host``,+ ``user@@example.com``) is not a directive: the following character+ must be alphabetic or ``{`` for the sigil to count.+ * ``@* ... *@`` comments are skipped by both passes. Commented-out code+ compiles to nothing, so a block or tag inside one would be a wrong edge.+ * ``@using X`` directives are NOT projected (Razor drops the trailing+ ``;``, which the C# grammar needs; the projection would have to+ rewrite bytes to satisfy it). The ``@inject`` / ``@bind`` /+ ``@on*`` attribute-value forms are two-way bindings, not call edges,+ the same posture as Svelte's ``{#each}`` heads and Vue's ``v-for``.+ """+ comments: list[tuple[int, int]] = []++ # -- C# regions ----------------------------------------------------------+ # Scanned FIRST so the component-tag pass below can skip their interiors:+ # ``List<Order>`` inside a C# region is a generic type argument, not a+ # component tag, and the C# grammar (not the tag pass) owns that text.+ # One sequential walk, so a ``@code`` inside a comment and a ``@*`` inside+ # a C# string are each jumped over rather than matched.+ pos = 0+ while True:+ at = source.find(b"@", pos)+ if at < 0:+ break+ following = source[at + 1 : at + 2]+ # Skip the @@ escape.+ if following == b"@":+ pos = at + 2+ continue+ if following == b"*":+ close = source.find(_RAZOR_COMMENT_CLOSE, at + 2)+ end = len(source) if close < 0 else close + len(_RAZOR_COMMENT_CLOSE)+ comments.append((at, end))+ pos = end+ continue+ rest = source[at + 1 :]+ matched = None+ for opener in _RAZOR_BLOCK_OPENERS:+ if rest.startswith(opener):+ matched = opener+ break+ if matched is None:+ # Not a block opener: keep scanning for the next sigil.+ pos = at + 1+ continue++ open_brace = at + 1 + len(matched)+ if matched == b"{":+ # For ``@{`` the sigil IS the opener: the brace sits at ``at + 1``,+ # not one past a keyword like ``code`` / ``functions``.+ open_brace = at + 1+ # Skip whitespace between the keyword and the opening brace.+ while open_brace < len(source) and source[open_brace : open_brace + 1] in (+ b" ",+ b"\t",+ b"\r",+ b"\n",+ ):+ open_brace += 1+ if open_brace >= len(source) or source[open_brace : open_brace + 1] != b"{":+ pos = at + 1+ continue++ depth = 0+ end = None+ cursor = open_brace+ while cursor < len(source):+ byte = source[cursor : cursor + 1]+ if byte in (b'"', b"'", b"/", b"@", b"$"):+ skip = _csharp_literal_end(source, cursor)+ if skip is not None:+ cursor = skip+ continue+ if byte == b"{":+ depth += 1+ elif byte == b"}":+ depth -= 1+ if depth == 0:+ end = cursor+ break+ cursor += 1+ if end is None:+ pos = at + 1+ continue++ # The interior is the C# body. Fence it with both braces so a+ # sibling block cannot run into it and vice versa.+ interior_start, interior_end = open_brace + 1, end+ if interior_end > interior_start:+ state["spans"].append((interior_start, interior_end))+ state["terminators"].append(open_brace)+ state["terminators"].append(end)+ pos = end + 1++ # -- component tags: <PascalCase ...> / <PascalCase /> ------------------+ # Skip any ``<`` inside a C# region or a Razor comment: ``List<Order>`` is+ # a generic type argument, ``a < b`` is a comparison, and a commented-out+ # tag renders nothing. HTML comments are jumped over for the same reason.+ hidden = tuple(state["spans"]) + tuple(comments)++ def _is_hidden(offset: int) -> bool:+ return any(start <= offset < end for start, end in hidden)++ pos = 0+ while True:+ lt = source.find(b"<", pos)+ if lt < 0:+ break+ if _is_hidden(lt):+ pos = lt + 1+ continue+ if source.startswith(_HTML_COMMENT_OPEN, lt):+ close = source.find(_HTML_COMMENT_CLOSE, lt + len(_HTML_COMMENT_OPEN))+ pos = len(source) if close < 0 else close + len(_HTML_COMMENT_CLOSE)+ continue+ name_start = lt + 1+ name_end = name_start+ while name_end < len(source) and (+ source[name_end : name_end + 1].isalnum()+ or source[name_end : name_end + 1] in (b"_", b".")+ ):+ name_end += 1+ if name_end > name_start:+ # A namespace-qualified tag (``<Shared.Grid />``) instantiates the+ # last dotted segment.+ raw = source[name_start:name_end].decode("utf-8", errors="replace")+ name = _razor_component_name(raw.rsplit(".", 1)[-1])+ if name:+ line = source.count(b"\n", 0, lt) + 1+ state["tags"].append((name, line))+ pos = lt + 1+++def _razor_component_name(name: str) -> str | None:+ """``<RadzenDataGrid>`` instantiates a component; ``<div>`` is HTML.++ The Svelte rule transfers verbatim: a PascalCase tag names a user+ component, a lowercase tag is a plain element. Razor components are+ PascalCase by convention, so no kebab- or ``+``-normalisation is+ needed.+ """+ if not name or not name[0].isupper():+ return None+ return name++# ---------------------------------------------------------------------------# Registry# ---------------------------------------------------------------------------@@ -378,6 +630,14 @@ _LOCATORS: dict[str, Locator] = {visit=_vue_visit,component_name=_vue_component_name,),+ # Razor has no usable tree-sitter grammar on PyPI, and an HTML grammar+ # actively mis-parses it (``List<Order>`` reads as an HTML element). The+ # locator byte-scans instead: ``@code`` / ``@functions`` / ``@{ }``+ # interiors project as C#, PascalCase tags become component calls.+ "razor": Locator(+ component_name=_razor_component_name,+ byte_scan=_razor_byte_scan,+ ),}@@ -419,7 +679,21 @@ def scan(language: str, source: bytes) -> SfcScan:@lru_cache(maxsize=4)def _cached_scan(language: str, source: bytes) -> SfcScan:locator = _LOCATORS[language]- grammar = _grammar(locator.grammar_module)+ state: dict = {"spans": [], "terminators": [], "tags": []}++ # Byte-scanned locator (Razor): no markup grammar exists, so the raw+ # bytes are scanned directly. There is no tree to carry a parse-error+ # flag, and a byte scan cannot mis-parse, so ``has_error`` stays False.+ if locator.byte_scan is not None:+ locator.byte_scan(source, state)+ return SfcScan(+ js_spans=tuple(sorted(state["spans"])),+ terminators=tuple(sorted(state["terminators"])),+ component_tags=tuple(state["tags"]),+ has_error=False,+ )++ grammar = _grammar(locator.grammar_module or "")if grammar is None:return _EMPTY_SCAN@@ -431,7 +705,6 @@ def _cached_scan(language: str, source: bytes) -> SfcScan:log.debug("sfc_scan_failed", language=language, error=str(exc))return _EMPTY_SCAN- state: dict = {"spans": [], "terminators": [], "tags": []}_walk(tree.root_node, locator.visit, state)return SfcScan(js_spans=tuple(sorted(state["spans"])),diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex 9ea07d756..bf32990a6 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -159,9 +159,7 @@ _MAX_UNKNOWN_LANGUAGE_PATHS = 500_REFERENCE_BEARING_EXTENSIONS: frozenset[str] = frozenset({".api", # also matches Kotlin's .klib.api- ".cshtml",".properties",- ".razor",".rst",".topic",".xml",diff --git a/tests/unit/ingestion/test_razor_extractors.py b/tests/unit/ingestion/test_razor_extractors.pynew file mode 100644index 000000000..d4917262b--- /dev/null+++ b/tests/unit/ingestion/test_razor_extractors.py@@ -0,0 +1,218 @@+"""Razor/Blazor end-to-end extraction: symbols, calls, health.++A ``.razor`` / ``.cshtml`` file projects its C# regions (``@code`` /+``@functions`` / ``@{ }`` blocks) into a C# buffer at byte-identical+offsets via ``sfc_source``, exactly as a ``.svelte`` file projects into+TypeScript. These tests pin the edges the issue #1404 reporter named:+component instantiations (``<RadzenDataGrid />``) and call edges from+``@code`` bodies (``Service.Method()``), plus the component symbol the+file itself declares.+"""++from __future__ import annotations++from datetime import datetime++import pytest++from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser++_COMPONENT = b"""@page "/orders"+@inject OrderService OrderService++<RadzenAlert AlertStyle="AlertStyle.Warning">+ Some orders require attention.+</RadzenAlert>++<RadzenDataGrid Data="@orders" TItem="Order">+ <Columns>+ <RadzenDataGridColumn TItem="Order" Property="Name" Title="Name" />+ </Columns>+</RadzenDataGrid>++<RadzenButton Text="Save" Click="@SaveOrders" />++@code {+ private List<Order> orders = new();++ private async Task SaveAsync()+ {+ await OrderService.SaveOrdersAsync(orders);+ }+}+"""+++def _file(path: str = "Components/Orders.razor") -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language="razor",+ size_bytes=len(_COMPONENT),+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )++[email protected](scope="module")+def parser() -> ASTParser:+ return ASTParser()++[email protected](scope="module")+def parsed(parser: ASTParser):+ return parser.parse_file(_file(), _COMPONENT)+++class TestSymbols:+ def test_the_file_itself_becomes_a_component_symbol(self, parsed) -> None:+ # Nothing in a .razor source names the component; the filename does.+ component = [s for s in parsed.symbols if s.name == "Orders"]+ assert len(component) == 1+ assert component[0].kind == "class"+ assert component[0].start_line == 1++ def test_no_parse_errors_on_a_well_formed_component(self, parsed) -> None:+ assert parsed.parse_errors == []+++class TestCalls:+ def test_code_block_method_calls_are_extracted(self, parsed) -> None:+ # `OrderService.SaveOrdersAsync(orders)` lives in the @code block,+ # which is projected into C#, so the call edge must survive.+ assert "SaveOrdersAsync" in {c.target_name for c in parsed.calls}++ def test_markup_component_tags_become_calls(self, parsed) -> None:+ # <RadzenDataGrid /> etc. are how Razor instantiates components,+ # the JSX analogue, minted from the markup by component_call_sites.+ targets = {c.target_name for c in parsed.calls}+ assert {+ "RadzenAlert",+ "RadzenDataGrid",+ "RadzenDataGridColumn",+ "RadzenButton",+ } <= targets++ def test_generic_type_arguments_are_not_component_calls(self, parsed) -> None:+ # ``List<Order>`` inside @code is a generic type argument. Treating+ # it as markup would mint a bogus Order edge.+ targets = {c.target_name for c in parsed.calls}+ assert "Order" not in targets+ assert "List" not in targets++ def test_calls_are_attributed_to_the_component(self, parsed) -> None:+ grid = next(c for c in parsed.calls if c.target_name == "RadzenDataGrid")+ assert grid.caller_symbol_id is not None+ assert grid.caller_symbol_id.endswith("::Orders")++ @pytest.mark.xfail(+ strict=True,+ reason="attribute-bound handlers (Click=\"@SaveOrders\") are not projected yet",+ )+ def test_attribute_bound_handler_carries_an_edge(self, parsed) -> None:+ # ``Click="@SaveOrders"`` is the only reference to SaveOrders in the+ # component. Until attribute expressions are projected it reads as+ # unreferenced; this turns green when they are.+ assert "SaveOrders" in {c.target_name for c in parsed.calls}+++class TestCshtml:+ def test_cshtml_files_parse_as_razor(self, parser) -> None:+ src = b"""@{+ ViewData["Title"] = "Orders";+ var filtered = orders.Where(o => o.IsActive);+}++@functions {+ public int Count;+}++<div>@filtered.Count() orders</div>+"""+ file_info = _file("Views/Orders.cshtml")+ result = parser.parse_file(file_info, src)+ assert result.parse_errors == []+ # The component symbol comes from the filename, not the source.+ assert "Orders" in {s.name for s in result.symbols}+ # .Where lives inside the @{ } statement block, which is projected+ # into C#, so the call site must survive.+ assert "Where" in {c.target_name for c in result.calls}+ # The @functions body is class content at C# top level (there is no+ # class wrapper yet), so `Count` carries no symbol today, and+ # `@filtered.Count()` is a single expression in markup, which is not+ # projected either.+ assert "Count" not in {s.name for s in result.symbols}++ def test_mvc_view_directives_are_blanked_and_mint_no_edge(self, parser) -> None:+ # ``@model``, ``@Html.Partial`` and the awaited partial / view+ # component forms are single expressions in markup, not code+ # blocks. They are blanked like ``@inject``: no symbol, no edge.+ src = b"""@model OrderDetailViewModel+@using Microsoft.AspNetCore.Mvc.Localization++<h1>@Model.Title</h1>[email protected]("_OrderSummary", Model.Summary)+@await Html.PartialAsync("_OrderLines", Model.Lines)+@await Component.InvokeAsync("Basket")++@{+ var summary = OrderFormatter.Summarise(Model.Lines);+}+"""+ result = parser.parse_file(_file("Views/Order/Detail.cshtml"), src)+ targets = {c.target_name for c in result.calls}+ assert "Partial" not in targets+ assert "PartialAsync" not in targets+ assert "InvokeAsync" not in targets+ assert "OrderDetailViewModel" not in targets+ assert {s.name for s in result.symbols} == {"Detail"}+ # The statement block still projects.+ assert "Summarise" in targets+++class TestHealth:+ def test_complexity_walker_reads_the_projection(self) -> None:+ from repowise.core.analysis.health.complexity.walker import walk_file++ src = b"""@page "/orders"++<RadzenDataGrid Data="@orders" TItem="Order">+</RadzenDataGrid>++@code {+ private int count;++ private async Task SaveAsync()+ {+ for (var i = 0; i < 10; i++)+ {+ await OrderService.SaveOrdersAsync(orders);+ }+ }+}+"""+ import os+ import tempfile++ with tempfile.NamedTemporaryFile(suffix=".razor", delete=False) as f:+ f.write(src)+ path = f.name+ try:+ fc = walk_file(path, "razor", src)+ names = {fn.name for fn in fc.functions}+ assert "SaveAsync" in names+ assert fc.file_nloc > 0+ finally:+ os.unlink(path)++ def test_perf_dialect_is_registered(self) -> None:+ # Razor reaches the perf pass as a C# buffer, so the C# dialect+ # serves it, the same alias pattern as svelte -> ts_js.+ from repowise.core.analysis.health.perf.dialects import PERF_DIALECTS++ assert "razor" in PERF_DIALECTSdiff --git a/tests/unit/ingestion/test_sfc_source.py b/tests/unit/ingestion/test_sfc_source.pyindex 9de901320..7e01ab663 100644--- a/tests/unit/ingestion/test_sfc_source.py+++ b/tests/unit/ingestion/test_sfc_source.py@@ -196,7 +196,9 @@ class TestVueOffsetInvariants:def test_non_ascii_markup_keeps_offsets(self) -> None:# A multi-byte character in the markup must not shift the script that# follows it — the blanking works in bytes, not code points.- src = "<template><p>日本語のテキスト</p></template>\n<script>const a = 1;</script>\n".encode()+ src = (+ "<template><p>日本語のテキスト</p></template>\n<script>const a = 1;</script>\n".encode()+ )prepared = prepare_source("vue", src)assert len(prepared) == len(src)assert prepared.index(b"const a = 1;") == src.index(b"const a = 1;")@@ -332,3 +334,268 @@ class TestVueDegradation:prepared = prepare_source("vue", src)assert len(prepared) == len(src)assert prepared.count(b"\n") == src.count(b"\n")+++# ---------------------------------------------------------------------------+# Razor / Blazor+# ---------------------------------------------------------------------------++_RAZOR_COMPONENT = b"""@page "/orders"+@inject OrderService OrderService++<RadzenAlert AlertStyle="AlertStyle.Warning">+ Some orders require attention.+</RadzenAlert>++<RadzenDataGrid Data="@orders" TItem="Order">+ <Columns>+ <RadzenDataGridColumn TItem="Order" Property="Name" Title="Name" />+ </Columns>+</RadzenDataGrid>++<RadzenButton Text="Save" Click="@SaveOrders" />++@code {+ private List<Order> orders = new();++ private async Task SaveAsync()+ {+ await OrderService.SaveOrdersAsync(orders);+ }+}+"""+++class TestRazorOffsetInvariants:+ """Byte length and line numbering must survive the projection untouched."""++ def test_length_is_preserved(self) -> None:+ assert len(prepare_source("razor", _RAZOR_COMPONENT)) == len(_RAZOR_COMPONENT)++ def test_line_count_is_preserved(self) -> None:+ prepared = prepare_source("razor", _RAZOR_COMPONENT)+ assert prepared.count(b"\n") == _RAZOR_COMPONENT.count(b"\n")++ def test_code_block_lines_are_byte_identical(self) -> None:+ prepared = prepare_source("razor", _RAZOR_COMPONENT).splitlines()+ original = _RAZOR_COMPONENT.splitlines()+ # The @code interior (1-indexed lines 17-22) is projected verbatim.+ # The brace lines themselves are fenced to ``;`` by design, so they+ # are excluded: the offset, not the byte, is what must survive there.+ for index in range(16, 22):+ assert prepared[index] == original[index]++ def test_markup_lines_are_blanked(self) -> None:+ prepared = prepare_source("razor", _RAZOR_COMPONENT).splitlines()+ # Directives and markup (lines 1, 2, 4, 8, 14) become whitespace.+ for index in (0, 1, 3, 7, 13):+ assert prepared[index].strip() == b""++ def test_non_ascii_markup_keeps_offsets(self) -> None:+ src = '@code { var s = "héllo wörld 🎉"; }\n<p>résumé</p>\n'.encode()+ prepared = prepare_source("razor", src)+ assert len(prepared) == len(src)+ assert prepared.count(b"\n") == src.count(b"\n")++ def test_cshtml_extension_shares_the_projection(self) -> None:+ # .cshtml files carry the same razor tag, so the locator applies.+ from repowise.core.ingestion.models import EXTENSION_TO_LANGUAGE++ assert EXTENSION_TO_LANGUAGE[".cshtml"] == "razor"+ prepared = prepare_source("razor", _RAZOR_COMPONENT)+ assert len(prepared) == len(_RAZOR_COMPONENT)+++class TestRazorBlanking:+ def test_statement_block_is_projected(self) -> None:+ src = b"@{\n var total = orders.Sum(o => o.Amount);\n}\n"+ prepared = prepare_source("razor", src)+ assert b"total" in prepared+ assert b"Sum" in prepared++ def test_functions_block_is_projected(self) -> None:+ src = b"@functions {\n public int Count { get; set; }\n}\n"+ prepared = prepare_source("razor", src)+ assert b"Count" in prepared++ def test_markup_and_directives_are_blanked(self) -> None:+ prepared = prepare_source("razor", _RAZOR_COMPONENT)+ assert b"RadzenAlert" not in prepared+ assert b"@page" not in prepared+ assert b"@inject" not in prepared+ assert b"Click" not in prepared+ # Attribute binding values (@orders, @SaveOrders) are not call edges+ # and are blanked with the rest of the markup. ``SaveOrdersAsync``+ # (inside @code) legitimately survives; the bound name without the+ # sigil must not.+ assert b"@SaveOrders" not in prepared+ assert b"SaveOrdersAsync" in prepared++ def test_generics_inside_code_are_not_treated_as_markup(self) -> None:+ # ``List<Order>`` is a generic type argument inside @code, not a+ # component tag. The tag pass must skip C# regions.+ names = {name for name, _ in scan("razor", _RAZOR_COMPONENT).component_tags}+ assert "Order" not in names+ assert "List" not in names++ def test_brace_inside_a_string_does_not_break_matching(self) -> None:+ src = b'@code { var s = "{"; }\n<Live />\n'+ result = scan("razor", src)+ assert len(result.js_spans) == 1+ assert dict(result.component_tags) == {"Live": 2}++ def test_brace_inside_a_verbatim_string_does_not_break_matching(self) -> None:+ src = b'@code { var s = @"{"; }\n<Live />\n'+ result = scan("razor", src)+ assert len(result.js_spans) == 1+ assert dict(result.component_tags) == {"Live": 2}++ def test_brace_inside_a_char_literal_does_not_break_matching(self) -> None:+ src = b"@code { var c = '{'; }\n<Live />\n"+ result = scan("razor", src)+ assert len(result.js_spans) == 1+ assert dict(result.component_tags) == {"Live": 2}++ def test_brace_inside_a_line_comment_does_not_break_matching(self) -> None:+ src = b"@code {\n // }\n void Go() { }\n}\n<Live />\n"+ result = scan("razor", src)+ assert len(result.js_spans) == 1+ assert dict(result.component_tags) == {"Live": 5}++ def test_brace_inside_a_block_comment_does_not_break_matching(self) -> None:+ src = b"@code {\n /* { */\n void Go() { }\n}\n<Live />\n"+ result = scan("razor", src)+ assert len(result.js_spans) == 1+ assert dict(result.component_tags) == {"Live": 5}++ def test_adjacent_blocks_are_fenced(self) -> None:+ src = b"@{ var a = 1; }\n@{ var b = 2; }\n"+ prepared = prepare_source("razor", src)+ compact = prepared.replace(b" ", b"")+ # Each interior is fenced on both sides; the trailing ``;`` inside+ # the body plus the fenced closing brace give the ``;;`` run.+ assert b";vara=1;;" in compact+ assert b";varb=2;;" in compact+++class TestRazorComponentTags:+ def test_capitalized_tags_are_component_usages(self) -> None:+ names = {name for name, _ in scan("razor", _RAZOR_COMPONENT).component_tags}+ assert {+ "RadzenAlert",+ "RadzenDataGrid",+ "RadzenDataGridColumn",+ "RadzenButton",+ "Columns",+ } <= names++ def test_lowercase_html_elements_are_not_components(self) -> None:+ src = b"<div><span>hi</span></div>\n@code { }\n"+ assert scan("razor", src).component_tags == ()++ def test_tag_line_numbers_point_at_the_original_file(self) -> None:+ tags = dict(scan("razor", _RAZOR_COMPONENT).component_tags)+ assert tags["RadzenDataGrid"] == 8++ def test_namespace_qualified_tag_records_the_last_segment(self) -> None:+ names = {name for name, _ in scan("razor", b"<Foo.Bar />\n").component_tags}+ assert names == {"Bar"}++ def test_digits_are_part_of_a_component_name(self) -> None:+ names = {name for name, _ in scan("razor", b"<Grid2 />\n").component_tags}+ assert names == {"Grid2"}++ def test_lowercase_namespace_with_a_pascal_case_component_is_a_tag(self) -> None:+ names = {name for name, _ in scan("razor", b"<foo.Bar />\n").component_tags}+ assert names == {"Bar"}++ def test_lowercase_last_segment_is_not_a_component(self) -> None:+ assert scan("razor", b"<Foo.bar />\n").component_tags == ()++ def test_comparisons_inside_code_are_not_tags(self) -> None:+ src = b"@code { if (a < B) { Go(); } }\n"+ names = {name for name, _ in scan("razor", src).component_tags}+ assert names == set()++ def test_tags_inside_pre_are_still_components(self) -> None:+ # Razor gives <pre> no verbatim semantics: a component inside it+ # renders, so the tag pass reads it like any other markup. A code+ # sample has to be HTML-escaped to show up literally, and an escaped+ # ``<Foo`` opens no tag.+ src = b"<pre><Foo /></pre>\n<pre><Bar /></pre>\n"+ names = {name for name, _ in scan("razor", src).component_tags}+ assert names == {"Foo"}+++class TestRazorComments:+ """Commented-out code compiles to nothing, so it must mint nothing."""++ def test_razor_comment_hides_code_blocks(self) -> None:+ src = b"@* @code { void Hidden() { Go(); } } *@\n@code { void Live() { } }\n"+ prepared = prepare_source("razor", src)+ assert b"Hidden" not in prepared+ assert b"Go" not in prepared+ assert b"Live" in prepared++ def test_razor_comment_hides_component_tags(self) -> None:+ src = b"@*\n<Hidden />\n*@\n<Live />\n"+ tags = dict(scan("razor", src).component_tags)+ assert tags == {"Live": 4}++ def test_razor_comment_keeps_offsets(self) -> None:+ src = b"@* one\ntwo *@\n@code { var x = 1; }\n"+ prepared = prepare_source("razor", src)+ assert len(prepared) == len(src)+ assert prepared.count(b"\n") == src.count(b"\n")+ assert prepared.index(b"var x") == src.index(b"var x")++ def test_unterminated_razor_comment_hides_the_rest_of_the_file(self) -> None:+ src = b"@* forgot to close\n@code { void Hidden() { } }\n<Hidden />\n"+ result = scan("razor", src)+ assert result.js_spans == ()+ assert result.component_tags == ()++ def test_comment_marker_inside_a_code_block_is_not_a_comment(self) -> None:+ # ``@*`` inside a C# string is C#, not a Razor comment; the block was+ # already jumped over, so the tag after it is still found.+ src = b'@code { var s = "@*"; }\n<Live />\n'+ result = scan("razor", src)+ assert len(result.js_spans) == 1+ assert dict(result.component_tags) == {"Live": 2}++ def test_html_comment_hides_component_tags_but_not_code(self) -> None:+ # A component inside ``<!-- -->`` never renders, but a Razor+ # expression inside one still runs, so only the tag pass skips it.+ src = b"<!-- <Hidden /> @{ Run(); } -->\n<Live />\n"+ result = scan("razor", src)+ assert dict(result.component_tags) == {"Live": 2}+ assert b"Run" in prepare_source("razor", src)++ def test_unterminated_html_comment_hides_the_rest_of_the_tags(self) -> None:+ src = b"<!-- open\n<Hidden />\n"+ assert scan("razor", src).component_tags == ()+++class TestRazorDegradation:+ @pytest.mark.parametrize(+ "src",+ [+ b"",+ b"<p>markup only, no code block</p>\n",+ b"@code {",+ b"@code",+ b"@",+ b"@using System.Linq\n",+ b"@@code { this is escaped markup }\n",+ b"<RadzenDataGrid",+ ],+ )+ def test_malformed_or_code_less_input_never_raises(self, src: bytes) -> None:+ prepared = prepare_source("razor", src)+ assert len(prepared) == len(src)+ assert prepared.count(b"\n") == src.count(b"\n")++ def test_unterminated_code_block_degrades_to_no_spans(self) -> None:+ src = b"@code {\n private int x;\n"+ result = scan("razor", src)+ assert result.js_spans == ()