-- | Critical overlaps and bounded Knuth–Bendix-style completion.
-- Convex rewriting works with monogamous acyclic string diagrams and checks
-- all maximal path contexts. Hypergraph completion uses the ordinary matcher
-- with shared Frobenius wiring. Port completion checks schematic overlaps
-- with captured wire sequences.
--
-- See "Proarrow.Tools.KnuthBendix" for completion of typed paths.
module Proarrow.Tools.HypergraphRewrite.Completion
  ( -- * Overlaps and path contexts
    CriticalOverlap (..)
  , criticalOverlaps
  , hypergraphOverlaps
  , HypergraphConfluenceResult (..)
  , checkHypergraphConfluence
  , PathContextResult (..)
  , checkPathContexts

    -- * Variadic overlaps
  , portOverlapTemplates
  , parameterPortOverlapTemplates
  , PortTemplateResult (..)
  , checkPortTemplate
  , PortSymmetry (..)
  , checkPortTemplateWithSymmetry
  , checkPortTemplateWithScalars

    -- * Variadic completion
  , orientPortOverlap
  , orientParameterPortOverlap
  , PortCompletion (..)
  , PortCompletionStop (..)
  , completePorts
  , completeParameterPorts
  , completeParameterPortsFor
  , completeParameterPortsForWithScalars
  , completeParameterPortsReparameterised

    -- * Convex rewriting and completion
  , withFixedRule
  , ConvexRules
  , compileConvexRules
  , normaliseConvex
  , ConvexCompletion (..)
  , ConvexCompletionStop (..)
  , completeConvex

    -- * Hypergraph completion
  , HypergraphCompletion (..)
  , HypergraphCompletionStop (..)
  , completeHypergraph
  ) where

import Control.Applicative ((<|>))
import Control.Monad (foldM, guard, unless, void, when)
import Data.Containers.ListUtils (nubOrd)
import Data.Foldable (toList)
import Data.Function (on)
import Data.Graph (SCC (..), stronglyConnComp)
import Data.IntMap.Strict qualified as IM
import Data.IntSet qualified as IS
import Data.Kind (Type)
import Data.List (tails)
import Data.List qualified as List
import Data.Map.Strict qualified as M
import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe, maybeToList)
import Data.Typeable (Typeable)
import Numeric.Natural (Natural)
import Prelude

import Proarrow.Category.Instance.FinHask (unionFind)
import Proarrow.Category.Instance.OpenHypergraph
  ( Box (..)
  , OPENHG
  , Wires
  , isomorphic
  , reifySorts
  , sameSort
  , unsafeOpenHypergraph
  )
import Proarrow.Core (CategoryOf (..), Kind)
import Proarrow.Object (SomeOf (..))
import Proarrow.Optic.Iso (DecidableIso)
import Proarrow.Tools.HypergraphRewrite
  ( CompiledRules
  , NormalisationResult (..)
  , NormalisationStatus (NormalForm)
  , RewriteLimits (..)
  , compileRules
  )
import Proarrow.Tools.HypergraphRewrite.Internal
  ( Graph (..)
  , LabelTest (..)
  , Match
  , Parameter (Literal, Variable)
  , Port (..)
  , PortGraph (..)
  , PortReplacement (..)
  , PortSymmetry (..)
  , Prepared
  , Rule (..)
  , checkPortLeft
  , deletedImages
  , graph
  , internalNodes
  , mapLabels
  , mapPortLabels
  , matches
  , nonConflictingBy
  , normaliseBy
  , normaliseGraphBy
  , parameterPortRule
  , parameterPortVariants
  , portRule
  , replaceMany
  , rule
  , sameGraph
  , symmetricInputs
  , symmetricOutputs
  , traverseLabels
  )
import Proarrow.Tools.HypergraphRewrite.Internal.Matcher (compiledMatches, compiledMatchesAvoiding)

-- | Two one-step reductions of a common diagram. The rule keys identify the
-- two steps. The source and both reducts share an ordered boundary.
type CriticalOverlap :: Type -> Kind -> Type -> Type
data CriticalOverlap key s l where
  CriticalOverlap
    :: forall {key} {s} {l} as bs
     . key
    -> key
    -> Wires @s @l as ~> Wires @s @l bs
    -> Wires @s @l as ~> Wires @s @l bs
    -> Wires @s @l as ~> Wires @s @l bs
    -> CriticalOverlap key s l

