Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion benches/scan_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
//!
//! Measures: language detection, pattern matching, full analysis pipeline.

use criterion::{black_box, criterion_group, criterion_main, Criterion};
use criterion::{criterion_group, criterion_main, Criterion};
use panic_attack::types::Language;
use std::hint::black_box;

/// Benchmark language detection from file extension
fn bench_language_detect(c: &mut Criterion) {
Expand Down Expand Up @@ -223,6 +224,7 @@ fn bench_statistics_calculation(c: &mut Criterion) {
unsafe_blocks: 5,
panic_sites: 0,
unwrap_calls: 50,
safe_unwrap_calls: 0,
allocation_sites: 12,
io_operations: 4,
threading_constructs: 3,
Expand Down
15 changes: 7 additions & 8 deletions src/assail/analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3966,7 +3966,7 @@ impl Analyzer {

// Detect function definitions
if line.trim().starts_with("fn ") && !line.trim().starts_with("fn test") {
if let Some(func_name) = line.trim().split_whitespace().nth(1) {
if let Some(func_name) = line.split_whitespace().nth(1) {
let func_name = func_name.split('(').next().unwrap_or(func_name);
current_function = func_name.to_string();
function_calls
Expand Down Expand Up @@ -5174,12 +5174,11 @@ impl Analyzer {
}
}

Language::Erlang => {
if content.contains("-behaviour(gen_server)")
|| content.contains("-behaviour(supervisor)")
{
frameworks.insert(Framework::OTP);
}
Language::Erlang
if (content.contains("-behaviour(gen_server)")
|| content.contains("-behaviour(supervisor)")) =>
{
frameworks.insert(Framework::OTP);
}

Language::Go => {
Expand Down Expand Up @@ -6007,7 +6006,7 @@ func main() {
&& wp
.location
.as_deref()
.map_or(false, |loc| loc.contains("node_modules"))
.is_some_and(|loc| loc.contains("node_modules"))
})
.collect();

Expand Down
2 changes: 1 addition & 1 deletion src/assemblyline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ pub fn run_with_cache(
.count();

// Sort by weak point count descending (riskiest repos first)
results.sort_by(|a, b| b.weak_point_count.cmp(&a.weak_point_count));
results.sort_by_key(|r| std::cmp::Reverse(r.weak_point_count));

// Apply filters
if config.findings_only {
Expand Down
8 changes: 5 additions & 3 deletions src/bridge/lockfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ use std::path::Path;
/// order. All successful parses are merged into a single list. Errors from
/// individual parsers are logged as warnings and skipped so one malformed
/// lockfile does not abort triage of the whole project.
type LockfileParser = fn(&Path) -> Result<Vec<LockedDependency>>;

pub fn discover_and_parse(dir: &Path) -> Vec<LockedDependency> {
let mut all = Vec::new();

let candidates: &[(&str, fn(&Path) -> Result<Vec<LockedDependency>>)] = &[
let candidates: &[(&str, LockfileParser)] = &[
("Cargo.lock", parse_cargo_lock),
("mix.lock", parse_mix_lock),
("package-lock.json", parse_package_lock_json),
Expand Down Expand Up @@ -66,7 +68,7 @@ pub fn parse_cargo_lock(path: &Path) -> Result<Vec<LockedDependency>> {
if let (Some(name), Some(version)) = (current_name.take(), current_version.take()) {
if current_source
.as_ref()
.map_or(false, |s| s.contains("registry"))
.is_some_and(|s| s.contains("registry"))
{
deps.push(LockedDependency {
name,
Expand Down Expand Up @@ -94,7 +96,7 @@ pub fn parse_cargo_lock(path: &Path) -> Result<Vec<LockedDependency>> {
if let (Some(name), Some(version)) = (current_name, current_version) {
if current_source
.as_ref()
.map_or(false, |s| s.contains("registry"))
.is_some_and(|s| s.contains("registry"))
{
deps.push(LockedDependency {
name,
Expand Down
2 changes: 1 addition & 1 deletion src/bridge/reachability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub fn check_reachability(project_dir: &Path, crate_name: &str) -> Result<Reacha
}

let path = entry.path();
if path.extension().map_or(true, |ext| ext != "rs") {
if path.extension().is_none_or(|ext| ext != "rs") {
continue;
}

Expand Down
6 changes: 6 additions & 0 deletions src/bridge/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ pub struct MitigationRegistry {
pub entries: Vec<MitigationEntry>,
}

impl Default for MitigationRegistry {
fn default() -> Self {
Self::new()
}
}

impl MitigationRegistry {
/// Create an empty registry.
pub fn new() -> Self {
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2250,8 +2250,8 @@ fn run_main() -> Result<()> {
println!("Run `panic-attack bridge triage --register` to populate.");
} else {
println!(
"{:<12} {:<20} {:<15} {:<15} {}",
"ID", "ADVISORY", "PACKAGE", "STATUS", "ACTION"
"{:<12} {:<20} {:<15} {:<15} ACTION",
"ID", "ADVISORY", "PACKAGE", "STATUS"
);
println!("{}", "-".repeat(80));
for entry in &registry.entries {
Expand Down
2 changes: 1 addition & 1 deletion src/mass_panic/imaging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ pub fn build_image(report: &AssemblylineReport) -> SystemImage {
.into_iter()
.map(|(name, count)| CategoryCount { name, count })
.collect();
cats.sort_by(|a, b| b.count.cmp(&a.count));
cats.sort_by_key(|c| std::cmp::Reverse(c.count));
cats
} else {
Vec::new()
Expand Down
14 changes: 7 additions & 7 deletions src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ pub fn push_hexad_http(hexad: &PanicAttackHexad, gateway_url: &str) -> Result<St
let status = response.status().as_u16();
let body = read_body(response);

if status >= 200 && status < 300 {
if (200..300).contains(&status) {
Ok(body)
} else {
Err(anyhow!("VeriSimDB returned {}: {}", status, body))
Expand Down Expand Up @@ -580,16 +580,16 @@ pub fn push_hexad_http_with_retry(hexad: &PanicAttackHexad, gateway_url: &str) -
std::time::Duration::from_secs(2),
std::time::Duration::from_secs(4),
];
let max_attempts: usize = 3;
let max_attempts = delays.len();
let mut last_err: Option<anyhow::Error> = None;

for attempt in 0..max_attempts {
for (attempt, delay) in delays.iter().enumerate() {
match push_hexad_http(hexad, gateway_url) {
Ok(body) => return Ok(body),
Err(e) => {
last_err = Some(e);
if attempt < max_attempts - 1 {
std::thread::sleep(delays[attempt]);
std::thread::sleep(*delay);
}
}
}
Expand Down Expand Up @@ -632,7 +632,7 @@ pub fn push_hexads_batch(hexads: &[PanicAttackHexad], gateway_url: &str) -> Resu
results.push(body);
}
Ok(results)
} else if status >= 200 && status < 300 {
} else if (200..300).contains(&status) {
Ok(vec![read_body(response)])
} else {
let body = read_body(response);
Expand Down Expand Up @@ -669,7 +669,7 @@ pub fn query_hexads(gateway_url: &str, limit: usize) -> Result<Vec<PanicAttackHe
let status = response.status().as_u16();
let body = read_body(response);

if status >= 200 && status < 300 {
if (200..300).contains(&status) {
let hexads: Vec<PanicAttackHexad> = serde_json::from_str(&body)
.map_err(|e| anyhow!("Failed to parse VeriSimDB response: {}", e))?;
Ok(hexads)
Expand Down Expand Up @@ -708,7 +708,7 @@ pub fn check_gateway(gateway_url: &str) -> bool {
let is_healthy = match builder.call() {
Ok(resp) => {
let s = resp.status().as_u16();
s >= 200 && s < 300
(200..300).contains(&s)
}
Err(_) => false,
};
Expand Down
2 changes: 1 addition & 1 deletion tests/aspect_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ fn aspect_parallel_analysis_correctness() {
.collect();

// Using rayon parallel iterator (same as assemblyline)
let _results: Vec<_> = files.par_iter().map(|path| assail::analyze(path)).collect();
let _results: Vec<_> = files.par_iter().map(assail::analyze).collect();

// Should complete without data races or panics
// (In practice, rayon + Rust's type system ensure this)
Expand Down
3 changes: 2 additions & 1 deletion tests/panll_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ fn test_panll_export_constraints_from_failed_attacks() -> Result<(), Box<dyn std
duration: Duration::from_millis(100),
peak_memory: 0,
crashes: vec![CrashReport {
schema_version: "2.5".to_string(),
timestamp: "2026-03-01T00:00:00Z".to_string(),
signal: Some("SIGSEGV".to_string()),
backtrace: None,
Expand All @@ -245,7 +246,7 @@ fn test_panll_export_constraints_from_failed_attacks() -> Result<(), Box<dyn std
assert!(
constraints.iter().any(|c| c["id"]
.as_str()
.map_or(false, |id| id.starts_with("attack-fail-"))),
.is_some_and(|id| id.starts_with("attack-fail-"))),
"failed attack should generate a constraint"
);
Ok(())
Expand Down
9 changes: 5 additions & 4 deletions tests/property_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ fn prop_kanren_self_unification() {
let subst = Substitution::new();

// If unification works correctly, these atoms should unify
if let Some(_) = subst.unify(&term1, &term2) {
if subst.unify(&term1, &term2).is_some() {
// Success: atoms unify correctly
assert_eq!(term1, term2);
}
Expand Down Expand Up @@ -257,7 +257,7 @@ fn prop_report_statistics_consistency() {
/// Property: Weak point list should not contain duplicates by location
#[test]
fn prop_no_duplicate_weak_points_at_same_location() {
let points = vec![
let points = [
WeakPoint {
category: WeakPointCategory::UnsafeCode,
severity: Severity::High,
Expand Down Expand Up @@ -321,6 +321,7 @@ fn prop_long_file_names() {
#[test]
fn prop_unicode_content_handling() {
let unicode_content = "fn test() { // 你好世界 🦀 }\n";
// Should not panic on unicode
assert!(unicode_content.len() > 0);
// Should not panic when iterating chars across multi-byte boundaries.
let char_count = unicode_content.chars().count();
assert!(char_count > 0);
}
1 change: 1 addition & 0 deletions tests/report_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ fn make_assail_report() -> AssailReport {
fn make_attack_result(axis: AttackAxis, success: bool, crashes: usize) -> AttackResult {
let crash_reports: Vec<CrashReport> = (0..crashes)
.map(|_| CrashReport {
schema_version: "2.5".to_string(),
timestamp: "2026-03-01T00:00:00Z".to_string(),
signal: Some("SIGSEGV".to_string()),
backtrace: None,
Expand Down
12 changes: 5 additions & 7 deletions tests/seam_contract_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
//! - **Schema version sentinel** (all consumers):
//! reads `schema_version` to detect incompatible changes

use panic_attack::abduct::{self, AbductReport};
use panic_attack::amuck::{self, AmuckReport};
use panic_attack::axial::{self, AxialReport};
use panic_attack::abduct::AbductReport;
use panic_attack::amuck::AmuckReport;
use panic_attack::axial::AxialReport;
use panic_attack::types::*;
use serde_json::Value;

Expand Down Expand Up @@ -433,8 +433,7 @@ fn old_amuck_report_without_schema_version_deserializes_with_default() {
"combinations_run": 0,
"outcomes": []
}"#;
let report: AmuckReport =
serde_json::from_str(json_str).expect("deserialize old amuck report");
let report: AmuckReport = serde_json::from_str(json_str).expect("deserialize old amuck report");
assert_eq!(
report.schema_version, "2.5",
"old AmuckReport missing schema_version must default to '2.5'"
Expand Down Expand Up @@ -490,8 +489,7 @@ fn old_axial_report_without_schema_version_deserializes_with_default() {
"observed_reports": 0,
"language": "en"
}"#;
let report: AxialReport =
serde_json::from_str(json_str).expect("deserialize old axial report");
let report: AxialReport = serde_json::from_str(json_str).expect("deserialize old axial report");
assert_eq!(
report.schema_version, "2.5",
"old AxialReport missing schema_version must default to '2.5'"
Expand Down
Loading