Compare commits

..
3 Commits
Author SHA1 Message Date
sharangandClaude Opus 5.5 29d3c91f5a feat(graph): Razor and Web Forms code in the code graph (t84) (#944)
CI / Agent integration (push) Skipped
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 6m14s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:10:23 +00:00
sharangandClaude Opus 5.5 5a11a3b602 feat(graph): Visual Basic .NET in the code graph (t84) (#943)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 3m30s
CI / Deploy Dashboard (push) Successful in 4m8s
CI / Deploy Agent (push) Successful in 6m21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 11:49:59 +00:00
sharangandClaude Opus 5.5 ca66b9a7b1 fix(scan): read UTF-16 and Windows-1252 files in the remaining readers (t84) (#942)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 51s
CI / Deploy Dashboard (push) Successful in 5m8s
CI / Deploy Agent (push) Successful in 7m21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:58:55 +00:00
25 changed files with 1477 additions and 35 deletions

No files matched your search

Generated
+15 -3
View File
@@ -662,6 +662,7 @@ dependencies = [
"base64 0.22.1",
"bson",
"chrono",
"encoding_rs",
"hex",
"jsonschema",
"jsonwebtoken",
@@ -749,7 +750,6 @@ dependencies = [
"bson",
"chrono",
"compliance-core",
"encoding_rs",
"futures-util",
"mongodb",
"petgraph",
@@ -765,6 +765,7 @@ dependencies = [
"tree-sitter-python",
"tree-sitter-rust",
"tree-sitter-typescript",
"tree-sitter-vb-dotnet",
]
[[package]]
@@ -6495,13 +6496,14 @@ dependencies = [
[[package]]
name = "tree-sitter"
version = "0.24.7"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5387dffa7ffc7d2dae12b50c6f7aab8ff79d6210147c6613561fc3d474c6f75"
checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87"
dependencies = [
"cc",
"regex",
"regex-syntax",
"serde_json",
"streaming-iterator",
"tree-sitter-language",
]
@@ -6572,6 +6574,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-vb-dotnet"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180e4a199378505f9305c3d01d6ece8a8d34035f310de1c727693f8a2296025e"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "try-lock"
version = "0.2.5"
+1 -1
View File
@@ -413,7 +413,7 @@ pub async fn get_file_content(
// Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens.
let content =
compliance_graph::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
compliance_core::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
// Cap at 10,000 lines
let truncated: String = content.lines().take(10_000).collect::<Vec<_>>().join("\n");
+1 -1
View File
@@ -215,7 +215,7 @@ pub async fn grounded_surface_findings(
/// Read a window of lines around `line` (1-based) from `repo_path/file`.
fn fetch_region(repo_path: &Path, file: &str, line: u32) -> Option<CandidateRegion> {
let content = compliance_graph::encoding::read_source(&repo_path.join(file)).ok()?;
let content = compliance_core::encoding::read_source(&repo_path.join(file)).ok()?;
let lines: Vec<&str> = content.lines().collect();
if lines.is_empty() {
return None;
+22 -3
View File
@@ -116,8 +116,8 @@ pub const SURFACES: &[Surface] = &[
/// Source file extensions worth reading (skip binaries/assets/lockfiles).
const CODE_EXTS: &[&str] = &[
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "kt", "c", "h", "cc",
"cpp", "hpp",
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "vb", "kt", "c", "h",
"cc", "cpp", "hpp",
];
/// Directories never worth walking.
const SKIP_DIRS: &[&str] = &[
@@ -156,7 +156,8 @@ pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec<Ca
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
let Ok(content) = compliance_core::encoding::read_source(path) else {
continue;
};
let rel = path
@@ -286,6 +287,24 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_windows_1252_file_is_read() {
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
// "Prüfung" as Windows-1252 writes it: 0xFC for "ü".
let path = dir.join("app/Auth.cs");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
b"// Pr\xFCfung\nbool Login(string u, string p) { }\n",
)
.unwrap();
let regions = retrieve(&dir, terms_for("cra-ai-11"), &[]);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(regions.len(), 1);
assert!(regions[0].content.contains("Prüfung"));
}
#[test]
fn firmware_update_code_is_read_but_not_the_vendor_hal() {
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
+1 -1
View File
@@ -861,7 +861,7 @@ fn read_surrounding_context(finding: &Finding) -> Option<String> {
let line = finding.line_number? as usize;
// Try to read the file — this works because the repo is cloned locally
let content = compliance_graph::encoding::read_source(std::path::Path::new(file_path)).ok()?;
let content = compliance_core::encoding::read_source(std::path::Path::new(file_path)).ok()?;
let lines: Vec<&str> = content.lines().collect();
let start = line.saturating_sub(25);
+2 -2
View File
@@ -146,14 +146,14 @@ pub(crate) fn relative(root: &Path, path: &Path) -> String {
/// The text of a file that may start with a byte-order mark (Visual Studio
/// writes UTF-8 with BOM, older tools UTF-16) or be Windows-1252, decoded by
/// [`compliance_graph::encoding::read_source`]. `None` for a file too large or
/// [`compliance_core::encoding::read_source`]. `None` for a file too large or
/// unreadable.
pub(crate) fn read_text(path: &Path) -> Option<String> {
let meta = std::fs::metadata(path).ok()?;
if meta.len() > MAX_FILE_BYTES {
return None;
}
compliance_graph::encoding::read_source(path).ok()
compliance_core::encoding::read_source(path).ok()
}
/// Parse XML the way project and configuration files need: a DTD is allowed
@@ -148,7 +148,7 @@ pub fn detect(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES);
let Some(text) = small
// Vendor SDK headers are often Windows-1252 (a "©" in the banner).
.then(|| compliance_graph::encoding::read_source(entry.path()).ok())
.then(|| compliance_core::encoding::read_source(entry.path()).ok())
.flatten()
else {
continue;
+22 -1
View File
@@ -973,7 +973,8 @@ fn content_fingerprints(tree: &Path, findings: &mut [Finding]) {
continue;
};
let lines = files.entry(path.clone()).or_insert_with(|| {
std::fs::read_to_string(tree.join(&path))
// Decoded like the scanners read it: UTF-8, UTF-16, Windows-1252.
compliance_core::encoding::read_source(&tree.join(&path))
.ok()
.map(|text| text.lines().map(normalised).collect())
});
@@ -1249,6 +1250,26 @@ mod tests {
assert!(missing[0].legacy_fingerprints.is_empty());
}
#[test]
fn a_windows_1252_file_is_keyed_by_content_as_its_utf8_version_is() {
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
// "größe" as Windows-1252 writes it (0xF6 0xDF), then the same file
// saved again as UTF-8.
std::fs::write(dir.join("a.c"), b"int x;\nint gr\xF6\xDFe = read();\n").unwrap();
let ansi = keyed(&dir, vec![at("a.c", 2)]);
std::fs::write(dir.join("a.c"), "int x;\nint größe = read();\n").unwrap();
let utf8 = keyed(&dir, vec![at("a.c", 2)]);
let _ = std::fs::remove_dir_all(&dir);
// Keyed by content, with the line-based key kept to adopt the row
// stored under it while the file could not be read.
let line_key = crate::pipeline::dedup::compute_fingerprint(&["repo-1", "rule", "a.c", "2"]);
assert_eq!(ansi[0].legacy_fingerprints, std::slice::from_ref(&line_key));
assert_ne!(ansi[0].fingerprint, line_key);
// Re-saving the file in another encoding keeps the key.
assert_eq!(ansi[0].fingerprint, utf8[0].fingerprint);
}
#[test]
fn a_scanners_own_content_and_groups_are_respected() {
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
+46 -1
View File
@@ -495,7 +495,18 @@ impl GitOps {
_ => "",
};
let content = std::str::from_utf8(line.content()).unwrap_or("");
// A diff line is UTF-8 or, from an older tool, Windows-1252
// (single-byte, so a line decodes on its own). UTF-16 files are
// binary to git and have no lines here.
let bytes = line.content();
let decoded;
let content = match std::str::from_utf8(bytes) {
Ok(text) => text,
Err(_) => {
decoded = compliance_core::encoding::decode(bytes.to_vec()).unwrap_or_default();
decoded.as_str()
}
};
diff_file.hunks.push_str(prefix);
diff_file.hunks.push_str(content);
@@ -919,4 +930,38 @@ mod tests {
.expect_err("private origin must be refused");
assert!(err.to_string().contains("10.0.0.5"), "{err}");
}
#[test]
fn a_windows_1252_line_shows_in_the_diff() {
// Arrange: a file committed, then a line with "für" as Windows-1252
// writes it (0xFC) added in a second commit.
let dir = source_repo();
let repo = git2::Repository::open(&dir).unwrap();
let old = repo.head().unwrap().peel_to_commit().unwrap();
std::fs::write(
dir.join("README.md"),
b"pump controller\n// f\xFCr Halle 2\n",
)
.unwrap();
let mut index = repo.index().unwrap();
index.add_path(Path::new("README.md")).unwrap();
index.write().unwrap();
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
let sig = git2::Signature::now("t", "t@example.com").unwrap();
let new = repo
.commit(Some("HEAD"), &sig, &sig, "note", &tree, &[&old])
.unwrap();
// Act
let diff = GitOps::get_diff_content(&dir, &old.id().to_string(), &new.to_string()).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
// Assert: the added line is there, decoded.
assert_eq!(diff.len(), 1);
assert!(
diff[0].hunks.contains("+// für Halle 2"),
"{}",
diff[0].hunks
);
}
}
+37 -3
View File
@@ -186,9 +186,17 @@ fn scan_with_patterns(
.unwrap_or("")
.to_string();
let content = match std::fs::read_to_string(path) {
Ok(c) => c,
Err(_) => continue, // skip binary files
// Only files a pattern looks at are read at all.
if !patterns.iter().any(|p| p.file_extensions.contains(&ext)) {
continue;
}
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
let content = match compliance_core::encoding::read_source(path) {
Ok(text) => text,
Err(error) => {
tracing::debug!(file = %path.display(), %error, "pattern scan: file not readable");
continue;
}
};
let relative_path = path
@@ -417,4 +425,30 @@ mod tests {
assert!(!pattern.file_extensions.contains(&"rs".to_string()));
assert!(!pattern.file_extensions.contains(&"py".to_string()));
}
// --- file decoding ---
#[test]
fn a_windows_1252_file_is_scanned_not_skipped() {
// Arrange: a C# file written by an older tool, "Größe" as 0xF6 0xDF.
let dir = std::env::temp_dir().join(format!("cs-pat-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("Log.cs"), b"// Gr\xF6\xDFe\nLog(email);\n").unwrap();
let rule = PatternRule {
id: "pii".into(),
title: "t".into(),
description: "d".into(),
pattern: compile_regex(r"Log\(email\)"),
severity: Severity::Medium,
file_extensions: vec!["cs".into()],
};
// Act
let findings = scan_with_patterns(&dir, "repo", &[rule], ScanType::Gdpr, "t").unwrap();
let _ = std::fs::remove_dir_all(&dir);
// Assert: found on its line.
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].line_number, Some(2));
}
}
+3 -3
View File
@@ -60,7 +60,7 @@ pub(crate) struct PlcFile {
/// Read every PLC source file under `root` (Structured Text, and PLCopen XML
/// exports) into its POUs. Files with no POU are left out.
///
/// Each file is decoded by [`compliance_graph::encoding::read_source`]:
/// Each file is decoded by [`compliance_core::encoding::read_source`]:
/// CODESYS and TIA exports are often Windows-1252 or UTF-16. Files still not
/// readable as text are logged as one warning per tree.
pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
@@ -84,7 +84,7 @@ pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
if !is_st && !is_xml {
continue;
}
let content = match compliance_graph::encoding::read_source(path) {
let content = match compliance_core::encoding::read_source(path) {
Ok(text) => text,
Err(error) => {
// A binary `.project` is CODESYS's native format, which
@@ -210,7 +210,7 @@ pub fn native_projects(root: &Path) -> Vec<String> {
.to_ascii_lowercase();
let native = match ext.as_str() {
// Decoded as [`read_tree`] reads it: a UTF-16 export is no native one.
"project" => !compliance_graph::encoding::read_source(path)
"project" => !compliance_core::encoding::read_source(path)
.is_ok_and(|text| looks_like_xml(&text)),
"projectarchive" => sbom::check_archive(path).is_ok(),
_ => false,
+2 -2
View File
@@ -20,7 +20,7 @@ pub fn relative_path(root: &Path, path: &str) -> String {
}
/// The whole text of `root/rel`, decoded by
/// [`compliance_graph::encoding::read_source`]. `None` when the file is
/// [`compliance_core::encoding::read_source`]. `None` when the file is
/// unreadable or the path would leave `root`: scanner output is not trusted
/// to stay inside the tree.
pub fn read_text(root: &Path, rel: &str) -> Option<String> {
@@ -33,7 +33,7 @@ pub fn read_text(root: &Path, rel: &str) -> Option<String> {
return None;
}
// UTF-16 with a BOM and Windows-1252 too, as the code graph reads them.
compliance_graph::encoding::read_source(&root.join(rel_path)).ok()
compliance_core::encoding::read_source(&root.join(rel_path)).ok()
}
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
+2
View File
@@ -45,6 +45,8 @@ serde = { workspace = true }
serde_json = { workspace = true }
chrono = { workspace = true }
thiserror = { workspace = true }
# Decoding source files: BOM sniffing, UTF-16, Windows-1252
encoding_rs = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
uuid = { workspace = true }
@@ -72,7 +72,7 @@ pub fn read_source(path: &Path) -> Result<String, SourceTextError> {
/// # Examples
///
/// ```
/// use compliance_graph::encoding::decode;
/// use compliance_core::encoding::decode;
///
/// // "€" is 0x80 in Windows-1252.
/// assert_eq!(decode(b"// 5 \x80".to_vec()).ok().as_deref(), Some("// 5 €"));
@@ -108,7 +108,23 @@ pub fn decode(mut bytes: Vec<u8>) -> Result<String, SourceTextError> {
#[cfg(test)]
mod tests {
use super::*;
use crate::test_tree::utf16;
/// `text` as UTF-16 with its BOM, in the byte order asked for.
fn utf16(text: &str, little_endian: bool) -> Vec<u8> {
let bom: [u8; 2] = if little_endian {
[0xFF, 0xFE]
} else {
[0xFE, 0xFF]
};
let units = text.encode_utf16().flat_map(|unit| {
if little_endian {
unit.to_le_bytes()
} else {
unit.to_be_bytes()
}
});
bom.into_iter().chain(units).collect()
}
#[test]
fn utf8_without_a_bom_is_kept_as_it_is() {
@@ -164,7 +180,7 @@ mod tests {
#[test]
fn a_missing_file_is_an_io_error() {
let missing = std::env::temp_dir().join("compliance-graph-no-such-file.cs");
let missing = std::env::temp_dir().join("compliance-core-no-such-file.cs");
assert!(matches!(read_source(&missing), Err(SourceTextError::Io(_))));
}
}
+1
View File
@@ -4,6 +4,7 @@ pub mod control_check;
pub mod csaf_docs;
pub mod csaf_ingest;
pub mod db;
pub mod encoding;
pub mod enisa_docs;
pub mod error;
pub mod exec_policy;
+5
View File
@@ -3171,6 +3171,7 @@ pub mod compliance {
"php" => "PHP",
"rust" => "Rust",
"csharp" => "C#",
"vb" => "Visual Basic",
"swift" => "Swift",
"structured_text" => "Structured Text",
"plcopen" => "PLCopen XML",
@@ -3312,6 +3313,10 @@ pub mod compliance {
not_assessed_reason(&reason, Lang::De).as_deref(),
Some("Keine Prüfregel für den gefundenen Code: C, C++")
);
assert_eq!(
language_list(&[serde_json::json!("csharp"), serde_json::json!("vb")]),
"C#, Visual Basic"
);
assert_eq!(
not_assessed_reason(&serde_json::json!({ "kind": "no_tool" }), Lang::En).as_deref(),
Some("Checkable in code, but no rule checks it yet.")
+3 -3
View File
@@ -15,17 +15,17 @@ tokio = { workspace = true }
mongodb = { workspace = true }
thiserror = { workspace = true }
# Decoding source files: BOM sniffing, UTF-16, Windows-1252
encoding_rs = { workspace = true }
# Tree-sitter parsing
tree-sitter = "0.24"
tree-sitter = "0.25"
tree-sitter-rust = "0.23"
tree-sitter-python = "0.23"
tree-sitter-javascript = "0.23"
tree-sitter-typescript = "0.23"
tree-sitter-c = "0.23"
tree-sitter-c-sharp = "=0.23.1"
# VB.NET, CodeAnt-AI grammar (MIT), ABI 15: needs tree-sitter 0.25
tree-sitter-vb-dotnet = "=0.1.0"
# Graph algorithms
petgraph = "0.7"
+1 -1
View File
@@ -30,7 +30,7 @@ pub fn extract_chunks(
for node in nodes {
let file = repo_path.join(&node.file_path);
// Decoded as the graph's parser read it, so every node has its lines.
let source = match crate::encoding::read_source(&file) {
let source = match compliance_core::encoding::read_source(&file) {
Ok(s) => s,
Err(_) => continue,
};
-1
View File
@@ -1,7 +1,6 @@
#![allow(clippy::only_used_in_recursion)]
#![allow(clippy::too_many_arguments)]
pub mod encoding;
pub mod graph;
pub mod parsers;
pub mod search;
+2 -2
View File
@@ -19,7 +19,7 @@ use super::common::{parse, text, walk, FileGraph};
/// Base types whose methods a web framework calls: MVC and API
/// controllers, Razor pages, SignalR hubs, Web Forms pages, controls and
/// master pages, and ASMX services.
const WEB_BASES: [&str; 9] = [
pub(super) const WEB_BASES: [&str; 9] = [
"Controller",
"ControllerBase",
"ApiController",
@@ -32,7 +32,7 @@ const WEB_BASES: [&str; 9] = [
];
/// Attributes that expose a method over HTTP.
const ENDPOINT_ATTRIBUTES: [&str; 10] = [
pub(super) const ENDPOINT_ATTRIBUTES: [&str; 10] = [
"HttpGet",
"HttpPost",
"HttpPut",
+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");
}
}
+2
View File
@@ -2,9 +2,11 @@ pub mod c;
mod common;
pub mod csharp;
pub mod javascript;
pub mod markup;
pub mod python;
pub mod registry;
pub mod rust_parser;
pub mod typescript;
pub mod vb;
pub use common::FileGraph;
+44 -2
View File
@@ -8,9 +8,11 @@ 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;
use super::vb::VbParser;
/// What [`ParserRegistry::parse_directory`] made of a tree.
#[derive(Debug, Default)]
@@ -38,6 +40,8 @@ impl ParserRegistry {
Box::new(TypeScriptParser::new()),
Box::new(CParser::new()),
Box::new(CSharpParser::new()),
Box::new(VbParser::new()),
Box::new(MarkupParser::new()),
];
let mut extension_map = HashMap::new();
@@ -91,7 +95,7 @@ impl ParserRegistry {
/// Parse all supported files in a directory tree.
///
/// Each file is decoded by [`crate::encoding::read_source`] (UTF-8,
/// Each file is decoded by [`compliance_core::encoding::read_source`] (UTF-8,
/// UTF-16 with a BOM, Windows-1252); a file still not readable as text
/// is counted, not parsed.
///
@@ -175,6 +179,9 @@ impl ParserRegistry {
|| name == "vendor"
|| name == "dist"
|| name == "build"
// .NET's intermediate output: generated sources such as
// `*.g.cs` and the Razor compiler's `*.razor.g.cs`.
|| name == "obj"
|| name == ".git"
{
continue;
@@ -205,7 +212,7 @@ impl ParserRegistry {
// Use relative path from base
let rel_path = path.strip_prefix(base).unwrap_or(&path);
let source = match crate::encoding::read_source(&path) {
let source = match compliance_core::encoding::read_source(&path) {
Ok(text) => text,
Err(error) => {
debug!(file = %rel_path.display(), %error, "Source file not readable");
@@ -372,6 +379,41 @@ mod tests {
assert_eq!(parsed.unreadable_files, 2);
}
#[test]
fn vb_files_parse_and_dotnet_build_output_is_left_out() {
// Arrange: a Windows-1252 VB module ("für" as 0xFC) and what a .NET
// build leaves in `obj/`.
let tree = crate::test_tree::TempTree::new("registry-vb");
tree.write(
"Pump.vb",
b"' Pumpe f\xFCr Halle 2\nModule Pump\n Sub Main()\n End Sub\nEnd Module\n",
);
std::fs::create_dir_all(tree.path().join("obj/Debug")).expect("obj dir");
tree.write(
"obj/Debug/App.g.cs",
b"class Generated { void Run() { } }\n",
);
// Act
let parsed = ParserRegistry::new()
.parse_directory(tree.path(), "repo1", "build1", 1000)
.expect("tree parses");
// Assert
let names: Vec<&str> = parsed
.output
.nodes
.iter()
.map(|n| n.name.as_str())
.collect();
assert!(
names.contains(&"Pump") && names.contains(&"Main"),
"{names:?}"
);
assert!(!names.contains(&"Generated"), "{names:?}");
assert_eq!(parsed.unreadable_files, 0);
}
#[test]
fn test_default_trait() {
let registry = ParserRegistry::default();
+565
View File
@@ -0,0 +1,565 @@
//! Visual Basic .NET: classes, modules, structures, interfaces and enums,
//! their methods and constructors, base types, and calls. Entry points are
//! `Main` and what a framework calls from outside, as for C#: ASP.NET
//! controller actions, Web Forms pages and controls, ASMX web methods, HTTP
//! handlers, and event handlers wired with `Handles`.
//!
//! VB is case-insensitive, so keywords, modifiers, attribute and base type
//! names are compared ignoring case; names keep the case they are written in.
//!
//! The grammar (CodeAnt-AI's tree-sitter-vb-dotnet) expects `Inherits` and
//! `Implements` on the `Class` line itself, while VB puts them on the lines
//! after it, so base types are read from the source text instead.
//! `Imports` statements are left out: the graph has no namespace nodes they
//! could point to.
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
use tree_sitter::Node;
use super::common::{line, parse, text, walk, FileGraph};
use super::csharp::{ENDPOINT_ATTRIBUTES, WEB_BASES};
/// Parses Visual Basic .NET sources.
#[derive(Debug, Default)]
pub struct VbParser;
/// What a method's entry-point rule needs to know about its type.
#[derive(Clone, Copy)]
struct TypeContext<'a> {
qualified: &'a str,
/// A `Module`, whose members are all `Shared`.
module: bool,
/// The type inherits a web framework base or is an `<ApiController>`.
web: bool,
/// The type implements `IHttpHandler`, whose `ProcessRequest` the server calls.
http_handler: bool,
}
/// A type named in an `Inherits` or `Implements` statement.
struct BaseType<'s> {
name: &'s str,
kind: CodeEdgeKind,
line: u32,
}
impl VbParser {
/// A Visual Basic .NET parser.
pub fn new() -> Self {
Self
}
/// Visit type blocks at file level and in namespaces.
fn declarations(root: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
walk(root, |node| match node.kind() {
"class_block" | "module_block" | "structure_block" | "interface_block"
| "enum_block" => {
Self::type_block(node, source, graph);
false
}
"source_file" | "namespace_block" | "type_declaration" => true,
_ => false,
});
}
fn type_block(node: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
let Some(name) = node.child_by_field_name("name").map(|n| text(n, source)) else {
return;
};
let qualified = graph.top_level(name);
let kind = match node.kind() {
"module_block" => CodeNodeKind::Module,
"structure_block" => CodeNodeKind::Struct,
"interface_block" => CodeNodeKind::Interface,
"enum_block" => CodeNodeKind::Enum,
_ => CodeNodeKind::Class,
};
graph.node_at(
qualified.clone(),
name.to_string(),
kind,
lines(node),
false,
);
let bases = base_types(node, source);
for base in &bases {
graph.edge_at(&qualified, base.name, base.kind.clone(), base.line);
}
let named = |kind: CodeEdgeKind, wanted: &[&str]| {
bases
.iter()
.any(|b| b.kind == kind && wanted.iter().any(|w| b.name.eq_ignore_ascii_case(w)))
};
let context = TypeContext {
qualified: &qualified,
module: node.kind() == "module_block",
web: named(CodeEdgeKind::Inherits, &WEB_BASES)
|| attributes(node, source).any(|a| a.eq_ignore_ascii_case("ApiController")),
http_handler: named(CodeEdgeKind::Implements, &["IHttpHandler"]),
};
let mut cursor = node.walk();
for member in node.named_children(&mut cursor) {
if matches!(
member.kind(),
"method_declaration" | "constructor_declaration"
) {
Self::method(member, context, source, graph);
}
}
}
fn method(node: Node<'_>, ty: TypeContext<'_>, source: &str, graph: &mut FileGraph<'_>) {
// A constructor is `Sub New`, and has no name field.
let name = match node.child_by_field_name("name") {
Some(name) => text(name, source),
None if node.kind() == "constructor_declaration" => "New",
None => return,
};
let qualified = format!("{}.{name}", ty.qualified);
let is_entry =
node.kind() == "method_declaration" && is_entry_point(node, name, ty, source);
graph.node_at(
qualified.clone(),
name.to_string(),
CodeNodeKind::Method,
lines(node),
is_entry,
);
Self::calls(node, &qualified, source, graph);
}
/// Calls by method name (`repo.Find(id)` and `Init` without parentheses
/// call `Find` and `Init`) and constructions (`New OrderDto(o)` calls
/// `OrderDto`).
fn calls(method: Node<'_>, caller: &str, source: &str, graph: &mut FileGraph<'_>) {
walk(method, |node| {
let callee = match node.kind() {
"invocation" => node.child_by_field_name("target").and_then(simple_name),
"new_expression" => node.child_by_field_name("type").and_then(simple_name),
// A statement that is only a name calls it: `Init`, `Me.Save`.
"call_statement" => node
.named_child(0)
.and_then(|expression| expression.named_child(0))
.filter(|e| matches!(e.kind(), "identifier" | "member_access"))
.and_then(simple_name),
_ => None,
};
if let Some(callee) = callee {
graph.edge(caller, text(callee, source), CodeEdgeKind::Calls, node);
}
true
});
}
}
/// Whether the framework, not our own code, calls this method.
fn is_entry_point(method: Node<'_>, name: &str, ty: TypeContext<'_>, source: &str) -> bool {
let modifiers: Vec<&str> = method
.child_by_field_name("modifiers")
.map(|list| {
let mut cursor = list.walk();
list.named_children(&mut cursor)
.map(|m| text(m, source))
.collect()
})
.unwrap_or_default();
let has_modifier = |wanted: &str| modifiers.iter().any(|m| m.eq_ignore_ascii_case(wanted));
if name.eq_ignore_ascii_case("Main") && (ty.module || has_modifier("Shared")) {
return true;
}
if attributes(method, source).any(|a| {
ENDPOINT_ATTRIBUTES
.iter()
.any(|e| a.eq_ignore_ascii_case(e))
}) {
return true;
}
if ty.http_handler && name.eq_ignore_ascii_case("ProcessRequest") {
return true;
}
// `Sub Page_Load(...) Handles Me.Load`: the framework raises the event.
// The grammar doesn't parse the clause, so the header line decides.
if header(method, source)
.split_whitespace()
.any(|word| word.eq_ignore_ascii_case("Handles"))
{
return true;
}
// Controller actions are public, Web Forms event handlers usually
// protected.
ty.web && (has_modifier("Public") || has_modifier("Protected"))
}
/// The 1-based first and last line of a declaration. A VB block ends with
/// its line break, so its end position is column 0 of the next line, which
/// is not part of it.
fn lines(node: Node<'_>) -> (u32, u32) {
let end = node.end_position();
let last_row = if end.column == 0 && end.row > node.start_position().row {
end.row - 1
} else {
end.row
};
(line(node), last_row as u32 + 1)
}
/// A declaration's first line, without a trailing comment.
fn header<'s>(declaration: Node<'_>, source: &'s str) -> &'s str {
let first = text(declaration, source).lines().next().unwrap_or_default();
first.split('\'').next().unwrap_or_default()
}
/// The simple names of a declaration's attributes, without namespace or
/// the `Attribute` suffix: `<System.Web.Services.WebMethodAttribute()>` is
/// `WebMethod`.
fn attributes<'s>(declaration: Node<'_>, source: &'s str) -> impl Iterator<Item = &'s str> {
let mut names = Vec::new();
let mut cursor = declaration.walk();
for block in declaration
.children(&mut cursor)
.filter(|c| c.kind() == "attribute_block")
{
let mut inner = block.walk();
for attribute in block.named_children(&mut inner) {
if let Some(name) = attribute.child_by_field_name("name").and_then(simple_name) {
let name = text(name, source);
let stem = name.len().checked_sub("Attribute".len()).filter(|&at| {
name.is_char_boundary(at) && name[at..].eq_ignore_ascii_case("Attribute")
});
names.push(stem.map_or(name, |at| &name[..at]));
}
}
}
names.into_iter()
}
/// The types a type block's `Inherits` and `Implements` statements name,
/// read from the lines that open the block: the header line (`Class A :
/// Inherits B`) and the lines after it, until the first member.
fn base_types<'s>(block: Node<'_>, source: &'s str) -> Vec<BaseType<'s>> {
let mut bases = Vec::new();
let first_line = line(block);
for (offset, line_text) in text(block, source).lines().enumerate() {
let code = line_text.split('\'').next().unwrap_or_default().trim();
if code.is_empty() {
continue;
}
// Statements on one line are separated by `:`; the header line's
// first one is the `Class` statement itself.
let mut found = false;
for statement in code
.split(':')
.map(str::trim)
.skip(usize::from(offset == 0))
{
let (kind, types) = if let Some(types) = keyword_rest(statement, "Inherits") {
(CodeEdgeKind::Inherits, types)
} else if let Some(types) = keyword_rest(statement, "Implements") {
(CodeEdgeKind::Implements, types)
} else {
continue;
};
found = true;
let line = first_line + u32::try_from(offset).unwrap_or(u32::MAX);
bases.extend(
split_types(types)
.filter_map(simple_type_name)
.map(|name| BaseType {
name,
kind: kind.clone(),
line,
}),
);
}
// `Inherits` and `Implements` come before every member.
if offset > 0 && !found {
break;
}
}
bases
}
/// What follows `keyword` (case-insensitive) at the start of `statement`.
fn keyword_rest<'s>(statement: &'s str, keyword: &str) -> Option<&'s str> {
let head = statement.get(..keyword.len())?;
let rest = &statement[keyword.len()..];
(head.eq_ignore_ascii_case(keyword) && rest.starts_with(char::is_whitespace))
.then(|| rest.trim())
}
/// The comma-separated types of a list, with commas inside `(Of K, V)`
/// left alone.
fn split_types(list: &str) -> impl Iterator<Item = &str> {
let mut depth = 0usize;
let mut start = 0;
let mut parts = Vec::new();
for (at, ch) in list.char_indices() {
match ch {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
parts.push(&list[start..at]);
start = at + 1;
}
_ => {}
}
}
parts.push(&list[start..]);
parts.into_iter().map(str::trim)
}
/// The simple name of a written type: `System.Web.UI.Page` is `Page`,
/// `List(Of Order)` is `List`.
fn simple_type_name(written: &str) -> Option<&str> {
let without_args = written.split('(').next().unwrap_or_default();
let name = without_args.rsplit('.').next().unwrap_or_default().trim();
(!name.is_empty()).then_some(name)
}
/// The last identifier of a name in the syntax tree: `Me.repo.Find` is
/// `Find`, `List(Of Integer)` is `List`.
fn simple_name(node: Node<'_>) -> Option<Node<'_>> {
match node.kind() {
"identifier" => Some(node),
"member_access" => node.child_by_field_name("member").and_then(simple_name),
"namespace_name" => {
let mut cursor = node.walk();
let last = node
.named_children(&mut cursor)
.filter(|n| n.kind() == "identifier")
.last();
last
}
"expression" | "type" | "generic_type" => node.named_child(0).and_then(simple_name),
_ => None,
}
}
impl LanguageParser for VbParser {
fn language(&self) -> &str {
"vb"
}
fn extensions(&self) -> &[&str] {
&["vb"]
}
fn parse_file(
&self,
file_path: &Path,
source: &str,
repo_id: &str,
graph_build_id: &str,
) -> Result<ParseOutput, CoreError> {
let tree = parse(tree_sitter_vb_dotnet::LANGUAGE.into(), source, "VB.NET")?;
let mut graph = FileGraph::new(
file_path,
source.lines().count() as u32,
repo_id,
graph_build_id,
"vb",
);
Self::declarations(tree.root_node(), source, &mut graph);
Ok(graph.finish())
}
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::graph::CodeNode;
const WEB_APP: &str = r#"Imports System.Web.UI
Namespace Plant.Web
Public Module Program
Sub Main(args As String())
Dim c = New Pump(3)
c.Start
End Sub
End Module
Public Class OrdersPage
Inherits System.Web.UI.Page
Implements IDisposable, IComparable(Of OrdersPage)
Public Sub New()
Init()
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim names = From p In Pumps Where p.Active Select p.Name
Bind(names)
End Sub
Private Sub Bind(names As Object)
End Sub
Private Sub Init()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class Pump : Inherits Machine
Private Sub OnTick(sender As Object, e As EventArgs) handles timer.Tick
End Sub
Public Sub Start(n As Integer)
Helper.Scale(n)
End Sub
End Class
Public Class Service
Inherits WebService
<WebMethodAttribute()>
Public Shared Function Ping() As String
Return "pong"
End Function
End Class
Public Class Download
Implements IHttpHandler
Public Sub ProcessRequest(c As HttpContext)
End Sub
Public Shared Sub Main()
End Sub
End Class
Public Structure Pt
Public X As Integer
End Structure
Public Enum Kind
A
B
End Enum
End Namespace
"#;
fn parsed() -> ParseOutput {
VbParser::new()
.parse_file(Path::new("Web/Orders.vb"), WEB_APP, "repo", "build")
.expect("VB parses")
}
fn node<'a>(out: &'a ParseOutput, qualified: &str) -> &'a CodeNode {
let qualified = format!("Web/Orders.vb::{qualified}");
out.nodes
.iter()
.find(|n| n.qualified_name == qualified)
.unwrap_or_else(|| panic!("no node {qualified}"))
}
#[test]
fn types_and_methods_become_nodes() {
let out = parsed();
assert!(matches!(node(&out, "Program").kind, CodeNodeKind::Module));
assert!(matches!(node(&out, "OrdersPage").kind, CodeNodeKind::Class));
assert!(matches!(node(&out, "Pt").kind, CodeNodeKind::Struct));
assert!(matches!(node(&out, "Kind").kind, CodeNodeKind::Enum));
// Members around a LINQ query the grammar can't parse still come out.
for method in [
"Program.Main",
"OrdersPage.New",
"OrdersPage.Page_Load",
"OrdersPage.Bind",
"OrdersPage.Dispose",
"Pump.Start",
] {
assert!(
matches!(node(&out, method).kind, CodeNodeKind::Method),
"{method}"
);
}
let page_load = node(&out, "OrdersPage.Page_Load");
assert_eq!((page_load.start_line, page_load.end_line), (19, 22));
}
#[test]
fn framework_called_methods_are_entry_points() {
let out = parsed();
for entry in [
"Program.Main",
"OrdersPage.Page_Load",
"OrdersPage.Dispose",
"Pump.OnTick",
"Service.Ping",
"Download.ProcessRequest",
"Download.Main",
] {
assert!(
node(&out, entry).is_entry_point,
"{entry} is an entry point"
);
}
for internal in [
"OrdersPage.New",
"OrdersPage.Bind",
"OrdersPage.Init",
"Pump.Start",
] {
assert!(!node(&out, internal).is_entry_point, "{internal} is not");
}
}
#[test]
fn bases_and_calls_become_edges() {
let out = parsed();
let edges: Vec<(&str, &str, &str, Option<u32>)> = out
.edges
.iter()
.map(|e| {
let kind = match e.kind {
CodeEdgeKind::Calls => "calls",
CodeEdgeKind::Inherits => "inherits",
CodeEdgeKind::Implements => "implements",
_ => "other",
};
(kind, e.source.as_str(), e.target.as_str(), e.line_number)
})
.collect();
let page = "Web/Orders.vb::OrdersPage";
assert!(edges.contains(&("inherits", page, "Page", Some(12))));
assert!(edges.contains(&("implements", page, "IDisposable", Some(13))));
assert!(edges.contains(&("implements", page, "IComparable", Some(13))));
assert!(edges.contains(&("inherits", "Web/Orders.vb::Pump", "Machine", Some(34))));
let main = "Web/Orders.vb::Program.Main";
assert!(edges.contains(&("calls", main, "Pump", Some(6))));
assert!(edges.contains(&("calls", main, "Start", Some(7))));
let calls = |source: &str| -> Vec<&str> {
edges
.iter()
.filter(|(kind, s, _, _)| *kind == "calls" && *s == source)
.map(|(_, _, target, _)| *target)
.collect()
};
assert!(calls("Web/Orders.vb::OrdersPage.New").contains(&"Init"));
assert!(calls("Web/Orders.vb::OrdersPage.Page_Load").contains(&"Bind"));
assert!(calls("Web/Orders.vb::Pump.Start").contains(&"Scale"));
}
#[test]
fn the_registry_parses_vb_files() {
let registry = super::super::registry::ParserRegistry::new();
assert!(registry.supports_extension("vb"));
let out = registry
.parse_file(
Path::new("A.vb"),
"Module M\nSub Main()\nEnd Sub\nEnd Module\n",
"r",
"b",
)
.expect("parses")
.expect("VB is supported");
assert!(out.nodes.iter().any(|n| n.qualified_name == "A.vb::M.Main"));
}
}
+16 -1
View File
@@ -96,7 +96,8 @@ pub fn extract_program(root: &Path) -> Option<PlcProgram> {
if !is_st && !is_xml {
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
// UTF-8, UTF-16 with a BOM, or Windows-1252, as PLC tools write them.
let Ok(content) = compliance_core::encoding::read_source(path) else {
continue;
};
let name = path
@@ -334,6 +335,20 @@ mod tests {
assert_eq!(prog2.file_name, "proj.xml");
}
#[test]
fn extract_reads_a_windows_1252_st_program() {
let s = Scratch::new();
// A comment with "Pumpe für" as Windows-1252 writes it: 0xFC for "ü".
std::fs::write(
s.0.join("main.st"),
b"(* Pumpe f\xFCr Halle 2 *)\nPROGRAM Main\nEND_PROGRAM\nCONFIGURATION C\nEND_CONFIGURATION\n",
)
.expect("w");
let prog = extract_program(&s.0).expect("program");
assert_eq!(prog.file_name, "main.st");
assert!(prog.source.contains("Pumpe für"));
}
#[test]
fn extract_returns_none_without_control_logic() {
let s = Scratch::new();