//  A user enclave in Varc (proof-enclaves.md E4): a directed graph, a proof enclave (proof-enclaves.md EN10,
//  E3). Its vertices are cells, and each vertex's edges point at the cells of other vertices
//  (or its own), so a vertex is shared by every edge into it and the edges may make cycles,
//  which ownership forbids; the heap engine proves the operations against the graph's model,
//  its vertices' degrees and its edges, so that clients treat a graph as that value.
import Verada.Containers.Functional.Sequences;
import Verada.Footprints;
package Graphs @Annotate(Verada, Enclave) {
    import Ada.Unchecked_Deallocation;
    pub let Max_Vertices = 1000;
    pub let Max_Degree = 8;
    pub subtype Vertex_Count_Type = Natural range 0..=Max_Vertices;
    pub subtype Vertex = Positive range 1..=Max_Vertices;
    pub subtype Degree_Type = Natural range 0..=Max_Degree;

    //  an edge, from a vertex to a vertex
    pub struct Edge {
        pub From, To: Vertex,
    }

    pub package Edge_Sequences = new Verada.Containers.Functional.Sequences<Edge>;
    pub package Degree_Sequences = new Verada.Containers.Functional.Sequences<Degree_Type>;
    pub use type Edge_Sequences.Sequence;
    pub use type Degree_Sequences.Sequence;

    //  a graph's value: the out-degree of each vertex, the vertices being 1 .. the count of
    //  degrees; and the edges, each once, in the order they were added
    pub struct Graph_Model {
        pub Degrees: Degree_Sequences.Sequence,
        pub Edges: Edge_Sequences.Sequence,
    }

    pub type Graph = limited private @Default_Initial_Condition(Degree_Sequences.Length(Model(Graph).Degrees) == 0 && Edge_Sequences.Length(Model(Graph).Edges) == 0) @Finalizable(Finalize => Clear, Relaxed_Finalization => True);
    pub ghost fn Model(G: Graph) -> Graph_Model;

    pub fn Vertex_Count(G: Graph) -> Vertex_Count_Type
        ensures result == Degree_Sequences.Length(Model(G).Degrees);

    //  whether a graph's model has an edge from From to To (of the model, not the graph, so
    //  that clients see what it says: a function of an enclave object is opaque to them)
    pub ghost fn Has_Edge(M: Graph_Model, From, To: Vertex) -> Boolean = exists K in 1..=Edge_Sequences.Length(M.Edges) => Edge_Sequences.Get(M.Edges, K) == (From, To) as Edge;

    //  how many edges leave V
    pub fn Out_Degree(G: Graph, V: Vertex) -> Degree_Type
        requires V <= Vertex_Count(G)
        ensures result == Degree_Sequences.Get(Model(G).Degrees, V);

    fn Free = new Ada.Unchecked_Deallocation<Vertex_Cell, Vertex_Ptr>;

    //  whether an edge leads from From to To, found by following From's edges
    pub fn Adjacent(G: Graph, From, To: Vertex) -> Boolean
        requires From <= Vertex_Count(G) && To <= Vertex_Count(G)
        ensures result == Has_Edge(Model(G), From, To)
    {
        let V: Vertex_Ptr = G.Table[From];
        for K in 1..=V.Degree {
            invariant forall J in 1..=K - 1 => V.Links[J] != G.Table[To];
            if V.Links[K] == G.Table[To] {
                return True;
            }
        }
        return False;
    }

    //  a new vertex, with no edges, numbered after the others
    pub fn Add_Vertex(G: inout Graph, V: out Vertex)
        requires Vertex_Count(G) < Max_Vertices
        ensures (Model(G).Degrees == Degree_Sequences.Add(old(Model(G)).Degrees, 0)) & (Model(G).Edges == old(Model(G)).Edges) & (V == Vertex_Count(G))
    {
        let N: Vertex_Ptr = new Vertex_Cell(Id: G.Count + 1, Degree: 0, Links: (others: null));
        G.Count = G.Count + 1;
        G.Table[G.Count] = N;
        G.Repr = Vertex_Cells.Add(G.Repr, N);
        G.Degree_List = Degree_Sequences.Add(G.Degree_List, 0);
        V = G.Count;
    }

    //  an edge from From to To (to itself when they are the same), not there before
    pub fn Add_Edge(G: inout Graph, From, To: Vertex)
        requires From <= Vertex_Count(G) && To <= Vertex_Count(G) && Out_Degree(G, From) < Max_Degree && !Has_Edge(Model(G), From, To)
        ensures (Model(G).Degrees == Degree_Sequences.Set(old(Model(G)).Degrees, From, Degree_Sequences.Get(old(Model(G)).Degrees, From) + 1)) & (Model(G).Edges == Edge_Sequences.Add(old(Model(G)).Edges, (From, To) as Edge))
    {
        G.Table[From].Degree = G.Table[From].Degree + 1;
        G.Table[From].Links[G.Table[From].Degree] = G.Table[To];
        G.Degree_List = Degree_Sequences.Set(G.Degree_List, From, G.Table[From].Degree);
        G.Edge_List = Edge_Sequences.Add(G.Edge_List, (From, To) as Edge);
        G.Slot_List = Degree_Sequences.Add(G.Slot_List, G.Table[From].Degree);
    }

    //  the last vertex's cell freed (its edges and the edges into it are the caller's to
    //  forget)
    fn Drop_Last(G: inout Graph)
        @Always_Terminates
        requires G.Count > 0 && Cells_Kept(G)
        ensures G.Count == old(G.Count) - 1 && Cells_Kept(G) && Degree_Sequences.Length(G.Degree_List) == Degree_Sequences.Length(old(G.Degree_List)) && Edge_Sequences.Length(G.Edge_List) == Edge_Sequences.Length(old(G.Edge_List)) && Degree_Sequences.Length(G.Slot_List) == Degree_Sequences.Length(old(G.Slot_List))
    {
        var Old: Vertex_Ptr = G.Table[G.Count];
        G.Table[G.Count] = null;
        G.Repr = Vertex_Cells.Remove(G.Repr, Old);
        G.Count = G.Count - 1;
        Free(&Old);
    }

    //  every vertex and edge removed (and the cells freed: a graph that ends is cleared)
    pub fn Clear(G: inout Graph)
        ensures Vertex_Count(G) == 0 && Edge_Sequences.Length(Model(G).Edges) == 0
    {
        G.Edge_List = Edge_Sequences.Empty_Sequence;
        G.Slot_List = Degree_Sequences.Empty_Sequence;
        G.Degree_List = Degree_Sequences.Empty_Sequence;
        while G.Count > 0 {
            invariant Cells_Kept(G);
            invariant Degree_Sequences.Length(G.Degree_List) == 0 && Edge_Sequences.Length(G.Edge_List) == 0 && Degree_Sequences.Length(G.Slot_List) == 0;
            decreases G.Count;
            Drop_Last(&G);
        }
    }

    pub(child) type Vertex_Cell;
    pub(child) type Vertex_Ptr = *Vertex_Cell;
    pub(child) type Targets = [1..=Max_Degree]Vertex_Ptr;

    //  a vertex: its number, and the cells its edges lead to, the first Degree of Links
    pub(child) struct Vertex_Cell {
        Id: Vertex,
        Degree: Degree_Type = 0,
        Links: Targets = (others: null),
    }

    pub(child) package Vertex_Cells = new Verada.Footprints<Vertex_Ptr>;
    pub(child) type Vertex_Table = [Vertex]Vertex_Ptr;

    //  vertex I is the cell Table (I), whose number is I, in the footprint, its degree the
    //  model's; each of its edges leads to a vertex's cell and is an edge of the model; each
    //  edge of the model is one of its From's edges; the footprint holds exactly the cells
    pub(child) type Graph = limited struct {
        Count: Vertex_Count_Type = 0,
        Table: Vertex_Table = (others: null),
        Repr: Vertex_Cells.Cells = Vertex_Cells.Empty,
        Degree_List: Degree_Sequences.Sequence = Degree_Sequences.Empty_Sequence,
        Edge_List: Edge_Sequences.Sequence = Edge_Sequences.Empty_Sequence,
        //  each edge's place among its From's links (the invariant names the link an edge is)
        Slot_List: Degree_Sequences.Sequence = Degree_Sequences.Empty_Sequence,
    } @Type_Invariant(Well_Formed(Graph))

    //  the cells: vertex I's is Table (I), whose number is I, and the footprint holds exactly
    //  them (all that clearing needs)
    pub(child) fn Cells_Kept(G: Graph) -> Boolean = (forall I in 1..=G.Count => G.Table[I] != null && Vertex_Cells.Contains(G.Repr, G.Table[I]) && G.Table[I].Id == I) && (forall P in G.Repr => exists I in 1..=G.Count => G.Table[I] == P);

    pub(child) fn Well_Formed(G: Graph) -> Boolean = Cells_Kept(G) && Degree_Sequences.Length(G.Degree_List) == G.Count && (forall I in 1..=G.Count => G.Table[I].Degree == Degree_Sequences.Get(G.Degree_List, I) && (forall K in 1..=G.Table[I].Degree => K <= Max_Degree && G.Table[I].Links[K] != null && Vertex_Cells.Contains(G.Repr, G.Table[I].Links[K]) && G.Table[I].Links[K].Id <= G.Count && G.Table[G.Table[I].Links[K].Id] == G.Table[I].Links[K] && (exists E in 1..=Edge_Sequences.Length(G.Edge_List) => Edge_Sequences.Get(G.Edge_List, E) == (I, G.Table[I].Links[K].Id) as Edge))) && Degree_Sequences.Length(G.Slot_List) == Edge_Sequences.Length(G.Edge_List) && (forall E in 1..=Edge_Sequences.Length(G.Edge_List) => Edge_Sequences.Get(G.Edge_List, E).From <= G.Count && Edge_Sequences.Get(G.Edge_List, E).To <= G.Count && Degree_Sequences.Get(G.Slot_List, E) >= 1 && Degree_Sequences.Get(G.Slot_List, E) <= G.Table[Edge_Sequences.Get(G.Edge_List, E).From].Degree && Degree_Sequences.Get(G.Slot_List, E) <= Max_Degree && G.Table[Edge_Sequences.Get(G.Edge_List, E).From].Links[Degree_Sequences.Get(G.Slot_List, E)] == G.Table[Edge_Sequences.Get(G.Edge_List, E).To]);
    pub(child) fn Model(G: Graph) -> Graph_Model = (Degrees: G.Degree_List, Edges: G.Edge_List);
    pub(child) fn Vertex_Count(G: Graph) -> Vertex_Count_Type = G.Count;
    pub(child) fn Out_Degree(G: Graph, V: Vertex) -> Degree_Type = G.Table[V].Degree;
}
