# graph API

## Purpose

`graph` is the data model of rille: a decision graph of one function, its
nodes, their kinds and edges, the ids that name them, and its JSON form. It
does no IO and knows nothing of the parser. A graph is built only through
`GraphBuilder`, which keeps its invariants by construction; the
[design](../design/graph.md) states them.

## Importing

```moonbit nocheck
import {
  "Luna-Flow/rille/graph",
}
```

## Names

### `FnKey`

A function of the module: its package path and its name in the package
(`name`, or `Type::name` for a method).

```mbti
pub struct FnKey {
  package_path : String
  name : String
}
pub fn FnKey::new(String, String) -> Self
pub fn FnKey::to_string(Self) -> String
```

Its text form is `package::name`, for example
`Luna-Flow/floating/binary::Binary::pown_ctx`.

### `SiteId`

A place in the source, the same wherever the call path that reaches it.

```mbti
pub struct SiteId {
  function : FnKey
  path : String
}
pub fn SiteId::to_string(Self) -> String
```

`path` is the path of edges from the function's body to the node, empty for
the function itself. Text form: `package::name` or `package::name#path`.

### `NodeId`

The id of a node in its graph: the path of edges from the root.

```mbti
pub struct NodeId {
  // private fields
}
pub fn NodeId::to_string(Self) -> String
```

Only a `GraphBuilder` makes ids.

## Kinds

### `NodeKind`

What a node stands for, with the source text that belongs to that kind.

```mbti
pub(all) enum NodeKind {
  Function(FnKey)
  If(cond~ : String)
  Guard(cond~ : String)
  Match(scrutinee~ : String)
  Arm(pattern~ : String)
  ArmGuard(cond~ : String)
  While(cond~ : String)
  For(cond~ : String?)
  ForIn(binders~ : String, iterable~ : String)
  Try
  Return(value~ : String?)
  Raise(value~ : String)
  Abort(args~ : String)
  Panic
  Call(callee~ : String, resolution~ : Resolution, target~ : TargetChoice)
  Closure(text~ : String)
}
pub fn NodeKind::is_exit(Self) -> Bool
pub fn NodeKind::is_test(Self) -> Bool
pub fn NodeKind::name(Self) -> String
```

Texts are as written in the source. `For`'s `cond` is `None` for a `for`
without a condition and `Return`'s `value` for a bare `return`. The guard of
an arm, `p if g => b`, is an `ArmGuard(cond=g)` of its own, the child of the
`Arm` under the `guard` edge: a test made after the pattern matched, which
sends the flow to the next arm when it fails. An arm without a guard has no
such child and is not a test. `is_test` holds for `If`, `Guard`, `Match`,
`ArmGuard`, `While`, `For`, `ForIn` and `Try`; `is_exit` for `Return`,
`Raise`, `Abort` and `Panic`. `name` is the name in output: `fn`, `if`,
`guard`, `match`, `arm`, `arm_guard`, `while`, `for`, `for_in`, `try`,
`return`, `raise`, `abort`, `panic`, `call`, `closure`.

### `EdgeKind`

The part of the parent an edge leads into.

```mbti
pub(all) enum EdgeKind {
  Body
  Cond
  Then
  Else
  Arm
  Guard
  Call
  Return
}
pub fn EdgeKind::name(Self) -> String
```

`Body` leads to a step of a body, `Cond` to a step inside a condition or a
scrutinee, `Then` and `Else` to the steps of the branches, `Arm` to an arm
or handler, `Guard` from an arm to its `ArmGuard`, `Call` from a call to the
callee's `Function` node and `Return` to a step inside a returned, raised or
aborted value.

### `Resolution`

What became of a call.

```mbti
pub(all) enum Resolution {
  Expanded(FnKey)
  BackEdge(FnKey)
  DepthLimit(FnKey)
  Local(name~ : String)
  Unresolved(Unresolved)
}
```

`Expanded`: the callee's body is the child under the `call` edge.
`BackEdge`: the callee is already on the path from the root. `DepthLimit`:
resolved, not followed. `Local`: a local function or closure binding.

### `TargetChoice`

Whether the file of a call's definition was chosen by a target condition
rille understands.

```mbti
pub(all) enum TargetChoice {
  Known
  Unknown(file~ : String)
}
```

