1pub mod composer;
2pub mod dockerfile;
3pub mod endpoints;
4pub mod go_lang;
5pub mod html;
6pub mod java;
7pub mod java_web;
8pub mod javascript;
9pub mod kubernetes;
10pub mod laravel;
11pub mod php;
12pub mod python;
13pub mod resolver;
14pub mod rust_lang;
15pub mod terraform;
16
17use std::path::{Path, PathBuf};
18use std::time::Instant;
19
20use anyhow::Result;
21use rayon::prelude::*;
22
23use verum_nucleus::{
24 matchable_path, panic_guard, FileId, FileInfo, Finding, Framework, Ir, Language, SymbolId,
25};
26
27pub fn stable_hash(s: &str) -> u64 {
33 verum_nucleus::stable_hash(s)
34}
35
36pub(crate) fn strip_comments(source: &str, slash: bool, hash: bool, single_quote: bool) -> String {
47 let chars: Vec<char> = source.chars().collect();
48 let mut out = String::with_capacity(source.len());
49 let mut i = 0;
50 while i < chars.len() {
51 let c = chars[i];
52 if !single_quote && c == '\'' {
56 let lit_end = if i + 1 < chars.len() && chars[i + 1] == '\\' {
57 (i + 2..(i + 12).min(chars.len())).find(|&j| chars[j] == '\'')
58 } else if i + 2 < chars.len() && chars[i + 2] == '\'' && chars[i + 1] != '\'' {
59 Some(i + 2)
60 } else {
61 None
62 };
63 if let Some(end) = lit_end {
64 for ch in &chars[i..=end] {
65 out.push(*ch);
66 }
67 i = end + 1;
68 } else {
69 out.push(c);
70 i += 1;
71 }
72 continue;
73 }
74 if c == '"' || (single_quote && c == '\'') || c == '`' {
75 let quote = c;
76 out.push(c);
77 i += 1;
78 while i < chars.len() {
79 let ch = chars[i];
80 out.push(ch);
81 i += 1;
82 if ch == '\\' && i < chars.len() {
83 out.push(chars[i]);
84 i += 1;
85 } else if ch == quote {
86 break;
87 }
88 }
89 continue;
90 }
91 if slash && c == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
92 while i < chars.len() && chars[i] != '\n' {
93 i += 1;
94 }
95 continue;
96 }
97 if slash && c == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
98 i += 2;
99 while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
100 i += 1;
101 }
102 i = (i + 2).min(chars.len());
103 continue;
104 }
105 if hash && c == '#' {
106 while i < chars.len() && chars[i] != '\n' {
107 i += 1;
108 }
109 continue;
110 }
111 out.push(c);
112 i += 1;
113 }
114 out
115}
116
117pub(crate) mod parser_pool {
124 use std::cell::RefCell;
125
126 use tree_sitter::{Language, Parser, Tree};
127
128 thread_local! {
129 static PARSERS: RefCell<Vec<(&'static str, Parser)>> = const { RefCell::new(Vec::new()) };
132 }
133
134 pub(crate) fn parse(
137 key: &'static str,
138 language: impl FnOnce() -> Language,
139 source: &str,
140 ) -> Option<Tree> {
141 PARSERS.with(|cell| {
142 let mut pool = cell.borrow_mut();
143 if let Some((_, parser)) = pool.iter_mut().find(|(k, _)| *k == key) {
144 return parser.parse(source, None);
145 }
146 let mut parser = Parser::new();
147 parser.set_language(&language()).ok()?;
148 let tree = parser.parse(source, None);
149 pool.push((key, parser));
150 tree
151 })
152 }
153}
154
155#[derive(Debug, Clone)]
157pub struct AtlasConfig {
158 pub root: PathBuf,
159 pub language: Language,
160 pub exclude_patterns: Vec<String>,
161 pub cache_path: Option<PathBuf>,
162 pub delta_mode: bool,
163}
164
165impl Default for AtlasConfig {
166 fn default() -> Self {
167 Self {
168 root: PathBuf::from("."),
169 language: Language::Php,
170 exclude_patterns: Vec::new(),
171 cache_path: None,
172 delta_mode: false,
173 }
174 }
175}
176
177pub struct Atlas {
179 pub config: AtlasConfig,
180}
181
182fn profile_phase(profile: bool, name: &str, since: Instant) -> Instant {
186 if profile {
187 eprintln!(
188 " atlas {:<18} {:>6.2}s",
189 name,
190 since.elapsed().as_secs_f64()
191 );
192 }
193 Instant::now()
194}
195
196impl Atlas {
197 pub fn new(config: AtlasConfig) -> Self {
198 Self { config }
199 }
200
201 pub fn build(&self) -> Result<Ir> {
203 let start = Instant::now();
204 let profile = std::env::var("VERUM_PROFILE").is_ok();
205 let mut mark = Instant::now();
206
207 let (files, infra_files) = self.collect_all();
208 tracing::info!("Collected {} files", files.len());
209 mark = profile_phase(profile, "walk", mark);
210
211 let partial_irs: Vec<Ir> = files
215 .par_iter()
216 .filter_map(|path| match panic_guard::catch(|| self.parse_file(path)) {
217 Some(Ok(ir)) => Some(ir),
218 Some(Err(e)) => {
219 tracing::warn!("Failed to parse {}: {}", path.display(), e);
220 None
221 }
222 None => {
223 tracing::warn!("Parser panicked on {}; file isolated", path.display());
224 Some(parse_failure_ir(path))
225 }
226 })
227 .collect();
228 mark = profile_phase(profile, "parse", mark);
229
230 let mut ir = partial_irs.into_iter().fold(Ir::new(), |mut acc, partial| {
231 acc.merge(partial);
232 acc
233 });
234 mark = profile_phase(profile, "merge", mark);
235
236 if !infra_files.is_empty() {
237 tracing::info!("Collected {} infrastructure files", infra_files.len());
238 let infra_irs: Vec<Ir> = infra_files
239 .par_iter()
240 .filter_map(
241 |path| match panic_guard::catch(|| self.parse_infra_file(path)) {
242 Some(Ok(partial)) => Some(partial),
243 Some(Err(e)) => {
244 tracing::warn!("Failed to parse infra file {}: {}", path.display(), e);
245 None
246 }
247 None => {
248 tracing::warn!(
249 "Parser panicked on infra file {}; file isolated",
250 path.display()
251 );
252 Some(parse_failure_ir(path))
253 }
254 },
255 )
256 .collect();
257 for partial in infra_irs {
258 ir.merge(partial);
259 }
260 }
261
262 let framework = composer::detect_framework(&self.config.root);
263 ir.framework = framework;
264
265 if ir.framework == Framework::Laravel {
268 laravel::extract_routes(&self.config.root, &mut ir);
269 }
270 mark = profile_phase(profile, "infra+framework", mark);
271
272 resolver::resolve(&mut ir);
273 mark = profile_phase(profile, "resolve", mark);
274
275 java_web::extract_routes(&mut ir);
276
277 endpoints::promote_wrapper_calls(&mut ir);
280
281 endpoints::link(&mut ir);
284
285 detect_entry_points(&mut ir);
286 profile_phase(profile, "link+entrypoints", mark);
287
288 let elapsed = start.elapsed();
289 ir.metadata.build_time_ms = elapsed.as_millis() as u64;
290 ir.metadata.total_symbols = ir.symbols.len();
291 ir.metadata.language = self.config.language.clone();
292 ir.metadata.verum_version = env!("CARGO_PKG_VERSION").to_string();
293
294 Ok(ir)
295 }
296
297 fn collect_all(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
308 let mut files = Vec::new();
309 let mut infra_files = Vec::new();
310
311 let walker = ignore::WalkBuilder::new(&self.config.root)
312 .follow_links(false)
313 .hidden(false)
316 .git_ignore(true)
317 .git_exclude(true)
318 .git_global(false)
320 .parents(false)
321 .ignore(false)
323 .require_git(true)
324 .filter_entry(|e| e.file_name() != ".git")
325 .build();
326
327 for entry in walker.filter_map(|e| e.ok()) {
328 let path = entry.path();
329
330 if !path.is_file() {
331 continue;
332 }
333
334 let path_str = matchable_path(path);
335 if path_str.contains("vendor/") || path_str.contains("node_modules/") {
336 continue;
337 }
338 if is_build_output(&path_str) {
339 continue;
340 }
341
342 let excluded = self
343 .config
344 .exclude_patterns
345 .iter()
346 .any(|pat| path_str.contains(pat.as_str()));
347 if excluded {
348 continue;
349 }
350
351 if entry
356 .metadata()
357 .map(|m| m.len() > MAX_SOURCE_FILE_BYTES)
358 .unwrap_or(false)
359 {
360 continue;
361 }
362
363 let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
364 if file_name == "Dockerfile"
365 || file_name.ends_with(".dockerfile")
366 || file_name.starts_with("Dockerfile.")
367 {
368 infra_files.push(path.to_path_buf());
369 continue;
370 }
371
372 let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
373 continue;
374 };
375
376 match ext {
377 "yaml" | "yml" => {
378 if let Ok(content) = std::fs::read_to_string(path) {
380 if content.contains("apiVersion:") && content.contains("kind:") {
381 infra_files.push(path.to_path_buf());
382 }
383 }
384 continue;
385 }
386 "tf" => {
387 infra_files.push(path.to_path_buf());
388 continue;
389 }
390 _ => {}
391 }
392
393 if language_for_extension(ext).is_none() {
394 continue;
395 }
396
397 if is_blade_template(path) {
401 continue;
402 }
403
404 if is_minified_or_generated(path) {
408 continue;
409 }
410
411 if looks_binary(path) {
414 continue;
415 }
416
417 files.push(path.to_path_buf());
418 }
419
420 files.sort();
421 infra_files.sort();
422 (files, infra_files)
423 }
424
425 fn parse_infra_file(&self, path: &Path) -> Result<Ir> {
426 let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
427
428 if file_name == "Dockerfile"
429 || file_name.ends_with(".dockerfile")
430 || file_name.starts_with("Dockerfile.")
431 {
432 return dockerfile::parse_file(path);
433 }
434
435 if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
436 match ext {
437 "yaml" | "yml" => return kubernetes::parse_file(path),
438 "tf" => return terraform::parse_file(path),
439 _ => {}
440 }
441 }
442
443 anyhow::bail!("Unknown infrastructure file type: {}", path.display())
444 }
445
446 fn parse_file(&self, path: &Path) -> Result<Ir> {
448 #[cfg(test)]
453 if path.file_name().and_then(|n| n.to_str()) == Some("__verum_panic_hook__.rs") {
454 panic!("deliberate test-only parse panic");
455 }
456
457 let ext = path.extension().and_then(|e| e.to_str());
458
459 if matches!(ext, Some("html") | Some("htm")) {
462 return html::parse_file(path);
463 }
464
465 let lang = ext
466 .and_then(language_for_extension)
467 .unwrap_or_else(|| self.config.language.clone());
468
469 match &lang {
470 Language::Php => php::parse_file(path),
471 Language::Python => python::parse_file(path),
472 Language::Rust => rust_lang::parse_file(path),
473 Language::Go => go_lang::parse_file(path),
474 Language::Java => java::parse_file(path),
475 Language::JavaScript => javascript::parse_file(path, false),
476 Language::TypeScript => javascript::parse_file(path, true),
477 _ => {
478 let mut ir = Ir::new();
480 let source = std::fs::read_to_string(path)?;
481 let line_count = source.lines().count() as u32;
482 let size_bytes = std::fs::metadata(path)?.len();
483
484 let file_id = FileId(crate::stable_hash(path.to_string_lossy().as_ref()));
485 ir.files.insert(
486 path.to_path_buf(),
487 FileInfo {
488 id: file_id,
489 path: path.to_path_buf(),
490 language: lang,
491 line_count,
492 size_bytes,
493 last_modified: 0,
494 hash: 0,
495 symbols: Vec::new(),
496 },
497 );
498 ir.metadata.total_files += 1;
499 ir.metadata.total_lines += line_count as u64;
500
501 Ok(ir)
502 }
503 }
504 }
505}
506
507const MAX_SOURCE_FILE_BYTES: u64 = 5 * 1024 * 1024;
511
512pub(crate) const MAX_RECURSION_DEPTH: usize = 512;
529
530fn parse_failure_ir(path: &Path) -> Ir {
537 let mut ir = Ir::new();
538 ir.parse_failures
539 .push(Finding::parse_failure(path, "parser panicked on this file"));
540 ir
541}
542
543fn looks_binary(path: &Path) -> bool {
547 use std::io::Read;
548 let Ok(file) = std::fs::File::open(path) else {
549 return false;
550 };
551 let mut buf = [0u8; 8192];
552 let mut head = file.take(buf.len() as u64);
553 let Ok(n) = head.read(&mut buf) else {
554 return false;
555 };
556 buf[..n].contains(&0)
557}
558
559fn is_blade_template(path: &Path) -> bool {
564 path.file_name()
565 .and_then(|n| n.to_str())
566 .map(|n| n.ends_with(".blade.php"))
567 .unwrap_or(false)
568}
569
570fn is_minified_or_generated(path: &Path) -> bool {
577 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
578 if name.ends_with(".min.js") || name.ends_with(".min.css") {
579 return true;
580 }
581 }
582
583 let is_scannable = path
585 .extension()
586 .and_then(|e| e.to_str())
587 .map(|e| matches!(e, "js" | "jsx" | "ts" | "tsx" | "css"))
588 .unwrap_or(false);
589 if !is_scannable {
590 return false;
591 }
592
593 if let Ok(file) = std::fs::File::open(path) {
595 use std::io::Read;
596 let mut buf = vec![0u8; 64 * 1024];
597 if let Ok(n) = file.take(64 * 1024).read(&mut buf[..]) {
598 let sample = String::from_utf8_lossy(&buf[..n]);
599 let longest_line = sample.lines().map(|l| l.len()).max().unwrap_or(0);
600 if longest_line > 5000 {
601 return true;
602 }
603 }
604 }
605
606 false
607}
608
609fn is_build_output(path_str: &str) -> bool {
613 const DIRS: &[&str] = &[
614 "/build/",
615 "/dist/",
616 "/.svelte-kit/",
617 "/.next/",
618 "/.nuxt/",
619 "/.output/",
620 "/out/",
621 "/coverage/",
622 "/.turbo/",
623 ];
624 DIRS.iter().any(|d| path_str.contains(d))
625}
626
627fn language_for_extension(ext: &str) -> Option<Language> {
628 match ext {
629 "php" => Some(Language::Php),
630 "rs" => Some(Language::Rust),
631 "js" | "jsx" => Some(Language::JavaScript),
632 "ts" | "tsx" => Some(Language::TypeScript),
633 "py" => Some(Language::Python),
634 "go" => Some(Language::Go),
635 "java" => Some(Language::Java),
636 "html" | "htm" => Some(Language::JavaScript),
637 _ => None,
638 }
639}
640
641fn detect_entry_points(ir: &mut Ir) {
644 let mut entry_point_ids: Vec<SymbolId> = Vec::new();
645
646 for route in &ir.routes {
648 if let Some(controller_id) = &route.controller {
649 entry_point_ids.push(*controller_id);
650 }
651 }
652
653 let is_laravel = ir.framework == Framework::Laravel;
654
655 for (id, sym) in &ir.symbols {
656 let path_str = matchable_path(&sym.file);
657
658 if path_str.contains("Controller")
659 && matches!(
660 sym.kind,
661 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
662 )
663 {
664 entry_point_ids.push(*id);
665 continue;
666 }
667
668 if is_laravel {
669 if path_str.contains("/Providers/")
670 && matches!(
671 sym.kind,
672 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
673 )
674 {
675 entry_point_ids.push(*id);
676 continue;
677 }
678 if path_str.contains("/Middleware/")
679 && matches!(
680 sym.kind,
681 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
682 )
683 {
684 entry_point_ids.push(*id);
685 continue;
686 }
687 if path_str.contains("/Console/")
688 && matches!(
689 sym.kind,
690 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
691 )
692 {
693 entry_point_ids.push(*id);
694 continue;
695 }
696 if (path_str.contains("/Listeners/") || path_str.contains("/Events/"))
697 && matches!(
698 sym.kind,
699 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
700 )
701 {
702 entry_point_ids.push(*id);
703 continue;
704 }
705 if path_str.contains("/Jobs/")
706 && matches!(
707 sym.kind,
708 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
709 )
710 {
711 entry_point_ids.push(*id);
712 continue;
713 }
714 if path_str.contains("/Notifications/")
715 && matches!(
716 sym.kind,
717 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
718 )
719 {
720 entry_point_ids.push(*id);
721 continue;
722 }
723 if path_str.contains("/Models/")
725 && matches!(
726 sym.kind,
727 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
728 )
729 {
730 entry_point_ids.push(*id);
731 continue;
732 }
733 if path_str.contains("/Transformers/")
735 && matches!(
736 sym.kind,
737 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
738 )
739 {
740 entry_point_ids.push(*id);
741 continue;
742 }
743 if path_str.contains("/Observers/")
744 && matches!(
745 sym.kind,
746 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
747 )
748 {
749 entry_point_ids.push(*id);
750 continue;
751 }
752 if path_str.contains("/Policies/")
753 && matches!(
754 sym.kind,
755 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
756 )
757 {
758 entry_point_ids.push(*id);
759 continue;
760 }
761 if path_str.contains("/Rules/")
762 && matches!(
763 sym.kind,
764 verum_nucleus::SymbolKind::Class | verum_nucleus::SymbolKind::Method
765 )
766 {
767 entry_point_ids.push(*id);
768 continue;
769 }
770 }
771
772 if matches!(
774 sym.language,
775 verum_nucleus::Language::TypeScript | verum_nucleus::Language::JavaScript
776 ) && matches!(sym.visibility, verum_nucleus::Visibility::Public)
777 && (path_str.contains("/routers/") || path_str.contains("/pages/"))
778 {
779 entry_point_ids.push(*id);
780 }
781 }
782
783 for id in &entry_point_ids {
784 if let Some(sym) = ir.symbols.get_mut(id) {
785 sym.is_entry_point = true;
786 }
787 }
788
789 ir.entry_points.extend(entry_point_ids);
790}
791
792#[cfg(test)]
793mod panic_isolation_tests {
794 use super::*;
795
796 struct ScratchTree(PathBuf);
799
800 impl ScratchTree {
801 fn new(tag: &str) -> Self {
802 let dir = std::env::temp_dir().join(format!(
803 "verum_mappa_{}_{}_{}",
804 tag,
805 std::process::id(),
806 std::thread::current()
807 .name()
808 .unwrap_or("t")
809 .replace("::", "_"),
810 ));
811 let _ = std::fs::remove_dir_all(&dir);
812 std::fs::create_dir_all(&dir).expect("create scratch dir");
813 Self(dir)
814 }
815 }
816
817 impl Drop for ScratchTree {
818 fn drop(&mut self) {
819 let _ = std::fs::remove_dir_all(&self.0);
820 }
821 }
822
823 #[test]
824 fn a_panicking_parse_is_isolated_and_reported() {
825 let tree = ScratchTree::new("panic_hook");
826 std::fs::write(tree.0.join("__verum_panic_hook__.rs"), "fn broken() {}\n")
829 .expect("write hook file");
830 std::fs::write(
831 tree.0.join("healthy.rs"),
832 "pub fn fine() { helper(); }\nfn helper() {}\n",
833 )
834 .expect("write healthy file");
835
836 let ir = Atlas::new(AtlasConfig {
837 root: tree.0.clone(),
838 language: Language::Rust,
839 ..Default::default()
840 })
841 .build()
842 .expect("the run must complete despite the panicking file");
843
844 assert_eq!(
845 ir.parse_failures.len(),
846 1,
847 "exactly the hook file is isolated"
848 );
849 let failure = &ir.parse_failures[0];
850 assert_eq!(failure.kind, verum_nucleus::FindingKind::ParseFailure);
851 assert_eq!(failure.severity, verum_nucleus::Severity::Low);
852 assert!(
853 failure
854 .message
855 .starts_with("parser panicked on this file: "),
856 "fixed phrase, never the panic payload: {}",
857 failure.message
858 );
859 assert!(failure.message.ends_with("__verum_panic_hook__.rs"));
860 assert!(
861 !failure.message.contains("deliberate test-only"),
862 "the panic payload must not leak into the finding"
863 );
864 assert!(
866 ir.symbols.values().any(|s| s.name == "fine"),
867 "the rest of the tree still maps"
868 );
869 }
870
871 #[test]
872 fn a_clean_tree_reports_no_parse_failures() {
873 let tree = ScratchTree::new("clean");
874 std::fs::write(tree.0.join("lib.rs"), "pub fn ok() {}\n").expect("write file");
875
876 let ir = Atlas::new(AtlasConfig {
877 root: tree.0.clone(),
878 language: Language::Rust,
879 ..Default::default()
880 })
881 .build()
882 .expect("clean tree builds");
883
884 assert!(ir.parse_failures.is_empty());
885 }
886}