コード行数(LoC)

このドキュメントでは、このクレートで利用できる LoC メトリクスの実装方法についての手引きを示します。コード行数は、ソースコードの行を数えることでソースコードの規模の目安を与えるソフトウェアメトリクスです。LoC には多くの種類があるため、まず例を使ってそれらを説明します。

LoC の種類

#![allow(unused)]
fn main() {
/*
課題: 階乗関数を実装せよ
追加加点として、可変状態や `for`・`while` のような命令型ループは使用しないこと。
 */

/// 階乗: n! = n*(n-1)*(n-2)*(n-3)...3*2*1
fn factorial(num: u64) -> u64 {

    // `Iterator` の `product` を使う
    (1..=num).product()
}
}

上の例を使って、以下で説明する各 LoC メトリクスを説明します。

SLOC

コード、コメント、空行を含む、ファイル内の全行を単純に数えたものです。
メトリクス値: 11

PLOC

ソースコードに含まれる命令行の数です。新しい行に置かれた括弧などの類似構文も含まれます。コメントと空行はここには数えられないことに注意してください。メトリクス値: 3

LLOC

「論理」行は、コード内の文の数を数えたものです。何を文とみなすかは言語によって異なることに注意してください。上の例では文は 1 つだけで、それは Iterator を引数とする product の関数呼び出しです。メトリクス値: 1

CLOC

コード内のコメントの数です。単一行、ブロック、doc といったコメントの種類は問いません。
メトリクス値: 6

BLANK

最後になりましたが、このメトリクスはコード中に存在する空行を数えます。メトリクス値: 2

空白文字のみのファイル

Source that contains no token at all — a file of nothing but spaces, tabs, and newlines — reports the rows it has: a four-row file of spaces is sloc 4, ploc 0, blank 4, with or without a trailing newline.

This used to be the one input class where a trailing newline changed a LoC value. Most grammars collapse tree-sitter's root node to a zero-width node at end-of-input for such input rather than spanning the file, and the file-level SLOC span was measured from that node — so those files reported sloc 0 when they ended in a newline and sloc 1 when they did not, while Elixir, Tcl, iRules and the preproc / ccomment helpers kept the root span and reported the rows either way.

The file-level span is now anchored at line 1 rather than measured from the root node's first token, so where the root node starts is no longer observable in LoC and every grammar answers alike. The sweep that used to pin the split — whitespace_only_input_is_uniform_across_grammars in /src/metrics/loc.rs — now pins the absence of one.

The same anchoring is what makes leading blank lines count. A file opening with three blank rows before its first token reports those rows in sloc and blank, exactly as interior blank rows are reported.

実装

上で説明した LoC 関連のメトリクスを実装するには、サポートしたい言語に対して Loc トレイトを実装する必要があります。

これには compute 関数の実装が必要です。実装場所と他言語の例については /src/metrics/loc.rs を参照してください。

PLOC に行を挿入するキャッチオールの _ アームには注意してください。Tcl ファミリーのように、文法が行終端子を extra ではなく_トークン_として表出する場合、そのトークンの開始行は終端する行そのものなので、キャッチオールはコメントのみの行や空行を PLOC に計上してしまいます。そうしたトークンには明示的な no-op アームを与えてください。