-- | Rewriting of open hypergraphs, modulo Frobenius wiring, with individual
-- rules or a compiled discrimination net sharing matching work across rules.
-- A rule's common boundary is the interface retained when replacing its left side.
-- Fixed-pattern matches are injective on nodes and box occurrences. The left boundary must also
-- be injective; the right boundary may join interface nodes. This is a restricted
-- DPO rewriting operation, not a general pushout-complement search for DPOI.
--
-- See "Proarrow.Tools.HypergraphRewrite.Completion" for Knuth–Bendix-style
-- completion and "Proarrow.Tools.HypergraphRewrite.Laws" for rule construction
-- from categorical laws.
module Proarrow.Tools.HypergraphRewrite
  ( -- * Rules
    Rule
  , rule
  , (==>)
  , Parameter (Literal, Variable)
  , mapParameter
  , zipParameters
  , parameterRule
  , subgraphRule
  , withSortParameters
  , Port (..)
  , PortSymmetry (..)
  , PortGraph (..)
  , portRule
  , parameterPortRule
  , parameterPortExample
  , parameterPortVariants
  , parameterPortRuleWith

    -- * Rewriting
  , rewrites
  , rewriteBatch
  , CompiledRules
  , compileRules
  , compileReducingRules
  , rewritesCompiled
  , rewriteBatchCompiled

    -- * Normalisation
  , RewriteLimits (..)
  , unlimitedRewrites
  , NormalisationStatus (..)
  , NormalisationResult (..)
  , normalise
  ) where

import Data.Vector qualified as V
import Prelude

import Proarrow.Category.Instance.OpenHypergraph (OPENHG, WireSorts, Wires, unsafeOpenHypergraph)
import Proarrow.Core (CategoryOf (..), (//))
import Proarrow.Optic.Iso (DecidableIso)
import Proarrow.Tools.HypergraphRewrite.Internal
  ( Graph (..)
  , NormalisationResult (..)
  , NormalisationStatus (..)
  , Parameter (Literal, Variable)
  , Port (..)
  , PortGraph (..)
  , PortSymmetry (..)
  , Prepared
  , RewriteLimits (..)
  , Rule (..)
  , deletedImages
  , graph
  , mapParameter
  , matches
  , nonConflictingBy
  , normaliseBy
  , parameterPortExample
  , parameterPortRule
  , parameterPortRuleWith
  , parameterPortVariants
  , parameterRule
  , portRule
  , replaceMany
  , replaceSelected
  , rule
  , subgraphRule
  , unlimitedRewrites
  , withSortParameters
  , zipParameters
  )
import Proarrow.Tools.HypergraphRewrite.Internal.Matcher (CompiledRules (..), compileRuleSet, compiledMatches)

infix 1 ==>

-- | An oriented rule written left to right. This checks the same boundary
-- conditions as 'rule'.
(==>) :: (a :: OPENHG s l) ~> b -> a ~> b -> Either String (Rule s l)
==> :: forall (s :: Kind) (l :: Kind) (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> (a ~> b) -> Either String (Rule s l)
(==>) = (a ~> b) -> (a ~> b) -> Either String (Rule s l)
forall (s :: Kind) (l :: Kind) (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> (a ~> b) -> Either String (Rule s l)
rule

-- | All valid single-step rewrites, in box and node enumeration order.
-- Works for closed hosts (empty boundaries) as well as open hosts. No result
-- deletes a node used by an unmatched box or the host boundary. Unmatched nodes,
-- including isolated nodes, are retained. Distinct matches may produce isomorphic results;
-- results are not deduplicated. Matching is a finite exhaustive search.
-- Compatible label/arity candidates are cached per pattern box, and mapped
-- ports constrain later boxes through incidence indices. Labels only need 'Eq'.
rewrites
  :: forall {s} l a b
   . (Eq l, DecidableIso s)
  => Rule s l
  -> (a :: OPENHG s l) ~> b
  -> [Wires (WireSorts a) ~> (Wires (WireSorts b) :: OPENHG s l)]
rewrites :: forall {s :: Kind} (l :: Kind) (a :: OPENHG s l) (b :: OPENHG s l).
(Eq l, DecidableIso s) =>
Rule s l
-> (a ~> b) -> [Wires (WireSorts a) ~> Wires (WireSorts b)]
rewrites (Rule Graph s (LabelTest l)
lhs [l] -> Maybe (Graph s l)
instantiate) a ~> b
host =
  let g :: Graph s l
g = (a ~> b) -> Graph s l
forall (s :: Kind) (l :: Kind) (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph a ~> b
host
  in a ~> b
DecCospan a b
host DecCospan a b
-> ((Ob a, Ob b) =>
    [DecCospan
       (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
       (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b)))))))])
