Skip to main content

drep/languages/
spec.rs

1//! Language support contract shared by every registered language.
2//!
3//! drep analyzes a file in two layers, and this module is what keeps them free of
4//! per-language conditionals:
5//!
6//! - **Deterministic**: the project's own tools (ruff, eslint, gofmt, clippy).
7//!   They are precise, so their findings can gate a commit.
8//! - **Semantic**: the LLM, told which language it is looking at. It reads any
9//!   language without a parser, so it needs no per-language machinery beyond a
10//!   prompt - which is why adding a language here is a data change, not a
11//!   refactor.
12
13pub const DEFAULT_TOOL_TIMEOUT_SECS: u64 = 120;
14
15/// How to parse the tool's diagnostics into findings.
16///
17/// A fieldless enum rather than a string: `parse_output` dispatches on it, so
18/// a misspelling is a compile error at the definition site instead of a
19/// runtime "no parser for output format" surfacing only when the tool runs.
20/// No `#[non_exhaustive]` - this crate is the only consumer, and the
21/// wildcard arm it forces is exactly the silent-fallback hole the enum
22/// exists to close.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum OutputFormat {
25    Lines,
26    Json,
27    Position,
28    Tsc,
29    Cargo,
30    Sarif,
31    Ktlint,
32    Shellcheck,
33    Rubocop,
34    Phpcs,
35    Credo,
36    Sqlfluff,
37    Msbuild,
38}
39
40impl OutputFormat {
41    /// Whether this format's parser *skips* input it does not recognise
42    /// instead of erroring on it.
43    ///
44    /// The skip parsers exist because their tools interleave chatter among
45    /// the diagnostics (Go's `# pkg` headers, MSBuild's restore noise). The
46    /// price is that a run whose every line is chatter of a new shape - an
47    /// SDK error, a rejected invocation - parses as zero findings on a
48    /// non-empty stream, which is why the runner treats that combination as
49    /// `Unavailable` for these formats and no others. Every other format
50    /// errors on input it cannot parse, so the hole cannot open there.
51    pub fn skips_unmatched_input(self) -> bool {
52        matches!(self, Self::Position | Self::Tsc | Self::Msbuild)
53    }
54}
55
56/// Which process stream carries a tool's diagnostics.
57///
58/// `go vet` writes to stderr, so reading only stdout would report every Go
59/// file clean. An enum because the runner compares it exactly once: a typo'd
60/// string silently selected stdout, which is that same failure.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum DiagnosticsStream {
63    Stdout,
64    Stderr,
65}
66
67/// What a tool is handed on its command line after its own flags.
68///
69/// Anything but [`ToolArguments::Files`] reports on more than the files being checked, so its findings are narrowed back to them. Without that a commit gate would block on pre-existing issues in code the commit never touched.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum ToolArguments {
72    /// The files being checked.
73    Files,
74    /// The Go package directory each file being checked sits in, each once, as `./dir`, after `go list` has said which of the files the build includes.
75    ///
76    /// `go vet` checks a package, and a Go package is a directory. Handed files, it type-checks them as a package of their own: a diff touching one file of a multi-file package reported every symbol its siblings declare as `undefined`, and a diff spanning two directories failed with "named files must all be in one directory". The `./` prefix is what makes `go` read the argument as a path rather than an import path.
77    ///
78    /// A directory is all-or-nothing for the whole call, so `go list -e -json` runs first. A file build constraints exclude (`//go:build tools`, `x_windows.go` on a Mac) is reported in [`ToolOutcome::excluded`](crate::languages::runner::ToolOutcome::excluded) and its directory is left out: `go vet ./tools` on a directory with no buildable file fails, and that failure aborts every other package in the call. A package that fails to load, an unresolvable import say, aborts the call the same way, so its load errors become the findings and vet does not run.
79    GoPackages,
80    /// Nothing: the tool checks its whole project.
81    ///
82    /// `cargo clippy` checks a *crate*, and a path argument is rejected outright with "unexpected argument". Appending files to it therefore made every run fail, so every Rust file came back `Unavailable` and `drep check` exited 2 on any Rust repository - the deterministic half for Rust never ran at all.
83    Project,
84}
85
86/// A deterministic checker for one language.
87#[derive(Debug, Clone, PartialEq)]
88pub struct ToolSpec {
89    /// Tool name, used in logs and finding provenance.
90    pub name: &'static str,
91    /// argv to run, minus the files. The first element is resolved against `local_paths` before PATH.
92    pub command: &'static [&'static str],
93    /// Repo-relative locations to prefer over PATH, so a project gets the
94    /// version its own CI runs (`node_modules/.bin/eslint` rather than
95    /// whatever is installed globally).
96    pub local_paths: &'static [&'static str],
97    /// Repo-relative paths that mean "this project has opted into this tool".
98    /// A tool with none of them present is skipped: its defaults are not the
99    /// project's chosen style, so running it anyway would invent findings the
100    /// project never asked for.
101    pub config_files: &'static [&'static str],
102    /// Flag that hands the discovered config file to the tool, e.g. `"-c"`.
103    ///
104    /// Most checkers find their own config: ruff reads `pyproject.toml` out of
105    /// the working directory without being told. The JVM linters do not.
106    /// `checkstyle` run bare exits 1 with "Must specify a config XML", so
107    /// without this it could not run at all. When set, the config path
108    /// `config_files` already discovered is appended as
109    /// `[config_flag, <path>]` ahead of the file arguments.
110    pub config_flag: Option<&'static str>,
111    /// How to parse the tool's diagnostics into findings.
112    pub output_format: OutputFormat,
113    /// Which stream carries them.
114    pub diagnostics_stream: DiagnosticsStream,
115    /// Wall-clock ceiling for the process. This includes any tool-owned lock
116    /// wait before analysis starts.
117    pub timeout_secs: u64,
118    /// Optional diagnostic suffix explaining a legitimate long wait.
119    pub timeout_context: Option<&'static str>,
120    /// A zero-exit run proves the checked files compiled/typechecked.
121    pub establishes_compilation: bool,
122    /// Whether invocations of this tool must be serialized within a repo.
123    pub serial_in_repository: bool,
124    /// What the tool is handed after its own flags. See [`ToolArguments`].
125    pub arguments: ToolArguments,
126    /// Whether the tool, given files, may also read other files: an import it
127    /// follows (eslint, `go vet`), a sourced script (ShellCheck), a package
128    /// marker whose presence it checks (ruff's `__init__.py`), a schema a
129    /// plugin reads (rubocop-rails' `db/schema.rb`), or code its configuration
130    /// loads (a `.luacheckrc` is a Lua script that can `require` more, and a
131    /// PHPCS ruleset can name custom sniffs).
132    ///
133    /// In staged mode such a tool is refused while any file in the
134    /// repository is uncommitted, since it could read content the commit does
135    /// not hold: an import or a sourced helper can sit outside its workspace,
136    /// under any name, and in another language drep registers. Only a tool that reads nothing but the files it
137    /// is given, as `gofmt` formats each one alone, says false; saying true
138    /// of one that does not only costs a refusal, while saying false of one
139    /// that does lets an uncommitted file decide a commit's lint. A tool not handed exactly its files ([`ToolArguments::GoPackages`] or [`ToolArguments::Project`]) reads beyond them by definition and must say true, which the registry's tests hold.
140    pub reads_other_sources: bool,
141}
142
143impl Default for ToolSpec {
144    fn default() -> Self {
145        Self {
146            name: "",
147            command: &[],
148            local_paths: &[],
149            config_files: &[],
150            config_flag: None,
151            output_format: OutputFormat::Json,
152            diagnostics_stream: DiagnosticsStream::Stdout,
153            timeout_secs: DEFAULT_TOOL_TIMEOUT_SECS,
154            timeout_context: None,
155            establishes_compilation: false,
156            serial_in_repository: false,
157            arguments: ToolArguments::Files,
158            reads_other_sources: true,
159        }
160    }
161}
162
163/// Everything drep needs to know about one language.
164#[derive(Debug, Default, Clone, PartialEq)]
165pub struct LanguageSupport {
166    /// Registry key (lowercase, e.g. `"typescript"`).
167    pub name: &'static str,
168    /// How the language is named to the LLM and to users.
169    pub display_name: &'static str,
170    /// Lowercased suffixes this language owns, including the dot.
171    pub extensions: &'static [&'static str],
172    /// Whole file names this language owns, for files that carry no extension
173    /// at all.
174    ///
175    /// `Path::extension` returns `None` for `Dockerfile`, `Gemfile` and
176    /// `Rakefile`, so an extension-only registry drops them before either
177    /// analysis layer sees them - the same silent pass that unregistered
178    /// `.java` produced, on files most repositories have. Only names a
179    /// registered language actually claims belong here: `Makefile` and
180    /// `Jenkinsfile` are deliberately absent, because no language claims them
181    /// and a name with no owner would still resolve to nothing.
182    /// Matched only when the extension lookup finds nothing, so a name here
183    /// can never shadow a language that claims the suffix.
184    pub filenames: &'static [&'static str],
185    /// Stems that additionally claim their dotted variants, for families like
186    /// `Dockerfile.dev`.
187    ///
188    /// `filenames` claims the exact canonical name; a stem here claims
189    /// `<stem>.<anything>` as well. Multi-image layouts name per-environment
190    /// Dockerfiles `Dockerfile.dev`, `Dockerfile.prod`, `Dockerfile.web` - an
191    /// unbounded family an exact list cannot cover, and hadolint lints the
192    /// variants the same as the canonical file. The extension lookup runs
193    /// first, so `Dockerfile.ts` remains TypeScript, and the variant must
194    /// carry a non-empty suffix after the dot, so `Dockerfile.` itself is
195    /// not claimed.
196    pub filename_prefixes: &'static [&'static str],
197    /// Deterministic checkers, in the order they should run.
198    pub tools: &'static [&'static ToolSpec],
199    /// Language-specific guidance appended to the analysis prompt - the part
200    /// that used to be hardcoded as PEP 8.
201    pub conventions: &'static [&'static str],
202    /// Dependency and build directories this language creates, never
203    /// descended into. Declared here rather than in a global list so adding
204    /// a language stays a single-file change.
205    pub vendored_dirs: &'static [&'static str],
206}