apply/erl

Types

Opaque marker for an Erlang atom.

Usage: obtained from string_to_atom / string_to_existing_atom, or restored with atom_to_string. Note: opaque; Gleam has no built-in atom type, so it can only be used through this module’s interface.

pub type Atom
pub type ErlError(tupled_args) {
  PathFormatError(path: String)
  ModuleAtomNotExist(path: String, module: String)
  FunctionAtomNotExist(path: String, func: String)
  ModuleLoadError(module: String, reason: String)
  FunctionArityNotExist(func: String, arity: Int, module: String)
  RuntimeError(need: String, now: String)
  NotACallableError(func: Function)
  ArgsTypeError(args: tupled_args)
  FuncRunningError(
    func: Function,
    args: tupled_args,
    error_type: String,
    error_reason: String,
    error_stack: List(String),
  )
}

Constructors

  • PathFormatError(path: String)

    Path is not in “module:func” form

  • ModuleAtomNotExist(path: String, module: String)

    Module atom does not exist (atom tables may differ across runtime standards)

  • FunctionAtomNotExist(path: String, func: String)

    Function atom does not exist

  • ModuleLoadError(module: String, reason: String)

    Module failed to load; reason is nofile / badfile / embedded …

  • FunctionArityNotExist(func: String, arity: Int, module: String)

    The function atom exists, but the module does not export that arity (unlike FunctionAtomNotExist, where the function atom itself is missing)

  • RuntimeError(need: String, now: String)

    Wrong runtime (this function needs to run under need, but is running under now)

  • NotACallableError(func: Function)

    Target is not callable

  • ArgsTypeError(args: tupled_args)

    Arguments must be a tuple

  • FuncRunningError(
      func: Function,
      args: tupled_args,
      error_type: String,
      error_reason: String,
      error_stack: List(String),
    )

    The function threw while running; type / reason / stack are kept structured

Opaque marker for a raw Erlang value (counterpart of JsObj in js).

Usage: returned by apply / try_catch, typically passed straight through. Note: opaque, cannot be constructed externally, and cannot be used directly as a concrete Gleam type.

pub type ErlObj

Collapses any Erlang value into an ErlValue carrying the concrete value, by runtime type.

Usage: case erl.classify(raw) { ErlAtom(a) -> ...; ErlFunction(f) -> ... }, getting Atom / Function directly and skipping to_custom_type. The parameter is untyped, so erl.apply results and Dynamic collection elements can be passed as-is. Note: ErlFunction / ErlAtom / ErlLocal are precise / handle types; elements and keys of ErlList / ErlDict / ErlTuple are gleam/dynamic.Dynamic and can be read with gleam/dynamic decoders; a tuple can be split with erl.tuple_to_list into List(ErlObj) and classified element by element. It does no runtime checking — it trusts identify’s tags; ErlValue is only meaningful on the Erlang runtime — use js.classify on JavaScript.

pub type ErlValue {
  ErlBool(v: Bool)
  ErlInt(v: Int)
  ErlFloat(v: Float)
  ErlString(v: String)
  ErlBitArray(v: BitArray)
  ErlList(v: List(dynamic.Dynamic))
  ErlDict(v: dict.Dict(dynamic.Dynamic, dynamic.Dynamic))
  ErlNil
  ErlTuple(v: dynamic.Dynamic)
  ErlFunction(v: Function)
  ErlAtom(v: Atom)
  ErlLocal(v: ErlObj)
}

Constructors

Error type for ensure_loaded: mirrors the failure reasons of code:ensure_loaded/1.

pub type ErlangEnsureLoadedError {
  Embedded
  Badfile
  Nofile
  NotErlangRuntime
}

Constructors

  • Embedded
  • Badfile
  • Nofile
  • NotErlangRuntime

Opaque marker for an Erlang callable (counterpart of Function in js).

Usage: built by get_erlang_function, executed by try_catch. Note: opaque, so it cannot be constructed externally; internally it holds only the module and function atoms, and the arity comes from the length of the argument tuple at call time.

pub opaque type Function

Error type for string_to_existing_atom (only badarg).

pub type StringToExistingAtomError {
  Badarg
}

Constructors

  • Badarg

Values

pub fn apply(
  path: String,
  args: tupled_args,
) -> Result(a, ErlError(tupled_args))

Fetches an Erlang function by path and runs it — get_erlang_function + try_catch.

