Metastatic.Analysis.Complexity.Halstead (Metastatic v0.10.4)

View Source

Halstead complexity metrics calculation.

Halstead metrics measure program complexity based on the count of operators and operands in the code.

Metrics Calculated

  • n1: Number of distinct operators
  • n2: Number of distinct operands
  • N1: Total operators
  • N2: Total operands
  • Vocabulary (n): n1 + n2
  • Length (N): N1 + N2
  • Volume (V): N × log2(n)
  • Difficulty (D): (n1/2) × (N2/n2)
  • Effort (E): D × V

What Counts as Operator/Operand

Operators:

  • Binary operators (+, -, *, /, >, <, ==, and, or, etc.)
  • Unary operators (-, not)
  • Assignment (=)
  • Function call operator ()
  • Control flow (if, while, for, try, case)

Operands:

  • Variables
  • Literals (numbers, strings, booleans)
  • Function names

Examples

iex> ast = {:binary_op, [category: :arithmetic, operator: :+], [{:variable, [], "x"}, {:literal, [subtype: :integer], 5}]}
iex> metrics = Metastatic.Analysis.Complexity.Halstead.calculate(ast)
iex> metrics.distinct_operators
1
iex> metrics.distinct_operands
2

Summary

Functions

Calculates Halstead metrics for a MetaAST node.

Types

t()

@type t() :: %{
  distinct_operators: non_neg_integer(),
  distinct_operands: non_neg_integer(),
  total_operators: non_neg_integer(),
  total_operands: non_neg_integer(),
  vocabulary: non_neg_integer(),
  length: non_neg_integer(),
  volume: float(),
  difficulty: float(),
  effort: float()
}

Functions

calculate(ast)

@spec calculate(Metastatic.AST.meta_ast()) :: t()

Calculates Halstead metrics for a MetaAST node.

Returns a map with all Halstead metrics.

Examples

iex> ast = {:literal, [subtype: :integer], 42}
iex> metrics = Metastatic.Analysis.Complexity.Halstead.calculate(ast)
iex> metrics.total_operands
1
iex> metrics.total_operators
0