1use std::collections::HashSet;
2use std::fmt;
3use std::fs::read_to_string;
4use std::io::Error as IoError;
5use std::path::{Component, Path, PathBuf};
6use std::str::{from_utf8, Utf8Error};
7
8use ast_grep_language::SupportLang;
9use ignore::WalkBuilder;
10use serde::{Deserialize, Serialize};
11use serde_yaml::Value;
12use slopguard_rules::BuiltinRules;
13use strum::{Display, EnumIter, EnumString};
14use thiserror::Error;
15
16use crate::cross_file::CrossFileKind;
17use crate::metric::Metric;
18use crate::resolution::ResolutionKind;
19use crate::source::{ResolvedSource, RuleOrigin};
20
21#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
22pub struct RuleId(pub String);
23
24impl fmt::Display for RuleId {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 f.write_str(&self.0)
27 }
28}
29
30impl RuleId {
31 pub fn as_str(&self) -> &str {
32 &self.0
33 }
34}
35
36impl From<String> for RuleId {
37 fn from(s: String) -> Self {
38 Self(s)
39 }
40}
41
42impl From<&str> for RuleId {
43 fn from(s: &str) -> Self {
44 Self(s.to_string())
45 }
46}
47
48#[derive(Debug, Display, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "lowercase")]
50#[strum(serialize_all = "lowercase")]
51pub enum Severity {
52 Error,
53 Warning,
54}
55
56#[derive(Debug, Display, EnumIter, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
57#[serde(rename_all = "lowercase")]
58#[strum(serialize_all = "lowercase")]
59pub enum Language {
60 Rust,
61 TypeScript,
62}
63
64impl Language {
65 pub fn ast_grep_langs(&self) -> &'static [SupportLang] {
68 match self {
69 Language::Rust => &[SupportLang::Rust],
70 Language::TypeScript => &[SupportLang::TypeScript, SupportLang::Tsx],
71 }
72 }
73}
74
75#[derive(Debug, Display, EnumString, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "lowercase")]
77#[strum(serialize_all = "lowercase")]
78pub enum Category {
79 Slop,
80 Security,
81 #[default]
82 Correctness,
83}
84
85impl Category {
86 fn from_rule_path(path: &Path) -> Option<Self> {
90 match path.components().next()? {
91 Component::Normal(dir) => dir.to_str()?.parse().ok(),
92 _ => None,
93 }
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101pub struct FixCase {
102 pub before: String,
103 pub after: String,
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct RuleTests {
108 #[serde(default)]
109 pub should_match: Vec<String>,
110 #[serde(default)]
111 pub should_not_match: Vec<String>,
112 #[serde(default)]
116 pub should_fix: Vec<FixCase>,
117 #[serde(default)]
121 pub should_match_files: Vec<String>,
122 #[serde(default)]
123 pub should_not_match_files: Vec<String>,
124}
125
126#[derive(Debug, Display, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
129#[serde(rename_all = "lowercase")]
130#[strum(serialize_all = "lowercase")]
131pub enum ReasonMode {
132 #[default]
134 Static,
135 Generated,
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146pub struct AiCheck {
147 pub prompt: String,
151 #[serde(default)]
153 pub model: Option<String>,
154 #[serde(default)]
157 pub reason: ReasonMode,
158 #[serde(default)]
161 pub threshold: Option<f64>,
162 #[serde(default)]
165 pub if_true: Option<String>,
166 #[serde(default)]
169 pub if_false: Option<String>,
170}
171
172fn default_enabled() -> bool {
173 true
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct Rule {
178 pub id: RuleId,
179 pub language: Language,
180 pub severity: Severity,
181 pub message: String,
182 #[serde(default)]
183 pub note: Option<String>,
184 #[serde(default)]
185 pub category: Option<Category>,
186 #[serde(default)]
187 pub fix: Option<String>,
188 #[serde(default)]
193 pub rewrite: Option<String>,
194 #[serde(default)]
200 pub autofix_safe: bool,
201 #[serde(default, skip_serializing_if = "Value::is_null")]
210 pub autofix_rule: Value,
211 #[serde(default)]
212 pub rule: Value,
213 #[serde(default, skip_serializing_if = "Value::is_null")]
217 pub constraints: Value,
218 #[serde(default)]
220 pub metric: Option<Metric>,
221 #[serde(default)]
223 pub threshold: Option<f64>,
224 #[serde(default)]
228 pub min_lines: Option<usize>,
229 #[serde(default)]
233 pub cross_file: Option<CrossFileKind>,
234 #[serde(default)]
240 pub resolution: Option<ResolutionKind>,
241 #[serde(skip)]
244 pub source_dir: Option<PathBuf>,
245 #[serde(skip)]
248 pub origin: RuleOrigin,
249 #[serde(default)]
250 pub files: Option<Vec<String>>,
251 #[serde(default)]
252 pub ignores: Option<Vec<String>>,
253 #[serde(default = "default_enabled")]
256 pub enabled: bool,
257 #[serde(default)]
258 pub skip_test_code: bool,
259 #[serde(default)]
260 pub tests: Option<RuleTests>,
261 #[serde(default)]
264 pub ai_check: Option<AiCheck>,
265}
266
267impl Rule {
268 pub fn effective_category(&self) -> Category {
271 self.category.clone().unwrap_or_default()
272 }
273
274 pub fn is_metric(&self) -> bool {
276 self.metric.is_some()
277 }
278
279 pub fn metric_spec(&self) -> Option<(Metric, f64)> {
281 Some((self.metric?, self.threshold?))
282 }
283
284 pub fn is_cross_file(&self) -> bool {
286 self.cross_file.is_some()
287 }
288
289 pub fn is_resolution(&self) -> bool {
291 self.resolution.is_some()
292 }
293
294 pub fn is_autofixable(&self) -> bool {
299 self.autofix_safe && self.rewrite.is_some()
300 }
301
302 pub fn fix_matcher(&self) -> &Value {
305 if self.autofix_rule.is_null() {
306 &self.rule
307 } else {
308 &self.autofix_rule
309 }
310 }
311
312 pub fn cross_file_kind(&self) -> Option<CrossFileKind> {
316 self.cross_file
317 }
318
319 pub fn resolution_kind(&self) -> Option<ResolutionKind> {
323 self.resolution
324 }
325}
326
327#[derive(Debug, Error)]
328pub enum RuleError {
329 #[error("failed to parse rule YAML: {0}")]
330 Parse(#[from] serde_yaml::Error),
331
332 #[error("rule '{id}': rule field must not be empty")]
333 EmptyRule { id: RuleId },
334
335 #[error("rule '{id}': 'metric' and 'rule' are mutually exclusive")]
336 MetricAndRule { id: RuleId },
337
338 #[error("rule '{id}': 'cross_file' and 'rule' are mutually exclusive")]
339 CrossFileAndRule { id: RuleId },
340
341 #[error("rule '{id}': 'cross_file' and 'metric' are mutually exclusive")]
342 CrossFileAndMetric { id: RuleId },
343
344 #[error("rule '{id}': 'resolution' and 'rule' are mutually exclusive")]
345 ResolutionAndRule { id: RuleId },
346
347 #[error("rule '{id}': 'resolution' and 'metric' are mutually exclusive")]
348 ResolutionAndMetric { id: RuleId },
349
350 #[error("rule '{id}': 'resolution' and 'cross_file' are mutually exclusive")]
351 ResolutionAndCrossFile { id: RuleId },
352
353 #[error("rule '{id}': a metric rule requires a 'threshold'")]
354 MissingThreshold { id: RuleId },
355
356 #[error("rule '{id}': test fixture files are only supported for metric rules")]
357 FixturesOnAstRule { id: RuleId },
358
359 #[error("rule '{id}': fixture path '{path}' must be relative and must not contain '..'")]
360 InvalidFixturePath { id: RuleId, path: String },
361
362 #[error("rule '{id}': fixture '{path}' not found")]
363 FixtureNotFound { id: RuleId, path: String },
364
365 #[error("duplicate rule id: '{id}'")]
366 DuplicateId { id: RuleId },
367
368 #[error("rule '{id}' from source '{origin}' reuses a builtin rule id; rename it (external sources may not shadow builtin rules)")]
369 SourceReusesBuiltinId { id: RuleId, origin: String },
370
371 #[error("failed to read rule file '{path}': {source}")]
372 Io {
373 path: String,
374 #[source]
375 source: IoError,
376 },
377
378 #[error("rule file '{path}' is not valid UTF-8: {source}")]
379 Utf8 {
380 path: String,
381 #[source]
382 source: Utf8Error,
383 },
384}
385
386impl RuleError {
387 fn io(path: &Path, source: IoError) -> Self {
388 Self::Io {
389 path: path.display().to_string(),
390 source,
391 }
392 }
393}
394
395pub fn parse_rule(yaml: &str) -> Result<Rule, RuleError> {
400 let rule: Rule = serde_yaml::from_str(yaml)?;
401 let has_rule = !rule.rule.is_null();
402 let has_metric = rule.metric.is_some();
403 let has_cross = rule.cross_file.is_some();
404 let has_resolution = rule.resolution.is_some();
405 if has_resolution {
406 if has_rule {
407 return Err(RuleError::ResolutionAndRule { id: rule.id });
408 }
409 if has_metric {
410 return Err(RuleError::ResolutionAndMetric { id: rule.id });
411 }
412 if has_cross {
413 return Err(RuleError::ResolutionAndCrossFile { id: rule.id });
414 }
415 }
416 match (has_cross, has_metric, has_rule) {
417 (true, _, true) => return Err(RuleError::CrossFileAndRule { id: rule.id }),
418 (true, true, _) => return Err(RuleError::CrossFileAndMetric { id: rule.id }),
419 (false, true, true) => return Err(RuleError::MetricAndRule { id: rule.id }),
420 (false, true, false) if rule.threshold.is_none() => {
421 return Err(RuleError::MissingThreshold { id: rule.id })
422 }
423 (false, false, false) if !has_resolution => {
424 return Err(RuleError::EmptyRule { id: rule.id })
425 }
426 _ => {}
427 }
428 if !rule.is_metric() {
429 if let Some(tests) = &rule.tests {
430 if !tests.should_match_files.is_empty() || !tests.should_not_match_files.is_empty() {
431 return Err(RuleError::FixturesOnAstRule { id: rule.id });
432 }
433 }
434 }
435 Ok(rule)
436}
437
438pub fn read_fixture(rule: &Rule, relative: &str) -> Result<String, RuleError> {
442 let path = Path::new(relative);
443 let traverses = path.components().any(|c| matches!(c, Component::ParentDir));
444 if path.is_absolute() || traverses {
445 return Err(RuleError::InvalidFixturePath {
446 id: rule.id.clone(),
447 path: relative.to_string(),
448 });
449 }
450
451 match &rule.source_dir {
452 Some(dir) => {
453 let full = dir.join(path);
454 read_to_string(&full).map_err(|e| {
455 if e.kind() == std::io::ErrorKind::NotFound {
456 RuleError::FixtureNotFound {
457 id: rule.id.clone(),
458 path: relative.to_string(),
459 }
460 } else {
461 RuleError::io(&full, e)
462 }
463 })
464 }
465 None => {
466 let file = BuiltinRules::get(relative).ok_or_else(|| RuleError::FixtureNotFound {
467 id: rule.id.clone(),
468 path: relative.to_string(),
469 })?;
470 from_utf8(&file.data)
471 .map(str::to_string)
472 .map_err(|e| RuleError::Utf8 {
473 path: relative.to_string(),
474 source: e,
475 })
476 }
477 }
478}
479
480fn parse_rule_at(yaml: &str, relative_path: &Path) -> Result<Rule, RuleError> {
483 let mut rule = parse_rule(yaml)?;
484 if rule.category.is_none() {
485 rule.category = Category::from_rule_path(relative_path);
486 }
487 Ok(rule)
488}
489
490fn is_rule_file(path: &Path) -> bool {
491 matches!(
492 path.extension().and_then(|e| e.to_str()),
493 Some("yml" | "yaml")
494 )
495}
496
497pub fn load_builtin_rules() -> Result<Vec<Rule>, RuleError> {
499 BuiltinRules::iter()
500 .filter(|path| is_rule_file(Path::new(path.as_ref())))
501 .filter_map(|path| BuiltinRules::get(&path).map(|file| (path, file)))
502 .map(|(path, file)| {
503 let yaml = from_utf8(&file.data).map_err(|e| RuleError::Utf8 {
504 path: path.to_string(),
505 source: e,
506 })?;
507 parse_rule_at(yaml, Path::new(path.as_ref()))
508 })
509 .collect()
510}
511
512fn load_rules_in_dir(dir: &Path, origin: &RuleOrigin) -> Result<Vec<Rule>, RuleError> {
516 let mut rules = Vec::new();
517 for entry in WalkBuilder::new(dir).standard_filters(false).build() {
520 let entry = entry.map_err(|e| RuleError::io(dir, IoError::other(e)))?;
521 let path = entry.path();
522 let is_file = entry.file_type().is_some_and(|t| t.is_file());
523 if !is_file || !is_rule_file(path) {
524 continue;
525 }
526 let yaml = read_to_string(path).map_err(|e| RuleError::io(path, e))?;
527 let relative = path.strip_prefix(dir).unwrap_or(path);
528 let mut rule = parse_rule_at(&yaml, relative)?;
529 rule.source_dir = Some(dir.to_path_buf());
530 rule.origin = origin.clone();
531 rules.push(rule);
532 }
533 Ok(rules)
534}
535
536pub fn load_custom_rules(dirs: &[PathBuf]) -> Result<Vec<Rule>, RuleError> {
539 let mut rules = Vec::new();
540 for dir in dirs.iter().filter(|dir| dir.is_dir()) {
541 let origin = RuleOrigin::Local { path: dir.clone() };
542 rules.extend(load_rules_in_dir(dir, &origin)?);
543 }
544 Ok(rules)
545}
546
547pub fn load_source_rules(sources: &[ResolvedSource]) -> Result<Vec<Rule>, RuleError> {
551 let mut rules = Vec::new();
552 for source in sources.iter().filter(|s| s.dir.is_dir()) {
553 rules.extend(load_rules_in_dir(&source.dir, &source.origin)?);
554 }
555 Ok(rules)
556}
557
558fn reject_builtin_id_reuse(external: &[Rule], builtin: &[Rule]) -> Result<(), RuleError> {
561 let builtin_ids: HashSet<(&RuleId, &Language)> =
562 builtin.iter().map(|r| (&r.id, &r.language)).collect();
563 for rule in external {
564 if builtin_ids.contains(&(&rule.id, &rule.language)) {
565 return Err(RuleError::SourceReusesBuiltinId {
566 id: rule.id.clone(),
567 origin: rule.origin.label(),
568 });
569 }
570 }
571 Ok(())
572}
573
574pub fn is_rule_active(rule: &Rule, config: &crate::config::Config) -> bool {
580 let listed = |ids: &[String]| ids.iter().any(|id| id == rule.id.as_str());
581 if listed(&config.rules.enable) {
582 return true;
583 }
584 let ruleset_on = match rule.effective_category() {
585 Category::Slop => config.rulesets.slop,
586 Category::Security => config.rulesets.security,
587 Category::Correctness => config.rulesets.correctness,
588 };
589 ruleset_on && rule.enabled && !listed(&config.rules.disable)
590}
591
592fn load_external_rules(
596 config: &crate::config::Config,
597 sources: &[ResolvedSource],
598 builtin: &[Rule],
599) -> Result<Vec<Rule>, RuleError> {
600 let source_rules = load_source_rules(sources)?;
601 reject_builtin_id_reuse(&source_rules, builtin)?;
602
603 let mut external = load_custom_rules(&config.rules.custom_dirs)?;
604 external.extend(source_rules);
605 Ok(external)
606}
607
608pub fn load_effective_rules(
613 config: &crate::config::Config,
614 sources: &[ResolvedSource],
615) -> Result<Vec<Rule>, RuleError> {
616 let builtin = load_builtin_rules()?;
617 let external = load_external_rules(config, sources, &builtin)?;
618
619 let mut rules: Vec<Rule> = builtin
620 .into_iter()
621 .filter(|rule| is_rule_active(rule, config))
622 .collect();
623 rules.extend(external);
624 validate_unique_ids(&rules)?;
625 Ok(rules)
626}
627
628pub fn load_all_rules(
632 config: &crate::config::Config,
633 sources: &[ResolvedSource],
634) -> Result<Vec<Rule>, RuleError> {
635 let builtin = load_builtin_rules()?;
636 let external = load_external_rules(config, sources, &builtin)?;
637
638 let mut rules = builtin;
639 rules.extend(external);
640 Ok(rules)
641}
642
643pub fn validate_unique_ids(rules: &[Rule]) -> Result<(), RuleError> {
647 let mut seen = HashSet::new();
648 for rule in rules {
649 if !seen.insert((&rule.id, &rule.language)) {
650 return Err(RuleError::DuplicateId {
651 id: rule.id.clone(),
652 });
653 }
654 }
655 Ok(())
656}
657
658#[cfg(test)]
659mod load_tests;
660#[cfg(test)]
661mod parse_tests;