1use std::collections::HashMap;
2use std::fs::{self, read_to_string};
3use std::path::{Path, PathBuf};
4
5use ast_grep_config::{
6 CombinedScan, GlobalRules, RuleCollection, RuleConfig, RuleConfigError, SerializableRuleConfig,
7};
8use ast_grep_core::tree_sitter::LanguageExt;
9use ast_grep_core::Language as AstLanguage;
10use ast_grep_language::SupportLang;
11use globset::{Error as GlobError, Glob, GlobSet, GlobSetBuilder};
12use ignore::WalkBuilder;
13use rayon::prelude::*;
14use serde::Serialize;
15use serde_yaml::with::singleton_map_recursive;
16use serde_yaml::{to_value, Value};
17use strum::IntoEnumIterator;
18use thiserror::Error;
19
20use crate::cache::{file_content_hash, rules_hash, CacheStore};
21use crate::config::Config;
22use crate::disable::filter_disabled;
23use crate::finding::{CacheStats, Finding, ScanResult, ScanStats};
24use crate::rule::{Language, Rule, RuleId, Severity};
25use crate::test_filter::CfgTestRanges;
26
27#[derive(Debug, Error)]
28pub enum ScanError {
29 #[error("failed to compile rule '{id}': {source}")]
30 RuleCompile {
31 id: RuleId,
32 #[source]
33 source: RuleConfigError,
34 },
35
36 #[error("invalid glob pattern: {0}")]
37 Glob(#[from] GlobError),
38}
39
40#[derive(Serialize)]
43pub struct AstGrepRule<'a> {
44 pub id: &'a str,
45 pub language: SupportLang,
46 pub severity: &'a Severity,
47 pub message: &'a str,
48 #[serde(skip_serializing_if = "Option::is_none")]
49 pub note: Option<&'a str>,
50 pub rule: &'a Value,
51 #[serde(skip_serializing_if = "Option::is_none")]
52 pub files: Option<&'a [String]>,
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub ignores: Option<&'a [String]>,
55}
56
57struct CompiledRules<'a> {
60 collection: RuleCollection<SupportLang>,
61 by_id: HashMap<(&'a str, Language), &'a Rule>,
62}
63
64fn extension_to_lang(path: &Path) -> Option<SupportLang> {
65 SupportLang::from_path(path)
66 .filter(|lang| Language::iter().any(|l| l.ast_grep_langs().contains(lang)))
67}
68
69fn support_lang_to_language(lang: SupportLang) -> Language {
70 match lang {
71 SupportLang::Rust => Language::Rust,
72 _ => Language::TypeScript,
73 }
74}
75
76pub(crate) fn compile_ast_grep_rule(
77 rule: &AstGrepRule,
78) -> Result<RuleConfig<SupportLang>, RuleConfigError> {
79 let inner: SerializableRuleConfig<SupportLang> = to_value(rule)
80 .and_then(singleton_map_recursive::deserialize)
81 .map_err(RuleConfigError::from)?;
82 RuleConfig::try_from(inner, &GlobalRules::default())
83}
84
85fn compile_rule(rule: &Rule, lang: SupportLang) -> Result<RuleConfig<SupportLang>, ScanError> {
86 let ast_grep_rule = AstGrepRule {
87 id: rule.id.as_str(),
88 language: lang,
89 severity: &rule.severity,
90 message: &rule.message,
91 note: rule.note.as_deref(),
92 rule: &rule.rule,
93 files: rule.files.as_deref(),
94 ignores: rule.ignores.as_deref(),
95 };
96 compile_ast_grep_rule(&ast_grep_rule).map_err(|source| ScanError::RuleCompile {
97 id: rule.id.clone(),
98 source,
99 })
100}
101
102fn compile_rules(rules: &[Rule]) -> Result<CompiledRules<'_>, ScanError> {
103 let configs = rules
104 .iter()
105 .flat_map(|rule| {
106 rule.language
107 .ast_grep_langs()
108 .iter()
109 .map(move |lang| compile_rule(rule, *lang))
110 })
111 .collect::<Result<Vec<_>, _>>()?;
112 Ok(CompiledRules {
113 collection: RuleCollection::try_new(configs)?,
114 by_id: rules
115 .iter()
116 .map(|rule| ((rule.id.as_str(), rule.language.clone()), rule))
117 .collect::<HashMap<_, _>>(),
118 })
119}
120
121fn build_glob_set(patterns: &[String]) -> Result<GlobSet, GlobError> {
122 let mut builder = GlobSetBuilder::new();
123 for pattern in patterns {
124 builder.add(Glob::new(pattern)?);
125 }
126 builder.build()
127}
128
129fn scan_file(path: &Path, lang: SupportLang, rules: &CompiledRules) -> Vec<Finding> {
130 let applicable = rules.collection.get_rule_from_lang(path, lang);
131 if applicable.is_empty() {
132 return Vec::new();
133 }
134 let Ok(source) = read_to_string(path) else {
135 return Vec::new();
136 };
137
138 let root = lang.ast_grep(&source);
139 let combined = CombinedScan::new(applicable);
140 let result = combined.scan(&root, false);
141
142 let cfg_test = (lang == SupportLang::Rust && !result.matches.is_empty())
143 .then(|| CfgTestRanges::from_root(&root));
144 let cfg_test = cfg_test.as_ref();
145
146 let findings = result
147 .matches
148 .into_iter()
149 .filter_map(|(config, matches)| {
150 let rule_lang = support_lang_to_language(lang);
151 let rule = rules.by_id.get(&(config.id.as_str(), rule_lang))?;
152 Some((*rule, matches))
153 })
154 .flat_map(|(rule, matches)| {
155 let skip_test_code = rule.skip_test_code;
156 matches
157 .into_iter()
158 .map(move |node_match| {
159 let start = node_match.start_pos();
160 let end = node_match.end_pos();
161 Finding {
162 rule_id: rule.id.clone(),
163 severity: rule.severity.clone(),
164 category: rule.category.clone().unwrap_or_default(),
165 message: rule.message.clone(),
166 note: rule.note.clone(),
167 fix: rule.fix.clone(),
168 file: path.to_path_buf(),
169 line: start.line() + 1,
170 column: start.byte_point().1 + 1,
171 end_line: end.line() + 1,
172 end_column: end.byte_point().1 + 1,
173 matched_text: node_match.text().to_string(),
174 }
175 })
176 .filter(move |f| {
177 !(skip_test_code && cfg_test.is_some_and(|r| r.contains_line(f.line)))
178 })
179 })
180 .collect();
181
182 filter_disabled(findings, &source)
183}
184
185pub fn scan(paths: &[PathBuf], rules: &[Rule], config: &Config) -> Result<ScanResult, ScanError> {
187 let compiled = compile_rules(rules)?;
188 let ignores = build_glob_set(&config.scan.ignores)?;
189
190 let files: Vec<(PathBuf, SupportLang)> = paths
191 .iter()
192 .flat_map(|path| WalkBuilder::new(path).build().flatten())
193 .filter(|entry| entry.file_type().is_some_and(|t| t.is_file()))
194 .map(|entry| entry.into_path())
195 .filter(|path| !ignores.is_match(path))
196 .filter_map(|path| extension_to_lang(&path).map(|lang| (path, lang)))
197 .collect();
198
199 let mut findings: Vec<Finding> = files
200 .par_iter()
201 .flat_map_iter(|(path, lang)| scan_file(path, *lang, &compiled))
202 .collect();
203 findings.sort_by(|a, b| (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column)));
204 findings.dedup_by(|a, b| {
205 a.rule_id == b.rule_id && a.file == b.file && a.line == b.line && a.column == b.column
206 });
207
208 let (errors, warnings) =
209 findings
210 .iter()
211 .fold((0, 0), |(errors, warnings), f| match f.severity {
212 Severity::Error => (errors + 1, warnings),
213 Severity::Warning => (errors, warnings + 1),
214 });
215
216 Ok(ScanResult {
217 findings,
218 stats: ScanStats {
219 errors,
220 warnings,
221 total: errors + warnings,
222 files_scanned: files.len(),
223 },
224 cache_stats: None,
225 })
226}
227
228pub fn scan_cached(
232 paths: &[PathBuf],
233 rules: &[Rule],
234 config: &Config,
235 cache_root: &Path,
236) -> Result<ScanResult, ScanError> {
237 let compiled = compile_rules(rules)?;
238 let ignores = build_glob_set(&config.scan.ignores)?;
239
240 let files: Vec<(PathBuf, SupportLang)> = paths
241 .iter()
242 .flat_map(|path| WalkBuilder::new(path).build().flatten())
243 .filter(|entry| entry.file_type().is_some_and(|t| t.is_file()))
244 .map(|entry| entry.into_path())
245 .filter(|path| !ignores.is_match(path))
246 .filter_map(|path| extension_to_lang(&path).map(|lang| (path, lang)))
247 .collect();
248
249 let store = CacheStore::new(cache_root);
250 let current_rules_hash = rules_hash(rules);
251 let rules_changed = store
252 .check_rules_changed(¤t_rules_hash)
253 .unwrap_or(true);
254
255 let file_contents: Vec<(PathBuf, SupportLang, Vec<u8>, String)> = files
256 .into_iter()
257 .filter_map(|(path, lang)| {
258 let content = fs::read(&path).ok()?;
259 let hash = file_content_hash(&content);
260 Some((path, lang, content, hash))
261 })
262 .collect();
263
264 let mut cached_count = 0usize;
265 let mut changed_count = 0usize;
266 let mut all_findings: Vec<Finding> = Vec::new();
267
268 struct FileWork {
269 path: PathBuf,
270 lang: SupportLang,
271 hash: String,
272 }
273
274 let mut to_scan: Vec<FileWork> = Vec::new();
275
276 for (path, lang, _content, hash) in file_contents.iter() {
277 if !rules_changed {
278 if let Some(cached_findings) = store.get(hash) {
279 cached_count += 1;
280 all_findings.extend(cached_findings);
281 continue;
282 }
283 }
284 changed_count += 1;
285 to_scan.push(FileWork {
286 path: path.clone(),
287 lang: *lang,
288 hash: hash.clone(),
289 });
290 }
291
292 let scanned_findings: Vec<(String, Vec<Finding>)> = to_scan
293 .par_iter()
294 .map(|work| {
295 let findings = scan_file(&work.path, work.lang, &compiled);
296 (work.hash.clone(), findings)
297 })
298 .collect();
299
300 for (hash, findings) in scanned_findings {
301 store.put(&hash, &findings).ok();
302 all_findings.extend(findings);
303 }
304
305 let current_hashes: Vec<String> = file_contents.iter().map(|(_, _, _, h)| h.clone()).collect();
306 store.cleanup(¤t_hashes).ok();
307
308 all_findings.sort_by(|a, b| (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column)));
309 all_findings.dedup_by(|a, b| {
310 a.rule_id == b.rule_id && a.file == b.file && a.line == b.line && a.column == b.column
311 });
312
313 let (errors, warnings) =
314 all_findings
315 .iter()
316 .fold((0, 0), |(errors, warnings), f| match f.severity {
317 Severity::Error => (errors + 1, warnings),
318 Severity::Warning => (errors, warnings + 1),
319 });
320
321 let files_scanned = cached_count + changed_count;
322
323 Ok(ScanResult {
324 findings: all_findings,
325 stats: ScanStats {
326 errors,
327 warnings,
328 total: errors + warnings,
329 files_scanned,
330 },
331 cache_stats: Some(CacheStats {
332 cached: cached_count,
333 changed: changed_count,
334 }),
335 })
336}
337
338#[cfg(test)]
339mod tests {
340 use std::fs::{create_dir, write};
341
342 use tempfile::tempdir;
343
344 use super::*;
345 use crate::rule::{load_builtin_rules, parse_rule, RuleId};
346
347 fn unwrap_rule() -> Rule {
348 parse_rule(
349 r#"
350id: test-unwrap
351language: rust
352severity: error
353category: correctness
354message: ".unwrap() forbidden"
355rule:
356 kind: call_expression
357 regex: '\.unwrap\(\)\s*$'
358"#,
359 )
360 .unwrap()
361 }
362
363 fn scan_dir(dir: &Path, rules: &[Rule]) -> ScanResult {
364 scan(&[dir.to_path_buf()], rules, &Config::default()).unwrap()
365 }
366
367 #[test]
368 fn scan_finds_unwrap_violation() {
369 let dir = tempdir().unwrap();
370 write(
371 dir.path().join("main.rs"),
372 "fn main() {\n foo().unwrap();\n}\n",
373 )
374 .unwrap();
375 let result = scan_dir(dir.path(), &[unwrap_rule()]);
376 assert_eq!(result.findings.len(), 1);
377 let f = &result.findings[0];
378 assert_eq!(f.rule_id, RuleId::from("test-unwrap"));
379 assert_eq!(f.severity, Severity::Error);
380 assert_eq!(f.line, 2);
381 assert!(f.matched_text.contains("unwrap()"));
382 }
383
384 #[test]
385 fn scan_clean_file_no_findings() {
386 let dir = tempdir().unwrap();
387 write(dir.path().join("main.rs"), "fn main() { let x = foo(); }\n").unwrap();
388 let result = scan_dir(dir.path(), &[unwrap_rule()]);
389 assert_eq!(result.findings.len(), 0);
390 assert_eq!(result.stats.files_scanned, 1);
391 }
392
393 #[test]
394 fn scan_unsupported_language_ignored() {
395 let dir = tempdir().unwrap();
396 write(dir.path().join("script.py"), "x.unwrap()\n").unwrap();
397 write(dir.path().join("main.rs"), "fn main() {}\n").unwrap();
398 let result = scan_dir(dir.path(), &[unwrap_rule()]);
399 assert_eq!(result.findings.len(), 0);
400 assert_eq!(result.stats.files_scanned, 1);
401 }
402
403 #[test]
404 fn scan_explicit_file_path() {
405 let dir = tempdir().unwrap();
406 let file = dir.path().join("main.rs");
407 write(&file, "fn main() { foo().unwrap(); }\n").unwrap();
408 let result = scan(&[file], &[unwrap_rule()], &Config::default()).unwrap();
409 assert_eq!(result.findings.len(), 1);
410 assert_eq!(result.stats.files_scanned, 1);
411 }
412
413 #[test]
414 fn rule_ignores_glob_respected() {
415 let dir = tempdir().unwrap();
416 let tests_dir = dir.path().join("tests");
417 create_dir(&tests_dir).unwrap();
418 write(
419 tests_dir.join("test_main.rs"),
420 "fn t() { foo().unwrap(); }\n",
421 )
422 .unwrap();
423 write(
424 dir.path().join("main.rs"),
425 "fn main() { foo().unwrap(); }\n",
426 )
427 .unwrap();
428 let rule = parse_rule(
429 r#"
430id: ign
431language: rust
432severity: error
433category: correctness
434message: x
435rule:
436 kind: call_expression
437 regex: '\.unwrap\(\)\s*$'
438ignores:
439 - "**/tests/**"
440"#,
441 )
442 .unwrap();
443 let result = scan_dir(dir.path(), &[rule]);
444 assert_eq!(result.findings.len(), 1);
445 assert!(result.findings[0]
446 .file
447 .to_string_lossy()
448 .contains("main.rs"));
449 }
450
451 #[test]
452 fn config_ignores_respected() {
453 let dir = tempdir().unwrap();
454 let gen = dir.path().join("generated");
455 create_dir(&gen).unwrap();
456 write(gen.join("out.rs"), "fn g() { foo().unwrap(); }\n").unwrap();
457 write(
458 dir.path().join("main.rs"),
459 "fn main() { foo().unwrap(); }\n",
460 )
461 .unwrap();
462 let mut cfg = Config::default();
463 cfg.scan.ignores = vec!["**/generated/**".to_string()];
464 let result = scan(&[dir.path().to_path_buf()], &[unwrap_rule()], &cfg).unwrap();
465 assert_eq!(result.stats.files_scanned, 1);
466 assert_eq!(result.findings.len(), 1);
467 }
468
469 #[test]
470 fn config_invalid_glob_is_an_error() {
471 let dir = tempdir().unwrap();
472 let mut cfg = Config::default();
473 cfg.scan.ignores = vec!["[".to_string()];
474 let err = scan(&[dir.path().to_path_buf()], &[unwrap_rule()], &cfg).unwrap_err();
475 assert!(matches!(err, ScanError::Glob(_)), "{err:?}");
476 }
477
478 #[test]
479 fn rule_without_kind_fails_to_compile() {
480 let dir = tempdir().unwrap();
481 let rule = parse_rule(
482 r#"
483id: no-kind
484language: rust
485severity: error
486category: correctness
487message: x
488rule:
489 regex: 'unwrap'
490"#,
491 )
492 .unwrap();
493 let err = scan(&[dir.path().to_path_buf()], &[rule], &Config::default()).unwrap_err();
494 assert!(
495 matches!(&err, ScanError::RuleCompile { id, .. } if *id == RuleId::from("no-kind")),
496 "{err:?}"
497 );
498 }
499
500 #[test]
501 fn stats_counting_accurate() {
502 let dir = tempdir().unwrap();
503 write(
504 dir.path().join("a.rs"),
505 "fn f() { foo().unwrap(); bar().unwrap(); }\n",
506 )
507 .unwrap();
508 let result = scan_dir(dir.path(), &[unwrap_rule()]);
509 assert_eq!(result.stats.errors, 2);
510 assert_eq!(result.stats.warnings, 0);
511 assert_eq!(result.stats.total, 2);
512 assert_eq!(result.stats.files_scanned, 1);
513 }
514
515 #[test]
516 fn scan_empty_file() {
517 let dir = tempdir().unwrap();
518 write(dir.path().join("empty.rs"), "").unwrap();
519 let result = scan_dir(dir.path(), &[unwrap_rule()]);
520 assert_eq!(result.findings.len(), 0);
521 assert_eq!(result.stats.files_scanned, 1);
522 }
523
524 #[test]
525 fn scan_complex_rule() {
526 let rule = parse_rule(
527 r#"
528id: dbg
529language: rust
530severity: error
531category: security
532message: debug on secret
533rule:
534 kind: attribute_item
535 all:
536 - regex: 'derive\([^)]*Debug'
537 - precedes:
538 kind: struct_item
539 has:
540 kind: field_identifier
541 regex: '^(api_key|password|secret)$'
542 stopBy: end
543"#,
544 )
545 .unwrap();
546 let dir = tempdir().unwrap();
547 write(
548 dir.path().join("t.rs"),
549 "#[derive(Debug)]\nstruct Config {\n api_key: String,\n}\n",
550 )
551 .unwrap();
552 let result = scan_dir(dir.path(), &[rule]);
553 assert_eq!(result.findings.len(), 1);
554 assert_eq!(result.findings[0].rule_id, RuleId::from("dbg"));
555 }
556
557 #[test]
558 fn typescript_rule_applies_to_tsx_files() {
559 let rule = parse_rule(
560 r#"
561id: ts-any
562language: typescript
563severity: warning
564category: slop
565message: no any
566rule:
567 kind: predefined_type
568 regex: '^any$'
569"#,
570 )
571 .unwrap();
572 let dir = tempdir().unwrap();
573 write(dir.path().join("a.ts"), "let x: any = 1;\n").unwrap();
574 write(dir.path().join("b.tsx"), "let y: any = 2;\n").unwrap();
575 let result = scan_dir(dir.path(), &[rule]);
576 assert_eq!(result.stats.files_scanned, 2);
577 assert_eq!(result.stats.warnings, 2);
578 }
579
580 #[test]
581 fn scan_with_disable_comment_filters_findings() {
582 let dir = tempdir().unwrap();
583 write(
584 dir.path().join("main.rs"),
585 "fn main() {\n // slopguard-disable-next-line\n foo().unwrap();\n bar().unwrap();\n}\n",
586 )
587 .unwrap();
588 let result = scan_dir(dir.path(), &[unwrap_rule()]);
589 assert_eq!(
590 result.findings.len(),
591 1,
592 "only the non-disabled unwrap should remain"
593 );
594 assert_eq!(result.findings[0].line, 4);
595 }
596
597 #[test]
598 fn scan_with_disable_rule_id_filters_only_that_rule() {
599 let dir = tempdir().unwrap();
600 write(
601 dir.path().join("main.rs"),
602 "fn main() {\n // slopguard-disable-next-line test-unwrap\n foo().unwrap();\n}\n",
603 )
604 .unwrap();
605 let result = scan_dir(dir.path(), &[unwrap_rule()]);
606 assert_eq!(result.findings.len(), 0);
607 }
608
609 fn unwrap_rule_skipping_test_code() -> Rule {
610 parse_rule(
611 r#"
612id: test-unwrap
613language: rust
614severity: error
615category: correctness
616message: ".unwrap() forbidden"
617rule:
618 kind: call_expression
619 regex: '\.unwrap\(\)\s*$'
620skip_test_code: true
621"#,
622 )
623 .unwrap()
624 }
625
626 #[test]
627 fn cfg_test_block_excluded_by_post_filter() {
628 let dir = tempdir().unwrap();
629 write(
630 dir.path().join("main.rs"),
631 "fn prod() {\n foo().unwrap();\n}\n\n#[cfg(test)]\nmod tests {\n fn test_it() {\n bar().unwrap();\n }\n}\n",
632 )
633 .unwrap();
634 let result = scan_dir(dir.path(), &[unwrap_rule_skipping_test_code()]);
635 assert_eq!(
636 result.findings.len(),
637 1,
638 "should only find the prod unwrap, not the one inside #[cfg(test)]"
639 );
640 assert_eq!(result.findings[0].line, 2);
641 }
642
643 #[test]
644 fn cfg_test_kept_without_skip_test_code() {
645 let dir = tempdir().unwrap();
646 write(
647 dir.path().join("main.rs"),
648 "fn prod() {\n foo().unwrap();\n}\n\n#[cfg(test)]\nmod tests {\n fn test_it() {\n bar().unwrap();\n }\n}\n",
649 )
650 .unwrap();
651 let result = scan_dir(dir.path(), &[unwrap_rule()]);
652 assert_eq!(
653 result.findings.len(),
654 2,
655 "rule without skip_test_code should find both"
656 );
657 }
658
659 #[test]
660 fn all_builtin_rules_compile() {
661 let rules = load_builtin_rules().unwrap();
662 assert!(
663 rules.len() >= 55,
664 "expected at least 55 rules, got {}",
665 rules.len()
666 );
667 let compiled = compile_rules(&rules).expect("all builtin rules should compile");
668 assert_eq!(compiled.by_id.len(), rules.len());
669 }
670
671 #[test]
672 fn scan_with_cache() {
673 let dir = tempdir().unwrap();
674 write(
675 dir.path().join("main.rs"),
676 "fn main() {\n foo().unwrap();\n}\n",
677 )
678 .unwrap();
679
680 let rules = [unwrap_rule()];
681 let config = Config::default();
682
683 let result1 =
684 scan_cached(&[dir.path().to_path_buf()], &rules, &config, dir.path()).unwrap();
685
686 assert_eq!(result1.findings.len(), 1);
687 let cache_stats1 = result1.cache_stats.as_ref().unwrap();
688 assert_eq!(cache_stats1.cached, 0, "first scan: nothing cached");
689 assert_eq!(cache_stats1.changed, 1, "first scan: one file scanned");
690
691 let result2 =
692 scan_cached(&[dir.path().to_path_buf()], &rules, &config, dir.path()).unwrap();
693
694 assert_eq!(result2.findings.len(), 1);
695 let cache_stats2 = result2.cache_stats.as_ref().unwrap();
696 assert_eq!(cache_stats2.cached, 1, "second scan: one file from cache");
697 assert_eq!(cache_stats2.changed, 0, "second scan: nothing changed");
698 }
699}