1use std::collections::{BTreeMap, HashMap};
9use std::ffi::OsString;
10use std::fs;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13use std::time::Duration;
14
15use anyhow::{Context, Result};
16use serde::{Deserialize, Serialize};
17
18use crate::config::{RoleTools, ToolOptions, de_duration, resolve_path};
19use crate::exec::StepReport;
20use crate::flows::{self, Bindings, Role, StepResult, step_results};
21use crate::repo::{Design, Repo, Scope};
22use crate::step::{Judging, Outcome, ParseFn, Step};
23use crate::tools::{
24 self, Capability, LintMessage, LintRequest, Linter, Severity, ToolEnv, lint_counts, sources,
25};
26use crate::tops;
27
28pub mod report;
29
30pub const SCHEMA: &str = "dv/lint/1";
31
32pub const RESULT_SCHEMA: &str = "dv/lint-result/1";
33
34#[derive(Debug, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct LintConfig {
39 #[allow(dead_code)]
41 pub schema: String,
42 #[serde(default)]
46 pub tool: RoleTools,
47 #[serde(default)]
49 pub tools: ToolOptions,
50 #[serde(default = "default_target")]
54 pub target: String,
55 #[serde(default)]
58 pub mappings: Vec<String>,
59 #[serde(default, deserialize_with = "de_duration")]
61 pub timeout: Option<Duration>,
62 #[serde(default)]
65 pub resources: crate::config::Resources,
66 #[serde(default)]
68 pub tags: Vec<String>,
69}
70
71fn default_target() -> String {
72 "lint".to_owned()
73}
74
75pub const NAME: &str = "lint";
77
78const LINTER: &str = "linter";
79
80pub const ROLES: &[Role] = &[Role {
82 name: LINTER,
83 capability: Capability::Linter,
84 optional: false,
85}];
86
87impl LintConfig {
88 pub fn validate(&self, defaults: Option<&RoleTools>) -> Result<()> {
93 flows::bound(NAME, ROLES, &self.tool, defaults)?;
94 crate::config::check_tags(&self.tags)?;
95 self.tools.check(NAME, &[Capability::Linter])
96 }
97
98 #[cfg(test)]
100 pub fn linters(&self) -> Vec<String> {
101 let bound = flows::bound(NAME, ROLES, &self.tool, None).unwrap();
102 bound.into_iter().flat_map(|(_, tools)| tools).collect()
103 }
104}
105
106pub struct Lint<'a> {
109 context: Option<&'a Design>,
110 core: &'a str,
112}
113
114const LINT_STEP: &str = "lint";
115
116pub struct Job {
117 id: String,
118 design: String,
119 config: PathBuf,
121 context: Option<String>,
123 work: PathBuf,
124 steps: Vec<Step>,
125 until: Option<String>,
127 linter: Arc<dyn Linter>,
128 attrs: crate::select::Attrs,
129}
130
131pub fn plan(repo: &Repo, design: &Design, contexts: &[Option<&Design>]) -> Result<Vec<Job>> {
135 let cfg = design
136 .lint
137 .as_ref()
138 .map(|f| &f.config)
139 .with_context(|| format!("design `{}` has no lint config", design.name))?;
140 let core = design.core.as_deref().with_context(|| {
141 format!(
142 "design `{}` has no `core` to lint; set it in {}",
143 design.name,
144 design.file.display()
145 )
146 })?;
147 let mut jobs = Vec::new();
148 for &context in contexts {
149 let flow = Lint { context, core };
150 jobs.extend(flows::plan_jobs(&flow, repo, design, cfg, &cfg.tool)?);
151 }
152 Ok(jobs)
153}
154
155impl flows::Flow for Lint<'_> {
156 type Config = LintConfig;
157 type Job = Job;
158
159 fn name(&self) -> &'static str {
160 NAME
161 }
162
163 fn roles(&self) -> &'static [Role] {
164 ROLES
165 }
166
167 fn plan(
168 &self,
169 repo: &Repo,
170 design: &Design,
171 cfg: &LintConfig,
172 tools: &Bindings,
173 ) -> Result<Job> {
174 let linter = tools::linter(tools.tool(LINTER)?, &cfg.tools)?;
175 plan_job(repo, design, self.context, cfg, self.core, linter, tools)
176 }
177}
178
179fn plan_job(
180 repo: &Repo,
181 design: &Design,
182 context: Option<&Design>,
183 cfg: &LintConfig,
184 core: &str,
185 linter: Arc<dyn Linter>,
186 tools: &Bindings,
187) -> Result<Job> {
188 let job_design = tops::job_design(context, design);
191 let id = format!("lint/{job_design}@{}", tools.label());
192 let name = format!("{}@{}", tops::dir_name(&job_design), tools.label());
193 let work = repo.work_dir().join("lint").join(name);
194 let dir = |step: &str| work.join(step);
195
196 let mappings = tops::mappings(context, design, &cfg.mappings);
199 let source_manager = tools::source_manager(sources::SOURCE_MANAGER, &cfg.tools)?;
200 let source_steps = sources::steps(
201 source_manager.as_ref(),
202 &sources::Setup {
203 core,
204 target: &cfg.target,
205 format: linter.backend(),
206 mappings: &mappings,
207 top: design.top.clone(),
208 },
209 &work,
210 &repo.cores_root,
211 )?;
212 let sources = source_steps.sources();
215 let filelist = source_steps.filelist();
216 let flags = source_steps.flags();
217
218 let lint_dir = dir(LINT_STEP);
220 let lint = linter.lint(&LintRequest {
221 dir: lint_dir.clone(),
222 filelist: filelist.path.clone(),
223 flag_file: flags
225 .as_ref()
226 .map(|f| crate::tree::relative_to(&f.path, &lint_dir))
227 .unwrap_or_default(),
228 top: design.top.clone(),
229 })?;
230 let mut lint_step = Step::exec(LINT_STEP, lint_dir.clone(), lint.invocation).reads(&sources);
233 for flattened in source_steps.flattened() {
234 lint_step = lint_step.reads(&flattened);
235 }
236 let logs = linter.logs();
239 for log in &logs {
240 lint_step = lint_step.output(log, lint_dir.join(log));
241 }
242 let parse: ParseFn = {
246 let (linter, work, sources) = (linter.clone(), work.clone(), sources.path.clone());
247 Arc::new(move |dir: &Path| {
248 let parsed = Parsed {
249 log: job_relative(&tools::lint_log(dir, &logs), dir, &work),
250 messages: parse_messages(linter.as_ref(), &logs, dir, &sources, &work)?,
251 };
252 Ok(serde_json::to_value(parsed)?)
253 })
254 };
255 lint_step = lint_step.parsed(MESSAGES, lint_dir.join(MESSAGES_FILE), parse);
256 lint_step.timeout = cfg.timeout;
257 lint_step.complete_on = lint.complete_on;
258 let (judge, job_dir) = (lint.judge, work.clone());
259 lint_step.judge = Some(Arc::new(move |j: &Judging| {
260 let parsed: Parsed = match j.parsed.map(|p| serde_json::from_value(p.clone())) {
261 Some(Ok(parsed)) => parsed,
262 _ => return Outcome::StepError("the linter's messages were not parsed".into()),
263 };
264 judge(&parsed.messages, j.code, &job_dir.join(&parsed.log))
265 }));
266
267 let mut steps =
269 crate::group::flatten(vec![source_steps.setup, source_steps.flatten, lint_step])?;
270 flows::apply_resources(&mut steps, &cfg.resources, &[], &crate::tools::names()?)?;
271
272 Ok(Job {
273 id,
274 design: design.qualified(),
275 config: design
276 .lint
277 .as_ref()
278 .map(|f| f.file.clone())
279 .unwrap_or_default(),
280 context: context
282 .filter(|_| design.scope == Scope::Shared)
283 .map(|top| top.name.clone()),
284 work,
285 steps,
286 until: None,
287 linter,
288 attrs: flows::attrs(NAME, design, context, tools.roles(), &cfg.tags),
289 })
290}
291
292#[derive(Clone, Serialize, Deserialize)]
293pub struct ToolNames {
294 pub linter: String,
295}
296
297#[derive(Serialize, Deserialize)]
299pub struct LintResult {
300 pub schema: String,
301 pub dut: String,
302 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub context: Option<String>,
306 pub tool: ToolNames,
307 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
309 pub versions: BTreeMap<String, String>,
310 pub produced_by: String,
311 #[serde(default, skip_serializing_if = "Vec::is_empty")]
313 pub tags: Vec<String>,
314 #[serde(skip_serializing_if = "Option::is_none")]
315 pub revision: Option<String>,
316 pub timestamp: String,
317 pub job: String,
318 #[serde(skip_serializing_if = "Option::is_none")]
321 pub until: Option<String>,
322 pub outcome: String,
323 #[serde(skip_serializing_if = "Option::is_none")]
324 pub message: Option<String>,
325 pub linted: bool,
328 pub errors: usize,
329 pub warnings: usize,
330 pub messages: Vec<LintMessage>,
333 pub steps: Vec<StepResult>,
334}
335
336impl LintResult {
337 pub fn by_rule(&self) -> Vec<(Severity, Option<&str>, usize)> {
340 let mut counts: Vec<(Severity, Option<&str>, usize)> = Vec::new();
341 for m in &self.messages {
342 let rule = m.rule.as_deref();
343 match counts
344 .iter_mut()
345 .find(|(s, r, _)| *s == m.severity && *r == rule)
346 {
347 Some((_, _, n)) => *n += 1,
348 None => counts.push((m.severity, rule, 1)),
349 }
350 }
351 counts.sort_by_key(|(s, _, n)| (*s != Severity::Error, std::cmp::Reverse(*n)));
354 counts
355 }
356}
357
358const MESSAGES: &str = "messages";
361const MESSAGES_FILE: &str = "messages.json";
362
363#[derive(Serialize, Deserialize)]
366struct Parsed {
367 log: PathBuf,
368 messages: Vec<LintMessage>,
369}
370
371fn parse_messages(
380 linter: &dyn Linter,
381 logs: &[String],
382 lint_dir: &Path,
383 sources: &Path,
384 work: &Path,
385) -> Result<Vec<LintMessage>> {
386 let log = tools::read_logs(lint_dir, logs);
387 let mut messages = linter.parse(&log)?;
388 let mut by_name = None;
389 for m in &mut messages {
390 if let Some(file) = &mut m.file {
391 *file = job_file(file, lint_dir, sources, work, &mut by_name);
392 }
393 }
394 Ok(messages)
395}
396
397fn job_file(
401 file: &Path,
402 lint_dir: &Path,
403 sources: &Path,
404 work: &Path,
405 by_name: &mut Option<HashMap<OsString, Vec<PathBuf>>>,
406) -> PathBuf {
407 if !is_bare_name(file) || lint_dir.join(file).exists() {
408 return job_relative(file, lint_dir, work);
409 }
410 let by_name = by_name.get_or_insert_with(|| files_by_name(sources));
411 match file
412 .file_name()
413 .and_then(|n| by_name.get(n))
414 .map(Vec::as_slice)
415 {
416 Some([source]) => job_relative(source, lint_dir, work),
417 _ => file.to_owned(),
418 }
419}
420
421fn is_bare_name(file: &Path) -> bool {
423 let mut parts = file.components();
424 matches!(
425 (parts.next(), parts.next()),
426 (Some(std::path::Component::Normal(_)), None)
427 )
428}
429
430fn files_by_name(dir: &Path) -> HashMap<OsString, Vec<PathBuf>> {
432 let mut found: HashMap<OsString, Vec<PathBuf>> = HashMap::new();
433 let mut dirs = vec![dir.to_owned()];
434 while let Some(dir) = dirs.pop() {
435 let Ok(entries) = fs::read_dir(&dir) else {
436 continue;
437 };
438 for entry in entries.flatten() {
439 let path = entry.path();
440 match entry.file_type() {
441 Ok(t) if t.is_dir() => dirs.push(path),
442 Ok(_) => found.entry(entry.file_name()).or_default().push(path),
443 Err(_) => {}
444 }
445 }
446 }
447 found
448}
449
450impl Job {
451 fn messages(&self, reports: &[StepReport]) -> Option<Vec<LintMessage>> {
456 let completed = reports.iter().any(|r| {
457 r.name == LINT_STEP && matches!(r.outcome, Outcome::Passed | Outcome::Failed(_))
458 });
459 if !completed {
460 return None;
461 }
462 let file = self.work.join(LINT_STEP).join(MESSAGES_FILE);
463 let parsed: Parsed = serde_json::from_slice(&fs::read(file).ok()?).ok()?;
464 Some(parsed.messages)
465 }
466}
467
468fn job_relative(file: &Path, step_dir: &Path, job_dir: &Path) -> PathBuf {
471 resolve_path(step_dir, file)
472 .strip_prefix(job_dir)
473 .map(Path::to_owned)
474 .unwrap_or_else(|_| file.to_owned())
475}
476
477impl flows::Job for Job {
478 fn id(&self) -> &str {
479 &self.id
480 }
481
482 fn attrs(&self) -> &crate::select::Attrs {
483 &self.attrs
484 }
485
486 fn work_dir(&self) -> &std::path::Path {
487 &self.work
488 }
489
490 fn design(&self) -> &str {
491 &self.design
492 }
493
494 fn config(&self) -> &std::path::Path {
495 &self.config
496 }
497
498 fn steps(&self) -> &[Step] {
499 &self.steps
500 }
501
502 fn stop_after(&mut self, step: &str) -> Result<()> {
503 flows::prune(&mut self.steps, step)?;
504 self.until = Some(step.to_owned());
505 Ok(())
506 }
507
508 fn write_result(
509 &self,
510 repo: &Repo,
511 reports: &[StepReport],
512 tools: &ToolEnv,
513 ) -> Result<(Outcome, PathBuf)> {
514 let worst = flows::worst(reports);
515 let messages = self.messages(reports);
516 let linted = messages.is_some();
517 let messages = messages.unwrap_or_default();
518 let (errors, warnings) = lint_counts(&messages);
519 let result = LintResult {
520 schema: RESULT_SCHEMA.to_owned(),
521 dut: self.design.clone(),
522 context: self.context.clone(),
523 tool: ToolNames {
524 linter: self.linter.name().to_owned(),
525 },
526 versions: flows::tool_versions(&self.steps, tools),
527 produced_by: format!("doris {}", env!("CARGO_PKG_VERSION")),
528 tags: self.attrs.tags.clone(),
529 revision: flows::git_revision(&repo.root),
530 timestamp: flows::timestamp(),
531 job: self.id.clone(),
532 until: self.until.clone(),
533 outcome: worst.label().to_owned(),
534 message: worst.message().map(str::to_owned),
535 linted,
536 errors,
537 warnings,
538 messages,
539 steps: step_results(reports),
540 };
541 fs::create_dir_all(&self.work)?;
542 let path = self.work.join("result.json");
543 crate::tree::write_atomic(&path, serde_json::to_string_pretty(&result)? + "\n")?;
544 Ok((worst, path))
545 }
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551
552 #[test]
553 fn files_are_named_from_the_job_directory() {
554 let job = Path::new("/w/lint/aes");
555 let rel = |f: &str| job_relative(Path::new(f), &job.join("lint"), job);
556 assert_eq!(
557 rel("../filelist/work/src/aes_0/rtl/aes.sv"),
558 Path::new("filelist/work/src/aes_0/rtl/aes.sv")
559 );
560 assert_eq!(rel("/opt/lib/prim.sv"), Path::new("/opt/lib/prim.sv"));
562 assert_eq!(rel("../../../x.sv"), Path::new("../../../x.sv"));
563 }
564
565 #[test]
566 fn a_bare_name_is_the_one_source_of_that_name() {
567 let job = std::env::temp_dir().join(format!("doris-lint-names-{}", std::process::id()));
568 let sources = job.join("filelist/work");
569 let lint = job.join("lint");
570 for f in [
571 "src/a_0/rtl/a.sv",
572 "src/b_0/rtl/pkg.sv",
573 "src/c_0/rtl/pkg.sv",
574 ] {
575 let f = sources.join(f);
576 fs::create_dir_all(f.parent().unwrap()).unwrap();
577 fs::write(f, "").unwrap();
578 }
579 fs::create_dir_all(&lint).unwrap();
580 fs::write(lint.join("here.sv"), "").unwrap();
581 let mut by_name = None;
582 let mut named = |f: &str| job_file(Path::new(f), &lint, &sources, &job, &mut by_name);
583 assert_eq!(named("a.sv"), Path::new("filelist/work/src/a_0/rtl/a.sv"));
584 assert_eq!(named("pkg.sv"), Path::new("pkg.sv"));
586 assert_eq!(named("gone.sv"), Path::new("gone.sv"));
587 assert_eq!(named("here.sv"), Path::new("lint/here.sv"));
589 assert_eq!(
590 named("../filelist/work/src/c_0/rtl/pkg.sv"),
591 Path::new("filelist/work/src/c_0/rtl/pkg.sv")
592 );
593 fs::remove_dir_all(&job).unwrap();
594 }
595}