-- | Compile and run the discrimination net for many-to-one graph matching.
module Proarrow.Tools.HypergraphRewrite.Internal.Matcher
  ( CompiledRules (..)
  , compileRuleSet
  , compiledMatches
  , compiledMatchesAvoiding
  ) where

import Control.Monad (foldM, unless, when)
import Data.Containers.ListUtils (nubOrd)
import Data.IntMap.Strict qualified as IM
import Data.IntSet qualified as IS
import Data.Kind (Type)
import Data.List (mapAccumL, maximumBy, sortOn)
import Data.Map.Strict qualified as M
import Data.Maybe (maybeToList)
import Data.Ord (comparing)
import Data.Set qualified as S
import Data.Vector qualified as V
import Prelude

import Proarrow.Category.Instance.FinHask (unionFind)
import Proarrow.Category.Instance.OpenHypergraph (Box (..), SomeSort, sameSort)
import Proarrow.Core (Kind)
import Proarrow.Optic.Iso (DecidableIso)
import Proarrow.Tools.HypergraphRewrite.Internal
  ( Graph (..)
  , LabelTest (..)
  , Port (..)
  , PortGraph (..)
  , Prepared
  , Rule (..)
  , acceptsLabel
  , hasSubgraphs
  , instantiatePorts
  , internalNodes
  , mapLabels
  , portsOf
  , rulePattern
  , sameGraph
  , sameLabelTest
  )

-- | Rules compiled into a discrimination net of box-selection and port-binding
-- tests. Common prefixes share their matching work. Graph-node bindings add
-- repeated-wire, sort, and injectivity checks to the usual discrimination-net
-- construction for many-to-one term matching; see
-- <https://arxiv.org/abs/1710.06915 MatchPy: A Pattern Matching Library>.
-- A single host index is shared by every rule in one matching pass.
--
-- Keys identify rules and give an explicit conflict priority: smaller keys win.
-- The order of the input list does not affect matching or batch selection.
type CompiledRules :: Type -> Kind -> Type -> Type
data CompiledRules key s l = CompiledRules (V.Vector (key, Rule s l)) (V.Vector (Signature l)) (Net s) Bool

data Arity = Exactly Int | AtLeast Int deriving (Arity -> Arity -> Bool
(Arity -> Arity -> Bool) -> (Arity -> Arity -> Bool) -> Eq Arity
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Arity -> Arity -> Bool
== :: Arity -> Arity -> Bool
$c/= :: Arity -> Arity -> Bool
/= :: Arity -> Arity -> Bool
Eq)

type Signature :: Type -> Type
data Signature l = Signature (LabelTest l) Arity Arity

portArity :: [Port] -> Arity
portArity :: [Port] -> Arity
portArity [Port]
ps = if (Port -> Bool) -> [Port] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
any Port -> Bool
capture [Port]
ps then Int -> Arity
AtLeast Int
minimumSize else Int -> Arity
Exactly Int
minimumSize
  where
    minimumSize :: Int
minimumSize = [()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [() | Node Int
_ <- [Port]
ps]
    capture :: Port -> Bool
capture Capture{} = Bool
True
    capture Port
_ = Bool
False

acceptsArity :: Arity -> Int -> Bool
acceptsArity :: Arity -> Int -> Bool
acceptsArity (Exactly Int
n) Int
m = Int
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
m
acceptsArity (AtLeast Int
n) Int
m = Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
m

instance (Eq l) => Eq (Signature l) where
  Signature LabelTest l
a Arity
i Arity
o == :: Signature l -> Signature l -> Bool
== Signature LabelTest l
b Arity
i' Arity
o' = Arity
i Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
== Arity
i' Bool -> Bool -> Bool
&& Arity
o Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
== Arity
o' Bool -> Bool -> Bool
&& LabelTest l -> LabelTest l -> Bool
forall l. Eq l => LabelTest l -> LabelTest l -> Bool
sameLabelTest LabelTest l
a LabelTest l
b

-- Registers name pattern nodes in order of first encounter, independent of the
-- pattern's node numbering. Separate selection from binding so patterns with
-- different repeated-wire constraints still share their gate dispatch.
type Step :: Kind -> Type
data Step s
  = SelectBox Int [Hint]
  | BindPort Bool Int Int (Maybe (SomeSort s))
  | SelectNode Bool Int (Maybe (SomeSort s))
  | BindPorts [PortTest s] [PortTest s]
  | CheckSubgraphs [(Int, Int)]

-- Position-free incidence hints anchor connections after a variable prefix.
data Hint = AtPort Int Int | Incident Int deriving (Hint -> Hint -> Bool
(Hint -> Hint -> Bool) -> (Hint -> Hint -> Bool) -> Eq Hint
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Hint -> Hint -> Bool
== :: Hint -> Hint -> Bool
$c/= :: Hint -> Hint -> Bool
/= :: Hint -> Hint -> Bool
Eq)

type PortTest :: Kind -> Type
data PortTest s = TestNode Int (Maybe (SomeSort s)) | TestCapture String

-- Original-node to register map, and traversal positions in original box order.
data Terminal = Terminal Int (IM.IntMap Int) [Int]

type Net :: Kind -> Type
data Net s = Net [Terminal] [(Step s, Net s)]

compileRuleSet
  :: (Ord key, Eq l, DecidableIso s)
  => Bool -> [(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRuleSet :: forall key l s.
(Ord key, Eq l, DecidableIso s) =>
Bool -> [(key, Rule s l)] -> Either String (CompiledRules key s l)
compileRuleSet Bool
reducing [(key, Rule s l)]
entries
  | Set key -> Int
forall a. Set a -> Int
S.size ([key] -> Set key
forall a. Ord a => [a] -> Set a
S.fromList (((key, Rule s l) -> key) -> [(key, Rule s l)] -> [key]
forall a b. (a -> b) -> [a] -> [b]
map (key, Rule s l) -> key
forall a b. (a, b) -> a
fst [(key, Rule s l)]
entries)) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= [(key, Rule s l)] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [(key, Rule s l)]
entries = String -> Either String (CompiledRules key s l)
forall a b. a -> Either a b
Left String
"compileRules: duplicate rule key"
  | Bool
otherwise = CompiledRules key s l -> Either String (CompiledRules key s l)
forall a b. b -> Either a b
Right (Vector (key, Rule s l)
-> Vector (Signature l) -> Net s -> Bool -> CompiledRules key s l
forall key s l.
Vector (key, Rule s l)
-> Vector (Signature l) -> Net s -> Bool -> CompiledRules key s l
CompiledRules Vector (key, Rule s l)
rules Vector (Signature l)
signatures Net s
net Bool
reducing)
  where
    rules :: Vector (key, Rule s l)
rules = [(key, Rule s l)] -> Vector (key, Rule s l)
forall a. [a] -> Vector a
V.fromList (((key, Rule s l) -> key) -> [(key, Rule s l)] -> [(key, Rule s l)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (key, Rule s l) -> key
forall a b. (a, b) -> a
fst [(key, Rule s l)]
entries)
    signatures :: Vector (Signature l)
signatures = [Signature l] -> Vector (Signature l)
forall a. [a] -> Vector a
V.fromList (([Signature l] -> Signature l -> [Signature l])
-> [Signature l] -> [Signature l] -> [Signature l]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: Type -> Type) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' [Signature l] -> Signature l -> [Signature l]
forall {a}. Eq a => [a] -> a -> [a]
add [] [Box (LabelTest l) Port -> Signature l
forall l. Box (LabelTest l) Port -> Signature l
signature Box (LabelTest l) Port
b | (key
_, Rule s l
r) <- Vector (key, Rule s l) -> [(key, Rule s l)]
forall a. Vector a -> [a]
V.toList Vector (key, Rule s l)
rules, let PortGraph [SomeSort s]
_ [Int]
_ [Box (LabelTest l) Port]
bs = Rule s l -> PortGraph s (LabelTest l)
forall s l. Rule s l -> PortGraph s (LabelTest l)
rulePattern Rule s l
r, Box (LabelTest l) Port
b <- [Box (LabelTest l) Port]
bs])
    add :: [a] -> a -> [a]
add [a]
xs a
x = if a
x a -> [a] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: Type -> Type) a.
(Foldable t, Eq a) =>
a -> t a -> Bool
`elem` [a]
xs then [a]
xs else [a]
xs [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ [a
x]
    paths :: [([Step s], Terminal)]
paths = [Vector (Signature l) -> Int -> Rule s l -> ([Step s], Terminal)
forall l s.
Eq l =>
Vector (Signature l) -> Int -> Rule s l -> ([Step s], Terminal)
compilePattern Vector (Signature l)
signatures Int
i Rule s l
r | (Int
i, (key
_, Rule s l
r)) <- [Int] -> [(key, Rule s l)] -> [(Int, (key, Rule s l))]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] (Vector (key, Rule s l) -> [(key, Rule s l)]
forall a. Vector a -> [a]
V.toList Vector (key, Rule s l)
rules)]
    net :: Net s
net = (Net s -> ([Step s], Terminal) -> Net s)
-> Net s -> [([Step s], Terminal)] -> Net s
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' (\Net s
n ([Step s]
steps, Terminal
terminal) -> [Step s] -> Terminal -> Net s -> Net s
forall s. DecidableIso s => [Step s] -> Terminal -> Net s -> Net s
insertNet [Step s]
steps Terminal
terminal Net s
n) ([Terminal] -> [(Step s, Net s)] -> Net s
forall s. [Terminal] -> [(Step s, Net s)] -> Net s
Net [] []) [([Step s], Terminal)]
paths

signature :: Box (LabelTest l) Port -> Signature l
signature :: forall l. Box (LabelTest l) Port -> Signature l
signature (Box LabelTest l
l [Port]
ins [Port]
outs) = LabelTest l -> Arity -> Arity -> Signature l
forall l. LabelTest l -> Arity -> Arity -> Signature l
Signature LabelTest l
l ([Port] -> Arity
portArity [Port]
ins) ([Port] -> Arity
portArity [Port]
outs)

compilePattern :: (Eq l) => V.Vector (Signature l) -> Int -> Rule s l -> ([Step s], Terminal)
compilePattern :: forall l s.
Eq l =>
Vector (Signature l) -> Int -> Rule s l -> ([Step s], Terminal)
compilePattern Vector (Signature l)
signatures Int
index Rule s l
ruleToCompile =
  let ([Step s]
steps, IntMap Int
registers, [Int]
order) = IntMap Int
-> [(Int, Box (LabelTest l) Port)] -> ([Step s], IntMap Int, [Int])
boxes IntMap Int
forall a. IntMap a
IM.empty ([Int]
-> [Box (LabelTest l) Port] -> [(Int, Box (LabelTest l) Port)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] [Box (LabelTest l) Port]
bs)
      (IntMap Int
allRegisters, [[Step s]]
isolated) = (IntMap Int -> Int -> (IntMap Int, [Step s]))
-> IntMap Int -> [Int] -> (IntMap Int, [[Step s]])
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, [Step s])
isolatedNode IntMap Int
registers [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 -> IntMap Int -> Bool
forall a. Int -> IntMap a -> Bool
IM.notMember Int
n IntMap Int
registers]
      boxRegisters :: [Int]
