1use std::fs;
2use std::path::{Path, PathBuf};
3
4use pedant_types::{AnalysisTier, ExecutionContext};
5
6use crate::analysis_result::AnalysisResult;
7use crate::capabilities::detect_capabilities;
8use crate::check_config::CheckConfig;
9use crate::ir;
10use crate::ir::DataFlowFact;
11use crate::ir::extract::compute_fingerprints;
12use crate::ir::semantic::SemanticContext;
13use crate::style::check_style;
14
15type ManifestPresence = (bool, bool);
16
17#[derive(Debug, thiserror::Error)]
19pub enum LintError {
20 #[error("IO error: {0}")]
22 IoError(#[from] std::io::Error),
23 #[error("parse error: {0}")]
25 ParseError(#[from] syn::Error),
26 #[error("TOML parse error: {0}")]
28 TomlParseError(#[from] toml::de::Error),
29}
30
31pub fn analyze(
36 file_path: &str,
37 source: &str,
38 config: &CheckConfig,
39 semantic: Option<&SemanticContext>,
40) -> Result<AnalysisResult, syn::Error> {
41 analyze_inner(file_path, source, config, semantic, None)
42}
43
44pub fn analyze_build_script(
46 file_path: &str,
47 source: &str,
48 config: &CheckConfig,
49 semantic: Option<&SemanticContext>,
50) -> Result<AnalysisResult, syn::Error> {
51 analyze_inner(
52 file_path,
53 source,
54 config,
55 semantic,
56 Some(ExecutionContext::BuildHook),
57 )
58}
59
60fn analyze_inner(
61 file_path: &str,
62 source: &str,
63 config: &CheckConfig,
64 semantic: Option<&SemanticContext>,
65 execution_context: Option<ExecutionContext>,
66) -> Result<AnalysisResult, syn::Error> {
67 let syntax = syn::parse_file(source)?;
68 let ir = ir::extract(file_path, &syntax, semantic);
69 let violations = check_style(&ir, config).into_boxed_slice();
70 let capabilities = detect_capabilities(&ir, execution_context);
71
72 #[cfg(feature = "semantic")]
73 let capabilities = {
74 let mut caps = capabilities;
75 if let Some(ctx) = semantic {
76 enrich_reachability(&mut caps.findings, ctx);
77 }
78 caps
79 };
80
81 let fn_fingerprints = compute_fingerprints(&ir);
82
83 Ok(AnalysisResult {
84 violations,
85 capabilities,
86 data_flows: ir.data_flows,
87 fn_fingerprints,
88 })
89}
90
91pub fn lint_str(source: &str, config: &CheckConfig) -> Result<AnalysisResult, LintError> {
93 analyze("<string>", source, config, None).map_err(LintError::from)
94}
95
96pub fn lint_file(path: &Path, config: &CheckConfig) -> Result<AnalysisResult, LintError> {
98 let source = fs::read_to_string(path)?;
99 let file_path = path.to_string_lossy();
100 analyze(&file_path, &source, config, None).map_err(LintError::from)
101}
102
103pub fn discover_workspace_root(start: &Path) -> Result<Option<PathBuf>, LintError> {
109 let start_dir = match (start.is_dir(), start.parent()) {
110 (true, _) => start,
111 (false, Some(parent)) => parent,
112 (false, None) => return Ok(None),
113 };
114
115 let mut nearest_package: Option<PathBuf> = None;
116 for dir in start_dir.ancestors() {
117 let cargo_toml = dir.join("Cargo.toml");
118 let (has_workspace, has_package) = read_manifest_presence(&cargo_toml)?;
119 match (has_workspace, has_package, nearest_package.is_some()) {
120 (true, _, _) => return Ok(Some(dir.to_path_buf())),
121 (false, true, false) => nearest_package = Some(dir.to_path_buf()),
122 _ => {}
123 }
124 }
125 Ok(nearest_package)
126}
127
128fn read_manifest_presence(cargo_toml: &Path) -> Result<ManifestPresence, LintError> {
129 let contents = match fs::read_to_string(cargo_toml) {
130 Ok(contents) => contents,
131 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok((false, false)),
132 Err(error) => return Err(LintError::IoError(error)),
133 };
134 let table: toml::Table = contents.parse()?;
135 Ok((
136 contains_manifest_table(&table, "workspace"),
137 contains_manifest_table(&table, "package"),
138 ))
139}
140
141fn contains_manifest_table(table: &toml::Table, section_name: &str) -> bool {
142 table
143 .get(section_name)
144 .and_then(toml::Value::as_table)
145 .is_some()
146}
147
148pub fn discover_build_script(crate_root: &Path) -> Result<Option<PathBuf>, LintError> {
153 let cargo_toml_path = crate_root.join("Cargo.toml");
154 let cargo_toml_contents = match fs::read_to_string(&cargo_toml_path) {
155 Ok(contents) => contents,
156 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
157 Err(e) => return Err(LintError::IoError(e)),
158 };
159 let table: toml::Table = cargo_toml_contents.parse()?;
160
161 let custom_path = table
162 .get("package")
163 .and_then(toml::Value::as_table)
164 .and_then(|pkg| pkg.get("build"))
165 .and_then(toml::Value::as_str);
166
167 let candidate = match custom_path {
168 Some(build_path) => crate_root.join(build_path),
169 None => crate_root.join("build.rs"),
170 };
171
172 Ok(candidate.is_file().then_some(candidate))
173}
174
175pub fn analyze_with_build_script(
180 file_path: &str,
181 source: &str,
182 config: &CheckConfig,
183 semantic: Option<&SemanticContext>,
184 build_source: Option<(&str, &str)>,
185) -> Result<AnalysisResult, syn::Error> {
186 let mut result = analyze(file_path, source, config, semantic)?;
187
188 let Some((build_path, build_src)) = build_source else {
189 return Ok(result);
190 };
191
192 let build_caps = analyze_build_script(build_path, build_src, config, semantic)?.capabilities;
193
194 let mut merged = result.capabilities.findings.into_vec();
195 merged.extend(build_caps.findings);
196 result.capabilities.findings = merged.into_boxed_slice();
197
198 Ok(result)
199}
200
201pub fn determine_analysis_tier(
208 semantic: Option<&SemanticContext>,
209 data_flows: &[DataFlowFact],
210) -> AnalysisTier {
211 match (semantic.is_some(), !data_flows.is_empty()) {
212 (true, true) => AnalysisTier::DataFlow,
213 (true, false) => AnalysisTier::Semantic,
214 (false, _) => AnalysisTier::Syntactic,
215 }
216}
217
218#[cfg(feature = "semantic")]
224fn enrich_reachability(findings: &mut [pedant_types::CapabilityFinding], ctx: &SemanticContext) {
225 use std::collections::BTreeMap;
226 use std::sync::Arc;
227
228 let mut by_file: BTreeMap<Arc<str>, Vec<usize>> = BTreeMap::new();
230 for (idx, finding) in findings.iter().enumerate() {
231 by_file
232 .entry(Arc::clone(&finding.location.file))
233 .or_default()
234 .push(idx);
235 }
236
237 for (file, indices) in &by_file {
238 let Some(analysis) = ctx.analyze_file(file) else {
239 continue;
240 };
241 let lines: Vec<usize> = indices.iter().map(|&i| findings[i].location.line).collect();
242 let results = analysis.check_reachability_batch(&lines);
243 for (pos, &idx) in indices.iter().enumerate() {
244 findings[idx].reachable = Some(results[pos]);
245 }
246 }
247}