Usage: apply("erlang:length", #([1, 2, 3])); the arity is the length of the argument tuple. Note: arguments must be a tuple; any failure in path parsing, fetching, or execution returns ErlError; the success value is a generic a, asserted for the use case (used directly as a concrete type, or as ErlObj handed to erl.classify); when a function can return several types, branch with erl.classify.

pub fn atom_to_string(a: Atom) -> Result(String, Nil)

Converts an atom to a String.

Usage: atom_to_string(atom), often paired with string_to_atom for a round-trip. Note: only available on the Erlang runtime; on non-Erlang it returns Error(Nil).

pub fn classify(value: any) -> ErlValue

See ErlValue. Dispatches on boundary.identify’s tag and does an identity cast.

Usage: erl.classify(raw); raw usually comes from erl.apply / erl.try_catch, or from an ErlObj element of an outer ErlValue. Note: unrecognized tags fall back to ErlLocal.

pub fn format_error(error: ErlError(a)) -> String

Renders any ErlError as one readable, detailed error message.

Usage: the apply.call facade uses it to flatten errors to String; you can also call it yourself for logging. Note: values (arguments, etc.) are rendered via boundary.debug_string, whose representation differs per runtime, e.g. a string is <<"x">> on erl and "x" on js.

pub fn format_func_running_error(
  error_type: String,
  error_reason: String,
  error_stack: List(String),
) -> String

Joins the structured type / reason / stack into one readable error message.

Usage: usually not called directly; format_error takes this path for FuncRunningError. Note: same signature as the identically named function on the JS side; when a stack is present the output is multi-line.

pub fn get_erlang_function(
  path: String,
  arity: Int,
) -> Result(Function, ErlError(a))

Fetches an Erlang function by path ("module:func" or bare "func") and arity.

Usage: get_erlang_function("lists:map", 2); a bare name defaults to module erlang. Note: only available on the Erlang runtime, otherwise returns RuntimeError; a missing function atom returns FunctionAtomNotExist, and an atom that exists but does not export that arity returns FunctionArityNotExist.

pub fn string_to_atom(str: String) -> Result(Atom, Nil)

Converts a String to an atom.

Usage: string_to_atom("foo"). Note: creates a new atom (as opposed to string_to_existing_atom); only available on the Erlang runtime, on non-Erlang it returns Error(Nil).

pub fn try_catch(
  func func: Function,
  args args: tupled_args,
) -> Result(a, ErlError(tupled_args))

Runs func with the tuple args, capturing exceptions.

Usage: try_catch(get_erlang_function("binary_to_atom", 1), #("123")). Note: the success value is a generic a, asserted by the caller for the use case (used directly as a concrete type, or as ErlObj handed to erl.classify); args must be a tuple or ArgsTypeError is returned; when the function throws (error/exit/throw) a structured FuncRunningError (type / reason / stack) is returned instead of propagating the exception.

pub fn tuple_to_list(obj: any) -> Result(List(ErlObj), Nil)

Splits an Erlang tuple into List(ErlObj) for per-element dispatch.

Usage: Erlang functions often use tuples for multi-shape results (a hit returns {X, Y}, a miss returns false). First erl.classify(raw) to get ErlTuple(_), then split it with this function and classify each element to branch by type, e.g.:

case erl.apply("lists:keyfind", #("a", 1, records)) {
  Ok(raw) ->
    case erl.classify(raw) {
      ErlTuple(_) ->
        case erl.tuple_to_list(raw) {
          Ok([key, value]) -> Ok(#(erl.classify(key), erl.classify(value)))
          _ -> Error(Nil)
        }
      _ -> Error(Nil) // false: no match
    }
  Error(_) -> Error(Nil)
}

Note: accepts only tuples and returns Error(Nil) otherwise; elements are opaque ErlObj, classify them when you need a concrete type; Erlang runtime only, other runtimes return Error(Nil).

pub fn tuple_to_values(obj: any) -> Result(List(ErlValue), Nil)

Splits an Erlang tuple into List(ErlValue): tuple_to_list then classify each element.

Usage: case erl.tuple_to_values(raw) { Ok([ErlAtom(_), value]) -> ...; _ -> ... }; elements are already ErlValue, so you can match constructors directly without classifying each. Note: accepts only tuples, otherwise Error(Nil); unclassifiable elements fall back to ErlLocal, so end your match with _.

✨ Search Document