boxRegisters = ((Int, Int) -> Int) -> [(Int, Int)] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Int) -> Int
forall a b. (a, b) -> b
snd (((Int, Int) -> Int) -> [(Int, Int)] -> [(Int, Int)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Int, Int) -> Int
forall a b. (a, b) -> a
fst ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
order [Int
0 ..]))
  in ([Step s]
steps [Step s] -> [Step s] -> [Step s]
forall a. [a] -> [a] -> [a]
++ IntMap Int -> [Step s]
checks IntMap Int
registers [Step s] -> [Step s] -> [Step s]
forall a. [a] -> [a] -> [a]
++ [[Step s]] -> [Step s]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat [[Step s]]
isolated, Int -> IntMap Int -> [Int] -> Terminal
Terminal Int
index IntMap Int
allRegisters [Int]
boxRegisters)
  where
    PortGraph [SomeSort s]
ns [Int]
_ [Box (LabelTest l) Port]
bs = Rule s l -> PortGraph s (LabelTest l)
forall s l. Rule s l -> PortGraph s (LabelTest l)
rulePattern Rule s l
ruleToCompile
    aliases :: Bool
aliases = Rule s l -> Bool
forall s l. Rule s l -> Bool
hasSubgraphs Rule s l
ruleToCompile
    arrowHoles :: [(Int, Int)]
arrowHoles = Rule s l -> [(Int, Int)]
forall {s} {l}. Rule s l -> [(Int, Int)]
holes Rule s l
ruleToCompile
    sorts :: Vector (Maybe (SomeSort s))
sorts = [Maybe (SomeSort s)] -> Vector (Maybe (SomeSort s))
forall a. [a] -> Vector a
V.fromList ((SomeSort s -> Maybe (SomeSort s))
-> [SomeSort s] -> [Maybe (SomeSort s)]
forall a b. (a -> b) -> [a] -> [b]
map SomeSort s -> Maybe (SomeSort s)
testSort [SomeSort s]
ns)
    testSort :: SomeSort s -> Maybe (SomeSort s)
testSort = case Rule s l
ruleToCompile of
      SortRule{} -> Maybe (SomeSort s) -> SomeSort s -> Maybe (SomeSort s)
forall a b. a -> b -> a
const Maybe (SomeSort s)
forall a. Maybe a
Nothing
      Rule s l
_ -> SomeSort s -> Maybe (SomeSort s)
forall a. a -> Maybe a
Just
    register :: IntMap Int -> Int -> (IntMap Int, Int)
register IntMap Int
m Int
n = case Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
n IntMap Int
m of
      Just Int
r -> (IntMap Int
m, Int
r)
      Maybe Int
Nothing -> let r :: Int
r = IntMap Int -> Int
forall a. IntMap a -> Int
IM.size IntMap Int
m in (Int -> Int -> IntMap Int -> IntMap Int
forall a. Int -> a -> IntMap a -> IntMap a
IM.insert Int
n Int
r IntMap Int
m, Int
r)
    checks :: IntMap Int -> [Step s]
checks IntMap Int
m = case [(Int
a', Int
b') | (Int
a, Int
b) <- [(Int, Int)]
arrowHoles, Just Int
a' <- [Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
a IntMap Int
m], Just Int
b' <- [Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
b IntMap Int
m]] of
      [] -> []
      [(Int, Int)]
connected -> [[(Int, Int)] -> Step s
forall s. [(Int, Int)] -> Step s
CheckSubgraphs [(Int, Int)]
connected]
    holes :: Rule s l -> [(Int, Int)]
holes (SubgraphRule (Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box (Either l String) Int]
patternBoxes) Graph s (Either l String)
_) = [(Int
a, Int
b) | Box (Right String
_) [Int
a] [Int
b] <- [Box (Either l String) Int]
patternBoxes]
    holes (SortRule [SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]
_ Rule s l
r) = Rule s l -> [(Int, Int)]
holes Rule s l
r
    holes Rule s l
_ = []
    isolatedNode :: IntMap Int -> Int -> (IntMap Int, [Step s])