-> [DecCospan
      (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
      (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b)))))))]
forall {k1 :: Kind} {k2 :: Kind} (p :: k1 +-> k2) (a :: k2)
       (b :: k1) (r :: Kind).
Profunctor p =>
p a b -> ((Ob a, Ob b) => r) -> r
//
       [ [SomeSort s]
-> [Int]
-> [Int]
-> [Box l Int]
-> Wires (PortSorts (FH (UN FH (UN SUB (UN DC a)))))
   ~> Wires (PortSorts (FH (UN FH (UN SUB (UN DC b)))))
forall {s :: Kind} (l :: Kind) (as :: [s]) (bs :: [s]).
(SortList as, SortList bs) =>
[SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires as ~> Wires bs
unsafeOpenHypergraph [SomeSort s]
nodes [Int]
ins [Int]
outs [Box l Int]
boxes
       | (Match
match, [l]
labels) <- Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
forall (l :: Kind) (s :: Kind).
(Eq l, DecidableIso s) =>
Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matches Graph s (LabelTest l)
lhs Graph s l
g
       , Just Graph s l
rhs <- [[l] -> Maybe (Graph s l)
instantiate [l]
labels]
       , let Graph [SomeSort s]
nodes [Int]
ins [Int]
outs [Box l Int]
boxes = Graph s (LabelTest l)
-> Graph s l -> Graph s l -> [Match] -> Graph s l
forall (s :: Kind) (p :: Kind) (l :: Kind).
Graph s p -> Graph s l -> Graph s l -> [Match] -> Graph s l
replaceMany Graph s (LabelTest l)
lhs Graph s l
rhs Graph s l
g [Match
match]
       ]
rewrites Rule s l
r a ~> b
host = (((),
  DecCospan
    (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
    (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b))))))))
 -> DecCospan
      (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
      (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b))))))))
-> [((),
     DecCospan
       (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
       (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b))))))))]
-> [DecCospan
      (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
      (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b)))))))]
forall (a :: Kind) (b :: Kind). (a -> b) -> [a] -> [b]
map ((),
 DecCospan
   (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
   (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b))))))))
-> DecCospan
     (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
     (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b)))))))
forall (a :: Kind) (b :: Kind). (a, b) -> b
snd (CompiledRules () s l
-> (a ~> b)
-> [((),
     DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a))))))
     ~> DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b)))))))]
forall {s :: Kind} (key :: Kind) (l :: Kind) (a :: OPENHG s l)
       (b :: OPENHG s l).
(Eq l, DecidableIso s) =>
CompiledRules key s l
-> (a ~> b) -> [(key, Wires (WireSorts a) ~> Wires (WireSorts b))]
rewritesCompiled ((String -> CompiledRules () s l)
-> (CompiledRules () s l -> CompiledRules () s l)
-> Either String (CompiledRules () s l)
-> CompiledRules () s l
forall (a :: Kind) (c :: Kind) (b :: Kind).
(a -> c) -> (b -> c) -> Either a b -> c
either String -> CompiledRules () s l
forall a. HasCallStack => String -> a
error CompiledRules () s l -> CompiledRules () s l
forall (a :: Kind). a -> a
id ([((), Rule s l)] -> Either String (CompiledRules () s l)
forall (key :: Kind) (l :: Kind) (s :: Kind).
(Ord key, Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRules [((), Rule s l
r)])) a ~> b
host)

-- | Apply a greedy maximal set of non-conflicting matches of one rule from a
-- single host snapshot, rebuilding the graph once. Returns the number applied
-- and the result, or @(0, host)@ when the rule does not match.
--
-- Matches are considered in the same order as 'rewrites'. They may share
-- preserved interface nodes, including adjacent regions connected through those
-- nodes. They cannot share boxes, or delete a node used by another chosen match.
-- Each replacement gets fresh nodes and all interfaces are glued simultaneously.
-- This selects one maximal batch, not a maximum-size batch or all possible batches.
-- New matches created by replacement are left for a later batch.
rewriteBatch
  :: forall {s} l as bs
   . (Eq l, DecidableIso s)
  => Rule s l
  -> (Wires as :: OPENHG s l) ~> Wires bs
  -> (Int, Wires as ~> (Wires bs :: OPENHG s l))