`Unknown(file~)`: the file's condition in `moon.pkg` has a form rille does
not understand, so it was read for every target and the resolution may be
wrong or ambiguous because of it.

### `Unresolved`

Why a call was not resolved; each reason says what the source does not
write.

```mbti
pub(all) enum Unresolved {
  UntypedReceiver(method_name~ : String, candidates~ : Array[FnKey])
  MissingMethod(type_name~ : String, method_name~ : String, package_path~ : String)
  NoDefinition(name~ : String, package_path~ : String)
  NotImported(package_alias~ : String, package_path~ : String)
  OutsideModule(package_path~ : String)
  Ambiguous(name~ : String, definitions~ : Array[(FnKey, @source.Span)])
  ExpressionCallee
  ExternStub(FnKey)
}
pub fn Unresolved::code(Self) -> String
pub fn Unresolved::message(Self) -> String
```

`code` is a short name for output (`untyped_receiver`, `missing_method`,
`no_definition`, `not_imported`, `outside_module`, `ambiguous`,
`expression_callee`, `extern_stub`); `message` a sentence.

## Graphs

### `Node`, `Edge`

```mbti
pub struct Node {
  id : NodeId
  site : SiteId
  kind : NodeKind
  span : @source.Span
  // private fields
}
pub fn Node::edges(Self) -> Iter[Edge]

pub struct Edge {
  kind : EdgeKind
  to : NodeId
}
```

`edges` gives the edges to the children in source order; edges of one kind
form a sequence (the `then` edges of an `if` are the steps of its
then-branch).

### `Graph`

```mbti
pub struct Graph {
  module_name : String
  package_path : String
  entry : String
  depth : Int
  target : String
  // private fields
}
pub fn Graph::children(Self, Node) -> Iter[(EdgeKind, Node)]
pub fn Graph::length(Self) -> Int
pub fn Graph::node(Self, NodeId) -> Node?
pub fn Graph::nodes(Self) -> Iter[Node]
pub fn Graph::root(Self) -> Node
pub fn Graph::tests(Self) -> Iter[Node]
```

`target` is the target whose files the graph was drawn from. `nodes` gives
every node in pre-order, the order in which the flow meets
them; `tests` the test nodes in that order. `node` finds a node by id in
constant time; `children` follows a node's edges.

### `GraphBuilder`

```mbti
pub struct GraphBuilder {
  // private fields
}
pub fn GraphBuilder::new(module_name~ : String, package_path~ : String, entry~ : String, depth~ : Int, target~ : String, root~ : FnKey, span~ : @source.Span) -> (Self, NodeId)
pub fn GraphBuilder::add(Self, NodeId, EdgeKind, NodeKind, @source.Span) -> NodeId raise GraphError
pub fn GraphBuilder::finish(Self) -> Graph
```

`new` makes a builder whose root is the `Function` node of `root`. `add`
adds a child under an edge and returns its id; the parent must be on the
open path (the last node added or one of its ancestors), and adding to an
ancestor closes the nodes below it. `finish` returns the graph built so far;
the builder may go on without changing it.

```moonbit
test "build a graph" {
  let (b, root) = @graph.GraphBuilder::new(
    module_name="m", package_path="m", entry="f", depth=0, target="native",
    root=@graph.FnKey::new("m", "f"),
    span={ file: "a.mbt", start_line: 1, start_col: 1, end_line: 3, end_col: 2 },
  )
  let test_if = b.add(root, Body, If(cond="x > 0"), { file: "a.mbt", start_line: 2, start_col: 3, end_line: 2, end_col: 20 })
  ignore(b.add(test_if, Then, Return(value=Some("1")), { file: "a.mbt", start_line: 2, start_col: 12, end_line: 2, end_col: 20 }))
  let graph = b.finish()
  inspect(graph.tests().map(n => "\{n.site}").join(" "), content="m::f#body0")
}
```

### `GraphError`

```mbti
pub suberror GraphError {
  UnknownParent(NodeId)
  ClosedParent(NodeId)
}
```

`UnknownParent`: the parent is not a node of this builder. `ClosedParent`:
it is, but adding to it would break pre-order.

## JSON form

### `schema_version`, `Graph::to_json`, `Node::to_json`

```mbti
pub let schema_version : String
pub fn Graph::to_json(Self) -> @json.Json
pub fn Node::to_json(Self) -> @json.Json
```

