Elex.Validator (Elex v0.3.0)

View Source

Validates a parsed expression AST for type correctness.

Checks that operators are applied to compatible types, variables exist in the context, and function calls match registered signatures. Used by Elex.Parser during parsing and available for direct AST validation.

Examples

context = Elex.new_context() |> Elex.add_variable!("x", 10)
{:ok, ast, _} = Elex.Parser.parse("x + 5", context, validate: false)
Elex.Validator.validate(ast, context)
#=> {:ok, :decimal}

Summary

Functions

Formats a same_numeric_type/2 mismatch as a function error message.

Checks that every AST node is the same numeric type.

Validates an expression AST against a context.

Functions

numeric_mismatch_message(name, arg)

@spec numeric_mismatch_message(
  String.t(),
  {:mismatch, atom() | Elex.Dimension.t()}
  | {:mismatch, atom() | Elex.Dimension.t(), atom() | Elex.Dimension.t()}
) :: String.t()

Formats a same_numeric_type/2 mismatch as a function error message.

Mixed categories become cannot mix length and mass. A number mixed with a quantity is cannot mix number and length. A non-numeric first argument stays name function expects number arguments, got ….

same_numeric_type(asts, ctx)

@spec same_numeric_type([term()], Elex.Context.t()) ::
  {:ok, atom() | Elex.Dimension.t()}
  | {:mismatch, atom() | Elex.Dimension.t()}
  | {:mismatch, atom() | Elex.Dimension.t(), atom() | Elex.Dimension.t()}
  | {:error, String.t()}

Checks that every AST node is the same numeric type.

Numeric types are :decimal and %Elex.Dimension{}. Returns {:ok, type} when all arguments match, {:mismatch, type} when the first argument is not numeric, {:mismatch, expected, got} when later arguments differ, or {:error, reason} when validation of an argument fails.

Use this from custom function validate/2 callbacks that accept either a either a number or a quantity of one category. See Advanced Topics.

validate(ast, ctx)

@spec validate(term(), Elex.Context.t()) ::
  {:ok, atom() | Elex.Dimension.t()} | {:error, String.t()}

Validates an expression AST against a context.

Parameters

Returns

  • {:ok, type} - The expression's result type (:decimal, :boolean, :string, nil, or %Elex.Dimension{})
  • {:error, reason} - A human-readable validation error

Examples

context = Elex.new_context() |> Elex.add_variable!("x", 10)
{:ok, ast, _} = Elex.Parser.parse("x > 0", context, validate: false)
Elex.Validator.validate(ast, context)
#=> {:ok, :boolean}