From f4b50459ee1138bf1f487ea95c045e7eac6e68fa Mon Sep 17 00:00:00 2001
From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Date: Mon, 9 Nov 2026 12:40:09 +0100
Subject: [PATCH] feat(graph): Razor and Web Forms code in the code graph (t84)
The code regions of ASP.NET markup files are now parsed: @code and
@functions blocks of .razor and .cshtml files, and ` 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 `` 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 {
+ 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, ®ions, &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, ®ions);
+ 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 `` tag.
+fn web_forms_regions(source: &str) -> Vec {
+ // 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"").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) {
+ // 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 {
+ 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::, 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 {
+ 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 {
+ 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() { } } *@
+
Counter: @currentCount
+
Save your work
+
+
+@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" %>
+
+
+
+
+
+
+
+"#;
+
+ 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\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
@Model.Title
\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");
+ }
+}
diff --git a/compliance-graph/src/parsers/mod.rs b/compliance-graph/src/parsers/mod.rs
index 0548529..ca42577 100644
--- a/compliance-graph/src/parsers/mod.rs
+++ b/compliance-graph/src/parsers/mod.rs
@@ -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;
diff --git a/compliance-graph/src/parsers/registry.rs b/compliance-graph/src/parsers/registry.rs
index 38f482d..5b101e8 100644
--- a/compliance-graph/src/parsers/registry.rs
+++ b/compliance-graph/src/parsers/registry.rs
@@ -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();
--
2.54.1