The document of schema `rille.graph/1`, with fields in a fixed order. As
printed by rille (`Graph::document`) it has `producer` after `schema`;
`Graph::to_json` gives the same document without it.

```json
{
  "schema": "rille.graph/1",
  "producer": {
    "name": "rille",
    "version": "0.1.0",
    "commit": null,
    "commit_unknown": "not embedded: built from a source checkout",
    "module": "Luna-Flow/floating",
    "module_commit": "f403bd66..."
  },
  "module": "Luna-Flow/floating",
  "package": "Luna-Flow/floating/interval",
  "entry": "mul_interval_impl",
  "depth": 2,
  "target": "native",
  "root": "Luna-Flow/floating/interval::mul_interval_impl",
  "nodes": [
    {
      "id": "<node id>",
      "site": "<site id>",
      "kind": "call",
      "callee": "multiplication_bounds",
      "resolution": { "status": "expanded", "target": "<fn key>" },
      "span": { "file": "src/interval/interval.mbt", "start": [950, 17], "end": [950, 55] },
      "edges": [{ "kind": "call", "to": "<node id>" }]
    }
  ]
}
```

After `kind` come the texts of the kind: `function` (fn); `cond` (if,
guard, arm_guard, while, and for when written); `scrutinee` (match);
`pattern` (arm); `binders` and `iterable` (for_in); `value`
(return when written, raise); `args` (abort); `callee`, `resolution` and,
for a `TargetChoice` of `Unknown`, `target_unknown` with the file (call);
`text` (closure). A `resolution` has `status` `expanded`,
`back_edge` or `depth_limit` with `target`; `local` with `name`; or
`unresolved` with `reason` (the `Unresolved::code`), `message` and, where
the reason has them, `candidates`.

## Producer

### `Producer`, `Commit`

```mbti
pub(all) struct Producer {
  name : String
  version : String
  commit : Commit
  module_commit : Commit
}
pub(all) enum Commit {
  Known(String)
  Unknown(reason~ : String)
}
pub fn Producer::tool_text(Self) -> String
pub fn Producer::summary(Self, Graph) -> String
pub fn Producer::to_json(Self, Graph) -> @json.Json
pub fn Graph::document(Self, Producer) -> @json.Json
```

What produced a graph: the tool's `name` and `version`, the `commit` it was
built from, and the `module_commit` checked out at the analysed module's
root (its `HEAD`; uncommitted changes in the working tree are not seen). A
commit that is not known is `Unknown` with the reason, never a guess.

`tool_text` is `rille 0.1.0 (commit <hash>)` or `rille 0.1.0 (commit
unknown: <reason>)`. `summary` adds the module and its commit, the package,
entry, depth and target of the graph, on one line; the renderers print it
as a comment. `to_json` is the `producer` object, fields in this order:
`name`, `version`, `commit`, `module` and `module_commit`; a commit that is
not known is `null` and is followed by `commit_unknown` or
`module_commit_unknown` with the reason. `document` is what `rille graph
--format json` prints: the graph's JSON form with `producer` after
`schema`.

```moonbit
test "producer" {
  let producer : @graph.Producer = {
    name: "rille",
    version: "0.1.0",
    commit: Unknown(reason="not embedded"),
    module_commit: Known("3bea539c"),
  }
  inspect(producer.tool_text(), content="rille 0.1.0 (commit unknown: not embedded)")
}
```

## Complete public interface

