Skip to main content

doris/flows/
lint.rs

1// Copyright lowRISC and contributors.
2// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3// SPDX-License-Identifier: Apache-2.0
4
5//! Lint: a linter checks a design's RTL, as FuseSoC's `lint` target of its
6//! core describes it. See the book's "Lint" chapter.
7
8use 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/// A lint config file, conventionally `lint.hjson`. It belongs to the design
35/// whose `design.hjson` is nearest above it, and lints that design's `core`.
36#[derive(Debug, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct LintConfig {
39    /// Checked by `config::load` before the rest is parsed.
40    #[allow(dead_code)]
41    pub schema: String,
42    /// The tool for each role: `linter`, a name or a list of names. Each
43    /// linter lints the design in a job of its own. A role left out has the
44    /// project file's `tool.lint`.
45    #[serde(default)]
46    pub tool: RoleTools,
47    /// Options for a tool, by its name, then the step it is used in.
48    #[serde(default)]
49    pub tools: ToolOptions,
50    /// The target of the design's core that describes a lint build: its
51    /// filesets, with the waiver files of the linter, its top module and the
52    /// linter's options.
53    #[serde(default = "default_target")]
54    pub target: String,
55    /// Cores to prefer where a virtual core has several providers, such as
56    /// `lowrisc:prim_generic:all`: FuseSoC's `--mapping`.
57    #[serde(default)]
58    pub mappings: Vec<String>,
59    /// Wall-clock limit for the lint step, such as `"30m"`.
60    #[serde(default, deserialize_with = "de_duration")]
61    pub timeout: Option<Duration>,
62    /// What steps hold from the resource pools, by step name: `threads`,
63    /// `memory` and `disk`.
64    #[serde(default)]
65    pub resources: crate::config::Resources,
66    /// Labels for the design's lint jobs, added to the design file's.
67    #[serde(default)]
68    pub tags: Vec<String>,
69}
70
71fn default_target() -> String {
72    "lint".to_owned()
73}
74
75/// The flow's name, on the command line and in the project file's `tool`.
76pub const NAME: &str = "lint";
77
78const LINTER: &str = "linter";
79
80/// Lint has one role: the linter.
81pub const ROLES: &[Role] = &[Role {
82    name: LINTER,
83    capability: Capability::Linter,
84    optional: false,
85}];
86
87impl LintConfig {
88    /// Checks the types can't express: that a linter is bound, each once,
89    /// and is known, given the project file's `tool.lint`. Run at load
90    /// time, so mistakes are found by `doris validate` rather than when a
91    /// job is planned.
92    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    /// The linters the config itself binds, in order.
99    #[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
106/// The lint flow, for one design in one context: a top whose mappings the
107/// design is resolved with, or `None` for the design on its own.
108pub struct Lint<'a> {
109    context: Option<&'a Design>,
110    /// The design's RTL core.
111    core: &'a str,
112}
113
114const LINT_STEP: &str = "lint";
115
116pub struct Job {
117    id: String,
118    design: String,
119    /// The lint config file.
120    config: PathBuf,
121    /// The top a shared design is linted in the context of, if any.
122    context: Option<String>,
123    work: PathBuf,
124    steps: Vec<Step>,
125    /// The step the job was cut short at with `--until`, if it was.
126    until: Option<String>,
127    linter: Arc<dyn Linter>,
128    attrs: crate::select::Attrs,
129}
130
131/// One job per linter bound for the design's lint config, in each of
132/// `contexts`: a top whose mappings the design is resolved with, or `None`
133/// for the design on its own. Filters choose from them.
134pub 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    // `[TOP/]DESIGN@LINTER`: the job ID without the flow. The job's
189    // directory has the same name, with a `.` for the `/`.
190    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    // filelist: the source manager's files for the linter, then flatten:
197    // one argument file.
198    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    // The filelist only names the sources. They are the filelist step's
213    // output, so the lint step reads both.
214    let sources = source_steps.sources();
215    let filelist = source_steps.filelist();
216    let flags = source_steps.flags();
217
218    // lint: the linter, on the sources the filelist step copied.
219    let lint_dir = dir(LINT_STEP);
220    let lint = linter.lint(&LintRequest {
221        dir: lint_dir.clone(),
222        filelist: filelist.path.clone(),
223        // Relative to the lint step's directory, as the paths in the list are.
224        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    // Everything the flatten step wrote: the list, and the flag file and
231    // script of a linter that has them.
232    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    // The logs are outputs, for a person to read: a cached step has the
237    // logs of the run that was stored.
238    let logs = linter.logs();
239    for log in &logs {
240        lint_step = lint_step.output(log, lint_dir.join(log));
241    }
242    // The linter's messages are parsed from its logs once, when the step
243    // completes, with files named from the job's directory. The judge
244    // decides from them, and the result file is written from them.
245    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    // Composite steps become their children before anything names a step.
268    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        // A top's own design names its top already.
281        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/// A job's result file. The reports are made from this, never from logs.
298#[derive(Serialize, Deserialize)]
299pub struct LintResult {
300    pub schema: String,
301    pub dut: String,
302    /// The top a shared design was linted in the context of: its mappings
303    /// chose the cores the design's virtual cores resolved to.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub context: Option<String>,
306    pub tool: ToolNames,
307    /// The version of each tool the job's steps use, by the tool's name.
308    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
309    pub versions: BTreeMap<String, String>,
310    pub produced_by: String,
311    /// The job's tags: the design file's, then the lint config's.
312    #[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    /// Set when the job was stopped early with `--until`: the result covers
319    /// only the steps up to this one.
320    #[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    /// Whether the lint step completed, so that `messages` is everything
326    /// the linter reported. If not, there is nothing to count.
327    pub linted: bool,
328    pub errors: usize,
329    pub warnings: usize,
330    /// What the linter reported, in the order it reported it. Waived
331    /// messages are not here: the linter does not report them.
332    pub messages: Vec<LintMessage>,
333    pub steps: Vec<StepResult>,
334}
335
336impl LintResult {
337    /// How many messages each rule has, most first. Messages with no rule
338    /// are counted together under their severity.
339    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        // Errors first, then by count. The sort is stable, so rules with
352        // the same count stay in the order they were first reported.
353        counts.sort_by_key(|(s, _, n)| (*s != Severity::Error, std::cmp::Reverse(*n)));
354        counts
355    }
356}
357
358/// The output of the lint step that holds what its parse function read
359/// from the linter's logs, and its file in the step's directory.
360const MESSAGES: &str = "messages";
361const MESSAGES_FILE: &str = "messages.json";
362
363/// What the lint step's parse function writes: the linter's messages, and
364/// the log to point at, named from the job's directory.
365#[derive(Serialize, Deserialize)]
366struct Parsed {
367    log: PathBuf,
368    messages: Vec<LintMessage>,
369}
370
371/// What the linter reported in the logs in `lint_dir`.
372///
373/// The linter names files relative to the lint step's directory. They are
374/// rewritten relative to the job's directory, `work`, where a report can
375/// link to them, and which is the same in every checkout. A linter that
376/// names a file by its name only, as AscentLint's report does, names the
377/// source of that name in `sources`, the directory the filelist step copied
378/// them to, if there is one; with none or several, the name is left as it is.
379fn 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
397/// `file`, as a linter running in `lint_dir` named it, relative to `work`.
398/// `by_name` is every file in `sources` by its name, found the first time
399/// a bare name needs it.
400fn 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
421/// Whether `file` is a file's name and nothing else.
422fn 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
430/// Every file below `dir`, by its name.
431fn 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    /// What the linter reported, if the lint step completed in this job, or
452    /// `None` if it did not: the messages its parse function wrote. They
453    /// are an output of the step, so a cached step has those of the run
454    /// that was stored.
455    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
468/// `file`, as a linter running in `step_dir` named it, relative to
469/// `job_dir`. A file outside the job's directory is left as it was named.
470fn 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        // Outside the job's directory: as the linter named it.
561        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        // Two sources of the name, or none: left as the linter named it.
585        assert_eq!(named("pkg.sv"), Path::new("pkg.sv"));
586        assert_eq!(named("gone.sv"), Path::new("gone.sv"));
587        // A file in the lint step's directory is that file.
588        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}