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
127// Internal-only modules. Nothing is re-exported from these.
128mod c_declarator;
129mod c_langs_macros;
130mod c_macro;
131mod cfg_predicate;
132mod checker;
133mod getter;
134// Fast hashing for the walk's integer-keyed maps. Shared by `spaces`
135// (node ids) and `metrics::halstead` (grammar `kind_id`s); `metrics::loc`
136// was the third until #1109 moved its line sets to a bitset. The module
137// doc is the single place that lists them and says why the text-keyed
138// collections are excluded — extend it, not this line, when a third
139// arrives.
140mod int_hash;
141#[cfg(test)]
142mod language_enum_roundtrip;
143mod languages;
144mod macros;
145// One declaration form for the thread-local counters that make an
146// output-invisible optimization testable. The module doc states the
147// shared invariant (the counter is unconditional, only its accessor is
148// test-gated) once; each invocation carries its own narrative.
149mod observation;
150// Parse-and-inspect shims shared by the per-metric test modules. Kept out
151// of any production file so the self-scan gate does not spend a shipping
152// module's metric budget on test-only code (#1066).
153#[cfg(test)]
154mod test_support;
155
156// `langs` hosts the `mk_langs!` macro expansion. `LANG` is the only
157// public name; the per-language `<Lang>Code` tags and `<Lang>Parser`
158// aliases are `pub(crate)` parser machinery reached only through the
159// [`Ast`] seam.
160mod langs;
161pub use crate::langs::{LANG, get_from_emacs_mode, get_from_ext};
162// `<Lang>Code` tags are reached crate-internally through `use crate::*`
163// in the per-language `Checker` / `Getter` / `Alterator` / metric impls.
164pub(crate) use crate::langs::{
165    BashCode, CCode, CcommentCode, CppCode, CsharpCode, ElixirCode, GoCode, GroovyCode, IrulesCode,
166    JavaCode, JavascriptCode, KotlinCode, LuaCode, MozcppCode, MozjsCode, ObjcCode, PerlCode,
167    PhpCode, PreprocCode, PythonCode, RubyCode, RustCode, TclCode, TsxCode, TypescriptCode,
168};
169// The `<Lang>Parser` aliases are the concrete `Parser<<Lang>Code>` types
170// driven by the `AstInner` dispatch in `crate::langs`; at the crate root
171// they are reached only from `#[cfg(test)]` modules, so the re-export is
172// `unused` in a non-test build.
173#[allow(unused_imports)]
174pub(crate) use crate::langs::{
175    BashParser, CParser, CcommentParser, CppParser, CsharpParser, ElixirParser, GoParser,
176    GroovyParser, IrulesParser, JavaParser, JavascriptParser, KotlinParser, LuaParser,
177    MozcppParser, MozjsParser, ObjcParser, PerlParser, PhpParser, PreprocParser, PythonParser,
178    RubyParser, RustParser, TclParser, TsxParser, TypescriptParser,
179};
180// `ParseLangError` is the `FromStr` error for `LANG`; it is defined in
181// the `mk_lang!` macro layer (`crate::macros`) rather than `crate::langs`.
182pub use crate::macros::ParseLangError;
183
184// Internal crate-root re-exports. Hand-written per-language modules
185// (`src/getter.rs`, `src/checker.rs`, `src/alterator.rs`, the
186// per-language metric impls) use `use crate::*` to bring the
187// macro-generated `<Lang>Code` token enums and per-language helper
188// types into scope; the per-language token enums in
189// `src/languages/language_*.rs` are also reached through the crate
190// root. Re-exporting these as `pub(crate)` keeps internal compilation
191// working without widening the published surface.
192pub(crate) use crate::checker::*;
193pub(crate) use crate::languages::*;
194
195// Hand-written modules (`src/spaces.rs`, `src/output/dump_metrics.rs`,
196// the metric macros) refer to per-metric submodules by their short
197// crate-root path (`crate::abc`, `crate::cognitive`, ...). Re-export
198// them under those names without widening the public surface.
199pub(crate) use crate::metrics::{
200    abc, cognitive, cyclomatic, halstead, loc, mi, nargs, nexits, nom, npa, npm, tokens, wmc,
201};
202
203// Module declarations. Each `pub use` line below names exactly the
204// items intended to be part of the public API surface; anything not
205// listed stays out of the crate root. Per issue #255, glob re-exports
206// (`pub use module::*`) are no longer used here because every newly
207// `pub`-marked helper in any sub-module would silently leak into the
208// published API.
209
210// --- Core analysis entry points and result types (spaces.rs) ---
211mod spaces;
212pub use crate::spaces::{Ast, CodeMetrics, FuncSpace, MetricsOptions, Source, SpaceKind, analyze};
213// `metrics_inner` is the per-`ParserTrait` metric walk core consumed by
214// feature-gated arms in `mk_action!` (`AstInner::run_metrics`). With
215// `--no-default-features` and no language feature, every arm compiles
216// out and the re-export becomes nominally unused; the language-features
217// that ship in the default set keep the symbol live in any normal build.
218#[allow(unused_imports)]
219pub(crate) use crate::spaces::metrics_inner;
220
221/// Per-metric implementations.
222///
223/// Each sub-module owns one metric — its `Stats` accumulator, the
224/// per-language trait implementations, and any small helpers used
225/// only by tests. Most callers will not need these directly; reach
226/// through [`CodeMetrics`] on a [`FuncSpace`] instead.
227pub mod metrics;
228
229/// Plain, `Deserialize`-capable data-transfer structs mirroring the
230/// serialized metric wire shape. The compute types' `Serialize` impls
231/// delegate here, making these the single definition of the JSON / YAML /
232/// TOML / CBOR output format and the canonical way to read `bca` output
233/// back (`serde_json::from_str::<wire::FuncSpace>(…)`).
234pub mod wire;
235
236// --- Change-history (VCS) metrics ---
237//
238// The project's first language-agnostic, non-AST metric family
239// (issue #328). Gated behind the `vcs-git` backend feature (the
240// `vcs` umbrella turns it on); the generic surface is backend-neutral
241// so future backends (#335) reuse it unchanged.
242/// Change-history (VCS) metrics derived from version-control history:
243/// churn, commit frequency, author count / ownership dilution, bug- and
244/// security-fix history, and an ordinal composite risk score. See
245/// [`vcs::build_history_index`].
246///
247/// Enable with the `vcs` Cargo feature (the umbrella over the current
248/// `vcs-git` backend, which is what the availability badge names).
249#[cfg(feature = "vcs-git")]
250#[cfg_attr(docsrs, doc(cfg(feature = "vcs-git")))]
251pub mod vcs;
252
253// --- Diagnostics ---
254//
255// The single place the library writes a `warning:` prefix; the CLI has
256// its own severity ladder in `big-code-analysis-cli/src/diag.rs`.
257mod diag;
258
259// --- Errors ---
260mod error;
261pub use crate::error::{FromPathError, MetricsError};
262
263// --- Metric selection ---
264mod metric_set;
265pub use crate::metric_set::{Metric, MetricSet, ParseMetricError};
266
267// --- Suppression markers ---
268mod suppression;
269pub use crate::suppression::{
270    SuppressionDialect, SuppressionMarker, SuppressionPolicy, SuppressionScope, SuppressionTarget,
271    threshold_metric_for_name,
272};
273
274/// Canonical metric catalog: offender sub-metric ids with their
275/// long-form sentences and [`metric_catalog::Direction`], plus the
276/// family view rendered by `bca list-metrics`. Single source of truth
277/// shared by the library's offender formatters and the CLI's threshold
278/// engine, which pins its extractor ids to [`metric_catalog::METRICS`]
279/// via a parity test.
280pub mod metric_catalog;
281
282/// Output formatters: CSV, SARIF, Checkstyle, clang/MSVC warning
283/// lines, and AST/metric pretty-dumps used by `bca` and the offender
284/// reporters.
285///
286/// The most commonly used writers (`write_csv`, `write_sarif`,
287/// `write_checkstyle`, `write_clang_warning`, `write_code_climate`,
288/// `write_msvc_warning`) and shared types (`OffenderRecord`,
289/// `Severity`, `TOOL_ID`, `CSV_HEADER`, `CSV_EXTENSION`) are also
290/// re-exported at the crate root.
291pub mod output;
292pub use crate::output::{
293    CSV_EXTENSION, CSV_HEADER, ColorMode, OffenderRecord, Severity, TOOL_ID, defang_formula,
294    dump_node, dump_node_with_color, dump_ops, dump_ops_with_color, dump_root,
295    dump_root_with_color, write_checkstyle, write_clang_warning, write_code_climate, write_csv,
296    write_csv_aggregate, write_msvc_warning, write_sarif, write_sarif_with_suppressed,
297};
298
299// --- AST plumbing (Node) ---
300mod node;
301pub(crate) use crate::node::Ancestors;
302pub use crate::node::Node;
303
304// --- Language detection / I/O helpers ---
305mod tools;
306pub use crate::tools::{
307    SkipReason, get_language_for_file, guess_language, is_generated, normalize_eol, read_file,
308    read_file_with_eol, read_file_with_eol_classified, write_file,
309};
310
311// --- Source walker ---
312mod concurrent_files;
313pub use crate::concurrent_files::{
314    ConcurrentErrors, ConcurrentRunner, FilesData, NumJobs, ParseNumJobsError,
315};
316
317// --- Comment removal ---
318//
319// `rm_comments` is the internal walk core reached only through the
320// [`Ast::strip_comments`] seam (`AstInner::run_strip_comments`).
321mod comment_rm;
322
323// --- Per-file node counting / finding (reached via the `Ast` seam) ---
324mod count;
325pub use crate::count::{Count, CountCollector};
326
327mod find;
328
329mod function;
330pub use crate::function::{FunctionSpan, dump_function_spans, dump_function_spans_with_color};
331
332// --- AST dump ---
333mod ast;
334pub use crate::ast::{AstCfg, AstNode, AstPayload, AstResponse, MAX_AST_SERIALIZE_DEPTH, Span};
335
336// --- Stack-depth bounds shared by the crate's recursive types ---
337mod recursion;
338
339// --- Halstead operator/operand result type ---
340mod ops;
341pub use crate::ops::Ops;
342// `ops_inner` is the explicit-name walk core consumed by feature-gated
343// `mk_action!` arms (`AstInner::run_ops`); mirrors the `metrics_inner`
344// re-export above and is nominally unused under `--no-default-features`.
345#[allow(unused_imports)]
346pub(crate) use crate::ops::ops_inner;
347
348// --- Preprocessor handling (C/C++) ---
349mod preproc;
350pub use crate::preproc::{
351    PreprocDiagnostic, PreprocFile, PreprocResults, fix_includes, get_macros, preprocess,
352};
353
354// --- Alterator trait (per-language AST simplification) ---
355//
356// Crate-internal: an extension trait over the `pub(crate)` `Checker`
357// machinery, used only by the per-language `Parser<T>` impls behind the
358// [`Ast`] seam.
359mod alterator;
360pub(crate) use crate::alterator::Alterator;
361
362// --- Generic parser plumbing (crate-internal) ---
363//
364// `Parser`, `ParserTrait`, `Filter`, and `LanguageInfo` are the
365// internal parser machinery driving every metric walk. They are
366// `pub(crate)` only: the single public analysis seam is [`Ast`],
367// which wraps the language-dispatched `AstInner` carrier. See
368// STABILITY.md.
369mod parser;
370pub(crate) use crate::parser::Parser;
371
372mod traits;
373pub(crate) use crate::traits::{LanguageInfo, ParserTrait, Search};
374
375/// Re-export of the underlying `tree-sitter` crate.
376///
377/// Lets callers build a [`tree_sitter::Tree`] (via
378/// [`tree_sitter::Parser`]) against the exact grammar version this
379/// library is pinned to, and feed it back through
380/// [`Ast::from_tree_sitter`] without taking a separate `tree-sitter`
381/// dependency that may drift out of pin.
382///
383/// This is part of the value-not-stable surface: the underlying
384/// pin may bump in any minor release (see `STABILITY.md`). The inner
385/// node of a [`Node`] is reached the same way, through
386/// [`Node::as_tree_sitter`], and carries the same value-not-stable
387/// caveat.
388pub use ::tree_sitter;
389
390/// The version of this `big-code-analysis` library crate.
391///
392/// Sourced from the crate's own `CARGO_PKG_VERSION` at compile time.
393/// Exposed so downstream surfaces (the REST `/v1/version` endpoint, the
394/// Python `__version__` attribute, …) can report the exact library
395/// version they were built against without re-deriving it from Cargo
396/// metadata.
397pub const VERSION: &str = env!("CARGO_PKG_VERSION");
398
399/// Recommended entry points for the 90% case.
400///
401/// Star-import this module to get the curated set of types and
402/// functions most callers need:
403///
404/// ```no_run
405/// use big_code_analysis::prelude::*;
406///
407/// let source = b"fn main() {}";
408/// let space = analyze(
409///     Source::new(LANG::Rust, source),
410///     MetricsOptions::default(),
411/// ).expect("Rust source parses");
412/// # let _ = space;
413/// ```
414///
415/// Anything not exposed here can still be imported with its
416/// fully-qualified name from the crate root (`use
417/// big_code_analysis::Something;`). Items deliberately omitted from
418/// the prelude are either deprecated, doc-hidden, or unlikely to
419/// appear in typical caller code.
420pub mod prelude {
421    pub use crate::{
422        // Parse-once handle
423        Ast,
424        // Result types
425        CodeMetrics,
426        // Errors and options
427        FromPathError,
428        FuncSpace,
429        // Language enum
430        LANG,
431        // Metric selection
432        Metric,
433        MetricsError,
434        MetricsOptions,
435        Source,
436        SpaceKind,
437        // Core entry points
438        analyze,
439    };
440}