{-# LANGUAGE DeriveAnyClass #-}{-# LANGUAGE DeriveGeneric #-}{-# LANGUAGE OverloadedRecordDot #-}{-# LANGUAGE OverloadedStrings #-}-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com-- SPDX-License-Identifier: MITmodule RuleSpec whereimport AST (Argument (..), Attribute (..), Binding (..), Bytes (..), Expression (..), Function (..), Slot (..), inert)import Builder (buildExpressionThrows)import Control.Exception (evaluate)import Control.Monadimport Data.Aesonimport Data.List (isInfixOf)import Data.Yaml qualified as Yimport Engine (Engine (_normal))import Files (allPathsIn)import Fixtures (linked)import Functions (buildTerm)import GHC.Genericsimport Logger (LogLevel (DEBUG, ERROR), setLogConfig)import Matcherimport Parser (Form (MONOFORM), parseExpressionThrows, parseExpressionThrows')import Printer (printSubsts)import Rule (RuleContext (RuleContext), isNF, matchExpressionWithRule, meetCondition, normal, normalHeld, redex)import System.FilePathimport System.IO (stderr)import System.IO.Silently (hCapture)import System.Timeout (timeout)import Test.Hspec (Spec, after_, describe, expectationFailure, it, runIO, shouldBe, shouldReturn, shouldSatisfy)import Yaml qualifieddata ConditionPack = ConditionPack { failure :: Maybe Bool , expression :: String , pattern :: Expression , condition :: Yaml.Condition } deriving (Generic, FromJSON, Show)spec :: Specspec = do describe "check conditions" $ do let resources = "test-resources/condition-packs" packs <- runIO (allPathsIn resources) forM_ packs ( \pth -> it (makeRelative resources pth) $ do pack <- Y.decodeFileThrow pth :: IO ConditionPack expr <- parseExpressionThrows' MONOFORM (expression pack) let matched = matchExpression (pattern pack) expr unless (matched /= []) (expectationFailure "List of matched substitutions is empty which is not expected") met <- meetCondition (condition pack) matched (RuleContext buildTerm Nothing (_normal linked) False) case failure pack of Just True -> unless (null met) ( expectationFailure $ "List of substitutions after condition check must be empty, but got:\n" ++ printSubsts matched ) _ -> when (null met) ( expectationFailure $ "List of substitution after condition check must be not empty\nOriginal substitutions:\n" ++ printSubsts matched ) ) describe "an 'or' condition does not depend on the order of its items" $ do let ctx = RuleContext buildTerm Nothing (_normal linked) False rule :: Yaml.Condition -> Yaml.Rule rule cond = Yaml.Rule "or-order" Nothing Nothing (ExFormation [BiTau (AtLabel "s") (ExMeta "e1")]) (ExFormation [BiTau (AtLabel "ok") (ExFormation [])]) (Just cond) Nothing Nothing term = ExFormation [BiTau (AtLabel "s") (ExFormation [BiVoid (AtLabel "q")])] inner = ExFormation [BiVoid (AtLabel "q")] raising = Yaml.Matches "x" (ExMeta "e1") met = Yaml.Eq (Yaml.CmpNum (Yaml.Literal 1)) (Yaml.CmpNum (Yaml.Literal 1)) unmatched = Yaml.Eq (Yaml.CmpNum (Yaml.Literal 1)) (Yaml.CmpNum (Yaml.Literal 2)) buildE1 cond = mapM (buildExpressionThrows (ExMeta "e1")) =<< matchExpressionWithRule term (rule cond) ctx it "keeps a later item met when an earlier one raises" $ buildE1 (Yaml.Or [raising, met]) `shouldReturn` [inner] it "keeps an earlier item met when a later one raises" $ buildE1 (Yaml.Or [met, raising]) `shouldReturn` [inner] it "keeps a last item met after a middle one raises" $ buildE1 (Yaml.Or [unmatched, raising, met]) `shouldReturn` [inner] it "stays not met when no item is met" $ buildE1 (Yaml.Or [raising, unmatched]) `shouldReturn` [] it "stays not met under 'not' when an item raises" $ buildE1 (Yaml.Not (Yaml.Or [raising, unmatched])) `shouldReturn` [] describe "isNF determines normal form" $ do let ctx = RuleContext buildTerm Nothing (_normal linked) False forM_ [ ("returns true for ExXi", ExXi, True) , ("returns true for ExRoot", ExRoot, True) , ("returns true for ExTermination", ExTermination, True) , ("returns true for dispatch on ExXi", ExDispatch ExXi (AtLabel "foo"), True) , ("returns true for dispatch on ExRoot", ExDispatch ExRoot (AtLabel "bar"), True) , ("returns false for dispatch on ExTermination", ExDispatch ExTermination (AtLabel "x"), False) , ("returns false for application on ExTermination", ExApplication ExTermination (ArTau (AtLabel "y") ExRoot), False) , ("returns true for empty formation", ExFormation [], True) , ("returns true for formation with only delta binding", ExFormation [BiDelta (BtMany ["00", "01"])], True) , ("returns true for formation with only void binding", ExFormation [BiVoid (AtLabel "x")], True) , ("returns true for formation with only lambda binding", ExFormation [BiLambda (Function "Func")], True) , ("returns false for formation with delta void and lambda", ExFormation [BiDelta (BtOne "FF"), BiVoid (AtLabel "y"), BiLambda (Function "G")], False) , ("returns false for formation with delta and lambda, which dl reduces", ExFormation [BiDelta (BtMany ["01"]), BiLambda (Function "Fn")], False) , ("returns true for a formation with a tau binding whose expression is already normal", ExFormation [BiTau (AtLabel "x") ExRoot], True) , ("returns false for a formation with a tau binding matching a normalization rule", ExFormation [BiTau (AtLabel "x") (ExDispatch ExTermination (AtLabel "y"))], False) , ("returns false for a dispatch whose body no rule of contextualization takes", ExDispatch (ExFormation [BiTau (AtLabel "kq") (ExDispatch (ExMeta "e5") (AtLabel "wb"))]) (AtLabel "kq"), False) ] (\(desc, expr, expected) -> it desc $ isNF expr ctx `shouldBe` expected) describe "tells a normal form of a chain of nested copies in time" $ do let chain :: Int -> Expression chain depth = iterate (ExApplication (ExFormation [BiVoid (AtLabel "x"), BiTau (AtLabel "y") (ExDispatch ExXi (AtLabel "x"))]) . ArTau (AtLabel "x")) (ExFormation [BiDelta (BtOne "00")]) !! depth forM_ [("the rules of YAML", normal), ("the engine linked", _normal linked)] $ \(name, test) -> it ("by " ++ name) $ timeout 10000000 (evaluate (test (chain 40))) `shouldReturn` Just False describe "matchExpressionWithRule via a 'where' extension or a φ-marker meta" $ do let ctx :: RuleContext ctx = RuleContext buildTerm Nothing (_normal linked) False joinRule :: Yaml.Rule joinRule = Yaml.Rule "extra-join-test" Nothing Nothing (ExFormation [BiMeta "B"]) (ExMeta "B") Nothing (Just [Yaml.Extra (Yaml.ArgBinding (BiMeta "J")) "join" [Yaml.ArgBinding (BiMeta "B")]]) Nothing cascadeRule :: Yaml.Rule cascadeRule = Yaml.Rule "extra-cascade-test" Nothing Nothing (ExMeta "e") (ExMeta "e") Nothing ( Just [ Yaml.Extra (Yaml.ArgExpression ExRoot) "random-tau" [] , Yaml.Extra (Yaml.ArgAttribute (AtMeta "J")) "random-tau" [] ] ) Nothing phiMeetRule :: Yaml.Rule phiMeetRule = Yaml.Rule "phimeet-n-test" Nothing Nothing (ExFormation [BiTau (AtLabel "x") (ExPhiMeet Nothing 0 (ExMeta "n1")), BiVoid AtRho]) (ExMeta "n1") Nothing Nothing Nothing phiAgainRule :: Yaml.Rule phiAgainRule = Yaml.Rule "phiagain-n-test" Nothing Nothing (ExFormation [BiTau (AtLabel "x") (ExPhiAgain Nothing 0 (ExMeta "n2")), BiVoid AtRho]) (ExMeta "n2") Nothing Nothing Nothing forM_ [ ( "binds a fresh meta from a bindings-list built by join()" , ExFormation [BiTau (AtLabel "x") ExRoot, BiVoid AtRho] , joinRule , True ) , ("drops a substitution once an earlier extension fails to name a meta", ExRoot, cascadeRule, False) , ( "finds an 'n' meta nested inside a φ-meet marker" , ExFormation [BiTau (AtLabel "x") (ExPhiMeet Nothing 0 ExRoot), BiVoid AtRho] , phiMeetRule , True ) , ( "finds an 'n' meta nested inside a φ-again marker" , ExFormation [BiTau (AtLabel "x") (ExPhiAgain Nothing 0 ExRoot), BiVoid AtRho] , phiAgainRule , True ) ] ( \(desc, expr, rule, expectNonEmpty) -> it desc $ do matched <- matchExpressionWithRule expr rule ctx if expectNonEmpty then matched `shouldSatisfy` (not . null) else matched `shouldBe` [] ) describe "matchExpressionWithRule names a formation in the universe of its context" $ do let namingRule :: Yaml.Rule namingRule = Yaml.Rule "named-test" Nothing Nothing (ExFormation [BiMeta "B", BiVoid AtRho]) (ExMeta "e2") Nothing (Just [Yaml.Extra (Yaml.ArgExpression (ExMeta "e2")) "named" [Yaml.ArgExpression (ExFormation [BiMeta "B", BiVoid AtRho])]]) Nothing world :: Expression world = ExFormation [BiTau (AtLabel "qwj") (ExFormation [BiDelta (BtOne "7C")]), BiVoid AtRho] it "writes Φ for the whole program the context stands in" $ do (mapM (buildExpressionThrows (ExMeta "e2")) =<< matchExpressionWithRule world namingRule (RuleContext buildTerm (Just world) (_normal linked) False)) `shouldReturn` [ExRoot] it "writes the formation itself where the context knows no universe" $ do (mapM (buildExpressionThrows (ExMeta "e2")) =<< matchExpressionWithRule world namingRule (RuleContext buildTerm Nothing (_normal linked) False)) `shouldReturn` [world] describe "normalHeld" $ do it "tells no meta a term holds a normal form" $ normalHeld (const True) (ExMeta "qd") `shouldBe` False it "tells no slot a term holds a normal form" $ normalHeld (const True) (ExAny (Slot "n" 7)) `shouldBe` False it "asks the test about a term that is no meta" $ normalHeld (== ExDispatch ExXi (AtLabel "wv")) (ExDispatch ExXi (AtLabel "wv")) `shouldBe` True describe "redex" $ do it "takes every normalization rule for a redex" $ all redex Yaml.normalizationRules `shouldBe` True it "does not take a rule of a formation holding a λ alone for a redex" $ redex (Yaml.Rule "lone" Nothing Nothing (ExFormation [BiMeta "B1", BiLambda (FnMeta "f1")]) ExTermination Nothing Nothing Nothing) `shouldBe` False it "does not take a rule demanding a Δ under 'not' for a redex" $ redex (Yaml.Rule "negated" Nothing Nothing (ExFormation [BiMeta "B1", BiLambda (FnMeta "f1")]) ExTermination (Just (Yaml.Not (Yaml.In [AtDelta] [BiMeta "B1"]))) Nothing Nothing) `shouldBe` False it "does not take a rule dispatching on a meta for a redex" $ redex (Yaml.Rule "loose" Nothing Nothing (ExDispatch (ExMeta "e1") (AtMeta "t1")) ExTermination Nothing Nothing Nothing) `shouldBe` False describe "normalization rules over inert terms" $ do let samples :: [String] samples = [ "⟦ kx ↦ ξ.ow( jy ↦ Φ.ya ), λ ⤍ L_ok, b ↦ ∅ ⟧" , "⟦ φ ↦ Φ.number( φ ↦ Φ.bytes( φ ↦ ⟦ λ ⤍ 𝜎3 ⟧ ) ), ρ ↦ ∅, qe ↦ ⟦ Δ ⤍ 1F- ⟧ ⟧" , "Φ.hz( ⟦ ab ↦ ⟦ kw ↦ ξ.ρ, λ ⤍ L_z ⟧ ⟧ ).uv( α0 ↦ ⊥ )" , "⟦ x ↦ ∅, dd ↦ ⟦ λ ⤍ L_dd, ρ ↦ ∅ ⟧, m1 ↦ ⟦ b ↦ ∅, φ ↦ ξ.ρ.dd( b ↦ ξ.b ), ρ ↦ ∅ ⟧ ⟧" ] context :: RuleContext context = RuleContext buildTerm Nothing (_normal linked) False matches :: Expression -> Yaml.Rule -> IO [Subst] matches term rule = maybe pure (\cond substs -> meetCondition cond substs context) rule.when (matchExpressionDeep rule.pattern term) it "takes every sample for inert" $ do terms <- mapM parseExpressionThrows samples all inert terms `shouldBe` True it "does not find a normalization rule matching anywhere in an inert term" $ do terms <- mapM parseExpressionThrows samples found <- concat <$> sequence [matches term rule | term <- terms, rule <- Yaml.normalizationRules] found `shouldBe` [] describe "a condition that cannot be built" $ do after_ (setLogConfig ERROR 25) $ do let context :: RuleContext context = RuleContext buildTerm Nothing (_normal linked) False it "logs an unbound meta in 'part-of' and treats the condition as not met" $ do expr <- parseExpressionThrows "[[ x -> Q.y ]]" let substs = matchExpressionDeep (ExFormation [BiTau (AtLabel "x") (ExMeta "e1")]) expr cond = Yaml.PartOf (ExMeta "e1") (BiMeta "B1") length substs `shouldBe` 1 setLogConfig DEBUG 25 (captured, met) <- hCapture [stderr] (meetCondition cond substs context) met `shouldBe` [] "Condition part-of(" `isInfixOf` captured `shouldBe` True it "logs an unbound meta in 'matches' and treats the condition as not met" $ do expr <- parseExpressionThrows "[[ x -> Q.y ]]" nested <- parseExpressionThrows "Q.x.!t9" let substs = matchExpressionDeep (ExFormation [BiTau (AtLabel "x") (ExMeta "e1")]) expr cond = Yaml.Matches "Q" nested length substs `shouldBe` 1 setLogConfig DEBUG 25 (captured, met) <- hCapture [stderr] (meetCondition cond substs context) met `shouldBe` [] "Condition matches(" `isInfixOf` captured `shouldBe` True