feat(graph): Razor and Web Forms code in the code graph (t84)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m19s
CI / Check (pull_request) Successful in 19m26s

The code regions of ASP.NET markup files are now parsed: @code and
@functions blocks of .razor and .cshtml files, and <script runat="server">
blocks of .aspx, .ascx and .master files, in C# or, as the page directive
says, VB. The markup around them is blanked out with its line breaks kept
and each region is wrapped in the file's class, so the C# and VB parsers
read the members and report the markup file's own lines.

Methods the markup refers to (@onclick="Save", OnClick="BtnSave_Click",
<%# Title() %>) and the framework's lifecycle hooks (OnInitialized,
Page_Load) are entry points. A markup file without code regions is a file
node. Inline Razor and <% %> render blocks are left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-09 12:50:08 +01:00
1 parent 5a11a3b602
commit f4b50459ee
3 files changed
+667

No files matched your search

+664
View File
@@ -0,0 +1,664 @@
//! ASP.NET markup: Razor components and views (`.razor`, `.cshtml`) and Web
//! Forms pages, user controls and master pages (`.aspx`, `.ascx`,
//! `.master`). Only their code regions hold declarations:
//!
//! - Razor: `@code { … }` and `@functions { … }` blocks, C# members;
//! - Web Forms: `<script runat="server"> … </script>` blocks, members in the
//! language the `<%@ Page/Control/Master Language="…" %>` directive names
//! (C# when it names none).
//!
//! Everything else is blanked out, line breaks kept, and each region is
//! wrapped in a class named after the file, so the C# or VB parser reads the
//! members and every line it reports is the line in the markup file.
//! Inline Razor (`@{ … }`, `@if`, `@x.Y()`) and Web Forms render blocks
//! (`<% … %>`) mix code with markup and are left out.
//!
//! The framework calls a markup file's methods from the markup itself
//! (`@onclick="Save"`, `OnClick="BtnSave_Click"`, `<%# GetTitle() %>`) and
//! through lifecycle hooks (`OnInitialized`, `Page_Load`), so those are
//! entry points.
use std::collections::HashSet;
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::graph::CodeNodeKind;
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
use super::common::FileGraph;
use super::csharp::CSharpParser;
use super::vb::VbParser;
/// Methods a Razor component's or Web Forms page's framework calls without
/// the markup naming them.
const LIFECYCLE_HOOKS: [&str; 22] = [
// Blazor components
"OnInitialized",
"OnInitializedAsync",
"OnParametersSet",
"OnParametersSetAsync",
"OnAfterRender",
"OnAfterRenderAsync",
"SetParametersAsync",
"ShouldRender",
"Dispose",
"DisposeAsync",
// Web Forms, wired by AutoEventWireup
"Page_PreInit",
"Page_Init",
"Page_InitComplete",
"Page_PreLoad",
"Page_Load",
"Page_LoadComplete",
"Page_PreRender",
"Page_PreRenderComplete",
"Page_SaveStateComplete",
"Page_Unload",
"Page_Error",
"Page_DataBind",
];
/// Parses the code regions of ASP.NET markup files.
#[derive(Debug, Default)]
pub struct MarkupParser;
/// The language of a markup file's code regions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CodeLanguage {
CSharp,
Vb,
}
/// One code region: the markup in `markup_start..code_start` (the
/// `@code` keyword, the `<script>` tag) is replaced by `open`, the code in
/// `code_start..code_end` is kept, and the markup in `code_end..markup_end`
/// (the `</script>` tag) is replaced by `close`.
#[derive(Debug)]
struct Region {
markup_start: usize,
code_start: usize,
code_end: usize,
markup_end: usize,
}
impl MarkupParser {
/// An ASP.NET markup parser.
pub fn new() -> Self {
Self
}
}
impl LanguageParser for MarkupParser {
fn language(&self) -> &str {
"aspnet-markup"
}
fn extensions(&self) -> &[&str] {
&["razor", "cshtml", "aspx", "ascx", "master"]
}
fn parse_file(
&self,
file_path: &Path,
source: &str,
repo_id: &str,
graph_build_id: &str,
) -> Result<ParseOutput, CoreError> {
let ext = file_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or_default()
.to_ascii_lowercase();
let razor = matches!(ext.as_str(), "razor" | "cshtml");
let (language, inherits, regions) = if razor {
(CodeLanguage::CSharp, None, razor_regions(source))
} else {
let (language, inherits) = web_forms_directive(source);
(language, inherits, web_forms_regions(source))
};
if regions.is_empty() {
// Markup only: the file is part of the application all the same.
let lines = source.lines().count() as u32;
let name = match language {
CodeLanguage::CSharp => "csharp",
CodeLanguage::Vb => "vb",
};
return Ok(FileGraph::new(file_path, lines, repo_id, graph_build_id, name).finish());
}
// A Web Forms page's class is the one its directive names (Visual
// Studio names `Default.aspx`'s `_Default`, `Default` being a VB
// keyword); a Razor file's is named after the file.
let class = inherits.unwrap_or_else(|| class_name(file_path));
let (open, close) = match (razor, language) {
// The `@code` keyword is followed by the block's own braces.
(true, _) => (format!("class {class} "), ""),
(false, CodeLanguage::CSharp) => (format!("class {class} {{"), "}"),
(false, CodeLanguage::Vb) => (format!("Class {class}"), "End Class"),
};
let code = blank_markup(source, &regions, &open, close);
let mut output = match language {
CodeLanguage::CSharp => {
CSharpParser::new().parse_file(file_path, &code, repo_id, graph_build_id)?
}
CodeLanguage::Vb => {
VbParser::new().parse_file(file_path, &code, repo_id, graph_build_id)?
}
};
let referenced = markup_references(source, &regions);
for node in output
.nodes
.iter_mut()
.filter(|n| matches!(n.kind, CodeNodeKind::Method))
{
let name = node.name.to_ascii_lowercase();
if referenced.contains(&name)
|| LIFECYCLE_HOOKS
.iter()
.any(|h| h.eq_ignore_ascii_case(&name))
{
node.is_entry_point = true;
}
}
Ok(output)
}
}
/// The class a markup file compiles to, named after the file: `Counter` for
/// `Counter.razor`, `_Layout` for `_Layout.cshtml`, as an identifier.
fn class_name(file_path: &Path) -> String {
let stem = file_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("Page");
let mut name: String = stem
.chars()
.map(|c| {
if c.is_alphanumeric() || c == '_' {
c
} else {
'_'
}
})
.collect();
if name.starts_with(|c: char| c.is_ascii_digit()) || name.is_empty() {
name.insert(0, '_');
}
name
}
/// `source` with everything outside `regions` replaced by spaces (line
/// breaks kept), each region's opening markup by `open` and its closing
/// markup by `close`.
fn blank_markup(source: &str, regions: &[Region], open: &str, close: &str) -> String {
let mut code = String::with_capacity(source.len());
let blank = |code: &mut String, markup: &str| {
code.extend(markup.chars().map(|c| if c == '\n' { '\n' } else { ' ' }));
};
let mut at = 0;
for region in regions {
blank(&mut code, &source[at..region.markup_start]);
code.push_str(open);
// The rest of the opening markup, if it spans lines (a `<script>`
// tag with its attributes on several), keeps its line breaks.
blank(&mut code, &source[region.markup_start..region.code_start]);
code.push_str(&source[region.code_start..region.code_end]);
code.push_str(close);
blank(&mut code, &source[region.code_end..region.markup_end]);
at = region.markup_end;
}
blank(&mut code, &source[at..]);
code
}
/// The `@code { … }` and `@functions { … }` blocks of a Razor file, outside
/// Razor comments (`@* … *@`). The opening markup is the keyword; the block
/// with its braces is the code.
fn razor_regions(source: &str) -> Vec<Region> {
let bytes = source.as_bytes();
let mut regions = Vec::new();
let mut at = 0;
while at < bytes.len() {
if bytes[at..].starts_with(b"@*") {
at = find(bytes, at + 2, b"*@").map_or(bytes.len(), |end| end + 2);
continue;
}
if bytes[at] == b'@' && (at == 0 || !is_identifier_byte(bytes[at - 1])) {
let keyword = [b"code".as_slice(), b"functions"]
.into_iter()
.find(|k| bytes[at + 1..].starts_with(k));
if let Some(keyword) = keyword {
let after = at + 1 + keyword.len();
let open = after
+ bytes[after..]
.iter()
.take_while(|b| b.is_ascii_whitespace())
.count();
if bytes.get(open) == Some(&b'{') {
if let Some(close) = matching_brace(bytes, open) {
regions.push(Region {
markup_start: at,
code_start: after,
code_end: close + 1,
markup_end: close + 1,
});
at = close + 1;
continue;
}
}
}
}
at += 1;
}
regions
}
/// The `<script runat="server">` blocks of a Web Forms file. The opening
/// markup is the tag, the closing markup the `</script>` tag.
fn web_forms_regions(source: &str) -> Vec<Region> {
// ASCII lowercase keeps every byte offset.
let lower = source.to_ascii_lowercase();
let bytes = lower.as_bytes();
let mut regions = Vec::new();
let mut at = 0;
while let Some(tag) = find(bytes, at, b"<script") {
let Some(tag_end) = find(bytes, tag, b">") else {
break;
};
let attributes: String = lower[tag..tag_end]
.chars()
.filter(|c| !c.is_whitespace())
.collect();
let server = ["runat=\"server\"", "runat='server'", "runat=server"]
.iter()
.any(|a| attributes.contains(a));
let Some(close) = find(bytes, tag_end, b"</script") else {
break;
};
let close_end = find(bytes, close, b">").map_or(bytes.len(), |end| end + 1);
if server {
regions.push(Region {
markup_start: tag,
code_start: tag_end + 1,
code_end: close,
markup_end: close_end,
});
}
at = close_end;
}
regions
}
/// The language and class a Web Forms file's directive names: `<%@ Page
/// Language="VB" Inherits="Plant._Default" %>` is VB and `_Default`. No
/// language, or another one, is C#.
fn web_forms_directive(source: &str) -> (CodeLanguage, Option<String>) {
// ASCII lowercase keeps every byte offset, so a match in `lower` is the
// same range in `source`.
let lower = source.to_ascii_lowercase();
let bytes = lower.as_bytes();
let mut at = 0;
while let Some(start) = find(bytes, at, b"<%@") {
let end = find(bytes, start, b"%>").unwrap_or(bytes.len());
let directive = start + 3..end;
let kind = lower[directive.clone()]
.split_whitespace()
.next()
.unwrap_or_default();
if matches!(kind, "page" | "control" | "master") {
let value = |name: &str| {
attribute_value(&lower, &source[directive.clone()], directive.start, name)
};
let language = match value("language") {
Some(v) if v.to_ascii_lowercase().starts_with("vb") => CodeLanguage::Vb,
_ => CodeLanguage::CSharp,
};
// `Plant._Default, Plant` names the class with its assembly.
let inherits = value("inherits")
.and_then(|v| v.split(',').next())
.and_then(|v| v.trim().rsplit('.').next())
.filter(|name| !name.is_empty())
.map(str::to_string);
return (language, inherits);
}
at = end;
}
(CodeLanguage::CSharp, None)
}
/// The value of the attribute `name` in a directive, `directive` being its
/// text in the original case and `offset` where it starts in `lower`.
fn attribute_value<'s>(
lower: &str,
directive: &'s str,
offset: usize,
name: &str,
) -> Option<&'s str> {
let lower_directive = &lower[offset..offset + directive.len()];
let mut from = 0;
while let Some(found) = lower_directive[from..].find(name) {
let at = from + found;
from = at + name.len();
// A whole attribute name: not the end of a longer one.
if at > 0 && is_identifier_byte(lower_directive.as_bytes()[at - 1]) {
continue;
}
let rest = directive[from..].trim_start();
let Some(rest) = rest.strip_prefix('=') else {
continue;
};
let rest = rest.trim_start();
let (quote, rest) = match rest.chars().next() {
Some(q @ ('"' | '\'')) => (Some(q), &rest[1..]),
_ => (None, rest),
};
let end = match quote {
Some(q) => rest.find(q),
None => rest.find(char::is_whitespace),
}
.unwrap_or(rest.len());
return Some(&rest[..end]);
}
None
}
/// Lowercased identifiers the markup outside `regions` refers to: in
/// attribute values (`OnClick="BtnSave_Click"`, `@onclick="Save"`), right
/// after an `@` (`@Title()`), and in Web Forms code blocks (`<%# Eval(…) %>`).
/// Text between tags is not code and doesn't count.
fn markup_references(source: &str, regions: &[Region]) -> HashSet<String> {
let mut slices = Vec::with_capacity(regions.len() + 1);
let mut at = 0;
for region in regions {
slices.push(&source[at..region.markup_start]);
at = region.markup_end;
}
slices.push(&source[at..]);
let mut found = HashSet::new();
for slice in slices {
let bytes = slice.as_bytes();
let (mut in_tag, mut quote, mut server_block) = (false, None::<u8>, false);
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if quote.is_none() && !server_block && bytes[i..].starts_with(b"<%") {
server_block = true;
} else if server_block && bytes[i..].starts_with(b"%>") {
server_block = false;
} else if !server_block && quote == Some(b) {
quote = None;
} else if in_tag && !server_block && quote.is_none() && (b == b'"' || b == b'\'') {
quote = Some(b);
} else if !server_block && quote.is_none() && b == b'<' {
in_tag = bytes
.get(i + 1)
.is_some_and(|n| n.is_ascii_alphabetic() || *n == b'/');
} else if !server_block && quote.is_none() && b == b'>' {
in_tag = false;
} else if is_identifier_start(b) && (i == 0 || !is_identifier_byte(bytes[i - 1])) {
let len = bytes[i..]
.iter()
.take_while(|&&c| is_identifier_byte(c))
.count();
let after_at = i > 0 && bytes[i - 1] == b'@';
if quote.is_some() || server_block || after_at {
found.insert(slice[i..i + len].to_ascii_lowercase());
}
i += len;
continue;
}
i += 1;
}
}
found
}
/// The index of the `}` that closes the `{` at `open`, skipping C# strings,
/// characters and comments.
fn matching_brace(bytes: &[u8], open: usize) -> Option<usize> {
let mut depth = 0usize;
let mut i = open;
while i < bytes.len() {
match bytes[i] {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
b'/' if bytes.get(i + 1) == Some(&b'/') => {
i = find(bytes, i, b"\n").unwrap_or(bytes.len());
continue;
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i = find(bytes, i + 2, b"*/").map_or(bytes.len(), |end| end + 2);
continue;
}
b'"' if bytes[i..].starts_with(b"\"\"\"") => {
i = find(bytes, i + 3, b"\"\"\"").map_or(bytes.len(), |end| end + 3);
continue;
}
b'"' => {
let verbatim = i > 0
&& (bytes[i - 1] == b'@'
|| (bytes[i - 1] == b'$' && i > 1 && bytes[i - 2] == b'@'));
i = string_end(bytes, i + 1, verbatim);
continue;
}
b'\'' => {
// `'x'`, `'\''`: skip the escaped character, then to the quote.
let start = i + 1 + usize::from(bytes.get(i + 1) == Some(&b'\\'));
i = find(bytes, start + 1, b"'").map_or(bytes.len(), |end| end + 1);
continue;
}
_ => {}
}
i += 1;
}
None
}
/// The index after the `"` that ends a string starting at `from`: a
/// verbatim string (`@"…"`) escapes a quote by doubling it, a regular one
/// with a backslash and ends at the line's end at the latest.
fn string_end(bytes: &[u8], from: usize, verbatim: bool) -> usize {
let mut i = from;
while i < bytes.len() {
match bytes[i] {
b'"' if verbatim && bytes.get(i + 1) == Some(&b'"') => i += 2,
b'"' => return i + 1,
b'\\' if !verbatim => i += 2,
b'\n' if !verbatim => return i,
_ => i += 1,
}
}
bytes.len()
}
/// The first index of `needle` in `bytes` at or after `from`.
fn find(bytes: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
bytes
.get(from..)?
.windows(needle.len())
.position(|w| w == needle)
.map(|at| from + at)
}
fn is_identifier_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_'
}
fn is_identifier_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::graph::CodeNode;
const COUNTER: &str = r#"@page "/counter"
@* @code { void Commented() { } } *@
<h1>Counter: @currentCount</h1>
<p>Save your work</p>
<button class="btn" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private string label = "}";
protected override void OnInitialized() { Reset(); }
private void IncrementCount()
{
// a brace in a comment: }
currentCount++;
Log(@"C:\path ""quoted"" }");
}
private void Reset() { currentCount = 0; }
private void Save() { }
}
"#;
const DEFAULT_ASPX: &str = r#"<%@ Page Language="VB" AutoEventWireup="true" Inherits="Plant.DefaultPage" %>
<html>
<body>
<script runat="server">
Protected Sub Page_Load(sender As Object, e As EventArgs)
Bind()
End Sub
Protected Sub BtnSave_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Bind()
End Sub
</script>
<script type="text/javascript">function notServer() { }</script>
<form runat="server">
<asp:Button ID="BtnSave" runat="server" OnClick="BtnSave_Click" Text="Save" />
<%# Title() %>
</form>
</body>
</html>
"#;
fn parse(path: &str, source: &str) -> ParseOutput {
MarkupParser::new()
.parse_file(Path::new(path), source, "repo", "build")
.expect("markup parses")
}
fn node<'a>(out: &'a ParseOutput, qualified: &str) -> &'a CodeNode {
out.nodes
.iter()
.find(|n| n.qualified_name == qualified)
.unwrap_or_else(|| panic!("no node {qualified}: {:?}", out.nodes))
}
#[test]
fn a_razor_components_code_block_becomes_its_class() {
let out = parse("Pages/Counter.razor", COUNTER);
let class = node(&out, "Pages/Counter.razor::Counter");
assert!(matches!(class.kind, CodeNodeKind::Class));
assert_eq!(class.language, "csharp");
// Lines are the markup file's lines.
let increment = node(&out, "Pages/Counter.razor::Counter.IncrementCount");
assert_eq!((increment.start_line, increment.end_line), (13, 18));
// Braces in strings and comments don't end the block early.
node(&out, "Pages/Counter.razor::Counter.Save");
// A commented-out block is not code.
assert!(!out.nodes.iter().any(|n| n.name == "Commented"));
}
#[test]
fn methods_the_markup_or_the_framework_calls_are_entry_points() {
let out = parse("Pages/Counter.razor", COUNTER);
let entry =
|name: &str| node(&out, &format!("Pages/Counter.razor::Counter.{name}")).is_entry_point;
assert!(entry("IncrementCount"), "wired by @onclick");
assert!(entry("OnInitialized"), "a lifecycle hook");
assert!(!entry("Reset"), "called from code only");
// "Save" is only text between tags.
assert!(!entry("Save"));
}
#[test]
fn a_web_forms_page_in_vb_reads_its_server_script() {
let out = parse("Default.aspx", DEFAULT_ASPX);
let page = node(&out, "Default.aspx::DefaultPage");
assert_eq!(page.language, "vb");
let load = node(&out, "Default.aspx::DefaultPage.Page_Load");
assert_eq!((load.start_line, load.end_line), (5, 7));
assert!(load.is_entry_point, "AutoEventWireup");
assert!(
node(&out, "Default.aspx::DefaultPage.BtnSave_Click").is_entry_point,
"OnClick"
);
assert!(!node(&out, "Default.aspx::DefaultPage.Bind").is_entry_point);
// The client-side script is not server code.
assert!(!out.nodes.iter().any(|n| n.name == "notServer"));
assert!(out
.edges
.iter()
.any(|e| e.source == "Default.aspx::DefaultPage.Page_Load" && e.target == "Bind"));
}
#[test]
fn a_web_forms_control_without_a_language_is_csharp() {
let source = "<%@ Control %>\n<script runat=server>\n protected void Page_Load(object s, EventArgs e) { Go(); }\n void Go() { }\n</script>\n";
let out = parse("Menu.ascx", source);
let load = node(&out, "Menu.ascx::Menu.Page_Load");
assert_eq!(load.language, "csharp");
assert_eq!(load.start_line, 3);
assert!(out
.edges
.iter()
.any(|e| e.source == "Menu.ascx::Menu.Page_Load" && e.target == "Go"));
}
#[test]
fn the_directive_names_the_class_and_language() {
let (language, class) = web_forms_directive(
"<%@ Master language='vb' Inherits=\"Plant._Site, Plant\" CodeFileBaseClass=\"X\" %>",
);
assert_eq!(language, CodeLanguage::Vb);
assert_eq!(class.as_deref(), Some("_Site"));
// `CodeFileBaseClass` doesn't count as `Inherits`, nor a later
// directive as the page's.
let (language, class) = web_forms_directive(
"<%@ Register Src=\"a.ascx\" %><%@ Page CodeFileBaseClass=\"Base\" %>",
);
assert_eq!(language, CodeLanguage::CSharp);
assert_eq!(class, None);
}
#[test]
fn a_view_without_code_is_a_file_only() {
let out = parse(
"Views/Home/Index.cshtml",
"@model HomeVm\n<h1>@Model.Title</h1>\n",
);
assert_eq!(out.nodes.len(), 1);
assert!(matches!(out.nodes[0].kind, CodeNodeKind::File));
assert_eq!(out.nodes[0].end_line, 2);
}
#[test]
fn the_registry_hands_markup_files_to_this_parser() {
let registry = super::super::registry::ParserRegistry::new();
for ext in ["razor", "cshtml", "aspx", "ascx", "master"] {
assert!(registry.supports_extension(ext), "{ext}");
}
}
#[test]
fn a_class_name_is_an_identifier() {
assert_eq!(class_name(Path::new("Pages/Counter.razor")), "Counter");
assert_eq!(class_name(Path::new("_Layout.cshtml")), "_Layout");
assert_eq!(class_name(Path::new("404-page.aspx")), "_404_page");
}
}
+1
View File
@@ -2,6 +2,7 @@ pub mod c;
mod common;
pub mod csharp;
pub mod javascript;
pub mod markup;
pub mod python;
pub mod registry;
pub mod rust_parser;
+2
View File
@@ -8,6 +8,7 @@ use tracing::{debug, info, warn};
use super::c::CParser;
use super::csharp::CSharpParser;
use super::javascript::JavaScriptParser;
use super::markup::MarkupParser;
use super::python::PythonParser;
use super::rust_parser::RustParser;
use super::typescript::TypeScriptParser;
@@ -40,6 +41,7 @@ impl ParserRegistry {
Box::new(CParser::new()),
Box::new(CSharpParser::new()),
Box::new(VbParser::new()),
Box::new(MarkupParser::new()),
];
let mut extension_map = HashMap::new();