isolatedNode IntMap Int
m Int
n = let (IntMap Int
m', Int
r) = IntMap Int -> Int -> (IntMap Int, Int)
register IntMap Int
m Int
n in (IntMap Int
m', Bool -> Int -> Maybe (SomeSort s) -> Step s
forall s. Bool -> Int -> Maybe (SomeSort s) -> Step s
SelectNode Bool
aliases Int
r (Vector (Maybe (SomeSort s))
sorts Vector (Maybe (SomeSort s)) -> Int -> Maybe (SomeSort s)
forall a. Vector a -> Int -> a
V.! Int
n) Step s -> [Step s] -> [Step s]
forall a. a -> [a] -> [a]
: IntMap Int -> [Step s]
checks IntMap Int
m')
    boxes :: IntMap Int
-> [(Int, Box (LabelTest l) Port)] -> ([Step s], IntMap Int, [Int])
boxes IntMap Int
m [] = ([], IntMap Int
m, [])
    boxes IntMap Int
m [(Int, Box (LabelTest l) Port)]
remaining =
      let score :: (Int, Box (LabelTest l) Port) -> (Int, Int, Bool)
score (Int
_, candidate :: Box (LabelTest l) Port
candidate@(Box LabelTest l
_ [Port]
candidateIns [Port]
candidateOuts)) =
            ( [()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [() | (Int
_, Node Int
n) <- Box (LabelTest l) Port -> [(Int, Port)]
forall l n. Box l n -> [(Int, n)]
portsOf Box (LabelTest l) Port
candidate, Int -> IntMap Int -> Bool
forall a. Int -> IntMap a -> Bool
IM.member Int
n IntMap Int
m]
            , [()] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [() | (Int
_, Node Int
_) <- Box (LabelTest l) Port -> [(Int, Port)]
forall l n. Box l n -> [(Int, n)]
portsOf Box (LabelTest l) Port
candidate]
            , case ([Port] -> Arity
portArity [Port]
candidateIns, [Port] -> Arity
portArity [Port]
candidateOuts) of (Exactly Int
_, Exactly Int
_) -> Bool
True; (Arity, Arity)
_ -> Bool
False
            )
          (Int
i, b :: Box (LabelTest l) Port
b@(Box LabelTest l
_ [Port]
ins [Port]
outs)) = ((Int, Box (LabelTest l) Port)
 -> (Int, Box (LabelTest l) Port) -> Ordering)
-> [(Int, Box (LabelTest l) Port)] -> (Int, Box (LabelTest l) Port)
forall (t :: Type -> Type) a.
Foldable t =>
(a -> a -> Ordering) -> t a -> a
maximumBy (((Int, Box (LabelTest l) Port) -> ((Int, Int, Bool), Int))
-> (Int, Box (LabelTest l) Port)
-> (Int, Box (LabelTest l) Port)
-> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing (\entry :: (Int, Box (LabelTest l) Port)
entry@(Int
j, Box (LabelTest l) Port
_) -> ((Int, Box (LabelTest l) Port) -> (Int, Int, Bool)
score (Int, Box (LabelTest l) Port)
entry, Int -> Int
forall a. Num a => a -> a
negate Int
j))) [(Int, Box (LabelTest l) Port)]
remaining
          sig :: Int
sig = case (Signature l -> Bool) -> Vector (Signature l) -> Maybe Int
forall a. (a -> Bool) -> Vector a -> Maybe Int
V.findIndex (Signature l -> Signature l -> Bool
forall a. Eq a => a -> a -> Bool
== Box (LabelTest l) Port -> Signature l
forall l. Box (LabelTest l) Port -> Signature l
signature Box (LabelTest l) Port
b) Vector (Signature l)
signatures of
            Just Int
s -> Int
s
            Maybe Int
Nothing -> String -> Int
forall a. HasCallStack => String -> a
error String
"compilePattern: missing signature"
          hints :: [Hint]
hints = Bool -> [Port] -> [Hint]
hintsFor Bool
False [Port]
ins [Hint] -> [Hint] -> [Hint]
forall a. [a] -> [a] -> [a]
++ Bool -> [Port] -> [Hint]
hintsFor Bool
True [Port]
outs
          hintsFor :: Bool -> [Port] -> [Hint]
hintsFor Bool
out [Port]
ps = Int -> Bool -> [Port] -> [Hint]
go Int
0 Bool
True [Port]
ps
            where
              go :: Int -> Bool -> [Port] -> [Hint]
go Int
_ Bool
_ [] = []
              go Int
p Bool
positioned (Node Int
n : [Port]
more) =
                [if Bool
positioned then Int -> Int -> Hint
AtPort (Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
p Int -> Int -> Int
forall a. Num a => a -> a -> a
+ if Bool
out then Int
1 else Int
0) Int
r else Int -> Hint
Incident Int
r | Just Int
r <- [Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
n IntMap Int
m]]
                  [Hint] -> [Hint] -> [Hint]
forall a. [a] -> [a] -> [a]
++ Int -> Bool -> [Port] -> [Hint]
go (Int
p Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Bool
positioned [Port]
more
              go Int
p Bool
_ (Port
_ : [Port]
more) = Int -> Bool -> [Port] -> [Hint]
go Int
p Bool
False [Port]
more
          bind :: IntMap Int -> Port -> (IntMap Int, PortTest s)
bind IntMap Int
regs (Node Int
n) = let (IntMap Int
regs', Int
r) = IntMap Int -> Int -> (IntMap Int, Int)
register IntMap Int
regs Int
n in (IntMap Int
regs', Int -> Maybe (SomeSort s) -> PortTest s
forall s. Int -> Maybe (SomeSort s) -> PortTest s
TestNode Int
r (Vector (Maybe (SomeSort s))
sorts Vector (Maybe (SomeSort s)) -> Int -> Maybe (SomeSort s)
forall a. Vector a -> Int -> a
V.! Int
n))
          bind IntMap Int
regs (Capture String
name) = (IntMap Int
regs, String -> PortTest s
forall s. String -> PortTest s
TestCapture String
name)
          bind IntMap Int
_ Element{} = String -> (IntMap Int, PortTest s)
forall a. HasCallStack => String -> a
error String
"compilePattern: Element on the left"
          (IntMap Int
m1, [PortTest s]
testsIn) = (IntMap Int -> Port -> (IntMap Int, PortTest s))
-> IntMap Int -> [Port] -> (IntMap Int, [PortTest s])
forall (t :: Type -> Type) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
mapAccumL IntMap Int -> Port -> (IntMap Int, PortTest s)
bind IntMap Int
m [Port]
ins
          (IntMap Int
m', [PortTest s]
testsOut) = (IntMap Int -> Port -> (IntMap Int, PortTest s))
-> IntMap Int -> [Port] -> (IntMap Int, [PortTest s])
forall (t :: Type -> Type) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
mapAccumL IntMap Int -> Port -> (IntMap Int, PortTest s)
bind IntMap Int
m1 [Port]
outs
          fixed :: Int -> PortTest s -> Step s
fixed Int
p (TestNode Int
r Maybe (SomeSort s)
s) = Bool -> Int -> Int -> Maybe (SomeSort s) -> Step s
forall s. Bool -> Int -> Int -> Maybe (SomeSort s) -> Step s
BindPort Bool
aliases Int
p Int
r Maybe (SomeSort s)
s
          fixed Int
_ TestCapture{} = String -> Step s
forall a. HasCallStack => String -> a
error String
"compilePattern: capture in fixed pattern"
          bindings :: [Step s]
bindings = case ([Port] -> Arity
portArity [Port]
ins, [Port] -> Arity
portArity [Port]
outs) of
            (Exactly Int
_, Exactly Int
_) -> (Int -> PortTest s -> Step s) -> [Int] -> [PortTest s] -> [Step s]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> PortTest s -> Step s
fixed [Int
0, Int
2 ..] [PortTest s]
testsIn [Step s] -> [Step s] -> [Step s]
forall a. [a] -> [a] -> [a]
++ (Int -> PortTest s -> Step s) -> [Int] -> [PortTest s] -> [Step s]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> PortTest s -> Step s
fixed [Int
1, Int
3 ..] [PortTest s]
testsOut
            (Arity, Arity)
_ -> [[PortTest s] -> [PortTest s] -> Step s
forall s. [PortTest s] -> [PortTest s] -> Step s
BindPorts [PortTest s]
testsIn [PortTest s]
testsOut]
          ([Step s]
rest, IntMap Int
result, [Int]
order) = IntMap Int
-> [(Int, Box (LabelTest l) Port)] -> ([Step s], IntMap Int, [Int])
boxes IntMap Int
m' [(Int, Box (LabelTest l) Port)
entry | entry :: (Int, Box (LabelTest l) Port)
entry@(Int
j, Box (LabelTest l) Port
_) <- [(Int, Box (LabelTest l) Port)]
remaining, Int
j Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
i]
      in (Int -> [Hint] -> Step s
forall s. Int -> [Hint] -> Step s
SelectBox Int
sig [Hint]
hints Step s -> [Step s] -> [Step s]
forall a. a -> [a] -> [a]
: [Step s]
bindings [Step s] -> [Step s] -> [Step s]
forall a. [a] -> [a] -> [a]
++ [Step s]
rest, IntMap Int
result, Int
i Int -> [Int] -> [Int]
forall a. a -> [a] -> [a]
: [Int]
order)

insertNet :: (DecidableIso s) => [Step s] -> Terminal -> Net s -> Net s
insertNet :: forall s. DecidableIso s => [Step s] -> Terminal -> Net s -> Net s
insertNet [] Terminal
terminal (Net [Terminal]
terminals [(Step s, Net s)]
branches) = [Terminal] -> [(Step s, Net s)] -> Net s
forall s. [Terminal] -> [(Step s, Net s)] -> Net s
Net (Terminal
terminal Terminal -> [Terminal] -> [Terminal]
forall a. a -> [a] -> [a]
: [Terminal]
terminals) [(Step s, Net s)]
branches
insertNet (Step s
step : [Step s]
rest) Terminal
terminal (Net [Terminal]
terminals [(Step s, Net s)]
branches) = [Terminal] -> [(Step s, Net s)] -> Net s
forall s. [Terminal] -> [(Step s, Net s)] -> Net s
Net [Terminal]
terminals ([(Step s, Net s)] -> [(Step s, Net s)]
insert [(Step s, Net s)]
branches)
  where
    insert :: [(Step s, Net s)] -> [(Step s, Net s)]
insert [] = [(Step s
step, [Step s] -> Terminal -> Net s -> Net s
forall s. DecidableIso s => [Step s] -> Terminal -> Net s -> Net s
insertNet [Step s]
rest Terminal
terminal ([Terminal] -> [(Step s, Net s)] -> Net s
forall s. [Terminal] -> [(Step s, Net s)] -> Net s
Net [] []))]
    insert ((Step s
test, Net s
next) : [(Step s, Net s)]
more)
      | Step s -> Step s -> Bool
forall s. DecidableIso s => Step s -> Step s -> Bool
sameStep Step s
step Step s
test = (Step s
test, [Step s] -> Terminal -> Net s -> Net s
forall s. DecidableIso s => [Step s] -> Terminal -> Net s -> Net s
insertNet [Step s]
rest Terminal
terminal Net s
next) (Step s, Net s) -> [(Step s, Net s)] -> [(Step s, Net s)]
forall a. a -> [a] -> [a]
: [(Step s, Net s)]
more
      | Bool
otherwise = (Step s
test, Net s
next) (Step s, Net s) -> [(Step s, Net s)] -> [(Step s, Net s)]
forall a. a -> [a] -> [a]
: [(Step s, Net s)] -> [(Step s, Net s)]
insert [(Step s, Net s)]
more

sameStep :: (DecidableIso s) => Step s -> Step s -> Bool
sameStep :: forall s. DecidableIso s => Step s -> Step s -> Bool
sameStep (SelectBox Int
a [Hint]
hints) (SelectBox Int
b [Hint]
hints') = Int
a Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
b Bool -> Bool -> Bool
&& [Hint]
hints [Hint] -> [Hint] -> Bool
forall a. Eq a => a -> a -> Bool
== [Hint]
hints'
sameStep (BindPort Bool
a Int
p Int
r Maybe (SomeSort s)
s) (BindPort Bool
a' Int
p' Int
r' Maybe (SomeSort s)
s') = Bool
a Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
a' Bool -> Bool -> Bool
&& Int
p Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
p' Bool -> Bool -> Bool
&& Int
r Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
r' Bool -> Bool -> Bool
&& Maybe (SomeSort s) -> Maybe (SomeSort s) -> Bool
forall s.
DecidableIso s =>
Maybe (SomeSort s) -> Maybe (SomeSort s) -> Bool
sameSortTest Maybe (SomeSort s)
s Maybe (SomeSort s)
s'
sameStep (SelectNode Bool
a Int
r Maybe (SomeSort s)
s) (SelectNode Bool
a' Int
r' Maybe (SomeSort s)
s') = Bool
a Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
a' Bool -> Bool -> Bool
&& Int
r Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
r' Bool -> Bool -> Bool
&& Maybe (SomeSort s) -> Maybe (SomeSort s) -> Bool
forall s.
DecidableIso s =>
Maybe (SomeSort s) -> Maybe (SomeSort s) -> Bool
sameSortTest Maybe (SomeSort s)
s Maybe (SomeSort s)
s'
sameStep (CheckSubgraphs [(Int, Int)]
a) (CheckSubgraphs [(Int, Int)]
b) = [(Int, Int)]
a [(Int, Int)] -> [(Int, Int)] -> Bool
forall a. Eq a => a -> a -> Bool
== [(Int, Int)]
b
sameStep (BindPorts [PortTest s]
is [PortTest s]
os) (BindPorts [PortTest s]
is' [PortTest s]
os') = [PortTest s] -> [PortTest s] -> Bool
forall {s}. DecidableIso s => [PortTest s] -> [PortTest s] -> Bool
sameTests [PortTest s]
is [PortTest s]
is' Bool -> Bool -> Bool
&& [PortTest s] -> [PortTest s] -> Bool
forall {s}. DecidableIso s => [PortTest s] -> [PortTest s] -> Bool
sameTests [PortTest s]
os [PortTest s]
os'
  where
    sameTests :: [PortTest s] -> [PortTest s] -> Bool
sameTests [] [] = Bool
True
    sameTests (TestNode Int
r Maybe (SomeSort s)
s : [PortTest s]
xs) (TestNode Int
r' Maybe (SomeSort s)
s' : [PortTest s]
ys) = Int
r Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
r' Bool -> Bool -> Bool
&& Maybe (SomeSort s) -> Maybe (SomeSort s) -> Bool
forall s.
DecidableIso s =>
Maybe (SomeSort s) -> Maybe (SomeSort s) -> Bool
sameSortTest Maybe (SomeSort s)
s Maybe (SomeSort s)
s' Bool -> Bool -> Bool
&& [PortTest s] -> [PortTest s] -> Bool
sameTests [PortTest s]
xs [PortTest s]
ys
    sameTests (TestCapture String
a : [PortTest s]
xs) (TestCapture String
b : [PortTest s]
ys) = String
a String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
b Bool -> Bool -> Bool
&& [PortTest s] -> [PortTest s] -> Bool
sameTests [PortTest s]
xs [PortTest s]
ys
    sameTests [PortTest s]
_ [PortTest s]
_ = Bool
False
sameStep Step s
_ Step s
_ = Bool
False

sameSortTest :: (DecidableIso s) => Maybe (SomeSort s) -> Maybe (SomeSort s) -> Bool
sameSortTest :: forall s.
DecidableIso s =>
Maybe (SomeSort s) -> Maybe (SomeSort s) -> Bool
sameSortTest Maybe (SomeSort s)
Nothing Maybe (SomeSort s)
Nothing = Bool
True
sameSortTest (Just SomeSort s
a) (Just SomeSort s
b) = SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort SomeSort s
a SomeSort s
b
sameSortTest Maybe (SomeSort s)
_ Maybe (SomeSort s)
_ = Bool
False

-- Incidence and signature buckets cache their lengths for candidate selection.
type HostIndex :: Kind -> Type -> Type
data HostIndex s l = HostIndex
  { forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts :: V.Vector (SomeSort s)
  , forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes :: V.Vector (Box l Int)
  , forall s l. HostIndex s l -> Vector IntSet
indexedSignatures :: V.Vector IS.IntSet
  , forall s l. HostIndex s l -> Vector (Int, [Int])
indexedCandidates :: V.Vector (Int, [Int])
  , forall s l. HostIndex s l -> Vector (IntMap (Int, [Int]))
indexedIncidence :: V.Vector (IM.IntMap (Int, [Int]))
  , forall s l. HostIndex s l -> Vector (Int, [Int])
indexedNeighbours :: V.Vector (Int, [Int])
  , forall s l. HostIndex s l -> IntSet
indexedBoundary :: IS.IntSet
  }

indexHost :: (Eq l) => V.Vector (Signature l) -> Graph s l -> HostIndex s l
indexHost :: forall l s.
Eq l =>
Vector (Signature l) -> Graph s l -> HostIndex s l
indexHost Vector (Signature l)
signatures (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box l Int]
bs) = Vector (SomeSort s)
-> Vector (Box l Int)
-> Vector IntSet
-> Vector (Int, [Int])
-> Vector (IntMap (Int, [Int]))
-> Vector (Int, [Int])
-> IntSet
-> HostIndex s l
forall s l.
Vector (SomeSort s)
-> Vector (Box l Int)
-> Vector IntSet
-> Vector (Int, [Int])
-> Vector (IntMap (Int, [Int]))
-> Vector (Int, [Int])
-> IntSet
-> HostIndex s l
HostIndex ([SomeSort s] -> Vector (SomeSort s)
forall a. [a] -> Vector a
V.fromList [SomeSort s]
ns) ([Box l Int] -> Vector (Box l Int)
forall a. [a] -> Vector a
V.fromList [Box l Int]
bs) Vector IntSet
ids Vector (Int, [Int])
candidates Vector (IntMap (Int, [Int]))
incidence Vector (Int, [Int])
neighbours ([Int] -> IntSet
IS.fromList ([Int]
ins [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
outs))
  where
    -- A host label may satisfy both an exact signature and a constructor key.
    -- Classify it once per snapshot, with exact-label lookup kept separate.
    exact :: Map (Int, Int) [(l, Int)]
exact =
      ([(l, Int)] -> [(l, Int)] -> [(l, Int)])
-> [((Int, Int), [(l, Int)])] -> Map (Int, Int) [(l, Int)]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith
        [(l, Int)] -> [(l, Int)] -> [(l, Int)]
forall a. [a] -> [a] -> [a]
(++)
        [((Int
a, Int
b), [(l
l, Int
i)]) | (Int
i, Signature (ExactLabel l
l) (Exactly Int
a) (Exactly Int
b)) <- [Int] -> [Signature l] -> [(Int, Signature l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] (Vector (Signature l) -> [Signature l]
forall a. Vector a -> [a]
V.toList Vector (Signature l)
signatures)]
    other :: [(LabelTest l, Arity, Arity, Int)]
other = [(LabelTest l
test, Arity
a, Arity
b, Int
i) | (Int
i, Signature LabelTest l
test Arity
a Arity
b) <- [Int] -> [Signature l] -> [(Int, Signature l)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] (Vector (Signature l) -> [Signature l]
forall a. Vector a -> [a]
V.toList Vector (Signature l)
signatures), Bool -> Bool
not (LabelTest l -> Arity -> Arity -> Bool
forall {l}. LabelTest l -> Arity -> Arity -> Bool
literalFixed LabelTest l
test Arity
a Arity
b)]
    literalFixed :: LabelTest l -> Arity -> Arity -> Bool
literalFixed ExactLabel{} (Exactly Int
_) (Exactly Int
_) = Bool
True
    literalFixed LabelTest l
_ Arity
_ Arity
_ = Bool
False
    classify :: Box l Int -> IntSet
classify (Box l
l [Int]
a [Int]
b) =
      let shape :: (Int, Int)
shape = ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
a, [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
b)
      in [Int] -> IntSet
IS.fromList
           ( [Int] -> (Int -> [Int]) -> Maybe Int -> [Int]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Int -> [Int]
forall a. a -> [a]
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (l -> [(l, Int)] -> Maybe Int
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup l
l ([(l, Int)] -> (Int, Int) -> Map (Int, Int) [(l, Int)] -> [(l, Int)]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] (Int, Int)
shape Map (Int, Int) [(l, Int)]
exact))
               [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [ Int
i
                  | (LabelTest l
test, Arity
arityIn, Arity
arityOut, Int
i) <- [(LabelTest l, Arity, Arity, Int)]
other
                  , Arity -> Int -> Bool
acceptsArity Arity
arityIn ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
a)
                  , Arity -> Int -> Bool
acceptsArity Arity
arityOut ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
b)
                  , LabelTest l -> l -> Bool
forall l. Eq l => LabelTest l -> l -> Bool
acceptsLabel LabelTest l
test l
l
                  ]
           )
    ids :: Vector IntSet
ids = [IntSet] -> Vector IntSet
forall a. [a] -> Vector a
V.fromList ((Box l Int -> IntSet) -> [Box l Int] -> [IntSet]
forall a b. (a -> b) -> [a] -> [b]
map Box l Int -> IntSet
classify [Box l Int]
bs)
    bucket :: [a] -> (Int, [a])
bucket [a]
xs = ([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]
reverse [a]
xs)
    candidates :: Vector (Int, [Int])
candidates =
      ([Int] -> (Int, [Int])) -> Vector [Int] -> Vector (Int, [Int])
forall a b. (a -> b) -> Vector a -> Vector b
V.map
        [Int] -> (Int, [Int])
forall {a}. [a] -> (Int, [a])
bucket
        ( ([Int] -> Int -> [Int])
-> Vector [Int] -> [(Int, Int)] -> Vector [Int]
forall a b. (a -> b -> a) -> Vector a -> [(Int, b)] -> Vector a
V.accum
            ((Int -> [Int] -> [Int]) -> [Int] -> Int -> [Int]
forall a b c. (a -> b -> c) -> b -> a -> c
flip (:))
            (Int -> [Int] -> Vector [Int]
forall a. Int -> a -> Vector a
V.replicate (Vector (Signature l) -> Int
forall a. Vector a -> Int
V.length Vector (Signature l)
signatures) [])
            [(Int
s, Int
i) | (Int
i, IntSet
matches') <- [Int] -> [IntSet] -> [(Int, IntSet)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] (Vector IntSet -> [IntSet]
forall a. Vector a -> [a]
V.toList Vector IntSet
ids), Int
s <- IntSet -> [Int]
IS.toList IntSet
matches']
        )
    incidence :: Vector (IntMap (Int, [Int]))
incidence =
      (IntMap [Int] -> IntMap (Int, [Int]))
-> Vector (IntMap [Int]) -> Vector (IntMap (Int, [Int]))
forall a b. (a -> b) -> Vector a -> Vector b
V.map (([Int] -> (Int, [Int])) -> IntMap [Int] -> IntMap (Int, [Int])
forall a b. (a -> b) -> IntMap a -> IntMap b
IM.map [Int] -> (Int, [Int])
forall {a}. [a] -> (Int, [a])
bucket) (Vector (IntMap [Int]) -> Vector (IntMap (Int, [Int])))
-> Vector (IntMap [Int]) -> Vector (IntMap (Int, [Int]))
forall a b. (a -> b) -> a -> b
$
        (IntMap [Int] -> (Int, Int) -> IntMap [Int])
-> Vector (IntMap [Int])
-> [(Int, (Int, Int))]
-> Vector (IntMap [Int])
forall a b. (a -> b -> a) -> Vector a -> [(Int, b)] -> Vector a
V.accum
          (\IntMap [Int]
m (Int
p, Int
i) -> ([Int] -> [Int] -> [Int])
-> Int -> [Int] -> IntMap [Int] -> IntMap [Int]
forall a. (a -> a -> a) -> Int -> a -> IntMap a -> IntMap a
IM.insertWith [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
(++) Int
p [Int
i] IntMap [Int]
m)
          (Int -> IntMap [Int] -> Vector (IntMap [Int])
forall a. Int -> a -> Vector a
V.replicate ([SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
ns) IntMap [Int]
forall a. IntMap a
IM.empty)
          [(Int
n, (Int
p, Int
i)) | (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]
bs, (Int
p, Int
n) <- Box l Int -> [(Int, Int)]
forall l n. Box l n -> [(Int, n)]
portsOf Box l Int
b]

    neighbours :: Vector (Int, [Int])
neighbours = (IntMap (Int, [Int]) -> (Int, [Int]))
-> Vector (IntMap (Int, [Int])) -> Vector (Int, [Int])
forall a b. (a -> b) -> Vector a -> Vector b
V.map ([Int] -> (Int, [Int])
forall {a}. [a] -> (Int, [a])
bucket ([Int] -> (Int, [Int]))
-> (IntMap (Int, [Int]) -> [Int])
-> IntMap (Int, [Int])
-> (Int, [Int])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IntSet -> [Int]
IS.toDescList (IntSet -> [Int])
-> (IntMap (Int, [Int]) -> IntSet) -> IntMap (Int, [Int]) -> [Int]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Int] -> IntSet
IS.fromList ([Int] -> IntSet)
-> (IntMap (Int, [Int]) -> [Int]) -> IntMap (Int, [Int]) -> IntSet
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Int, [Int]) -> [Int]) -> [(Int, [Int])] -> [Int]
forall (t :: Type -> Type) a b.
Foldable t =>
(a -> [b]) -> t a -> [b]
concatMap (Int, [Int]) -> [Int]
forall a b. (a, b) -> b
snd ([(Int, [Int])] -> [Int])
-> (IntMap (Int, [Int]) -> [(Int, [Int])])
-> IntMap (Int, [Int])
-> [Int]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IntMap (Int, [Int]) -> [(Int, [Int])]
forall a. IntMap a -> [a]
IM.elems) Vector (IntMap (Int, [Int]))
incidence

-- Register bindings, their range, selected boxes in reverse traversal order,
-- and their set for injectivity and dangling checks.
type SearchState = (IM.IntMap Int, IS.IntSet, [Int], IS.IntSet, M.Map String [Int])

runStep :: (DecidableIso s) => HostIndex s l -> Step s -> SearchState -> [SearchState]
runStep :: forall s l.
DecidableIso s =>
HostIndex s l -> Step s -> SearchState -> [SearchState]
runStep HostIndex s l
host (SelectBox Int
sig [Hint]
hints) (IntMap Int
m, IntSet
range, [Int]
order, IntSet
used, Map String [Int]
captures) =
  [ (IntMap Int
m, IntSet
range, Int
i Int -> [Int] -> [Int]
forall a. a -> [a] -> [a]
: [Int]
order, Int -> IntSet -> IntSet
IS.insert Int
i IntSet
used, Map String [Int]
captures)
  | Int
i <- (Int, [Int]) -> [Int]
forall a b. (a, b) -> b
snd (((Int, [Int]) -> (Int, [Int]) -> (Int, [Int]))
-> (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, [Int]) -> (Int, [Int])
forall {a} {b}. Ord a => (a, b) -> (a, b) -> (a, b)
smaller (HostIndex s l -> Vector (Int, [Int])
forall s l. HostIndex s l -> Vector (Int, [Int])
indexedCandidates HostIndex s l
host Vector (Int, [Int]) -> Int -> (Int, [Int])
forall a. Vector a -> Int -> a
V.! Int
sig) [(Int, [Int])]
constrained)
  , Int -> IntSet -> Bool
IS.notMember Int
i IntSet
used
  , Int -> IntSet -> Bool
IS.member Int
sig (HostIndex s l -> Vector IntSet
forall s l. HostIndex s l -> Vector IntSet
indexedSignatures HostIndex s l
host Vector IntSet -> Int -> IntSet
forall a. Vector a -> Int -> a
V.! Int
i)
  ]
  where
    constrained :: [(Int, [Int])]
constrained = (Hint -> (Int, [Int])) -> [Hint] -> [(Int, [Int])]
forall a b. (a -> b) -> [a] -> [b]
map Hint -> (Int, [Int])
constrain [Hint]
hints
    constrain :: Hint -> (Int, [Int])
constrain (AtPort Int
p Int
r) = (Int, [Int]) -> Int -> IntMap (Int, [Int]) -> (Int, [Int])
forall a. a -> Int -> IntMap a -> a
IM.findWithDefault (Int
0, []) Int
p (HostIndex s l -> Vector (IntMap (Int, [Int]))
forall s l. HostIndex s l -> Vector (IntMap (Int, [Int]))
indexedIncidence HostIndex s l
host Vector (IntMap (Int, [Int])) -> Int -> IntMap (Int, [Int])
forall a. Vector a -> Int -> a
V.! (IntMap Int
m IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
r))
    constrain (Incident Int
r) = HostIndex s l -> Vector (Int, [Int])
forall s l. HostIndex s l -> Vector (Int, [Int])
indexedNeighbours HostIndex s l
host Vector (Int, [Int]) -> Int -> (Int, [Int])
forall a. Vector a -> Int -> a
V.! (IntMap Int
m IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
r)
    smaller :: (a, b) -> (a, b) -> (a, b)
smaller (a, b)
a (a, b)
b = if (a, b) -> a
forall a b. (a, b) -> a
fst (a, b)
a a -> a -> Bool
forall a. Ord a => a -> a -> Bool
<= (a, b) -> a
forall a b. (a, b) -> a
fst (a, b)
b then (a, b)
a else (a, b)
b
runStep HostIndex s l
host (BindPort Bool
aliases Int
p Int
r Maybe (SomeSort s)
sort) state :: SearchState
state@(IntMap Int
_, IntSet
_, [Int]
order, IntSet
_, Map String [Int]
_) = case [Int]
order of
  Int
i : [Int]
_ ->
    let Box l
_ [Int]
ins [Int]
outs = HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i
        n :: Int
n = (if Int -> Bool
forall a. Integral a => a -> Bool
even Int
p then [Int]
ins else [Int]
outs) [Int] -> Int -> Int
forall a. HasCallStack => [a] -> Int -> a
!! (Int
p Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
2)
    in [SearchState]
-> (SearchState -> [SearchState])
-> Maybe SearchState
-> [SearchState]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] SearchState -> [SearchState]
forall a. a -> [a]
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (Bool
-> HostIndex s l
-> Int
-> Maybe (SomeSort s)
-> Int
-> SearchState
-> Maybe SearchState
forall s l.
DecidableIso s =>
Bool
-> HostIndex s l
-> Int
-> Maybe (SomeSort s)
-> Int
-> SearchState
-> Maybe SearchState
bindNode Bool
aliases HostIndex s l
host Int
r Maybe (SomeSort s)
sort Int
n SearchState
state)
  [] -> String -> [SearchState]
forall a. HasCallStack => String -> a
error String
"runStep: port test without a box"
runStep HostIndex s l
host (SelectNode Bool
aliases Int
r Maybe (SomeSort s)
sort) SearchState
state =
  [SearchState
next | Int
n <- [Int
0 .. Vector (SomeSort s) -> Int
forall a. Vector a -> Int
V.length (HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host) Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1], Just SearchState
next <- [Bool
-> HostIndex s l
-> Int
-> Maybe (SomeSort s)
-> Int
-> SearchState
-> Maybe SearchState
forall s l.
DecidableIso s =>
Bool
-> HostIndex s l
-> Int
-> Maybe (SomeSort s)
-> Int
-> SearchState
-> Maybe SearchState
bindNode Bool
aliases HostIndex s l
host Int
r Maybe (SomeSort s)
sort Int
n SearchState
state]]
runStep HostIndex s l
host (CheckSubgraphs [(Int, Int)]
holes) state :: SearchState
state@(IntMap Int
m, IntSet
_, [Int]
_, IntSet
used, Map String [Int]
_) =
  [SearchState
state | ((Int, Int) -> Bool) -> [(Int, Int)] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\(Int
a, Int
b) -> Bool -> Bool
not ([IntSet] -> Bool
forall a. [a] -> Bool
forall (t :: Type -> Type) a. Foldable t => t a -> Bool
null (HostIndex s l -> IntSet -> IntSet -> Int -> Int -> [IntSet]
forall s l.
HostIndex s l -> IntSet -> IntSet -> Int -> Int -> [IntSet]
captureRegions HostIndex s l
host ([Int] -> IntSet
IS.fromList (IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
m)) IntSet
used (IntMap Int
m IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
a) (IntMap Int
m IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
b)))) [(Int, Int)]
holes]
runStep HostIndex s l
host (BindPorts [PortTest s]
ins [PortTest s]
outs) state :: SearchState
state@(IntMap Int
_, IntSet
_, [Int]
order, IntSet
_, Map String [Int]
_) = case [Int]
order of
  Int
i : [Int]
_ -> let Box l
_ [Int]
is [Int]
os = HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i in [PortTest s] -> [Int] -> SearchState -> [SearchState]
matchPorts [PortTest s]
ins [Int]
is SearchState
state [SearchState] -> (SearchState -> [SearchState]) -> [SearchState]
forall a b. [a] -> (a -> [b]) -> [b]
forall (m :: Type -> Type) a b. Monad m => m a -> (a -> m b) -> m b
>>= [PortTest s] -> [Int] -> SearchState -> [SearchState]
matchPorts [PortTest s]
outs [Int]
os
  [] -> String -> [SearchState]
forall a. HasCallStack => String -> a
error String
"runStep: port capture without a box"
  where
    matchPorts :: [PortTest s] -> [Int] -> SearchState -> [SearchState]
matchPorts [] [] SearchState
current = [SearchState
current]
    matchPorts (TestNode Int
r Maybe (SomeSort s)
sort : [PortTest s]
more) (Int
n : [Int]
rest) SearchState
current =
      [SearchState]
-> (SearchState -> [SearchState])
-> Maybe SearchState
-> [SearchState]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ([PortTest s] -> [Int] -> SearchState -> [SearchState]
matchPorts [PortTest s]
more [Int]
rest) (Bool
-> HostIndex s l
-> Int
-> Maybe (SomeSort s)
-> Int
-> SearchState
-> Maybe SearchState
forall s l.
DecidableIso s =>
Bool
-> HostIndex s l
-> Int
-> Maybe (SomeSort s)
-> Int
-> SearchState
-> Maybe SearchState
bindNode Bool
False HostIndex s l
host Int
r Maybe (SomeSort s)
sort Int
n SearchState
current)
    matchPorts [TestCapture String
name] [Int]
nodes current :: SearchState
current@(IntMap Int
m, IntSet
range, [Int]
chosen, IntSet
used, Map String [Int]
captures) =
      case String -> Map String [Int] -> Maybe [Int]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup String
name Map String [Int]
captures of
        Just [Int]
bound -> [SearchState
current | [Int]
bound [Int] -> [Int] -> Bool
forall a. Eq a => a -> a -> Bool
== [Int]
nodes]
        Maybe [Int]
Nothing -> [(IntMap Int
m, IntSet
range, [Int]
chosen, IntSet
used, String -> [Int] -> Map String [Int] -> Map String [Int]
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert String
name [Int]
nodes Map String [Int]
captures)]
    matchPorts (TestCapture String
name : [PortTest s]
more) [Int]
nodes current :: SearchState
current@(IntMap Int
m, IntSet
range, [Int]
chosen, IntSet
used, Map String [Int]
captures) =
      case String -> Map String [Int] -> Maybe [Int]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup String
name Map String [Int]
captures of
        Just [Int]
bound -> [SearchState
next | Int -> [Int] -> [Int]
forall a. Int -> [a] -> [a]
take ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
bound) [Int]
nodes [Int] -> [Int] -> Bool
forall a. Eq a => a -> a -> Bool
== [Int]
bound, SearchState
next <- [PortTest s] -> [Int] -> SearchState -> [SearchState]
matchPorts [PortTest s]
more (Int -> [Int] -> [Int]
forall a. Int -> [a] -> [a]
drop ([Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
bound) [Int]
nodes) SearchState
current]
        Maybe [Int]
Nothing ->
          [ SearchState
next
          | Int
size <- case [PortTest s]
more of
              TestNode Int
r Maybe (SomeSort s)
_ : [PortTest s]
_
                | Just Int
expected <- Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
r IntMap Int
m ->
                    [Int
i | (Int
i, Int
n) <- [Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [Int]
nodes, Int
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
expected]
              [PortTest s]
_ -> [Int
0 .. [Int] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [Int]
nodes]
          , let ([Int]
prefix, [Int]
rest) = Int -> [Int] -> ([Int], [Int])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
size [Int]
nodes
          , SearchState
next <- [PortTest s] -> [Int] -> SearchState -> [SearchState]
matchPorts [PortTest s]
more [Int]
rest (IntMap Int
m, IntSet
range, [Int]
chosen, IntSet
used, String -> [Int] -> Map String [Int] -> Map String [Int]
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert String
name [Int]
prefix Map String [Int]
captures)
          ]
    matchPorts [PortTest s]
_ [Int]
_ SearchState
_ = []

bindNode
  :: (DecidableIso s) => Bool -> HostIndex s l -> Int -> Maybe (SomeSort s) -> Int -> SearchState -> Maybe SearchState
bindNode :: forall s l.
DecidableIso s =>
Bool
-> HostIndex s l
-> Int
-> Maybe (SomeSort s)
-> Int
-> SearchState
-> Maybe SearchState
bindNode Bool
aliases HostIndex s l
host Int
r Maybe (SomeSort s)
sort Int
n state :: SearchState
state@(IntMap Int
m, IntSet
range, [Int]
order, IntSet
used, Map String [Int]
captures)
  | Just Int
n' <- Int -> IntMap Int -> Maybe Int
forall a. Int -> IntMap a -> Maybe a
IM.lookup Int
r IntMap Int
m = if Int
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
n' then SearchState -> Maybe SearchState
forall a. a -> Maybe a
Just SearchState
state else Maybe SearchState
forall a. Maybe a
Nothing
  | Bool -> Bool
not Bool
aliases Bool -> Bool -> Bool
&& Int -> IntSet -> Bool
IS.member Int
n IntSet
range = Maybe SearchState
forall a. Maybe a
Nothing
  | Bool -> (SomeSort s -> Bool) -> Maybe (SomeSort s) -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (\SomeSort s
expected -> Bool -> Bool
not (SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort SomeSort s
expected (HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.! Int
n))) Maybe (SomeSort s)
sort = Maybe SearchState
forall a. Maybe a
Nothing
  | Bool
otherwise = SearchState -> Maybe SearchState
forall a. a -> Maybe a
Just (Int -> Int -> IntMap Int -> IntMap Int
forall a. Int -> a -> IntMap a -> IntMap a
IM.insert Int
r Int
n IntMap Int
m, Int -> IntSet -> IntSet
IS.insert Int
n IntSet
range, [Int]
order, IntSet
used, Map String [Int]
captures)

compiledMatches :: (Eq l, DecidableIso s) => CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatches :: forall l s key.
(Eq l, DecidableIso s) =>
CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatches = IntSet
-> CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
forall l s key.
(Eq l, DecidableIso s) =>
IntSet
-> CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatchesAvoiding IntSet
IS.empty

-- Protected nodes may occur inside captured sequences, but may not be
-- selected by a numbered pattern port (including an explicit interface).
-- Only fixed replacements can use captures containing these nodes.
compiledMatchesAvoiding
  :: (Eq l, DecidableIso s) => IS.IntSet -> CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatchesAvoiding :: forall l s key.
(Eq l, DecidableIso s) =>
IntSet
-> CompiledRules key s l -> Graph s l -> [(Int, Prepared s l)]
compiledMatchesAvoiding IntSet
protected (CompiledRules Vector (key, Rule s l)
rules Vector (Signature l)
signatures Net s
net Bool
reducing) Graph s l
g =
  [ (Int
i, Prepared s l
prepared)
  | (Int
i, [Int]
_, IntMap Int
_, Prepared s l
prepared) <-
      ((Int, [Int], IntMap Int, Prepared s l) -> (Int, [Int], [Int]))
-> [(Int, [Int], IntMap Int, Prepared s l)]
-> [(Int, [Int], IntMap Int, Prepared s l)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn
        (\(Int
i, [Int]
order, IntMap Int
m, Prepared s l
_) -> (Int
i, [Int]
order, IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
m))
        (Net s -> SearchState -> [(Int, [Int], IntMap Int, Prepared s l)]
walk Net s
net (IntMap Int
forall a. IntMap a
IM.empty, IntSet
IS.empty, [], IntSet
IS.empty, Map String [Int]
forall k a. Map k a
M.empty))
  ]
  where
    host :: HostIndex s l
host = Vector (Signature l) -> Graph s l -> HostIndex s l
forall l s.
Eq l =>
Vector (Signature l) -> Graph s l -> HostIndex s l
indexHost Vector (Signature l)
signatures Graph s l
g
    walk :: Net s -> SearchState -> [(Int, [Int], IntMap Int, Prepared s l)]
walk (Net [Terminal]
terminals [(Step s, Net s)]
branches) state :: SearchState
state@(IntMap Int
registers, IntSet
range, [Int]
order, IntSet
used, Map String [Int]
captures) =
      [ (Int
i, [Int]
originalOrder, IntMap Int
mapping, Prepared s l
prepared)
      | IntSet -> IntSet -> Bool
IS.disjoint IntSet
protected IntSet
range
      , Terminal Int
i IntMap Int
originalNodes [Int]
boxRegisters <- [Terminal]
terminals
      , let mapping :: IntMap Int
mapping = (Int -> Int) -> IntMap Int -> IntMap Int
forall a b. (a -> b) -> IntMap a -> IntMap b
IM.map (IntMap Int
registers IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) IntMap Int
originalNodes
            (key
_, Rule s l
r) = Vector (key, Rule s l)
rules Vector (key, Rule s l) -> Int -> (key, Rule s l)
forall a. Vector a -> Int -> a
V.! Int
i
            originalOrder :: [Int]
originalOrder = (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Vector Int
boxImages Vector Int -> Int -> Int
forall a. Vector a -> Int -> a
V.!) [Int]
boxRegisters
      , prepared :: Prepared s l
prepared@(Graph s (LabelTest l)
lhs, Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box l Int]
replacement, (IntMap Int
nodes, IntSet
selected)) <-
          IntSet
-> HostIndex s l
-> Rule s l
-> IntMap Int
-> IntSet
-> Map String [Int]
-> [Int]
-> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
IntSet
-> HostIndex s l
-> Rule s l
-> IntMap Int
-> IntSet
-> Map String [Int]
-> [Int]
-> [Prepared s l]
prepareMatch IntSet
protected HostIndex s l
host Rule s l
r IntMap Int
mapping IntSet
used Map String [Int]
captures [Int]
originalOrder
      , Bool -> Bool
not Bool
reducing 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]
replacement Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< IntSet -> Int
IS.size IntSet
selected
      , (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
nodes IntSet
selected) (Graph s (LabelTest l) -> [Int]
forall s l. Graph s l -> [Int]
internalNodes Graph s (LabelTest l)
lhs)
      ]
        [(Int, [Int], IntMap Int, Prepared s l)]
-> [(Int, [Int], IntMap Int, Prepared s l)]
-> [(Int, [Int], IntMap Int, Prepared s l)]
forall a. [a] -> [a] -> [a]
++ [(Int, [Int], IntMap Int, Prepared s l)
result | (Step s
step, Net s
next) <- [(Step s, Net s)]
branches, SearchState
state' <- HostIndex s l -> Step s -> SearchState -> [SearchState]
forall s l.
DecidableIso s =>
HostIndex s l -> Step s -> SearchState -> [SearchState]
runStep HostIndex s l
host Step s
step SearchState
state, (Int, [Int], IntMap Int, Prepared s l)
result <- Net s -> SearchState -> [(Int, [Int], IntMap Int, Prepared s l)]
walk Net s
next SearchState
state']
      where
        boxImages :: Vector Int
boxImages = [Int] -> Vector Int
forall a. [a] -> Vector a
V.fromList ([Int] -> [Int]
forall a. [a] -> [a]
reverse [Int]
order)
    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 (HostIndex s l -> IntSet
forall s l. HostIndex s l -> IntSet
indexedBoundary HostIndex s l
host)
           Bool -> Bool -> Bool
&& ((Int, [Int]) -> Bool) -> [(Int, [Int])] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\(Int
_, [Int]
boxes) -> (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (Int -> IntSet -> Bool
`IS.member` IntSet
used) [Int]
boxes) (IntMap (Int, [Int]) -> [(Int, [Int])]
forall a. IntMap a -> [a]
IM.elems (HostIndex s l -> Vector (IntMap (Int, [Int]))
forall s l. HostIndex s l -> Vector (IntMap (Int, [Int]))
indexedIncidence HostIndex s l
host Vector (IntMap (Int, [Int])) -> Int -> IntMap (Int, [Int])
forall a. Vector a -> Int -> a
V.! Int
y))

prepareMatch
  :: (Eq l, DecidableIso s)
  => IS.IntSet -> HostIndex s l -> Rule s l -> IM.IntMap Int -> IS.IntSet -> M.Map String [Int] -> [Int] -> [Prepared s l]
prepareMatch :: forall l s.
(Eq l, DecidableIso s) =>
IntSet
-> HostIndex s l
-> Rule s l
-> IntMap Int
-> IntSet
-> Map String [Int]
-> [Int]
-> [Prepared s l]
prepareMatch IntSet
_ HostIndex s l
host (Rule Graph s (LabelTest l)
lhs [l] -> Maybe (Graph s l)
instantiate) IntMap Int
mapping IntSet
used Map String [Int]
_ [Int]
order = Maybe (Prepared s l) -> [Prepared s l]
forall a. Maybe a -> [a]
maybeToList (Maybe (Prepared s l) -> [Prepared s l])
-> Maybe (Prepared s l) -> [Prepared s l]
forall a b. (a -> b) -> a -> b
$ do
  rhs <- [l] -> Maybe (Graph s l)
instantiate [Box l Int -> l
forall l n. Box l n -> l
label (HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i) | Int
i <- [Int]
order]
  pure (lhs, rhs, (mapping, used))
prepareMatch IntSet
protected HostIndex s l
host (PortRule (PortGraph [SomeSort s]
ns [Int]
interface [Box (LabelTest l) Port]
_) PortReplacement s l
replacement) IntMap Int
mapping IntSet
used Map String [Int]
captures [Int]
order = Maybe (Prepared s l) -> [Prepared s l]
forall a. Maybe a -> [a]
maybeToList (Maybe (Prepared s l) -> [Prepared s l])
-> Maybe (Prepared s l) -> [Prepared s l]
forall a b. (a -> b) -> a -> b
$ do
  PortGraph rs rightInterface rightBoxes <- IntSet
-> PortReplacement s l
-> Map String [Int]
-> [l]
-> Maybe (PortGraph s l)
forall s l.
IntSet
-> PortReplacement s l
-> Map String [Int]
-> [l]
-> Maybe (PortGraph s l)
instantiatePorts IntSet
protected PortReplacement s l
replacement Map String [Int]
captures ((Box l Int -> l) -> [Box l Int] -> [l]
forall a b. (a -> b) -> [a] -> [b]
map Box l Int -> l
forall l n. Box l n -> l
label [Box l Int]
selected)
  let captured = [Int] -> [Int]
forall a. Ord a => [a] -> [a]
nubOrd ([[Int]] -> [Int]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat (Map String [Int] -> [[Int]]
forall k a. Map k a -> [a]
M.elems Map String [Int]
captures))
      kept = [Int] -> [Int]
forall a. Ord a => [a] -> [a]
nubOrd ((Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) [Int]
interface [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
captured)
      deleted = [IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! 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
n Int -> [Int] -> Bool
forall (t :: Type -> Type) a.
(Foldable t, Eq a) =>
a -> t a -> Bool
`notElem` [Int]
interface]
  -- A captured alias must remain alive, even if it also matched a numbered node.
  unless (all (`notElem` captured) deleted) Nothing
  let nodes = [Int] -> [Int]
forall a. Ord a => [a] -> [a]
nubOrd (IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
mapping [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
captured)
      leftIndices = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
nodes [Int
0 ..])
      interfaceMap = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip ((Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) [Int]
interface) [Int]
rightInterface)
      extra = [Int
n | Int
n <- [Int]
captured, Int -> IntMap Int -> Bool
forall a. Int -> IntMap a -> Bool
IM.notMember Int
n IntMap Int
interfaceMap]
      rightIndices = IntMap Int -> IntMap Int -> IntMap Int
forall a. IntMap a -> IntMap a -> IntMap a
IM.union IntMap Int
interfaceMap ([(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
extra [[SomeSort s] -> Int
forall a. [a] -> Int
forall (t :: Type -> Type) a. Foldable t => t a -> Int
length [SomeSort s]
rs ..]))
      port (Node Int
n) = [Int] -> Maybe [Int]
forall a. a -> Maybe a
Just [Int
n]
      port (Capture String
name) = (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (IntMap Int
rightIndices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) ([Int] -> [Int]) -> Maybe [Int] -> Maybe [Int]
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> Map String [Int] -> Maybe [Int]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup String
name Map String [Int]
captures
      port (Element String
name Int
i) = do
        values <- String -> Map String [Int] -> Maybe [Int]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup String
name Map String [Int]
captures
        if i >= 0 && i < length values then Just [rightIndices IM.! (values !! i)] else Nothing
      expand [Port]
ps = [[Int]] -> [Int]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat ([[Int]] -> [Int]) -> Maybe [[Int]] -> Maybe [Int]
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> (Port -> Maybe [Int]) -> [Port] -> Maybe [[Int]]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Port -> Maybe [Int]
port [Port]
ps
      left =
        [SomeSort s]
-> [Int]
-> [Int]
-> [Box (LabelTest l) Int]
-> Graph s (LabelTest l)
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph
          [HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.! Int
n | Int
n <- [Int]
nodes]
          [IntMap Int
leftIndices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
n | Int
n <- [Int]
kept]
          []
          [(Int -> Int) -> Box (LabelTest l) Int -> Box (LabelTest l) Int
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 (IntMap Int
leftIndices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) (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]
is [Int]
os) | Box l
l [Int]
is [Int]
os <- [Box l Int]
selected]
      rightSorts = [SomeSort s]
rs [SomeSort s] -> [SomeSort s] -> [SomeSort s]
forall a. [a] -> [a] -> [a]
++ [HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.! Int
n | Int
n <- [Int]
extra]
  boxes <- traverse (\(Box l
l [Port]
is [Port]
os) -> l -> [Int] -> [Int] -> Box l Int
forall l n. l -> [n] -> [n] -> Box l n
Box l
l ([Int] -> [Int] -> Box l Int)
-> Maybe [Int] -> Maybe ([Int] -> Box l Int)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> [Port] -> Maybe [Int]
expand [Port]
is Maybe ([Int] -> Box l Int) -> Maybe [Int] -> Maybe (Box l Int)
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
<*> [Port] -> Maybe [Int]
expand [Port]
os) rightBoxes
  pure (left, Graph rightSorts [rightIndices IM.! n | n <- kept] [] boxes, (IM.fromList (zip [0 ..] nodes), used))
  where
    selected :: [Box l Int]
selected = [HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i | Int
i <- [Int]
order]
prepareMatch IntSet
_ HostIndex s l
host (SubgraphRule Graph s (Either l String)
lhs Graph s (Either l String)
rhs) IntMap Int
mapping IntSet
used Map String [Int]
_ [Int]
_ =
  HostIndex s l
-> Graph s (Either l String)
-> Graph s (Either l String)
-> IntMap Int
-> IntSet
-> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
HostIndex s l
-> Graph s (Either l String)
-> Graph s (Either l String)
-> IntMap Int
-> IntSet
-> [Prepared s l]
prepareSubgraphs HostIndex s l
host Graph s (Either l String)
lhs Graph s (Either l String)
rhs IntMap Int
mapping IntSet
used
prepareMatch IntSet
_ HostIndex s l
host (SortRule [SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]
instantiate (SubgraphRule Graph s (Either l String)
lhs (Graph [SomeSort s]
rs [Int]
ri [Int]
ro [Box (Either l String) Int]
rb))) IntMap Int
mapping IntSet
used Map String [Int]
_ [Int]
_ = do
  let Graph [SomeSort s]
ls [Int]
_ [Int]
_ [Box (Either l String) Int]
_ = Graph s (Either l String)
lhs
      actual :: [SomeSort s]
actual = [HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.! (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! 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]
ls Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]]
  sorts <- Maybe [SomeSort s] -> [[SomeSort s]]
forall a. Maybe a -> [a]
maybeToList ([SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]
instantiate [SomeSort s]
ls [SomeSort s]
actual [SomeSort s]
rs)
  if length sorts == length rs
    then prepareSubgraphs host lhs (Graph sorts ri ro rb) mapping used
    else []
prepareMatch IntSet
protected HostIndex s l
host (SortRule [SomeSort s] -> [SomeSort s] -> [SomeSort s] -> Maybe [SomeSort s]
instantiate Rule s l
r) IntMap Int
mapping IntSet
used Map String [Int]
captures [Int]
order = do
  (Graph ls li lo lb, Graph rs ri ro rb, match@(images, _)) <- IntSet
-> HostIndex s l
-> Rule s l
-> IntMap Int
-> IntSet
-> Map String [Int]
-> [Int]
-> [Prepared s l]
forall l s.
(Eq l, DecidableIso s) =>
IntSet
-> HostIndex s l
-> Rule s l
-> IntMap Int
-> IntSet
-> Map String [Int]
-> [Int]
-> [Prepared s l]
prepareMatch IntSet
protected HostIndex s l
host Rule s l
r IntMap Int
mapping IntSet
used Map String [Int]
captures [Int]
order
  maybeToList $ do
    let PortGraph patternSorts _ _ = rulePattern r
        actual = [HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.! (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! 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]
patternSorts Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]]
        leftSorts = [HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.! (IntMap Int
images IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! 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]
ls Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]]
    rightSorts <- instantiate patternSorts actual rs
    unless (length rightSorts == length rs) Nothing
    unless (length li + length lo == length ri + length ro) Nothing
    unless (and [sameSort (leftSorts !! l) (rightSorts !! r') | (l, r') <- zip (li ++ lo) (ri ++ ro)]) Nothing
    pure (Graph leftSorts li lo lb, Graph rightSorts ri ro rb, match)

-- Pattern nodes delimit captures. Outside those cuts, every incident box must
-- belong to the same region; the final dangling check protects host boundaries
-- and connections to fixed boxes. No arbitrary subsets of a region are searched.
prepareSubgraphs
  :: (Eq l, DecidableIso s)
  => HostIndex s l
  -> Graph s (Either l String)
  -> Graph s (Either l String)
  -> IM.IntMap Int
  -> IS.IntSet
  -> [Prepared s l]
prepareSubgraphs :: forall l s.
(Eq l, DecidableIso s) =>
HostIndex s l
-> Graph s (Either l String)
-> Graph s (Either l String)
-> IntMap Int
-> IntSet
-> [Prepared s l]
prepareSubgraphs HostIndex s l
host (Graph [SomeSort s]
_ [Int]
li [Int]
lo [Box (Either l String) Int]
lb) Graph s (Either l String)
rhs IntMap Int
mapping IntSet
fixed = do
  let holes :: [(String, Int, Int)]
holes = [(String
name, Int
a, Int
b) | Box (Right String
name) [Int
a] [Int
b] <- [Box (Either l String) Int]
lb]
      aliases :: Int -> Int
aliases = [(Int, Int)] -> Int -> Int
forall a. Enum a => [(a, a)] -> a -> a
unionFind [(Int
a, Int
b) | (String
_, Int
a, Int
b) <- [(String, Int, Int)]
holes, IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
a Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
b]
      groups :: IntMap IntSet
groups = (IntSet -> IntSet -> IntSet) -> [(Int, IntSet)] -> IntMap IntSet
forall a. (a -> a -> a) -> [(Int, a)] -> IntMap a
IM.fromListWith IntSet -> IntSet -> IntSet
IS.union [(Int
image, Int -> IntSet
IS.singleton (Int -> Int
aliases Int
n)) | (Int
n, Int
image) <- IntMap Int -> [(Int, Int)]
forall a. IntMap a -> [(Int, a)]
IM.toList IntMap Int
mapping]
  -- Only identity substitution may identify distinct pattern nodes.
  Bool -> [()] -> [()]
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless ((IntSet -> Bool) -> [IntSet] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all ((Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1) (Int -> Bool) -> (IntSet -> Int) -> IntSet -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IntSet -> Int
IS.size) (IntMap IntSet -> [IntSet]
forall a. IntMap a -> [a]
IM.elems IntMap IntSet
groups)) []
  (environment, selected) <- ((Map String (Graph s l), IntSet)
 -> (String, Int, Int) -> [(Map String (Graph s l), IntSet)])
-> (Map String (Graph s l), IntSet)
-> [(String, Int, Int)]
-> [(Map String (Graph s l), IntSet)]
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 (Graph s l), IntSet)
-> (String, Int, Int) -> [(Map String (Graph s l), IntSet)]
capture (Map String (Graph s l)
forall k a. Map k a
M.empty, IntSet
fixed) [(String, Int, Int)]
holes
  -- An unanchored identity would have no box occurrence to locate the rule.
  -- In particular, terminal uniqueness must not expand every terminal wire.
  when (IS.null selected) []
  replacement@(Graph rs ri ro _) <- maybeToList (instantiateSubgraphs rhs environment)
  let nodes = IntSet -> [Int]
IS.toAscList ([IntSet] -> IntSet
forall (f :: Type -> Type). Foldable f => f IntSet -> IntSet
IS.unions ([Int] -> IntSet
IS.fromList (IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
mapping) IntSet -> [IntSet] -> [IntSet]
forall a. a -> [a] -> [a]
: (Int -> IntSet) -> [Int] -> [IntSet]
forall a b. (a -> b) -> [a] -> [b]
map Int -> IntSet
boxNodes (IntSet -> [Int]
IS.toList IntSet
selected)))
      indices = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
nodes [Int
0 ..])
      leftSorts = (Int -> SomeSort s) -> [Int] -> [SomeSort s]
