use std::collections::HashSet;
use std::fmt;
use std::fs::read_to_string;
use std::io::Error as IoError;
use std::path::{Component, Path, PathBuf};
use std::str::{from_utf8, Utf8Error};
use ast_grep_language::SupportLang;
use ignore::WalkBuilder;
use serde::{Deserialize, Serialize};
use serde_yaml::Value;
use slopguard_rules::BuiltinRules;
use strum::{Display, EnumIter, EnumString};
use thiserror::Error;
use crate::cross_file::CrossFileKind;
use crate::metric::Metric;
use crate::resolution::ResolutionKind;
use crate::source::{ResolvedSource, RuleOrigin};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RuleId(pub String);
impl fmt::Display for RuleId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl RuleId {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<String> for RuleId {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for RuleId {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
#[derive(Debug, Display, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Display, EnumIter, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum Language {
Rust,
TypeScript,
}
impl Language {
pub fn ast_grep_langs(&self) -> &'static [SupportLang] {
match self {
Language::Rust => &[SupportLang::Rust],
Language::TypeScript => &[SupportLang::TypeScript, SupportLang::Tsx],
}
}
}
#[derive(Debug, Display, EnumString, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum Category {
Slop,
Security,
#[default]
Correctness,
}
impl Category {
fn from_rule_path(path: &Path) -> Option<Self> {
match path.components().next()? {
Component::Normal(dir) => dir.to_str()?.parse().ok(),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FixCase {
pub before: String,
pub after: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuleTests {
#[serde(default)]
pub should_match: Vec<String>,
#[serde(default)]
pub should_not_match: Vec<String>,
#[serde(default)]
pub should_fix: Vec<FixCase>,
#[serde(default)]
pub should_match_files: Vec<String>,
#[serde(default)]
pub should_not_match_files: Vec<String>,
}
#[derive(Debug, Display, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum ReasonMode {
#[default]
Static,
Generated,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AiCheck {
pub prompt: String,
#[serde(default)]
pub model: Option<String>,
#[serde(default)]
pub reason: ReasonMode,
#[serde(default)]
pub threshold: Option<f64>,
#[serde(default)]
pub if_true: Option<String>,
#[serde(default)]
pub if_false: Option<String>,
}
fn default_enabled() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rule {
pub id: RuleId,
pub language: Language,
pub severity: Severity,
pub message: String,
#[serde(default)]
pub note: Option<String>,
#[serde(default)]
pub category: Option<Category>,
#[serde(default)]
pub fix: Option<String>,
#[serde(default)]
pub rewrite: Option<String>,
#[serde(default)]
pub autofix_safe: bool,
#[serde(default, skip_serializing_if = "Value::is_null")]
pub autofix_rule: Value,
#[serde(default)]
pub rule: Value,
#[serde(default, skip_serializing_if = "Value::is_null")]
pub constraints: Value,
#[serde(default)]
pub metric: Option<Metric>,
#[serde(default)]
pub threshold: Option<f64>,
#[serde(default)]
pub min_lines: Option<usize>,
#[serde(default)]
pub cross_file: Option<CrossFileKind>,
#[serde(default)]
pub resolution: Option<ResolutionKind>,
#[serde(skip)]
pub source_dir: Option<PathBuf>,
#[serde(skip)]
pub origin: RuleOrigin,
#[serde(default)]
pub files: Option<Vec<String>>,
#[serde(default)]
pub ignores: Option<Vec<String>>,
#[serde(default = "default_enabled")]
pub enabled: bool,
#[serde(default)]
pub skip_test_code: bool,
#[serde(default)]
pub tests: Option<RuleTests>,
#[serde(default)]
pub ai_check: Option<AiCheck>,
}
impl Rule {
pub fn effective_category(&self) -> Category {
self.category.clone().unwrap_or_default()
}
pub fn is_metric(&self) -> bool {
self.metric.is_some()
}
pub fn metric_spec(&self) -> Option<(Metric, f64)> {
Some((self.metric?, self.threshold?))
}
pub fn is_cross_file(&self) -> bool {
self.cross_file.is_some()
}
pub fn is_resolution(&self) -> bool {
self.resolution.is_some()
}
pub fn is_autofixable(&self) -> bool {
self.autofix_safe && self.rewrite.is_some()
}
pub fn fix_matcher(&self) -> &Value {
if self.autofix_rule.is_null() {
&self.rule
} else {
&self.autofix_rule
}
}
pub fn cross_file_kind(&self) -> Option<CrossFileKind> {
self.cross_file
}
pub fn resolution_kind(&self) -> Option<ResolutionKind> {
self.resolution
}
}
#[derive(Debug, Error)]
pub enum RuleError {
#[error("failed to parse rule YAML: {0}")]
Parse(#[from] serde_yaml::Error),
#[error("rule '{id}': rule field must not be empty")]
EmptyRule { id: RuleId },
#[error("rule '{id}': 'metric' and 'rule' are mutually exclusive")]
MetricAndRule { id: RuleId },
#[error("rule '{id}': 'cross_file' and 'rule' are mutually exclusive")]
CrossFileAndRule { id: RuleId },
#[error("rule '{id}': 'cross_file' and 'metric' are mutually exclusive")]
CrossFileAndMetric { id: RuleId },
#[error("rule '{id}': 'resolution' and 'rule' are mutually exclusive")]
ResolutionAndRule { id: RuleId },
#[error("rule '{id}': 'resolution' and 'metric' are mutually exclusive")]
ResolutionAndMetric { id: RuleId },
#[error("rule '{id}': 'resolution' and 'cross_file' are mutually exclusive")]
ResolutionAndCrossFile { id: RuleId },
#[error("rule '{id}': a metric rule requires a 'threshold'")]
MissingThreshold { id: RuleId },
#[error("rule '{id}': test fixture files are only supported for metric rules")]
FixturesOnAstRule { id: RuleId },
#[error("rule '{id}': fixture path '{path}' must be relative and must not contain '..'")]
InvalidFixturePath { id: RuleId, path: String },
#[error("rule '{id}': fixture '{path}' not found")]
FixtureNotFound { id: RuleId, path: String },
#[error("duplicate rule id: '{id}'")]
DuplicateId { id: RuleId },
#[error("rule '{id}' from source '{origin}' reuses a builtin rule id; rename it (external sources may not shadow builtin rules)")]
SourceReusesBuiltinId { id: RuleId, origin: String },
#[error("failed to read rule file '{path}': {source}")]
Io {
path: String,
#[source]
source: IoError,
},
#[error("rule file '{path}' is not valid UTF-8: {source}")]
Utf8 {
path: String,
#[source]
source: Utf8Error,
},
}
impl RuleError {
fn io(path: &Path, source: IoError) -> Self {
Self::Io {
path: path.display().to_string(),
source,
}
}
}
pub fn parse_rule(yaml: &str) -> Result<Rule, RuleError> {
let rule: Rule = serde_yaml::from_str(yaml)?;
let has_rule = !rule.rule.is_null();
let has_metric = rule.metric.is_some();
let has_cross = rule.cross_file.is_some();
let has_resolution = rule.resolution.is_some();
if has_resolution {
if has_rule {
return Err(RuleError::ResolutionAndRule { id: rule.id });
}
if has_metric {
return Err(RuleError::ResolutionAndMetric { id: rule.id });
}
if has_cross {
return Err(RuleError::ResolutionAndCrossFile { id: rule.id });
}
}
match (has_cross, has_metric, has_rule) {
(true, _, true) => return Err(RuleError::CrossFileAndRule { id: rule.id }),
(true, true, _) => return Err(RuleError::CrossFileAndMetric { id: rule.id }),
(false, true, true) => return Err(RuleError::MetricAndRule { id: rule.id }),
(false, true, false) if rule.threshold.is_none() => {
return Err(RuleError::MissingThreshold { id: rule.id })
}
(false, false, false) if !has_resolution => {
return Err(RuleError::EmptyRule { id: rule.id })
}
_ => {}
}
if !rule.is_metric() {
if let Some(tests) = &rule.tests {
if !tests.should_match_files.is_empty() || !tests.should_not_match_files.is_empty() {
return Err(RuleError::FixturesOnAstRule { id: rule.id });
}
}
}
Ok(rule)
}
pub fn read_fixture(rule: &Rule, relative: &str) -> Result<String, RuleError> {
let path = Path::new(relative);
let traverses = path.components().any(|c| matches!(c, Component::ParentDir));
if path.is_absolute() || traverses {
return Err(RuleError::InvalidFixturePath {
id: rule.id.clone(),
path: relative.to_string(),
});
}
match &rule.source_dir {
Some(dir) => {
let full = dir.join(path);
read_to_string(&full).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
RuleError::FixtureNotFound {
id: rule.id.clone(),
path: relative.to_string(),
}
} else {
RuleError::io(&full, e)
}
})
}
None => {
let file = BuiltinRules::get(relative).ok_or_else(|| RuleError::FixtureNotFound {
id: rule.id.clone(),
path: relative.to_string(),
})?;
from_utf8(&file.data)
.map(str::to_string)
.map_err(|e| RuleError::Utf8 {
path: relative.to_string(),
source: e,
})
}
}
}
fn parse_rule_at(yaml: &str, relative_path: &Path) -> Result<Rule, RuleError> {
let mut rule = parse_rule(yaml)?;
if rule.category.is_none() {
rule.category = Category::from_rule_path(relative_path);
}
Ok(rule)
}
fn is_rule_file(path: &Path) -> bool {
matches!(
path.extension().and_then(|e| e.to_str()),
Some("yml" | "yaml")
)
}
pub fn load_builtin_rules() -> Result<Vec<Rule>, RuleError> {
BuiltinRules::iter()
.filter(|path| is_rule_file(Path::new(path.as_ref())))
.filter_map(|path| BuiltinRules::get(&path).map(|file| (path, file)))
.map(|(path, file)| {
let yaml = from_utf8(&file.data).map_err(|e| RuleError::Utf8 {
path: path.to_string(),
source: e,
})?;
parse_rule_at(yaml, Path::new(path.as_ref()))
})
.collect()
}
fn load_rules_in_dir(dir: &Path, origin: &RuleOrigin) -> Result<Vec<Rule>, RuleError> {
let mut rules = Vec::new();
for entry in WalkBuilder::new(dir).standard_filters(false).build() {
let entry = entry.map_err(|e| RuleError::io(dir, IoError::other(e)))?;
let path = entry.path();
let is_file = entry.file_type().is_some_and(|t| t.is_file());
if !is_file || !is_rule_file(path) {
continue;
}
let yaml = read_to_string(path).map_err(|e| RuleError::io(path, e))?;
let relative = path.strip_prefix(dir).unwrap_or(path);
let mut rule = parse_rule_at(&yaml, relative)?;
rule.source_dir = Some(dir.to_path_buf());
rule.origin = origin.clone();
rules.push(rule);
}
Ok(rules)
}
pub fn load_custom_rules(dirs: &[PathBuf]) -> Result<Vec<Rule>, RuleError> {
let mut rules = Vec::new();
for dir in dirs.iter().filter(|dir| dir.is_dir()) {
let origin = RuleOrigin::Local { path: dir.clone() };
rules.extend(load_rules_in_dir(dir, &origin)?);
}
Ok(rules)
}
pub fn load_source_rules(sources: &[ResolvedSource]) -> Result<Vec<Rule>, RuleError> {
let mut rules = Vec::new();
for source in sources.iter().filter(|s| s.dir.is_dir()) {
rules.extend(load_rules_in_dir(&source.dir, &source.origin)?);
}
Ok(rules)
}
fn reject_builtin_id_reuse(external: &[Rule], builtin: &[Rule]) -> Result<(), RuleError> {
let builtin_ids: HashSet<(&RuleId, &Language)> =
builtin.iter().map(|r| (&r.id, &r.language)).collect();
for rule in external {
if builtin_ids.contains(&(&rule.id, &rule.language)) {
return Err(RuleError::SourceReusesBuiltinId {
id: rule.id.clone(),
origin: rule.origin.label(),
});
}
}
Ok(())
}
pub fn is_rule_active(rule: &Rule, config: &crate::config::Config) -> bool {
let listed = |ids: &[String]| ids.iter().any(|id| id == rule.id.as_str());
if listed(&config.rules.enable) {
return true;
}
let ruleset_on = match rule.effective_category() {
Category::Slop => config.rulesets.slop,
Category::Security => config.rulesets.security,
Category::Correctness => config.rulesets.correctness,
};
ruleset_on && rule.enabled && !listed(&config.rules.disable)
}
fn load_external_rules(
config: &crate::config::Config,
sources: &[ResolvedSource],
builtin: &[Rule],
) -> Result<Vec<Rule>, RuleError> {
let source_rules = load_source_rules(sources)?;
reject_builtin_id_reuse(&source_rules, builtin)?;
let mut external = load_custom_rules(&config.rules.custom_dirs)?;
external.extend(source_rules);
Ok(external)
}
pub fn load_effective_rules(
config: &crate::config::Config,
sources: &[ResolvedSource],
) -> Result<Vec<Rule>, RuleError> {
let builtin = load_builtin_rules()?;
let external = load_external_rules(config, sources, &builtin)?;
let mut rules: Vec<Rule> = builtin
.into_iter()
.filter(|rule| is_rule_active(rule, config))
.collect();
rules.extend(external);
validate_unique_ids(&rules)?;
Ok(rules)
}
pub fn load_all_rules(
config: &crate::config::Config,
sources: &[ResolvedSource],
) -> Result<Vec<Rule>, RuleError> {
let builtin = load_builtin_rules()?;
let external = load_external_rules(config, sources, &builtin)?;
let mut rules = builtin;
rules.extend(external);
Ok(rules)
}
pub fn validate_unique_ids(rules: &[Rule]) -> Result<(), RuleError> {
let mut seen = HashSet::new();
for rule in rules {
if !seen.insert((&rule.id, &rule.language)) {
return Err(RuleError::DuplicateId {
id: rule.id.clone(),
});
}
}
Ok(())
}
#[cfg(test)]
mod load_tests;
#[cfg(test)]
mod parse_tests;