-- | Shared graph representation, rule construction, and application of matches.
module Proarrow.Tools.HypergraphRewrite.Internal
  ( Graph (..)
  , graph
  , mapLabels
  , traverseLabels
  , sameGraph
  , Rule (..)
  , rule
  , Parameter (Literal, Variable)
  , mapParameter
  , zipParameters
  , parameterRule
  , subgraphRule
  , withSortParameters
  , Port (..)
  , PortSymmetry (..)
  , symmetricInputs
  , symmetricOutputs
  , PortGraph (..)
  , mapPortLabels
  , PortReplacement (..)
  , instantiatePorts
  , checkPortLeft
  , portRule
  , parameterPortRule
  , parameterPortExample
  , parameterPortVariants
  , parameterPortRuleWith
  , rulePattern
  , hasSubgraphs
  , LabelTest (..)
  , sameLabelTest
  , acceptsLabel
  , Match
  , Prepared
  , portsOf
  , internalNodes
  , deletedImages
  , nonConflictingBy
  , matches
  , replaceMany
  , replaceSelected
  , RewriteLimits (..)
  , unlimitedRewrites
  , NormalisationStatus (..)
  , NormalisationResult (..)
  , normaliseBy
  , normaliseGraphBy
  ) where

import Control.Monad (foldM, unless, void, when)
import Data.Either (isRight)
import Data.Foldable (toList)
import Data.IntMap.Strict qualified as IM
import Data.IntSet qualified as IS
import Data.Kind (Type)
import Data.List (genericTake, mapAccumL, permutations)
import Data.Map.Strict qualified as M
import Data.Set qualified as S
import Data.Type.Equality ((:~:) (..))
import Data.Typeable (Typeable, eqT)
import Data.Vector qualified as V
import Numeric.Natural (Natural)
import Prelude

import Proarrow.Category.Instance.FinHask (unionFind)
import Proarrow.Category.Instance.OpenHypergraph
  ( Box (..)
  , OPENHG
  , SomeSort
  , Wires
  , hypergraphParts
  , sameSort
  , unsafeOpenHypergraph
  )
import Proarrow.Core (CategoryOf (..), Kind, (//))
import Proarrow.Optic.Iso (DecidableIso)

type Graph :: Kind -> Type -> Type
data Graph s l = Graph [SomeSort s] [Int] [Int] [Box l Int]

-- | An oriented equation between diagrams with the same input and output sorts.
-- Construct with 'rule', 'parameterRule' or 'subgraphRule'. The interface consists of all boundary positions.
type Rule :: Kind -> Type -> Type
data Rule s l
  = Rule (Graph s (LabelTest l)) ([l] -> Maybe (Graph s l))
  | PortRule (PortGraph s (LabelTest l)) (PortReplacement s l)
  | SortRule ([SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]) (Rule s l)
  | SubgraphRule (Graph s (Either l String)) (Graph s (Either l String))

-- | Unary arrow parameters with explicit input and output boundaries. The
-- classifier returns 'Left' for a literal label or 'Right' for a parameter name.
-- Parameters capture connected regions with no external connections except their two boundaries;
-- identity captures identify those boundaries. Repeated names require boundary-
-- preserving graph isomorphism. RHS occurrences copy the captured region with
-- fresh internal nodes; omitted parameters are discarded.
--
-- This restricted higher-order matching follows the fixed-interface approach
-- of <https://arxiv.org/abs/1211.4098 Higher-order port-graph rewriting>.
-- Concrete boxes share the discrimination net. Capture regions are recovered
-- from connected components after cutting at the matched pattern nodes.
-- Disconnected captures and non-identity captures with coincident endpoints
-- are not supported. Boundary nodes must each have one incident captured port,
-- an input and an output respectively. Matching is structural, not modulo laws.
-- Each complete match must contain at least one box; an unanchored identity
-- cannot match. Structurally identical replacements are skipped. Identity
-- captures may identify pattern nodes only across that parameter's endpoints.
subgraphRule
  :: (p -> Either l String)
  -> (a :: OPENHG s p) ~> b
  -> a ~> b
  -> Either String (Rule s l)
subgraphRule :: forall p l s (a :: OPENHG s p) (b :: OPENHG s p).
(p -> Either l String)
-> (a ~> b) -> (a ~> b) -> Either String (Rule s l)
subgraphRule p -> Either l String
classify a ~> b
lhs a ~> b
rhs = do
  Graph s (Either l String) -> Either String ()
forall s l. Graph s l -> Either String ()
checkInterface Graph s (Either l String)
left
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless ((Box (Either l String) Int -> Bool)
-> [Box (Either l String) Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all Box (Either l String) Int -> Bool
forall {a} {b} {a}. Box (Either a b) a -> Bool
unary ([Box (Either l String) Int]
lb [Box (Either l String) Int]
-> [Box (Either l String) Int] -> [Box (Either l String) Int]
forall a. [a] -> [a] -> [a]
++ [Box (Either l String) Int]
rb)) (String -> Either String ()
forall a b. a -> Either a b
Left String
"subgraphRule: arrow parameters must have one input and one output")
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (Set String -> Set String -> Bool
forall a. Ord a => Set a -> Set a -> Bool
S.isSubsetOf ([Box (Either l String) Int] -> Set String
forall {a} {a} {n}. Ord a => [Box (Either a a) n] -> Set a
names [Box (Either l String) Int]
rb) ([Box (Either l String) Int] -> Set String
forall {a} {a} {n}. Ord a => [Box (Either a a) n] -> Set a
names [Box (Either l String) Int]
lb)) (String -> Either String ()
forall a b. a -> Either a b
Left String
"subgraphRule: unbound arrow parameter on the right")
  Rule s l -> Either String (Rule s l)
forall a. a -> Either String a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (Graph s (Either l String) -> Graph s (Either l String) -> Rule s l
forall s l.
Graph s (Either l String) -> Graph s (Either l String) -> Rule s l
SubgraphRule Graph s (Either l String)
left Graph s (Either l String)
right)
  where
    left :: Graph s (Either l String)
left@(Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box (Either l String) Int]
lb) = (p -> Either l String) -> Graph s p -> Graph s (Either l String)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels p -> Either l String
classify ((a ~> b) -> Graph s p
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph a ~> b
lhs)
    right :: Graph s (Either l String)
right@(Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box (Either l String) Int]
rb) = (p -> Either l String) -> Graph s p -> Graph s (Either l String)
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels p -> Either l String
classify ((a ~> b) -> Graph s p
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph a ~> b
rhs)
    unary :: Box (Either a b) a -> Bool
unary (Box (Right b
_) [a]
i [a]
o) = [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
== Int
1 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
== Int
1
    unary Box (Either a b) a
_ = Bool
True
    names :: [Box (Either a a) n] -> Set a
names [Box (Either a a) n]
bs = [a] -> Set a
forall a. Ord a => [a] -> Set a
S.fromList [a
n | Box (Right a
n) [n]
_ [n]
_ <- [Box (Either a a) n]
bs]

-- | Defer a rule's sort checks to a per-match instantiation. The callback receives
-- the numbered pattern sorts, their matched host sorts, and replacement sorts.
-- Return one instantiated sort per replacement node, or reject the candidate.
-- The callback must validate the pattern sorts against the matched host sorts.
-- Interface sorts are checked against the host before a replacement is accepted.
-- Box selection and node binding still share the compiled discrimination net.
withSortParameters
  :: ([SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s])
  -> Rule s l
  -> Rule s l
withSortParameters :: forall s l.
([SomeSort s]
 -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s])
-> Rule s l -> Rule s l
withSortParameters = ([SomeSort s]
 -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s])
-> Rule s l -> Rule s l
forall s l.
([SomeSort s]
 -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s])
-> Rule s l -> Rule s l
SortRule

-- | A numbered node, a named sequence of ports, or one element of a captured
-- sequence. Captures may be empty and preserve order and repeated nodes.
-- 'Element' is available only on the right of a port rule.
data Port = Node Int | Capture String | Element String Int
  deriving (Port -> Port -> Bool
(Port -> Port -> Bool) -> (Port -> Port -> Bool) -> Eq Port
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Port -> Port -> Bool
== :: Port -> Port -> Bool
$c/= :: Port -> Port -> Bool
/= :: Port -> Port -> Bool
Eq, Eq Port
Eq Port =>
(Port -> Port -> Ordering)
-> (Port -> Port -> Bool)
-> (Port -> Port -> Bool)
-> (Port -> Port -> Bool)
-> (Port -> Port -> Bool)
-> (Port -> Port -> Port)
-> (Port -> Port -> Port)
-> Ord Port
Port -> Port -> Bool
Port -> Port -> Ordering
Port -> Port -> Port
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Port -> Port -> Ordering
compare :: Port -> Port -> Ordering
$c< :: Port -> Port -> Bool
< :: Port -> Port -> Bool
$c<= :: Port -> Port -> Bool
<= :: Port -> Port -> Bool
$c> :: Port -> Port -> Bool
> :: Port -> Port -> Bool
$c>= :: Port -> Port -> Bool
>= :: Port -> Port -> Bool
$cmax :: Port -> Port -> Port
max :: Port -> Port -> Port
$cmin :: Port -> Port -> Port
min :: Port -> Port -> Port
Ord, Int -> Port -> ShowS
[Port] -> ShowS
Port -> String
(Int -> Port -> ShowS)
-> (Port -> String) -> ([Port] -> ShowS) -> Show Port
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Port -> ShowS
showsPrec :: Int -> Port -> ShowS
$cshow :: Port -> String
show :: Port -> String
$cshowList :: [Port] -> ShowS
showList :: [Port] -> ShowS
Show)

-- | Permitted permutations of a box's ports. Inputs and outputs permute independently.
data PortSymmetry = OrderedPorts | SymmetricInputs | SymmetricOutputs | SymmetricPorts
  deriving (PortSymmetry -> PortSymmetry -> Bool
(PortSymmetry -> PortSymmetry -> Bool)
-> (PortSymmetry -> PortSymmetry -> Bool) -> Eq PortSymmetry
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PortSymmetry -> PortSymmetry -> Bool
== :: PortSymmetry -> PortSymmetry -> Bool
$c/= :: PortSymmetry -> PortSymmetry -> Bool
/= :: PortSymmetry -> PortSymmetry -> Bool
Eq, Int -> PortSymmetry -> ShowS
[PortSymmetry] -> ShowS
PortSymmetry -> String
(Int -> PortSymmetry -> ShowS)
-> (PortSymmetry -> String)
-> ([PortSymmetry] -> ShowS)
-> Show PortSymmetry
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PortSymmetry -> ShowS
showsPrec :: Int -> PortSymmetry -> ShowS
$cshow :: PortSymmetry -> String
show :: PortSymmetry -> String
$cshowList :: [PortSymmetry] -> ShowS
showList :: [PortSymmetry] -> ShowS
Show)

symmetricInputs, symmetricOutputs :: PortSymmetry -> Bool
symmetricInputs :: PortSymmetry -> Bool
symmetricInputs PortSymmetry
policy = PortSymmetry
policy PortSymmetry -> PortSymmetry -> Bool
forall a. Eq a => a -> a -> Bool
== PortSymmetry
SymmetricInputs Bool -> Bool -> Bool
|| PortSymmetry
policy PortSymmetry -> PortSymmetry -> Bool
forall a. Eq a => a -> a -> Bool
== PortSymmetry
SymmetricPorts
symmetricOutputs :: PortSymmetry -> Bool
symmetricOutputs PortSymmetry
policy = PortSymmetry
policy PortSymmetry -> PortSymmetry -> Bool
forall a. Eq a => a -> a -> Bool
== PortSymmetry
SymmetricOutputs Bool -> Bool -> Bool
|| PortSymmetry
policy PortSymmetry -> PortSymmetry -> Bool
forall a. Eq a => a -> a -> Bool
== PortSymmetry
SymmetricPorts

-- | A port-rule fragment: sorts of numbered nodes, its explicit interface, and
-- boxes. Every captured node is also preserved, including aliases between
-- captures or with explicit interface nodes. RHS numbered nodes are fresh,
-- except where glued to the left through the two explicit interfaces.
type PortGraph :: Kind -> Type -> Type
data PortGraph s l = PortGraph [SomeSort s] [Int] [Box l Port]