<!-- generated-api-start -->
```mbti
// Generated using `moon info`, DON'T EDIT IT
package "Luna-Flow/rille/graph"

import {
  "Luna-Flow/rille/source",
  "moonbitlang/core/debug",
  "moonbitlang/core/json",
}

// Values
pub let schema_version : String

// Errors
pub suberror GraphError {
  UnknownParent(NodeId)
  ClosedParent(NodeId)
}
pub impl Show for GraphError

// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum Commit {
  Known(String)
  Unknown(reason~ : String)
}

#derive(Eq, @debug.Debug)
pub struct Edge {
  kind : EdgeKind
  to : NodeId
}

#derive(Eq, Hash, @debug.Debug)
pub(all) enum EdgeKind {
  Body
  Cond
  Then
  Else
  Arm
  Guard
  Call
  Return
}
pub fn EdgeKind::name(Self) -> String

#derive(Compare, Eq, Hash, @debug.Debug)
pub struct FnKey {
  package_path : String
  name : String
}
pub fn FnKey::new(String, String) -> Self
pub fn FnKey::to_string(Self) -> String
pub impl Show for FnKey

pub struct Graph {
  module_name : String
  package_path : String
  entry : String
  depth : Int32
  target : String
  // private fields
}
pub fn Graph::children(Self, Node) -> Iter[(EdgeKind, Node)]
pub fn Graph::document(Self, Producer) -> @json.Json
pub fn Graph::length(Self) -> Int32
pub fn Graph::node(Self, NodeId) -> Node?
pub fn Graph::nodes(Self) -> Iter[Node]
pub fn Graph::root(Self) -> Node
pub fn Graph::tests(Self) -> Iter[Node]
pub fn Graph::to_json(Self) -> @json.Json
pub impl @json.ToJson for Graph

pub struct GraphBuilder {
  // private fields
}
pub fn GraphBuilder::add(Self, NodeId, EdgeKind, NodeKind, @source.Span) -> NodeId raise GraphError
pub fn GraphBuilder::finish(Self) -> Graph
pub fn GraphBuilder::new(module_name~ : String, package_path~ : String, entry~ : String, depth~ : Int32, target~ : String, root~ : FnKey, span~ : @source.Span) -> (Self, NodeId)

#derive(@debug.Debug)
pub struct Node {
  id : NodeId
  site : SiteId
  kind : NodeKind
  span : @source.Span
  // private fields
}
pub fn Node::edges(Self) -> Iter[Edge]
pub fn Node::to_json(Self) -> @json.Json
pub impl @json.ToJson for Node

#derive(Compare, Eq, Hash, @debug.Debug)
pub struct NodeId {
  // private fields
}
pub fn NodeId::to_string(Self) -> String
pub impl Show for NodeId

#derive(Eq, @debug.Debug)
pub(all) enum NodeKind {
  Function(FnKey)
  If(cond~ : String)
  Guard(cond~ : String)
  Match(scrutinee~ : String)
  Arm(pattern~ : String)
  ArmGuard(cond~ : String)
  While(cond~ : String)
  For(cond~ : String?)
  ForIn(binders~ : String, iterable~ : String)
  Try
  Return(value~ : String?)
  Raise(value~ : String)
  Abort(args~ : String)
  Panic
  Call(callee~ : String, resolution~ : Resolution, target~ : TargetChoice)
  Closure(text~ : String)
}
pub fn NodeKind::is_exit(Self) -> Bool
pub fn NodeKind::is_test(Self) -> Bool
pub fn NodeKind::name(Self) -> String

#derive(Eq, @debug.Debug)
pub(all) struct Producer {
  name : String
  version : String
  commit : Commit
  module_commit : Commit
}
pub fn Producer::summary(Self, Graph) -> String
pub fn Producer::to_json(Self, Graph) -> @json.Json
pub fn Producer::tool_text(Self) -> String

#derive(Eq, @debug.Debug)
pub(all) enum Resolution {
  Expanded(FnKey)
  BackEdge(FnKey)
  DepthLimit(FnKey)
  Local(name~ : String)
  Unresolved(Unresolved)
}

#derive(Compare, Eq, Hash, @debug.Debug)
pub struct SiteId {
  function : FnKey
  path : String
}
pub fn SiteId::to_string(Self) -> String
pub impl Show for SiteId

#derive(Eq, @debug.Debug)
pub(all) enum TargetChoice {
  Known
  Unknown(file~ : String)
}

#derive(Eq, @debug.Debug)
pub(all) enum Unresolved {
  UntypedReceiver(method_name~ : String, candidates~ : Array[FnKey])
  MissingMethod(type_name~ : String, method_name~ : String, package_path~ : String)
  NoDefinition(name~ : String, package_path~ : String)
  NotImported(package_alias~ : String, package_path~ : String)
  OutsideModule(package_path~ : String)
  Ambiguous(name~ : String, definitions~ : Array[(FnKey, @source.Span)])
  ExpressionCallee
  ExternStub(FnKey)
}
pub fn Unresolved::code(Self) -> String
pub fn Unresolved::message(Self) -> String

// Type aliases

// Traits
```
<!-- generated-api-end -->
