{-# LANGUAGE DeriveGeneric #-}{-# LANGUAGE LambdaCase #-}{-# LANGUAGE OverloadedStrings #-}{-# LANGUAGE PatternSynonyms #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE ViewPatterns #-}-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com-- SPDX-License-Identifier: MITmodule AST ( Slot (..) , Expression (ExFormation, ExXi, ExRoot, ExTermination, ExApplication, ExDispatch, ExMeta, ExAny, ExPhiMeet, ExPhiAgain, ExBytes, BaseObject, DataString, DataNumber, DataObject) , Argument (..) , Binding (..) , Bytes (..) , Attribute (..) , Function (..) , hashExpression , hashShape , hashSkeleton , inert , distinct , repeated , attributeFromBinding , alike , alike' , bijection , bijection' , akin , akin' , akin'' , deepness , reaches , boxed , intact , suffixed , within , within' , within'' , Searched , isName , symbols , lifted , denoted , countNodes , matchBaseObject , matchDataObject , dataBytes )whereimport Data.Bits (xor)import qualified Data.IntMap.Strict as IntMapimport qualified Data.IntSet as IntSetimport qualified Data.List as Listimport qualified Data.Map.Strict as Mapimport Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe)import Data.Text (Text)import qualified Data.Text as Timport GHC.Generics (Generic)import Pointer (identical)data Slot = Slot Text Int deriving (Eq, Ord, Show)data Expression = Formed Facts [Binding] | ExXi | ExRoot | ExTermination | Applied Facts Expression Argument | Dispatched Facts Expression Attribute | ExMeta Text | ExAny Slot | ExPhiMeet (Maybe String) Int Expression | ExPhiAgain (Maybe String) Int Expression | ExBytes Bytesdata Facts = Facts !Int Int !Int !Bool !Bool{-# COMPLETE ExFormation, ExXi, ExRoot, ExTermination, ExApplication, ExDispatch, ExMeta, ExAny, ExPhiMeet, ExPhiAgain, ExBytes #-}pattern ExFormation :: [Binding] -> Expressionpattern ExFormation bds <- Formed _ bds where ExFormation bds = cached (`Formed` bds)pattern ExApplication :: Expression -> Argument -> Expressionpattern ExApplication expr arg <- Applied _ expr arg where ExApplication expr arg = cached (\facts -> Applied facts expr arg)pattern ExDispatch :: Expression -> Attribute -> Expressionpattern ExDispatch expr attr <- Dispatched _ expr attr where ExDispatch expr attr = cached (\facts -> Dispatched facts expr attr)intact :: (Eq part) => part -> whole -> (part -> whole) -> part -> wholeintact old whole make new | new == old = whole | otherwise = make newsuffixed :: (Monad walk, Eq item) => (item -> walk item) -> [item] -> walk [item]suffixed change items = snd <$> go change items where go :: (Monad walk, Eq item) => (item -> walk item) -> [item] -> walk (Bool, [item]) go _ [] = pure (True, []) go turn whole@(item : rest) = do item' <- turn item (same, rest') <- go turn rest pure (if same && item' == item then (True, whole) else (False, item' : rest'))cached :: (Facts -> Expression) -> Expressioncached node = let term = node (established term) in termknown :: Expression -> Factsknown (Formed facts _) = factsknown (Applied facts _ _) = factsknown (Dispatched facts _ _) = factsknown term = established termestablished :: Expression -> Factsestablished term = Facts (layer id hashExpression term) (layer (const 0) hashShape term) (tally term) (calm term) (unrepeated term)instance Eq Expression where left == right = identical left right || congruent left right where congruent :: Expression -> Expression -> Bool congruent (Formed facts bds) (Formed facts' bds') = alongside facts facts' && bds == bds' congruent (Applied facts expr arg) (Applied facts' expr' arg') = alongside facts facts' && expr == expr' && arg == arg' congruent (Dispatched facts expr attr) (Dispatched facts' expr' attr') = alongside facts facts' && attr == attr' && expr == expr' congruent ExXi ExXi = True congruent ExRoot ExRoot = True congruent ExTermination ExTermination = True congruent (ExMeta meta) (ExMeta meta') = meta == meta' congruent (ExAny slot) (ExAny slot') = slot == slot' congruent (ExPhiMeet prefix idx expr) (ExPhiMeet prefix' idx' expr') = prefix == prefix' && idx == idx' && expr == expr' congruent (ExPhiAgain prefix idx expr) (ExPhiAgain prefix' idx' expr') = prefix == prefix' && idx == idx' && expr == expr' congruent (ExBytes bts) (ExBytes bts') = bts == bts' congruent _ _ = False alongside :: Facts -> Facts -> Bool alongside (Facts digest _ _ _ _) (Facts digest' _ _ _ _) = digest == digest'instance Ord Expression where compare left right | identical left right = EQ | otherwise = ordered left right where ordered :: Expression -> Expression -> Ordering ordered (ExFormation bds) (ExFormation bds') = compare bds bds' ordered (ExApplication expr arg) (ExApplication expr' arg') = compare expr expr' <> compare arg arg' ordered (ExDispatch expr attr) (ExDispatch expr' attr') = compare expr expr' <> compare attr attr' ordered (ExMeta meta) (ExMeta meta') = compare meta meta' ordered (ExAny slot) (ExAny slot') = compare slot slot' ordered (ExPhiMeet prefix idx expr) (ExPhiMeet prefix' idx' expr') = compare prefix prefix' <> compare idx idx' <> compare expr expr' ordered (ExPhiAgain prefix idx expr) (ExPhiAgain prefix' idx' expr') = compare prefix prefix' <> compare idx idx' <> compare expr expr' ordered (ExBytes bts) (ExBytes bts') = compare bts bts' ordered one two = compare (rank one) (rank two) rank :: Expression -> Int rank = \case ExFormation _ -> 0 ExXi -> 1 ExRoot -> 2 ExTermination -> 3 ExApplication _ _ -> 4 ExDispatch _ _ -> 5 ExMeta _ -> 6 ExAny _ -> 7 ExPhiMeet{} -> 8 ExPhiAgain{} -> 9 ExBytes _ -> 10instance Show Expression where showsPrec prec = \case ExFormation bds -> showParen (prec > 10) (showString "ExFormation " . showsPrec 11 bds) ExXi -> showString "ExXi" ExRoot -> showString "ExRoot" ExTermination -> showString "ExTermination" ExApplication expr arg -> showParen (prec > 10) (showString "ExApplication " . showsPrec 11 expr . showChar ' ' . showsPrec 11 arg) ExDispatch expr attr -> showParen (prec > 10) (showString "ExDispatch " . showsPrec 11 expr . showChar ' ' . showsPrec 11 attr) ExMeta meta -> showParen (prec > 10) (showString "ExMeta " . showsPrec 11 meta) ExAny slot -> showParen (prec > 10) (showString "ExAny " . showsPrec 11 slot) ExPhiMeet prefix idx expr -> showParen (prec > 10) (showString "ExPhiMeet " . showsPrec 11 prefix . showChar ' ' . showsPrec 11 idx . showChar ' ' . showsPrec 11 expr) ExPhiAgain prefix idx expr -> showParen (prec > 10) (showString "ExPhiAgain " . showsPrec 11 prefix . showChar ' ' . showsPrec 11 idx . showChar ' ' . showsPrec 11 expr) ExBytes bts -> showParen (prec > 10) (showString "ExBytes " . showsPrec 11 bts)data Argument = ArTau Attribute Expression deriving (Eq, Ord, Show, Generic)data Binding = BiTau Attribute Expression | BiVoid Attribute | BiDelta Bytes | BiLambda Function | BiMeta Text | BiAny Slot deriving (Eq, Ord, Show, Generic)data Bytes = BtEmpty | BtOne String | BtMany [String] | BtMeta Text | BtAny Slot deriving (Eq, Ord, Show, Generic)data Attribute = AtLabel Text | AtPhi | AtRho | AtLambda | AtDelta | AtMeta Text | AtAny Slot deriving (Eq, Generic, Ord)data Function = Function Text | FnMeta Text | FnAny Slot | FnSymbol Int | FnFresh Slot deriving (Eq, Generic, Show, Ord)instance Show Attribute where show (AtLabel label) = T.unpack label show AtRho = "ρ" show AtPhi = "φ" show AtDelta = "Δ" show AtLambda = "λ" show (AtMeta meta) = '!' : T.unpack meta show (AtAny (Slot kind _)) = '!' : T.unpack kindhashExpression :: Expression -> InthashExpression term = case known term of Facts digest _ _ _ _ -> digesthashShape :: Expression -> InthashShape term = case known term of Facts _ shape _ _ _ -> shapeisName :: Text -> BoolisName = T.isPrefixOf "n·"hashSkeleton :: Expression -> InthashSkeleton = hashShape . \case ExFormation bds -> ExFormation (map bare bds) ExApplication _ (ArTau attr _) -> ExApplication ExXi (ArTau attr ExXi) ExDispatch _ attr -> ExDispatch ExXi attr ExPhiMeet prefix idx _ -> ExPhiMeet prefix idx ExXi ExPhiAgain prefix idx _ -> ExPhiAgain prefix idx ExXi term -> term where bare :: Binding -> Binding bare (BiTau attr _) = BiTau attr ExXi bare binding = bindinglayer :: (Int -> Int) -> (Expression -> Int) -> Expression -> Intlayer symbol child = goExpr fnvOffset where fnvPrime, fnvOffset :: Int fnvPrime = 1099511628211 fnvOffset = 14695981039 step :: Int -> Int -> Int step h x = (h `xor` x) * fnvPrime hashText :: Int -> Text -> Int hashText = T.foldl' (\h c -> step h (fromEnum c)) hashString :: Int -> String -> Int hashString = List.foldl' (\h c -> step h (fromEnum c)) goSlot :: Int -> Slot -> Int goSlot h (Slot kind idx) = step (hashText h kind) idx hashMaybeString :: Int -> Maybe String -> Int hashMaybeString h Nothing = step h 0 hashMaybeString h (Just s) = hashString (step h 1) s goExpr :: Int -> Expression -> Int goExpr h = \case ExFormation bds -> List.foldl' goBinding (step h 1) bds ExXi -> step h 2 ExRoot -> step h 3 ExTermination -> step h 4 ExApplication ex arg -> goArgument (step (step h 5) (child ex)) arg ExDispatch ex at -> goAttribute (step (step h 6) (child ex)) at ExMeta t | isName t -> step (step h 40) (symbol (hashText fnvOffset t)) | otherwise -> hashText (step h 7) t ExAny slot -> goSlot (step h 32) slot ExPhiMeet ms i ex -> step (hashMaybeString (step (step h 9) i) ms) (child ex) ExPhiAgain ms i ex -> step (hashMaybeString (step (step h 10) i) ms) (child ex) ExBytes bts -> goBytes (step h 8) bts goBinding :: Int -> Binding -> Int goBinding h = \case BiTau at ex -> step (goAttribute (step h 11) at) (child ex) BiDelta bts -> goBytes (step h 12) bts BiVoid at -> goAttribute (step h 13) at BiLambda fn -> goFunction (step h 14) fn BiMeta t -> hashText (step h 15) t BiAny slot -> goSlot (step h 33) slot goBytes :: Int -> Bytes -> Int goBytes h = \case BtEmpty -> step h 17 BtOne s -> hashString (step h 18) s BtMany ss -> List.foldl' hashString (step h 19) ss BtMeta t -> hashText (step h 20) t BtAny slot -> goSlot (step h 34) slot goAttribute :: Int -> Attribute -> Int goAttribute h = \case AtLabel t -> hashText (step h 21) t AtPhi -> step h 23 AtRho -> step h 24 AtLambda -> step h 25 AtDelta -> step h 26 AtMeta t -> hashText (step h 27) t AtAny slot -> goSlot (step h 35) slot goArgument :: Int -> Argument -> Int goArgument h = \case ArTau at ex -> step (goAttribute (step h 22) at) (child ex) goFunction :: Int -> Function -> Int goFunction h = \case Function t -> hashText (step h 16) t FnMeta t -> hashText (step h 29) t FnAny slot -> goSlot (step h 37) slot FnSymbol idx -> step (step h 38) (symbol idx) FnFresh slot -> goSlot (step h 39) slotalike :: Expression -> Expression -> Boolalike = alike' (const Nothing)alike' :: (Text -> Maybe Expression) -> Expression -> Expression -> Boolalike' = likenedakin :: Expression -> Expression -> Boolakin = akin' (const Nothing) (const Nothing)akin' :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Expression -> Expression -> Boolakin' look depth before after = fst (akin'' look depth Map.empty before after)akin'' :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Searched -> Expression -> Expression -> (Bool, Searched)akin'' look depth searched one two = case matching look grown searched one two of (found, searched') -> (isJust found, searched') where grown :: Expression -> Expression -> Searched -> (Maybe Bool, Searched) grown before@(ExFormation left) after@(ExFormation right) kept | boxed left && boxed right = decided (within'' look kept before after) grown before after kept | pending before && pending after && deeper before after = decided (within'' look kept before after) grown _ _ kept = (Nothing, kept) decided :: (Bool, Searched) -> (Maybe Bool, Searched) decided (found, kept) = (Just found, kept) deeper :: Expression -> Expression -> Bool deeper before after = not (reaches look depth (deepness look depth after) before) pending :: Expression -> Bool pending (ExMeta name) = maybe False pending (look name) pending (ExApplication _ _) = True pending (ExDispatch inner _) = pending inner pending _ = Falsedeepness :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Expression -> Intdeepness look depth = go where go :: Expression -> Int go (ExMeta name) = fromMaybe (maybe 0 go (look name)) (depth name) go (ExApplication callee (ArTau _ arg)) = deepest [callee, arg] go (ExDispatch inner _) = deepest [inner] go (ExFormation bds) = deepest [body | BiTau _ body <- bds] go _ = 0 deepest :: [Expression] -> Int deepest = List.foldl' (\most part -> max most (go part + 1)) 1reaches :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Int -> Expression -> Boolreaches look depth = go where go :: Int -> Expression -> Bool go limit _ | limit <= 0 = True go limit (ExMeta name) = maybe (maybe False (go limit) (look name)) (>= limit) (depth name) go limit (ExApplication callee (ArTau _ arg)) = limit <= 1 || go (pred limit) callee || go (pred limit) arg go limit (ExDispatch inner _) = limit <= 1 || go (pred limit) inner go limit (ExFormation bds) = limit <= 1 || any (go (pred limit)) [body | BiTau _ body <- bds] go _ _ = Falseboxed :: [Binding] -> Boolboxed bds = any phi bds && not (any lambda bds) && not (any delta bds) where phi :: Binding -> Bool phi (BiTau AtPhi _) = True phi _ = False lambda :: Binding -> Bool lambda (BiLambda _) = True lambda _ = False delta :: Binding -> Bool delta (BiDelta _) = True delta _ = Falsebijection :: Expression -> Expression -> Maybe (Map.Map Int Int)bijection = bijection' (const Nothing)bijection' :: (Text -> Maybe Expression) -> Expression -> Expression -> Maybe (Map.Map Int Int)bijection' look one two = fst <$> fst (matching look strict () one two)likened :: (Text -> Maybe Expression) -> Expression -> Expression -> Boollikened look one two = isJust (fst (matching look strict () one two))strict :: Expression -> Expression -> () -> (Maybe Bool, ())strict _ _ kept = (Nothing, kept)type Pairing = (Map.Map Int Int, Map.Map Int Int, Map.Map (Text, Text) ())matching :: forall state. (Text -> Maybe Expression) -> (Expression -> Expression -> state -> (Maybe Bool, state)) -> state -> Expression -> Expression -> (Maybe (Map.Map Int Int, Map.Map Int Int), state)matching look loose initial one two = case goExpr (Map.empty, Map.empty, Map.empty) one two initial of (found, final) -> ((\(forward, backward, _) -> (forward, backward)) <$> found, final) where goExpr :: Pairing -> Expression -> Expression -> state -> (Maybe Pairing, state) goExpr pairing left right kept = case loose left right kept of (Just True, kept') -> (Just pairing, kept') (Just False, kept') -> (Nothing, kept') (Nothing, kept') -> goStrict pairing left right kept' goStrict :: Pairing -> Expression -> Expression -> state -> (Maybe Pairing, state) goStrict pairing@(forward, backward, met) (ExMeta left) (ExMeta right) kept | Map.member (left, right) met = (Just pairing, kept) | Just left' <- look left , Just right' <- look right = goExpr (forward, backward, Map.insert (left, right) () met) left' right' kept goStrict pairing (ExMeta left) right kept | Just left' <- look left = goExpr pairing left' right kept goStrict pairing left (ExMeta right) kept | Just right' <- look right = goExpr pairing left right' kept goStrict pairing (ExFormation left) (ExFormation right) kept = goList goBinding pairing left right kept goStrict pairing (ExApplication left arg) (ExApplication right arg') kept = chained (goExpr pairing left right kept) (\next -> goArgument next arg arg') goStrict pairing (ExDispatch left attr) (ExDispatch right attr') kept | attr == attr' = goExpr pairing left right kept goStrict pairing (ExPhiMeet prefix idx left) (ExPhiMeet prefix' idx' right) kept | prefix == prefix' && idx == idx' = goExpr pairing left right kept goStrict pairing (ExPhiAgain prefix idx left) (ExPhiAgain prefix' idx' right) kept | prefix == prefix' && idx == idx' = goExpr pairing left right kept goStrict pairing left right kept = (same pairing left right, kept) goBinding :: Pairing -> Binding -> Binding -> state -> (Maybe Pairing, state) goBinding pairing (BiTau attr left) (BiTau attr' right) kept | attr == attr' = goExpr pairing left right kept goBinding pairing (BiLambda (FnSymbol left)) (BiLambda (FnSymbol right)) kept = (twinned pairing left right, kept) goBinding pairing left right kept = (same pairing left right, kept) goArgument :: Pairing -> Argument -> Argument -> state -> (Maybe Pairing, state) goArgument pairing (ArTau attr left) (ArTau attr' right) kept | attr == attr' = goExpr pairing left right kept goArgument pairing left right kept = (same pairing left right, kept) goList :: (Pairing -> item -> item -> state -> (Maybe Pairing, state)) -> Pairing -> [item] -> [item] -> state -> (Maybe Pairing, state) goList _ pairing [] [] kept = (Just pairing, kept) goList walk pairing (left : lefts) (right : rights) kept = chained (walk pairing left right kept) (\next -> goList walk next lefts rights) goList _ _ _ _ kept = (Nothing, kept) chained :: (Maybe Pairing, state) -> (Pairing -> state -> (Maybe Pairing, state)) -> (Maybe Pairing, state) chained (Just pairing, kept) next = next pairing kept chained (Nothing, kept) _ = (Nothing, kept) same :: (Eq item) => Pairing -> item -> item -> Maybe Pairing same pairing left right | left == right = Just pairing | otherwise = Nothing twinned :: Pairing -> Int -> Int -> Maybe Pairing twinned (forward, backward, met) left right = case (Map.lookup left forward, Map.lookup right backward) of (Nothing, Nothing) -> Just (Map.insert left right forward, Map.insert right left backward, met) (Just right', Just _) | right' == right -> Just (forward, backward, met) _ -> Nothingtype Searched = Map.Map (Int, Int) [(Expression, Expression, Bool)]type Search = Searched -> (Bool, Searched)within :: Expression -> Expression -> Boolwithin = within' (const Nothing)within' :: (Text -> Maybe Expression) -> Expression -> Expression -> Boolwithin' look before after = fst (within'' look Map.empty before after)within'' :: (Text -> Maybe Expression) -> Searched -> Expression -> Expression -> (Bool, Searched)within'' look start before after = coupled (opened before) (opened after) start where opened :: Expression -> Expression opened term = maybe term opened (through term) through :: Expression -> Maybe Expression through (ExMeta name) = look name through _ = Nothing embedded :: Expression -> Expression -> Search embedded inner' outer' searched = case recalled inner outer searched of Just found -> (found, searched) Nothing -> remembered inner outer (some [answered (general inner outer), coupled inner outer, some (map (embedded inner) (children outer))] searched) where inner :: Expression inner = opened inner' outer :: Expression outer = opened outer' recalled :: Expression -> Expression -> Searched -> Maybe Bool recalled inner outer searched = listToMaybe [found | (inner', outer', found) <- Map.findWithDefault [] (digests inner outer) searched, inner' == inner, outer' == outer] remembered :: Expression -> Expression -> (Bool, Searched) -> (Bool, Searched) remembered inner outer (found, searched) = (found, Map.insertWith (++) (digests inner outer) [(inner, outer, found)] searched) digests :: Expression -> Expression -> (Int, Int) digests inner outer = (hashExpression inner, hashExpression outer) general :: Expression -> Expression -> Bool general inner (ExFormation [BiLambda (FnSymbol _)]) = plain inner general _ _ = False plain :: Expression -> Bool plain (ExFormation bds) = all plainBinding bds plain (ExApplication expr (ArTau AtRho _)) = plain expr plain (ExApplication expr (ArTau _ arg)) = plain expr && plain arg plain (ExDispatch expr _) = plain expr plain (ExPhiMeet _ _ expr) = plain expr plain (ExPhiAgain _ _ expr) = plain expr plain _ = True plainBinding :: Binding -> Bool plainBinding (BiTau AtRho _) = True plainBinding (BiTau _ expr) = plain expr plainBinding (BiLambda (FnSymbol _)) = False plainBinding _ = True coupled :: Expression -> Expression -> Search coupled (ExFormation left) (ExFormation right) = every (answered (length left == length right) : zipWith goBinding left right) coupled (ExApplication left arg) (ExApplication right arg') = every [embedded left right, goArgument arg arg'] coupled (ExDispatch left attr) (ExDispatch right attr') = every [answered (attr == attr'), embedded left right] coupled (ExPhiMeet prefix idx left) (ExPhiMeet prefix' idx' right) = every [answered (prefix == prefix' && idx == idx'), embedded left right] coupled (ExPhiAgain prefix idx left) (ExPhiAgain prefix' idx' right) = every [answered (prefix == prefix' && idx == idx'), embedded left right] coupled (ExMeta left) (ExMeta right) | left == right = answered True coupled left@(ExMeta _) right | Just left' <- through left = coupled left' right coupled left right@(ExMeta _) | Just right' <- through right = coupled left right' coupled left right = answered (left == right) goBinding :: Binding -> Binding -> Search goBinding (BiTau attr left) (BiTau attr' right) = every [answered (attr == attr'), embedded left right] goBinding (BiLambda (FnSymbol _)) (BiLambda (FnSymbol _)) = answered True goBinding left right = answered (left == right) goArgument :: Argument -> Argument -> Search goArgument (ArTau attr left) (ArTau attr' right) = every [answered (attr == attr'), embedded left right] answered :: Bool -> Search answered = (,) every :: [Search] -> Search every [] searched = (True, searched) every (search : rest) searched = case search searched of (True, searched') -> every rest searched' failed -> failed some :: [Search] -> Search some [] searched = (False, searched) some (search : rest) searched = case search searched of (False, searched') -> some rest searched' found -> found children :: Expression -> [Expression] children (ExFormation bds) = [expr | BiTau attr expr <- bds, attr /= AtRho] children (ExApplication expr (ArTau _ arg)) = [expr, arg] children (ExDispatch expr _) = [expr] children (ExPhiMeet _ _ expr) = [expr] children (ExPhiAgain _ _ expr) = [expr] children _ = []symbols :: Expression -> [Int]symbols whole = case goExpr (IntMap.empty, IntSet.empty, []) whole of (_, _, found) -> reverse found where goExpr :: (IntMap.IntMap [Expression], IntSet.IntSet, [Int]) -> Expression -> (IntMap.IntMap [Expression], IntSet.IntSet, [Int]) goExpr walked@(seen, met, found) term | compound term && term `elem` IntMap.findWithDefault [] digest seen = walked | compound term = nested (IntMap.insertWith (++) digest [term] seen, met, found) term | otherwise = nested walked term where digest :: Int digest = hashExpression term compound :: Expression -> Bool compound (ExFormation _) = True compound (ExApplication _ _) = True compound (ExDispatch _ _) = True compound _ = False nested :: (IntMap.IntMap [Expression], IntSet.IntSet, [Int]) -> Expression -> (IntMap.IntMap [Expression], IntSet.IntSet, [Int]) nested walked (ExFormation bds) = List.foldl' goBinding walked bds nested walked (ExApplication expr arg) = goArgument (goExpr walked expr) arg nested walked (ExDispatch expr _) = goExpr walked expr nested walked (ExPhiMeet _ _ expr) = goExpr walked expr nested walked (ExPhiAgain _ _ expr) = goExpr walked expr nested walked _ = walked goBinding :: (IntMap.IntMap [Expression], IntSet.IntSet, [Int]) -> Binding -> (IntMap.IntMap [Expression], IntSet.IntSet, [Int]) goBinding walked (BiTau _ expr) = goExpr walked expr goBinding walked@(seen, met, found) (BiLambda (FnSymbol idx)) | IntSet.member idx met = walked | otherwise = (seen, IntSet.insert idx met, idx : found) goBinding walked _ = walked goArgument :: (IntMap.IntMap [Expression], IntSet.IntSet, [Int]) -> Argument -> (IntMap.IntMap [Expression], IntSet.IntSet, [Int]) goArgument walked (ArTau _ expr) = goExpr walked exprlifted :: Int -> Int -> Expression -> Expressionlifted floor' offset = goExpr where goExpr :: Expression -> Expression goExpr (ExFormation bds) = ExFormation (map goBinding bds) goExpr (ExApplication expr arg) = ExApplication (goExpr expr) (goArgument arg) goExpr (ExDispatch expr attr) = ExDispatch (goExpr expr) attr goExpr (ExPhiMeet prefix idx expr) = ExPhiMeet prefix idx (goExpr expr) goExpr (ExPhiAgain prefix idx expr) = ExPhiAgain prefix idx (goExpr expr) goExpr expr = expr goBinding :: Binding -> Binding goBinding (BiTau attr expr) = BiTau attr (goExpr expr) goBinding (BiLambda (FnSymbol idx)) | idx > floor' = BiLambda (FnSymbol (idx + offset)) goBinding bd = bd goArgument :: Argument -> Argument goArgument (ArTau attr expr) = ArTau attr (goExpr expr)denoted :: Expression -> Maybe Intdenoted = goExpr where goExpr :: Expression -> Maybe Int goExpr (ExFormation bds) = listToMaybe (concatMap goBinding bds) goExpr (ExApplication _ (ArTau AtPhi expr)) = goExpr expr goExpr (ExApplication expr _) = goExpr expr goExpr (ExPhiMeet _ _ expr) = goExpr expr goExpr (ExPhiAgain _ _ expr) = goExpr expr goExpr _ = Nothing goBinding :: Binding -> [Int] goBinding (BiLambda (FnSymbol idx)) = [idx] goBinding (BiTau AtPhi expr) = maybe [] pure (goExpr expr) goBinding _ = []countNodes :: Expression -> IntcountNodes term = case known term of Facts _ _ size _ _ -> sizetally :: Expression -> Inttally (ExFormation bds) = 1 + sum (map nodesInBinding bds) + length bds where nodesInBinding :: Binding -> Int nodesInBinding (BiTau _ expr) = countNodes expr + 2 nodesInBinding (BiMeta _) = 1 nodesInBinding (BiAny _) = 1 nodesInBinding _ = 3tally (ExApplication expr (ArTau _ expr')) = 4 + countNodes expr + countNodes expr'tally (ExDispatch expr' _) = 2 + countNodes expr'tally (ExPhiMeet _ _ expr) = countNodes exprtally (ExPhiAgain _ _ expr) = countNodes exprtally _ = 1inert :: Expression -> Boolinert term = case known term of Facts _ _ _ still _ -> stilldistinct :: Expression -> Booldistinct term = case known term of Facts _ _ _ _ unique -> uniqueunrepeated :: Expression -> Boolunrepeated (ExFormation bds) = isNothing (repeated bds)unrepeated _ = Truerepeated :: [Binding] -> Maybe Attributerepeated = go IntMap.empty where go :: IntMap.IntMap [Attribute] -> [Binding] -> Maybe Attribute go _ [] = Nothing go seen (bd : rest) = case attributeFromBinding bd of Just attr | attr `elem` IntMap.findWithDefault [] (key attr) seen -> Just attr | otherwise -> go (IntMap.insertWith (++) (key attr) [attr] seen) rest Nothing -> go seen rest key :: Attribute -> Int key (AtLabel label) = T.foldl' (\hash char -> (hash `xor` fromEnum char) * 1099511628211) 14695981039 label key (AtMeta meta) = T.length meta key _ = 0attributeFromBinding :: Binding -> Maybe AttributeattributeFromBinding (BiTau attr _) = Just attrattributeFromBinding (BiVoid attr) = Just attrattributeFromBinding (BiDelta _) = Just AtDeltaattributeFromBinding (BiLambda _) = Just AtLambdaattributeFromBinding (BiMeta _) = NothingattributeFromBinding (BiAny _) = Nothingcalm :: Expression -> Boolcalm = \case ExFormation bds -> settled False False bds ExDispatch expr attr -> inert expr && headless expr && plain attr ExApplication expr (ArTau attr arg) -> inert expr && headless expr && plain attr && inert arg ExXi -> True ExRoot -> True ExTermination -> True _ -> False where settled :: Bool -> Bool -> [Binding] -> Bool settled _ _ [] = True settled lambda delta (bd : rest) = quiet bd && case bd of BiLambda _ -> not delta && settled True delta rest BiDelta _ -> not lambda && settled lambda True rest _ -> settled lambda delta rest quiet :: Binding -> Bool quiet (BiTau attr expr) = plain attr && inert expr quiet (BiVoid attr) = plain attr quiet (BiDelta (BtMeta _)) = False quiet (BiDelta (BtAny _)) = False quiet (BiDelta _) = True quiet (BiLambda (Function _)) = True quiet (BiLambda (FnSymbol _)) = True quiet _ = False headless :: Expression -> Bool headless (ExFormation _) = False headless ExTermination = False headless _ = True plain :: Attribute -> Bool plain (AtMeta _) = False plain (AtAny _) = False plain _ = TruematchBaseObject :: Expression -> Maybe T.TextmatchBaseObject (ExDispatch ExRoot (AtLabel label)) = Just labelmatchBaseObject _ = Nothingpattern BaseObject :: T.Text -> Expressionpattern BaseObject label <- (matchBaseObject -> Just label) where BaseObject label = ExDispatch ExRoot (AtLabel label)matchDataObject :: Expression -> Maybe (T.Text, Bytes)matchDataObject (ExApplication outer arg) | Just inner <- asBytesArg arg = case (matchOuter outer, matchInner inner) of (Just label, Just bts) -> Just (label, bts) _ -> Nothing where asBytesArg :: Argument -> Maybe Expression asBytesArg (ArTau AtPhi inner) = Just inner asBytesArg (ArTau (AtLabel "as-bytes") inner) = Just inner asBytesArg _ = Nothing dataArg :: Argument -> Maybe Expression dataArg (ArTau AtPhi formation) = Just formation dataArg (ArTau (AtLabel "data") formation) = Just formation dataArg _ = Nothing matchOuter :: Expression -> Maybe T.Text matchOuter (BaseObject label) = Just label matchOuter (ExPhiAgain _ _ (BaseObject label)) = Just label matchOuter _ = Nothing matchInner :: Expression -> Maybe Bytes matchInner (ExPhiAgain _ _ inner') = matchInner inner' matchInner inner' = matchInner' inner' matchInner' :: Expression -> Maybe Bytes matchInner' (ExApplication bytes arg') | Just formation <- dataArg arg' = case (matchesBytes bytes, matchFormation formation) of (True, Just bts) -> Just bts _ -> Nothing matchInner' _ = Nothing matchesBytes :: Expression -> Bool matchesBytes (BaseObject "bytes") = True matchesBytes (ExPhiAgain _ _ (BaseObject "bytes")) = True matchesBytes _ = False matchFormation :: Expression -> Maybe Bytes matchFormation (ExFormation [BiDelta bts]) = Just bts matchFormation (ExPhiAgain _ _ (ExFormation [BiDelta bts])) = Just bts matchFormation _ = NothingmatchDataObject _ = Nothingpattern DataString :: Bytes -> Expressionpattern DataString bts = DataObject "string" btspattern DataNumber :: Bytes -> Expressionpattern DataNumber bts = DataObject "number" btspattern DataObject :: T.Text -> Bytes -> Expressionpattern DataObject label bts <- (matchDataObject -> Just (label, bts)) where DataObject label bts = ExApplication (BaseObject label) (ArTau AtPhi (dataBytes bts))dataBytes :: Bytes -> ExpressiondataBytes bts = ExApplication (BaseObject "bytes") (ArTau AtPhi (ExFormation [BiDelta bts]))