{-# LANGUAGE DeriveAnyClass #-}{-# LANGUAGE DeriveGeneric #-}{-# LANGUAGE LambdaCase #-}{-# LANGUAGE OverloadedStrings #-}{-# OPTIONS_GHC -Wno-orphans #-}-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com-- SPDX-License-Identifier: MITmodule RewriterSpec whereimport AST (Argument (ArTau), Attribute (AtLabel, AtRho), Binding (BiMeta, BiTau, BiVoid), Expression (ExApplication, ExDispatch, ExFormation, ExRoot, ExTermination, ExXi))import Control.Exception (IOException, SomeException, throw)import Control.Monad (forM_, unless)import Data.Aesonimport Data.Char (isSpace)import Data.IORef (modifyIORef', newIORef, readIORef)import Data.List (isInfixOf, nub)import Data.List.NonEmpty qualified as NEimport Data.Set qualified as Setimport Data.Yaml qualified as Yamlimport Deps (Judgment (..), dontSaveMade, dontSaveStep)import Engine (Engine (_matching, _normal), building, stepOf)import Files (allPathsIn, ensuredFile)import Fixtures (linked)import Functions (buildTerm)import GHC.Genericsimport Must (Must (..))import Parser (Form (MONOFORM), parseExpressionThrows, parseExpressionThrows')import Printer (printExpression)import Rewriter (RewriteContext (RewriteContext), direct, every, fast, rewrite)import Rule (RuleContext (RuleContext), Step (Step, _applied))import System.FilePath (makeRelative, replaceExtension, (</>))import Tau (seedTaus)import Test.Hspec (Spec, describe, expectationFailure, it, pending, runIO, shouldBe, shouldReturn, shouldSatisfy, shouldThrow)import Yaml (normalizationRules)import Yaml qualified as Ydata Rules = Rules { basic :: Maybe [String] , custom :: Maybe [Y.Rule] } deriving (Generic, FromJSON, Show)data YamlPack = YamlPack { input :: String , output :: String , rules :: Maybe Rules , skip :: Maybe Bool , repeat_ :: Maybe Int , must :: Maybe Int , normalize :: Maybe Bool } deriving (Generic, Show)instance FromJSON YamlPack where parseJSON = genericParseJSON defaultOptions { fieldLabelModifier = \case "repeat_" -> "repeat" other -> other }yamlPack :: FilePath -> IO YamlPackyamlPack = Yaml.decodeFileThrownoSpaces :: String -> StringnoSpaces = filter (not . isSpace)spec :: Specspec = do describe "--max-cycles and --max-depth limits" $ forM_ [ ( "throws with --depth-sensitive once --max-cycles is reached" , "⟦ t ↦ ⊥.a ⟧" , (5, 0, True) , Left "--max-cycles=0" ) , ( "stops silently without --depth-sensitive once --max-cycles is reached" , "⟦ t ↦ ⊥.a ⟧" , (5, 0, False) , Right snd ) , ( "throws with --depth-sensitive once --max-depth is reached for a rule" , "⟦ t ↦ ⊥.a ⟧" , (0, 5, True) , Left "--max-depth=0" ) , ( "does not throw without --depth-sensitive once --max-depth is reached for a rule" , "⟦ t ↦ ⊥.a ⟧" , (0, 5, False) , Right (\(rewrittens, _) -> fst (NE.last rewrittens) == ExFormation [BiTau (AtLabel "t") (ExDispatch ExTermination (AtLabel "a"))]) ) , ( "throws with --depth-sensitive when a rule still applies after --max-depth steps" , "⟦ t ↦ ⊥.a.b ⟧" , (1, 5, True) , Left "--max-depth=1" ) , ( "does not throw with --depth-sensitive when a rule finishes in exactly --max-depth steps" , "⟦ t ↦ ⊥.a ⟧" , (1, 5, True) , Right (\(rewrittens, _) -> fst (NE.last rewrittens) == ExFormation [BiTau (AtLabel "t") ExTermination]) ) , ( "does not throw with --depth-sensitive when rewriting finishes in exactly --max-cycles cycles" , "⟦ t ↦ ⊥.a ⟧" , (5, 1, True) , Right (\(rewrittens, _) -> fst (NE.last rewrittens) == ExFormation [BiTau (AtLabel "t") ExTermination]) ) , ( "does not exceed without --depth-sensitive when rewriting finishes in exactly --max-cycles cycles" , "⟦ t ↦ ⊥.a ⟧" , (5, 1, False) , Right (\(_, exceeded) -> not exceeded) ) ] ( \(desc, input', (maxDepth, maxCycles, depthSensitive), expected) -> it desc $ do expr <- parseExpressionThrows input' let action = rewrite expr (map (stepOf linked) normalizationRules) (RewriteContext ExRoot maxDepth maxCycles depthSensitive Nothing (building linked) (_normal linked) (_matching linked) MtDisabled Nothing dontSaveStep dontSaveMade) case expected of Left fragment -> action `shouldThrow` (\exc -> fragment `isInfixOf` show (exc :: SomeException)) Right predicate -> do result <- action result `shouldSatisfy` predicate ) describe "--max-cycles at the boundary, with rules that keep applying" $ do let steps = [ direct "te" False (\_ expr -> [ExXi | ExTermination <- [expr]]) , direct "ex" False (\_ expr -> [ExRoot | ExXi <- [expr]]) , direct "rt" False (\_ expr -> [ExTermination | ExRoot <- [expr]]) ] context depthSensitive = RewriteContext ExRoot 5 1 depthSensitive Nothing (building linked) (_normal linked) (every steps) MtDisabled Nothing dontSaveStep dontSaveMade it "exceeds without --depth-sensitive when a rule still applies at --max-cycles" $ do (_, exceeded) <- rewrite ExXi steps (context False) exceeded `shouldBe` True it "throws with --depth-sensitive when a rule still applies at --max-cycles" $ rewrite ExXi steps (context True) `shouldThrow` (\exc -> "--max-cycles=1" `isInfixOf` show (exc :: SomeException)) describe "a rule that raises while applicable is probed at the boundary" $ do let steps = [Step "boom" (\_ _ -> throw (userError "boom"))] context depthSensitive = RewriteContext ExRoot 5 0 depthSensitive Nothing (building linked) (_normal linked) (every steps) MtDisabled Nothing dontSaveStep dontSaveMade it "treats the raise as not applicable without --depth-sensitive" $ do (_, exceeded) <- rewrite ExXi steps (context False) exceeded `shouldBe` False it "propagates the raise with --depth-sensitive" $ rewrite ExXi steps (context True) `shouldThrow` (\exc -> "boom" `isInfixOf` show (exc :: IOException)) describe "--must once --max-cycles stops the run" $ forM_ [ ( "throws when --must demands more cycles than --max-cycles allowed" , MtExact 3 , Left "--must=3" ) , ( "throws when the lower bound of --must lies above --max-cycles" , MtRange (Just 2) Nothing , Left "--must=2.." ) , ( "does not throw when --max-cycles stops the run inside the range of --must" , MtRange (Just 1) (Just 4) , Right snd ) ] ( \(desc, must', expected) -> it desc $ do expr <- parseExpressionThrows "⟦ t ↦ ⊥.a.b.c ⟧" let action = rewrite expr (map (stepOf linked) normalizationRules) (RewriteContext ExRoot 1 1 False Nothing (building linked) (_normal linked) (_matching linked) must' Nothing dontSaveStep dontSaveMade) case expected of Left fragment -> action `shouldThrow` (\exc -> fragment `isInfixOf` show (exc :: SomeException)) Right predicate -> do result <- action result `shouldSatisfy` predicate ) describe "judges the steps it takes" $ it "takes every step by normalization" $ do expr <- parseExpressionThrows "⟦ k ↦ ⟦ w ↦ ⟦ Δ ⤍ 1F- ⟧ ⟧.w ⟧" (rewrittens, _) <- rewrite expr (map (stepOf linked) normalizationRules) (RewriteContext ExRoot 25 25 False Nothing (building linked) (_normal linked) (_matching linked) MtDisabled Nothing dontSaveStep dontSaveMade) nub [judgment | (_, Just (judgment, _)) <- NE.toList rewrittens] `shouldBe` [Normalization] describe "tells what an application made" $ do it "tells the application a step turned into an object, beside the object" $ do made <- newIORef [] _ <- rewrite (ExApplication (ExFormation [BiVoid (AtLabel "ж")]) (ArTau (AtLabel "ж") (ExFormation []))) (map (stepOf linked) normalizationRules) (RewriteContext ExRoot 25 25 False Nothing (building linked) (_normal linked) (_matching linked) MtDisabled Nothing dontSaveStep (\redex copy -> modifyIORef' made ((redex, copy) :))) readIORef made `shouldReturn` [(ExApplication (ExFormation [BiVoid (AtLabel "ж")]) (ArTau (AtLabel "ж") (ExFormation [])), ExFormation [BiTau (AtLabel "ж") (ExFormation [])])] it "tells an application a step left the object it was" $ do made <- newIORef [] _ <- rewrite (ExApplication (ExFormation [BiTau AtRho (ExFormation []), BiTau (AtLabel "ъ") (ExFormation [])]) (ArTau AtRho (ExFormation [BiVoid (AtLabel "ц")]))) (map (stepOf linked) normalizationRules) (RewriteContext ExRoot 25 25 False Nothing (building linked) (_normal linked) (_matching linked) MtDisabled Nothing dontSaveStep (\redex copy -> modifyIORef' made ((redex, copy) :))) readIORef made `shouldReturn` [(ExApplication (ExFormation [BiTau AtRho (ExFormation []), BiTau (AtLabel "ъ") (ExFormation [])]) (ArTau AtRho (ExFormation [BiVoid (AtLabel "ц")])), ExFormation [BiTau AtRho (ExFormation []), BiTau (AtLabel "ъ") (ExFormation [])])] it "tells the ρ a dispatch fills, beside the object it made" $ do made <- newIORef [] _ <- rewrite (ExApplication (ExFormation [BiVoid AtRho, BiVoid (AtLabel "щ")]) (ArTau AtRho (ExFormation [BiTau (AtLabel "ё") (ExFormation [])]))) (map (stepOf linked) normalizationRules) (RewriteContext ExRoot 25 25 False Nothing (building linked) (_normal linked) (_matching linked) MtDisabled Nothing dontSaveStep (\redex copy -> modifyIORef' made ((redex, copy) :))) readIORef made `shouldReturn` [(ExApplication (ExFormation [BiVoid AtRho, BiVoid (AtLabel "щ")]) (ArTau AtRho (ExFormation [BiTau (AtLabel "ё") (ExFormation [])])), ExFormation [BiTau AtRho (ExFormation [BiTau (AtLabel "ё") (ExFormation [])]), BiVoid (AtLabel "щ")])] it "tells the dispatch a step took into an object" $ do made <- newIORef [] _ <- rewrite (ExDispatch (ExFormation [BiTau (AtLabel "ыж") (ExFormation [BiVoid (AtLabel "ю")])]) (AtLabel "ыж")) (map (stepOf linked) normalizationRules) (RewriteContext ExRoot 25 25 False Nothing (building linked) (_normal linked) (_matching linked) MtDisabled Nothing dontSaveStep (\redex copy -> modifyIORef' made ((redex, copy) :))) readIORef made >>= (`shouldSatisfy` elem (ExDispatch (ExFormation [BiTau (AtLabel "ыж") (ExFormation [BiVoid (AtLabel "ю")])]) (AtLabel "ыж")) . map fst) describe "rewrites by a locator" $ do it "rewrites the located part step after step" $ do expr <- parseExpressionThrows "⟦ t ↦ ⊥.a.b, u ↦ ⊥.c ⟧" (rewrittens, _) <- rewrite expr (map (stepOf linked) normalizationRules) (RewriteContext (ExDispatch ExRoot (AtLabel "t")) 25 25 False Nothing (building linked) (_normal linked) (_matching linked) MtDisabled Nothing dontSaveStep dontSaveMade) fst (NE.last rewrittens) `shouldBe` ExFormation [BiTau (AtLabel "t") ExTermination, BiTau (AtLabel "u") (ExDispatch ExTermination (AtLabel "c"))] it "fails on a locator that points nowhere even when no rule runs" $ do expr <- parseExpressionThrows "⟦ t ↦ ⊥.a ⟧" rewrite expr [] (RewriteContext (ExDispatch ExRoot (AtLabel "w")) 25 25 False Nothing (building linked) (_normal linked) (_matching linked) MtDisabled Nothing dontSaveStep dontSaveMade) `shouldThrow` (\exc -> "Can't find object by locator" `isInfixOf` show (exc :: SomeException)) describe "catches a loop that comes back to the term the run started from" $ do let steps = [ direct "a-to-b" False (\_ expr -> [ExFormation [BiTau (AtLabel "b") ExXi] | ExFormation [BiTau (AtLabel "a") ExXi] <- [expr]]) , direct "b-to-a" False (\_ expr -> [ExFormation [BiTau (AtLabel "a") ExXi] | ExFormation [BiTau (AtLabel "b") ExXi] <- [expr]]) ] context cycles locator some = RewriteContext locator 25 cycles False Nothing (building linked) (_normal linked) (every some) MtDisabled Nothing dontSaveStep dontSaveMade looping exc = "looping" `isInfixOf` show (exc :: SomeException) it "catches a loop that comes back to the term the run started from" $ do forM_ [ (ExFormation [BiTau (AtLabel "a") ExXi], steps) , (ExFormation [BiTau (AtLabel "b") ExXi], steps) , (ExFormation [BiTau (AtLabel "a") ExXi], reverse steps) , (ExFormation [BiTau (AtLabel "b") ExXi], reverse steps) ] (\(start, some) -> rewrite start some (context 25 ExRoot some) `shouldThrow` looping) rewrite (ExFormation [BiTau (AtLabel "x") (ExFormation [BiTau (AtLabel "a") ExXi])]) steps (context 1 (ExDispatch ExRoot (AtLabel "x")) steps) `shouldThrow` looping describe "rewrite packs" $ do let resources = "test-resources/rewriter-packs" packs <- runIO (allPathsIn resources) forM_ packs ( \pth -> it (makeRelative resources pth) $ do pack <- yamlPack pth let normalize' = case normalize pack of Just _ -> True _ -> False repeat' = if normalize' then 50 else case repeat_ pack of Just num -> num _ -> 1 must' = case must pack of Just num -> MtExact num _ -> MtDisabled case skip pack of Just True -> pending _ -> do expr <- parseExpressionThrows' MONOFORM (input pack) seedTaus expr rules' <- case rules pack of Just _rules -> case custom _rules of Just custom' -> pure custom' _ -> case basic _rules of Just basic' -> mapM ( \name -> do yaml <- ensuredFile ("resources/normalize" </> replaceExtension name ".yaml") Y.yamlRule yaml ) basic' _ -> pure [] Nothing -> if normalize' then pure normalizationRules else pure [] let steps = map (stepOf linked) rules' (rewrittens, _) <- rewrite expr steps ( RewriteContext ExRoot repeat' repeat' False Nothing (building linked) (_normal linked) (every steps) must' Nothing dontSaveStep dontSaveMade ) let (rewritten, _) = NE.last rewrittens result' <- parseExpressionThrows' MONOFORM (output pack) unless (rewritten == result') $ expectationFailure ( "Wrong rewritten expression. Expected:\n" ++ printExpression result' ++ "\nGot:\n" ++ printExpression rewritten ) ) describe "asks which steps match" $ do it "does not try a step the matching does not name" $ (fst . NE.last . fst <$> rewrite ExXi [direct "qv" False (\_ expr -> [ExRoot | ExXi <- [expr]])] (RewriteContext ExRoot 25 25 False Nothing (building linked) (_normal linked) (\_ _ -> Set.empty) MtDisabled Nothing dontSaveStep dontSaveMade)) `shouldReturn` ExXi it "asks the matching again once a step changed the term" $ (fst . NE.last . fst <$> rewrite ExXi [direct "xr" False (\_ expr -> [ExRoot | ExXi <- [expr]]), direct "rt" False (\_ expr -> [ExTermination | ExRoot <- [expr]])] (RewriteContext ExRoot 25 1 False Nothing (building linked) (_normal linked) (\_ expr -> Set.fromList [idx | (idx, ptn) <- [(0, ExXi), (1, ExRoot)], ptn == expr]) MtDisabled Nothing dontSaveStep dontSaveMade)) `shouldReturn` ExTermination describe "every" $ it "names each of the steps it is handed" $ every [Step "wd" (\_ _ -> pure Nothing), Step "ok" (\_ _ -> pure Nothing), Step "wd" (\_ _ -> pure Nothing)] Nothing (ExDispatch ExXi (AtLabel "pz")) `shouldBe` Set.fromList [0, 1, 2] describe "direct" $ do it "rewrites every place the function matches at" $ fmap fst <$> _applied (direct "tx" False (\_ expr -> [ExRoot | ExXi <- [expr]])) (RuleContext buildTerm Nothing (const True)) (ExDispatch (ExApplication ExXi (ArTau (AtLabel "o") ExXi)) (AtLabel "m")) `shouldReturn` Just (ExDispatch (ExApplication ExRoot (ArTau (AtLabel "o") ExRoot)) (AtLabel "m")) it "tells every place it rewrote, beside what it rewrote it to" $ fmap snd <$> _applied (direct "tq" False (\_ expr -> [ExRoot | ExXi <- [expr]])) (RuleContext buildTerm Nothing (const True)) (ExApplication ExXi (ArTau (AtLabel "ё") ExXi)) `shouldReturn` Just [(ExXi, ExRoot), (ExXi, ExRoot)] it "tells it matched nowhere" $ _applied (direct "tx" False (\_ expr -> [ExRoot | ExXi <- [expr]])) (RuleContext buildTerm Nothing (const True)) (ExDispatch ExTermination (AtLabel "m")) `shouldReturn` Nothing it "hands the world to the function" $ fmap fst <$> _applied (direct "tw" False (\universe expr -> [world | ExXi <- [expr], Just world <- [universe]])) (RuleContext buildTerm (Just ExTermination) (const True)) ExXi `shouldReturn` Just ExTermination describe "fast" $ do it "holds for a formation rewritten between the same two meta bindings" $ fast (ExFormation [BiMeta "B1", BiVoid (AtLabel "j"), BiMeta "B2"]) (ExFormation [BiMeta "B1", BiVoid (AtLabel "k"), BiMeta "B2"]) `shouldBe` True it "fails for a formation rewritten into a dispatch" $ fast (ExFormation [BiMeta "B1", BiVoid (AtLabel "j"), BiMeta "B2"]) (ExDispatch ExXi (AtLabel "k")) `shouldBe` False