-- | Construct the overlapping pre-critical pairs of fixed, left-connected
-- string-diagram rules. The sides must have acyclic, monogamous wiring, and
-- every input of a left-hand side must reach every output. Rule instances with
-- captures or parameters are outside this fragment. Parallel disjoint steps
-- commute and are omitted. Boundaries are ordered by node number.
-- See <https://arxiv.org/html/2109.06049#S5.SS4 String Diagram Rewrite Theory III, §5.4>.
criticalOverlaps :: (Eq l, DecidableIso s) => [(key, Rule s l)] -> Either String [CriticalOverlap key s l]
criticalOverlaps :: forall l s key.
(Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String [CriticalOverlap key s l]
criticalOverlaps [(key, Rule s l)]
rules = do
  patterns <- ((key, Rule s l) -> Either String (FixedRule key s l))
-> [(key, Rule s l)] -> Either String [FixedRule key s l]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (key, Rule s l) -> Either String (FixedRule key s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
fixedRule [(key, Rule s l)]
rules
  unless
    (all leftConnected patterns)
    (Left "criticalOverlaps: every left input must reach every left output")
  pure [renderOverlap host left right | (host, left, right) <- preCriticalPairs (StringOverlaps False) patterns]
  where
    leftConnected :: (a, Graph s l, c) -> Bool
leftConnected (a
_, Graph [SomeSort s]
_ [Int]
ins [Int]
outs [Box l Int]
bs, c
_) =
      let edges :: IntMap [Int]
edges = [Box l Int] -> IntMap [Int]
forall l. [Box l Int] -> IntMap [Int]
wireEdges [Box l Int]
bs
      in (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\Int
i -> (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (Int -> IntSet -> Bool
`IS.member` IntMap [Int] -> Int -> IntSet
reachableNodes IntMap [Int]
edges Int
i) [Int]
outs) [Int]
ins

-- | Enumerate overlaps of fixed literal hypergraph rules under the ordinary
-- matcher. Glue compatible box occurrences and their ports, then consider
-- additional sort-preserving node identifications. Retain pairs that share a
-- box, delete a node used by the other match, or identify two nodes of the
-- other match in a replacement. Each witness exposes the nodes preserved by
-- both steps as inputs, in node order.
hypergraphOverlaps :: (Eq l, DecidableIso s) => [(key, Rule s l)] -> Either String [CriticalOverlap key s l]
hypergraphOverlaps :: forall l s key.
(Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String [CriticalOverlap key s l]
hypergraphOverlaps [(key, Rule s l)]
rules = do
  patterns <- ((key, Rule s l) -> Either String (FixedRule key s l))
-> [(key, Rule s l)] -> Either String [FixedRule key s l]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (key, Rule s l) -> Either String (FixedRule key s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
literalRule [(key, Rule s l)]
rules
  pure [renderOverlap host left right | (host, left, right) <- preCriticalPairs HypergraphOverlaps patterns]

-- | The outcome of checking local confluence for single-step hypergraph
-- rewriting. Success counts the overlaps checked. Failure returns a fork
-- whose branches have disjoint sets of reducts, and a depth limit returns an
-- unresolved fork.
type HypergraphConfluenceResult :: Type -> Kind -> Type -> Type
data HypergraphConfluenceResult key s l
  = HypergraphLocallyConfluent Int
  | HypergraphNotLocallyConfluent (CriticalOverlap key s l)
  | HypergraphConfluenceLimit (CriticalOverlap key s l)

-- | Check local confluence of fixed literal rules with unique keys. The depth
-- bound applies separately to each side of an overlap. Use @Nothing@ for an
-- unbounded search, which can diverge on a nonterminating system.
--
-- Any two matches in a host restrict to their union. A host boundary port or
-- an outside box can meet that union only at a node preserved by both steps.
-- Those nodes are exactly the boundary exposed by 'hypergraphOverlaps'. A
-- joining derivation tracks each attachment through the boundary map, so it
-- lifts back into the host. Even when it merges two boundary nodes, adding back the
-- context leaves the current overlap graph embedded injectively: the context
-- started with a distinct node for each attachment. Omitted pairs commute
-- because their boxes and deletions do not interfere and neither replacement
-- folds the other match. See the clipping and embedding argument in
-- <https://arxiv.org/html/2109.06049#S3 String Diagram Rewrite Theory III, §3>.
--
-- This check concerns the single-step relation of
-- 'Proarrow.Tools.HypergraphRewrite.rewritesCompiled'. For a terminating
-- system, local confluence implies confluence.
checkHypergraphConfluence
  :: (Ord key, Eq l, DecidableIso s)
  => Maybe Natural -> [(key, Rule s l)] -> Either String (HypergraphConfluenceResult key s l)
checkHypergraphConfluence :: forall key l s.
(Ord key, Eq l, DecidableIso s) =>
Maybe Natural
-> [(key, Rule s l)]
-> Either String (HypergraphConfluenceResult key s l)
checkHypergraphConfluence Maybe Natural
maxDepth [(key, Rule s l)]
rules = do
  patterns <- ((key, Rule s l) -> Either String (FixedRule key s l))
-> [(key, Rule s l)] -> Either String [FixedRule key s l]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (key, Rule s l) -> Either String (FixedRule key s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
literalRule [(key, Rule s l)]
rules
  compiled <- compileRules rules
  pure $ case checkHypergraphPairs maxDepth (map snd . compiledMatches compiled) patterns of
    AllJoinable Int
count -> Int -> HypergraphConfluenceResult key s l
forall key s l. Int -> HypergraphConfluenceResult key s l
HypergraphLocallyConfluent Int
count
    Unjoinable (Graph s l
host, DiagramStep key s l
left, DiagramStep key s l
right) -> CriticalOverlap key s l -> HypergraphConfluenceResult key s l
forall key s l.
CriticalOverlap key s l -> HypergraphConfluenceResult key s l
HypergraphNotLocallyConfluent (Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s l
host DiagramStep key s l
left DiagramStep key s l
right)
    JoinLimit (Graph s l
host, DiagramStep key s l
left, DiagramStep key s l
right) -> CriticalOverlap key s l -> HypergraphConfluenceResult key s l
forall key s l.
CriticalOverlap key s l -> HypergraphConfluenceResult key s l
HypergraphConfluenceLimit (Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s l
host DiagramStep key s l
left DiagramStep key s l
right)

-- | The result of checking all pairs of symbolic steps from a supplied
-- template. Witnesses represent each named sequence by one extra input node
-- after the template's explicit boundary, in first-occurrence order.
data PortTemplateResult key l
  = PortTemplateJoinable Int
  | PortTemplateUnjoinable (CriticalOverlap key () l)
  | PortTemplateJoinLimit (CriticalOverlap key () l)

-- | Check the forks of a schematic source with unit-sorted wires. Fixed
-- replacements may refer to explicit interface nodes, fresh numbered nodes
-- or whole captures. Interface positions may be identified in a replacement.
-- Label parameters are evaluated in the label type of the caller-supplied source.
--
-- Each sequence is represented by a distinct protected boundary node. A
-- numbered port cannot match a sequence marker, even at the rule interface.
-- Captures may consume entire markers, and fixed replacements copy their
-- sequences in order. A computed replacement can be applied when every
-- capture contains only numbered wires, so the lengths and individual ports
-- are known. Consequently a symbolic join lifts to any substitution
-- of the markers by port sequences (including empty sequences and aliases),
-- provided those ports stay outside the template's numbered nodes. Any
-- numbered nodes introduced along the derivation are fresh for the substitution.
-- The result concerns the forks represented this way in the supplied template.
-- Concrete instances may have additional matches, including computed
-- replacements whose captures include sequence markers in the template.
checkPortTemplate
  :: (Eq l) => Maybe Natural -> [(key, Rule () l)] -> PortGraph () l -> Either String (PortTemplateResult key l)
checkPortTemplate :: forall l key.
Eq l =>
Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkPortTemplate = (Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
forall l key.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkPortTemplateWith Graph () l -> Graph () l -> Bool
forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph

-- | Turn an unjoinable symbolic fork into a literal port rule. The input
-- template supplies the names and order of the sequences in the witness.
-- The ordering must strictly decrease after every allowed capture
-- substitution, including empty sequences. Orientation rejects a rule
-- whose two sides are isomorphic with all captures empty. The resulting
-- rule uses the labels from the witness. The rule can factor through one
-- port per left interface node if the right branch preserves every left
-- identification and the factored rule still decreases. The right branch
-- may identify additional positions. Adjacent captures that occur once and
-- stay together in the same order can become a single capture.
orientPortOverlap
  :: (Eq l)
  => (PortGraph () l -> PortGraph () l -> Ordering)
  -> PortGraph () l
  -> PortTemplateResult key l
  -> Either String (Rule () l)
orientPortOverlap :: forall l key.
Eq l =>
(PortGraph () l -> PortGraph () l -> Ordering)
-> PortGraph () l
-> PortTemplateResult key l
-> Either String (Rule () l)
orientPortOverlap = (PortGraph () l -> PortGraph () l -> Either String (Rule () l))
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> PortGraph () l
-> PortTemplateResult key l
-> Either String (Rule () l)
forall l m key.
Eq l =>
(PortGraph () l -> PortGraph () l -> Either String (Rule () m))
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> PortGraph () l
-> PortTemplateResult key l
-> Either String (Rule () m)
orientPortOverlapWith PortGraph () l -> PortGraph () l -> Either String (Rule () l)
forall s l.
DecidableIso s =>
PortGraph s l -> PortGraph s l -> Either String (Rule s l)
portRule

-- | Orient a symbolic fork into a parameterized port rule. The caller
-- converts values from the symbolic algebra into label parameters. Variables
-- must use the same names in both branches. The oriented left side can only
-- contain variables and literals, and the right side can compute expressions
-- from the variables bound on the left. The comparison follows the ordering
-- requirements of 'completeParameterPorts'.
orientParameterPortOverlap
  :: (Traversable f, Typeable f, Eq (f ()), Eq (f symbolic), Eq a)
  => (symbolic -> Parameter a)
  -> (PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Ordering)
  -> PortGraph () (f symbolic)
  -> PortTemplateResult key (f symbolic)
  -> Either String (Rule () (f a))
orientParameterPortOverlap :: forall (f :: Type -> Type) symbolic a key.
(Traversable f, Typeable f, Eq (f ()), Eq (f symbolic), Eq a) =>
(symbolic -> Parameter a)
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> PortGraph () (f symbolic)
-> PortTemplateResult key (f symbolic)
-> Either String (Rule () (f a))
orientParameterPortOverlap symbolic -> Parameter a
parameter = (PortGraph () (f symbolic)
 -> PortGraph () (f symbolic) -> Either String (Rule () (f a)))
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> PortGraph () (f symbolic)
-> PortTemplateResult key (f symbolic)
-> Either String (Rule () (f a))
forall l m key.
Eq l =>
(PortGraph () l -> PortGraph () l -> Either String (Rule () m))
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> PortGraph () l
-> PortTemplateResult key l
-> Either String (Rule () m)
orientPortOverlapWith ((symbolic -> Parameter a)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String (Rule () (f a))
forall (f :: Type -> Type) a symbolic.
(Traversable f, Typeable f, Eq (f ()), Eq a) =>
(symbolic -> Parameter a)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String (Rule () (f a))
reifyPortRule symbolic -> Parameter a
parameter)

reifyPortRule
  :: (Traversable f, Typeable f, Eq (f ()), Eq a)
  => (symbolic -> Parameter a)
  -> PortGraph () (f symbolic)
  -> PortGraph () (f symbolic)
  -> Either String (Rule () (f a))
reifyPortRule :: forall (f :: Type -> Type) a symbolic.
(Traversable f, Typeable f, Eq (f ()), Eq a) =>
(symbolic -> Parameter a)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String (Rule () (f a))
reifyPortRule symbolic -> Parameter a
parameter PortGraph () (f symbolic)
left PortGraph () (f symbolic)
right =
  PortGraph () (f (Parameter a))
-> PortGraph () (f (Parameter a)) -> Either String (Rule () (f a))
forall s (f :: Type -> Type) a.
(DecidableIso s, Traversable f, Eq (f ()), Typeable f, Eq a) =>
PortGraph s (f (Parameter a))
-> PortGraph s (f (Parameter a)) -> Either String (Rule s (f a))
parameterPortRule ((f symbolic -> f (Parameter a))
-> PortGraph () (f symbolic) -> PortGraph () (f (Parameter a))
forall l m s. (l -> m) -> PortGraph s l -> PortGraph s m
mapPortLabels ((symbolic -> Parameter a) -> f symbolic -> f (Parameter a)
forall a b. (a -> b) -> f a -> f b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap symbolic -> Parameter a
parameter) PortGraph () (f symbolic)
left) ((f symbolic -> f (Parameter a))
-> PortGraph () (f symbolic) -> PortGraph () (f (Parameter a))
forall l m s. (l -> m) -> PortGraph s l -> PortGraph s m
mapPortLabels ((symbolic -> Parameter a) -> f symbolic -> f (Parameter a)
forall a b. (a -> b) -> f a -> f b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap symbolic -> Parameter a
parameter) PortGraph () (f symbolic)
right)

orientPortOverlapWith
  :: (Eq l)
  => (PortGraph () l -> PortGraph () l -> Either String (Rule () m))
  -> (PortGraph () l -> PortGraph () l -> Ordering)
  -> PortGraph () l
  -> PortTemplateResult key l
  -> Either String (Rule () m)
orientPortOverlapWith :: forall l m key.
Eq l =>
(PortGraph () l -> PortGraph () l -> Either String (Rule () m))
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> PortGraph () l
-> PortTemplateResult key l
-> Either String (Rule () m)
orientPortOverlapWith PortGraph () l -> PortGraph () l -> Either String (Rule () m)
build PortGraph () l -> PortGraph () l -> Ordering
order PortGraph () l
source (PortTemplateUnjoinable (CriticalOverlap key
_ key
_ Wires as ~> Wires bs
host Wires as ~> Wires bs
left Wires as ~> Wires bs
right)) = do
  symbolic <- PortGraph () l -> Either String (Graph () l)
forall l. PortGraph () l -> Either String (Graph () l)
symbolicPortGraph PortGraph () l
source
  unless (sameGraph symbolic (graph host)) (Left "orientPortOverlap: the witness does not match the supplied template")
  (l, r) <- orientPortBranches (const OrderedPorts) order source (graph left) (graph right)
  build l r
orientPortOverlapWith PortGraph () l -> PortGraph () l -> Either String (Rule () m)
_ PortGraph () l -> PortGraph () l -> Ordering
_ PortGraph () l
_ PortTemplateResult key l
_ = String -> Either String (Rule () m)
forall a b. a -> Either a b
Left String
"orientPortOverlap: expected an unjoinable fork"

orientPortBranches
  :: (Eq l)
  => (l -> PortSymmetry)
  -> (PortGraph () l -> PortGraph () l -> Ordering)
  -> PortGraph () l
  -> Graph () l
  -> Graph () l
  -> Either String (PortGraph () l, PortGraph () l)
orientPortBranches :: forall l.
Eq l =>
(l -> PortSymmetry)
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> PortGraph () l
-> Graph () l
-> Graph () l
-> Either String (PortGraph () l, PortGraph () l)
orientPortBranches l -> PortSymmetry
symmetry PortGraph () l -> PortGraph () l -> Ordering
order source :: PortGraph () l
source@(PortGraph [SomeSort ()]
_ [Int]
sourceBoundary [Box l Port]
_) Graph () l
left Graph () l
right = do
  let branch :: Graph () l -> Either String (PortGraph () l)
branch = Int -> [String] -> Graph () l -> Either String (PortGraph () l)
forall l.
Int -> [String] -> Graph () l -> Either String (PortGraph () l)
restorePortSequences ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
sourceBoundary) (PortGraph () l -> [String]
forall s l. PortGraph s l -> [String]
portSequenceNames PortGraph () l
source)
  (l, r) <- (l -> PortSymmetry)
-> PortGraph () l
-> PortGraph () l
-> (PortGraph () l, PortGraph () l)
forall l.
(l -> PortSymmetry)
-> PortGraph () l
-> PortGraph () l
-> (PortGraph () l, PortGraph () l)
coalescePortCaptures (PortSymmetry -> l -> PortSymmetry
forall a b. a -> b -> a
const PortSymmetry
OrderedPorts) (PortGraph () l
 -> PortGraph () l -> (PortGraph () l, PortGraph () l))
-> Either String (PortGraph () l)
-> Either
     String (PortGraph () l -> (PortGraph () l, PortGraph () l))
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> Graph () l -> Either String (PortGraph () l)
branch Graph () l
left Either String (PortGraph () l -> (PortGraph () l, PortGraph () l))
-> Either String (PortGraph () l)
-> Either String (PortGraph () l, PortGraph () l)
forall a b.
Either String (a -> b) -> Either String a -> Either String b
forall (f :: Type -> Type) a b.
Applicative f =>
f (a -> b) -> f a -> f b
<*> Graph () l -> Either String (PortGraph () l)
branch Graph () l
right
  case order l r of
    Ordering
GT -> PortGraph () l
-> PortGraph () l -> Either String (PortGraph () l, PortGraph () l)
finish PortGraph () l
l PortGraph () l
r
    Ordering
LT -> PortGraph () l
-> PortGraph () l -> Either String (PortGraph () l, PortGraph () l)
finish PortGraph () l
r PortGraph () l
l
    Ordering
EQ -> String -> Either String (PortGraph () l, PortGraph () l)
forall a b. a -> Either a b
Left String
"orientPortOverlap: the branches have equal rank"
  where
    finish :: PortGraph () l
-> PortGraph () l -> Either String (PortGraph () l, PortGraph () l)
finish PortGraph () l
l PortGraph () l
r = do
      let (PortGraph () l
l', PortGraph () l
r') = (l -> PortSymmetry)
-> PortGraph () l
-> PortGraph () l
-> (PortGraph () l, PortGraph () l)
forall l.
(l -> PortSymmetry)
-> PortGraph () l
-> PortGraph () l
-> (PortGraph () l, PortGraph () l)
coalescePortCaptures l -> PortSymmetry
symmetry PortGraph () l
l PortGraph () l
r
      Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (PortGraph () l -> PortGraph () l -> Ordering
order PortGraph () l
l' PortGraph () l
r' Ordering -> Ordering -> Bool
forall a. Eq a => a -> a -> Bool
== Ordering
GT) (String -> Either String ()
forall a b. a -> Either a b
Left String
"orientPortOverlap: the coalesced rule does not decrease")
      (lhs, rhs) <- PortGraph () l
-> PortGraph () l -> Either String (PortGraph () l, PortGraph () l)
factor PortGraph () l
l' PortGraph () l
r'
      when (not (null (portSequenceNames lhs)) && sameGraph (emptyCaptures lhs) (emptyCaptures rhs)) $
        Left "orientPortOverlap: empty captures make the rule a no-op"
      pure (lhs, rhs)
    emptyCaptures :: PortGraph s l -> Graph s l
emptyCaptures (PortGraph [SomeSort s]
ns [Int]
boundary [Box l Port]
boxes) =
      [SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph [SomeSort s]
ns [Int]
boundary [] [l -> [Int] -> [Int] -> Box l Int
forall l n. l -> [n] -> [n] -> Box l n
Box l
l ((Port -> Maybe Int) -> [Port] -> [Int]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe Port -> Maybe Int
numbered [Port]
ins) ((Port -> Maybe Int) -> [Port] -> [Int]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe Port -> Maybe Int
numbered [Port]
outs) | Box l
l [Port]
ins [Port]
outs <- [Box l Port]
boxes]
    numbered :: Port -> Maybe Int
numbered (Node Int
n) = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
n
    numbered Port
_ = Maybe Int
forall a. Maybe a
Nothing
    factor :: PortGraph () l
-> PortGraph () l -> Either String (PortGraph () l, PortGraph () l)
factor l :: PortGraph () l
l@(PortGraph [SomeSort ()]
ls [Int]
li [Box l Port]
lb) r :: PortGraph () l
r@(PortGraph [SomeSort ()]
rs [Int]
ri [Box l Port]
rb)
      | [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
li Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
leftCount = (PortGraph () l, PortGraph () l)
-> Either String (PortGraph () l, PortGraph () l)
forall a b. b -> Either a b
Right (PortGraph () l
l, PortGraph () l
r)
      | [(Int, Int)] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [(Int, Int)]
pairs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
leftCount =
          String -> Either String (PortGraph () l, PortGraph () l)
forall a b. a -> Either a b
Left String
"orientPortOverlap: the right branch splits a left interface wire"
      | PortGraph () l -> PortGraph () l -> Ordering
order PortGraph () l
l' PortGraph () l
r' Ordering -> Ordering -> Bool
forall a. Eq a => a -> a -> Bool
== Ordering
GT = (PortGraph () l, PortGraph () l)
-> Either String (PortGraph () l, PortGraph () l)
forall a b. b -> Either a b
Right (PortGraph () l
l', PortGraph () l
r')
      | Bool
otherwise = String -> Either String (PortGraph () l, PortGraph () l)
forall a b. a -> Either a b
Left String
"orientPortOverlap: the factored rule does not decrease"
      where
        leftCount :: Int
leftCount = [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length ([Int] -> [Int]
forall a. Ord a => [a] -> [a]
nubOrd [Int]
li)
        pairs :: [(Int, Int)]
pairs = [(Int, Int)] -> [(Int, Int)]
forall a. Ord a => [a] -> [a]
nubOrd ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
li [Int]
ri)
        l' :: PortGraph () l
l' = [SomeSort ()] -> [Int] -> [Box l Port] -> PortGraph () l
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph [SomeSort ()]
ls (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> a
fst [(Int, Int)]
pairs) [Box l Port]
lb
        r' :: PortGraph () l
r' = [SomeSort ()] -> [Int] -> [Box l Port] -> PortGraph () l
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph [SomeSort ()]
rs (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> b
snd [(Int, Int)]
pairs) [Box l Port]
rb

coalescePortCaptures :: (l -> PortSymmetry) -> PortGraph () l -> PortGraph () l -> (PortGraph () l, PortGraph () l)
coalescePortCaptures :: forall l.
(l -> PortSymmetry)
-> PortGraph () l
-> PortGraph () l
-> (PortGraph () l, PortGraph () l)
coalescePortCaptures l -> PortSymmetry
symmetry PortGraph () l
left PortGraph () l
right = case ((String, String) -> Bool)
-> [(String, String)] -> Maybe (String, String)
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Maybe a
List.find (String, String) -> Bool
mergeable [(String, String)]
leftPairs of
  Just (String
a, String
b) -> (l -> PortSymmetry)
-> PortGraph () l
-> PortGraph () l
-> (PortGraph () l, PortGraph () l)
forall l.
(l -> PortSymmetry)
-> PortGraph () l
-> PortGraph () l
-> (PortGraph () l, PortGraph () l)
coalescePortCaptures l -> PortSymmetry
symmetry ((l -> PortSymmetry)
-> String -> String -> PortGraph () l -> PortGraph () l
forall {l} {s}.
(l -> PortSymmetry)
-> String -> String -> PortGraph s l -> PortGraph s l
replace (PortSymmetry -> l -> PortSymmetry
forall a b. a -> b -> a
const PortSymmetry
OrderedPorts) String
a String
b PortGraph () l
left) ((l -> PortSymmetry)
-> String -> String -> PortGraph () l -> PortGraph () l
forall {l} {s}.
(l -> PortSymmetry)
-> String -> String -> PortGraph s l -> PortGraph s l
replace l -> PortSymmetry
symmetry String
a String
b PortGraph () l
right)
  Maybe (String, String)
Nothing -> (PortGraph () l
left, PortGraph () l
right)
  where
    -- Both sides see the same concatenation, so any assignment to the new
    -- capture is covered by taking the second sequence empty. A symmetric
    -- replacement port list can first bring the two sequences together.
    leftPairs :: [(String, String)]
leftPairs = ([Port] -> [(String, String)]) -> [[Port]] -> [(String, String)]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap [Port] -> [(String, String)]
adjacent (PortGraph () l -> [[Port]]
forall {s} {l}. PortGraph s l -> [[Port]]
lists PortGraph () l
left)
    rightLists :: [(Bool, [Port])]
rightLists = [(Bool
symmetric, [Port]
ps) | Box l Port
box <- PortGraph () l -> [Box l Port]
forall {s} {l}. PortGraph s l -> [Box l Port]
diagramBoxes PortGraph () l
right, (Bool
symmetric, [Port]
ps) <- (l -> PortSymmetry) -> Box l Port -> [(Bool, [Port])]
forall {t} {n}. (t -> PortSymmetry) -> Box t n -> [(Bool, [n])]
portLists l -> PortSymmetry
symmetry Box l Port
box]
    mergeable :: (String, String) -> Bool
mergeable pair :: (String, String)
pair@(String
a, String
b) =
      (String -> Bool) -> [String] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all String -> Bool
onceInBoth [String
a, String
b] Bool -> Bool -> Bool
&& ((Bool, [Port]) -> Bool) -> [(Bool, [Port])] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (Bool, [Port]) -> Bool
supports [(Bool, [Port])]
rightLists
      where
        supports :: (Bool, [Port]) -> Bool
supports (Bool
symmetric, [Port]
ps)
          | Bool
symmetric = String -> Port
Capture String
a Port -> [Port] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: Type -> Type) a.
(Foldable t, Eq a) =>
a -> t a -> Bool
`elem` [Port]
ps Bool -> Bool -> Bool
&& String -> Port
Capture String
b Port -> [Port] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: Type -> Type) a.
(Foldable t, Eq a) =>
a -> t a -> Bool
`elem` [Port]
ps
          | Bool
otherwise = (String, String)
pair (String, String) -> [(String, String)] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: Type -> Type) a.
(Foldable t, Eq a) =>
a -> t a -> Bool
`elem` [Port] -> [(String, String)]
adjacent [Port]
ps
    onceInBoth :: String -> Bool
onceInBoth String
n = String -> PortGraph () l -> Int
forall {s} {l}. String -> PortGraph s l -> Int
count String
n PortGraph () l
left Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 Bool -> Bool -> Bool
&& String -> PortGraph () l -> Int
forall {s} {l}. String -> PortGraph s l -> Int
count String
n PortGraph () l
right Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1
    count :: String -> PortGraph s l -> Int
count String
n PortGraph s l
g = [()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [() | [Port]
ps <- PortGraph s l -> [[Port]]
forall {s} {l}. PortGraph s l -> [[Port]]
lists PortGraph s l
g, Capture String
name <- [Port]
ps, String
name String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
n]
    adjacent :: [Port] -> [(String, String)]
adjacent [Port]
ps = [(String
a, String
b) | (Capture String
a, Capture String
b) <- [Port] -> [Port] -> [(Port, Port)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Port]
ps (Int -> [Port] -> [Port]
forall a. Int -> [a] -> [a]
drop Int
1 [Port]
ps)]
    lists :: PortGraph s l -> [[Port]]
lists = (Box l Port -> [[Port]]) -> [Box l Port] -> [[Port]]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap (\Box l Port
box -> [Box l Port -> [Port]
forall l n. Box l n -> [n]
inputs Box l Port
box, Box l Port -> [Port]
forall l n. Box l n -> [n]
outputs Box l Port
box]) ([Box l Port] -> [[Port]])
-> (PortGraph s l -> [Box l Port]) -> PortGraph s l -> [[Port]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PortGraph s l -> [Box l Port]
forall {s} {l}. PortGraph s l -> [Box l Port]
diagramBoxes
    diagramBoxes :: PortGraph s l -> [Box l Port]
diagramBoxes (PortGraph [SomeSort s]
_ [Int]
_ [Box l Port]
boxes) = [Box l Port]
boxes
    portLists :: (t -> PortSymmetry) -> Box t n -> [(Bool, [n])]
portLists t -> PortSymmetry
policyFor (Box t
l [n]
i [n]
o) =
      let policy :: PortSymmetry
policy = t -> PortSymmetry
policyFor t
l in [(PortSymmetry -> Bool
symmetricInputs PortSymmetry
policy, [n]
i), (PortSymmetry -> Bool
symmetricOutputs PortSymmetry
policy, [n]
o)]
    replace :: (l -> PortSymmetry)
-> String -> String -> PortGraph s l -> PortGraph s l
replace l -> PortSymmetry
policyFor String
a String
b (PortGraph [SomeSort s]
ns [Int]
boundary [Box l Port]
boxes) = [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph [SomeSort s]
ns [Int]
boundary ((Box l Port -> Box l Port) -> [Box l Port] -> [Box l Port]
forall a b. (a -> b) -> [a] -> [b]
map Box l Port -> Box l Port
change [Box l Port]
boxes)
      where
        change :: Box l Port -> Box l Port
change (Box l
l [Port]
i [Port]
o) =
          let policy :: PortSymmetry
policy = l -> PortSymmetry
policyFor l
l
          in l -> [Port] -> [Port] -> Box l Port
forall l n. l -> [n] -> [n] -> Box l n
Box l
l (Bool -> [Port] -> [Port]
mergeList (PortSymmetry -> Bool
symmetricInputs PortSymmetry
policy) [Port]
i) (Bool -> [Port] -> [Port]
mergeList (PortSymmetry -> Bool
symmetricOutputs PortSymmetry
policy) [Port]
o)
        belongs :: Port -> Bool
belongs Port
p = Port
p Port -> Port -> Bool
forall a. Eq a => a -> a -> Bool
== String -> Port
Capture String
a Bool -> Bool -> Bool
|| Port
p Port -> Port -> Bool
forall a. Eq a => a -> a -> Bool
== String -> Port
Capture String
b
        mergeList :: Bool -> [Port] -> [Port]
mergeList Bool
symmetric [Port]
ps
          | Bool
symmetric Bool -> Bool -> Bool
&& String -> Port
Capture String
a Port -> [Port] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: Type -> Type) a.
(Foldable t, Eq a) =>
a -> t a -> Bool
`elem` [Port]
ps Bool -> Bool -> Bool
&& String -> Port
Capture String
b Port -> [Port] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: Type -> Type) a.
(Foldable t, Eq a) =>
a -> t a -> Bool
`elem` [Port]
ps =
              let ([Port]
before, [Port]
after) = (Port -> Bool) -> [Port] -> ([Port], [Port])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break Port -> Bool
belongs [Port]
ps in [Port]
before [Port] -> [Port] -> [Port]
forall a. [a] -> [a] -> [a]
++ String -> Port
Capture String
a Port -> [Port] -> [Port]
forall a. a -> [a] -> [a]
: (Port -> Bool) -> [Port] -> [Port]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Port -> Bool) -> Port -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Port -> Bool
belongs) [Port]
after
          | Bool
otherwise = [Port] -> [Port]
merge [Port]
ps
        merge :: [Port] -> [Port]
merge (Capture String
x : Capture String
y : [Port]
rest) | String
x String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
a Bool -> Bool -> Bool
&& String
y String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
b = String -> Port
Capture String
a Port -> [Port] -> [Port]
forall a. a -> [a] -> [a]
: [Port]
rest
        merge (Port
p : [Port]
rest) = Port
p Port -> [Port] -> [Port]
forall a. a -> [a] -> [a]
: [Port] -> [Port]
merge [Port]
rest
        merge [] = []

-- | Like 'checkPortTemplate', allowing permutations of the indicated ports
-- when testing whether branches meet. Boundary order and port multiplicity
-- are preserved. The search still applies the supplied rules to ordered
-- ports and uses exact isomorphism to identify visited states.
checkPortTemplateWithSymmetry
  :: (Eq l)
  => (l -> PortSymmetry)
  -> Maybe Natural
  -> [(key, Rule () l)]
  -> PortGraph () l
  -> Either String (PortTemplateResult key l)
checkPortTemplateWithSymmetry :: forall l key.
Eq l =>
(l -> PortSymmetry)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkPortTemplateWithSymmetry l -> PortSymmetry
symmetry = (Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
forall l key.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkPortTemplateWith ((l -> PortSymmetry) -> Graph () l -> Graph () l -> Bool
forall l.
Eq l =>
(l -> PortSymmetry) -> Graph () l -> Graph () l -> Bool
sameGraphWithSymmetry l -> PortSymmetry
symmetry)

-- | Compare reducts up to port symmetries and products of nullary scalars.
-- The classifier selects scalar labels and supplies their values in a
-- commutative monoid. A label with ports remains part of the graph. Scalar
-- products affect only the comparison between branches.
checkPortTemplateWithScalars
  :: (Eq l, Eq m, Monoid m)
  => (l -> PortSymmetry)
  -> (l -> Maybe m)
  -> Maybe Natural
  -> [(key, Rule () l)]
  -> PortGraph () l
  -> Either String (PortTemplateResult key l)
checkPortTemplateWithScalars :: forall l m key.
(Eq l, Eq m, Monoid m) =>
(l -> PortSymmetry)
-> (l -> Maybe m)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkPortTemplateWithScalars l -> PortSymmetry
symmetry l -> Maybe m
scalar = (Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
forall l key.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkPortTemplateWith ((l -> PortSymmetry)
-> (l -> Maybe m) -> Graph () l -> Graph () l -> Bool
forall l m.
(Eq l, Eq m, Monoid m) =>
(l -> PortSymmetry)
-> (l -> Maybe m) -> Graph () l -> Graph () l -> Bool
sameGraphWithScalars l -> PortSymmetry
symmetry l -> Maybe m
scalar)

sameGraphWithScalars
  :: (Eq l, Eq m, Monoid m) => (l -> PortSymmetry) -> (l -> Maybe m) -> Graph () l -> Graph () l -> Bool
sameGraphWithScalars :: forall l m.
(Eq l, Eq m, Monoid m) =>
(l -> PortSymmetry)
-> (l -> Maybe m) -> Graph () l -> Graph () l -> Bool
sameGraphWithScalars l -> PortSymmetry
symmetry l -> Maybe m
scalar Graph () l
left Graph () l
right =
  let (m
leftProduct, Graph () l
l) = Graph () l -> (m, Graph () l)
separate Graph () l
left
      (m
rightProduct, Graph () l
r) = Graph () l -> (m, Graph () l)
separate Graph () l
right
  in m
leftProduct m -> m -> Bool
forall a. Eq a => a -> a -> Bool
== m
rightProduct Bool -> Bool -> Bool
&& (l -> PortSymmetry) -> Graph () l -> Graph () l -> Bool
forall l.
Eq l =>
(l -> PortSymmetry) -> Graph () l -> Graph () l -> Bool
sameGraphWithSymmetry l -> PortSymmetry
symmetry Graph () l
l Graph () l
r
  where
    separate :: Graph () l -> (m, Graph () l)
separate (Graph [SomeSort ()]
sorts [Int]
ins [Int]
outs [Box l Int]
boxes) =
      let (m
factor, [Box l Int]
ordinary) = (Box l Int -> (m, [Box l Int]) -> (m, [Box l Int]))
-> (m, [Box l Int]) -> [Box l Int] -> (m, [Box l Int])
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Box l Int -> (m, [Box l Int]) -> (m, [Box l Int])
split (m
forall a. Monoid a => a
mempty, []) [Box l Int]
boxes
      in (m
factor, [SomeSort ()] -> [Int] -> [Int] -> [Box l Int] -> Graph () l
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph [SomeSort ()]
sorts [Int]
ins [Int]
outs [Box l Int]
ordinary)
    split :: Box l Int -> (m, [Box l Int]) -> (m, [Box l Int])
split (Box l
l [] []) (m
factor, [Box l Int]
boxes) | Just m
value <- l -> Maybe m
scalar l
l = (m
value m -> m -> m
forall a. Semigroup a => a -> a -> a
<> m
factor, [Box l Int]
boxes)
    split Box l Int
box (m
factor, [Box l Int]
boxes) = (m
factor, Box l Int
box Box l Int -> [Box l Int] -> [Box l Int]
forall a. a -> [a] -> [a]
: [Box l Int]
boxes)

checkPortTemplateWith
  :: (Eq l)
  => (Graph () l -> Graph () l -> Bool)
  -> Maybe Natural
  -> [(key, Rule () l)]
  -> PortGraph () l
  -> Either String (PortTemplateResult key l)
checkPortTemplateWith :: forall l key.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> [(key, Rule () l)]
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkPortTemplateWith Graph () l -> Graph () l -> Bool
equivalent Maybe Natural
maxDepth [(key, Rule () l)]
rules PortGraph () l
source = do
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless
    (((key, Rule () l) -> Bool) -> [(key, Rule () l)] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (Maybe OverlapReplacement -> Bool
forall a. Maybe a -> Bool
isJust (Maybe OverlapReplacement -> Bool)
-> ((key, Rule () l) -> Maybe OverlapReplacement)
-> (key, Rule () l)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Rule () l -> Maybe OverlapReplacement
forall s l. Rule s l -> Maybe OverlapReplacement
overlapReplacement (Rule () l -> Maybe OverlapReplacement)
-> ((key, Rule () l) -> Rule () l)
-> (key, Rule () l)
-> Maybe OverlapReplacement
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (key, Rule () l) -> Rule () l
forall a b. (a, b) -> b
snd) [(key, Rule () l)]
rules)
    ( String -> Either String ()
forall a b. a -> Either a b
Left
        String
"checkPortTemplate: expected port rules with computed replacements or fixed replacements using numbered nodes and whole captures"
    )
  let ([key]
keys, [Rule () l]
patterns) = [(key, Rule () l)] -> ([key], [Rule () l])
forall a b. [(a, b)] -> ([a], [b])
unzip [(key, Rule () l)]
rules
  compiled <- [(Int, Rule () l)] -> Either String (CompiledRules Int () l)
forall key l s.
(Ord key, Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRules ([Int] -> [Rule () l] -> [(Int, Rule () l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] [Rule () l]
patterns)
  checkCompiledPortTemplate equivalent maxDepth (keys !!) compiled source

checkCompiledPortTemplate
  :: (Eq l)
  => (Graph () l -> Graph () l -> Bool)
  -> Maybe Natural
  -> (Int -> key)
  -> CompiledRules Int () l
  -> PortGraph () l
  -> Either String (PortTemplateResult key l)
checkCompiledPortTemplate :: forall l key.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> (Int -> key)
-> CompiledRules Int () l
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkCompiledPortTemplate Graph () l -> Graph () l -> Bool
equivalent Maybe Natural
maxDepth Int -> key
key CompiledRules Int () l
compiled PortGraph () l
source = do
  host <- PortGraph () l -> Either String (Graph () l)
forall l. PortGraph () l -> Either String (Graph () l)
symbolicPortGraph PortGraph () l
source
  let PortGraph _ boundary _ = source
      matchesSymbolic = Int
-> CompiledRules Int () l -> Graph () l -> [(Int, Prepared () l)]
forall l key.
Eq l =>
Int
-> CompiledRules key () l -> Graph () l -> [(Int, Prepared () l)]
symbolicMatches ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
boundary) CompiledRules Int () l
compiled
      steps =
        [(Int -> key
key Int
i, Graph () (LabelTest l)
-> Graph () l -> Graph () l -> [Match] -> Graph () l
forall s p l.
Graph s p -> Graph s l -> Graph s l -> [Match] -> Graph s l
replaceMany Graph () (LabelTest l)
lhs Graph () l
rhs Graph () l
host [Match
match]) | (Int
i, (Graph () (LabelTest l)
lhs, Graph () l
rhs, Match
match)) <- Graph () l -> [(Int, Prepared () l)]
matchesSymbolic Graph () l
host]
      forks = [((key, Graph () l)
left, (key, Graph () l)
right) | (key, Graph () l)
left : [(key, Graph () l)]
rest <- [(key, Graph () l)] -> [[(key, Graph () l)]]
forall a. [a] -> [[a]]
tails [(key, Graph () l)]
steps, (key, Graph () l)
right <- [(key, Graph () l)]
rest]
      witness ((key
lk, Graph () l
left), (key
rk, Graph () l
right)) = Graph () l
-> (forall (as :: [()]) (bs :: [()]).
    (Graph () l -> Wires as ~> Wires bs) -> CriticalOverlap key () l)
-> CriticalOverlap key () l
forall s l r.
Graph s l
-> (forall (as :: [s]) (bs :: [s]).
    (Graph s l -> Wires as ~> Wires bs) -> r)
-> r
withDiagramBoundary Graph () l
host \Graph () l -> Wires as ~> Wires bs
render ->
        key
-> key
-> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs)
-> CriticalOverlap key () l
forall {key} {s} {l} (as :: [s]) (bs :: [s]).
key
-> key
-> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs)
-> CriticalOverlap key s l
CriticalOverlap key
lk key
rk (Graph () l -> Wires as ~> Wires bs
render Graph () l
host) (Graph () l -> Wires as ~> Wires bs
render Graph () l
left) (Graph () l -> Wires as ~> Wires bs
render Graph () l
right)
      join = (Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> (Graph () l -> [Graph () l])
-> Graph () l
-> Graph () l
-> Maybe Bool
forall l s.
(Eq l, DecidableIso s) =>
(Graph s l -> Graph s l -> Bool)
-> Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
joinGraphsWith Graph () l -> Graph () l -> Bool
equivalent Maybe Natural
maxDepth ((Graph () l -> [Prepared () l]) -> Graph () l -> [Graph () l]
forall s l.
(Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
singleReducts (((Int, Prepared () l) -> Prepared () l)
-> [(Int, Prepared () l)] -> [Prepared () l]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Prepared () l) -> Prepared () l
forall a b. (a, b) -> b
snd ([(Int, Prepared () l)] -> [Prepared () l])
-> (Graph () l -> [(Int, Prepared () l)])
-> Graph () l
-> [Prepared () l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Graph () l -> [(Int, Prepared () l)]
matchesSymbolic))
  pure $ case checkJoins join (\((key
_, Graph () l
l), (key
_, Graph () l
r)) -> (Graph () l
l, Graph () l
r)) forks of
    AllJoinable Int
count -> Int -> PortTemplateResult key l
forall key l. Int -> PortTemplateResult key l
PortTemplateJoinable Int
count
    Unjoinable ((key, Graph () l), (key, Graph () l))
fork -> CriticalOverlap key () l -> PortTemplateResult key l
forall key l. CriticalOverlap key () l -> PortTemplateResult key l
PortTemplateUnjoinable (((key, Graph () l), (key, Graph () l)) -> CriticalOverlap key () l
witness ((key, Graph () l), (key, Graph () l))
fork)
    JoinLimit ((key, Graph () l), (key, Graph () l))
fork -> CriticalOverlap key () l -> PortTemplateResult key l
forall key l. CriticalOverlap key () l -> PortTemplateResult key l
PortTemplateJoinLimit (((key, Graph () l), (key, Graph () l)) -> CriticalOverlap key () l
witness ((key, Graph () l), (key, Graph () l))
fork)

symbolicMatches :: (Eq l) => Int -> CompiledRules key () l -> Graph () l -> [(Int, Prepared () l)]
symbolicMatches :: forall l key.
Eq l =>
Int
-> CompiledRules key () l -> Graph () l -> [(Int, Prepared () l)]
symbolicMatches Int
boundarySize CompiledRules key () l
compiled host :: Graph () l
host@(Graph [SomeSort ()]
_ [Int]
inputs' [Int]
_ [Box l Int]
_) =
  IntSet
-> CompiledRules key () l -> Graph () l -> [(Int, Prepared () l)]
forall l s key.
(Eq l, DecidableIso s) =>
IntSet
-> CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatchesAvoiding ([Int] -> IntSet
IS.fromList (Int -> [Int] -> [Int]
forall a. Int -> [a] -> [a]
drop Int
boundarySize [Int]
inputs')) CompiledRules key () l
compiled Graph () l
host

-- | Bounded completion of port rules on the generated templates.
-- The returned rules are in input and discovery order.
data PortCompletion l
  = PortComplete [Rule () l] (CompiledRules Int () l)
  | PortIncomplete [Rule () l] (PortCompletionStop l)

-- | The unresolved template and its fork. Keys index the returned rules.
data PortCompletionStop l
  = PortRuleLimit (PortGraph () l) (CriticalOverlap Int () l)
  | PortJoinLimit (PortGraph () l) (CriticalOverlap Int () l)
  | PortUnorientable String (PortGraph () l) (CriticalOverlap Int () l)

-- | Complete fixed literal port rules within bounds on the number of learned
-- rules and the search depth from either branch. The caller supplies a
-- well-founded comparison preserved by contexts. Seed and learned rules must
-- strictly decrease after every allowed capture substitution, including empty
-- sequences. Each learned rule orients the simplified branches of a fork and
-- is rejected if setting all captures to empty makes it a no-op. Success
-- covers the templates generated for the final rules under the symbolic
-- semantics of 'checkPortTemplate'.
completePorts
  :: (Eq l)
  => Natural
  -> Natural
  -> (PortGraph () l -> PortGraph () l -> Ordering)
  -> [Rule () l]
  -> Either String (PortCompletion l)
completePorts :: forall l.
Eq l =>
Natural
-> Natural
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> [Rule () l]
-> Either String (PortCompletion l)
completePorts Natural
maxRules Natural
maxDepth PortGraph () l -> PortGraph () l -> Ordering
order [Rule () l]
rules =
  (PortCompletion l, [()]) -> PortCompletion l
forall a b. (a, b) -> a
fst
    ((PortCompletion l, [()]) -> PortCompletion l)
-> Either String (PortCompletion l, [()])
-> Either String (PortCompletion l)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Graph () l -> Graph () l -> Bool)
-> (l -> PortSymmetry)
-> ([Rule () l] -> Either String [PortGraph () l])
-> (PortGraph () l
    -> PortGraph () l -> Either String ([Rule () l], ()))
-> Natural
-> Natural
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> [Rule () l]
-> Either String (PortCompletion l, [()])
forall l a.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> (l -> PortSymmetry)
-> ([Rule () l] -> Either String [PortGraph () l])
-> (PortGraph () l
    -> PortGraph () l -> Either String ([Rule () l], a))
-> Natural
-> Natural
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> [Rule () l]
-> Either String (PortCompletion l, [a])
completePortsWith
      Graph () l -> Graph () l -> Bool
forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph
      (PortSymmetry -> l -> PortSymmetry
forall a b. a -> b -> a
const PortSymmetry
OrderedPorts)
      [Rule () l] -> Either String [PortGraph () l]
forall l. Eq l => [Rule () l] -> Either String [PortGraph () l]
portOverlapTemplates
      (\PortGraph () l
l PortGraph () l
r -> (,()) ([Rule () l] -> ([Rule () l], ()))
-> (Rule () l -> [Rule () l]) -> Rule () l -> ([Rule () l], ())
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Rule () l -> [Rule () l] -> [Rule () l]
forall a. a -> [a] -> [a]
: []) (Rule () l -> ([Rule () l], ()))
-> Either String (Rule () l) -> Either String ([Rule () l], ())
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> PortGraph () l -> PortGraph () l -> Either String (Rule () l)
forall s l.
DecidableIso s =>
PortGraph s l -> PortGraph s l -> Either String (Rule s l)
portRule PortGraph () l
l PortGraph () l
r)
      Natural
maxRules
      Natural
maxDepth
      PortGraph () l -> PortGraph () l -> Ordering
order
      [Rule () l]
rules

-- | Like 'completePorts', with label parameters interpreted in a symbolic
-- algebra. The first argument supplies fresh variables for overlap generation.
-- The second reifies symbolic values into parameters that evaluate in the same
-- algebra. It must preserve variable names, literals and expressions between
-- the two branches. The learned rules are used in subsequent rounds, and the
-- compiled result rewrites labels in that algebra. The comparison must also
-- be preserved under substitution of label parameters.
completeParameterPorts
  :: (Traversable f, Typeable f, Eq (f ()), Eq (f a), Eq a)
  => (Int -> a)
  -> (a -> Parameter a)
  -> Natural
  -> Natural
  -> (PortGraph () (f a) -> PortGraph () (f a) -> Ordering)
  -> [Rule () (f a)]
  -> Either String (PortCompletion (f a))
completeParameterPorts :: forall (f :: Type -> Type) a.
(Traversable f, Typeable f, Eq (f ()), Eq (f a), Eq a) =>
(Int -> a)
-> (a -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f a) -> PortGraph () (f a) -> Ordering)
-> [Rule () (f a)]
-> Either String (PortCompletion (f a))
completeParameterPorts Int -> a
fresh a -> Parameter a
parameter Natural
maxRules Natural
maxDepth PortGraph () (f a) -> PortGraph () (f a) -> Ordering
order [Rule () (f a)]
rules =
  (PortCompletion (f a), [()]) -> PortCompletion (f a)
forall a b. (a, b) -> a
fst
    ((PortCompletion (f a), [()]) -> PortCompletion (f a))
-> Either String (PortCompletion (f a), [()])
-> Either String (PortCompletion (f a))
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Graph () (f a) -> Graph () (f a) -> Bool)
-> (f a -> PortSymmetry)
-> ([Rule () (f a)] -> Either String [PortGraph () (f a)])
-> (PortGraph () (f a)
    -> PortGraph () (f a) -> Either String ([Rule () (f a)], ()))
-> Natural
-> Natural
-> (PortGraph () (f a) -> PortGraph () (f a) -> Ordering)
-> [Rule () (f a)]
-> Either String (PortCompletion (f a), [()])
forall l a.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> (l -> PortSymmetry)
-> ([Rule () l] -> Either String [PortGraph () l])
-> (PortGraph () l
    -> PortGraph () l -> Either String ([Rule () l], a))
-> Natural
-> Natural
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> [Rule () l]
-> Either String (PortCompletion l, [a])
completePortsWith
      Graph () (f a) -> Graph () (f a) -> Bool
forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph
      (PortSymmetry -> f a -> PortSymmetry
forall a b. a -> b -> a
const PortSymmetry
OrderedPorts)
      ((Int -> a) -> [Rule () (f a)] -> Either String [PortGraph () (f a)]
forall (f :: Type -> Type) a.
(Traversable f, Eq (f ()), Eq (f a), Eq a) =>
(Int -> a) -> [Rule () (f a)] -> Either String [PortGraph () (f a)]
parameterPortOverlapTemplates Int -> a
fresh)
      (\PortGraph () (f a)
l PortGraph () (f a)
r -> (,()) ([Rule () (f a)] -> ([Rule () (f a)], ()))
-> (Rule () (f a) -> [Rule () (f a)])
-> Rule () (f a)
-> ([Rule () (f a)], ())
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Rule () (f a) -> [Rule () (f a)] -> [Rule () (f a)]
forall a. a -> [a] -> [a]
: []) (Rule () (f a) -> ([Rule () (f a)], ()))
-> Either String (Rule () (f a))
-> Either String ([Rule () (f a)], ())
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (a -> Parameter a)
-> PortGraph () (f a)
-> PortGraph () (f a)
-> Either String (Rule () (f a))
forall (f :: Type -> Type) a symbolic.
(Traversable f, Typeable f, Eq (f ()), Eq a) =>
(symbolic -> Parameter a)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String (Rule () (f a))
reifyPortRule a -> Parameter a
parameter PortGraph () (f a)
l PortGraph () (f a)
r)
      Natural
maxRules
      Natural
maxDepth
      PortGraph () (f a) -> PortGraph () (f a) -> Ordering
order
      [Rule () (f a)]
rules

-- | Like 'completeParameterPorts', and also emit the learned rules for a
-- concrete parameter type. The two reifiers must interpret the same
-- expressions in their respective algebras. The emitted rules are in
-- discovery order, including those learned before a bounded stop. Append
-- these to the corresponding concrete seed rules to use the same priorities.
completeParameterPortsFor
  :: (Traversable f, Typeable f, Eq (f ()), Eq (f symbolic), Eq symbolic, Eq a)
  => (Int -> symbolic)
  -> (symbolic -> Parameter symbolic)
  -> (symbolic -> Parameter a)
  -> Natural
  -> Natural
  -> (PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Ordering)
  -> [Rule () (f symbolic)]
  -> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsFor :: forall (f :: Type -> Type) symbolic a.
(Traversable f, Typeable f, Eq (f ()), Eq (f symbolic),
 Eq symbolic, Eq a) =>
(Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsFor = (Graph () (f symbolic) -> Graph () (f symbolic) -> Bool)
-> (f symbolic -> PortSymmetry)
-> (f () -> PortSymmetry)
-> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
forall (f :: Type -> Type) symbolic a.
(Traversable f, Typeable f, Eq (f ()), Eq (f symbolic),
 Eq symbolic, Eq a) =>
(Graph () (f symbolic) -> Graph () (f symbolic) -> Bool)
-> (f symbolic -> PortSymmetry)
-> (f () -> PortSymmetry)
-> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsForWith Graph () (f symbolic) -> Graph () (f symbolic) -> Bool
forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph (PortSymmetry -> f symbolic -> PortSymmetry
forall a b. a -> b -> a
const PortSymmetry
OrderedPorts) (PortSymmetry -> f () -> PortSymmetry
forall a b. a -> b -> a
const PortSymmetry
OrderedPorts) (\[symbolic]
_ [symbolic]
_ -> symbolic -> symbolic
forall a. a -> a
id)

-- | Like 'completeParameterPortsFor', comparing branches using the port
-- symmetries and scalar products of 'checkPortTemplateWithScalars'. The
-- declared symmetries can also bring captures together on a replacement box
-- and must hold under parameter substitution.
completeParameterPortsForWithScalars
  :: (Traversable f, Typeable f, Eq (f ()), Eq (f symbolic), Eq symbolic, Eq a, Eq m, Monoid m)
  => (f symbolic -> PortSymmetry)
  -> (f symbolic -> Maybe m)
  -> (Int -> symbolic)
  -> (symbolic -> Parameter symbolic)
  -> (symbolic -> Parameter a)
  -> Natural
  -> Natural
  -> (PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Ordering)
  -> [Rule () (f symbolic)]
  -> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsForWithScalars :: forall (f :: Type -> Type) symbolic a m.
(Traversable f, Typeable f, Eq (f ()), Eq (f symbolic),
 Eq symbolic, Eq a, Eq m, Monoid m) =>
(f symbolic -> PortSymmetry)
-> (f symbolic -> Maybe m)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsForWithScalars f symbolic -> PortSymmetry
symmetry f symbolic -> Maybe m
scalar =
  (f symbolic -> PortSymmetry)
-> (f () -> PortSymmetry)
-> (f symbolic -> Maybe m)
-> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
forall (f :: Type -> Type) symbolic a m.
(Traversable f, Typeable f, Eq (f ()), Eq (f symbolic),
 Eq symbolic, Eq a, Eq m, Monoid m) =>
(f symbolic -> PortSymmetry)
-> (f () -> PortSymmetry)
-> (f symbolic -> Maybe m)
-> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsReparameterised f symbolic -> PortSymmetry
symmetry (PortSymmetry -> f () -> PortSymmetry
forall a b. a -> b -> a
const PortSymmetry
OrderedPorts) f symbolic -> Maybe m
scalar (\[symbolic]
_ [symbolic]
_ -> symbolic -> symbolic
forall a. a -> a
id)

-- | Like 'completeParameterPortsForWithScalars', with an optional algebraic
-- change of variables before reifying a learned rule. The callback sees the
-- parameter values of the oriented left and right branches. It returns a map
-- applied to both branches, for both symbolic and concrete rule emission.
-- The caller must ensure the new equation holds for all its parameter values.
-- The second symmetry policy selects fixed port lists to expand for matching
-- new rules, as in 'parameterPortVariants'. The order must respect these
-- symmetries. One learned rule consumes one budget slot and emits all its
-- ordered variants.
completeParameterPortsReparameterised
  :: (Traversable f, Typeable f, Eq (f ()), Eq (f symbolic), Eq symbolic, Eq a, Eq m, Monoid m)
  => (f symbolic -> PortSymmetry)
  -> (f () -> PortSymmetry)
  -> (f symbolic -> Maybe m)
  -> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
  -> (Int -> symbolic)
  -> (symbolic -> Parameter symbolic)
  -> (symbolic -> Parameter a)
  -> Natural
  -> Natural
  -> (PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Ordering)
  -> [Rule () (f symbolic)]
  -> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsReparameterised :: forall (f :: Type -> Type) symbolic a m.
(Traversable f, Typeable f, Eq (f ()), Eq (f symbolic),
 Eq symbolic, Eq a, Eq m, Monoid m) =>
(f symbolic -> PortSymmetry)
-> (f () -> PortSymmetry)
-> (f symbolic -> Maybe m)
-> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsReparameterised f symbolic -> PortSymmetry
symmetry f () -> PortSymmetry
matchingSymmetry f symbolic -> Maybe m
scalar =
  (Graph () (f symbolic) -> Graph () (f symbolic) -> Bool)
-> (f symbolic -> PortSymmetry)
-> (f () -> PortSymmetry)
-> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
forall (f :: Type -> Type) symbolic a.
(Traversable f, Typeable f, Eq (f ()), Eq (f symbolic),
 Eq symbolic, Eq a) =>
(Graph () (f symbolic) -> Graph () (f symbolic) -> Bool)
-> (f symbolic -> PortSymmetry)
-> (f () -> PortSymmetry)
-> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsForWith ((f symbolic -> PortSymmetry)
-> (f symbolic -> Maybe m)
-> Graph () (f symbolic)
-> Graph () (f symbolic)
-> Bool
forall l m.
(Eq l, Eq m, Monoid m) =>
(l -> PortSymmetry)
-> (l -> Maybe m) -> Graph () l -> Graph () l -> Bool
sameGraphWithScalars f symbolic -> PortSymmetry
symmetry f symbolic -> Maybe m
scalar) f symbolic -> PortSymmetry
symmetry f () -> PortSymmetry
matchingSymmetry

completeParameterPortsForWith
  :: forall f symbolic a
   . (Traversable f, Typeable f, Eq (f ()), Eq (f symbolic), Eq symbolic, Eq a)
  => (Graph () (f symbolic) -> Graph () (f symbolic) -> Bool)
  -> (f symbolic -> PortSymmetry)
  -> (f () -> PortSymmetry)
  -> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
  -> (Int -> symbolic)
  -> (symbolic -> Parameter symbolic)
  -> (symbolic -> Parameter a)
  -> Natural
  -> Natural
  -> (PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Ordering)
  -> [Rule () (f symbolic)]
  -> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsForWith :: forall (f :: Type -> Type) symbolic a.
(Traversable f, Typeable f, Eq (f ()), Eq (f symbolic),
 Eq symbolic, Eq a) =>
(Graph () (f symbolic) -> Graph () (f symbolic) -> Bool)
-> (f symbolic -> PortSymmetry)
-> (f () -> PortSymmetry)
-> ([symbolic] -> [symbolic] -> symbolic -> symbolic)
-> (Int -> symbolic)
-> (symbolic -> Parameter symbolic)
-> (symbolic -> Parameter a)
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either String (PortCompletion (f symbolic), [Rule () (f a)])
completeParameterPortsForWith Graph () (f symbolic) -> Graph () (f symbolic) -> Bool
equivalent f symbolic -> PortSymmetry
symmetry f () -> PortSymmetry
matchingSymmetry [symbolic] -> [symbolic] -> symbolic -> symbolic
reparameterise Int -> symbolic
fresh symbolic -> Parameter symbolic
symbolic symbolic -> Parameter a
concrete Natural
maxRules Natural
maxDepth PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Ordering
order [Rule () (f symbolic)]
rules = do
  (result, concreteRules) <-
    (Graph () (f symbolic) -> Graph () (f symbolic) -> Bool)
-> (f symbolic -> PortSymmetry)
-> ([Rule () (f symbolic)]
    -> Either String [PortGraph () (f symbolic)])
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic)
    -> Either
         String ([Rule () (f symbolic)], Either String [Rule () (f a)]))
-> Natural
-> Natural
-> (PortGraph () (f symbolic)
    -> PortGraph () (f symbolic) -> Ordering)
-> [Rule () (f symbolic)]
-> Either
     String
     (PortCompletion (f symbolic), [Either String [Rule () (f a)]])
forall l a.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> (l -> PortSymmetry)
-> ([Rule () l] -> Either String [PortGraph () l])
-> (PortGraph () l
    -> PortGraph () l -> Either String ([Rule () l], a))
-> Natural
-> Natural
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> [Rule () l]
-> Either String (PortCompletion l, [a])
completePortsWith
      Graph () (f symbolic) -> Graph () (f symbolic) -> Bool
equivalent
      f symbolic -> PortSymmetry
symmetry
      ((Int -> symbolic)
-> [Rule () (f symbolic)]
-> Either String [PortGraph () (f symbolic)]
forall (f :: Type -> Type) a.
(Traversable f, Eq (f ()), Eq (f a), Eq a) =>
(Int -> a) -> [Rule () (f a)] -> Either String [PortGraph () (f a)]
parameterPortOverlapTemplates Int -> symbolic
fresh)
      PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either
     String ([Rule () (f symbolic)], Either String [Rule () (f a)])
build
      Natural
maxRules
      Natural
maxDepth
      PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Ordering
order
      [Rule () (f symbolic)]
rules
  emitted <- concat <$> sequence concreteRules
  pure (result, emitted)
  where
    build :: PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either
     String ([Rule () (f symbolic)], Either String [Rule () (f a)])
build PortGraph () (f symbolic)
left PortGraph () (f symbolic)
right = do
      let relabel :: PortGraph () (f symbolic) -> PortGraph () (f symbolic)
relabel = (f symbolic -> f symbolic)
-> PortGraph () (f symbolic) -> PortGraph () (f symbolic)
forall l m s. (l -> m) -> PortGraph s l -> PortGraph s m
mapPortLabels ((symbolic -> symbolic) -> f symbolic -> f symbolic
forall a b. (a -> b) -> f a -> f b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap ([symbolic] -> [symbolic] -> symbolic -> symbolic
reparameterise (PortGraph () (f symbolic) -> [symbolic]
forall {t :: Type -> Type} {s} {b}.
Foldable t =>
PortGraph s (t b) -> [b]
values PortGraph () (f symbolic)
left) (PortGraph () (f symbolic) -> [symbolic]
forall {t :: Type -> Type} {s} {b}.
Foldable t =>
PortGraph s (t b) -> [b]
values PortGraph () (f symbolic)
right)))
          l :: PortGraph () (f symbolic)
l = PortGraph () (f symbolic) -> PortGraph () (f symbolic)
relabel PortGraph () (f symbolic)
left
          r :: PortGraph () (f symbolic)
r = PortGraph () (f symbolic) -> PortGraph () (f symbolic)
relabel PortGraph () (f symbolic)
right
      Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Ordering
order PortGraph () (f symbolic)
l PortGraph () (f symbolic)
r Ordering -> Ordering -> Bool
forall a. Eq a => a -> a -> Bool
== Ordering
GT) (String -> Either String ()
forall a b. a -> Either a b
Left String
"completeParameterPorts: the reparameterised rule does not decrease")
      learned <- (symbolic -> Parameter symbolic)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String [Rule () (f symbolic)]
forall b.
Eq b =>
(symbolic -> Parameter b)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String [Rule () (f b)]
emit symbolic -> Parameter symbolic
symbolic PortGraph () (f symbolic)
l PortGraph () (f symbolic)
r
      pure (learned, emit concrete l r)
    emit
      :: (Eq b)
      => (symbolic -> Parameter b) -> PortGraph () (f symbolic) -> PortGraph () (f symbolic) -> Either String [Rule () (f b)]
    emit :: forall b.
Eq b =>
(symbolic -> Parameter b)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String [Rule () (f b)]
emit symbolic -> Parameter b
parameter PortGraph () (f symbolic)
l PortGraph () (f symbolic)
r = (symbolic -> Parameter b)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String (Rule () (f b))
forall (f :: Type -> Type) a symbolic.
(Traversable f, Typeable f, Eq (f ()), Eq a) =>
(symbolic -> Parameter a)
-> PortGraph () (f symbolic)
-> PortGraph () (f symbolic)
-> Either String (Rule () (f a))
reifyPortRule symbolic -> Parameter b
parameter PortGraph () (f symbolic)
l PortGraph () (f symbolic)
r Either String (Rule () (f b))
-> (Rule () (f b) -> Either String [Rule () (f b)])
-> Either String [Rule () (f b)]
forall a b.
Either String a -> (a -> Either String b) -> Either String b
forall (m :: Type -> Type) a b. Monad m => m a -> (a -> m b) -> m b
>>= (f () -> PortSymmetry)
-> Rule () (f b) -> Either String [Rule () (f b)]
forall (f :: Type -> Type) s a.
(f () -> PortSymmetry)
-> Rule s (f a) -> Either String [Rule s (f a)]
parameterPortVariants f () -> PortSymmetry
matchingSymmetry
    values :: PortGraph s (t b) -> [b]
values (PortGraph [SomeSort s]
_ [Int]
_ [Box (t b) Port]
boxes) = (Box (t b) Port -> [b]) -> [Box (t b) Port] -> [b]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap (t b -> [b]
forall a. t a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList (t b -> [b]) -> (Box (t b) Port -> t b) -> Box (t b) Port -> [b]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Box (t b) Port -> t b
forall l n. Box l n -> l
label) [Box (t b) Port]
boxes

completePortsWith
  :: (Eq l)
  => (Graph () l -> Graph () l -> Bool)
  -> (l -> PortSymmetry)
  -> ([Rule () l] -> Either String [PortGraph () l])
  -> (PortGraph () l -> PortGraph () l -> Either String ([Rule () l], a))
  -> Natural
  -> Natural
  -> (PortGraph () l -> PortGraph () l -> Ordering)
  -> [Rule () l]
  -> Either String (PortCompletion l, [a])
completePortsWith :: forall l a.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> (l -> PortSymmetry)
-> ([Rule () l] -> Either String [PortGraph () l])
-> (PortGraph () l
    -> PortGraph () l -> Either String ([Rule () l], a))
-> Natural
-> Natural
-> (PortGraph () l -> PortGraph () l -> Ordering)
-> [Rule () l]
-> Either String (PortCompletion l, [a])
completePortsWith Graph () l -> Graph () l -> Bool
equivalent l -> PortSymmetry
symmetry [Rule () l] -> Either String [PortGraph () l]
overlaps PortGraph () l -> PortGraph () l -> Either String ([Rule () l], a)
build Natural
maxRules Natural
maxDepth PortGraph () l -> PortGraph () l -> Ordering
order = Natural
-> [a] -> [Rule () l] -> Either String (PortCompletion l, [a])
go Natural
maxRules []
  where
    depth :: Maybe Natural
depth = Natural -> Maybe Natural
forall a. a -> Maybe a
Just Natural
maxDepth
    go :: Natural
-> [a] -> [Rule () l] -> Either String (PortCompletion l, [a])
go Natural
budget [a]
learnedRev [Rule () l]
rules = do
      templates <- [Rule () l] -> Either String [PortGraph () l]
overlaps [Rule () l]
rules
      compiled <- compileRules (zip [0 ..] rules)
      let finish PortCompletion l
result = (PortCompletion l, [a]) -> Either String (PortCompletion l, [a])
forall a b. b -> Either a b
Right (PortCompletion l
result, [a] -> [a]
forall a. [a] -> [a]
reverse [a]
learnedRev)
          incomplete = PortCompletion l -> Either String (PortCompletion l, [a])
finish (PortCompletion l -> Either String (PortCompletion l, [a]))
-> (PortCompletionStop l -> PortCompletion l)
-> PortCompletionStop l
-> Either String (PortCompletion l, [a])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Rule () l] -> PortCompletionStop l -> PortCompletion l
forall l. [Rule () l] -> PortCompletionStop l -> PortCompletion l
PortIncomplete [Rule () l]
rules
          check Maybe (PortCompletionStop l)
limited [] = PortCompletion l -> Either String (PortCompletion l, [a])
finish (PortCompletion l
-> (PortCompletionStop l -> PortCompletion l)
-> Maybe (PortCompletionStop l)
-> PortCompletion l
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ([Rule () l] -> CompiledRules Int () l -> PortCompletion l
forall l. [Rule () l] -> CompiledRules Int () l -> PortCompletion l
PortComplete [Rule () l]
rules CompiledRules Int () l
compiled) ([Rule () l] -> PortCompletionStop l -> PortCompletion l
forall l. [Rule () l] -> PortCompletionStop l -> PortCompletion l
PortIncomplete [Rule () l]
rules) Maybe (PortCompletionStop l)
limited)
          check Maybe (PortCompletionStop l)
limited (PortGraph () l
source : [PortGraph () l]
rest) = do
            result <- (Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> (Int -> Int)
-> CompiledRules Int () l
-> PortGraph () l
-> Either String (PortTemplateResult Int l)
forall l key.
Eq l =>
(Graph () l -> Graph () l -> Bool)
-> Maybe Natural
-> (Int -> key)
-> CompiledRules Int () l
-> PortGraph () l
-> Either String (PortTemplateResult key l)
checkCompiledPortTemplate Graph () l -> Graph () l -> Bool
equivalent Maybe Natural
depth Int -> Int
forall a. a -> a
id CompiledRules Int () l
compiled PortGraph () l
source
            case result of
              PortTemplateJoinable Int
_ -> Maybe (PortCompletionStop l)
-> [PortGraph () l] -> Either String (PortCompletion l, [a])
check Maybe (PortCompletionStop l)
limited [PortGraph () l]
rest
              PortTemplateJoinLimit CriticalOverlap Int () l
fork -> Maybe (PortCompletionStop l)
-> [PortGraph () l] -> Either String (PortCompletion l, [a])
check (Maybe (PortCompletionStop l)
limited Maybe (PortCompletionStop l)
-> Maybe (PortCompletionStop l) -> Maybe (PortCompletionStop l)
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: Type -> Type) a. Alternative f => f a -> f a -> f a
<|> PortCompletionStop l -> Maybe (PortCompletionStop l)
forall a. a -> Maybe a
Just (PortGraph () l -> CriticalOverlap Int () l -> PortCompletionStop l
forall l.
PortGraph () l -> CriticalOverlap Int () l -> PortCompletionStop l
PortJoinLimit PortGraph () l
source CriticalOverlap Int () l
fork)) [PortGraph () l]
rest
              PortTemplateUnjoinable CriticalOverlap Int () l
fork
                | Natural
budget Natural -> Natural -> Bool
forall a. Eq a => a -> a -> Bool
== Natural
0 -> PortCompletionStop l -> Either String (PortCompletion l, [a])
incomplete (PortGraph () l -> CriticalOverlap Int () l -> PortCompletionStop l
forall l.
PortGraph () l -> CriticalOverlap Int () l -> PortCompletionStop l
PortRuleLimit PortGraph () l
source CriticalOverlap Int () l
fork)
                | Bool
otherwise -> case PortGraph () l
-> CriticalOverlap Int () l -> Either String ([Rule () l], a)
learn PortGraph () l
source CriticalOverlap Int () l
fork of
                    Left String
err -> PortCompletionStop l -> Either String (PortCompletion l, [a])
incomplete (String
-> PortGraph () l
-> CriticalOverlap Int () l
-> PortCompletionStop l
forall l.
String
-> PortGraph () l
-> CriticalOverlap Int () l
-> PortCompletionStop l
PortUnorientable String
err PortGraph () l
source CriticalOverlap Int () l
fork)
                    Right ([Rule () l]
learned, a
emitted) -> Natural
-> [a] -> [Rule () l] -> Either String (PortCompletion l, [a])
go (Natural
budget Natural -> Natural -> Natural
forall a. Num a => a -> a -> a
- Natural
1) (a
emitted a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
learnedRev) ([Rule () l]
rules [Rule () l] -> [Rule () l] -> [Rule () l]
forall a. [a] -> [a] -> [a]
++ [Rule () l]
learned)
          learn source :: PortGraph () l
source@(PortGraph [SomeSort ()]
_ [Int]
boundary [Box l Port]
_) (CriticalOverlap Int
_ Int
_ Wires as ~> Wires bs
_ Wires as ~> Wires bs
left Wires as ~> Wires bs
right) = do
            let next :: Graph () l -> [Graph () l]
next = (Graph () l -> [Prepared () l]) -> Graph () l -> [Graph () l]
forall s l.
(Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
singleReducts (((Int, Prepared () l) -> Prepared () l)
-> [(Int, Prepared () l)] -> [Prepared () l]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Prepared () l) -> Prepared () l
forall a b. (a, b) -> b
snd ([(Int, Prepared () l)] -> [Prepared () l])
-> (Graph () l -> [(Int, Prepared () l)])
-> Graph () l
-> [Prepared () l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int
-> CompiledRules Int () l -> Graph () l -> [(Int, Prepared () l)]
forall l key.
Eq l =>
Int
-> CompiledRules key () l -> Graph () l -> [(Int, Prepared () l)]
symbolicMatches ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
boundary) CompiledRules Int () l
compiled)
                normalForm :: Graph () l -> Either String (Graph () l)
normalForm Graph () l
diagram =
                  Either String (Graph () l)
-> (Graph () l -> Either String (Graph () l))
-> Maybe (Graph () l)
-> Either String (Graph () l)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
                    (String -> Either String (Graph () l)
forall a b. a -> Either a b
Left String
"completePorts: could not normalise both branches within the depth limit")
                    Graph () l -> Either String (Graph () l)
forall a b. b -> Either a b
Right
                    (Natural
-> (Graph () l -> [Graph () l]) -> Graph () l -> Maybe (Graph () l)
forall l s.
(Eq l, DecidableIso s) =>
Natural
-> (Graph s l -> [Graph s l]) -> Graph s l -> Maybe (Graph s l)
normalFormWithin Natural
maxDepth Graph () l -> [Graph () l]
next Graph () l
diagram)
            l <- Graph () l -> Either String (Graph () l)
normalForm ((Wires as ~> Wires bs) -> Graph () l
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph Wires as ~> Wires bs
left)
            r <- normalForm (graph right)
            (lhs, rhs) <- orientPortBranches symmetry order source l r
            result@(learned, _) <- build lhs rhs
            _ <- overlaps learned
            pure result
      check Nothing templates

data SymmetryLabel l = OriginalBox l | InputLeg | OutputLeg
  deriving (SymmetryLabel l -> SymmetryLabel l -> Bool
(SymmetryLabel l -> SymmetryLabel l -> Bool)
-> (SymmetryLabel l -> SymmetryLabel l -> Bool)
-> Eq (SymmetryLabel l)
forall l. Eq l => SymmetryLabel l -> SymmetryLabel l -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: forall l. Eq l => SymmetryLabel l -> SymmetryLabel l -> Bool
== :: SymmetryLabel l -> SymmetryLabel l -> Bool
$c/= :: forall l. Eq l => SymmetryLabel l -> SymmetryLabel l -> Bool
/= :: SymmetryLabel l -> SymmetryLabel l -> Bool
Eq)

sameGraphWithSymmetry :: (Eq l) => (l -> PortSymmetry) -> Graph () l -> Graph () l -> Bool
sameGraphWithSymmetry :: forall l.
Eq l =>
(l -> PortSymmetry) -> Graph () l -> Graph () l -> Bool
sameGraphWithSymmetry l -> PortSymmetry
symmetry Graph () l
left Graph () l
right =
  Graph () (SymmetryLabel l)
-> (forall (as :: [()]) (bs :: [()]).
    (Graph () (SymmetryLabel l) -> Wires as ~> Wires bs) -> Bool)
-> Bool
forall s l r.
Graph s l
-> (forall (as :: [s]) (bs :: [s]).
    (Graph s l -> Wires as ~> Wires bs) -> r)
-> r
withDiagramBoundary Graph () (SymmetryLabel l)
l \Graph () (SymmetryLabel l) -> Wires as ~> Wires bs
render -> (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Bool
forall {s} l (a :: OPENHG s l) (b :: OPENHG s l).
(Eq l, DecidableIso s) =>
(a ~> b) -> (a ~> b) -> Bool
isomorphic (Graph () (SymmetryLabel l) -> Wires as ~> Wires bs
render Graph () (SymmetryLabel l)
l) (Graph () (SymmetryLabel l) -> Wires as ~> Wires bs
render (Graph () l -> Graph () (SymmetryLabel l)
encode Graph () l
right))
  where
    l :: Graph () (SymmetryLabel l)
l = Graph () l -> Graph () (SymmetryLabel l)
encode Graph () l
left
    -- Identical legs incident to a private hub encode a multiset of ports.
    -- The ordered boundary is copied directly, so its node map is fixed
    -- before the isomorphism search compares any legs.
    encode :: Graph () l -> Graph () (SymmetryLabel l)
encode (Graph [SomeSort ()]
sorts [Int]
ins [Int]
outs [Box l Int]
boxes) =
      let (Int
end, [[Box (SymmetryLabel l) Int]]
expanded) = (Int -> Box l Int -> (Int, [Box (SymmetryLabel l) Int]))
-> Int -> [Box l Int] -> (Int, [[Box (SymmetryLabel l) Int]])
forall (t :: Type -> Type) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
List.mapAccumL Int -> Box l Int -> (Int, [Box (SymmetryLabel l) Int])
encodeBox ([SomeSort ()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort ()]
sorts) [Box l Int]
boxes
      in [SomeSort ()]
-> [Int]
-> [Int]
-> [Box (SymmetryLabel l) Int]
-> Graph () (SymmetryLabel l)
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph ([SomeSort ()]
sorts [SomeSort ()] -> [SomeSort ()] -> [SomeSort ()]
forall a. [a] -> [a] -> [a]
++ Int -> SomeSort () -> [SomeSort ()]
forall a. Int -> a -> [a]
replicate (Int
end Int -> Int -> Int
forall a. Num a => a -> a -> a
- [SomeSort ()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort ()]
sorts) (forall {k} {c :: OB k} (x :: k). c x => SomeOf c
forall (x :: ()). SortOb x => SomeSort ()
Some @'())) [Int]
ins [Int]
outs ([[Box (SymmetryLabel l) Int]] -> [Box (SymmetryLabel l) Int]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat [[Box (SymmetryLabel l) Int]]
expanded)
    encodeBox :: Int -> Box l Int -> (Int, [Box (SymmetryLabel l) Int])
encodeBox Int
start (Box l
label' [Int]
ins [Int]
outs) =
      let order :: PortSymmetry
order = l -> PortSymmetry
symmetry l
label'
          symIn :: Bool
symIn = PortSymmetry -> Bool
symmetricInputs PortSymmetry
order
          symOut :: Bool
symOut = PortSymmetry -> Bool
symmetricOutputs PortSymmetry
order
          (Int
afterInputs, [Int]
ins', [Box (SymmetryLabel l) Int]
inputLegs)
            | Bool
symIn = (Int
start Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1, [Int
start], [SymmetryLabel l -> [Int] -> [Int] -> Box (SymmetryLabel l) Int
forall l n. l -> [n] -> [n] -> Box l n
Box SymmetryLabel l
forall l. SymmetryLabel l
InputLeg [Int
i] [Int
start] | Int
i <- [Int]
ins])
            | Bool
otherwise = (Int
start, [Int]
ins, [])
          (Int
end, [Int]
outs', [Box (SymmetryLabel l) Int]
outputLegs)
            | Bool
symOut = (Int
afterInputs Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1, [Int
afterInputs], [SymmetryLabel l -> [Int] -> [Int] -> Box (SymmetryLabel l) Int
forall l n. l -> [n] -> [n] -> Box l n
Box SymmetryLabel l
forall l. SymmetryLabel l
OutputLeg [Int
afterInputs] [Int
o] | Int
o <- [Int]
outs])
            | Bool
otherwise = (Int
afterInputs, [Int]
outs, [])
      in (Int
end, SymmetryLabel l -> [Int] -> [Int] -> Box (SymmetryLabel l) Int
forall l n. l -> [n] -> [n] -> Box l n
Box (l -> SymmetryLabel l
forall l. l -> SymmetryLabel l
OriginalBox l
label') [Int]
ins' [Int]
outs' Box (SymmetryLabel l) Int
-> [Box (SymmetryLabel l) Int] -> [Box (SymmetryLabel l) Int]
forall a. a -> [a] -> [a]
: [Box (SymmetryLabel l) Int]
inputLegs [Box (SymmetryLabel l) Int]
-> [Box (SymmetryLabel l) Int] -> [Box (SymmetryLabel l) Int]
forall a. [a] -> [a] -> [a]
++ [Box (SymmetryLabel l) Int]
outputLegs)

-- | Enumerate schematic sources where two literal port rules share one or two
-- boxes, or share interface wires that one rule can merge and the other needs
-- to keep distinct. Each left port list allows at most one capture in each gap between numbered ports,
-- including before the first port and after the last. Each capture must occur
-- once on the left, and every numbered node must occur at a box port.
-- Captures stand for external leg sequences.
--
-- A numbered port can align with another numbered port or occupy a capture
-- on the other side. A deleted node must stay within the deleting match and
-- cannot also occur in one of that match's captures. Preserved nodes can
-- be identified even when they do not meet at a shared port. Numbered nodes
-- preserved by both matches are exposed as the template's boundary.
-- Retain a common symbolic sequence wherever both lists allow a capture.
-- Different embeddings can give the same template.
-- Pass the generated sources to 'checkPortTemplate' to check their joins.
portOverlapTemplates :: (Eq l) => [Rule () l] -> Either String [PortGraph () l]
portOverlapTemplates :: forall l. Eq l => [Rule () l] -> Either String [PortGraph () l]
portOverlapTemplates =
  String
-> (Rule () l -> Maybe (PortGraph () l))
-> (l -> l -> Bool)
-> ([(l, l)] -> [Either l l] -> Maybe [l])
-> [Rule () l]
-> Either String [PortGraph () l]
forall l p.
Eq l =>
String
-> (Rule () l -> Maybe (PortGraph () p))
-> (p -> p -> Bool)
-> ([(p, p)] -> [Either p p] -> Maybe [l])
-> [Rule () l]
-> Either String [PortGraph () l]
portOverlapTemplatesBy String
"literal labels" Rule () l -> Maybe (PortGraph () l)
forall s l. Rule s l -> Maybe (PortGraph s l)
literalPortPattern l -> l -> Bool
forall a. Eq a => a -> a -> Bool
(==) (\[(l, l)]
_ -> [l] -> Maybe [l]
forall a. a -> Maybe a
Just ([l] -> Maybe [l])
-> ([Either l l] -> [l]) -> [Either l l] -> Maybe [l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Either l l -> l) -> [Either l l] -> [l]
forall a b. (a -> b) -> [a] -> [b]
map ((l -> l) -> (l -> l) -> Either l l -> l
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either l -> l
forall a. a -> a
id l -> l
forall a. a -> a
id))

-- | Generate overlaps from rules built with
-- 'Proarrow.Tools.HypergraphRewrite.parameterPortRule' or
-- 'Proarrow.Tools.HypergraphRewrite.parameterPortRuleWith'. Shared boxes unify
-- their label parameters. Literal constraints propagate to every occurrence
-- of the same variable in its rule, and conflicting constraints discard the
-- overlap. Supply a distinct symbolic value for each free variable class,
-- disjoint from the literal values in the rules.
-- Computed replacements can overlap when the template fixes every capture
-- length and both matches instantiate successfully. The template specialises
-- shared gaps and captures on unshared computed boxes to empty. Wire-only
-- overlaps use the computed interface at those empty capture lengths.
parameterPortOverlapTemplates
  :: (Traversable f, Eq (f ()), Eq (f a), Eq a)
  => (Int -> a) -> [Rule () (f a)] -> Either String [PortGraph () (f a)]
parameterPortOverlapTemplates :: forall (f :: Type -> Type) a.
(Traversable f, Eq (f ()), Eq (f a), Eq a) =>
(Int -> a) -> [Rule () (f a)] -> Either String [PortGraph () (f a)]
parameterPortOverlapTemplates Int -> a
fresh =
  String
-> (Rule () (f a) -> Maybe (PortGraph () (f (Parameter a))))
-> (f (Parameter a) -> f (Parameter a) -> Bool)
-> ([(f (Parameter a), f (Parameter a))]
    -> [Either (f (Parameter a)) (f (Parameter a))] -> Maybe [f a])
-> [Rule () (f a)]
-> Either String [PortGraph () (f a)]
forall l p.
Eq l =>
String
-> (Rule () l -> Maybe (PortGraph () p))
-> (p -> p -> Bool)
-> ([(p, p)] -> [Either p p] -> Maybe [l])
-> [Rule () l]
-> Either String [PortGraph () l]
portOverlapTemplatesBy String
"label parameters" Rule () (f a) -> Maybe (PortGraph () (f (Parameter a)))
forall s (f :: Type -> Type) a.
Rule s (f a) -> Maybe (PortGraph s (f (Parameter a)))
parameterPortPattern (f () -> f () -> Bool
forall a. Eq a => a -> a -> Bool
(==) (f () -> f () -> Bool)
-> (f (Parameter a) -> f ())
-> f (Parameter a)
-> f (Parameter a)
-> Bool
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` f (Parameter a) -> f ()
forall (f :: Type -> Type) a. Functor f => f a -> f ()
void) ((Int -> a)
-> [(f (Parameter a), f (Parameter a))]
-> [Either (f (Parameter a)) (f (Parameter a))]
-> Maybe [f a]
forall (f :: Type -> Type) a.
(Traversable f, Eq a) =>
(Int -> a)
-> [(f (Parameter a), f (Parameter a))]
-> [Either (f (Parameter a)) (f (Parameter a))]
-> Maybe [f a]
solvePortLabels Int -> a
fresh)

portOverlapTemplatesBy
  :: (Eq l)
  => String
  -> (Rule () l -> Maybe (PortGraph () p))
  -> (p -> p -> Bool)
  -> ([(p, p)] -> [Either p p] -> Maybe [l])
  -> [Rule () l]
  -> Either String [PortGraph () l]
portOverlapTemplatesBy :: forall l p.
Eq l =>
String
-> (Rule () l -> Maybe (PortGraph () p))
-> (p -> p -> Bool)
-> ([(p, p)] -> [Either p p] -> Maybe [l])
-> [Rule () l]
-> Either String [PortGraph () l]
portOverlapTemplatesBy String
labelKind Rule () l -> Maybe (PortGraph () p)
patternFor p -> p -> Bool
compatible [(p, p)] -> [Either p p] -> Maybe [l]
solve [Rule () l]
rules = do
  patterns <- (Rule () l -> Either String (PortOverlapPattern p l))
-> [Rule () l] -> Either String [PortOverlapPattern p l]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Rule () l -> Either String (PortOverlapPattern p l)
validate [Rule () l]
rules
  pure
    [ source
    | first : rest <- tails patterns
    , (sameRule, second) <- (True, first) : map (False,) rest
    , source <- gluePortOverlap compatible solve sameRule first second
    ]
  where
    validate :: Rule () l -> Either String (PortOverlapPattern p l)
validate Rule () l
ruleToCheck = do
      left@(PortGraph sorts _ boxes) <-
        Either String (PortGraph () p)
-> (PortGraph () p -> Either String (PortGraph () p))
-> Maybe (PortGraph () p)
-> Either String (PortGraph () p)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
          (String -> Either String (PortGraph () p)
forall a b. a -> Either a b
Left (String
"portOverlapTemplates: expected port rules with " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
labelKind))
          PortGraph () p -> Either String (PortGraph () p)
forall a b. b -> Either a b
Right
          (Rule () l -> Maybe (PortGraph () p)
patternFor Rule () l
ruleToCheck)
      let lists = (Box p Port -> [[Port]]) -> [Box p Port] -> [[Port]]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap (\Box p Port
box -> [Box p Port -> [Port]
forall l n. Box l n -> [n]
inputs Box p Port
box, Box p Port -> [Port]
forall l n. Box l n -> [n]
outputs Box p Port
box]) [Box p Port]
boxes
          names = [String
name | [Port]
ps <- [[Port]]
lists, Capture String
name <- [Port]
ps]
          used = [Int] -> IntSet
IS.fromList [Int
n | [Port]
ps <- [[Port]]
lists, Node Int
n <- [Port]
ps]
      unless
        (all oneCapturePerGap lists && length names == length (nubOrd names))
        (Left "portOverlapTemplates: captures must occur once, with at most one in each port-list gap")
      unless
        (IS.size used == length sorts)
        (Left "portOverlapTemplates: each numbered node must occur at a box port")
      replacement <-
        maybe
          (Left "portOverlapTemplates: expected a computed replacement or a fixed replacement without indexed captures")
          Right
          (overlapReplacement ruleToCheck)
      compiled <- compileRules [((), ruleToCheck)]
      pure (PortOverlapPattern left replacement compiled)
    oneCapturePerGap :: [Port] -> Bool
oneCapturePerGap [Port]
ps = Bool -> Bool
not (((Port, Port) -> Bool) -> [(Port, Port)] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (Port, Port) -> Bool
bothCaptures ([Port] -> [Port] -> [(Port, Port)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Port]
ps (Int -> [Port] -> [Port]
forall a. Int -> [a] -> [a]
drop Int
1 [Port]
ps)))
    bothCaptures :: (Port, Port) -> Bool
bothCaptures (Port
p, Port
q) = Port -> Bool
isCapture Port
p Bool -> Bool -> Bool
&& Port -> Bool
isCapture Port
q

data PortOverlapPattern p l = PortOverlapPattern (PortGraph () p) OverlapReplacement (CompiledRules () () l)

data OverlapReplacement = FixedInterface [Int] | ComputedInterface (Maybe [Int])

gluePortOverlap
  :: (Eq l)
  => (p -> p -> Bool)
  -> ([(p, p)] -> [Either p p] -> Maybe [l])
  -> Bool
  -> PortOverlapPattern p l
  -> PortOverlapPattern p l
  -> [PortGraph () l]
gluePortOverlap :: forall l p.
Eq l =>
(p -> p -> Bool)
-> ([(p, p)] -> [Either p p] -> Maybe [l])
-> Bool
-> PortOverlapPattern p l
-> PortOverlapPattern p l
-> [PortGraph () l]
gluePortOverlap
  p -> p -> Bool
compatible
  [(p, p)] -> [Either p p] -> Maybe [l]
solve
  Bool
sameRule
  (PortOverlapPattern (PortGraph [SomeSort ()]
ls [Int]
li [Box p Port]
left) OverlapReplacement
leftReplacement CompiledRules () () l
leftCompiled)
  (PortOverlapPattern (PortGraph [SomeSort ()]
rs [Int]
ri [Box p Port]
right) OverlapReplacement
rightReplacement CompiledRules () () l
rightCompiled) = do
    boxPairs <-
      [[] | Bool
wireConflictPossible]
        [[(Int, Int)]] -> [[(Int, Int)]] -> [[(Int, Int)]]
forall a. [a] -> [a] -> [a]
++ ((Int, Int) -> [(Int, Int)]) -> [(Int, Int)] -> [[(Int, Int)]]
forall a b. (a -> b) -> [a] -> [b]
map ((Int, Int) -> [(Int, Int)] -> [(Int, Int)]
forall a. a -> [a] -> [a]
: []) [(Int, Int)]
candidates
        [[(Int, Int)]] -> [[(Int, Int)]] -> [[(Int, Int)]]
forall a. [a] -> [a] -> [a]
++ [[(Int, Int)
p, (Int, Int)
q] | p :: (Int, Int)
p@(Int
i, Int
j) : [(Int, Int)]
rest <- [(Int, Int)] -> [[(Int, Int)]]
forall a. [a] -> [[a]]
tails [(Int, Int)]
candidates, q :: (Int, Int)
q@(Int
k, Int
l) <- [(Int, Int)]
rest, Int
i Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
k, Int
j Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
l]
    guard (not sameRule || boxPairs <= List.sort [(j, i) | (i, j) <- boxPairs])
    let leftOnly = IntMap (Box p Port) -> IntSet -> IntMap (Box p Port)
forall a. IntMap a -> IntSet -> IntMap a
IM.withoutKeys IntMap (Box p Port)
leftBoxes ([Int] -> IntSet
IS.fromList (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> a
fst [(Int, Int)]
boxPairs))
        rightOnly = IntMap (Box p Port) -> IntSet -> IntMap (Box p Port)
forall a. IntMap a -> IntSet -> IntMap a
IM.withoutKeys IntMap (Box p Port)
rightBoxes ([Int] -> IntSet
IS.fromList (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> b
snd [(Int, Int)]
boxPairs))
        attached IntMap (Box l Port)
side = [Int] -> IntSet
IS.fromList [Int
n | Box l Port
b <- IntMap (Box l Port) -> [Box l Port]
forall a. IntMap a -> [a]
IM.elems IntMap (Box l Port)
side, Node Int
n <- Box l Port -> [Port]
forall l n. Box l n -> [n]
inputs Box l Port
b [Port] -> [Port] -> [Port]
forall a. [a] -> [a] -> [a]
++ Box l Port -> [Port]
forall l n. Box l n -> [n]
outputs Box l Port
b]
        outsideLeft = IntMap (Box p Port) -> IntSet
forall {l}. IntMap (Box l Port) -> IntSet
attached IntMap (Box p Port)
leftOnly
        outsideRight = IntMap (Box p Port) -> IntSet
forall {l}. IntMap (Box l Port) -> IntSet
attached IntMap (Box p Port)
rightOnly
        canIdentify Int
l Int
r =
          (Int -> IntSet -> Bool
IS.member Int
l IntSet
leftKept Bool -> Bool -> Bool
|| Int -> IntSet -> Bool
IS.notMember Int
r IntSet
outsideRight)
            Bool -> Bool -> Bool
&& (Int -> IntSet -> Bool
IS.member Int
r IntSet
rightKept Bool -> Bool -> Bool
|| Int -> IntSet -> Bool
IS.notMember Int
l IntSet
outsideLeft)
    let sharedLabels = [(Box p Port -> p
forall l n. Box l n -> l
label (IntMap (Box p Port)
leftBoxes IntMap (Box p Port) -> Int -> Box p Port
forall a. IntMap a -> Int -> a
IM.! Int
i), Box p Port -> p
forall l n. Box l n -> l
label (IntMap (Box p Port)
rightBoxes IntMap (Box p Port) -> Int -> Box p Port
forall a. IntMap a -> Int -> a
IM.! Int
j)) | (Int
i, Int
j) <- [(Int, Int)]
boxPairs]
        sourceLabels = (Box p Port -> Either p p) -> [Box p Port] -> [Either p p]
forall a b. (a -> b) -> [a] -> [b]
map (p -> Either p p
forall a b. a -> Either a b
Left (p -> Either p p) -> (Box p Port -> p) -> Box p Port -> Either p p
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Box p Port -> p
forall l n. Box l n -> l
label) [Box p Port]
left [Either p p] -> [Either p p] -> [Either p p]
forall a. [a] -> [a] -> [a]
++ (Box p Port -> Either p p) -> [Box p Port] -> [Either p p]
forall a b. (a -> b) -> [a] -> [b]
map (p -> Either p p
forall a b. b -> Either a b
Right (p -> Either p p) -> (Box p Port -> p) -> Box p Port -> Either p p
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Box p Port -> p
forall l n. Box l n -> l
label) (IntMap (Box p Port) -> [Box p Port]
forall a. IntMap a -> [a]
IM.elems IntMap (Box p Port)
rightOnly)
    labels <- maybeToList (solve sharedLabels sourceLabels)
    shared <- IM.fromList <$> traverse (share canIdentify) boxPairs
    let sharedPorts = (Box p AlignedPort -> [AlignedPort])
-> [Box p AlignedPort] -> [AlignedPort]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap (\Box p AlignedPort
b -> Box p AlignedPort -> [AlignedPort]
forall l n. Box l n -> [n]
inputs Box p AlignedPort
b [AlignedPort] -> [AlignedPort] -> [AlignedPort]
forall a. [a] -> [a] -> [a]
++ Box p AlignedPort -> [AlignedPort]
forall l n. Box l n -> [n]
outputs Box p AlignedPort
b) (IntMap (Box p AlignedPort) -> [Box p AlignedPort]
forall a. IntMap a -> [a]
IM.elems IntMap (Box p AlignedPort)
shared)
        wirePairs = [(Int, Int)] -> [(Int, Int)]
forall a. Ord a => [a] -> [a]
nubOrd [(Int
r, Int
l) | Identified Int
l Int
r <- [AlignedPort]
sharedPorts]
        rightToLeft = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int, Int)]
wirePairs
        leftToRight = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int
l, Int
r) | (Int
r, Int
l) <- [(Int, Int)]
wirePairs]
        solo = [Int
n | Unaligned (Node Int
n) <- [AlignedPort]
sharedPorts]
        -- A solo numbered port occurs inside the other rule's capture.
        -- Any numbered node identified with it must survive that rule.
        preservesCaptured Int
n =
          Bool -> (Int -> Bool) -> Maybe Int -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Int -> IntSet -> Bool
`IS.member` IntSet
leftKept) (Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
n IntMap Int
rightToLeft)
            Bool -> Bool -> Bool
&& Bool -> (Int -> Bool) -> Maybe Int -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Int -> IntSet -> Bool
`IS.member` IntSet
rightKept) (Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
n IntMap Int
leftToRight)
    guard (IM.size rightToLeft == length wirePairs && IM.size leftToRight == length wirePairs)
    guard (all preservesCaptured solo)
    extraPairs <-
      partialInjections
        [ (r, IS.toList (IS.difference leftKept (IM.keysSet leftToRight)))
        | r <- IS.toList (IS.difference rightKept (IM.keysSet rightToLeft))
        ]
    let wires = IntMap Int -> IntMap Int -> IntMap Int
forall a. IntMap a -> IntMap a -> IntMap a
IM.union IntMap Int
rightToLeft ([(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int, Int)]
extraPairs)
        identical =
          [(Int, Int)]
boxPairs [(Int, Int)] -> [(Int, Int)] -> Bool
forall a. Eq a => a -> a -> Bool
== [(Int
i, Int
i) | Int
i <- IntMap (Box p Port) -> [Int]
forall a. IntMap a -> [Int]
IM.keys IntMap (Box p Port)
leftBoxes]
            Bool -> Bool -> Bool
&& [Int] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [Int]
solo
            Bool -> Bool -> Bool
&& ((Int, Int) -> Bool) -> [(Int, Int)] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\(Int
r, Int
l) -> Int
r Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [SomeSort ()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort ()]
ls Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
l) (IntMap Int -> [(Int, Int)]
forall a. IntMap a -> [(Int, a)]
IM.toList IntMap Int
wires)
    guard (not sameRule || not identical)
    guard
      ( not (null boxPairs)
          || sharesMergedWires (IS.fromList (IM.elems wires)) (IM.keysSet wires)
      )
    let canonical Int
n = Int -> Int -> IntMap Int -> Int
forall a. a -> Int -> IntMap a -> a
IM.findWithDefault Int
n Int
n IntMap Int
wires
        retained = [(Int
i, SomeSort ()
s) | (Int
i, SomeSort ()
s) <- [Int] -> [SomeSort ()] -> [(Int, SomeSort ())]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] ([SomeSort ()]
ls [SomeSort ()] -> [SomeSort ()] -> [SomeSort ()]
forall a. [a] -> [a] -> [a]
++ [SomeSort ()]
rs), Int -> IntMap Int -> Bool
forall a. Int -> IntMap a -> Bool
IM.notMember Int
i IntMap Int
wires]
        indices = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip (((Int, SomeSort ()) -> Int) -> [(Int, SomeSort ())] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, SomeSort ()) -> Int
forall a b. (a, b) -> a
fst [(Int, SomeSort ())]
retained) [Int
0 ..])
        deleted = [Int] -> IntSet
IS.fromList [Int -> Int
canonical Int
i | Int
i <- [Int
0 .. [SomeSort ()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort ()]
ls Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [SomeSort ()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort ()]
rs Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1], Int -> IntSet -> Bool
IS.notMember Int
i IntSet
kept]
        boundary = [Int
j | (Int
i, Int
j) <- IntMap Int -> [(Int, Int)]
forall a. IntMap a -> [(Int, a)]
IM.toList IntMap Int
indices, Int -> IntSet -> Bool
IS.notMember Int
i IntSet
deleted]
        kept = IntSet -> IntSet -> IntSet
IS.union IntSet
leftKept IntSet
rightKept
        resolve (Identified Int
l Int
_) = Int -> Port
Node (IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
l)
        resolve (Unaligned (Node Int
n)) = Int -> Port
Node (IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int -> Int
canonical Int
n)
        resolve (Unaligned Port
p) = Port
p
        boxes =
          IntMap (Box p AlignedPort) -> [Box p AlignedPort]
forall a. IntMap a -> [a]
IM.elems (IntMap (Box p AlignedPort)
-> IntMap (Box p AlignedPort) -> IntMap (Box p AlignedPort)
forall a. IntMap a -> IntMap a -> IntMap a
IM.union IntMap (Box p AlignedPort)
shared ((Box p Port -> Box p AlignedPort)
-> IntMap (Box p Port) -> IntMap (Box p AlignedPort)
forall a b. (a -> b) -> IntMap a -> IntMap b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap (OverlapReplacement -> Box p Port -> Box p AlignedPort
forall {l}. OverlapReplacement -> Box l Port -> Box l AlignedPort
unsharedBox OverlapReplacement
leftReplacement) IntMap (Box p Port)
leftOnly))
            [Box p AlignedPort] -> [Box p AlignedPort] -> [Box p AlignedPort]
forall a. [a] -> [a] -> [a]
++ IntMap (Box p AlignedPort) -> [Box p AlignedPort]
forall a. IntMap a -> [a]
IM.elems ((Box p Port -> Box p AlignedPort)
-> IntMap (Box p Port) -> IntMap (Box p AlignedPort)
forall a b. (a -> b) -> IntMap a -> IntMap b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap (OverlapReplacement -> Box p Port -> Box p AlignedPort
forall {l}. OverlapReplacement -> Box l Port -> Box l AlignedPort
unsharedBox OverlapReplacement
rightReplacement) IntMap (Box p Port)
rightOnly)
        source = [SomeSort ()] -> [Int] -> [Box l Port] -> PortGraph () l
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph (((Int, SomeSort ()) -> SomeSort ())
-> [(Int, SomeSort ())] -> [SomeSort ()]
forall a b. (a -> b) -> [a] -> [b]
map (Int, SomeSort ()) -> SomeSort ()
forall a b. (a, b) -> b
snd [(Int, SomeSort ())]
retained) [Int]
boundary [l -> [Port] -> [Port] -> Box l Port
forall l n. l -> [n] -> [n] -> Box l n
Box l
l ((AlignedPort -> Port) -> [AlignedPort] -> [Port]
forall a b. (a -> b) -> [a] -> [b]
map AlignedPort -> Port
resolve [AlignedPort]
i) ((AlignedPort -> Port) -> [AlignedPort] -> [Port]
forall a b. (a -> b) -> [a] -> [b]
map AlignedPort -> Port
resolve [AlignedPort]
o) | (l
l, Box p
_ [AlignedPort]
i [AlignedPort]
o) <- [l] -> [Box p AlignedPort] -> [(l, Box p AlignedPort)]
forall a b. [a] -> [b] -> [(a, b)]
zip [l]
labels [Box p AlignedPort]
boxes]
    unless bothFixed do
      host <- either (const []) pure (symbolicPortGraph source)
      let leftSelection = IntMap (Box p Port) -> IntSet
forall a. IntMap a -> IntSet
IM.keysSet IntMap (Box p Port)
leftBoxes
          rightSelection = [Int] -> IntSet
IS.fromList (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> a
fst [(Int, Int)]
boxPairs [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [[Box p Port] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Box p Port]
left .. [Box p AlignedPort] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Box p AlignedPort]
boxes Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1])
          matchesUsing IntSet
selection CompiledRules () () l
compiled =
            [ Prepared () l
prepared
            | (Int
_, prepared :: Prepared () l
prepared@(Graph () (LabelTest l)
_, Graph () l
_, (IntMap Int
_, IntSet
selected))) <- Int
-> CompiledRules () () l -> Graph () l -> [(Int, Prepared () l)]
forall l key.
Eq l =>
Int
-> CompiledRules key () l -> Graph () l -> [(Int, Prepared () l)]
symbolicMatches ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
boundary) CompiledRules () () l
compiled Graph () l
host
            , IntSet
selected IntSet -> IntSet -> Bool
forall a. Eq a => a -> a -> Bool
== IntSet
selection
            ]
          leftMatches = IntSet -> CompiledRules () () l -> [Prepared () l]
matchesUsing IntSet
leftSelection CompiledRules () () l
leftCompiled
          rightMatches = IntSet -> CompiledRules () () l -> [Prepared () l]
matchesUsing IntSet
rightSelection CompiledRules () () l
rightCompiled
          sharedNodes = [Int] -> IntSet
IS.fromList [IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
l | Int
l <- IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
wires]
          mergesShared (Graph [SomeSort ()]
_ [Int]
lhsInterface [Int]
_ [Box (LabelTest l) Int]
_, Graph [SomeSort ()]
_ [Int]
rhsInterface [Int]
_ [Box l Int]
_, (IntMap Int
images, IntSet
_)) =
            [(Int, Int)] -> IntSet -> Bool
identifiesNodes ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip ((Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (IntMap Int
images IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) [Int]
lhsInterface) [Int]
rhsInterface) IntSet
sharedNodes
      if sameRule && leftSelection == rightSelection
        then guard (length leftMatches >= 2)
        else guard (not (null leftMatches) && not (null rightMatches))
      guard (not (null boxPairs) || any mergesShared leftMatches || any mergesShared rightMatches)
    pure source
    where
      bothFixed :: Bool
bothFixed = case (OverlapReplacement
leftReplacement, OverlapReplacement
rightReplacement) of
        (FixedInterface [Int]
_, FixedInterface [Int]
_) -> Bool
True
        (OverlapReplacement, OverlapReplacement)
_ -> Bool
False
      leftKept :: IntSet
leftKept = [Int] -> IntSet
IS.fromList [Int]
li
      rightInterface :: [Int]
rightInterface = (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [SomeSort ()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort ()]
ls) [Int]
ri
      rightKept :: IntSet
rightKept = [Int] -> IntSet
IS.fromList [Int]
rightInterface
      wireConflictPossible :: Bool
wireConflictPossible = IntSet -> IntSet -> Bool
sharesMergedWires IntSet
leftKept IntSet
rightKept
      sharesMergedWires :: IntSet -> IntSet -> Bool
sharesMergedWires IntSet
leftShared IntSet
rightShared
        | IntSet -> Int
IS.size IntSet
leftShared Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
2 Bool -> Bool -> Bool
|| IntSet -> Int
IS.size IntSet
rightShared Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
2 = Bool
False
        | Bool
otherwise = case (OverlapReplacement -> Maybe [Int]
wireOnlyInterface OverlapReplacement
leftReplacement, OverlapReplacement -> Maybe [Int]
wireOnlyInterface OverlapReplacement
rightReplacement) of
            (Just [Int]
lt, Just [Int]
rt) ->
              [(Int, Int)] -> IntSet -> Bool
identifiesNodes ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
li [Int]
lt) IntSet
leftShared Bool -> Bool -> Bool
|| [(Int, Int)] -> IntSet -> Bool
identifiesNodes ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
rightInterface [Int]
rt) IntSet
rightShared
            (Maybe [Int], Maybe [Int])
_ -> Bool
False
      wireOnlyInterface :: OverlapReplacement -> Maybe [Int]
wireOnlyInterface (FixedInterface [Int]
targets) = [Int] -> Maybe [Int]
forall a. a -> Maybe a
Just [Int]
targets
      wireOnlyInterface (ComputedInterface Maybe [Int]
targets) = Maybe [Int]
targets
      unsharedBox :: OverlapReplacement -> Box l Port -> Box l AlignedPort
unsharedBox (FixedInterface [Int]
_) Box l Port
box = (Port -> AlignedPort) -> Box l Port -> Box l AlignedPort
forall a b. (a -> b) -> Box l a -> Box l b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap Port -> AlignedPort
Unaligned Box l Port
box
      unsharedBox (ComputedInterface Maybe [Int]
_) (Box l
l [Port]
ins [Port]
outs) =
        let known :: [Port] -> [AlignedPort]
known = (Port -> AlignedPort) -> [Port] -> [AlignedPort]
forall a b. (a -> b) -> [a] -> [b]
map Port -> AlignedPort
Unaligned ([Port] -> [AlignedPort])
-> ([Port] -> [Port]) -> [Port] -> [AlignedPort]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Port -> Bool) -> [Port] -> [Port]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Port -> Bool) -> Port -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Port -> Bool
isCapture)
        in l -> [AlignedPort] -> [AlignedPort] -> Box l AlignedPort
forall l n. l -> [n] -> [n] -> Box l n
Box l
l ([Port] -> [AlignedPort]
known [Port]
ins) ([Port] -> [AlignedPort]
known [Port]
outs)
      leftBoxes :: IntMap (Box p Port)
leftBoxes = (Port -> Port) -> [Box p Port] -> IntMap (Box p Port)
forall {f :: Type -> Type} {a} {b}.
Functor f =>
(a -> b) -> [f a] -> IntMap (f b)
indexed (String -> Int -> Port -> Port
rename String
"left:" Int
0) [Box p Port]
left
      rightBoxes :: IntMap (Box p Port)
rightBoxes = (Port -> Port) -> [Box p Port] -> IntMap (Box p Port)
forall {f :: Type -> Type} {a} {b}.
Functor f =>
(a -> b) -> [f a] -> IntMap (f b)
indexed (String -> Int -> Port -> Port
rename String
"right:" ([SomeSort ()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort ()]
ls)) [Box p Port]
right
      indexed :: (a -> b) -> [f a] -> IntMap (f b)
indexed a -> b
f = [(Int, f b)] -> IntMap (f b)
forall a. [(Int, a)] -> IntMap a
IM.fromDistinctAscList ([(Int, f b)] -> IntMap (f b))
-> ([f a] -> [(Int, f b)]) -> [f a] -> IntMap (f b)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Int] -> [f b] -> [(Int, f b)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] ([f b] -> [(Int, f b)])
-> ([f a] -> [f b]) -> [f a] -> [(Int, f b)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (f a -> f b) -> [f a] -> [f b]
forall a b. (a -> b) -> [a] -> [b]
map ((a -> b) -> f a -> f b
forall a b. (a -> b) -> f a -> f b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> b
f)
      candidates :: [(Int, Int)]
candidates = [(Int
i, Int
j) | (Int
i, Box p Port
l) <- IntMap (Box p Port) -> [(Int, Box p Port)]
forall a. IntMap a -> [(Int, a)]
IM.toList IntMap (Box p Port)
leftBoxes, (Int
j, Box p Port
r) <- IntMap (Box p Port) -> [(Int, Box p Port)]
forall a. IntMap a -> [(Int, a)]
IM.toList IntMap (Box p Port)
rightBoxes, p -> p -> Bool
compatible (Box p Port -> p
forall l n. Box l n -> l
label Box p Port
l) (Box p Port -> p
forall l n. Box l n -> l
label Box p Port
r)]
      share :: (Int -> Int -> Bool) -> (Int, Int) -> [(Int, Box p AlignedPort)]
share Int -> Int -> Bool
canIdentify (Int
i, Int
j) = do
        let l :: Box p Port
l = IntMap (Box p Port)
leftBoxes IntMap (Box p Port) -> Int -> Box p Port
forall a. IntMap a -> Int -> a
IM.! Int
i
            r :: Box p Port
r = IntMap (Box p Port)
rightBoxes IntMap (Box p Port) -> Int -> Box p Port
forall a. IntMap a -> Int -> a
IM.! Int
j
            prefix :: String
prefix = String
"shared:" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
i String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
":"
        ins <- Bool
-> (Int -> Int -> Bool)
-> String
-> [Port]
-> [Port]
-> [[AlignedPort]]
alignPortLists Bool
bothFixed Int -> Int -> Bool
canIdentify (String
prefix String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"inputs:") (Box p Port -> [Port]
forall l n. Box l n -> [n]
inputs Box p Port
l) (Box p Port -> [Port]
forall l n. Box l n -> [n]
inputs Box p Port
r)
        outs <- alignPortLists bothFixed canIdentify (prefix ++ "outputs:") (outputs l) (outputs r)
        pure (i, Box (label l) ins outs)
      rename :: String -> Int -> Port -> Port
rename String
_ Int
offset (Node Int
n) = Int -> Port
Node (Int
offset Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
n)
      rename String
prefix Int
_ (Capture String
name) = String -> Port
Capture (String
prefix String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name)
      rename String
prefix Int
_ (Element String
name Int
i) = String -> Int -> Port
Element (String
prefix String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
name) Int
i

data AlignedPort = Unaligned Port | Identified Int Int

-- A side can take a numbered port from the other side only while its current
-- gap is open. Taking both ports identifies their nodes in the overlap.
alignPortLists :: Bool -> (Int -> Int -> Bool) -> String -> [Port] -> [Port] -> [[AlignedPort]]
alignPortLists :: Bool
-> (Int -> Int -> Bool)
-> String
-> [Port]
-> [Port]
-> [[AlignedPort]]
alignPortLists Bool
keepSharedGaps Int -> Int -> Bool
canIdentify String
prefix = Int -> [Port] -> [Port] -> [[AlignedPort]]
go (Int
0 :: Int)
  where
    go :: Int -> [Port] -> [Port] -> [[AlignedPort]]
go Int
i [Port]
left [Port]
right = ([AlignedPort] -> [AlignedPort])
-> [[AlignedPort]] -> [[AlignedPort]]
forall a b. (a -> b) -> [a] -> [b]
map ([AlignedPort]
common [AlignedPort] -> [AlignedPort] -> [AlignedPort]
forall a. [a] -> [a] -> [a]
++) [[AlignedPort]]
continuations
      where
        (Bool
leftOpen, [Port]
ls) = [Port] -> (Bool, [Port])
gap [Port]
left
        (Bool
rightOpen, [Port]
rs) = [Port] -> (Bool, [Port])
gap [Port]
right
        common :: [AlignedPort]
common = [Port -> AlignedPort
Unaligned (String -> Port
Capture (String
prefix String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
i)) | Bool
keepSharedGaps Bool -> Bool -> Bool
&& Bool
leftOpen Bool -> Bool -> Bool
&& Bool
rightOpen]
        continuations :: [[AlignedPort]]
continuations = case ([Port]
ls, [Port]
rs) of
          ([], []) -> [[]]
          ([Port], [Port])
_ ->
            [Port -> AlignedPort
Unaligned Port
p AlignedPort -> [AlignedPort] -> [AlignedPort]
forall a. a -> [a] -> [a]
: [AlignedPort]
rest | Bool
rightOpen, Port
p : [Port]
ps <- [[Port]
ls], [AlignedPort]
rest <- Int -> [Port] -> [Port] -> [[AlignedPort]]
go (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) [Port]
ps [Port]
right]
              [[AlignedPort]] -> [[AlignedPort]] -> [[AlignedPort]]
forall a. [a] -> [a] -> [a]
++ [Port -> AlignedPort
Unaligned Port
p AlignedPort -> [AlignedPort] -> [AlignedPort]
forall a. a -> [a] -> [a]
: [AlignedPort]
rest | Bool
leftOpen, Port
p : [Port]
ps <- [[Port]
rs], [AlignedPort]
rest <- Int -> [Port] -> [Port] -> [[AlignedPort]]
go (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) [Port]
left [Port]
ps]
              [[AlignedPort]] -> [[AlignedPort]] -> [[AlignedPort]]
forall a. [a] -> [a] -> [a]
++ [Int -> Int -> AlignedPort
Identified Int
l Int
r AlignedPort -> [AlignedPort] -> [AlignedPort]
forall a. a -> [a] -> [a]
: [AlignedPort]
rest | Node Int
l : [Port]
ps <- [[Port]
ls], Node Int
r : [Port]
qs <- [[Port]
rs], Int -> Int -> Bool
canIdentify Int
l Int
r, [AlignedPort]
rest <- Int -> [Port] -> [Port] -> [[AlignedPort]]
go (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) [Port]
ps [Port]
qs]
    gap :: [Port] -> (Bool, [Port])
gap (Capture String
_ : [Port]
ps) = (Bool
True, [Port]
ps)
    gap [Port]
ps = (Bool
False, [Port]
ps)

isCapture :: Port -> Bool
isCapture :: Port -> Bool
isCapture Capture{} = Bool
True
isCapture Port
_ = Bool
False

literalPortPattern :: Rule s l -> Maybe (PortGraph s l)
literalPortPattern :: forall s l. Rule s l -> Maybe (PortGraph s l)
literalPortPattern (PortRule (PortGraph [SomeSort s]
sorts [Int]
boundary [Box (LabelTest l) Port]
lhs) PortTemplate{}) =
  [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph [SomeSort s]
sorts [Int]
boundary ([Box l Port] -> PortGraph s l)
-> Maybe [Box l Port] -> Maybe (PortGraph s l)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Box (LabelTest l) Port -> Maybe (Box l Port))
-> [Box (LabelTest l) Port] -> Maybe [Box l Port]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Box (LabelTest l) Port -> Maybe (Box l Port)
forall {l} {n}. Box (LabelTest l) n -> Maybe (Box l n)
literalBox [Box (LabelTest l) Port]
lhs
  where
    literalBox :: Box (LabelTest l) n -> Maybe (Box l n)
literalBox (Box (ExactLabel l
l) [n]
i [n]
o) = Box l n -> Maybe (Box l n)
forall a. a -> Maybe a
Just (l -> [n] -> [n] -> Box l n
forall l n. l -> [n] -> [n] -> Box l n
Box l
l [n]
i [n]
o)
    literalBox (Box ConstructorLabel{} [n]
_ [n]
_) = Maybe (Box l n)
forall a. Maybe a
Nothing
literalPortPattern Rule s l
_ = Maybe (PortGraph s l)
forall a. Maybe a
Nothing

parameterPortPattern :: Rule s (f a) -> Maybe (PortGraph s (f (Parameter a)))
parameterPortPattern :: forall s (f :: Type -> Type) a.
Rule s (f a) -> Maybe (PortGraph s (f (Parameter a)))
parameterPortPattern (PortRule (PortGraph [SomeSort s]
sorts [Int]
boundary [Box (LabelTest (f a)) Port]
lhs) PortReplacement s (f a)
replacement) = do
  parameters <- case PortReplacement s (f a)
replacement of
    ParameterPorts [f (Parameter a)]
ps PortGraph s (f (Parameter a))
_ -> [f (Parameter a)] -> Maybe [f (Parameter a)]
forall a. a -> Maybe a
Just [f (Parameter a)]
[f (Parameter a)]
ps
    ComputedPorts [f (Parameter a)]
ps Map String Int -> Maybe (PortGraph s (f (Parameter a)))
_ -> [f (Parameter a)] -> Maybe [f (Parameter a)]
forall a. a -> Maybe a
Just [f (Parameter a)]
[f (Parameter a)]
ps
    PortTemplate{} -> Maybe [f (Parameter a)]
forall a. Maybe a
Nothing
  pure (PortGraph sorts boundary [Box l i o | (l, Box _ i o) <- zip parameters lhs])
parameterPortPattern Rule s (f a)
_ = Maybe (PortGraph s (f (Parameter a)))
forall a. Maybe a
Nothing

data ScopedParameter a = ScopedVariable (Either String String) | ScopedLiteral a

solvePortLabels
  :: (Traversable f, Eq a)
  => (Int -> a)
  -> [(f (Parameter a), f (Parameter a))]
  -> [Either (f (Parameter a)) (f (Parameter a))]
  -> Maybe [f a]
solvePortLabels :: forall (f :: Type -> Type) a.
(Traversable f, Eq a) =>
(Int -> a)
-> [(f (Parameter a), f (Parameter a))]
-> [Either (f (Parameter a)) (f (Parameter a))]
-> Maybe [f a]
solvePortLabels Int -> a
fresh [(f (Parameter a), f (Parameter a))]
shared [Either (f (Parameter a)) (f (Parameter a))]
sources = do
  boxes <- (Either (f (Parameter a)) (f (Parameter a))
 -> Maybe (f (ScopedParameter a)))
-> [Either (f (Parameter a)) (f (Parameter a))]
-> Maybe [f (ScopedParameter a)]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ((f (Parameter a) -> Maybe (f (ScopedParameter a)))
-> (f (Parameter a) -> Maybe (f (ScopedParameter a)))
-> Either (f (Parameter a)) (f (Parameter a))
-> Maybe (f (ScopedParameter a))
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ((Parameter a -> Maybe (ScopedParameter a))
-> f (Parameter a) -> Maybe (f (ScopedParameter a))
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> f a -> f (f b)
traverse ((String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
forall {a}.
(String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
scope String -> Either String String
forall a b. a -> Either a b
Left)) ((Parameter a -> Maybe (ScopedParameter a))
-> f (Parameter a) -> Maybe (f (ScopedParameter a))
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> f a -> f (f b)
traverse ((String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
forall {a}.
(String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
scope String -> Either String String
forall a b. b -> Either a b
Right))) [Either (f (Parameter a)) (f (Parameter a))]
sources
  equations <- concat <$> traverse fields shared
  let variables =
        [Either String String] -> [Either String String]
forall a. Ord a => [a] -> [a]
nubOrd [Either String String
n | ScopedVariable Either String String
n <- (f (ScopedParameter a) -> [ScopedParameter a])
-> [f (ScopedParameter a)] -> [ScopedParameter a]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap f (ScopedParameter a) -> [ScopedParameter a]
forall a. f a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList [f (ScopedParameter a)]
boxes [ScopedParameter a] -> [ScopedParameter a] -> [ScopedParameter a]
forall a. [a] -> [a] -> [a]
++ [[ScopedParameter a]] -> [ScopedParameter a]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat [[ScopedParameter a
l, ScopedParameter a
r] | (ScopedParameter a
l, ScopedParameter a
r) <- [(ScopedParameter a, ScopedParameter a)]
equations]]
      ids = [(Either String String, Int)] -> Map (Either String String) Int
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList ([Either String String] -> [Int] -> [(Either String String, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Either String String]
variables [Int
0 ..])
      root = [(Int, Int)] -> Int -> Int
forall a. Enum a => [(a, a)] -> a -> a
unionFind [(Map (Either String String) Int
ids Map (Either String String) Int -> Either String String -> Int
forall k a. Ord k => Map k a -> k -> a
M.! Either String String
l, Map (Either String String) Int
ids Map (Either String String) Int -> Either String String -> Int
forall k a. Ord k => Map k a -> k -> a
M.! Either String String
r) | (ScopedVariable Either String String
l, ScopedVariable Either String String
r) <- [(ScopedParameter a, ScopedParameter a)]
equations]
      representative Either String String
n = Int -> Int
root (Map (Either String String) Int
ids Map (Either String String) Int -> Either String String -> Int
forall k a. Ord k => Map k a -> k -> a
M.! Either String String
n)
      bind IntMap a
acc (ScopedLiteral a
l, ScopedLiteral a
r) = IntMap a
acc IntMap a -> Maybe () -> Maybe (IntMap a)
forall a b. a -> Maybe b -> Maybe a
forall (f :: Type -> Type) a b. Functor f => a -> f b -> f a
<$ Bool -> Maybe ()
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard (a
l a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
r)
      bind IntMap a
acc (ScopedVariable Either String String
n, ScopedLiteral a
a) = IntMap a -> Int -> a -> Maybe (IntMap a)
forall {a}. Eq a => IntMap a -> Int -> a -> Maybe (IntMap a)
assign IntMap a
acc (Either String String -> Int
representative Either String String
n) a
a
      bind IntMap a
acc (ScopedLiteral a
a, ScopedVariable Either String String
n) = IntMap a -> Int -> a -> Maybe (IntMap a)
forall {a}. Eq a => IntMap a -> Int -> a -> Maybe (IntMap a)
assign IntMap a
acc (Either String String -> Int
representative Either String String
n) a
a
      bind IntMap a
acc (ScopedVariable Either String String
_, ScopedVariable Either String String
_) = IntMap a -> Maybe (IntMap a)
forall a. a -> Maybe a
Just IntMap a
acc
  literals <- foldM bind IM.empty equations
  let instantiate (ScopedLiteral a
a) = a
a
      instantiate (ScopedVariable Either String String
n) =
        let i :: Int
i = Either String String -> Int
representative Either String String
n in a -> Int -> IntMap a -> a
forall a. a -> Int -> IntMap a -> a
IM.findWithDefault (Int -> a
fresh Int
i) Int
i IntMap a
literals
  pure (map (fmap instantiate) boxes)
  where
    scope :: (String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
scope String -> Either String String
_ (Literal a
a) = ScopedParameter a -> Maybe (ScopedParameter a)
forall a. a -> Maybe a
Just (a -> ScopedParameter a
forall a. a -> ScopedParameter a
ScopedLiteral a
a)
    scope String -> Either String String
side (Variable String
n) = ScopedParameter a -> Maybe (ScopedParameter a)
forall a. a -> Maybe a
Just (Either String String -> ScopedParameter a
forall a. Either String String -> ScopedParameter a
ScopedVariable (String -> Either String String
side String
n))
    scope String -> Either String String
_ Parameter a
_ = Maybe (ScopedParameter a)
forall a. Maybe a
Nothing
    fields :: (t (Parameter a), t (Parameter a))
-> Maybe [(ScopedParameter a, ScopedParameter a)]
fields (t (Parameter a)
l, t (Parameter a)
r) = [ScopedParameter a]
-> [ScopedParameter a] -> [(ScopedParameter a, ScopedParameter a)]
forall a b. [a] -> [b] -> [(a, b)]
zip ([ScopedParameter a]
 -> [ScopedParameter a] -> [(ScopedParameter a, ScopedParameter a)])
-> Maybe [ScopedParameter a]
-> Maybe
     ([ScopedParameter a] -> [(ScopedParameter a, ScopedParameter a)])
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Parameter a -> Maybe (ScopedParameter a))
-> [Parameter a] -> Maybe [ScopedParameter a]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ((String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
forall {a}.
(String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
scope String -> Either String String
forall a b. a -> Either a b
Left) (t (Parameter a) -> [Parameter a]
forall a. t a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList t (Parameter a)
l) Maybe
  ([ScopedParameter a] -> [(ScopedParameter a, ScopedParameter a)])
-> Maybe [ScopedParameter a]
-> Maybe [(ScopedParameter a, ScopedParameter a)]
forall a b. Maybe (a -> b) -> Maybe a -> Maybe b
forall (f :: Type -> Type) a b.
Applicative f =>
f (a -> b) -> f a -> f b
<*> (Parameter a -> Maybe (ScopedParameter a))
-> [Parameter a] -> Maybe [ScopedParameter a]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ((String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
forall {a}.
(String -> Either String String)
-> Parameter a -> Maybe (ScopedParameter a)
scope String -> Either String String
forall a b. b -> Either a b
Right) (t (Parameter a) -> [Parameter a]
forall a. t a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList t (Parameter a)
r)
    assign :: IntMap a -> Int -> a -> Maybe (IntMap a)
assign IntMap a
literals Int
i a
a = case Int -> IntMap a -> Maybe a
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
i IntMap a
literals of
      Maybe a
Nothing -> IntMap a -> Maybe (IntMap a)
forall a. a -> Maybe a
Just (Int -> a -> IntMap a -> IntMap a
forall a. Int -> a -> IntMap a -> IntMap a
IM.insert Int
i a
a IntMap a
literals)
      Just a
b -> IntMap a
literals IntMap a -> Maybe () -> Maybe (IntMap a)
forall a b. a -> Maybe b -> Maybe a
forall (f :: Type -> Type) a b. Functor f => a -> f b -> f a
<$ Bool -> Maybe ()
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard (a
a a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
b)

overlapReplacement :: Rule s l -> Maybe OverlapReplacement
overlapReplacement :: forall s l. Rule s l -> Maybe OverlapReplacement
overlapReplacement (PortRule PortGraph s (LabelTest l)
lhs PortReplacement s l
replacement) = case PortReplacement s l
replacement of
  PortTemplate PortGraph s l
rhs -> [Int] -> OverlapReplacement
FixedInterface ([Int] -> OverlapReplacement)
-> Maybe [Int] -> Maybe OverlapReplacement
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> PortGraph s l -> Maybe [Int]
forall {f :: Type -> Type} {s} {l}.
Alternative f =>
PortGraph s l -> f [Int]
interfaceWithoutElements PortGraph s l
rhs
  ParameterPorts [f (Parameter a)]
_ PortGraph s (f (Parameter a))
rhs -> [Int] -> OverlapReplacement
FixedInterface ([Int] -> OverlapReplacement)
-> Maybe [Int] -> Maybe OverlapReplacement
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> PortGraph s (f (Parameter a)) -> Maybe [Int]
forall {f :: Type -> Type} {s} {l}.
Alternative f =>
PortGraph s l -> f [Int]
interfaceWithoutElements PortGraph s (f (Parameter a))
rhs
  ComputedPorts [f (Parameter a)]
_ Map String Int -> Maybe (PortGraph s (f (Parameter a)))
build ->
    -- An indexed element cannot exist in an empty capture.
    let emptyLengths :: Map String Int
emptyLengths = [(String, Int)] -> Map String Int
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(String
name, Int
0) | String
name <- PortGraph s (LabelTest l) -> [String]
forall s l. PortGraph s l -> [String]
portSequenceNames PortGraph s (LabelTest l)
lhs]
    in OverlapReplacement -> Maybe OverlapReplacement
forall a. a -> Maybe a
Just (Maybe [Int] -> OverlapReplacement
ComputedInterface (Map String Int -> Maybe (PortGraph s (f (Parameter a)))
build Map String Int
emptyLengths Maybe (PortGraph s (f (Parameter a)))
-> (PortGraph s (f (Parameter a)) -> Maybe [Int]) -> Maybe [Int]
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: Type -> Type) a b. Monad m => m a -> (a -> m b) -> m b
>>= PortGraph s (f (Parameter a)) -> Maybe [Int]
forall {f :: Type -> Type} {s} {l}.
Alternative f =>
PortGraph s l -> f [Int]
interfaceWithoutElements))
  where
    interfaceWithoutElements :: PortGraph s l -> f [Int]
interfaceWithoutElements (PortGraph [SomeSort s]
_ [Int]
boundary [Box l Port]
rhs) =
      [Int]
boundary [Int] -> f () -> f [Int]
forall a b. a -> f b -> f a
forall (f :: Type -> Type) a b. Functor f => a -> f b -> f a
<$ Bool -> f ()
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard ((Port -> Bool) -> [Port] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all Port -> Bool
supported [Port
p | Box l Port
box <- [Box l Port]
rhs, Port
p <- Box l Port -> [Port]
forall l n. Box l n -> [n]
inputs Box l Port
box [Port] -> [Port] -> [Port]
forall a. [a] -> [a] -> [a]
++ Box l Port -> [Port]
forall l n. Box l n -> [n]
outputs Box l Port
box])
    supported :: Port -> Bool
supported Element{} = Bool
False
    supported Port
_ = Bool
True
overlapReplacement Rule s l
_ = Maybe OverlapReplacement
forall a. Maybe a
Nothing

symbolicPortGraph :: PortGraph () l -> Either String (Graph () l)
symbolicPortGraph :: forall l. PortGraph () l -> Either String (Graph () l)
symbolicPortGraph template :: PortGraph () l
template@(PortGraph [SomeSort ()]
sorts [Int]
boundary [Box l Port]
boxes) = do
  PortGraph () l -> Either String ()
forall s l. PortGraph s l -> Either String ()
checkPortLeft PortGraph () l
template
  let names :: [String]
names = PortGraph () l -> [String]
forall s l. PortGraph s l -> [String]
portSequenceNames PortGraph () l
template
      markers :: [Int]
markers = Int -> [Int] -> [Int]
forall a. Int -> [a] -> [a]
take ([String] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [String]
names) [[SomeSort ()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort ()]
sorts ..]
      positions :: Map String Int
positions = [(String, Int)] -> Map String Int
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList ([String] -> [Int] -> [(String, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [String]
names [Int]
markers)
      resolve :: Port -> Either String Int
resolve (Node Int
i) = Int -> Either String Int
forall a b. b -> Either a b
Right Int
i
      resolve (Capture String
name) = Int -> Either String Int
forall a b. b -> Either a b
Right (Map String Int
positions Map String Int -> String -> Int
forall k a. Ord k => Map k a -> k -> a
M.! String
name)
      resolve Element{} = String -> Either String Int
forall a b. a -> Either a b
Left String
"checkPortTemplate: Element in the source"
      expand :: Box l Port -> Either String (Box l Int)
expand (Box l
l [Port]
ins [Port]
outs) = l -> [Int] -> [Int] -> Box l Int
forall l n. l -> [n] -> [n] -> Box l n
Box l
l ([Int] -> [Int] -> Box l Int)
-> Either String [Int] -> Either String ([Int] -> Box l Int)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Port -> Either String Int) -> [Port] -> Either String [Int]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Port -> Either String Int
resolve [Port]
ins Either String ([Int] -> Box l Int)
-> Either String [Int] -> Either String (Box l Int)
forall a b.
Either String (a -> b) -> Either String a -> Either String b
forall (f :: Type -> Type) a b.
Applicative f =>
f (a -> b) -> f a -> f b
<*> (Port -> Either String Int) -> [Port] -> Either String [Int]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Port -> Either String Int
resolve [Port]
outs
  [SomeSort ()] -> [Int] -> [Int] -> [Box l Int] -> Graph () l
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph ([SomeSort ()]
sorts [SomeSort ()] -> [SomeSort ()] -> [SomeSort ()]
forall a. [a] -> [a] -> [a]
++ Int -> SomeSort () -> [SomeSort ()]
forall a. Int -> a -> [a]
replicate ([String] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [String]
names) (forall {k} {c :: OB k} (x :: k). c x => SomeOf c
forall (x :: ()). SortOb x => SomeSort ()
Some @'())) ([Int]
boundary [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
markers) [] ([Box l Int] -> Graph () l)
-> Either String [Box l Int] -> Either String (Graph () l)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Box l Port -> Either String (Box l Int))
-> [Box l Port] -> Either String [Box l Int]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Box l Port -> Either String (Box l Int)
expand [Box l Port]
boxes

portSequenceNames :: PortGraph s l -> [String]
portSequenceNames :: forall s l. PortGraph s l -> [String]
portSequenceNames (PortGraph [SomeSort s]
_ [Int]
_ [Box l Port]
boxes) = [String] -> [String]
forall a. Ord a => [a] -> [a]
nubOrd [String
name | Box l Port
box <- [Box l Port]
boxes, Capture String
name <- Box l Port -> [Port]
forall l n. Box l n -> [n]
inputs Box l Port
box [Port] -> [Port] -> [Port]
forall a. [a] -> [a] -> [a]
++ Box l Port -> [Port]
forall l n. Box l n -> [n]
outputs Box l Port
box]

restorePortSequences :: Int -> [String] -> Graph () l -> Either String (PortGraph () l)
restorePortSequences :: forall l.
Int -> [String] -> Graph () l -> Either String (PortGraph () l)
restorePortSequences Int
boundarySize [String]
names (Graph [SomeSort ()]
sorts [Int]
ins [Int]
outs [Box l Int]
boxes) = do
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless ([Int] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [Int]
outs Bool -> Bool -> Bool
&& [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
markers Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [String] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [String]
names Bool -> Bool -> Bool
&& IntMap String -> Int
forall a. IntMap a -> Int
IM.size IntMap String
captures Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [String] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [String]
names) Either String ()
forall {b}. Either String b
invalidBoundary
  interface <- (Int -> Either String Int) -> [Int] -> Either String [Int]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Int -> Either String Int
reindex [Int]
boundary
  restored <- traverse (\(Box l
l [Int]
i [Int]
o) -> l -> [Port] -> [Port] -> Box l Port
forall l n. l -> [n] -> [n] -> Box l n
Box l
l ([Port] -> [Port] -> Box l Port)
-> Either String [Port] -> Either String ([Port] -> Box l Port)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Int -> Either String Port) -> [Int] -> Either String [Port]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Int -> Either String Port
restore [Int]
i Either String ([Port] -> Box l Port)
-> Either String [Port] -> Either String (Box l Port)
forall a b.
Either String (a -> b) -> Either String a -> Either String b
forall (f :: Type -> Type) a b.
Applicative f =>
f (a -> b) -> f a -> f b
<*> (Int -> Either String Port) -> [Int] -> Either String [Port]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Int -> Either String Port
restore [Int]
o) boxes
  pure (PortGraph (map snd numbered) interface restored)
  where
    invalidBoundary :: Either String b
invalidBoundary = String -> Either String b
forall a b. a -> Either a b
Left String
"orientPortOverlap: the witness changed a sequence marker at the boundary"
    ([Int]
boundary, [Int]
markers) = Int -> [Int] -> ([Int], [Int])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
boundarySize [Int]
ins
    captures :: IntMap String
captures = [(Int, String)] -> IntMap String
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [String] -> [(Int, String)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
markers [String]
names)
    numbered :: [(Int, SomeSort ())]
numbered = [(Int
i, SomeSort ()
sort) | (Int
i, SomeSort ()
sort) <- [Int] -> [SomeSort ()] -> [(Int, SomeSort ())]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [SomeSort ()]
sorts, Int -> IntMap String -> Bool
forall a. Int -> IntMap a -> Bool
IM.notMember Int
i IntMap String
captures]
    indices :: IntMap Int
indices = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip (((Int, SomeSort ()) -> Int) -> [(Int, SomeSort ())] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, SomeSort ()) -> Int
forall a b. (a, b) -> a
fst [(Int, SomeSort ())]
numbered) [Int
0 ..])
    reindex :: Int -> Either String Int
reindex Int
i = Either String Int
-> (Int -> Either String Int) -> Maybe Int -> Either String Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Either String Int
forall {b}. Either String b
invalidBoundary Int -> Either String Int
forall a b. b -> Either a b
Right (Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
i IntMap Int
indices)
    restore :: Int -> Either String Port
restore Int
i = Either String Port
-> (String -> Either String Port)
-> Maybe String
-> Either String Port
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Int -> Port
Node (Int -> Port) -> Either String Int -> Either String Port
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> Either String Int
reindex Int
i) (Port -> Either String Port
forall a b. b -> Either a b
Right (Port -> Either String Port)
-> (String -> Port) -> String -> Either String Port
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Port
Capture) (Int -> IntMap String -> Maybe String
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
i IntMap String
captures)

literalRule :: (key, Rule s l) -> Either String (FixedRule key s l)
literalRule :: forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
literalRule (key
key, Rule Graph s (LabelTest l)
patternGraph [l] -> Maybe (Graph s l)
instantiate) = do
  lhs@(Graph _ _ _ bs) <-
    Either String (Graph s l)
-> (Graph s l -> Either String (Graph s l))
-> Maybe (Graph s l)
-> Either String (Graph s l)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> Either String (Graph s l)
forall a b. a -> Either a b
Left String
"expected literal labels") Graph s l -> Either String (Graph s l)
forall a b. b -> Either a b
Right ((LabelTest l -> Maybe l)
-> Graph s (LabelTest l) -> Maybe (Graph s l)
forall l m s. (l -> Maybe m) -> Graph s l -> Maybe (Graph s m)
traverseLabels LabelTest l -> Maybe l
forall l. LabelTest l -> Maybe l
exact Graph s (LabelTest l)
patternGraph)
  rhs <- maybe (Left "the rule rejected its own pattern") Right (instantiate (map label bs))
  pure (key, lhs, rhs)
  where
    exact :: LabelTest l -> Maybe l
    exact :: forall l. LabelTest l -> Maybe l
exact (ExactLabel l
l) = l -> Maybe l
forall a. a -> Maybe a
Just l
l
    exact ConstructorLabel{} = Maybe l
forall a. Maybe a
Nothing
literalRule (key, Rule s l)
_ = String -> Either String (FixedRule key s l)
forall a b. a -> Either a b
Left String
"expected a fixed rule"

fixedRule :: (key, Rule s l) -> Either String (FixedRule key s l)
fixedRule :: forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
fixedRule (key, Rule s l)
ruleEntry = do
  fixed@(_, lhs, rhs) <- (key, Rule s l) -> Either String (FixedRule key s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
literalRule (key, Rule s l)
ruleEntry
  unless
    (validDiagram lhs && validDiagram rhs)
    (Left "rule sides must be monogamous acyclic diagrams")
  pure fixed

-- | Inspect the parallel sides of a fixed string-diagram rule. Both sides
-- must have monogamous acyclic wiring, as in 'compileConvexRules'.
withFixedRule
  :: forall s l r
   . Rule s l
  -> (forall as bs. (Wires @s @l as ~> Wires @s @l bs) -> (Wires @s @l as ~> Wires @s @l bs) -> r)
  -> Either String r
withFixedRule :: forall s l r.
Rule s l
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> r)
-> Either String r
withFixedRule Rule s l
fixed forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> r
inspect = do
  (_, lhs, rhs) <- ((), Rule s l) -> Either String ((), Graph s l, Graph s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
fixedRule ((), Rule s l
fixed)
  pure (withDiagramBoundary lhs (\Graph s l -> Wires as ~> Wires bs
makeDiagram -> (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> r
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> r
inspect (Graph s l -> Wires as ~> Wires bs
makeDiagram Graph s l
lhs) (Graph s l -> Wires as ~> Wires bs
makeDiagram Graph s l
rhs)))

validDiagram :: Graph s l -> Bool
validDiagram :: forall s l. Graph s l -> Bool
validDiagram (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs) =
  Int -> [Box l Int] -> Maybe ([Int], [Int])
forall l. Int -> [Box l Int] -> Maybe ([Int], [Int])
diagramBoundary ([SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ns) [Box l Int]
bs Maybe ([Int], [Int]) -> Maybe ([Int], [Int]) -> Bool
forall a. Eq a => a -> a -> Bool
== ([Int], [Int]) -> Maybe ([Int], [Int])
forall a. a -> Maybe a
Just ([Int] -> [Int]
forall a. Ord a => [a] -> [a]
List.sort [Int]
ins, [Int] -> [Int]
forall a. Ord a => [a] -> [a]
List.sort [Int]
outs)

diagramBoundary :: Int -> [Box l Int] -> Maybe ([Int], [Int])
diagramBoundary :: forall l. Int -> [Box l Int] -> Maybe ([Int], [Int])
diagramBoundary Int
n [Box l Int]
bs = do
  Bool -> Maybe ()
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
produced Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== IntSet -> Int
IS.size IntSet
producers Bool -> Bool -> Bool
&& [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
consumed Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== IntSet -> Int
IS.size IntSet
consumers)
  Bool -> Maybe ()
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard ((SCC Int -> Bool) -> [SCC Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all SCC Int -> Bool
forall {vertex}. SCC vertex -> Bool
acyclic ([(Int, Int, [Int])] -> [SCC Int]
forall key node. Ord key => [(node, key, [key])] -> [SCC node]
stronglyConnComp [(Int
v, Int
v, [Int] -> Int -> IntMap [Int] -> [Int]
forall a. a -> Int -> IntMap a -> a
IM.findWithDefault [] Int
v IntMap [Int]
edges) | Int
v <- [Int]
vertices]))
  ([Int], [Int]) -> Maybe ([Int], [Int])
forall a. a -> Maybe a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure ([Int
v | Int
v <- [Int]
vertices, Int -> IntSet -> Bool
IS.notMember Int
v IntSet
producers], [Int
v | Int
v <- [Int]
vertices, Int -> IntSet -> Bool
IS.notMember Int
v IntSet
consumers])
  where
    vertices :: [Int]
vertices = [Int
0 .. Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
    produced :: [Int]
produced = (Box l Int -> [Int]) -> [Box l Int] -> [Int]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap Box l Int -> [Int]
forall l n. Box l n -> [n]
outputs [Box l Int]
bs
    consumed :: [Int]
consumed = (Box l Int -> [Int]) -> [Box l Int] -> [Int]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap Box l Int -> [Int]
forall l n. Box l n -> [n]
inputs [Box l Int]
bs
    producers :: IntSet
producers = [Int] -> IntSet
IS.fromList [Int]
produced
    consumers :: IntSet
consumers = [Int] -> IntSet
IS.fromList [Int]
consumed
    edges :: IntMap [Int]
edges = [Box l Int] -> IntMap [Int]
forall l. [Box l Int] -> IntMap [Int]
wireEdges [Box l Int]
bs
    acyclic :: SCC vertex -> Bool
acyclic AcyclicSCC{} = Bool
True
    acyclic CyclicSCC{} = Bool
False

wireEdges :: [Box l Int] -> IM.IntMap [Int]
wireEdges :: forall l. [Box l Int] -> IntMap [Int]
wireEdges [Box l Int]
bs = ([Int] -> [Int] -> [Int]) -> [(Int, [Int])] -> IntMap [Int]
forall a. (a -> a -> a) -> [(Int, a)] -> IntMap a
IM.fromListWith [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
(++) [(Int
i, Box l Int -> [Int]
forall l n. Box l n -> [n]
outputs Box l Int
b) | Box l Int
b <- [Box l Int]
bs, Int
i <- Box l Int -> [Int]
forall l n. Box l n -> [n]
inputs Box l Int
b]

reachableNodes :: IM.IntMap [Int] -> Int -> IS.IntSet
reachableNodes :: IntMap [Int] -> Int -> IntSet
reachableNodes IntMap [Int]
edges Int
start = IntSet -> [Int] -> IntSet
visit IntSet
IS.empty [Int
start]
  where
    visit :: IntSet -> [Int] -> IntSet
visit IntSet
seen [] = IntSet
seen
    visit IntSet
seen (Int
i : [Int]
rest)
      | Int -> IntSet -> Bool
IS.member Int
i IntSet
seen = IntSet -> [Int] -> IntSet
visit IntSet
seen [Int]
rest
      | Bool
otherwise = IntSet -> [Int] -> IntSet
visit (Int -> IntSet -> IntSet
IS.insert Int
i IntSet
seen) ([Int] -> Int -> IntMap [Int] -> [Int]
forall a. a -> Int -> IntMap a -> a
IM.findWithDefault [] Int
i IntMap [Int]
edges [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
rest)

type FixedRule :: Type -> Kind -> Type -> Type
type FixedRule key s l = (key, Graph s l, Graph s l)

type DiagramStep :: Type -> Kind -> Type -> Type
type DiagramStep key s l = (key, Graph s l, Graph s l, Match)

type PreCriticalPair :: Type -> Kind -> Type -> Type
type PreCriticalPair key s l = (Graph s l, DiagramStep key s l, DiagramStep key s l)

data OverlapMode = StringOverlaps Bool | HypergraphOverlaps

preCriticalPairs
  :: (Eq l, DecidableIso s)
  => OverlapMode -> [FixedRule key s l] -> [PreCriticalPair key s l]
preCriticalPairs :: forall l s key.
(Eq l, DecidableIso s) =>
OverlapMode -> [FixedRule key s l] -> [PreCriticalPair key s l]
preCriticalPairs OverlapMode
mode [FixedRule key s l]
patterns =
  [ PreCriticalPair key s l
peak
  | (FixedRule key s l
first : [FixedRule key s l]
rest) <- [FixedRule key s l] -> [[FixedRule key s l]]
forall a. [a] -> [[a]]
tails [FixedRule key s l]
patterns
  , (Bool
sameRule, FixedRule key s l
second) <- (Bool
True, FixedRule key s l
first) (Bool, FixedRule key s l)
-> [(Bool, FixedRule key s l)] -> [(Bool, FixedRule key s l)]
forall a. a -> [a] -> [a]
: (FixedRule key s l -> (Bool, FixedRule key s l))
-> [FixedRule key s l] -> [(Bool, FixedRule key s l)]
forall a b. (a -> b) -> [a] -> [b]
map (Bool
False,) [FixedRule key s l]
rest
  , PreCriticalPair key s l
peak <- OverlapMode
-> Bool
-> FixedRule key s l
-> FixedRule key s l
-> [PreCriticalPair key s l]
forall l s key.
(Eq l, DecidableIso s) =>
OverlapMode
-> Bool
-> FixedRule key s l
-> FixedRule key s l
-> [PreCriticalPair key s l]
glueOverlaps OverlapMode
mode Bool
sameRule FixedRule key s l
first FixedRule key s l
second
  ]

glueOverlaps
  :: (Eq l, DecidableIso s)
  => OverlapMode -> Bool -> FixedRule key s l -> FixedRule key s l -> [PreCriticalPair key s l]
glueOverlaps :: forall l s key.
(Eq l, DecidableIso s) =>
OverlapMode
-> Bool
-> FixedRule key s l
-> FixedRule key s l
-> [PreCriticalPair key s l]
glueOverlaps OverlapMode
mode Bool
sameRule (key
lk, left :: Graph s l
left@(Graph [SomeSort s]
ls [Int]
li [Int]
lo [Box l Int]
lb), Graph s l
lr) (key
rk, right :: Graph s l
right@(Graph [SomeSort s]
rs [Int]
ri [Int]
ro [Box l Int]
rb), Graph s l
rr) = do
  boxPairs <-
    [(Int, [Int])] -> [[(Int, Int)]]
partialInjections
      [(Int
j, [Int
i | (Int
i, Box l Int
l) <- [Int] -> [Box l Int] -> [(Int, Box l Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [Box l Int]
lb, Box l Int -> Box l Int -> Bool
forall {a} {a} {a}. Eq a => Box a a -> Box a a -> Bool
compatible Box l Int
l Box l Int
r]) | (Int
j, Box l Int
r) <- [Int] -> [Box l Int] -> [(Int, Box l Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [Box l Int]
rb]
  case mode of
    StringOverlaps Bool
includeParallel -> Bool -> [()]
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard (Bool
includeParallel Bool -> Bool -> Bool
|| Bool -> Bool
not ([(Int, Int)] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [(Int, Int)]
boxPairs))
    OverlapMode
HypergraphOverlaps -> Bool -> [()]
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard (Bool -> Bool
not ([(Int, Int)] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [(Int, Int)]
boxPairs) Bool -> Bool -> Bool
|| Graph s l -> Graph s l -> Graph s l -> Bool
forall s l.
DecidableIso s =>
Graph s l -> Graph s l -> Graph s l -> Bool
interferesOnWires Graph s l
left Graph s l
lr Graph s l
right Bool -> Bool -> Bool
|| Graph s l -> Graph s l -> Graph s l -> Bool
forall s l.
DecidableIso s =>
Graph s l -> Graph s l -> Graph s l -> Bool
interferesOnWires Graph s l
right Graph s l
rr Graph s l
left)
  let ports =
        [[(Int, Int)]] -> [(Int, Int)]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat
          [[Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip (Box l Int -> [Int]
forall l n. Box l n -> [n]
inputs Box l Int
r [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ Box l Int -> [Int]
forall l n. Box l n -> [n]
outputs Box l Int
r) (Box l Int -> [Int]
forall l n. Box l n -> [n]
inputs Box l Int
l [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ Box l Int -> [Int]
forall l n. Box l n -> [n]
outputs Box l Int
l) | (Int
j, Int
i) <- [(Int, Int)]
boxPairs, let r :: Box l Int
r = [Box l Int]
rb [Box l Int] -> Int -> Box l Int
forall a. HasCallStack => [a] -> Int -> a
!! Int
j, let l :: Box l Int
l = [Box l Int]
lb [Box l Int] -> Int -> Box l Int
forall a. HasCallStack => [a] -> Int -> a
!! Int
i]
  (forced, used) <- maybeToList (foldM bind (IM.empty, IS.empty) ports)
  -- Sharing a box identifies its ports. Monogamous wiring only allows further
  -- identifications between an unused input and an unused output.
  let nodeCandidates = case OverlapMode
mode of
        StringOverlaps Bool
_ -> [([Int]
ri, [Int]
lo), ([Int]
ro, [Int]
li)]
        OverlapMode
HypergraphOverlaps -> [([Int
0 .. [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
rs Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1], [Int
0 .. [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ls Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1])]
  wirePairs <-
    partialInjections
      [ (j, [i | i <- candidates, IS.notMember i used, sameSort (rs !! j) (ls !! i)])
      | (boundary, candidates) <- nodeCandidates
      , j <- boundary
      , IM.notMember j forced
      ]
  let shared = IntMap Int -> IntMap Int -> IntMap Int
forall a. IntMap a -> IntMap a -> IntMap a
IM.union IntMap Int
forced ([(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int, Int)]
wirePairs)
      inverse [(b, a)]
pairs = [(a, b)] -> [(a, b)]
forall a. Ord a => [a] -> [a]
List.sort [(a
b, b
a) | (b
a, a
b) <- [(b, a)]
pairs]
      wires = IntMap Int -> [(Int, Int)]
forall a. IntMap a -> [(Int, a)]
IM.toList IntMap Int
shared
  guard (not sameRule || (List.sort boxPairs, wires) <= (inverse boxPairs, inverse wires))
  let fresh = [(Int
j, SomeSort s
s) | (Int
j, SomeSort s
s) <- [Int] -> [SomeSort s] -> [(Int, SomeSort s)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [SomeSort s]
rs, Int -> IntMap Int -> Bool
forall a. Int -> IntMap a -> Bool
IM.notMember Int
j IntMap Int
shared]
      ns = [SomeSort s]
ls [SomeSort s] -> [SomeSort s] -> [SomeSort s]
forall a. [a] -> [a] -> [a]
++ ((Int, SomeSort s) -> SomeSort s)
-> [(Int, SomeSort s)] -> [SomeSort s]
forall a b. (a -> b) -> [a] -> [b]
map (Int, SomeSort s) -> SomeSort s
forall a b. (a, b) -> b
snd [(Int, SomeSort s)]
fresh
      nodeMap = IntMap Int -> IntMap Int -> IntMap Int
forall a. IntMap a -> IntMap a -> IntMap a
IM.union IntMap Int
shared ([(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip (((Int, SomeSort s) -> Int) -> [(Int, SomeSort s)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, SomeSort s) -> Int
forall a b. (a, b) -> a
fst [(Int, SomeSort s)]
fresh) [[SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ls ..]))
      sharedBoxes = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int, Int)]
boxPairs
      remaining = [(Int
j, Box l Int
b) | (Int
j, Box l Int
b) <- [Int] -> [Box l Int] -> [(Int, Box l Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [Box l Int]
rb, Int -> IntMap Int -> Bool
forall a. Int -> IntMap a -> Bool
IM.notMember Int
j IntMap Int
sharedBoxes]
      boxMap = IntMap Int -> IntMap Int -> IntMap Int
forall a. IntMap a -> IntMap a -> IntMap a
IM.union IntMap Int
sharedBoxes ([(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip (((Int, Box l Int) -> Int) -> [(Int, Box l Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Box l Int) -> Int
forall a b. (a, b) -> a
fst [(Int, Box l Int)]
remaining) [[Box l Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Box l Int]
lb ..]))
      bs = [Box l Int]
lb [Box l Int] -> [Box l Int] -> [Box l Int]
forall a. [a] -> [a] -> [a]
++ [(Int -> Int) -> Box l Int -> Box l Int
forall a b. (a -> b) -> Box l a -> Box l b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap (IntMap Int
nodeMap IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) Box l Int
b | (Int
_, Box l Int
b) <- [(Int, Box l Int)]
remaining]
      lm = ([(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int
i, Int
i) | Int
i <- [Int
0 .. [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ls Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]], [Int] -> IntSet
IS.fromList [Int
0 .. [Box l Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Box l Int]
lb Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1])
      rm = (IntMap Int
nodeMap, [Int] -> IntSet
IS.fromList (IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
boxMap))
  guard (not sameRule || lm /= rm)
  (ins, outs) <- case mode of
    StringOverlaps Bool
_ -> Maybe ([Int], [Int]) -> [([Int], [Int])]
forall a. Maybe a -> [a]
maybeToList (Int -> [Box l Int] -> Maybe ([Int], [Int])
forall l. Int -> [Box l Int] -> Maybe ([Int], [Int])
diagramBoundary ([SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ns) [Box l Int]
bs)
    OverlapMode
HypergraphOverlaps -> do
      let leftDeleted :: IntSet
leftDeleted = Graph s l -> IntMap Int -> IntSet
forall s l. Graph s l -> IntMap Int -> IntSet
deletedImages Graph s l
left (Match -> IntMap Int
forall a b. (a, b) -> a
fst Match
lm)
          rightDeleted :: IntSet
rightDeleted = Graph s l -> IntMap Int -> IntSet
forall s l. Graph s l -> IntMap Int -> IntSet
deletedImages Graph s l
right (Match -> IntMap Int
forall a b. (a, b) -> a
fst Match
rm)
      Bool -> [()]
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard
        ( [(IntSet, Match)] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length ((IntSet -> Match -> IntSet)
-> [(IntSet, Match)] -> [(IntSet, Match)]
forall a. (a -> Match -> IntSet) -> [(a, Match)] -> [(a, Match)]
nonConflictingBy IntSet -> Match -> IntSet
forall a b. a -> b -> a
const [(IntSet
leftDeleted, Match
lm), (IntSet
rightDeleted, Match
rm)])
            Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1
              Bool -> Bool -> Bool
|| Graph s l -> Graph s l -> Match -> Match -> Bool
forall s l. Graph s l -> Graph s l -> Match -> Match -> Bool
identifiesMatchNodes Graph s l
left Graph s l
lr Match
lm Match
rm
              Bool -> Bool -> Bool
|| Graph s l -> Graph s l -> Match -> Match -> Bool
forall s l. Graph s l -> Graph s l -> Match -> Match -> Bool
identifiesMatchNodes Graph s l
right Graph s l
rr Match
rm Match
lm
        )
      let deleted :: IntSet
deleted = IntSet -> IntSet -> IntSet
IS.union IntSet
leftDeleted IntSet
rightDeleted
      ([Int], [Int]) -> [([Int], [Int])]
forall a. a -> [a]
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure ([Int
i | Int
i <- [Int
0 .. [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ns Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1], Int -> IntSet -> Bool
IS.notMember Int
i IntSet
deleted], [])
  let host = [SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs
  guard (lm `elem` map fst (matches lhs host) && rm `elem` map fst (matches rhs host))
  pure (host, (lk, left, lr, lm), (rk, right, rr, rm))
  where
    lhs :: Graph s (LabelTest l)
lhs = (l -> LabelTest l) -> Graph s l -> Graph s (LabelTest l)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels l -> LabelTest l
forall l. l -> LabelTest l
ExactLabel Graph s l
left
    rhs :: Graph s (LabelTest l)
rhs = (l -> LabelTest l) -> Graph s l -> Graph s (LabelTest l)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels l -> LabelTest l
forall l. l -> LabelTest l
ExactLabel Graph s l
right
    compatible :: Box a a -> Box a a -> Bool
compatible (Box a
l [a]
i [a]
o) (Box a
r [a]
j [a]
p) = a
l a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
r Bool -> Bool -> Bool
&& [a] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [a]
i Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [a] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [a]
j Bool -> Bool -> Bool
&& [a] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [a]
o Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [a] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [a]
p
    bind :: Match -> (Int, Int) -> Maybe Match
bind (IntMap Int
mapping, IntSet
used) (Int
j, Int
i)
      | Just Int
previous <- Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
j IntMap Int
mapping = (IntMap Int
mapping, IntSet
used) Match -> Maybe () -> Maybe Match
forall a b. a -> Maybe b -> Maybe a
forall (f :: Type -> Type) a b. Functor f => a -> f b -> f a
<$ Bool -> Maybe ()
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard (Int
previous Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
i)
      | Int -> IntSet -> Bool
IS.member Int
i IntSet
used Bool -> Bool -> Bool
|| Bool -> Bool
not (SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort ([SomeSort s]
rs [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!! Int
j) ([SomeSort s]
ls [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!! Int
i)) = Maybe Match
forall a. Maybe a
Nothing
      | Bool
otherwise = Match -> Maybe Match
forall a. a -> Maybe a
Just (Int -> Int -> IntMap Int -> IntMap Int
forall a. Int -> a -> IntMap a -> IntMap a
IM.insert Int
j Int
i IntMap Int
mapping, Int -> IntSet -> IntSet
IS.insert Int
i IntSet
used)

-- Disjoint boxes can interfere through node deletion or identification.
interferesOnWires :: (DecidableIso s) => Graph s l -> Graph s l -> Graph s l -> Bool
interferesOnWires :: forall s l.
DecidableIso s =>
Graph s l -> Graph s l -> Graph s l -> Bool
interferesOnWires lhs :: Graph s l
lhs@(Graph [SomeSort s]
sorts [Int]
li [Int]
lo [Box l Int]
_) (Graph [SomeSort s]
_ [Int]
ri [Int]
ro [Box l Int]
_) (Graph [SomeSort s]
otherSorts [Int]
_ [Int]
_ [Box l Int]
_) =
  (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any Int -> Bool
canDelete (Graph s l -> [Int]
forall s l. Graph s l -> [Int]
internalNodes Graph s l
lhs)
    Bool -> Bool -> Bool
|| ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
targets Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= IntSet -> Int
IS.size ([Int] -> IntSet
IS.fromList [Int]
targets) Bool -> Bool -> Bool
&& ([Int] -> Bool) -> [[Int]] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any [Int] -> Bool
canMerge (IntMap [Int] -> [[Int]]
forall a. IntMap a -> [a]
IM.elems IntMap [Int]
mergedSources))
  where
    targets :: [Int]
targets = [Int]
ri [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
ro
    mergedSources :: IntMap [Int]
mergedSources = ([Int] -> [Int] -> [Int]) -> [(Int, [Int])] -> IntMap [Int]
forall a. (a -> a -> a) -> [(Int, a)] -> IntMap a
IM.fromListWith [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
(++) [(Int
r, [Int
l]) | (Int
l, Int
r) <- [Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip ([Int]
li [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
lo) [Int]
targets]
    canDelete :: Int -> Bool
canDelete Int
node = (SomeSort s -> Bool) -> [SomeSort s] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort ([SomeSort s]
sorts [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!! Int
node)) [SomeSort s]
otherSorts
    -- A merge identifies two nodes of the same sort in the other match.
    canMerge :: [Int] -> Bool
canMerge (Int
node : Int
_ : [Int]
_) = case (SomeSort s -> Bool) -> [SomeSort s] -> [SomeSort s]
forall a. (a -> Bool) -> [a] -> [a]
filter (SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort ([SomeSort s]
sorts [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!! Int
node)) [SomeSort s]
otherSorts of
      SomeSort s
_ : SomeSort s
_ : [SomeSort s]
_ -> Bool
True
      [SomeSort s]
_ -> Bool
False
    canMerge [Int]
_ = Bool
False

-- A replacement can identify nodes that another match needs to keep distinct.
identifiesMatchNodes :: Graph s l -> Graph s l -> Match -> Match -> Bool
identifiesMatchNodes :: forall s l. Graph s l -> Graph s l -> Match -> Match -> Bool
identifiesMatchNodes (Graph [SomeSort s]
_ [Int]
li [Int]
lo [Box l Int]
_) (Graph [SomeSort s]
_ [Int]
ri [Int]
ro [Box l Int]
_) (IntMap Int
mapping, IntSet
_) (IntMap Int
other, IntSet
_) =
  [(Int, Int)] -> IntSet -> Bool
identifiesNodes ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip ((Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) ([Int]
li [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
lo)) ([Int]
ri [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
ro)) ([Int] -> IntSet
IS.fromList (IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
other))

identifiesNodes :: [(Int, Int)] -> IS.IntSet -> Bool
identifiesNodes :: [(Int, Int)] -> IntSet -> Bool
identifiesNodes [(Int, Int)]
interface IntSet
readNodes =
  [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
targets Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= IntSet -> Int
IS.size ([Int] -> IntSet
IS.fromList [Int]
targets)
  where
    targets :: [Int]
targets = [Int
r | (Int
l, Int
r) <- [(Int, Int)]
interface, Int -> IntSet -> Bool
IS.member Int
l IntSet
readNodes]

partialInjections :: [(Int, [Int])] -> [[(Int, Int)]]
partialInjections :: [(Int, [Int])] -> [[(Int, Int)]]
partialInjections = IntSet -> [(Int, [Int])] -> [[(Int, Int)]]
forall {a}. IntSet -> [(a, [Int])] -> [[(a, Int)]]
go IntSet
IS.empty
  where
    go :: IntSet -> [(a, [Int])] -> [[(a, Int)]]
go IntSet
_ [] = [[]]
    go IntSet
used ((a
i, [Int]
choices) : [(a, [Int])]
rest) =
      IntSet -> [(a, [Int])] -> [[(a, Int)]]
go IntSet
used [(a, [Int])]
rest
        [[(a, Int)]] -> [[(a, Int)]] -> [[(a, Int)]]
forall a. [a] -> [a] -> [a]
++ [(a
i, Int
j) (a, Int) -> [(a, Int)] -> [(a, Int)]
forall a. a -> [a] -> [a]
: [(a, Int)]
pairs | Int
j <- [Int]
choices, Int -> IntSet -> Bool
IS.notMember Int
j IntSet
used, [(a, Int)]
pairs <- IntSet -> [(a, [Int])] -> [[(a, Int)]]
go (Int -> IntSet -> IntSet
IS.insert Int
j IntSet
used) [(a, [Int])]
rest]

renderOverlap :: forall key s l. Graph s l -> DiagramStep key s l -> DiagramStep key s l -> CriticalOverlap key s l
renderOverlap :: forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s l
host left :: DiagramStep key s l
left@(key
lk, Graph s l
_, Graph s l
_, Match
_) right :: DiagramStep key s l
right@(key
rk, Graph s l
_, Graph s l
_, Match
_) =
  Graph s l
-> (forall (as :: [s]) (bs :: [s]).
    (Graph s l -> Wires as ~> Wires bs) -> CriticalOverlap key s l)
-> CriticalOverlap key s l
forall s l r.
Graph s l
-> (forall (as :: [s]) (bs :: [s]).
    (Graph s l -> Wires as ~> Wires bs) -> r)
-> r
withDiagramBoundary Graph s l
host \Graph s l -> Wires as ~> Wires bs
toDiagram ->
    key
-> key
-> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs)
-> CriticalOverlap key s l
forall {key} {s} {l} (as :: [s]) (bs :: [s]).
key
-> key
-> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs)
-> CriticalOverlap key s l
CriticalOverlap key
lk key
rk (Graph s l -> Wires as ~> Wires bs
toDiagram Graph s l
host) (Graph s l -> Wires as ~> Wires bs
toDiagram (Graph s l -> DiagramStep key s l -> Graph s l
forall s l key. Graph s l -> DiagramStep key s l -> Graph s l
applyStep Graph s l
host DiagramStep key s l
left)) (Graph s l -> Wires as ~> Wires bs
toDiagram (Graph s l -> DiagramStep key s l -> Graph s l
forall s l key. Graph s l -> DiagramStep key s l -> Graph s l
applyStep Graph s l
host DiagramStep key s l
right))

withDiagramBoundary
  :: forall s l r
   . Graph s l
  -> (forall as bs. (Graph s l -> Wires @s @l as ~> Wires @s @l bs) -> r)
  -> r
withDiagramBoundary :: forall s l r.
Graph s l
-> (forall (as :: [s]) (bs :: [s]).
    (Graph s l -> Wires as ~> Wires bs) -> r)
-> r
withDiagramBoundary (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
_) forall (as :: [s]) (bs :: [s]).
(Graph s l -> Wires as ~> Wires bs) -> r
k =
  [SomeSort s] -> (forall (xs :: [s]). SortList xs => r) -> r
forall s r.
[SomeSort s] -> (forall (xs :: [s]). SortList xs => r) -> r
reifySorts ((Int -> SomeSort s) -> [Int] -> [SomeSort s]
forall a b. (a -> b) -> [a] -> [b]
map ([SomeSort s]
ns [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!!) [Int]
ins) \ @as -> [SomeSort s] -> (forall (xs :: [s]). SortList xs => r) -> r
forall s r.
[SomeSort s] -> (forall (xs :: [s]). SortList xs => r) -> r
reifySorts ((Int -> SomeSort s) -> [Int] -> [SomeSort s]
forall a b. (a -> b) -> [a] -> [b]
map ([SomeSort s]
ns [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!!) [Int]
outs) \ @bs ->
    let toDiagram :: Graph s l -> (Wires as :: OPENHG s l) ~> Wires bs
        toDiagram :: Graph s l -> Wires xs ~> Wires xs
toDiagram (Graph [SomeSort s]
ss [Int]
is [Int]
os [Box l Int]
boxes) = [SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires xs ~> Wires xs
forall {s} l (as :: [s]) (bs :: [s]).
(SortList as, SortList bs) =>
[SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires as ~> Wires bs
unsafeOpenHypergraph [SomeSort s]
ss [Int]
is [Int]
os [Box l Int]
boxes
    in (Graph s l -> Wires xs ~> Wires xs) -> r
forall (as :: [s]) (bs :: [s]).
(Graph s l -> Wires as ~> Wires bs) -> r
k Graph s l -> Wires xs ~> Wires xs
toDiagram

applyStep :: Graph s l -> DiagramStep key s l -> Graph s l
applyStep :: forall s l key. Graph s l -> DiagramStep key s l -> Graph s l
applyStep Graph s l
host (key
_, Graph s l
lhs, Graph s l
rhs, Match
match) = Graph s l -> Graph s l -> Graph s l -> [Match] -> Graph s l
forall s p l.
Graph s p -> Graph s l -> Graph s l -> [Match] -> Graph s l
replaceMany Graph s l
lhs Graph s l
rhs Graph s l
host [Match
match]

-- | The result of testing all maximal path contexts. A failed join contains
-- its extended source and both reducts. 'Left' labels in that witness are
-- the numbered formal path boxes, and 'Right' labels are original generators.
-- Failure concerns the extended signature that includes the formal boxes.
type PathContextResult :: Type -> Kind -> Type -> Type
data PathContextResult key s l
  = PathContextsJoinable Int
  | PathContextNotJoinable (CriticalOverlap key s (Either Int l))
  | PathContextLimitReached

-- | Check path joinability for fixed, left-linear string-diagram rules.
-- Includes parallel pairs, which can interfere under convex matching. Both
-- sides of each rule must be monogamous and acyclic. The optional bound is
-- the maximum search depth from each reduct, for each path context. Use
-- 'Nothing' for a terminating rule set to exhaust the search.
-- See <https://arxiv.org/html/2109.06049#S5.SS5 String Diagram Rewrite Theory III, §5.5>.
checkPathContexts
  :: (Eq l, DecidableIso s)
  => Maybe Natural -> [(key, Rule s l)] -> Either String (PathContextResult key s l)
checkPathContexts :: forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> [(key, Rule s l)] -> Either String (PathContextResult key s l)
checkPathContexts Maybe Natural
maxDepth [(key, Rule s l)]
rules = do
  patterns <- ((key, Rule s l) -> Either String (FixedRule key s l))
-> [(key, Rule s l)] -> Either String [FixedRule key s l]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (key, Rule s l) -> Either String (FixedRule key s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
fixedRule [(key, Rule s l)]
rules
  pure $ case checkContexts maxDepth patterns (preCriticalPairs (StringOverlaps True) patterns) of
    AllJoinable Int
count -> Int -> PathContextResult key s l
forall key s l. Int -> PathContextResult key s l
PathContextsJoinable Int
count
    Unjoinable (Graph s (Either Int l)
host, DiagramStep key s (Either Int l)
left, DiagramStep key s (Either Int l)
right) -> CriticalOverlap key s (Either Int l) -> PathContextResult key s l
forall key s l.
CriticalOverlap key s (Either Int l) -> PathContextResult key s l
PathContextNotJoinable (Graph s (Either Int l)
-> DiagramStep key s (Either Int l)
-> DiagramStep key s (Either Int l)
-> CriticalOverlap key s (Either Int l)
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s (Either Int l)
host DiagramStep key s (Either Int l)
left DiagramStep key s (Either Int l)
right)
    JoinLimit (Graph s (Either Int l), DiagramStep key s (Either Int l),
 DiagramStep key s (Either Int l))
_ -> PathContextResult key s l
forall key s l. PathContextResult key s l
PathContextLimitReached

checkContexts
  :: (Eq l, DecidableIso s)
  => Maybe Natural -> [FixedRule key s l] -> [PreCriticalPair key s l] -> PairCheck key s (Either Int l)
checkContexts :: forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> [FixedRule key s l]
-> [PreCriticalPair key s l]
-> PairCheck key s (Either Int l)
checkContexts Maybe Natural
maxDepth [FixedRule key s l]
patterns = Maybe Natural
-> (Graph s (Either Int l) -> [Graph s (Either Int l)])
-> [PreCriticalPair key s (Either Int l)]
-> PairCheck key s (Either Int l)
forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Graph s l])
-> [PreCriticalPair key s l]
-> PairCheck key s l
checkPairs Maybe Natural
maxDepth (ConvexRules s (Either Int l)
-> Graph s (Either Int l) -> [Graph s (Either Int l)]
forall l s.
(Eq l, DecidableIso s) =>
ConvexRules s l -> Graph s l -> [Graph s l]
convexReducts ((l -> Either Int l)
-> [FixedRule key s l] -> ConvexRules s (Either Int l)
forall l m key s.
(l -> m) -> [FixedRule key s l] -> ConvexRules s m
convexRulesWith l -> Either Int l
forall a b. b -> Either a b
Right [FixedRule key s l]
patterns)) ([PreCriticalPair key s (Either Int l)]
 -> PairCheck key s (Either Int l))
-> ([PreCriticalPair key s l]
    -> [PreCriticalPair key s (Either Int l)])
-> [PreCriticalPair key s l]
-> PairCheck key s (Either Int l)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [PreCriticalPair key s l] -> [PreCriticalPair key s (Either Int l)]
forall key s l.
[PreCriticalPair key s l] -> [PreCriticalPair key s (Either Int l)]
pathContexts

pathContexts :: [PreCriticalPair key s l] -> [PreCriticalPair key s (Either Int l)]
pathContexts :: forall key s l.
[PreCriticalPair key s l] -> [PreCriticalPair key s (Either Int l)]
pathContexts [PreCriticalPair key s l]
pairs =
  [ (Graph s l -> [(Int, Int)] -> Graph s (Either Int l)
forall s l. Graph s l -> [(Int, Int)] -> Graph s (Either Int l)
pathExtension Graph s l
host [(Int, Int)]
relation, DiagramStep key s l -> DiagramStep key s (Either Int l)
forall key s l.
DiagramStep key s l -> DiagramStep key s (Either Int l)
liftStep DiagramStep key s l
first, DiagramStep key s l -> DiagramStep key s (Either Int l)
forall key s l.
DiagramStep key s l -> DiagramStep key s (Either Int l)
liftStep DiagramStep key s l
second)
  | (Graph s l
host, DiagramStep key s l
first, DiagramStep key s l
second) <- [PreCriticalPair key s l]
pairs
  , [(Int, Int)]
relation <- Graph s l -> [(Int, Int)] -> [[(Int, Int)]]
forall s l. Graph s l -> [(Int, Int)] -> [[(Int, Int)]]
maximalPathRelations Graph s l
host (DiagramStep key s l -> [(Int, Int)]
forall key s l. DiagramStep key s l -> [(Int, Int)]
forbiddenPaths DiagramStep key s l
first [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]
forall a. [a] -> [a] -> [a]
++ DiagramStep key s l -> [(Int, Int)]
forall key s l. DiagramStep key s l -> [(Int, Int)]
forbiddenPaths DiagramStep key s l
second)
  ]

liftStep :: DiagramStep key s l -> DiagramStep key s (Either Int l)
liftStep :: forall key s l.
DiagramStep key s l -> DiagramStep key s (Either Int l)
liftStep (key
key, Graph s l
lhs, Graph s l
rhs, Match
match) = (key
key, (l -> Either Int l) -> Graph s l -> Graph s (Either Int l)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels l -> Either Int l
forall a b. b -> Either a b
Right Graph s l
lhs, (l -> Either Int l) -> Graph s l -> Graph s (Either Int l)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels l -> Either Int l
forall a b. b -> Either a b
Right Graph s l
rhs, Match
match)

type PairCheck key s l = JoinCheck (PreCriticalPair key s l)

data JoinCheck a
  = AllJoinable Int
  | Unjoinable a
  | JoinLimit a

checkPairs
  :: (Eq l, DecidableIso s)
  => Maybe Natural -> (Graph s l -> [Graph s l]) -> [PreCriticalPair key s l] -> PairCheck key s l
checkPairs :: forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Graph s l])
-> [PreCriticalPair key s l]
-> PairCheck key s l
checkPairs Maybe Natural
maxDepth Graph s l -> [Graph s l]
reducts = (Graph s l -> Graph s l -> Maybe Bool)
-> (PreCriticalPair key s l -> (Graph s l, Graph s l))
-> [PreCriticalPair key s l]
-> JoinCheck (PreCriticalPair key s l)
forall g a.
(g -> g -> Maybe Bool) -> (a -> (g, g)) -> [a] -> JoinCheck a
checkJoins (Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
forall l s.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
joinGraphs Maybe Natural
maxDepth Graph s l -> [Graph s l]
reducts) \(Graph s l
host, DiagramStep key s l
left, DiagramStep key s l
right) -> (Graph s l -> DiagramStep key s l -> Graph s l
forall s l key. Graph s l -> DiagramStep key s l -> Graph s l
applyStep Graph s l
host DiagramStep key s l
left, Graph s l -> DiagramStep key s l -> Graph s l
forall s l key. Graph s l -> DiagramStep key s l -> Graph s l
applyStep Graph s l
host DiagramStep key s l
right)

checkJoins :: (g -> g -> Maybe Bool) -> (a -> (g, g)) -> [a] -> JoinCheck a
checkJoins :: forall g a.
(g -> g -> Maybe Bool) -> (a -> (g, g)) -> [a] -> JoinCheck a
checkJoins g -> g -> Maybe Bool
join a -> (g, g)
branches = Int -> Maybe a -> [a] -> JoinCheck a
checkAll Int
0 Maybe a
forall a. Maybe a
Nothing
  where
    checkAll :: Int -> Maybe a -> [a] -> JoinCheck a
checkAll Int
count Maybe a
pending [] = JoinCheck a -> (a -> JoinCheck a) -> Maybe a -> JoinCheck a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Int -> JoinCheck a
forall a. Int -> JoinCheck a
AllJoinable Int
count) a -> JoinCheck a
forall a. a -> JoinCheck a
JoinLimit Maybe a
pending
    checkAll Int
count Maybe a
pending (a
pair : [a]
more) =
      case (g -> g -> Maybe Bool) -> (g, g) -> Maybe Bool
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry g -> g -> Maybe Bool
join (a -> (g, g)
branches a
pair) of
        Just Bool
True -> Int -> Maybe a -> [a] -> JoinCheck a
checkAll (Int
count Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Maybe a
pending [a]
more
        Just Bool
False -> a -> JoinCheck a
forall a. a -> JoinCheck a
Unjoinable a
pair
        Maybe Bool
Nothing -> Int -> Maybe a -> [a] -> JoinCheck a
checkAll Int
count (a -> Maybe a
forall a. a -> Maybe a
Just (a -> Maybe a -> a
forall a. a -> Maybe a -> a
fromMaybe a
pair Maybe a
pending)) [a]
more

checkHypergraphPairs
  :: (Eq l, DecidableIso s)
  => Maybe Natural -> (Graph s l -> [Prepared s l]) -> [FixedRule key s l] -> PairCheck key s l
checkHypergraphPairs :: forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Prepared s l])
-> [FixedRule key s l]
-> PairCheck key s l
checkHypergraphPairs Maybe Natural
maxDepth Graph s l -> [Prepared s l]
next = Maybe Natural
-> (Graph s l -> [Graph s l])
-> [PreCriticalPair key s l]
-> PairCheck key s l
forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Graph s l])
-> [PreCriticalPair key s l]
-> PairCheck key s l
checkPairs Maybe Natural
maxDepth ((Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
forall s l.
(Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
singleReducts Graph s l -> [Prepared s l]
next) ([PreCriticalPair key s l] -> PairCheck key s l)
-> ([FixedRule key s l] -> [PreCriticalPair key s l])
-> [FixedRule key s l]
-> PairCheck key s l
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OverlapMode -> [FixedRule key s l] -> [PreCriticalPair key s l]
forall l s key.
(Eq l, DecidableIso s) =>
OverlapMode -> [FixedRule key s l] -> [PreCriticalPair key s l]
preCriticalPairs OverlapMode
HypergraphOverlaps

-- | The rules returned by bounded convex completion. Supplied rules come
-- before learned rules. On success, redundant rules may be removed and
-- retained right sides may be simplified. All path contexts of the resulting
-- system rejoin.
type ConvexCompletion :: Kind -> Type -> Type
data ConvexCompletion s l
  = ConvexComplete [Rule s l] (ConvexRules s l)
  | ConvexIncomplete [Rule s l] (ConvexCompletionStop s l)

-- | Why completion stopped. Rule keys in witnesses are zero-based positions
-- in the returned rule list. 'Left' labels denote formal path boxes.
type ConvexCompletionStop :: Kind -> Type -> Type
data ConvexCompletionStop s l
  = ConvexRuleLimit (CriticalOverlap Int s l)
  | ConvexJoinLimit (CriticalOverlap Int s (Either Int l))
  | ConvexUnorientable String (CriticalOverlap Int s l)
  | ConvexContextFailure (CriticalOverlap Int s (Either Int l))

-- | Knuth–Bendix-style completion of a fixed string-diagram presentation,
-- bounded by the number of new rules and the search depth from each reduct.
-- On a failed join in the empty context, orient the two deterministic normal
-- forms using the supplied comparison. The caller supplies a well-founded order invariant
-- under isomorphism and preserved by contexts, and ensures the initial rules
-- decrease in that order.
-- Failures in formal path contexts are returned with their witnesses.
-- After success, use the other rules to remove redundant rules and simplify
-- right sides. Keep each change only when the resulting system passes the
-- path-context check within the same depth bound.
completeConvex
  :: forall s l
   . (Eq l, DecidableIso s)
  => Natural
  -> Natural
  -> (forall as bs. (Wires @s @l as ~> Wires @s @l bs) -> (Wires @s @l as ~> Wires @s @l bs) -> Ordering)
  -> [Rule s l]
  -> Either String (ConvexCompletion s l)
completeConvex :: forall s l.
(Eq l, DecidableIso s) =>
Natural
-> Natural
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> [Rule s l]
-> Either String (ConvexCompletion s l)
completeConvex Natural
maxRules Natural
maxDepth forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams [Rule s l]
initial = do
  patterns <- ((Int, Rule s l) -> Either String (FixedRule Int s l))
-> [(Int, Rule s l)] -> Either String [FixedRule Int s l]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (Int, Rule s l) -> Either String (FixedRule Int s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
fixedRule ([Int] -> [Rule s l] -> [(Int, Rule s l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [Rule s l]
initial)
  pure (go maxRules initial patterns)
  where
    go :: Natural
-> [Rule s l] -> [FixedRule Int s l] -> ConvexCompletion s l
go Natural
budget [Rule s l]
rules [FixedRule Int s l]
patterns =
      let compiled :: ConvexRules s l
compiled = (l -> l) -> [FixedRule Int s l] -> ConvexRules s l
forall l m key s.
(l -> m) -> [FixedRule key s l] -> ConvexRules s m
convexRulesWith l -> l
forall a. a -> a
id [FixedRule Int s l]
patterns
          pairs :: [PreCriticalPair Int s l]
pairs = OverlapMode -> [FixedRule Int s l] -> [PreCriticalPair Int s l]
forall l s key.
(Eq l, DecidableIso s) =>
OverlapMode -> [FixedRule key s l] -> [PreCriticalPair key s l]
preCriticalPairs (Bool -> OverlapMode
StringOverlaps Bool
True) [FixedRule Int s l]
patterns
          bare :: [PreCriticalPair Int s l]
bare =
            [ PreCriticalPair Int s l
pair
            | pair :: PreCriticalPair Int s l
pair@(Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box l Int]
boxes, DiagramStep Int s l
left, DiagramStep Int s l
right) <- [PreCriticalPair Int s l]
pairs
            , let edges :: IntMap [Int]
edges = [Box l Int] -> IntMap [Int]
forall l. [Box l Int] -> IntMap [Int]
wireEdges [Box l Int]
boxes
            , ((Int, Int) -> Bool) -> [(Int, Int)] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\(Int
o, Int
i) -> Int -> IntSet -> Bool
IS.notMember Int
i (IntMap [Int] -> Int -> IntSet
reachableNodes IntMap [Int]
edges Int
o)) (DiagramStep Int s l -> [(Int, Int)]
forall key s l. DiagramStep key s l -> [(Int, Int)]
forbiddenPaths DiagramStep Int s l
left [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]
forall a. [a] -> [a] -> [a]
++ DiagramStep Int s l -> [(Int, Int)]
forall key s l. DiagramStep key s l -> [(Int, Int)]
forbiddenPaths DiagramStep Int s l
right)
            ]
          incomplete :: ConvexCompletionStop s l -> ConvexCompletion s l
incomplete = [Rule s l] -> ConvexCompletionStop s l -> ConvexCompletion s l
forall s l.
[Rule s l] -> ConvexCompletionStop s l -> ConvexCompletion s l
ConvexIncomplete [Rule s l]
rules
          withMarkers :: (Graph s l, DiagramStep key s l, DiagramStep key s l)
-> CriticalOverlap key s (Either Int l)
withMarkers (Graph s l
host, DiagramStep key s l
left, DiagramStep key s l
right) = Graph s (Either Int l)
-> DiagramStep key s (Either Int l)
-> DiagramStep key s (Either Int l)
-> CriticalOverlap key s (Either Int l)
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap ((l -> Either Int l) -> Graph s l -> Graph s (Either Int l)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels l -> Either Int l
forall a b. b -> Either a b
Right Graph s l
host) (DiagramStep key s l -> DiagramStep key s (Either Int l)
forall key s l.
DiagramStep key s l -> DiagramStep key s (Either Int l)
liftStep DiagramStep key s l
left) (DiagramStep key s l -> DiagramStep key s (Either Int l)
forall key s l.
DiagramStep key s l -> DiagramStep key s (Either Int l)
liftStep DiagramStep key s l
right)
      in case Maybe Natural
-> (Graph s l -> [Graph s l])
-> [PreCriticalPair Int s l]
-> PairCheck Int s l
forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Graph s l])
-> [PreCriticalPair key s l]
-> PairCheck key s l
checkPairs (Natural -> Maybe Natural
forall a. a -> Maybe a
Just Natural
maxDepth) (ConvexRules s l -> Graph s l -> [Graph s l]
forall l s.
(Eq l, DecidableIso s) =>
ConvexRules s l -> Graph s l -> [Graph s l]
convexReducts ConvexRules s l
compiled) [PreCriticalPair Int s l]
bare of
           Unjoinable (Graph s l
host, DiagramStep Int s l
left, DiagramStep Int s l
right) ->
             let peak :: CriticalOverlap Int s l
peak = Graph s l
-> DiagramStep Int s l
-> DiagramStep Int s l
-> CriticalOverlap Int s l
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s l
host DiagramStep Int s l
left DiagramStep Int s l
right
             in if Natural
budget Natural -> Natural -> Bool
forall a. Eq a => a -> a -> Bool
== Natural
0
                  then ConvexCompletionStop s l -> ConvexCompletion s l
incomplete (CriticalOverlap Int s l -> ConvexCompletionStop s l
forall s l. CriticalOverlap Int s l -> ConvexCompletionStop s l
ConvexRuleLimit CriticalOverlap Int s l
peak)
                  else case Natural
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> (Graph s l -> [Prepared s l])
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs)
    -> (Wires as ~> Wires bs) -> Either String (Rule s l))
-> CriticalOverlap Int s l
-> Either String (Rule s l)
forall s l key.
Natural
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> (Graph s l -> [Prepared s l])
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs)
    -> (Wires as ~> Wires bs) -> Either String (Rule s l))
-> CriticalOverlap key s l
-> Either String (Rule s l)
orientPeak Natural
maxDepth (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams (ConvexRules s l -> Graph s l -> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
ConvexRules s l -> Graph s l -> [Prepared s l]
convexMatches ConvexRules s l
compiled) (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs) -> Either String (Rule s l)
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs)
-> (Wires as ~> Wires bs) -> Either String (Rule s l)
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> (a ~> b) -> Either String (Rule s l)
rule CriticalOverlap Int s l
peak of
                    Left String
err -> ConvexCompletionStop s l -> ConvexCompletion s l
incomplete (String -> CriticalOverlap Int s l -> ConvexCompletionStop s l
forall s l.
String -> CriticalOverlap Int s l -> ConvexCompletionStop s l
ConvexUnorientable String
err CriticalOverlap Int s l
peak)
                    Right Rule s l
newRule -> case (Int, Rule s l) -> Either String (FixedRule Int s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
fixedRule ([Rule s l] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Rule s l]
rules, Rule s l
newRule) of
                      Left String
err -> ConvexCompletionStop s l -> ConvexCompletion s l
incomplete (String -> CriticalOverlap Int s l -> ConvexCompletionStop s l
forall s l.
String -> CriticalOverlap Int s l -> ConvexCompletionStop s l
ConvexUnorientable String
err CriticalOverlap Int s l
peak)
                      Right FixedRule Int s l
pattern' -> Natural
-> [Rule s l] -> [FixedRule Int s l] -> ConvexCompletion s l
go (Natural
budget Natural -> Natural -> Natural
forall a. Num a => a -> a -> a
- Natural
1) ([Rule s l]
rules [Rule s l] -> [Rule s l] -> [Rule s l]
forall a. [a] -> [a] -> [a]
++ [Rule s l
newRule]) ([FixedRule Int s l]
patterns [FixedRule Int s l] -> [FixedRule Int s l] -> [FixedRule Int s l]
forall a. [a] -> [a] -> [a]
++ [FixedRule Int s l
pattern'])
           JoinLimit PreCriticalPair Int s l
pair -> ConvexCompletionStop s l -> ConvexCompletion s l
incomplete (CriticalOverlap Int s (Either Int l) -> ConvexCompletionStop s l
forall s l.
CriticalOverlap Int s (Either Int l) -> ConvexCompletionStop s l
ConvexJoinLimit (PreCriticalPair Int s l -> CriticalOverlap Int s (Either Int l)
forall {s} {l} {key}.
(Graph s l, DiagramStep key s l, DiagramStep key s l)
-> CriticalOverlap key s (Either Int l)
withMarkers PreCriticalPair Int s l
pair))
           AllJoinable Int
_ ->
             case Maybe Natural
-> [FixedRule Int s l]
-> [PreCriticalPair Int s l]
-> PairCheck Int s (Either Int l)
forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> [FixedRule key s l]
-> [PreCriticalPair key s l]
-> PairCheck key s (Either Int l)
checkContexts (Natural -> Maybe Natural
forall a. a -> Maybe a
Just Natural
maxDepth) [FixedRule Int s l]
patterns [PreCriticalPair Int s l]
pairs of
               AllJoinable Int
_ ->
                 let next :: [FixedRule key s l] -> Graph s l -> [Prepared s l]
next = ConvexRules s l -> Graph s l -> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
ConvexRules s l -> Graph s l -> [Prepared s l]
convexMatches (ConvexRules s l -> Graph s l -> [Prepared s l])
-> ([FixedRule key s l] -> ConvexRules s l)
-> [FixedRule key s l]
-> Graph s l
-> [Prepared s l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (l -> l) -> [FixedRule key s l] -> ConvexRules s l
forall l m key s.
(l -> m) -> [FixedRule key s l] -> ConvexRules s m
convexRulesWith l -> l
forall a. a -> a
id
                     check :: [FixedRule Int s l] -> PairCheck Int s (Either Int l)
check [FixedRule Int s l]
ps = Maybe Natural
-> [FixedRule Int s l]
-> [PreCriticalPair Int s l]
-> PairCheck Int s (Either Int l)
forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> [FixedRule key s l]
-> [PreCriticalPair key s l]
-> PairCheck key s (Either Int l)
checkContexts (Natural -> Maybe Natural
forall a. a -> Maybe a
Just Natural
maxDepth) [FixedRule Int s l]
ps (OverlapMode -> [FixedRule Int s l] -> [PreCriticalPair Int s l]
forall l s key.
(Eq l, DecidableIso s) =>
OverlapMode -> [FixedRule key s l] -> [PreCriticalPair key s l]
preCriticalPairs (Bool -> OverlapMode
StringOverlaps Bool
True) [FixedRule Int s l]
ps)
                     ([Rule s l]
remainingRules, [FixedRule Int s l]
remainingPatterns) = [(Rule s l, FixedRule Int s l)]
-> ([Rule s l], [FixedRule Int s l])
forall a b. [(a, b)] -> ([a], [b])
unzip (Natural
-> ([FixedRule Int s l] -> Graph s l -> [Prepared s l])
-> ([FixedRule Int s l] -> PairCheck Int s (Either Int l))
-> [(Rule s l, FixedRule Int s l)]
-> [(Rule s l, FixedRule Int s l)]
forall l s key m.
(Eq l, DecidableIso s) =>
Natural
-> ([FixedRule key s l] -> Graph s l -> [Prepared s l])
-> ([FixedRule key s l] -> PairCheck key s m)
-> [RuleEntry key s l]
-> [RuleEntry key s l]
interreduce Natural
maxDepth [FixedRule Int s l] -> Graph s l -> [Prepared s l]
forall {key}. [FixedRule key s l] -> Graph s l -> [Prepared s l]
next [FixedRule Int s l] -> PairCheck Int s (Either Int l)
check ([Rule s l]
-> [FixedRule Int s l] -> [(Rule s l, FixedRule Int s l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Rule s l]
rules [FixedRule Int s l]
patterns))
                 in [Rule s l] -> ConvexRules s l -> ConvexCompletion s l
forall s l. [Rule s l] -> ConvexRules s l -> ConvexCompletion s l
ConvexComplete [Rule s l]
remainingRules ((l -> l) -> [FixedRule Int s l] -> ConvexRules s l
forall l m key s.
(l -> m) -> [FixedRule key s l] -> ConvexRules s m
convexRulesWith l -> l
forall a. a -> a
id [FixedRule Int s l]
remainingPatterns)
               JoinLimit (Graph s (Either Int l)
host, DiagramStep Int s (Either Int l)
left, DiagramStep Int s (Either Int l)
right) -> ConvexCompletionStop s l -> ConvexCompletion s l
incomplete (CriticalOverlap Int s (Either Int l) -> ConvexCompletionStop s l
forall s l.
CriticalOverlap Int s (Either Int l) -> ConvexCompletionStop s l
ConvexJoinLimit (Graph s (Either Int l)
-> DiagramStep Int s (Either Int l)
-> DiagramStep Int s (Either Int l)
-> CriticalOverlap Int s (Either Int l)
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s (Either Int l)
host DiagramStep Int s (Either Int l)
left DiagramStep Int s (Either Int l)
right))
               Unjoinable (Graph s (Either Int l)
host, DiagramStep Int s (Either Int l)
left, DiagramStep Int s (Either Int l)
right) -> ConvexCompletionStop s l -> ConvexCompletion s l
incomplete (CriticalOverlap Int s (Either Int l) -> ConvexCompletionStop s l
forall s l.
CriticalOverlap Int s (Either Int l) -> ConvexCompletionStop s l
ConvexContextFailure (Graph s (Either Int l)
-> DiagramStep Int s (Either Int l)
-> DiagramStep Int s (Either Int l)
-> CriticalOverlap Int s (Either Int l)
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s (Either Int l)
host DiagramStep Int s (Either Int l)
left DiagramStep Int s (Either Int l)
right))

-- | The result of checking and completing the overlaps enumerated by
-- 'hypergraphOverlaps'. The rules are listed in input and discovery order,
-- with redundant rules removed and right sides simplified on success.
type HypergraphCompletion :: Kind -> Type -> Type
data HypergraphCompletion s l
  = HypergraphComplete [Rule s l] (CompiledRules Int s l)
  | HypergraphIncomplete [Rule s l] (HypergraphCompletionStop s l)

-- | The outstanding overlap when bounded hypergraph completion stops. Rule
-- keys are zero-based positions in the returned rule list.
type HypergraphCompletionStop :: Kind -> Type -> Type
data HypergraphCompletionStop s l
  = HypergraphRuleLimit (CriticalOverlap Int s l)
  | HypergraphJoinLimit (CriticalOverlap Int s l)
  | HypergraphUnorientable String (CriticalOverlap Int s l)

-- | Bounded Knuth–Bendix-style completion of fixed literal hypergraph rules.
-- The two bounds limit the number of learned rules and the search depth from
-- each reduct. As with 'completeConvex', the caller supplies a well-founded
-- comparison that decreases on rules and is preserved by contexts.
-- Success establishes local confluence for the resulting single-step system
-- by the same check as 'checkHypergraphConfluence'. After a successful join
-- check, remove redundant rules and simplify right sides using the other
-- rules. Each change must pass the overlap check within the same depth bound.
-- A learned rule with repeated left boundary nodes uses one port per shared
-- node when both sides identify the same ports and the factored rule still
-- decreases. Otherwise completion returns 'HypergraphUnorientable' with the
-- original overlap witness.
completeHypergraph
  :: forall s l
   . (Eq l, DecidableIso s)
  => Natural
  -> Natural
  -> (forall as bs. (Wires @s @l as ~> Wires @s @l bs) -> (Wires @s @l as ~> Wires @s @l bs) -> Ordering)
  -> [Rule s l]
  -> Either String (HypergraphCompletion s l)
completeHypergraph :: forall s l.
(Eq l, DecidableIso s) =>
Natural
-> Natural
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> [Rule s l]
-> Either String (HypergraphCompletion s l)
completeHypergraph Natural
maxRules Natural
maxDepth forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams [Rule s l]
initial = do
  patterns <- ((Int, Rule s l) -> Either String (FixedRule Int s l))
-> [(Int, Rule s l)] -> Either String [FixedRule Int s l]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (Int, Rule s l) -> Either String (FixedRule Int s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
literalRule ([Int] -> [Rule s l] -> [(Int, Rule s l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [Rule s l]
initial)
  go maxRules initial patterns
  where
    go :: Natural
-> [Rule s l]
-> [FixedRule Int s l]
-> Either String (HypergraphCompletion s l)
go Natural
budget [Rule s l]
rules [FixedRule Int s l]
patterns = do
      compiled <- [(Int, Rule s l)] -> Either String (CompiledRules Int s l)
forall key l s.
(Ord key, Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRules ([Int] -> [Rule s l] -> [(Int, Rule s l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] [Rule s l]
rules)
      let next = ((Int, Prepared s l) -> Prepared s l)
-> [(Int, Prepared s l)] -> [Prepared s l]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Prepared s l) -> Prepared s l
forall a b. (a, b) -> b
snd ([(Int, Prepared s l)] -> [Prepared s l])
-> (Graph s l -> [(Int, Prepared s l)])
-> Graph s l
-> [Prepared s l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CompiledRules Int s l -> Graph s l -> [(Int, Prepared s l)]
forall l s key.
(Eq l, DecidableIso s) =>
CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatches CompiledRules Int s l
compiled
          incomplete = HypergraphCompletion s l
-> Either String (HypergraphCompletion s l)
forall a b. b -> Either a b
Right (HypergraphCompletion s l
 -> Either String (HypergraphCompletion s l))
-> (HypergraphCompletionStop s l -> HypergraphCompletion s l)
-> HypergraphCompletionStop s l
-> Either String (HypergraphCompletion s l)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Rule s l]
-> HypergraphCompletionStop s l -> HypergraphCompletion s l
forall s l.
[Rule s l]
-> HypergraphCompletionStop s l -> HypergraphCompletion s l
HypergraphIncomplete [Rule s l]
rules
      case checkHypergraphPairs (Just maxDepth) next patterns of
        AllJoinable Int
_ -> do
          let rewritesFor :: [FixedRule key s l] -> Graph s l -> [Prepared s l]
rewritesFor = [(Graph s (LabelTest l), Graph s l)] -> Graph s l -> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
[(Graph s (LabelTest l), Graph s l)] -> Graph s l -> [Prepared s l]
fixedMatches ([(Graph s (LabelTest l), Graph s l)]
 -> Graph s l -> [Prepared s l])
-> ([FixedRule key s l] -> [(Graph s (LabelTest l), Graph s l)])
-> [FixedRule key s l]
-> Graph s l
-> [Prepared s l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (l -> l)
-> [FixedRule key s l] -> [(Graph s (LabelTest l), Graph s l)]
forall l m key s.
(l -> m)
-> [FixedRule key s l] -> [(Graph s (LabelTest m), Graph s m)]
fixedPatterns l -> l
forall a. a -> a
id
              check :: [FixedRule Int s l] -> PairCheck Int s l
check [FixedRule Int s l]
ps = Maybe Natural
-> (Graph s l -> [Prepared s l])
-> [FixedRule Int s l]
-> PairCheck Int s l
forall l s key.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Prepared s l])
-> [FixedRule key s l]
-> PairCheck key s l
checkHypergraphPairs (Natural -> Maybe Natural
forall a. a -> Maybe a
Just Natural
maxDepth) ([FixedRule Int s l] -> Graph s l -> [Prepared s l]
forall {key}. [FixedRule key s l] -> Graph s l -> [Prepared s l]
rewritesFor [FixedRule Int s l]
ps) [FixedRule Int s l]
ps
              retained :: [Rule s l]
retained = ((Rule s l, FixedRule Int s l) -> Rule s l)
-> [(Rule s l, FixedRule Int s l)] -> [Rule s l]
forall a b. (a -> b) -> [a] -> [b]
map (Rule s l, FixedRule Int s l) -> Rule s l
forall a b. (a, b) -> a
fst (Natural
-> ([FixedRule Int s l] -> Graph s l -> [Prepared s l])
-> ([FixedRule Int s l] -> PairCheck Int s l)
-> [(Rule s l, FixedRule Int s l)]
-> [(Rule s l, FixedRule Int s l)]
forall l s key m.
(Eq l, DecidableIso s) =>
Natural
-> ([FixedRule key s l] -> Graph s l -> [Prepared s l])
-> ([FixedRule key s l] -> PairCheck key s m)
-> [RuleEntry key s l]
-> [RuleEntry key s l]
interreduce Natural
maxDepth [FixedRule Int s l] -> Graph s l -> [Prepared s l]
forall {key}. [FixedRule key s l] -> Graph s l -> [Prepared s l]
rewritesFor [FixedRule Int s l] -> PairCheck Int s l
check ([Rule s l]
-> [FixedRule Int s l] -> [(Rule s l, FixedRule Int s l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Rule s l]
rules [FixedRule Int s l]
patterns))
          [Rule s l] -> CompiledRules Int s l -> HypergraphCompletion s l
forall s l.
[Rule s l] -> CompiledRules Int s l -> HypergraphCompletion s l
HypergraphComplete [Rule s l]
retained (CompiledRules Int s l -> HypergraphCompletion s l)
-> Either String (CompiledRules Int s l)
-> Either String (HypergraphCompletion s l)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> [(Int, Rule s l)] -> Either String (CompiledRules Int s l)
forall key l s.
(Ord key, Eq l, DecidableIso s) =>
[(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRules ([Int] -> [Rule s l] -> [(Int, Rule s l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [Rule s l]
retained)
        JoinLimit (Graph s l
host, DiagramStep Int s l
left, DiagramStep Int s l
right) -> HypergraphCompletionStop s l
-> Either String (HypergraphCompletion s l)
incomplete (CriticalOverlap Int s l -> HypergraphCompletionStop s l
forall s l. CriticalOverlap Int s l -> HypergraphCompletionStop s l
HypergraphJoinLimit (Graph s l
-> DiagramStep Int s l
-> DiagramStep Int s l
-> CriticalOverlap Int s l
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s l
host DiagramStep Int s l
left DiagramStep Int s l
right))
        Unjoinable (Graph s l
host, DiagramStep Int s l
left, DiagramStep Int s l
right) ->
          let peak :: CriticalOverlap Int s l
peak = Graph s l
-> DiagramStep Int s l
-> DiagramStep Int s l
-> CriticalOverlap Int s l
forall key s l.
Graph s l
-> DiagramStep key s l
-> DiagramStep key s l
-> CriticalOverlap key s l
renderOverlap Graph s l
host DiagramStep Int s l
left DiagramStep Int s l
right
          in if Natural
budget Natural -> Natural -> Bool
forall a. Eq a => a -> a -> Bool
== Natural
0
               then HypergraphCompletionStop s l
-> Either String (HypergraphCompletion s l)
incomplete (CriticalOverlap Int s l -> HypergraphCompletionStop s l
forall s l. CriticalOverlap Int s l -> HypergraphCompletionStop s l
HypergraphRuleLimit CriticalOverlap Int s l
peak)
               else case Natural
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> (Graph s l -> [Prepared s l])
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs)
    -> (Wires as ~> Wires bs) -> Either String (Rule s l))
-> CriticalOverlap Int s l
-> Either String (Rule s l)
forall s l key.
Natural
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> (Graph s l -> [Prepared s l])
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs)
    -> (Wires as ~> Wires bs) -> Either String (Rule s l))
-> CriticalOverlap key s l
-> Either String (Rule s l)
orientPeak Natural
maxDepth (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams Graph s l -> [Prepared s l]
next ((forall (as :: [s]) (bs :: [s]).
 (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> (DC (SUB (FH (Port as))) ~> DC (SUB (FH (Port bs))))
-> (DC (SUB (FH (Port as))) ~> DC (SUB (FH (Port bs))))
-> Either String (Rule s l)
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(forall (as :: [s]) (bs :: [s]).
 (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> (a ~> b) -> (a ~> b) -> Either String (Rule s l)
factorBoundaryRule (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams) CriticalOverlap Int s l
peak of
                 Left String
err -> HypergraphCompletionStop s l
-> Either String (HypergraphCompletion s l)
incomplete (String -> CriticalOverlap Int s l -> HypergraphCompletionStop s l
forall s l.
String -> CriticalOverlap Int s l -> HypergraphCompletionStop s l
HypergraphUnorientable String
err CriticalOverlap Int s l
peak)
                 Right Rule s l
newRule -> do
                   pattern' <- (Int, Rule s l) -> Either String (FixedRule Int s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
literalRule ([Rule s l] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Rule s l]
rules, Rule s l
newRule)
                   go (budget - 1) (rules ++ [newRule]) (patterns ++ [pattern'])

factorBoundaryRule
  :: (forall as bs. Wires @s @l as ~> Wires @s @l bs -> Wires @s @l as ~> Wires @s @l bs -> Ordering)
  -> (a :: OPENHG s l) ~> b
  -> a ~> b
  -> Either String (Rule s l)
factorBoundaryRule :: forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(forall (as :: [s]) (bs :: [s]).
 (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> (a ~> b) -> (a ~> b) -> Either String (Rule s l)
factorBoundaryRule forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams a ~> b
lhs a ~> b
rhs
  | [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
leftPorts Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
leftCount = (a ~> b) -> (a ~> b) -> Either String (Rule s l)
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> (a ~> b) -> Either String (Rule s l)
rule a ~> b
lhs a ~> b
rhs
  | [(Int, Int)] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [(Int, Int)]
pairs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
leftCount Bool -> Bool -> Bool
|| [(Int, Int)] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [(Int, Int)]
pairs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= IntSet -> Int
IS.size ([Int] -> IntSet
IS.fromList [Int]
rightPorts) =
      String -> Either String (Rule s l)
forall a b. a -> Either a b
Left String
"completion: the reducts identify different boundary ports"
  | Bool
otherwise = Graph s l
-> (forall (as :: [s]) (bs :: [s]).
    (Graph s l -> Wires as ~> Wires bs) -> Either String (Rule s l))
-> Either String (Rule s l)
forall s l r.
Graph s l
-> (forall (as :: [s]) (bs :: [s]).
    (Graph s l -> Wires as ~> Wires bs) -> r)
-> r
withDiagramBoundary Graph s l
left' \Graph s l -> Wires as ~> Wires bs
render ->
      let l :: Wires as ~> Wires bs
l = Graph s l -> Wires as ~> Wires bs
render Graph s l
left'
          r :: Wires as ~> Wires bs
r = Graph s l -> Wires as ~> Wires bs
render Graph s l
right'
      in if (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams Wires as ~> Wires bs
l Wires as ~> Wires bs
r Ordering -> Ordering -> Bool
forall a. Eq a => a -> a -> Bool
== Ordering
GT
           then (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs) -> Either String (Rule s l)
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> (a ~> b) -> Either String (Rule s l)
rule Wires as ~> Wires bs
l Wires as ~> Wires bs
r
           else String -> Either String (Rule s l)
forall a b. a -> Either a b
Left String
"completion: the factored rule does not decrease"
  where
    Graph [SomeSort s]
ls [Int]
li [Int]
lo [Box l Int]
lb = (a ~> b) -> Graph s l
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph a ~> b
lhs
    Graph [SomeSort s]
rs [Int]
ri [Int]
ro [Box l Int]
rb = (a ~> b) -> Graph s l
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph a ~> b
rhs
    leftPorts :: [Int]
leftPorts = [Int]
li [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
lo
    rightPorts :: [Int]
rightPorts = [Int]
ri [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
ro
    leftCount :: Int
leftCount = IntSet -> Int
IS.size ([Int] -> IntSet
IS.fromList [Int]
leftPorts)
    pairs :: [(Int, Int)]
pairs = [(Int, Int)] -> [(Int, Int)]
forall a. Ord a => [a] -> [a]
nubOrd ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
leftPorts [Int]
rightPorts)
    ([(Int, Int)]
ins, [(Int, Int)]
outs) = Int -> [(Int, Int)] -> ([(Int, Int)], [(Int, Int)])
forall a. Int -> [a] -> ([a], [a])
splitAt ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length ([Int] -> [Int]
forall a. Ord a => [a] -> [a]
nubOrd [Int]
li)) [(Int, Int)]
pairs
    left' :: Graph s l
left' = [SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph [SomeSort s]
ls (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> a
fst [(Int, Int)]
ins) (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> a
fst [(Int, Int)]
outs) [Box l Int]
lb
    right' :: Graph s l
right' = [SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph [SomeSort s]
rs (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> b
snd [(Int, Int)]
ins) (((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> b
snd [(Int, Int)]
outs) [Box l Int]
rb

orientPeak
  :: Natural
  -> (forall as bs. (Wires @s @l as ~> Wires @s @l bs) -> (Wires @s @l as ~> Wires @s @l bs) -> Ordering)
  -> (Graph s l -> [Prepared s l])
  -> (forall as bs. (Wires @s @l as ~> Wires @s @l bs) -> (Wires @s @l as ~> Wires @s @l bs) -> Either String (Rule s l))
  -> CriticalOverlap key s l
  -> Either String (Rule s l)
orientPeak :: forall s l key.
Natural
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering)
-> (Graph s l -> [Prepared s l])
-> (forall (as :: [s]) (bs :: [s]).
    (Wires as ~> Wires bs)
    -> (Wires as ~> Wires bs) -> Either String (Rule s l))
-> CriticalOverlap key s l
-> Either String (Rule s l)
orientPeak Natural
maxDepth forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams Graph s l -> [Prepared s l]
next forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs)
-> (Wires as ~> Wires bs) -> Either String (Rule s l)
makeRule (CriticalOverlap key
_ key
_ Wires as ~> Wires bs
_ Wires as ~> Wires bs
left Wires as ~> Wires bs
right) =
  let limits :: RewriteLimits
limits = Maybe Natural -> Maybe Natural -> RewriteLimits
RewriteLimits (Natural -> Maybe Natural
forall a. a -> Maybe a
Just Natural
maxDepth) Maybe Natural
forall a. Maybe a
Nothing
      l :: NormalisationResult (Wires as ~> Wires bs)
l = RewriteLimits
-> (Graph s l -> [Prepared s l])
-> (Wires as ~> Wires bs)
-> NormalisationResult (Wires as ~> Wires bs)
forall {s} l (as :: [s]) (bs :: [s]).
RewriteLimits
-> (Graph s l -> [Prepared s l])
-> (Wires as ~> Wires bs)
-> NormalisationResult (Wires as ~> Wires bs)
normaliseBy RewriteLimits
limits (Int -> [Prepared s l] -> [Prepared s l]
forall a. Int -> [a] -> [a]
take Int
1 ([Prepared s l] -> [Prepared s l])
-> (Graph s l -> [Prepared s l]) -> Graph s l -> [Prepared s l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Graph s l -> [Prepared s l]
next) Wires as ~> Wires bs
left
      r :: NormalisationResult (Wires as ~> Wires bs)
r = RewriteLimits
-> (Graph s l -> [Prepared s l])
-> (Wires as ~> Wires bs)
-> NormalisationResult (Wires as ~> Wires bs)
forall {s} l (as :: [s]) (bs :: [s]).
RewriteLimits
-> (Graph s l -> [Prepared s l])
-> (Wires as ~> Wires bs)
-> NormalisationResult (Wires as ~> Wires bs)
normaliseBy RewriteLimits
limits (Int -> [Prepared s l] -> [Prepared s l]
forall a. Int -> [a] -> [a]
take Int
1 ([Prepared s l] -> [Prepared s l])
-> (Graph s l -> [Prepared s l]) -> Graph s l -> [Prepared s l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Graph s l -> [Prepared s l]
next) Wires as ~> Wires bs
right
      ln :: DecCospan (Wires as) (Wires bs)
ln = NormalisationResult (DecCospan (Wires as) (Wires bs))
-> DecCospan (Wires as) (Wires bs)
forall a. NormalisationResult a -> a
normalisedGraph NormalisationResult (Wires as ~> Wires bs)
NormalisationResult (DecCospan (Wires as) (Wires bs))
l
      rn :: DecCospan (Wires as) (Wires bs)
rn = NormalisationResult (DecCospan (Wires as) (Wires bs))
-> DecCospan (Wires as) (Wires bs)
forall a. NormalisationResult a -> a
normalisedGraph NormalisationResult (Wires as ~> Wires bs)
NormalisationResult (DecCospan (Wires as) (Wires bs))
r
  in if NormalisationResult (DecCospan (Wires as) (Wires bs))
-> NormalisationStatus
forall a. NormalisationResult a -> NormalisationStatus
normalisationStatus NormalisationResult (Wires as ~> Wires bs)
NormalisationResult (DecCospan (Wires as) (Wires bs))
l NormalisationStatus -> NormalisationStatus -> Bool
forall a. Eq a => a -> a -> Bool
/= NormalisationStatus
NormalForm Bool -> Bool -> Bool
|| NormalisationResult (DecCospan (Wires as) (Wires bs))
-> NormalisationStatus
forall a. NormalisationResult a -> NormalisationStatus
normalisationStatus NormalisationResult (Wires as ~> Wires bs)
NormalisationResult (DecCospan (Wires as) (Wires bs))
r NormalisationStatus -> NormalisationStatus -> Bool
forall a. Eq a => a -> a -> Bool
/= NormalisationStatus
NormalForm
       then String -> Either String (Rule s l)
forall a b. a -> Either a b
Left String
"could not normalise both reducts within the depth limit"
       else case (Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs) -> (Wires as ~> Wires bs) -> Ordering
compareDiagrams Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
ln Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
rn of
         Ordering
LT -> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs) -> Either String (Rule s l)
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs)
-> (Wires as ~> Wires bs) -> Either String (Rule s l)
makeRule Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
rn Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
ln
         Ordering
GT -> (Wires as ~> Wires bs)
-> (Wires as ~> Wires bs) -> Either String (Rule s l)
forall (as :: [s]) (bs :: [s]).
(Wires as ~> Wires bs)
-> (Wires as ~> Wires bs) -> Either String (Rule s l)
makeRule Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
ln Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
rn
         Ordering
EQ -> String -> Either String (Rule s l)
forall a b. a -> Either a b
Left String
"the comparison did not orient the equation"

type RuleEntry key s l = (Rule s l, FixedRule key s l)

interreduce
  :: (Eq l, DecidableIso s)
  => Natural
  -> ([FixedRule key s l] -> Graph s l -> [Prepared s l])
  -> ([FixedRule key s l] -> PairCheck key s m)
  -> [RuleEntry key s l]
  -> [RuleEntry key s l]
interreduce :: forall l s key m.
(Eq l, DecidableIso s) =>
Natural
-> ([FixedRule key s l] -> Graph s l -> [Prepared s l])
-> ([FixedRule key s l] -> PairCheck key s m)
-> [RuleEntry key s l]
-> [RuleEntry key s l]
interreduce Natural
depth [FixedRule key s l] -> Graph s l -> [Prepared s l]
next [FixedRule key s l] -> PairCheck key s m
check = [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
simplifyRightSides [] ([(Rule s l, FixedRule key s l)]
 -> [(Rule s l, FixedRule key s l)])
-> ([(Rule s l, FixedRule key s l)]
    -> [(Rule s l, FixedRule key s l)])
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
pruneRules []
  where
    bound :: Maybe Natural
bound = Natural -> Maybe Natural
forall a. a -> Maybe a
Just Natural
depth
    pruneRules :: [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
pruneRules [(Rule s l, FixedRule key s l)]
kept [] = [(Rule s l, FixedRule key s l)] -> [(Rule s l, FixedRule key s l)]
forall a. [a] -> [a]
reverse [(Rule s l, FixedRule key s l)]
kept
    pruneRules [(Rule s l, FixedRule key s l)]
kept (candidate :: (Rule s l, FixedRule key s l)
candidate@(Rule s l
_, (key
_, Graph s l
lhs, Graph s l
rhs)) : [(Rule s l, FixedRule key s l)]
pending)
      | Just Bool
True <- Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
forall l s.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
joinGraphs Maybe Natural
bound ((Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
forall s l.
(Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
singleReducts ([FixedRule key s l] -> Graph s l -> [Prepared s l]
next [FixedRule key s l]
patterns)) Graph s l
lhs Graph s l
rhs
      , AllJoinable Int
_ <- [FixedRule key s l] -> PairCheck key s m
check [FixedRule key s l]
patterns =
          [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
pruneRules [] [(Rule s l, FixedRule key s l)]
remaining
      | Bool
otherwise = [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
pruneRules ((Rule s l, FixedRule key s l)
candidate (Rule s l, FixedRule key s l)
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
forall a. a -> [a] -> [a]
: [(Rule s l, FixedRule key s l)]
kept) [(Rule s l, FixedRule key s l)]
pending
      where
        remaining :: [(Rule s l, FixedRule key s l)]
remaining = [(Rule s l, FixedRule key s l)] -> [(Rule s l, FixedRule key s l)]
forall a. [a] -> [a]
reverse [(Rule s l, FixedRule key s l)]
kept [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
forall a. [a] -> [a] -> [a]
++ [(Rule s l, FixedRule key s l)]
pending
        patterns :: [FixedRule key s l]
patterns = ((Rule s l, FixedRule key s l) -> FixedRule key s l)
-> [(Rule s l, FixedRule key s l)] -> [FixedRule key s l]
forall a b. (a -> b) -> [a] -> [b]
map (Rule s l, FixedRule key s l) -> FixedRule key s l
forall a b. (a, b) -> b
snd [(Rule s l, FixedRule key s l)]
remaining

    simplifyRightSides :: [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
simplifyRightSides [(Rule s l, FixedRule key s l)]
kept [] = [(Rule s l, FixedRule key s l)] -> [(Rule s l, FixedRule key s l)]
forall a. [a] -> [a]
reverse [(Rule s l, FixedRule key s l)]
kept
    simplifyRightSides [(Rule s l, FixedRule key s l)]
kept (candidate :: (Rule s l, FixedRule key s l)
candidate@(Rule s l
_, (key
key, Graph s l
lhs, Graph s l
rhs)) : [(Rule s l, FixedRule key s l)]
pending) =
      [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
simplifyRightSides ((Rule s l, FixedRule key s l)
chosen (Rule s l, FixedRule key s l)
-> [(Rule s l, FixedRule key s l)]
-> [(Rule s l, FixedRule key s l)]
forall a. a -> [a] -> [a]
: [(Rule s l, FixedRule key s l)]
kept) [(Rule s l, FixedRule key s l)]
pending
      where
        before :: [FixedRule key s l]
before = ((Rule s l, FixedRule key s l) -> FixedRule key s l)
-> [(Rule s l, FixedRule key s l)] -> [FixedRule key s l]
forall a b. (a -> b) -> [a] -> [b]
map (Rule s l, FixedRule key s l) -> FixedRule key s l
forall a b. (a, b) -> b
snd ([(Rule s l, FixedRule key s l)] -> [(Rule s l, FixedRule key s l)]
forall a. [a] -> [a]
reverse [(Rule s l, FixedRule key s l)]
kept)
        after :: [FixedRule key s l]
after = ((Rule s l, FixedRule key s l) -> FixedRule key s l)
-> [(Rule s l, FixedRule key s l)] -> [FixedRule key s l]
forall a b. (a -> b) -> [a] -> [b]
map (Rule s l, FixedRule key s l) -> FixedRule key s l
forall a b. (a, b) -> b
snd [(Rule s l, FixedRule key s l)]
pending
        result :: NormalisationResult (Graph s l)
result = RewriteLimits
-> (Graph s l -> [Prepared s l])
-> Graph s l
-> NormalisationResult (Graph s l)
forall s l.
RewriteLimits
-> (Graph s l -> [Prepared s l])
-> Graph s l
-> NormalisationResult (Graph s l)
normaliseGraphBy (Maybe Natural -> Maybe Natural -> RewriteLimits
RewriteLimits Maybe Natural
bound Maybe Natural
forall a. Maybe a
Nothing) (Int -> [Prepared s l] -> [Prepared s l]
forall a. Int -> [a] -> [a]
take Int
1 ([Prepared s l] -> [Prepared s l])
-> (Graph s l -> [Prepared s l]) -> Graph s l -> [Prepared s l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [FixedRule key s l] -> Graph s l -> [Prepared s l]
next ([FixedRule key s l]
before [FixedRule key s l] -> [FixedRule key s l] -> [FixedRule key s l]
forall a. [a] -> [a] -> [a]
++ [FixedRule key s l]
after)) Graph s l
rhs
        reduced :: Graph s l
reduced = NormalisationResult (Graph s l) -> Graph s l
forall a. NormalisationResult a -> a
normalisedGraph NormalisationResult (Graph s l)
result
        replacement :: FixedRule key s l
replacement = (key
key, Graph s l
lhs, Graph s l
reduced)
        patterns :: [FixedRule key s l]
patterns = [FixedRule key s l]
before [FixedRule key s l] -> [FixedRule key s l] -> [FixedRule key s l]
forall a. [a] -> [a] -> [a]
++ FixedRule key s l
replacement FixedRule key s l -> [FixedRule key s l] -> [FixedRule key s l]
forall a. a -> [a] -> [a]
: [FixedRule key s l]
after
        chosen :: (Rule s l, FixedRule key s l)
chosen
          | NormalisationResult (Graph s l) -> NormalisationStatus
forall a. NormalisationResult a -> NormalisationStatus
normalisationStatus NormalisationResult (Graph s l)
result NormalisationStatus -> NormalisationStatus -> Bool
forall a. Eq a => a -> a -> Bool
== NormalisationStatus
NormalForm
          , NormalisationResult (Graph s l) -> Natural
forall a. NormalisationResult a -> Natural
normalisationRewrites NormalisationResult (Graph s l)
result Natural -> Natural -> Bool
forall a. Ord a => a -> a -> Bool
> Natural
0
          , AllJoinable Int
_ <- [FixedRule key s l] -> PairCheck key s m
check [FixedRule key s l]
patterns =
              (Graph s (LabelTest l) -> ([l] -> Maybe (Graph s l)) -> Rule s l
forall s l.
Graph s (LabelTest l) -> ([l] -> Maybe (Graph s l)) -> Rule s l
Rule ((l -> LabelTest l) -> Graph s l -> Graph s (LabelTest l)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels l -> LabelTest l
forall l. l -> LabelTest l
ExactLabel Graph s l
lhs) (Maybe (Graph s l) -> [l] -> Maybe (Graph s l)
forall a b. a -> b -> a
const (Graph s l -> Maybe (Graph s l)
forall a. a -> Maybe a
Just Graph s l
reduced)), FixedRule key s l
replacement)
          | Bool
otherwise = (Rule s l, FixedRule key s l)
candidate

-- In a monogamous acyclic diagram, a path can leave and re-enter a match
-- only through an output and an input of its left side.
forbiddenPaths :: DiagramStep key s l -> [(Int, Int)]
forbiddenPaths :: forall key s l. DiagramStep key s l -> [(Int, Int)]
forbiddenPaths (key
_, Graph [SomeSort s]
_ [Int]
ins [Int]
outs [Box l Int]
_, Graph s l
_, (IntMap Int
mapping, IntSet
_)) =
  [(IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
o, IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
i) | Int
o <- [Int]
outs, Int
i <- [Int]
ins]

-- | Validated fixed rules for convex string-diagram rewriting.
type ConvexRules :: Kind -> Type -> Type
newtype ConvexRules s l = ConvexRules [(Graph s (LabelTest l), Graph s l)]

-- | Validate fixed rules with monogamous acyclic sides. Rule order determines
-- which match 'normaliseConvex' takes when several are available.
compileConvexRules :: [Rule s l] -> Either String (ConvexRules s l)
compileConvexRules :: forall s l. [Rule s l] -> Either String (ConvexRules s l)
compileConvexRules [Rule s l]
rules = (l -> l) -> [FixedRule () s l] -> ConvexRules s l
forall l m key s.
(l -> m) -> [FixedRule key s l] -> ConvexRules s m
convexRulesWith l -> l
forall a. a -> a
id ([FixedRule () s l] -> ConvexRules s l)
-> Either String [FixedRule () s l]
-> Either String (ConvexRules s l)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Rule s l -> Either String (FixedRule () s l))
-> [Rule s l] -> Either String [FixedRule () s l]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (((), Rule s l) -> Either String (FixedRule () s l)
forall key s l.
(key, Rule s l) -> Either String (FixedRule key s l)
fixedRule (((), Rule s l) -> Either String (FixedRule () s l))
-> (Rule s l -> ((), Rule s l))
-> Rule s l
-> Either String (FixedRule () s l)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((),)) [Rule s l]
rules

convexRulesWith :: (l -> m) -> [FixedRule key s l] -> ConvexRules s m
convexRulesWith :: forall l m key s.
(l -> m) -> [FixedRule key s l] -> ConvexRules s m
convexRulesWith l -> m
wrap = [(Graph s (LabelTest m), Graph s m)] -> ConvexRules s m
forall s l. [(Graph s (LabelTest l), Graph s l)] -> ConvexRules s l
ConvexRules ([(Graph s (LabelTest m), Graph s m)] -> ConvexRules s m)
-> ([FixedRule key s l] -> [(Graph s (LabelTest m), Graph s m)])
-> [FixedRule key s l]
-> ConvexRules s m
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (l -> m)
-> [FixedRule key s l] -> [(Graph s (LabelTest m), Graph s m)]
forall l m key s.
(l -> m)
-> [FixedRule key s l] -> [(Graph s (LabelTest m), Graph s m)]
fixedPatterns l -> m
wrap

fixedPatterns :: (l -> m) -> [FixedRule key s l] -> [(Graph s (LabelTest m), Graph s m)]
fixedPatterns :: forall l m key s.
(l -> m)
-> [FixedRule key s l] -> [(Graph s (LabelTest m), Graph s m)]
fixedPatterns l -> m
wrap [FixedRule key s l]
patterns =
  [((l -> LabelTest m) -> Graph s l -> Graph s (LabelTest m)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels (m -> LabelTest m
forall l. l -> LabelTest l
ExactLabel (m -> LabelTest m) -> (l -> m) -> l -> LabelTest m
forall b c a. (b -> c) -> (a -> b) -> a -> c
. l -> m
wrap) Graph s l
lhs, (l -> m) -> Graph s l -> Graph s m
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels l -> m
wrap Graph s l
rhs) | (key
_, Graph s l
lhs, Graph s l
rhs) <- [FixedRule key s l]
patterns]

convexReducts :: (Eq l, DecidableIso s) => ConvexRules s l -> Graph s l -> [Graph s l]
convexReducts :: forall l s.
(Eq l, DecidableIso s) =>
ConvexRules s l -> Graph s l -> [Graph s l]
convexReducts ConvexRules s l
rules = (Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
forall s l.
(Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
singleReducts (ConvexRules s l -> Graph s l -> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
ConvexRules s l -> Graph s l -> [Prepared s l]
convexMatches ConvexRules s l
rules)

singleReducts :: (Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
singleReducts :: forall s l.
(Graph s l -> [Prepared s l]) -> Graph s l -> [Graph s l]
singleReducts Graph s l -> [Prepared s l]
next Graph s l
host =
  [Graph s (LabelTest l)
-> Graph s l -> Graph s l -> [Match] -> Graph s l
forall s p l.
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
host [Match
match] | (Graph s (LabelTest l)
lhs, Graph s l
rhs, Match
match) <- Graph s l -> [Prepared s l]
next Graph s l
host]

convexMatches :: (Eq l, DecidableIso s) => ConvexRules s l -> Graph s l -> [Prepared s l]
convexMatches :: forall l s.
(Eq l, DecidableIso s) =>
ConvexRules s l -> Graph s l -> [Prepared s l]
convexMatches (ConvexRules [(Graph s (LabelTest l), Graph s l)]
rules) host :: Graph s l
host@(Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box l Int]
bs) =
  [ (Graph s (LabelTest l)
lhs, Graph s l
rhs, Match
match)
  | (lhs :: Graph s (LabelTest l)
lhs@(Graph [SomeSort s]
_ [Int]
ins [Int]
outs [Box (LabelTest l) Int]
_), Graph s l
rhs, match :: Match
match@(IntMap Int
mapping, IntSet
_)) <- [(Graph s (LabelTest l), Graph s l)] -> Graph s l -> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
[(Graph s (LabelTest l), Graph s l)] -> Graph s l -> [Prepared s l]
fixedMatches [(Graph s (LabelTest l), Graph s l)]
rules Graph s l
host
  , (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all
      ( \Int
o ->
          let reachable :: IntSet
reachable = IntMap [Int] -> Int -> IntSet
reachableNodes IntMap [Int]
edges (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
o)
          in (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\Int
i -> Int -> IntSet -> Bool
IS.notMember (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
i) IntSet
reachable) [Int]
ins
      )
      [Int]
outs
  ]
  where
    edges :: IntMap [Int]
edges = [Box l Int] -> IntMap [Int]
forall l. [Box l Int] -> IntMap [Int]
wireEdges [Box l Int]
bs

fixedMatches
  :: (Eq l, DecidableIso s) => [(Graph s (LabelTest l), Graph s l)] -> Graph s l -> [Prepared s l]
fixedMatches :: forall l s.
(Eq l, DecidableIso s) =>
[(Graph s (LabelTest l), Graph s l)] -> Graph s l -> [Prepared s l]
fixedMatches [(Graph s (LabelTest l), Graph s l)]
rules Graph s l
host =
  [(Graph s (LabelTest l)
lhs, Graph s l
rhs, Match
match) | (Graph s (LabelTest l)
lhs, Graph s l
rhs) <- [(Graph s (LabelTest l), Graph s l)]
rules, (Match
match, [l]
_) <- Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
forall l s.
(Eq l, DecidableIso s) =>
Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matches Graph s (LabelTest l)
lhs Graph s l
host]

-- Search by depth on both sides. A failed join requires exhausting both
-- descendant sets. The seen sets also make finite cyclic searches terminate.
joinGraphs
  :: (Eq l, DecidableIso s)
  => Maybe Natural -> (Graph s l -> [Graph s l]) -> Graph s l -> Graph s l -> Maybe Bool
joinGraphs :: forall l s.
(Eq l, DecidableIso s) =>
Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
joinGraphs = (Graph s l -> Graph s l -> Bool)
-> Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
forall l s.
(Eq l, DecidableIso s) =>
(Graph s l -> Graph s l -> Bool)
-> Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
joinGraphsWith Graph s l -> Graph s l -> Bool
forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph

joinGraphsWith
  :: (Eq l, DecidableIso s)
  => (Graph s l -> Graph s l -> Bool)
  -> Maybe Natural
  -> (Graph s l -> [Graph s l])
  -> Graph s l
  -> Graph s l
  -> Maybe Bool
joinGraphsWith :: forall l s.
(Eq l, DecidableIso s) =>
(Graph s l -> Graph s l -> Bool)
-> Maybe Natural
-> (Graph s l -> [Graph s l])
-> Graph s l
-> Graph s l
-> Maybe Bool
joinGraphsWith Graph s l -> Graph s l -> Bool
equivalent Maybe Natural
maxDepth Graph s l -> [Graph s l]
next Graph s l
left Graph s l
right = Maybe Natural
-> [Graph s l]
-> [Graph s l]
-> [Graph s l]
-> [Graph s l]
-> Maybe Bool
search Maybe Natural
maxDepth [] [Graph s l
left] [] [Graph s l
right]
  where
    search :: Maybe Natural
-> [Graph s l]
-> [Graph s l]
-> [Graph s l]
-> [Graph s l]
-> Maybe Bool
search Maybe Natural
depth [Graph s l]
seenL [Graph s l]
frontL [Graph s l]
seenR [Graph s l]
frontR
      | (Graph s l -> Bool) -> [Graph s l] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (\Graph s l
g -> (Graph s l -> Bool) -> [Graph s l] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (Graph s l -> Graph s l -> Bool
equivalent Graph s l
g) ([Graph s l]
frontR [Graph s l] -> [Graph s l] -> [Graph s l]
forall a. [a] -> [a] -> [a]
++ [Graph s l]
seenR)) [Graph s l]
frontL
          Bool -> Bool -> Bool
|| (Graph s l -> Bool) -> [Graph s l] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (\Graph s l
g -> (Graph s l -> Bool) -> [Graph s l] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (Graph s l -> Graph s l -> Bool
equivalent Graph s l
g) [Graph s l]
seenL) [Graph s l]
frontR =
          Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
True
      | [Graph s l] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [Graph s l]
frontL Bool -> Bool -> Bool
&& [Graph s l] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [Graph s l]
frontR = Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
False
      | Bool
otherwise =
          let ([Graph s l]
seenL', [Graph s l]
frontL') = [Graph s l] -> [Graph s l] -> ([Graph s l], [Graph s l])
advance [Graph s l]
seenL [Graph s l]
frontL
              ([Graph s l]
seenR', [Graph s l]
frontR') = [Graph s l] -> [Graph s l] -> ([Graph s l], [Graph s l])
advance [Graph s l]
seenR [Graph s l]
frontR
          in case Maybe Natural
depth of
               Just Natural
0 -> if [Graph s l] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [Graph s l]
frontL' Bool -> Bool -> Bool
&& [Graph s l] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [Graph s l]
frontR' then Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
False else Maybe Bool
forall a. Maybe a
Nothing
               Maybe Natural
_ -> Maybe Natural
-> [Graph s l]
-> [Graph s l]
-> [Graph s l]
-> [Graph s l]
-> Maybe Bool
search (Natural -> Natural -> Natural
forall a. Num a => a -> a -> a
subtract Natural
1 (Natural -> Natural) -> Maybe Natural -> Maybe Natural
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Natural
depth) [Graph s l]
seenL' [Graph s l]
frontL' [Graph s l]
seenR' [Graph s l]
frontR'
    advance :: [Graph s l] -> [Graph s l] -> ([Graph s l], [Graph s l])
advance [Graph s l]
seen [Graph s l]
front = ([Graph s l]
seen', [Graph s l] -> [Graph s l] -> [Graph s l]
forall l s.
(Eq l, DecidableIso s) =>
[Graph s l] -> [Graph s l] -> [Graph s l]
freshGraphs [Graph s l]
seen' ((Graph s l -> [Graph s l]) -> [Graph s l] -> [Graph s l]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap Graph s l -> [Graph s l]
next [Graph s l]
front))
      where
        seen' :: [Graph s l]
seen' = [Graph s l]
front [Graph s l] -> [Graph s l] -> [Graph s l]
forall a. [a] -> [a] -> [a]
++ [Graph s l]
seen

-- Search shallowest first, using match priority to break ties at each depth.
normalFormWithin
  :: (Eq l, DecidableIso s) => Natural -> (Graph s l -> [Graph s l]) -> Graph s l -> Maybe (Graph s l)
normalFormWithin :: forall l s.
(Eq l, DecidableIso s) =>
Natural
-> (Graph s l -> [Graph s l]) -> Graph s l -> Maybe (Graph s l)
normalFormWithin Natural
maxDepth Graph s l -> [Graph s l]
next Graph s l
start = Natural -> [Graph s l] -> [Graph s l] -> Maybe (Graph s l)
search Natural
maxDepth [] [Graph s l
start]
  where
    search :: Natural -> [Graph s l] -> [Graph s l] -> Maybe (Graph s l)
search Natural
_ [Graph s l]
_ [] = Maybe (Graph s l)
forall a. Maybe a
Nothing
    search Natural
depth [Graph s l]
seen [Graph s l]
front =
      let layer :: [(Graph s l, [Graph s l])]
layer = [(Graph s l
g, Graph s l -> [Graph s l]
next Graph s l
g) | Graph s l
g <- [Graph s l]
front]
          seen' :: [Graph s l]
seen' = [Graph s l]
front [Graph s l] -> [Graph s l] -> [Graph s l]
forall a. [a] -> [a] -> [a]
++ [Graph s l]
seen
      in case ((Graph s l, [Graph s l]) -> Bool)
-> [(Graph s l, [Graph s l])] -> Maybe (Graph s l, [Graph s l])
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Maybe a
List.find ([Graph s l] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null ([Graph s l] -> Bool)
-> ((Graph s l, [Graph s l]) -> [Graph s l])
-> (Graph s l, [Graph s l])
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Graph s l, [Graph s l]) -> [Graph s l]
forall a b. (a, b) -> b
snd) [(Graph s l, [Graph s l])]
layer of
           Just (Graph s l
g, [Graph s l]
_) -> Graph s l -> Maybe (Graph s l)
forall a. a -> Maybe a
Just Graph s l
g
           Maybe (Graph s l, [Graph s l])
Nothing
             | Natural
depth Natural -> Natural -> Bool
forall a. Eq a => a -> a -> Bool
== Natural
0 -> Maybe (Graph s l)
forall a. Maybe a
Nothing
             | Bool
otherwise -> Natural -> [Graph s l] -> [Graph s l] -> Maybe (Graph s l)
search (Natural
depth Natural -> Natural -> Natural
forall a. Num a => a -> a -> a
- Natural
1) [Graph s l]
seen' ([Graph s l] -> [Graph s l]
forall a. [a] -> [a]
reverse ([Graph s l] -> [Graph s l] -> [Graph s l]
forall l s.
(Eq l, DecidableIso s) =>
[Graph s l] -> [Graph s l] -> [Graph s l]
freshGraphs [Graph s l]
seen' (((Graph s l, [Graph s l]) -> [Graph s l])
-> [(Graph s l, [Graph s l])] -> [Graph s l]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap (Graph s l, [Graph s l]) -> [Graph s l]
forall a b. (a, b) -> b
snd [(Graph s l, [Graph s l])]
layer)))

freshGraphs :: (Eq l, DecidableIso s) => [Graph s l] -> [Graph s l] -> [Graph s l]
freshGraphs :: forall l s.
(Eq l, DecidableIso s) =>
[Graph s l] -> [Graph s l] -> [Graph s l]
freshGraphs [Graph s l]
seen = ([Graph s l] -> Graph s l -> [Graph s l])
-> [Graph s l] -> [Graph s l] -> [Graph s l]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: Type -> Type) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' [Graph s l] -> Graph s l -> [Graph s l]
insert []
  where
    insert :: [Graph s l] -> Graph s l -> [Graph s l]
insert [Graph s l]
found Graph s l
g
      | (Graph s l -> Bool) -> [Graph s l] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (Graph s l -> Graph s l -> Bool
forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph Graph s l
g) [Graph s l]
found Bool -> Bool -> Bool
|| (Graph s l -> Bool) -> [Graph s l] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (Graph s l -> Graph s l -> Bool
forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph Graph s l
g) [Graph s l]
seen = [Graph s l]
found
      | Bool
otherwise = Graph s l
g Graph s l -> [Graph s l] -> [Graph s l]
forall a. a -> [a] -> [a]
: [Graph s l]
found

-- The map stores transitive reachability without reflexive pairs. Adding
-- u → v connects every predecessor of u to every successor of v.
maximalPathRelations :: Graph s l -> [(Int, Int)] -> [[(Int, Int)]]
maximalPathRelations :: forall s l. Graph s l -> [(Int, Int)] -> [[(Int, Int)]]
maximalPathRelations (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs) [(Int, Int)]
forbidden =
  [ [(Int, Int)]
relation
  | IntMap IntSet -> Bool
sound IntMap IntSet
initial
  , ([(Int, Int)]
relation, IntMap IntSet
reach) <- [(Int, Int)]
-> IntMap IntSet -> [(Int, Int)] -> [([(Int, Int)], IntMap IntSet)]
search [] IntMap IntSet
initial [(Int, Int)]
candidates
  , ((Int, Int) -> Bool) -> [(Int, Int)] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\(Int, Int)
edge -> (Int, Int)
edge (Int, Int) -> [(Int, Int)] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: Type -> Type) a.
(Foldable t, Eq a) =>
a -> t a -> Bool
`elem` [(Int, Int)]
relation Bool -> Bool -> Bool
|| Maybe (IntMap IntSet) -> Bool
forall a. Maybe a -> Bool
isNothing (IntMap IntSet -> (Int, Int) -> Maybe (IntMap IntSet)
addPath IntMap IntSet
reach (Int, Int)
edge)) [(Int, Int)]
candidates
  ]
  where
    edges :: IntMap [Int]
edges = [Box l Int] -> IntMap [Int]
forall l. [Box l Int] -> IntMap [Int]
wireEdges [Box l Int]
bs
    initial :: IntMap IntSet
initial = [(Int, IntSet)] -> IntMap IntSet
forall a. [(Int, a)] -> IntMap a
IM.fromDistinctAscList [(Int
i, Int -> IntSet -> IntSet
IS.delete Int
i (IntMap [Int] -> Int -> IntSet
reachableNodes IntMap [Int]
edges Int
i)) | Int
i <- [Int
0 .. [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ns Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]]
    candidates :: [(Int, Int)]
candidates = [(Int, Int)
edge | Int
o <- [Int]
outs, Int
i <- [Int]
ins, let edge :: (Int, Int)
edge = (Int
o, Int
i), Maybe (IntMap IntSet) -> Bool
forall a. Maybe a -> Bool
isJust (IntMap IntSet -> (Int, Int) -> Maybe (IntMap IntSet)
addPath IntMap IntSet
initial (Int, Int)
edge)]
    sound :: IntMap IntSet -> Bool
sound IntMap IntSet
reach = ((Int, Int) -> Bool) -> [(Int, Int)] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\(Int
o, Int
i) -> Int -> IntSet -> Bool
IS.notMember Int
i (IntMap IntSet
reach IntMap IntSet -> Int -> IntSet
forall a. IntMap a -> Int -> a
IM.! Int
o)) [(Int, Int)]
forbidden
    addPath :: IntMap IntSet -> (Int, Int) -> Maybe (IntMap IntSet)
addPath IntMap IntSet
reach (Int
u, Int
v)
      | Int
u Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
v Bool -> Bool -> Bool
|| Int -> IntSet -> Bool
IS.member Int
u (IntMap IntSet
reach IntMap IntSet -> Int -> IntSet
forall a. IntMap a -> Int -> a
IM.! Int
v) = Maybe (IntMap IntSet)
forall a. Maybe a
Nothing
      | Bool
otherwise = IntMap IntSet
updated IntMap IntSet -> Maybe () -> Maybe (IntMap IntSet)
forall a b. a -> Maybe b -> Maybe a
forall (f :: Type -> Type) a b. Functor f => a -> f b -> f a
<$ Bool -> Maybe ()
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard (IntMap IntSet -> Bool
sound IntMap IntSet
updated)
      where
        targets :: IntSet
targets = Int -> IntSet -> IntSet
IS.insert Int
v (IntMap IntSet
reach IntMap IntSet -> Int -> IntSet
forall a. IntMap a -> Int -> a
IM.! Int
v)
        updated :: IntMap IntSet
updated = (Int -> IntSet -> IntSet) -> IntMap IntSet -> IntMap IntSet
forall a b. (Int -> a -> b) -> IntMap a -> IntMap b
IM.mapWithKey (\Int
i IntSet
row -> if Int
i Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
u Bool -> Bool -> Bool
|| Int -> IntSet -> Bool
IS.member Int
u IntSet
row then IntSet -> IntSet -> IntSet
IS.union IntSet
row IntSet
targets else IntSet
row) IntMap IntSet
reach
    search :: [(Int, Int)]
-> IntMap IntSet -> [(Int, Int)] -> [([(Int, Int)], IntMap IntSet)]
search [(Int, Int)]
relation IntMap IntSet
reach [(Int, Int)]
remaining =
      let viable :: [(Int, Int)]
viable = ((Int, Int) -> Bool) -> [(Int, Int)] -> [(Int, Int)]
forall a. (a -> Bool) -> [a] -> [a]
filter (Maybe (IntMap IntSet) -> Bool
forall a. Maybe a -> Bool
isJust (Maybe (IntMap IntSet) -> Bool)
-> ((Int, Int) -> Maybe (IntMap IntSet)) -> (Int, Int) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IntMap IntSet -> (Int, Int) -> Maybe (IntMap IntSet)
addPath IntMap IntSet
reach) [(Int, Int)]
remaining
      in case (IntMap IntSet -> (Int, Int) -> Maybe (IntMap IntSet))
-> IntMap IntSet -> [(Int, Int)] -> Maybe (IntMap IntSet)
forall (t :: Type -> Type) (m :: Type -> Type) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM IntMap IntSet -> (Int, Int) -> Maybe (IntMap IntSet)
addPath IntMap IntSet
reach [(Int, Int)]
viable of
           Just IntMap IntSet
complete -> [([(Int, Int)]
relation [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]
forall a. [a] -> [a] -> [a]
++ [(Int, Int)]
viable, IntMap IntSet
complete)]
           Maybe (IntMap IntSet)
Nothing -> case [(Int, Int)]
viable of
             [] -> []
             (Int, Int)
edge : [(Int, Int)]
rest ->
               [([(Int, Int)], IntMap IntSet)
result | IntMap IntSet
extended <- Maybe (IntMap IntSet) -> [IntMap IntSet]
forall a. Maybe a -> [a]
maybeToList (IntMap IntSet -> (Int, Int) -> Maybe (IntMap IntSet)
addPath IntMap IntSet
reach (Int, Int)
edge), ([(Int, Int)], IntMap IntSet)
result <- [(Int, Int)]
-> IntMap IntSet -> [(Int, Int)] -> [([(Int, Int)], IntMap IntSet)]
search ((Int, Int)
edge (Int, Int) -> [(Int, Int)] -> [(Int, Int)]
forall a. a -> [a] -> [a]
: [(Int, Int)]
relation) IntMap IntSet
extended [(Int, Int)]
rest]
                 [([(Int, Int)], IntMap IntSet)]
-> [([(Int, Int)], IntMap IntSet)]
-> [([(Int, Int)], IntMap IntSet)]
forall a. [a] -> [a] -> [a]
++ [(Int, Int)]
-> IntMap IntSet -> [(Int, Int)] -> [([(Int, Int)], IntMap IntSet)]
search [(Int, Int)]
relation IntMap IntSet
reach [(Int, Int)]
rest

-- Fan-out and fan-in boxes give one private wire to each selected relation
-- edge. Unique marker labels pin their attachments during isomorphism checks.
pathExtension :: Graph s l -> [(Int, Int)] -> Graph s (Either Int l)
pathExtension :: forall s l. Graph s l -> [(Int, Int)] -> Graph s (Either Int l)
pathExtension (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs) [(Int, Int)]
relation =
  [SomeSort s]
-> [Int]
-> [Int]
-> [Box (Either Int l) Int]
-> Graph s (Either Int l)
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph
    [SomeSort s]
sorts'
    ((Int -> Bool) -> [Int] -> [Int]
forall a. (a -> Bool) -> [a] -> [a]
filter (Int -> IntMap [Int] -> Bool
forall a. Int -> IntMap a -> Bool
`IM.notMember` IntMap [Int]
toward) [Int]
ins)
    ((Int -> Bool) -> [Int] -> [Int]
forall a. (a -> Bool) -> [a] -> [a]
filter (Int -> IntMap [Int] -> Bool
forall a. Int -> IntMap a -> Bool
`IM.notMember` IntMap [Int]
from) [Int]
outs)
    ((Box l Int -> Box (Either Int l) Int)
-> [Box l Int] -> [Box (Either Int l) Int]
forall a b. (a -> b) -> [a] -> [b]
map (\Box l Int
b -> Box l Int
b{label = Right (label b)}) [Box l Int]
bs [Box (Either Int l) Int]
-> [Box (Either Int l) Int] -> [Box (Either Int l) Int]
forall a. [a] -> [a] -> [a]
++ [Box (Either Int l) Int]
fanOut [Box (Either Int l) Int]
-> [Box (Either Int l) Int] -> [Box (Either Int l) Int]
forall a. [a] -> [a] -> [a]
++ [Box (Either Int l) Int]
fanIn)
  where
    numbered :: [(Int, (Int, Int))]
numbered = [Int] -> [(Int, Int)] -> [(Int, (Int, Int))]
forall a b. [a] -> [b] -> [(a, b)]
zip [[SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ns ..] [(Int, Int)]
relation
    sorts' :: [SomeSort s]
sorts' = [SomeSort s]
ns [SomeSort s] -> [SomeSort s] -> [SomeSort s]
forall a. [a] -> [a] -> [a]
++ [[SomeSort s]
ns [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!! Int
o | (Int
_, (Int
o, Int
_)) <- [(Int, (Int, Int))]
numbered]
    from :: IntMap [Int]
from = ([Int] -> [Int] -> [Int]) -> [(Int, [Int])] -> IntMap [Int]
forall a. (a -> a -> a) -> [(Int, a)] -> IntMap a
IM.fromListWith [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
(++) [(Int
o, [Int
n]) | (Int
n, (Int
o, Int
_)) <- [(Int, (Int, Int))]
numbered]
    toward :: IntMap [Int]
toward = ([Int] -> [Int] -> [Int]) -> [(Int, [Int])] -> IntMap [Int]
forall a. (a -> a -> a) -> [(Int, a)] -> IntMap a
IM.fromListWith [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
(++) [(Int
i, [Int
n]) | (Int
n, (Int
_, Int
i)) <- [(Int, (Int, Int))]
numbered]
    fanOut :: [Box (Either Int l) Int]
fanOut = [Either Int l -> [Int] -> [Int] -> Box (Either Int l) Int
forall l n. l -> [n] -> [n] -> Box l n
Box (Int -> Either Int l
forall a b. a -> Either a b
Left Int
o) [Int
o] [Int]
wires | (Int
o, [Int]
wires) <- IntMap [Int] -> [(Int, [Int])]
forall a. IntMap a -> [(Int, a)]
IM.toList IntMap [Int]
from]
    fanIn :: [Box (Either Int l) Int]
fanIn = [Either Int l -> [Int] -> [Int] -> Box (Either Int l) Int
forall l n. l -> [n] -> [n] -> Box l n
Box (Int -> Either Int l
forall a b. a -> Either a b
Left Int
i) [Int]
wires [Int
i] | (Int
i, [Int]
wires) <- IntMap [Int] -> [(Int, [Int])]
forall a. IntMap a -> [(Int, a)]
IM.toList IntMap [Int]
toward]

-- | Normalise a monogamous acyclic string diagram using one convex match at
-- a time. Each successful step counts as one rewrite and one batch. Use
-- 'Proarrow.Tools.HypergraphRewrite.unlimitedRewrites' when the rules are known to terminate, and
-- 'checkPathContexts' to check whether different rewrite choices rejoin.
normaliseConvex
  :: forall {s} l as bs
   . (Eq l, DecidableIso s)
  => RewriteLimits
  -> ConvexRules s l
  -> (Wires as :: OPENHG s l) ~> Wires bs
  -> Either String (NormalisationResult (Wires as ~> (Wires bs :: OPENHG s l)))
normaliseConvex :: forall {s} l (as :: [s]) (bs :: [s]).
(Eq l, DecidableIso s) =>
RewriteLimits
-> ConvexRules s l
-> (Wires as ~> Wires bs)
-> Either String (NormalisationResult (Wires as ~> Wires bs))
normaliseConvex RewriteLimits
limits ConvexRules s l
rules Wires as ~> Wires bs
host
  | Graph s l -> Bool
forall s l. Graph s l -> Bool
validDiagram ((Wires as ~> Wires bs) -> Graph s l
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph Wires as ~> Wires bs
host) = NormalisationResult (DecCospan (Wires as) (Wires bs))
-> Either
     String (NormalisationResult (DecCospan (Wires as) (Wires bs)))
forall a b. b -> Either a b
Right (RewriteLimits
-> (Graph s l -> [Prepared s l])
-> (Wires as ~> Wires bs)
-> NormalisationResult (Wires as ~> Wires bs)
forall {s} l (as :: [s]) (bs :: [s]).
RewriteLimits
-> (Graph s l -> [Prepared s l])
-> (Wires as ~> Wires bs)
-> NormalisationResult (Wires as ~> Wires bs)
normaliseBy RewriteLimits
limits (Int -> [Prepared s l] -> [Prepared s l]
forall a. Int -> [a] -> [a]
take Int
1 ([Prepared s l] -> [Prepared s l])
-> (Graph s l -> [Prepared s l]) -> Graph s l -> [Prepared s l]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ConvexRules s l -> Graph s l -> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
ConvexRules s l -> Graph s l -> [Prepared s l]
convexMatches ConvexRules s l
rules) Wires as ~> Wires bs
host)
  | Bool
otherwise = String
-> Either
     String (NormalisationResult (DecCospan (Wires as) (Wires bs)))
forall a b. a -> Either a b
Left String
"normaliseConvex: the host must be a monogamous acyclic diagram"