Skip to main content

Crate big_code_analysis

Crate big_code_analysis 

Source
Expand description

big-code-analysis is a library to analyze and extract information from source codes written in many different programming languages.

You can find the source code of this software on GitHub, while issues and feature requests can be posted on the respective GitHub Issue Tracker.

§Quick start

Most callers want the recommended entry points exposed in prelude:

use big_code_analysis::prelude::*;

let source = b"fn main() {}";
let space = analyze(
    Source::new(LANG::Rust, source),
    MetricsOptions::default(),
).expect("Rust source parses");
println!("cognitive sum: {}", space.metrics.cognitive.cognitive_sum());

§Supported Languages

Each grammar is gated behind a per-language Cargo feature; the default all-languages feature enables every grammar so the historical “every language compiled in” behaviour is preserved. Library consumers that only need a subset can opt out of the defaults — see Per-language Cargo features in the book.

  • Bash (bash)
  • C (c, upstream tree-sitter-c; owns .c)
  • C/C++ (cpp, upstream tree-sitter-cpp; the default for .cpp / .cc / .h and also exposes the internal ccomment / preproc C-family helpers)
  • C++, Firefox-internal “Mozcpp” (mozcpp, opt-in; owns no file extensions — select it by name)
  • C# (csharp)
  • Objective-C (objc, upstream tree-sitter-objc; owns .m; .mm Objective-C++ stays on C/C++)
  • Elixir (elixir)
  • Go (go)
  • Groovy (groovy)
  • F5 iRules (irules)
  • Java (java)
  • JavaScript (javascript)
  • JavaScript, Firefox-internal “MozJS” (mozjs)
  • Kotlin (kotlin)
  • Lua (lua)
  • Perl (perl)
  • PHP (php)
  • Python (python)
  • Ruby (ruby)
  • Rust (rust)
  • Tcl (tcl)
  • TSX (tsx)
  • TypeScript (typescript)

§Supported Metrics

  • ABC: it measures the size of a source code based on assignments, branches, and conditions.
  • CC: it calculates the code complexity examining the control flow of a program. Both standard and modified flavours are exposed: the modified variant collapses all case/match arms inside a single switch/match/when/select into one decision point.
  • Cognitive Complexity: it measures how difficult it is to understand a unit of code.
  • SLOC: it counts the number of lines in a source file.
  • PLOC: it counts the number of physical lines (instructions) contained in a source file.
  • LLOC: it counts the number of logical lines (statements) contained in a source file.
  • CLOC: it counts the number of comments in a source file.
  • BLANK: it counts the number of blank lines in a source file.
  • HALSTEAD: it is a suite that provides a series of information, such as the effort required to maintain the analyzed code, the size in bits to store the program, the difficulty to understand the code, an estimate of the number of bugs present in the codebase, and an estimate of the time needed to implement the software.
  • MI: it is a suite that allows to evaluate the maintainability of a software.
  • NOM: it counts the number of functions and closures in a file/trait/class.
  • NEXITS: it counts the number of possible exit points from a method/function.
  • NARGS: it counts the number of arguments of a function/method.
  • NPA: it counts the number of public attributes of a class.
  • NPM: it counts the number of public methods of a class.
  • WMC: it is the sum of the complexities of all methods in a class.

Re-exports§

pub use crate::output::CSV_EXTENSION;
pub use crate::output::CSV_HEADER;
pub use crate::output::ColorMode;
pub use crate::output::OffenderRecord;
pub use crate::output::Severity;
pub use crate::output::TOOL_ID;
pub use crate::output::defang_formula;
pub use crate::output::dump_node;
pub use crate::output::dump_node_with_color;
pub use crate::output::dump_ops;
pub use crate::output::dump_ops;
pub use crate::output::dump_ops_with_color;
pub use crate::output::dump_root;
pub use crate::output::dump_root_with_color;
pub use crate::output::write_checkstyle;
pub use crate::output::write_clang_warning;
pub use crate::output::write_code_climate;
pub use crate::output::write_csv;
pub use crate::output::write_csv_aggregate;
pub use crate::output::write_msvc_warning;
pub use crate::output::write_sarif;
pub use crate::output::write_sarif_with_suppressed;
pub use ::tree_sitter;

Modules§