data PortReplacement s l where
  PortTemplate :: PortGraph s l -> PortReplacement s l
  ParameterPorts
    :: (Traversable f, Eq a) => [f (Parameter a)] -> PortGraph s (f (Parameter a)) -> PortReplacement s (f a)
  ComputedPorts
    :: (Traversable f, Eq a)
    => [f (Parameter a)]
    -> (M.Map String Int -> Maybe (PortGraph s (f (Parameter a))))
    -> PortReplacement s (f a)

instantiatePorts :: IS.IntSet -> PortReplacement s l -> M.Map String [Int] -> [l] -> Maybe (PortGraph s l)
instantiatePorts :: forall s l.
IntSet
-> PortReplacement s l
-> Map String [Int]
-> [l]
-> Maybe (PortGraph s l)
instantiatePorts IntSet
_ (PortTemplate PortGraph s l
rhs) Map String [Int]
_ [l]
_ = PortGraph s l -> Maybe (PortGraph s l)
forall a. a -> Maybe a
Just PortGraph s l
rhs
instantiatePorts IntSet
_ (ParameterPorts [f (Parameter a)]
lhs PortGraph s (f (Parameter a))
rhs) Map String [Int]
_ [l]
labels = [f (Parameter a)]
-> PortGraph s (f (Parameter a))
-> [f a]
-> Maybe (PortGraph s (f a))
forall (f :: Type -> Type) a s.
(Traversable f, Eq a) =>
[f (Parameter a)]
-> PortGraph s (f (Parameter a))
-> [f a]
-> Maybe (PortGraph s (f a))
instantiateParameterPorts [f (Parameter a)]
lhs PortGraph s (f (Parameter a))
rhs [l]
[f a]
labels
instantiatePorts IntSet
protected (ComputedPorts [f (Parameter a)]
lhs Map String Int -> Maybe (PortGraph s (f (Parameter a)))
build) Map String [Int]
captures [l]
labels = do
  -- A symbolic marker stands for a sequence of unknown length.
  Bool -> Maybe () -> Maybe ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (IntSet -> Bool
IS.null IntSet
protected Bool -> Bool -> Bool
|| ([Int] -> Bool) -> Map String [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all ((Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (Int -> IntSet -> Bool
`IS.notMember` IntSet
protected)) Map String [Int]
captures) Maybe ()
forall a. Maybe a
Nothing
  rhs <- Map String Int -> Maybe (PortGraph s (f (Parameter a)))
build (([Int] -> Int) -> Map String [Int] -> Map String Int
forall a b k. (a -> b) -> Map k a -> Map k b
M.map [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length Map String [Int]
captures)
  instantiateParameterPorts lhs rhs labels

mapPortLabels :: (l -> m) -> PortGraph s l -> PortGraph s m
mapPortLabels :: forall l m s. (l -> m) -> PortGraph s l -> PortGraph s m
mapPortLabels l -> m
f (PortGraph [SomeSort s]
ns [Int]
interface [Box l Port]
bs) = [SomeSort s] -> [Int] -> [Box m Port] -> PortGraph s m
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph [SomeSort s]
ns [Int]
interface [m -> [Port] -> [Port] -> Box m Port
forall l n. l -> [n] -> [n] -> Box l n
Box (l -> m
f l
l) [Port]
i [Port]
o | Box l
l [Port]
i [Port]
o <- [Box l Port]
bs]

portLabels :: PortGraph s l -> [l]
portLabels :: forall s l. PortGraph s l -> [l]
portLabels (PortGraph [SomeSort s]
_ [Int]
_ [Box l Port]
bs) = (Box l Port -> l) -> [Box l Port] -> [l]
forall a b. (a -> b) -> [a] -> [b]
map Box l Port -> l
forall l n. Box l n -> l
label [Box l Port]
bs

-- | Match variable port sequences with literal labels. A capture on the left
-- matches a contiguous sequence; use captures before and after a numbered node
-- to find a connection at any port position. Repeated names require equal
-- sequences. Captured nodes cannot be deleted, even when they alias numbered
-- nodes. Existing dangling, sort, injectivity and batch-conflict checks apply.
portRule :: (DecidableIso s) => PortGraph s l -> PortGraph s l -> Either String (Rule s l)
portRule :: forall s l.
DecidableIso s =>
PortGraph s l -> PortGraph s l -> Either String (Rule s l)
portRule PortGraph s l
lhs PortGraph s l
rhs = do
  PortGraph s l -> Either String ()
forall s l. PortGraph s l -> Either String ()
checkPortLeft PortGraph s l
lhs
  PortGraph s l -> PortGraph s l -> Either String ()
forall s l m.
DecidableIso s =>
PortGraph s l -> PortGraph s m -> Either String ()
checkPortRight PortGraph s l
lhs PortGraph s l
rhs
  Rule s l -> Either String (Rule s l)
forall a. a -> Either String a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (PortGraph s (LabelTest l) -> PortReplacement s l -> Rule s l
forall s l.
PortGraph s (LabelTest l) -> PortReplacement s l -> Rule s l
PortRule ((l -> LabelTest l) -> PortGraph s l -> PortGraph s (LabelTest l)
forall l m s. (l -> m) -> PortGraph s l -> PortGraph s m
mapPortLabels l -> LabelTest l
forall l. l -> LabelTest l
ExactLabel PortGraph s l
lhs) (PortGraph s l -> PortReplacement s l
forall s l. PortGraph s l -> PortReplacement s l
PortTemplate PortGraph s l
rhs))

-- | A port rule with the label parameters of 'parameterRule'. Both its
-- topology template and parameter names are checked when constructing the rule.
parameterPortRule
  :: (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 :: 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 PortGraph s (f (Parameter a))
lhs PortGraph s (f (Parameter a))
rhs = do
  PortGraph s (f (Parameter a)) -> Either String ()
forall s l. PortGraph s l -> Either String ()
checkPortLeft PortGraph s (f (Parameter a))
lhs
  PortGraph s (f (Parameter a))
-> PortGraph s (f (Parameter a)) -> Either String ()
forall s l m.
DecidableIso s =>
PortGraph s l -> PortGraph s m -> Either String ()
checkPortRight PortGraph s (f (Parameter a))
lhs PortGraph s (f (Parameter a))
rhs
  [f (Parameter a)] -> [f (Parameter a)] -> Either String ()
forall (f :: Type -> Type) a.
Foldable f =>
[f (Parameter a)] -> [f (Parameter a)] -> Either String ()
checkParameters (PortGraph s (f (Parameter a)) -> [f (Parameter a)]
forall s l. PortGraph s l -> [l]
portLabels PortGraph s (f (Parameter a))
lhs) (PortGraph s (f (Parameter a)) -> [f (Parameter a)]
forall s l. PortGraph s l -> [l]
portLabels PortGraph s (f (Parameter a))
rhs)
  Rule s (f a) -> Either String (Rule s (f a))
forall a. a -> Either String a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (PortGraph s (LabelTest (f a))
-> PortReplacement s (f a) -> Rule s (f a)
forall s l.
PortGraph s (LabelTest l) -> PortReplacement s l -> Rule s l
PortRule ((f (Parameter a) -> LabelTest (f a))
-> PortGraph s (f (Parameter a)) -> PortGraph s (LabelTest (f a))
forall l m s. (l -> m) -> PortGraph s l -> PortGraph s m
mapPortLabels (f () -> LabelTest (f a)
forall (f :: Type -> Type) a.
(Functor f, Eq (f ()), Typeable f) =>
f () -> LabelTest (f a)
ConstructorLabel (f () -> LabelTest (f a))
-> (f (Parameter a) -> f ()) -> f (Parameter a) -> LabelTest (f a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. f (Parameter a) -> f ()
forall (f :: Type -> Type) a. Functor f => f a -> f ()
void) PortGraph s (f (Parameter a))
lhs) ([f (Parameter a)]
-> PortGraph s (f (Parameter a)) -> PortReplacement s (f a)
forall (f :: Type -> Type) a s.
(Traversable f, Eq a) =>
[f (Parameter a)]
-> PortGraph s (f (Parameter a)) -> PortReplacement s (f a)
ParameterPorts (PortGraph s (f (Parameter a)) -> [f (Parameter a)]
forall s l. PortGraph s l -> [l]
portLabels PortGraph s (f (Parameter a))
lhs) PortGraph s (f (Parameter a))
rhs))

-- | Instantiate the labels of a fixed parameterized port rule for inspection.
-- The two fragments retain their capture names and numbered interfaces.
parameterPortExample
  :: (String -> a) -> Rule s (f a) -> Either String (PortGraph s (f a), PortGraph s (f a))
parameterPortExample :: forall a s (f :: Type -> Type).
(String -> a)
-> Rule s (f a)
-> Either String (PortGraph s (f a), PortGraph s (f a))
parameterPortExample String -> a
value (PortRule (PortGraph [SomeSort s]
ns [Int]
boundary [Box (LabelTest (f a)) Port]
boxes) (ParameterPorts [f (Parameter a)]
patterns PortGraph s (f (Parameter a))
rhs)) = do
  let names :: Set String
names = [Set String] -> Set String
forall (f :: Type -> Type) a.
(Foldable f, Ord a) =>
f (Set a) -> Set a
S.unions ((Parameter a -> Set String) -> [Parameter a] -> [Set String]
forall a b. (a -> b) -> [a] -> [b]
map Parameter a -> Set String
forall a. Parameter a -> Set String
parameterNames ((f (Parameter a) -> [Parameter a])
-> [f (Parameter a)] -> [Parameter a]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap f (Parameter a) -> [Parameter a]
forall a. f a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList [f (Parameter a)]
patterns))
      env :: Map String a
env = (String -> a) -> Set String -> Map String a
forall k a. (k -> a) -> Set k -> Map k a
M.fromSet String -> a
value Set String
names
      instantiate :: f (Parameter a) -> Maybe (f a)
instantiate = (Parameter a -> Maybe a) -> f (Parameter a) -> Maybe (f 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 (Parameter a -> Map String a -> Maybe a
forall a. Parameter a -> Map String a -> Maybe a
`evaluateParameter` Map String a
env)
      makeBox :: Box (LabelTest (f a)) Port
-> f (Parameter a) -> Maybe (Box (f a) Port)
makeBox (Box LabelTest (f a)
_ [Port]
ins [Port]
outs) f (Parameter a)
p = (\f a
l -> f a -> [Port] -> [Port] -> Box (f a) Port
forall l n. l -> [n] -> [n] -> Box l n
Box f a
l [Port]
ins [Port]
outs) (f a -> Box (f a) Port) -> Maybe (f a) -> Maybe (Box (f a) Port)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> f (Parameter a) -> Maybe (f a)
instantiate f (Parameter a)
p
  labels <- Either String [Box (f a) Port]
-> ([Box (f a) Port] -> Either String [Box (f a) Port])
-> Maybe [Box (f a) Port]
-> Either String [Box (f a) Port]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> Either String [Box (f a) Port]
forall a b. a -> Either a b
Left String
"parameterPortExample: unbound parameter") [Box (f a) Port] -> Either String [Box (f a) Port]
forall a b. b -> Either a b
Right (((Box (LabelTest (f a)) Port, f (Parameter a))
 -> Maybe (Box (f a) Port))
-> [(Box (LabelTest (f a)) Port, f (Parameter a))]
-> Maybe [Box (f a) 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 (f a)) Port
 -> f (Parameter a) -> Maybe (Box (f a) Port))
-> (Box (LabelTest (f a)) Port, f (Parameter a))
-> Maybe (Box (f a) Port)
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Box (LabelTest (f a)) Port
-> f (Parameter a) -> Maybe (Box (f a) Port)
makeBox) ([Box (LabelTest (f a)) Port]
-> [f (Parameter a)]
-> [(Box (LabelTest (f a)) Port, f (Parameter a))]
forall a b. [a] -> [b] -> [(a, b)]
zip [Box (LabelTest (f a)) Port]
boxes [f (Parameter a)]
[f (Parameter a)]
patterns))
  replacement <-
    maybe
      (Left "parameterPortExample: replacement rejected its example labels")
      Right
      (instantiateParameterPorts patterns rhs (map label labels))
  pure (PortGraph ns boundary labels, replacement)
parameterPortExample String -> a
_ Rule s (f a)
_ = String -> Either String (PortGraph s (f a), PortGraph s (f a))
forall a b. a -> Either a b
Left String
"parameterPortExample: expected a parameterized port rule with a fixed replacement"

-- | Expand a fixed parameterized port rule into ordered matching variants.
-- The classifier sees the label with its parameters erased. Permute only
-- numbered port lists on the left, preserving the boundary and replacement.
-- Lists with captures stay ordered. Symmetric lists enumerate all distinct
-- permutations with the original list first, so use this for small arities.
parameterPortVariants
  :: (f () -> PortSymmetry)
  -> Rule s (f a)
  -> Either String [Rule s (f a)]
parameterPortVariants :: forall (f :: Type -> Type) s a.
(f () -> PortSymmetry)
-> Rule s (f a) -> Either String [Rule s (f a)]
parameterPortVariants f () -> PortSymmetry
symmetry (PortRule (PortGraph [SomeSort s]
ns [Int]
boundary [Box (LabelTest (f a)) Port]
boxes) replacement :: PortReplacement s (f a)
replacement@ParameterPorts{}) =
  [Rule s (f a)] -> Either String [Rule s (f a)]
forall a b. b -> Either a b
Right [PortGraph s (LabelTest (f a))
-> PortReplacement s (f a) -> Rule s (f a)
forall s l.
PortGraph s (LabelTest l) -> PortReplacement s l -> Rule s l
PortRule ([SomeSort s]
-> [Int]
-> [Box (LabelTest (f a)) Port]
-> PortGraph s (LabelTest (f a))
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph [SomeSort s]
ns [Int]
boundary [Box (LabelTest (f a)) Port]
variant) PortReplacement s (f a)
replacement | [Box (LabelTest (f a)) Port]
variant <- (Box (LabelTest (f a)) Port -> [Box (LabelTest (f a)) Port])
-> [Box (LabelTest (f a)) Port] -> [[Box (LabelTest (f a)) 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 (f a)) Port -> [Box (LabelTest (f a)) Port]
variants [Box (LabelTest (f a)) Port]
boxes]
  where
    variants :: Box (LabelTest (f a)) Port -> [Box (LabelTest (f a)) Port]
variants box :: Box (LabelTest (f a)) Port
box@(Box LabelTest (f a)
label' [Port]
ins [Port]
outs) = case LabelTest (f a)
label' of
      ConstructorLabel f ()
shape ->
        let policy :: PortSymmetry
policy = f () -> PortSymmetry
symmetry f ()
f ()
shape
        in [ LabelTest (f a) -> [Port] -> [Port] -> Box (LabelTest (f a)) Port
forall l n. l -> [n] -> [n] -> Box l n
Box LabelTest (f a)
label' [Port]
i [Port]
o
           | [Port]
i <- Bool -> [Port] -> [[Port]]
orders (PortSymmetry -> Bool
symmetricInputs PortSymmetry
policy) [Port]
ins
           , [Port]
o <- Bool -> [Port] -> [[Port]]
orders (PortSymmetry -> Bool
symmetricOutputs PortSymmetry
policy) [Port]
outs
           ]
      ExactLabel{} -> [Box (LabelTest (f a)) Port
box]
    orders :: Bool -> [Port] -> [[Port]]
orders Bool
symmetric [Port]
ps
      | Bool
symmetric Bool -> Bool -> Bool
&& (Port -> Bool) -> [Port] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all Port -> Bool
numbered [Port]
ps = [Port] -> [[Port]]
forall a. Ord a => [a] -> [[a]]
distinctPermutations [Port]
ps
      | Bool
otherwise = [[Port]
ps]
    numbered :: Port -> Bool
numbered Node{} = Bool
True
    numbered Port
_ = Bool
False
parameterPortVariants f () -> PortSymmetry
_ Rule s (f a)
_ = String -> Either String [Rule s (f a)]
forall a b. a -> Either a b
Left String
"parameterPortVariants: expected a parameterized port rule with a fixed replacement"

distinctPermutations :: (Ord a) => [a] -> [[a]]
distinctPermutations :: forall a. Ord a => [a] -> [[a]]
distinctPermutations [a]
xs
  | Map a Int -> Int
forall k a. Map k a -> Int
M.size Map a Int
counts 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]
xs = [a] -> [[a]]
forall a. [a] -> [[a]]
permutations [a]
xs
  | Bool
otherwise = [a]
xs [a] -> [[a]] -> [[a]]
forall a. a -> [a] -> [a]
: ([a] -> Bool) -> [[a]] -> [[a]]
forall a. (a -> Bool) -> [a] -> [a]
filter ([a] -> [a] -> Bool
forall a. Eq a => a -> a -> Bool
/= [a]
xs) (Map a Int -> [[a]]
forall {a} {a}. (Num a, Ord a, Eq a) => Map a a -> [[a]]
arrange Map a Int
counts)
  where
    counts :: Map a Int
counts = (Int -> Int -> Int) -> [(a, Int)] -> Map a Int
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) [(a
x, Int
1 :: Int) | a
x <- [a]
xs]
    arrange :: Map a a -> [[a]]
arrange Map a a
remaining
      | Map a a -> Bool
forall k a. Map k a -> Bool
M.null Map a a
remaining = [[]]
      | Bool
otherwise =
          [ a
x a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
rest
          | (a
x, a
count) <- Map a a -> [(a, a)]
forall k a. Map k a -> [(k, a)]
M.toAscList Map a a
remaining
          , let unused :: Map a a
unused = if a
count a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
1 then a -> Map a a -> Map a a
forall k a. Ord k => k -> Map k a -> Map k a
M.delete a
x Map a a
remaining else a -> a -> Map a a -> Map a a
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert a
x (a
count a -> a -> a
forall a. Num a => a -> a -> a
- a
1) Map a a
remaining
          , [a]
rest <- Map a a -> [[a]]
arrange Map a a
unused
          ]

-- | Build a replacement from capture lengths, for example one Hadamard per
-- captured leg. 'Element' refers to an individual captured port. The builder
-- receives only lengths, not host node IDs. Replacement node references,
-- interface sorts, captures and parameter names are checked for each candidate;
-- an invalid replacement rejects that candidate before batch selection.
parameterPortRuleWith
  :: (DecidableIso s, Traversable f, Eq (f ()), Typeable f, Eq a)
  => PortGraph s (f (Parameter a))
  -> (M.Map String Int -> PortGraph s (f (Parameter a)))
  -> Either String (Rule s (f a))
parameterPortRuleWith :: forall s (f :: Type -> Type) a.
(DecidableIso s, Traversable f, Eq (f ()), Typeable f, Eq a) =>
PortGraph s (f (Parameter a))
-> (Map String Int -> PortGraph s (f (Parameter a)))
-> Either String (Rule s (f a))
parameterPortRuleWith PortGraph s (f (Parameter a))
lhs Map String Int -> PortGraph s (f (Parameter a))
build = do
  PortGraph s (f (Parameter a)) -> Either String ()
forall s l. PortGraph s l -> Either String ()
checkPortLeft PortGraph s (f (Parameter a))
lhs
  [f (Parameter a)] -> [f (Parameter a)] -> Either String ()
forall (f :: Type -> Type) a.
Foldable f =>
[f (Parameter a)] -> [f (Parameter a)] -> Either String ()
checkParameters [f (Parameter a)]
parameters []
  Rule s (f a) -> Either String (Rule s (f a))
forall a. a -> Either String a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (PortGraph s (LabelTest (f a))
-> PortReplacement s (f a) -> Rule s (f a)
forall s l.
PortGraph s (LabelTest l) -> PortReplacement s l -> Rule s l
PortRule ((f (Parameter a) -> LabelTest (f a))
-> PortGraph s (f (Parameter a)) -> PortGraph s (LabelTest (f a))
forall l m s. (l -> m) -> PortGraph s l -> PortGraph s m
mapPortLabels (f () -> LabelTest (f a)
forall (f :: Type -> Type) a.
(Functor f, Eq (f ()), Typeable f) =>
f () -> LabelTest (f a)
ConstructorLabel (f () -> LabelTest (f a))
-> (f (Parameter a) -> f ()) -> f (Parameter a) -> LabelTest (f a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. f (Parameter a) -> f ()
forall (f :: Type -> Type) a. Functor f => f a -> f ()
void) PortGraph s (f (Parameter a))
lhs) ([f (Parameter a)]
-> (Map String Int -> Maybe (PortGraph s (f (Parameter a))))
-> PortReplacement s (f a)
forall (f :: Type -> Type) a s.
(Traversable f, Eq a) =>
[f (Parameter a)]
-> (Map String Int -> Maybe (PortGraph s (f (Parameter a))))
-> PortReplacement s (f a)
ComputedPorts [f (Parameter a)]
parameters Map String Int -> Maybe (PortGraph s (f (Parameter a)))
replacement))
  where
    parameters :: [f (Parameter a)]
parameters = PortGraph s (f (Parameter a)) -> [f (Parameter a)]
forall s l. PortGraph s l -> [l]
portLabels PortGraph s (f (Parameter a))
lhs
    replacement :: Map String Int -> Maybe (PortGraph s (f (Parameter a)))
replacement Map String Int
sizes = do
      let rhs :: PortGraph s (f (Parameter a))
rhs = Map String Int -> PortGraph s (f (Parameter a))
build Map String Int
sizes
      Bool -> Maybe () -> Maybe ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (Either String () -> Bool
forall a b. Either a b -> Bool
isRight (PortGraph s (f (Parameter a))
-> PortGraph s (f (Parameter a)) -> Either String ()
forall s l m.
DecidableIso s =>
PortGraph s l -> PortGraph s m -> Either String ()
checkPortRight PortGraph s (f (Parameter a))
lhs PortGraph s (f (Parameter a))
rhs)) Maybe ()
forall a. Maybe a
Nothing
      Bool -> Maybe () -> Maybe ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (Either String () -> Bool
forall a b. Either a b -> Bool
isRight ([f (Parameter a)] -> [f (Parameter a)] -> Either String ()
forall (f :: Type -> Type) a.
Foldable f =>
[f (Parameter a)] -> [f (Parameter a)] -> Either String ()
checkParameters [f (Parameter a)]
parameters (PortGraph s (f (Parameter a)) -> [f (Parameter a)]
forall s l. PortGraph s l -> [l]
portLabels PortGraph s (f (Parameter a))
rhs))) Maybe ()
forall a. Maybe a
Nothing
      PortGraph s (f (Parameter a))
-> Maybe (PortGraph s (f (Parameter a)))
forall a. a -> Maybe a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure PortGraph s (f (Parameter a))
rhs

instantiateParameterPorts
  :: (Traversable f, Eq a) => [f (Parameter a)] -> PortGraph s (f (Parameter a)) -> [f a] -> Maybe (PortGraph s (f a))
instantiateParameterPorts :: forall (f :: Type -> Type) a s.
(Traversable f, Eq a) =>
[f (Parameter a)]
-> PortGraph s (f (Parameter a))
-> [f a]
-> Maybe (PortGraph s (f a))
instantiateParameterPorts [f (Parameter a)]
lhs (PortGraph [SomeSort s]
ns [Int]
boundary [Box (f (Parameter a)) Port]
bs) [f a]
labels = do
  env <- [f (Parameter a)] -> [f a] -> Maybe (Map String a)
forall (f :: Type -> Type) a.
(Foldable f, Eq a) =>
[f (Parameter a)] -> [f a] -> Maybe (Map String a)
parameterBindings [f (Parameter a)]
lhs [f a]
labels
  boxes <- traverse (\(Box f (Parameter a)
l [Port]
i [Port]
o) -> (\f a
l' -> f a -> [Port] -> [Port] -> Box (f a) Port
forall l n. l -> [n] -> [n] -> Box l n
Box f a
l' [Port]
i [Port]
o) (f a -> Box (f a) Port) -> Maybe (f a) -> Maybe (Box (f a) Port)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Parameter a -> Maybe a) -> f (Parameter a) -> Maybe (f 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 (Parameter a -> Map String a -> Maybe a
forall a. Parameter a -> Map String a -> Maybe a
`evaluateParameter` Map String a
env) f (Parameter a)
l) bs
  pure (PortGraph ns boundary boxes)

captureNames :: PortGraph s l -> S.Set String
captureNames :: forall s l. PortGraph s l -> Set String
captureNames (PortGraph [SomeSort s]
_ [Int]
_ [Box l Port]
bs) = [String] -> Set String
forall a. Ord a => [a] -> Set a
S.fromList [String
name | Box l Port
b <- [Box l Port]
bs, Capture String
name <- 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]

checkPortNodes :: PortGraph s l -> Either String ()
checkPortNodes :: forall s l. PortGraph s l -> Either String ()
checkPortNodes (PortGraph [SomeSort s]
ns [Int]
boundary [Box l Port]
bs) = do
  let valid :: Int -> Bool
valid Int
n = Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
0 Bool -> Bool -> Bool
&& Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ns
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless
    ((Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all Int -> Bool
valid [Int]
boundary Bool -> Bool -> Bool
&& (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all Int -> Bool
valid [Int
n | Box l Port
b <- [Box l Port]
bs, 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])
    (String -> Either String ()
forall a b. a -> Either a b
Left String
"portRule: invalid node reference")
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless
    ((Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
0) [Int
i | Box l Port
b <- [Box l Port]
bs, Element String
_ Int
i <- 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])
    (String -> Either String ()
forall a b. a -> Either a b
Left String
"portRule: negative capture index")

checkPortLeft :: PortGraph s l -> Either String ()
checkPortLeft :: forall s l. PortGraph s l -> Either String ()
checkPortLeft g :: PortGraph s l
g@(PortGraph [SomeSort s]
_ [Int]
boundary [Box l Port]
bs) = do
  PortGraph s l -> Either String ()
forall s l. PortGraph s l -> Either String ()
checkPortNodes PortGraph s l
g
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
boundary Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Set Int -> Int
forall a. Set a -> Int
S.size ([Int] -> Set Int
forall a. Ord a => [a] -> Set a
S.fromList [Int]
boundary)) (String -> Either String ()
forall a b. a -> Either a b
Left String
"portRule: repeated left interface node")
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
when ((Port -> Bool) -> [Port] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any Port -> Bool
element [Port
p | Box l Port
b <- [Box l Port]
bs, Port
p <- 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]) (String -> Either String ()
forall a b. a -> Either a b
Left String
"portRule: Element on the left")
  where
    element :: Port -> Bool
element Element{} = Bool
True
    element Port
_ = Bool
False

checkPortRight :: (DecidableIso s) => PortGraph s l -> PortGraph s m -> Either String ()
checkPortRight :: forall s l m.
DecidableIso s =>
PortGraph s l -> PortGraph s m -> Either String ()
checkPortRight lhs :: PortGraph s l
lhs@(PortGraph [SomeSort s]
ls [Int]
li [Box l Port]
_) rhs :: PortGraph s m
rhs@(PortGraph [SomeSort s]
rs [Int]
ri [Box m Port]
bs) = do
  PortGraph s m -> Either String ()
forall s l. PortGraph s l -> Either String ()
checkPortNodes PortGraph s m
rhs
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless
    ([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] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
ri Bool -> Bool -> Bool
&& [Bool] -> Bool
forall (t :: Type -> Type). Foldable t => t Bool -> Bool
and [SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort ([SomeSort s]
ls [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!! Int
l) ([SomeSort s]
rs [SomeSort s] -> Int -> SomeSort s
forall a. HasCallStack => [a] -> Int -> a
!! Int
r) | (Int
l, Int
r) <- [Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
li [Int]
ri])
    (String -> Either String ()
forall a b. a -> Either a b
Left String
"portRule: incompatible explicit interfaces")
  let references :: Set String
references =
        [String] -> Set String
forall a. Ord a => [a] -> Set a
S.fromList
          [String
name | Box m Port
b <- [Box m Port]
bs, Port
p <- Box m Port -> [Port]
forall l n. Box l n -> [n]
inputs Box m Port
b [Port] -> [Port] -> [Port]
forall a. [a] -> [a] -> [a]
++ Box m Port -> [Port]
forall l n. Box l n -> [n]
outputs Box m Port
b, String
name <- case Port
p of Node Int
_ -> []; Capture String
n -> [String
n]; Element String
n Int
_ -> [String
n]]
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (Set String -> Set String -> Bool
forall a. Ord a => Set a -> Set a -> Bool
S.isSubsetOf Set String
references (PortGraph s l -> Set String
forall s l. PortGraph s l -> Set String
captureNames PortGraph s l
lhs)) (String -> Either String ()
forall a b. a -> Either a b
Left String
"portRule: unbound port capture")

rulePattern :: Rule s l -> PortGraph s (LabelTest l)
rulePattern :: forall s l. Rule s l -> PortGraph s (LabelTest l)
rulePattern (Rule (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box (LabelTest l) Int]
bs) [l] -> Maybe (Graph s l)
_) = [SomeSort s]
-> [Int] -> [Box (LabelTest l) Port] -> PortGraph s (LabelTest l)
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph [SomeSort s]
ns ([Int]
ins [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
outs) ((Box (LabelTest l) Int -> Box (LabelTest l) Port)
-> [Box (LabelTest l) Int] -> [Box (LabelTest l) Port]
forall a b. (a -> b) -> [a] -> [b]
map ((Int -> Port) -> Box (LabelTest l) Int -> Box (LabelTest l) Port
forall a b. (a -> b) -> Box (LabelTest l) a -> Box (LabelTest l) b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap Int -> Port
Node) [Box (LabelTest l) Int]
bs)
rulePattern (PortRule PortGraph s (LabelTest l)
pattern' PortReplacement s l
_) = PortGraph s (LabelTest l)
pattern'
rulePattern (SortRule [SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]
_ Rule s l
r) = Rule s l -> PortGraph s (LabelTest l)
forall s l. Rule s l -> PortGraph s (LabelTest l)
rulePattern Rule s l
r
rulePattern (SubgraphRule (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box (Either l String) Int]
bs) Graph s (Either l String)
_) =
  [SomeSort s]
-> [Int] -> [Box (LabelTest l) Port] -> PortGraph s (LabelTest l)
forall s l. [SomeSort s] -> [Int] -> [Box l Port] -> PortGraph s l
PortGraph [SomeSort s]
ns ([Int]
ins [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
outs) [(Int -> Port) -> Box (LabelTest l) Int -> Box (LabelTest l) Port
forall a b. (a -> b) -> Box (LabelTest l) a -> Box (LabelTest l) b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap Int -> Port
Node (LabelTest l -> [Int] -> [Int] -> Box (LabelTest l) Int
forall l n. l -> [n] -> [n] -> Box l n
Box (l -> LabelTest l
forall l. l -> LabelTest l
ExactLabel l
l) [Int]
i [Int]
o) | Box (Left l
l) [Int]
i [Int]
o <- [Box (Either l String) Int]
bs]

hasSubgraphs :: Rule s l -> Bool
hasSubgraphs :: forall s l. Rule s l -> Bool
hasSubgraphs (SubgraphRule (Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box (Either l String) Int]
bs) Graph s (Either l String)
_) = (Box (Either l String) Int -> Bool)
-> [Box (Either l String) Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any (Either l String -> Bool
forall a b. Either a b -> Bool
isRight (Either l String -> Bool)
-> (Box (Either l String) Int -> Either l String)
-> Box (Either l String) Int
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Box (Either l String) Int -> Either l String
forall l n. Box l n -> l
label) [Box (Either l String) Int]
bs
hasSubgraphs (SortRule [SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]
_ Rule s l
r) = Rule s l -> Bool
forall s l. Rule s l -> Bool
hasSubgraphs Rule s l
r
hasSubgraphs Rule s l
_ = Bool
False

-- | A literal value, a named parameter, or a computed replacement value.
-- Repeated names in a rule bind equal values. Arithmetic constructs replacement
-- expressions; computed expressions are rejected on the left of a rule.
type Parameter :: Type -> Type
data Parameter a
  = Literal a
  | Variable String
  | Computed (S.Set String) (M.Map String a -> Maybe a)

-- | Transform a replacement expression, for example to normalise a phase.
mapParameter :: (a -> a) -> Parameter a -> Parameter a
mapParameter :: forall a. (a -> a) -> Parameter a -> Parameter a
mapParameter a -> a
f (Literal a
a) = a -> Parameter a
forall a. a -> Parameter a
Literal (a -> a
f a
a)
mapParameter a -> a
f Parameter a
p = Set String -> (Map String a -> Maybe a) -> Parameter a
forall a. Set String -> (Map String a -> Maybe a) -> Parameter a
Computed (Parameter a -> Set String
forall a. Parameter a -> Set String
parameterNames Parameter a
p) ((a -> a) -> Maybe a -> Maybe a
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> a
f (Maybe a -> Maybe a)
-> (Map String a -> Maybe a) -> Map String a -> Maybe a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Parameter a -> Map String a -> Maybe a
forall a. Parameter a -> Map String a -> Maybe a
evaluateParameter Parameter a
p)

-- | Combine two replacement expressions, for example by adding phases modulo two.
zipParameters :: (a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
zipParameters :: forall a.
(a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
zipParameters a -> a -> a
f (Literal a
a) (Literal a
b) = a -> Parameter a
forall a. a -> Parameter a
Literal (a -> a -> a
f a
a a
b)
zipParameters a -> a -> a
f Parameter a
a Parameter a
b = Set String -> (Map String a -> Maybe a) -> Parameter a
forall a. Set String -> (Map String a -> Maybe a) -> Parameter a
Computed (Set String -> Set String -> Set String
forall a. Ord a => Set a -> Set a -> Set a
S.union (Parameter a -> Set String
forall a. Parameter a -> Set String
parameterNames Parameter a
a) (Parameter a -> Set String
forall a. Parameter a -> Set String
parameterNames Parameter a
b)) \Map String a
env ->
  a -> a -> a
f (a -> a -> a) -> Maybe a -> Maybe (a -> a)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> Parameter a -> Map String a -> Maybe a
forall a. Parameter a -> Map String a -> Maybe a
evaluateParameter Parameter a
a Map String a
env Maybe (a -> a) -> Maybe a -> Maybe 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 -> Map String a -> Maybe a
forall a. Parameter a -> Map String a -> Maybe a
evaluateParameter Parameter a
b Map String a
env

instance (Num a) => Num (Parameter a) where
  + :: Parameter a -> Parameter a -> Parameter a
(+) = (a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
forall a.
(a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
zipParameters a -> a -> a
forall a. Num a => a -> a -> a
(+)
  (-) = (a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
forall a.
(a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
zipParameters (-)
  * :: Parameter a -> Parameter a -> Parameter a
(*) = (a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
forall a.
(a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
zipParameters a -> a -> a
forall a. Num a => a -> a -> a
(*)
  negate :: Parameter a -> Parameter a
negate = (a -> a) -> Parameter a -> Parameter a
forall a. (a -> a) -> Parameter a -> Parameter a
mapParameter a -> a
forall a. Num a => a -> a
negate
  abs :: Parameter a -> Parameter a
abs = (a -> a) -> Parameter a -> Parameter a
forall a. (a -> a) -> Parameter a -> Parameter a
mapParameter a -> a
forall a. Num a => a -> a
abs
  signum :: Parameter a -> Parameter a
signum = (a -> a) -> Parameter a -> Parameter a
forall a. (a -> a) -> Parameter a -> Parameter a
mapParameter a -> a
forall a. Num a => a -> a
signum
  fromInteger :: Integer -> Parameter a
fromInteger = a -> Parameter a
forall a. a -> Parameter a
Literal (a -> Parameter a) -> (Integer -> a) -> Integer -> Parameter a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> a
forall a. Num a => Integer -> a
fromInteger

instance (Fractional a) => Fractional (Parameter a) where
  / :: Parameter a -> Parameter a -> Parameter a
(/) = (a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
forall a.
(a -> a -> a) -> Parameter a -> Parameter a -> Parameter a
zipParameters a -> a -> a
forall a. Fractional a => a -> a -> a
(/)
  recip :: Parameter a -> Parameter a
recip = (a -> a) -> Parameter a -> Parameter a
forall a. (a -> a) -> Parameter a -> Parameter a
mapParameter a -> a
forall a. Fractional a => a -> a
recip
  fromRational :: Rational -> Parameter a
fromRational = a -> Parameter a
forall a. a -> Parameter a
Literal (a -> Parameter a) -> (Rational -> a) -> Rational -> Parameter a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Rational -> a
forall a. Fractional a => Rational -> a
fromRational

parameterNames :: Parameter a -> S.Set String
parameterNames :: forall a. Parameter a -> Set String
parameterNames (Literal a
_) = Set String
forall a. Set a
S.empty
parameterNames (Variable String
name) = String -> Set String
forall a. a -> Set a
S.singleton String
name
parameterNames (Computed Set String
names Map String a -> Maybe a
_) = Set String
names

evaluateParameter :: Parameter a -> M.Map String a -> Maybe a
evaluateParameter :: forall a. Parameter a -> Map String a -> Maybe a
evaluateParameter (Literal a
a) Map String a
_ = a -> Maybe a
forall a. a -> Maybe a
Just a
a
evaluateParameter (Variable String
name) Map String a
env = String -> Map String a -> Maybe a
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup String
name Map String a
env
evaluateParameter (Computed Set String
_ Map String a -> Maybe a
expression) Map String a
env = Map String a -> Maybe a
expression Map String a
env

-- The constructor key erases only Traversable fields. All other label data,
-- such as a spider's colour, remains part of discrimination-net dispatch.
type LabelTest :: Type -> Type
data LabelTest l where
  ExactLabel :: l -> LabelTest l
  ConstructorLabel :: (Functor f, Eq (f ()), Typeable f) => f () -> LabelTest (f a)

sameLabelTest :: (Eq l) => LabelTest l -> LabelTest l -> Bool
sameLabelTest :: forall l. Eq l => LabelTest l -> LabelTest l -> Bool
sameLabelTest (ExactLabel l
a) (ExactLabel l
b) = l
a l -> l -> Bool
forall a. Eq a => a -> a -> Bool
== l
b
sameLabelTest (ConstructorLabel (f ()
a :: f ())) (ConstructorLabel (f ()
b :: g ())) =
  case forall {k} (a :: k) (b :: k).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
forall (a :: Type -> Type) (b :: Type -> Type).
(Typeable a, Typeable b) =>
Maybe (a :~: b)
eqT @f @g of
    Just f :~: f
Refl -> f ()
a f () -> f () -> Bool
forall a. Eq a => a -> a -> Bool
== f ()
f ()
b
    Maybe (f :~: f)
Nothing -> Bool
False
sameLabelTest LabelTest l
_ LabelTest l
_ = Bool
False

acceptsLabel :: (Eq l) => LabelTest l -> l -> Bool
acceptsLabel :: forall l. Eq l => LabelTest l -> l -> Bool
acceptsLabel (ExactLabel l
expected) l
actual = l
expected l -> l -> Bool
forall a. Eq a => a -> a -> Bool
== l
actual
acceptsLabel (ConstructorLabel f ()
expected) l
actual = f ()
expected f () -> f () -> Bool
forall a. Eq a => a -> a -> Bool
== f a -> f ()
forall (f :: Type -> Type) a. Functor f => f a -> f ()
void l
f a
actual

-- | Construct a rule. Rejects repeated nodes across the left input and output
-- boundaries, since this implementation requires an injective left interface.
-- For example, a chain of two unary boxes can rewrite to an identity wire;
-- the reverse orientation needs a more general complement construction.
rule :: (a :: OPENHG s l) ~> b -> a ~> b -> Either String (Rule s l)
rule :: 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 = do
  Graph s l -> Either String ()
forall s l. Graph s l -> Either String ()
checkInterface ((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)
  Rule s l -> Either String (Rule s l)
forall a. a -> Either String a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (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 ((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)) (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 ((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))))

-- | Construct a rule with parameters in the 'Traversable' fields of its labels.
-- Both diagrams have labels @f (Parameter a)@; hosts have labels @f a@.
-- Constructors and fields outside the traversal match literally. 'Literal'
-- matches one value; 'Variable' binds a name shared across the whole rule.
-- Right-side expressions can use arithmetic and 'mapParameter'. Unbound names
-- and computed left-side expressions are rejected when constructing the rule.
--
-- Rule topology and arity remain fixed. The compiled matcher dispatches on the
-- label with its traversed fields erased, then checks bindings before choosing
-- a batch. Each occurrence gets its own bindings and instantiated replacement.
parameterRule
  :: (Traversable f, Eq (f ()), Typeable f, Eq a)
  => (x :: OPENHG s (f (Parameter a))) ~> y
  -> x ~> y
  -> Either String (Rule s (f a))
parameterRule :: forall (f :: Type -> Type) a s (x :: OPENHG s (f (Parameter a)))
       (y :: OPENHG s (f (Parameter a))).
(Traversable f, Eq (f ()), Typeable f, Eq a) =>
(x ~> y) -> (x ~> y) -> Either String (Rule s (f a))
parameterRule x ~> y
lhs x ~> y
rhs = do
  Graph s (f (Parameter a)) -> Either String ()
forall s l. Graph s l -> Either String ()
checkInterface Graph s (f (Parameter a))
left
  [f (Parameter a)] -> [f (Parameter a)] -> Either String ()
forall (f :: Type -> Type) a.
Foldable f =>
[f (Parameter a)] -> [f (Parameter a)] -> Either String ()
checkParameters [f (Parameter a)]
leftLabels ((Box (f (Parameter a)) Int -> f (Parameter a))
-> [Box (f (Parameter a)) Int] -> [f (Parameter a)]
forall a b. (a -> b) -> [a] -> [b]
map Box (f (Parameter a)) Int -> f (Parameter a)
forall l n. Box l n -> l
label [Box (f (Parameter a)) Int]
rightBoxes)
  Rule s (f a) -> Either String (Rule s (f a))
forall a. a -> Either String a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (Graph s (LabelTest (f a))
-> ([f a] -> Maybe (Graph s (f a))) -> Rule s (f a)
forall s l.
Graph s (LabelTest l) -> ([l] -> Maybe (Graph s l)) -> Rule s l
Rule ((f (Parameter a) -> LabelTest (f a))
-> Graph s (f (Parameter a)) -> Graph s (LabelTest (f a))
forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels (f () -> LabelTest (f a)
forall (f :: Type -> Type) a.
(Functor f, Eq (f ()), Typeable f) =>
f () -> LabelTest (f a)
ConstructorLabel (f () -> LabelTest (f a))
-> (f (Parameter a) -> f ()) -> f (Parameter a) -> LabelTest (f a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. f (Parameter a) -> f ()
forall (f :: Type -> Type) a. Functor f => f a -> f ()
void) Graph s (f (Parameter a))
left) [f a] -> Maybe (Graph s (f a))
instantiate)
  where
    left :: Graph s (f (Parameter a))
left = (x ~> y) -> Graph s (f (Parameter a))
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph x ~> y
lhs
    right :: Graph s (f (Parameter a))
right = (x ~> y) -> Graph s (f (Parameter a))
forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph x ~> y
rhs
    Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box (f (Parameter a)) Int]
leftBoxes = Graph s (f (Parameter a))
left
    Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box (f (Parameter a)) Int]
rightBoxes = Graph s (f (Parameter a))
right
    leftLabels :: [f (Parameter a)]
leftLabels = (Box (f (Parameter a)) Int -> f (Parameter a))
-> [Box (f (Parameter a)) Int] -> [f (Parameter a)]
forall a b. (a -> b) -> [a] -> [b]
map Box (f (Parameter a)) Int -> f (Parameter a)
forall l n. Box l n -> l
label [Box (f (Parameter a)) Int]
leftBoxes
    instantiate :: [f a] -> Maybe (Graph s (f a))
instantiate [f a]
labels = do
      env <- [f (Parameter a)] -> [f a] -> Maybe (Map String a)
forall (f :: Type -> Type) a.
(Foldable f, Eq a) =>
[f (Parameter a)] -> [f a] -> Maybe (Map String a)
parameterBindings [f (Parameter a)]
leftLabels [f a]
labels
      traverseLabels (traverse (`evaluateParameter` env)) right

checkParameters :: (Foldable f) => [f (Parameter a)] -> [f (Parameter a)] -> Either String ()
checkParameters :: forall (f :: Type -> Type) a.
Foldable f =>
[f (Parameter a)] -> [f (Parameter a)] -> Either String ()
checkParameters [f (Parameter a)]
lhs [f (Parameter a)]
rhs = do
  let left :: [Parameter a]
left = (f (Parameter a) -> [Parameter a])
-> [f (Parameter a)] -> [Parameter a]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap f (Parameter a) -> [Parameter a]
forall a. f a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList [f (Parameter a)]
lhs
      leftNames :: Set String
leftNames = [Set String] -> Set String
forall (f :: Type -> Type) a.
(Foldable f, Ord a) =>
f (Set a) -> Set a
S.unions ((Parameter a -> Set String) -> [Parameter a] -> [Set String]
forall a b. (a -> b) -> [a] -> [b]
map Parameter a -> Set String
forall a. Parameter a -> Set String
parameterNames [Parameter a]
left)
      rightNames :: Set String
rightNames = [Set String] -> Set String
forall (f :: Type -> Type) a.
(Foldable f, Ord a) =>
f (Set a) -> Set a
S.unions ((Parameter a -> Set String) -> [Parameter a] -> [Set String]
forall a b. (a -> b) -> [a] -> [b]
map Parameter a -> Set String
forall a. Parameter a -> Set String
parameterNames ((f (Parameter a) -> [Parameter a])
-> [f (Parameter a)] -> [Parameter a]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap f (Parameter a) -> [Parameter a]
forall a. f a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList [f (Parameter a)]
rhs))
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
when ((Parameter a -> Bool) -> [Parameter a] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any Parameter a -> Bool
forall {a}. Parameter a -> Bool
computed [Parameter a]
left) (String -> Either String ()
forall a b. a -> Either a b
Left String
"parameterRule: computed expression on the left")
  Bool -> Either String () -> Either String ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (Set String -> Set String -> Bool
forall a. Ord a => Set a -> Set a -> Bool
S.isSubsetOf Set String
rightNames Set String
leftNames) (String -> Either String ()
forall a b. a -> Either a b
Left String
"parameterRule: unbound parameter on the right")
  where
    computed :: Parameter a -> Bool
computed Computed{} = Bool
True
    computed Parameter a
_ = Bool
False

parameterBindings :: (Foldable f, Eq a) => [f (Parameter a)] -> [f a] -> Maybe (M.Map String a)
parameterBindings :: forall (f :: Type -> Type) a.
(Foldable f, Eq a) =>
[f (Parameter a)] -> [f a] -> Maybe (Map String a)
parameterBindings [f (Parameter a)]
patterns [f a]
labels = do
  let parameters :: [Parameter a]
parameters = (f (Parameter a) -> [Parameter a])
-> [f (Parameter a)] -> [Parameter a]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap f (Parameter a) -> [Parameter a]
forall a. f a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList [f (Parameter a)]
patterns
      values :: [a]
values = (f a -> [a]) -> [f a] -> [a]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap f a -> [a]
forall a. f a -> [a]
forall (t :: Type -> Type) a. Foldable t => t a -> [a]
toList [f a]
labels
  Bool -> Maybe () -> Maybe ()
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless ([Parameter a] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Parameter a]
parameters 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]
values) Maybe ()
forall a. Maybe a
Nothing
  (Map String a -> (Parameter a, a) -> Maybe (Map String a))
-> Map String a -> [(Parameter a, a)] -> Maybe (Map String a)
forall (t :: Type -> Type) (m :: Type -> Type) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM Map String a -> (Parameter a, a) -> Maybe (Map String a)
forall {a}.
Eq a =>
Map String a -> (Parameter a, a) -> Maybe (Map String a)
bind Map String a
forall k a. Map k a
M.empty ([Parameter a] -> [a] -> [(Parameter a, a)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Parameter a]
parameters [a]
values)
  where
    bind :: Map String a -> (Parameter a, a) -> Maybe (Map String a)
bind Map String a
env (Literal a
expected, a
actual) = if a
expected a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
actual then Map String a -> Maybe (Map String a)
forall a. a -> Maybe a
Just Map String a
env else Maybe (Map String a)
forall a. Maybe a
Nothing
    bind Map String a
env (Variable String
name, a
actual) = case String -> Map String a -> Maybe a
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup String
name Map String a
env of
      Just a
expected -> if a
expected a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
actual then Map String a -> Maybe (Map String a)
forall a. a -> Maybe a
Just Map String a
env else Maybe (Map String a)
forall a. Maybe a
Nothing
      Maybe a
Nothing -> Map String a -> Maybe (Map String a)
forall a. a -> Maybe a
Just (String -> a -> Map String a -> Map String a
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert String
name a
actual Map String a
env)
    bind Map String a
_ (Computed{}, a
_) = Maybe (Map String a)
forall a. Maybe a
Nothing

checkInterface :: Graph s l -> Either String ()
checkInterface :: forall s l. Graph s l -> Either String ()
checkInterface (Graph [SomeSort s]
_ [Int]
ins [Int]
outs [Box l Int]
_) =
  let boundary :: [Int]
boundary = [Int]
ins [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
outs
  in if Set Int -> Int
forall a. Set a -> Int
S.size ([Int] -> Set Int
forall a. Ord a => [a] -> Set a
S.fromList [Int]
boundary) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
boundary
       then () -> Either String ()
forall a b. b -> Either a b
Right ()
       else String -> Either String ()
forall a b. a -> Either a b
Left String
"rule: the left boundary must attach to distinct nodes"

mapLabels :: (l -> m) -> Graph s l -> Graph s m
mapLabels :: forall l m s. (l -> m) -> Graph s l -> Graph s m
mapLabels l -> m
f (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs) = [SomeSort s] -> [Int] -> [Int] -> [Box m Int] -> Graph s m
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph [SomeSort s]
ns [Int]
ins [Int]
outs [m -> [Int] -> [Int] -> Box m Int
forall l n. l -> [n] -> [n] -> Box l n
Box (l -> m
f l
l) [Int]
i [Int]
o | Box l
l [Int]
i [Int]
o <- [Box l Int]
bs]

traverseLabels :: (l -> Maybe m) -> Graph s l -> Maybe (Graph s m)
traverseLabels :: forall l m s. (l -> Maybe m) -> Graph s l -> Maybe (Graph s m)
traverseLabels l -> Maybe m
f (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs) = [SomeSort s] -> [Int] -> [Int] -> [Box m Int] -> Graph s m
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph [SomeSort s]
ns [Int]
ins [Int]
outs ([Box m Int] -> Graph s m)
-> Maybe [Box m Int] -> Maybe (Graph s m)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Box l Int -> Maybe (Box m Int))
-> [Box l Int] -> Maybe [Box m 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
l [Int]
i [Int]
o) -> (\m
l' -> m -> [Int] -> [Int] -> Box m Int
forall l n. l -> [n] -> [n] -> Box l n
Box m
l' [Int]
i [Int]
o) (m -> Box m Int) -> Maybe m -> Maybe (Box m Int)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> l -> Maybe m
f l
l) [Box l Int]
bs

sameGraph :: (Eq l, DecidableIso s) => Graph s l -> Graph s l -> Bool
sameGraph :: forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph lhs :: Graph s l
lhs@(Graph [SomeSort s]
ls [Int]
li [Int]
lo [Box l Int]
lb) rhs :: Graph s l
rhs@(Graph [SomeSort s]
rs [Int]
ri [Int]
ro [Box l Int]
rb) =
  [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ls Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
rs
    Bool -> Bool -> Bool
&& [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 -> Bool
forall a. Eq a => a -> a -> Bool
== [Box l Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Box l Int]
rb
    Bool -> Bool -> Bool
&& [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] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
ri
    Bool -> Bool -> Bool
&& [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
lo Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
ro
    Bool -> Bool -> Bool
&& (SomeSort s -> SomeSort s -> Bool)
-> [SomeSort s] -> [SomeSort s] -> Bool
forall {t} {a}. (t -> a -> Bool) -> [t] -> [a] -> Bool
sameMultiset SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort [SomeSort s]
ls [SomeSort s]
rs
    Bool -> Bool -> Bool
&& ((l, Int, Int, [Int]) -> (l, Int, Int, [Int]) -> Bool)
-> [(l, Int, Int, [Int])] -> [(l, Int, Int, [Int])] -> Bool
forall {t} {a}. (t -> a -> Bool) -> [t] -> [a] -> Bool
sameMultiset (l, Int, Int, [Int]) -> (l, Int, Int, [Int]) -> Bool
forall a. Eq a => a -> a -> Bool
(==) ((Box l Int -> (l, Int, Int, [Int]))
-> [Box l Int] -> [(l, Int, Int, [Int])]
forall a b. (a -> b) -> [a] -> [b]
map Box l Int -> (l, Int, Int, [Int])
forall {a}. Box a Int -> (a, Int, Int, [Int])
boxShape [Box l Int]
lb) ((Box l Int -> (l, Int, Int, [Int]))
-> [Box l Int] -> [(l, Int, Int, [Int])]
forall a b. (a -> b) -> [a] -> [b]
map Box l Int -> (l, Int, Int, [Int])
forall {a}. Box a Int -> (a, Int, Int, [Int])
boxShape [Box l Int]
rb)
    Bool -> Bool -> Bool
&& Bool -> Bool
not ([(Match, [l])] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null ([(Int, Int)]
-> Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
forall l s.
(Eq l, DecidableIso s) =>
[(Int, Int)]
-> Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matchesWithBindings ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
li [Int]
ri [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)]
forall a. [a] -> [a] -> [a]
++ [Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
lo [Int]
ro) ((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) Graph s l
rhs))
  where
    boxShape :: Box a Int -> (a, Int, Int, [Int])
boxShape (Box a
l [Int]
ins [Int]
outs) = (a
l, [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
ins, [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
outs, (IntMap Int, [Int]) -> [Int]
forall a b. (a, b) -> b
snd ((IntMap Int -> Int -> (IntMap Int, Int))
-> IntMap Int -> [Int] -> (IntMap Int, [Int])
forall (t :: Type -> Type) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
mapAccumL IntMap Int -> Int -> (IntMap Int, Int)
numberPort IntMap Int
forall a. IntMap a
IM.empty ([Int]
ins [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
outs)))
    -- Number each node by its first occurrence, across both port lists.
    numberPort :: IntMap Int -> Int -> (IntMap Int, Int)
numberPort IntMap Int
seen Int
node = case Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
node IntMap Int
seen of
      Just Int
number -> (IntMap Int
seen, Int
number)
      Maybe Int
Nothing ->
        let number :: Int
number = IntMap Int -> Int
forall a. IntMap a -> Int
IM.size IntMap Int
seen
        in (Int -> Int -> IntMap Int -> IntMap Int
forall a. Int -> a -> IntMap a -> IntMap a
IM.insert Int
node Int
number IntMap Int
seen, Int
number)
    sameMultiset :: (t -> a -> Bool) -> [t] -> [a] -> Bool
sameMultiset t -> a -> Bool
_ [] [a]
ys = [a] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null [a]
ys
    sameMultiset t -> a -> Bool
equal (t
x : [t]
xs) [a]
ys = case (a -> Bool) -> [a] -> ([a], [a])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (t -> a -> Bool
equal t
x) [a]
ys of
      ([a]
_, []) -> Bool
False
      ([a]
before, a
_ : [a]
after) -> (t -> a -> Bool) -> [t] -> [a] -> Bool
sameMultiset t -> a -> Bool
equal [t]
xs ([a]
before [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ [a]
after)

graph :: (a :: OPENHG s l) ~> b -> Graph s l
graph :: forall s l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> Graph s l
graph a ~> b
h = let ([SomeSort s]
ns, [Int]
i, [Int]
o, [Box l Int]
bs) = (a ~> b) -> ([SomeSort s], [Int], [Int], [Box l Int])
forall {s} l (a :: OPENHG s l) (b :: OPENHG s l).
(a ~> b) -> ([SomeSort s], [Int], [Int], [Box l Int])
hypergraphParts a ~> b
h in [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]
i [Int]
o [Box l Int]
bs

-- Node images and the set of selected host box occurrences.
type Match = (IM.IntMap Int, IS.IntSet)

internalNodes :: Graph s l -> [Int]
internalNodes :: forall s l. Graph s l -> [Int]
internalNodes (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
_) = [Int
n | Int
n <- [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
n IntSet
interface]
  where
    interface :: IntSet
interface = [Int] -> IntSet
IS.fromList ([Int]
ins [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
outs)

deletedImages :: Graph s l -> IM.IntMap Int -> IS.IntSet
deletedImages :: forall s l. Graph s l -> IntMap Int -> IntSet
deletedImages Graph s l
lhs IntMap Int
m = [Int] -> IntSet
IS.fromList [IntMap Int
m IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
n | Int
n <- Graph s l -> [Int]
forall s l. Graph s l -> [Int]
internalNodes Graph s l
lhs]

-- Track both read and deleted nodes: disjoint box sets alone do not protect
-- isolated nodes or interface nodes of another match.
nonConflictingBy :: (a -> Match -> IS.IntSet) -> [(a, Match)] -> [(a, Match)]
nonConflictingBy :: forall a. (a -> Match -> IntSet) -> [(a, Match)] -> [(a, Match)]
nonConflictingBy a -> Match -> IntSet
deletions [(a, Match)]
candidates = [(a, Match)] -> [(a, Match)]
forall a. [a] -> [a]
reverse [(a, Match)]
chosen
  where
    ([(a, Match)]
chosen, IntSet
_, IntSet
_, IntSet
_) = (([(a, Match)], IntSet, IntSet, IntSet)
 -> (a, Match) -> ([(a, Match)], IntSet, IntSet, IntSet))
-> ([(a, Match)], IntSet, IntSet, IntSet)
-> [(a, Match)]
-> ([(a, Match)], IntSet, IntSet, IntSet)
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' ([(a, Match)], IntSet, IntSet, IntSet)
-> (a, Match) -> ([(a, Match)], IntSet, IntSet, IntSet)
select ([], IntSet
IS.empty, IntSet
IS.empty, IntSet
IS.empty) [(a, Match)]
candidates
    select :: ([(a, Match)], IntSet, IntSet, IntSet)
-> (a, Match) -> ([(a, Match)], IntSet, IntSet, IntSet)
select state :: ([(a, Match)], IntSet, IntSet, IntSet)
state@([(a, Match)]
accepted, IntSet
boxes, IntSet
nodes, IntSet
deleted) candidate :: (a, Match)
candidate@(a
key, match :: Match
match@(IntMap Int
mapping, IntSet
used)) =
      let readNodes :: IntSet
readNodes = [Int] -> IntSet
IS.fromList (IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
mapping)
          deleteNodes :: IntSet
deleteNodes = a -> Match -> IntSet
deletions a
key Match
match
      in if IntSet -> IntSet -> Bool
IS.disjoint IntSet
boxes IntSet
used Bool -> Bool -> Bool
&& IntSet -> IntSet -> Bool
IS.disjoint IntSet
deleted IntSet
readNodes Bool -> Bool -> Bool
&& IntSet -> IntSet -> Bool
IS.disjoint IntSet
nodes IntSet
deleteNodes
           then ((a, Match)
candidate (a, Match) -> [(a, Match)] -> [(a, Match)]
forall a. a -> [a] -> [a]
: [(a, Match)]
accepted, IntSet -> IntSet -> IntSet
IS.union IntSet
boxes IntSet
used, IntSet -> IntSet -> IntSet
IS.union IntSet
nodes IntSet
readNodes, IntSet -> IntSet -> IntSet
IS.union IntSet
deleted IntSet
deleteNodes)
           else ([(a, Match)], IntSet, IntSet, IntSet)
state

matches :: (Eq l, DecidableIso s) => Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matches :: forall l s.
(Eq l, DecidableIso s) =>
Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matches = [(Int, Int)]
-> Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
forall l s.
(Eq l, DecidableIso s) =>
[(Int, Int)]
-> Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matchesWithBindings []

matchesWithBindings :: (Eq l, DecidableIso s) => [(Int, Int)] -> Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matchesWithBindings :: forall l s.
(Eq l, DecidableIso s) =>
[(Int, Int)]
-> Graph s (LabelTest l) -> Graph s l -> [(Match, [l])]
matchesWithBindings [(Int, Int)]
bindings (Graph [SomeSort s]
ns [Int]
li [Int]
lo [Box (LabelTest l) Int]
boxes) (Graph [SomeSort s]
hs [Int]
hi [Int]
ho [Box l Int]
hostBoxes) = do
  initial <- [Match] -> (Match -> [Match]) -> Maybe Match -> [Match]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Match -> [Match]
forall a. a -> [a]
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure ((Match -> (Int, Int) -> Maybe Match)
-> Match -> [(Int, Int)] -> Maybe Match
forall (t :: Type -> Type) (m :: Type -> Type) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM Match -> (Int, Int) -> Maybe Match
extend (IntMap Int
forall a. IntMap a
IM.empty, IntSet
IS.empty) [(Int, Int)]
bindings)
  (nodes, used, labels) <- matchBoxes plans initial IS.empty
  match <- complete [0 .. V.length patternSorts - 1] nodes used
  pure (match, labels)
  where
    patternSorts :: Vector (SomeSort s)
patternSorts = [SomeSort s] -> Vector (SomeSort s)
forall a. [a] -> Vector a
V.fromList [SomeSort s]
ns
    hostSorts :: Vector (SomeSort s)
hostSorts = [SomeSort s] -> Vector (SomeSort s)
forall a. [a] -> Vector a
V.fromList [SomeSort s]
hs
    host :: Vector (Box l Int)
host = [Box l Int] -> Vector (Box l Int)
forall a. [a] -> Vector a
V.fromList [Box l Int]
hostBoxes
    numbered :: [(Int, Box l Int)]
numbered = [Int] -> [Box l Int] -> [(Int, Box l Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [Box l Int]
hostBoxes
    -- Keep host box order within each node's incidences.
    byNode :: Vector [(Int, Int)]
byNode =
      ([(Int, Int)] -> [(Int, Int)])
-> Vector [(Int, Int)] -> Vector [(Int, Int)]
forall a b. (a -> b) -> Vector a -> Vector b
V.map [(Int, Int)] -> [(Int, Int)]
forall a. [a] -> [a]
reverse (Vector [(Int, Int)] -> Vector [(Int, Int)])
-> Vector [(Int, Int)] -> Vector [(Int, Int)]
forall a b. (a -> b) -> a -> b
$
        ([(Int, Int)] -> (Int, Int) -> [(Int, Int)])
-> Vector [(Int, Int)]
-> [(Int, (Int, Int))]
-> Vector [(Int, Int)]
forall a b. (a -> b -> a) -> Vector a -> [(Int, b)] -> Vector a
V.accum
          (((Int, Int) -> [(Int, Int)] -> [(Int, Int)])
-> [(Int, Int)] -> (Int, Int) -> [(Int, Int)]
forall a b c. (a -> b -> c) -> b -> a -> c
flip (:))
          (Int -> [(Int, Int)] -> Vector [(Int, Int)]
forall a. Int -> a -> Vector a
V.replicate (Vector (SomeSort s) -> Int
forall a. Vector a -> Int
V.length Vector (SomeSort s)
hostSorts) [])
          [(Int
n, (Int
p, Int
i)) | (Int
i, Box l Int
b) <- [(Int, Box l Int)]
numbered, (Int
p, Int
n) <- Box l Int -> [(Int, Int)]
forall l n. Box l n -> [(Int, n)]
portsOf Box l Int
b]
    atNode :: Int -> [(Int, Int)]
atNode Int
n = Vector [(Int, Int)]
byNode Vector [(Int, Int)] -> Int -> [(Int, Int)]
forall a. Vector a -> Int -> a
V.! Int
n
    boundary :: IntSet
boundary = [Int] -> IntSet
IS.fromList ([Int]
hi [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
ho)
    interface :: IntSet
interface = [Int] -> IntSet
IS.fromList ([Int]
li [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
lo)
    internal :: [Int]
internal = [Int
n | Int
n <- [Int
0 .. Vector (SomeSort s) -> Int
forall a. Vector a -> Int
V.length Vector (SomeSort s)
patternSorts Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1], Int -> IntSet -> Bool
IS.notMember Int
n IntSet
interface]
    plans :: [(Box (LabelTest l) Int, [(Int, Box l Int)])]
plans =
      [ (Box (LabelTest l) Int
b, [(Int
i, Box l Int
h) | (Int
i, Box l Int
h) <- [(Int, Box l Int)]
numbered, Box (LabelTest l) Int -> Box l Int -> Bool
forall {l} {a} {a}. Eq l => Box (LabelTest l) a -> Box l a -> Bool
compatible Box (LabelTest l) Int
b Box l Int
h])
      | Box (LabelTest l) Int
b <- [Box (LabelTest l) Int]
boxes
      ]
    compatible :: Box (LabelTest l) a -> Box l a -> Bool
compatible (Box LabelTest l
l [a]
i [a]
o) (Box l
l' [a]
i' [a]
o') = LabelTest l -> l -> Bool
forall l. Eq l => LabelTest l -> l -> Bool
acceptsLabel LabelTest l
l l
l' 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]
i' 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]
o'
    extend :: Match -> (Int, Int) -> Maybe Match
extend state :: Match
state@(IntMap Int
m, IntSet
range) (Int
x, Int
y)
      | Just Int
y' <- Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
x IntMap Int
m = if Int
y Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
y' then Match -> Maybe Match
forall a. a -> Maybe a
Just Match
state else Maybe Match
forall a. Maybe a
Nothing
      | Int -> IntSet -> Bool
IS.member Int
y IntSet
range = Maybe Match
forall a. Maybe a
Nothing
      | Bool -> Bool
not (SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort (Vector (SomeSort s)
patternSorts Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.! Int
x) (Vector (SomeSort s)
hostSorts Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.! Int
y)) = 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
x Int
y IntMap Int
m, Int -> IntSet -> IntSet
IS.insert Int
y IntSet
range)
    matchBoxes :: [(Box (LabelTest l) Int, [(Int, Box l Int)])]
-> Match -> IntSet -> [(Match, IntSet, [l])]
matchBoxes [] Match
m IntSet
used = [(Match
m, IntSet
used, [])]
    matchBoxes ((b :: Box (LabelTest l) Int
b@(Box LabelTest l
_ [Int]
ins [Int]
outs), [(Int, Box l Int)]
base) : [(Box (LabelTest l) Int, [(Int, Box l Int)])]
rest) nodes :: Match
nodes@(IntMap Int
m, IntSet
_) IntSet
used = do
      let constrained :: [[Int]]
constrained =
            [ [Int
i | (Int
s, Int
i) <- Int -> [(Int, Int)]
atNode Int
y, Int
s Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
p]
            | (Int
p, Int
x) <- Box (LabelTest l) Int -> [(Int, Int)]
forall l n. Box l n -> [(Int, n)]
portsOf Box (LabelTest l) Int
b
            , Just Int
y <- [Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
x IntMap Int
m]
            ]
          candidates :: [(Int, Box l Int)]
candidates = case [[Int]]
constrained of
            [] -> [(Int
i, Box l Int
h) | (Int
i, Box l Int
h) <- [(Int, Box l Int)]
base, Int -> IntSet -> Bool
IS.notMember Int
i IntSet
used]
            [Int]
first : [[Int]]
more ->
              -- Start from the smallest known-port neighbourhood; extend checks every port.
              [ (Int
i, Box l Int
h)
              | Int
i <- ([Int] -> [Int] -> [Int]) -> [Int] -> [[Int]] -> [Int]
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' [Int] -> [Int] -> [Int]
forall {t :: Type -> Type} {a}. Foldable t => t a -> t a -> t a
shorter [Int]
first [[Int]]
more
              , Int -> IntSet -> Bool
IS.notMember Int
i IntSet
used
              , let h :: Box l Int
h = Vector (Box l Int)
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i
              , Box (LabelTest l) Int -> Box l Int -> Bool
forall {l} {a} {a}. Eq l => Box (LabelTest l) a -> Box l a -> Bool
compatible Box (LabelTest l) Int
b Box l Int
h
              ]
      (i, Box l ins' outs') <- [(Int, Box l Int)]
candidates
      case foldM extend nodes (zip ins ins' ++ zip outs outs') of
        Maybe Match
Nothing -> []
        Just Match
nodes' -> [(Match
m', IntSet
used', l
l l -> [l] -> [l]
forall a. a -> [a] -> [a]
: [l]
labels) | (Match
m', IntSet
used', [l]
labels) <- [(Box (LabelTest l) Int, [(Int, Box l Int)])]
-> Match -> IntSet -> [(Match, IntSet, [l])]
matchBoxes [(Box (LabelTest l) Int, [(Int, Box l Int)])]
rest Match
nodes' (Int -> IntSet -> IntSet
IS.insert Int
i IntSet
used)]
    shorter :: t a -> t a -> t a
shorter t a
a t a
b = if t a -> Int
forall a. t a -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length t a
a Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= t a -> Int
forall a. t a -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length t a
b then t a
a else t a
b
    complete :: [Int] -> Match -> IntSet -> [Match]
complete [] (IntMap Int
m, IntSet
_) IntSet
used
      | (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (IntMap Int -> IntSet -> Int -> Bool
deletable IntMap Int
m IntSet
used) [Int]
internal = [(IntMap Int
m, IntSet
used)]
      | Bool
otherwise = []
    complete (Int
x : [Int]
xs) nodes :: Match
nodes@(IntMap Int
m, IntSet
_) IntSet
used
      | Int -> IntMap Int -> Bool
forall a. Int -> IntMap a -> Bool
IM.member Int
x IntMap Int
m = [Int] -> Match -> IntSet -> [Match]
complete [Int]
xs Match
nodes IntSet
used
      | Bool
otherwise = do
          y <- [Int
0 .. Vector (SomeSort s) -> Int
forall a. Vector a -> Int
V.length Vector (SomeSort s)
hostSorts Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
          nodes' <- maybe [] pure (extend nodes (x, y))
          complete xs nodes' used
    deletable :: IntMap Int -> IntSet -> Int -> Bool
deletable IntMap Int
m IntSet
used Int
x =
      let y :: Int
y = IntMap Int
m IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
x
      in Int -> IntSet -> Bool
IS.notMember Int
y IntSet
boundary Bool -> Bool -> Bool
&& ((Int, Int) -> Bool) -> [(Int, Int)] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\(Int
_, Int
i) -> Int -> IntSet -> Bool
IS.member Int
i IntSet
used) (Int -> [(Int, Int)]
atNode Int
y)

-- Matches satisfy the dangling condition and have non-conflicting deletions.
replaceMany :: Graph s p -> Graph s l -> Graph s l -> [Match] -> Graph s l
replaceMany :: forall s p l.
Graph s p -> Graph s l -> Graph s l -> [Match] -> Graph s l
replaceMany Graph s p
lhs Graph s l
rhs Graph s l
host [Match]
chosen = Graph s l -> [(Graph s p, Graph s l, Match)] -> Graph s l
forall s l p.
Graph s l -> [(Graph s p, Graph s l, Match)] -> Graph s l
replaceSelected Graph s l
host [(Graph s p
lhs, Graph s l
rhs, Match
m) | Match
m <- [Match]
chosen]

replaceSelected :: Graph s l -> [(Graph s p, Graph s l, Match)] -> Graph s l
replaceSelected :: forall s l p.
Graph s l -> [(Graph s p, Graph s l, Match)] -> Graph s l
replaceSelected (Graph [SomeSort s]
hs [Int]
hi [Int]
ho [Box l Int]
hb) [(Graph s p, Graph s l, Match)]
chosen =
  [SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph (IntMap (SomeSort s) -> [SomeSort s]
forall a. IntMap a -> [a]
IM.elems IntMap (SomeSort s)
nodeSorts) ((Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Int
renumber [Int]
hi) ((Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Int
renumber [Int]
ho) ((Box l Int -> Box l Int) -> [Box l Int] -> [Box l Int]
forall a b. (a -> b) -> [a] -> [b]
map ((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 Int -> Int
renumber) [Box l Int]
boxes)
  where
    deleted :: IntSet
deleted = [IntSet] -> IntSet
forall (f :: Type -> Type). Foldable f => f IntSet -> IntSet
IS.unions [Graph s p -> IntMap Int -> IntSet
forall s l. Graph s l -> IntMap Int -> IntSet
deletedImages Graph s p
lhs IntMap Int
mapping | (Graph s p
lhs, Graph s l
_, (IntMap Int
mapping, IntSet
_)) <- [(Graph s p, Graph s l, Match)]
chosen]
    selected :: IntSet
selected = [IntSet] -> IntSet
forall (f :: Type -> Type). Foldable f => f IntSet -> IntSet
IS.unions [IntSet
used | (Graph s p
_, Graph s l
_, (IntMap Int
_, IntSet
used)) <- [(Graph s p, Graph s l, Match)]
chosen]
    retainedBoxes :: [Box l Int]
retainedBoxes = [Box l Int
b | (Int
i, 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]
hb, Int -> IntSet -> Bool
IS.notMember Int
i IntSet
selected]
    (Int
_, [(Int, (Graph s p, Graph s l, Match))]
copies) = (Int
 -> (Graph s p, Graph s l, Match)
 -> (Int, (Int, (Graph s p, Graph s l, Match))))
-> Int
-> [(Graph s p, Graph s l, Match)]
-> (Int, [(Int, (Graph s p, Graph s l, Match))])
forall (t :: Type -> Type) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
mapAccumL (\Int
start entry :: (Graph s p, Graph s l, Match)
entry@(Graph s p
_, Graph [SomeSort s]
rs [Int]
_ [Int]
_ [Box l Int]
_, Match
_) -> (Int
start Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
rs, (Int
start, (Graph s p, Graph s l, Match)
entry))) ([SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
hs) [(Graph s p, Graph s l, Match)]
chosen
    root :: Int -> Int
root =
      [(Int, Int)] -> Int -> Int
forall a. Enum a => [(a, a)] -> a -> a
unionFind
        [ (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
l, Int
start Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
r)
        | (Int
start, (Graph [SomeSort s]
_ [Int]
li [Int]
lo [Box p Int]
_, Graph [SomeSort s]
_ [Int]
ri [Int]
ro [Box l Int]
_, (IntMap Int
mapping, IntSet
_))) <- [(Int, (Graph s p, Graph s l, Match))]
copies
        , (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]
ri [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
ro)
        ]
    nodes :: [(Int, SomeSort s)]
nodes =
      [(Int
i, SomeSort s
s) | (Int
i, SomeSort s
s) <- [Int] -> [SomeSort s] -> [(Int, SomeSort s)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [SomeSort s]
hs, Int -> IntSet -> Bool
IS.notMember Int
i IntSet
deleted]
        [(Int, SomeSort s)] -> [(Int, SomeSort s)] -> [(Int, SomeSort s)]
forall a. [a] -> [a] -> [a]
++ [[(Int, SomeSort s)]] -> [(Int, SomeSort s)]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat [[Int] -> [SomeSort s] -> [(Int, SomeSort s)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
start ..] [SomeSort s]
rs | (Int
start, (Graph s p
_, Graph [SomeSort s]
rs [Int]
_ [Int]
_ [Box l Int]
_, Match
_)) <- [(Int, (Graph s p, Graph s l, Match))]
copies]
    nodeSorts :: IntMap (SomeSort s)
nodeSorts = [(Int, SomeSort s)] -> IntMap (SomeSort s)
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int -> Int
root Int
i, SomeSort s
s) | (Int
i, SomeSort s
s) <- [(Int, SomeSort s)]
nodes]
    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 (IntMap (SomeSort s) -> [Int]
forall a. IntMap a -> [Int]
IM.keys IntMap (SomeSort s)
nodeSorts) [Int
0 ..])
    renumber :: Int -> Int
renumber Int
i = IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int -> Int
root Int
i
    boxes :: [Box l Int]
boxes = [Box l Int]
retainedBoxes [Box l Int] -> [Box l Int] -> [Box l Int]
forall a. [a] -> [a] -> [a]
++ [[Box l Int]] -> [Box l Int]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat [(Box l Int -> Box l Int) -> [Box l Int] -> [Box l Int]
forall a b. (a -> b) -> [a] -> [b]
map ((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 (Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
start)) [Box l Int]
rb | (Int
start, (Graph s p
_, Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box l Int]
rb, Match
_)) <- [(Int, (Graph s p, Graph s l, Match))]
copies]

portsOf :: Box l n -> [(Int, n)]
portsOf :: forall l n. Box l n -> [(Int, n)]
portsOf (Box l
_ [n]
ins [n]
outs) = [(Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
p, n
n) | (Int
p, n
n) <- [Int] -> [n] -> [(Int, n)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [n]
ins] [(Int, n)] -> [(Int, n)] -> [(Int, n)]
forall a. [a] -> [a] -> [a]
++ [(Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
p Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1, n
n) | (Int
p, n
n) <- [Int] -> [n] -> [(Int, n)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [n]
outs]

type Prepared :: Kind -> Type -> Type
type Prepared s l = (Graph s (LabelTest l), Graph s l, Match)

-- | Bounds on successful rule applications and batches. 'Nothing' leaves that
-- count unrestricted; zero permits checking for a normal form but no applications.
-- These limits do not bound the cost of finding matches.
data RewriteLimits = RewriteLimits
  { RewriteLimits -> Maybe Natural
maxRewrites :: Maybe Natural
  , RewriteLimits -> Maybe Natural
maxBatches :: Maybe Natural
  }
  deriving (RewriteLimits -> RewriteLimits -> Bool
(RewriteLimits -> RewriteLimits -> Bool)
-> (RewriteLimits -> RewriteLimits -> Bool) -> Eq RewriteLimits
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RewriteLimits -> RewriteLimits -> Bool
== :: RewriteLimits -> RewriteLimits -> Bool
$c/= :: RewriteLimits -> RewriteLimits -> Bool
/= :: RewriteLimits -> RewriteLimits -> Bool
Eq, Int -> RewriteLimits -> ShowS
[RewriteLimits] -> ShowS
RewriteLimits -> String
(Int -> RewriteLimits -> ShowS)
-> (RewriteLimits -> String)
-> ([RewriteLimits] -> ShowS)
-> Show RewriteLimits
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> RewriteLimits -> ShowS
showsPrec :: Int -> RewriteLimits -> ShowS
$cshow :: RewriteLimits -> String
show :: RewriteLimits -> String
$cshowList :: [RewriteLimits] -> ShowS
showList :: [RewriteLimits] -> ShowS
Show)

-- | No rewrite or batch limit. Use when the rules are known to terminate, or
-- with the strictly decreasing policy of 'Proarrow.Tools.HypergraphRewrite.compileReducingRules'.
unlimitedRewrites :: RewriteLimits
unlimitedRewrites :: RewriteLimits
unlimitedRewrites = Maybe Natural -> Maybe Natural -> RewriteLimits
RewriteLimits Maybe Natural
forall a. Maybe a
Nothing Maybe Natural
forall a. Maybe a
Nothing

-- | Why normalisation stopped. A normal form has no applicable rule, even when
-- a limit was reached exactly. If both limits prevent further rewriting, the
-- rewrite limit takes precedence.
data NormalisationStatus = NormalForm | RewriteLimitReached | BatchLimitReached
  deriving (NormalisationStatus -> NormalisationStatus -> Bool
(NormalisationStatus -> NormalisationStatus -> Bool)
-> (NormalisationStatus -> NormalisationStatus -> Bool)
-> Eq NormalisationStatus
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: NormalisationStatus -> NormalisationStatus -> Bool
== :: NormalisationStatus -> NormalisationStatus -> Bool
$c/= :: NormalisationStatus -> NormalisationStatus -> Bool
/= :: NormalisationStatus -> NormalisationStatus -> Bool
Eq, Int -> NormalisationStatus -> ShowS
[NormalisationStatus] -> ShowS
NormalisationStatus -> String
(Int -> NormalisationStatus -> ShowS)
-> (NormalisationStatus -> String)
-> ([NormalisationStatus] -> ShowS)
-> Show NormalisationStatus
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> NormalisationStatus -> ShowS
showsPrec :: Int -> NormalisationStatus -> ShowS
$cshow :: NormalisationStatus -> String
show :: NormalisationStatus -> String
$cshowList :: [NormalisationStatus] -> ShowS
showList :: [NormalisationStatus] -> ShowS
Show)

-- | The current graph and counts of successful rule applications and nonempty
-- batches. Counts and limits are local to this call; the graph can be passed to
-- 'Proarrow.Tools.HypergraphRewrite.normalise' again to continue after exhausting a limit.
type NormalisationResult :: Type -> Type
data NormalisationResult a = NormalisationResult
  { forall a. NormalisationResult a -> a
normalisedGraph :: a
  , forall a. NormalisationResult a -> NormalisationStatus
normalisationStatus :: NormalisationStatus
  , forall a. NormalisationResult a -> Natural
normalisationRewrites :: Natural
  , forall a. NormalisationResult a -> Natural
normalisationBatches :: Natural
  }

normaliseBy
  :: forall {s} l as bs
   . RewriteLimits
  -> (Graph s l -> [Prepared s l])
  -> (Wires as :: OPENHG s l) ~> Wires bs
  -> NormalisationResult (Wires as ~> (Wires bs :: OPENHG s l))
normaliseBy :: 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 Graph s l -> [Prepared s l]
next Wires as ~> Wires bs
host =
  Wires as ~> Wires bs
DecCospan (Wires as) (Wires bs)
host DecCospan (Wires as) (Wires bs)
-> ((Ob (Wires as), Ob (Wires bs)) =>
    NormalisationResult (DecCospan (Wires as) (Wires bs)))
-> NormalisationResult (DecCospan (Wires as) (Wires bs))
forall {k1} {k2} (p :: k1 +-> k2) (a :: k2) (b :: k1) r.
Profunctor p =>
p a b -> ((Ob a, Ob b) => r) -> r
//
    let 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 RewriteLimits
limits Graph s l -> [Prepared s l]
next ((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)
        Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
boxes = NormalisationResult (Graph s l) -> Graph s l
forall a. NormalisationResult a -> a
normalisedGraph NormalisationResult (Graph s l)
result
        output :: Wires as ~> Wires bs
output = if NormalisationResult (Graph s l) -> Natural
forall a. NormalisationResult a -> Natural
normalisationBatches NormalisationResult (Graph s l)
result Natural -> Natural -> Bool
forall a. Eq a => a -> a -> Bool
== Natural
0 then Wires as ~> Wires bs
host else [SomeSort s]
-> [Int] -> [Int] -> [Box l Int] -> Wires as ~> Wires bs
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]
ns [Int]
ins [Int]
outs [Box l Int]
boxes
    in NormalisationResult (Graph s l)
result{normalisedGraph = output}

normaliseGraphBy
  :: RewriteLimits -> (Graph s l -> [Prepared s l]) -> Graph s l -> NormalisationResult (Graph s l)
normaliseGraphBy :: forall s l.
RewriteLimits
-> (Graph s l -> [Prepared s l])
-> Graph s l
-> NormalisationResult (Graph s l)
normaliseGraphBy RewriteLimits
limits Graph s l -> [Prepared s l]
next = Natural -> Natural -> Graph s l -> NormalisationResult (Graph s l)
go Natural
0 Natural
0
  where
    reached :: Maybe a -> a -> Bool
reached Maybe a
limit a
count = Bool -> (a -> Bool) -> Maybe a -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (a
count a -> a -> Bool
forall a. Ord a => a -> a -> Bool
>=) Maybe a
limit
    go :: Natural -> Natural -> Graph s l -> NormalisationResult (Graph s l)
go !Natural
steps !Natural
batches Graph s l
current = case Graph s l -> [Prepared s l]
next Graph s l
current of
      [] -> Graph s l
-> NormalisationStatus
-> Natural
-> Natural
-> NormalisationResult (Graph s l)
forall a.
a
-> NormalisationStatus
-> Natural
-> Natural
-> NormalisationResult a
NormalisationResult Graph s l
current NormalisationStatus
NormalForm Natural
steps Natural
batches
      [Prepared s l]
chosen
        | Maybe Natural -> Natural -> Bool
forall {a}. Ord a => Maybe a -> a -> Bool
reached (RewriteLimits -> Maybe Natural
maxRewrites RewriteLimits
limits) Natural
steps -> Graph s l
-> NormalisationStatus
-> Natural
-> Natural
-> NormalisationResult (Graph s l)
forall a.
a
-> NormalisationStatus
-> Natural
-> Natural
-> NormalisationResult a
NormalisationResult Graph s l
current NormalisationStatus
RewriteLimitReached Natural
steps Natural
batches
        | Maybe Natural -> Natural -> Bool
forall {a}. Ord a => Maybe a -> a -> Bool
reached (RewriteLimits -> Maybe Natural
maxBatches RewriteLimits
limits) Natural
batches -> Graph s l
-> NormalisationStatus
-> Natural
-> Natural
-> NormalisationResult (Graph s l)
forall a.
a
-> NormalisationStatus
-> Natural
-> Natural
-> NormalisationResult a
NormalisationResult Graph s l
current NormalisationStatus
BatchLimitReached Natural
steps Natural
batches
        | Bool
otherwise ->
            let applied :: [Prepared s l]
applied = case RewriteLimits -> Maybe Natural
maxRewrites RewriteLimits
limits of
                  Maybe Natural
Nothing -> [Prepared s l]
chosen
                  Just Natural
limit -> Natural -> [Prepared s l] -> [Prepared s l]
forall i a. Integral i => i -> [a] -> [a]
genericTake (Natural
limit Natural -> Natural -> Natural
forall a. Num a => a -> a -> a
- Natural
steps) [Prepared s l]
chosen
                count :: Natural
count = Int -> Natural
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Prepared s l] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Prepared s l]
applied)
            in Natural -> Natural -> Graph s l -> NormalisationResult (Graph s l)
go (Natural
steps Natural -> Natural -> Natural
forall a. Num a => a -> a -> a
+ Natural
count) (Natural
batches Natural -> Natural -> Natural
forall a. Num a => a -> a -> a
+ Natural
1) (Graph s l -> [Prepared s l] -> Graph s l
forall s l p.
Graph s l -> [(Graph s p, Graph s l, Match)] -> Graph s l
replaceSelected Graph s l
current [Prepared s l]
applied)