forall a b. (a -> b) -> [a] -> [b]
map (HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.!) [Int]
nodes
      ins = (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map ((IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) (Int -> Int) -> (Int -> Int) -> Int -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!)) [Int]
li
      outs = (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map ((IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) (Int -> Int) -> (Int -> Int) -> Int -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!)) [Int]
lo
      leftPlain =
        [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]
leftSorts
          [Int]
ins
          [Int]
outs
          [(Int -> Int) -> Box l Int -> Box l Int
forall a b. (a -> b) -> Box l a -> Box l b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap (IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) (HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i) | Int
i <- IntSet -> [Int]
IS.toList IntSet
selected]
      left = (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
leftPlain
  unless (length ins + length outs == length ri + length ro) []
  unless (and [sameSort (leftSorts !! a) (rs !! b) | (a, b) <- zip (ins ++ outs) (ri ++ ro)]) []
  when (sameGraph leftPlain replacement) []
  pure (left, replacement, (IM.fromList (zip [0 ..] nodes), selected))
  where
    cuts :: IntSet
cuts = [Int] -> IntSet
IS.fromList (IntMap Int -> [Int]
forall a. IntMap a -> [a]
IM.elems IntMap Int
mapping)
    boxNodes :: Int -> IntSet
boxNodes Int
i = let b :: Box l Int
b = HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i in [Int] -> IntSet
IS.fromList (Box l Int -> [Int]
forall l n. Box l n -> [n]
inputs Box l Int
b [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ Box l Int -> [Int]
forall l n. Box l n -> [n]
outputs Box l Int
b)
    capture :: (Map String (Graph s l), IntSet)
-> (String, Int, Int) -> [(Map String (Graph s l), IntSet)]
capture (Map String (Graph s l)
env, IntSet
used) (String
name, Int
a, Int
b) = do
      let input :: Int
input = IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
a
          output :: Int
output = IntMap Int
mapping IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
b
      region <- HostIndex s l -> IntSet -> IntSet -> Int -> Int -> [IntSet]
forall s l.
HostIndex s l -> IntSet -> IntSet -> Int -> Int -> [IntSet]
captureRegions HostIndex s l
host IntSet
cuts IntSet
used Int
input Int
output
      let nodes = IntSet -> [Int]
IS.toAscList (Int -> IntSet -> IntSet
IS.insert Int
input (Int -> IntSet -> IntSet
IS.insert Int
output ([IntSet] -> IntSet
forall (f :: Type -> Type). Foldable f => f IntSet -> IntSet
IS.unions ((Int -> IntSet) -> [Int] -> [IntSet]
forall a b. (a -> b) -> [a] -> [b]
map Int -> IntSet
boxNodes (IntSet -> [Int]
IS.toList IntSet
region)))))
          indices = [(Int, Int)] -> IntMap Int
forall a. [(Int, a)] -> IntMap a
IM.fromList ([Int] -> [Int] -> [(Int, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int]
nodes [Int
0 ..])
          captured =
            [SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
forall s l.
[SomeSort s] -> [Int] -> [Int] -> [Box l Int] -> Graph s l
Graph
              ((Int -> SomeSort s) -> [Int] -> [SomeSort s]
forall a b. (a -> b) -> [a] -> [b]
map (HostIndex s l -> Vector (SomeSort s)
forall s l. HostIndex s l -> Vector (SomeSort s)
indexedSorts HostIndex s l
host Vector (SomeSort s) -> Int -> SomeSort s
forall a. Vector a -> Int -> a
V.!) [Int]
nodes)
              [IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
input]
              [IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.! Int
output]
              [(Int -> Int) -> Box l Int -> Box l Int
forall a b. (a -> b) -> Box l a -> Box l b
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
fmap (IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) (HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i) | Int
i <- IntSet -> [Int]
IS.toList IntSet
region]
      case M.lookup name env of
        Just Graph s l
previous -> Bool -> [()] -> [()]
forall (f :: Type -> Type). Applicative f => Bool -> f () -> f ()
unless (Graph s l -> Graph s l -> Bool
forall l s.
(Eq l, DecidableIso s) =>
Graph s l -> Graph s l -> Bool
sameGraph Graph s l
previous Graph s l
captured) []
        Maybe (Graph s l)
Nothing -> () -> [()]
forall a. a -> [a]
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure ()
      pure (M.insert name captured env, IS.union used region)

-- Once endpoints are known, grow from an incident box until a cut is reached.
-- Every internal incidence belongs to the region; this also prevents a capture
-- from crossing another capture's interior or a host boundary.
captureRegions :: HostIndex s l -> IS.IntSet -> IS.IntSet -> Int -> Int -> [IS.IntSet]
captureRegions :: forall s l.
HostIndex s l -> IntSet -> IntSet -> Int -> Int -> [IntSet]
captureRegions HostIndex s l
host IntSet
cuts IntSet
used Int
input Int
output
  | Int
input Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
output = [IntSet
IS.empty]
  | Bool
otherwise =
      [ IntSet
region
      | IntSet
region <- [IntSet] -> [IntSet]
forall a. Ord a => [a] -> [a]
nubOrd [IntSet -> [Int] -> IntSet
visit IntSet
IS.empty [Int
seed] | Int
seed <- (Int, [Int]) -> [Int]
forall a b. (a, b) -> b
snd (HostIndex s l -> Vector (Int, [Int])
forall s l. HostIndex s l -> Vector (Int, [Int])
indexedNeighbours HostIndex s l
host Vector (Int, [Int]) -> Int -> (Int, [Int])
forall a. Vector a -> Int -> a
V.! Int
input), Int -> IntSet -> Bool
IS.notMember Int
seed IntSet
used]
      , let nodes :: IntSet
nodes = [IntSet] -> IntSet
forall (f :: Type -> Type). Foldable f => f IntSet -> IntSet
IS.unions ((Int -> IntSet) -> [Int] -> [IntSet]
forall a b. (a -> b) -> [a] -> [b]
map Int -> IntSet
boxNodes (IntSet -> [Int]
IS.toList IntSet
region))
            interior :: IntSet
interior = IntSet -> IntSet -> IntSet
IS.difference IntSet
nodes IntSet
cuts
      , IntSet -> IntSet -> IntSet
IS.intersection IntSet
cuts IntSet
nodes IntSet -> IntSet -> Bool
forall a. Eq a => a -> a -> Bool
== [Int] -> IntSet
IS.fromList [Int
input, Int
output]
      , IntSet -> Int -> [Bool]
boundaryPorts IntSet
region Int
input [Bool] -> [Bool] -> Bool
forall a. Eq a => a -> a -> Bool
== [Bool
False]
      , IntSet -> Int -> [Bool]
boundaryPorts IntSet
region Int
output [Bool] -> [Bool] -> Bool
forall a. Eq a => a -> a -> Bool
== [Bool
True]
      , IntSet -> IntSet -> Bool
IS.disjoint IntSet
interior (HostIndex s l -> IntSet
forall s l. HostIndex s l -> IntSet
indexedBoundary HostIndex s l
host)
      , (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (\Int
n -> (Int -> Bool) -> [Int] -> Bool
forall (t :: Type -> Type) a.
Foldable t =>
(a -> Bool) -> t a -> Bool
all (Int -> IntSet -> Bool
`IS.member` IntSet
region) ((Int, [Int]) -> [Int]
forall a b. (a, b) -> b
snd (HostIndex s l -> Vector (Int, [Int])
forall s l. HostIndex s l -> Vector (Int, [Int])
indexedNeighbours HostIndex s l
host Vector (Int, [Int]) -> Int -> (Int, [Int])
forall a. Vector a -> Int -> a
V.! Int
n))) (IntSet -> [Int]
IS.toList IntSet
interior)
      ]
  where
    boxNodes :: Int -> IntSet
boxNodes Int
i = let b :: Box l Int
b = HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i in [Int] -> IntSet
IS.fromList (Box l Int -> [Int]
forall l n. Box l n -> [n]
inputs Box l Int
b [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ Box l Int -> [Int]
forall l n. Box l n -> [n]
outputs Box l Int
b)
    visit :: IntSet -> [Int] -> IntSet
visit IntSet
seen [] = IntSet
seen
    visit IntSet
seen (Int
i : [Int]
pending)
      | Int -> IntSet -> Bool
IS.member Int
i IntSet
seen Bool -> Bool -> Bool
|| Int -> IntSet -> Bool
IS.member Int
i IntSet
used = IntSet -> [Int] -> IntSet
visit IntSet
seen [Int]
pending
      | Bool
otherwise =
          IntSet -> [Int] -> IntSet
visit
            (Int -> IntSet -> IntSet
IS.insert Int
i IntSet
seen)
            ([[Int]] -> [Int]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat [(Int, [Int]) -> [Int]
forall a b. (a, b) -> b
snd (HostIndex s l -> Vector (Int, [Int])
forall s l. HostIndex s l -> Vector (Int, [Int])
indexedNeighbours HostIndex s l
host Vector (Int, [Int]) -> Int -> (Int, [Int])
forall a. Vector a -> Int -> a
V.! Int
n) | Int
n <- IntSet -> [Int]
IS.toList (IntSet -> IntSet -> IntSet
IS.difference (Int -> IntSet
boxNodes Int
i) IntSet
cuts)] [Int] -> [Int] -> [Int]
forall a. [a] -> [a] -> [a]
++ [Int]
pending)
    boundaryPorts :: IntSet -> Int -> [Bool]
boundaryPorts IntSet
region Int
node =
      [Int -> Bool
forall a. Integral a => a -> Bool
odd Int
p | Int
i <- IntSet -> [Int]
IS.toList IntSet
region, (Int
p, Int
n) <- Box l Int -> [(Int, Int)]
forall l n. Box l n -> [(Int, n)]
portsOf (HostIndex s l -> Vector (Box l Int)
forall s l. HostIndex s l -> Vector (Box l Int)
indexedBoxes HostIndex s l
host Vector (Box l Int) -> Int -> Box l Int
forall a. Vector a -> Int -> a
V.! Int
i), Int
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
node]

instantiateSubgraphs
  :: (DecidableIso s)
  => Graph s (Either l String) -> M.Map String (Graph s l) -> Maybe (Graph s l)
instantiateSubgraphs :: forall s l.
DecidableIso s =>
Graph s (Either l String)
-> Map String (Graph s l) -> Maybe (Graph s l)
instantiateSubgraphs (Graph [SomeSort s]
ns [Int]
ins [Int]
outs [Box (Either l String) Int]
bs) Map String (Graph s l)
env = do
  captures <- ((String, Int, Int) -> Maybe (Int, Int, Graph s l))
-> [(String, Int, Int)] -> Maybe [(Int, Int, Graph s l)]
forall (t :: Type -> Type) (f :: Type -> Type) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: Type -> Type) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (\(String
name, Int
a, Int
b) -> (Int
a,Int
b,) (Graph s l -> (Int, Int, Graph s l))
-> Maybe (Graph s l) -> Maybe (Int, Int, Graph s l)
forall (f :: Type -> Type) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> Map String (Graph s l) -> Maybe (Graph s l)
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup String
name Map String (Graph s l)
env) [(String
name, Int
a, Int
b) | Box (Right String
name) [Int
a] [Int
b] <- [Box (Either l String) Int]
bs]
  let (_, copies) = mapAccumL (\Int
offset (Int
a, Int
b, g :: Graph s l
g@(Graph [SomeSort s]
sorts [Int]
_ [Int]
_ [Box l Int]
_)) -> (Int
offset 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]
sorts, (Int
offset, Int
a, Int
b, Graph s l
g))) (length ns) captures
      root = [(Int, Int)] -> Int -> Int
forall a. Enum a => [(a, a)] -> a -> a
unionFind ([[(Int, Int)]] -> [(Int, Int)]
forall (t :: Type -> Type) a. Foldable t => t [a] -> [a]
concat [[(Int
a, Int
offset Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
i), (Int
b, Int
offset Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
o)] | (Int
offset, Int
a, Int
b, Graph [SomeSort s]
_ [Int
i] [Int
o] [Box l Int]
_) <- [(Int, Int, Int, Graph s l)]
copies])
      numbered = [Int] -> [SomeSort s] -> [(Int, SomeSort s)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [SomeSort s]
ns [(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
offset ..] [SomeSort s]
sorts | (Int
offset, Int
_, Int
_, Graph [SomeSort s]
sorts [Int]
_ [Int]
_ [Box l Int]
_) <- [(Int, Int, Int, Graph s l)]
copies]
      nodeSorts = [(Int, SomeSort s)] -> IntMap (SomeSort s)
forall a. [(Int, a)] -> IntMap a
IM.fromList [(Int -> Int
root Int
n, SomeSort s
s) | (Int
n, SomeSort s
s) <- [(Int, SomeSort s)]
numbered]
      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 = (IntMap Int
indices IntMap Int -> Int -> Int
forall a. IntMap a -> Int -> a
IM.!) (Int -> Int) -> (Int -> Int) -> Int -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Int
root
      boxes =
        [l -> [Int] -> [Int] -> Box l Int
forall l n. l -> [n] -> [n] -> Box l n
Box l
l [Int]
i [Int]
o | Box (Left l
l) [Int]
i [Int]
o <- [Box (Either l String) Int]
bs]
          [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
offset)) [Box l Int]
boxes' | (Int
offset, Int
_, Int
_, Graph [SomeSort s]
_ [Int]
_ [Int]
_ [Box l Int]
boxes') <- [(Int, Int, Int, Graph s l)]
copies]
  unless (all (\(Int
n, SomeSort s
s) -> SomeSort s -> SomeSort s -> Bool
forall s. DecidableIso s => SomeSort s -> SomeSort s -> Bool
sameSort SomeSort s
s (IntMap (SomeSort s)
nodeSorts IntMap (SomeSort s) -> Int -> SomeSort s
forall a. IntMap a -> Int -> a
IM.! Int -> Int
root Int
n)) numbered) Nothing
  pure (Graph (IM.elems nodeSorts) (map renumber ins) (map renumber outs) (map (fmap renumber) boxes))