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
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>
This commit was merged in pull request #943.
This commit is contained in:
1 parent
ca66b9a7b1
commit
5a11a3b602
8 files changed
+632
-7
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",
|
||||
|
||||
@@ -6,5 +6,6 @@ pub mod python;
|
||||
pub mod registry;
|
||||
pub mod rust_parser;
|
||||
pub mod typescript;
|
||||
pub mod vb;
|
||||
|
||||
pub use common::FileGraph;
|
||||
@@ -11,6 +11,7 @@ use super::javascript::JavaScriptParser;
|
||||
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 +39,7 @@ impl ParserRegistry {
|
||||
Box::new(TypeScriptParser::new()),
|
||||
Box::new(CParser::new()),
|
||||
Box::new(CSharpParser::new()),
|
||||
Box::new(VbParser::new()),
|
||||
];
|
||||
|
||||
let mut extension_map = HashMap::new();
|
||||
@@ -175,6 +177,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 +377,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