rewriteBatch :: forall {s :: Kind} (l :: Kind) (as :: [s]) (bs :: [s]).
(Eq l, DecidableIso s) =>
Rule s l -> (Wires as ~> Wires bs) -> (Int, Wires as ~> Wires bs)
rewriteBatch (Rule Graph s (LabelTest l)
lhs [l] -> Maybe (Graph s l)
instantiate) Wires as ~> Wires bs
host =
  let g :: Graph s l
g = (Wires as ~> Wires bs) -> Graph s l
forall (s :: Kind) (l :: Kind) (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph Wires as ~> Wires bs
host
      candidates :: [(Graph s l, Match)]
candidates = [(Graph s l
rhs, Match
match) | (Match
match, [l]
labels) <- Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
forall (l :: Kind) (s :: Kind).
(Eq l, DecidableIso s) =>
Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matches Graph s (LabelTest l)
lhs Graph s l
g, Just Graph s l
rhs <- [[l] -> Maybe (Graph s l)
instantiate [l]
labels]]
      chosen :: [(Graph s l, Match)]
chosen = (Graph s l -> Match -> IntSet)
-> [(Graph s l, Match)] -> [(Graph s l, Match)]
forall (a :: Kind).
(a -> Match -> IntSet) -> [(a, Match)] -> [(a, Match)]
nonConflictingBy (\Graph s l
_ (IntMap Int
m, IntSet
_) -> Graph s (LabelTest l) -> IntMap Int -> IntSet
forall (s :: Kind) (l :: Kind). Graph s l -> IntMap Int -> IntSet
deletedImages Graph s (LabelTest l)
lhs IntMap Int
m) [(Graph s l, Match)]
candidates
  in case [(Graph s l, Match)]
chosen of
       [] -> (Int
0, Wires as ~> Wires bs
host)
       [(Graph s l, Match)]
_ ->
         Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
host DecCospan (Wires as) (Wires bs)
-> ((Ob (Wires as), Ob (Wires bs)) =>
    (Int, DecCospan (Wires as) (Wires bs)))
-> (Int, DecCospan (Wires as) (Wires bs))
forall {k1 :: Kind} {k2 :: Kind} (p :: k1 +-> k2) (a :: k2)
       (b :: k1) (r :: Kind).
Profunctor p =>
p a b -> ((Ob a, Ob b) => r) -> r
//
           let Graph [SomeSort s]
nodes [Int]
ins [Int]
outs [Box l Int]
boxes = Graph s l
-> [(Graph s (LabelTest l), Graph s l, Match)] -> Graph s l
forall (s :: Kind) (l :: Kind) (p :: Kind).
Graph s l -> [(Graph s p, Graph s l, Match)] -> Graph s l
replaceSelected Graph s l
g [(Graph s (LabelTest l)
lhs, Graph s l
rhs, Match
match) | (Graph s l
rhs, Match
match) <- [(Graph s l, Match)]
chosen]
           in ([(Graph s l, Match)] -> Int
forall (a :: Kind). [a] -> Int
forall (t :: Kind -> Kind) (a :: Kind). Foldable t => t a -> Int
length [(Graph s l, Match)]
chosen, [SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires as ~> Wires bs
forall {s :: Kind} (l :: Kind) (as :: [s]) (bs :: [s]).
(SortList as, SortList bs) =>
[SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires as ~> Wires bs
unsafeOpenHypergraph [SomeSort s]
nodes [Int]
ins [Int]
outs [Box l Int]
boxes)
rewriteBatch Rule s l
r Wires as ~> Wires bs
host = CompiledRules () s l
-> (Wires as ~> Wires bs) -> (Int, Wires as ~> Wires bs)
forall {s :: Kind} (key :: Kind) (l :: Kind) (as :: [s])
       (bs :: [s]).
(Eq l, DecidableIso s) =>
CompiledRules key s l
-> (Wires as ~> Wires bs) -> (Int, Wires as ~> Wires bs)
rewriteBatchCompiled ((String -> CompiledRules () s l)
-> (CompiledRules () s l -> CompiledRules () s l)
-> Either String (CompiledRules () s l)
-> CompiledRules () s l
forall (a :: Kind) (c :: Kind) (b :: Kind).
(a -> c) -> (b -> c) -> Either a b -> c
either String -> CompiledRules () s l
forall a. HasCallStack => String -> a
error CompiledRules () s l -> CompiledRules () s l
forall (a :: Kind). a -> a
id ([((), Rule s l)] -> Either String (CompiledRules () s l)
forall (key :: Kind) (l :: Kind) (s :: Kind).
(Ord key, Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRules [((), Rule s l
r)])) Wires as ~> Wires bs
host

-- | Compile uniquely keyed rules. Box traversal favours connected boxes and
-- then boxes with more fixed ports; fixed arity breaks ties.
-- This anchors a mux before its constant inputs and fixed edges before captures.
-- Common tests are inserted into a discrimination trie, including bindings for
-- isolated nodes and separate searches for disconnected pattern components.
-- Literal labels dispatch by equality; parameter labels dispatch by constructor
-- and fixed fields. Bindings are checked separately for each rule at a terminal.
-- Compilation also compares sorts up to isomorphism. Rules using
-- 'withSortParameters' defer sort validation to their terminals.
compileRules
  :: (Ord key, Eq l, DecidableIso s)
  => [(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRules :: forall (key :: Kind) (l :: Kind) (s :: Kind).
(Ord key, Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRules = Bool -> [(key, Rule s l)] -> Either String (CompiledRules key s l)
forall (key :: Kind) (l :: Kind) (s :: Kind).
(Ord key, Eq l, DecidableIso s) =>
Bool -> [(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRuleSet Bool
False

-- | Compile rules with a strictly decreasing box-count policy. A candidate is
-- accepted only when its instantiated replacement has fewer boxes than the
-- matched region. This check precedes batch selection, so a rejected candidate
-- cannot block a competing reduction. Parameters and dynamically constructed
-- replacements are checked per match; compilation does not certify that every
-- application of the supplied rules decreases.
--
-- Every application removes at least one box, and compatible batches cannot
-- share boxes. Consequently 'normalise' with 'unlimitedRewrites' terminates on
-- finite hosts after at most the initial number of boxes in rule applications,
-- assuming replacement callbacks terminate. Matching is still an exhaustive
-- finite search and may be expensive. Confluence is not guaranteed.
--
-- Equal-sized changes, including relabelling, and growing replacements are
-- excluded, even if semantically useful. 'NormalForm' means no decreasing
-- application remains; other applications of the original rules may exist.
--
-- >>> import Proarrow.Category.Instance.OpenHypergraph (Box (..))
-- >>> let before = unsafeOpenHypergraph [] [] [] [Box "x" [] []] :: (Wires '[] :: OPENHG () String) ~> Wires '[]
-- >>> let after = unsafeOpenHypergraph [] [] [] [] :: (Wires '[] :: OPENHG () String) ~> Wires '[]
-- >>> let r = either error id (before ==> after)
-- >>> let compiled = either error id (compileReducingRules [((), r)])
-- >>> let result = normalise unlimitedRewrites compiled before
-- >>> (normalisationStatus result, normalisationRewrites result)
-- (NormalForm,1)
compileReducingRules
  :: (Ord key, Eq l, DecidableIso s)
  => [(key, Rule s l)] -> Either String (CompiledRules key s l)
compileReducingRules :: forall (key :: Kind) (l :: Kind) (s :: Kind).
(Ord key, Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String (CompiledRules key s l)
compileReducingRules = Bool -> [(key, Rule s l)] -> Either String (CompiledRules key s l)
forall (key :: Kind) (l :: Kind) (s :: Kind).
(Ord key, Eq l, DecidableIso s) =>
Bool -> [(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRuleSet Bool
True

-- | Enumerate every valid match of every compiled rule, returning its key and
-- single-step result. Results are ordered by key, then by the original rule's
-- box and node enumeration order, as in 'rewrites'. Matching work is shared;
-- overlapping matches and isomorphic results are retained.
rewritesCompiled
  :: forall {s} key l a b
   . (Eq l, DecidableIso s)
  => CompiledRules key s l
  -> (a :: OPENHG s l) ~> b
  -> [(key, Wires (WireSorts a) ~> (Wires (WireSorts b) :: OPENHG s l))]
rewritesCompiled :: forall {s :: Kind} (key :: Kind) (l :: Kind) (a :: OPENHG s l)
       (b :: OPENHG s l).
(Eq l, DecidableIso s) =>
CompiledRules key s l
-> (a ~> b) -> [(key, Wires (WireSorts a) ~> Wires (WireSorts b))]
rewritesCompiled compiled :: CompiledRules key s l
compiled@(CompiledRules Vector (key, Rule s l)
rules Vector (Signature l)
_ Net s
_ Bool
_) a ~> b
host =
  a ~> b
DecCospan a b
host DecCospan a b
-> ((Ob a, Ob b) =>
    [(key,
      DecCospan
        (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
        (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b))))))))])
-> [(key,
     DecCospan
       (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC a)))))))
       (DC (SUB (FH (Port (PortSorts (UN SUB (UN DC b))))))))]
forall {k1 :: Kind} {k2 :: Kind} (p :: k1 +-> k2) (a :: k2)
       (b :: k1) (r :: Kind).
Profunctor p =>
p a b -> ((Ob a, Ob b) => r) -> r
//
    [ (key
key, [SomeSort s]
-> [Int]
-> [Int]
-> [Box l Int]
-> Wires (PortSorts (FH (UN FH (UN SUB (UN DC a)))))
   ~> Wires (PortSorts (FH (UN FH (UN SUB (UN DC b)))))
forall {s :: Kind} (l :: Kind) (as :: [s]) (bs :: [s]).
(SortList as, SortList bs) =>
[SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires as ~> Wires bs
unsafeOpenHypergraph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs)
    | (Int
i, (Graph s (LabelTest l)
lhs, Graph s l
rhs, Match
match)) <- CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
forall (l :: Kind) (s :: Kind) (key :: Kind).
(Eq l, DecidableIso s) =>
CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatches CompiledRules key s l
compiled Graph s l
g
    , let (key
key, Rule s l
_) = Vector (key, Rule s l)
rules Vector (key, Rule s l) -> Int -> (key, Rule s l)
forall (a :: Kind). Vector a -> Int -> a
V.! Int
i
          Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs = Graph s (LabelTest l)
-> Graph s l -> Graph s l -> [Match] -> Graph s l
forall (s :: Kind) (p :: Kind) (l :: Kind).
Graph s p -> Graph s l -> Graph s l -> [Match] -> Graph s l
replaceMany Graph s (LabelTest l)
lhs Graph s l
rhs Graph s l
g [Match
match]
    ]
  where
    g :: Graph s l
g = (a ~> b) -> Graph s l
forall (s :: Kind) (l :: Kind) (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph a ~> b
host

-- | Match the entire compiled rule set on one snapshot and apply one greedy
-- maximal batch across rules. Smaller keys have conflict priority; matches of
-- one rule follow 'rewrites' order. Compatible matches of different rules share
-- the batch and the result is rebuilt once. Sharing and deletion conditions are
-- the same as in 'rewriteBatch'. New matches wait for a subsequent batch.
rewriteBatchCompiled
  :: forall {s} key l as bs
   . (Eq l, DecidableIso s)
  => CompiledRules key s l
  -> (Wires as :: OPENHG s l) ~> Wires bs
  -> (Int, Wires as ~> (Wires bs :: OPENHG s l))
rewriteBatchCompiled :: forall {s :: Kind} (key :: Kind) (l :: Kind) (as :: [s])
       (bs :: [s]).
(Eq l, DecidableIso s) =>
CompiledRules key s l
-> (Wires as ~> Wires bs) -> (Int, Wires as ~> Wires bs)
rewriteBatchCompiled CompiledRules key s l
compiled Wires as ~> Wires bs
host =
  let g :: Graph s l
g = (Wires as ~> Wires bs) -> Graph s l
forall (s :: Kind) (l :: Kind) (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph Wires as ~> Wires bs
host
      chosen :: [Prepared s l]
chosen = CompiledRules key s l -> Graph s l -> [Prepared s l]
forall (l :: Kind) (s :: Kind) (key :: Kind).
(Eq l, DecidableIso s) =>
CompiledRules key s l -> Graph s l -> [Prepared s l]
batchMatches CompiledRules key s l
compiled Graph s l
g
  in case [Prepared s l]
chosen of
       [] -> (Int
0, Wires as ~> Wires bs
host)
       [Prepared s l]
_ ->
         Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
host DecCospan (Wires as) (Wires bs)
-> ((Ob (Wires as), Ob (Wires bs)) =>
    (Int, DecCospan (Wires as) (Wires bs)))
-> (Int, DecCospan (Wires as) (Wires bs))
forall {k1 :: Kind} {k2 :: Kind} (p :: k1 +-> k2) (a :: k2)
       (b :: k1) (r :: Kind).
Profunctor p =>
p a b -> ((Ob a, Ob b) => r) -> r
//
           let Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs = Graph s l -> [Prepared s l] -> Graph s l
forall (s :: Kind) (l :: Kind) (p :: Kind).
Graph s l -> [(Graph s p, Graph s l, Match)] -> Graph s l
replaceSelected Graph s l
g [Prepared s l]
chosen
           in ([Prepared s l] -> Int
forall (a :: Kind). [a] -> Int
forall (t :: Kind -> Kind) (a :: Kind). Foldable t => t a -> Int
length [Prepared s l]
chosen, [SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires as ~> Wires bs
forall {s :: Kind} (l :: Kind) (as :: [s]) (bs :: [s]).
(SortList as, SortList bs) =>
[SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires as ~> Wires bs
unsafeOpenHypergraph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs)

-- | Repeatedly apply compatible batches from the compiled rule set. Matches
-- created by one batch are considered on the next snapshot. Conflict priorities
-- are those of 'compileRules'. A rewrite limit can truncate a batch to its first
-- compatible matches, so neither limit is exceeded.
--
-- Stopping at a limit probes for further matches to distinguish exhaustion from
-- a normal form, without applying another rewrite. Ordinary rules do not compare
-- graphs: reproducing the left side still counts as an application and needs a
-- limit. Subgraph rules skip structurally identical replacements. Arbitrary
-- rule sets may not terminate with 'unlimitedRewrites';
-- 'compileReducingRules' excludes all non-decreasing applications.
normalise
  :: forall {s} key l as bs
   . (Eq l, DecidableIso s)
  => RewriteLimits
  -> CompiledRules key s l
  -> (Wires as :: OPENHG s l) ~> Wires bs
  -> NormalisationResult (Wires as ~> (Wires bs :: OPENHG s l))
normalise :: forall {s :: Kind} (key :: Kind) (l :: Kind) (as :: [s])
       (bs :: [s]).
(Eq l, DecidableIso s) =>
RewriteLimits
-> CompiledRules key s l
-> (Wires as ~> Wires bs)
-> NormalisationResult (Wires as ~> Wires bs)
normalise RewriteLimits
limits CompiledRules key s l
compiled = RewriteLimits
-> (Graph s l -> [Prepared s l])
-> (DC (SUB (FH (Port as))) ~> DC (SUB (FH (Port bs))))
-> NormalisationResult
     (DC (SUB (FH (Port as))) ~> DC (SUB (FH (Port bs))))
forall {s :: Kind} (l :: Kind) (as :: [s]) (bs :: [s]).
RewriteLimits
-> (Graph s l -> [Prepared s l])
-> (Wires as ~> Wires bs)
-> NormalisationResult (Wires as ~> Wires bs)
normaliseBy RewriteLimits
limits (CompiledRules key s l -> Graph s l -> [Prepared s l]
forall (l :: Kind) (s :: Kind) (key :: Kind).
(Eq l, DecidableIso s) =>
CompiledRules key s l -> Graph s l -> [Prepared s l]
batchMatches CompiledRules key s l
compiled)

batchMatches :: (Eq l, DecidableIso s) => CompiledRules key s l -> Graph s l -> [Prepared s l]
batchMatches :: forall (l :: Kind) (s :: Kind) (key :: Kind).
(Eq l, DecidableIso s) =>
CompiledRules key s l -> Graph s l -> [Prepared s l]
batchMatches CompiledRules key s l
compiled Graph s l
g =
  [ (Graph s (LabelTest l)
lhs, Graph s l
rhs, Match
match)
  | ((Graph s (LabelTest l)
lhs, Graph s l
rhs), Match
match) <-
      ((Graph s (LabelTest l), Graph s l) -> Match -> IntSet)
-> [((Graph s (LabelTest l), Graph s l), Match)]
-> [((Graph s (LabelTest l), Graph s l), Match)]
forall (a :: Kind).
(a -> Match -> IntSet) -> [(a, Match)] -> [(a, Match)]
nonConflictingBy
        (\(Graph s (LabelTest l)
lhs, Graph s l
_) (IntMap Int
m, IntSet
_) -> Graph s (LabelTest l) -> IntMap Int -> IntSet
forall (s :: Kind) (l :: Kind). Graph s l -> IntMap Int -> IntSet
deletedImages Graph s (LabelTest l)
lhs IntMap Int
m)
        [((Graph s (LabelTest l)
lhs, Graph s l
rhs), Match
match) | (Int
_, (Graph s (LabelTest l)
lhs, Graph s l
rhs, Match
match)) <- CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
forall (l :: Kind) (s :: Kind) (key :: Kind).
(Eq l, DecidableIso s) =>
CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatches CompiledRules key s l
compiled Graph s l
g]
  ]