# Elixir API

Use ASP text with `Clingo.solve!/2` for a result or `Clingo.models/2` for a
lazy stream. Models, symbols, and results are Elixir values that survive
native cleanup.

```elixir
result = Clingo.solve!("{a;b}.", models: :all)
Enum.map(result.models, & &1.shown)

Clingo.models("{a;b;c}.", models: :all) |> Enum.take(2)
```

Both accept `files: [path]` with or without inline ASP. Relative
`#include` paths resolve against the loaded file. Clingo defaults to one
model. Use `models: :all` to enumerate all models. The result's
`exhausted` flag distinguishes a completed search from stopping at a limit.
A satisfiable model may have an empty `shown` list. For optimization, read
`cost` and `optimality_proven` from each snapshot.

## Incremental solving

Keep a control when grounding additional parts or changing externals between
solves.

```elixir
alias Clingo.Control

Clingo.with_control(fn control ->
  Control.add!(control, "#external enabled. answer :- enabled.")
  Control.ground!(control)
  Control.assign_external!(control, "enabled", true)
  Control.solve!(control)
end)
```

`with_control` closes its control when the function exits. Close a control
created by `Control.new!` explicitly. For file input on an existing control,
use `Control.load!` followed by `Control.ground!`. Mutations return `:ok`
and native errors raise `Clingo.Error`.

### Options

| Entry point | Options |
| --- | --- |
| `Control.new!`, `Clingo.with_control` | Native `arguments`, `models`, a two-argument `logger`, and `session: [max_arena: ..., max_queue: ..., max_callbacks: ...]` |
| `Control.ground!` | `context` maps function names to one-argument Elixir functions |
| `Control.models`, `Control.with_solve!` | `models`, `assumptions`, `show`, `symbols`, `async`, and native solve hooks |
| `Control.solve!` | The same solve options plus `collect` and `on_model` |
| `Clingo.solve!`, `Clingo.models` | Corresponding control, grounding, and solve options plus `files` |
| `Ground.to_string!` | Control and grounding options plus `files` and `format: :aspif` or `:reify` |

Unknown, duplicate, or invalid options raise `ArgumentError`. Streams
validate options when constructed and report solver failures during enumeration.

An existing control's `models:` option lasts for one solve. Set a persistent
default at construction or with `Configuration.put!(control, ["solve", "models"], "0")`.
Configuration paths use binary names and zero-based indices. Values are native
strings.

`assumptions:` accepts signed program literals or `{symbol, boolean}` pairs.
`show:` accepts a clingo show constant or bitset. `symbols: true` includes
decoded symbol structs, while `Model.shown` is ready to display.
`on_model` receives a copied model in the solving process and returns
`:cont` or `:halt`. Set `collect: false` to deliver models without storing
them in the result. Grounding context functions receive a list of symbols and
return one symbol or a list of symbols.

### Solve handles and cancellation

Only one solve handle may be open per control. Close it before mutating the
control or opening a backend bracket. Streams close their handles on completion
or early halt. The dispatcher also handles a consumer process that dies.

Use `Control.with_solve!` for explicit resume, wait, model, result, last model,
unsat core, and cancellation. With `async: true`, resume returns before progress
is available. `SolveHandle.wait!` waits for progress and `model!` can wait for a
snapshot.

Another process may call `SolveHandle.cancel!` to stop and drain the search. A
model already in flight may still arrive. Within a native callback, use
`Control.interrupt!` or return `:halt` from a model hook. Closing an owned control
interrupts its solve and waits for cleanup, including active Elixir hooks.
Close is idempotent. Operations on a closed control raise `ArgumentError`.

## Extensions

- `Inspection` copies symbolic and theory atoms. `Statistics` copies statistics
  into maps, lists, and numbers.
- `Backend.with_backend/2` builds rules and atoms using program literals. Finish
  the bracket before solving on the same control.
- `AST.with_ast/1` scopes parsing and construction. Updates and postorder walks
  rebuild changed nodes. Keep native nodes within their owning session and copy
  text or attributes to retain them after close.
- `Ground.to_string!` exports ASPIF by default or reified ASP facts. It removes
  temporary output on exit. Pass the resulting text to `Clingo.solve!` or save it
  and use `Control.load!`.
- `Dimacs.solve!` translates DIMACS CNF and shows true variables as `v(N)`.
- `CLI.run!` captures a child process's output. `CLI.run_native!` uses the
  current process's I/O and provides borrowed controls to its application
  hooks. `Script.register!` registers global hooks until
  `Clingo.finalize_scripts/0` permanently ends scripting for the VM.

Native solve hooks are `on_model_view`, `on_unsat`, `on_statistics`, and
`on_finish`. The model view lets you add clauses and extend the model during
the hook. Use `ModelView.snapshot!` to retain a copy. Return `:cont` or
`:halt` from that hook. Other solve hooks receive the copied lower bound, two
writable statistics views, or the result, respectively. Their return values
are ignored.

Propagator and observer hooks accept maps of functions with userdata omitted.
`Clingo.View` gives access to scoped propagation and assignment operations.
The decide hook returns a literal. Other observer and propagator hooks return
`:ok`.

Native hooks run in supervised Elixir workers. Views expire on callback return.
Calls from a hook go back to the originating native thread. A hook must avoid
waiting for another process to do ordinary work on the same session. Solve
hook failures raise `Clingo.Error` at the next handle operation, including close.

## Memory

The wrapper reclaims temporary grounding, inspection, and callback storage.
Persistent observers, propagators, and loggers live with their control. BEAM
garbage collection retires escaped view identities.
Clingo 5 interns symbol strings for the life of the VM. Solver memory, BEAM
heaps, and temporary scratch sit outside the wrapper arena. See the
[ownership rules](NATIVE_OWNERSHIP.md) and [ABI guide](API.md).
