Skip to main content

lint_lang/
lib.rs

1//! # lint_lang
2//!
3//! A lint framework: named, configurable rules that run over a syntax tree and
4//! report what they find as diagnostics.
5//!
6//! A compiler's checks fall into two groups. Some are hard errors the language
7//! defines — a type mismatch, an unresolved name. Others are judgements: code
8//! that is legal but almost certainly a mistake, needlessly complex, or against a
9//! project's style. Those belong in a linter, where each check is a separate rule
10//! the user can turn up to an error, down to a warning, or off entirely.
11//! lint-lang is the machinery for that second group. It owns no rules and no
12//! grammar; a language supplies both, and lint-lang runs the rules, applies the
13//! user's configuration, and collects the results.
14//!
15//! ## The model
16//!
17//! - A [`Rule`] is one check. It has a stable [`name`](Rule::name), a
18//!   [`default_level`](Rule::default_level), and a [`check`](Rule::check) that
19//!   inspects one node and reports problems.
20//! - A [`Level`] — [`Allow`](Level::Allow), [`Warn`](Level::Warn), or
21//!   [`Deny`](Level::Deny) — is how strictly a rule is applied.
22//! - A [`Linter`] holds the registered rules and their levels, and runs them all
23//!   over a tree in a **single walk**.
24//! - A [`Context`] is what a rule sees while checking a node: the arena, the
25//!   node's ancestors and depth, and the [`report`](Context::report) call.
26//! - A [`Finding`] is one reported problem: a [`Diagnostic`] tagged with the rule
27//!   that produced it.
28//!
29//! Trees are the ones [`ast_lang`] defines: nodes of any type implementing
30//! [`Node`], stored in an [`Arena`] and linked by [`Id`] handles. Findings are
31//! [`diag_lang`] diagnostics, so they render with source context through the same
32//! renderer as every other error the compiler produces.
33//!
34//! ## Example
35//!
36//! A two-variant expression type and a rule that flags adding zero.
37//!
38//! ```
39//! use lint_lang::{Arena, Context, Id, Label, Level, Linter, Node, Rule, Span};
40//!
41//! enum Expr {
42//!     Int(i64, Span),
43//!     Add(Id<Expr>, Id<Expr>, Span),
44//! }
45//!
46//! impl Node for Expr {
47//!     fn span(&self) -> Span {
48//!         match self {
49//!             Expr::Int(_, s) | Expr::Add(_, _, s) => *s,
50//!         }
51//!     }
52//!     fn each_child(&self, f: &mut dyn FnMut(Id<Self>)) {
53//!         if let Expr::Add(a, b, _) = self {
54//!             f(*a);
55//!             f(*b);
56//!         }
57//!     }
58//!     fn map_children(&self, f: &mut dyn FnMut(Id<Self>) -> Id<Self>) -> Self {
59//!         match self {
60//!             Expr::Int(v, s) => Expr::Int(*v, *s),
61//!             Expr::Add(a, b, s) => Expr::Add(f(*a), f(*b), *s),
62//!         }
63//!     }
64//! }
65//!
66//! struct AddZero;
67//! impl Rule<Expr> for AddZero {
68//!     fn name(&self) -> &'static str {
69//!         "add-zero"
70//!     }
71//!     fn check(&self, node: &Expr, cx: &mut Context<'_, Expr>) {
72//!         let Expr::Add(a, b, span) = node else { return };
73//!         let arena = cx.arena();
74//!         let is_zero = |id: &Id<Expr>| matches!(arena.get(*id), Some(Expr::Int(0, _)));
75//!         if is_zero(a) || is_zero(b) {
76//!             cx.report("adding zero has no effect", Label::new(*span, "this addition"));
77//!         }
78//!     }
79//! }
80//!
81//! // `x + 0`, with `x` = 9
82//! let mut arena = Arena::new();
83//! let x = arena.alloc(Expr::Int(9, Span::new(0, 1)));
84//! let zero = arena.alloc(Expr::Int(0, Span::new(4, 5)));
85//! let sum = arena.alloc(Expr::Add(x, zero, Span::new(0, 5)));
86//!
87//! let mut linter = Linter::new();
88//! linter.register(AddZero)?;
89//!
90//! let findings = linter.run(&arena, sum);
91//! assert_eq!(findings.len(), 1);
92//! assert_eq!(findings[0].to_string(), "warning[add-zero]: adding zero has no effect");
93//!
94//! // The user decides how seriously to take it.
95//! linter.set_level("add-zero", Level::Deny)?;
96//! assert!(linter.run(&arena, sum)[0].is_error());
97//! # Ok::<(), lint_lang::LintError>(())
98//! ```
99//!
100//! ## Performance
101//!
102//! A run is one iterative depth-first walk, whatever the number of rules: each
103//! node is visited once and handed to every enabled rule in turn. Disabled rules
104//! are never called, a linter with nothing enabled does not walk at all, and the
105//! only allocations a run makes are the walk's own stacks and the findings
106//! themselves. [`Linter::run_into`] reuses a caller's buffer across runs.
107//!
108//! ## Features
109//!
110//! - `std` (default) — the standard library. Without it the crate is
111//!   `#![no_std]` and needs only `alloc`. Forwards to `ast-lang/std` and
112//!   `diag-lang/std`.
113//! - `serde` — `Serialize` and `Deserialize` for [`Level`], as the lowercase
114//!   strings `"allow"`, `"warn"`, and `"deny"`, so rule levels can be read straight
115//!   from a configuration file.
116//!
117//! ## Stability
118//!
119//! The public surface is frozen and stable as of `1.0.0`: it follows Semantic
120//! Versioning, with no breaking changes before `2.0`. The full surface, the
121//! behavioural guarantees, and the SemVer promise are catalogued in
122//! [`docs/API.md`](https://github.com/jamesgober/lint-lang/blob/main/docs/API.md#stability).
123
124#![cfg_attr(not(feature = "std"), no_std)]
125#![cfg_attr(docsrs, feature(doc_cfg))]
126#![forbid(unsafe_code)]
127#![deny(
128    warnings,
129    missing_docs,
130    unsafe_op_in_unsafe_fn,
131    unused_must_use,
132    unused_results,
133    clippy::unwrap_used,
134    clippy::expect_used,
135    clippy::panic,
136    clippy::todo,
137    clippy::unimplemented,
138    clippy::unreachable,
139    clippy::dbg_macro,
140    clippy::print_stdout,
141    clippy::print_stderr,
142    clippy::undocumented_unsafe_blocks
143)]
144
145extern crate alloc;
146
147mod context;
148mod error;
149mod finding;
150mod level;
151mod linter;
152mod rule;
153
154// Re-exported so a downstream defining rules can name the tree and diagnostic
155// types this crate's API is built on without also depending on `ast-lang` and
156// `diag-lang` directly. Both crates share one `span-lang`, so a node's `Span`
157// labels a diagnostic with no conversion.
158pub use ast_lang::{Arena, Id, Node, Span};
159pub use context::Context;
160pub use diag_lang::{Diagnostic, Label, Severity};
161pub use error::LintError;
162pub use finding::Finding;
163pub use level::Level;
164pub use linter::Linter;
165pub use rule::Rule;
166
167/// Compiles and runs the `rust` code blocks in `README.md` and `docs/API.md` as
168/// part of `cargo test`, so the published examples cannot drift from the API.
169///
170/// Present only while collecting doctests (`#[cfg(doctest)]`); it is not part of
171/// the public surface and does not appear in the built library or its docs.
172#[cfg(doctest)]
173#[doc = include_str!("../README.md")]
174#[doc = include_str!("../docs/API.md")]
175pub struct MarkdownDocTests;