phino 0.0.166 → 0.0.167
raw patch · 42 files changed
+1556/−334 lines, 42 filesPVP: major bump suggested
API removals or changes: PVP suggests a major version bump
API changes (from Hackage documentation)
+ AST: akin'' :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Searched -> Expression -> Expression -> (Bool, Searched)
+ AST: deepness :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Expression -> Int
+ AST: reaches :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Int -> Expression -> Bool
+ AST: type Searched = Map (Int, Int) [(Expression, Expression, Bool)]
+ AST: within'' :: (Text -> Maybe Expression) -> Searched -> Expression -> Expression -> (Bool, Searched)
+ CLI.Parsers: optProfile :: Parser Bool
+ CLI.Parsers: sodgParser :: Parser Command
+ CLI.Runners: runSodg :: OptsSodg -> IO ()
+ CLI.Types: CmdSodg :: OptsSodg -> Command
+ CLI.Types: OptsSodg :: LogLevel -> Int -> IOFormat -> Maybe FilePath -> OptsSodg
+ CLI.Types: [_profile] :: OptsMorph -> Bool
+ CLI.Types: data OptsSodg
+ Canonizer: canonizeExpression :: Expression -> CanonState -> (Expression, CanonState)
+ Canonizer: emptyCanon :: CanonState
+ Canonizer: type CanonState = (Map Text Text, Int)
+ Deps: Profile :: Double -> IORef Double -> Profile
+ Deps: [_previous] :: Profile -> IORef Double
+ Deps: [_start] :: Profile -> Double
+ Deps: data Profile
+ Deps: profiling :: IO Profile
+ Deps: stamped :: Profile -> Int -> Int -> IO String
+ Sides: gauge :: Sides -> IO (Text -> Maybe Int)
+ Sodg: Application :: Int -> Int -> Text -> Int -> Command
+ Sodg: Delta :: Int -> Text -> Command
+ Sodg: Dispatch :: Int -> Int -> Text -> Command
+ Sodg: Formation :: Int -> [Text] -> Command
+ Sodg: Lambda :: Int -> Text -> Command
+ Sodg: Patterned :: Text -> Text -> SodgException
+ Sodg: Put :: Int -> Text -> Int -> Command
+ Sodg: Terminated :: Text -> SodgException
+ Sodg: Unbound :: Text -> SodgException
+ Sodg: commands :: Expression -> Either SodgException [Command]
+ Sodg: data Command
+ Sodg: data SodgException
+ Sodg: instance GHC.Classes.Eq Sodg.Command
+ Sodg: instance GHC.Exception.Type.Exception Sodg.SodgException
+ Sodg: instance GHC.Show.Show Sodg.Command
+ Sodg: instance GHC.Show.Show Sodg.SodgException
+ Sodg: printCommands :: [Command] -> String
+ Sodg: sodg :: Expression -> IO [Command]
+ Sodg: vertex :: Int -> String
- AST: akin' :: (Text -> Maybe Expression) -> Expression -> Expression -> Bool
+ AST: akin' :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Expression -> Expression -> Bool
- CLI.Helpers: saveStepFunc :: Maybe FilePath -> PrintContext -> [Expression] -> [Expression] -> IO SaveStepFunc
+ CLI.Helpers: saveStepFunc :: Maybe FilePath -> PrintContext -> [Expression] -> [Expression] -> Expression -> IO SaveStepFunc
- CLI.Helpers: withEvalFunc :: Maybe FilePath -> Maybe FilePath -> PrintContext -> (SaveEvalFunc -> IO a) -> IO a
+ CLI.Helpers: withEvalFunc :: Maybe FilePath -> Maybe FilePath -> Bool -> PrintContext -> (SaveEvalFunc -> IO a) -> IO a
- CLI.Helpers: withEvalFunc' :: Maybe FilePath -> Maybe FilePath -> PrintContext -> (SaveEvalFunc -> IO a) -> IO a
+ CLI.Helpers: withEvalFunc' :: Maybe FilePath -> Maybe FilePath -> Bool -> PrintContext -> (SaveEvalFunc -> IO a) -> IO a
- CLI.Types: OptsDataize :: LogLevel -> Int -> IOFormat -> Form -> IOFormat -> SugarType -> Bool -> LineFormat -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Bool -> Bool -> Maybe Acyclic -> Int -> Bool -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Maybe Int -> Maybe Int -> [String] -> [String] -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe FilePath -> Maybe FilePath -> Maybe FilePath -> Maybe Int -> Bool -> Maybe FilePath -> Maybe FilePath -> OptsDataize
+ CLI.Types: OptsDataize :: LogLevel -> Int -> IOFormat -> Form -> IOFormat -> SugarType -> Bool -> LineFormat -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Bool -> Bool -> Maybe Acyclic -> Int -> Bool -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Maybe Int -> Maybe Int -> [String] -> [String] -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe FilePath -> Maybe FilePath -> Maybe FilePath -> Bool -> Maybe Int -> Bool -> Maybe FilePath -> Maybe FilePath -> OptsDataize
- CLI.Types: OptsMorph :: LogLevel -> Int -> IOFormat -> Form -> IOFormat -> SugarType -> Bool -> LineFormat -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Bool -> Bool -> Maybe Acyclic -> Int -> Bool -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Maybe Int -> Maybe Int -> [String] -> [String] -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe FilePath -> Maybe FilePath -> Maybe FilePath -> Maybe Int -> Bool -> Maybe FilePath -> Maybe FilePath -> OptsMorph
+ CLI.Types: OptsMorph :: LogLevel -> Int -> IOFormat -> Form -> IOFormat -> SugarType -> Bool -> LineFormat -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Bool -> Bool -> Maybe Acyclic -> Int -> Bool -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Maybe Int -> Maybe Int -> [String] -> [String] -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe FilePath -> Maybe FilePath -> Maybe FilePath -> Bool -> Maybe Int -> Bool -> Maybe FilePath -> Maybe FilePath -> OptsMorph
- CLI.Types: [_inputFile] :: OptsMatch -> Maybe FilePath
+ CLI.Types: [_inputFile] :: OptsSodg -> Maybe FilePath
- CLI.Types: [_inputFormat] :: OptsMerge -> IOFormat
+ CLI.Types: [_inputFormat] :: OptsSodg -> IOFormat
- Deps: saveEval :: Handle -> IORef Protocol -> (Expression -> IO String) -> (Expression -> IO String) -> SaveEvalFunc
+ Deps: saveEval :: Handle -> IORef Protocol -> (Expression -> IO String) -> (Expression -> IO String) -> Maybe Profile -> SaveEvalFunc
- Morph: Memo :: IORef (Store (Int, Kept)) -> IORef (Map Firing (Expression, Answer)) -> IORef Int -> IORef Int -> Kin -> Memo
+ Morph: Memo :: IORef (Store (Int, Kept)) -> IORef (Map Firing (Expression, Answer)) -> IORef Int -> IORef Int -> Kin -> IORef Searched -> Memo
Files
- README.md +97/−82
- phino.cabal +5/−2
- src/AST.hs +110/−54
- src/CLI.hs +2/−0
- src/CLI/Helpers.hs +25/−12
- src/CLI/Parsers.hs +23/−0
- src/CLI/Runners.hs +16/−4
- src/CLI/Types.hs +10/−0
- src/Canonizer.hs +6/−3
- src/Deps.hs +40/−4
- src/Evaluate.hs +35/−23
- src/Morph.hs +42/−25
- src/Sides.hs +12/−6
- src/Sodg.hs +134/−0
- test-resources/evaluate-packs/answers-bottom-where-both-sides-dispatch-off-a-symbol.yaml +37/−0
- test-resources/evaluate-packs/ends-a-side-at-a-dispatch-off-a-symbol.yaml +42/−0
- test-resources/evaluate-packs/ends-a-side-at-a-stall-of-an-opaque-replayed-by-the-memo.yaml +50/−0
- test-resources/evaluate-packs/ends-a-side-at-an-evaluate-line-stuck-on-a-symbol.yaml +50/−0
- test-resources/evaluate-packs/ends-a-side-read-off-a-path-at-a-dispatch-off-a-symbol.yaml +34/−0
- test-resources/evaluate-packs/gets-stuck-on-a-dispatch-off-a-symbol-outside-a-join.yaml +32/−0
- test-resources/sodg-packs/bottom-argument.yaml +5/−0
- test-resources/sodg-packs/bottom.yaml +5/−0
- test-resources/sodg-packs/empty-bytes-and-symbol.yaml +10/−0
- test-resources/sodg-packs/empty.yaml +6/−0
- test-resources/sodg-packs/meta-attribute.yaml +5/−0
- test-resources/sodg-packs/meta-binding.yaml +5/−0
- test-resources/sodg-packs/meta-bytes.yaml +5/−0
- test-resources/sodg-packs/meta.yaml +5/−0
- test-resources/sodg-packs/nested-xi.yaml +13/−0
- test-resources/sodg-packs/not-formation.yaml +8/−0
- test-resources/sodg-packs/number.yaml +13/−0
- test-resources/sodg-packs/order.yaml +13/−0
- test-resources/sodg-packs/root-rho-delta-lambda.yaml +26/−0
- test-resources/sodg-packs/spelled-rho.yaml +8/−0
- test-resources/sodg-packs/two-arguments.yaml +11/−0
- test-resources/sodg-packs/unbound-xi.yaml +5/−0
- test/ASTSpec.hs +71/−0
- test/CLISpec.hs +65/−0
- test/CSTSpec.hs +296/−116
- test/Fixtures.hs +3/−3
- test/SidesSpec.hs +28/−0
- test/SodgSpec.hs +148/−0
README.md view
@@ -34,7 +34,7 @@ ```bash cabal update-cabal install --overwrite-policy=always phino-0.0.165+cabal install --overwrite-policy=always phino-0.0.166 phino --version ``` @@ -59,7 +59,7 @@ for the runner and puts it on the `PATH`: ```yaml-- uses: objectionary/phino@0.0.165+- uses: objectionary/phino@0.0.166 with: version-file: phino-version.txt - run: phino --version@@ -295,6 +295,8 @@ as a tree in XML, for a program to read. The `--minutes` option writes the same tree as indented text, and one run may take both.+With `--profile`, every record of the minutes ends with the milliseconds+it took, the time since the start, and the memory in use. Here, `L_down` answers with a call of its own object over a fresh symbol, so without `--acyclic` the run would go on until `--max-steps` runs out: @@ -517,6 +519,19 @@ d >> 68-65-6C-6C-6F ``` +## SODG++The `sodg` command prints the commands that build the graph of a+𝜑-expression, one per line, in the language of+[sodg-maven-plugin](https://github.com/objectionary/sodg-maven-plugin):++```bash+$ echo '⟦ x ↦ ξ.y, y ↦ ∅ ⟧' | phino sodg+F c0 x y+D c1 c0 y+P c0 x c1+```+ ## Compile By default, `phino` reads its rules from YAML and interprets them at every@@ -734,119 +749,119 @@ === parse/phi === warmup: 3 iterations batches: 10 x 1- total: 1624060.124 μs- avg: 162406.012 μs- min: 144277.371 μs- max: 194535.221 μs- std dev: 21570.423 μs+ total: 2413980.968 μs+ avg: 241398.097 μs+ min: 215225.227 μs+ max: 284695.902 μs+ std dev: 25724.434 μs === parse/xmir === warmup: 3 iterations batches: 10 x 1- total: 7009151.691 μs- avg: 700915.169 μs- min: 651934.228 μs- max: 762411.055 μs- std dev: 44745.118 μs+ total: 10044170.261 μs+ avg: 1004417.026 μs+ min: 928746.607 μs+ max: 1079348.074 μs+ std dev: 50756.236 μs === rewrite/normalize === warmup: 3 iterations batches: 10 x 1- total: 12.959 μs- avg: 1.296 μs- min: 1.166 μs- max: 1.418 μs- std dev: 0.091 μs+ total: 20.328 μs+ avg: 2.033 μs+ min: 1.723 μs+ max: 2.685 μs+ std dev: 0.289 μs === print/sweet/multiline === warmup: 3 iterations batches: 10 x 1- total: 4217518.009 μs- avg: 421751.801 μs- min: 403493.618 μs- max: 457424.859 μs- std dev: 16536.568 μs+ total: 1911999.027 μs+ avg: 191199.903 μs+ min: 185908.584 μs+ max: 202990.068 μs+ std dev: 4905.518 μs === print/sweet/flat === warmup: 3 iterations batches: 10 x 1- total: 545770.341 μs- avg: 54577.034 μs- min: 49166.277 μs- max: 63498.089 μs- std dev: 5148.406 μs+ total: 1145909.419 μs+ avg: 114590.942 μs+ min: 92613.667 μs+ max: 139357.482 μs+ std dev: 15308.656 μs === print/salty/multiline === warmup: 3 iterations batches: 10 x 1- total: 13219408.124 μs- avg: 1321940.812 μs- min: 1272904.132 μs- max: 1364186.958 μs- std dev: 31154.946 μs+ total: 7468225.700 μs+ avg: 746822.570 μs+ min: 735697.009 μs+ max: 774034.524 μs+ std dev: 10278.722 μs === morph/symbolic/demo/e1 === warmup: 3 iterations- batches: 10 x 12- total: 11083.017 μs- avg: 92.358 μs- min: 90.596 μs- max: 97.264 μs- std dev: 1.942 μs+ batches: 10 x 9+ total: 13798.063 μs+ avg: 153.312 μs+ min: 149.894 μs+ max: 163.169 μs+ std dev: 3.598 μs === morph/symbolic/demo/e2 === warmup: 3 iterations- batches: 10 x 183- total: 169227.669 μs- avg: 92.474 μs- min: 92.145 μs- max: 93.183 μs- std dev: 0.311 μs+ batches: 10 x 116+ total: 177830.095 μs+ avg: 153.302 μs+ min: 152.510 μs+ max: 155.166 μs+ std dev: 0.755 μs === morph/symbolic/demo/e3 === warmup: 3 iterations- batches: 10 x 185- total: 173845.799 μs- avg: 93.971 μs- min: 93.445 μs- max: 94.542 μs- std dev: 0.317 μs+ batches: 10 x 109+ total: 172419.898 μs+ avg: 158.183 μs+ min: 156.401 μs+ max: 160.218 μs+ std dev: 1.203 μs === morph/symbolic/demo/e4 === warmup: 3 iterations- batches: 10 x 189- total: 176636.558 μs- avg: 93.458 μs- min: 92.301 μs- max: 97.186 μs- std dev: 1.478 μs+ batches: 10 x 114+ total: 179087.429 μs+ avg: 157.094 μs+ min: 155.294 μs+ max: 159.724 μs+ std dev: 1.170 μs === morph/symbolic/demo/e5 === warmup: 3 iterations- batches: 10 x 186- total: 176437.359 μs- avg: 94.859 μs- min: 94.521 μs- max: 95.173 μs- std dev: 0.205 μs+ batches: 10 x 96+ total: 169758.902 μs+ avg: 176.832 μs+ min: 175.759 μs+ max: 177.918 μs+ std dev: 0.603 μs === morph/symbolic/native/e5 === warmup: 3 iterations- batches: 10 x 6- total: 80211.099 μs- avg: 1336.852 μs- min: 1211.536 μs- max: 1384.878 μs- std dev: 55.380 μs+ batches: 10 x 5+ total: 54422.069 μs+ avg: 1088.441 μs+ min: 1031.613 μs+ max: 1174.642 μs+ std dev: 53.929 μs === morph/symbolic/accum/0 === warmup: 3 iterations- batches: 10 x 107- total: 83668.975 μs- avg: 78.195 μs- min: 77.496 μs- max: 78.759 μs- std dev: 0.356 μs+ batches: 10 x 68+ total: 87262.677 μs+ avg: 128.327 μs+ min: 126.014 μs+ max: 130.276 μs+ std dev: 1.292 μs === morph/symbolic/accum/400 === warmup: 3 iterations- batches: 10 x 77- total: 70478.596 μs- avg: 91.531 μs- min: 90.598 μs- max: 92.469 μs- std dev: 0.645 μs+ batches: 10 x 48+ total: 70884.786 μs+ avg: 147.677 μs+ min: 144.986 μs+ max: 152.842 μs+ std dev: 1.934 μs ``` The results were calculated in [this GHA job][benchmark-gha]-on 2026-11-16 at 09:21,+on 2026-11-19 at 15:32, on Linux with 4 CPUs. <!-- benchmark_end -->@@ -889,4 +904,4 @@ [jna]: https://github.com/java-native-access/jna [jna-native]: https://github.com/java-native-access/jna/blob/master/src/com/sun/jna/Native.java [jeo]: https://github.com/objectionary/jeo-maven-plugin-[benchmark-gha]: https://github.com/objectionary/phino/actions/runs/43835713699+[benchmark-gha]: https://github.com/objectionary/phino/actions/runs/44555174198
phino.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: phino-version: 0.0.166+version: 0.0.167 license: MIT synopsis: Command-Line Manipulator of 𝜑-Calculus Expressions description: Please see the README on GitHub at <https://github.com/objectionary/phino#readme>@@ -12,7 +12,7 @@ copyright: 2025 Objectionary.com category: Language, Code Analysis build-type: Simple-tested-with: GHC ==9.6.7 || ==9.8.4 || ==9.10.3+tested-with: GHC ==9.6.7 || ==9.8.4 || ==9.10.3 || ==9.14.1 extra-source-files: resources/normalize/*.yaml resources/morphing/*.yaml resources/dataization/*.yaml resources/contextualization/*.yaml benchmark/demo.phi benchmark/atoms.yaml benchmark/accum.phi benchmark/accum.yaml test-resources/**/*.yaml test-resources/**/*.phi extra-doc-files: README.md @@ -90,6 +90,7 @@ Rewriter Rule Sides+ Sodg Slots Sugar Tau@@ -203,6 +204,8 @@ ReplacerSpec RewriterSpec RuleSpec+ SidesSpec+ SodgSpec Spec SugarSpec TauSpec
src/AST.hs view
@@ -3,6 +3,7 @@ {-# LANGUAGE MagicHash #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} -- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com@@ -10,7 +11,7 @@ module AST ( Slot (..)- , Expression (ExFormation, ExXi, ExRoot, ExTermination, ExApplication, ExDispatch, ExMeta, ExAny, ExPhiMeet, ExPhiAgain, ExBytes)+ , Expression (ExFormation, ExXi, ExRoot, ExTermination, ExApplication, ExDispatch, ExMeta, ExAny, ExPhiMeet, ExPhiAgain, ExBytes, BaseObject, DataString, DataNumber, DataObject) , Argument (..) , Alpha (..) , Binding (..)@@ -30,22 +31,23 @@ , bijection' , akin , akin'+ , akin''+ , deepness+ , reaches , boxed , intact , suffixed , within , within'+ , within''+ , Searched , isName , symbols , lifted , denoted , countNodes , matchBaseObject- , pattern BaseObject , matchDataObject- , pattern DataString- , pattern DataNumber- , pattern DataObject , dataBytes ) where@@ -54,7 +56,7 @@ import qualified Data.IntMap.Strict as IntMap import qualified Data.List as List import qualified Data.Map.Strict as Map-import Data.Maybe (isJust, isNothing, listToMaybe)+import Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe) import Data.Text (Text) import qualified Data.Text as T import GHC.Exts (isTrue#, reallyUnsafePtrEquality#)@@ -342,18 +344,59 @@ alike = alike' (const Nothing) alike' :: (Text -> Maybe Expression) -> Expression -> Expression -> Bool-alike' look = likened look (\_ _ -> False)+alike' = likened akin :: Expression -> Expression -> Bool-akin = akin' (const Nothing)+akin = akin' (const Nothing) (const Nothing) -akin' :: (Text -> Maybe Expression) -> Expression -> Expression -> Bool-akin' look = likened look grown+akin' :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Expression -> Expression -> Bool+akin' 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 -> Bool- grown before@(ExFormation left) after@(ExFormation right) = boxed left && boxed right && within' look before after- grown _ _ = False+ 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 _ = False +deepness :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Expression -> Int+deepness 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 (ExApplication callee (ArAlpha _ 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)) 1++reaches :: (Text -> Maybe Expression) -> (Text -> Maybe Int) -> Int -> Expression -> Bool+reaches 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 (ExApplication callee (ArAlpha _ 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 _ _ = False+ boxed :: [Binding] -> Bool boxed bds = any phi bds && not (any lambda bds) && not (any delta bds) where@@ -371,53 +414,63 @@ bijection = bijection' (const Nothing) bijection' :: (Text -> Maybe Expression) -> Expression -> Expression -> Maybe (Map.Map Int Int)-bijection' look one two = fst <$> matching look (\_ _ -> False) one two+bijection' look one two = fst <$> fst (matching look strict () one two) -likened :: (Text -> Maybe Expression) -> (Expression -> Expression -> Bool) -> Expression -> Expression -> Bool-likened look loose one two = isJust (matching look loose one two)+likened :: (Text -> Maybe Expression) -> Expression -> Expression -> Bool+likened 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 :: (Text -> Maybe Expression) -> (Expression -> Expression -> Bool) -> Expression -> Expression -> Maybe (Map.Map Int Int, Map.Map Int Int)-matching look loose one two = (\(forward, backward, _) -> (forward, backward)) <$> goExpr (Map.empty, Map.empty, Map.empty) one two+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 -> Maybe Pairing- goExpr pairing left right- | loose left right = Just pairing- goExpr pairing@(forward, backward, met) (ExMeta left) (ExMeta right)- | Map.member (left, right) met = Just pairing+ 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'- goExpr pairing (ExMeta left) right- | Just left' <- look left = goExpr pairing left' right- goExpr pairing left (ExMeta right)- | Just right' <- look right = goExpr pairing left right'- goExpr pairing (ExFormation left) (ExFormation right) = goList goBinding pairing left right- goExpr pairing (ExApplication left arg) (ExApplication right arg') = goExpr pairing left right >>= \next -> goArgument next arg arg'- goExpr pairing (ExDispatch left attr) (ExDispatch right attr')- | attr == attr' = goExpr pairing left right- goExpr pairing (ExPhiMeet prefix idx left) (ExPhiMeet prefix' idx' right)- | prefix == prefix' && idx == idx' = goExpr pairing left right- goExpr pairing (ExPhiAgain prefix idx left) (ExPhiAgain prefix' idx' right)- | prefix == prefix' && idx == idx' = goExpr pairing left right- goExpr pairing left right = same pairing left right- goBinding :: Pairing -> Binding -> Binding -> Maybe Pairing- goBinding pairing (BiTau attr left) (BiTau attr' right)- | attr == attr' = goExpr pairing left right- goBinding pairing (BiLambda (FnSymbol left)) (BiLambda (FnSymbol right)) = twinned pairing left right- goBinding pairing left right = same pairing left right- goArgument :: Pairing -> Argument -> Argument -> Maybe Pairing- goArgument pairing (ArTau attr left) (ArTau attr' right)- | attr == attr' = goExpr pairing left right- goArgument pairing (ArAlpha alpha left) (ArAlpha alpha' right)- | alpha == alpha' = goExpr pairing left right- goArgument pairing left right = same pairing left right- goList :: (pairing -> item -> item -> Maybe pairing) -> pairing -> [item] -> [item] -> Maybe pairing- goList _ pairing [] [] = Just pairing- goList walk pairing (left : lefts) (right : rights) = walk pairing left right >>= \next -> goList walk next lefts rights- goList _ _ _ _ = Nothing- same :: (Eq item) => pairing -> item -> item -> Maybe pairing+ 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 (ArAlpha alpha left) (ArAlpha alpha' right) kept+ | alpha == alpha' = 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@@ -435,7 +488,10 @@ within = within' (const Nothing) within' :: (Text -> Maybe Expression) -> Expression -> Expression -> Bool-within' look before after = fst (coupled (opened before) (opened after) Map.empty)+within' 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)
src/CLI.hs view
@@ -54,6 +54,7 @@ CmdExplain opts -> runExplain opts CmdMerge opts -> runMerge opts CmdMatch opts -> runMatch opts+ CmdSodg opts -> runSodg opts CmdCompile opts -> runCompile opts where prefixFirstLine :: String -> String -> String@@ -77,6 +78,7 @@ CmdExplain OptsExplain{_logLevel, _logLines} -> (_logLevel, _logLines) CmdMerge OptsMerge{_logLevel, _logLines} -> (_logLevel, _logLines) CmdMatch OptsMatch{_logLevel, _logLines} -> (_logLevel, _logLines)+ CmdSodg OptsSodg{_logLevel, _logLines} -> (_logLevel, _logLines) CmdCompile OptsCompile{_logLevel, _logLines} -> (_logLevel, _logLines) in setLogConfig level lns checkPin :: Maybe Pin -> IO ()
src/CLI/Helpers.hs view
@@ -12,7 +12,7 @@ import CLI.Types import CLI.Validators (invalidCLIArguments) import CST (EXPRESSION)-import Canonizer (canonize, canonizeExpr, lambdaNames)+import Canonizer (CanonState, canonize, canonizeExpr, canonizeExpression, emptyCanon, lambdaNames) import Compiled (compiled) import Control.Exception import Control.Monad (mfilter, when, zipWithM, (>=>))@@ -26,9 +26,10 @@ import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time (getZonedTime)+import Data.Tuple (swap) import Data.Version (showVersion) import qualified Data.Yaml as Yaml-import Deps (Evaluation (EvHeader, EvRun), Header (Header), Judgment, SaveEvalFunc, SaveStepFunc, World (World), dontSaveEval, emptyNesting, emptyProgress, emptyProtocol, endEval, endEvalXml, progressed, resited, saveEval, saveEvalXml, saveStep)+import Deps (Evaluation (EvHeader, EvRun), Header (Header), Judgment, SaveEvalFunc, SaveStepFunc, World (World), dontSaveEval, emptyNesting, emptyProgress, emptyProtocol, endEval, endEvalXml, profiling, progressed, resited, saveEval, saveEvalXml, saveStep) import Encoding import Engine (Engine, fresh, yaml) import Files (ensuredFile, overwrite)@@ -38,7 +39,7 @@ import LaTeX (LatexContext (LatexContext), defaultMeetLength, defaultMeetPopularity, expressionToLaTeX, rewrittensToLatex) import Lambdas (Lambdas, emptyLambdas, readLambdas, sized, taken) import Lining (LineFormat (SINGLELINE))-import Locator (locatedExpression, withLocatedExpression)+import Locator (LocatorException, locatedExpression, withLocatedExpression) import Logger import Morph (ReduceContext (..), insideUniverse) import Parser (Form, parseExpressionThrows, parseExpressionThrows')@@ -79,25 +80,36 @@ isFile <- doesFileExist path when isFile (removeFile path) -saveStepFunc :: Maybe FilePath -> PrintContext -> [Expression] -> [Expression] -> IO SaveStepFunc-saveStepFunc stepsDir ctx@PrintCtx{..} included excluded = do+saveStepFunc :: Maybe FilePath -> PrintContext -> [Expression] -> [Expression] -> Expression -> IO SaveStepFunc+saveStepFunc stepsDir ctx@PrintCtx{..} included excluded start = do clearedStepsDir stepsDir counter <- newIORef (0 :: Int)+ names <- newIORef =<< seeded let ioToExt :: String ioToExt | _outputFormat == LATEX = "tex" | otherwise = show _outputFormat+ render :: Expression -> IO String render expr = do- shown <- F.exclude' expr excluded >>= (`F.include'` included)- printAnswer ctx shown+ visible <- shown expr+ if _canonize+ then atomicModifyIORef' names (swap . canonizeExpression visible) >>= printCanonized ctx visible+ else printAnswer ctx visible save :: SaveStepFunc save expr = do step <- atomicModifyIORef' counter (\value -> (value + 1, value + 1)) saveStep stepsDir ioToExt render step expr pure save+ where+ shown :: Expression -> IO Expression+ shown expr = F.exclude' expr excluded >>= (`F.include'` included)+ seeded :: IO CanonState+ seeded+ | _canonize && isJust stepsDir = (snd . (`canonizeExpression` emptyCanon) <$> shown start) `catch` (\(_ :: LocatorException) -> pure emptyCanon)+ | otherwise = pure emptyCanon -withEvalFunc :: forall a. Maybe FilePath -> Maybe FilePath -> PrintContext -> (SaveEvalFunc -> IO a) -> IO a-withEvalFunc xml text ctx action = withEvalFunc' xml text ctx (tracked >=> action)+withEvalFunc :: forall a. Maybe FilePath -> Maybe FilePath -> Bool -> PrintContext -> (SaveEvalFunc -> IO a) -> IO a+withEvalFunc xml text profile ctx action = withEvalFunc' xml text profile ctx (tracked >=> action) where tracked :: SaveEvalFunc -> IO SaveEvalFunc tracked record = do@@ -108,8 +120,8 @@ pure (progressed cursor 5 (flattened ctx) record) else pure record -withEvalFunc' :: forall a. Maybe FilePath -> Maybe FilePath -> PrintContext -> (SaveEvalFunc -> IO a) -> IO a-withEvalFunc' xml text ctx action =+withEvalFunc' :: forall a. Maybe FilePath -> Maybe FilePath -> Bool -> PrintContext -> (SaveEvalFunc -> IO a) -> IO a+withEvalFunc' xml text profile ctx action = markedUp xml (\marked -> plain text (\lined -> action (\record -> marked record >> lined record))) where markedUp :: Maybe FilePath -> (SaveEvalFunc -> IO a) -> IO a@@ -126,8 +138,9 @@ logDebug (printf "The option '--minutes' is specified, every firing will be recorded in '%s' as text" file) cursor <- newIORef emptyProtocol began <- getMonotonicTime+ watch <- if profile then Just <$> profiling else pure Nothing bracket (opened file) (\protocol -> endEval protocol cursor began `finally` hClose protocol) $ \protocol ->- go (saveEval protocol cursor (flattened ctx) (salted ctx))+ go (saveEval protocol cursor (flattened ctx) (salted ctx) watch) opened :: FilePath -> IO Handle opened file = do createDirectoryIfMissing True (takeDirectory file)
src/CLI/Parsers.hs view
@@ -336,6 +336,16 @@ ) ) +optProfile :: Parser Bool+optProfile =+ switch+ ( long "profile"+ <> help+ "Close every record of the --minutes file with a comment holding the milliseconds since the record \+ \above and since the start, the depth of the record, the firings so far, the live heap and the peak memory, \+ \so a slow or memory-hungry spot shows next to the lines that caused it"+ )+ optAbridged :: Parser (Maybe Int) optAbridged = optional@@ -481,6 +491,7 @@ <*> optStepsDir <*> optProtocol <*> optMinutes+ <*> optProfile <*> optAbridged <*> optAbridgedData <*> optSymbolic@@ -535,6 +546,7 @@ <*> optStepsDir <*> optProtocol <*> optMinutes+ <*> optProfile <*> optAbridged <*> optAbridgedData <*> optSymbolic@@ -621,6 +633,16 @@ <*> optSeed ) +sodgParser :: Parser Command+sodgParser =+ CmdSodg+ <$> ( OptsSodg+ <$> optLogLevel+ <*> optLogLines+ <*> optInputFormat+ <*> argInputFile+ )+ compileParser :: Parser Command compileParser = CmdCompile@@ -640,6 +662,7 @@ <> command "explain" (info explainParser (progDesc "Explain rules in LaTeX format")) <> command "merge" (info mergeParser (progDesc "Merge 𝜑-expressions into single one by merging their top level formations")) <> command "match" (info matchParser (progDesc "Match 𝜑-expression against provided pattern and build matched substitutions"))+ <> command "sodg" (info sodgParser (progDesc "Print the SODG commands that build the graph of the 𝜑-expression")) <> command "compile" (info compileParser (progDesc "Compile the rules into a Haskell module a build with the flag 'compiled' links in")) )
src/CLI/Runners.hs view
@@ -37,13 +37,14 @@ import Merge (merge) import Metas (Metas (..)) import Morph-import Parser (parseExpressionThrows)+import Parser (Form (POLYFORM), parseExpressionThrows) import qualified Printer as P import qualified Random as R import Rewriter import Rule (RuleContext (..), matchExpressionWithRule) import Sides (sides) import Slots (anonymous)+import Sodg (printCommands, sodg) import System.Directory (canonicalizePath, doesFileExist, getModificationTime) import System.Exit (exitSuccess) import System.FilePath (takeDirectory, (</>))@@ -78,7 +79,7 @@ printCtx = toPrintCtx xmirCtx foc exclude = (`F.exclude` excluded) include = (`F.include` included)- save <- saveStepFunc _stepsDir printCtx included excluded+ save <- saveStepFunc _stepsDir printCtx included excluded expr let steps = map ((if _cheat then cheating else id) . stepOf linked) rules (rewrittens, exceeded) <- rewrite expr steps (RewriteContext loc _maxDepth _maxCycles _depthSensitive Nothing (building linked) linked._normal (every steps) _must _breakpoint save dontSaveMade) when (isJust _breakpoint && NE.length rewrittens == 1) (clearedStepsDir _stepsDir)@@ -181,7 +182,7 @@ let printCtx = toPrintCtx atoms foc exclude = (`F.exclude` excluded) include = (`F.include` included)- save <- saveStepFunc _stepsDir printCtx included excluded+ save <- saveStepFunc _stepsDir printCtx included excluded expr tally <- tallied _maxFirings minted <- newIORef 0 named <- sides@@ -193,6 +194,7 @@ withEvalFunc _protocol _minutes+ _profile printCtx ( \record -> do let ctx = ReduceContext loc loc Nothing _maxDepth _maxCycles _maxNodes _maxMemory (Steps _maxSteps 0) tally minted named deadline memo 1 (Just (1, Dataization, loc)) _depthSensitive _shuffle _partial _acyclic _maxLoops Dataization [] Map.empty (Just facts) lambdas [] False Nothing (building linked) reduction evaluation save record linked@@ -224,6 +226,7 @@ validateXmirOptions _outputFormat [(_omitListing, "omit-listing"), (_omitComments, "omit-comments")] _focus when (length _show > 1) (invalidCLIArguments "The option --show can be used only once") when (isJust _abridged && isNothing _protocol && isNothing _minutes) (invalidCLIArguments "The option --abridged requires --protocol or --minutes, since only the protocol is abridged")+ when (_profile && isNothing _minutes) (invalidCLIArguments "The option --profile requires --minutes, since only the minutes are profiled") when (_abridgedData && isNothing _abridged) (invalidCLIArguments "The option --abridged-data requires --abridged, since only an abridged protocol cuts its data") when (_maxLoops > 0 && isNothing _acyclic) (invalidCLIArguments "The option --max-loops requires --acyclic, since only --acyclic cuts a loop") when (isJust _inside) $ do@@ -273,7 +276,7 @@ let printCtx = toPrintCtx atoms foc exclude = (`F.exclude` excluded) include = (`F.include` included)- save <- saveStepFunc _stepsDir printCtx included excluded+ save <- saveStepFunc _stepsDir printCtx included excluded expr tally <- tallied _maxFirings minted <- newIORef 0 named <- sides@@ -285,6 +288,7 @@ withEvalFunc _protocol _minutes+ _profile printCtx ( \record -> do let ctx = ReduceContext loc loc Nothing _maxDepth _maxCycles _maxNodes _maxMemory (Steps _maxSteps 0) tally minted named deadline memo 1 (Just (1, Morphing, loc)) _depthSensitive _shuffle _partial _acyclic _maxLoops Morphing [] Map.empty (Just facts) lambdas [] False Nothing (building linked) reduction evaluation save record linked@@ -312,6 +316,7 @@ validateXmirOptions _outputFormat [(_omitListing, "omit-listing"), (_omitComments, "omit-comments")] _focus when (length _show > 1) (invalidCLIArguments "The option --show can be used only once") when (isJust _abridged && isNothing _protocol && isNothing _minutes) (invalidCLIArguments "The option --abridged requires --protocol or --minutes, since only the protocol is abridged")+ when (_profile && isNothing _minutes) (invalidCLIArguments "The option --profile requires --minutes, since only the minutes are profiled") when (_abridgedData && isNothing _abridged) (invalidCLIArguments "The option --abridged-data requires --abridged, since only an abridged protocol cuts its data") when (_maxLoops > 0 && isNothing _acyclic) (invalidCLIArguments "The option --max-loops requires --acyclic, since only --acyclic cuts a loop") when (isJust _inside) $ do@@ -434,6 +439,13 @@ unboundMetas ptn condition = filter (`notElem` namedMetas ptn) (namedMetas condition) namedMetas :: (Metas a) => a -> [T.Text] namedMetas term = filter ((> 1) . T.length) (metas term)++runSodg :: OptsSodg -> IO ()+runSodg OptsSodg{..} = do+ input <- readInput _inputFile+ expr <- parseInput input _inputFormat POLYFORM+ graph <- sodg expr+ putStr (printCommands graph) runCompile :: OptsCompile -> IO () runCompile OptsCompile{..} = do
src/CLI/Types.hs view
@@ -74,6 +74,7 @@ | CmdExplain OptsExplain | CmdMerge OptsMerge | CmdMatch OptsMatch+ | CmdSodg OptsSodg | CmdCompile OptsCompile data Pin = PinVersion String | PinFile FilePath@@ -136,6 +137,7 @@ , _stepsDir :: Maybe FilePath , _protocol :: Maybe FilePath , _minutes :: Maybe FilePath+ , _profile :: Bool , _abridged :: Maybe Int , _abridgedData :: Bool , _symbolic :: Maybe FilePath@@ -187,6 +189,7 @@ , _stepsDir :: Maybe FilePath , _protocol :: Maybe FilePath , _minutes :: Maybe FilePath+ , _profile :: Bool , _abridged :: Maybe Int , _abridgedData :: Bool , _symbolic :: Maybe FilePath@@ -275,6 +278,13 @@ , _when :: Maybe String , _inputFile :: Maybe FilePath , _seed :: Int+ }++data OptsSodg = OptsSodg+ { _logLevel :: LogLevel+ , _logLines :: Int+ , _inputFormat :: IOFormat+ , _inputFile :: Maybe FilePath } data OptsCompile = OptsCompile
src/Canonizer.hs view
@@ -1,7 +1,7 @@ -- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com -- SPDX-License-Identifier: MIT -module Canonizer (canonize, canonizeExpr, lambdaNames) where+module Canonizer (CanonState, canonize, canonizeExpr, canonizeExpression, emptyCanon, lambdaNames) where import AST import qualified Data.Map as Map@@ -10,6 +10,9 @@ type CanonState = (Map.Map T.Text T.Text, Int) +emptyCanon :: CanonState+emptyCanon = (Map.empty, 1)+ canonizeBindings :: [Binding] -> CanonState -> ([Binding], CanonState) canonizeBindings [] st = ([], st) canonizeBindings ((BiLambda (Function name)) : rest) st@@ -75,10 +78,10 @@ lambdaNames _ = [] canonizeExpr :: Expression -> Expression-canonizeExpr expr = fst (canonizeExpression expr (Map.empty, 1))+canonizeExpr expr = fst (canonizeExpression expr emptyCanon) canonize :: [Rewritten] -> [Rewritten]-canonize rewrittens = go rewrittens (Map.empty, 1)+canonize rewrittens = go rewrittens emptyCanon where go :: [Rewritten] -> CanonState -> [Rewritten] go [] _ = []
src/Deps.hs view
@@ -16,15 +16,17 @@ import Data.Bifunctor (bimap, first, second) import Data.Char (isAlphaNum) import Data.Either (lefts, rights)-import Data.IORef (IORef, readIORef, writeIORef)+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef) import Data.List (intercalate, sortOn) import qualified Data.Map.Strict as Map import Data.Maybe (catMaybes, fromMaybe, isJust, listToMaybe, mapMaybe, maybeToList) import qualified Data.Text as T import Data.Time (ZonedTime, defaultTimeLocale, formatTime)+import Data.Word (Word64) import Files (overwrite) import Forks (Refusal (..), Side (..)) import GHC.Clock (getMonotonicTime)+import GHC.Stats (GCDetails (gcdetails_live_bytes), RTSStats (gc, max_mem_in_use_bytes), getRTSStats, getRTSStatsEnabled) import Logger (logDebug, logInfo) import Matcher import Printer (printAlpha, printAttribute, printBinding, printFunction)@@ -348,11 +350,18 @@ statement :: Expression -> Expression -> Named [(Expression, (T.Text, T.Text))] -> Maybe (String, String) statement object source facts = bimap T.unpack T.unpack <$> (namedLookup object facts >>= lookup source) -saveEval :: Handle -> IORef Protocol -> (Expression -> IO String) -> (Expression -> IO String) -> SaveEvalFunc-saveEval handle cursor printed printed' report = do+saveEval :: Handle -> IORef Protocol -> (Expression -> IO String) -> (Expression -> IO String) -> Maybe Profile -> SaveEvalFunc+saveEval handle cursor printed printed' profile report = do made <- atomicModify cursor (fmap (first (forgotten report) . headed) . written (tier report) report . beside (tier report) report . outer (tier report))- mapM_ saved made+ mapM_ saved =<< maybe pure timed profile made where+ timed :: Profile -> [String] -> IO [String]+ timed _ [] = pure []+ timed _ made | EvHeader{} <- report = pure made+ timed watch made = do+ protocol <- readIORef cursor+ stamp <- stamped watch (tier report) protocol._fired+ pure (init made ++ [printf "%s # %s" (last made) stamp]) forgotten :: Evaluation -> Protocol -> Protocol forgotten EvBound{} protocol = protocol forgotten EvDelta{} protocol = protocol@@ -702,6 +711,33 @@ let (index, counted) = numbered protocol taken <- printed (abbreviatedInside protocol._made term) pure (counted{_made = namedInsert term (alias (opener protocol) index) counted._made}, Just (indented at (printf "%s %s·%d := %s" word (labelled protocol answer) index taken)))++data Profile = Profile+ { _start :: Double+ , _previous :: IORef Double+ }++profiling :: IO Profile+profiling = do+ now <- getMonotonicTime+ Profile now <$> newIORef now++stamped :: Profile -> Int -> Int -> IO String+stamped watch depth firings = do+ now <- getMonotonicTime+ before <- atomicModifyIORef' watch._previous (now,)+ printf "+%d ms, at %d ms, depth %d, firings %d%s" (milliseconds before now) (milliseconds watch._start now) depth firings <$> memory+ where+ memory :: IO String+ memory = do+ enabled <- getRTSStatsEnabled+ if enabled+ then do+ stats <- getRTSStats+ pure (printf ", heap %s, peak %s" (megabytes (gcdetails_live_bytes (gc stats))) (megabytes (max_mem_in_use_bytes stats)))+ else pure (mempty :: String)+ megabytes :: Word64 -> String+ megabytes bytes = printf "%.1f MB" (fromIntegral bytes / 1048576 :: Double) endEval :: Handle -> IORef Protocol -> Double -> IO () endEval handle cursor began = do
src/Evaluate.hs view
@@ -91,8 +91,8 @@ let ctx = caller{_nesting = caller._nesting + 1, _raising = entry._terminators} outcome <- try $ raised ctx $ do (bound, dataized, conditions) <- foldM (down ctx) (substEmpty, state, []) entry._dataized- (bound', morphed, normals) <- foldM (through ctx "morph" (still pure)) (bound, dataized, []) entry._morphed- (bound'', undressed, normals') <- foldM (through ctx "undress" (peeled ctx)) (bound', morphed, normals) entry._undressed+ (bound', morphed, normals) <- foldM (through ctx (joining entry._ending) "morph" (still pure)) (bound, dataized, []) entry._morphed+ (bound'', undressed, normals') <- foldM (through ctx (joining entry._ending) "undress" (peeled ctx)) (bound', morphed, normals) entry._undressed firing <- Firing func (reverse conditions) . (reverse normals' ++) <$> sides entry._ending known <- remembered caller._memo firing (answer, state') <- maybe (worked ctx entry firing bound'' undressed) (\(first, answer) -> (answer, undressed) <$ recited ctx._nesting first answer) known@@ -148,13 +148,13 @@ sourced _ = Nothing line :: ReduceContext -> Ending -> (Subst, State) -> Line -> IO (Subst, State) line ctx _ held (Dataized meta source) = lowered ctx held meta source- line ctx _ held (Morphed meta source) = reduced ctx held meta source+ line ctx ending held (Morphed meta source) = reduced ctx (joining ending) held meta source line ctx ending held (Evaluated meta source) = evaluated ctx ending held meta source- line ctx _ (bound, state') (Deferred meta source) = (,state') <$> deferred ctx state' meta source bound- line ctx _ held (Stayed meta source) = reshaped ctx "stay" (still (pure . stayed)) meta source held- line ctx _ held (Rewritten meta source rules) = reshaped ctx "rewrite" (still (awaited ctx . rewritten (RuleContext ctx._buildTerm ctx._universe ctx._engine._normal False) rules)) meta source held- line ctx _ held (Symbolized meta source) = reshaped ctx "symbolize" (still (masked ctx)) meta source held- line ctx _ held (Undressed meta source) = reshaped ctx "undress" (peeled ctx) meta source held+ line ctx ending (bound, state') (Deferred meta source) = (,state') <$> deferred ctx (joining ending) state' meta source bound+ line ctx ending held (Stayed meta source) = reshaped ctx (joining ending) "stay" (still (pure . stayed)) meta source held+ line ctx ending held (Rewritten meta source rules) = reshaped ctx (joining ending) "rewrite" (still (awaited ctx . rewritten (RuleContext ctx._buildTerm ctx._universe ctx._engine._normal False) rules)) meta source held+ line ctx ending held (Symbolized meta source) = reshaped ctx (joining ending) "symbolize" (still (masked ctx)) meta source held+ line ctx ending held (Undressed meta source) = reshaped ctx (joining ending) "undress" (peeled ctx) meta source held line ctx _ held (Cast one first two second) = casting ctx held (one, first) (two, second) shown :: Int -> Answer -> IO () shown depth (Answer built normal) = do@@ -226,11 +226,13 @@ ctx._saveEval (EvData ctx._nesting meta._spelling origin datum) bound' <- bind meta (MvBytes bytes) bound pure (datum, bound', state'')- through :: ReduceContext -> T.Text -> (State -> Expression -> IO (Expression, State)) -> (Subst, State, [Expression]) -> (Meta, Expression) -> IO (Subst, State, [Expression])- through ctx block change (bound, state', normals) (meta, term) = do+ through :: ReduceContext -> Bool -> T.Text -> (State -> Expression -> IO (Expression, State)) -> (Subst, State, [Expression]) -> (Meta, Expression) -> IO (Subst, State, [Expression])+ through ctx side block change (bound, state', normals) (meta, term) = do placed <- operand term- (normal, state'') <- morphing univ ctx{_site = term} placed state'- (shaped, state''') <- change state'' normal+ ((normal, shaped), state''') <- blanked side ((ExTermination, ExTermination), state') $ do+ (normal, state'') <- morphing univ ctx{_site = term} placed state'+ (shaped, state''') <- change state'' normal+ pure ((normal, shaped), state''') ctx._saveEval ( if shaped == normal then EvTerm ctx._nesting meta._spelling Morphing term normal@@ -238,17 +240,17 @@ ) bound' <- bind meta (MvExpression shaped) bound pure (bound', state''', shaped : normals)- reduced :: ReduceContext -> (Subst, State) -> Meta -> Meta -> IO (Subst, State)- reduced ctx (bound, state') meta source = do+ reduced :: ReduceContext -> Bool -> (Subst, State) -> Meta -> Meta -> IO (Subst, State)+ reduced ctx side (bound, state') meta source = do term <- buildExpressionThrows (ExMeta source._name) bound- (normal, state'') <- morphing univ ctx{_site = ExMeta source._name} term state'+ (normal, state'') <- blanked side (ExTermination, state') (morphing univ ctx{_site = ExMeta source._name} term state') ctx._saveEval (EvTerm ctx._nesting meta._spelling Morphing (ExMeta source._name) normal) bound' <- bind meta (MvExpression normal) bound pure (bound', state'')- reshaped :: ReduceContext -> T.Text -> (State -> Expression -> IO (Expression, State)) -> Meta -> Meta -> (Subst, State) -> IO (Subst, State)- reshaped ctx block change meta source (bound, state') = do+ reshaped :: ReduceContext -> Bool -> T.Text -> (State -> Expression -> IO (Expression, State)) -> Meta -> Meta -> (Subst, State) -> IO (Subst, State)+ reshaped ctx side block change meta source (bound, state') = do kept <- buildExpressionThrows (ExMeta source._name) bound- (term, state'') <- change state' kept+ (term, state'') <- blanked side (ExTermination, state') (change state' kept) ctx._saveEval ( if term == kept then EvBound ctx._nesting (ExMeta meta._name) term@@ -296,7 +298,7 @@ evaluated :: ReduceContext -> Ending -> (Subst, State) -> Meta -> Meta -> IO (Subst, State) evaluated ctx ending (bound, state') meta source = do term <- buildExpressionThrows (ExMeta source._name) bound- (answer, state'') <- kindled ctx ending (ExMeta source._name) state' term+ (answer, state'') <- blanked (joining ending) (ExTermination, state') (kindled ctx ending (ExMeta source._name) state' term) ctx._saveEval ( if answer == term then EvBound ctx._nesting (ExMeta meta._name) term@@ -323,10 +325,10 @@ named :: Attribute -> Binding -> Bool named attr (BiTau attr' _) = attr == attr' named _ _ = False- deferred :: ReduceContext -> State -> Meta -> Meta -> Subst -> IO Subst- deferred ctx state' meta source bound = do+ deferred :: ReduceContext -> Bool -> State -> Meta -> Meta -> Subst -> IO Subst+ deferred ctx side state' meta source bound = do term <- buildExpressionThrows (ExMeta source._name) bound- answer <- postponing ctx state' (ExMeta source._name) term >>= maybe (kept term) pure+ answer <- blanked side ExTermination (postponing ctx state' (ExMeta source._name) term >>= maybe (kept term) pure) bind meta (MvExpression answer) bound where kept :: Expression -> IO Expression@@ -458,7 +460,17 @@ walked term = Just term reached :: ReduceContext -> Subst -> Expression -> State -> IO (Expression, State) reached _ bound (ExMeta name) state' = (,state') <$> buildExpressionThrows (ExMeta name) bound- reached ctx _ side state' = (\placed -> morphing univ ctx{_site = side} placed state') =<< operand side+ reached ctx _ side state' = (\placed -> blanked True (ExTermination, state') (morphing univ ctx{_site = side} placed state')) =<< operand side+ joining :: Ending -> Bool+ joining Joining{} = True+ joining _ = False+ blanked :: Bool -> result -> IO result -> IO result+ blanked True fallback work = catch work (\failure -> if opaqued failure then pure fallback else throwIO failure)+ blanked False _ work = work+ opaqued :: ReduceException -> Bool+ opaqued (Stuck name) = "𝜎" `T.isPrefixOf` name+ opaqued (StuckAt name _ _) = "𝜎" `T.isPrefixOf` name+ opaqued _ = False mint :: Subst -> (Slot, Function) -> IO Subst mint bound (slot, fresh) = case combine (substSlot slot (MvFunction fresh)) bound of Just bound' -> pure bound'
src/Morph.hs view
@@ -42,7 +42,7 @@ import Random (shuffle) import Rewriter (RewriteContext (RewriteContext), Rewritten, Seen, rewrite, seenInsert) import Rule (RuleContext (RuleContext), xiFree)-import Sides (Sides, minted, named, opened, resolver, spelled)+import Sides (Sides, gauge, minted, named, opened, resolver, spelled) import System.Timeout (timeout) import Text.Printf (printf) import Yaml (ExtraArgument (..))@@ -71,7 +71,7 @@ , _until :: Double } -data Memo = Memo (IORef (Store (Int, Kept))) (IORef (Map.Map Firing (Expression, Answer))) (IORef Int) (IORef Int) Kin+data Memo = Memo (IORef (Store (Int, Kept))) (IORef (Map.Map Firing (Expression, Answer))) (IORef Int) (IORef Int) Kin (IORef Searched) data Kin = Kin (IORef Spots) (IORef (Map.Map Int [Kindred])) (IORef (Map.Map Int Firing)) @@ -201,7 +201,7 @@ where starve :: Maybe Memo -> IO () starve Nothing = pure ()- starve (Just (Memo _ _ _ exhausted _)) = modifyIORef' exhausted (+ 1)+ starve (Just (Memo _ _ _ exhausted _ _)) = modifyIORef' exhausted (+ 1) measured :: ReduceContext -> Expression -> IO () measured ctx term = do@@ -258,12 +258,12 @@ maybe (expired ctx cap) pure =<< timeout (ceiling (max 0 (due - now) * 1000000)) action memoized :: Maybe Acyclic -> IO (Maybe Memo)-memoized (Just Plausible) = Just <$> (Memo <$> newIORef Map.empty <*> newIORef Map.empty <*> newIORef 0 <*> newIORef 0 <*> (Kin <$> newIORef (Spots Map.empty Map.empty) <*> newIORef Map.empty <*> newIORef Map.empty))+memoized (Just Plausible) = Just <$> (Memo <$> newIORef Map.empty <*> newIORef Map.empty <*> newIORef 0 <*> newIORef 0 <*> (Kin <$> newIORef (Spots Map.empty Map.empty) <*> newIORef Map.empty <*> newIORef Map.empty) <*> newIORef Map.empty) memoized _ = pure Nothing recalled :: Maybe Memo -> Expression -> Int -> IO (Maybe Kept) recalled Nothing _ _ = pure Nothing-recalled (Just (Memo store _ answers _ _)) form spent = do+recalled (Just (Memo store _ answers _ _ _)) form spent = do kept <- readIORef store count <- readIORef answers let live = [known | (term, (stamp, known)) <- Map.findWithDefault [] (hashExpression form) kept, term == form, current count stamp known]@@ -278,29 +278,29 @@ counted :: Maybe Memo -> IO Int counted Nothing = pure 0-counted (Just (Memo _ _ answers _ _)) = readIORef answers+counted (Just (Memo _ _ answers _ _ _)) = readIORef answers starved :: Maybe Memo -> IO Int starved Nothing = pure 0-starved (Just (Memo _ _ _ exhausted _)) = readIORef exhausted+starved (Just (Memo _ _ _ exhausted _ _)) = readIORef exhausted retained :: Maybe Memo -> Expression -> Int -> Kept -> IO () retained Nothing _ _ _ = pure ()-retained (Just (Memo store _ _ _ _)) form stamp kept =+retained (Just (Memo store _ _ _ _ _)) form stamp kept = modifyIORef' store (Map.insertWith (++) (hashExpression form) [(form, (stamp, kept))]) remembered :: Maybe Memo -> Firing -> IO (Maybe (Expression, Answer)) remembered Nothing _ = pure Nothing-remembered (Just (Memo _ firings _ _ _)) firing = Map.lookup firing <$> readIORef firings+remembered (Just (Memo _ firings _ _ _ _)) firing = Map.lookup firing <$> readIORef firings remember :: Maybe Memo -> Firing -> Expression -> Answer -> IO () remember Nothing _ _ _ = pure ()-remember (Just (Memo _ firings answers _ _)) firing form answer = do+remember (Just (Memo _ firings answers _ _ _)) firing form answer = do modifyIORef' firings (Map.insert firing (form, answer)) modifyIORef' answers (+ 1) placed :: Maybe Memo -> Expression -> Int -> IO ()-placed (Just (Memo _ _ _ _ (Kin places _ _))) term idx+placed (Just (Memo _ _ _ _ (Kin places _ _) _)) term idx | not (bare term) = modifyIORef' places (\spots -> List.foldl' spot spots (List.nub [term, stayed term])) where spot :: Spots -> Expression -> Spots@@ -352,14 +352,14 @@ goArgument cache arg@(ArAlpha alpha expr) = first (intact expr arg (ArAlpha alpha)) <$> goExpr cache expr kindle :: Sides -> Maybe Memo -> Expression -> Firing -> Answer -> IO ()-kindle store (Just (Memo _ _ _ _ (Kin places likes _))) form firing answer = do+kindle store (Just (Memo _ _ _ _ (Kin places likes _) _)) form firing answer = do spots <- readIORef places key <- fst <$> abstracted store spots form modifyIORef' likes (Map.insertWith (++) (hashShape key) [Kindred key form firing answer]) kindle _ _ _ _ _ = pure () minting :: Maybe Memo -> Firing -> Answer -> IO ()-minting (Just (Memo _ _ _ _ (Kin _ _ minters))) firing@(Firing _ operands normals) answer =+minting (Just (Memo _ _ _ _ (Kin _ _ minters) _)) firing@(Firing _ operands normals) answer = modifyIORef' minters (\known -> List.foldl' (\held idx -> Map.insertWith (\_ old -> old) idx firing held) known [idx | idx <- answered answer, idx `notElem` inputs]) where inputs :: [Int]@@ -372,7 +372,7 @@ answered Raised = [] kindred :: ReduceContext -> Expression -> IO (Maybe (Kindred, Map.Map Int Int, [(Int, Expression)]))-kindred ctx@ReduceContext{_memo = Just (Memo _ _ _ _ (Kin places likes _))} form = do+kindred ctx@ReduceContext{_memo = Just (Memo _ _ _ _ (Kin places likes _) _)} form = do spots <- readIORef places known <- readIORef likes (key, posed) <- abstracted ctx._sides spots form@@ -382,7 +382,7 @@ kindred _ _ = pure Nothing adopted :: ReduceContext -> (Kindred, Map.Map Int Int, [(Int, Expression)]) -> Expression -> IO Answer-adopted ctx@ReduceContext{_memo = Just (Memo _ _ _ _ (Kin places _ _))} (Kindred key form firing answer, pairing, posed) target = do+adopted ctx@ReduceContext{_memo = Just (Memo _ _ _ _ (Kin places _ _) _)} (Kindred key form firing answer, pairing, posed) target = do table <- newIORef pairing visiting <- newIORef Set.empty Spots known _ <- readIORef places@@ -426,10 +426,10 @@ reanswered (Joined normal) = Joined <$> renamedTerm ctx renaming normal reanswered Raised = pure Raised held :: Maybe Memo -> IO (Map.Map Int Firing)- held (Just (Memo _ _ _ _ (Kin _ _ minters))) = readIORef minters+ held (Just (Memo _ _ _ _ (Kin _ _ minters) _)) = readIORef minters held Nothing = pure Map.empty minted' :: Maybe Memo -> Firing -> [Int] -> IO ()- minted' (Just (Memo _ _ _ _ (Kin _ _ minters))) firing' fresh = modifyIORef' minters (\known -> List.foldl' (\kept idx -> Map.insert idx firing' kept) known fresh)+ minted' (Just (Memo _ _ _ _ (Kin _ _ minters) _)) firing' fresh = modifyIORef' minters (\known -> List.foldl' (\kept idx -> Map.insert idx firing' kept) known fresh) minted' Nothing _ _ = pure () refired :: ReduceContext -> Renaming -> Firing -> IO Firing@@ -480,7 +480,7 @@ unknown :: IO Int unknown = do minter <- case ctx._memo of- Just (Memo _ _ _ _ (Kin _ _ minters)) -> Map.lookup idx <$> readIORef minters+ Just (Memo _ _ _ _ (Kin _ _ minters) _) -> Map.lookup idx <$> readIORef minters Nothing -> pure Nothing seen <- readIORef visiting case minter of@@ -756,14 +756,31 @@ repeats :: Acyclic -> Expression -> ReduceContext -> IO [Expression] repeats mode form ctx = do look <- resolver ctx._sides- let hits = take (succ ctx._maxLoops) (filter (repeated look mode) (Map.findWithDefault [] (digest mode form) ctx._entered))- awaited ctx (evaluate (length hits `seq` hits))+ depth <- gauge ctx._sides+ start <- maybe (pure Map.empty) readIORef (searching ctx._memo)+ (hits, kept) <- awaited ctx (evaluate (forced (goHits look depth start (succ ctx._maxLoops) (Map.findWithDefault [] (digest mode form) ctx._entered))))+ mapM_ (\ref -> writeIORef ref (bounded kept)) (searching ctx._memo)+ pure hits where- repeated :: (T.Text -> Maybe Expression) -> Acyclic -> Expression -> Bool- repeated look Proven before = alike' look form before- repeated look Plausible before- | atomic form = akin' look before form- | otherwise = within' look before form+ goHits :: (T.Text -> Maybe Expression) -> (T.Text -> Maybe Int) -> Searched -> Int -> [Expression] -> ([Expression], Searched)+ goHits _ _ kept 0 _ = ([], kept)+ goHits _ _ kept _ [] = ([], kept)+ goHits look depth kept wanted (before : rest) = case repeated look depth mode before kept of+ (True, kept') -> first (before :) (goHits look depth kept' (pred wanted) rest)+ (False, kept') -> goHits look depth kept' wanted rest+ forced :: ([Expression], Searched) -> ([Expression], Searched)+ forced result@(hits, kept) = length hits `seq` kept `seq` result+ bounded :: Searched -> Searched+ bounded kept+ | Map.size kept > 1000000 = Map.empty+ | otherwise = kept+ searching :: Maybe Memo -> Maybe (IORef Searched)+ searching = fmap (\(Memo _ _ _ _ _ searched) -> searched)+ repeated :: (T.Text -> Maybe Expression) -> (T.Text -> Maybe Int) -> Acyclic -> Expression -> Searched -> (Bool, Searched)+ repeated look _ Proven before kept = (alike' look form before, kept)+ repeated look depth Plausible before kept+ | atomic form = akin'' look depth kept before form+ | otherwise = within'' look kept before form atomic :: Expression -> Bool atomic (ExFormation bds) = any isLambda bds atomic _ = False
src/Sides.hs view
@@ -3,7 +3,7 @@ -- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com -- SPDX-License-Identifier: MIT -module Sides (Sides, minted, opened, named, resolver, sides, spelled) where+module Sides (Sides, gauge, minted, opened, named, resolver, sides, spelled) where import AST import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef)@@ -19,12 +19,13 @@ , _names :: !(IntMap.IntMap [(Expression, Text)]) , _count :: !Int , _spelt :: !(Set.Set Text)+ , _depths :: !(Map.Map Text Int) } newtype Sides = Sides (IORef Store) sides :: IO Sides-sides = Sides <$> newIORef (Store Map.empty IntMap.empty 0 Set.empty)+sides = Sides <$> newIORef (Store Map.empty IntMap.empty 0 Set.empty Map.empty) named :: Sides -> Expression -> IO Expression named store term = fst <$> given False store term@@ -39,15 +40,15 @@ digest :: Int digest = hashExpression term found :: Store -> (Store, (Expression, Bool))- found known@(Store terms names count kept) = case lookup term (IntMap.findWithDefault [] digest names) of+ found known@(Store terms names count kept depths) = case lookup term (IntMap.findWithDefault [] digest names) of Just name -> (known, (ExMeta name, False)) Nothing -> let name = T.pack ("n·" ++ show (succ count))- in (Store (Map.insert name term terms) (IntMap.insertWith (++) digest [(term, name)] names) (succ count) (if spelt then Set.insert name kept else kept), (ExMeta name, True))+ in (Store (Map.insert name term terms) (IntMap.insertWith (++) digest [(term, name)] names) (succ count) (if spelt then Set.insert name kept else kept) (Map.insert name (deepness (`Map.lookup` terms) (`Map.lookup` depths) term) depths), (ExMeta name, True)) spelled :: Sides -> Expression -> IO Expression spelled (Sides store) whole = do- Store terms _ _ kept <- readIORef store+ Store terms _ _ kept _ <- readIORef store cache <- newIORef Map.empty let goExpr :: Expression -> IO Expression goExpr term@(ExMeta name)@@ -81,5 +82,10 @@ resolver :: Sides -> IO (Text -> Maybe Expression) resolver (Sides store) = do- Store terms _ _ _ <- readIORef store+ Store terms _ _ _ _ <- readIORef store pure (`Map.lookup` terms)++gauge :: Sides -> IO (Text -> Maybe Int)+gauge (Sides store) = do+ Store _ _ _ _ depths <- readIORef store+ pure (`Map.lookup` depths)
+ src/Sodg.hs view
@@ -0,0 +1,134 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TupleSections #-}++-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+-- SPDX-License-Identifier: MIT++module Sodg+ ( Command (..)+ , SodgException (..)+ , commands+ , sodg+ , printCommands+ , vertex+ )+where++import AST+import Control.Exception (Exception, throwIO)+import Control.Monad (foldM)+import Data.Text (Text)+import qualified Data.Text as T+import Printer (printExpression)++data Command+ = Formation Int [Text]+ | Dispatch Int Int Text+ | Application Int Int Text Int+ | Put Int Text Int+ | Delta Int Text+ | Lambda Int Text+ deriving (Eq, Show)++data SodgException+ = Terminated Text+ | Patterned Text Text+ | Unbound Text+ deriving (Exception)++instance Show SodgException where+ show (Terminated place) =+ T.unpack ("The attribute " <> place <> " is ⊥, which no SODG command makes")+ show (Patterned place what) =+ T.unpack ("The term at " <> place <> " holds " <> what <> ", which only a pattern of a rule may hold, not a program")+ show (Unbound place) =+ T.unpack ("The ξ at " <> place <> " has no formation around it")++type Walk = (Int, [Command])++commands :: Expression -> Either SodgException [Command]+commands expr = reverse . snd <$> top expr+ where+ top :: Expression -> Either SodgException Walk+ top formation@(ExFormation _) = snd <$> go Nothing "Φ" formation (0, [])+ top other = snd <$> go Nothing "Φ" other (1, [Formation 0 []])+ go :: Maybe Int -> Text -> Expression -> Walk -> Either SodgException (Int, Walk)+ go _ place (ExFormation bds) (next, done) = do+ names <- concat <$> traverse (listed place) bds+ walked <- foldM (binding next place) (next + 1, Formation next names : done) bds+ pure (next, walked)+ go (Just around) _ ExXi walk = Right (around, walk)+ go Nothing place ExXi _ = Left (Unbound place)+ go _ _ ExRoot walk = Right (0, walk)+ go _ place ExTermination _ = Left (Terminated place)+ go around place (ExDispatch base attr) walk = do+ name <- attribute place attr+ (from, (next, done)) <- go around place base walk+ pure (next, (next + 1, Dispatch next from name : done))+ go around place (ExApplication proto arg) walk = do+ (name, value) <- argument place arg+ (from, walked) <- go around place proto walk+ (kid, (next, done)) <- go around (place <> "." <> name) value walked+ pure (next, (next + 1, Application next from name kid : done))+ go _ place pattern _ = patterned place pattern+ listed :: Text -> Binding -> Either SodgException [Text]+ listed place = \case+ BiTau attr _ -> pure <$> attribute place attr+ BiVoid attr -> pure <$> attribute place attr+ BiDelta _ -> Right []+ BiLambda _ -> Right []+ other -> patterned place (ExFormation [other])+ binding :: Int -> Text -> Walk -> Binding -> Either SodgException Walk+ binding self place walk = \case+ BiTau attr value -> do+ name <- attribute place attr+ (kid, (next, done)) <- go (Just self) (place <> "." <> name) value walk+ pure (next, Put self name kid : done)+ BiVoid _ -> Right walk+ BiDelta bts -> (\data' -> fmap (Delta self data' :) walk) <$> bytes place bts+ BiLambda fn -> (\name -> fmap (Lambda self name :) walk) <$> function place fn+ _ -> Right walk+ attribute :: Text -> Attribute -> Either SodgException Text+ attribute place = \case+ AtLabel label -> Right label+ AtPhi -> Right "φ"+ AtRho -> Right "ρ"+ other -> patterned place (ExDispatch ExXi other)+ argument :: Text -> Argument -> Either SodgException (Text, Expression)+ argument place = \case+ ArTau attr value -> (,value) <$> attribute place attr+ ArAlpha (Alpha idx) value -> Right ("α" <> T.pack (show idx), value)+ other -> patterned place (ExApplication ExXi other)+ bytes :: Text -> Bytes -> Either SodgException Text+ bytes place = \case+ BtEmpty -> Right "--"+ BtOne byte -> Right (T.pack byte <> "-")+ BtMany many -> Right (T.intercalate "-" (map T.pack many))+ other -> patterned place (ExFormation [BiDelta other])+ patterned :: Text -> Expression -> Either SodgException result+ patterned place pattern = Left (Patterned place (T.pack (printExpression pattern)))+ function :: Text -> Function -> Either SodgException Text+ function place = \case+ Function name -> Right name+ FnSymbol idx -> Right ("𝜎" <> T.pack (show idx))+ other -> patterned place (ExFormation [BiLambda other])++sodg :: Expression -> IO [Command]+sodg = either throwIO pure . commands++vertex :: Int -> String+vertex idx = 'c' : show idx++printCommands :: [Command] -> String+printCommands = concatMap ((++ "\n") . unwords . spelled)+ where+ spelled :: Command -> [String]+ spelled = \case+ Formation self names -> "F" : vertex self : map T.unpack names+ Dispatch self base attr -> ["D", vertex self, vertex base, T.unpack attr]+ Application self proto attr arg -> ["A", vertex self, vertex proto, T.unpack attr, vertex arg]+ Put self attr kid -> ["P", vertex self, T.unpack attr, vertex kid]+ Delta self data' -> ["Δ", vertex self, T.unpack data']+ Lambda self name -> ["λ", vertex self, T.unpack name]
+ test-resources/evaluate-packs/answers-bottom-where-both-sides-dispatch-off-a-symbol.yaml view
@@ -0,0 +1,37 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+# yamllint disable rule:line-length+# Both sides dispatch off a bare symbol, so both are 'opaque' and both end as+# ⊥ (#2427). Two sides that are the same join, and the fork answers ⊥.+symbolic: |+ - λ: L_fork+ dataize:+ 𝛿1: $.on🌵+ morph:+ 𝑛1: $.left🌵+ 𝑛2: $.right🌵+ join:+ on: 𝛿1+ left: 𝑛1+ right: 𝑛2+ otherwise: L_fork+location: 'Q.e1'+input: '⟦ e1 ↦ ⟦ λ ⤍ L_fork, on🌵 ↦ ⟦ Δ ⤍ 00- ⟧, left🌵 ↦ ⟦ λ ⤍ 𝜎1 ⟧.p, right🌵 ↦ ⟦ λ ⤍ 𝜎1 ⟧.q ⟧.φ ⟧'+result: '⊥'+protocol: |+ 𝕄(Φ.e1):+ 𝔼(L_fork):+ 𝔻(ξ.on🌵):+ 𝛿·1·1 := 00-+ 𝛿1·1 := 𝛿·1·1 # 𝔻(ξ.on🌵)+ 𝕄(ξ.left🌵):+ opaque 𝜎1 # 𝕄(𝜎1:λ.p)+ 𝑛1·1 := ⊥ # 𝕄(ξ.left🌵)+ 𝕄(ξ.right🌵):+ opaque 𝜎1 # 𝕄(𝜎1:λ.q)+ 𝑛2·1 := ⊥ # 𝕄(ξ.right🌵)+ 𝑛·1·1 := ⊥+ evaluated 𝑛·1·2 := ⊥ # ⟦ λ ⤍ L_fork, on🌵 ↦ 00-:Δ, left🌵 ↦ 𝜎1:λ.p, right🌵 ↦ 𝜎1:λ.q ⟧+ normalized 𝑛·0·1 := ⊥ # ⊥.φ+ morphed 𝑛·0·2 := ⊥
+ test-resources/evaluate-packs/ends-a-side-at-a-dispatch-off-a-symbol.yaml view
@@ -0,0 +1,42 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+# yamllint disable rule:line-length+# The right side dispatches 'q' off a bare symbol, which nothing answers, so+# its morph is 'opaque'. Before #2427 that got the whole fork stuck and threw+# away the left side. Now the opaque ends that side alone, as ⊥ does: the side+# is ⊥ and the join answers the left side under the condition, writing a+# 'guarded' line.+symbolic: |+ - λ: L_fork+ dataize:+ 𝛿1: $.on🌵+ morph:+ 𝑛1: $.left🌵+ 𝑛2: $.right🌵+ join:+ on: 𝛿1+ left: 𝑛1+ right: 𝑛2+ otherwise: L_fork+location: 'Q.e1'+input: '⟦ k ↦ ⟦ q ↦ ⟦⟧ ⟧, e1 ↦ ⟦ λ ⤍ L_fork, on🌵 ↦ ⟦ Δ ⤍ 00- ⟧, left🌵 ↦ ⟦ φ ↦ Φ.k ⟧, right🌵 ↦ ⟦ λ ⤍ 𝜎1 ⟧.q ⟧.φ ⟧'+result: '⟦⟧:q'+protocol: |+ 𝕄(Φ.e1):+ 𝔼(L_fork):+ 𝔻(ξ.on🌵):+ 𝛿·1·1 := 00-+ 𝛿1·1 := 𝛿·1·1 # 𝔻(ξ.on🌵)+ 𝕄(ξ.left🌵):+ morphed 𝑛·1·1 := Φ.k:φ+ 𝑛1·1 := 𝑛·1·1 # 𝕄(ξ.left🌵)+ 𝕄(ξ.right🌵):+ opaque 𝜎1 # 𝕄(𝜎1:λ.q)+ 𝑛2·1 := ⊥ # 𝕄(ξ.right🌵)+ guarded 𝛿1·1 ? 𝑛1·1 : 𝑛2·1 # where 𝑛2·1 is ⊥+ 𝑛·1·2 := 𝑛·1·1+ evaluated 𝑛·1·3 := 𝑛·1·2 # ⟦ λ ⤍ L_fork, on🌵 ↦ 00-:Δ, left🌵 ↦ 𝑛·1·2, right🌵 ↦ 𝜎1:λ.q ⟧+ normalized 𝑛·0·1 := Φ.k # 𝑛·1·3.φ+ normalized 𝑛·0·2 := ⟦⟧:q # Φ.k+ morphed 𝑛·0·3 := 𝑛·0·2
+ test-resources/evaluate-packs/ends-a-side-at-a-stall-of-an-opaque-replayed-by-the-memo.yaml view
@@ -0,0 +1,50 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+# yamllint disable rule:line-length+# Both sides fire the same copy of 'L_id', whose operand dispatches off a+# bare symbol. The left one is 'opaque' and the memo keeps the stall, so the+# right one is told 'stall 𝜎1' with no 'opaque' line. Both still end their+# side alone as ⊥ (#2427), since the stall names the symbol.+symbolic: |+ - λ: L_fork+ dataize:+ 𝛿1: $.on🌵+ morph:+ 𝑛1: $.left🌵+ 𝑛2: $.right🌵+ join:+ on: 𝛿1+ left: 𝑛1+ right: 𝑛2+ otherwise: L_fork+ - λ: L_id+ morph:+ 𝑛1: $.x+ 𝑛: 𝑛1+location: 'Q.e1'+acyclic: plausible+input: '⟦ k ↦ ⟦ q ↦ ⟦⟧ ⟧, id ↦ ⟦ λ ⤍ L_id, x ↦ ⟦ λ ⤍ 𝜎1 ⟧.q ⟧, e1 ↦ ⟦ λ ⤍ L_fork, on🌵 ↦ ⟦ Δ ⤍ 00- ⟧, left🌵 ↦ Φ.id.φ, right🌵 ↦ Φ.id.φ ⟧.φ ⟧'+result: '⊥'+protocol: |+ 𝕄(Φ.e1):+ 𝔼(L_fork):+ 𝔻(ξ.on🌵):+ 𝛿·1·1 := 00-+ 𝛿1·1 := 𝛿·1·1 # 𝔻(ξ.on🌵)+ 𝕄(ξ.left🌵):+ remembered 𝑛·1·1 ≡ Φ.id # ⟦ λ ⤍ L_id, x ↦ 𝜎1:λ.q ⟧+ 𝔼(L_id):+ 𝕄(ξ.x):+ opaque 𝜎1 # 𝕄(𝜎1:λ.q)+ stuck 𝜎1+ 𝑛1·1 := ⊥ # 𝕄(ξ.left🌵)+ 𝕄(ξ.right🌵):+ 𝔼(L_id):+ stall 𝜎1+ 𝑛2·1 := ⊥ # 𝕄(ξ.right🌵)+ 𝑛·1·2 := ⊥+ memoized 𝑛·1·3 ⇛ ⊥ # ⟦ λ ⤍ L_fork, on🌵 ↦ 00-:Δ, left🌵 ↦ Φ.id.φ, right🌵 ↦ Φ.id.φ ⟧+ evaluated 𝑛·1·4 := ⊥ # 𝑛·1·3+ normalized 𝑛·0·1 := ⊥ # ⊥.φ+ morphed 𝑛·0·2 := ⊥
+ test-resources/evaluate-packs/ends-a-side-at-an-evaluate-line-stuck-on-a-symbol.yaml view
@@ -0,0 +1,50 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+# yamllint disable rule:line-length+# An 'evaluate' line of a joining entry fires a copy of 'L_id', whose operand+# dispatches off a bare symbol and gets 'opaque'. The line binds its meta to+# ⊥ (#2427), so the join keeps the right side instead of getting stuck.+symbolic: |+ - λ: L_fork+ dataize:+ 𝛿1: $.on🌵+ morph:+ 𝑛1: $.left🌵+ 𝑛2: $.right🌵+ evaluate:+ 𝑛3: 𝑛1+ join:+ on: 𝛿1+ left: 𝑛3+ right: 𝑛2+ - λ: L_id+ morph:+ 𝑛1: $.x+ 𝑛: 𝑛1+location: 'Q.e1'+input: '⟦ k ↦ ⟦ q ↦ ⟦⟧ ⟧, e1 ↦ ⟦ λ ⤍ L_fork, on🌵 ↦ ⟦ Δ ⤍ 00- ⟧, left🌵 ↦ ⟦ λ ⤍ L_id, x ↦ ⟦ λ ⤍ 𝜎1 ⟧.q ⟧, right🌵 ↦ ⟦ φ ↦ Φ.k ⟧ ⟧.φ ⟧'+result: '⟦⟧:q'+protocol: |+ 𝕄(Φ.e1):+ 𝔼(L_fork):+ 𝔻(ξ.on🌵):+ 𝛿·1·1 := 00-+ 𝛿1·1 := 𝛿·1·1 # 𝔻(ξ.on🌵)+ 𝕄(ξ.left🌵):+ morphed 𝑛·1·1 := ⟦ λ ⤍ L_id, x ↦ 𝜎1:λ.q ⟧+ 𝑛1·1 := ⟦ λ ⤍ L_id, x ↦ 𝜎1:λ.q ⟧ # 𝕄(ξ.left🌵)+ 𝕄(ξ.right🌵):+ morphed 𝑛·1·2 := Φ.k:φ+ 𝑛2·1 := 𝑛·1·2 # 𝕄(ξ.right🌵)+ 𝔼(L_id): # 𝔼(𝑛1 of L_fork)+ 𝕄(ξ.x):+ opaque 𝜎1 # 𝕄(𝜎1:λ.q)+ stuck 𝜎1+ 𝑛3·1 := ⊥ # 𝔼(𝑛1 of L_fork)+ guarded 𝛿1·1 ? 𝑛3·1 : 𝑛2·1 # where 𝑛3·1 is ⊥+ 𝑛·1·3 := 𝑛·1·2+ evaluated 𝑛·1·4 := 𝑛·1·3 # ⟦ λ ⤍ L_fork, on🌵 ↦ 00-:Δ, left🌵 ↦ ⟦ λ ⤍ L_id, x ↦ 𝜎1:λ.q ⟧, right🌵 ↦ 𝑛·1·3 ⟧+ normalized 𝑛·0·1 := Φ.k # 𝑛·1·4.φ+ normalized 𝑛·0·2 := ⟦⟧:q # Φ.k+ morphed 𝑛·0·3 := 𝑛·0·2
+ test-resources/evaluate-packs/ends-a-side-read-off-a-path-at-a-dispatch-off-a-symbol.yaml view
@@ -0,0 +1,34 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+# yamllint disable rule:line-length+# The join reads its left side off a path, which dispatches 'q' off a bare+# symbol and is 'opaque'. The opaque ends that side alone as ⊥ (#2427), and+# the join keeps the right side under the condition.+symbolic: |+ - λ: L_fork+ dataize:+ 𝛿1: $.on🌵+ join:+ on: 𝛿1+ left: $.left🌵+ right: $.right🌵+location: 'Q.e1'+input: '⟦ k ↦ ⟦ q ↦ ⟦⟧ ⟧, e1 ↦ ⟦ λ ⤍ L_fork, on🌵 ↦ ⟦ Δ ⤍ 00- ⟧, left🌵 ↦ ⟦ λ ⤍ 𝜎1 ⟧.q, right🌵 ↦ ⟦ φ ↦ Φ.k ⟧ ⟧.φ ⟧'+result: '⟦⟧:q'+protocol: |+ 𝕄(Φ.e1):+ 𝔼(L_fork):+ 𝔻(ξ.on🌵):+ 𝛿·1·1 := 00-+ 𝛿1·1 := 𝛿·1·1 # 𝔻(ξ.on🌵)+ 𝕄(ξ.left🌵):+ opaque 𝜎1 # 𝕄(𝜎1:λ.q)+ 𝕄(ξ.right🌵):+ morphed 𝑛·1·1 := Φ.k:φ+ guarded 𝛿1·1 ? ⊥ : 𝑛·1·1 # where ⊥ is ⊥+ 𝑛·1·2 := 𝑛·1·1+ evaluated 𝑛·1·3 := 𝑛·1·2 # ⟦ λ ⤍ L_fork, on🌵 ↦ 00-:Δ, left🌵 ↦ 𝜎1:λ.q, right🌵 ↦ 𝑛·1·2 ⟧+ normalized 𝑛·0·1 := Φ.k # 𝑛·1·3.φ+ normalized 𝑛·0·2 := ⟦⟧:q # Φ.k+ morphed 𝑛·0·3 := 𝑛·0·2
+ test-resources/evaluate-packs/gets-stuck-on-a-dispatch-off-a-symbol-outside-a-join.yaml view
@@ -0,0 +1,32 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+# yamllint disable rule:line-length+# An entry that does not join morphs an operand dispatching off a bare+# symbol. There is no side to end, so the 'opaque' still gets the firing stuck+# (#2427).+symbolic: |+ - λ: L_fork+ dataize:+ 𝛿1: $.on🌵+ morph:+ 𝑛1: $.left🌵+ 𝑛2: $.right🌵+ join:+ on: 𝛿1+ left: 𝑛1+ right: 𝑛2+ otherwise: L_fork+ - λ: L_id+ morph:+ 𝑛1: $.x+ 𝑛: 𝑛1+location: 'Q.e1'+input: '⟦ e1 ↦ ⟦ λ ⤍ L_id, x ↦ ⟦ λ ⤍ 𝜎1 ⟧.q ⟧.φ ⟧'+fails: "No entry of --symbolic answers the λ function '𝜎1'"+protocol: |+ 𝕄(Φ.e1):+ 𝔼(L_id):+ 𝕄(ξ.x):+ opaque 𝜎1 # 𝕄(𝜎1:λ.q)+ stuck 𝜎1
+ test-resources/sodg-packs/bottom-argument.yaml view
@@ -0,0 +1,5 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ a ↦ Φ.f( x ↦ ⊥ ) ⟧'+fails: 'The attribute Φ.a.x is ⊥'
+ test-resources/sodg-packs/bottom.yaml view
@@ -0,0 +1,5 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ a ↦ ⟦ b ↦ ⊥ ⟧ ⟧'+fails: 'The attribute Φ.a.b is ⊥'
+ test-resources/sodg-packs/empty-bytes-and-symbol.yaml view
@@ -0,0 +1,10 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ a ↦ ⟦ Δ ⤍ --, λ ⤍ 𝜎3 ⟧ ⟧'+output: |+ F c0 a+ F c1+ Δ c1 --+ λ c1 𝜎3+ P c0 a c1
+ test-resources/sodg-packs/empty.yaml view
@@ -0,0 +1,6 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦⟧'+output: |+ F c0
+ test-resources/sodg-packs/meta-attribute.yaml view
@@ -0,0 +1,5 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ a ↦ ξ.𝜏1 ⟧'+fails: 'holds 𝜏1'
+ test-resources/sodg-packs/meta-binding.yaml view
@@ -0,0 +1,5 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ a ↦ ⟦ 𝐵1 ⟧ ⟧'+fails: 'holds ⟦ 𝐵1 ⟧'
+ test-resources/sodg-packs/meta-bytes.yaml view
@@ -0,0 +1,5 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ Δ ⤍ 𝛿1 ⟧'+fails: 'The term at Φ holds 𝛿1:Δ'
+ test-resources/sodg-packs/meta.yaml view
@@ -0,0 +1,5 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ a ↦ 𝑒1 ⟧'+fails: 'holds 𝑒1, which only a pattern of a rule may hold'
+ test-resources/sodg-packs/nested-xi.yaml view
@@ -0,0 +1,13 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ a ↦ ⟦ b ↦ ξ.c, c ↦ ξ ⟧, d ↦ ξ.a ⟧'+output: |+ F c0 a d+ F c1 b c+ D c2 c1 c+ P c1 b c2+ P c1 c c1+ P c0 a c1+ D c3 c0 a+ P c0 d c3
+ test-resources/sodg-packs/not-formation.yaml view
@@ -0,0 +1,8 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: 'Φ.foo.bar'+output: |+ F c0+ D c1 c0 foo+ D c2 c1 bar
+ test-resources/sodg-packs/number.yaml view
@@ -0,0 +1,13 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ x ↦ 42 ⟧'+output: |+ F c0 x+ D c1 c0 number+ D c2 c0 bytes+ F c3+ Δ c3 40-45-00-00-00-00-00-00+ A c4 c2 φ c3+ A c5 c1 φ c4+ P c0 x c5
+ test-resources/sodg-packs/order.yaml view
@@ -0,0 +1,13 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ order(qty, price) ↦ ⟦ cost ↦ ξ.qty.mul( ξ.price ) ⟧ ⟧'+output: |+ F c0 order+ F c1 qty price cost+ D c2 c1 qty+ D c3 c2 mul+ D c4 c1 price+ A c5 c3 α0 c4+ P c1 cost c5+ P c0 order c1
+ test-resources/sodg-packs/root-rho-delta-lambda.yaml view
@@ -0,0 +1,26 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: |+ ⟦+ foo ↦ ⟦ x ↦ ⟦ Δ ⤍ 2A- ⟧, y ↦ Φ.bar( z ↦ ξ.x ).t, λ ⤍ L_foo ⟧,+ bar ↦ ⟦ z ↦ ∅, t ↦ ξ.ρ.z ⟧+ ⟧+output: |+ F c0 foo bar+ F c1 x y+ F c2+ Δ c2 2A-+ P c1 x c2+ D c3 c0 bar+ D c4 c1 x+ A c5 c3 z c4+ D c6 c5 t+ P c1 y c6+ λ c1 L_foo+ P c0 foo c1+ F c7 z t+ D c8 c7 ρ+ D c9 c8 z+ P c7 t c9+ P c0 bar c7
+ test-resources/sodg-packs/spelled-rho.yaml view
@@ -0,0 +1,8 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ ρ ↦ ∅, φ ↦ ξ.ρ ⟧'+output: |+ F c0 ρ φ+ D c1 c0 ρ+ P c0 φ c1
+ test-resources/sodg-packs/two-arguments.yaml view
@@ -0,0 +1,11 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: '⟦ x ↦ Φ.f( a ↦ ξ.y, b ↦ Φ ), y ↦ ∅ ⟧'+output: |+ F c0 x y+ D c1 c0 f+ D c2 c0 y+ A c3 c1 a c2+ A c4 c3 b c0+ P c0 x c4
+ test-resources/sodg-packs/unbound-xi.yaml view
@@ -0,0 +1,5 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+# SPDX-License-Identifier: MIT+---+input: 'ξ.foo'+fails: 'The ξ at Φ has no formation around it'
test/ASTSpec.hs view
@@ -10,9 +10,14 @@ import Control.Exception (evaluate) import Control.Monad (forM_) import Data.List (nub, sort)+import Data.List qualified as List+import Data.Map.Strict qualified as Map import Data.Text qualified as T import GHC.Clock (getMonotonicTime)+import Grown (Grown (..))+import System.Timeout (timeout) import Test.Hspec (Spec, describe, it, shouldBe, shouldNotBe, shouldSatisfy)+import Test.Hspec.QuickCheck (prop) spec :: Spec spec = do@@ -342,6 +347,72 @@ akin (ExFormation [BiTau (AtLabel "w") (down ExXi), BiLambda (Function "L_ab")]) (ExFormation [BiTau (AtLabel "w") (down (next ExXi)), BiLambda (Function "L_cd")]) `shouldBe` False it "does not map one symbol outside a boxed formation to two others" $ akin (atom (down ExRoot) 4) (ExFormation [BiTau (AtLabel "on") (ExFormation [BiLambda (FnSymbol 6)]), BiTau AtRho (ExFormation [BiTau (AtLabel "rt") (down ExRoot), BiTau (AtLabel "of") (ExFormation [BiLambda (FnSymbol 6)])]), BiLambda (Function "L_vex")]) `shouldBe` False+ it "does not find an atom inside one whose boxed formation is not within, however alike their parts" $+ akin (atom (ExFormation [BiTau AtPhi ExRoot, BiTau (AtLabel "z") ExXi]) 1) (atom (ExFormation [BiTau AtPhi ExRoot, BiTau (AtLabel "z") ExRoot]) 1) `shouldBe` False+ prop "finds every term inside itself, as the looser search does" $ \(Grown one) ->+ (akin one one, within one one) `shouldBe` (True, True)+ it "does not walk a name it already measured again when it compares how deep two calls are" $ do+ let named :: Int -> Expression+ named idx = ExMeta (T.pack ("n·" ++ show idx))+ term :: Int -> Expression+ term idx = ExApplication (ExApplication (ExDispatch ExRoot (AtLabel "f")) (ArTau (AtLabel "a") (named (pred idx)))) (ArTau (AtLabel "b") (named (pred idx)))+ look :: T.Text -> Maybe Expression+ look name = case T.stripPrefix "n·" name of+ Just idx | idx /= "0" -> Just (term (read (T.unpack idx)))+ _ -> Nothing+ depths :: Map.Map T.Text Int+ depths = List.foldl' (\kept idx -> Map.insert (T.pack ("n·" ++ show idx)) (deepness look (`Map.lookup` kept) (term idx)) kept) Map.empty [1 .. 22 :: Int]+ start <- getMonotonicTime+ found <- evaluate (akin' look (`Map.lookup` depths) (ExDispatch (named 21) (AtLabel "q")) (ExDispatch (named 22) (AtLabel "q")))+ end <- getMonotonicTime+ (found, end - start < 1) `shouldBe` (True, True)+ prop "answers the same with what an earlier search kept as with nothing" $ \(Grown one) (Grown two) (Grown three) ->+ fst (akin'' (const Nothing) (const Nothing) (snd (akin'' (const Nothing) (const Nothing) Map.empty three one)) one two) `shouldBe` akin one two++ describe "deepness" $ do+ it "counts a call one deeper than the deepest of its head and its argument" $+ deepness (const Nothing) (const Nothing) (ExApplication (ExDispatch (ExDispatch ExRoot (AtLabel "f")) (AtLabel "g")) (ArTau (AtLabel "x") ExXi)) `shouldBe` 3+ it "takes the depth of a name it was told instead of walking its term" $+ deepness (const (Just (ExDispatch ExRoot (AtLabel "f")))) (const (Just 7)) (ExDispatch (ExMeta "n·1") (AtLabel "q")) `shouldBe` 8+ prop "measures a term the same with the depths of its names kept as by walking them" $ \(Grown one) (Grown two) (Grown three) ->+ let terms :: Map.Map T.Text Expression+ terms = Map.fromList [("n·1", one), ("n·2", ExApplication two (ArTau (AtLabel "x") (ExMeta "n·1")))]+ look :: T.Text -> Maybe Expression+ look = (`Map.lookup` terms)+ depths :: Map.Map T.Text Int+ depths = List.foldl' (\kept (name, term) -> Map.insert name (deepness look (`Map.lookup` kept) term) kept) Map.empty (Map.toAscList terms)+ whole :: Expression+ whole = ExApplication three (ArAlpha (Alpha 0) (ExMeta "n·2"))+ in deepness look (`Map.lookup` depths) whole `shouldBe` deepness look (const Nothing) whole++ describe "reaches" $ do+ prop "tells a term reaches a depth exactly where it measures at least that deep" $ \(Grown one) ->+ let deep :: Int+ deep = deepness (const Nothing) (const Nothing) one+ in map (\limit -> reaches (const Nothing) (const Nothing) limit one) [0 .. deep + 1] `shouldBe` map (<= deep) [0 .. deep + 1]+ prop "takes the depth of a name it was told as deepness does" $ \(Grown one) (Grown two) ->+ let look :: T.Text -> Maybe Expression+ look name = if name == "n·1" then Just one else Nothing+ depth :: T.Text -> Maybe Int+ depth name = if name == "n·1" then Just (deepness look (const Nothing) one) else Nothing+ whole :: Expression+ whole = ExApplication two (ArTau (AtLabel "x") (ExMeta "n·1"))+ deep :: Int+ deep = deepness look depth whole+ in map (\limit -> reaches look depth limit whole) [0 .. deep + 1] `shouldBe` map (<= deep) [0 .. deep + 1]+ it "does not walk an earlier call deeper than the new one when it compares them" $ do+ let named :: Int -> Expression+ named idx = ExMeta (T.pack ("n·" ++ show idx))+ term :: Int -> Expression+ term idx = ExApplication (ExApplication (ExDispatch ExRoot (AtLabel "f")) (ArTau (AtLabel "a") (named (pred idx)))) (ArTau AtRho (named (pred idx)))+ look :: T.Text -> Maybe Expression+ look name = case T.stripPrefix "n·" name of+ Just idx | idx /= "0" -> Just (term (read (T.unpack idx)))+ _ -> Nothing+ call :: Expression -> Expression+ call arg = ExApplication (ExDispatch ExRoot (AtLabel "g")) (ArTau (AtLabel "x") arg)+ found <- timeout 1000000 (evaluate (akin' look (const Nothing) (call (ExFormation [BiTau AtRho (named 64)])) (call ExRoot)))+ found `shouldBe` Just False describe "hashSkeleton" $ do it "does not tell apart two formations that bind other terms to the same attributes" $
test/CLISpec.hs view
@@ -693,6 +693,28 @@ concat saved `shouldNotContain` "Minus" concat saved `shouldNotContain` "Plus" + it "keeps the name a function has under --sequence in every --steps-dir file under --canonize" $+ withTempDirectory "phino-steps-canonized" $ \dir ->+ withStdin "[[ a -> [[ x -> [[ L> Fa ]] ]].q, b -> [[ y -> [[ L> Fb ]] ]].y ]]" $ do+ testCLISucceeded+ ["rewrite", "--normalize", "--sequence", "--canonize", "--flat", "--steps-dir=" ++ dir]+ ["⟦ a ↦ ⊥, b ↦ ⟦ λ ⤍ Fn2 ⟧ ⟧"]+ saved <- traverse (readUtf8 . (dir </>)) ["00001.phi", "00002.phi", "00003.phi"]+ map (filter (/= '\n')) saved+ `shouldBe` [ "⟦ a ↦ ⟦ x ↦ ⟦ λ ⤍ Fn1 ⟧ ⟧.q, b ↦ ⟦ λ ⤍ Fn2 ⟧( ρ ↦ ⟦ y ↦ ⟦ λ ⤍ Fn2 ⟧ ⟧ ) ⟧"+ , "⟦ a ↦ ⟦ x ↦ ⟦ λ ⤍ Fn1 ⟧ ⟧.q, b ↦ ⟦ λ ⤍ Fn2 ⟧ ⟧"+ , "⟦ a ↦ ⊥, b ↦ ⟦ λ ⤍ Fn2 ⟧ ⟧"+ ]++ it "saves the --canonize steps when --show names an object only the steps hold" $+ withTempDirectory "phino-steps-shown" $ \dir ->+ withStdin "[[ app -> [[ x -> [[ L> Fx ]] ]](^ -> [[ ]]) ]]" $ do+ testCLISucceeded+ ["rewrite", "--normalize", "--canonize", "--flat", "--show=Q.app.x", "--steps-dir=" ++ dir]+ ["⟦ app ↦ ⟦ x ↦ ⟦ λ ⤍ Fn1 ⟧ ⟧ ⟧"]+ saved <- readUtf8 (dir </> "00001.phi")+ filter (/= '\n') saved `shouldBe` "⟦ app ↦ ⟦ x ↦ ⟦ λ ⤍ Fn1 ⟧ ⟧ ⟧"+ it "gives the saved steps the --focus of the printed ones" $ withTempDirectory "phino-steps-focused" $ \dir -> withStdin "⟦ x ↦ ⟦ k ↦ ⟦ q ↦ ⟦⟧ ⟧ ⟧.k, y ↦ ⟦ z ↦ ⟦⟧ ⟧ ⟧" $ do@@ -1720,6 +1742,14 @@ records <- map (dropWhile (== ' ')) . lines <$> readProtocol path records `shouldContain` ["looped 𝜎5 := 𝑛·5·1.plus # plausible, repeats 𝑛·0·4"] + describe "over a recursion that hands its own growing call to an atom" $ do+ let world = "⟦ go(x) ↦ ⟦ λ ⤍ L_go ⟧, seq(i) ↦ ⟦ ok ↦ Φ.go( Φ.seq( i.next ).ok ) ⟧, app ↦ Φ.seq( 𝜎1:λ ).ok ⟧"+ atoms = T.pack "- λ: L_go\n morph: {𝑛1: $.x}\n 𝑛: 𝑛1\n"+ it "cuts the recursion by --max-loops, not by --max-steps" $+ withLambdasOf atoms $ \file ->+ withStdin world $+ testCLISucceeded ["dataize", "--symbolic=" ++ file, "--locator=Q.app", "--acyclic=plausible", "--max-loops=1", "--max-steps=200"] ["40-45-00-00-00-00-00-00"]+ it "refuses a negative count" $ withStdin once $ testCLIFailed ["dataize", "--locator=Q.t", "--acyclic=plausible", "--max-loops=-1"] ["--max-loops must be >= 0"]@@ -2160,6 +2190,18 @@ records <- readProtocol path records `shouldBe` "𝔻(Φ):\n 𝛿·0·1 := 01-\n" + it "adds the time, the depth, the firings and the memory to every line under --profile" $+ withTempFile "protocolXXXXXX.txt" $ \(path, stream) -> do+ hClose stream+ withStdin "[[ D> 01- ]]" $+ testCLISucceeded ["dataize", "--minutes=" ++ path, "--profile", "--quiet"] []+ records <- readProtocol path+ lines records `shouldSatisfy` all (\line -> all (`isInfixOf` line) [" ms, at ", ", depth ", ", firings ", ", heap ", ", peak "])++ it "refuses --profile without --minutes" $+ withStdin "[[ D> 01- ]]" $+ testCLIFailed ["dataize", "--profile", "--quiet"] ["The option --profile requires --minutes"]+ it "opens the protocol with a header naming the phino that wrote it" $ withTempFile "protocolXXXXXX.txt" $ \(path, stream) -> do hClose stream@@ -4709,6 +4751,29 @@ createDirectoryIfMissing True dir writeFile (dir </> "having.yaml") "name: hv\npattern: '[[ x -> !e1, !B1 ]]'\nresult: '[[ !B1 ]]'\nhaving:\n eq: ['!e1', '!e1']\n" withCurrentDirectory dir (testCLIFailed ["compile", "--rule=having.yaml", "--target=Compiled.hs"] ["The rule 'hv' cannot be compiled, since it has a 'having' condition"])++ describe "sodg" $ do+ it "prints help" $+ testCLISucceeded ["sodg", "--help"] ["Print the SODG commands that build the graph of the 𝜑-expression"]++ it "takes from stdin" $+ withStdin "⟦ x ↦ ξ.y, y ↦ ∅ ⟧" $+ testCLISucceeded ["sodg"] ["F c0 x y\nD c1 c0 y\nP c0 x c1\n"]++ it "takes from file" $+ testCLISucceeded ["sodg", resource "foo.phi"] ["F c0 foo\nD c1 c0 org\nD c2 c1 eolang\nD c3 c2 x\nP c0 foo c3\n"]++ it "reads XMIR" $+ withStdin "<object><o name=\"app\"><o name=\"x\" base=\"Φ.number\"/></o></object>" $+ testCLISucceeded ["sodg", "--input=xmir"] ["F c0 app\nF c1 x\nD c2 c0 number\nP c1 x c2\nP c0 app c1\n"]++ it "fails on ⊥ and names the attribute" $+ withStdin "⟦ a ↦ ⊥ ⟧" $+ testCLIFailed ["sodg"] ["The attribute Φ.a is ⊥"]++ it "rejects an option of other commands" $+ withStdin "⟦⟧" $+ testCLIFailed ["sodg", "--sweet"] ["Invalid option"] describe "match" $ do it "prints help" $
test/CSTSpec.hs view
@@ -471,7 +471,10 @@ describe "TAB field accessors" $ it "exposes every TAB field via its accessor" $ do let tabVal = TAB{indent = 3}- tabVal.indent `shouldBe` 3+ case tabVal of+ actual@TAB{} ->+ actual.indent `shouldBe` 3+ _ -> expectationFailure "Expected TAB" shouldShowAndEqSelf "TAB" tabVal shouldShowAndEqSelf "TAB'" TAB' shouldShowAndEqSelf "NO_TAB" NO_TAB@@ -480,10 +483,16 @@ it "exposes every ALPHA field via its accessor" $ do let idxAlpha = AL_IDX{sym = ALPHA, idx = 2} metaAlpha = AL_META{sym = ALPHA', meta = META EXCL TAU "x"}- idxAlpha.sym `shouldBe` ALPHA- idxAlpha.idx `shouldBe` 2- metaAlpha.sym `shouldBe` ALPHA'- metaAlpha.meta `shouldBe` META EXCL TAU "x"+ case idxAlpha of+ actual@AL_IDX{} -> do+ actual.sym `shouldBe` ALPHA+ actual.idx `shouldBe` 2+ _ -> expectationFailure "Expected AL_IDX"+ case metaAlpha of+ actual@AL_META{} -> do+ actual.sym `shouldBe` ALPHA'+ actual.meta `shouldBe` META EXCL TAU "x"+ _ -> expectationFailure "Expected AL_META" shouldShowAndEqSelf "AL_IDX" idxAlpha shouldShowAndEqSelf "AL_META" metaAlpha @@ -504,27 +513,63 @@ pairDelta' = PA_DELTA'{bytes = BT_ONE "40"} pairMetaDelta = PA_META_DELTA{meta = metaVal} pairMetaDelta' = PA_META_DELTA'{meta = metaVal}- pairTau.attr `shouldBe` attrLabel- pairTau.arrow `shouldBe` ARROW- pairTau.expr `shouldBe` exprGlobal- pairAlpha.alpha `shouldBe` AL_IDX ALPHA 0- pairAlpha.arrow `shouldBe` ARROW- pairAlpha.expr `shouldBe` exprGlobal- pairFormation.attr `shouldBe` attrLabel- pairFormation.voids `shouldBe` [AT_RHO RHO]- pairFormation.arrow `shouldBe` ARROW- pairFormation.expr `shouldBe` exprGlobal- pairVoid.attr `shouldBe` attrLabel- pairVoid.arrow `shouldBe` ARROW- pairVoid.void `shouldBe` EMPTY- pairLambda.func `shouldBe` "fn"- pairLambda'.func `shouldBe` "fn"- pairMetaLambda.meta `shouldBe` metaVal- pairMetaLambda'.meta `shouldBe` metaVal- pairDelta.bytes `shouldBe` BT_ONE "40"- pairDelta'.bytes `shouldBe` BT_ONE "40"- pairMetaDelta.meta `shouldBe` metaVal- pairMetaDelta'.meta `shouldBe` metaVal+ case pairTau of+ actual@PA_TAU{} -> do+ actual.attr `shouldBe` attrLabel+ actual.arrow `shouldBe` ARROW+ actual.expr `shouldBe` exprGlobal+ _ -> expectationFailure "Expected PA_TAU"+ case pairAlpha of+ actual@PA_ALPHA{} -> do+ actual.alpha `shouldBe` AL_IDX ALPHA 0+ actual.arrow `shouldBe` ARROW+ actual.expr `shouldBe` exprGlobal+ _ -> expectationFailure "Expected PA_ALPHA"+ case pairFormation of+ actual@PA_FORMATION{} -> do+ actual.attr `shouldBe` attrLabel+ actual.voids `shouldBe` [AT_RHO RHO]+ actual.arrow `shouldBe` ARROW+ actual.expr `shouldBe` exprGlobal+ _ -> expectationFailure "Expected PA_FORMATION"+ case pairVoid of+ actual@PA_VOID{} -> do+ actual.attr `shouldBe` attrLabel+ actual.arrow `shouldBe` ARROW+ actual.void `shouldBe` EMPTY+ _ -> expectationFailure "Expected PA_VOID"+ case pairLambda of+ actual@PA_LAMBDA{} ->+ actual.func `shouldBe` "fn"+ _ -> expectationFailure "Expected PA_LAMBDA"+ case pairLambda' of+ actual@PA_LAMBDA'{} ->+ actual.func `shouldBe` "fn"+ _ -> expectationFailure "Expected PA_LAMBDA'"+ case pairMetaLambda of+ actual@PA_META_LAMBDA{} ->+ actual.meta `shouldBe` metaVal+ _ -> expectationFailure "Expected PA_META_LAMBDA"+ case pairMetaLambda' of+ actual@PA_META_LAMBDA'{} ->+ actual.meta `shouldBe` metaVal+ _ -> expectationFailure "Expected PA_META_LAMBDA'"+ case pairDelta of+ actual@PA_DELTA{} ->+ actual.bytes `shouldBe` BT_ONE "40"+ _ -> expectationFailure "Expected PA_DELTA"+ case pairDelta' of+ actual@PA_DELTA'{} ->+ actual.bytes `shouldBe` BT_ONE "40"+ _ -> expectationFailure "Expected PA_DELTA'"+ case pairMetaDelta of+ actual@PA_META_DELTA{} ->+ actual.meta `shouldBe` metaVal+ _ -> expectationFailure "Expected PA_META_DELTA"+ case pairMetaDelta' of+ actual@PA_META_DELTA'{} ->+ actual.meta `shouldBe` metaVal+ _ -> expectationFailure "Expected PA_META_DELTA'" shouldShowAndEqSelf "PA_TAU" pairTau shouldShowAndEqSelf "PA_ALPHA" pairAlpha shouldShowAndEqSelf "PA_FORMATION" pairFormation@@ -552,12 +597,18 @@ bindingsEmpty = BDS_EMPTY{tab = TAB 0} biPair = BI_PAIR{pair = pairTau, bindings = bindingsEmpty, tab = TAB 1} biMeta = BI_META{meta = metaVal, bindings = bindingsEmpty, tab = TAB 1}- biPair.pair `shouldBe` pairTau- biPair.bindings `shouldBe` bindingsEmpty- biPair.tab `shouldBe` TAB 1- biMeta.meta `shouldBe` metaVal- biMeta.bindings `shouldBe` bindingsEmpty- biMeta.tab `shouldBe` TAB 1+ case biPair of+ actual@BI_PAIR{} -> do+ actual.pair `shouldBe` pairTau+ actual.bindings `shouldBe` bindingsEmpty+ actual.tab `shouldBe` TAB 1+ _ -> expectationFailure "Expected BI_PAIR"+ case biMeta of+ actual@BI_META{} -> do+ actual.meta `shouldBe` metaVal+ actual.bindings `shouldBe` bindingsEmpty+ actual.tab `shouldBe` TAB 1+ _ -> expectationFailure "Expected BI_META" shouldShowAndEqSelf "BI_PAIR" biPair shouldShowAndEqSelf "BI_META" biMeta @@ -568,14 +619,20 @@ bindingsEmpty = BDS_EMPTY{tab = TAB 0} bdsPair = BDS_PAIR{eol = EOL, tab = TAB 1, pair = pairTau, bindings = bindingsEmpty} bdsMeta = BDS_META{eol = EOL, tab = TAB 1, meta = metaVal, bindings = bindingsEmpty}- bdsPair.eol `shouldBe` EOL- bdsPair.tab `shouldBe` TAB 1- bdsPair.pair `shouldBe` pairTau- bdsPair.bindings `shouldBe` bindingsEmpty- bdsMeta.eol `shouldBe` EOL- bdsMeta.tab `shouldBe` TAB 1- bdsMeta.meta `shouldBe` metaVal- bdsMeta.bindings `shouldBe` bindingsEmpty+ case bdsPair of+ actual@BDS_PAIR{} -> do+ actual.eol `shouldBe` EOL+ actual.tab `shouldBe` TAB 1+ actual.pair `shouldBe` pairTau+ actual.bindings `shouldBe` bindingsEmpty+ _ -> expectationFailure "Expected BDS_PAIR"+ case bdsMeta of+ actual@BDS_META{} -> do+ actual.eol `shouldBe` EOL+ actual.tab `shouldBe` TAB 1+ actual.meta `shouldBe` metaVal+ actual.bindings `shouldBe` bindingsEmpty+ _ -> expectationFailure "Expected BDS_META" shouldShowAndEqSelf "BDS_PAIR" bdsPair shouldShowAndEqSelf "BDS_META" bdsMeta @@ -593,10 +650,13 @@ let exprGlobal = EX_GLOBAL Φ appArgsEmpty = AAS_EMPTY appArgsExpr = AAS_EXPR{eol = EOL, tab = TAB 1, expr = exprGlobal, args = appArgsEmpty}- appArgsExpr.eol `shouldBe` EOL- appArgsExpr.tab `shouldBe` TAB 1- appArgsExpr.expr `shouldBe` exprGlobal- appArgsExpr.args `shouldBe` appArgsEmpty+ case appArgsExpr of+ actual@AAS_EXPR{} -> do+ actual.eol `shouldBe` EOL+ actual.tab `shouldBe` TAB 1+ actual.expr `shouldBe` exprGlobal+ actual.args `shouldBe` appArgsEmpty+ _ -> expectationFailure "Expected AAS_EXPR" shouldShowAndEqSelf "AAS_EXPR" appArgsExpr describe "APP_ARGUMENT derived instances" $@@ -644,43 +704,82 @@ exMeta = EX_META{meta = metaVal} exPhiMeet = EX_PHI_MEET{prefix = Just "p", idx = 1, expr = exGlobal} exBytes = EX_BYTES{bytes = BT_ONE "40"}- exGlobal.global `shouldBe` Φ- exXi.xi `shouldBe` XI- exAttr.attr `shouldBe` attrLabel- exTermination.termination `shouldBe` DEAD- exFormation.lsb `shouldBe` LSB- exFormation.eol `shouldBe` EOL- exFormation.tab `shouldBe` TAB 1- exFormation.binding `shouldBe` bindingEmpty- exFormation.eol' `shouldBe` EOL- exFormation.tab' `shouldBe` TAB 0- exFormation.rsb `shouldBe` RSB- exDispatch.expr `shouldBe` exGlobal- exDispatch.space `shouldBe` NO_SPACE- exDispatch.attr `shouldBe` attrLabel- exApplication.expr `shouldBe` exGlobal- exApplication.space `shouldBe` NO_SPACE- exApplication.eol `shouldBe` EOL- exApplication.tab `shouldBe` TAB 1- exApplication.argument `shouldBe` argumentVal- exApplication.eol' `shouldBe` EOL- exApplication.tab' `shouldBe` TAB 0- exApplication.indent `shouldBe` 1- exString.str `shouldBe` "hi"- exString.tab `shouldBe` TAB 0- exString.rhos `shouldBe` []- exNumber.num `shouldBe` 5- exNumber.tab `shouldBe` TAB 0- exNumber.rhos `shouldBe` []- exNonFinite.global `shouldBe` Φ- exNonFinite.nonfinite `shouldBe` NfNan- exNonFinite.tab `shouldBe` TAB 0- exNonFinite.rhos `shouldBe` []- exMeta.meta `shouldBe` metaVal- exPhiMeet.prefix `shouldBe` Just "p"- exPhiMeet.idx `shouldBe` 1- exPhiMeet.expr `shouldBe` exGlobal- exBytes.bytes `shouldBe` BT_ONE "40"+ case exGlobal of+ actual@EX_GLOBAL{} ->+ actual.global `shouldBe` Φ+ _ -> expectationFailure "Expected EX_GLOBAL"+ case exXi of+ actual@EX_XI{} ->+ actual.xi `shouldBe` XI+ _ -> expectationFailure "Expected EX_XI"+ case exAttr of+ actual@EX_ATTR{} ->+ actual.attr `shouldBe` attrLabel+ _ -> expectationFailure "Expected EX_ATTR"+ case exTermination of+ actual@EX_TERMINATION{} ->+ actual.termination `shouldBe` DEAD+ _ -> expectationFailure "Expected EX_TERMINATION"+ case exFormation of+ actual@EX_FORMATION{} -> do+ actual.lsb `shouldBe` LSB+ actual.eol `shouldBe` EOL+ actual.tab `shouldBe` TAB 1+ actual.binding `shouldBe` bindingEmpty+ actual.eol' `shouldBe` EOL+ actual.tab' `shouldBe` TAB 0+ actual.rsb `shouldBe` RSB+ _ -> expectationFailure "Expected EX_FORMATION"+ case exDispatch of+ actual@EX_DISPATCH{} -> do+ actual.expr `shouldBe` exGlobal+ actual.space `shouldBe` NO_SPACE+ actual.attr `shouldBe` attrLabel+ _ -> expectationFailure "Expected EX_DISPATCH"+ case exApplication of+ actual@EX_APPLICATION{} -> do+ actual.expr `shouldBe` exGlobal+ actual.space `shouldBe` NO_SPACE+ actual.eol `shouldBe` EOL+ actual.tab `shouldBe` TAB 1+ actual.argument `shouldBe` argumentVal+ actual.eol' `shouldBe` EOL+ actual.tab' `shouldBe` TAB 0+ actual.indent `shouldBe` 1+ _ -> expectationFailure "Expected EX_APPLICATION"+ case exString of+ actual@EX_STRING{} -> do+ actual.str `shouldBe` "hi"+ actual.tab `shouldBe` TAB 0+ actual.rhos `shouldBe` []+ _ -> expectationFailure "Expected EX_STRING"+ case exNumber of+ actual@EX_NUMBER{} -> do+ actual.num `shouldBe` 5+ actual.tab `shouldBe` TAB 0+ actual.rhos `shouldBe` []+ _ -> expectationFailure "Expected EX_NUMBER"+ case exNonFinite of+ actual@EX_NONFINITE{} -> do+ actual.global `shouldBe` Φ+ actual.nonfinite `shouldBe` NfNan+ actual.tab `shouldBe` TAB 0+ actual.rhos `shouldBe` []+ _ -> expectationFailure "Expected EX_NONFINITE"+ case exMeta of+ actual@EX_META{} ->+ actual.meta `shouldBe` metaVal+ _ -> expectationFailure "Expected EX_META"+ case exPhiMeet of+ actual@EX_PHI_MEET{} -> do+ actual.prefix `shouldBe` Just "p"+ actual.idx `shouldBe` 1+ actual.expr `shouldBe` exGlobal+ _ -> expectationFailure "Expected EX_PHI_MEET"+ case exBytes of+ actual@EX_BYTES{} ->+ actual.bytes `shouldBe` BT_ONE "40"+ _ -> expectationFailure "Expected EX_BYTES" shouldShowAndEqSelf "EX_GLOBAL" exGlobal shouldShowAndEqSelf "EX_XI" exXi shouldShowAndEqSelf "EX_ATTR" exAttr@@ -705,13 +804,34 @@ atDelta = AT_DELTA{delta = DELTA} atMeta = AT_META{meta = metaVal} atRest = AT_REST{dots = DOTS}- atLabel.label `shouldBe` "x"- atRho.rho `shouldBe` RHO- atPhi.phi `shouldBe` PHI- atLambda.lambda `shouldBe` LAMBDA- atDelta.delta `shouldBe` DELTA- atMeta.meta `shouldBe` metaVal- atRest.dots `shouldBe` DOTS+ case atLabel of+ actual@AT_LABEL{} ->+ actual.label `shouldBe` "x"+ _ -> expectationFailure "Expected AT_LABEL"+ case atRho of+ actual@AT_RHO{} ->+ actual.rho `shouldBe` RHO+ _ -> expectationFailure "Expected AT_RHO"+ case atPhi of+ actual@AT_PHI{} ->+ actual.phi `shouldBe` PHI+ _ -> expectationFailure "Expected AT_PHI"+ case atLambda of+ actual@AT_LAMBDA{} ->+ actual.lambda `shouldBe` LAMBDA+ _ -> expectationFailure "Expected AT_LAMBDA"+ case atDelta of+ actual@AT_DELTA{} ->+ actual.delta `shouldBe` DELTA+ _ -> expectationFailure "Expected AT_DELTA"+ case atMeta of+ actual@AT_META{} ->+ actual.meta `shouldBe` metaVal+ _ -> expectationFailure "Expected AT_META"+ case atRest of+ actual@AT_REST{} ->+ actual.dots `shouldBe` DOTS+ _ -> expectationFailure "Expected AT_REST" shouldShowAndEqSelf "AT_LABEL" atLabel shouldShowAndEqSelf "AT_RHO" atRho shouldShowAndEqSelf "AT_PHI" atPhi@@ -730,8 +850,14 @@ let bindingEmpty = BI_EMPTY{tab = TAB 0} stBinding = ST_BINDING{binding = bindingEmpty} stAttributes = ST_ATTRIBUTES{attrs = [AT_LABEL "x"]}- stBinding.binding `shouldBe` bindingEmpty- stAttributes.attrs `shouldBe` [AT_LABEL "x"]+ case stBinding of+ actual@ST_BINDING{} ->+ actual.binding `shouldBe` bindingEmpty+ _ -> expectationFailure "Expected ST_BINDING"+ case stAttributes of+ actual@ST_ATTRIBUTES{} ->+ actual.attrs `shouldBe` [AT_LABEL "x"]+ _ -> expectationFailure "Expected ST_ATTRIBUTES" shouldShowAndEqSelf "ST_BINDING" stBinding shouldShowAndEqSelf "ST_ATTRIBUTES" stAttributes @@ -754,9 +880,18 @@ idxMeta = IDX_META{meta = metaVal} lengthVal = LENGTH{binding = bindingEmpty} literalVal = LITERAL{num = 5}- idxMeta.meta `shouldBe` metaVal- lengthVal.binding `shouldBe` bindingEmpty- literalVal.num `shouldBe` 5+ case idxMeta of+ actual@IDX_META{} ->+ actual.meta `shouldBe` metaVal+ _ -> expectationFailure "Expected IDX_META"+ case lengthVal of+ actual@LENGTH{} ->+ actual.binding `shouldBe` bindingEmpty+ _ -> expectationFailure "Expected LENGTH"+ case literalVal of+ actual@LITERAL{} ->+ actual.num `shouldBe` 5+ _ -> expectationFailure "Expected LITERAL" shouldShowAndEqSelf "IDX_META" idxMeta shouldShowAndEqSelf "LENGTH" lengthVal shouldShowAndEqSelf "LITERAL" literalVal@@ -768,9 +903,18 @@ cmpAttr = CMP_ATTR{attr = attrLabel} cmpExpr = CMP_EXPR{expr = exprGlobal} cmpNum = CMP_NUM{num = LITERAL 5}- cmpAttr.attr `shouldBe` attrLabel- cmpExpr.expr `shouldBe` exprGlobal- cmpNum.num `shouldBe` LITERAL 5+ case cmpAttr of+ actual@CMP_ATTR{} ->+ actual.attr `shouldBe` attrLabel+ _ -> expectationFailure "Expected CMP_ATTR"+ case cmpExpr of+ actual@CMP_EXPR{} ->+ actual.expr `shouldBe` exprGlobal+ _ -> expectationFailure "Expected CMP_EXPR"+ case cmpNum of+ actual@CMP_NUM{} ->+ actual.num `shouldBe` LITERAL 5+ _ -> expectationFailure "Expected CMP_NUM" shouldShowAndEqSelf "CMP_ATTR" cmpAttr shouldShowAndEqSelf "CMP_EXPR" cmpExpr shouldShowAndEqSelf "CMP_NUM" cmpNum@@ -789,22 +933,46 @@ coMatches = CO_MATCHES{regex = "x*", expr = exprGlobal} coPartOf = CO_PART_OF{expr = exprGlobal, binding = bindingEmpty} coDisjoint = CO_DISJOINT{attrs = [attrLabel], groups = [bindingEmpty]}- coBelongs.attr `shouldBe` attrLabel- coBelongs.belongs `shouldBe` IN- coBelongs.set `shouldBe` ST_BINDING bindingEmpty- coLogic.conditions `shouldBe` [CO_EMPTY]- coLogic.operator `shouldBe` AND- coNf.expr `shouldBe` exprGlobal- coNot.condition `shouldBe` CO_EMPTY- coCompare.left `shouldBe` cmpAttr- coCompare.equal `shouldBe` EQUAL- coCompare.right `shouldBe` cmpAttr- coMatches.regex `shouldBe` "x*"- coMatches.expr `shouldBe` exprGlobal- coPartOf.expr `shouldBe` exprGlobal- coPartOf.binding `shouldBe` bindingEmpty- coDisjoint.attrs `shouldBe` [attrLabel]- coDisjoint.groups `shouldBe` [bindingEmpty]+ case coBelongs of+ actual@CO_BELONGS{} -> do+ actual.attr `shouldBe` attrLabel+ actual.belongs `shouldBe` IN+ actual.set `shouldBe` ST_BINDING bindingEmpty+ _ -> expectationFailure "Expected CO_BELONGS"+ case coLogic of+ actual@CO_LOGIC{} -> do+ actual.conditions `shouldBe` [CO_EMPTY]+ actual.operator `shouldBe` AND+ _ -> expectationFailure "Expected CO_LOGIC"+ case coNf of+ actual@CO_NF{} ->+ actual.expr `shouldBe` exprGlobal+ _ -> expectationFailure "Expected CO_NF"+ case coNot of+ actual@CO_NOT{} ->+ actual.condition `shouldBe` CO_EMPTY+ _ -> expectationFailure "Expected CO_NOT"+ case coCompare of+ actual@CO_COMPARE{} -> do+ actual.left `shouldBe` cmpAttr+ actual.equal `shouldBe` EQUAL+ actual.right `shouldBe` cmpAttr+ _ -> expectationFailure "Expected CO_COMPARE"+ case coMatches of+ actual@CO_MATCHES{} -> do+ actual.regex `shouldBe` "x*"+ actual.expr `shouldBe` exprGlobal+ _ -> expectationFailure "Expected CO_MATCHES"+ case coPartOf of+ actual@CO_PART_OF{} -> do+ actual.expr `shouldBe` exprGlobal+ actual.binding `shouldBe` bindingEmpty+ _ -> expectationFailure "Expected CO_PART_OF"+ case coDisjoint of+ actual@CO_DISJOINT{} -> do+ actual.attrs `shouldBe` [attrLabel]+ actual.groups `shouldBe` [bindingEmpty]+ _ -> expectationFailure "Expected CO_DISJOINT" shouldShowAndEqSelf "CO_BELONGS" coBelongs shouldShowAndEqSelf "CO_LOGIC" coLogic shouldShowAndEqSelf "CO_NF" coNf@@ -823,10 +991,22 @@ argAttr = ARG_ATTR{attr = attrLabel} argBinding = ARG_BINDING{binding = bindingEmpty} argBytes = ARG_BYTES{bytes = BT_ONE "40"}- argExpr.expr `shouldBe` exprGlobal- argAttr.attr `shouldBe` attrLabel- argBinding.binding `shouldBe` bindingEmpty- argBytes.bytes `shouldBe` BT_ONE "40"+ case argExpr of+ actual@ARG_EXPR{} ->+ actual.expr `shouldBe` exprGlobal+ _ -> expectationFailure "Expected ARG_EXPR"+ case argAttr of+ actual@ARG_ATTR{} ->+ actual.attr `shouldBe` attrLabel+ _ -> expectationFailure "Expected ARG_ATTR"+ case argBinding of+ actual@ARG_BINDING{} ->+ actual.binding `shouldBe` bindingEmpty+ _ -> expectationFailure "Expected ARG_BINDING"+ case argBytes of+ actual@ARG_BYTES{} ->+ actual.bytes `shouldBe` BT_ONE "40"+ _ -> expectationFailure "Expected ARG_BYTES" shouldShowAndEqSelf "ARG_EXPR" argExpr shouldShowAndEqSelf "ARG_ATTR" argAttr shouldShowAndEqSelf "ARG_BINDING" argBinding
test/Fixtures.hs view
@@ -115,21 +115,21 @@ recorded' :: Bool -> (SaveEvalFunc -> IO a) -> IO (a, String) recorded' hidden action = withTemp "phino-protocol-.txt" BS.empty $ \path -> do- answer <- withEvalFunc Nothing (Just path) (printing hidden) action+ answer <- withEvalFunc Nothing (Just path) False (printing hidden) action written <- withoutTotals <$> readUtf8 path pure (answer, written) recordedXml :: (SaveEvalFunc -> IO a) -> IO (a, String) recordedXml action = withTemp "phino-protocol-.xml" BS.empty $ \path -> do- answer <- withEvalFunc (Just path) Nothing (printing False) action+ answer <- withEvalFunc (Just path) Nothing False (printing False) action written <- readProtocol path pure (answer, written) recordedWhole :: (SaveEvalFunc -> IO a) -> IO (a, String) recordedWhole action = withTemp "phino-protocol-.xml" BS.empty $ \path -> do- answer <- withEvalFunc (Just path) Nothing (printing False) action+ answer <- withEvalFunc (Just path) Nothing False (printing False) action written <- readUtf8 path pure (answer, written)
+ test/SidesSpec.hs view
@@ -0,0 +1,28 @@+{-# LANGUAGE OverloadedStrings #-}++-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+-- SPDX-License-Identifier: MIT++module SidesSpec where++import AST+import Control.Monad (foldM)+import Sides (gauge, named, resolver, sides)+import Test.Hspec (Spec, describe, it, shouldBe)++spec :: Spec+spec =+ describe "gauge" $ do+ it "keeps the depth of every name it hands out" $ do+ store <- sides+ top <- foldM (\prev _ -> named store (ExApplication (ExApplication (ExDispatch ExRoot (AtLabel "f")) (ArTau (AtLabel "a") prev)) (ArTau (AtLabel "b") prev))) ExXi [1 .. 30 :: Int]+ depth <- gauge store+ look <- resolver store+ (deepness look depth top, deepness look (const Nothing) (ExDispatch ExRoot (AtLabel "q"))) `shouldBe` (61, 1)+ it "measures a name as the term it stands for" $ do+ store <- sides+ inner <- named store (ExApplication (ExDispatch ExRoot (AtLabel "g")) (ArTau (AtLabel "x") ExXi))+ outer <- named store (ExDispatch inner (AtLabel "q"))+ depth <- gauge store+ look <- resolver store+ deepness look depth outer `shouldBe` deepness (const Nothing) (const Nothing) (ExDispatch (ExApplication (ExDispatch ExRoot (AtLabel "g")) (ArTau (AtLabel "x") ExXi)) (AtLabel "q"))
+ test/SodgSpec.hs view
@@ -0,0 +1,148 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}++-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com+-- SPDX-License-Identifier: MIT++module SodgSpec where++import AST+import Control.Monad (forM_)+import Data.Aeson+import Data.List (nub)+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import Data.Yaml qualified as Yaml+import Files (allPathsIn)+import GHC.Generics (Generic)+import Grown (Grown (..))+import Parser (parseExpression, parseExpressionThrows)+import Printer (printExpression)+import Sodg+import System.FilePath+import Test.Hspec+import Test.Hspec.QuickCheck (prop)+import Test.QuickCheck (Property, conjoin, counterexample, (===))+import Text.Printf (printf)++data YamlPack = YamlPack+ { input :: String+ , output :: Maybe String+ , fails :: Maybe String+ }+ deriving (Generic, Show, FromJSON)++spec :: Spec+spec = do+ describe "sodg packs" $ do+ let resources = "test-resources/sodg-packs"+ packs <- runIO (allPathsIn resources)+ forM_+ packs+ ( \pth -> it (makeRelative resources pth) $ do+ YamlPack{..} <- Yaml.decodeFileThrow pth+ expr <- parseExpressionThrows input+ case (output, fails, commands expr) of+ (Just expected, Nothing, Right graph) -> printCommands graph `shouldBe` expected+ (Just _, Nothing, Left err) -> expectationFailure (printf "The term failed with '%s', while the pack expects commands" (show err))+ (Nothing, Just message, Left err) -> show err `shouldContain` message+ (Nothing, Just _, Right graph) -> expectationFailure (printf "The term gave commands, while the pack expects it to fail:\n%s" (printCommands graph))+ _ -> expectationFailure "The pack holds neither a single 'output' nor a single 'fails'"+ )++ describe "sodg keeps its four promises on any program" $ do+ prop "every F, D and A makes a fresh name and a command uses only names made above it" $ \(Grown grown) ->+ let expr = scrubbed False grown+ in either (counterexample "the walk failed" . const False) (ordered expr) (commands expr)+ prop "every attached attribute of every formation gets exactly one P" $ \(Grown grown) ->+ let expr = scrubbed False grown+ in either (counterexample "the walk failed" . const False) (attached expr) (commands expr)+ prop "the same input gives the same output, byte for byte" $ \(Grown grown) ->+ let expr = scrubbed False grown+ in case parseExpression (printExpression expr) of+ Left err -> counterexample err False+ Right parsed -> either show printCommands (commands parsed) === either show printCommands (commands expr)++ordered :: Expression -> [Command] -> Property+ordered expr graph = counterexample (printExpression expr ++ "\n" ++ printCommands graph) (go [] graph)+ where+ go :: [Int] -> [Command] -> Bool+ go _ [] = True+ go made (cmd : rest) =+ all (`elem` made) (used cmd)+ && all (`notElem` made) (defined cmd)+ && go (defined cmd ++ made) rest+ defined :: Command -> [Int]+ defined = \case+ Formation self _ -> [self]+ Dispatch self _ _ -> [self]+ Application self _ _ _ -> [self]+ _ -> []+ used :: Command -> [Int]+ used = \case+ Formation _ _ -> []+ Dispatch _ base _ -> [base]+ Application _ proto _ arg -> [proto, arg]+ Put self _ kid -> [self, kid]+ Delta self _ -> [self]+ Lambda self _ -> [self]++attached :: Expression -> [Command] -> Property+attached expr graph =+ counterexample+ (printExpression expr ++ "\n" ++ printCommands graph)+ ( conjoin+ [ length puts === taus expr+ , nub puts === puts+ , counterexample "a P puts an attribute its F does not list" (all listed puts)+ , length [() | Formation _ _ <- graph] === formations expr + (case expr of ExFormation _ -> 0; _ -> 1)+ ]+ )+ where+ puts :: [(Int, Text)]+ puts = [(self, attr) | Put self attr _ <- graph]+ listed :: (Int, Text) -> Bool+ listed (self, attr) = or [attr `elem` names | Formation self' names <- graph, self' == self]+ taus :: Expression -> Int+ taus = \case+ ExFormation bds -> sum [1 + taus inner | BiTau _ inner <- bds]+ ExDispatch inner _ -> taus inner+ ExApplication inner arg -> taus inner + taus (held arg)+ _ -> 0+ formations :: Expression -> Int+ formations = \case+ ExFormation bds -> 1 + sum [formations inner | BiTau _ inner <- bds]+ ExDispatch inner _ -> formations inner+ ExApplication inner arg -> formations inner + formations (held arg)+ _ -> 0+ held :: Argument -> Expression+ held (ArTau _ inner) = inner+ held (ArAlpha _ inner) = inner++scrubbed :: Bool -> Expression -> Expression+scrubbed inside = \case+ ExFormation bds -> ExFormation (mapMaybe binding bds)+ ExDispatch inner attr -> ExDispatch (scrubbed inside inner) (label attr)+ ExApplication inner (ArTau attr arg) -> ExApplication (scrubbed inside inner) (ArTau (label attr) (scrubbed inside arg))+ ExApplication inner (ArAlpha alpha arg) -> ExApplication (scrubbed inside inner) (ArAlpha (indexed alpha) (scrubbed inside arg))+ ExXi | inside -> ExXi+ _ -> ExRoot+ where+ binding :: Binding -> Maybe Binding+ binding = \case+ BiTau (AtMeta _) _ -> Nothing+ BiVoid (AtMeta _) -> Nothing+ BiTau attr inner -> Just (BiTau attr (scrubbed True inner))+ BiDelta (BtMeta _) -> Just (BiDelta BtEmpty)+ BiLambda (FnMeta _) -> Just (BiLambda (Function "L_scrubbed"))+ BiMeta _ -> Nothing+ other -> Just other+ indexed :: Alpha -> Alpha+ indexed (AlMeta _) = Alpha 0+ indexed alpha = alpha+ label :: Attribute -> Attribute+ label (AtMeta _) = AtLabel "scrubbed"+ label attr = attr