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