Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

クイックスタート

This page shows the minimum code needed to compute metrics from a string of source code. It assumes a working Rust toolchain and a crate to add the dependency to.

1. クレートを追加する

# Cargo.toml
[dependencies]
big-code-analysis = "2.4.0"

The crate uses Rust edition 2024 and pins rust-version = "1.94". Older toolchains will not build it; see the MSRV section of STABILITY.md for the policy.

2. 文字列からメトリクスを計算する

推奨エントリポイントは analyze です。言語、ソースバイト列、省略可能な表示名を持つ Source と、走査ごとのフラグを指定する MetricsOptions を渡します。ファイルシステムのパスは不要です。

use big_code_analysis::{analyze, MetricsOptions, Source, LANG};

fn main() {
    let source = "fn add(a: i32, b: i32) -> i32 { a + b }";

    let space = analyze(
        Source::new(LANG::Rust, source.as_bytes())
            .with_name(Some("snippet.rs".to_owned())),
        MetricsOptions::default(),
    )
    .expect("Rust source should parse");

    println!(
        "cognitive complexity (file-level): {}",
        space.metrics.cognitive.cognitive_sum(),
    );
}

Source::name becomes the top-level FuncSpace::name; passing None leaves the top-level name unset. The return type is Result<FuncSpace, MetricsError>. In practice the Err variant means the requested language’s Cargo feature is disabled in this build. A parse failure does not produce Err: tree-sitter recovers with ERROR nodes. See Error handling for the variant set and matching patterns. MetricsError is #[non_exhaustive], so always include a _ arm when matching.

Tip: use big_code_analysis::prelude::*; brings the recommended entry points (analyze, Ast, Source, MetricsOptions, MetricsError, FromPathError, SkipReason, LANG, FuncSpace, CodeMetrics, SpaceKind, Metric) into scope in one line. Anything outside the prelude is still reachable by name, for example use big_code_analysis::guess_language;.

Need more than metrics from one parse (operators and operands, an AST dump, a function-span list)? Parse once with Ast::parse and call the per-pass methods on the handle. See Parse once, run metrics many times. If you already drive your own tree_sitter::Parser, adopt the resulting tree with Ast::from_tree_sitter (see Reusing an existing tree-sitter Tree).

3. Inspect the result

FuncSpace is a tree of spaces. The top-level node represents the whole file; its spaces field holds nested function, class and impl spaces. Every node carries the same CodeMetrics struct, so you can read any metric at any level.

use big_code_analysis::{analyze, MetricsOptions, Source, SpaceKind, LANG};

fn main() {
    let source = "\
fn outer() {
    fn inner() {}
}
";
    let space = analyze(
        Source::new(LANG::Rust, source.as_bytes())
            .with_name(Some("snippet.rs".to_owned())),
        MetricsOptions::default(),
    )
    .expect("Rust source should parse");

    assert_eq!(space.kind, SpaceKind::Unit);
    assert_eq!(space.spaces.len(), 1); // `outer`
    assert_eq!(space.spaces[0].spaces.len(), 1); // `inner`
}

FuncSpace をより深く走査する方法は FuncSpace 結果の走査を参照してください。

言語の選択

If you do not know the language up front, use guess_language. It consults the path extension, an Emacs mode declaration in the buffer, and the shebang, in that order:

use std::path::PathBuf;

use big_code_analysis::{analyze, guess_language, MetricsOptions, Source};

fn main() {
    let source = b"print('hi')\n";
    let path = PathBuf::from("hello.py");

    let (Some(lang), _name) = guess_language(source, &path) else {
        eprintln!("unrecognised language");
        return;
    };

    let _space = analyze(
        Source::new(lang, source).with_name(Some("hello.py".to_owned())),
        MetricsOptions::default(),
    );
}

guess_language returns (None, _) only when the extension, the mode declaration, and the shebang all fail to name a language; treat that as “skip this file” rather than as a parse error.