# `Decree.Verify.Eventless`
[🔗](https://github.com/sparkle-space/decree/blob/v0.1.0/lib/decree/verify/eventless.ex#L1)

Finds the routed handler arms that can accept a command without an event.

`Decree.Aggregates.Aggregate` calls a route's handler (`execute/2` on the aggregate,
`handle/2` on a `to: Handler, aggregate: Agg` route, or the route's `function:`) with
`Kernel.apply/3`, and reads an answer of `[]`, `nil` or `:ok` as accepted with no
events: it replies `{:ok, []}` and appends nothing. `{:ok, []}` and `{:ok, nil}` reach
the same place through `List.wrap/1`. A recognised repeat answers
`{:error, :duplicate_command}` instead, and every other accepted arm returns at least
one event (sparkle-space/sparklespace#5680). `lint/2` reports every routed arm that can
answer one of those eventless values, with no allow-list and no waiver; no runtime or
router guard backs it. `mix decree.verify.eventless` runs it over a host's routers.

A decision's `decide/2` is walked with the same tails plus `{:streams, []}`.
`Decree.Decision.Dispatch.shape/1` already refuses `[]`, `:ok`, `nil` and
`{:streams, []}` at runtime with `{:error, :decision_returned_no_events}` (and
`{:ok, _}` with `:invalid_decision_return`), so for `decide/2` this is an early answer
at lint time. The gap it fences is the aggregate handler, which the aggregate accepts
with no events.

## Mechanism

A syntax-only source walk (`Code.string_to_quoted!/2`; nothing is compiled or loaded).
Every `.ex` file under the given `paths:` is parsed and split into one scope per
`defmodule`, at any depth, nested names qualified against their enclosing chain and
nested bodies pruned from their parent's. That gives a module index: each module's
`def`/`defp`/`defdelegate` clauses by name and arity (`\\` defaults counted, a
bodyless default head applied), its `alias` table (file-wide plus its own body), its
`import`s (anywhere in its body, function-local ones included, with their `only:` and
`except:` selectors; one inside a `quote`'s `do` body belongs to the caller and is
skipped, while its options and `unquote` calls are the module's own), its
`use`s and its literal module attributes.

## Population

The caller names the entries: `%{module: module, fun: atom, kind: :aggregate |
:decision}`, one per routed handler function, read from a router's registry (`mix
decree.verify.eventless` reads `__route__/1`). Entries sharing a module and function are
walked once, as a `:decision` when any of them is one (its tails are a superset). The
walk starts at every PUBLIC `def` clause of `fun/2` in the module, a `defdelegate`
included; a `defp` is never called by `Kernel.apply/3`. `use Decree.Aggregate` injects
no `execute/2` (the command window runs in the aggregate process before the handler is
applied), so such a module is walked through its own `execute/2` like any other.

## Shapes

A TAIL value is a finding when it is one of:

  1. `[]`;
  2. `nil` (including an `if`/`unless` with no `else`);
  3. `:ok`;
  4. `{:ok, []}` or `{:ok, nil}`;
  5. a `Keyword.get/3` or `Map.get/3` default that is one of the above, or the implicit
     `nil` default of `Keyword.get/2` and `Map.get/2`;
  6. `{:streams, []}`, from a `:decision` entry only: written literally, or a
     `{:streams, value}` whose value resolves to `[]` (a binding, a module attribute, a
     followed call). Any other value passes, an unclassifiable one included: runtime
     members are the normal decision answer.

## Tail positions

The last expression of a clause body or block (`do: …` included); every branch of
`if`/`unless`, `cond`, `case`, `with` (its `do` body and every `else` clause), `try`
(`do`, `rescue`, `catch`, `else`) and `receive` (clauses and `after`); both operands of
`||` and `&&`, the right operand of `and` and `or` (a non-boolean left raises
`BadBooleanError`, so the left is never returned), both of `++` when both can be empty,
the first argument of `tap/2`, the value of the function `then/2` applies (`Kernel.tap/2`
and `Kernel.then/2` alike), and the value of a tail `=` or `|>` (a pipe is rewritten
into its call first). A falsy left of `||` and a truthy left of `&&` are never returned,
so an eventless literal there is a finding only when it can be: a truthy one (`[]`,
`:ok`, `{:ok, …}`) on the left of `||`, a `nil` on the left of `&&`.

A `with` with no `else` returns the value of a `<-` clause whose pattern it does not
match. Only a literal eventless fall-through is caught: an eventless literal a clause's
right side resolves to is a finding unless the pattern certainly matches it (a bare
variable, `_`, an equal literal, or a tuple or `[]` that matches element-wise). A guard,
a pin, a map, a struct or a non-empty list pattern may not match, so the value stays a
finding. A runtime fall-through value is a stated residual below and is not marked
`unclassified`. A bare-variable clause never falls through.

A tail VARIABLE is resolved to its binding. One bound by `var = expr` in an enclosing
block, or by a bare-variable `with` clause or `case` clause, is analysed as `expr` (the
subject, for a `case` clause), in the scope where it was bound. One bound to a followed
callee's parameter is analysed as the caller's argument, in the caller's scope. A
variable bound inside a pattern, an entry clause's own parameter, or an unbound name is
`unclassified`.

## Reachability

From a tail position the walk follows:

  * a local call to a `def`/`defp` of the same module, or to a function of a module the
    module `import`s, when it is indexed — every clause of that name and arity. An
    import anywhere in the module counts for every call in it: lexical scope is not
    modelled, so the walk cannot tell which import a call sees, and it follows every
    import whose selectors may supply the name and arity. A literal `name: arity` list,
    `:functions`, `:macros` or `:sigils` selects exactly (for a module outside the index,
    whose kinds are unknown, `:functions` and `:macros` may supply anything); any other
    selector (an attribute, a variable) may supply anything;
  * a remote call whose receiver resolves to an indexed module: an alias (through the
    module's `alias` table, chained), `__MODULE__`, `__MODULE__.X`, a nested module's
    short name, or a module atom;
  * an anonymous call `f.(args)` at a tail, resolved through its binding to a `fn` (its
    clause bodies are tails, in the `fn`'s defining scope, with its parameters bound to
    the call's arguments), a capture `&f/n` or `&Mod.f/n` (followed), or a
    `Keyword.fetch!/2`/`Keyword.get/2,3` on a resolvable options list. An `fn` handed to
    a followed helper is therefore analysed where the helper applies it at a tail; an
    `fn` handed to a call the walk does not follow (`Enum.flat_map/2`) is not analysed;
  * a `Keyword.fetch!/2` or `Keyword.get/2,3` whose options resolve to a literal keyword
    list, through bindings, parameters, `Keyword.put/3`, `Keyword.put_new/3`,
    `Keyword.merge/2` and `Keyword.delete/2` — the option's value is a tail. So a
    literal eventless value passed as an option to a followed helper that returns it is
    a finding, at the line where the caller wrote it.

A followed function already on the current call path is not re-entered (recursion); a
path deeper than 40 calls is `unclassified`.

A receiver that resolves to no indexed module is classified by the caller's
`internal?:` predicate: one it claims is `unclassified` (its source is not under the
scanned paths); any other is external and passes, as `Enum`, `Map` and a dependency's
modules do, apart from the shape-5 defaults above. `Kernel` functions pass. The Kernel
reading is never removed: an `import Kernel` selector that may leave the name out,
anywhere in the module, only puts the imports that may supply the call beside it (an
import's position is not modelled). Kernel's own exports are known, so an
`import Kernel` supplies no other name.

## Fail closed

A tail the walk cannot classify is reported `unclassified` and fails like a finding: a
routed module with no source under the scanned paths; a routed module with no public
`fun/2` in source (naming its `use`s, any of which may inject one); a call through a
variable module, `apply/2,3`, an anonymous call it cannot resolve, `Keyword.fetch!/2` or
`Keyword.get/2,3` on options it cannot resolve, a local call with no `def` in the module
and no import that could supply it (or one an `internal?` import outside the index
could, including a Kernel name an `import Kernel` selector may leave out), a local call
to a macro the module defines (a local macro) or a public `defmacro` an indexed import's
selectors may supply (an imported macro, even when another candidate is a def or
Kernel), a call to an indexed module that defines no such function in source, an
`internal?` receiver outside the index, a receiver whose first segment is an alias the
module's table (file-wide plus its own) maps to two or more different modules (the walk
models no lexical scope, so it cannot tell which one the call sees; the same target
aliased twice is no conflict), a module attribute with no literal value, a runtime field
or `Access` read, `quote`/`unquote`/`super`, and the unresolved variables above.

## Stated residuals

  * a runtime-empty list from a call the walk does not follow (`Enum.map/2` over an
    empty input, a `for` comprehension, `++` of two runtime lists);
  * the fall-through of a `with` with no `else`, when the failing clause's value is not
    a literal the walk resolves (a runtime value that fails the pattern);
  * `apply/3` with a static module and function — reported `unclassified`, never
    followed;
  * a `Decree.Aggregate.Multi` whose run produces no events;
  * a function in a module `internal?` calls external (a dependency), which is not
    read, a local call an import of such a module may supply included (its macros are
    not read either);
  * a followed function's clauses are all analysed, whichever one the caller's
    arguments select;
  * a Kernel name an `import Kernel` excludes keeps the Kernel reading beside its real
    supplier (a dependency's `then/2`), which can report a false finding, fail-closed;
  * a decision's `{:streams, members}` whose members are empty at runtime, or whose
    value the walk cannot resolve: `Decree.Decision.Dispatch.shape/1` refuses an empty or
    malformed members list at runtime, so it is not reported.

## Findings

`lint/2` answers `{:ok, %{modules: n, entries: m}}` (distinct routed modules, entry
clauses walked) or `{:error, findings}`, each a `%{kind: :eventless | :unclassified,
file, line, module, fun, shape, origin, message}` map, sorted by file and line. The
message reads `path:line  Module.fun/arity  <shape>  (reached from Module.fun clause at
path:line)`. A literal carries no line in the AST, so its line is recovered from the
enclosing construct's metadata (the previous expression's end, a `->` arrow, a `do`);
it can point at that construct.

# `entry`

```elixir
@type entry() :: %{module: module(), fun: atom(), kind: :aggregate | :decision}
```

# `finding`

```elixir
@type finding() :: %{
  kind: :eventless | :unclassified,
  file: String.t(),
  line: non_neg_integer(),
  module: module(),
  fun: {atom(), arity()},
  shape: String.t(),
  origin: map() | nil,
  message: String.t()
}
```

# `lint`

```elixir
@spec lint([entry()], keyword()) ::
  {:ok, %{modules: non_neg_integer(), entries: non_neg_integer()}}
  | {:error, [finding()]}
```

Walks `entries` over the sources under `opts[:paths]` (relative to `opts[:root]`).

Options:

  * `:root` — the directory `:paths` and the findings' paths are relative to; required;
  * `:paths` — the source directories to index, relative to `:root`; required;
  * `:internal?` — a 1-arity predicate on a module atom, true for a module whose source
    should be under `:paths`; required, so no caller treats every unindexed module as
    external by omission.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
