Skip to main content

big_code_analysis/
lib.rs

1// Per-language metric and AST modules deliberately consume the macro-
2// generated tree-sitter token enums via `use crate::*` and `use Foo::*`
3// inside match expressions — explicit imports would list dozens of
4// variants per arm and obscure the per-language token sets that are the
5// point of these files. Allowed at the module level rather than per
6// function so the per-language impl blocks stay readable.
7#![allow(clippy::doc_markdown, clippy::enum_glob_use, clippy::wildcard_imports)]
8// Per-language Cargo features (commit 7e96b466) let a downstream build
9// only a subset of grammars. In such a build the code for the disabled
10// languages — their macro-generated `*Code` / `*Parser` tags plus the
11// getter / checker / metric helpers and shared plumbing only those
12// languages reach — is compiled but never constructed, so `-D dead-code`
13// fires on ~180 items that are all live in the default `all-languages`
14// build. Relax dead-code to a warning only when the full language set is
15// NOT enabled; the default build and `--all-features` (and thus the
16// primary CI gate and `make pre-commit`) still hard-deny it, so genuine
17// dead code is caught there. Fixes the long-red `features
18// (no-default-features / minimal-langs (lib))` CI legs.
19#![cfg_attr(not(feature = "all-languages"), allow(dead_code))]
20// docs.rs (and the local `doc-check-docsrs` gate) build with `--cfg docsrs`
21// on nightly, enabling per-item "Available on crate feature …" badges for
22// non-default surfaces such as `vcs`. Guarded so stable builds are unaffected.
23#![cfg_attr(docsrs, feature(doc_cfg))]
24
25//! big-code-analysis is a library to analyze and extract information
26//! from source codes written in many different programming languages.
27//!
28//! You can find the source code of this software on
29//! <a href="https://github.com/dekobon/big-code-analysis/" target="_blank">GitHub</a>,
30//! while issues and feature requests can be posted on the respective
31//! <a href="https://github.com/dekobon/big-code-analysis/issues/" target="_blank">GitHub Issue Tracker</a>.
32//!
33//! ## Quick start
34//!
35//! Most callers want the recommended entry points exposed in
36//! [`prelude`]:
37//!
38//! ```no_run
39//! use big_code_analysis::prelude::*;
40//!
41//! let source = b"fn main() {}";
42//! let space = analyze(
43//!     Source::new(LANG::Rust, source),
44//!     MetricsOptions::default(),
45//! ).expect("Rust source parses");
46//! println!("cognitive sum: {}", space.metrics.cognitive.cognitive_sum());
47//! ```
48//!
49//! ## Supported Languages
50//!
51//! Each grammar is gated behind a per-language Cargo feature; the
52//! default `all-languages` feature enables every grammar so the
53//! historical "every language compiled in" behaviour is preserved.
54//! Library consumers that only need a subset can opt out of the
55//! defaults — see [Per-language Cargo features][feat] in the book.
56//!
57//! - Bash (`bash`)
58//! - C (`c`, upstream `tree-sitter-c`; owns `.c`)
59//! - C/C++ (`cpp`, upstream `tree-sitter-cpp`; the default for `.cpp` /
60//!   `.cc` / `.h` and also exposes the internal `ccomment` / `preproc`
61//!   C-family helpers)
62//! - C++, Firefox-internal "Mozcpp" (`mozcpp`, opt-in; owns no file
63//!   extensions — select it by name)
64//! - C# (`csharp`)
65//! - Objective-C (`objc`, upstream `tree-sitter-objc`; owns `.m`; `.mm`
66//!   Objective-C++ stays on C/C++)
67//! - Elixir (`elixir`)
68//! - Go (`go`)
69//! - Groovy (`groovy`)
70//! - F5 iRules (`irules`)
71//! - Java (`java`)
72//! - JavaScript (`javascript`)
73//! - JavaScript, Firefox-internal "MozJS" (`mozjs`)
74//! - Kotlin (`kotlin`)
75//! - Lua (`lua`)
76//! - Perl (`perl`)
77//! - PHP (`php`)
78//! - Python (`python`)
79//! - Ruby (`ruby`)
80//! - Rust (`rust`)
81//! - Tcl (`tcl`)
82//! - TSX (`tsx`)
83//! - TypeScript (`typescript`)
84//!
85//! [feat]: https://dekobon.github.io/big-code-analysis/library/cargo-features.html
86//!
87//! ## Supported Metrics
88//!
89//! - ABC: it measures the size of a source code based on
90//!   assignments, branches, and conditions.
91//! - CC: it calculates the code complexity examining the control flow of a
92//!   program.  Both standard and modified flavours are exposed: the
93//!   modified variant collapses all case/match arms inside a single
94//!   switch/match/when/select into one decision point.
95//! - Cognitive Complexity: it measures how difficult it is
96//!   to understand a unit of code.
97//! - SLOC: it counts the number of lines in a source file.
98//! - PLOC: it counts the number of physical lines (instructions)
99//!   contained in a source file.
100//! - LLOC: it counts the number of logical lines (statements)
101//!   contained in a source file.
102//! - CLOC: it counts the number of comments in a source file.
103//! - BLANK: it counts the number of blank lines in a source file.
104//! - HALSTEAD: it is a suite that provides a series of information,
105//!   such as the effort required to maintain the analyzed code,
106//!   the size in bits to store the program, the difficulty to understand
107//!   the code, an estimate of the number of bugs present in the codebase,
108//!   and an estimate of the time needed to implement the software.
109//! - MI: it is a suite that allows to evaluate the maintainability
110//!   of a software.
111//! - NOM: it counts the number of functions and closures
112//!   in a file/trait/class.
113//! - NEXITS: it counts the number of possible exit points
114//!   from a method/function.
115//! - NARGS: it counts the number of arguments of a function/method.
116//! - NPA: it counts the number of public attributes of a class.
117//! - NPM: it counts the number of public methods of a class.
118//! - WMC: it is the sum of the complexities of all methods
119//!   in a class.
120
121#![allow(clippy::upper_case_acronyms)]
122// Production-only `unwrap()` ban. See `[workspace.lints.clippy]` in the
123// root `Cargo.toml` for why this is a per-root attribute and not a
124// Cargo lint (#1227).
125#![cfg_attr(not(test), warn(clippy::unwrap_used))]
126// The parse and classification layer lives in `big-code-analysis-ast`
127// (#1376). Its public names — the generated token enums, the `*Code` /
128// `*Parser` tags, `Node`, `Ancestors`, `Checker`, `Getter`, the language
129// helpers — are the working vocabulary every metric module reaches
130// through `use crate::*`, so the whole crate root is glob-imported here
131// at `pub(crate)`. Only the explicit `pub use` lines further down widen
132// the published surface.
133
134// The import half of the `allow(dead_code)` carve-out above, and for
135// the same reason: per-language test gating (#1472) makes "is this
136// import live" a function of the enabled feature set, which no `cfg` on
137// the import itself can express. Partial builds only — `all-languages`
138// is on by default and under `--all-features`, so the build CI gates on
139// and the one a contributor runs still police every unused import. See
140// `.claude/rules/testing.md`, "Why the import lint is off on a partial
141// build".
142#![cfg_attr(not(feature = "all-languages"), allow(unused_imports))]
143#[doc(hidden)]
144pub(crate) use big_code_analysis_ast::*;
145
146// Fast hashing for the walk's integer-keyed maps. Shared by `spaces`
147// (node ids) and `metrics::halstead` (grammar `kind_id`s); `metrics::loc`
148// was the third until #1109 moved its line sets to a bitset. The module
149// doc is the single place that lists them and says why the text-keyed
150// collections are excluded — extend it, not this line, when a third
151// arrives.
152mod int_hash;
153// The metric-side macros (`implement_metric_trait!`) plus re-exports of
154// the kind-set and dispatch macros defined in `big-code-analysis-ast`.
155mod macros;
156// Parse-and-inspect shims shared by the per-metric test modules. Kept out
157// of any production file so the self-scan gate does not spend a shipping
158// module's metric budget on test-only code (#1066).
159#[cfg(test)]
160mod test_support;
161// Gated on the four grammars its tables name, so a build enabling none
162// of them drops the module rather than tripping its `checked > 0`
163// non-vacuity guard (`.claude/rules/testing.md`, #1286). The guard then
164// covers only the residual case where `is_enabled` stops agreeing with
165// the feature it compiled under.
166#[cfg(test)]
167#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))]
168mod c_family_space_names_tests;
169// Drift guard for the crate-level `## Supported Languages` list above.
170#[cfg(test)]
171mod lib_docs_tests;
172#[cfg(test)]
173mod observation_tests;
174
175// --- Language identification (defined in `big-code-analysis-ast`) ---
176pub use big_code_analysis_ast::{LANG, ParseLangError, get_from_emacs_mode, get_from_ext};
177
178// Hand-written modules (`src/spaces.rs`, `src/output/dump_metrics.rs`,
179// the metric macros) refer to per-metric submodules by their short
180// crate-root path (`crate::abc`, `crate::cognitive`, ...). Re-export
181// them under those names without widening the public surface.
182pub(crate) use crate::metrics::{
183    abc, cognitive, cyclomatic, halstead, loc, mi, nargs, nexits, nom, npa, npm, tokens, wmc,
184};
185
186// Module declarations. Each `pub use` line below names exactly the
187// items intended to be part of the public API surface; anything not
188// listed stays out of the crate root. Per issue #255, glob re-exports
189// (`pub use module::*`) are no longer used here because every newly
190// `pub`-marked helper in any sub-module would silently leak into the
191// published API.
192
193// --- Core analysis entry points and result types (spaces.rs) ---
194mod spaces;
195pub use crate::spaces::{Ast, CodeMetrics, FuncSpace, MetricsOptions, Source, SpaceKind, analyze};
196
197/// Per-metric implementations.
198///
199/// Each sub-module owns one metric — its `Stats` accumulator, the
200/// per-language trait implementations, and any small helpers used
201/// only by tests. Most callers will not need these directly; reach
202/// through [`CodeMetrics`] on a [`FuncSpace`] instead.
203pub mod metrics;
204
205/// Plain, `Deserialize`-capable data-transfer structs mirroring the
206/// serialized metric wire shape. The compute types' `Serialize` impls
207/// delegate here, making these the single definition of the JSON / YAML /
208/// TOML / CBOR output format and the canonical way to read `bca` output
209/// back (`serde_json::from_str::<wire::FuncSpace>(…)`).
210pub mod wire;
211
212// --- Change-history (VCS) metrics ---
213//
214// The project's first language-agnostic, non-AST metric family
215// (issue #328). Gated behind the `vcs-git` backend feature (the
216// `vcs` umbrella turns it on); the generic surface is backend-neutral
217// so future backends (#335) reuse it unchanged.
218/// Change-history (VCS) metrics derived from version-control history:
219/// churn, commit frequency, author count / ownership dilution, bug- and
220/// security-fix history, and an ordinal composite risk score. See
221/// [`vcs::build_history_index`].
222///
223/// Enable with the `vcs` Cargo feature (the umbrella over the current
224/// `vcs-git` backend, which is what the availability badge names).
225#[cfg(feature = "vcs-git")]
226#[cfg_attr(docsrs, doc(cfg(feature = "vcs-git")))]
227pub mod vcs;
228
229// --- Diagnostics ---
230//
231// The single place the library writes a `warning:` prefix; the CLI has
232// its own severity ladder in `big-code-analysis-cli/src/diag.rs`.
233mod diag;
234
235// --- Errors ---
236//
237// `MetricsError` is the parse layer's error (every dispatch entry point
238// returns it, including `LANG::tree_sitter_language`), so it is defined
239// in `big-code-analysis-ast`; `FromPathError` wraps it for the
240// file-backed `Ast::from_path` and stays here.
241pub use big_code_analysis_ast::MetricsError;
242mod from_path_error;
243pub use crate::from_path_error::FromPathError;
244
245// --- Metric selection ---
246mod metric_set;
247pub use crate::metric_set::{Metric, MetricSet, ParseMetricError};
248
249// --- Suppression markers ---
250mod suppression;
251pub use crate::suppression::{
252    SuppressionDialect, SuppressionMarker, SuppressionPolicy, SuppressionScope, SuppressionTarget,
253    threshold_metric_for_name,
254};
255
256/// Canonical metric catalog: offender sub-metric ids with their
257/// long-form sentences, [`metric_catalog::Direction`] and
258/// [`metric_catalog::Scale`], plus the family view rendered by
259/// `bca list-metrics` and the metric-selector resolver
260/// ([`metric_catalog::resolve_selector`]). Single source of truth
261/// shared by the library's offender formatters, the CLI's threshold
262/// engine (which pins its extractor ids to
263/// [`metric_catalog::METRICS`] via a parity test), and the metric
264/// selections of `bca metrics --metrics` and the Python `metrics=`.
265/// [`metric_catalog::Threshold`] is the validated limit that answers
266/// breach, severity, soft-tier, change and drift questions in the
267/// metric's own direction and scale.
268pub mod metric_catalog;
269
270// "Did you mean?" suggestions. The resolver's error uses it in-crate;
271// the hidden re-export exists only so the CLI's unknown-name errors
272// share the one algorithm (#1614).
273mod suggestion;
274#[doc(hidden)]
275pub use crate::suggestion::format_suggestion;
276
277/// Output formatters: CSV, SARIF, Checkstyle, clang/MSVC warning
278/// lines, and AST/metric pretty-dumps used by `bca` and the offender
279/// reporters.
280///
281/// The most commonly used writers (`write_csv`, `write_sarif`,
282/// `write_checkstyle`, `write_clang_warning`, `write_code_climate`,
283/// `write_msvc_warning`) and shared types (`OffenderRecord`,
284/// `Severity`, `TOOL_ID`, `CSV_HEADER`, `CSV_EXTENSION`) are also
285/// re-exported at the crate root.
286pub mod output;
287pub use crate::output::{
288    CSV_EXTENSION, CSV_HEADER, ColorMode, OffenderRecord, Severity, TOOL_ID, defang_formula,
289    dump_node, dump_node_with_color, dump_ops, dump_ops_with_color, dump_root,
290    dump_root_with_color, write_checkstyle, write_clang_warning, write_code_climate, write_csv,
291    write_csv_aggregate, write_msvc_warning, write_sarif, write_sarif_with_suppressed,
292};
293
294// --- AST plumbing (Node) ---
295pub use big_code_analysis_ast::Node;
296
297// --- Language detection / I/O helpers ---
298pub use big_code_analysis_ast::{
299    SkipReason, get_language_for_file, guess_language, is_generated, normalize_eol, read_file,
300    read_file_with_eol, read_file_with_eol_classified, write_file,
301};
302
303// --- Source walker ---
304mod concurrent_files;
305pub use crate::concurrent_files::{
306    ConcurrentErrors, ConcurrentRunner, FilesData, NumJobs, ParseNumJobsError,
307};
308
309// --- Per-file node counting (reached via the `Ast` seam) ---
310pub use big_code_analysis_ast::{Count, CountCollector};
311
312mod function;
313pub use crate::function::{FunctionSpan, dump_function_spans, dump_function_spans_with_color};
314
315// --- AST dump ---
316pub use big_code_analysis_ast::{
317    AstCfg, AstNode, AstPayload, AstResponse, MAX_AST_SERIALIZE_DEPTH, Span,
318};
319
320// --- Halstead operator/operand result type ---
321mod ops;
322pub use crate::ops::Ops;
323
324// --- Preprocessor handling (C/C++) ---
325pub use big_code_analysis_ast::{
326    PreprocDiagnostic, PreprocFile, PreprocResults, fix_includes, get_macros, preprocess,
327};
328
329// --- Generic parser plumbing ---
330//
331// `Parser`, `ParserTrait`, `Filter`, `LanguageInfo`, `Checker`,
332// `Getter` and `Alterator` are defined in `big-code-analysis-ast` and
333// reach this crate through the glob import above. They are not
334// re-exported: the single public analysis seam is [`Ast`], which wraps
335// the language-dispatched `AnyParser` carrier. See STABILITY.md.
336//
337// The metric half of the parser contract; `ParserTrait` is the parse
338// half. See `src/metric_suite.rs`.
339mod metric_suite;
340pub(crate) use crate::metric_suite::MetricSuite;
341
342/// Re-export of the underlying `tree-sitter` crate.
343///
344/// Lets callers build a [`tree_sitter::Tree`] (via
345/// [`tree_sitter::Parser`]) against the exact grammar version this
346/// library is pinned to, and feed it back through
347/// [`Ast::from_tree_sitter`] without taking a separate `tree-sitter`
348/// dependency that may drift out of pin.
349///
350/// This is part of the value-not-stable surface: the underlying
351/// pin may bump in any minor release (see `STABILITY.md`). The inner
352/// node of a [`Node`] is reached the same way, through
353/// [`Node::as_tree_sitter`], and carries the same value-not-stable
354/// caveat.
355pub use ::tree_sitter;
356
357/// The version of this `big-code-analysis` library crate.
358///
359/// Sourced from the crate's own `CARGO_PKG_VERSION` at compile time.
360/// Exposed so downstream surfaces (the REST `/v1/version` endpoint, the
361/// Python `__version__` attribute, …) can report the exact library
362/// version they were built against without re-deriving it from Cargo
363/// metadata.
364pub const VERSION: &str = env!("CARGO_PKG_VERSION");
365
366/// Recommended entry points for the 90% case.
367///
368/// Star-import this module to get the curated set of types and
369/// functions most callers need:
370///
371/// ```no_run
372/// use big_code_analysis::prelude::*;
373///
374/// let source = b"fn main() {}";
375/// let space = analyze(
376///     Source::new(LANG::Rust, source),
377///     MetricsOptions::default(),
378/// ).expect("Rust source parses");
379/// # let _ = space;
380/// ```
381///
382/// Anything not exposed here can still be imported with its
383/// fully-qualified name from the crate root (`use
384/// big_code_analysis::Something;`). Items deliberately omitted from
385/// the prelude are either deprecated, doc-hidden, or unlikely to
386/// appear in typical caller code.
387pub mod prelude {
388    pub use crate::{
389        // Parse-once handle
390        Ast,
391        // Result types
392        CodeMetrics,
393        // Errors and options
394        FromPathError,
395        FuncSpace,
396        // Language enum
397        LANG,
398        // Metric selection
399        Metric,
400        MetricsError,
401        MetricsOptions,
402        Source,
403        SpaceKind,
404        // Core entry points
405        analyze,
406    };
407}