Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29d3c91f5a | ||
|
|
5a11a3b602 |
No files matched your search
Generated
+14
-2
@@ -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"
|
||||
|
||||
@@ -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] = &[
|
||||
|
||||
@@ -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.")
|
||||
|
||||
@@ -17,13 +17,15 @@ thiserror = { 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"
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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, ®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 `<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,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;
|
||||
@@ -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();
|
||||
@@ -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;
|
||||
@@ -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();
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user