metric_catalog
Canonical metric catalog: offender sub-metric ids with their long-form sentences and metric_catalog::Direction, plus the family view rendered by bca list-metrics. Single source of truth shared by the library’s offender formatters and the CLI’s threshold engine, which pins its extractor ids to metric_catalog::METRICS via a parity test. Single source of truth for the metric catalog.
metrics
Per-metric implementations.
output
Output formatters: CSV, SARIF, Checkstyle, clang/MSVC warning lines, and AST/metric pretty-dumps used by bca and the offender reporters.
prelude
Recommended entry points for the 90% case.
wire
Plain, Deserialize-capable data-transfer structs mirroring the serialized metric wire shape. The compute types’ Serialize impls delegate here, making these the single definition of the JSON / YAML / TOML / CBOR output format and the canonical way to read bca output back (serde_json::from_str::<wire::FuncSpace>(…)). Plain, public data-transfer structs mirroring the serialized metric wire shape — the single source of truth for the JSON / YAML / TOML / CBOR output format and the only Deserialize-capable view of it.

Structs§

Ast
Parse-once, compute-many handle.
AstCfg
Configuration options for retrieving the nodes of an AST.
AstNode
Information on an AST node.
AstPayload
The payload of an Ast request.
AstResponse
The response of an AST request.
CodeMetrics
All metrics data.
ConcurrentRunner
A runner to process files concurrently.
Count
Count of different types of nodes in a code.
CountCollector
Opaque, shareable collector that accumulates a Count across the worker threads of a crate::ConcurrentRunner walk.
FilesData
A resolved, terminal file list for ConcurrentRunner.
FuncSpace
Function space data.
FunctionSpan
Function span data.
MetricSet
Bitfield of selected metrics.
MetricsOptions
Per-traversal options for analyze / Ast::metrics.
Node
An AST node.
Ops
All operands and operators of a space.
ParseLangError
Error returned by LANG’s FromStr impl when the input is not a recognised language name.
ParseMetricError
Error returned by Metric::from_str when the input is not a recognised metric name.
PreprocFile
Preprocessor data of a C/C++ file.
PreprocResults
Preprocessor data of a series of C/C++ files.
Source
In-memory source bundle handed to analyze.
Span
Start and end positions of a node in a code in terms of lines, columns, and byte offsets.
SuppressionMarker
A single in-source suppression marker located within a file, carrying the context needed to audit it.

Enums§

ConcurrentErrors
Series of errors that might happen when processing files concurrently.
FromPathError
Error returned by Ast::from_path.
LANG
The list of supported languages.
Metric
One metric computed by the analysis walker.
MetricsError
Error returned by the library’s metric-computation entry points.
NumJobs
Parsed worker-count selector for ConcurrentRunner, shared by the bca CLI and the bca-web server so both binaries resolve the same <N|auto> contract.
ParseNumJobsError
Error returned by NumJobs::from_str when the input is neither auto nor a usable positive integer.
PreprocDiagnostic
A non-fatal diagnostic produced while resolving the C/C++ include graph in fix_includes.
SpaceKind
The list of supported space kinds.
SuppressionDialect
Which marker dialect produced a suppression.
SuppressionPolicy
Whether downstream consumers (threshold checking, audit logging) should honor parsed suppression markers.
SuppressionScope
Which metrics a suppression marker covers.
SuppressionTarget
Whether an audited suppression marker applies to its enclosing function or to the whole file.

Constants§

VERSION
The version of this big-code-analysis library crate.

Functions§

analyze
Compute every metric for a Source.
dump_function_spans
Render spans for path to colored stdout (nothing when spans is empty). Callers obtain spans from crate::Ast::functions and render them without naming the parser surface. Mirrors the self-contained-stdout shape of crate::dump_root / crate::dump_ops.
dump_function_spans_with_color
Like dump_function_spans, but the caller selects the ColorMode.
fix_includes
Constructs a dependency graph of the include directives in a C/C++ file.
get_from_emacs_mode
Detects the language associated to the input Emacs mode.
get_from_ext
Detects the language associated to the input file extension.
get_language_for_file
Detects the language of a code using the extension of a file.
get_macros
Returns the macros contained in a C/C++ file.
guess_language
Guesses the language of a code.
is_generated
Returns true when buf looks like generated code: its leading window (first ~50 lines or first 5 KiB, whichever is smaller) contains a known marker phrase. Matching is case-insensitive for the marker and never allocates on the negative path.
normalize_eol
Normalises an in-memory source buffer to match the read_file_with_eol on-disk path: all CR-only and CRLF line endings become LF, and the buffer is guaranteed to end with exactly one \n.
preprocess
Extracts preprocessor data from a C/C++ source buffer and inserts it into a PreprocResults object.
read_file
Reads a file, normalising all CR-only and CRLF line endings to LF.
read_file_with_eol
Reads a file, normalising all CR-only and CRLF line endings to LF, and ensures the buffer ends with exactly one \n. Returns None for files ≤ 3 bytes or files that appear to be non-UTF-8.
threshold_metric_for_name
Resolve a sub-metric threshold name (e.g. cyclomatic.modified, halstead.volume, loc.lloc) to its parent Metric.
write_file
Writes data to a file.