From 0bf20cdc69ff1ab6b10d3b45b7b40714c7341640 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Mon, 9 Nov 2026 15:59:43 +0200 Subject: [PATCH 01/37] Add TermGenerator --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 3 +- src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs | 5 +- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 67 ++++++++++++++++++- src/Codec/CBOR/Cuddle/CDDL/Resolve.hs | 15 ++--- src/Codec/CBOR/Cuddle/Huddle.hs | 18 +++-- 5 files changed, 89 insertions(+), 19 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 1eaec336..fcde6e49 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -51,6 +51,7 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenConfig (..), GenEnv (..), GenPhase, + TermGenerator (..), TwiddleConfig (..), TwiddlePolicy (..), isDefiniteAllowed, @@ -369,7 +370,7 @@ genForCTree node = annotateTerm node $ case node of CTree.Unwrap n -> genForCTree n CTree.Tag t n -> genTag t n CTree.CTreeE (GenRef n) -> genForNode n - CTree.CTreeE (GenGenerator gen _) -> gen + CTree.CTreeE (GenGenerator gen _) -> tgGenerator gen CTree.CTreeE (GenValidator _ x) -> genForCTree x isInvalidAgainstNode :: CTreeRoot GenPhase -> Term -> CTree GenPhase -> Bool diff --git a/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs b/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs index b17fbc63..39ebc3e3 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs @@ -12,8 +12,7 @@ module Codec.CBOR.Cuddle.CDDL.CTreePhase ( ) where import Codec.CBOR.Cuddle.CDDL (XCddl, XRule, XTerm, XXTopLevel, XXType2) -import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) -import Codec.CBOR.Cuddle.CDDL.Custom.Generator (CBORGen) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator (TermGenerator) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (TermValidator) import Data.Default.Class (Default) import Data.Hashable (Hashable) @@ -32,7 +31,7 @@ data instance XCddl CTreePhase = CTreeXCddl deriving (Generic, Show, Eq, Ord) data instance XRule CTreePhase - = CTreeXRule (Maybe (CBORGen RuleTerm)) (Maybe TermValidator) + = CTreeXRule (Maybe TermGenerator) (Maybe TermValidator) deriving (Generic) data instance XXType2 CTreePhase diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 5c9f2f39..78744ed2 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -12,6 +12,11 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( withAntiGen, withLocalGenBindings, + -- * Term generator + TermGenerator (..), + simpleGen, + constrain, + -- * Twiddling TwiddleConfig (..), TwiddlePolicy (..), @@ -22,19 +27,31 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( twiddleNothing, withTwiddle, disableTwiddle, + + -- * Contstraints + GenConstraint (..), + + -- * Interval + Interval (..), + IntervalBound (..), ) where import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..)) import Codec.CBOR.Cuddle.CDDL.CTree (CTree, CTreeRoot (..), XXCTree) import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (TermValidator) +import Codec.CBOR.Term (Term) import Control.Monad.Reader (MonadReader (..), MonadTrans (..), ReaderT (..), asks, mapReaderT) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map +import Data.Set (Set) +import Data.Text (Text) +import Data.Word (Word64, Word8) import GHC.Generics (Generic) import Optics.Lens (Lens') import Test.AntiGen (AntiGen, MonadAntiGen (..)) import Test.QuickCheck.GenT (MonadGen (..)) +import Text.Regex.TDFA (Regex) type data GenPhase @@ -148,8 +165,54 @@ withLocalGenBindings binds = data instance XXCTree GenPhase = GenRef Name - | GenGenerator (CBORGen RuleTerm) (CTree GenPhase) + | GenGenerator TermGenerator (CTree GenPhase) | GenValidator TermValidator (CTree GenPhase) class HasGenerator a where - generatorL :: Lens' a (Maybe (CBORGen RuleTerm)) + generatorL :: Lens' a (Maybe TermGenerator) + +data IntervalBound a + = OpenBound a + | ClosedBound a + | Unbounded + deriving (Eq, Show) + +data Interval a = Interval (IntervalBound a) (IntervalBound a) + deriving (Eq, Show) + +data GenConstraint + = -- | Constrains the size of a string or bytestring in bytes + Size (Interval Word64) + | -- | Constrains the range of allowed values to the interval. This also covers + -- the .gt and .lt operators. + Range (Interval Word64) + | Eq Term + | Neq Term + | -- | Specifies the indices at which a bit is allowed to be set + Bits (Set Word8) + | -- | Constrains the string to ones that match the regex + Regexp Regex + | -- | The bytestring must match the CDDL rule + Cbor (CTree GenPhase) + | -- | Catch-all for nonstandard control operators + CustomControl Text Term + deriving (Generic) + +data TermGenerator = TermGenerator + { tgGenerator :: CBORGen RuleTerm + , tgConstrain :: GenConstraint -> Maybe TermGenerator + } + +-- | Constructs a @TermGenerator@ that fails whenever a control operator is +-- applied to it. +simpleGen :: CBORGen RuleTerm -> TermGenerator +simpleGen gen = + TermGenerator + { tgGenerator = gen + , tgConstrain = const Nothing + } + +constrain :: GenConstraint -> TermGenerator -> TermGenerator +constrain c (TermGenerator _ f) = case f c of + Just g -> g + Nothing -> error "Failed to apply constraint" diff --git a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs index 77eac173..6d2698c8 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs @@ -67,10 +67,9 @@ import Data.Hashable import Data.List (foldl') #endif import Codec.CBOR.Cuddle.CDDL.CTreePhase (CTreePhase, XRule (..)) -import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( - CBORGen, GenPhase, + TermGenerator (..), XXCTree (..), withLocalGenBindings, ) @@ -106,7 +105,7 @@ newtype PartialCTreeRoot i = PartialCTreeRoot (Map.Map Name (ProvidedParameters data CDDLMapEntry = CDDLMapEntry { cmeProvidedParameters :: ProvidedParameters (TypeOrGroup CTreePhase) - , cmeCustomGenerator :: Maybe (CBORGen RuleTerm) + , cmeCustomGenerator :: Maybe TermGenerator , cmeCustomValidator :: Maybe TermValidator } deriving (Generic) @@ -168,7 +167,7 @@ type data OrReferenced data instance XXCTree OrReferenced = -- | Reference to another node with possible generic arguments supplied OrRef Name [CTree OrReferenced] - | OGenerator (CBORGen RuleTerm) (CTree OrReferenced) + | OGenerator TermGenerator (CTree OrReferenced) | OValidator TermValidator (CTree OrReferenced) type data OrReferencedSimple @@ -416,7 +415,7 @@ instance Pretty (XXCTree i) => Pretty (DistRef i) where data instance XXCTree DistReferenced = DRef (DistRef DistReferenced) - | DGenerator (CBORGen RuleTerm) (CTree DistReferenced) + | DGenerator TermGenerator (CTree DistReferenced) | DValidator TermValidator (CTree DistReferenced) type data DistReferencedNoGen @@ -472,7 +471,7 @@ type data MonoReferenced data instance XXCTree MonoReferenced = MRuleRef Name - | MGenerator (CBORGen RuleTerm) (CTree MonoReferenced) + | MGenerator TermGenerator (CTree MonoReferenced) | MValidator TermValidator (CTree MonoReferenced) type MonoEnv = BindingEnv DistReferenced MonoReferenced @@ -633,12 +632,12 @@ resolveGenericRef (DRef (GenericRef n)) = do case Map.lookup n localBinds of Just node -> pure node Nothing -> throwNR $ UnboundReference n -resolveGenericRef (DGenerator g x) = do +resolveGenericRef (DGenerator (TermGenerator g cf) x) = do binds <- ask @"local" body <- resolveGenericCTree x let bindsGen = mapIndex @CTree @MonoReferenced @GenPhase <$> binds g' = withLocalGenBindings bindsGen g - pure . CTreeE $ MGenerator g' body + pure . CTreeE $ MGenerator (TermGenerator g' cf) body resolveGenericRef (DValidator v x) = do binds <- ask @"local" body <- resolveGenericCTree x diff --git a/src/Codec/CBOR/Cuddle/Huddle.hs b/src/Codec/CBOR/Cuddle/Huddle.hs index a11abddc..70bfe115 100644 --- a/src/Codec/CBOR/Cuddle/Huddle.hs +++ b/src/Codec/CBOR/Cuddle/Huddle.hs @@ -94,6 +94,7 @@ module Codec.CBOR.Cuddle.Huddle ( -- * Generators withCBORGen, + withGenerator, -- * Validators withValidator, @@ -120,7 +121,12 @@ import Codec.CBOR.Cuddle.CDDL ( import Codec.CBOR.Cuddle.CDDL qualified as C import Codec.CBOR.Cuddle.CDDL.CtlOp qualified as CtlOp import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) -import Codec.CBOR.Cuddle.CDDL.Custom.Generator (CBORGen, HasGenerator (..)) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( + CBORGen, + HasGenerator (..), + TermGenerator, + simpleGen, + ) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (HasValidator (..), TermValidator) import Codec.CBOR.Cuddle.Comments (Comment, HasComment (..)) import Codec.CBOR.Cuddle.Comments qualified as C @@ -157,7 +163,7 @@ newtype instance C.XCddl HuddleStage = HuddleXCddl [C.Comment] data instance C.XRule HuddleStage = HuddleXRule { hxrComment :: C.Comment - , hxrGenerator :: Maybe (CBORGen RuleTerm) + , hxrGenerator :: Maybe TermGenerator , hxrValidator :: Maybe TermValidator } deriving (Generic) @@ -1377,10 +1383,12 @@ toCDDL' HuddleConfig {..} hdl = C.GenericParameters $ fmap (\(GRef t) -> GenericParameter (C.Name t) $ HuddleXTerm mempty) (args gr) --- | Use a custom `CBORGen` generator to generate the term. Will override --- the custom generator passed via `withGenerator`. +withGenerator :: HasGenerator a => TermGenerator -> a -> a +withGenerator gen = L.set generatorL $ Just gen + +-- | Use a custom `CBORGen` generator to generate the term. withCBORGen :: HasGenerator a => CBORGen RuleTerm -> a -> a -withCBORGen gen = L.set generatorL $ Just gen +withCBORGen = withGenerator . simpleGen withValidator :: HasValidator a => TermValidator -> a -> a withValidator p = L.set validatorL $ Just p From 63bbcfbc2b17069f6317b7b18dfdd836b6fd90bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 10 Nov 2026 14:33:14 +0200 Subject: [PATCH 02/37] WIP --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 44 +++++-- src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs | 3 +- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 107 ++++++++++++++++-- src/Codec/CBOR/Cuddle/CDDL/Resolve.hs | 9 +- src/Codec/CBOR/Cuddle/Huddle.hs | 4 +- 5 files changed, 139 insertions(+), 28 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index fcde6e49..9f37f6eb 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -27,7 +27,7 @@ module Codec.CBOR.Cuddle.CBOR.Gen ( #if MIN_VERSION_random(1,3,0) #endif -import Codec.CBOR.Cuddle.CBOR.Canonical (nintMin, toCanonical, uintMax) +import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm (..), nintMin, toCanonical, uintMax) import Codec.CBOR.Cuddle.CBOR.Validator (validateAgainst) import Codec.CBOR.Cuddle.CDDL ( GRef (..), @@ -54,10 +54,13 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( TermGenerator (..), TwiddleConfig (..), TwiddlePolicy (..), + genFromInterval, isDefiniteAllowed, isIndefiniteAllowed, withTwiddle, ) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Gen +import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Interval import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( CustomValidatorResult (..), ValidatorPhase, @@ -78,6 +81,7 @@ import Data.List (sortOn) import Data.List.NonEmpty qualified as NE import Data.Maybe (fromMaybe) import Data.Ord (Down (..)) +import Data.Set qualified as Set import Data.Text (Text) import Data.Text qualified as T import Data.Text.Internal.Encoding.Utf8 (utf8Length) @@ -160,12 +164,34 @@ simple = -- [0 .. 19] ++ [23] ++ [32 ..] [23] -genHalf :: MonadGen m => m Float -genHalf = do - half <- Half <$> arbitrary - if isDenormalized half - then genHalf - else pure $ fromHalf half +genHalf :: TermGenerator Float +genHalf = go mempty mempty + where + go rng exclude = + TermGenerator + { tgGenerator = + let gen = do + half <- Half <$> genFromInterval rng `suchThat` (`Set.notMember` exclude) + if isDenormalized half + then gen + else pure $ fromHalf half + in gen + , tgConstrain = \case + Gen.Range cRng -> Just $ go (rng <> fmap fromIntegral cRng) exclude + Gen.Eq term + | CTFloat x <- term -> Just $ go (rng <> Interval.singleton _) exclude + | otherwise -> Nothing + Gen.Neq term + | CTFloat x <- term -> Just $ go rng $ Set.insert _ exclude + | otherwise -> Just $ go rng exclude + _ -> Nothing + } + +-- do +-- half <- Half <$> arbitrary +-- if isDenormalized half +-- then genHalf c +-- else pure $ fromHalf half genTwiddled :: (TwiddleConfig -> TwiddlePolicy) -> (a -> Term) -> (a -> Term) -> a -> CBORGen Term genTwiddled getPolicy definite indefinite term = do @@ -202,7 +228,7 @@ genTerm = , TBool <$> arbitrary , pure TNull , TSimple <$> elements simple - , THalf <$> genHalf + , THalf <$> genHalf mempty , TFloat <$> arbitrary , TDouble <$> arbitrary ] @@ -241,7 +267,7 @@ genText :: MonadGen m => m Text genText = sized $ \sz -> genNBytesText =<< choose (0, sz) -- | Primitive types defined by the CDDL specification, with their generators -genPostlude :: PTerm -> CBORGen Term +genPostlude :: PTerm -> TermGenerator Term genPostlude pt = genPTerm =<< faultyPTerm pt where genExcluding ls = diff --git a/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs b/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs index 39ebc3e3..2f1cb3b0 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs @@ -12,6 +12,7 @@ module Codec.CBOR.Cuddle.CDDL.CTreePhase ( ) where import Codec.CBOR.Cuddle.CDDL (XCddl, XRule, XTerm, XXTopLevel, XXType2) +import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Generator (TermGenerator) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (TermValidator) import Data.Default.Class (Default) @@ -31,7 +32,7 @@ data instance XCddl CTreePhase = CTreeXCddl deriving (Generic, Show, Eq, Ord) data instance XRule CTreePhase - = CTreeXRule (Maybe TermGenerator) (Maybe TermValidator) + = CTreeXRule (Maybe (TermGenerator RuleTerm)) (Maybe TermValidator) deriving (Generic) data instance XXType2 CTreePhase diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 78744ed2..d282a5bc 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE TypeData #-} {-# LANGUAGE TypeFamilies #-} @@ -34,8 +36,14 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( -- * Interval Interval (..), IntervalBound (..), + isEmpty, + intersect, + singleton, + contains, + genFromInterval, ) where +import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm) import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..)) import Codec.CBOR.Cuddle.CDDL.CTree (CTree, CTreeRoot (..), XXCTree) import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm) @@ -44,13 +52,15 @@ import Codec.CBOR.Term (Term) import Control.Monad.Reader (MonadReader (..), MonadTrans (..), ReaderT (..), asks, mapReaderT) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map +import Data.Maybe (fromMaybe) import Data.Set (Set) import Data.Text (Text) import Data.Word (Word64, Word8) import GHC.Generics (Generic) import Optics.Lens (Lens') +import System.Random (Random) import Test.AntiGen (AntiGen, MonadAntiGen (..)) -import Test.QuickCheck.GenT (MonadGen (..)) +import Test.QuickCheck.GenT (MonadGen (..), suchThat) import Text.Regex.TDFA (Regex) type data GenPhase @@ -165,11 +175,11 @@ withLocalGenBindings binds = data instance XXCTree GenPhase = GenRef Name - | GenGenerator TermGenerator (CTree GenPhase) + | GenGenerator (TermGenerator RuleTerm) (CTree GenPhase) | GenValidator TermValidator (CTree GenPhase) class HasGenerator a where - generatorL :: Lens' a (Maybe TermGenerator) + generatorL :: Lens' a (Maybe (TermGenerator RuleTerm)) data IntervalBound a = OpenBound a @@ -177,17 +187,90 @@ data IntervalBound a | Unbounded deriving (Eq, Show) +boundary :: IntervalBound a -> Maybe a +boundary = \case + Unbounded -> Nothing + OpenBound x -> Just x + ClosedBound x -> Just x + data Interval a = Interval (IntervalBound a) (IntervalBound a) deriving (Eq, Show) +-- | This function checks whether the interval contains any elements. It does +-- not take the bounds of the type into account, it only checks whether the +-- lower bound is smaller than the upper bound +isEmpty :: Ord a => Interval a -> Bool +isEmpty = \case + Interval (ClosedBound lo) (ClosedBound hi) -> lo > hi + Interval lo hi + | Just l <- boundary lo + , Just h <- boundary hi -> + l >= h + _ -> False + +-- | Computes the intersection of two intervals. The result may be empty (see +-- 'isEmpty'). +intersect :: Ord a => Interval a -> Interval a -> Interval a +intersect (Interval lo1 hi1) (Interval lo2 hi2) = + Interval (tighter (>) lo1 lo2) (tighter (<) hi1 hi2) + where + -- Picks the more restrictive of two bounds. @better x y@ holds when @x@ + -- is strictly more restrictive than @y@. On equal boundaries an open bound + -- is more restrictive than a closed one. + tighter _ Unbounded b = b + tighter _ a Unbounded = a + tighter better a b + | Just x <- boundary a + , Just y <- boundary b = + if + | better x y -> a + | better y x -> b + | OpenBound _ <- a -> a + | otherwise -> b + tighter _ a _ = a + +singleton :: a -> Interval a +singleton x = Interval (ClosedBound x) (ClosedBound x) + +contains :: Ord a => Interval a -> a -> Bool +contains (Interval lo hi) x = satisifesUpper && satisfiesLower + where + satisifesUpper = case hi of + Unbounded -> True + OpenBound y -> x < y + ClosedBound y -> x <= y + satisfiesLower = case lo of + Unbounded -> True + OpenBound y -> y < x + ClosedBound y -> y <= x + +instance Ord a => Semigroup (Interval a) where + (<>) = intersect + +instance Ord a => Monoid (Interval a) where + mempty = Interval Unbounded Unbounded + +genFromInterval :: + ( MonadGen m + , Bounded a + , Random a + , Ord a + ) => + Interval a -> + m a +genFromInterval int@(Interval lo hi) = choose (boundLo, boundHi) `suchThat` contains int + where + boundLo = fromMaybe minBound $ boundary lo + boundHi = fromMaybe maxBound $ boundary hi + data GenConstraint = -- | Constrains the size of a string or bytestring in bytes - Size (Interval Word64) + Size (Interval CanonicalTerm) | -- | Constrains the range of allowed values to the interval. This also covers -- the .gt and .lt operators. - Range (Interval Word64) - | Eq Term - | Neq Term + Range (Interval CanonicalTerm) + | Eq CanonicalTerm + | Neq CanonicalTerm | -- | Specifies the indices at which a bit is allowed to be set Bits (Set Word8) | -- | Constrains the string to ones that match the regex @@ -198,21 +281,21 @@ data GenConstraint CustomControl Text Term deriving (Generic) -data TermGenerator = TermGenerator - { tgGenerator :: CBORGen RuleTerm - , tgConstrain :: GenConstraint -> Maybe TermGenerator +data TermGenerator a = TermGenerator + { tgGenerator :: CBORGen a + , tgConstrain :: GenConstraint -> Maybe (TermGenerator a) } -- | Constructs a @TermGenerator@ that fails whenever a control operator is -- applied to it. -simpleGen :: CBORGen RuleTerm -> TermGenerator +simpleGen :: CBORGen a -> TermGenerator a simpleGen gen = TermGenerator { tgGenerator = gen , tgConstrain = const Nothing } -constrain :: GenConstraint -> TermGenerator -> TermGenerator +constrain :: GenConstraint -> TermGenerator a -> TermGenerator a constrain c (TermGenerator _ f) = case f c of Just g -> g Nothing -> error "Failed to apply constraint" diff --git a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs index 6d2698c8..4c7c4022 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs @@ -67,6 +67,7 @@ import Data.Hashable import Data.List (foldl') #endif import Codec.CBOR.Cuddle.CDDL.CTreePhase (CTreePhase, XRule (..)) +import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenPhase, TermGenerator (..), @@ -105,7 +106,7 @@ newtype PartialCTreeRoot i = PartialCTreeRoot (Map.Map Name (ProvidedParameters data CDDLMapEntry = CDDLMapEntry { cmeProvidedParameters :: ProvidedParameters (TypeOrGroup CTreePhase) - , cmeCustomGenerator :: Maybe TermGenerator + , cmeCustomGenerator :: Maybe (TermGenerator RuleTerm) , cmeCustomValidator :: Maybe TermValidator } deriving (Generic) @@ -167,7 +168,7 @@ type data OrReferenced data instance XXCTree OrReferenced = -- | Reference to another node with possible generic arguments supplied OrRef Name [CTree OrReferenced] - | OGenerator TermGenerator (CTree OrReferenced) + | OGenerator (TermGenerator RuleTerm) (CTree OrReferenced) | OValidator TermValidator (CTree OrReferenced) type data OrReferencedSimple @@ -415,7 +416,7 @@ instance Pretty (XXCTree i) => Pretty (DistRef i) where data instance XXCTree DistReferenced = DRef (DistRef DistReferenced) - | DGenerator TermGenerator (CTree DistReferenced) + | DGenerator (TermGenerator RuleTerm) (CTree DistReferenced) | DValidator TermValidator (CTree DistReferenced) type data DistReferencedNoGen @@ -471,7 +472,7 @@ type data MonoReferenced data instance XXCTree MonoReferenced = MRuleRef Name - | MGenerator TermGenerator (CTree MonoReferenced) + | MGenerator (TermGenerator RuleTerm) (CTree MonoReferenced) | MValidator TermValidator (CTree MonoReferenced) type MonoEnv = BindingEnv DistReferenced MonoReferenced diff --git a/src/Codec/CBOR/Cuddle/Huddle.hs b/src/Codec/CBOR/Cuddle/Huddle.hs index 70bfe115..d91ac1cd 100644 --- a/src/Codec/CBOR/Cuddle/Huddle.hs +++ b/src/Codec/CBOR/Cuddle/Huddle.hs @@ -163,7 +163,7 @@ newtype instance C.XCddl HuddleStage = HuddleXCddl [C.Comment] data instance C.XRule HuddleStage = HuddleXRule { hxrComment :: C.Comment - , hxrGenerator :: Maybe TermGenerator + , hxrGenerator :: Maybe (TermGenerator RuleTerm) , hxrValidator :: Maybe TermValidator } deriving (Generic) @@ -1383,7 +1383,7 @@ toCDDL' HuddleConfig {..} hdl = C.GenericParameters $ fmap (\(GRef t) -> GenericParameter (C.Name t) $ HuddleXTerm mempty) (args gr) -withGenerator :: HasGenerator a => TermGenerator -> a -> a +withGenerator :: HasGenerator a => TermGenerator RuleTerm -> a -> a withGenerator gen = L.set generatorL $ Just gen -- | Use a custom `CBORGen` generator to generate the term. From 7707ed2965dcb1e95b8d7177825d65a6182c1615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Mon, 16 Nov 2026 14:57:44 +0200 Subject: [PATCH 03/37] WIP --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 241 +++++++++--------- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 7 +- 2 files changed, 122 insertions(+), 126 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 9f37f6eb..26efca72 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -49,14 +49,18 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( CBORGen, GenConfig (..), + GenConstraint, GenEnv (..), GenPhase, + Interval (..), TermGenerator (..), TwiddleConfig (..), TwiddlePolicy (..), + constrain, genFromInterval, isDefiniteAllowed, isIndefiniteAllowed, + simpleGen, withTwiddle, ) import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Gen @@ -71,11 +75,12 @@ import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Term (Term (..)) import Codec.CBOR.Term qualified as CBOR import Codec.CBOR.Write qualified as CBOR -import Control.Monad (zipWithM, (<=<)) +import Control.Monad (when, zipWithM, (<=<)) import Control.Monad.Reader (asks) import Data.ByteString (ByteString) import Data.ByteString.Lazy qualified as LBS import Data.Char (chr) +import Data.Foldable (Foldable (..)) import Data.Functor ((<&>)) import Data.List (sortOn) import Data.List.NonEmpty qualified as NE @@ -91,7 +96,7 @@ import Data.Text.Lazy.Builder (toLazyText) import Data.Text.Lazy.Builder qualified as LB import Data.Word (Word64, Word8) import GHC.Stack (HasCallStack) -import Numeric.Half (Half (..), fromHalf) +import Numeric.Half (Half (..), fromHalf, toHalf) import Prettyprinter (Pretty (..), layoutCompact) import Prettyprinter.Render.Text (renderStrict) import System.Random.Stateful (Random, StatefulGen (..), runStateGen_, uniformByteStringM) @@ -171,7 +176,7 @@ genHalf = go mempty mempty TermGenerator { tgGenerator = let gen = do - half <- Half <$> genFromInterval rng `suchThat` (`Set.notMember` exclude) + half <- toHalf <$> genFromInterval rng `suchThat` (`Set.notMember` exclude) if isDenormalized half then gen else pure $ fromHalf half @@ -179,36 +184,30 @@ genHalf = go mempty mempty , tgConstrain = \case Gen.Range cRng -> Just $ go (rng <> fmap fromIntegral cRng) exclude Gen.Eq term - | CTFloat x <- term -> Just $ go (rng <> Interval.singleton _) exclude + | CTFloat x <- term -> Just $ go (rng <> Interval.singleton x) exclude | otherwise -> Nothing Gen.Neq term - | CTFloat x <- term -> Just $ go rng $ Set.insert _ exclude + | CTFloat x <- term -> Just $ go rng $ Set.insert x exclude | otherwise -> Just $ go rng exclude _ -> Nothing } --- do --- half <- Half <$> arbitrary --- if isDenormalized half --- then genHalf c --- else pure $ fromHalf half - -genTwiddled :: (TwiddleConfig -> TwiddlePolicy) -> (a -> Term) -> (a -> Term) -> a -> CBORGen Term +genTwiddled :: (TwiddleConfig -> TwiddlePolicy) -> (a -> Term) -> (a -> Term) -> a -> m Term genTwiddled getPolicy definite indefinite term = do policy <- asks $ getPolicy . gcTwiddle . geConfig elements $ [definite term | isDefiniteAllowed policy] <> [indefinite term | isIndefiniteAllowed policy] -twiddleArray :: [Term] -> CBORGen Term +twiddleArray :: [Term] -> m Term twiddleArray = genTwiddled tcArrays TList TListI -twiddleMap :: [(Term, Term)] -> CBORGen Term +twiddleMap :: [(Term, Term)] -> m Term twiddleMap = genTwiddled tcMaps TMap TMapI -twiddleText :: Text -> CBORGen Term +twiddleText :: Text -> m Term twiddleText = genTwiddled tcText TString (TStringI . TL.fromStrict) -twiddleBytes :: ByteString -> CBORGen Term +twiddleBytes :: ByteString -> m Term twiddleBytes = genTwiddled tcBytes TBytes (TBytesI . LBS.fromStrict) genTerm :: CBORGen Term @@ -228,7 +227,7 @@ genTerm = , TBool <$> arbitrary , pure TNull , TSimple <$> elements simple - , THalf <$> genHalf mempty + , THalf <$> tgGenerator genHalf , TFloat <$> arbitrary , TDouble <$> arbitrary ] @@ -299,7 +298,7 @@ genPostlude pt = genPTerm =<< faultyPTerm pt PTDouble -> TDouble <$> arbitrary PTBytes -> twiddleBytes =<< genBytes PTText -> twiddleText =<< genText - PTAny -> genTerm + PTAny -> simpleGen genTerm PTNil -> pure TNull PTUndefined -> pure $ TSimple 23 @@ -358,7 +357,7 @@ genBetween rng = do -- | Annotate a generator with the label derived from a CTree node. -- Control nodes are transparent — the annotation comes from the target inside. -annotateTerm :: CTree GenPhase -> CBORGen a -> CBORGen a +annotateTerm :: MonadAntiGen m => CTree GenPhase -> m a -> m a annotateTerm = \case CTree.Literal _ -> annotate "literal" CTree.Postlude pt -> annotate $ renderStrict . layoutCompact $ pretty pt @@ -377,7 +376,7 @@ annotateTerm = \case CTree.CTreeE (GenGenerator _ _) -> annotate "custom_generator" CTree.CTreeE (GenValidator _ _) -> id -genForCTree :: HasCallStack => CTree GenPhase -> CBORGen RuleTerm +genForCTree :: HasCallStack => CTree GenPhase -> TermGenerator RuleTerm genForCTree node = annotateTerm node $ case node of CTree.Literal v -> SingleTerm <$> valueToTerm v CTree.Postlude pt -> SingleTerm <$> genPostlude pt @@ -390,13 +389,13 @@ genForCTree node = annotateTerm node $ case node of CTree.KV key value _cut -> genKV key value CTree.Occur item occurs -> applyOccurenceIndicator occurs (genForCTree item) - CTree.Range from to bounds -> genRange from to bounds + CTree.Range from to bounds -> simpleGen $ genRange from to bounds CTree.Control op target controller -> genControl op target controller CTree.Enum tree -> genEnum tree CTree.Unwrap n -> genForCTree n CTree.Tag t n -> genTag t n CTree.CTreeE (GenRef n) -> genForNode n - CTree.CTreeE (GenGenerator gen _) -> tgGenerator gen + CTree.CTreeE (GenGenerator gen _) -> gen CTree.CTreeE (GenValidator _ x) -> genForCTree x isInvalidAgainstNode :: CTreeRoot GenPhase -> Term -> CTree GenPhase -> Bool @@ -407,8 +406,8 @@ isInvalidAgainstNode cTreeRoot term node = -- | Generate a map from a list of nodes genMap :: - HasCallStack => [CTree GenPhase] -> CBORGen RuleTerm -genMap nodes = do + HasCallStack => [CTree GenPhase] -> TermGenerator RuleTerm +genMap nodes = simpleGen $ do let elemsNeeded KV {} = 1 elemsNeeded (Occur _ OIOneOrMore) = 1 @@ -429,7 +428,7 @@ genMap nodes = do canonicalKeys = toCanonical . fst <$> m unS (SingleTerm x) = x unS x = error $ "Expected single, got " <> show x - genFromNode n = unS <$> scale (`div` 2) (genForCTree n) + genFromNode n = unS <$> scale (`div` 2) (tgGenerator $ genForCTree n) go !n | n > 0 = do k <- genFromNode kNode #! "key" @@ -519,34 +518,37 @@ genMap nodes = do Nothing -> error "Failed to generate unique keys for map after max retries" -- | Generate an array from a list of nodes -genArray :: HasCallStack => [CTree GenPhase] -> CBORGen RuleTerm -genArray nodes = do - items <- - singleTermList . flattenWrappedList - <$> zipWithM - (\i node -> annotate (T.pack $ show i) $ genForCTree node) - [0 :: Int ..] - nodes - case items of - Just ts -> do - cTreeRoot <- asks $ gcRoot . geConfig - SingleTerm - <$> twiddleArray ts ||! do - let - genCorruptedList = do - idx <- choose (0, length ts) - junkElem <- genTerm +genArray :: HasCallStack => [CTree GenPhase] -> TermGenerator RuleTerm +genArray nodes = simpleGen generator + where + generator :: CBORGen RuleTerm + generator = do + items <- + singleTermList . flattenWrappedList + <$> zipWithM + (\i node -> annotate (T.pack $ show i) . tgGenerator $ genForCTree node) + [0 :: Int ..] + nodes + case items of + Just ts -> do + cTreeRoot <- asks $ gcRoot . geConfig + SingleTerm + <$> twiddleArray ts ||! do let - (lInit, lTail) = splitAt idx ts - twiddleArray $ lInit <> [junkElem] <> lTail - genCorruptedList `suchThat` \l -> isInvalidAgainstNode cTreeRoot l (Array nodes) - Nothing -> error "Something weird happened which shouldn't be possible" + genCorruptedList = do + idx <- choose (0, length ts) + junkElem <- genTerm + let + (lInit, lTail) = splitAt idx ts + twiddleArray $ lInit <> [junkElem] <> lTail + genCorruptedList `suchThat` \l -> isInvalidAgainstNode cTreeRoot l (Array nodes) + Nothing -> error "Something weird happened which shouldn't be possible" -- | Generate a key-value pair -genKV :: HasCallStack => CTree GenPhase -> CTree GenPhase -> CBORGen RuleTerm -genKV key value = do - kg <- annotate "key" $ genForCTree key - vg <- annotate "value" $ genForCTree value +genKV :: HasCallStack => CTree GenPhase -> CTree GenPhase -> TermGenerator RuleTerm +genKV key value = simpleGen $ do + kg <- annotate "key" . tgGenerator $ genForCTree key + vg <- annotate "value" . tgGenerator $ genForCTree value case (kg, vg) of (SingleTerm k, SingleTerm v) -> pure $ PairTerm k v _ -> @@ -564,8 +566,8 @@ genRange :: RangeBound -> CBORGen RuleTerm genRange from to bounds = do - term1 <- dropNegativeGen $ genForCTree from - term2 <- dropNegativeGen $ genForCTree to + term1 <- dropNegativeGen . tgGenerator $ genForCTree from + term2 <- dropNegativeGen . tgGenerator $ genForCTree to case (term1, term2) of (SingleTerm (TInt a), SingleTerm (TInt b)) | a <= b -> genBetween (range bounds a b) <&> SingleTerm . TInt @@ -588,74 +590,64 @@ genControl :: CtlOp.CtlOp -> CTree GenPhase -> CTree GenPhase -> - CBORGen RuleTerm -genControl op target controller = annotateTerm target $ do - resolvedController <- case controller of - CTreeE (GenRef n) -> dropNegativeGen $ resolveRef n - x -> pure x - case (op, resolvedController) of - (CtlOp.Le, CTree.Literal (Value (VUInt n) _)) -> case target of - CTree.Postlude PTUInt -> SingleTerm . TInteger <$> choose (0, fromIntegral n) - _ -> error "Cannot apply le operator to target" - (CtlOp.Le, _) -> error $ "Invalid controller for .le operator: " <> showSimple controller - (CtlOp.Lt, CTree.Literal (Value (VUInt n) _)) -> case target of - CTree.Postlude PTUInt -> SingleTerm . TInteger <$> choose (0, fromIntegral n - 1) - _ -> error "Cannot apply lt operator to target" - (CtlOp.Lt, _) -> error $ "Invalid controller for .lt operator: " <> showSimple controller - (CtlOp.Size, CTree.Literal (Value (VUInt s) _)) -> do - s' <- pure s |! sized (\sz -> choose (0, fromIntegral sz) `suchThat` (/= s)) - genSized s' target - (CtlOp.Size, CTree.Range {CTree.from, CTree.to}) -> - case (from, to) of - (CTree.Literal (Value (VUInt f) _), CTree.Literal (Value (VUInt t) _)) -> do - s <- sized $ \sz -> - antiChoose - (fromIntegral f, fromIntegral t) - (0, max (succ t) $ fromIntegral sz) - genSized s target - _ -> - error $ - "Invalid controller for .size operator: " - <> showSimple controller - (CtlOp.Size, _) -> - error $ - "Invalid controller for .size operator: " - <> showSimple controller - (CtlOp.Cbor, _) -> do - enc <- genForCTree controller - case enc of - SingleTerm x -> fmap SingleTerm . twiddleBytes $ CBOR.toStrictByteString (CBOR.encodeTerm x) - _ -> error "Controller does not correspond to a single term" - (c, _) -> error $ "Controller not yet implemented: " <> show c + TermGenerator RuleTerm +genControl op target controller = constrain constraint (genForCTree target) + where + constraint = case op of + CtlOp.Size -> Gen.Size $ Interval _ _ + CtlOp.Bits -> Gen.Bits _ + CtlOp.Regexp -> Gen.Regexp _ + CtlOp.Cbor -> Gen.Cbor _ + CtlOp.Cborseq -> Gen.Cborseq _ + CtlOp.Within -> Gen.Within _ + CtlOp.And -> Gen.And _ + CtlOp.Lt -> Gen.Range _ + CtlOp.Le -> Gen.Range _ + CtlOp.Gt -> Gen.Range _ + CtlOp.Ge -> Gen.Range _ + CtlOp.Eq -> Gen.Eq _ + CtlOp.Ne -> Gen.Neq _ + CtlOp.Default -> Gen.Default _ -- | Generate a value from an enum -genEnum :: HasCallStack => CTree GenPhase -> CBORGen RuleTerm -genEnum tree = case tree of +genEnum :: HasCallStack => CTree GenPhase -> TermGenerator RuleTerm +genEnum tree = simpleGen $ case tree of CTree.Group trees -> do ix <- choose (0, length trees - 1) - genForCTree $ trees !! ix + tgGenerator $ genForCTree $ trees !! ix _ -> error "Attempt to form an enum from something other than a group" -- | Generate a tagged value -genTag :: HasCallStack => Word64 -> CTree GenPhase -> CBORGen RuleTerm -genTag t node = do +genTag :: HasCallStack => Word64 -> CTree GenPhase -> TermGenerator RuleTerm +genTag t node = simpleGen $ do omitTag <- faultyBool False if omitTag - then genForCTree node + then tgGenerator $ genForCTree node else do tag <- faultyNum t enc <- case tag of n | n == 2 || n == 3 -> -- TODO remove this once `cborg` can decode indefinite bytes in bignums - withTwiddle (\c -> c {tcBytes = DefiniteOnly}) $ genForCTree node - _ -> genForCTree node + withTwiddle (\c -> c {tcBytes = DefiniteOnly}) . tgGenerator $ genForCTree node + _ -> tgGenerator $ genForCTree node case enc of SingleTerm x -> pure $ SingleTerm $ TTagged tag x _ -> error "Tag controller does not correspond to a single term" -genForNode :: HasCallStack => Name -> CBORGen RuleTerm -genForNode = genForCTree <=< resolveRef +genForNode :: HasCallStack => Name -> TermGenerator RuleTerm +genForNode name = go mempty + where + go :: [GenConstraint] -> TermGenerator RuleTerm + go constraints = + TermGenerator + { tgGenerator = do + rule <- resolveRef name + let + termGen = genForCTree rule + tgGenerator $ foldr' constrain termGen constraints + , tgConstrain = \c -> Just $ go $ c : constraints + } -- | Take a reference and resolve it to the relevant Tree, following multiple -- links if necessary. @@ -682,7 +674,7 @@ generateFromName n = do case mRule of Nothing -> error $ "Unbound reference: " <> show n Just val -> - genForCTree val >>= \case + tgGenerator (genForCTree val) >>= \case SingleTerm x -> pure x _ -> error $ @@ -698,7 +690,7 @@ generateFromGRef ref = do mRule <- lookupGRef ref case mRule of Nothing -> error $ "Unbound generic reference: " <> show ref - Just val -> genForCTree val + Just val -> tgGenerator $ genForCTree val sizeBiasedBool :: MonadGen m => m Bool sizeBiasedBool = sized $ \sz -> (> 1) <$> choose (0, sz) @@ -716,28 +708,27 @@ listOfScaled1 g = sized $ \sz -> do -- | Apply an occurence indicator to a group entry applyOccurenceIndicator :: OccurrenceIndicator -> - CBORGen RuleTerm -> - CBORGen RuleTerm -applyOccurenceIndicator OIOptional oldGen = - sizeBiasedBool >>= \case - False -> pure $ GroupTerm mempty - True -> oldGen -applyOccurenceIndicator OIZeroOrMore oldGen = - GroupTerm <$> listOfScaled oldGen -applyOccurenceIndicator OIOneOrMore oldGen = - GroupTerm <$> listOfScaled1 oldGen -applyOccurenceIndicator (OIBounded mlb mub) oldGen = - sized $ \sz -> do - let - lb = fromMaybe 0 mlb - ub = fromMaybe (lb + fromIntegral sz) mub - i <- fromIntegral <$> genBetween (lb, ub) - GroupTerm <$> vectorOf i (scale (`div` (i + 1)) oldGen) - -valueToTerm :: Value -> CBORGen Term -valueToTerm (Value x _) = valueVariantToTerm x - -valueVariantToTerm :: ValueVariant -> CBORGen Term + TermGenerator RuleTerm -> + TermGenerator RuleTerm +applyOccurenceIndicator oi oldGen = simpleGen $ case oi of + OIOptional -> + sizeBiasedBool >>= \case + False -> pure $ GroupTerm mempty + True -> tgGenerator oldGen + OIZeroOrMore -> GroupTerm <$> listOfScaled (tgGenerator oldGen) + OIOneOrMore -> GroupTerm <$> listOfScaled1 (tgGenerator oldGen) + OIBounded mlb mub -> + sized $ \sz -> do + let + lb = fromMaybe 0 mlb + ub = fromMaybe (lb + fromIntegral sz) mub + i <- fromIntegral <$> genBetween (lb, ub) + GroupTerm <$> vectorOf i (scale (`div` (i + 1)) (tgGenerator oldGen)) + +valueToTerm :: Value -> TermGenerator Term +valueToTerm (Value x _) = simpleGen $ valueVariantToTerm x + +valueVariantToTerm :: MonadGen m => ValueVariant -> m Term valueVariantToTerm (VUInt i) | toInteger i <= toInteger (maxBound :: Int) = pure $ TInt (fromIntegral i) | otherwise = pure $ TInteger (fromIntegral i) diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index d282a5bc..c758d273 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -55,7 +55,7 @@ import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe) import Data.Set (Set) import Data.Text (Text) -import Data.Word (Word64, Word8) +import Data.Word (Word8) import GHC.Generics (Generic) import Optics.Lens (Lens') import System.Random (Random) @@ -271,20 +271,25 @@ data GenConstraint Range (Interval CanonicalTerm) | Eq CanonicalTerm | Neq CanonicalTerm + | Default CanonicalTerm | -- | Specifies the indices at which a bit is allowed to be set Bits (Set Word8) | -- | Constrains the string to ones that match the regex Regexp Regex | -- | The bytestring must match the CDDL rule Cbor (CTree GenPhase) + | Cborseq (CTree GenPhase) | -- | Catch-all for nonstandard control operators CustomControl Text Term + | And (CTree GenPhase) + | Within (CTree GenPhase) deriving (Generic) data TermGenerator a = TermGenerator { tgGenerator :: CBORGen a , tgConstrain :: GenConstraint -> Maybe (TermGenerator a) } + deriving (Functor) -- | Constructs a @TermGenerator@ that fails whenever a control operator is -- applied to it. From c487075a7fa781436f8670bf16787cae80789a0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 17 Nov 2026 13:22:28 +0200 Subject: [PATCH 04/37] WIP --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 82 +++++++++++++------ .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 27 ++++-- 2 files changed, 74 insertions(+), 35 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 26efca72..0e7fced9 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -60,6 +60,7 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( genFromInterval, isDefiniteAllowed, isIndefiniteAllowed, + rangeInInterval, simpleGen, withTwiddle, ) @@ -75,8 +76,8 @@ import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Term (Term (..)) import Codec.CBOR.Term qualified as CBOR import Codec.CBOR.Write qualified as CBOR -import Control.Monad (when, zipWithM, (<=<)) -import Control.Monad.Reader (asks) +import Control.Monad (forM, when, zipWithM, (<=<)) +import Control.Monad.Reader (MonadReader, asks) import Data.ByteString (ByteString) import Data.ByteString.Lazy qualified as LBS import Data.Char (chr) @@ -176,13 +177,17 @@ genHalf = go mempty mempty TermGenerator { tgGenerator = let gen = do - half <- toHalf <$> genFromInterval rng `suchThat` (`Set.notMember` exclude) + half <- toHalf <$> rangeInInterval (-65504, 65504) rng `suchThat` (`Set.notMember` exclude) if isDenormalized half then gen else pure $ fromHalf half in gen , tgConstrain = \case - Gen.Range cRng -> Just $ go (rng <> fmap fromIntegral cRng) exclude + Gen.Range cRng -> do + rng' <- forM cRng $ \case + CTFloat f -> Just f + _ -> Nothing + pure $ go (rng <> rng') exclude Gen.Eq term | CTFloat x <- term -> Just $ go (rng <> Interval.singleton x) exclude | otherwise -> Nothing @@ -192,22 +197,27 @@ genHalf = go mempty mempty _ -> Nothing } -genTwiddled :: (TwiddleConfig -> TwiddlePolicy) -> (a -> Term) -> (a -> Term) -> a -> m Term +genTwiddled :: + (TwiddleConfig -> TwiddlePolicy) -> + (a -> Term) -> + (a -> Term) -> + a -> + CBORGen Term genTwiddled getPolicy definite indefinite term = do policy <- asks $ getPolicy . gcTwiddle . geConfig elements $ [definite term | isDefiniteAllowed policy] <> [indefinite term | isIndefiniteAllowed policy] -twiddleArray :: [Term] -> m Term +twiddleArray :: [Term] -> CBORGen Term twiddleArray = genTwiddled tcArrays TList TListI -twiddleMap :: [(Term, Term)] -> m Term +twiddleMap :: [(Term, Term)] -> CBORGen Term twiddleMap = genTwiddled tcMaps TMap TMapI -twiddleText :: Text -> m Term +twiddleText :: Text -> CBORGen Term twiddleText = genTwiddled tcText TString (TStringI . TL.fromStrict) -twiddleBytes :: ByteString -> m Term +twiddleBytes :: ByteString -> CBORGen Term twiddleBytes = genTwiddled tcBytes TBytes (TBytesI . LBS.fromStrict) genTerm :: CBORGen Term @@ -238,10 +248,18 @@ genTerm = genNBytes :: MonadGen m => Int -> m ByteString genNBytes n = liftGen (uniformByteStringM n QC) -genBytes :: MonadGen m => m ByteString -genBytes = sized $ \sz -> do - numElems <- choose (0, sz) - genNBytes numElems +genBytesTerm :: TermGenerator Term +genBytesTerm = + TermGenerator + { tgGenerator = generator + , tgConstrain = \case + _ -> Nothing + } + where + generator = + sized $ \sz -> do + numElems <- choose (0, sz) + twiddleBytes =<< genNBytes numElems genCharAtMostBytes :: MonadGen m => Int -> m Char genCharAtMostBytes 1 = chr <$> choose (0x00, 0x7F) @@ -262,8 +280,18 @@ genNBytesText n = do builder <- go n mempty pure . LT.toStrict $ toLazyText builder -genText :: MonadGen m => m Text -genText = sized $ \sz -> genNBytesText =<< choose (0, sz) +genTextTerm :: TermGenerator Term +genTextTerm = go maxBound + where + go maxSize = + TermGenerator + { tgGenerator = sized $ \sz -> do + n <- choose (0, min maxSize sz) + twiddleText =<< genNBytesText n + , tgConstrain = \case + Interval.Size s -> Just $ go $ min maxSize s + _ -> Nothing + } -- | Primitive types defined by the CDDL specification, with their generators genPostlude :: PTerm -> TermGenerator Term @@ -287,7 +315,7 @@ genPostlude pt = genPTerm =<< faultyPTerm pt genBelowNInt = choose (2 * nintMin, nintMin - 1) -- \| Given a CDDL postlude type, generates a value of that type genPTerm = \case - PTBool -> TBool <$> arbitrary + PTBool -> simpleGen $ TBool <$> arbitrary -- For integers, introduce decision points that sometimes generate -- out-of-bounds values PTUInt -> TInteger <$> genUInt |! oneof [genNInt, genBelowNInt, genAboveUInt] @@ -296,11 +324,11 @@ genPostlude pt = genPTerm =<< faultyPTerm pt PTHalf -> THalf <$> genHalf PTFloat -> TFloat <$> arbitrary PTDouble -> TDouble <$> arbitrary - PTBytes -> twiddleBytes =<< genBytes - PTText -> twiddleText =<< genText + PTBytes -> genBytesTerm + PTText -> genTextTerm PTAny -> simpleGen genTerm - PTNil -> pure TNull - PTUndefined -> pure $ TSimple 23 + PTNil -> simpleGen $ pure TNull + PTUndefined -> simpleGen $ pure $ TSimple 23 -------------------------------------------------------------------------------- -- Kinds of terms @@ -377,15 +405,15 @@ annotateTerm = \case CTree.CTreeE (GenValidator _ _) -> id genForCTree :: HasCallStack => CTree GenPhase -> TermGenerator RuleTerm -genForCTree node = annotateTerm node $ case node of +genForCTree node = case node of CTree.Literal v -> SingleTerm <$> valueToTerm v CTree.Postlude pt -> SingleTerm <$> genPostlude pt CTree.Map nodes -> genMap nodes CTree.Array nodes -> genArray nodes - CTree.Choice (NE.toList -> nodes) -> do + CTree.Choice (NE.toList -> nodes) -> simpleGen $ do ix <- choose (0, length nodes - 1) - genForCTree $ nodes !! ix - CTree.Group nodes -> GroupTerm <$> traverse genForCTree nodes + tgGenerator . genForCTree $ nodes !! ix + CTree.Group nodes -> simpleGen $ GroupTerm <$> traverse (tgGenerator . genForCTree) nodes CTree.KV key value _cut -> genKV key value CTree.Occur item occurs -> applyOccurenceIndicator occurs (genForCTree item) @@ -594,7 +622,7 @@ genControl :: genControl op target controller = constrain constraint (genForCTree target) where constraint = case op of - CtlOp.Size -> Gen.Size $ Interval _ _ + CtlOp.Size -> Gen.Size _ CtlOp.Bits -> Gen.Bits _ CtlOp.Regexp -> Gen.Regexp _ CtlOp.Cbor -> Gen.Cbor _ @@ -739,8 +767,8 @@ valueVariantToTerm (VBignum i) = pure $ TInteger i valueVariantToTerm (VFloat16 i) = pure $ THalf i valueVariantToTerm (VFloat32 i) = pure $ TFloat i valueVariantToTerm (VFloat64 i) = pure $ TDouble i -valueVariantToTerm (VText t) = twiddleText t -valueVariantToTerm (VBytes b) = twiddleBytes b +valueVariantToTerm (VText t) = simpleGen $ twiddleText t +valueVariantToTerm (VBytes b) = simpleGen $ twiddleBytes b valueVariantToTerm (VBool b) = pure $ TBool b instance IndexMappable CTree GenPhase ValidatorPhase where diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index c758d273..1c3737bf 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -41,6 +41,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( singleton, contains, genFromInterval, + rangeInInterval, ) where import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm) @@ -55,7 +56,6 @@ import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe) import Data.Set (Set) import Data.Text (Text) -import Data.Word (Word8) import GHC.Generics (Generic) import Optics.Lens (Lens') import System.Random (Random) @@ -185,7 +185,7 @@ data IntervalBound a = OpenBound a | ClosedBound a | Unbounded - deriving (Eq, Show) + deriving (Eq, Show, Functor, Foldable, Traversable) boundary :: IntervalBound a -> Maybe a boundary = \case @@ -194,7 +194,7 @@ boundary = \case ClosedBound x -> Just x data Interval a = Interval (IntervalBound a) (IntervalBound a) - deriving (Eq, Show) + deriving (Eq, Show, Functor, Foldable, Traversable) -- | This function checks whether the interval contains any elements. It does -- not take the bounds of the type into account, it only checks whether the @@ -258,14 +258,25 @@ genFromInterval :: ) => Interval a -> m a -genFromInterval int@(Interval lo hi) = choose (boundLo, boundHi) `suchThat` contains int +genFromInterval = rangeInInterval (minBound, maxBound) + +rangeInInterval :: + ( MonadGen m + , Random a + , Ord a + ) => + (a, a) -> + Interval a -> + m a +rangeInInterval (lb, ub) int@(Interval lo hi) = + choose (boundLo, boundHi) `suchThat` contains int where - boundLo = fromMaybe minBound $ boundary lo - boundHi = fromMaybe maxBound $ boundary hi + boundLo = fromMaybe lb $ boundary lo + boundHi = fromMaybe ub $ boundary hi data GenConstraint = -- | Constrains the size of a string or bytestring in bytes - Size (Interval CanonicalTerm) + Size Int | -- | Constrains the range of allowed values to the interval. This also covers -- the .gt and .lt operators. Range (Interval CanonicalTerm) @@ -273,7 +284,7 @@ data GenConstraint | Neq CanonicalTerm | Default CanonicalTerm | -- | Specifies the indices at which a bit is allowed to be set - Bits (Set Word8) + Bits (Set Int) | -- | Constrains the string to ones that match the regex Regexp Regex | -- | The bytestring must match the CDDL rule From 07469c8ad3ce7369064ecc82a84197ffa99b1a57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 17 Nov 2026 14:52:27 +0200 Subject: [PATCH 05/37] WIP --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 161 +++++++++++------- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 29 +++- 2 files changed, 122 insertions(+), 68 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 0e7fced9..86b3531f 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -23,11 +23,14 @@ module Codec.CBOR.Cuddle.CBOR.Gen ( twiddleMap, twiddleText, twiddleBytes, + evalDouble, + evalInteger, + evalArray, ) where #if MIN_VERSION_random(1,3,0) #endif -import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm (..), nintMin, toCanonical, uintMax) +import Codec.CBOR.Cuddle.CBOR.Canonical (nintMin, toCanonical, uintMax) import Codec.CBOR.Cuddle.CBOR.Validator (validateAgainst) import Codec.CBOR.Cuddle.CDDL ( GRef (..), @@ -52,12 +55,10 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenConstraint, GenEnv (..), GenPhase, - Interval (..), TermGenerator (..), TwiddleConfig (..), TwiddlePolicy (..), constrain, - genFromInterval, isDefiniteAllowed, isIndefiniteAllowed, rangeInInterval, @@ -74,10 +75,8 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( import Codec.CBOR.Cuddle.CDDL.Resolve (XXCTree (..), showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Term (Term (..)) -import Codec.CBOR.Term qualified as CBOR -import Codec.CBOR.Write qualified as CBOR -import Control.Monad (forM, when, zipWithM, (<=<)) -import Control.Monad.Reader (MonadReader, asks) +import Control.Monad (forM, zipWithM) +import Control.Monad.Reader (asks) import Data.ByteString (ByteString) import Data.ByteString.Lazy qualified as LBS import Data.Char (chr) @@ -96,8 +95,9 @@ import Data.Text.Lazy qualified as TL import Data.Text.Lazy.Builder (toLazyText) import Data.Text.Lazy.Builder qualified as LB import Data.Word (Word64, Word8) +import GHC.Float (double2Float, float2Double) import GHC.Stack (HasCallStack) -import Numeric.Half (Half (..), fromHalf, toHalf) +import Numeric.Half (fromHalf, toHalf) import Prettyprinter (Pretty (..), layoutCompact) import Prettyprinter.Render.Text (renderStrict) import System.Random.Stateful (Random, StatefulGen (..), runStateGen_, uniformByteStringM) @@ -184,16 +184,15 @@ genHalf = go mempty mempty in gen , tgConstrain = \case Gen.Range cRng -> do - rng' <- forM cRng $ \case - CTFloat f -> Just f - _ -> Nothing + -- TODO think about the edges + rng' <- forM cRng $ fmap double2Float . evalDouble pure $ go (rng <> rng') exclude Gen.Eq term - | CTFloat x <- term -> Just $ go (rng <> Interval.singleton x) exclude + | Just x <- evalDouble term -> Just $ go (rng <> Interval.singleton (double2Float x)) exclude | otherwise -> Nothing Gen.Neq term - | CTFloat x <- term -> Just $ go rng $ Set.insert x exclude - | otherwise -> Just $ go rng exclude + | Just x <- evalDouble term -> Just $ go rng $ Set.insert (double2Float x) exclude + | otherwise -> Nothing _ -> Nothing } @@ -289,19 +288,28 @@ genTextTerm = go maxBound n <- choose (0, min maxSize sz) twiddleText =<< genNBytesText n , tgConstrain = \case - Interval.Size s -> Just $ go $ min maxSize s + Interval.Size s -> Just $ go $ min maxSize $ fromIntegral s _ -> Nothing } -- | Primitive types defined by the CDDL specification, with their generators genPostlude :: PTerm -> TermGenerator Term -genPostlude pt = genPTerm =<< faultyPTerm pt +genPostlude pt = go $ genPTerm pt where + -- Constraints only reach the generator for @pt@: a term of a different + -- type is invalid whatever the control operator says. + go tg = + TermGenerator + { tgGenerator = do + p <- faultyPTerm pt + tgGenerator $ if p == pt then tg else genPTerm p + , tgConstrain = fmap go . tgConstrain tg + } genExcluding ls = elements (filter (`notElem` ls) [minBound .. maxBound]) nonPInteger p = pure p |! genExcluding [PTUInt, PTNInt, PTInt, PTAny] - -- \| Introduces a decision point that can change the type of the CBOR term that is generated + -- Introduces a decision point that can change the type of the CBOR term that is generated faultyPTerm t = reweigh 0.1 $ case t of PTAny -> pure PTAny @@ -309,26 +317,35 @@ genPostlude pt = genPTerm =<< faultyPTerm pt p@PTNInt -> nonPInteger p p@PTInt -> nonPInteger p p -> pure p |! genExcluding [PTAny, p] - genUInt = choose (0, uintMax) - genNInt = choose (nintMin, -1) - genAboveUInt = choose (uintMax + 1, 2 * uintMax) - genBelowNInt = choose (2 * nintMin, nintMin - 1) - -- \| Given a CDDL postlude type, generates a value of that type - genPTerm = \case - PTBool -> simpleGen $ TBool <$> arbitrary - -- For integers, introduce decision points that sometimes generate - -- out-of-bounds values - PTUInt -> TInteger <$> genUInt |! oneof [genNInt, genBelowNInt, genAboveUInt] - PTNInt -> TInteger <$> genNInt |! oneof [genUInt, genBelowNInt, genAboveUInt] - PTInt -> TInteger <$> choose (nintMin, uintMax) - PTHalf -> THalf <$> genHalf - PTFloat -> TFloat <$> arbitrary - PTDouble -> TDouble <$> arbitrary - PTBytes -> genBytesTerm - PTText -> genTextTerm - PTAny -> simpleGen genTerm - PTNil -> simpleGen $ pure TNull - PTUndefined -> simpleGen $ pure $ TSimple 23 + +genInteger :: (Integer, Integer) -> (Integer, Integer) -> TermGenerator Term +genInteger validRng invalidRng = simpleGen $ TInteger <$> antiChoose validRng invalidRng + +genFloat :: TermGenerator Float +genFloat = simpleGen arbitrary + +genDouble :: TermGenerator Double +genDouble = simpleGen arbitrary + +-- | Given a CDDL postlude type, generates a value of that type +genPTerm :: PTerm -> TermGenerator Term +genPTerm = \case + PTBool -> simpleGen $ TBool <$> arbitrary + -- For integers, introduce decision points that sometimes generate + -- out-of-bounds values + PTUInt -> genInteger (0, uintMax) outOfBounds + PTNInt -> genInteger (nintMin, -1) outOfBounds + PTInt -> genInteger (nintMin, uintMax) (nintMin, uintMax) + PTHalf -> THalf <$> genHalf + PTFloat -> TFloat <$> genFloat + PTDouble -> TDouble <$> genDouble + PTBytes -> genBytesTerm + PTText -> genTextTerm + PTAny -> simpleGen genTerm + PTNil -> simpleGen $ pure TNull + PTUndefined -> simpleGen $ pure $ TSimple 23 + where + outOfBounds = (2 * nintMin, 2 * uintMax) -------------------------------------------------------------------------------- -- Kinds of terms @@ -358,13 +375,6 @@ dropNegativeGen = mapAntiGen $ liftGen . runAntiGen -- Generator functions -------------------------------------------------------------------------------- -genSized :: HasCallStack => Word64 -> CTree GenPhase -> CBORGen RuleTerm -genSized s target = annotateTerm target $ case target of - CTree.Postlude PTText -> fmap SingleTerm . twiddleText =<< genNBytesText (fromIntegral s) - CTree.Postlude PTBytes -> fmap SingleTerm . twiddleBytes =<< genNBytes (fromIntegral s) - CTree.Postlude PTUInt -> SingleTerm . TInteger <$> choose (0, 256 ^ s - 1) - _ -> error "Cannot apply size operator to target " - range :: Enum a => RangeBound -> a -> a -> (a, a) range ClOpen x y = (x, pred y) range Closed x y = (x, y) @@ -612,6 +622,35 @@ genRange from to bounds = do | a <= b -> choose (range bounds a b) <&> SingleTerm . TDouble (a, b) -> error $ "invalid range (a = " <> show a <> ", b = " <> show b <> ")" +evalDouble :: CTree GenPhase -> CBORGen Double +evalDouble = \case + Literal (Value var _) + | VFloat16 x <- var -> pure $ float2Double x + | VFloat32 x <- var -> pure $ float2Double x + | VFloat64 x <- var -> pure x + CTreeE (GenGenerator _ t) -> evalDouble t + CTreeE (GenValidator _ t) -> evalDouble t + CTreeE (GenRef n) -> evalDouble =<< resolveRef n + _ -> error "Expected a double" + +evalInteger :: CTree GenPhase -> CBORGen Integer +evalInteger = \case + Literal (Value var _) + | VUInt x <- var -> pure $ toInteger x + | VNInt x <- var -> pure . negate $ toInteger x + CTreeE (GenGenerator _ t) -> evalInteger t + CTreeE (GenValidator _ t) -> evalInteger t + CTreeE (GenRef n) -> evalInteger =<< resolveRef n + _ -> error "Expected an integer" + +evalArray :: (CTree GenPhase -> CBORGen a) -> CTree GenPhase -> CBORGen [a] +evalArray f = \case + Array es -> foldMap (fmap (: []) . f) es + CTreeE (GenGenerator _ t) -> evalArray f t + CTreeE (GenValidator _ t) -> evalArray f t + CTreeE (GenRef n) -> evalArray f =<< resolveRef n + _ -> error "Expected an array" + -- | Generate a value with a control operator applied genControl :: HasCallStack => @@ -622,20 +661,20 @@ genControl :: genControl op target controller = constrain constraint (genForCTree target) where constraint = case op of - CtlOp.Size -> Gen.Size _ - CtlOp.Bits -> Gen.Bits _ - CtlOp.Regexp -> Gen.Regexp _ - CtlOp.Cbor -> Gen.Cbor _ - CtlOp.Cborseq -> Gen.Cborseq _ - CtlOp.Within -> Gen.Within _ - CtlOp.And -> Gen.And _ - CtlOp.Lt -> Gen.Range _ - CtlOp.Le -> Gen.Range _ - CtlOp.Gt -> Gen.Range _ - CtlOp.Ge -> Gen.Range _ - CtlOp.Eq -> Gen.Eq _ - CtlOp.Ne -> Gen.Neq _ - CtlOp.Default -> Gen.Default _ + CtlOp.Size -> Gen.Size controller + CtlOp.Bits -> error "Not yet implemented" + CtlOp.Regexp -> error "Not yet implemented" + CtlOp.Cbor -> Gen.Cbor controller + CtlOp.Cborseq -> error "Not yet implemented" + CtlOp.Within -> error "Not yet implemented" + CtlOp.And -> error "Not yet implemented" + CtlOp.Lt -> Gen.Range $ Interval.lessThan controller + CtlOp.Le -> Gen.Range $ Interval.lessThanOrEqual controller + CtlOp.Gt -> Gen.Range $ Interval.greaterThan controller + CtlOp.Ge -> Gen.Range $ Interval.greaterThanOrEqual controller + CtlOp.Eq -> Gen.Eq controller + CtlOp.Ne -> Gen.Neq controller + CtlOp.Default -> Gen.Default controller -- | Generate a value from an enum genEnum :: HasCallStack => CTree GenPhase -> TermGenerator RuleTerm @@ -756,7 +795,7 @@ applyOccurenceIndicator oi oldGen = simpleGen $ case oi of valueToTerm :: Value -> TermGenerator Term valueToTerm (Value x _) = simpleGen $ valueVariantToTerm x -valueVariantToTerm :: MonadGen m => ValueVariant -> m Term +valueVariantToTerm :: ValueVariant -> CBORGen Term valueVariantToTerm (VUInt i) | toInteger i <= toInteger (maxBound :: Int) = pure $ TInt (fromIntegral i) | otherwise = pure $ TInteger (fromIntegral i) @@ -767,8 +806,8 @@ valueVariantToTerm (VBignum i) = pure $ TInteger i valueVariantToTerm (VFloat16 i) = pure $ THalf i valueVariantToTerm (VFloat32 i) = pure $ TFloat i valueVariantToTerm (VFloat64 i) = pure $ TDouble i -valueVariantToTerm (VText t) = simpleGen $ twiddleText t -valueVariantToTerm (VBytes b) = simpleGen $ twiddleBytes b +valueVariantToTerm (VText t) = twiddleText t +valueVariantToTerm (VBytes b) = twiddleBytes b valueVariantToTerm (VBool b) = pure $ TBool b instance IndexMappable CTree GenPhase ValidatorPhase where diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 1c3737bf..53d434b3 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -36,6 +36,10 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( -- * Interval Interval (..), IntervalBound (..), + greaterThanOrEqual, + greaterThan, + lessThanOrEqual, + lessThan, isEmpty, intersect, singleton, @@ -44,7 +48,6 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( rangeInInterval, ) where -import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm) import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..)) import Codec.CBOR.Cuddle.CDDL.CTree (CTree, CTreeRoot (..), XXCTree) import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm) @@ -196,6 +199,18 @@ boundary = \case data Interval a = Interval (IntervalBound a) (IntervalBound a) deriving (Eq, Show, Functor, Foldable, Traversable) +greaterThanOrEqual :: a -> Interval a +greaterThanOrEqual x = Interval (ClosedBound x) Unbounded + +greaterThan :: a -> Interval a +greaterThan x = Interval (OpenBound x) Unbounded + +lessThanOrEqual :: a -> Interval a +lessThanOrEqual x = Interval Unbounded (ClosedBound x) + +lessThan :: a -> Interval a +lessThan x = Interval Unbounded (OpenBound x) + -- | This function checks whether the interval contains any elements. It does -- not take the bounds of the type into account, it only checks whether the -- lower bound is smaller than the upper bound @@ -276,15 +291,15 @@ rangeInInterval (lb, ub) int@(Interval lo hi) = data GenConstraint = -- | Constrains the size of a string or bytestring in bytes - Size Int + Size (CTree GenPhase) | -- | Constrains the range of allowed values to the interval. This also covers -- the .gt and .lt operators. - Range (Interval CanonicalTerm) - | Eq CanonicalTerm - | Neq CanonicalTerm - | Default CanonicalTerm + Range (Interval (CTree GenPhase)) + | Eq (CTree GenPhase) + | Neq (CTree GenPhase) + | Default (CTree GenPhase) | -- | Specifies the indices at which a bit is allowed to be set - Bits (Set Int) + Bits (Set Integer) | -- | Constrains the string to ones that match the regex Regexp Regex | -- | The bytestring must match the CDDL rule From e0f4a8f8324769db2c78aeb2baa2617e3c0a7864 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 17 Nov 2026 14:55:59 +0200 Subject: [PATCH 06/37] Add deferGen --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 84 ++++++++++--------- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 15 ++++ 2 files changed, 59 insertions(+), 40 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 86b3531f..4185158c 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -52,13 +52,13 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( CBORGen, GenConfig (..), - GenConstraint, GenEnv (..), GenPhase, TermGenerator (..), TwiddleConfig (..), TwiddlePolicy (..), constrain, + deferGen, isDefiniteAllowed, isIndefiniteAllowed, rangeInInterval, @@ -80,10 +80,10 @@ import Control.Monad.Reader (asks) import Data.ByteString (ByteString) import Data.ByteString.Lazy qualified as LBS import Data.Char (chr) -import Data.Foldable (Foldable (..)) import Data.Functor ((<&>)) import Data.List (sortOn) import Data.List.NonEmpty qualified as NE +import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe) import Data.Ord (Down (..)) import Data.Set qualified as Set @@ -288,7 +288,7 @@ genTextTerm = go maxBound n <- choose (0, min maxSize sz) twiddleText =<< genNBytesText n , tgConstrain = \case - Interval.Size s -> Just $ go $ min maxSize $ fromIntegral s + Interval.Size s -> go . min maxSize . fromIntegral <$> evalInteger s _ -> Nothing } @@ -622,34 +622,44 @@ genRange from to bounds = do | a <= b -> choose (range bounds a b) <&> SingleTerm . TDouble (a, b) -> error $ "invalid range (a = " <> show a <> ", b = " <> show b <> ")" -evalDouble :: CTree GenPhase -> CBORGen Double +-- | Replace every rule reference with the rule it names. The result is built +-- lazily, so a reference to a recursive rule is only unfolded as far as it is +-- inspected. +inlineRefs :: CTreeRoot GenPhase -> CTree GenPhase -> CTree GenPhase +inlineRefs root@(CTreeRoot rules) = foldCTree inlineExt (inlineRefs root) + where + inlineExt = \case + GenRef n -> + inlineRefs root . fromMaybe (error $ "Unbound reference: " <> show n) $ Map.lookup n rules + GenGenerator g t -> CTreeE . GenGenerator g $ inlineRefs root t + GenValidator v t -> CTreeE . GenValidator v $ inlineRefs root t + +evalDouble :: CTree GenPhase -> Maybe Double evalDouble = \case Literal (Value var _) - | VFloat16 x <- var -> pure $ float2Double x - | VFloat32 x <- var -> pure $ float2Double x - | VFloat64 x <- var -> pure x + | VFloat16 x <- var -> Just $ float2Double x + | VFloat32 x <- var -> Just $ float2Double x + | VFloat64 x <- var -> Just x CTreeE (GenGenerator _ t) -> evalDouble t CTreeE (GenValidator _ t) -> evalDouble t - CTreeE (GenRef n) -> evalDouble =<< resolveRef n - _ -> error "Expected a double" + _ -> Nothing -evalInteger :: CTree GenPhase -> CBORGen Integer +evalInteger :: CTree GenPhase -> Maybe Integer evalInteger = \case Literal (Value var _) - | VUInt x <- var -> pure $ toInteger x - | VNInt x <- var -> pure . negate $ toInteger x + | VUInt x <- var -> Just $ toInteger x + | VNInt x <- var -> Just . negate $ toInteger x + | VBignum x <- var -> Just x CTreeE (GenGenerator _ t) -> evalInteger t CTreeE (GenValidator _ t) -> evalInteger t - CTreeE (GenRef n) -> evalInteger =<< resolveRef n - _ -> error "Expected an integer" + _ -> Nothing -evalArray :: (CTree GenPhase -> CBORGen a) -> CTree GenPhase -> CBORGen [a] +evalArray :: (CTree GenPhase -> Maybe a) -> CTree GenPhase -> Maybe [a] evalArray f = \case - Array es -> foldMap (fmap (: []) . f) es + Array es -> traverse f es CTreeE (GenGenerator _ t) -> evalArray f t CTreeE (GenValidator _ t) -> evalArray f t - CTreeE (GenRef n) -> evalArray f =<< resolveRef n - _ -> error "Expected an array" + _ -> Nothing -- | Generate a value with a control operator applied genControl :: @@ -658,23 +668,28 @@ genControl :: CTree GenPhase -> CTree GenPhase -> TermGenerator RuleTerm -genControl op target controller = constrain constraint (genForCTree target) +genControl op target controller = deferGen $ do + -- The controller may name other rules, which can only be looked up while + -- generating + root <- asks $ gcRoot . geConfig + pure $ constrain (constraint $ inlineRefs root controller) (genForCTree target) where - constraint = case op of - CtlOp.Size -> Gen.Size controller + constraint ctl = case op of + CtlOp.Size -> Gen.Size ctl CtlOp.Bits -> error "Not yet implemented" CtlOp.Regexp -> error "Not yet implemented" + -- Generated from rather than evaluated, so it keeps its references CtlOp.Cbor -> Gen.Cbor controller CtlOp.Cborseq -> error "Not yet implemented" CtlOp.Within -> error "Not yet implemented" CtlOp.And -> error "Not yet implemented" - CtlOp.Lt -> Gen.Range $ Interval.lessThan controller - CtlOp.Le -> Gen.Range $ Interval.lessThanOrEqual controller - CtlOp.Gt -> Gen.Range $ Interval.greaterThan controller - CtlOp.Ge -> Gen.Range $ Interval.greaterThanOrEqual controller - CtlOp.Eq -> Gen.Eq controller - CtlOp.Ne -> Gen.Neq controller - CtlOp.Default -> Gen.Default controller + CtlOp.Lt -> Gen.Range $ Interval.lessThan ctl + CtlOp.Le -> Gen.Range $ Interval.lessThanOrEqual ctl + CtlOp.Gt -> Gen.Range $ Interval.greaterThan ctl + CtlOp.Ge -> Gen.Range $ Interval.greaterThanOrEqual ctl + CtlOp.Eq -> Gen.Eq ctl + CtlOp.Ne -> Gen.Neq ctl + CtlOp.Default -> Gen.Default ctl -- | Generate a value from an enum genEnum :: HasCallStack => CTree GenPhase -> TermGenerator RuleTerm @@ -703,18 +718,7 @@ genTag t node = simpleGen $ do _ -> error "Tag controller does not correspond to a single term" genForNode :: HasCallStack => Name -> TermGenerator RuleTerm -genForNode name = go mempty - where - go :: [GenConstraint] -> TermGenerator RuleTerm - go constraints = - TermGenerator - { tgGenerator = do - rule <- resolveRef name - let - termGen = genForCTree rule - tgGenerator $ foldr' constrain termGen constraints - , tgConstrain = \c -> Just $ go $ c : constraints - } +genForNode name = deferGen $ genForCTree <$> resolveRef name -- | Take a reference and resolve it to the relevant Tree, following multiple -- links if necessary. diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 53d434b3..8e7220ed 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -18,6 +18,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( TermGenerator (..), simpleGen, constrain, + deferGen, -- * Twiddling TwiddleConfig (..), @@ -330,3 +331,17 @@ constrain :: GenConstraint -> TermGenerator a -> TermGenerator a constrain c (TermGenerator _ f) = case f c of Just g -> g Nothing -> error "Failed to apply constraint" + +-- | A 'TermGenerator' that can only be built while generating, for example +-- because building it needs to look up a rule. Constraints applied to it are +-- kept and applied in order once it has been built. +deferGen :: CBORGen (TermGenerator a) -> TermGenerator a +deferGen mkGen = go [] + where + go cs = + TermGenerator + { tgGenerator = do + g <- mkGen + tgGenerator $ foldr constrain g cs + , tgConstrain = \c -> Just . go $ c : cs + } From d57e317a0abdaa9195d62316c734c2abe079875c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 17 Nov 2026 15:17:22 +0200 Subject: [PATCH 07/37] WIP --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 109 +++++++++++------------------- 1 file changed, 39 insertions(+), 70 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 4185158c..9bb7de73 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -83,7 +83,6 @@ import Data.Char (chr) import Data.Functor ((<&>)) import Data.List (sortOn) import Data.List.NonEmpty qualified as NE -import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe) import Data.Ord (Down (..)) import Data.Set qualified as Set @@ -98,8 +97,6 @@ import Data.Word (Word64, Word8) import GHC.Float (double2Float, float2Double) import GHC.Stack (HasCallStack) import Numeric.Half (fromHalf, toHalf) -import Prettyprinter (Pretty (..), layoutCompact) -import Prettyprinter.Render.Text (renderStrict) import System.Random.Stateful (Random, StatefulGen (..), runStateGen_, uniformByteStringM) import Test.AntiGen ( MonadAntiGen (..), @@ -183,16 +180,16 @@ genHalf = go mempty mempty else pure $ fromHalf half in gen , tgConstrain = \case - Gen.Range cRng -> do + Gen.Range cRng -> Just $ deferGen $ do -- TODO think about the edges rng' <- forM cRng $ fmap double2Float . evalDouble pure $ go (rng <> rng') exclude - Gen.Eq term - | Just x <- evalDouble term -> Just $ go (rng <> Interval.singleton (double2Float x)) exclude - | otherwise -> Nothing - Gen.Neq term - | Just x <- evalDouble term -> Just $ go rng $ Set.insert (double2Float x) exclude - | otherwise -> Nothing + Gen.Eq term -> Just $ deferGen $ do + x <- evalDouble term + pure $ go (rng <> Interval.singleton (double2Float x)) exclude + Gen.Neq term -> Just $ deferGen $ do + x <- evalDouble term + pure $ go rng $ Set.insert (double2Float x) exclude _ -> Nothing } @@ -248,17 +245,20 @@ genNBytes :: MonadGen m => Int -> m ByteString genNBytes n = liftGen (uniformByteStringM n QC) genBytesTerm :: TermGenerator Term -genBytesTerm = - TermGenerator - { tgGenerator = generator - , tgConstrain = \case - _ -> Nothing - } +genBytesTerm = go maxBound where - generator = - sized $ \sz -> do - numElems <- choose (0, sz) - twiddleBytes =<< genNBytes numElems + go maxSize = + TermGenerator + { tgGenerator = + sized $ \sz -> do + numElems <- choose (0, min maxSize sz) + twiddleBytes =<< genNBytes numElems + , tgConstrain = \case + Gen.Size szRule -> Just $ deferGen $ do + sz <- evalInteger szRule + pure $ go $ min maxSize $ fromIntegral sz + _ -> Nothing + } genCharAtMostBytes :: MonadGen m => Int -> m Char genCharAtMostBytes 1 = chr <$> choose (0x00, 0x7F) @@ -288,7 +288,9 @@ genTextTerm = go maxBound n <- choose (0, min maxSize sz) twiddleText =<< genNBytesText n , tgConstrain = \case - Interval.Size s -> go . min maxSize . fromIntegral <$> evalInteger s + Gen.Size szRule -> Just $ deferGen $ do + sz <- evalInteger szRule + pure . go . min maxSize $ fromIntegral sz _ -> Nothing } @@ -393,27 +395,6 @@ genBetween rng = do sizeBounds = (0, fromIntegral size) antiChoose rng sizeBounds --- | Annotate a generator with the label derived from a CTree node. --- Control nodes are transparent — the annotation comes from the target inside. -annotateTerm :: MonadAntiGen m => CTree GenPhase -> m a -> m a -annotateTerm = \case - CTree.Literal _ -> annotate "literal" - CTree.Postlude pt -> annotate $ renderStrict . layoutCompact $ pretty pt - CTree.Map _ -> annotate "map" - CTree.Array _ -> annotate "array" - CTree.Choice _ -> id - CTree.Group _ -> annotate "group" - CTree.KV {} -> annotate "kv" - CTree.Occur {} -> id - CTree.Range {} -> annotate "range" - CTree.Control {} -> id - CTree.Enum _ -> annotate "enum" - CTree.Unwrap _ -> annotate "unwrap" - CTree.Tag {} -> annotate "tag" - CTree.CTreeE (GenRef n) -> annotate (unName n) - CTree.CTreeE (GenGenerator _ _) -> annotate "custom_generator" - CTree.CTreeE (GenValidator _ _) -> id - genForCTree :: HasCallStack => CTree GenPhase -> TermGenerator RuleTerm genForCTree node = case node of CTree.Literal v -> SingleTerm <$> valueToTerm v @@ -622,44 +603,35 @@ genRange from to bounds = do | a <= b -> choose (range bounds a b) <&> SingleTerm . TDouble (a, b) -> error $ "invalid range (a = " <> show a <> ", b = " <> show b <> ")" --- | Replace every rule reference with the rule it names. The result is built --- lazily, so a reference to a recursive rule is only unfolded as far as it is --- inspected. -inlineRefs :: CTreeRoot GenPhase -> CTree GenPhase -> CTree GenPhase -inlineRefs root@(CTreeRoot rules) = foldCTree inlineExt (inlineRefs root) - where - inlineExt = \case - GenRef n -> - inlineRefs root . fromMaybe (error $ "Unbound reference: " <> show n) $ Map.lookup n rules - GenGenerator g t -> CTreeE . GenGenerator g $ inlineRefs root t - GenValidator v t -> CTreeE . GenValidator v $ inlineRefs root t - -evalDouble :: CTree GenPhase -> Maybe Double +evalDouble :: CTree GenPhase -> CBORGen Double evalDouble = \case Literal (Value var _) - | VFloat16 x <- var -> Just $ float2Double x - | VFloat32 x <- var -> Just $ float2Double x - | VFloat64 x <- var -> Just x + | VFloat16 x <- var -> pure $ float2Double x + | VFloat32 x <- var -> pure $ float2Double x + | VFloat64 x <- var -> pure x CTreeE (GenGenerator _ t) -> evalDouble t CTreeE (GenValidator _ t) -> evalDouble t - _ -> Nothing + CTreeE (GenRef n) -> evalDouble =<< resolveRef n + _ -> error "Expected double" -evalInteger :: CTree GenPhase -> Maybe Integer +evalInteger :: CTree GenPhase -> CBORGen Integer evalInteger = \case Literal (Value var _) - | VUInt x <- var -> Just $ toInteger x - | VNInt x <- var -> Just . negate $ toInteger x - | VBignum x <- var -> Just x + | VUInt x <- var -> pure $ toInteger x + | VNInt x <- var -> pure . negate $ toInteger x + | VBignum x <- var -> pure x CTreeE (GenGenerator _ t) -> evalInteger t CTreeE (GenValidator _ t) -> evalInteger t - _ -> Nothing + CTreeE (GenRef n) -> evalInteger =<< resolveRef n + _ -> error "Expected integer" -evalArray :: (CTree GenPhase -> Maybe a) -> CTree GenPhase -> Maybe [a] +evalArray :: (CTree GenPhase -> CBORGen a) -> CTree GenPhase -> CBORGen [a] evalArray f = \case Array es -> traverse f es CTreeE (GenGenerator _ t) -> evalArray f t CTreeE (GenValidator _ t) -> evalArray f t - _ -> Nothing + CTreeE (GenRef n) -> evalArray f =<< resolveRef n + _ -> error "Expected array" -- | Generate a value with a control operator applied genControl :: @@ -669,10 +641,7 @@ genControl :: CTree GenPhase -> TermGenerator RuleTerm genControl op target controller = deferGen $ do - -- The controller may name other rules, which can only be looked up while - -- generating - root <- asks $ gcRoot . geConfig - pure $ constrain (constraint $ inlineRefs root controller) (genForCTree target) + pure $ constrain (constraint controller) (genForCTree target) where constraint ctl = case op of CtlOp.Size -> Gen.Size ctl From 73a53f5bf37e6553150d310a1a980dd25d5b04b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 17 Nov 2026 15:45:14 +0200 Subject: [PATCH 08/37] make QC size bounds soft not hard caps --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 48 ++++++++++++++----- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 16 +++++-- 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 9bb7de73..e81f0118 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -54,13 +54,18 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenConfig (..), GenEnv (..), GenPhase, + Interval (..), + IntervalBound (..), TermGenerator (..), TwiddleConfig (..), TwiddlePolicy (..), constrain, deferGen, + genFromInterval, + greaterThanOrEqual, isDefiniteAllowed, isIndefiniteAllowed, + lessThanOrEqual, rangeInInterval, simpleGen, withTwiddle, @@ -244,19 +249,28 @@ genTerm = genNBytes :: MonadGen m => Int -> m ByteString genNBytes n = liftGen (uniformByteStringM n QC) +-- | Caps a length range at the QuickCheck size, unless that would leave it +-- empty, in which case the range is returned unchanged. +capAtSize :: Int -> Interval Int -> Interval Int +capAtSize sz int + | Interval.isEmpty capped = int + | otherwise = capped + where + capped = int <> lessThanOrEqual sz + genBytesTerm :: TermGenerator Term -genBytesTerm = go maxBound +genBytesTerm = go $ greaterThanOrEqual 0 where - go maxSize = + go szRange = TermGenerator { tgGenerator = sized $ \sz -> do - numElems <- choose (0, min maxSize sz) + numElems <- genFromInterval $ capAtSize sz szRange twiddleBytes =<< genNBytes numElems , tgConstrain = \case - Gen.Size szRule -> Just $ deferGen $ do - sz <- evalInteger szRule - pure $ go $ min maxSize $ fromIntegral sz + Gen.Size rngRule -> Just $ deferGen $ do + newRange <- evalInterval evalInteger rngRule + pure $ go $ szRange <> fmap fromIntegral newRange _ -> Nothing } @@ -280,17 +294,17 @@ genNBytesText n = do pure . LT.toStrict $ toLazyText builder genTextTerm :: TermGenerator Term -genTextTerm = go maxBound +genTextTerm = go $ greaterThanOrEqual 0 where - go maxSize = + go sizeRange = TermGenerator { tgGenerator = sized $ \sz -> do - n <- choose (0, min maxSize sz) + n <- genFromInterval $ capAtSize sz sizeRange twiddleText =<< genNBytesText n , tgConstrain = \case - Gen.Size szRule -> Just $ deferGen $ do - sz <- evalInteger szRule - pure . go . min maxSize $ fromIntegral sz + Gen.Size rngRule -> Just $ deferGen $ do + newRange <- evalInterval evalInteger rngRule + pure . go $ sizeRange <> fmap fromIntegral newRange _ -> Nothing } @@ -633,6 +647,16 @@ evalArray f = \case CTreeE (GenRef n) -> evalArray f =<< resolveRef n _ -> error "Expected array" +evalInterval :: (CTree GenPhase -> CBORGen a) -> CTree GenPhase -> CBORGen (Interval a) +evalInterval f = \case + Range loRule hiRule bound -> do + lo <- f loRule + hi <- f hiRule + pure $ Interval (ClosedBound lo) $ case bound of + ClOpen -> OpenBound hi + Closed -> ClosedBound hi + x -> Interval.singleton <$> f x + -- | Generate a value with a control operator applied genControl :: HasCallStack => diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 8e7220ed..051734f9 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -61,6 +61,7 @@ import Data.Maybe (fromMaybe) import Data.Set (Set) import Data.Text (Text) import GHC.Generics (Generic) +import GHC.Stack (HasCallStack) import Optics.Lens (Lens') import System.Random (Random) import Test.AntiGen (AntiGen, MonadAntiGen (..)) @@ -267,25 +268,32 @@ instance Ord a => Monoid (Interval a) where mempty = Interval Unbounded Unbounded genFromInterval :: - ( MonadGen m + ( HasCallStack + , MonadGen m , Bounded a , Random a , Ord a + , Show a ) => Interval a -> m a genFromInterval = rangeInInterval (minBound, maxBound) +-- | Generates a value in the interval, using the given bounds in place of +-- missing boundaries. Fails if the interval is empty (see 'isEmpty'). rangeInInterval :: - ( MonadGen m + ( HasCallStack + , MonadGen m , Random a , Ord a + , Show a ) => (a, a) -> Interval a -> m a -rangeInInterval (lb, ub) int@(Interval lo hi) = - choose (boundLo, boundHi) `suchThat` contains int +rangeInInterval (lb, ub) int@(Interval lo hi) + | isEmpty int = error $ "rangeInInterval: empty interval " <> show int + | otherwise = choose (boundLo, boundHi) `suchThat` contains int where boundLo = fromMaybe lb $ boundary lo boundHi = fromMaybe ub $ boundary hi From f3a3d00ce7ee5c7373ca7b9b158239b60bc0f27c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 17 Nov 2026 16:41:11 +0200 Subject: [PATCH 09/37] Implement integer constraints --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 31 ++++++++++++++++--- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 24 ++++++++++++-- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index e81f0118..00e14414 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -334,8 +334,29 @@ genPostlude pt = go $ genPTerm pt p@PTInt -> nonPInteger p p -> pure p |! genExcluding [PTAny, p] -genInteger :: (Integer, Integer) -> (Integer, Integer) -> TermGenerator Term -genInteger validRng invalidRng = simpleGen $ TInteger <$> antiChoose validRng invalidRng +genInteger :: Interval Integer -> (Integer, Integer) -> TermGenerator Term +genInteger validRng invalidRng = go validRng mempty + where + go validInterval excluded = + TermGenerator + { tgGenerator = do + x <- rangeInInterval invalidRng validInterval `suchThat` (`Set.notMember` excluded) + pure $ TInteger x + , tgConstrain = \case + Interval.Size szRule -> Just $ deferGen $ do + sz <- evalInteger szRule + pure $ go (validInterval <> lessThanOrEqual (2 ^ sz)) excluded + Interval.Range intRule -> Just $ deferGen $ do + int <- traverse evalInteger intRule + pure $ go (validInterval <> int) excluded + Interval.Eq r -> Just $ deferGen $ do + x <- evalInteger r + pure $ go (validInterval <> Interval.singleton x) excluded + Interval.Neq r -> Just $ deferGen $ do + x <- evalInteger r + pure $ go validInterval $ Set.insert x excluded + _ -> Nothing + } genFloat :: TermGenerator Float genFloat = simpleGen arbitrary @@ -349,9 +370,9 @@ genPTerm = \case PTBool -> simpleGen $ TBool <$> arbitrary -- For integers, introduce decision points that sometimes generate -- out-of-bounds values - PTUInt -> genInteger (0, uintMax) outOfBounds - PTNInt -> genInteger (nintMin, -1) outOfBounds - PTInt -> genInteger (nintMin, uintMax) (nintMin, uintMax) + PTUInt -> genInteger (Interval (ClosedBound 0) (ClosedBound uintMax)) outOfBounds + PTNInt -> genInteger (Interval (ClosedBound nintMin) $ ClosedBound $ -1) outOfBounds + PTInt -> genInteger (Interval (ClosedBound nintMin) (ClosedBound uintMax)) outOfBounds PTHalf -> THalf <$> genHalf PTFloat -> TFloat <$> genFloat PTDouble -> TDouble <$> genDouble diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 051734f9..81cf58c2 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -1,7 +1,9 @@ {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} +{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeData #-} {-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE UndecidableInstances #-} module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenPhase, @@ -33,6 +35,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( -- * Contstraints GenConstraint (..), + showConstraint, -- * Interval Interval (..), @@ -53,13 +56,13 @@ import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..)) import Codec.CBOR.Cuddle.CDDL.CTree (CTree, CTreeRoot (..), XXCTree) import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (TermValidator) -import Codec.CBOR.Term (Term) import Control.Monad.Reader (MonadReader (..), MonadTrans (..), ReaderT (..), asks, mapReaderT) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe) import Data.Set (Set) import Data.Text (Text) +import Data.Text qualified as T import GHC.Generics (Generic) import GHC.Stack (HasCallStack) import Optics.Lens (Lens') @@ -315,7 +318,7 @@ data GenConstraint Cbor (CTree GenPhase) | Cborseq (CTree GenPhase) | -- | Catch-all for nonstandard control operators - CustomControl Text Term + CustomControl Text (CTree GenPhase) | And (CTree GenPhase) | Within (CTree GenPhase) deriving (Generic) @@ -338,7 +341,7 @@ simpleGen gen = constrain :: GenConstraint -> TermGenerator a -> TermGenerator a constrain c (TermGenerator _ f) = case f c of Just g -> g - Nothing -> error "Failed to apply constraint" + Nothing -> error $ "Failed to apply constraint:\n" <> T.unpack (showConstraint c) -- | A 'TermGenerator' that can only be built while generating, for example -- because building it needs to look up a rule. Constraints applied to it are @@ -353,3 +356,18 @@ deferGen mkGen = go [] tgGenerator $ foldr constrain g cs , tgConstrain = \c -> Just . go $ c : cs } + +showConstraint :: GenConstraint -> Text +showConstraint = \case + Size _ -> ".size" + Range _ -> ".range" + Eq _ -> ".eq" + Neq _ -> ".neq" + Default _ -> ".default" + Bits _ -> ".bits" + Regexp _ -> ".regexp" + Cbor _ -> ".cbor" + Cborseq _ -> ".cborseq" + CustomControl c _ -> "." <> c + And _ -> ".and" + Within _ -> ".within" From eb96381a7f1b6a490523945612ea97e892b1ce16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 17 Nov 2026 16:59:07 +0200 Subject: [PATCH 10/37] Implement cbor constraint --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 00e14414..4dd1474b 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -80,6 +80,8 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( import Codec.CBOR.Cuddle.CDDL.Resolve (XXCTree (..), showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Term (Term (..)) +import Codec.CBOR.Term qualified as CBOR +import Codec.CBOR.Write qualified as CBOR import Control.Monad (forM, zipWithM) import Control.Monad.Reader (asks) import Data.ByteString (ByteString) @@ -259,18 +261,27 @@ capAtSize sz int capped = int <> lessThanOrEqual sz genBytesTerm :: TermGenerator Term -genBytesTerm = go $ greaterThanOrEqual 0 +genBytesTerm = go Nothing $ greaterThanOrEqual 0 where - go szRange = + go mCbor szRange = TermGenerator { tgGenerator = - sized $ \sz -> do - numElems <- genFromInterval $ capAtSize sz szRange - twiddleBytes =<< genNBytes numElems + twiddleBytes =<< case mCbor of + Nothing -> sized $ \sz -> do + numElems <- genFromInterval $ capAtSize sz szRange + genNBytes numElems + Just cbor -> do + term <- tgGenerator $ genForCTree cbor + case term of + SingleTerm t -> pure $ CBOR.toStrictByteString $ CBOR.encodeTerm t + _ -> error "Expected a single term" , tgConstrain = \case Gen.Size rngRule -> Just $ deferGen $ do newRange <- evalInterval evalInteger rngRule - pure $ go $ szRange <> fmap fromIntegral newRange + pure $ go mCbor $ szRange <> fmap fromIntegral newRange + Gen.Cbor cbor + -- Only allow constraining with .cbor once + | Nothing <- mCbor -> Just $ go (Just cbor) szRange _ -> Nothing } From 9c7a9c9d2254d0a68e64ee5352c78f5e92a2113f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 17 Nov 2026 17:16:29 +0200 Subject: [PATCH 11/37] Add Interval module --- cuddle.cabal | 1 + src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 47 ++++---- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 98 +---------------- src/Codec/CBOR/Cuddle/Interval.hs | 103 ++++++++++++++++++ 4 files changed, 133 insertions(+), 116 deletions(-) create mode 100644 src/Codec/CBOR/Cuddle/Interval.hs diff --git a/cuddle.cabal b/cuddle.cabal index 5aa377a1..67d822aa 100644 --- a/cuddle.cabal +++ b/cuddle.cabal @@ -54,6 +54,7 @@ library Codec.CBOR.Cuddle.Comments Codec.CBOR.Cuddle.Huddle Codec.CBOR.Cuddle.IndexMappable + Codec.CBOR.Cuddle.Interval Codec.CBOR.Cuddle.Parser Codec.CBOR.Cuddle.Parser.Lexer Codec.CBOR.Cuddle.Pretty diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 4dd1474b..3e8f2c50 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -54,24 +54,19 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenConfig (..), GenEnv (..), GenPhase, - Interval (..), - IntervalBound (..), TermGenerator (..), TwiddleConfig (..), TwiddlePolicy (..), constrain, deferGen, genFromInterval, - greaterThanOrEqual, isDefiniteAllowed, isIndefiniteAllowed, - lessThanOrEqual, rangeInInterval, simpleGen, withTwiddle, ) import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Gen -import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Interval import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( CustomValidatorResult (..), ValidatorPhase, @@ -79,6 +74,16 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( ) import Codec.CBOR.Cuddle.CDDL.Resolve (XXCTree (..), showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) +import Codec.CBOR.Cuddle.Interval ( + Interval (..), + IntervalBound (..), + greaterThanOrEqual, + intersect, + lessThanOrEqual, + universe, + (..=), + ) +import Codec.CBOR.Cuddle.Interval qualified as Interval import Codec.CBOR.Term (Term (..)) import Codec.CBOR.Term qualified as CBOR import Codec.CBOR.Write qualified as CBOR @@ -175,7 +180,7 @@ simple = [23] genHalf :: TermGenerator Float -genHalf = go mempty mempty +genHalf = go universe mempty where go rng exclude = TermGenerator @@ -190,10 +195,10 @@ genHalf = go mempty mempty Gen.Range cRng -> Just $ deferGen $ do -- TODO think about the edges rng' <- forM cRng $ fmap double2Float . evalDouble - pure $ go (rng <> rng') exclude + pure $ go (rng `intersect` rng') exclude Gen.Eq term -> Just $ deferGen $ do x <- evalDouble term - pure $ go (rng <> Interval.singleton (double2Float x)) exclude + pure $ go (rng `intersect` Interval.singleton (double2Float x)) exclude Gen.Neq term -> Just $ deferGen $ do x <- evalDouble term pure $ go rng $ Set.insert (double2Float x) exclude @@ -258,7 +263,7 @@ capAtSize sz int | Interval.isEmpty capped = int | otherwise = capped where - capped = int <> lessThanOrEqual sz + capped = int `intersect` lessThanOrEqual sz genBytesTerm :: TermGenerator Term genBytesTerm = go Nothing $ greaterThanOrEqual 0 @@ -278,7 +283,7 @@ genBytesTerm = go Nothing $ greaterThanOrEqual 0 , tgConstrain = \case Gen.Size rngRule -> Just $ deferGen $ do newRange <- evalInterval evalInteger rngRule - pure $ go mCbor $ szRange <> fmap fromIntegral newRange + pure $ go mCbor $ szRange `intersect` fmap fromIntegral newRange Gen.Cbor cbor -- Only allow constraining with .cbor once | Nothing <- mCbor -> Just $ go (Just cbor) szRange @@ -315,7 +320,7 @@ genTextTerm = go $ greaterThanOrEqual 0 , tgConstrain = \case Gen.Size rngRule -> Just $ deferGen $ do newRange <- evalInterval evalInteger rngRule - pure . go $ sizeRange <> fmap fromIntegral newRange + pure . go $ sizeRange `intersect` fmap fromIntegral newRange _ -> Nothing } @@ -354,16 +359,16 @@ genInteger validRng invalidRng = go validRng mempty x <- rangeInInterval invalidRng validInterval `suchThat` (`Set.notMember` excluded) pure $ TInteger x , tgConstrain = \case - Interval.Size szRule -> Just $ deferGen $ do + Gen.Size szRule -> Just $ deferGen $ do sz <- evalInteger szRule - pure $ go (validInterval <> lessThanOrEqual (2 ^ sz)) excluded - Interval.Range intRule -> Just $ deferGen $ do + pure $ go (validInterval `intersect` lessThanOrEqual (2 ^ sz)) excluded + Gen.Range intRule -> Just $ deferGen $ do int <- traverse evalInteger intRule - pure $ go (validInterval <> int) excluded - Interval.Eq r -> Just $ deferGen $ do + pure $ go (validInterval `intersect` int) excluded + Gen.Eq r -> Just $ deferGen $ do x <- evalInteger r - pure $ go (validInterval <> Interval.singleton x) excluded - Interval.Neq r -> Just $ deferGen $ do + pure $ go (validInterval `intersect` Interval.singleton x) excluded + Gen.Neq r -> Just $ deferGen $ do x <- evalInteger r pure $ go validInterval $ Set.insert x excluded _ -> Nothing @@ -381,9 +386,9 @@ genPTerm = \case PTBool -> simpleGen $ TBool <$> arbitrary -- For integers, introduce decision points that sometimes generate -- out-of-bounds values - PTUInt -> genInteger (Interval (ClosedBound 0) (ClosedBound uintMax)) outOfBounds - PTNInt -> genInteger (Interval (ClosedBound nintMin) $ ClosedBound $ -1) outOfBounds - PTInt -> genInteger (Interval (ClosedBound nintMin) (ClosedBound uintMax)) outOfBounds + PTUInt -> genInteger (0 ..= uintMax) outOfBounds + PTNInt -> genInteger (nintMin ..= (-1)) outOfBounds + PTInt -> genInteger (nintMin ..= uintMax) outOfBounds PTHalf -> THalf <$> genHalf PTFloat -> TFloat <$> genFloat PTDouble -> TDouble <$> genDouble diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 81cf58c2..654bf750 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -21,6 +21,8 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( simpleGen, constrain, deferGen, + genFromInterval, + rangeInInterval, -- * Twiddling TwiddleConfig (..), @@ -36,26 +38,13 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( -- * Contstraints GenConstraint (..), showConstraint, - - -- * Interval - Interval (..), - IntervalBound (..), - greaterThanOrEqual, - greaterThan, - lessThanOrEqual, - lessThan, - isEmpty, - intersect, - singleton, - contains, - genFromInterval, - rangeInInterval, ) where import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..)) import Codec.CBOR.Cuddle.CDDL.CTree (CTree, CTreeRoot (..), XXCTree) import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (TermValidator) +import Codec.CBOR.Cuddle.Interval (Interval (..), boundary, contains, isEmpty) import Control.Monad.Reader (MonadReader (..), MonadTrans (..), ReaderT (..), asks, mapReaderT) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map @@ -189,87 +178,6 @@ data instance XXCTree GenPhase class HasGenerator a where generatorL :: Lens' a (Maybe (TermGenerator RuleTerm)) -data IntervalBound a - = OpenBound a - | ClosedBound a - | Unbounded - deriving (Eq, Show, Functor, Foldable, Traversable) - -boundary :: IntervalBound a -> Maybe a -boundary = \case - Unbounded -> Nothing - OpenBound x -> Just x - ClosedBound x -> Just x - -data Interval a = Interval (IntervalBound a) (IntervalBound a) - deriving (Eq, Show, Functor, Foldable, Traversable) - -greaterThanOrEqual :: a -> Interval a -greaterThanOrEqual x = Interval (ClosedBound x) Unbounded - -greaterThan :: a -> Interval a -greaterThan x = Interval (OpenBound x) Unbounded - -lessThanOrEqual :: a -> Interval a -lessThanOrEqual x = Interval Unbounded (ClosedBound x) - -lessThan :: a -> Interval a -lessThan x = Interval Unbounded (OpenBound x) - --- | This function checks whether the interval contains any elements. It does --- not take the bounds of the type into account, it only checks whether the --- lower bound is smaller than the upper bound -isEmpty :: Ord a => Interval a -> Bool -isEmpty = \case - Interval (ClosedBound lo) (ClosedBound hi) -> lo > hi - Interval lo hi - | Just l <- boundary lo - , Just h <- boundary hi -> - l >= h - _ -> False - --- | Computes the intersection of two intervals. The result may be empty (see --- 'isEmpty'). -intersect :: Ord a => Interval a -> Interval a -> Interval a -intersect (Interval lo1 hi1) (Interval lo2 hi2) = - Interval (tighter (>) lo1 lo2) (tighter (<) hi1 hi2) - where - -- Picks the more restrictive of two bounds. @better x y@ holds when @x@ - -- is strictly more restrictive than @y@. On equal boundaries an open bound - -- is more restrictive than a closed one. - tighter _ Unbounded b = b - tighter _ a Unbounded = a - tighter better a b - | Just x <- boundary a - , Just y <- boundary b = - if - | better x y -> a - | better y x -> b - | OpenBound _ <- a -> a - | otherwise -> b - tighter _ a _ = a - -singleton :: a -> Interval a -singleton x = Interval (ClosedBound x) (ClosedBound x) - -contains :: Ord a => Interval a -> a -> Bool -contains (Interval lo hi) x = satisifesUpper && satisfiesLower - where - satisifesUpper = case hi of - Unbounded -> True - OpenBound y -> x < y - ClosedBound y -> x <= y - satisfiesLower = case lo of - Unbounded -> True - OpenBound y -> y < x - ClosedBound y -> y <= x - -instance Ord a => Semigroup (Interval a) where - (<>) = intersect - -instance Ord a => Monoid (Interval a) where - mempty = Interval Unbounded Unbounded - genFromInterval :: ( HasCallStack , MonadGen m diff --git a/src/Codec/CBOR/Cuddle/Interval.hs b/src/Codec/CBOR/Cuddle/Interval.hs new file mode 100644 index 00000000..d2731bf5 --- /dev/null +++ b/src/Codec/CBOR/Cuddle/Interval.hs @@ -0,0 +1,103 @@ +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE MultiWayIf #-} + +module Codec.CBOR.Cuddle.Interval ( + Interval (..), + IntervalBound (..), + (...), + (..=), + boundary, + greaterThanOrEqual, + greaterThan, + lessThanOrEqual, + lessThan, + isEmpty, + intersect, + singleton, + contains, + universe, +) where + +data IntervalBound a + = OpenBound a + | ClosedBound a + | Unbounded + deriving (Eq, Show, Functor, Foldable, Traversable) + +boundary :: IntervalBound a -> Maybe a +boundary = \case + Unbounded -> Nothing + OpenBound x -> Just x + ClosedBound x -> Just x + +data Interval a = Interval (IntervalBound a) (IntervalBound a) + deriving (Eq, Show, Functor, Foldable, Traversable) + +greaterThanOrEqual :: a -> Interval a +greaterThanOrEqual x = Interval (ClosedBound x) Unbounded + +greaterThan :: a -> Interval a +greaterThan x = Interval (OpenBound x) Unbounded + +lessThanOrEqual :: a -> Interval a +lessThanOrEqual x = Interval Unbounded (ClosedBound x) + +lessThan :: a -> Interval a +lessThan x = Interval Unbounded (OpenBound x) + +(...) :: a -> a -> Interval a +lo ... hi = Interval (ClosedBound lo) (OpenBound hi) + +(..=) :: a -> a -> Interval a +lo ..= hi = Interval (ClosedBound lo) (ClosedBound hi) + +-- | This function checks whether the interval contains any elements. It does +-- not take the bounds of the type into account, it only checks whether the +-- lower bound is smaller than the upper bound +isEmpty :: Ord a => Interval a -> Bool +isEmpty = \case + Interval (ClosedBound lo) (ClosedBound hi) -> lo > hi + Interval lo hi + | Just l <- boundary lo + , Just h <- boundary hi -> + l >= h + _ -> False + +-- | Computes the intersection of two intervals. The result may be empty (see +-- 'isEmpty'). +intersect :: Ord a => Interval a -> Interval a -> Interval a +intersect (Interval lo1 hi1) (Interval lo2 hi2) = + Interval (tighter (>) lo1 lo2) (tighter (<) hi1 hi2) + where + -- Picks the more restrictive of two bounds. @better x y@ holds when @x@ + -- is strictly more restrictive than @y@. On equal boundaries an open bound + -- is more restrictive than a closed one. + tighter _ Unbounded b = b + tighter _ a Unbounded = a + tighter better a b + | Just x <- boundary a + , Just y <- boundary b = + if + | better x y -> a + | better y x -> b + | OpenBound _ <- a -> a + | otherwise -> b + tighter _ a _ = a + +singleton :: a -> Interval a +singleton x = Interval (ClosedBound x) (ClosedBound x) + +contains :: Ord a => Interval a -> a -> Bool +contains (Interval lo hi) x = satisifesUpper && satisfiesLower + where + satisifesUpper = case hi of + Unbounded -> True + OpenBound y -> x < y + ClosedBound y -> x <= y + satisfiesLower = case lo of + Unbounded -> True + OpenBound y -> y < x + ClosedBound y -> y <= x + +universe :: Interval a +universe = Interval Unbounded Unbounded From da38163e41be755e0a444a3d4540f99906695bfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 19 Nov 2026 12:28:39 +0200 Subject: [PATCH 12/37] Add CTreeE cases to evalInterval --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 3e8f2c50..f37e6e1d 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -692,6 +692,9 @@ evalInterval f = \case pure $ Interval (ClosedBound lo) $ case bound of ClOpen -> OpenBound hi Closed -> ClosedBound hi + CTreeE (GenGenerator _ t) -> evalInterval f t + CTreeE (GenValidator _ t) -> evalInterval f t + CTreeE (GenRef n) -> evalInterval f =<< resolveRef n x -> Interval.singleton <$> f x -- | Generate a value with a control operator applied From 8a57610647dbb12f59c3120a64f3d545402684e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 19 Nov 2026 13:54:31 +0200 Subject: [PATCH 13/37] Remove twiddler --- bin/Main.hs | 7 +- example/Main.hs | 4 +- src/Codec/CBOR/Cuddle/CBOR/Canonical.hs | 2 + src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 71 +++++++++-------- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 76 +++---------------- .../Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs | 23 +----- test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs | 7 +- 7 files changed, 57 insertions(+), 133 deletions(-) diff --git a/bin/Main.hs b/bin/Main.hs index 26c57393..f38986e2 100644 --- a/bin/Main.hs +++ b/bin/Main.hs @@ -19,8 +19,6 @@ import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenConfig (..), runCBORGen, - twiddleAll, - twiddleNothing, ) import Codec.CBOR.Cuddle.CDDL.Postlude (appendPostlude) import Codec.CBOR.Cuddle.CDDL.Resolve ( @@ -404,10 +402,7 @@ run = \case | goNegative = 1 | otherwise = 0 cfg = - GenConfig - { gcRoot = mapIndex mt - , gcTwiddle = if goTwiddle then twiddleAll else twiddleNothing - } + GenConfig $ mapIndex mt term = runGen seed goSize . zapAntiGen zapN . runCBORGen cfg $ generateFromName (Name itemName) formatted = formatTerm term outputFormat case outputTo of diff --git a/example/Main.hs b/example/Main.hs index 7e0c08bb..50fdba2e 100644 --- a/example/Main.hs +++ b/example/Main.hs @@ -7,7 +7,7 @@ module Main (main) where import Codec.CBOR.Cuddle.CBOR.Gen (generateFromName) import Codec.CBOR.Cuddle.CDDL (Name (..)) -import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen, twiddleAll) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) import Codec.CBOR.Cuddle.CDDL.Resolve (MonoSimplePhase, fullResolveCDDL) import Codec.CBOR.Cuddle.Huddle (toCDDL) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..), mapCDDLDropExt) @@ -49,7 +49,7 @@ main = do case fullResolveCDDL (mapCDDLDropExt res) of Left nre -> error $ show nre Right resolved -> do - let cfg = GenConfig {gcRoot = mapIndex resolved, gcTwiddle = twiddleAll} + let cfg = GenConfig {gcRoot = mapIndex resolved} term <- generate . runAntiGen . runCBORGen cfg $ generateFromName (Name (T.pack name)) print term [] -> do diff --git a/src/Codec/CBOR/Cuddle/CBOR/Canonical.hs b/src/Codec/CBOR/Cuddle/CBOR/Canonical.hs index 89593bd2..94ee74b4 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Canonical.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Canonical.hs @@ -8,6 +8,8 @@ module Codec.CBOR.Cuddle.CBOR.Canonical ( toCanonical, uintMax, nintMin, + unsignedToBytes, + bytesToUnsigned, ) where import Codec.CBOR.Term (Term (..)) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index f37e6e1d..a04b8885 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -30,7 +30,11 @@ module Codec.CBOR.Cuddle.CBOR.Gen ( #if MIN_VERSION_random(1,3,0) #endif -import Codec.CBOR.Cuddle.CBOR.Canonical (nintMin, toCanonical, uintMax) +import Codec.CBOR.Cuddle.CBOR.Canonical ( + nintMin, + toCanonical, + uintMax, + ) import Codec.CBOR.Cuddle.CBOR.Validator (validateAgainst) import Codec.CBOR.Cuddle.CDDL ( GRef (..), @@ -55,16 +59,12 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenEnv (..), GenPhase, TermGenerator (..), - TwiddleConfig (..), - TwiddlePolicy (..), + bindGen, constrain, deferGen, genFromInterval, - isDefiniteAllowed, - isIndefiniteAllowed, rangeInInterval, simpleGen, - withTwiddle, ) import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Gen import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( @@ -206,27 +206,24 @@ genHalf = go universe mempty } genTwiddled :: - (TwiddleConfig -> TwiddlePolicy) -> (a -> Term) -> (a -> Term) -> a -> CBORGen Term -genTwiddled getPolicy definite indefinite term = do - policy <- asks $ getPolicy . gcTwiddle . geConfig - elements $ - [definite term | isDefiniteAllowed policy] <> [indefinite term | isIndefiniteAllowed policy] +genTwiddled definite indefinite term = do + elements [definite term, indefinite term] twiddleArray :: [Term] -> CBORGen Term -twiddleArray = genTwiddled tcArrays TList TListI +twiddleArray = genTwiddled TList TListI twiddleMap :: [(Term, Term)] -> CBORGen Term -twiddleMap = genTwiddled tcMaps TMap TMapI +twiddleMap = genTwiddled TMap TMapI twiddleText :: Text -> CBORGen Term -twiddleText = genTwiddled tcText TString (TStringI . TL.fromStrict) +twiddleText = genTwiddled TString (TStringI . TL.fromStrict) twiddleBytes :: ByteString -> CBORGen Term -twiddleBytes = genTwiddled tcBytes TBytes (TBytesI . LBS.fromStrict) +twiddleBytes = genTwiddled TBytes (TBytesI . LBS.fromStrict) genTerm :: CBORGen Term genTerm = @@ -265,13 +262,13 @@ capAtSize sz int where capped = int `intersect` lessThanOrEqual sz -genBytesTerm :: TermGenerator Term -genBytesTerm = go Nothing $ greaterThanOrEqual 0 +genBytes :: TermGenerator ByteString +genBytes = go Nothing $ greaterThanOrEqual 0 where go mCbor szRange = TermGenerator { tgGenerator = - twiddleBytes =<< case mCbor of + case mCbor of Nothing -> sized $ \sz -> do numElems <- genFromInterval $ capAtSize sz szRange genNBytes numElems @@ -309,14 +306,14 @@ genNBytesText n = do builder <- go n mempty pure . LT.toStrict $ toLazyText builder -genTextTerm :: TermGenerator Term +genTextTerm :: TermGenerator Text genTextTerm = go $ greaterThanOrEqual 0 where go sizeRange = TermGenerator { tgGenerator = sized $ \sz -> do n <- genFromInterval $ capAtSize sz sizeRange - twiddleText =<< genNBytesText n + genNBytesText n , tgConstrain = \case Gen.Size rngRule -> Just $ deferGen $ do newRange <- evalInterval evalInteger rngRule @@ -350,14 +347,13 @@ genPostlude pt = go $ genPTerm pt p@PTInt -> nonPInteger p p -> pure p |! genExcluding [PTAny, p] -genInteger :: Interval Integer -> (Integer, Integer) -> TermGenerator Term +genInteger :: Interval Integer -> (Integer, Integer) -> TermGenerator Integer genInteger validRng invalidRng = go validRng mempty where go validInterval excluded = TermGenerator - { tgGenerator = do - x <- rangeInInterval invalidRng validInterval `suchThat` (`Set.notMember` excluded) - pure $ TInteger x + { tgGenerator = + rangeInInterval invalidRng validInterval `suchThat` (`Set.notMember` excluded) , tgConstrain = \case Gen.Size szRule -> Just $ deferGen $ do sz <- evalInteger szRule @@ -386,14 +382,14 @@ genPTerm = \case PTBool -> simpleGen $ TBool <$> arbitrary -- For integers, introduce decision points that sometimes generate -- out-of-bounds values - PTUInt -> genInteger (0 ..= uintMax) outOfBounds - PTNInt -> genInteger (nintMin ..= (-1)) outOfBounds - PTInt -> genInteger (nintMin ..= uintMax) outOfBounds + PTUInt -> TInteger <$> genInteger (0 ..= uintMax) outOfBounds + PTNInt -> TInteger <$> genInteger (nintMin ..= (-1)) outOfBounds + PTInt -> TInteger <$> genInteger (nintMin ..= uintMax) outOfBounds PTHalf -> THalf <$> genHalf PTFloat -> TFloat <$> genFloat PTDouble -> TDouble <$> genDouble - PTBytes -> genBytesTerm - PTText -> genTextTerm + PTBytes -> bindGen twiddleBytes genBytes + PTText -> bindGen twiddleText genTextTerm PTAny -> simpleGen genTerm PTNil -> simpleGen $ pure TNull PTUndefined -> simpleGen $ pure $ TSimple 23 @@ -740,15 +736,18 @@ genTag t node = simpleGen $ do then tgGenerator $ genForCTree node else do tag <- faultyNum t - enc <- case tag of + innerTerm <- case tag of + -- TODO remove this case once we switch away from cborg's Term n - | n == 2 || n == 3 -> - -- TODO remove this once `cborg` can decode indefinite bytes in bignums - withTwiddle (\c -> c {tcBytes = DefiniteOnly}) . tgGenerator $ genForCTree node + | n == 2 || n == 3 -> do + res <- tgGenerator $ genForCTree node + pure $ case res of + SingleTerm (TBytesI bs) -> SingleTerm $ TBytes $ LBS.toStrict bs + _ -> res _ -> tgGenerator $ genForCTree node - case enc of - SingleTerm x -> pure $ SingleTerm $ TTagged tag x - _ -> error "Tag controller does not correspond to a single term" + case innerTerm of + SingleTerm term -> pure . SingleTerm $ TTagged tag term + _ -> error "Expected a single term" genForNode :: HasCallStack => Name -> TermGenerator RuleTerm genForNode name = deferGen $ genForCTree <$> resolveRef name diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 654bf750..1fa29faa 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -21,20 +21,10 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( simpleGen, constrain, deferGen, + bindGen, genFromInterval, rangeInInterval, - -- * Twiddling - TwiddleConfig (..), - TwiddlePolicy (..), - isIndefiniteAllowed, - isDefiniteAllowed, - twiddleUniform, - twiddleAll, - twiddleNothing, - withTwiddle, - disableTwiddle, - -- * Contstraints GenConstraint (..), showConstraint, @@ -62,47 +52,9 @@ import Text.Regex.TDFA (Regex) type data GenPhase -data TwiddlePolicy - = DefiniteOnly - | IndefiniteOnly - | DefiniteAndIndefinite - deriving (Generic, Show, Eq, Ord, Enum) - -isDefiniteAllowed :: TwiddlePolicy -> Bool -isDefiniteAllowed IndefiniteOnly = False -isDefiniteAllowed _ = True - -isIndefiniteAllowed :: TwiddlePolicy -> Bool -isIndefiniteAllowed DefiniteOnly = False -isIndefiniteAllowed _ = True - -data TwiddleConfig = TwiddleConfig - { tcBytes :: !TwiddlePolicy - , tcArrays :: !TwiddlePolicy - , tcText :: !TwiddlePolicy - , tcMaps :: !TwiddlePolicy - } - deriving (Generic, Show, Eq, Ord) - -twiddleUniform :: TwiddlePolicy -> TwiddleConfig -twiddleUniform policy = - TwiddleConfig - { tcBytes = policy - , tcArrays = policy - , tcText = policy - , tcMaps = policy - } - -twiddleAll :: TwiddleConfig -twiddleAll = twiddleUniform DefiniteAndIndefinite - -twiddleNothing :: TwiddleConfig -twiddleNothing = twiddleUniform DefiniteOnly - -- | User-supplied configuration for the generator monad. -data GenConfig = GenConfig +newtype GenConfig = GenConfig { gcRoot :: CTreeRoot GenPhase - , gcTwiddle :: !TwiddleConfig } deriving (Generic) @@ -147,21 +99,6 @@ instance MonadCddl CBORGen where withAntiGen :: (AntiGen a -> AntiGen b) -> CBORGen a -> CBORGen b withAntiGen f (CBORGen m) = CBORGen $ mapReaderT f m -withTwiddle :: (TwiddleConfig -> TwiddleConfig) -> CBORGen a -> CBORGen a -withTwiddle f = - local - ( \env -> - env - { geConfig = - (geConfig env) - { gcTwiddle = f (gcTwiddle $ geConfig env) - } - } - ) - -disableTwiddle :: CBORGen a -> CBORGen a -disableTwiddle = withTwiddle $ const twiddleNothing - -- | Run an action with the given local generic bindings installed. -- Used to wrap custom generators attached to generic rules so that -- 'lookupGRef' resolves to the type bound at the enclosing rule. @@ -265,6 +202,15 @@ deferGen mkGen = go [] , tgConstrain = \c -> Just . go $ c : cs } +-- | Runs a generator action on each value the generator produces. +-- Constraints still apply to the original generator. +bindGen :: (a -> CBORGen b) -> TermGenerator a -> TermGenerator b +bindGen f tg = + TermGenerator + { tgGenerator = f =<< tgGenerator tg + , tgConstrain = fmap (bindGen f) . tgConstrain tg + } + showConstraint :: GenConstraint -> Text showConstraint = \case Size _ -> ".size" diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs index e061b5e7..d3dd8e6c 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs @@ -7,7 +7,7 @@ module Test.Codec.CBOR.Cuddle.CDDL.GeneratorSpec (spec) where import Codec.CBOR.Cuddle.CBOR.Gen (GenPhase, generateFromName) import Codec.CBOR.Cuddle.CDDL (Name) import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot (..)) -import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen, twiddleAll) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) import Codec.CBOR.Cuddle.CDDL.Resolve (MonoReferenced, MonoSimplePhase, fullResolveCDDL) import Codec.CBOR.Cuddle.Huddle (Huddle, toCDDL) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..), mapCDDLDropExt) @@ -40,13 +40,7 @@ import Test.QuickCheck (Gen, Property, Testable (..), classify, counterexample) import Text.Pretty.Simple (pShow) generateCDDL :: CTreeRoot GenPhase -> Gen Term -generateCDDL cddl = runAntiGen . runCBORGen cfg $ generateFromName "root" - where - cfg = - GenConfig - { gcRoot = cddl - , gcTwiddle = twiddleAll - } +generateCDDL cddl = runAntiGen . runCBORGen (GenConfig cddl) $ generateFromName "root" tryResolveHuddle :: HasCallStack => Huddle -> SpecM () (CTreeRoot MonoReferenced) tryResolveHuddle huddle = do @@ -56,12 +50,7 @@ tryResolveHuddle huddle = do expectZapInvalidates :: CTreeRoot MonoReferenced -> Name -> Property expectZapInvalidates cddl name = property $ do - let - cfg = - GenConfig - { gcRoot = mapIndex cddl - , gcTwiddle = twiddleAll - } + let cfg = GenConfig $ mapIndex cddl res@ZapResult {zrValue} <- zapAntiGenResult 1 . runCBORGen cfg $ generateFromName name let bs = toStrictByteString $ encodeTerm zrValue @@ -157,11 +146,7 @@ spec = do describe "Tagged bytes zapping" $ do taggedBytesCddl <- tryResolveHuddle taggedUintExample - let cfg = - GenConfig - { gcRoot = mapIndex taggedBytesCddl - , gcTwiddle = twiddleAll - } + let cfg = GenConfig $ mapIndex taggedBytesCddl prop "labels zapped result" $ do ZapResult {zrValue} <- zapAntiGenResult 1 . runCBORGen cfg $ generateFromName "root" diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs index 0f9bebf6..e9b1dd53 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs @@ -28,7 +28,7 @@ import Codec.CBOR.Cuddle.CDDL (Name (..)) import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot (..)) import Codec.CBOR.Cuddle.CDDL.CTree qualified as CTree import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm (..)) -import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen, twiddleAll) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (TermValidator) import Codec.CBOR.Cuddle.CDDL.Postlude (appendPostlude) import Codec.CBOR.Cuddle.CDDL.Resolve (MonoReferenced, fullResolveCDDL) @@ -117,10 +117,7 @@ genAndValidateRule description name resolvedCddl = prop description $ do let genCfg = - GenConfig - { gcRoot = mapIndex resolvedCddl - , gcTwiddle = twiddleAll - } + GenConfig $ mapIndex resolvedCddl cborTerm <- runAntiGen . runCBORGen genCfg $ generateFromName name let generatedCbor = toStrictByteString $ encodeTerm cborTerm From de1772343f32dd8fd3a798d839d0f72c925177e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 19 Nov 2026 14:43:11 +0200 Subject: [PATCH 14/37] Export some helpers --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 14 +++++++++++--- src/Codec/CBOR/Cuddle/CDDL/Options.hs | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 src/Codec/CBOR/Cuddle/CDDL/Options.hs diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index a04b8885..90316309 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -26,6 +26,14 @@ module Codec.CBOR.Cuddle.CBOR.Gen ( evalDouble, evalInteger, evalArray, + + -- * Generator helpers + genNBytes, + genNBytesText, + genBytes, + genText, + genInteger, + genTerm, ) where #if MIN_VERSION_random(1,3,0) @@ -306,8 +314,8 @@ genNBytesText n = do builder <- go n mempty pure . LT.toStrict $ toLazyText builder -genTextTerm :: TermGenerator Text -genTextTerm = go $ greaterThanOrEqual 0 +genText :: TermGenerator Text +genText = go $ greaterThanOrEqual 0 where go sizeRange = TermGenerator @@ -389,7 +397,7 @@ genPTerm = \case PTFloat -> TFloat <$> genFloat PTDouble -> TDouble <$> genDouble PTBytes -> bindGen twiddleBytes genBytes - PTText -> bindGen twiddleText genTextTerm + PTText -> bindGen twiddleText genText PTAny -> simpleGen genTerm PTNil -> simpleGen $ pure TNull PTUndefined -> simpleGen $ pure $ TSimple 23 diff --git a/src/Codec/CBOR/Cuddle/CDDL/Options.hs b/src/Codec/CBOR/Cuddle/CDDL/Options.hs new file mode 100644 index 00000000..60f27da4 --- /dev/null +++ b/src/Codec/CBOR/Cuddle/CDDL/Options.hs @@ -0,0 +1,24 @@ +module Codec.CBOR.Cuddle.CDDL.Options ( + CuddleOptions (..), + AllowedLengthEncodings (..), +) where + +import Data.Default.Class (Default (..)) + +data AllowedLengthEncodings + = DefiniteAndIndefinite + | DefiniteOnly + | IndefiniteOnly + deriving (Eq, Ord, Enum, Bounded, Show) + +data CuddleOptions = CuddleOptions + { optAllowedLengthEncodings :: AllowedLengthEncodings + , optMapFailOnDuplicateKey :: Bool + } + +instance Default CuddleOptions where + def = + CuddleOptions + { optAllowedLengthEncodings = DefiniteAndIndefinite + , optMapFailOnDuplicateKey = False + } From eb292fd131bd3e0506c6c667883d2dc1f785c911 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 20 Nov 2026 14:30:40 +0200 Subject: [PATCH 15/37] Add IsConstrainable to Rule --- src/Codec/CBOR/Cuddle/Huddle.hs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Codec/CBOR/Cuddle/Huddle.hs b/src/Codec/CBOR/Cuddle/Huddle.hs index d91ac1cd..3e5d0155 100644 --- a/src/Codec/CBOR/Cuddle/Huddle.hs +++ b/src/Codec/CBOR/Cuddle/Huddle.hs @@ -527,6 +527,9 @@ instance IsConstrainable (Value a) a where instance IsConstrainable GRef CGRefType where toConstrainable = CGRef +instance IsConstrainable Rule CRefType where + toConstrainable (Rule {..}) = CRef $ AnyRef ruleName ruleDefinition + unconstrained :: Value a -> Constrained unconstrained v = Constrained (CValue v) def [] @@ -612,6 +615,7 @@ class IsCborable a instance IsCborable ByteString instance IsCborable AnyRef instance IsCborable GRef +instance IsCborable CRefType cbor :: (IsCborable b, IsConstrainable c b) => c -> Rule -> Constrained cbor v r@(Rule n _ _) = From 824d2e472f08235fb436877722c5ddc906f6e484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 20 Nov 2026 15:26:02 +0200 Subject: [PATCH 16/37] Remove AnyRef in favor of Rule --- src/Codec/CBOR/Cuddle/Huddle.hs | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/Huddle.hs b/src/Codec/CBOR/Cuddle/Huddle.hs index 3e5d0155..f539613b 100644 --- a/src/Codec/CBOR/Cuddle/Huddle.hs +++ b/src/Codec/CBOR/Cuddle/Huddle.hs @@ -481,18 +481,9 @@ inferInteger i -- Constraints and Ranges -------------------------------------------------------------------------------- --- | A reference can be to any type, so we allow it to inhabit all -data AnyRef = AnyRef - { arName :: Name - , arDefinition :: Type0 - } - -instance HasName AnyRef where - getName = arName - data Constrainable a = CValue (Value a) - | CRef AnyRef + | CRef Rule | CGRef GRef -- | Uninhabited type used as marker for the type of thing a CRef sizes @@ -518,7 +509,7 @@ data Constrained where class IsConstrainable a x | a -> x where toConstrainable :: a -> Constrainable x -instance IsConstrainable AnyRef CRefType where +instance IsConstrainable Rule CRefType where toConstrainable = CRef instance IsConstrainable (Value a) a where @@ -527,9 +518,6 @@ instance IsConstrainable (Value a) a where instance IsConstrainable GRef CGRefType where toConstrainable = CGRef -instance IsConstrainable Rule CRefType where - toConstrainable (Rule {..}) = CRef $ AnyRef ruleName ruleDefinition - unconstrained :: Value a -> Constrained unconstrained v = Constrained (CValue v) def [] @@ -613,7 +601,6 @@ sized v sz = class IsCborable a instance IsCborable ByteString -instance IsCborable AnyRef instance IsCborable GRef instance IsCborable CRefType @@ -633,7 +620,6 @@ cbor v r@(Rule n _ _) = class IsComparable a instance IsComparable Int -instance IsComparable AnyRef instance IsComparable GRef le :: (IsComparable a, IsConstrainable c a) => c -> Word64 -> Constrained @@ -1154,7 +1140,7 @@ collectFrom topRs = goT2 (T2Constrained (Constrained c _ refs)) = ( case c of CValue _ -> pure () - CRef AnyRef {..} -> goRule $ Rule arName arDefinition def + CRef rule -> goRule rule CGRef _ -> pure () ) >> mapM_ goRule refs From e28d891c06f7d629290a3db7c1e144c486c10732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 20 Nov 2026 16:55:24 +0200 Subject: [PATCH 17/37] Give custom generators access to the original generator --- src/Codec/CBOR/Cuddle/CBOR/Gen.hs | 2 +- src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs | 2 +- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 5 ++-- src/Codec/CBOR/Cuddle/CDDL/Resolve.hs | 26 +++++++++---------- src/Codec/CBOR/Cuddle/Huddle.hs | 22 +++++++++++----- src/Codec/CBOR/Cuddle/IndexMappable.hs | 2 +- 6 files changed, 34 insertions(+), 25 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs index 90316309..f0417b70 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Gen.hs @@ -469,7 +469,7 @@ genForCTree node = case node of CTree.Unwrap n -> genForCTree n CTree.Tag t n -> genTag t n CTree.CTreeE (GenRef n) -> genForNode n - CTree.CTreeE (GenGenerator gen _) -> gen + CTree.CTreeE (GenGenerator gen n) -> gen $ genForCTree n CTree.CTreeE (GenValidator _ x) -> genForCTree x isInvalidAgainstNode :: CTreeRoot GenPhase -> Term -> CTree GenPhase -> Bool diff --git a/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs b/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs index 2f1cb3b0..e3549a97 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs @@ -32,7 +32,7 @@ data instance XCddl CTreePhase = CTreeXCddl deriving (Generic, Show, Eq, Ord) data instance XRule CTreePhase - = CTreeXRule (Maybe (TermGenerator RuleTerm)) (Maybe TermValidator) + = CTreeXRule (TermGenerator RuleTerm -> TermGenerator RuleTerm) (Maybe TermValidator) deriving (Generic) data instance XXType2 CTreePhase diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 1fa29faa..89c12c96 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -1,5 +1,4 @@ {-# LANGUAGE LambdaCase #-} -{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeData #-} {-# LANGUAGE TypeFamilies #-} @@ -109,11 +108,11 @@ withLocalGenBindings binds = data instance XXCTree GenPhase = GenRef Name - | GenGenerator (TermGenerator RuleTerm) (CTree GenPhase) + | GenGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree GenPhase) | GenValidator TermValidator (CTree GenPhase) class HasGenerator a where - generatorL :: Lens' a (Maybe (TermGenerator RuleTerm)) + generatorL :: Lens' a (TermGenerator RuleTerm -> TermGenerator RuleTerm) genFromInterval :: ( HasCallStack diff --git a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs index 4c7c4022..2bfa9b57 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs @@ -63,9 +63,9 @@ import Control.Monad.State.Strict (StateT (..)) import Data.Generics.Product import Data.Generics.Sum import Data.Hashable -#if __GLASGOW_HASKELL__ < 910 + import Data.List (foldl') -#endif + import Codec.CBOR.Cuddle.CDDL.CTreePhase (CTreePhase, XRule (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( @@ -106,7 +106,7 @@ newtype PartialCTreeRoot i = PartialCTreeRoot (Map.Map Name (ProvidedParameters data CDDLMapEntry = CDDLMapEntry { cmeProvidedParameters :: ProvidedParameters (TypeOrGroup CTreePhase) - , cmeCustomGenerator :: Maybe (TermGenerator RuleTerm) + , cmeCustomGenerator :: TermGenerator RuleTerm -> TermGenerator RuleTerm , cmeCustomValidator :: Maybe TermValidator } deriving (Generic) @@ -157,7 +157,7 @@ asMap cddl = foldl' go Map.empty rules (TOGType _, _) -> error "Attempting to extend a type with a group" (TOGGroup _, _) -> error "Attempting to extend a group with a type" extend tog gps Nothing = - Just $ CDDLMapEntry (toParametrised tog gps) Nothing Nothing + Just $ CDDLMapEntry (toParametrised tog gps) id Nothing -------------------------------------------------------------------------------- -- 2. Conversion to CTree @@ -168,7 +168,7 @@ type data OrReferenced data instance XXCTree OrReferenced = -- | Reference to another node with possible generic arguments supplied OrRef Name [CTree OrReferenced] - | OGenerator (TermGenerator RuleTerm) (CTree OrReferenced) + | OGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree OrReferenced) | OValidator TermValidator (CTree OrReferenced) type data OrReferencedSimple @@ -213,9 +213,7 @@ buildRefCTree rules = PartialCTreeRoot $ toCTreeRule <$> rules toCTreeRule CDDLMapEntry {..} = applyValidator . applyGenerator . toCTreeTOG <$> cmeProvidedParameters where - applyGenerator = case cmeCustomGenerator of - Just g -> CTreeE . OGenerator g - Nothing -> id + applyGenerator = CTreeE . OGenerator cmeCustomGenerator applyValidator = case cmeCustomValidator of Just v -> CTreeE . OValidator v Nothing -> id @@ -416,7 +414,7 @@ instance Pretty (XXCTree i) => Pretty (DistRef i) where data instance XXCTree DistReferenced = DRef (DistRef DistReferenced) - | DGenerator (TermGenerator RuleTerm) (CTree DistReferenced) + | DGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree DistReferenced) | DValidator TermValidator (CTree DistReferenced) type data DistReferencedNoGen @@ -472,7 +470,7 @@ type data MonoReferenced data instance XXCTree MonoReferenced = MRuleRef Name - | MGenerator (TermGenerator RuleTerm) (CTree MonoReferenced) + | MGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree MonoReferenced) | MValidator TermValidator (CTree MonoReferenced) type MonoEnv = BindingEnv DistReferenced MonoReferenced @@ -633,12 +631,14 @@ resolveGenericRef (DRef (GenericRef n)) = do case Map.lookup n localBinds of Just node -> pure node Nothing -> throwNR $ UnboundReference n -resolveGenericRef (DGenerator (TermGenerator g cf) x) = do +resolveGenericRef (DGenerator fGen x) = do binds <- ask @"local" body <- resolveGenericCTree x let bindsGen = mapIndex @CTree @MonoReferenced @GenPhase <$> binds - g' = withLocalGenBindings bindsGen g - pure . CTreeE $ MGenerator (TermGenerator g' cf) body + g' tg = + let TermGenerator newGen m = fGen tg + in TermGenerator (withLocalGenBindings bindsGen newGen) m + pure . CTreeE $ MGenerator g' body resolveGenericRef (DValidator v x) = do binds <- ask @"local" body <- resolveGenericCTree x diff --git a/src/Codec/CBOR/Cuddle/Huddle.hs b/src/Codec/CBOR/Cuddle/Huddle.hs index f539613b..9547d262 100644 --- a/src/Codec/CBOR/Cuddle/Huddle.hs +++ b/src/Codec/CBOR/Cuddle/Huddle.hs @@ -94,7 +94,9 @@ module Codec.CBOR.Cuddle.Huddle ( -- * Generators withCBORGen, + withOverrideCBORGen, withGenerator, + withOverrideGenerator, -- * Validators withValidator, @@ -124,7 +126,7 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( CBORGen, HasGenerator (..), - TermGenerator, + TermGenerator (..), simpleGen, ) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (HasValidator (..), TermValidator) @@ -163,7 +165,7 @@ newtype instance C.XCddl HuddleStage = HuddleXCddl [C.Comment] data instance C.XRule HuddleStage = HuddleXRule { hxrComment :: C.Comment - , hxrGenerator :: Maybe (TermGenerator RuleTerm) + , hxrGenerator :: TermGenerator RuleTerm -> TermGenerator RuleTerm , hxrValidator :: Maybe TermValidator } deriving (Generic) @@ -177,7 +179,8 @@ instance HasValidator (C.XRule HuddleStage) where instance HasGenerator (C.XRule HuddleStage) where generatorL = #hxrGenerator -instance Default (XRule HuddleStage) +instance Default (XRule HuddleStage) where + def = HuddleXRule def id def newtype instance C.XXTopLevel HuddleStage = HuddleXXTopLevel C.Comment deriving (Generic, Semigroup, Monoid, Show, Eq) @@ -1154,7 +1157,7 @@ collectFrom topRs = goRanged (Unranged _) = pure () goRanged (Ranged lb ub _) = goRangeBound lb >> goRangeBound ub goRangeBound (RangeBoundLiteral _) = pure () - goRangeBound (RangeBoundRef n r) = goRule . Rule n r $ HuddleXRule mempty Nothing Nothing + goRangeBound (RangeBoundRef n r) = goRule . Rule n r $ HuddleXRule mempty id Nothing -- | Same as `collectFrom`, but the rules passed into this function will be put -- at the top of the Huddle, and all of their dependencies will be added at @@ -1374,11 +1377,18 @@ toCDDL' HuddleConfig {..} hdl = fmap (\(GRef t) -> GenericParameter (C.Name t) $ HuddleXTerm mempty) (args gr) withGenerator :: HasGenerator a => TermGenerator RuleTerm -> a -> a -withGenerator gen = L.set generatorL $ Just gen +withGenerator g = withOverrideGenerator $ const g + +withOverrideGenerator :: + HasGenerator a => (TermGenerator RuleTerm -> TermGenerator RuleTerm) -> a -> a +withOverrideGenerator = L.set generatorL -- | Use a custom `CBORGen` generator to generate the term. withCBORGen :: HasGenerator a => CBORGen RuleTerm -> a -> a -withCBORGen = withGenerator . simpleGen +withCBORGen g = withOverrideCBORGen $ const g + +withOverrideCBORGen :: HasGenerator a => (CBORGen RuleTerm -> CBORGen RuleTerm) -> a -> a +withOverrideCBORGen f = withOverrideGenerator $ simpleGen . f . tgGenerator withValidator :: HasValidator a => TermValidator -> a -> a withValidator p = L.set validatorL $ Just p diff --git a/src/Codec/CBOR/Cuddle/IndexMappable.hs b/src/Codec/CBOR/Cuddle/IndexMappable.hs index a4804b6b..63650c8f 100644 --- a/src/Codec/CBOR/Cuddle/IndexMappable.hs +++ b/src/Codec/CBOR/Cuddle/IndexMappable.hs @@ -230,7 +230,7 @@ instance IndexMappable XTerm ParserStage CTreePhase where mapIndex _ = CTreeXTerm instance IndexMappable XRule ParserStage CTreePhase where - mapIndex _ = CTreeXRule Nothing Nothing + mapIndex _ = CTreeXRule id Nothing -- ParserStage -> HuddleStage From 1f4be9377815b2b722d91abc1b13f69dbf5d4794 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Mon, 23 Nov 2026 16:24:46 +0200 Subject: [PATCH 18/37] Rename Gen module to Generator --- bin/Main.hs | 2 +- cuddle.cabal | 2 +- example/Main.hs | 2 +- src/Codec/CBOR/Cuddle/CBOR/{Gen.hs => Generator.hs} | 2 +- test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs | 2 +- test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs | 2 +- test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) rename src/Codec/CBOR/Cuddle/CBOR/{Gen.hs => Generator.hs} (99%) diff --git a/bin/Main.hs b/bin/Main.hs index f38986e2..52aa6106 100644 --- a/bin/Main.hs +++ b/bin/Main.hs @@ -6,7 +6,7 @@ module Main (main) where -import Codec.CBOR.Cuddle.CBOR.Gen (generateFromName) +import Codec.CBOR.Cuddle.CBOR.Generator (generateFromName) import Codec.CBOR.Cuddle.CBOR.Validator import Codec.CBOR.Cuddle.CBOR.Validator.Trace ( Evidenced (..), diff --git a/cuddle.cabal b/cuddle.cabal index 67d822aa..e75629cc 100644 --- a/cuddle.cabal +++ b/cuddle.cabal @@ -39,7 +39,7 @@ library import: warnings exposed-modules: Codec.CBOR.Cuddle.CBOR.Canonical - Codec.CBOR.Cuddle.CBOR.Gen + Codec.CBOR.Cuddle.CBOR.Generator Codec.CBOR.Cuddle.CBOR.Validator Codec.CBOR.Cuddle.CBOR.Validator.Trace Codec.CBOR.Cuddle.CDDL diff --git a/example/Main.hs b/example/Main.hs index 50fdba2e..038c546a 100644 --- a/example/Main.hs +++ b/example/Main.hs @@ -5,7 +5,7 @@ module Main (main) where -import Codec.CBOR.Cuddle.CBOR.Gen (generateFromName) +import Codec.CBOR.Cuddle.CBOR.Generator (generateFromName) import Codec.CBOR.Cuddle.CDDL (Name (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) import Codec.CBOR.Cuddle.CDDL.Resolve (MonoSimplePhase, fullResolveCDDL) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs b/src/Codec/CBOR/Cuddle/CBOR/Generator.hs similarity index 99% rename from src/Codec/CBOR/Cuddle/CBOR/Gen.hs rename to src/Codec/CBOR/Cuddle/CBOR/Generator.hs index f0417b70..09ee431b 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Gen.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Generator.hs @@ -14,7 +14,7 @@ {-# OPTIONS_GHC -Wno-orphans #-} -- | Generate example CBOR given a CDDL specification -module Codec.CBOR.Cuddle.CBOR.Gen ( +module Codec.CBOR.Cuddle.CBOR.Generator ( generateFromName, generateFromGRef, GenPhase, diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs index 582cf5d1..150727c5 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs @@ -31,7 +31,7 @@ module Test.Codec.CBOR.Cuddle.CDDL.Examples.Huddle ( tagRangeExample, ) where -import Codec.CBOR.Cuddle.CBOR.Gen (generateFromGRef) +import Codec.CBOR.Cuddle.CBOR.Generator (generateFromGRef) import Codec.CBOR.Cuddle.CBOR.Validator (validateFromGRef) import Codec.CBOR.Cuddle.CDDL (Name) import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm (..)) diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs index d3dd8e6c..148849a5 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs @@ -4,7 +4,7 @@ module Test.Codec.CBOR.Cuddle.CDDL.GeneratorSpec (spec) where -import Codec.CBOR.Cuddle.CBOR.Gen (GenPhase, generateFromName) +import Codec.CBOR.Cuddle.CBOR.Generator (GenPhase, generateFromName) import Codec.CBOR.Cuddle.CDDL (Name) import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs index e9b1dd53..81e17711 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs @@ -12,7 +12,7 @@ module Test.Codec.CBOR.Cuddle.CDDL.Validator ( ) where import Codec.CBOR.Cuddle.CBOR.Canonical (toCanonical) -import Codec.CBOR.Cuddle.CBOR.Gen (generateFromName) +import Codec.CBOR.Cuddle.CBOR.Generator (generateFromName) import Codec.CBOR.Cuddle.CBOR.Validator ( ValidatorPhase, validateCBOR, From c7084ee3d9cb1bcd0689552ec19fa16c398cb11b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 24 Nov 2026 12:41:56 +0200 Subject: [PATCH 19/37] Reorganize modules --- bin/Main.hs | 16 +- cuddle.cabal | 3 +- example/Main.hs | 7 +- src/Codec/CBOR/Cuddle/CBOR/Generator.hs | 15 +- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 79 ++- src/Codec/CBOR/Cuddle/CBOR/Validator/Trace.hs | 459 ----------------- src/Codec/CBOR/Cuddle/CDDL.hs | 179 ++++++- src/Codec/CBOR/Cuddle/CDDL/CTree.hs | 61 ++- src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs | 40 -- src/Codec/CBOR/Cuddle/CDDL/CtlOp.hs | 5 + .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 2 + .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 469 +++++++++++++++++- src/Codec/CBOR/Cuddle/CDDL/Phase.hs | 29 ++ src/Codec/CBOR/Cuddle/CDDL/Resolve.hs | 143 +++--- src/Codec/CBOR/Cuddle/Comments.hs | 23 + src/Codec/CBOR/Cuddle/Huddle.hs | 27 +- src/Codec/CBOR/Cuddle/IndexMappable.hs | 284 +---------- src/Codec/CBOR/Cuddle/Parser.hs | 15 + src/Codec/CBOR/Cuddle/Pretty.hs | 130 ++--- 19 files changed, 984 insertions(+), 1002 deletions(-) delete mode 100644 src/Codec/CBOR/Cuddle/CBOR/Validator/Trace.hs delete mode 100644 src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs create mode 100644 src/Codec/CBOR/Cuddle/CDDL/Phase.hs diff --git a/bin/Main.hs b/bin/Main.hs index 52aa6106..e28e6f86 100644 --- a/bin/Main.hs +++ b/bin/Main.hs @@ -8,23 +8,23 @@ module Main (main) where import Codec.CBOR.Cuddle.CBOR.Generator (generateFromName) import Codec.CBOR.Cuddle.CBOR.Validator -import Codec.CBOR.Cuddle.CBOR.Validator.Trace ( - Evidenced (..), - SValidity (..), - TraceOptions (..), - prettyValidationTrace, - ) -import Codec.CBOR.Cuddle.CDDL (CDDL, Name (..), fromRules, sortCDDL) +import Codec.CBOR.Cuddle.CDDL (CDDL, Name (..), fromRules, mapCDDLDropExt, sortCDDL) import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenConfig (..), runCBORGen, ) +import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( + Evidenced (..), + SValidity (..), + TraceOptions (..), + prettyValidationTrace, + ) import Codec.CBOR.Cuddle.CDDL.Postlude (appendPostlude) import Codec.CBOR.Cuddle.CDDL.Resolve ( fullResolveCDDL, ) -import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..), mapCDDLDropExt) +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Cuddle.Parser (ParserStage, pCDDL) import Codec.CBOR.Cuddle.Pretty (PrettyStage, renderCDDL) import Codec.CBOR.FlatTerm (toFlatTerm) diff --git a/cuddle.cabal b/cuddle.cabal index e75629cc..ad218c68 100644 --- a/cuddle.cabal +++ b/cuddle.cabal @@ -41,14 +41,13 @@ library Codec.CBOR.Cuddle.CBOR.Canonical Codec.CBOR.Cuddle.CBOR.Generator Codec.CBOR.Cuddle.CBOR.Validator - Codec.CBOR.Cuddle.CBOR.Validator.Trace Codec.CBOR.Cuddle.CDDL Codec.CBOR.Cuddle.CDDL.CTree - Codec.CBOR.Cuddle.CDDL.CTreePhase Codec.CBOR.Cuddle.CDDL.CtlOp Codec.CBOR.Cuddle.CDDL.Custom.Core Codec.CBOR.Cuddle.CDDL.Custom.Generator Codec.CBOR.Cuddle.CDDL.Custom.Validator + Codec.CBOR.Cuddle.CDDL.Phase Codec.CBOR.Cuddle.CDDL.Postlude Codec.CBOR.Cuddle.CDDL.Resolve Codec.CBOR.Cuddle.Comments diff --git a/example/Main.hs b/example/Main.hs index 038c546a..ee7118a8 100644 --- a/example/Main.hs +++ b/example/Main.hs @@ -6,11 +6,12 @@ module Main (main) where import Codec.CBOR.Cuddle.CBOR.Generator (generateFromName) -import Codec.CBOR.Cuddle.CDDL (Name (..)) +import Codec.CBOR.Cuddle.CDDL (Name (..), mapCDDLDropExt) import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) -import Codec.CBOR.Cuddle.CDDL.Resolve (MonoSimplePhase, fullResolveCDDL) +import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase) +import Codec.CBOR.Cuddle.CDDL.Resolve (fullResolveCDDL) import Codec.CBOR.Cuddle.Huddle (toCDDL) -import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..), mapCDDLDropExt) +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Cuddle.Parser (pCDDL) import Codec.CBOR.Cuddle.Pretty (PrettyStage) import Conway (conway) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Generator.hs b/src/Codec/CBOR/Cuddle/CBOR/Generator.hs index 09ee431b..65fa7e5f 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Generator.hs @@ -43,7 +43,7 @@ import Codec.CBOR.Cuddle.CBOR.Canonical ( toCanonical, uintMax, ) -import Codec.CBOR.Cuddle.CBOR.Validator (validateAgainst) +import Codec.CBOR.Cuddle.CBOR.Validator (validateTerm) import Codec.CBOR.Cuddle.CDDL ( GRef (..), Name (..), @@ -76,11 +76,12 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( ) import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Gen import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( - CustomValidatorResult (..), + Evidenced (..), + SValidity (..), ValidatorPhase, - runValidator, ) -import Codec.CBOR.Cuddle.CDDL.Resolve (XXCTree (..), showSimple) +import Codec.CBOR.Cuddle.CDDL.Phase (showSimple) +import Codec.CBOR.Cuddle.CDDL.Resolve (XXCTree (..)) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Cuddle.Interval ( Interval (..), @@ -474,9 +475,9 @@ genForCTree node = case node of isInvalidAgainstNode :: CTreeRoot GenPhase -> Term -> CTree GenPhase -> Bool isInvalidAgainstNode cTreeRoot term node = - case runValidator (validateAgainst term $ mapIndex node) (mapIndex cTreeRoot) of - CustomValidatorSuccess -> False - CustomValidatorFailure {} -> True + case validateTerm (mapIndex cTreeRoot) term $ mapIndex node of + Evidenced SValid _ -> False + Evidenced SInvalid _ -> True -- | Generate a map from a list of nodes genMap :: diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 5999860f..24891cac 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -2,44 +2,42 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} +{-# OPTIONS_GHC -Wno-orphans #-} module Codec.CBOR.Cuddle.CBOR.Validator ( validateCBOR, validateFromName, validateFromGRef, validateAgainst, + validateTerm, ValidatorPhase, ValidateCBORError (..), ) where import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm, toCanonical) -import Codec.CBOR.Cuddle.CBOR.Validator.Trace ( +import Codec.CBOR.Cuddle.CDDL hiding (CDDL, Group, Rule) +import Codec.CBOR.Cuddle.CDDL.CTree +import Codec.CBOR.Cuddle.CDDL.CtlOp +import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) +import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( ControlInfo (..), Evidenced (..), - IsValidationTrace (..), ListValidationTrace (..), MapValidationTrace (..), SValidity (..), + ValidateEnv (..), ValidationTrace (..), + Validator, + ValidatorPhase, + XXCTree (..), compareEvidencedProgress, evidence, isValid, mapTrace, - ) -import Codec.CBOR.Cuddle.CDDL hiding (CDDL, Group, Rule) -import Codec.CBOR.Cuddle.CDDL.CTree -import Codec.CBOR.Cuddle.CDDL.CtlOp -import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) -import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( - CustomValidatorResult (..), - TermValidator, - ValidateEnv (..), - Validator, - ValidatorPhase, - XXCTree (..), + measureProgress, runValidator, ) -import Codec.CBOR.Cuddle.CDDL.Resolve (showSimple) +import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase, showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Read import Codec.CBOR.Term @@ -131,7 +129,7 @@ validateTerm cddl term rule | CTreeE (VRuleRef n) <- rule = dereferenceAndValidate cddl n (validateTerm cddl term) | CTreeE (VValidator v _) <- rule = - runCustomValidator cddl (SingleTerm term) v + runValidator (v $ SingleTerm term) cddl | otherwise = case term of TInt i -> validateInteger cddl (fromIntegral i) rule @@ -155,18 +153,6 @@ validateTerm cddl term rule terminal :: CTree ValidatorPhase -> Evidenced ValidationTrace terminal = evidence . TerminalRule . mapIndex --- | Run a custom validator on a term. This is used by type-specific validators --- when they encounter a 'VValidator' node after dereferencing a rule reference. -runCustomValidator :: - CTreeRoot ValidatorPhase -> - RuleTerm -> - TermValidator -> - Evidenced ValidationTrace -runCustomValidator cddl term validator = - case runValidator (validator term) cddl of - CustomValidatorSuccess -> evidence CustomSuccess - CustomValidatorFailure err -> evidence $ CustomFailure err - unapplicable :: CTree ValidatorPhase -> Evidenced ValidationTrace unapplicable = evidence . UnapplicableRule . mapIndex @@ -193,7 +179,7 @@ validateInteger :: validateInteger cddl i rule = case rule of CTreeE (VRuleRef n) -> dereferenceAndValidate cddl n $ validateInteger cddl i - CTreeE (VValidator v _) -> runCustomValidator cddl (SingleTerm $ TInteger i) v + CTreeE (VValidator v _) -> runValidator (v $ SingleTerm $ TInteger i) cddl -- echo "C24101" | xxd -r -p - example.cbor -- echo "foo = int" > a.cddl -- cddl a.cddl validate example.cbor @@ -363,7 +349,7 @@ validateHalf :: CTree ValidatorPhase -> Evidenced ValidationTrace validateHalf cddl f (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateHalf cddl f -validateHalf cddl f (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ THalf f) v +validateHalf cddl f (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ THalf f) cddl validateHalf cddl f rule = case rule of -- a = any @@ -414,7 +400,7 @@ validateFloat :: Evidenced ValidationTrace validateFloat cddl f (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateFloat cddl f -validateFloat cddl f (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TFloat f) v +validateFloat cddl f (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TFloat f) cddl validateFloat cddl f rule = case rule of -- a = any @@ -476,7 +462,7 @@ validateDouble :: Evidenced ValidationTrace validateDouble cddl f (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateDouble cddl f -validateDouble cddl f (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TDouble f) v +validateDouble cddl f (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TDouble f) cddl validateDouble cddl f rule = case rule of -- a = any @@ -546,7 +532,7 @@ validateBool :: Evidenced ValidationTrace validateBool cddl b (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateBool cddl b -validateBool cddl b (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TBool b) v +validateBool cddl b (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TBool b) cddl validateBool cddl b rule = case rule of -- a = any @@ -592,7 +578,7 @@ validateSimple :: Evidenced ValidationTrace validateSimple cddl i (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateSimple cddl i -validateSimple cddl i (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TSimple i) v +validateSimple cddl i (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TSimple i) cddl validateSimple cddl 23 rule = case rule of -- a = any @@ -611,7 +597,7 @@ validateSimple _ n _ = error $ "Found simple different to 23! please report this validateNull :: CTreeRoot ValidatorPhase -> CTree ValidatorPhase -> Evidenced ValidationTrace validateNull cddl (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateNull cddl -validateNull cddl (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm TNull) v +validateNull cddl (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm TNull) cddl validateNull cddl rule = case rule of -- a = any @@ -629,7 +615,7 @@ validateBytes :: CTreeRoot ValidatorPhase -> BS.ByteString -> CTree ValidatorPhase -> Evidenced ValidationTrace validateBytes cddl bs (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateBytes cddl bs -validateBytes cddl bs (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TBytes bs) v +validateBytes cddl bs (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TBytes bs) cddl validateBytes cddl bs rule = case rule of -- a = any @@ -715,7 +701,7 @@ validateText :: Evidenced ValidationTrace validateText cddl txt (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateText cddl txt -validateText cddl txt (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TString txt) v +validateText cddl txt (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TString txt) cddl validateText cddl txt rule = case rule of -- a = any @@ -774,7 +760,7 @@ validateTagged :: CTreeRoot ValidatorPhase -> Word64 -> Term -> CTree ValidatorPhase -> Evidenced ValidationTrace validateTagged cddl tag term (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateTagged cddl tag term -validateTagged cddl tag term (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TTagged tag term) v +validateTagged cddl tag term (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TTagged tag term) cddl validateTagged cddl tag term rule = case rule of Postlude PTAny -> terminal rule @@ -828,7 +814,7 @@ validateList :: Evidenced ValidationTrace validateList cddl terms (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateList cddl terms -validateList cddl terms (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TList terms) v +validateList cddl terms (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TList terms) cddl validateList cddl terms rule = case rule of Postlude PTAny -> terminal rule @@ -920,7 +906,7 @@ validateMap :: Evidenced ValidationTrace validateMap cddl terms (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateMap cddl terms -validateMap cddl terms (CTreeE (VValidator v _)) = runCustomValidator cddl (SingleTerm $ TMap terms) v +validateMap cddl terms (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TMap terms) cddl validateMap cddl terms rule = case rule of Postlude PTAny -> terminal rule @@ -1116,3 +1102,16 @@ dereferenceAndValidate cddl n f = range :: Ord a => RangeBound -> a -> a -> Bool range Closed = (<=) range ClOpen = (<) + +-- * IndexMappable + +-- ValidatorPhase -> MonoSimplePhase + +instance IndexMappable CTree ValidatorPhase MonoSimplePhase where + mapIndex = foldCTree mapExt mapIndex + where + mapExt (VRuleRef n) = CTreeE $ MSimpleRef n + mapExt (VValidator _ x) = mapIndex x + +instance IndexMappable CTreeRoot ValidatorPhase MonoSimplePhase where + mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator/Trace.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator/Trace.hs deleted file mode 100644 index 1c296717..00000000 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator/Trace.hs +++ /dev/null @@ -1,459 +0,0 @@ -{-# LANGUAGE AllowAmbiguousTypes #-} -{-# LANGUAGE GADTs #-} -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE QuantifiedConstraints #-} -{-# LANGUAGE RecordWildCards #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE TypeData #-} -{-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE UndecidableInstances #-} - -module Codec.CBOR.Cuddle.CBOR.Validator.Trace ( - SValidity (..), - Validity (..), - ValidationTrace (..), - ListValidationTrace (..), - MapValidationTrace (..), - Evidenced (..), - IsValidationTrace (..), - ControlInfo (..), - TraceOptions (..), - Progress (..), - defaultTraceOptions, - isValid, - prettyValidationTrace, - showValidationTrace, - mapTrace, - compareEvidencedProgress, - evidence, - foldEvidenced, -) where - -import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm) -import Codec.CBOR.Cuddle.CDDL (Name (..)) -import Codec.CBOR.Cuddle.CDDL.CTree (CTree (..)) -import Codec.CBOR.Cuddle.CDDL.CtlOp (CtlOp) -import Codec.CBOR.Cuddle.CDDL.Resolve (MonoSimplePhase) -import Codec.CBOR.Term (Term) -import Data.Foldable (Foldable (..)) -import Data.Function (on) -import Data.Kind (Type) -import Data.List.NonEmpty (NonEmpty) -import Data.Text (Text) -import Data.Text qualified as T -import Data.Type.Equality (TestEquality (..), (:~:) (..)) -import Data.Word (Word64) -import Prettyprinter ( - Doc, - Pretty (..), - annotate, - defaultLayoutOptions, - hang, - indent, - layoutPretty, - vsep, - (<+>), - ) -import Prettyprinter.Render.Terminal (AnsiStyle, Color (..), color, italicized) -import Prettyprinter.Render.Terminal qualified as Ansi - --------------------------------------------------------------------------------- --- Validation result - -type data Validity - = IsValid - | IsInvalid - -data SValidity (v :: Validity) where - SInvalid :: SValidity IsInvalid - SValid :: SValidity IsValid - -deriving instance Eq (SValidity v) - -deriving instance Ord (SValidity v) - -deriving instance Show (SValidity v) - -instance TestEquality SValidity where - testEquality SValid SValid = Just Refl - testEquality SInvalid SInvalid = Just Refl - testEquality _ _ = Nothing - -data ControlInfo = ControlInfo - { ciOp :: CtlOp - , ciRule :: CTree MonoSimplePhase - } - deriving (Show) - -instance Pretty ControlInfo where - pretty ControlInfo {..} = pretty ciOp <+> pretty ciRule - -data ValidationTrace (v :: Validity) where - UnapplicableRule :: CTree MonoSimplePhase -> ValidationTrace IsInvalid - TerminalRule :: CTree MonoSimplePhase -> ValidationTrace IsValid - ControlTrace :: ControlInfo -> ValidationTrace IsValid -> ValidationTrace IsValid - ReferenceRule :: Name -> ValidationTrace v -> ValidationTrace v - CustomFailure :: Text -> ValidationTrace IsInvalid - CustomSuccess :: ValidationTrace IsValid - UnsatisfiedControl :: CtlOp -> CTree MonoSimplePhase -> ValidationTrace IsInvalid - ChoiceBranch :: Int -> ValidationTrace IsValid -> ValidationTrace IsValid - ListTrace :: ListValidationTrace v -> ValidationTrace v - MapTrace :: MapValidationTrace v -> ValidationTrace v - TagTrace :: Word64 -> ValidationTrace v -> ValidationTrace v - InvalidTag :: Word64 -> Word64 -> ValidationTrace IsInvalid - -deriving instance Show (ValidationTrace v) - -data ListValidationTrace (v :: Validity) where - ListValidationDone :: ListValidationTrace IsValid - ListValidationLeftoverTerms :: - NonEmpty Term -> - Maybe (CTree MonoSimplePhase, ValidationTrace IsInvalid) -> - ListValidationTrace IsInvalid - ListValidationUnappliedRule :: - CTree MonoSimplePhase -> - ListValidationTrace IsInvalid - ListValidationConsume :: - CTree MonoSimplePhase -> - ValidationTrace IsValid -> - ListValidationTrace v -> - ListValidationTrace v - ListValidationMissingRequired :: - CTree MonoSimplePhase -> - ValidationTrace IsInvalid -> - ListValidationTrace IsInvalid - ListValidationConsumeGroup :: - [Name] -> - ListValidationTrace IsValid -> - ListValidationTrace v -> - ListValidationTrace v - ListValidationBadGroup :: - [Name] -> - ListValidationTrace IsInvalid -> - ListValidationTrace IsInvalid - -deriving instance Show (ListValidationTrace v) - -data MapValidationTrace (v :: Validity) where - MapValidationDone :: MapValidationTrace IsValid - MapValidationLeftoverKVs :: - (Term, Term) -> - Maybe (CTree MonoSimplePhase, MapValidationTrace IsInvalid) -> - MapValidationTrace IsInvalid - MapValidationUnappliedRules :: NonEmpty (CTree MonoSimplePhase) -> MapValidationTrace IsInvalid - MapValidationInvalidValue :: - CTree MonoSimplePhase -> - ValidationTrace IsValid -> - ValidationTrace IsInvalid -> - MapValidationTrace IsInvalid - MapValidationConsume :: - CTree MonoSimplePhase -> - ValidationTrace IsValid -> - ValidationTrace IsValid -> - MapValidationTrace v -> - MapValidationTrace v - MapValidationDuplicateKeys :: - CTree MonoSimplePhase -> - CanonicalTerm -> - ValidationTrace IsValid -> - MapValidationTrace IsInvalid - -deriving instance Show (MapValidationTrace v) - -mapTrace :: (forall v. Show (u v)) => (forall v. t v -> u v) -> Evidenced t -> Evidenced u -mapTrace f (Evidenced v t) = Evidenced v $ f t - -data Evidenced t where - Evidenced :: - { eValidity :: SValidity v - , eTrace :: t v - } -> - Evidenced t - -foldEvidenced :: (forall v. t v -> a) -> Evidenced t -> a -foldEvidenced f (Evidenced v t) = - case v of - SValid -> f t - SInvalid -> f t - -deriving instance (forall v. Show (t v)) => Show (Evidenced t) - -instance IsValidationTrace t => Semigroup (Evidenced t) where - x@(Evidenced SValid _) <> _ = x - _ <> y@(Evidenced SValid _) = y - Evidenced SInvalid x <> Evidenced SInvalid y = - Evidenced SInvalid $ case compareInvalidProgress x y of - GT -> x - _ -> y - -data Progress = Progress {termProgress :: !Int, refProgress :: !Int} - deriving (Eq, Ord) - -instance Semigroup Progress where - Progress t1 r1 <> Progress t2 r2 = Progress (t1 + t2) (r1 + r2) - -instance Monoid Progress where - mempty = Progress 0 0 - -increaseTermProgress :: Progress -> Progress -increaseTermProgress p = p <> Progress 1 0 - -increaseRefProgress :: Progress -> Progress -increaseRefProgress p = p <> Progress 0 1 - -class IsValidationTrace (t :: Validity -> Type) where - traceValidity :: t v -> SValidity v - measureProgress :: t v -> Progress - -instance IsValidationTrace ValidationTrace where - traceValidity = \case - CustomSuccess {} -> SValid - TerminalRule {} -> SValid - ControlTrace {} -> SValid - ChoiceBranch {} -> SValid - UnapplicableRule {} -> SInvalid - CustomFailure {} -> SInvalid - UnsatisfiedControl {} -> SInvalid - InvalidTag {} -> SInvalid - ReferenceRule _ x -> traceValidity x - ListTrace x -> traceValidity x - MapTrace x -> traceValidity x - TagTrace _ x -> traceValidity x - - measureProgress = \case - TerminalRule {} -> Progress 1 0 - CustomSuccess -> Progress 1 0 - ControlTrace _ x -> measureProgress x - ChoiceBranch _ x -> measureProgress x - UnapplicableRule {} -> mempty - CustomFailure {} -> mempty - UnsatisfiedControl {} -> mempty - InvalidTag {} -> mempty - ReferenceRule _ x -> increaseRefProgress $ measureProgress x - ListTrace x -> measureProgress x - MapTrace x -> measureProgress x - TagTrace _ x -> increaseTermProgress $ measureProgress x - -instance IsValidationTrace ListValidationTrace where - traceValidity = \case - ListValidationDone -> SValid - ListValidationLeftoverTerms {} -> SInvalid - ListValidationUnappliedRule {} -> SInvalid - ListValidationMissingRequired {} -> SInvalid - ListValidationBadGroup _ _ -> SInvalid - ListValidationConsume _ _ x -> traceValidity x - ListValidationConsumeGroup _ _ x -> traceValidity x - - measureProgress = \case - ListValidationDone -> Progress 1 0 - ListValidationConsume _ _ x -> increaseTermProgress $ measureProgress x - ListValidationLeftoverTerms _ Nothing -> mempty - ListValidationLeftoverTerms _ (Just (_, trc)) -> measureProgress trc - ListValidationMissingRequired _ _ -> mempty - ListValidationUnappliedRule _ -> mempty - ListValidationConsumeGroup rs g x -> Progress 0 (length rs) <> measureProgress g <> measureProgress x - ListValidationBadGroup rs x -> Progress 0 (length rs) <> measureProgress x - -instance IsValidationTrace MapValidationTrace where - traceValidity = \case - MapValidationDone -> SValid - MapValidationLeftoverKVs _ _ -> SInvalid - MapValidationUnappliedRules _ -> SInvalid - MapValidationInvalidValue {} -> SInvalid - MapValidationDuplicateKeys {} -> SInvalid - MapValidationConsume _ _ _ x -> traceValidity x - - measureProgress = \case - MapValidationDone -> Progress 1 0 - MapValidationLeftoverKVs _ Nothing -> mempty - MapValidationLeftoverKVs _ (Just (_, trc)) -> measureProgress trc - MapValidationUnappliedRules _ -> mempty - MapValidationConsume _ kTrc vTrc x -> - measureProgress kTrc <> measureProgress vTrc <> measureProgress x - MapValidationInvalidValue _ kTrc vTrc -> - measureProgress kTrc <> measureProgress vTrc - MapValidationDuplicateKeys _ _ trc -> measureProgress trc - -evidence :: (Show (t v), IsValidationTrace t) => t v -> Evidenced t -evidence x = Evidenced (traceValidity x) x - -isValid :: Evidenced t -> Bool -isValid Evidenced {eValidity = SValid} = True -isValid _ = False - -compareEvidencedProgress :: IsValidationTrace t => Evidenced t -> Evidenced t -> Ordering -compareEvidencedProgress (Evidenced SValid _) (Evidenced SValid _) = EQ -compareEvidencedProgress (Evidenced SInvalid _) (Evidenced SValid _) = LT -compareEvidencedProgress (Evidenced SValid _) (Evidenced SInvalid _) = GT -compareEvidencedProgress (Evidenced SInvalid x) (Evidenced SInvalid y) = - x `compareInvalidProgress` y - -compareInvalidProgress :: IsValidationTrace t => t IsInvalid -> t IsInvalid -> Ordering -compareInvalidProgress = compare `on` measureProgress - -nestContainer :: Doc AnsiStyle -> Doc AnsiStyle -nestContainer = hang 2 . ("└ " <>) - -newtype TraceOptions = TraceOptions - { toFoldValid :: Bool - } - -defaultTraceOptions :: TraceOptions -defaultTraceOptions = TraceOptions {toFoldValid = False} - -prettyListValidationResult :: TraceOptions -> ListValidationTrace v -> Doc AnsiStyle -prettyListValidationResult opts@TraceOptions {..} = \case - ListValidationDone -> mempty - ListValidationLeftoverTerms _ Nothing -> - annotate (color Red) "leftover elements not matched by any rule" - ListValidationLeftoverTerms _ (Just (rule, trc)) -> - hang 2 $ - vsep - [ annotate (color Red) "leftover elements, closest matching rule:" - , annotate (color Green) $ pretty rule - , nestContainer $ prettyValidationTrace opts trc - ] - ListValidationUnappliedRule r -> - hang 2 $ - vsep - [ annotate (color Red) "required rule not satisfied:" - , pretty r - ] - ListValidationConsume _ t c - | toFoldValid -> foldValid 1 c - | otherwise -> vsep $ continue c [prettyValidationTrace opts t] - ListValidationMissingRequired _ t -> - vsep - [ annotate (color Red) "failed to apply required rule:" - , nestContainer $ prettyValidationTrace opts t - ] - ListValidationConsumeGroup refs x c -> vsep . continue c $ prettyGroup SValid refs x - ListValidationBadGroup refs x -> vsep $ prettyGroup SInvalid refs x - where - -- This prevents unnecessary empty lines - continue ListValidationDone l = l - continue x l = l <> [prettyListValidationResult opts x] - - prettyGroup :: SValidity v -> [Name] -> ListValidationTrace v -> [Doc AnsiStyle] - prettyGroup v refs x = go refs - where - go (n : ns) = - [ "ref" <+> pretty n - , nestContainer . vsep $ go ns - ] - go [] = - [ case v of - SValid -> "grp" - SInvalid -> "grp" <+> annotate (color Red) "(fail)" - , nestContainer $ prettyListValidationResult opts x - ] - - foldValid !n (ListValidationConsume _ _ c) = foldValid (n + 1) c - foldValid !n t = - vsep $ continue t [annotate italicized $ pretty (n :: Int) <> " valid elements"] - -prettyMapValidationResult :: TraceOptions -> MapValidationTrace v -> Doc AnsiStyle -prettyMapValidationResult opts@TraceOptions {..} = \case - MapValidationDone -> mempty - MapValidationLeftoverKVs _ Nothing -> - annotate (color Red) "leftover key-value pairs not matched by any rule" - MapValidationLeftoverKVs _ (Just (rule, trc)) -> - hang 2 $ - vsep - [ annotate (color Red) "leftover key-value pairs, closest matching rule:" - , annotate (color Green) $ pretty rule - , nestContainer $ prettyMapValidationResult opts trc - ] - MapValidationUnappliedRules rs -> - hang 2 $ - vsep - [ annotate (color Red) "not all required rules have been applied:" - , vsep (toList $ pretty <$> rs) - ] - MapValidationConsume _ k v c - | toFoldValid -> foldValid 1 c - | otherwise -> - vsep $ - continue - c - [ "key:" - , nestContainer $ prettyValidationTrace opts k - , "value:" - , nestContainer $ prettyValidationTrace opts v - ] - MapValidationInvalidValue _ k v -> - vsep - [ "key:" - , nestContainer $ prettyValidationTrace opts k - , "value:" <+> annotate (color Red) "(fail)" - , nestContainer $ prettyValidationTrace opts v - ] - MapValidationDuplicateKeys _ _ trc -> - vsep - [ "key: " <> annotate (color Red) "(duplicate)" - , nestContainer $ prettyValidationTrace opts trc - ] - where - foldValid !n (MapValidationConsume _ _ _ c) = foldValid (n + 1) c - foldValid !n t = - vsep . continue t $ - [ annotate italicized $ pretty (n :: Int) <> " valid key-value pairs" - , "..." - ] - - -- This prevents unnecessary empty lines - continue MapValidationDone l = l - continue x l = l <> [prettyMapValidationResult opts x] - -prettyValidationTrace :: TraceOptions -> ValidationTrace v -> Doc AnsiStyle -prettyValidationTrace opts = \case - UnapplicableRule x -> annotate (color Red) $ vsep ["failed to apply: ", indent 2 $ pretty x] - TerminalRule x -> "app: " <> annotate (color Green) (pretty x) - ControlTrace ci x -> - vsep - [ prettyValidationTrace opts x - , nestContainer $ "ctrl:" <+> annotate (color Yellow) ("." <> pretty ci) - ] - ChoiceBranch i c -> - vsep - [ "choice (idx: " <> pretty i <> ")" - , nestContainer $ prettyValidationTrace opts c - ] - ReferenceRule (Name n) x -> - vsep - [ "ref: " <> annotate (color Blue) (pretty n) - , nestContainer $ prettyValidationTrace opts x - ] - CustomFailure e -> annotate (color Red) $ pretty e - CustomSuccess -> "" - UnsatisfiedControl op ctl -> - annotate (color Red) $ - vsep - [ "unsatisfied control:" - , indent 2 $ "." <> pretty op <+> pretty ctl - ] - ListTrace l -> - vsep - [ "array" - , nestContainer $ prettyListValidationResult opts l - ] - MapTrace m -> - vsep - [ "map" - , nestContainer $ prettyMapValidationResult opts m - ] - TagTrace t x -> - vsep - [ "tag:" <+> annotate (color Green) ("#6." <> pretty t) - , nestContainer $ prettyValidationTrace opts x - ] - InvalidTag expected actual -> - "expected tag #6." <> pretty expected <> ", got #6." <> pretty actual - -showValidationTrace :: ValidationTrace v -> String -showValidationTrace = - T.unpack - . Ansi.renderStrict - . layoutPretty defaultLayoutOptions - . prettyValidationTrace defaultTraceOptions diff --git a/src/Codec/CBOR/Cuddle/CDDL.hs b/src/Codec/CBOR/Cuddle/CDDL.hs index 1ef388c2..f16462ad 100644 --- a/src/Codec/CBOR/Cuddle/CDDL.hs +++ b/src/Codec/CBOR/Cuddle/CDDL.hs @@ -2,6 +2,7 @@ {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE OverloadedLabels #-} +{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} @@ -47,11 +48,21 @@ module Codec.CBOR.Cuddle.CDDL ( XRule, XXTopLevel, XXType2, + mapCDDLDropExt, ) where import Codec.CBOR.Cuddle.CDDL.CtlOp (CtlOp) -import Codec.CBOR.Cuddle.Comments (CollectComments (..), Comment, HasComment (..)) +import Codec.CBOR.Cuddle.Comments ( + CollectComments (..), + Comment, + HasComment (..), + prettyCommentNoBreakWS, + ) +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) +import Data.Bifunctor (Bifunctor (..)) import Data.ByteString qualified as B +import Data.ByteString.Base16 qualified as B16 +import Data.ByteString.Char8 qualified as BS import Data.Default.Class (Default (..)) import Data.Function (on) import Data.Hashable (Hashable) @@ -64,6 +75,7 @@ import Data.Word (Word64, Word8) import GHC.Base (Constraint, Type) import GHC.Generics (Generic) import Optics.Core ((%), (%~), (&)) +import Prettyprinter data family XXTopLevel i @@ -157,6 +169,9 @@ newtype Name = Name {unName :: T.Text} deriving (Eq, Ord, Show) deriving newtype (Semigroup, Monoid) +instance Pretty Name where + pretty (Name name) = pretty name + -- | A reference to a generic parameter inside the body of a generic rule. newtype GRef = GRef T.Text deriving (Show) @@ -554,6 +569,9 @@ data Value = Value ValueVariant Comment deriving (Eq, Generic, Show, Default) deriving anyclass (Hashable, CollectComments) +instance Pretty Value where + pretty (Value v cmt) = pretty v <> prettyCommentNoBreakWS cmt + value :: ValueVariant -> Value value x = Value x mempty @@ -569,3 +587,162 @@ data ValueVariant | VBool Bool deriving (Eq, Generic, Show, Default) deriving anyclass (Hashable, CollectComments) + +instance Pretty ValueVariant where + pretty (VUInt i) = pretty i + pretty (VNInt i) = "-" <> pretty i + pretty (VBignum i) = pretty i + pretty (VFloat16 i) = pretty i + pretty (VFloat32 i) = pretty i + pretty (VFloat64 i) = pretty i + pretty (VText t) = enclose "\"" "\"" $ pretty t + pretty (VBytes b) = fromString $ "h" <> "'" <> BS.unpack (B16.encode b) <> "'" + pretty (VBool True) = "true" + pretty (VBool False) = "false" + +-- * IndexMappable + +instance + ( IndexMappable XCddl i j + , IndexMappable XXTopLevel i j + , IndexMappable XXType2 i j + , IndexMappable XTerm i j + , IndexMappable XRule i j + ) => + IndexMappable CDDL i j + where + mapIndex (CDDL r tls e) = CDDL (mapIndex r) (mapIndex <$> tls) (mapIndex <$> e) + +instance + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + , IndexMappable XRule i j + ) => + IndexMappable Rule i j + where + mapIndex (Rule n mg a t c) = Rule n (mapIndex <$> mg) a (mapIndex t) (mapIndex c) + +instance + ( IndexMappable XXTopLevel i j + , IndexMappable XXType2 i j + , IndexMappable XTerm i j + , IndexMappable XRule i j + ) => + IndexMappable TopLevel i j + where + mapIndex (TopLevelRule r) = TopLevelRule $ mapIndex r + mapIndex (XXTopLevel e) = XXTopLevel $ mapIndex e + +instance IndexMappable XTerm i j => IndexMappable GenericParameter i j where + mapIndex (GenericParameter n e) = GenericParameter n $ mapIndex e + +instance IndexMappable XTerm i j => IndexMappable GenericParameters i j where + mapIndex (GenericParameters ns) = GenericParameters $ mapIndex <$> ns + +instance + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + ) => + IndexMappable TypeOrGroup i j + where + mapIndex (TOGType t) = TOGType $ mapIndex t + mapIndex (TOGGroup g) = TOGGroup $ mapIndex g + +instance + ( IndexMappable XTerm i j + , IndexMappable XXType2 i j + ) => + IndexMappable GroupEntry i j + where + mapIndex (GroupEntry mo gev e) = GroupEntry mo (mapIndex gev) (mapIndex e) + +instance + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + ) => + IndexMappable GroupEntryVariant i j + where + mapIndex (GEType mk t) = GEType (mapIndex <$> mk) $ mapIndex t + mapIndex (GERef n ma) = GERef n (mapIndex <$> ma) + mapIndex (GEGroup g) = GEGroup (mapIndex g) + +instance + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + ) => + IndexMappable MemberKey i j + where + mapIndex (MKType t) = MKType $ mapIndex t + mapIndex (MKBareword n) = MKBareword n + mapIndex (MKValue x) = MKValue x + +instance + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + ) => + IndexMappable Type0 i j + where + mapIndex (Type0 ts) = Type0 $ mapIndex <$> ts + +instance + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + ) => + IndexMappable Type1 i j + where + mapIndex (Type1 t mo e) = Type1 (mapIndex t) (second mapIndex <$> mo) (mapIndex e) + +instance + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + ) => + IndexMappable Type2 i j + where + mapIndex (T2Value v) = T2Value v + mapIndex (T2Name n mg) = T2Name n (mapIndex <$> mg) + mapIndex (T2Group t) = T2Group $ mapIndex t + mapIndex (T2Map g) = T2Map $ mapIndex g + mapIndex (T2Array a) = T2Array $ mapIndex a + mapIndex (T2Unwrapped n mg) = T2Unwrapped n (mapIndex <$> mg) + mapIndex (T2Enum g) = T2Enum $ mapIndex g + mapIndex (T2EnumRef n mg) = T2EnumRef n (mapIndex <$> mg) + mapIndex (T2Tag mt t) = T2Tag mt $ mapIndex t + mapIndex (T2DataItem t mt) = T2DataItem t mt + mapIndex T2Any = T2Any + mapIndex (XXType2 e) = XXType2 $ mapIndex e + +instance + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + ) => + IndexMappable GenericArg i j + where + mapIndex (GenericArg g) = GenericArg $ mapIndex <$> g + +instance + ( IndexMappable XTerm i j + , IndexMappable XXType2 i j + ) => + IndexMappable Group i j + where + mapIndex (Group g) = Group $ mapIndex <$> g + +instance + ( IndexMappable XTerm i j + , IndexMappable XXType2 i j + ) => + IndexMappable GrpChoice i j + where + mapIndex (GrpChoice gs e) = GrpChoice (mapIndex <$> gs) $ mapIndex e + +mapCDDLDropExt :: + ( IndexMappable XXType2 i j + , IndexMappable XTerm i j + , IndexMappable XRule i j + ) => + CDDL i -> + CDDL j +mapCDDLDropExt (CDDL r tls _) = CDDL (mapIndex r) (foldMap mapTopLevelDropExt tls) [] + where + mapTopLevelDropExt (TopLevelRule x) = [TopLevelRule $ mapIndex x] + mapTopLevelDropExt (XXTopLevel _) = [] diff --git a/src/Codec/CBOR/Cuddle/CDDL/CTree.hs b/src/Codec/CBOR/Cuddle/CDDL/CTree.hs index 20bf641d..476216b7 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/CTree.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/CTree.hs @@ -1,10 +1,12 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Codec.CBOR.Cuddle.CDDL.CTree ( - XXCTree, + XXCTree (..), CTree (..), traverseCTree, foldCTree, @@ -16,8 +18,14 @@ module Codec.CBOR.Cuddle.CDDL.CTree ( ) where import Codec.CBOR.Cuddle.CBOR.Canonical (nintMin, uintMax) -import Codec.CBOR.Cuddle.CDDL (Name, OccurrenceIndicator, RangeBound, Value) +import Codec.CBOR.Cuddle.CDDL ( + Name, + OccurrenceIndicator (..), + RangeBound (..), + Value, + ) import Codec.CBOR.Cuddle.CDDL.CtlOp +import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase) import Control.Monad.Identity (Identity (..)) import Data.Hashable (Hashable) import Data.List.NonEmpty qualified as NE @@ -25,6 +33,7 @@ import Data.Map.Strict qualified as Map import Data.Word (Word64) import GHC.Generics (Generic) import Generic.Random (genericArbitraryU) +import Prettyprinter import Test.QuickCheck (Arbitrary (..)) -------------------------------------------------------------------------------- @@ -62,6 +71,29 @@ deriving instance Show (Node f) => Show (CTree f) instance Hashable (Node f) => Hashable (CTree f) +instance Pretty (XXCTree p) => Pretty (CTree p) where + pretty = \case + Literal v -> pretty v + Postlude v -> pretty v + Range lo hi ClOpen -> pretty lo <+> "..." <+> pretty hi + Range lo hi Closed -> pretty lo <+> ".." <+> pretty hi + KV k v _ -> pretty k <+> "==>" <+> pretty v + CTreeE x -> pretty x + Occur v oi -> + case oi of + OIOptional -> "?" <+> pretty v + OIZeroOrMore -> "*" <+> pretty v + OIOneOrMore -> "+" <+> pretty v + OIBounded lo hi -> foldMap pretty lo <> "*" <> foldMap pretty hi <+> pretty v + Map m -> encloseSep "{" "}" "," $ pretty <$> m + Array e -> list $ pretty <$> e + Choice c -> group . vsep . punctuate "//" $ pretty <$> NE.toList c + Group g -> tupled $ pretty <$> g + Control op tgt ctl -> pretty tgt <+> pretty op <+> pretty ctl + Enum e -> "&" <> pretty e + Unwrap x -> "~" <> pretty x + Tag t x -> "#6." <> pretty t <> "(" <> pretty x <> ")" + -- | Traverse the CTree, carrying out the given operation at each node traverseCTree :: Monad m => (XXCTree i -> m (CTree j)) -> (CTree i -> m (CTree j)) -> CTree i -> m (CTree j) @@ -152,7 +184,32 @@ data PTerm | PTUndefined deriving (Eq, Generic, Ord, Show, Enum, Bounded) +instance Pretty PTerm where + pretty = \case + PTBool -> "bool" + PTUInt -> "uint" + PTNInt -> "nint" + PTInt -> "int" + PTHalf -> "half" + PTFloat -> "float" + PTDouble -> "double" + PTBytes -> "bytes" + PTText -> "text" + PTAny -> "any" + PTNil -> "nil" + PTUndefined -> "undefined" + instance Arbitrary PTerm where arbitrary = genericArbitraryU instance Hashable PTerm + +-- | A simplified phase reachable from any of the function-bearing post-mono +-- phases ('MonoReferenced', 'GenPhase', 'ValidatorPhase'). It strips the +-- generator/validator extensions so the tree can be `Show`n, `Eq`-compared, +-- and pretty-printed for debug output. +newtype instance XXCTree MonoSimplePhase = MSimpleRef Name + deriving (Generic, Show, Eq) + +instance Pretty (XXCTree MonoSimplePhase) where + pretty (MSimpleRef n) = pretty n diff --git a/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs b/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs deleted file mode 100644 index e3549a97..00000000 --- a/src/Codec/CBOR/Cuddle/CDDL/CTreePhase.hs +++ /dev/null @@ -1,40 +0,0 @@ -{-# LANGUAGE DeriveAnyClass #-} -{-# LANGUAGE DerivingStrategies #-} -{-# LANGUAGE TypeData #-} -{-# LANGUAGE TypeFamilies #-} - -module Codec.CBOR.Cuddle.CDDL.CTreePhase ( - CTreePhase, - XTerm (..), - XCddl (..), - XRule (..), - XXTopLevel, -) where - -import Codec.CBOR.Cuddle.CDDL (XCddl, XRule, XTerm, XXTopLevel, XXType2) -import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) -import Codec.CBOR.Cuddle.CDDL.Custom.Generator (TermGenerator) -import Codec.CBOR.Cuddle.CDDL.Custom.Validator (TermValidator) -import Data.Default.Class (Default) -import Data.Hashable (Hashable) -import GHC.Generics (Generic) - -type data CTreePhase - -data instance XTerm CTreePhase = CTreeXTerm - deriving (Generic, Show, Eq, Ord) - deriving anyclass (Hashable, Default) - -data instance XXTopLevel CTreePhase - deriving (Generic, Show, Eq, Ord) - -data instance XCddl CTreePhase = CTreeXCddl - deriving (Generic, Show, Eq, Ord) - -data instance XRule CTreePhase - = CTreeXRule (TermGenerator RuleTerm -> TermGenerator RuleTerm) (Maybe TermValidator) - deriving (Generic) - -data instance XXType2 CTreePhase - deriving (Generic, Show, Eq, Ord) - deriving anyclass (Hashable) diff --git a/src/Codec/CBOR/Cuddle/CDDL/CtlOp.hs b/src/Codec/CBOR/Cuddle/CDDL/CtlOp.hs index 499b8db5..7e0f2e31 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/CtlOp.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/CtlOp.hs @@ -4,7 +4,9 @@ module Codec.CBOR.Cuddle.CDDL.CtlOp where import Data.Hashable (Hashable) +import Data.Text qualified as T import GHC.Generics (Generic) +import Prettyprinter (Pretty (..)) -- | A _control_ allows relating a _target_ type with a _controller_ type -- via a _control operator_. @@ -35,4 +37,7 @@ data CtlOp | Default deriving (Eq, Generic, Show) +instance Pretty CtlOp where + pretty = pretty . T.toLower . T.pack . show + instance Hashable CtlOp diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 89c12c96..860cb0f4 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -224,3 +224,5 @@ showConstraint = \case CustomControl c _ -> "." <> c And _ -> ".and" Within _ -> ".within" + +-- * IndexMappable diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index 32245628..01d8883b 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -1,28 +1,76 @@ +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE QuantifiedConstraints #-} +{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeData #-} {-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE UndecidableInstances #-} module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( TermValidator, ValidatorPhase, Validator, - CustomValidatorResult (..), XXCTree (..), HasValidator (..), ValidateEnv (..), withLocalValidateBindings, runValidator, + mapTrace, + isValid, + compareEvidencedProgress, + nestContainer, + TraceOptions (..), + defaultTraceOptions, + prettyListValidationResult, + showValidationTrace, + + -- * Trace + SValidity (..), + Validity (..), + Progress (..), + Evidenced (..), + ControlInfo (..), + ValidationTrace (..), + ListValidationTrace (..), + MapValidationTrace (..), + evidence, + foldEvidenced, + measureProgress, + prettyValidationTrace, ) where +import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm) import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..)) -import Codec.CBOR.Cuddle.CDDL.CTree (CTree, CTreeRoot (..), XXCTree) +import Codec.CBOR.Cuddle.CDDL.CTree (CTree (..), CTreeRoot (..), XXCTree) +import Codec.CBOR.Cuddle.CDDL.CtlOp (CtlOp) import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm) +import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase) +import Codec.CBOR.Term (Term) import Control.Monad.Reader (MonadReader (..), ReaderT (..), asks) +import Data.Function (on) +import Data.Kind (Type) +import Data.List.NonEmpty (NonEmpty) +import Data.List.NonEmpty qualified as NE import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Text (Text) import Data.Text qualified as T -import GHC.Generics (Generic) +import Data.Type.Equality (TestEquality (..), type (:~:) (..)) +import Data.Word (Word64) import Optics.Lens (Lens') +import Prettyprinter ( + Doc, + Pretty (..), + annotate, + defaultLayoutOptions, + hang, + indent, + layoutPretty, + vsep, + (<+>), + ) +import Prettyprinter.Render.Terminal (AnsiStyle, Color (..), color, italicized) +import Prettyprinter.Render.Terminal qualified as Ansi type data ValidatorPhase @@ -33,20 +81,15 @@ data instance XXCTree ValidatorPhase class HasValidator a where validatorL :: Lens' a (Maybe TermValidator) -data CustomValidatorResult - = CustomValidatorSuccess - | CustomValidatorFailure Text - deriving (Generic, Show, Eq) - data ValidateEnv = ValidateEnv { veRoot :: CTreeRoot ValidatorPhase , veLocal :: Map Name (CTree ValidatorPhase) } -newtype Validator a = Validator (ReaderT ValidateEnv (Either Text) a) +newtype Validator a = Validator (ReaderT ValidateEnv (Either (ValidationTrace IsInvalid)) a) deriving (Functor, Applicative, Monad, MonadReader ValidateEnv) -type TermValidator = RuleTerm -> Validator () +type TermValidator = RuleTerm -> Validator (ValidationTrace IsValid) instance MonadCddl Validator where type Phase Validator = ValidatorPhase @@ -60,7 +103,7 @@ instance MonadCddl Validator where pure $ Map.lookup (Name t) binds instance MonadFail Validator where - fail msg = Validator . ReaderT $ \_ -> Left $ T.pack msg + fail msg = Validator . ReaderT $ \_ -> Left $ CustomFailure $ T.pack msg -- | Run an action with the given local generic bindings installed. withLocalValidateBindings :: @@ -69,7 +112,407 @@ withLocalValidateBindings binds = local (\env -> env {veLocal = binds `Map.union` veLocal env}) runValidator :: - Validator () -> CTreeRoot ValidatorPhase -> CustomValidatorResult + Validator (ValidationTrace IsValid) -> CTreeRoot ValidatorPhase -> Evidenced ValidationTrace runValidator (Validator m) cddl = - either CustomValidatorFailure (const CustomValidatorSuccess) $ + either evidence evidence $ runReaderT m ValidateEnv {veRoot = cddl, veLocal = Map.empty} + +type data Validity + = IsValid + | IsInvalid + +data SValidity (v :: Validity) where + SInvalid :: SValidity IsInvalid + SValid :: SValidity IsValid + +deriving instance Eq (SValidity v) + +deriving instance Ord (SValidity v) + +deriving instance Show (SValidity v) + +instance TestEquality SValidity where + testEquality SValid SValid = Just Refl + testEquality SInvalid SInvalid = Just Refl + testEquality _ _ = Nothing + +data Evidenced t where + Evidenced :: + { eValidity :: SValidity v + , eTrace :: t v + } -> + Evidenced t + +mapTrace :: (forall v. Show (u v)) => (forall v. t v -> u v) -> Evidenced t -> Evidenced u +mapTrace f (Evidenced v t) = Evidenced v $ f t + +foldEvidenced :: (forall v. t v -> a) -> Evidenced t -> a +foldEvidenced f (Evidenced v t) = + case v of + SValid -> f t + SInvalid -> f t + +deriving instance (forall v. Show (t v)) => Show (Evidenced t) + +class IsValidationTrace (t :: Validity -> Type) where + traceValidity :: t v -> SValidity v + measureProgress :: t v -> Progress + +instance IsValidationTrace t => Semigroup (Evidenced t) where + x@(Evidenced SValid _) <> _ = x + _ <> y@(Evidenced SValid _) = y + Evidenced SInvalid x <> Evidenced SInvalid y = + Evidenced SInvalid $ case compareInvalidProgress x y of + GT -> x + _ -> y + +data Progress = Progress {termProgress :: !Int, refProgress :: !Int} + deriving (Eq, Ord) + +instance Semigroup Progress where + Progress t1 r1 <> Progress t2 r2 = Progress (t1 + t2) (r1 + r2) + +instance Monoid Progress where + mempty = Progress 0 0 + +increaseTermProgress :: Progress -> Progress +increaseTermProgress p = p <> Progress 1 0 + +increaseRefProgress :: Progress -> Progress +increaseRefProgress p = p <> Progress 0 1 + +-------------------------------------------------------------------------------- +-- Validation result + +data ControlInfo = ControlInfo + { ciOp :: CtlOp + , ciRule :: CTree MonoSimplePhase + } + deriving (Show) + +instance Pretty ControlInfo where + pretty ControlInfo {..} = pretty ciOp <+> pretty ciRule + +data ValidationTrace (v :: Validity) where + UnapplicableRule :: CTree MonoSimplePhase -> ValidationTrace IsInvalid + TerminalRule :: CTree MonoSimplePhase -> ValidationTrace IsValid + ControlTrace :: ControlInfo -> ValidationTrace IsValid -> ValidationTrace IsValid + ReferenceRule :: Name -> ValidationTrace v -> ValidationTrace v + CustomFailure :: Text -> ValidationTrace IsInvalid + CustomSuccess :: ValidationTrace IsValid + UnsatisfiedControl :: CtlOp -> CTree MonoSimplePhase -> ValidationTrace IsInvalid + ChoiceBranch :: Int -> ValidationTrace IsValid -> ValidationTrace IsValid + ListTrace :: ListValidationTrace v -> ValidationTrace v + MapTrace :: MapValidationTrace v -> ValidationTrace v + TagTrace :: Word64 -> ValidationTrace v -> ValidationTrace v + InvalidTag :: Word64 -> Word64 -> ValidationTrace IsInvalid + +deriving instance Show (ValidationTrace v) + +data ListValidationTrace (v :: Validity) where + ListValidationDone :: ListValidationTrace IsValid + ListValidationLeftoverTerms :: + NonEmpty Term -> + Maybe (CTree MonoSimplePhase, ValidationTrace IsInvalid) -> + ListValidationTrace IsInvalid + ListValidationUnappliedRule :: + CTree MonoSimplePhase -> + ListValidationTrace IsInvalid + ListValidationConsume :: + CTree MonoSimplePhase -> + ValidationTrace IsValid -> + ListValidationTrace v -> + ListValidationTrace v + ListValidationMissingRequired :: + CTree MonoSimplePhase -> + ValidationTrace IsInvalid -> + ListValidationTrace IsInvalid + ListValidationConsumeGroup :: + [Name] -> + ListValidationTrace IsValid -> + ListValidationTrace v -> + ListValidationTrace v + ListValidationBadGroup :: + [Name] -> + ListValidationTrace IsInvalid -> + ListValidationTrace IsInvalid + +deriving instance Show (ListValidationTrace v) + +data MapValidationTrace (v :: Validity) where + MapValidationDone :: MapValidationTrace IsValid + MapValidationLeftoverKVs :: + (Term, Term) -> + Maybe (CTree MonoSimplePhase, MapValidationTrace IsInvalid) -> + MapValidationTrace IsInvalid + MapValidationUnappliedRules :: NonEmpty (CTree MonoSimplePhase) -> MapValidationTrace IsInvalid + MapValidationInvalidValue :: + CTree MonoSimplePhase -> + ValidationTrace IsValid -> + ValidationTrace IsInvalid -> + MapValidationTrace IsInvalid + MapValidationConsume :: + CTree MonoSimplePhase -> + ValidationTrace IsValid -> + ValidationTrace IsValid -> + MapValidationTrace v -> + MapValidationTrace v + MapValidationDuplicateKeys :: + CTree MonoSimplePhase -> + CanonicalTerm -> + ValidationTrace IsValid -> + MapValidationTrace IsInvalid + +deriving instance Show (MapValidationTrace v) + +instance IsValidationTrace ValidationTrace where + traceValidity = \case + CustomSuccess {} -> SValid + TerminalRule {} -> SValid + ControlTrace {} -> SValid + ChoiceBranch {} -> SValid + UnapplicableRule {} -> SInvalid + CustomFailure {} -> SInvalid + UnsatisfiedControl {} -> SInvalid + InvalidTag {} -> SInvalid + ReferenceRule _ x -> traceValidity x + ListTrace x -> traceValidity x + MapTrace x -> traceValidity x + TagTrace _ x -> traceValidity x + + measureProgress = \case + TerminalRule {} -> Progress 1 0 + CustomSuccess -> Progress 1 0 + ControlTrace _ x -> measureProgress x + ChoiceBranch _ x -> measureProgress x + UnapplicableRule {} -> mempty + CustomFailure {} -> mempty + UnsatisfiedControl {} -> mempty + InvalidTag {} -> mempty + ReferenceRule _ x -> increaseRefProgress $ measureProgress x + ListTrace x -> measureProgress x + MapTrace x -> measureProgress x + TagTrace _ x -> increaseTermProgress $ measureProgress x + +instance IsValidationTrace ListValidationTrace where + traceValidity = \case + ListValidationDone -> SValid + ListValidationLeftoverTerms {} -> SInvalid + ListValidationUnappliedRule {} -> SInvalid + ListValidationMissingRequired {} -> SInvalid + ListValidationBadGroup _ _ -> SInvalid + ListValidationConsume _ _ x -> traceValidity x + ListValidationConsumeGroup _ _ x -> traceValidity x + + measureProgress = \case + ListValidationDone -> Progress 1 0 + ListValidationConsume _ _ x -> increaseTermProgress $ measureProgress x + ListValidationLeftoverTerms _ Nothing -> mempty + ListValidationLeftoverTerms _ (Just (_, trc)) -> measureProgress trc + ListValidationMissingRequired _ _ -> mempty + ListValidationUnappliedRule _ -> mempty + ListValidationConsumeGroup rs g x -> Progress 0 (length rs) <> measureProgress g <> measureProgress x + ListValidationBadGroup rs x -> Progress 0 (length rs) <> measureProgress x + +instance IsValidationTrace MapValidationTrace where + traceValidity = \case + MapValidationDone -> SValid + MapValidationLeftoverKVs _ _ -> SInvalid + MapValidationUnappliedRules _ -> SInvalid + MapValidationInvalidValue {} -> SInvalid + MapValidationDuplicateKeys {} -> SInvalid + MapValidationConsume _ _ _ x -> traceValidity x + + measureProgress = \case + MapValidationDone -> Progress 1 0 + MapValidationLeftoverKVs _ Nothing -> mempty + MapValidationLeftoverKVs _ (Just (_, trc)) -> measureProgress trc + MapValidationUnappliedRules _ -> mempty + MapValidationConsume _ kTrc vTrc x -> + measureProgress kTrc <> measureProgress vTrc <> measureProgress x + MapValidationInvalidValue _ kTrc vTrc -> + measureProgress kTrc <> measureProgress vTrc + MapValidationDuplicateKeys _ _ trc -> measureProgress trc + +evidence :: (Show (t v), IsValidationTrace t) => t v -> Evidenced t +evidence x = Evidenced (traceValidity x) x + +isValid :: Evidenced t -> Bool +isValid Evidenced {eValidity = SValid} = True +isValid _ = False + +compareEvidencedProgress :: IsValidationTrace t => Evidenced t -> Evidenced t -> Ordering +compareEvidencedProgress (Evidenced SValid _) (Evidenced SValid _) = EQ +compareEvidencedProgress (Evidenced SInvalid _) (Evidenced SValid _) = LT +compareEvidencedProgress (Evidenced SValid _) (Evidenced SInvalid _) = GT +compareEvidencedProgress (Evidenced SInvalid x) (Evidenced SInvalid y) = + x `compareInvalidProgress` y + +compareInvalidProgress :: IsValidationTrace t => t IsInvalid -> t IsInvalid -> Ordering +compareInvalidProgress = compare `on` measureProgress + +nestContainer :: Doc AnsiStyle -> Doc AnsiStyle +nestContainer = hang 2 . ("└ " <>) + +newtype TraceOptions = TraceOptions + { toFoldValid :: Bool + } + +defaultTraceOptions :: TraceOptions +defaultTraceOptions = TraceOptions {toFoldValid = False} + +prettyListValidationResult :: TraceOptions -> ListValidationTrace v -> Doc AnsiStyle +prettyListValidationResult opts@TraceOptions {..} = \case + ListValidationDone -> mempty + ListValidationLeftoverTerms _ Nothing -> + annotate (color Red) "leftover elements not matched by any rule" + ListValidationLeftoverTerms _ (Just (rule, trc)) -> + hang 2 $ + vsep + [ annotate (color Red) "leftover elements, closest matching rule:" + , annotate (color Green) $ pretty $ show rule + , nestContainer $ prettyValidationTrace opts trc + ] + ListValidationUnappliedRule r -> + hang 2 $ + vsep + [ annotate (color Red) "required rule not satisfied:" + , pretty r + ] + ListValidationConsume _ t c + | toFoldValid -> foldValid 1 c + | otherwise -> vsep $ continue c [prettyValidationTrace opts t] + ListValidationMissingRequired _ t -> + vsep + [ annotate (color Red) "failed to apply required rule:" + , nestContainer $ prettyValidationTrace opts t + ] + ListValidationConsumeGroup refs x c -> vsep . continue c $ prettyGroup SValid refs x + ListValidationBadGroup refs x -> vsep $ prettyGroup SInvalid refs x + where + -- This prevents unnecessary empty lines + continue ListValidationDone l = l + continue x l = l <> [prettyListValidationResult opts x] + + prettyGroup :: SValidity v -> [Name] -> ListValidationTrace v -> [Doc AnsiStyle] + prettyGroup v refs x = go refs + where + go (n : ns) = + [ "ref" <+> pretty n + , nestContainer . vsep $ go ns + ] + go [] = + [ case v of + SValid -> "grp" + SInvalid -> "grp" <+> annotate (color Red) "(fail)" + , nestContainer $ prettyListValidationResult opts x + ] + + foldValid !n (ListValidationConsume _ _ c) = foldValid (n + 1) c + foldValid !n t = + vsep $ continue t [annotate italicized $ pretty (n :: Int) <> " valid elements"] + +prettyMapValidationResult :: TraceOptions -> MapValidationTrace v -> Doc AnsiStyle +prettyMapValidationResult opts@TraceOptions {..} = \case + MapValidationDone -> mempty + MapValidationLeftoverKVs _ Nothing -> + annotate (color Red) "leftover key-value pairs not matched by any rule" + MapValidationLeftoverKVs _ (Just (rule, trc)) -> + hang 2 $ + vsep + [ annotate (color Red) "leftover key-value pairs, closest matching rule:" + , annotate (color Green) $ pretty rule + , nestContainer $ prettyMapValidationResult opts trc + ] + MapValidationUnappliedRules rs -> + hang 2 $ + vsep + [ annotate (color Red) "not all required rules have been applied:" + , vsep (NE.toList $ pretty <$> rs) + ] + MapValidationConsume _ k v c + | toFoldValid -> foldValid 1 c + | otherwise -> + vsep $ + continue + c + [ "key:" + , nestContainer $ prettyValidationTrace opts k + , "value:" + , nestContainer $ prettyValidationTrace opts v + ] + MapValidationInvalidValue _ k v -> + vsep + [ "key:" + , nestContainer $ prettyValidationTrace opts k + , "value:" <+> annotate (color Red) "(fail)" + , nestContainer $ prettyValidationTrace opts v + ] + MapValidationDuplicateKeys _ _ trc -> + vsep + [ "key: " <> annotate (color Red) "(duplicate)" + , nestContainer $ prettyValidationTrace opts trc + ] + where + foldValid !n (MapValidationConsume _ _ _ c) = foldValid (n + 1) c + foldValid !n t = + vsep . continue t $ + [ annotate italicized $ pretty (n :: Int) <> " valid key-value pairs" + , "..." + ] + + -- This prevents unnecessary empty lines + continue MapValidationDone l = l + continue x l = l <> [prettyMapValidationResult opts x] + +prettyValidationTrace :: TraceOptions -> ValidationTrace v -> Doc AnsiStyle +prettyValidationTrace opts = \case + UnapplicableRule x -> annotate (color Red) $ vsep ["failed to apply: ", indent 2 $ pretty x] + TerminalRule x -> "app: " <> annotate (color Green) (pretty x) + ControlTrace ci x -> + vsep + [ prettyValidationTrace opts x + , nestContainer $ "ctrl:" <+> annotate (color Yellow) ("." <> pretty ci) + ] + ChoiceBranch i c -> + vsep + [ "choice (idx: " <> pretty i <> ")" + , nestContainer $ prettyValidationTrace opts c + ] + ReferenceRule (Name n) x -> + vsep + [ "ref: " <> annotate (color Blue) (pretty n) + , nestContainer $ prettyValidationTrace opts x + ] + CustomFailure e -> annotate (color Red) $ pretty e + CustomSuccess -> "" + UnsatisfiedControl op ctl -> + annotate (color Red) $ + vsep + [ "unsatisfied control:" + , indent 2 $ "." <> pretty op <+> pretty ctl + ] + ListTrace l -> + vsep + [ "array" + , nestContainer $ prettyListValidationResult opts l + ] + MapTrace m -> + vsep + [ "map" + , nestContainer $ prettyMapValidationResult opts m + ] + TagTrace t x -> + vsep + [ "tag:" <+> annotate (color Green) ("#6." <> pretty t) + , nestContainer $ prettyValidationTrace opts x + ] + InvalidTag expected actual -> + "expected tag #6." <> pretty expected <> ", got #6." <> pretty actual + +showValidationTrace :: ValidationTrace v -> String +showValidationTrace = + T.unpack + . Ansi.renderStrict + . layoutPretty defaultLayoutOptions + . prettyValidationTrace defaultTraceOptions diff --git a/src/Codec/CBOR/Cuddle/CDDL/Phase.hs b/src/Codec/CBOR/Cuddle/CDDL/Phase.hs new file mode 100644 index 00000000..c0bcd301 --- /dev/null +++ b/src/Codec/CBOR/Cuddle/CDDL/Phase.hs @@ -0,0 +1,29 @@ +{-# LANGUAGE TypeData #-} + +module Codec.CBOR.Cuddle.CDDL.Phase ( + CTreePhase, + MonoReferenced, + MonoSimplePhase, + HuddleStage, + showSimple, +) where + +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) + +type data CTreePhase + +type data MonoReferenced + +type data MonoSimplePhase + +type data HuddleStage + +-- | Project any phase that maps to 'MonoSimplePhase' down to a `Show`able +-- representation. Used for debug output by `Gen`, `Validator`, etc. +showSimple :: + forall a phase. + ( IndexMappable a phase MonoSimplePhase + , Show (a MonoSimplePhase) + ) => + a phase -> String +showSimple = show . mapIndex @_ @_ @MonoSimplePhase diff --git a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs index 2bfa9b57..c2ebfe05 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs @@ -1,5 +1,6 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} +{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedLabels #-} @@ -9,6 +10,7 @@ {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} +{-# OPTIONS_GHC -Wno-orphans #-} -- | Module containing tools for 'resolving' CDDL -- @@ -35,8 +37,6 @@ module Codec.CBOR.Cuddle.CDDL.Resolve ( fullResolveCDDL, NameResolutionFailure (..), MonoReferenced, - MonoSimplePhase, - showSimple, XXCTree (..), ) where @@ -53,7 +53,7 @@ import Codec.CBOR.Cuddle.CDDL.CTree ( CTree (..), CTreeRoot (..), PTerm (..), - XXCTree, + XXCTree (..), foldCTree, ) import Codec.CBOR.Cuddle.CDDL.CTree qualified as CTree @@ -66,7 +66,6 @@ import Data.Hashable import Data.List (foldl') -import Codec.CBOR.Cuddle.CDDL.CTreePhase (CTreePhase, XRule (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenPhase, @@ -80,7 +79,11 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( XXCTree (..), withLocalValidateBindings, ) +import Codec.CBOR.Cuddle.CDDL.Phase (CTreePhase, HuddleStage, MonoReferenced, MonoSimplePhase) +import Codec.CBOR.Cuddle.Huddle (XRule (..), XXType2 (..)) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) +import Codec.CBOR.Cuddle.Parser (ParserStage) +import Data.Default.Class (Default) import Data.List.NonEmpty qualified as NE import Data.Map.Strict qualified as Map import Data.Text qualified as T @@ -101,6 +104,24 @@ instance Hashable a => Hashable (ProvidedParameters a) -- 1. Rule extensions -------------------------------------------------------------------------------- +data instance XTerm CTreePhase = CTreeXTerm + deriving (Generic, Show, Eq, Ord) + deriving anyclass (Hashable, Default) + +data instance XXTopLevel CTreePhase + deriving (Generic, Show, Eq, Ord) + +data instance XCddl CTreePhase = CTreeXCddl + deriving (Generic, Show, Eq, Ord) + +data instance XRule CTreePhase + = CTreeXRule (TermGenerator RuleTerm -> TermGenerator RuleTerm) (Maybe TermValidator) + deriving (Generic) + +data instance XXType2 CTreePhase + deriving (Generic, Show, Eq, Ord) + deriving anyclass (Hashable) + newtype PartialCTreeRoot i = PartialCTreeRoot (Map.Map Name (ProvidedParameters (CTree i))) deriving (Generic) @@ -420,7 +441,8 @@ data instance XXCTree DistReferenced type data DistReferencedNoGen newtype instance XXCTree DistReferencedNoGen = DHRef (DistRef DistReferencedNoGen) - deriving (Eq, Hashable, Show) + deriving (Generic, Eq, Show) + deriving anyclass (Hashable) deriving newtype (Pretty) resolveRef :: @@ -466,8 +488,6 @@ buildResolvedCTree (PartialCTreeRoot ct) = PartialCTreeRoot <$> traverse go ct -- 4. Monomorphisation -------------------------------------------------------------------------------- -type data MonoReferenced - data instance XXCTree MonoReferenced = MRuleRef Name | MGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree MonoReferenced) @@ -478,57 +498,6 @@ type MonoEnv = BindingEnv DistReferenced MonoReferenced -- | We introduce additional bindings in the state type MonoState = Map.Map Name (CTree MonoReferenced) --- | A simplified phase reachable from any of the function-bearing post-mono --- phases ('MonoReferenced', 'GenPhase', 'ValidatorPhase'). It strips the --- generator/validator extensions so the tree can be `Show`n, `Eq`-compared, --- and pretty-printed for debug output. -type data MonoSimplePhase - -newtype instance XXCTree MonoSimplePhase = MSimpleRef Name - deriving (Generic, Show, Eq) - -instance Pretty (XXCTree MonoSimplePhase) where - pretty (MSimpleRef n) = pretty n - -instance IndexMappable CTree MonoReferenced MonoSimplePhase where - mapIndex = foldCTree mapExt mapIndex - where - mapExt (MRuleRef n) = CTreeE $ MSimpleRef n - mapExt (MGenerator _ x) = mapIndex x - mapExt (MValidator _ x) = mapIndex x - -instance IndexMappable CTreeRoot MonoReferenced MonoSimplePhase where - mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m - -instance IndexMappable CTree GenPhase MonoSimplePhase where - mapIndex = foldCTree mapExt mapIndex - where - mapExt (GenRef n) = CTreeE $ MSimpleRef n - mapExt (GenGenerator _ x) = mapIndex x - mapExt (GenValidator _ x) = mapIndex x - -instance IndexMappable CTreeRoot GenPhase MonoSimplePhase where - mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m - -instance IndexMappable CTree ValidatorPhase MonoSimplePhase where - mapIndex = foldCTree mapExt mapIndex - where - mapExt (VRuleRef n) = CTreeE $ MSimpleRef n - mapExt (VValidator _ x) = mapIndex x - -instance IndexMappable CTreeRoot ValidatorPhase MonoSimplePhase where - mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m - --- | Project any phase that maps to 'MonoSimplePhase' down to a `Show`able --- representation. Used for debug output by `Gen`, `Validator`, etc. -showSimple :: - forall a phase. - ( IndexMappable a phase MonoSimplePhase - , Show (a MonoSimplePhase) - ) => - a phase -> String -showSimple = show . mapIndex @_ @_ @MonoSimplePhase - -- | Monad to run the monomorphisation process. We need some additional -- capabilities for this, so 'Either' doesn't fully cut it anymore. newtype MonoM a = MonoM @@ -538,7 +507,7 @@ newtype MonoM a = MonoM (StateT MonoState (Reader MonoEnv)) a } - deriving (Functor, Applicative, Monad) + deriving newtype (Functor, Applicative, Monad) deriving (HasThrow "nameResolution" NameResolutionFailure) via MonadError @@ -684,6 +653,10 @@ fullResolveCDDL cddl = do rCTree <- buildResolvedCTree refCTree buildMonoCTree rCTree +-- * IndexMappable + +-- DistReferenced -> DistReferencedNoGen + instance IndexMappable CTree DistReferenced DistReferencedNoGen where mapIndex = foldCTree mapExt mapIndex where @@ -694,3 +667,55 @@ instance IndexMappable CTree DistReferenced DistReferencedNoGen where instance IndexMappable DistRef DistReferenced DistReferencedNoGen where mapIndex (GenericRef n) = GenericRef n mapIndex (RuleRef n args) = RuleRef n $ mapIndex <$> args + +-- MonoReferenced -> MonoSimplePhase + +instance IndexMappable CTree MonoReferenced MonoSimplePhase where + mapIndex = foldCTree mapExt mapIndex + where + mapExt (MRuleRef n) = CTreeE $ MSimpleRef n + mapExt (MGenerator _ x) = mapIndex x + mapExt (MValidator _ x) = mapIndex x + +instance IndexMappable CTreeRoot MonoReferenced MonoSimplePhase where + mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m + +-- ParserStage -> CTreePhase + +instance IndexMappable XCddl ParserStage CTreePhase where + mapIndex _ = CTreeXCddl + +instance IndexMappable XXType2 ParserStage CTreePhase where + mapIndex (ParserXXType2 c) = case c of {} + +instance IndexMappable XTerm ParserStage CTreePhase where + mapIndex _ = CTreeXTerm + +instance IndexMappable XRule ParserStage CTreePhase where + mapIndex _ = CTreeXRule id Nothing + +-- GenPhase -> MonoSimplePhase + +instance IndexMappable CTree GenPhase MonoSimplePhase where + mapIndex = foldCTree mapExt mapIndex + where + mapExt (GenRef n) = CTreeE $ MSimpleRef n + mapExt (GenGenerator _ x) = mapIndex x + mapExt (GenValidator _ x) = mapIndex x + +instance IndexMappable CTreeRoot GenPhase MonoSimplePhase where + mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m + +-- HuddleStage -> CTreePhase + +instance IndexMappable XCddl HuddleStage CTreePhase where + mapIndex _ = CTreeXCddl + +instance IndexMappable XXType2 HuddleStage CTreePhase where + mapIndex (HuddleXXType2 c) = case c of {} + +instance IndexMappable XTerm HuddleStage CTreePhase where + mapIndex _ = CTreeXTerm + +instance IndexMappable XRule HuddleStage CTreePhase where + mapIndex (HuddleXRule _ g v) = CTreeXRule g v diff --git a/src/Codec/CBOR/Cuddle/Comments.hs b/src/Codec/CBOR/Cuddle/Comments.hs index 4c056ef1..d5a5a2a6 100644 --- a/src/Codec/CBOR/Cuddle/Comments.hs +++ b/src/Codec/CBOR/Cuddle/Comments.hs @@ -20,6 +20,11 @@ module Codec.CBOR.Cuddle.Comments ( toComment, commentLine, withComment, + + -- * Pretty + CommentRender (..), + prettyCommentNoBreak, + prettyCommentNoBreakWS, ) where import Data.ByteString (ByteString) @@ -32,6 +37,7 @@ import Data.Void (Void, absurd) import Data.Word (Word16, Word32, Word64, Word8) import GHC.Generics (Generic (..), K1 (..), M1 (..), U1 (..), V1, (:*:) (..), (:+:) (..)) import Optics.Core (Lens', lens, view, (%~), (&), (.~), (^.)) +import Prettyprinter newtype Comment = Comment [T.Text] deriving (Eq, Ord, Generic, Show) @@ -194,3 +200,20 @@ instance HasComment Comment where instance IsString Comment where fromString = toComment . T.pack + +data CommentRender + = PreComment + | PostComment + +prettyCommentNoBreak :: Comment -> Doc ann +prettyCommentNoBreak = align . vsep . fmap (pretty . (";" <>)) . unComment + +prettyCommentNoBreakWS :: Comment -> Doc ann +prettyCommentNoBreakWS cmt + | cmt == mempty = mempty + | otherwise = space <> prettyCommentNoBreak cmt + +instance Pretty Comment where + pretty c + | c == mempty = mempty + | otherwise = prettyCommentNoBreak c <> hardline diff --git a/src/Codec/CBOR/Cuddle/Huddle.hs b/src/Codec/CBOR/Cuddle/Huddle.hs index 9547d262..91536587 100644 --- a/src/Codec/CBOR/Cuddle/Huddle.hs +++ b/src/Codec/CBOR/Cuddle/Huddle.hs @@ -7,6 +7,7 @@ {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeData #-} {-# LANGUAGE TypeFamilies #-} +{-# OPTIONS_GHC -Wno-orphans #-} -- | Module for building CDDL in Haskell -- @@ -26,7 +27,6 @@ module Codec.CBOR.Cuddle.Huddle ( Type0 (..), -- * AST extensions - HuddleStage, C.XCddl (..), C.XTerm (..), C.XRule (..), @@ -118,7 +118,11 @@ import Codec.CBOR.Cuddle.CDDL ( GenericParameter (..), HasName (..), Name (..), + XCddl, XRule, + XTerm, + XXTopLevel, + XXType2, ) import Codec.CBOR.Cuddle.CDDL qualified as C import Codec.CBOR.Cuddle.CDDL.CtlOp qualified as CtlOp @@ -130,8 +134,11 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( simpleGen, ) import Codec.CBOR.Cuddle.CDDL.Custom.Validator (HasValidator (..), TermValidator) +import Codec.CBOR.Cuddle.CDDL.Phase (HuddleStage) import Codec.CBOR.Cuddle.Comments (Comment, HasComment (..)) import Codec.CBOR.Cuddle.Comments qualified as C +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) +import Codec.CBOR.Cuddle.Parser (ParserStage, XCddl (..), XTerm (..), XXTopLevel (..), XXType2 (..)) import Control.Monad (when) import Control.Monad.State (MonadState (get), State, execState, modify) import Data.ByteString (ByteString) @@ -155,8 +162,6 @@ import Optics.Core (lens, view, (%), (%~), (&)) import Optics.Core qualified as L import Prelude hiding ((/)) -type data HuddleStage - newtype instance C.XTerm HuddleStage = HuddleXTerm C.Comment deriving (Generic, Semigroup, Monoid, Show, Eq) @@ -1392,3 +1397,19 @@ withOverrideCBORGen f = withOverrideGenerator $ simpleGen . f . tgGenerator withValidator :: HasValidator a => TermValidator -> a -> a withValidator p = L.set validatorL $ Just p + +-- * IndexMappable + +-- ParserStage -> HuddleStage + +instance IndexMappable XCddl ParserStage HuddleStage where + mapIndex (ParserXCddl c) = HuddleXCddl c + +instance IndexMappable XXTopLevel ParserStage HuddleStage where + mapIndex (ParserXXTopLevel c) = HuddleXXTopLevel c + +instance IndexMappable XXType2 ParserStage HuddleStage where + mapIndex (ParserXXType2 c) = HuddleXXType2 c + +instance IndexMappable XTerm ParserStage HuddleStage where + mapIndex (ParserXTerm c) = HuddleXTerm c diff --git a/src/Codec/CBOR/Cuddle/IndexMappable.hs b/src/Codec/CBOR/Cuddle/IndexMappable.hs index 63650c8f..4c02f97b 100644 --- a/src/Codec/CBOR/Cuddle/IndexMappable.hs +++ b/src/Codec/CBOR/Cuddle/IndexMappable.hs @@ -1,290 +1,12 @@ {-# LANGUAGE DefaultSignatures #-} -module Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..), mapCDDLDropExt) where +module Codec.CBOR.Cuddle.IndexMappable ( + IndexMappable (..), +) where -import Codec.CBOR.Cuddle.CDDL ( - CDDL (..), - GenericArg (..), - GenericParameter (..), - GenericParameters (..), - Group (..), - GroupEntry (..), - GroupEntryVariant (..), - GrpChoice (..), - MemberKey (..), - Rule (..), - TopLevel (..), - Type0 (..), - Type1 (..), - Type2 (..), - TypeOrGroup (..), - XCddl, - XRule, - XTerm, - XXTopLevel, - XXType2, - ) -import Codec.CBOR.Cuddle.CDDL.CTreePhase ( - CTreePhase, - XCddl (..), - XRule (..), - XTerm (..), - ) -import Codec.CBOR.Cuddle.Huddle ( - HuddleStage, - XCddl (..), - XRule (..), - XTerm (..), - XXTopLevel (..), - XXType2 (..), - ) -import Codec.CBOR.Cuddle.Parser ( - ParserStage, - XCddl (..), - XRule (..), - XTerm (..), - XXTopLevel (..), - XXType2 (..), - ) -import Codec.CBOR.Cuddle.Pretty (PrettyStage, XCddl (..), XRule (..), XTerm (..), XXTopLevel (..)) -import Data.Bifunctor (Bifunctor (..)) import Data.Coerce (Coercible, coerce) -import Data.Void (absurd) class IndexMappable f i j where mapIndex :: f i -> f j default mapIndex :: Coercible (f i) (f j) => f i -> f j mapIndex = coerce - -mapCDDLDropExt :: - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - , IndexMappable XRule i j - ) => - CDDL i -> - CDDL j -mapCDDLDropExt (CDDL r tls _) = CDDL (mapIndex r) (foldMap mapTopLevelDropExt tls) [] - where - mapTopLevelDropExt (TopLevelRule x) = [TopLevelRule $ mapIndex x] - mapTopLevelDropExt (XXTopLevel _) = [] - -instance - ( IndexMappable XCddl i j - , IndexMappable XXTopLevel i j - , IndexMappable XXType2 i j - , IndexMappable XTerm i j - , IndexMappable XRule i j - ) => - IndexMappable CDDL i j - where - mapIndex (CDDL r tls e) = CDDL (mapIndex r) (mapIndex <$> tls) (mapIndex <$> e) - -instance - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - , IndexMappable XRule i j - ) => - IndexMappable Rule i j - where - mapIndex (Rule n mg a t c) = Rule n (mapIndex <$> mg) a (mapIndex t) (mapIndex c) - -instance - ( IndexMappable XXTopLevel i j - , IndexMappable XXType2 i j - , IndexMappable XTerm i j - , IndexMappable XRule i j - ) => - IndexMappable TopLevel i j - where - mapIndex (TopLevelRule r) = TopLevelRule $ mapIndex r - mapIndex (XXTopLevel e) = XXTopLevel $ mapIndex e - -instance IndexMappable XTerm i j => IndexMappable GenericParameter i j where - mapIndex (GenericParameter n e) = GenericParameter n $ mapIndex e - -instance IndexMappable XTerm i j => IndexMappable GenericParameters i j where - mapIndex (GenericParameters ns) = GenericParameters $ mapIndex <$> ns - -instance - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - ) => - IndexMappable TypeOrGroup i j - where - mapIndex (TOGType t) = TOGType $ mapIndex t - mapIndex (TOGGroup g) = TOGGroup $ mapIndex g - -instance - ( IndexMappable XTerm i j - , IndexMappable XXType2 i j - ) => - IndexMappable GroupEntry i j - where - mapIndex (GroupEntry mo gev e) = GroupEntry mo (mapIndex gev) (mapIndex e) - -instance - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - ) => - IndexMappable GroupEntryVariant i j - where - mapIndex (GEType mk t) = GEType (mapIndex <$> mk) $ mapIndex t - mapIndex (GERef n ma) = GERef n (mapIndex <$> ma) - mapIndex (GEGroup g) = GEGroup (mapIndex g) - -instance - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - ) => - IndexMappable MemberKey i j - where - mapIndex (MKType t) = MKType $ mapIndex t - mapIndex (MKBareword n) = MKBareword n - mapIndex (MKValue x) = MKValue x - -instance - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - ) => - IndexMappable Type0 i j - where - mapIndex (Type0 ts) = Type0 $ mapIndex <$> ts - -instance - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - ) => - IndexMappable Type1 i j - where - mapIndex (Type1 t mo e) = Type1 (mapIndex t) (second mapIndex <$> mo) (mapIndex e) - -instance - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - ) => - IndexMappable Type2 i j - where - mapIndex (T2Value v) = T2Value v - mapIndex (T2Name n mg) = T2Name n (mapIndex <$> mg) - mapIndex (T2Group t) = T2Group $ mapIndex t - mapIndex (T2Map g) = T2Map $ mapIndex g - mapIndex (T2Array a) = T2Array $ mapIndex a - mapIndex (T2Unwrapped n mg) = T2Unwrapped n (mapIndex <$> mg) - mapIndex (T2Enum g) = T2Enum $ mapIndex g - mapIndex (T2EnumRef n mg) = T2EnumRef n (mapIndex <$> mg) - mapIndex (T2Tag mt t) = T2Tag mt $ mapIndex t - mapIndex (T2DataItem t mt) = T2DataItem t mt - mapIndex T2Any = T2Any - mapIndex (XXType2 e) = XXType2 $ mapIndex e - -instance - ( IndexMappable XXType2 i j - , IndexMappable XTerm i j - ) => - IndexMappable GenericArg i j - where - mapIndex (GenericArg g) = GenericArg $ mapIndex <$> g - -instance - ( IndexMappable XTerm i j - , IndexMappable XXType2 i j - ) => - IndexMappable Group i j - where - mapIndex (Group g) = Group $ mapIndex <$> g - -instance - ( IndexMappable XTerm i j - , IndexMappable XXType2 i j - ) => - IndexMappable GrpChoice i j - where - mapIndex (GrpChoice gs e) = GrpChoice (mapIndex <$> gs) $ mapIndex e - --- ParserStage ~ PrettyStage - -instance IndexMappable XCddl ParserStage PrettyStage where - mapIndex (ParserXCddl c) = PrettyXCddl c - -instance IndexMappable XTerm ParserStage PrettyStage where - mapIndex (ParserXTerm c) = PrettyXTerm c - -instance IndexMappable XRule ParserStage PrettyStage where - mapIndex (ParserXRule c) = PrettyXRule c - -instance IndexMappable XXType2 ParserStage PrettyStage where - mapIndex (ParserXXType2 v) = absurd v - -instance IndexMappable XXTopLevel ParserStage PrettyStage where - mapIndex (ParserXXTopLevel c) = PrettyXXTopLevel c - --- ParserStage -> CTreePhase - -instance IndexMappable XCddl ParserStage CTreePhase where - mapIndex _ = CTreeXCddl - -instance IndexMappable XXType2 ParserStage CTreePhase where - mapIndex (ParserXXType2 c) = case c of {} - -instance IndexMappable XTerm ParserStage CTreePhase where - mapIndex _ = CTreeXTerm - -instance IndexMappable XRule ParserStage CTreePhase where - mapIndex _ = CTreeXRule id Nothing - --- ParserStage -> HuddleStage - -instance IndexMappable XCddl ParserStage HuddleStage where - mapIndex (ParserXCddl c) = HuddleXCddl c - -instance IndexMappable XXTopLevel ParserStage HuddleStage where - mapIndex (ParserXXTopLevel c) = HuddleXXTopLevel c - -instance IndexMappable XXType2 ParserStage HuddleStage where - mapIndex (ParserXXType2 c) = HuddleXXType2 c - -instance IndexMappable XTerm ParserStage HuddleStage where - mapIndex (ParserXTerm c) = HuddleXTerm c - --- HuddleStage -> CTreePhase - -instance IndexMappable XCddl HuddleStage CTreePhase where - mapIndex _ = CTreeXCddl - -instance IndexMappable XXType2 HuddleStage CTreePhase where - mapIndex (HuddleXXType2 c) = case c of {} - -instance IndexMappable XTerm HuddleStage CTreePhase where - mapIndex _ = CTreeXTerm - -instance IndexMappable XRule HuddleStage CTreePhase where - mapIndex (HuddleXRule _ g v) = CTreeXRule g v - --- HuddleStage -> PrettyStage - -instance IndexMappable XCddl HuddleStage PrettyStage where - mapIndex (HuddleXCddl c) = PrettyXCddl c - -instance IndexMappable XXTopLevel HuddleStage PrettyStage where - mapIndex (HuddleXXTopLevel c) = PrettyXXTopLevel c - -instance IndexMappable XXType2 HuddleStage PrettyStage where - mapIndex (HuddleXXType2 c) = absurd c - -instance IndexMappable XTerm HuddleStage PrettyStage where - mapIndex (HuddleXTerm c) = PrettyXTerm c - -instance IndexMappable XRule HuddleStage PrettyStage where - mapIndex (HuddleXRule c _ _) = PrettyXRule c - --- ParserStage ~ ParserStage - -instance IndexMappable XCddl ParserStage ParserStage - -instance IndexMappable XXTopLevel ParserStage ParserStage - -instance IndexMappable XXType2 ParserStage ParserStage - -instance IndexMappable XTerm ParserStage ParserStage - -instance IndexMappable XRule ParserStage ParserStage diff --git a/src/Codec/CBOR/Cuddle/Parser.hs b/src/Codec/CBOR/Cuddle/Parser.hs index 11be7afb..7dc94275 100644 --- a/src/Codec/CBOR/Cuddle/Parser.hs +++ b/src/Codec/CBOR/Cuddle/Parser.hs @@ -18,6 +18,7 @@ import Codec.CBOR.Cuddle.Comments ( (!*>), (<*!), ) +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable) import Codec.CBOR.Cuddle.Parser.Lexer ( Parser, charInRange, @@ -481,3 +482,17 @@ sepBy1' :: MonadParsec e s m => m a -> m sep -> m (NonEmpty a) sepBy1' p sep = NE.fromList <$> go where go = liftA2 (:) p (many (try $ sep *> p)) + +-- * IndexMappable + +-- ParserStage ~ ParserStage + +instance IndexMappable XCddl ParserStage ParserStage + +instance IndexMappable XXTopLevel ParserStage ParserStage + +instance IndexMappable XXType2 ParserStage ParserStage + +instance IndexMappable XTerm ParserStage ParserStage + +instance IndexMappable XRule ParserStage ParserStage diff --git a/src/Codec/CBOR/Cuddle/Pretty.hs b/src/Codec/CBOR/Cuddle/Pretty.hs index 2325b58a..cd7a6c66 100644 --- a/src/Codec/CBOR/Cuddle/Pretty.hs +++ b/src/Codec/CBOR/Cuddle/Pretty.hs @@ -9,7 +9,6 @@ {-# OPTIONS_GHC -Wno-orphans #-} module Codec.CBOR.Cuddle.Pretty ( - CommentRender (..), PrettyStage, XXTopLevel (..), XXType2 (..), @@ -20,10 +19,16 @@ module Codec.CBOR.Cuddle.Pretty ( ) where import Codec.CBOR.Cuddle.CDDL -import Codec.CBOR.Cuddle.CDDL.CTree (CTree, PTerm (..), XXCTree) -import Codec.CBOR.Cuddle.CDDL.CTree qualified as CT -import Codec.CBOR.Cuddle.CDDL.CtlOp (CtlOp) -import Codec.CBOR.Cuddle.Comments (CollectComments (..), Comment, HasComment (..), unComment) +import Codec.CBOR.Cuddle.CDDL.Phase (HuddleStage) +import Codec.CBOR.Cuddle.Comments ( + CollectComments (..), + Comment, + HasComment (..), + prettyCommentNoBreakWS, + ) +import Codec.CBOR.Cuddle.Huddle (XCddl (..), XRule (..), XTerm (..), XXTopLevel (..), XXType2 (..)) +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) +import Codec.CBOR.Cuddle.Parser (ParserStage, XRule (..)) import Codec.CBOR.Cuddle.Pretty.Columnar ( Cell (..), CellAlign (..), @@ -37,14 +42,11 @@ import Codec.CBOR.Cuddle.Pretty.Columnar ( singletonRow, ) import Codec.CBOR.Cuddle.Pretty.Utils (renderedLen, softspace) -import Data.ByteString.Base16 qualified as B16 -import Data.ByteString.Char8 qualified as BS import Data.Default.Class (Default) import Data.Foldable (Foldable (..)) import Data.List.NonEmpty qualified as NE -import Data.String (IsString, fromString) +import Data.String (IsString) import Data.Text (Text) -import Data.Text qualified as T import Data.Void (Void, absurd) import GHC.Generics (Generic) import Optics.Core ((^.)) @@ -82,26 +84,6 @@ instance Pretty (TopLevel PrettyStage) where pretty (XXTopLevel (PrettyXXTopLevel cmt)) = pretty cmt pretty (TopLevelRule x) = pretty x <> hardline -instance Pretty Name where - pretty (Name name) = pretty name - -data CommentRender - = PreComment - | PostComment - -prettyCommentNoBreak :: Comment -> Doc ann -prettyCommentNoBreak = align . vsep . toList . fmap (pretty . (";" <>)) . unComment - -prettyCommentNoBreakWS :: Comment -> Doc ann -prettyCommentNoBreakWS cmt - | cmt == mempty = mempty - | otherwise = space <> prettyCommentNoBreak cmt - -instance Pretty Comment where - pretty c - | c == mempty = mempty - | otherwise = prettyCommentNoBreak c <> hardline - type0Def :: Type0 PrettyStage -> Doc ann type0Def t = nest 2 $ line' <> pretty t @@ -145,9 +127,6 @@ instance Pretty (Type0 PrettyStage) where in Row [valCell, Cell (prettyCommentNoBreakWS cmt) LeftAlign] -instance Pretty CtlOp where - pretty = pretty . T.toLower . T.pack . show - instance Pretty TyOp where pretty (RangeOp ClOpen) = "..." pretty (RangeOp Closed) = ".." @@ -247,60 +226,43 @@ instance Pretty (MemberKey PrettyStage) where pretty (MKBareword n) = pretty n pretty (MKValue v) = pretty v -instance Pretty Value where - pretty (Value v cmt) = pretty v <> prettyCommentNoBreakWS cmt - -instance Pretty ValueVariant where - pretty (VUInt i) = pretty i - pretty (VNInt i) = "-" <> pretty i - pretty (VBignum i) = pretty i - pretty (VFloat16 i) = pretty i - pretty (VFloat32 i) = pretty i - pretty (VFloat64 i) = pretty i - pretty (VText t) = enclose "\"" "\"" $ pretty t - pretty (VBytes b) = fromString $ "h" <> "'" <> BS.unpack (B16.encode b) <> "'" - pretty (VBool True) = "true" - pretty (VBool False) = "false" - -instance Pretty PTerm where - pretty = \case - PTBool -> "bool" - PTUInt -> "uint" - PTNInt -> "nint" - PTInt -> "int" - PTHalf -> "half" - PTFloat -> "float" - PTDouble -> "double" - PTBytes -> "bytes" - PTText -> "text" - PTAny -> "any" - PTNil -> "nil" - PTUndefined -> "undefined" - -- | Render a pretty-stage CDDL to 'Text', removing trailing whitespace. renderCDDL :: LayoutOptions -> CDDL PrettyStage -> Text renderCDDL opts = PT.renderStrict . removeTrailingWhitespace . layoutPretty opts . pretty -instance Pretty (XXCTree p) => Pretty (CTree p) where - pretty = \case - CT.Literal v -> pretty v - CT.Postlude v -> pretty v - CT.Range lo hi ClOpen -> pretty lo <+> "..." <+> pretty hi - CT.Range lo hi Closed -> pretty lo <+> ".." <+> pretty hi - CT.KV k v _ -> pretty k <+> "==>" <+> pretty v - CT.CTreeE x -> pretty x - CT.Occur v oi -> - case oi of - OIOptional -> "?" <+> pretty v - OIZeroOrMore -> "*" <+> pretty v - OIOneOrMore -> "+" <+> pretty v - OIBounded lo hi -> foldMap pretty lo <> "*" <> foldMap pretty hi <+> pretty v - CT.Map m -> encloseSep "{" "}" "," $ pretty <$> m - CT.Array e -> list $ pretty <$> e - CT.Choice c -> group . vsep . punctuate "//" $ pretty <$> toList c - CT.Group g -> tupled $ pretty <$> g - CT.Control op tgt ctl -> pretty tgt <+> pretty op <+> pretty ctl - CT.Enum e -> "&" <> pretty e - CT.Unwrap x -> "~" <> pretty x - CT.Tag t x -> "#6." <> pretty t <> "(" <> pretty x <> ")" +-- * IndexMappable + +-- ParserStage ~ PrettyStage + +instance IndexMappable XCddl ParserStage PrettyStage where + mapIndex (ParserXCddl c) = PrettyXCddl c + +instance IndexMappable XTerm ParserStage PrettyStage where + mapIndex (ParserXTerm c) = PrettyXTerm c + +instance IndexMappable XRule ParserStage PrettyStage where + mapIndex (ParserXRule c) = PrettyXRule c + +instance IndexMappable XXType2 ParserStage PrettyStage where + mapIndex (ParserXXType2 v) = absurd v + +instance IndexMappable XXTopLevel ParserStage PrettyStage where + mapIndex (ParserXXTopLevel c) = PrettyXXTopLevel c + +-- HuddleStage -> PrettyStage + +instance IndexMappable XCddl HuddleStage PrettyStage where + mapIndex (HuddleXCddl c) = PrettyXCddl c + +instance IndexMappable XXTopLevel HuddleStage PrettyStage where + mapIndex (HuddleXXTopLevel c) = PrettyXXTopLevel c + +instance IndexMappable XXType2 HuddleStage PrettyStage where + mapIndex (HuddleXXType2 c) = absurd c + +instance IndexMappable XTerm HuddleStage PrettyStage where + mapIndex (HuddleXTerm c) = PrettyXTerm c + +instance IndexMappable XRule HuddleStage PrettyStage where + mapIndex (HuddleXRule c _ _) = PrettyXRule c From b736f0a33bae1688215726dcba0d827a285335f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 24 Nov 2026 14:15:34 +0200 Subject: [PATCH 20/37] Implement new validator monad --- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 111 ++++++++++++++++-- 1 file changed, 98 insertions(+), 13 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index 01d8883b..d71d8783 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -34,6 +34,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( ListValidationTrace (..), MapValidationTrace (..), evidence, + fromEither, foldEvidenced, measureProgress, prettyValidationTrace, @@ -41,12 +42,17 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm) import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..)) -import Codec.CBOR.Cuddle.CDDL.CTree (CTree (..), CTreeRoot (..), XXCTree) +import Codec.CBOR.Cuddle.CDDL.CTree (CTree (..), CTreeRoot (..), XXCTree (..), foldCTree) import Codec.CBOR.Cuddle.CDDL.CtlOp (CtlOp) import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm) import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase) +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Term (Term) +import Control.Applicative (Alternative (..)) +import Control.Monad.Except (ExceptT, MonadError (..), runExceptT, tryError) import Control.Monad.Reader (MonadReader (..), ReaderT (..), asks) +import Control.Monad.State.Strict (MonadState (..), State, modify, runState) +import Data.Foldable (Foldable (..)) import Data.Function (on) import Data.Kind (Type) import Data.List.NonEmpty (NonEmpty) @@ -86,10 +92,12 @@ data ValidateEnv = ValidateEnv , veLocal :: Map Name (CTree ValidatorPhase) } -newtype Validator a = Validator (ReaderT ValidateEnv (Either (ValidationTrace IsInvalid)) a) +newtype Validator a + = Validator + (ReaderT ValidateEnv (ExceptT (ValidationTrace IsInvalid) (State [ValidationTrace IsValid])) a) deriving (Functor, Applicative, Monad, MonadReader ValidateEnv) -type TermValidator = RuleTerm -> Validator (ValidationTrace IsValid) +type TermValidator = RuleTerm -> Validator () instance MonadCddl Validator where type Phase Validator = ValidatorPhase @@ -103,7 +111,51 @@ instance MonadCddl Validator where pure $ Map.lookup (Name t) binds instance MonadFail Validator where - fail msg = Validator . ReaderT $ \_ -> Left $ CustomFailure $ T.pack msg + fail msg = failWith $ CustomFailure $ T.pack msg + +instance Alternative Validator where + Validator x <|> Validator y = Validator $ do + initialSt <- get + xRes <- tryError x + case xRes of + Right res -> pure res + Left AlternativeFail -> put initialSt >> y + Left xFail -> do + xSt <- get + put initialSt + yRes <- tryError y + ySt <- get + case yRes of + Right res -> pure res + Left AlternativeFail -> put xSt >> throwError xFail + Left yFail -> do + let + xTrc = closeSteps xSt $ StepFailed xFail + yTrc = closeSteps ySt $ StepFailed yFail + case compareInvalidProgress xTrc yTrc of + GT -> put xSt >> throwError xFail + _ -> put ySt >> throwError yFail + empty = failWith AlternativeFail + +closeSteps :: [ValidationTrace IsValid] -> StepTrace v -> StepTrace v +closeSteps steps cap = foldl' (flip Step) cap steps + +capture :: Validator a -> Validator (Either (StepTrace IsInvalid) (a, StepTrace IsValid)) +capture (Validator m) = Validator $ do + saved <- get + put [] + r <- tryError m + steps <- get + put saved + pure $ case r of + Left err -> Left $ closeSteps steps (StepFailed err) + Right x -> Right (x, closeSteps steps StepsDone) + +accept :: CTree ValidatorPhase -> Validator () +accept rule = Validator $ modify (TerminalRule (mapIndex rule) :) + +failWith :: ValidationTrace IsInvalid -> Validator a +failWith err = Validator $ throwError err -- | Run an action with the given local generic bindings installed. withLocalValidateBindings :: @@ -111,11 +163,13 @@ withLocalValidateBindings :: withLocalValidateBindings binds = local (\env -> env {veLocal = binds `Map.union` veLocal env}) -runValidator :: - Validator (ValidationTrace IsValid) -> CTreeRoot ValidatorPhase -> Evidenced ValidationTrace -runValidator (Validator m) cddl = - either evidence evidence $ - runReaderT m ValidateEnv {veRoot = cddl, veLocal = Map.empty} +runValidator :: ValidateEnv -> Validator a -> Evidenced StepTrace +runValidator env (Validator m) = mkStepTrace $ runState (runExceptT $ runReaderT m env) [] + where + mkStepTrace (eFail, st) = + case eFail of + Right _ -> evidence $ closeSteps st StepsDone + Left err -> evidence $ closeSteps st (StepFailed err) type data Validity = IsValid @@ -152,6 +206,14 @@ foldEvidenced f (Evidenced v t) = SValid -> f t SInvalid -> f t +fromEither :: + ( IsValidationTrace t + , Show (t IsInvalid) + , Show (t IsValid) + ) => + Either (t IsInvalid) (t IsValid) -> Evidenced t +fromEither = either evidence evidence + deriving instance (forall v. Show (t v)) => Show (Evidenced t) class IsValidationTrace (t :: Validity -> Type) where @@ -193,13 +255,30 @@ data ControlInfo = ControlInfo instance Pretty ControlInfo where pretty ControlInfo {..} = pretty ciOp <+> pretty ciRule +data StepTrace v where + StepsDone :: StepTrace IsValid + Step :: ValidationTrace IsValid -> StepTrace v -> StepTrace v + StepFailed :: ValidationTrace IsInvalid -> StepTrace IsInvalid + +deriving instance Show (StepTrace v) + +instance IsValidationTrace StepTrace where + traceValidity = \case + StepsDone -> SValid + StepFailed _ -> SInvalid + Step _ next -> traceValidity next + measureProgress = \case + StepsDone -> Progress 1 0 + StepFailed x -> measureProgress x + Step this next -> measureProgress this <> measureProgress next + data ValidationTrace (v :: Validity) where + AlternativeFail :: ValidationTrace IsInvalid UnapplicableRule :: CTree MonoSimplePhase -> ValidationTrace IsInvalid TerminalRule :: CTree MonoSimplePhase -> ValidationTrace IsValid ControlTrace :: ControlInfo -> ValidationTrace IsValid -> ValidationTrace IsValid ReferenceRule :: Name -> ValidationTrace v -> ValidationTrace v CustomFailure :: Text -> ValidationTrace IsInvalid - CustomSuccess :: ValidationTrace IsValid UnsatisfiedControl :: CtlOp -> CTree MonoSimplePhase -> ValidationTrace IsInvalid ChoiceBranch :: Int -> ValidationTrace IsValid -> ValidationTrace IsValid ListTrace :: ListValidationTrace v -> ValidationTrace v @@ -267,7 +346,6 @@ deriving instance Show (MapValidationTrace v) instance IsValidationTrace ValidationTrace where traceValidity = \case - CustomSuccess {} -> SValid TerminalRule {} -> SValid ControlTrace {} -> SValid ChoiceBranch {} -> SValid @@ -279,16 +357,17 @@ instance IsValidationTrace ValidationTrace where ListTrace x -> traceValidity x MapTrace x -> traceValidity x TagTrace _ x -> traceValidity x + AlternativeFail -> SInvalid measureProgress = \case TerminalRule {} -> Progress 1 0 - CustomSuccess -> Progress 1 0 ControlTrace _ x -> measureProgress x ChoiceBranch _ x -> measureProgress x UnapplicableRule {} -> mempty CustomFailure {} -> mempty UnsatisfiedControl {} -> mempty InvalidTag {} -> mempty + AlternativeFail -> mempty ReferenceRule _ x -> increaseRefProgress $ measureProgress x ListTrace x -> measureProgress x MapTrace x -> measureProgress x @@ -485,7 +564,6 @@ prettyValidationTrace opts = \case , nestContainer $ prettyValidationTrace opts x ] CustomFailure e -> annotate (color Red) $ pretty e - CustomSuccess -> "" UnsatisfiedControl op ctl -> annotate (color Red) $ vsep @@ -509,6 +587,7 @@ prettyValidationTrace opts = \case ] InvalidTag expected actual -> "expected tag #6." <> pretty expected <> ", got #6." <> pretty actual + AlternativeFail -> mempty showValidationTrace :: ValidationTrace v -> String showValidationTrace = @@ -516,3 +595,9 @@ showValidationTrace = . Ansi.renderStrict . layoutPretty defaultLayoutOptions . prettyValidationTrace defaultTraceOptions + +instance IndexMappable CTree ValidatorPhase MonoSimplePhase where + mapIndex = foldCTree mapExt mapIndex + where + mapExt (VRuleRef n) = CTreeE $ MSimpleRef n + mapExt (VValidator _ x) = mapIndex x From c9f62bc29c9ebbbdb92c2721bdb9de3fb6bc8336 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Tue, 24 Nov 2026 17:05:14 +0200 Subject: [PATCH 21/37] Block indexed validator monad --- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 462 ++++++++---------- 1 file changed, 211 insertions(+), 251 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index d71d8783..d5a2f979 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -21,8 +21,8 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( nestContainer, TraceOptions (..), defaultTraceOptions, - prettyListValidationResult, showValidationTrace, + accept, -- * Trace SValidity (..), @@ -31,8 +31,6 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( Evidenced (..), ControlInfo (..), ValidationTrace (..), - ListValidationTrace (..), - MapValidationTrace (..), evidence, fromEither, foldEvidenced, @@ -59,6 +57,7 @@ import Data.List.NonEmpty (NonEmpty) import Data.List.NonEmpty qualified as NE import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map +import Data.Maybe (maybeToList) import Data.Text (Text) import Data.Text qualified as T import Data.Type.Equality (TestEquality (..), type (:~:) (..)) @@ -92,11 +91,13 @@ data ValidateEnv = ValidateEnv , veLocal :: Map Name (CTree ValidatorPhase) } -newtype Validator a +newtype ValidatorT (b :: Block) a = Validator - (ReaderT ValidateEnv (ExceptT (ValidationTrace IsInvalid) (State [ValidationTrace IsValid])) a) + (ReaderT ValidateEnv (ExceptT (ValidationTrace b IsInvalid) (State [ValidationTrace b IsValid])) a) deriving (Functor, Applicative, Monad, MonadReader ValidateEnv) +type Validator = ValidatorT TermBlock + type TermValidator = RuleTerm -> Validator () instance MonadCddl Validator where @@ -137,24 +138,13 @@ instance Alternative Validator where _ -> put ySt >> throwError yFail empty = failWith AlternativeFail -closeSteps :: [ValidationTrace IsValid] -> StepTrace v -> StepTrace v +closeSteps :: [ValidationTrace b IsValid] -> StepTrace b v -> StepTrace b v closeSteps steps cap = foldl' (flip Step) cap steps -capture :: Validator a -> Validator (Either (StepTrace IsInvalid) (a, StepTrace IsValid)) -capture (Validator m) = Validator $ do - saved <- get - put [] - r <- tryError m - steps <- get - put saved - pure $ case r of - Left err -> Left $ closeSteps steps (StepFailed err) - Right x -> Right (x, closeSteps steps StepsDone) - accept :: CTree ValidatorPhase -> Validator () accept rule = Validator $ modify (TerminalRule (mapIndex rule) :) -failWith :: ValidationTrace IsInvalid -> Validator a +failWith :: ValidationTrace b IsInvalid -> ValidatorT b a failWith err = Validator $ throwError err -- | Run an action with the given local generic bindings installed. @@ -163,7 +153,7 @@ withLocalValidateBindings :: withLocalValidateBindings binds = local (\env -> env {veLocal = binds `Map.union` veLocal env}) -runValidator :: ValidateEnv -> Validator a -> Evidenced StepTrace +runValidator :: ValidateEnv -> ValidatorT b a -> Evidenced (StepTrace b) runValidator env (Validator m) = mkStepTrace $ runState (runExceptT $ runReaderT m env) [] where mkStepTrace (eFail, st) = @@ -255,163 +245,151 @@ data ControlInfo = ControlInfo instance Pretty ControlInfo where pretty ControlInfo {..} = pretty ciOp <+> pretty ciRule -data StepTrace v where - StepsDone :: StepTrace IsValid - Step :: ValidationTrace IsValid -> StepTrace v -> StepTrace v - StepFailed :: ValidationTrace IsInvalid -> StepTrace IsInvalid +data StepTrace (b :: Block) (v :: Validity) where + StepsDone :: StepTrace b IsValid + Step :: ValidationTrace b IsValid -> StepTrace b v -> StepTrace b v + StepFailed :: ValidationTrace b IsInvalid -> StepTrace b IsInvalid + +toEvidencedList :: StepTrace b v -> [Evidenced (ValidationTrace b)] +toEvidencedList = \case + StepsDone -> [] + StepFailed x -> [evidence x] + Step x next -> evidence x : toEvidencedList next + +stepsTakeValid :: StepTrace b v -> [ValidationTrace b IsValid] +stepsTakeValid = \case + Step x next -> x : stepsTakeValid next + _ -> [] + +stepFailure :: StepTrace b v -> Maybe (ValidationTrace b IsInvalid) +stepFailure = \case + StepFailed x -> Just x + StepsDone -> Nothing + Step _ next -> stepFailure next -deriving instance Show (StepTrace v) +deriving instance Show (StepTrace b v) -instance IsValidationTrace StepTrace where +instance IsValidationTrace (StepTrace b) where traceValidity = \case StepsDone -> SValid StepFailed _ -> SInvalid Step _ next -> traceValidity next measureProgress = \case - StepsDone -> Progress 1 0 + StepsDone -> mempty StepFailed x -> measureProgress x Step this next -> measureProgress this <> measureProgress next -data ValidationTrace (v :: Validity) where - AlternativeFail :: ValidationTrace IsInvalid - UnapplicableRule :: CTree MonoSimplePhase -> ValidationTrace IsInvalid - TerminalRule :: CTree MonoSimplePhase -> ValidationTrace IsValid - ControlTrace :: ControlInfo -> ValidationTrace IsValid -> ValidationTrace IsValid - ReferenceRule :: Name -> ValidationTrace v -> ValidationTrace v - CustomFailure :: Text -> ValidationTrace IsInvalid - UnsatisfiedControl :: CtlOp -> CTree MonoSimplePhase -> ValidationTrace IsInvalid - ChoiceBranch :: Int -> ValidationTrace IsValid -> ValidationTrace IsValid - ListTrace :: ListValidationTrace v -> ValidationTrace v - MapTrace :: MapValidationTrace v -> ValidationTrace v - TagTrace :: Word64 -> ValidationTrace v -> ValidationTrace v - InvalidTag :: Word64 -> Word64 -> ValidationTrace IsInvalid - -deriving instance Show (ValidationTrace v) - -data ListValidationTrace (v :: Validity) where - ListValidationDone :: ListValidationTrace IsValid - ListValidationLeftoverTerms :: - NonEmpty Term -> - Maybe (CTree MonoSimplePhase, ValidationTrace IsInvalid) -> - ListValidationTrace IsInvalid - ListValidationUnappliedRule :: +type data Block = TermBlock | ListBlock | MapBlock + +data ValidationTrace (b :: Block) (v :: Validity) where + AlternativeFail :: ValidationTrace b IsInvalid + UnapplicableRule :: CTree MonoSimplePhase -> ValidationTrace TermBlock IsInvalid + TerminalRule :: CTree MonoSimplePhase -> ValidationTrace TermBlock IsValid + ControlTrace :: + ControlInfo -> ValidationTrace TermBlock IsValid -> ValidationTrace TermBlock IsValid + ReferenceRule :: Name -> StepTrace TermBlock v -> ValidationTrace TermBlock v + CustomSuccess :: ValidationTrace TermBlock IsValid + CustomFailure :: Text -> ValidationTrace b IsInvalid + UnsatisfiedControl :: CtlOp -> CTree MonoSimplePhase -> ValidationTrace TermBlock IsInvalid + ChoiceBranch :: Int -> StepTrace TermBlock IsValid -> ValidationTrace TermBlock IsValid + TagTrace :: Word64 -> StepTrace TermBlock v -> ValidationTrace TermBlock v + InvalidTag :: Word64 -> Word64 -> ValidationTrace TermBlock IsInvalid + ArrayTrace :: StepTrace ListBlock v -> ValidationTrace TermBlock v + ArrayElement :: CTree MonoSimplePhase -> - ListValidationTrace IsInvalid - ListValidationConsume :: + StepTrace TermBlock IsValid -> + ValidationTrace ListBlock IsValid + ArrayLeftoverTerms :: + NonEmpty Term -> + Maybe (CTree MonoSimplePhase, StepTrace TermBlock IsInvalid) -> + ValidationTrace ListBlock IsInvalid + ArrayLeftoverRule :: CTree MonoSimplePhase -> - ValidationTrace IsValid -> - ListValidationTrace v -> - ListValidationTrace v - ListValidationMissingRequired :: + ValidationTrace ListBlock IsInvalid + ArrayMissingRequired :: CTree MonoSimplePhase -> - ValidationTrace IsInvalid -> - ListValidationTrace IsInvalid - ListValidationConsumeGroup :: + StepTrace TermBlock IsInvalid -> + ValidationTrace ListBlock IsInvalid + ArrayConsumeGroup :: [Name] -> - ListValidationTrace IsValid -> - ListValidationTrace v -> - ListValidationTrace v - ListValidationBadGroup :: - [Name] -> - ListValidationTrace IsInvalid -> - ListValidationTrace IsInvalid - -deriving instance Show (ListValidationTrace v) - -data MapValidationTrace (v :: Validity) where - MapValidationDone :: MapValidationTrace IsValid - MapValidationLeftoverKVs :: - (Term, Term) -> - Maybe (CTree MonoSimplePhase, MapValidationTrace IsInvalid) -> - MapValidationTrace IsInvalid - MapValidationUnappliedRules :: NonEmpty (CTree MonoSimplePhase) -> MapValidationTrace IsInvalid - MapValidationInvalidValue :: + StepTrace ListBlock v -> + ValidationTrace ListBlock v + MapTrace :: StepTrace MapBlock v -> ValidationTrace TermBlock v + MapEntry :: CTree MonoSimplePhase -> - ValidationTrace IsValid -> - ValidationTrace IsInvalid -> - MapValidationTrace IsInvalid - MapValidationConsume :: + StepTrace TermBlock IsValid -> + StepTrace TermBlock IsValid -> + ValidationTrace MapBlock IsValid + MapInvalidValue :: CTree MonoSimplePhase -> - ValidationTrace IsValid -> - ValidationTrace IsValid -> - MapValidationTrace v -> - MapValidationTrace v - MapValidationDuplicateKeys :: + StepTrace TermBlock IsValid -> + StepTrace TermBlock IsInvalid -> + ValidationTrace MapBlock IsInvalid + MapDuplicateKeys :: CTree MonoSimplePhase -> CanonicalTerm -> - ValidationTrace IsValid -> - MapValidationTrace IsInvalid + StepTrace TermBlock IsValid -> + ValidationTrace MapBlock IsInvalid + MapUnappliedRules :: NonEmpty (CTree MonoSimplePhase) -> ValidationTrace MapBlock IsInvalid + MapLeftoverEntries :: + (Term, Term) -> + Maybe (CTree MonoSimplePhase, StepTrace MapBlock IsInvalid) -> + ValidationTrace MapBlock IsInvalid -deriving instance Show (MapValidationTrace v) +deriving instance Show (ValidationTrace b v) -instance IsValidationTrace ValidationTrace where +instance IsValidationTrace (ValidationTrace b) where traceValidity = \case TerminalRule {} -> SValid ControlTrace {} -> SValid - ChoiceBranch {} -> SValid + AlternativeFail -> SInvalid UnapplicableRule {} -> SInvalid + ReferenceRule _ x -> traceValidity x + CustomSuccess -> SValid CustomFailure {} -> SInvalid UnsatisfiedControl {} -> SInvalid + ChoiceBranch {} -> SValid + TagTrace _ x -> traceValidity x InvalidTag {} -> SInvalid - ReferenceRule _ x -> traceValidity x - ListTrace x -> traceValidity x + ArrayTrace x -> traceValidity x + ArrayElement {} -> SValid + ArrayLeftoverTerms {} -> SInvalid + ArrayLeftoverRule {} -> SInvalid + ArrayMissingRequired {} -> SInvalid + ArrayConsumeGroup _ x -> traceValidity x MapTrace x -> traceValidity x - TagTrace _ x -> traceValidity x - AlternativeFail -> SInvalid + MapEntry {} -> SValid + MapInvalidValue {} -> SInvalid + MapDuplicateKeys {} -> SInvalid + MapUnappliedRules {} -> SInvalid + MapLeftoverEntries {} -> SInvalid measureProgress = \case TerminalRule {} -> Progress 1 0 ControlTrace _ x -> measureProgress x - ChoiceBranch _ x -> measureProgress x + AlternativeFail -> mempty UnapplicableRule {} -> mempty + ReferenceRule _ x -> increaseRefProgress $ measureProgress x + CustomSuccess -> Progress 1 0 CustomFailure {} -> mempty UnsatisfiedControl {} -> mempty - InvalidTag {} -> mempty - AlternativeFail -> mempty - ReferenceRule _ x -> increaseRefProgress $ measureProgress x - ListTrace x -> measureProgress x - MapTrace x -> measureProgress x + ChoiceBranch _ x -> measureProgress x TagTrace _ x -> increaseTermProgress $ measureProgress x - -instance IsValidationTrace ListValidationTrace where - traceValidity = \case - ListValidationDone -> SValid - ListValidationLeftoverTerms {} -> SInvalid - ListValidationUnappliedRule {} -> SInvalid - ListValidationMissingRequired {} -> SInvalid - ListValidationBadGroup _ _ -> SInvalid - ListValidationConsume _ _ x -> traceValidity x - ListValidationConsumeGroup _ _ x -> traceValidity x - - measureProgress = \case - ListValidationDone -> Progress 1 0 - ListValidationConsume _ _ x -> increaseTermProgress $ measureProgress x - ListValidationLeftoverTerms _ Nothing -> mempty - ListValidationLeftoverTerms _ (Just (_, trc)) -> measureProgress trc - ListValidationMissingRequired _ _ -> mempty - ListValidationUnappliedRule _ -> mempty - ListValidationConsumeGroup rs g x -> Progress 0 (length rs) <> measureProgress g <> measureProgress x - ListValidationBadGroup rs x -> Progress 0 (length rs) <> measureProgress x - -instance IsValidationTrace MapValidationTrace where - traceValidity = \case - MapValidationDone -> SValid - MapValidationLeftoverKVs _ _ -> SInvalid - MapValidationUnappliedRules _ -> SInvalid - MapValidationInvalidValue {} -> SInvalid - MapValidationDuplicateKeys {} -> SInvalid - MapValidationConsume _ _ _ x -> traceValidity x - - measureProgress = \case - MapValidationDone -> Progress 1 0 - MapValidationLeftoverKVs _ Nothing -> mempty - MapValidationLeftoverKVs _ (Just (_, trc)) -> measureProgress trc - MapValidationUnappliedRules _ -> mempty - MapValidationConsume _ kTrc vTrc x -> - measureProgress kTrc <> measureProgress vTrc <> measureProgress x - MapValidationInvalidValue _ kTrc vTrc -> - measureProgress kTrc <> measureProgress vTrc - MapValidationDuplicateKeys _ _ trc -> measureProgress trc + InvalidTag {} -> mempty + ArrayTrace x -> increaseTermProgress $ measureProgress x + ArrayElement {} -> Progress 1 0 + ArrayLeftoverTerms _ Nothing -> mempty + ArrayLeftoverTerms _ (Just (_, x)) -> measureProgress x + ArrayLeftoverRule {} -> mempty + ArrayMissingRequired {} -> mempty + ArrayConsumeGroup ns x -> Progress 0 (length ns) <> measureProgress x + MapTrace x -> increaseTermProgress $ measureProgress x + MapEntry _ k v -> measureProgress k <> measureProgress v + MapInvalidValue _ k v -> measureProgress k <> measureProgress v + MapDuplicateKeys _ _ x -> measureProgress x + MapUnappliedRules {} -> mempty + MapLeftoverEntries _ Nothing -> mempty + MapLeftoverEntries _ (Just (_, x)) -> measureProgress x evidence :: (Show (t v), IsValidationTrace t) => t v -> Evidenced t evidence x = Evidenced (traceValidity x) x @@ -440,114 +418,26 @@ newtype TraceOptions = TraceOptions defaultTraceOptions :: TraceOptions defaultTraceOptions = TraceOptions {toFoldValid = False} -prettyListValidationResult :: TraceOptions -> ListValidationTrace v -> Doc AnsiStyle -prettyListValidationResult opts@TraceOptions {..} = \case - ListValidationDone -> mempty - ListValidationLeftoverTerms _ Nothing -> - annotate (color Red) "leftover elements not matched by any rule" - ListValidationLeftoverTerms _ (Just (rule, trc)) -> - hang 2 $ - vsep - [ annotate (color Red) "leftover elements, closest matching rule:" - , annotate (color Green) $ pretty $ show rule - , nestContainer $ prettyValidationTrace opts trc - ] - ListValidationUnappliedRule r -> - hang 2 $ - vsep - [ annotate (color Red) "required rule not satisfied:" - , pretty r - ] - ListValidationConsume _ t c - | toFoldValid -> foldValid 1 c - | otherwise -> vsep $ continue c [prettyValidationTrace opts t] - ListValidationMissingRequired _ t -> - vsep - [ annotate (color Red) "failed to apply required rule:" - , nestContainer $ prettyValidationTrace opts t - ] - ListValidationConsumeGroup refs x c -> vsep . continue c $ prettyGroup SValid refs x - ListValidationBadGroup refs x -> vsep $ prettyGroup SInvalid refs x - where - -- This prevents unnecessary empty lines - continue ListValidationDone l = l - continue x l = l <> [prettyListValidationResult opts x] - - prettyGroup :: SValidity v -> [Name] -> ListValidationTrace v -> [Doc AnsiStyle] - prettyGroup v refs x = go refs - where - go (n : ns) = - [ "ref" <+> pretty n - , nestContainer . vsep $ go ns - ] - go [] = - [ case v of - SValid -> "grp" - SInvalid -> "grp" <+> annotate (color Red) "(fail)" - , nestContainer $ prettyListValidationResult opts x - ] - - foldValid !n (ListValidationConsume _ _ c) = foldValid (n + 1) c - foldValid !n t = - vsep $ continue t [annotate italicized $ pretty (n :: Int) <> " valid elements"] - -prettyMapValidationResult :: TraceOptions -> MapValidationTrace v -> Doc AnsiStyle -prettyMapValidationResult opts@TraceOptions {..} = \case - MapValidationDone -> mempty - MapValidationLeftoverKVs _ Nothing -> - annotate (color Red) "leftover key-value pairs not matched by any rule" - MapValidationLeftoverKVs _ (Just (rule, trc)) -> - hang 2 $ - vsep - [ annotate (color Red) "leftover key-value pairs, closest matching rule:" - , annotate (color Green) $ pretty rule - , nestContainer $ prettyMapValidationResult opts trc +prettyStepTrace :: Bool -> TraceOptions -> StepTrace b v -> Doc AnsiStyle +prettyStepTrace mayFold opts@TraceOptions {..} steps + | toFoldValid && mayFold = + vsep $ + [ annotate italicized $ "... " <> pretty (length validInit) <> " valid entries not shown" + | not $ null validInit ] - MapValidationUnappliedRules rs -> - hang 2 $ - vsep - [ annotate (color Red) "not all required rules have been applied:" - , vsep (NE.toList $ pretty <$> rs) - ] - MapValidationConsume _ k v c - | toFoldValid -> foldValid 1 c - | otherwise -> - vsep $ - continue - c - [ "key:" - , nestContainer $ prettyValidationTrace opts k - , "value:" - , nestContainer $ prettyValidationTrace opts v - ] - MapValidationInvalidValue _ k v -> - vsep - [ "key:" - , nestContainer $ prettyValidationTrace opts k - , "value:" <+> annotate (color Red) "(fail)" - , nestContainer $ prettyValidationTrace opts v - ] - MapValidationDuplicateKeys _ _ trc -> - vsep - [ "key: " <> annotate (color Red) "(duplicate)" - , nestContainer $ prettyValidationTrace opts trc - ] + <> [ prettyValidationTrace opts f + | f <- maybeToList $ stepFailure steps + ] + | otherwise = + vsep $ foldEvidenced (prettyValidationTrace opts) <$> toEvidencedList steps where - foldValid !n (MapValidationConsume _ _ _ c) = foldValid (n + 1) c - foldValid !n t = - vsep . continue t $ - [ annotate italicized $ pretty (n :: Int) <> " valid key-value pairs" - , "..." - ] + validInit = stepsTakeValid steps - -- This prevents unnecessary empty lines - continue MapValidationDone l = l - continue x l = l <> [prettyMapValidationResult opts x] - -prettyValidationTrace :: TraceOptions -> ValidationTrace v -> Doc AnsiStyle +prettyValidationTrace :: TraceOptions -> ValidationTrace b v -> Doc AnsiStyle prettyValidationTrace opts = \case - UnapplicableRule x -> annotate (color Red) $ vsep ["failed to apply: ", indent 2 $ pretty x] TerminalRule x -> "app: " <> annotate (color Green) (pretty x) + AlternativeFail -> mempty + UnapplicableRule x -> annotate (color Red) $ vsep ["failed to apply: ", indent 2 $ pretty x] ControlTrace ci x -> vsep [ prettyValidationTrace opts x @@ -556,13 +446,14 @@ prettyValidationTrace opts = \case ChoiceBranch i c -> vsep [ "choice (idx: " <> pretty i <> ")" - , nestContainer $ prettyValidationTrace opts c + , nestContainer $ prettyStepTrace False opts c ] ReferenceRule (Name n) x -> vsep [ "ref: " <> annotate (color Blue) (pretty n) - , nestContainer $ prettyValidationTrace opts x + , nestContainer $ prettyStepTrace False opts x ] + CustomSuccess -> "" CustomFailure e -> annotate (color Red) $ pretty e UnsatisfiedControl op ctl -> annotate (color Red) $ @@ -570,26 +461,95 @@ prettyValidationTrace opts = \case [ "unsatisfied control:" , indent 2 $ "." <> pretty op <+> pretty ctl ] - ListTrace l -> + ArrayTrace l -> vsep [ "array" - , nestContainer $ prettyListValidationResult opts l + , nestContainer $ prettyStepTrace False opts l ] MapTrace m -> vsep [ "map" - , nestContainer $ prettyMapValidationResult opts m + , nestContainer $ prettyStepTrace False opts m ] TagTrace t x -> vsep [ "tag:" <+> annotate (color Green) ("#6." <> pretty t) - , nestContainer $ prettyValidationTrace opts x + , nestContainer $ prettyStepTrace False opts x ] InvalidTag expected actual -> "expected tag #6." <> pretty expected <> ", got #6." <> pretty actual - AlternativeFail -> mempty + ArrayLeftoverTerms _ Nothing -> + annotate (color Red) "leftover elements not matched by any rule" + ArrayLeftoverTerms _ (Just (rule, trc)) -> + hang 2 $ + vsep + [ annotate (color Red) "leftover elements, closest matching rule:" + , annotate (color Green) $ pretty $ show rule + , nestContainer $ prettyStepTrace True opts trc + ] + ArrayLeftoverRule r -> + hang 2 $ + vsep + [ annotate (color Red) "required rule not satisfied:" + , pretty r + ] + ArrayElement _ steps -> vsep [prettyStepTrace True opts steps] + ArrayMissingRequired _ t -> + vsep + [ annotate (color Red) "failed to apply required rule:" + , nestContainer $ prettyStepTrace True opts t + ] + ArrayConsumeGroup refs x -> vsep $ prettyGroup refs x + MapLeftoverEntries _ Nothing -> + annotate (color Red) "leftover key-value pairs not matched by any rule" + MapLeftoverEntries _ (Just (rule, trc)) -> + hang 2 $ + vsep + [ annotate (color Red) "leftover key-value pairs, closest matching rule:" + , annotate (color Green) $ pretty rule + , nestContainer $ prettyStepTrace True opts trc + ] + MapUnappliedRules rs -> + hang 2 $ + vsep + [ annotate (color Red) "not all required rules have been applied:" + , vsep (NE.toList $ pretty <$> rs) + ] + MapEntry _ k v -> + vsep + [ "key:" + , nestContainer $ prettyStepTrace True opts k + , "value:" + , nestContainer $ prettyStepTrace True opts v + ] + MapInvalidValue _ k v -> + vsep + [ "key:" + , nestContainer $ prettyStepTrace False opts k + , "value:" <+> annotate (color Red) "(fail)" + , nestContainer $ prettyStepTrace True opts v + ] + MapDuplicateKeys _ _ trc -> + vsep + [ "key: " <> annotate (color Red) "(duplicate)" + , nestContainer $ prettyStepTrace False opts trc + ] + where + prettyGroup :: [Name] -> StepTrace ListBlock v -> [Doc AnsiStyle] + prettyGroup refs x = go refs + where + go (n : ns) = + [ "ref" <+> pretty n + , nestContainer . vsep $ go ns + ] + go [] = + [ case traceValidity x of + SValid -> "grp" + SInvalid -> "grp" <+> annotate (color Red) "(fail)" + , nestContainer $ prettyStepTrace True opts x + ] -showValidationTrace :: ValidationTrace v -> String +showValidationTrace :: ValidationTrace b v -> String showValidationTrace = T.unpack . Ansi.renderStrict From f29363582871ca9208a55fd992584a52ce021d83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Wed, 25 Nov 2026 14:01:07 +0200 Subject: [PATCH 22/37] All done except array and map validation --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 914 ++++++++---------- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 73 +- 2 files changed, 480 insertions(+), 507 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 24891cac..f18ea0cc 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -8,7 +8,6 @@ module Codec.CBOR.Cuddle.CBOR.Validator ( validateCBOR, validateFromName, validateFromGRef, - validateAgainst, validateTerm, ValidatorPhase, ValidateCBORError (..), @@ -20,33 +19,37 @@ import Codec.CBOR.Cuddle.CDDL.CTree import Codec.CBOR.Cuddle.CDDL.CtlOp import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( - ControlInfo (..), + Block (..), Evidenced (..), - ListValidationTrace (..), - MapValidationTrace (..), SValidity (..), + StepTrace, ValidateEnv (..), ValidationTrace (..), Validator, ValidatorPhase, XXCTree (..), + accept, compareEvidencedProgress, + controlVerdict, evidence, - isValid, + failWith, mapTrace, measureProgress, + pickBranch, + reject, runValidator, + withTag, ) -import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase, showSimple) +import Codec.CBOR.Cuddle.CDDL.Phase (showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Read import Codec.CBOR.Term -import Control.Monad.Reader (asks) import Data.Bifunctor (Bifunctor (..)) import Data.Bits hiding (And) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BSL -import Data.Function (on, (&)) +import Data.Foldable (Foldable (..), asum) +import Data.Function (on) import Data.IntSet qualified as IS import Data.List (maximumBy) import Data.List.NonEmpty (NonEmpty (..)) @@ -76,13 +79,13 @@ validateCBOR :: BS.ByteString -> Name -> CTreeRoot ValidatorPhase -> - Either ValidateCBORError (Evidenced ValidationTrace) + Either ValidateCBORError (Evidenced (StepTrace TermBlock)) validateCBOR bs ruleName cddl@(CTreeRoot tree) = case deserialiseFromBytes decodeTerm (BSL.fromStrict bs) of Left e -> Left $ DecodingFailed e Right (rest, term) | BSL.null rest -> case tree Map.!? ruleName of - Just rule -> Right $ validateTerm cddl term rule + Just rule -> Right $ runValidator (ValidateEnv cddl mempty) $ validateTerm term rule Nothing -> Left $ RuleDoesNotExist ruleName | otherwise -> Left $ LeftoverBytes rest @@ -94,7 +97,7 @@ validateFromName n term = do mRule <- lookupCddl n case mRule of Nothing -> fail $ "Unbound name: " <> show n - Just rule -> validateAgainst term rule + Just rule -> validateTerm term rule -- | Validate a CBOR 'Term' against the type bound to the given generic -- parameter at the enclosing rule. Use this from inside a custom validator @@ -105,15 +108,7 @@ validateFromGRef ref term = do mRule <- lookupGRef ref case mRule of Nothing -> fail $ "Unbound generic reference: " <> show ref - Just rule -> validateAgainst term rule - -validateAgainst :: Term -> CTree ValidatorPhase -> Validator () -validateAgainst term rule = do - cddl <- asks veRoot - let res = validateTerm cddl term rule - if isValid res - then pure () - else fail $ "Validation failed for term: " <> show term + Just rule -> validateTerm term rule -------------------------------------------------------------------------------- -- Terms @@ -121,39 +116,33 @@ validateAgainst term rule = do -- | Core function that validates a CBOR term to a particular rule of the CDDL -- spec validateTerm :: - CTreeRoot ValidatorPhase -> Term -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateTerm cddl term rule - | CTreeE (VRuleRef n) <- rule = - dereferenceAndValidate cddl n (validateTerm cddl term) - | CTreeE (VValidator v _) <- rule = - runValidator (v $ SingleTerm term) cddl + Validator () +validateTerm term rule + | CTreeE (VRuleRef n) <- rule = validateTerm term =<< dereference n + | CTreeE (VValidator validator _) <- rule = validator $ SingleTerm term | otherwise = case term of - TInt i -> validateInteger cddl (fromIntegral i) rule - TInteger i -> validateInteger cddl i rule - TBytes b -> validateBytes cddl b rule - TBytesI b -> validateBytes cddl (BSL.toStrict b) rule - TString s -> validateText cddl s rule - TStringI s -> validateText cddl (TL.toStrict s) rule - TList ts -> validateList cddl ts rule - TListI ts -> validateList cddl ts rule - TMap ts -> validateMap cddl ts rule - TMapI ts -> validateMap cddl ts rule - TTagged w t -> validateTagged cddl w t rule - TBool b -> validateBool cddl b rule - TNull -> validateNull cddl rule - TSimple s -> validateSimple cddl s rule - THalf h -> validateHalf cddl h rule - TFloat h -> validateFloat cddl h rule - TDouble d -> validateDouble cddl d rule - -terminal :: CTree ValidatorPhase -> Evidenced ValidationTrace -terminal = evidence . TerminalRule . mapIndex - -unapplicable :: CTree ValidatorPhase -> Evidenced ValidationTrace + TInt i -> validateInteger (fromIntegral i) rule + TInteger i -> validateInteger i rule + TBytes b -> validateBytes b rule + TBytesI b -> validateBytes (BSL.toStrict b) rule + TString s -> validateText s rule + TStringI s -> validateText (TL.toStrict s) rule + TList ts -> validateList ts rule + TListI ts -> validateList ts rule + TMap ts -> validateMap ts rule + TMapI ts -> validateMap ts rule + TTagged w t -> validateTagged w t rule + TBool b -> validateBool b rule + TNull -> validateNull rule + TSimple s -> validateSimple s rule + THalf h -> validateHalf h rule + TFloat h -> validateFloat h rule + TDouble d -> validateDouble d rule + +unapplicable :: CTree ValidatorPhase -> Evidenced (ValidationTrace TermBlock) unapplicable = evidence . UnapplicableRule . mapIndex -------------------------------------------------------------------------------- @@ -172,14 +161,13 @@ unapplicable = evidence . UnapplicableRule . mapIndex -- Ints, so we convert everything to Integer. validateInteger :: HasCallStack => - CTreeRoot ValidatorPhase -> Integer -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateInteger cddl i rule = + Validator () +validateInteger i rule = case rule of - CTreeE (VRuleRef n) -> dereferenceAndValidate cddl n $ validateInteger cddl i - CTreeE (VValidator v _) -> runValidator (v $ SingleTerm $ TInteger i) cddl + CTreeE (VRuleRef n) -> validateInteger i =<< dereference n + CTreeE (VValidator validator _) -> validator $ SingleTerm $ TInteger i -- echo "C24101" | xxd -r -p - example.cbor -- echo "foo = int" > a.cddl -- cddl a.cddl validate example.cbor @@ -193,147 +181,142 @@ validateInteger cddl i rule = -- and they are both bigints? -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = int Postlude PTInt - | i >= nintMin && i <= uintMax -> terminal rule + | i >= nintMin && i <= uintMax -> accept rule -- a = uint Postlude PTUInt - | i >= 0 && i <= uintMax -> terminal rule + | i >= 0 && i <= uintMax -> accept rule -- a = nint Postlude PTNInt - | i >= nintMin && i <= -1 -> terminal rule + | i >= nintMin && i <= -1 -> accept rule -- a = x - Literal (Value (VUInt i') _) | i == fromIntegral i' -> terminal rule + Literal (Value (VUInt i') _) | i == fromIntegral i' -> accept rule -- a = -x - Literal (Value (VNInt i') _) | -i == fromIntegral i' -> terminal rule + Literal (Value (VNInt i') _) | -i == fromIntegral i' -> accept rule -- a = - Literal (Value (VBignum i') _) | i == i' -> terminal rule + Literal (Value (VBignum i') _) | i == i' -> accept rule -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateInteger cddl i) op tgt ctrl (controlInteger cddl i) + Control op tgt ctrl -> validateInteger i tgt >> controlInteger i op ctrl -- a = foo / bar - Choice opts -> validateChoice (validateInteger cddl i) opts + Choice opts -> validateChoice (validateInteger i) opts -- a = x..y Range low high bound -> case (low, high) of (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | n <= i && range bound i m -> terminal rule - | otherwise -> unapplicable rule + | n <= i && range bound i m -> accept rule + | otherwise -> reject rule (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | -n <= i && range bound i m -> terminal rule - | otherwise -> unapplicable rule + | -n <= i && range bound i m -> accept rule + | otherwise -> reject rule (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) - | -n <= i && range bound i (-m) -> terminal rule - | otherwise -> unapplicable rule + | -n <= i && range bound i (-m) -> accept rule + | otherwise -> reject rule (Literal (Value VUInt {} _), Literal (Value VNInt {} _)) -> error "range types mismatch" (Literal (Value (VBignum n) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | n <= i && range bound i m -> terminal rule - | otherwise -> unapplicable rule + | n <= i && range bound i m -> accept rule + | otherwise -> reject rule (Literal (Value (VBignum n) _), Literal (Value (VNInt (fromIntegral -> m)) _)) - | n <= i && range bound i (-m) -> terminal rule - | otherwise -> unapplicable rule + | n <= i && range bound i (-m) -> accept rule + | otherwise -> reject rule (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VBignum m) _)) - | n <= i && range bound i m -> terminal rule - | otherwise -> unapplicable rule + | n <= i && range bound i m -> accept rule + | otherwise -> reject rule (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VBignum m) _)) - | (-n) <= i && range bound i m -> terminal rule - | otherwise -> unapplicable rule - (CTreeE (VRuleRef n), _) -> - dereferenceAndValidate cddl n $ \lo -> validateInteger cddl i (Range lo high bound) - (_, CTreeE (VRuleRef n)) -> - dereferenceAndValidate cddl n $ \hi -> validateInteger cddl i (Range low hi bound) + | (-n) <= i && range bound i m -> accept rule + | otherwise -> reject rule + (CTreeE (VRuleRef n), _) -> do + lo <- dereference n + validateInteger i (Range lo high bound) + (_, CTreeE (VRuleRef n)) -> do + hi <- dereference n + validateInteger i (Range low hi bound) (lo, hi) -> error $ "Unable to validate range: (" <> showSimple lo <> ", " <> showSimple hi <> ")" -- a = &(x, y, z) Enum g -> case g of - CTreeE (VRuleRef n) -> dereferenceAndValidate cddl n $ validateInteger cddl i - Group g' -> validateInteger cddl i (Choice (NE.fromList g')) + CTreeE (VRuleRef n) -> validateInteger i =<< dereference n + Group g' -> validateInteger i (Choice (NE.fromList g')) _ -> error "Not yet implemented" -- a = x: y -- Note KV cannot appear on its own, but we will use this when validating -- lists. - KV _ v _ -> validateInteger cddl i v + KV _ v _ -> validateInteger i v Tag 2 x -> validateBigInt x Tag 3 x -> validateBigInt x - _ -> unapplicable rule + _ -> reject rule where validateBigInt x = case x of - CTreeE (VRuleRef n) -> dereferenceAndValidate cddl n validateBigInt - Postlude PTBytes -> terminal rule + CTreeE (VRuleRef n) -> validateBigInt =<< dereference n + Postlude PTBytes -> accept rule Control op tgt@(Postlude PTBytes) ctrl -> - ctrlDispatch (validateBytes cddl bs) op tgt ctrl (controlBytes cddl bs) + validateBytes bs tgt >> controlBytes bs op ctrl where -- TODO figure out a way to turn Integer into bytes or figure out why -- tagged bigints are decoded as integers in the first place bs = mempty - _ -> unapplicable rule + _ -> reject rule -- | Controls for an Integer controlInteger :: HasCallStack => - CTreeRoot ValidatorPhase -> Integer -> CtlOp -> CTree ValidatorPhase -> - Bool -controlInteger cddl i op (CTreeE (VRuleRef n)) = - controlInteger cddl i op $ dereference cddl n -controlInteger _ i Size ctrl = - case ctrl of - Literal (Value (VUInt sz) _) -> 0 <= i && i < 256 ^ sz - _ -> False -controlInteger cddl i Bits ctrl = do - let - indices = case ctrl of - Literal (Value (VUInt i') _) -> [i'] - Choice nodes -> getIndicesOfChoice cddl nodes - Range ff tt incl -> getIndicesOfRange cddl ff tt incl - Enum g -> getIndicesOfEnum cddl g + Validator () +controlInteger i op (CTreeE (VRuleRef n)) = controlInteger i op =<< dereference n +controlInteger i op ctrl = case op of + Size -> case ctrl of + Literal (Value (VUInt sz) _) -> verdict $ 0 <= i && i < 256 ^ sz + _ -> verdict False + Bits -> do + indices <- case ctrl of + Literal (Value (VUInt i') _) -> pure [i'] + Choice nodes -> getIndicesOfChoice nodes + Range ff tt incl -> getIndicesOfRange ff tt incl + Enum g -> getIndicesOfEnum g _ -> error "Not yet implemented" - go (IS.fromList (map fromIntegral indices)) i 0 + verdict $ go (IS.fromList (map fromIntegral indices)) i 0 + where + go _ 0 _ = True + go indices n idx = + let bitSet = testBit n 0 + allowed = not bitSet || IS.member idx indices + in allowed && go indices (shiftR n 1) (idx + 1) + Lt -> case ctrl of + Literal (Value (VUInt i') _) -> verdict $ i < fromIntegral i' + Literal (Value (VNInt i') _) -> verdict $ i < -fromIntegral i' + Literal (Value (VBignum i') _) -> verdict $ i < i' + _ -> verdict False + Gt -> case ctrl of + Literal (Value (VUInt i') _) -> verdict $ i > fromIntegral i' + Literal (Value (VNInt i') _) -> verdict $ i > -fromIntegral i' + Literal (Value (VBignum i') _) -> verdict $ i > i' + _ -> verdict False + Le -> case ctrl of + Literal (Value (VUInt i') _) -> verdict $ i <= fromIntegral i' + Literal (Value (VNInt i') _) -> verdict $ i <= -fromIntegral i' + Literal (Value (VBignum i') _) -> verdict $ i <= i' + _ -> verdict False + Ge -> case ctrl of + Literal (Value (VUInt i') _) -> verdict $ i >= fromIntegral i' + Literal (Value (VNInt i') _) -> verdict $ i >= -fromIntegral i' + Literal (Value (VBignum i') _) -> verdict $ i >= i' + _ -> verdict False + Eq -> case ctrl of + Literal (Value (VUInt i') _) -> verdict $ i == fromIntegral i' + Literal (Value (VNInt i') _) -> verdict $ i == -fromIntegral i' + Literal (Value (VBignum i') _) -> verdict $ i == i' + _ -> verdict False + Ne -> case ctrl of + Literal (Value (VUInt i') _) -> verdict $ i /= fromIntegral i' + Literal (Value (VNInt i') _) -> verdict $ i /= -fromIntegral i' + Literal (Value (VBignum i') _) -> verdict $ i /= i' + _ -> verdict False + _ -> error $ "unexpected control: " <> showSimple ctrl where - go _ 0 _ = True - go indices n idx = - let bitSet = testBit n 0 - allowed = not bitSet || IS.member idx indices - in allowed && go indices (shiftR n 1) (idx + 1) -controlInteger _ i Lt ctrl = - case ctrl of - Literal (Value (VUInt i') _) -> i < fromIntegral i' - Literal (Value (VNInt i') _) -> i < -fromIntegral i' - Literal (Value (VBignum i') _) -> i < i' - _ -> False -controlInteger _ i Gt ctrl = - case ctrl of - Literal (Value (VUInt i') _) -> i > fromIntegral i' - Literal (Value (VNInt i') _) -> i > -fromIntegral i' - Literal (Value (VBignum i') _) -> i > i' - _ -> False -controlInteger _ i Le ctrl = - case ctrl of - Literal (Value (VUInt i') _) -> i <= fromIntegral i' - Literal (Value (VNInt i') _) -> i <= -fromIntegral i' - Literal (Value (VBignum i') _) -> i <= i' - _ -> False -controlInteger _ i Ge ctrl = - case ctrl of - Literal (Value (VUInt i') _) -> i >= fromIntegral i' - Literal (Value (VNInt i') _) -> i >= -fromIntegral i' - Literal (Value (VBignum i') _) -> i >= i' - _ -> False -controlInteger _ i Eq ctrl = - case ctrl of - Literal (Value (VUInt i') _) -> i == fromIntegral i' - Literal (Value (VNInt i') _) -> i == -fromIntegral i' - Literal (Value (VBignum i') _) -> i == i' - _ -> False -controlInteger _ i Ne ctrl = - case ctrl of - Literal (Value (VUInt i') _) -> i /= fromIntegral i' - Literal (Value (VNInt i') _) -> i /= -fromIntegral i' - Literal (Value (VBignum i') _) -> i /= i' - _ -> False -controlInteger _ _ _ ctrl = error $ "unexpected control: " <> showSimple ctrl + verdict = controlVerdict op ctrl -------------------------------------------------------------------------------- -- Floating point (Float16, Float32, Float64) @@ -344,334 +327,330 @@ controlInteger _ _ _ ctrl = error $ "unexpected control: " <> showSimple ctrl -- | Validating a `Float16` validateHalf :: HasCallStack => - CTreeRoot ValidatorPhase -> Float -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateHalf cddl f (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateHalf cddl f -validateHalf cddl f (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ THalf f) cddl -validateHalf cddl f rule = + Validator () +validateHalf f (CTreeE (VRuleRef n)) = validateHalf f =<< dereference n +validateHalf f (CTreeE (VValidator v _)) = v $ SingleTerm $ THalf f +validateHalf f rule = case rule of -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = float16 - Postlude PTHalf -> terminal rule + Postlude PTHalf -> accept rule -- a = 0.5 - Literal (Value (VFloat16 f') _) | f == f' -> terminal rule + Literal (Value (VFloat16 f') _) | f == f' -> accept rule -- a = foo / bar - Choice opts -> validateChoice (validateHalf cddl f) opts + Choice opts -> validateChoice (validateHalf f) opts -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateHalf cddl f) op tgt ctrl (controlHalf cddl f) + Control op tgt ctrl -> validateHalf f tgt >> controlHalf f op ctrl -- a = x..y - Range (CTreeE (VRuleRef n)) high bound -> - dereferenceAndValidate cddl n $ \lo -> validateHalf cddl f $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> - dereferenceAndValidate cddl n $ \hi -> validateHalf cddl f $ Range low hi bound + Range (CTreeE (VRuleRef n)) high bound -> do + lo <- dereference n + validateHalf f $ Range lo high bound + Range low (CTreeE (VRuleRef n)) bound -> do + hi <- dereference n + validateHalf f $ Range low hi bound Range (Literal (Value (VFloat16 n) _)) (Literal (Value (VFloat16 m) _)) bound - | n <= f && range bound f m -> terminal rule - _ -> unapplicable rule + | n <= f && range bound f m -> accept rule + _ -> reject rule -- | Controls for `Float16` controlHalf :: HasCallStack => - CTreeRoot ValidatorPhase -> Float -> CtlOp -> CTree ValidatorPhase -> - Bool -controlHalf cddl f op (CTreeE (VRuleRef n)) = - controlHalf cddl f op $ dereference cddl n -controlHalf _ f Eq ctrl = - case ctrl of - Literal (Value (VFloat16 f') _) -> f == f' - _ -> False -controlHalf _ f Ne ctrl = - case ctrl of - Literal (Value (VFloat16 f') _) -> f /= f' - _ -> False -controlHalf _ _ op _ = error $ "Not yet implemented for half: " <> show op + Validator () +controlHalf f op (CTreeE (VRuleRef n)) = + controlHalf f op =<< dereference n +controlHalf f op ctrl = case op of + Eq -> case ctrl of + Literal (Value (VFloat16 f') _) -> verdict $ f == f' + _ -> verdict False + Ne -> case ctrl of + Literal (Value (VFloat16 f') _) -> verdict $ f /= f' + _ -> verdict False + _ -> error $ "Not yet implemented for half: " <> show op + where + verdict = controlVerdict op ctrl -- | Validating a `Float32` validateFloat :: HasCallStack => - CTreeRoot ValidatorPhase -> Float -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateFloat cddl f (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateFloat cddl f -validateFloat cddl f (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TFloat f) cddl -validateFloat cddl f rule = + Validator () +validateFloat f (CTreeE (VRuleRef n)) = + validateFloat f =<< dereference n +validateFloat f (CTreeE (VValidator v _)) = v $ SingleTerm $ TFloat f +validateFloat f rule = case rule of -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = float32 - Postlude PTFloat -> terminal rule + Postlude PTFloat -> accept rule -- a = 0.000000005 -- TODO: it is unclear if smaller floats should also validate - Literal (Value (VFloat32 f') _) | f == f' -> terminal rule + Literal (Value (VFloat32 f') _) | f == f' -> accept rule -- a = foo / bar - Choice opts -> validateChoice (validateFloat cddl f) opts + Choice opts -> validateChoice (validateFloat f) opts -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateFloat cddl f) op tgt ctrl (controlFloat cddl f) + Control op tgt ctrl -> validateFloat f tgt >> controlFloat f op ctrl -- a = x..y -- TODO it is unclear if this should mix floating point types too - Range (CTreeE (VRuleRef n)) high bound -> - dereferenceAndValidate cddl n $ \lo -> validateFloat cddl f $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> - dereferenceAndValidate cddl n $ \hi -> validateFloat cddl f $ Range low hi bound + Range (CTreeE (VRuleRef n)) high bound -> do + lo <- dereference n + validateFloat f $ Range lo high bound + Range low (CTreeE (VRuleRef n)) bound -> do + hi <- dereference n + validateFloat f $ Range low hi bound Range (Literal (Value nv _)) (Literal (Value mv _)) bound | VFloat16 n <- nv , VFloat16 m <- mv , n <= f && range bound f m -> - terminal rule + accept rule | VFloat32 n <- nv , VFloat32 m <- mv , n <= f && range bound f m -> - terminal rule - _ -> unapplicable rule + accept rule + _ -> reject rule -- | Controls for `Float32` controlFloat :: HasCallStack => - CTreeRoot ValidatorPhase -> Float -> CtlOp -> CTree ValidatorPhase -> - Bool -controlFloat cddl f op (CTreeE (VRuleRef n)) = - controlFloat cddl f op $ dereference cddl n -controlFloat _ f Eq ctrl = - case ctrl of - Literal (Value (VFloat16 f') _) -> f == f' - Literal (Value (VFloat32 f') _) -> f == f' - _ -> False -controlFloat _ f Ne ctrl = - case ctrl of - Literal (Value (VFloat16 f') _) -> f /= f' - Literal (Value (VFloat32 f') _) -> f /= f' - _ -> False -controlFloat _ _ op _ = error $ "Not yet implemented for float: " <> show op + Validator () +controlFloat f op (CTreeE (VRuleRef n)) = controlFloat f op =<< dereference n +controlFloat f op ctrl = case op of + Eq -> case ctrl of + Literal (Value (VFloat16 f') _) -> verdict $ f == f' + Literal (Value (VFloat32 f') _) -> verdict $ f == f' + _ -> verdict False + Ne -> case ctrl of + Literal (Value (VFloat16 f') _) -> verdict $ f /= f' + Literal (Value (VFloat32 f') _) -> verdict $ f /= f' + _ -> verdict False + _ -> error $ "Not yet implemented for float: " <> show op + where + verdict = controlVerdict op ctrl -- | Validating a `Float64` validateDouble :: HasCallStack => - CTreeRoot ValidatorPhase -> Double -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateDouble cddl f (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateDouble cddl f -validateDouble cddl f (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TDouble f) cddl -validateDouble cddl f rule = + Validator () +validateDouble f (CTreeE (VRuleRef n)) = validateDouble f =<< dereference n +validateDouble f (CTreeE (VValidator v _)) = v $ SingleTerm $ TDouble f +validateDouble f rule = case rule of -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = float64 - Postlude PTDouble -> terminal rule + Postlude PTDouble -> accept rule -- a = 0.0000000000000000000000000000000000000000000005 -- TODO: it is unclear if smaller floats should also validate - Literal (Value (VFloat64 f') _) | f == f' -> terminal rule + Literal (Value (VFloat64 f') _) | f == f' -> accept rule -- a = foo / bar - Choice opts -> validateChoice (validateDouble cddl f) opts + Choice opts -> validateChoice (validateDouble f) opts -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateDouble cddl f) op tgt ctrl (controlDouble cddl f) + Control op tgt ctrl -> validateDouble f tgt >> controlDouble f op ctrl -- a = x..y -- TODO it is unclear if this should mix floating point types too - Range (CTreeE (VRuleRef n)) high bound -> - dereferenceAndValidate cddl n $ \lo -> validateDouble cddl f $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> - dereferenceAndValidate cddl n $ \hi -> validateDouble cddl f $ Range low hi bound + Range (CTreeE (VRuleRef n)) high bound -> do + lo <- dereference n + validateDouble f $ Range lo high bound + Range low (CTreeE (VRuleRef n)) bound -> do + hi <- dereference n + validateDouble f $ Range low hi bound Range (Literal (Value nv _)) (Literal (Value mv _)) bound | VFloat16 n <- nv , VFloat16 m <- mv , float2Double n <= f && range bound f (float2Double m) -> - terminal rule + accept rule | VFloat32 n <- nv , VFloat32 m <- mv , float2Double n <= f && range bound f (float2Double m) -> - terminal rule + accept rule | VFloat64 n <- nv , VFloat64 m <- mv , n <= f && range bound f m -> - terminal rule - _ -> unapplicable rule + accept rule + _ -> reject rule -- | Controls for `Float64` controlDouble :: HasCallStack => - CTreeRoot ValidatorPhase -> Double -> CtlOp -> CTree ValidatorPhase -> - Bool -controlDouble cddl f op (CTreeE (VRuleRef n)) = - controlDouble cddl f op $ dereference cddl n -controlDouble _ f Eq ctrl = - case ctrl of - Literal (Value (VFloat16 f') _) -> f == float2Double f' - Literal (Value (VFloat32 f') _) -> f == float2Double f' - Literal (Value (VFloat64 f') _) -> f == f' - _ -> False -controlDouble _ f Ne ctrl = - case ctrl of - Literal (Value (VFloat16 f') _) -> f /= float2Double f' - Literal (Value (VFloat32 f') _) -> f /= float2Double f' - Literal (Value (VFloat64 f') _) -> f /= f' - _ -> False -controlDouble _ _ op _ = error $ "Not yet implmented for double: " <> show op + Validator () +controlDouble f op (CTreeE (VRuleRef n)) = controlDouble f op =<< dereference n +controlDouble f op ctrl = case op of + Eq -> case ctrl of + Literal (Value (VFloat16 f') _) -> verdict $ f == float2Double f' + Literal (Value (VFloat32 f') _) -> verdict $ f == float2Double f' + Literal (Value (VFloat64 f') _) -> verdict $ f == f' + _ -> verdict False + Ne -> case ctrl of + Literal (Value (VFloat16 f') _) -> verdict $ f /= float2Double f' + Literal (Value (VFloat32 f') _) -> verdict $ f /= float2Double f' + Literal (Value (VFloat64 f') _) -> verdict $ f /= f' + _ -> verdict False + _ -> error $ "Not yet implmented for double: " <> show op + where + verdict = controlVerdict op ctrl -------------------------------------------------------------------------------- -- Bool -- | Validating a boolean validateBool :: - CTreeRoot ValidatorPhase -> Bool -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateBool cddl b (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateBool cddl b -validateBool cddl b (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TBool b) cddl -validateBool cddl b rule = + Validator () +validateBool b (CTreeE (VRuleRef n)) = validateBool b =<< dereference n +validateBool b (CTreeE (VValidator v _)) = v $ SingleTerm $ TBool b +validateBool b rule = case rule of -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = bool - Postlude PTBool -> terminal rule + Postlude PTBool -> accept rule -- a = true - Literal (Value (VBool b') _) | b == b' -> terminal rule + Literal (Value (VBool b') _) | b == b' -> accept rule -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateBool cddl b) op tgt ctrl (controlBool cddl b) + Control op tgt ctrl -> validateBool b tgt >> controlBool b op ctrl -- a = foo / bar - Choice opts -> validateChoice (validateBool cddl b) opts - _ -> unapplicable rule + Choice opts -> validateChoice (validateBool b) opts + _ -> reject rule -- | Controls for `Bool` controlBool :: HasCallStack => - CTreeRoot ValidatorPhase -> Bool -> CtlOp -> CTree ValidatorPhase -> - Bool -controlBool cddl b op (CTreeE (VRuleRef n)) = - controlBool cddl b op $ dereference cddl n -controlBool _ b Eq ctrl = - case ctrl of - Literal (Value (VBool b') _) -> b == b' - _ -> False -controlBool _ b Ne ctrl = - case ctrl of - Literal (Value (VBool b') _) -> b /= b' - _ -> False -controlBool _ _ op _ = error $ "Not yet implemented for bool: " <> show op + Validator () +controlBool b op (CTreeE (VRuleRef n)) = controlBool b op =<< dereference n +controlBool b op ctrl = case op of + Eq -> case ctrl of + Literal (Value (VBool b') _) -> verdict $ b == b' + _ -> verdict False + Ne -> case ctrl of + Literal (Value (VBool b') _) -> verdict $ b /= b' + _ -> verdict False + _ -> error $ "Not yet implemented for bool: " <> show op + where + verdict = controlVerdict op ctrl -------------------------------------------------------------------------------- -- Simple -- | Validating a `TSimple`. It is unclear if this is used for anything else than `undefined`. validateSimple :: - CTreeRoot ValidatorPhase -> Word8 -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateSimple cddl i (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateSimple cddl i -validateSimple cddl i (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TSimple i) cddl -validateSimple cddl 23 rule = + Validator () +validateSimple i (CTreeE (VRuleRef n)) = validateSimple i =<< dereference n +validateSimple i (CTreeE (VValidator v _)) = v $ SingleTerm $ TSimple i +validateSimple 23 rule = case rule of -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = undefined - Postlude PTUndefined -> terminal rule + Postlude PTUndefined -> accept rule -- a = foo / bar - Choice opts -> validateChoice (validateSimple cddl 23) opts - _ -> unapplicable rule -validateSimple _ n _ = error $ "Found simple different to 23! please report this somewhere! Found: " <> show n + Choice opts -> validateChoice (validateSimple 23) opts + _ -> reject rule +validateSimple n _ = error $ "Found simple different to 23! please report this somewhere! Found: " <> show n -------------------------------------------------------------------------------- -- Null/nil -- | Validating nil -validateNull :: CTreeRoot ValidatorPhase -> CTree ValidatorPhase -> Evidenced ValidationTrace -validateNull cddl (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateNull cddl -validateNull cddl (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm TNull) cddl -validateNull cddl rule = +validateNull :: + CTree ValidatorPhase -> Validator () +validateNull (CTreeE (VRuleRef n)) = validateNull =<< dereference n +validateNull (CTreeE (VValidator v _)) = v $ SingleTerm TNull +validateNull rule = case rule of -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = nil - Postlude PTNil -> terminal rule - Choice opts -> validateChoice (validateNull cddl) opts - _ -> unapplicable rule + Postlude PTNil -> accept rule + Choice opts -> validateChoice validateNull opts + _ -> reject rule -------------------------------------------------------------------------------- -- Bytes -- | Validating a byte sequence validateBytes :: - CTreeRoot ValidatorPhase -> BS.ByteString -> CTree ValidatorPhase -> Evidenced ValidationTrace -validateBytes cddl bs (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateBytes cddl bs -validateBytes cddl bs (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TBytes bs) cddl -validateBytes cddl bs rule = + BS.ByteString -> + CTree ValidatorPhase -> + Validator () +validateBytes bs (CTreeE (VRuleRef n)) = validateBytes bs =<< dereference n +validateBytes bs (CTreeE (VValidator v _)) = v $ SingleTerm $ TBytes bs +validateBytes bs rule = case rule of -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = bytes - Postlude PTBytes -> terminal rule + Postlude PTBytes -> accept rule -- a = h'123456' - Literal (Value (VBytes bs') _) | bs == bs' -> terminal rule + Literal (Value (VBytes bs') _) | bs == bs' -> accept rule -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateBytes cddl bs) op tgt ctrl (controlBytes cddl bs) + Control op tgt ctrl -> validateBytes bs tgt >> controlBytes bs op ctrl -- a = foo / bar - Choice opts -> validateChoice (validateBytes cddl bs) opts - _ -> unapplicable rule + Choice opts -> validateChoice (validateBytes bs) opts + _ -> reject rule -- | Controls for byte strings controlBytes :: HasCallStack => - CTreeRoot ValidatorPhase -> BS.ByteString -> CtlOp -> CTree ValidatorPhase -> - Bool -controlBytes cddl bs op (CTreeE (VRuleRef n)) = - controlBytes cddl bs op $ dereference cddl n -controlBytes cddl bs op@Size ctrl = - case ctrl of - Literal (Value (VUInt sz) _) -> fromIntegral (BS.length bs) == sz - Range (CTreeE (VRuleRef n)) high bound -> - dereference cddl n & \lo -> controlBytes cddl bs op $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> - dereference cddl n & \hi -> controlBytes cddl bs op $ Range low hi bound + Validator () +controlBytes bs op (CTreeE (VRuleRef n)) = controlBytes bs op =<< dereference n +controlBytes bs op ctrl = case op of + Size -> case ctrl of + Literal (Value (VUInt sz) _) | fromIntegral (BS.length bs) == sz -> verdict True + Range (CTreeE (VRuleRef n)) high bound -> do + lo <- dereference n + controlBytes bs op $ Range lo high bound + Range low (CTreeE (VRuleRef n)) bound -> do + hi <- dereference n + controlBytes bs op $ Range low hi bound Range low high bound -> let i = BS.length bs in case (low, high) of - (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> - boundPlacement i (Just n, Just m) bound == WithinBounds - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> - boundPlacement i (Just $ -n, Just m) bound == WithinBounds - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) -> - boundPlacement i (Just $ -n, Just $ -m) bound == WithinBounds - _ -> False - _ -> False -controlBytes cddl bs Bits ctrl = do - let - indices = + (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) + | boundPlacement i (Just n, Just m) bound == WithinBounds -> verdict True + (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) + | boundPlacement i (Just $ -n, Just m) bound == WithinBounds -> verdict True + (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) + | boundPlacement i (Just $ -n, Just $ -m) bound == WithinBounds -> verdict True + _ -> verdict False + _ -> verdict False + Bits -> do + indices <- case ctrl of - Literal (Value (VUInt i') _) -> [i'] - Choice nodes -> getIndicesOfChoice cddl nodes - Range ff tt incl -> getIndicesOfRange cddl ff tt incl - Enum g -> getIndicesOfEnum cddl g + Literal (Value (VUInt i') _) -> pure [i'] + Choice nodes -> getIndicesOfChoice nodes + Range ff tt incl -> getIndicesOfRange ff tt incl + Enum g -> getIndicesOfEnum g _ -> error "Not yet implemented" - bitsControlCheck (map fromIntegral indices) - where - bitsControlCheck :: [Int] -> Bool - bitsControlCheck allowedBits = - let allowedSet = IS.fromList allowedBits + bitsControlCheck (map fromIntegral indices) + where + bitsControlCheck :: [Int] -> Validator () + bitsControlCheck allowedBits = verdict $ all isAllowedBit [0 .. totalBits - 1] + where + allowedSet = IS.fromList allowedBits totalBits = BS.length bs * 8 isAllowedBit n = let byteIndex = n `shiftR` 3 @@ -679,98 +658,100 @@ controlBytes cddl bs Bits ctrl = do in case BS.indexMaybe bs byteIndex of Just byte -> not (testBit byte bitIndex) || IS.member n allowedSet Nothing -> True - in all isAllowedBit [0 .. totalBits - 1] -controlBytes cddl bs Cbor ctrl = - case deserialiseFromBytes decodeTerm (BSL.fromStrict bs) of - Right (BSL.null -> True, term) -> isValid $ validateTerm cddl term ctrl - _ -> False -controlBytes cddl bs Cborseq ctrl = - case deserialiseFromBytes decodeTerm (BSL.fromStrict (BS.snoc (BS.cons 0x9f bs) 0xff)) of - Right (BSL.null -> True, TListI terms) -> isValid $ validateTerm cddl (TList terms) (Array [Occur ctrl OIZeroOrMore]) - _ -> False -controlBytes _ _ op _ = error $ "Not yet implmented for bytes: " <> show op + Cbor -> case deserialiseFromBytes decodeTerm (BSL.fromStrict bs) of + Right (BSL.null -> True, term) -> validateTerm term ctrl + _ -> verdict False + Cborseq -> case deserialiseFromBytes decodeTerm (BSL.fromStrict (BS.snoc (BS.cons 0x9f bs) 0xff)) of + Right (BSL.null -> True, TListI terms) -> validateTerm (TList terms) (Array [Occur ctrl OIZeroOrMore]) + _ -> verdict False + _ -> error $ "Not yet implmented for bytes: " <> show op + where + verdict = controlVerdict op ctrl -------------------------------------------------------------------------------- -- Text -- | Validating text strings validateText :: - CTreeRoot ValidatorPhase -> T.Text -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateText cddl txt (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateText cddl txt -validateText cddl txt (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TString txt) cddl -validateText cddl txt rule = + Validator () +validateText txt (CTreeE (VRuleRef n)) = validateText txt =<< dereference n +validateText txt (CTreeE (VValidator v _)) = v $ SingleTerm $ TString txt +validateText txt rule = case rule of -- a = any - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule -- a = text - Postlude PTText -> terminal rule + Postlude PTText -> accept rule -- a = "foo" - Literal (Value (VText txt') _) | txt == txt' -> terminal rule + Literal (Value (VText txt') _) | txt == txt' -> accept rule -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateText cddl txt) op tgt ctrl (controlText cddl txt) + Control op tgt ctrl -> validateText txt tgt >> controlText txt op ctrl -- a = foo / bar - Choice opts -> validateChoice (validateText cddl txt) opts - _ -> unapplicable rule + Choice opts -> validateChoice (validateText txt) opts + _ -> reject rule -- | Controls for text strings controlText :: HasCallStack => - CTreeRoot ValidatorPhase -> T.Text -> CtlOp -> CTree ValidatorPhase -> - Bool -controlText cddl bs op (CTreeE (VRuleRef n)) = - controlText cddl bs op $ dereference cddl n -controlText cddl bs op@Size ctrl = - let bsSize = BS.length $ encodeUtf8 bs - in case ctrl of - Literal (Value (VUInt (fromIntegral -> sz)) _) -> bsSize == sz - Range (CTreeE (VRuleRef n)) high bound -> - dereference cddl n & \lo -> controlText cddl bs op $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> - dereference cddl n & \hi -> controlText cddl bs op $ Range low hi bound - Range ff tt bound -> - case (ff, tt) of - (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> - n <= T.length bs && range bound bsSize m - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> - -n <= T.length bs && range bound bsSize m - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) -> - -n <= T.length bs && range bound bsSize (-m) - _ -> False - _ -> error "Invalid control value in .size" -controlText _ s Regexp ctrl = - case ctrl of - Literal (Value (VText rxp) _) -> case s =~ rxp :: (T.Text, T.Text, T.Text) of - ("", s', "") -> s == s' - _ -> False + Validator () +controlText bs op (CTreeE (VRuleRef n)) = controlText bs op =<< dereference n +controlText bs op ctrl = case op of + Size -> + let bsSize = BS.length $ encodeUtf8 bs + in case ctrl of + Literal (Value (VUInt (fromIntegral -> sz)) _) -> verdict $ bsSize == sz + Range (CTreeE (VRuleRef n)) high bound -> do + lo <- dereference n + controlText bs op $ Range lo high bound + Range low (CTreeE (VRuleRef n)) bound -> do + hi <- dereference n + controlText bs op $ Range low hi bound + Range ff tt bound -> + case (ff, tt) of + (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> + verdict $ n <= T.length bs && range bound bsSize m + (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> + verdict $ -n <= T.length bs && range bound bsSize m + (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) -> + verdict $ -n <= T.length bs && range bound bsSize (-m) + _ -> verdict False + _ -> error "Invalid control value in .size" + Regexp -> case ctrl of + Literal (Value (VText rxp) _) -> case bs =~ rxp :: (T.Text, T.Text, T.Text) of + ("", bs', "") -> verdict $ bs == bs' + _ -> verdict False _ -> error "Invalid control value in .regexp" -controlText _ _ op _ = error $ "Not yet implemented for text: " <> show op + _ -> error $ "Not yet implemented for text: " <> show op + where + verdict = controlVerdict op ctrl -------------------------------------------------------------------------------- -- Tagged values -- | Validating a `TTagged` validateTagged :: - CTreeRoot ValidatorPhase -> Word64 -> Term -> CTree ValidatorPhase -> Evidenced ValidationTrace -validateTagged cddl tag term (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateTagged cddl tag term -validateTagged cddl tag term (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TTagged tag term) cddl -validateTagged cddl tag term rule = + Word64 -> + Term -> + CTree ValidatorPhase -> + Validator () +validateTagged tag term (CTreeE (VRuleRef n)) = + validateTagged tag term =<< dereference n +validateTagged tag term (CTreeE (VValidator v _)) = v $ SingleTerm $ TTagged tag term +validateTagged tag term rule = case rule of - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule Tag tag' rule' -> -- If the tag does not match, this is a direct fail if tag == tag' - then mapTrace (TagTrace tag) $ validateTerm cddl term rule' - else evidence $ InvalidTag tag' tag - Choice opts -> validateChoice (validateTagged cddl tag term) opts - _ -> unapplicable rule + then withTag tag $ validateTerm term rule' + else failWith $ InvalidTag tag' tag + Choice opts -> validateChoice (validateTagged tag term) opts + _ -> reject rule -- -------------------------------------------------------------------------------- -- -- Lists @@ -808,16 +789,14 @@ decrementBounds (lb, ub) = OIBounded (clampedPred <$> lb) (clampedPred <$> ub) clampedPred x = pred x validateList :: - CTreeRoot ValidatorPhase -> [Term] -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateList cddl terms (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateList cddl terms -validateList cddl terms (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TList terms) cddl -validateList cddl terms rule = + Validator () +validateList terms (CTreeE (VRuleRef n)) = validateList terms =<< dereference n +validateList terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TList terms +validateList terms rule = case rule of - Postlude PTAny -> terminal rule + Postlude PTAny -> accept rule Array rules -> mapTrace ListTrace . fst $ validate finalize [] terms rules where finalize _ [] = evidence ListValidationDone @@ -836,14 +815,14 @@ validateList cddl terms rule = _ -> Just $ maximumBy (compare `on` (measureProgress . snd)) attempts in evidence $ ListValidationLeftoverTerms leftovers bestAttempt Choice opts -> validateChoice (validateList cddl terms) opts - _ -> unapplicable rule + _ -> reject rule where validate :: - ([CTree ValidatorPhase] -> [Term] -> Evidenced ListValidationTrace) -> + ([CTree ValidatorPhase] -> [Term] -> Evidenced (ValidationTrace ListBlock)) -> [CTree ValidatorPhase] -> [Term] -> [CTree ValidatorPhase] -> - (Evidenced ListValidationTrace, [Term]) + (Evidenced (ValidationTrace ListBlock), [Term]) validate f skipped tss [] = (f skipped tss, tss) validate f skipped [] (r : rs) | isOptional r = validate f skipped [] rs @@ -900,14 +879,13 @@ validateList cddl terms rule = validateMap :: HasCallStack => - CTreeRoot ValidatorPhase -> [(Term, Term)] -> CTree ValidatorPhase -> - Evidenced ValidationTrace -validateMap cddl terms (CTreeE (VRuleRef n)) = + Validator () +validateMap terms (CTreeE (VRuleRef n)) = dereferenceAndValidate cddl n $ validateMap cddl terms -validateMap cddl terms (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TMap terms) cddl -validateMap cddl terms rule = +validateMap terms (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TMap terms) cddl +validateMap terms rule = case rule of Postlude PTAny -> terminal rule Map rules -> mapTrace MapTrace $ validate [] terms rules mempty @@ -919,7 +897,7 @@ validateMap cddl terms rule = [(Term, Term)] -> [CTree ValidatorPhase] -> Set CanonicalTerm -> - Evidenced MapValidationTrace + Evidenced (ValidationTrace MapBlock) validate _ [] [] _ = evidence MapValidationDone validate exhausted (kv : _) [] _ = let @@ -987,114 +965,69 @@ validateMap cddl terms rule = -- Choices validateChoice :: - (CTree ValidatorPhase -> Evidenced ValidationTrace) -> + (CTree ValidatorPhase -> Validator ()) -> NE.NonEmpty (CTree ValidatorPhase) -> - Evidenced ValidationTrace -validateChoice v = go 0 + Validator () +validateChoice f rs = asum $ zipWith g [0 ..] (toList rs) where - go :: Int -> NE.NonEmpty (CTree ValidatorPhase) -> Evidenced ValidationTrace - go i (choice NE.:| xs) = do - case v choice of - Evidenced SValid trc -> evidence $ ChoiceBranch i trc - err -> case xs of - [] -> err - y : ys -> err <> go (succ i) (y NE.:| ys) - --------------------------------------------------------------------------------- --- Control helpers - --- | Validate both rules -ctrlAnd :: - (CTree ValidatorPhase -> Evidenced ValidationTrace) -> - CTree ValidatorPhase -> - CTree ValidatorPhase -> - Evidenced ValidationTrace -ctrlAnd v tgt ctrl = - case v tgt of - (isValid -> True) -> v ctrl - err -> err - --- | Dispatch to the appropriate control -ctrlDispatch :: - (CTree ValidatorPhase -> Evidenced ValidationTrace) -> - CtlOp -> - CTree ValidatorPhase -> - CTree ValidatorPhase -> - (CtlOp -> CTree ValidatorPhase -> Bool) -> - Evidenced ValidationTrace -ctrlDispatch v And tgt ctrl _ = ctrlAnd v tgt ctrl -ctrlDispatch v Within tgt ctrl _ = ctrlAnd v tgt ctrl -ctrlDispatch v op tgt ctrl vctrl = - case v tgt of - Evidenced SValid trc - | vctrl op ctrl -> - evidence $ ControlTrace (ControlInfo op (mapIndex ctrl)) trc - | otherwise -> - evidence $ UnsatisfiedControl op (mapIndex ctrl) - err -> err + g i r = pickBranch i $ f r -------------------------------------------------------------------------------- -- Bits control -getIndicesOfChoice :: CTreeRoot ValidatorPhase -> NE.NonEmpty (CTree ValidatorPhase) -> [Word64] -getIndicesOfChoice cddl = concatMap go +getIndicesOfChoice :: NE.NonEmpty (CTree ValidatorPhase) -> Validator [Word64] +getIndicesOfChoice x = mconcat <$> traverse go (toList x) where go = \case - Literal (Value (VUInt v) _) -> [fromIntegral v] + Literal (Value (VUInt v) _) -> pure [fromIntegral v] KV _ v _ -> case v of - CTreeE (VRuleRef n) -> go $ dereference cddl n - Literal (Value (VUInt v') _) -> [fromIntegral v'] + CTreeE (VRuleRef n) -> go =<< dereference n + Literal (Value (VUInt v') _) -> pure [fromIntegral v'] somethingElse -> error $ "Malformed value in KV in choice in .bits: " <> showSimple somethingElse - Range ff tt incl -> getIndicesOfRange cddl ff tt incl - Enum g -> getIndicesOfEnum cddl g + Range ff tt incl -> getIndicesOfRange ff tt incl + Enum g -> getIndicesOfEnum g somethingElse -> error $ "Malformed alternative in choice in .bits: " <> showSimple somethingElse getIndicesOfRange :: - CTreeRoot ValidatorPhase -> CTree ValidatorPhase -> CTree ValidatorPhase -> RangeBound -> [Word64] -getIndicesOfRange cddl (CTreeE (VRuleRef n)) tt incl = - dereference cddl n & \ff -> getIndicesOfRange cddl ff tt incl -getIndicesOfRange cddl ff (CTreeE (VRuleRef n)) incl = - dereference cddl n & \tt -> getIndicesOfRange cddl ff tt incl -getIndicesOfRange _ ff tt incl = + CTree ValidatorPhase -> CTree ValidatorPhase -> RangeBound -> Validator [Word64] +getIndicesOfRange (CTreeE (VRuleRef n)) tt incl = do + ff <- dereference n + getIndicesOfRange ff tt incl +getIndicesOfRange ff (CTreeE (VRuleRef n)) incl = do + tt <- dereference n + getIndicesOfRange ff tt incl +getIndicesOfRange ff tt incl = case (ff, tt) of (Literal (Value (VUInt ff') _), Literal (Value (VUInt tt') _)) -> - case incl of + pure $ case incl of ClOpen -> init rng Closed -> rng where rng = [ff' .. tt'] (lo, hi) -> error $ "Malformed range in .bits: (" <> showSimple lo <> ", " <> showSimple hi <> ")" -getIndicesOfEnum :: CTreeRoot ValidatorPhase -> CTree ValidatorPhase -> [Word64] -getIndicesOfEnum cddl (CTreeE (VRuleRef n)) = getIndicesOfEnum cddl $ dereference cddl n -getIndicesOfEnum cddl g = +getIndicesOfEnum :: CTree ValidatorPhase -> Validator [Word64] +getIndicesOfEnum (CTreeE (VRuleRef n)) = getIndicesOfEnum =<< dereference n +getIndicesOfEnum g = case g of - Group g' -> getIndicesOfChoice cddl (fromJust $ NE.nonEmpty g') + Group g' -> getIndicesOfChoice (fromJust $ NE.nonEmpty g') somethingElse -> error $ "Malformed enum in .bits: " <> showSimple somethingElse -dereference :: - CTreeRoot ValidatorPhase -> - Name -> - CTree ValidatorPhase -dereference (CTreeRoot m) n = - case Map.lookup n m of - Just r -> r - Nothing -> error $ "Nonexistent rule referenced: " <> T.unpack (unName n) +dereference :: Name -> Validator (CTree ValidatorPhase) +dereference n@(Name s) = do + mRes <- lookupCddl n + case mRes of + Just x -> pure x + Nothing -> fail $ "Rule does not exist: " <> T.unpack s -dereferenceAndValidate :: - CTreeRoot ValidatorPhase -> - Name -> - (CTree ValidatorPhase -> Evidenced ValidationTrace) -> - Evidenced ValidationTrace -dereferenceAndValidate cddl n f = - mapTrace (ReferenceRule n) . f $ dereference cddl n +-- mapTrace (ReferenceRule n) . f $ dereference cddl n -------------------------------------------------------------------------------- -- Utils @@ -1102,16 +1035,3 @@ dereferenceAndValidate cddl n f = range :: Ord a => RangeBound -> a -> a -> Bool range Closed = (<=) range ClOpen = (<) - --- * IndexMappable - --- ValidatorPhase -> MonoSimplePhase - -instance IndexMappable CTree ValidatorPhase MonoSimplePhase where - mapIndex = foldCTree mapExt mapIndex - where - mapExt (VRuleRef n) = CTreeE $ MSimpleRef n - mapExt (VValidator _ x) = mapIndex x - -instance IndexMappable CTreeRoot ValidatorPhase MonoSimplePhase where - mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index d5a2f979..c232e21e 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -23,6 +23,11 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( defaultTraceOptions, showValidationTrace, accept, + reject, + failWith, + pickBranch, + withTag, + controlVerdict, -- * Trace SValidity (..), @@ -31,6 +36,8 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( Evidenced (..), ControlInfo (..), ValidationTrace (..), + StepTrace (..), + Block (..), evidence, fromEither, foldEvidenced, @@ -141,12 +148,51 @@ instance Alternative Validator where closeSteps :: [ValidationTrace b IsValid] -> StepTrace b v -> StepTrace b v closeSteps steps cap = foldl' (flip Step) cap steps +pushStep :: ValidationTrace b IsValid -> ValidatorT b () +pushStep step = Validator $ modify (step :) + accept :: CTree ValidatorPhase -> Validator () -accept rule = Validator $ modify (TerminalRule (mapIndex rule) :) +accept = pushStep . TerminalRule . mapIndex + +reject :: CTree ValidatorPhase -> Validator () +reject = failWith . UnapplicableRule . mapIndex + +failWithSteps :: StepTrace b IsInvalid -> ValidatorT b a +failWithSteps = \case + Step t rest -> pushStep t >> failWithSteps rest + StepFailed e -> failWith e + +pickBranch :: Int -> Validator () -> Validator () +pickBranch i = wrapBlock $ ChoiceBranch i + +withTag :: Word64 -> Validator () -> Validator () +withTag t = wrapBlock $ TagTrace t + +controlVerdict :: CtlOp -> CTree ValidatorPhase -> Bool -> Validator () +controlVerdict op ctrl = \case + True -> pushStep $ ControlTrace info SValid + False -> failWith $ ControlTrace info SInvalid + where + info = ControlInfo op $ mapIndex ctrl failWith :: ValidationTrace b IsInvalid -> ValidatorT b a failWith err = Validator $ throwError err +checkEvidence :: ValidatorT b () -> ValidatorT b (Evidenced (StepTrace b)) +checkEvidence v = do + env <- ask + pure $ runValidator env v + +wrapBlock :: + (StepTrace b IsValid -> ValidationTrace b IsValid) -> + ValidatorT b () -> + ValidatorT b () +wrapBlock f v = do + ev <- checkEvidence v + case ev of + Evidenced SValid trc -> pushStep $ f trc + Evidenced SInvalid trc -> failWithSteps trc + -- | Run an action with the given local generic bindings installed. withLocalValidateBindings :: Map Name (CTree ValidatorPhase) -> Validator a -> Validator a @@ -285,8 +331,7 @@ data ValidationTrace (b :: Block) (v :: Validity) where AlternativeFail :: ValidationTrace b IsInvalid UnapplicableRule :: CTree MonoSimplePhase -> ValidationTrace TermBlock IsInvalid TerminalRule :: CTree MonoSimplePhase -> ValidationTrace TermBlock IsValid - ControlTrace :: - ControlInfo -> ValidationTrace TermBlock IsValid -> ValidationTrace TermBlock IsValid + ControlTrace :: ControlInfo -> SValidity v -> ValidationTrace TermBlock v ReferenceRule :: Name -> StepTrace TermBlock v -> ValidationTrace TermBlock v CustomSuccess :: ValidationTrace TermBlock IsValid CustomFailure :: Text -> ValidationTrace b IsInvalid @@ -341,7 +386,7 @@ deriving instance Show (ValidationTrace b v) instance IsValidationTrace (ValidationTrace b) where traceValidity = \case TerminalRule {} -> SValid - ControlTrace {} -> SValid + ControlTrace _ v -> v AlternativeFail -> SInvalid UnapplicableRule {} -> SInvalid ReferenceRule _ x -> traceValidity x @@ -366,7 +411,8 @@ instance IsValidationTrace (ValidationTrace b) where measureProgress = \case TerminalRule {} -> Progress 1 0 - ControlTrace _ x -> measureProgress x + ControlTrace _ SValid -> Progress 0 1 + ControlTrace _ SInvalid -> mempty AlternativeFail -> mempty UnapplicableRule {} -> mempty ReferenceRule _ x -> increaseRefProgress $ measureProgress x @@ -438,11 +484,15 @@ prettyValidationTrace opts = \case TerminalRule x -> "app: " <> annotate (color Green) (pretty x) AlternativeFail -> mempty UnapplicableRule x -> annotate (color Red) $ vsep ["failed to apply: ", indent 2 $ pretty x] - ControlTrace ci x -> - vsep - [ prettyValidationTrace opts x - , nestContainer $ "ctrl:" <+> annotate (color Yellow) ("." <> pretty ci) - ] + ControlTrace ci v -> + let col = case v of + SValid -> Green + SInvalid -> Red + in vsep + [ "ctrl:" <+> annotate (color col) ("." <> pretty ci) <+> case v of + SValid -> mempty + SInvalid -> "(failed)" + ] ChoiceBranch i c -> vsep [ "choice (idx: " <> pretty i <> ")" @@ -561,3 +611,6 @@ instance IndexMappable CTree ValidatorPhase MonoSimplePhase where where mapExt (VRuleRef n) = CTreeE $ MSimpleRef n mapExt (VValidator _ x) = mapIndex x + +instance IndexMappable CTreeRoot ValidatorPhase MonoSimplePhase where + mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m From 339d923805cbfeec83c989b37d38ae5686bc8447 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Wed, 25 Nov 2026 15:55:15 +0200 Subject: [PATCH 23/37] List validator basically done --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 146 ++++++++---------- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 80 ++++++---- 2 files changed, 111 insertions(+), 115 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index f18ea0cc..321b9902 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -27,24 +27,27 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( ValidationTrace (..), Validator, ValidatorPhase, + ValidatorT, XXCTree (..), accept, - compareEvidencedProgress, controlVerdict, + element, evidence, failWith, mapTrace, measureProgress, - pickBranch, reject, runValidator, + withArray, + withChoice, withTag, ) import Codec.CBOR.Cuddle.CDDL.Phase (showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Read import Codec.CBOR.Term -import Data.Bifunctor (Bifunctor (..)) +import Control.Applicative (Alternative (..), optional) +import Control.Monad (void) import Data.Bits hiding (And) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BSL @@ -52,7 +55,6 @@ import Data.Foldable (Foldable (..), asum) import Data.Function (on) import Data.IntSet qualified as IS import Data.List (maximumBy) -import Data.List.NonEmpty (NonEmpty (..)) import Data.List.NonEmpty qualified as NE import Data.Map.Strict qualified as Map import Data.Maybe @@ -64,7 +66,7 @@ import Data.Text.Lazy qualified as TL import Data.Word import GHC.Float import GHC.Stack (HasCallStack) -import Text.Regex.TDFA +import Text.Regex.TDFA ((=~)) data ValidateCBORError = DecodingFailed DeserialiseFailure @@ -85,7 +87,7 @@ validateCBOR bs ruleName cddl@(CTreeRoot tree) = Left e -> Left $ DecodingFailed e Right (rest, term) | BSL.null rest -> case tree Map.!? ruleName of - Just rule -> Right $ runValidator (ValidateEnv cddl mempty) $ validateTerm term rule + Just rule -> Right $ runValidator (validateTerm term rule) $ ValidateEnv cddl mempty Nothing -> Left $ RuleDoesNotExist ruleName | otherwise -> Left $ LeftoverBytes rest @@ -797,82 +799,59 @@ validateList terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TList terms validateList terms rule = case rule of Postlude PTAny -> accept rule - Array rules -> mapTrace ListTrace . fst $ validate finalize [] terms rules - where - finalize _ [] = evidence ListValidationDone - finalize skipped (x : xs) = - let leftovers = x :| xs - unwrapOccur (Occur ct _) = ct - unwrapOccur ct = ct - attempts = - [ (mapIndex r, trc) - | r <- skipped - , Evidenced SInvalid trc <- [validateTerm cddl x (unwrapOccur r)] - , measureProgress trc > mempty - ] - bestAttempt = case attempts of - [] -> Nothing - _ -> Just $ maximumBy (compare `on` (measureProgress . snd)) attempts - in evidence $ ListValidationLeftoverTerms leftovers bestAttempt - Choice opts -> validateChoice (validateList cddl terms) opts + Array rules -> withArray $ do + res <- matchSeq rules terms + case res of + [] -> pure () + (t : ts) -> failWith $ ArrayLeftoverTerms (t NE.:| ts) _ + Choice opts -> validateChoice (validateList terms) opts _ -> reject rule where - validate :: - ([CTree ValidatorPhase] -> [Term] -> Evidenced (ValidationTrace ListBlock)) -> - [CTree ValidatorPhase] -> - [Term] -> - [CTree ValidatorPhase] -> - (Evidenced (ValidationTrace ListBlock), [Term]) - validate f skipped tss [] = (f skipped tss, tss) - validate f skipped [] (r : rs) - | isOptional r = validate f skipped [] rs - | otherwise = (evidence . ListValidationUnappliedRule $ mapIndex r, []) - validate f skipped tss@(t : ts) (r : rs) = - let - orElse x@(Evidenced SValid _, _) _ = x - orElse x@(ex, _) y@(ey, _) = - case compareEvidencedProgress ex ey of - GT -> x - _ -> y - - consumeTerm ct g = case validateTerm cddl t ct of - Evidenced SValid trc -> first (mapTrace $ ListValidationConsume (mapIndex r) trc) $ g ts - Evidenced SInvalid trc -> (evidence $ ListValidationMissingRequired (mapIndex ct) trc, tss) - - consumeGroup ns gp g = case validate (\_ _ -> evidence ListValidationDone) [] tss gp of - (Evidenced SValid trc, leftover) -> first (mapTrace $ ListValidationConsumeGroup (reverse ns) trc) $ g leftover - (Evidenced SInvalid trc, leftover) -> (evidence $ ListValidationBadGroup (reverse ns) trc, leftover) - - consume ct@(CTreeE (VRuleRef n)) g = go n [] - where - go name ns = - case dereference cddl name of - Group gp -> consumeGroup (name : ns) gp g - CTreeE (VRuleRef newName) -> go newName (name : ns) - _ -> consumeTerm ct g - consume (Group gp) g = consumeGroup [] gp g - consume (KV _ v _) g = consume v g - consume ct g = consumeTerm ct g - continue l = validate f skipped l rs - skipRule = validate f (r : skipped) tss rs - rewriteRule newRule l = validate f skipped l (newRule : rs) - validateRule = - \case - Occur ct oi -> case oi of - OIOptional -> consume ct continue `orElse` skipRule - OIZeroOrMore -> consume ct (rewriteRule r) `orElse` skipRule - OIOneOrMore -> consume ct (rewriteRule (Occur ct OIZeroOrMore)) - OIBounded lb ub -> - let bounds = (lb, ub) - in case boundPlacement 1 bounds Closed of - BelowBounds -> consume ct (rewriteRule (Occur ct $ decrementBounds bounds)) - WithinBounds -> consume ct (rewriteRule (Occur ct $ decrementBounds bounds)) `orElse` skipRule - AboveBounds - | boundPlacement 0 (lb, ub) Closed == WithinBounds -> skipRule - | otherwise -> error "Negative upper bound" - _ -> consume r continue - in - validateRule r + matchSingle :: CTree ValidatorPhase -> [Term] -> ValidatorT ListBlock [Term] + matchSingle r [] = failWith $ ArrayLeftoverRule $ mapIndex r + matchSingle r (t : ts) = do + element $ validateTerm t r + pure ts + + -- low inclusive, high exclusive + matchBounded :: + Word64 -> Maybe Word64 -> CTree ValidatorPhase -> [Term] -> ValidatorT ListBlock [Term] + matchBounded lo mHi r ts + | withinBounds && canConsumeMore = do + res <- optional $ matchSingle r ts + case res of + Just remainingTerms -> matchBounded newLo newHi r remainingTerms + Nothing -> pure ts + | withinBounds = pure ts + | belowBounds = do + remainingTerms <- matchSingle r ts + matchBounded newLo newHi r remainingTerms + | otherwise = error "Invalid bounds" + where + withinBounds = lo == 0 && maybe True (> 0) mHi + canConsumeMore = maybe True (> 1) mHi + belowBounds = lo > 0 + + safePred :: Word64 -> Word64 + safePred 0 = 0 + safePred x = pred x + + newLo = safePred lo + newHi = safePred <$> mHi + + matchSeq :: [CTree ValidatorPhase] -> [Term] -> ValidatorT ListBlock [Term] + matchSeq [] ts = pure ts + matchSeq (r : rs) ts = case r of + Occur ct oi -> do + remainingTerms <- case oi of + OIOptional -> matchBounded 0 (Just 1) ct ts + OIBounded lb ub -> matchBounded (fromMaybe 0 lb) ub ct ts + OIZeroOrMore -> matchBounded 0 Nothing ct ts + OIOneOrMore -> matchBounded 1 Nothing ct ts + matchSeq rs remainingTerms + _ -> do + remainingTerms <- matchSingle r ts + matchSeq rs remainingTerms -------------------------------------------------------------------------------- -- Maps @@ -882,9 +861,8 @@ validateMap :: [(Term, Term)] -> CTree ValidatorPhase -> Validator () -validateMap terms (CTreeE (VRuleRef n)) = - dereferenceAndValidate cddl n $ validateMap cddl terms -validateMap terms (CTreeE (VValidator v _)) = runValidator (v $ SingleTerm $ TMap terms) cddl +validateMap terms (CTreeE (VRuleRef n)) = validateMap terms =<< dereference n +validateMap terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TMap terms validateMap terms rule = case rule of Postlude PTAny -> terminal rule @@ -970,7 +948,7 @@ validateChoice :: Validator () validateChoice f rs = asum $ zipWith g [0 ..] (toList rs) where - g i r = pickBranch i $ f r + g i = withChoice i . f -------------------------------------------------------------------------------- -- Bits control diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index c232e21e..0d2ae31f 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -10,6 +10,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( TermValidator, ValidatorPhase, Validator, + ValidatorT, XXCTree (..), HasValidator (..), ValidateEnv (..), @@ -25,9 +26,11 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( accept, reject, failWith, - pickBranch, + withChoice, withTag, + withArray, controlVerdict, + element, -- * Trace SValidity (..), @@ -56,7 +59,7 @@ import Codec.CBOR.Term (Term) import Control.Applicative (Alternative (..)) import Control.Monad.Except (ExceptT, MonadError (..), runExceptT, tryError) import Control.Monad.Reader (MonadReader (..), ReaderT (..), asks) -import Control.Monad.State.Strict (MonadState (..), State, modify, runState) +import Control.Monad.State.Strict (MonadState (..), State, modify', runState) import Data.Foldable (Foldable (..)) import Data.Function (on) import Data.Kind (Type) @@ -121,7 +124,7 @@ instance MonadCddl Validator where instance MonadFail Validator where fail msg = failWith $ CustomFailure $ T.pack msg -instance Alternative Validator where +instance Alternative (ValidatorT b) where Validator x <|> Validator y = Validator $ do initialSt <- get xRes <- tryError x @@ -149,7 +152,7 @@ closeSteps :: [ValidationTrace b IsValid] -> StepTrace b v -> StepTrace b v closeSteps steps cap = foldl' (flip Step) cap steps pushStep :: ValidationTrace b IsValid -> ValidatorT b () -pushStep step = Validator $ modify (step :) +pushStep step = Validator $ modify' (step :) accept :: CTree ValidatorPhase -> Validator () accept = pushStep . TerminalRule . mapIndex @@ -157,17 +160,32 @@ accept = pushStep . TerminalRule . mapIndex reject :: CTree ValidatorPhase -> Validator () reject = failWith . UnapplicableRule . mapIndex +failWith :: ValidationTrace b IsInvalid -> ValidatorT b a +failWith err = Validator $ throwError err + failWithSteps :: StepTrace b IsInvalid -> ValidatorT b a failWithSteps = \case Step t rest -> pushStep t >> failWithSteps rest StepFailed e -> failWith e -pickBranch :: Int -> Validator () -> Validator () -pickBranch i = wrapBlock $ ChoiceBranch i +withChoice :: Int -> Validator () -> Validator () +withChoice i m = + runBlock m >>= \case + Right (_, trc) -> pushStep $ ChoiceBranch i trc + Left trc -> failWithSteps trc withTag :: Word64 -> Validator () -> Validator () withTag t = wrapBlock $ TagTrace t +withArray :: ValidatorT ListBlock () -> Validator () +withArray = wrapBlock ArrayTrace + +element :: Validator () -> ValidatorT ListBlock () +element m = + runBlock m >>= \case + Right (_, trc) -> pushStep $ ArrayElement trc + Left trc -> failWith $ ArrayMissingRequired trc + controlVerdict :: CtlOp -> CTree ValidatorPhase -> Bool -> Validator () controlVerdict op ctrl = \case True -> pushStep $ ControlTrace info SValid @@ -175,23 +193,25 @@ controlVerdict op ctrl = \case where info = ControlInfo op $ mapIndex ctrl -failWith :: ValidationTrace b IsInvalid -> ValidatorT b a -failWith err = Validator $ throwError err - -checkEvidence :: ValidatorT b () -> ValidatorT b (Evidenced (StepTrace b)) -checkEvidence v = do - env <- ask - pure $ runValidator env v - wrapBlock :: - (StepTrace b IsValid -> ValidationTrace b IsValid) -> - ValidatorT b () -> - ValidatorT b () -wrapBlock f v = do - ev <- checkEvidence v - case ev of - Evidenced SValid trc -> pushStep $ f trc - Evidenced SInvalid trc -> failWithSteps trc + (forall v. StepTrace b' v -> ValidationTrace b v) -> + ValidatorT b' a -> + ValidatorT b a +wrapBlock r m = + runBlock m >>= \case + Right (x, steps) -> pushStep (r steps) >> pure x + Left steps -> failWith $ r steps + +runBlockWith :: + ValidatorT b' a -> ValidateEnv -> Either (StepTrace b' IsInvalid) (a, StepTrace b' IsValid) +runBlockWith (Validator m) env = case runState (runExceptT $ runReaderT m env) [] of + (Right x, trc) -> Right (x, closeSteps trc StepsDone) + (Left err, trc) -> Left $ closeSteps trc $ StepFailed err + +runBlock :: + ValidatorT b' a -> + ValidatorT b (Either (StepTrace b' IsInvalid) (a, StepTrace b' IsValid)) +runBlock m = asks $ runBlockWith m -- | Run an action with the given local generic bindings installed. withLocalValidateBindings :: @@ -199,13 +219,13 @@ withLocalValidateBindings :: withLocalValidateBindings binds = local (\env -> env {veLocal = binds `Map.union` veLocal env}) -runValidator :: ValidateEnv -> ValidatorT b a -> Evidenced (StepTrace b) -runValidator env (Validator m) = mkStepTrace $ runState (runExceptT $ runReaderT m env) [] +runValidator :: ValidatorT b a -> ValidateEnv -> Evidenced (StepTrace b) +runValidator m env = mkStepTrace $ runBlockWith m env where - mkStepTrace (eFail, st) = + mkStepTrace eFail = case eFail of - Right _ -> evidence $ closeSteps st StepsDone - Left err -> evidence $ closeSteps st (StepFailed err) + Right (_, trc) -> evidence trc + Left trc -> evidence trc type data Validity = IsValid @@ -341,7 +361,6 @@ data ValidationTrace (b :: Block) (v :: Validity) where InvalidTag :: Word64 -> Word64 -> ValidationTrace TermBlock IsInvalid ArrayTrace :: StepTrace ListBlock v -> ValidationTrace TermBlock v ArrayElement :: - CTree MonoSimplePhase -> StepTrace TermBlock IsValid -> ValidationTrace ListBlock IsValid ArrayLeftoverTerms :: @@ -352,7 +371,6 @@ data ValidationTrace (b :: Block) (v :: Validity) where CTree MonoSimplePhase -> ValidationTrace ListBlock IsInvalid ArrayMissingRequired :: - CTree MonoSimplePhase -> StepTrace TermBlock IsInvalid -> ValidationTrace ListBlock IsInvalid ArrayConsumeGroup :: @@ -543,8 +561,8 @@ prettyValidationTrace opts = \case [ annotate (color Red) "required rule not satisfied:" , pretty r ] - ArrayElement _ steps -> vsep [prettyStepTrace True opts steps] - ArrayMissingRequired _ t -> + ArrayElement steps -> vsep [prettyStepTrace True opts steps] + ArrayMissingRequired t -> vsep [ annotate (color Red) "failed to apply required rule:" , nestContainer $ prettyStepTrace True opts t From 1900b88cf7021cf41753ae836df01113048b9144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Wed, 25 Nov 2026 16:37:45 +0200 Subject: [PATCH 24/37] List validator fixes --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 51 +++++++++++++++---- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 5 +- 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 321b9902..a6e02d04 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -37,6 +37,7 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( mapTrace, measureProgress, reject, + runBlock, runValidator, withArray, withChoice, @@ -803,15 +804,47 @@ validateList terms rule = res <- matchSeq rules terms case res of [] -> pure () - (t : ts) -> failWith $ ArrayLeftoverTerms (t NE.:| ts) _ + (t : ts) -> do + closest <- closestMatch t + failWith $ ArrayLeftoverTerms (t NE.:| ts) closest + where + candidates = reverse [r | r@Occur {} <- rules] + + unwrapOccur (Occur ct _) = ct + unwrapOccur ct = ct + + tryCandidate t r = do + res <- runBlock . validateTerm t $ unwrapOccur r + pure (mapIndex r, res) + + closestMatch t = do + results <- traverse (tryCandidate t) candidates + let + attempts = + [ (r, trc) + | (r, Left trc) <- results + , measureProgress trc > mempty + ] + pure $ case attempts of + [] -> Nothing + _ -> Just $ maximumBy (compare `on` (measureProgress . snd)) attempts Choice opts -> validateChoice (validateList terms) opts _ -> reject rule where matchSingle :: CTree ValidatorPhase -> [Term] -> ValidatorT ListBlock [Term] matchSingle r [] = failWith $ ArrayLeftoverRule $ mapIndex r - matchSingle r (t : ts) = do - element $ validateTerm t r - pure ts + matchSingle r (t : ts) = case r of + CTreeE (VRuleRef n) -> do + ref <- dereference n + matchSingle ref (t : ts) + CTreeE (VValidator v _) -> do + element $ v $ SingleTerm t + pure ts + KV _ v _ -> matchSingle v (t : ts) + Group rs -> matchSeq rs (t : ts) + _ -> do + element $ validateTerm t r + pure ts -- low inclusive, high exclusive matchBounded :: @@ -823,14 +856,12 @@ validateList terms rule = Just remainingTerms -> matchBounded newLo newHi r remainingTerms Nothing -> pure ts | withinBounds = pure ts - | belowBounds = do + | otherwise = do remainingTerms <- matchSingle r ts matchBounded newLo newHi r remainingTerms - | otherwise = error "Invalid bounds" where - withinBounds = lo == 0 && maybe True (> 0) mHi - canConsumeMore = maybe True (> 1) mHi - belowBounds = lo > 0 + withinBounds = lo == 0 + canConsumeMore = maybe True (> 0) mHi safePred :: Word64 -> Word64 safePred 0 = 0 @@ -998,7 +1029,7 @@ getIndicesOfEnum g = Group g' -> getIndicesOfChoice (fromJust $ NE.nonEmpty g') somethingElse -> error $ "Malformed enum in .bits: " <> showSimple somethingElse -dereference :: Name -> Validator (CTree ValidatorPhase) +dereference :: Name -> ValidatorT b (CTree ValidatorPhase) dereference n@(Name s) = do mRes <- lookupCddl n case mRes of diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index 0d2ae31f..a69a7270 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -31,6 +31,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( withArray, controlVerdict, element, + runBlock, -- * Trace SValidity (..), @@ -110,8 +111,8 @@ type Validator = ValidatorT TermBlock type TermValidator = RuleTerm -> Validator () -instance MonadCddl Validator where - type Phase Validator = ValidatorPhase +instance MonadCddl (ValidatorT b) where + type Phase (ValidatorT b) = ValidatorPhase lookupCddl n = do CTreeRoot root <- asks veRoot From af43a974513b5fb820e633dac17628abc0612eae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 26 Nov 2026 13:54:06 +0200 Subject: [PATCH 25/37] Map validation almost done --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 198 +++++++----------- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 45 ++-- 2 files changed, 105 insertions(+), 138 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index a6e02d04..ac543ca2 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -13,42 +13,16 @@ module Codec.CBOR.Cuddle.CBOR.Validator ( ValidateCBORError (..), ) where -import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm, toCanonical) import Codec.CBOR.Cuddle.CDDL hiding (CDDL, Group, Rule) import Codec.CBOR.Cuddle.CDDL.CTree import Codec.CBOR.Cuddle.CDDL.CtlOp import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) -import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( - Block (..), - Evidenced (..), - SValidity (..), - StepTrace, - ValidateEnv (..), - ValidationTrace (..), - Validator, - ValidatorPhase, - ValidatorT, - XXCTree (..), - accept, - controlVerdict, - element, - evidence, - failWith, - mapTrace, - measureProgress, - reject, - runBlock, - runValidator, - withArray, - withChoice, - withTag, - ) +import Codec.CBOR.Cuddle.CDDL.Custom.Validator import Codec.CBOR.Cuddle.CDDL.Phase (showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Read import Codec.CBOR.Term -import Control.Applicative (Alternative (..), optional) -import Control.Monad (void) +import Control.Applicative (optional) import Data.Bits hiding (And) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BSL @@ -59,8 +33,6 @@ import Data.List (maximumBy) import Data.List.NonEmpty qualified as NE import Data.Map.Strict qualified as Map import Data.Maybe -import Data.Set (Set) -import Data.Set qualified as Set import Data.Text qualified as T import Data.Text.Encoding (encodeUtf8) import Data.Text.Lazy qualified as TL @@ -145,9 +117,6 @@ validateTerm term rule TFloat h -> validateFloat h rule TDouble d -> validateDouble d rule -unapplicable :: CTree ValidatorPhase -> Evidenced (ValidationTrace TermBlock) -unapplicable = evidence . UnapplicableRule . mapIndex - -------------------------------------------------------------------------------- -- Ints and integers @@ -759,17 +728,6 @@ validateTagged tag term rule = -- -------------------------------------------------------------------------------- -- -- Lists -isWithinBoundsInclusive :: Ord a => a -> Maybe a -> Maybe a -> Bool -isWithinBoundsInclusive x lb ub = maybe True (x >=) lb && maybe True (x <=) ub - -isOptional :: CTree i -> Bool -isOptional (Occur _ oi) = case oi of - OIOptional -> True - OIZeroOrMore -> True - OIBounded lb ub -> isWithinBoundsInclusive 0 lb ub - _ -> False -isOptional _ = False - data BoundPlacement = BelowBounds | WithinBounds @@ -785,11 +743,9 @@ boundPlacement x (Nothing, Just hi) bounds | range bounds x hi = WithinBounds | otherwise = AboveBounds -decrementBounds :: (Maybe Word64, Maybe Word64) -> OccurrenceIndicator -decrementBounds (lb, ub) = OIBounded (clampedPred <$> lb) (clampedPred <$> ub) - where - clampedPred 0 = 0 - clampedPred x = pred x +clampedPred :: (Eq a, Num a, Enum a) => a -> a +clampedPred 0 = 0 +clampedPred x = pred x validateList :: [Term] -> @@ -804,7 +760,7 @@ validateList terms rule = res <- matchSeq rules terms case res of [] -> pure () - (t : ts) -> do + t : ts -> do closest <- closestMatch t failWith $ ArrayLeftoverTerms (t NE.:| ts) closest where @@ -863,12 +819,8 @@ validateList terms rule = withinBounds = lo == 0 canConsumeMore = maybe True (> 0) mHi - safePred :: Word64 -> Word64 - safePred 0 = 0 - safePred x = pred x - - newLo = safePred lo - newHi = safePred <$> mHi + newLo = clampedPred lo + newHi = clampedPred <$> mHi matchSeq :: [CTree ValidatorPhase] -> [Term] -> ValidatorT ListBlock [Term] matchSeq [] ts = pure ts @@ -896,79 +848,73 @@ validateMap terms (CTreeE (VRuleRef n)) = validateMap terms =<< dereference n validateMap terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TMap terms validateMap terms rule = case rule of - Postlude PTAny -> terminal rule - Map rules -> mapTrace MapTrace $ validate [] terms rules mempty - Choice opts -> validateChoice (validateMap cddl terms) opts - _ -> unapplicable rule + Postlude PTAny -> accept rule + Map rules -> withMap $ do + res <- matchSeq [] rules terms + case res of + [] -> pure () + t : ts -> do + closest <- closestMatch + failWith $ MapLeftoverEntries (t NE.:| ts) closest + Choice opts -> validateChoice (validateMap terms) opts + _ -> reject rule where - validate :: - [CTree ValidatorPhase] -> + matchSingle :: + CTree ValidatorPhase -> [(Term, Term)] -> + ValidatorT MapBlock [(Term, Term)] + matchSingle r [] = failWith $ MapUnappliedRules $ mapIndex r NE.:| [] + matchSingle r ts@((k, v) : tt) = case r of + CTreeE (VRuleRef n) -> do + r' <- dereference n + matchSingle r' ts + CTreeE (VValidator _ _) -> + error + "Custom validators not supported for individual map entries. Write a custom validator for the map instead" + KV kr vr _ -> do + entry (validateTerm k kr) (validateTerm v vr) + pure tt + Group rules -> matchSeq [] rules ts + _ -> error "Unsupported rule in map" + + matchSeq :: [CTree ValidatorPhase] -> - Set CanonicalTerm -> - Evidenced (ValidationTrace MapBlock) - validate _ [] [] _ = evidence MapValidationDone - validate exhausted (kv : _) [] _ = - let - unwrapOccur (Occur ct _) = ct - unwrapOccur ct = ct - attempts = - [ (mapIndex r, MapValidationInvalidValue (mapIndex r) kTrc vTrc) - | r <- exhausted - , KV k v _ <- [unwrapOccur r] - , Evidenced SValid kTrc <- [validateTerm cddl (fst kv) k] - , Evidenced SInvalid vTrc <- [validateTerm cddl (snd kv) v] - , measureProgress (MapValidationInvalidValue (mapIndex r) kTrc vTrc) > mempty - ] - bestAttempt = case attempts of - [] -> Nothing - _ -> Just $ maximumBy (compare `on` (measureProgress . snd)) attempts - in - evidence $ MapValidationLeftoverKVs kv bestAttempt - validate [] [] rs _ = - case NE.nonEmpty $ filter (not . isOptional) rs of - Nothing -> evidence MapValidationDone - Just requiredRules -> evidence $ MapValidationUnappliedRules (mapIndex <$> requiredRules) - validate exhausted kvs (r : rs) seen = - let - consume (KV k v _) f = case kvs of - ((tk, tv) : leftover) -> - let - cKey = toCanonical tk - in - case validateTerm cddl tk k of - Evidenced SValid kTrc - | cKey `Set.notMember` seen -> - case validateTerm cddl tv v of - Evidenced SValid vTrc -> mapTrace (MapValidationConsume (mapIndex r) kTrc vTrc) $ f leftover (Set.insert cKey seen) - Evidenced SInvalid vTrc -> evidence $ MapValidationInvalidValue (mapIndex r) kTrc vTrc - | otherwise -> evidence $ MapValidationDuplicateKeys (mapIndex r) cKey kTrc - Evidenced SInvalid _ -> evidence $ MapValidationUnappliedRules (NE.singleton $ mapIndex r) - [] -> error "No remaining KV pairs" - consume x _ = error $ "Unexpected value in map: " <> showSimple x - postponeRule l = validate (r : exhausted) l rs - dropRule l = validate exhausted l rs - resetDropRule l = validate [] l (exhausted <> rs) - rewriteRule newRule l = validate [] l (newRule : exhausted <> rs) - in - case r of - Occur ct oi -> - case oi of - OIOptional -> - consume ct resetDropRule <> postponeRule kvs seen - OIZeroOrMore -> - consume ct (rewriteRule r) <> postponeRule kvs seen - OIOneOrMore -> - consume ct (rewriteRule (Occur ct OIZeroOrMore)) <> postponeRule kvs seen - OIBounded mlb mub - | Just lb <- mlb, Just ub <- mub, lb > ub -> error "Unsatisfiable range encountered" - | otherwise -> case compare 0 <$> mub of - Just EQ -> dropRule kvs seen - Just GT -> error "Unsatisfiable range encountered" - _ -> - consume ct (rewriteRule (Occur ct $ decrementBounds (mlb, mub))) - <> postponeRule kvs seen - _ -> consume r resetDropRule <> postponeRule kvs seen + [CTree ValidatorPhase] -> + [(Term, Term)] -> + ValidatorT MapBlock [(Term, Term)] + matchSeq _ [] ts = pure ts + matchSeq tried (curRule : remaining) ts = + case curRule of + Occur ct oi -> case oi of + OIOptional -> do + res <- optional $ matchSingle ct ts + resetWith Nothing $ fromMaybe ts res + OIZeroOrMore -> do + res <- optional $ matchSingle ct ts + resetWith (Just curRule) $ fromMaybe ts res + OIOneOrMore -> do + remainingTerms <- matchSingle ct ts + resetWith (Just $ Occur ct OIZeroOrMore) remainingTerms + OIBounded mlb mub + | maybe False (> 0) mlb -> do + remainingTerms <- matchSingle ct ts + resetWith (Just newBounds) remainingTerms + | maybe True (> 0) mub -> do + res <- optional $ matchSingle ct ts + case res of + Just remainingTerms -> resetWith (Just newBounds) remainingTerms + Nothing -> resetWith Nothing ts + | otherwise -> resetWith Nothing ts + where + newBounds = Occur ct $ OIBounded (clampedPred <$> mlb) (clampedPred <$> mub) + _ -> do + res <- optional $ matchSingle curRule ts + case res of + Just remainingTerms -> resetWith Nothing remainingTerms + Nothing -> continue + where + resetWith newRule = matchSeq [] (reverse tried <> maybeToList newRule <> remaining) + continue = matchSeq (curRule : tried) remaining ts -------------------------------------------------------------------------------- -- Choices diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index a69a7270..d0b4835d 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -29,8 +29,10 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( withChoice, withTag, withArray, + withMap, controlVerdict, element, + entry, runBlock, -- * Trace @@ -122,7 +124,7 @@ instance MonadCddl (ValidatorT b) where binds <- asks veLocal pure $ Map.lookup (Name t) binds -instance MonadFail Validator where +instance MonadFail (ValidatorT b) where fail msg = failWith $ CustomFailure $ T.pack msg instance Alternative (ValidatorT b) where @@ -181,12 +183,24 @@ withTag t = wrapBlock $ TagTrace t withArray :: ValidatorT ListBlock () -> Validator () withArray = wrapBlock ArrayTrace +withMap :: ValidatorT MapBlock () -> Validator () +withMap = wrapBlock MapTrace + element :: Validator () -> ValidatorT ListBlock () element m = runBlock m >>= \case Right (_, trc) -> pushStep $ ArrayElement trc Left trc -> failWith $ ArrayMissingRequired trc +entry :: Validator () -> Validator () -> ValidatorT MapBlock () +entry mk mv = + runBlock mk >>= \case + Right (_, kTrc) -> + runBlock mv >>= \case + Right (_, vTrc) -> pushStep $ MapEntry kTrc vTrc + Left trc -> failWith $ MapInvalidValue kTrc trc + Left trc -> failWith $ MapInvalidKey trc + controlVerdict :: CtlOp -> CTree ValidatorPhase -> Bool -> Validator () controlVerdict op ctrl = \case True -> pushStep $ ControlTrace info SValid @@ -380,23 +394,23 @@ data ValidationTrace (b :: Block) (v :: Validity) where ValidationTrace ListBlock v MapTrace :: StepTrace MapBlock v -> ValidationTrace TermBlock v MapEntry :: - CTree MonoSimplePhase -> StepTrace TermBlock IsValid -> StepTrace TermBlock IsValid -> ValidationTrace MapBlock IsValid + MapInvalidKey :: + StepTrace TermBlock IsInvalid -> + ValidationTrace MapBlock IsInvalid MapInvalidValue :: - CTree MonoSimplePhase -> StepTrace TermBlock IsValid -> StepTrace TermBlock IsInvalid -> ValidationTrace MapBlock IsInvalid MapDuplicateKeys :: - CTree MonoSimplePhase -> CanonicalTerm -> StepTrace TermBlock IsValid -> ValidationTrace MapBlock IsInvalid MapUnappliedRules :: NonEmpty (CTree MonoSimplePhase) -> ValidationTrace MapBlock IsInvalid MapLeftoverEntries :: - (Term, Term) -> + NonEmpty (Term, Term) -> Maybe (CTree MonoSimplePhase, StepTrace MapBlock IsInvalid) -> ValidationTrace MapBlock IsInvalid @@ -423,6 +437,7 @@ instance IsValidationTrace (ValidationTrace b) where ArrayConsumeGroup _ x -> traceValidity x MapTrace x -> traceValidity x MapEntry {} -> SValid + MapInvalidKey {} -> SInvalid MapInvalidValue {} -> SInvalid MapDuplicateKeys {} -> SInvalid MapUnappliedRules {} -> SInvalid @@ -449,9 +464,10 @@ instance IsValidationTrace (ValidationTrace b) where ArrayMissingRequired {} -> mempty ArrayConsumeGroup ns x -> Progress 0 (length ns) <> measureProgress x MapTrace x -> increaseTermProgress $ measureProgress x - MapEntry _ k v -> measureProgress k <> measureProgress v - MapInvalidValue _ k v -> measureProgress k <> measureProgress v - MapDuplicateKeys _ _ x -> measureProgress x + MapEntry k v -> measureProgress k <> measureProgress v + MapInvalidKey k -> measureProgress k + MapInvalidValue k v -> measureProgress k <> measureProgress v + MapDuplicateKeys _ x -> measureProgress x MapUnappliedRules {} -> mempty MapLeftoverEntries _ Nothing -> mempty MapLeftoverEntries _ (Just (_, x)) -> measureProgress x @@ -584,21 +600,26 @@ prettyValidationTrace opts = \case [ annotate (color Red) "not all required rules have been applied:" , vsep (NE.toList $ pretty <$> rs) ] - MapEntry _ k v -> + MapEntry k v -> vsep [ "key:" , nestContainer $ prettyStepTrace True opts k , "value:" , nestContainer $ prettyStepTrace True opts v ] - MapInvalidValue _ k v -> + MapInvalidKey k -> + vsep + [ "key:" <+> annotate (color Red) "(fail)" + , nestContainer $ prettyStepTrace False opts k + ] + MapInvalidValue k v -> vsep [ "key:" , nestContainer $ prettyStepTrace False opts k , "value:" <+> annotate (color Red) "(fail)" - , nestContainer $ prettyStepTrace True opts v + , nestContainer $ prettyStepTrace False opts v ] - MapDuplicateKeys _ _ trc -> + MapDuplicateKeys _ trc -> vsep [ "key: " <> annotate (color Red) "(duplicate)" , nestContainer $ prettyStepTrace False opts trc From 8891f0ed670356f45251e47e2525f8230343b790 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 26 Nov 2026 15:25:31 +0200 Subject: [PATCH 26/37] Map validation fixes --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 75 +++++++++++++------------ 1 file changed, 40 insertions(+), 35 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index ac543ca2..b1f9845f 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -22,12 +22,14 @@ import Codec.CBOR.Cuddle.CDDL.Phase (showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Read import Codec.CBOR.Term -import Control.Applicative (optional) +import Control.Applicative (Alternative (..), optional) +import Control.Monad (filterM) import Data.Bits hiding (And) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BSL -import Data.Foldable (Foldable (..), asum) +import Data.Foldable (Foldable (..), asum, foldrM) import Data.Function (on) +import Data.Functor (($>)) import Data.IntSet qualified as IS import Data.List (maximumBy) import Data.List.NonEmpty qualified as NE @@ -877,44 +879,47 @@ validateMap terms rule = Group rules -> matchSeq [] rules ts _ -> error "Unsupported rule in map" + consumeOne :: + CTree ValidatorPhase -> + [(Term, Term)] -> + ValidatorT MapBlock ([(Term, Term)], Maybe (CTree ValidatorPhase)) + consumeOne r ts = case r of + Occur _ (OIBounded _ (Just 0)) -> empty -- no capacity left + Occur ct oi -> (,next ct oi) <$> matchSingle ct ts + _ -> (,Nothing) <$> matchSingle r ts + where + next ct = \case + OIOptional -> Nothing + OIOneOrMore -> Just $ Occur ct OIZeroOrMore + OIZeroOrMore -> Just $ Occur ct OIZeroOrMore + OIBounded mlb mub -> Just $ Occur ct $ OIBounded (clampedPred <$> mlb) (clampedPred <$> mub) + matchSeq :: [CTree ValidatorPhase] -> [CTree ValidatorPhase] -> [(Term, Term)] -> ValidatorT MapBlock [(Term, Term)] - matchSeq _ [] ts = pure ts - matchSeq tried (curRule : remaining) ts = - case curRule of - Occur ct oi -> case oi of - OIOptional -> do - res <- optional $ matchSingle ct ts - resetWith Nothing $ fromMaybe ts res - OIZeroOrMore -> do - res <- optional $ matchSingle ct ts - resetWith (Just curRule) $ fromMaybe ts res - OIOneOrMore -> do - remainingTerms <- matchSingle ct ts - resetWith (Just $ Occur ct OIZeroOrMore) remainingTerms - OIBounded mlb mub - | maybe False (> 0) mlb -> do - remainingTerms <- matchSingle ct ts - resetWith (Just newBounds) remainingTerms - | maybe True (> 0) mub -> do - res <- optional $ matchSingle ct ts - case res of - Just remainingTerms -> resetWith (Just newBounds) remainingTerms - Nothing -> resetWith Nothing ts - | otherwise -> resetWith Nothing ts - where - newBounds = Occur ct $ OIBounded (clampedPred <$> mlb) (clampedPred <$> mub) - _ -> do - res <- optional $ matchSingle curRule ts - case res of - Just remainingTerms -> resetWith Nothing remainingTerms - Nothing -> continue - where - resetWith newRule = matchSeq [] (reverse tried <> maybeToList newRule <> remaining) - continue = matchSeq (curRule : tried) remaining ts + matchSeq tried rules [] = do + let + checkUnsatisfied = \case + CTreeE (VRuleRef n) -> checkUnsatisfied =<< dereference n + Occur _ oi -> pure $ case oi of + OIOptional -> False + OIZeroOrMore -> False + OIBounded mlb _ -> maybe False (> 0) mlb + OIOneOrMore -> True + _ -> pure True + unappliedRules <- filterM checkUnsatisfied (reverse tried <> rules) + case unappliedRules of + [] -> pure [] + x : xs -> failWith $ MapUnappliedRules $ mapIndex <$> x NE.:| xs + matchSeq _ [] (t : ts) = failWith $ MapLeftoverEntries (t NE.:| ts) Nothing + matchSeq tried (r : rs) ts = + ( do + (rest, r') <- consumeOne r ts + matchSeq [] (reverse tried <> maybeToList r' <> rs) rest + ) + <|> matchSeq (r : tried) rs ts -------------------------------------------------------------------------------- -- Choices From 11ea3a961dc4e1ba417d7422cd8c8a29605a0557 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 26 Nov 2026 15:42:52 +0200 Subject: [PATCH 27/37] Map duplicate keys check --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 10 ++++++++++ src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs | 6 ++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index b1f9845f..57959bb7 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -13,6 +13,7 @@ module Codec.CBOR.Cuddle.CBOR.Validator ( ValidateCBORError (..), ) where +import Codec.CBOR.Cuddle.CBOR.Canonical (toCanonical) import Codec.CBOR.Cuddle.CDDL hiding (CDDL, Group, Rule) import Codec.CBOR.Cuddle.CDDL.CTree import Codec.CBOR.Cuddle.CDDL.CtlOp @@ -35,6 +36,7 @@ import Data.List (maximumBy) import Data.List.NonEmpty qualified as NE import Data.Map.Strict qualified as Map import Data.Maybe +import Data.Set qualified as Set import Data.Text qualified as T import Data.Text.Encoding (encodeUtf8) import Data.Text.Lazy qualified as TL @@ -852,6 +854,7 @@ validateMap terms rule = case rule of Postlude PTAny -> accept rule Map rules -> withMap $ do + checkDuplicates $ toCanonical . fst <$> terms res <- matchSeq [] rules terms case res of [] -> pure () @@ -861,6 +864,13 @@ validateMap terms rule = Choice opts -> validateChoice (validateMap terms) opts _ -> reject rule where + checkDuplicates = go mempty + where + go _ [] = pure () + go seen (k : ts) + | k `Set.member` seen = failWith $ MapDuplicateKeys k + | otherwise = go (Set.insert k seen) ts + matchSingle :: CTree ValidatorPhase -> [(Term, Term)] -> diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index d0b4835d..0b6509d0 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -406,7 +406,6 @@ data ValidationTrace (b :: Block) (v :: Validity) where ValidationTrace MapBlock IsInvalid MapDuplicateKeys :: CanonicalTerm -> - StepTrace TermBlock IsValid -> ValidationTrace MapBlock IsInvalid MapUnappliedRules :: NonEmpty (CTree MonoSimplePhase) -> ValidationTrace MapBlock IsInvalid MapLeftoverEntries :: @@ -467,7 +466,7 @@ instance IsValidationTrace (ValidationTrace b) where MapEntry k v -> measureProgress k <> measureProgress v MapInvalidKey k -> measureProgress k MapInvalidValue k v -> measureProgress k <> measureProgress v - MapDuplicateKeys _ x -> measureProgress x + MapDuplicateKeys x -> measureProgress x MapUnappliedRules {} -> mempty MapLeftoverEntries _ Nothing -> mempty MapLeftoverEntries _ (Just (_, x)) -> measureProgress x @@ -619,10 +618,9 @@ prettyValidationTrace opts = \case , "value:" <+> annotate (color Red) "(fail)" , nestContainer $ prettyStepTrace False opts v ] - MapDuplicateKeys _ trc -> + MapDuplicateKeys _ -> vsep [ "key: " <> annotate (color Red) "(duplicate)" - , nestContainer $ prettyStepTrace False opts trc ] where prettyGroup :: [Name] -> StepTrace ListBlock v -> [Doc AnsiStyle] From b0239326640a8c9a4697cd8993e3506318e4013a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 26 Nov 2026 16:04:20 +0200 Subject: [PATCH 28/37] Implement closestMatch --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 54 ++++++++++--------------- 1 file changed, 21 insertions(+), 33 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 57959bb7..70aa05cb 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -19,18 +19,17 @@ import Codec.CBOR.Cuddle.CDDL.CTree import Codec.CBOR.Cuddle.CDDL.CtlOp import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Validator -import Codec.CBOR.Cuddle.CDDL.Phase (showSimple) +import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase, showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Read import Codec.CBOR.Term import Control.Applicative (Alternative (..), optional) -import Control.Monad (filterM) +import Control.Monad (filterM, void) import Data.Bits hiding (And) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BSL -import Data.Foldable (Foldable (..), asum, foldrM) +import Data.Foldable (Foldable (..), asum) import Data.Function (on) -import Data.Functor (($>)) import Data.IntSet qualified as IS import Data.List (maximumBy) import Data.List.NonEmpty qualified as NE @@ -751,6 +750,18 @@ clampedPred :: (Eq a, Num a, Enum a) => a -> a clampedPred 0 = 0 clampedPred x = pred x +closestMatch :: + (CTree ValidatorPhase -> ValidatorT b' ()) -> + [CTree ValidatorPhase] -> + ValidatorT b (Maybe (CTree MonoSimplePhase, StepTrace b' IsInvalid)) +closestMatch tryRule candidates = do + results <- traverse (\r -> (mapIndex r,) <$> runBlock (tryRule $ unwrapOccur r)) candidates + pure . fmap (maximumBy (compare `on` (measureProgress . snd))) . NE.nonEmpty $ + [(r, trc) | (r, Left trc) <- results, measureProgress trc > mempty] + where + unwrapOccur (Occur ct _) = ct + unwrapOccur ct = ct + validateList :: [Term] -> CTree ValidatorPhase -> @@ -765,29 +776,8 @@ validateList terms rule = case res of [] -> pure () t : ts -> do - closest <- closestMatch t + closest <- closestMatch (validateTerm t) . reverse $ [r | r@Occur {} <- rules] failWith $ ArrayLeftoverTerms (t NE.:| ts) closest - where - candidates = reverse [r | r@Occur {} <- rules] - - unwrapOccur (Occur ct _) = ct - unwrapOccur ct = ct - - tryCandidate t r = do - res <- runBlock . validateTerm t $ unwrapOccur r - pure (mapIndex r, res) - - closestMatch t = do - results <- traverse (tryCandidate t) candidates - let - attempts = - [ (r, trc) - | (r, Left trc) <- results - , measureProgress trc > mempty - ] - pure $ case attempts of - [] -> Nothing - _ -> Just $ maximumBy (compare `on` (measureProgress . snd)) attempts Choice opts -> validateChoice (validateList terms) opts _ -> reject rule where @@ -855,12 +845,8 @@ validateMap terms rule = Postlude PTAny -> accept rule Map rules -> withMap $ do checkDuplicates $ toCanonical . fst <$> terms - res <- matchSeq [] rules terms - case res of - [] -> pure () - t : ts -> do - closest <- closestMatch - failWith $ MapLeftoverEntries (t NE.:| ts) closest + _ <- matchSeq [] rules terms + pure () Choice opts -> validateChoice (validateMap terms) opts _ -> reject rule where @@ -923,7 +909,9 @@ validateMap terms rule = case unappliedRules of [] -> pure [] x : xs -> failWith $ MapUnappliedRules $ mapIndex <$> x NE.:| xs - matchSeq _ [] (t : ts) = failWith $ MapLeftoverEntries (t NE.:| ts) Nothing + matchSeq tried [] (t : ts) = + failWith . MapLeftoverEntries (t NE.:| ts) + =<< closestMatch (\r -> void $ matchSingle r [t]) (reverse tried) matchSeq tried (r : rs) ts = ( do (rest, r') <- consumeOne r ts From 566a044db5855094819b1f88a76b047b9c40a06c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 26 Nov 2026 16:17:55 +0200 Subject: [PATCH 29/37] Compiles --- bin/Main.hs | 4 +- src/Codec/CBOR/Cuddle/CBOR/Generator.hs | 6 ++- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 40 ++++++++++--------- test/Test/Codec/CBOR/Cuddle/CDDL/Examples.hs | 3 +- .../Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs | 7 ++-- test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs | 33 +++++++-------- .../CBOR/Cuddle/CDDL/Validator/Golden.hs | 10 ++--- test/Test/Codec/CBOR/Cuddle/Huddle.hs | 1 + 8 files changed, 57 insertions(+), 47 deletions(-) diff --git a/bin/Main.hs b/bin/Main.hs index e28e6f86..6078569c 100644 --- a/bin/Main.hs +++ b/bin/Main.hs @@ -18,7 +18,7 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( Evidenced (..), SValidity (..), TraceOptions (..), - prettyValidationTrace, + prettyStepTrace, ) import Codec.CBOR.Cuddle.CDDL.Postlude (appendPostlude) import Codec.CBOR.Cuddle.CDDL.Resolve ( @@ -451,7 +451,7 @@ runValidateCBOR bs rule cddl traceOpts = exitFailure Right (Evidenced validity trc) -> do T.putStrLn . Ansi.renderStrict . layoutPretty defaultLayoutOptions $ - prettyValidationTrace traceOpts trc + prettyStepTrace traceOpts trc putStrLn mempty case validity of SValid -> do diff --git a/src/Codec/CBOR/Cuddle/CBOR/Generator.hs b/src/Codec/CBOR/Cuddle/CBOR/Generator.hs index 65fa7e5f..d28bf49a 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Generator.hs @@ -78,7 +78,9 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Gen import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( Evidenced (..), SValidity (..), + ValidateEnv (..), ValidatorPhase, + runValidator, ) import Codec.CBOR.Cuddle.CDDL.Phase (showSimple) import Codec.CBOR.Cuddle.CDDL.Resolve (XXCTree (..)) @@ -475,9 +477,11 @@ genForCTree node = case node of isInvalidAgainstNode :: CTreeRoot GenPhase -> Term -> CTree GenPhase -> Bool isInvalidAgainstNode cTreeRoot term node = - case validateTerm (mapIndex cTreeRoot) term $ mapIndex node of + case runValidator (validateTerm term (mapIndex node)) env of Evidenced SValid _ -> False Evidenced SInvalid _ -> True + where + env = ValidateEnv (mapIndex cTreeRoot) mempty -- | Generate a map from a list of nodes genMap :: diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index 0b6509d0..148bc87a 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -49,6 +49,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( foldEvidenced, measureProgress, prettyValidationTrace, + prettyStepTrace, ) where import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm) @@ -466,7 +467,7 @@ instance IsValidationTrace (ValidationTrace b) where MapEntry k v -> measureProgress k <> measureProgress v MapInvalidKey k -> measureProgress k MapInvalidValue k v -> measureProgress k <> measureProgress v - MapDuplicateKeys x -> measureProgress x + MapDuplicateKeys _ -> mempty MapUnappliedRules {} -> mempty MapLeftoverEntries _ Nothing -> mempty MapLeftoverEntries _ (Just (_, x)) -> measureProgress x @@ -498,8 +499,11 @@ newtype TraceOptions = TraceOptions defaultTraceOptions :: TraceOptions defaultTraceOptions = TraceOptions {toFoldValid = False} -prettyStepTrace :: Bool -> TraceOptions -> StepTrace b v -> Doc AnsiStyle -prettyStepTrace mayFold opts@TraceOptions {..} steps +prettyStepTrace :: TraceOptions -> StepTrace b v -> Doc AnsiStyle +prettyStepTrace opts@TraceOptions {..} = prettyStepTraceWithFold toFoldValid opts + +prettyStepTraceWithFold :: Bool -> TraceOptions -> StepTrace b v -> Doc AnsiStyle +prettyStepTraceWithFold mayFold opts@TraceOptions {..} steps | toFoldValid && mayFold = vsep $ [ annotate italicized $ "... " <> pretty (length validInit) <> " valid entries not shown" @@ -530,12 +534,12 @@ prettyValidationTrace opts = \case ChoiceBranch i c -> vsep [ "choice (idx: " <> pretty i <> ")" - , nestContainer $ prettyStepTrace False opts c + , nestContainer $ prettyStepTraceWithFold False opts c ] ReferenceRule (Name n) x -> vsep [ "ref: " <> annotate (color Blue) (pretty n) - , nestContainer $ prettyStepTrace False opts x + , nestContainer $ prettyStepTraceWithFold False opts x ] CustomSuccess -> "" CustomFailure e -> annotate (color Red) $ pretty e @@ -548,17 +552,17 @@ prettyValidationTrace opts = \case ArrayTrace l -> vsep [ "array" - , nestContainer $ prettyStepTrace False opts l + , nestContainer $ prettyStepTraceWithFold False opts l ] MapTrace m -> vsep [ "map" - , nestContainer $ prettyStepTrace False opts m + , nestContainer $ prettyStepTraceWithFold False opts m ] TagTrace t x -> vsep [ "tag:" <+> annotate (color Green) ("#6." <> pretty t) - , nestContainer $ prettyStepTrace False opts x + , nestContainer $ prettyStepTraceWithFold False opts x ] InvalidTag expected actual -> "expected tag #6." <> pretty expected <> ", got #6." <> pretty actual @@ -569,7 +573,7 @@ prettyValidationTrace opts = \case vsep [ annotate (color Red) "leftover elements, closest matching rule:" , annotate (color Green) $ pretty $ show rule - , nestContainer $ prettyStepTrace True opts trc + , nestContainer $ prettyStepTraceWithFold True opts trc ] ArrayLeftoverRule r -> hang 2 $ @@ -577,11 +581,11 @@ prettyValidationTrace opts = \case [ annotate (color Red) "required rule not satisfied:" , pretty r ] - ArrayElement steps -> vsep [prettyStepTrace True opts steps] + ArrayElement steps -> vsep [prettyStepTraceWithFold True opts steps] ArrayMissingRequired t -> vsep [ annotate (color Red) "failed to apply required rule:" - , nestContainer $ prettyStepTrace True opts t + , nestContainer $ prettyStepTraceWithFold True opts t ] ArrayConsumeGroup refs x -> vsep $ prettyGroup refs x MapLeftoverEntries _ Nothing -> @@ -591,7 +595,7 @@ prettyValidationTrace opts = \case vsep [ annotate (color Red) "leftover key-value pairs, closest matching rule:" , annotate (color Green) $ pretty rule - , nestContainer $ prettyStepTrace True opts trc + , nestContainer $ prettyStepTraceWithFold True opts trc ] MapUnappliedRules rs -> hang 2 $ @@ -602,21 +606,21 @@ prettyValidationTrace opts = \case MapEntry k v -> vsep [ "key:" - , nestContainer $ prettyStepTrace True opts k + , nestContainer $ prettyStepTraceWithFold True opts k , "value:" - , nestContainer $ prettyStepTrace True opts v + , nestContainer $ prettyStepTraceWithFold True opts v ] MapInvalidKey k -> vsep [ "key:" <+> annotate (color Red) "(fail)" - , nestContainer $ prettyStepTrace False opts k + , nestContainer $ prettyStepTraceWithFold False opts k ] MapInvalidValue k v -> vsep [ "key:" - , nestContainer $ prettyStepTrace False opts k + , nestContainer $ prettyStepTraceWithFold False opts k , "value:" <+> annotate (color Red) "(fail)" - , nestContainer $ prettyStepTrace False opts v + , nestContainer $ prettyStepTraceWithFold False opts v ] MapDuplicateKeys _ -> vsep @@ -634,7 +638,7 @@ prettyValidationTrace opts = \case [ case traceValidity x of SValid -> "grp" SInvalid -> "grp" <+> annotate (color Red) "(fail)" - , nestContainer $ prettyStepTrace True opts x + , nestContainer $ prettyStepTraceWithFold True opts x ] showValidationTrace :: ValidationTrace b v -> String diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Examples.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Examples.hs index fee3b2a2..c319f02d 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Examples.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Examples.hs @@ -2,7 +2,7 @@ module Test.Codec.CBOR.Cuddle.CDDL.Examples (spec) where -import Codec.CBOR.Cuddle.CDDL (Value (..), ValueVariant (..)) +import Codec.CBOR.Cuddle.CDDL (Value (..), ValueVariant (..), mapCDDLDropExt) import Codec.CBOR.Cuddle.CDDL.CTree (CTree (..), CTreeRoot, PTerm (..)) import Codec.CBOR.Cuddle.CDDL.Postlude (appendPostlude) import Codec.CBOR.Cuddle.CDDL.Resolve ( @@ -10,7 +10,6 @@ import Codec.CBOR.Cuddle.CDDL.Resolve ( NameResolutionFailure (..), fullResolveCDDL, ) -import Codec.CBOR.Cuddle.IndexMappable (mapCDDLDropExt) import Codec.CBOR.Cuddle.Parser (pCDDL) import Data.Text.IO qualified as T import Paths_cuddle (getDataFileName) diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs index 148849a5..8917c47c 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs @@ -5,12 +5,13 @@ module Test.Codec.CBOR.Cuddle.CDDL.GeneratorSpec (spec) where import Codec.CBOR.Cuddle.CBOR.Generator (GenPhase, generateFromName) -import Codec.CBOR.Cuddle.CDDL (Name) +import Codec.CBOR.Cuddle.CDDL (Name, mapCDDLDropExt) import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) -import Codec.CBOR.Cuddle.CDDL.Resolve (MonoReferenced, MonoSimplePhase, fullResolveCDDL) +import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase) +import Codec.CBOR.Cuddle.CDDL.Resolve (MonoReferenced, fullResolveCDDL) import Codec.CBOR.Cuddle.Huddle (Huddle, toCDDL) -import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..), mapCDDLDropExt) +import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Pretty (prettyHexEnc) import Codec.CBOR.Read (deserialiseFromBytes) import Codec.CBOR.Term (Term (..), decodeTerm, encodeTerm) diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs index 81e17711..90895bfd 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs @@ -17,19 +17,20 @@ import Codec.CBOR.Cuddle.CBOR.Validator ( ValidatorPhase, validateCBOR, ) -import Codec.CBOR.Cuddle.CBOR.Validator.Trace ( - Evidenced (..), - SValidity (..), - ValidationTrace, - defaultTraceOptions, - prettyValidationTrace, - ) -import Codec.CBOR.Cuddle.CDDL (Name (..)) +import Codec.CBOR.Cuddle.CDDL (Name (..), mapCDDLDropExt) import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot (..)) import Codec.CBOR.Cuddle.CDDL.CTree qualified as CTree import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) -import Codec.CBOR.Cuddle.CDDL.Custom.Validator (TermValidator) +import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( + Block (..), + Evidenced (..), + SValidity (..), + StepTrace, + TermValidator, + defaultTraceOptions, + prettyStepTrace, + ) import Codec.CBOR.Cuddle.CDDL.Postlude (appendPostlude) import Codec.CBOR.Cuddle.CDDL.Resolve (MonoReferenced, fullResolveCDDL) import Codec.CBOR.Cuddle.Huddle ( @@ -49,7 +50,7 @@ import Codec.CBOR.Cuddle.Huddle ( (=:~), ) import Codec.CBOR.Cuddle.Huddle qualified as H -import Codec.CBOR.Cuddle.IndexMappable (mapCDDLDropExt, mapIndex) +import Codec.CBOR.Cuddle.IndexMappable (mapIndex) import Codec.CBOR.Cuddle.Parser (pCDDL) import Codec.CBOR.Pretty (prettyHexEnc) import Codec.CBOR.Term (Term (..), encodeTerm) @@ -108,7 +109,7 @@ validateCBOR_ :: BS.ByteString -> Name -> CTreeRoot ValidatorPhase -> - Evidenced ValidationTrace + Evidenced (StepTrace TermBlock) validateCBOR_ bs n cddl = either (\e -> error $ "validateCBOR failed:\n" <> show e) id $ validateCBOR bs n cddl -- | Test that a specific rule in a resolved CDDL generates valid values @@ -274,7 +275,7 @@ validateHuddle :: Huddle -> Name -> Term -> - Evidenced ValidationTrace + Evidenced (StepTrace TermBlock) validateHuddle huddle name term = do let resolvedCddl = case fullResolveCDDL . mapCDDLDropExt $ toCDDL huddle of @@ -283,18 +284,18 @@ validateHuddle huddle name term = do bs = toStrictByteString $ encodeTerm term validateCBOR_ bs name (mapIndex resolvedCddl) -expectValid :: Evidenced ValidationTrace -> Expectation +expectValid :: Evidenced (StepTrace TermBlock) -> Expectation expectValid (Evidenced SValid _) = pure () expectValid (Evidenced SInvalid t) = expectationFailure . T.unpack $ "Expected a success, got failure:\n" - <> renderStrict (layoutPretty defaultLayoutOptions $ prettyValidationTrace defaultTraceOptions t) + <> renderStrict (layoutPretty defaultLayoutOptions $ prettyStepTrace defaultTraceOptions t) -expectInvalid :: Evidenced ValidationTrace -> Expectation +expectInvalid :: Evidenced (StepTrace TermBlock) -> Expectation expectInvalid (Evidenced SValid t) = expectationFailure . T.unpack $ "Expected a failure, but got success:\n" - <> renderStrict (layoutPretty defaultLayoutOptions $ prettyValidationTrace defaultTraceOptions t) + <> renderStrict (layoutPretty defaultLayoutOptions $ prettyStepTrace defaultTraceOptions t) expectInvalid _ = pure () stringValidator :: TermValidator diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator/Golden.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator/Golden.hs index 555a1e79..51027a3b 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator/Golden.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator/Golden.hs @@ -3,15 +3,15 @@ module Test.Codec.CBOR.Cuddle.CDDL.Validator.Golden (spec) where -import Codec.CBOR.Cuddle.CBOR.Validator.Trace ( +import Codec.CBOR.Cuddle.CDDL (Name, mapCDDLDropExt) +import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( defaultTraceOptions, foldEvidenced, - prettyValidationTrace, + prettyStepTrace, ) -import Codec.CBOR.Cuddle.CDDL (Name) import Codec.CBOR.Cuddle.CDDL.Resolve (fullResolveCDDL) import Codec.CBOR.Cuddle.Huddle (Huddle, toCDDL) -import Codec.CBOR.Cuddle.IndexMappable (mapCDDLDropExt, mapIndex) +import Codec.CBOR.Cuddle.IndexMappable (mapIndex) import Codec.CBOR.Term (Term (..), encodeTerm) import Codec.CBOR.Write (toStrictByteString) import Codec.CBOR.Write qualified as CBOR @@ -114,7 +114,7 @@ validatorPrettyGolden testName huddle n term = str = Ansi.renderStrict . layoutPretty defaultLayoutOptions - . foldEvidenced (prettyValidationTrace defaultTraceOptions) + . foldEvidenced (prettyStepTrace defaultTraceOptions) . validateCBOR_ bs n $ mapIndex treeRoot diff --git a/test/Test/Codec/CBOR/Cuddle/Huddle.hs b/test/Test/Codec/CBOR/Cuddle/Huddle.hs index 1712e905..edca35aa 100644 --- a/test/Test/Codec/CBOR/Cuddle/Huddle.hs +++ b/test/Test/Codec/CBOR/Cuddle/Huddle.hs @@ -8,6 +8,7 @@ module Test.Codec.CBOR.Cuddle.Huddle where import Codec.CBOR.Cuddle.CDDL (CDDL, fromRules, sortCDDL) +import Codec.CBOR.Cuddle.CDDL.Phase (HuddleStage) import Codec.CBOR.Cuddle.Comments (Comment) import Codec.CBOR.Cuddle.Huddle import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) From ebd85addbaecdd9c3c4f1ad146a756f3d89497ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 26 Nov 2026 16:42:25 +0200 Subject: [PATCH 30/37] Add ref steps --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 131 ++++++++---------- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 6 +- test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs | 4 +- 3 files changed, 63 insertions(+), 78 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 70aa05cb..05ad472e 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -98,7 +98,7 @@ validateTerm :: CTree ValidatorPhase -> Validator () validateTerm term rule - | CTreeE (VRuleRef n) <- rule = validateTerm term =<< dereference n + | CTreeE (VRuleRef n) <- rule = dereference n $ validateTerm term | CTreeE (VValidator validator _) <- rule = validator $ SingleTerm term | otherwise = case term of @@ -141,7 +141,7 @@ validateInteger :: Validator () validateInteger i rule = case rule of - CTreeE (VRuleRef n) -> validateInteger i =<< dereference n + CTreeE (VRuleRef n) -> dereference n $ validateInteger i CTreeE (VValidator validator _) -> validator $ SingleTerm $ TInteger i -- echo "C24101" | xxd -r -p - example.cbor -- echo "foo = int" > a.cddl @@ -201,17 +201,15 @@ validateInteger i rule = (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VBignum m) _)) | (-n) <= i && range bound i m -> accept rule | otherwise -> reject rule - (CTreeE (VRuleRef n), _) -> do - lo <- dereference n - validateInteger i (Range lo high bound) + (CTreeE (VRuleRef n), _) -> + dereference n $ \lo -> validateInteger i (Range lo high bound) (_, CTreeE (VRuleRef n)) -> do - hi <- dereference n - validateInteger i (Range low hi bound) + dereference n $ \hi -> validateInteger i (Range low hi bound) (lo, hi) -> error $ "Unable to validate range: (" <> showSimple lo <> ", " <> showSimple hi <> ")" -- a = &(x, y, z) Enum g -> case g of - CTreeE (VRuleRef n) -> validateInteger i =<< dereference n + CTreeE (VRuleRef n) -> dereference n $ validateInteger i Group g' -> validateInteger i (Choice (NE.fromList g')) _ -> error "Not yet implemented" -- a = x: y @@ -223,7 +221,7 @@ validateInteger i rule = _ -> reject rule where validateBigInt x = case x of - CTreeE (VRuleRef n) -> validateBigInt =<< dereference n + CTreeE (VRuleRef n) -> dereference n validateBigInt Postlude PTBytes -> accept rule Control op tgt@(Postlude PTBytes) ctrl -> validateBytes bs tgt >> controlBytes bs op ctrl @@ -240,7 +238,7 @@ controlInteger :: CtlOp -> CTree ValidatorPhase -> Validator () -controlInteger i op (CTreeE (VRuleRef n)) = controlInteger i op =<< dereference n +controlInteger i op (CTreeE (VRuleRef n)) = dereference n $ controlInteger i op controlInteger i op ctrl = case op of Size -> case ctrl of Literal (Value (VUInt sz) _) -> verdict $ 0 <= i && i < 256 ^ sz @@ -305,7 +303,7 @@ validateHalf :: Float -> CTree ValidatorPhase -> Validator () -validateHalf f (CTreeE (VRuleRef n)) = validateHalf f =<< dereference n +validateHalf f (CTreeE (VRuleRef n)) = dereference n $ validateHalf f validateHalf f (CTreeE (VValidator v _)) = v $ SingleTerm $ THalf f validateHalf f rule = case rule of @@ -321,11 +319,9 @@ validateHalf f rule = Control op tgt ctrl -> validateHalf f tgt >> controlHalf f op ctrl -- a = x..y Range (CTreeE (VRuleRef n)) high bound -> do - lo <- dereference n - validateHalf f $ Range lo high bound + dereference n $ \lo -> validateHalf f $ Range lo high bound Range low (CTreeE (VRuleRef n)) bound -> do - hi <- dereference n - validateHalf f $ Range low hi bound + dereference n $ \hi -> validateHalf f $ Range low hi bound Range (Literal (Value (VFloat16 n) _)) (Literal (Value (VFloat16 m) _)) bound | n <= f && range bound f m -> accept rule _ -> reject rule @@ -337,8 +333,7 @@ controlHalf :: CtlOp -> CTree ValidatorPhase -> Validator () -controlHalf f op (CTreeE (VRuleRef n)) = - controlHalf f op =<< dereference n +controlHalf f op (CTreeE (VRuleRef n)) = dereference n $ controlHalf f op controlHalf f op ctrl = case op of Eq -> case ctrl of Literal (Value (VFloat16 f') _) -> verdict $ f == f' @@ -356,8 +351,7 @@ validateFloat :: Float -> CTree ValidatorPhase -> Validator () -validateFloat f (CTreeE (VRuleRef n)) = - validateFloat f =<< dereference n +validateFloat f (CTreeE (VRuleRef n)) = dereference n $ validateFloat f validateFloat f (CTreeE (VValidator v _)) = v $ SingleTerm $ TFloat f validateFloat f rule = case rule of @@ -374,12 +368,10 @@ validateFloat f rule = Control op tgt ctrl -> validateFloat f tgt >> controlFloat f op ctrl -- a = x..y -- TODO it is unclear if this should mix floating point types too - Range (CTreeE (VRuleRef n)) high bound -> do - lo <- dereference n - validateFloat f $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> do - hi <- dereference n - validateFloat f $ Range low hi bound + Range (CTreeE (VRuleRef n)) high bound -> + dereference n $ \lo -> validateFloat f $ Range lo high bound + Range low (CTreeE (VRuleRef n)) bound -> + dereference n $ \hi -> validateFloat f $ Range low hi bound Range (Literal (Value nv _)) (Literal (Value mv _)) bound | VFloat16 n <- nv , VFloat16 m <- mv @@ -398,7 +390,7 @@ controlFloat :: CtlOp -> CTree ValidatorPhase -> Validator () -controlFloat f op (CTreeE (VRuleRef n)) = controlFloat f op =<< dereference n +controlFloat f op (CTreeE (VRuleRef n)) = dereference n $ controlFloat f op controlFloat f op ctrl = case op of Eq -> case ctrl of Literal (Value (VFloat16 f') _) -> verdict $ f == f' @@ -418,7 +410,7 @@ validateDouble :: Double -> CTree ValidatorPhase -> Validator () -validateDouble f (CTreeE (VRuleRef n)) = validateDouble f =<< dereference n +validateDouble f (CTreeE (VRuleRef n)) = dereference n $ validateDouble f validateDouble f (CTreeE (VValidator v _)) = v $ SingleTerm $ TDouble f validateDouble f rule = case rule of @@ -435,12 +427,10 @@ validateDouble f rule = Control op tgt ctrl -> validateDouble f tgt >> controlDouble f op ctrl -- a = x..y -- TODO it is unclear if this should mix floating point types too - Range (CTreeE (VRuleRef n)) high bound -> do - lo <- dereference n - validateDouble f $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> do - hi <- dereference n - validateDouble f $ Range low hi bound + Range (CTreeE (VRuleRef n)) high bound -> + dereference n $ \lo -> validateDouble f $ Range lo high bound + Range low (CTreeE (VRuleRef n)) bound -> + dereference n $ \hi -> validateDouble f $ Range low hi bound Range (Literal (Value nv _)) (Literal (Value mv _)) bound | VFloat16 n <- nv , VFloat16 m <- mv @@ -463,7 +453,7 @@ controlDouble :: CtlOp -> CTree ValidatorPhase -> Validator () -controlDouble f op (CTreeE (VRuleRef n)) = controlDouble f op =<< dereference n +controlDouble f op (CTreeE (VRuleRef n)) = dereference n $ controlDouble f op controlDouble f op ctrl = case op of Eq -> case ctrl of Literal (Value (VFloat16 f') _) -> verdict $ f == float2Double f' @@ -487,7 +477,7 @@ validateBool :: Bool -> CTree ValidatorPhase -> Validator () -validateBool b (CTreeE (VRuleRef n)) = validateBool b =<< dereference n +validateBool b (CTreeE (VRuleRef n)) = dereference n $ validateBool b validateBool b (CTreeE (VValidator v _)) = v $ SingleTerm $ TBool b validateBool b rule = case rule of @@ -510,7 +500,7 @@ controlBool :: CtlOp -> CTree ValidatorPhase -> Validator () -controlBool b op (CTreeE (VRuleRef n)) = controlBool b op =<< dereference n +controlBool b op (CTreeE (VRuleRef n)) = dereference n $ controlBool b op controlBool b op ctrl = case op of Eq -> case ctrl of Literal (Value (VBool b') _) -> verdict $ b == b' @@ -530,7 +520,7 @@ validateSimple :: Word8 -> CTree ValidatorPhase -> Validator () -validateSimple i (CTreeE (VRuleRef n)) = validateSimple i =<< dereference n +validateSimple i (CTreeE (VRuleRef n)) = dereference n $ validateSimple i validateSimple i (CTreeE (VValidator v _)) = v $ SingleTerm $ TSimple i validateSimple 23 rule = case rule of @@ -549,7 +539,7 @@ validateSimple n _ = error $ "Found simple different to 23! please report this s -- | Validating nil validateNull :: CTree ValidatorPhase -> Validator () -validateNull (CTreeE (VRuleRef n)) = validateNull =<< dereference n +validateNull (CTreeE (VRuleRef n)) = dereference n validateNull validateNull (CTreeE (VValidator v _)) = v $ SingleTerm TNull validateNull rule = case rule of @@ -568,7 +558,7 @@ validateBytes :: BS.ByteString -> CTree ValidatorPhase -> Validator () -validateBytes bs (CTreeE (VRuleRef n)) = validateBytes bs =<< dereference n +validateBytes bs (CTreeE (VRuleRef n)) = dereference n $ validateBytes bs validateBytes bs (CTreeE (VValidator v _)) = v $ SingleTerm $ TBytes bs validateBytes bs rule = case rule of @@ -591,16 +581,14 @@ controlBytes :: CtlOp -> CTree ValidatorPhase -> Validator () -controlBytes bs op (CTreeE (VRuleRef n)) = controlBytes bs op =<< dereference n +controlBytes bs op (CTreeE (VRuleRef n)) = dereference n $ controlBytes bs op controlBytes bs op ctrl = case op of Size -> case ctrl of Literal (Value (VUInt sz) _) | fromIntegral (BS.length bs) == sz -> verdict True - Range (CTreeE (VRuleRef n)) high bound -> do - lo <- dereference n - controlBytes bs op $ Range lo high bound + Range (CTreeE (VRuleRef n)) high bound -> + dereference n $ \lo -> controlBytes bs op $ Range lo high bound Range low (CTreeE (VRuleRef n)) bound -> do - hi <- dereference n - controlBytes bs op $ Range low hi bound + dereference n $ \hi -> controlBytes bs op $ Range low hi bound Range low high bound -> let i = BS.length bs in case (low, high) of @@ -651,7 +639,7 @@ validateText :: T.Text -> CTree ValidatorPhase -> Validator () -validateText txt (CTreeE (VRuleRef n)) = validateText txt =<< dereference n +validateText txt (CTreeE (VRuleRef n)) = dereference n $ validateText txt validateText txt (CTreeE (VValidator v _)) = v $ SingleTerm $ TString txt validateText txt rule = case rule of @@ -674,18 +662,16 @@ controlText :: CtlOp -> CTree ValidatorPhase -> Validator () -controlText bs op (CTreeE (VRuleRef n)) = controlText bs op =<< dereference n +controlText bs op (CTreeE (VRuleRef n)) = dereference n $ controlText bs op controlText bs op ctrl = case op of Size -> let bsSize = BS.length $ encodeUtf8 bs in case ctrl of Literal (Value (VUInt (fromIntegral -> sz)) _) -> verdict $ bsSize == sz - Range (CTreeE (VRuleRef n)) high bound -> do - lo <- dereference n - controlText bs op $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> do - hi <- dereference n - controlText bs op $ Range low hi bound + Range (CTreeE (VRuleRef n)) high bound -> + dereference n $ \lo -> controlText bs op $ Range lo high bound + Range low (CTreeE (VRuleRef n)) bound -> + dereference n $ \hi -> controlText bs op $ Range low hi bound Range ff tt bound -> case (ff, tt) of (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> @@ -714,8 +700,7 @@ validateTagged :: Term -> CTree ValidatorPhase -> Validator () -validateTagged tag term (CTreeE (VRuleRef n)) = - validateTagged tag term =<< dereference n +validateTagged tag term (CTreeE (VRuleRef n)) = dereference n $ validateTagged tag term validateTagged tag term (CTreeE (VValidator v _)) = v $ SingleTerm $ TTagged tag term validateTagged tag term rule = case rule of @@ -766,7 +751,7 @@ validateList :: [Term] -> CTree ValidatorPhase -> Validator () -validateList terms (CTreeE (VRuleRef n)) = validateList terms =<< dereference n +validateList terms (CTreeE (VRuleRef n)) = dereference n $ validateList terms validateList terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TList terms validateList terms rule = case rule of @@ -784,9 +769,8 @@ validateList terms rule = matchSingle :: CTree ValidatorPhase -> [Term] -> ValidatorT ListBlock [Term] matchSingle r [] = failWith $ ArrayLeftoverRule $ mapIndex r matchSingle r (t : ts) = case r of - CTreeE (VRuleRef n) -> do - ref <- dereference n - matchSingle ref (t : ts) + CTreeE (VRuleRef n) -> + dereference n $ \ref -> matchSingle ref (t : ts) CTreeE (VValidator v _) -> do element $ v $ SingleTerm t pure ts @@ -838,7 +822,7 @@ validateMap :: [(Term, Term)] -> CTree ValidatorPhase -> Validator () -validateMap terms (CTreeE (VRuleRef n)) = validateMap terms =<< dereference n +validateMap terms (CTreeE (VRuleRef n)) = dereference n $ validateMap terms validateMap terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TMap terms validateMap terms rule = case rule of @@ -864,8 +848,7 @@ validateMap terms rule = matchSingle r [] = failWith $ MapUnappliedRules $ mapIndex r NE.:| [] matchSingle r ts@((k, v) : tt) = case r of CTreeE (VRuleRef n) -> do - r' <- dereference n - matchSingle r' ts + dereference n $ \r' -> matchSingle r' ts CTreeE (VValidator _ _) -> error "Custom validators not supported for individual map entries. Write a custom validator for the map instead" @@ -898,7 +881,7 @@ validateMap terms rule = matchSeq tried rules [] = do let checkUnsatisfied = \case - CTreeE (VRuleRef n) -> checkUnsatisfied =<< dereference n + CTreeE (VRuleRef n) -> dereference n checkUnsatisfied Occur _ oi -> pure $ case oi of OIOptional -> False OIZeroOrMore -> False @@ -940,7 +923,7 @@ getIndicesOfChoice x = mconcat <$> traverse go (toList x) Literal (Value (VUInt v) _) -> pure [fromIntegral v] KV _ v _ -> case v of - CTreeE (VRuleRef n) -> go =<< dereference n + CTreeE (VRuleRef n) -> dereference n go Literal (Value (VUInt v') _) -> pure [fromIntegral v'] somethingElse -> error $ @@ -955,12 +938,10 @@ getIndicesOfChoice x = mconcat <$> traverse go (toList x) getIndicesOfRange :: CTree ValidatorPhase -> CTree ValidatorPhase -> RangeBound -> Validator [Word64] -getIndicesOfRange (CTreeE (VRuleRef n)) tt incl = do - ff <- dereference n - getIndicesOfRange ff tt incl -getIndicesOfRange ff (CTreeE (VRuleRef n)) incl = do - tt <- dereference n - getIndicesOfRange ff tt incl +getIndicesOfRange (CTreeE (VRuleRef n)) tt incl = + dereference n $ \ff -> getIndicesOfRange ff tt incl +getIndicesOfRange ff (CTreeE (VRuleRef n)) incl = + dereference n $ \tt -> getIndicesOfRange ff tt incl getIndicesOfRange ff tt incl = case (ff, tt) of (Literal (Value (VUInt ff') _), Literal (Value (VUInt tt') _)) -> @@ -972,21 +953,19 @@ getIndicesOfRange ff tt incl = (lo, hi) -> error $ "Malformed range in .bits: (" <> showSimple lo <> ", " <> showSimple hi <> ")" getIndicesOfEnum :: CTree ValidatorPhase -> Validator [Word64] -getIndicesOfEnum (CTreeE (VRuleRef n)) = getIndicesOfEnum =<< dereference n +getIndicesOfEnum (CTreeE (VRuleRef n)) = dereference n getIndicesOfEnum getIndicesOfEnum g = case g of Group g' -> getIndicesOfChoice (fromJust $ NE.nonEmpty g') somethingElse -> error $ "Malformed enum in .bits: " <> showSimple somethingElse -dereference :: Name -> ValidatorT b (CTree ValidatorPhase) -dereference n@(Name s) = do +dereference :: Name -> (CTree ValidatorPhase -> ValidatorT b a) -> ValidatorT b a +dereference n@(Name s) act = do mRes <- lookupCddl n case mRes of - Just x -> pure x + Just x -> withRef n $ act x Nothing -> fail $ "Rule does not exist: " <> T.unpack s --- mapTrace (ReferenceRule n) . f $ dereference cddl n - -------------------------------------------------------------------------------- -- Utils diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index 148bc87a..2d3b38f3 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -26,6 +26,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( accept, reject, failWith, + withRef, withChoice, withTag, withArray, @@ -187,6 +188,9 @@ withArray = wrapBlock ArrayTrace withMap :: ValidatorT MapBlock () -> Validator () withMap = wrapBlock MapTrace +withRef :: Name -> ValidatorT b a -> ValidatorT b a +withRef n = wrapBlock $ ReferenceRule n + element :: Validator () -> ValidatorT ListBlock () element m = runBlock m >>= \case @@ -368,7 +372,7 @@ data ValidationTrace (b :: Block) (v :: Validity) where UnapplicableRule :: CTree MonoSimplePhase -> ValidationTrace TermBlock IsInvalid TerminalRule :: CTree MonoSimplePhase -> ValidationTrace TermBlock IsValid ControlTrace :: ControlInfo -> SValidity v -> ValidationTrace TermBlock v - ReferenceRule :: Name -> StepTrace TermBlock v -> ValidationTrace TermBlock v + ReferenceRule :: Name -> StepTrace b v -> ValidationTrace b v CustomSuccess :: ValidationTrace TermBlock IsValid CustomFailure :: Text -> ValidationTrace b IsInvalid UnsatisfiedControl :: CtlOp -> CTree MonoSimplePhase -> ValidationTrace TermBlock IsInvalid diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs index 90895bfd..305fb43a 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs @@ -12,7 +12,7 @@ module Test.Codec.CBOR.Cuddle.CDDL.Validator ( ) where import Codec.CBOR.Cuddle.CBOR.Canonical (toCanonical) -import Codec.CBOR.Cuddle.CBOR.Generator (generateFromName) +import Codec.CBOR.Cuddle.CBOR.Generator (XXCTree (..), generateFromName) import Codec.CBOR.Cuddle.CBOR.Validator ( ValidatorPhase, validateCBOR, @@ -134,6 +134,8 @@ genAndValidateRule description name resolvedCddl = genAndValidateCddl :: String -> CTreeRoot MonoReferenced -> Spec genAndValidateCddl description resolvedCddl@(CTreeRoot m) = do let + isRule (CTree.CTreeE (MGenerator _ r)) = isRule r + isRule (CTree.CTreeE (MValidator _ r)) = isRule r isRule CTree.Group {} = False isRule _ = True describe description $ do From 23ead0ee967043d8e97a552675e165d7a19da8bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Thu, 26 Nov 2026 18:10:01 +0200 Subject: [PATCH 31/37] Fix test failures --- golden/cborControlBad.txt | 10 +- golden/huddleRangeArrayTwoStrings.txt | 7 +- golden/mapLeftoverKV.txt | 2 +- golden/mapNestedValue.txt | 2 +- golden/refTermTooLong.txt | 4 +- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 144 ++++++++++-------- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 62 +++++--- test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs | 5 - 8 files changed, 138 insertions(+), 98 deletions(-) diff --git a/golden/cborControlBad.txt b/golden/cborControlBad.txt index fd7e155e..2daf779d 100644 --- a/golden/cborControlBad.txt +++ b/golden/cborControlBad.txt @@ -1,2 +1,8 @@ -unsatisfied control: - .cbor simpleRule \ No newline at end of file +app: bytes +ctrl: .cbor [1, 2, 3] (failed) +└ array + └ app: 1 + app: 2 + failed to apply required rule: + └ failed to apply: + 3 \ No newline at end of file diff --git a/golden/huddleRangeArrayTwoStrings.txt b/golden/huddleRangeArrayTwoStrings.txt index bc33c65c..a0b427a9 100644 --- a/golden/huddleRangeArrayTwoStrings.txt +++ b/golden/huddleRangeArrayTwoStrings.txt @@ -1,7 +1,6 @@ array └ app: int app: int - app: text - app: text - required rule not satisfied: - 1* text \ No newline at end of file + failed to apply required rule: + └ failed to apply: + int \ No newline at end of file diff --git a/golden/mapLeftoverKV.txt b/golden/mapLeftoverKV.txt index f66ec9f6..25794ec1 100644 --- a/golden/mapLeftoverKV.txt +++ b/golden/mapLeftoverKV.txt @@ -3,6 +3,6 @@ map ? 2 ==> int └ key: └ app: 2 - value: (fail) + value: (failed) └ failed to apply: int \ No newline at end of file diff --git a/golden/mapNestedValue.txt b/golden/mapNestedValue.txt index b4143e20..c45650fa 100644 --- a/golden/mapNestedValue.txt +++ b/golden/mapNestedValue.txt @@ -3,7 +3,7 @@ map ? 1 ==> bar └ key: └ app: 1 - value: (fail) + value: (failed) └ ref: bar └ array └ app: int diff --git a/golden/refTermTooLong.txt b/golden/refTermTooLong.txt index bd29faa8..d0a081d6 100644 --- a/golden/refTermTooLong.txt +++ b/golden/refTermTooLong.txt @@ -1,7 +1,7 @@ array └ app: 0 - failed to apply required rule: - └ ref: bar + ref: bar + └ failed to apply required rule: └ array └ app: 1 app: 2 diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 05ad472e..49d8be74 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -202,9 +202,9 @@ validateInteger i rule = | (-n) <= i && range bound i m -> accept rule | otherwise -> reject rule (CTreeE (VRuleRef n), _) -> - dereference n $ \lo -> validateInteger i (Range lo high bound) + dereferenceNoTrace n $ \lo -> validateInteger i (Range lo high bound) (_, CTreeE (VRuleRef n)) -> do - dereference n $ \hi -> validateInteger i (Range low hi bound) + dereferenceNoTrace n $ \hi -> validateInteger i (Range low hi bound) (lo, hi) -> error $ "Unable to validate range: (" <> showSimple lo <> ", " <> showSimple hi <> ")" -- a = &(x, y, z) Enum g -> @@ -238,7 +238,7 @@ controlInteger :: CtlOp -> CTree ValidatorPhase -> Validator () -controlInteger i op (CTreeE (VRuleRef n)) = dereference n $ controlInteger i op +controlInteger i op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlInteger i op controlInteger i op ctrl = case op of Size -> case ctrl of Literal (Value (VUInt sz) _) -> verdict $ 0 <= i && i < 256 ^ sz @@ -319,9 +319,9 @@ validateHalf f rule = Control op tgt ctrl -> validateHalf f tgt >> controlHalf f op ctrl -- a = x..y Range (CTreeE (VRuleRef n)) high bound -> do - dereference n $ \lo -> validateHalf f $ Range lo high bound + dereferenceNoTrace n $ \lo -> validateHalf f $ Range lo high bound Range low (CTreeE (VRuleRef n)) bound -> do - dereference n $ \hi -> validateHalf f $ Range low hi bound + dereferenceNoTrace n $ \hi -> validateHalf f $ Range low hi bound Range (Literal (Value (VFloat16 n) _)) (Literal (Value (VFloat16 m) _)) bound | n <= f && range bound f m -> accept rule _ -> reject rule @@ -333,7 +333,7 @@ controlHalf :: CtlOp -> CTree ValidatorPhase -> Validator () -controlHalf f op (CTreeE (VRuleRef n)) = dereference n $ controlHalf f op +controlHalf f op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlHalf f op controlHalf f op ctrl = case op of Eq -> case ctrl of Literal (Value (VFloat16 f') _) -> verdict $ f == f' @@ -369,9 +369,9 @@ validateFloat f rule = -- a = x..y -- TODO it is unclear if this should mix floating point types too Range (CTreeE (VRuleRef n)) high bound -> - dereference n $ \lo -> validateFloat f $ Range lo high bound + dereferenceNoTrace n $ \lo -> validateFloat f $ Range lo high bound Range low (CTreeE (VRuleRef n)) bound -> - dereference n $ \hi -> validateFloat f $ Range low hi bound + dereferenceNoTrace n $ \hi -> validateFloat f $ Range low hi bound Range (Literal (Value nv _)) (Literal (Value mv _)) bound | VFloat16 n <- nv , VFloat16 m <- mv @@ -390,7 +390,7 @@ controlFloat :: CtlOp -> CTree ValidatorPhase -> Validator () -controlFloat f op (CTreeE (VRuleRef n)) = dereference n $ controlFloat f op +controlFloat f op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlFloat f op controlFloat f op ctrl = case op of Eq -> case ctrl of Literal (Value (VFloat16 f') _) -> verdict $ f == f' @@ -428,9 +428,9 @@ validateDouble f rule = -- a = x..y -- TODO it is unclear if this should mix floating point types too Range (CTreeE (VRuleRef n)) high bound -> - dereference n $ \lo -> validateDouble f $ Range lo high bound + dereferenceNoTrace n $ \lo -> validateDouble f $ Range lo high bound Range low (CTreeE (VRuleRef n)) bound -> - dereference n $ \hi -> validateDouble f $ Range low hi bound + dereferenceNoTrace n $ \hi -> validateDouble f $ Range low hi bound Range (Literal (Value nv _)) (Literal (Value mv _)) bound | VFloat16 n <- nv , VFloat16 m <- mv @@ -453,7 +453,7 @@ controlDouble :: CtlOp -> CTree ValidatorPhase -> Validator () -controlDouble f op (CTreeE (VRuleRef n)) = dereference n $ controlDouble f op +controlDouble f op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlDouble f op controlDouble f op ctrl = case op of Eq -> case ctrl of Literal (Value (VFloat16 f') _) -> verdict $ f == float2Double f' @@ -500,7 +500,7 @@ controlBool :: CtlOp -> CTree ValidatorPhase -> Validator () -controlBool b op (CTreeE (VRuleRef n)) = dereference n $ controlBool b op +controlBool b op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlBool b op controlBool b op ctrl = case op of Eq -> case ctrl of Literal (Value (VBool b') _) -> verdict $ b == b' @@ -581,14 +581,14 @@ controlBytes :: CtlOp -> CTree ValidatorPhase -> Validator () -controlBytes bs op (CTreeE (VRuleRef n)) = dereference n $ controlBytes bs op +controlBytes bs op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlBytes bs op controlBytes bs op ctrl = case op of Size -> case ctrl of Literal (Value (VUInt sz) _) | fromIntegral (BS.length bs) == sz -> verdict True Range (CTreeE (VRuleRef n)) high bound -> - dereference n $ \lo -> controlBytes bs op $ Range lo high bound + dereferenceNoTrace n $ \lo -> controlBytes bs op $ Range lo high bound Range low (CTreeE (VRuleRef n)) bound -> do - dereference n $ \hi -> controlBytes bs op $ Range low hi bound + dereferenceNoTrace n $ \hi -> controlBytes bs op $ Range low hi bound Range low high bound -> let i = BS.length bs in case (low, high) of @@ -622,10 +622,10 @@ controlBytes bs op ctrl = case op of Just byte -> not (testBit byte bitIndex) || IS.member n allowedSet Nothing -> True Cbor -> case deserialiseFromBytes decodeTerm (BSL.fromStrict bs) of - Right (BSL.null -> True, term) -> validateTerm term ctrl + Right (BSL.null -> True, term) -> withCborControl ctrl $ validateTerm term ctrl _ -> verdict False Cborseq -> case deserialiseFromBytes decodeTerm (BSL.fromStrict (BS.snoc (BS.cons 0x9f bs) 0xff)) of - Right (BSL.null -> True, TListI terms) -> validateTerm (TList terms) (Array [Occur ctrl OIZeroOrMore]) + Right (BSL.null -> True, TListI terms) -> withCborseqControl ctrl $ validateListBlock terms [Occur ctrl OIZeroOrMore] _ -> verdict False _ -> error $ "Not yet implmented for bytes: " <> show op where @@ -662,16 +662,16 @@ controlText :: CtlOp -> CTree ValidatorPhase -> Validator () -controlText bs op (CTreeE (VRuleRef n)) = dereference n $ controlText bs op +controlText bs op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlText bs op controlText bs op ctrl = case op of Size -> let bsSize = BS.length $ encodeUtf8 bs in case ctrl of Literal (Value (VUInt (fromIntegral -> sz)) _) -> verdict $ bsSize == sz Range (CTreeE (VRuleRef n)) high bound -> - dereference n $ \lo -> controlText bs op $ Range lo high bound + dereferenceNoTrace n $ \lo -> controlText bs op $ Range lo high bound Range low (CTreeE (VRuleRef n)) bound -> - dereference n $ \hi -> controlText bs op $ Range low hi bound + dereferenceNoTrace n $ \hi -> controlText bs op $ Range low hi bound Range ff tt bound -> case (ff, tt) of (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> @@ -747,30 +747,22 @@ closestMatch tryRule candidates = do unwrapOccur (Occur ct _) = ct unwrapOccur ct = ct -validateList :: +validateListBlock :: [Term] -> - CTree ValidatorPhase -> - Validator () -validateList terms (CTreeE (VRuleRef n)) = dereference n $ validateList terms -validateList terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TList terms -validateList terms rule = - case rule of - Postlude PTAny -> accept rule - Array rules -> withArray $ do - res <- matchSeq rules terms - case res of - [] -> pure () - t : ts -> do - closest <- closestMatch (validateTerm t) . reverse $ [r | r@Occur {} <- rules] - failWith $ ArrayLeftoverTerms (t NE.:| ts) closest - Choice opts -> validateChoice (validateList terms) opts - _ -> reject rule + [CTree ValidatorPhase] -> + ValidatorT ListBlock () +validateListBlock terms rules = do + res <- matchSeq rules terms + case res of + [] -> pure () + t : ts -> do + closest <- closestMatch (validateTerm t) . reverse $ [r | r@Occur {} <- rules] + failWith $ ArrayLeftoverTerms (t NE.:| ts) closest where matchSingle :: CTree ValidatorPhase -> [Term] -> ValidatorT ListBlock [Term] matchSingle r [] = failWith $ ArrayLeftoverRule $ mapIndex r matchSingle r (t : ts) = case r of - CTreeE (VRuleRef n) -> - dereference n $ \ref -> matchSingle ref (t : ts) + CTreeE (VRuleRef n) -> dereference n $ \ref -> matchSingle ref (t : ts) CTreeE (VValidator v _) -> do element $ v $ SingleTerm t pure ts @@ -814,25 +806,30 @@ validateList terms rule = remainingTerms <- matchSingle r ts matchSeq rs remainingTerms --------------------------------------------------------------------------------- --- Maps - -validateMap :: - HasCallStack => - [(Term, Term)] -> +validateList :: + [Term] -> CTree ValidatorPhase -> Validator () -validateMap terms (CTreeE (VRuleRef n)) = dereference n $ validateMap terms -validateMap terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TMap terms -validateMap terms rule = +validateList terms (CTreeE (VRuleRef n)) = dereference n $ validateList terms +validateList terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TList terms +validateList terms rule = case rule of Postlude PTAny -> accept rule - Map rules -> withMap $ do - checkDuplicates $ toCanonical . fst <$> terms - _ <- matchSeq [] rules terms - pure () - Choice opts -> validateChoice (validateMap terms) opts + Array rules -> withArray $ validateListBlock terms rules + Choice opts -> validateChoice (validateList terms) opts _ -> reject rule + +-------------------------------------------------------------------------------- +-- Maps + +validateMapBlock :: + [(Term, Term)] -> + [CTree ValidatorPhase] -> + ValidatorT MapBlock () +validateMapBlock terms rules = do + checkDuplicates $ toCanonical . fst <$> terms + _ <- matchSeq [] rules terms + pure () where checkDuplicates = go mempty where @@ -855,7 +852,7 @@ validateMap terms rule = KV kr vr _ -> do entry (validateTerm k kr) (validateTerm v vr) pure tt - Group rules -> matchSeq [] rules ts + Group rs -> matchSeq [] rs ts _ -> error "Unsupported rule in map" consumeOne :: @@ -878,7 +875,7 @@ validateMap terms rule = [CTree ValidatorPhase] -> [(Term, Term)] -> ValidatorT MapBlock [(Term, Term)] - matchSeq tried rules [] = do + matchSeq tried rs [] = do let checkUnsatisfied = \case CTreeE (VRuleRef n) -> dereference n checkUnsatisfied @@ -888,7 +885,7 @@ validateMap terms rule = OIBounded mlb _ -> maybe False (> 0) mlb OIOneOrMore -> True _ -> pure True - unappliedRules <- filterM checkUnsatisfied (reverse tried <> rules) + unappliedRules <- filterM checkUnsatisfied (reverse tried <> rs) case unappliedRules of [] -> pure [] x : xs -> failWith $ MapUnappliedRules $ mapIndex <$> x NE.:| xs @@ -902,6 +899,20 @@ validateMap terms rule = ) <|> matchSeq (r : tried) rs ts +validateMap :: + HasCallStack => + [(Term, Term)] -> + CTree ValidatorPhase -> + Validator () +validateMap terms (CTreeE (VRuleRef n)) = dereference n $ validateMap terms +validateMap terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TMap terms +validateMap terms rule = + case rule of + Postlude PTAny -> accept rule + Map rules -> withMap $ validateMapBlock terms rules + Choice opts -> validateChoice (validateMap terms) opts + _ -> reject rule + -------------------------------------------------------------------------------- -- Choices @@ -923,7 +934,7 @@ getIndicesOfChoice x = mconcat <$> traverse go (toList x) Literal (Value (VUInt v) _) -> pure [fromIntegral v] KV _ v _ -> case v of - CTreeE (VRuleRef n) -> dereference n go + CTreeE (VRuleRef n) -> dereferenceNoTrace n go Literal (Value (VUInt v') _) -> pure [fromIntegral v'] somethingElse -> error $ @@ -939,9 +950,9 @@ getIndicesOfChoice x = mconcat <$> traverse go (toList x) getIndicesOfRange :: CTree ValidatorPhase -> CTree ValidatorPhase -> RangeBound -> Validator [Word64] getIndicesOfRange (CTreeE (VRuleRef n)) tt incl = - dereference n $ \ff -> getIndicesOfRange ff tt incl + dereferenceNoTrace n $ \ff -> getIndicesOfRange ff tt incl getIndicesOfRange ff (CTreeE (VRuleRef n)) incl = - dereference n $ \tt -> getIndicesOfRange ff tt incl + dereferenceNoTrace n $ \tt -> getIndicesOfRange ff tt incl getIndicesOfRange ff tt incl = case (ff, tt) of (Literal (Value (VUInt ff') _), Literal (Value (VUInt tt') _)) -> @@ -953,18 +964,21 @@ getIndicesOfRange ff tt incl = (lo, hi) -> error $ "Malformed range in .bits: (" <> showSimple lo <> ", " <> showSimple hi <> ")" getIndicesOfEnum :: CTree ValidatorPhase -> Validator [Word64] -getIndicesOfEnum (CTreeE (VRuleRef n)) = dereference n getIndicesOfEnum +getIndicesOfEnum (CTreeE (VRuleRef n)) = dereferenceNoTrace n getIndicesOfEnum getIndicesOfEnum g = case g of Group g' -> getIndicesOfChoice (fromJust $ NE.nonEmpty g') somethingElse -> error $ "Malformed enum in .bits: " <> showSimple somethingElse -dereference :: Name -> (CTree ValidatorPhase -> ValidatorT b a) -> ValidatorT b a -dereference n@(Name s) act = do +dereferenceNoTrace :: Name -> (CTree ValidatorPhase -> ValidatorT b a) -> ValidatorT b a +dereferenceNoTrace n act = do mRes <- lookupCddl n case mRes of - Just x -> withRef n $ act x - Nothing -> fail $ "Rule does not exist: " <> T.unpack s + Just x -> act x + Nothing -> fail "Rule does not exist" + +dereference :: Name -> (CTree ValidatorPhase -> ValidatorT b a) -> ValidatorT b a +dereference n = withRef n . dereferenceNoTrace n -------------------------------------------------------------------------------- -- Utils diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index 2d3b38f3..88e67933 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -31,6 +31,8 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator ( withTag, withArray, withMap, + withCborControl, + withCborseqControl, controlVerdict, element, entry, @@ -191,6 +193,12 @@ withMap = wrapBlock MapTrace withRef :: Name -> ValidatorT b a -> ValidatorT b a withRef n = wrapBlock $ ReferenceRule n +withCborControl :: CTree ValidatorPhase -> Validator () -> Validator () +withCborControl r = wrapBlock $ CborControlTrace $ mapIndex r + +withCborseqControl :: CTree ValidatorPhase -> ValidatorT ListBlock () -> Validator () +withCborseqControl r = wrapBlock $ CborseqControlTrace $ mapIndex r + element :: Validator () -> ValidatorT ListBlock () element m = runBlock m >>= \case @@ -372,6 +380,10 @@ data ValidationTrace (b :: Block) (v :: Validity) where UnapplicableRule :: CTree MonoSimplePhase -> ValidationTrace TermBlock IsInvalid TerminalRule :: CTree MonoSimplePhase -> ValidationTrace TermBlock IsValid ControlTrace :: ControlInfo -> SValidity v -> ValidationTrace TermBlock v + CborControlTrace :: + CTree MonoSimplePhase -> StepTrace TermBlock v -> ValidationTrace TermBlock v + CborseqControlTrace :: + CTree MonoSimplePhase -> StepTrace ListBlock v -> ValidationTrace TermBlock v ReferenceRule :: Name -> StepTrace b v -> ValidationTrace b v CustomSuccess :: ValidationTrace TermBlock IsValid CustomFailure :: Text -> ValidationTrace b IsInvalid @@ -424,6 +436,8 @@ instance IsValidationTrace (ValidationTrace b) where traceValidity = \case TerminalRule {} -> SValid ControlTrace _ v -> v + CborControlTrace _ x -> traceValidity x + CborseqControlTrace _ x -> traceValidity x AlternativeFail -> SInvalid UnapplicableRule {} -> SInvalid ReferenceRule _ x -> traceValidity x @@ -451,6 +465,12 @@ instance IsValidationTrace (ValidationTrace b) where TerminalRule {} -> Progress 1 0 ControlTrace _ SValid -> Progress 0 1 ControlTrace _ SInvalid -> mempty + CborControlTrace _ trc + | SValid <- traceValidity trc -> Progress 0 1 + | otherwise -> mempty + CborseqControlTrace _ trc + | SValid <- traceValidity trc -> Progress 0 1 + | otherwise -> mempty AlternativeFail -> mempty UnapplicableRule {} -> mempty ReferenceRule _ x -> increaseRefProgress $ measureProgress x @@ -527,14 +547,21 @@ prettyValidationTrace opts = \case AlternativeFail -> mempty UnapplicableRule x -> annotate (color Red) $ vsep ["failed to apply: ", indent 2 $ pretty x] ControlTrace ci v -> - let col = case v of - SValid -> Green - SInvalid -> Red - in vsep - [ "ctrl:" <+> annotate (color col) ("." <> pretty ci) <+> case v of - SValid -> mempty - SInvalid -> "(failed)" - ] + "ctrl:" <+> ("." <> pretty ci) <+> case v of + SValid -> mempty + SInvalid -> failedDoc + CborControlTrace rule trc -> + vsep + [ "ctrl: .cbor" <+> pretty rule <+> case traceValidity trc of + SValid -> mempty + SInvalid -> failedDoc + , nestContainer $ prettyStepTraceWithFold False opts trc + ] + CborseqControlTrace rule trc -> + vsep + [ "ctrl: .cborseq" <+> pretty rule + , nestContainer $ prettyStepTrace opts trc + ] ChoiceBranch i c -> vsep [ "choice (idx: " <> pretty i <> ")" @@ -576,7 +603,7 @@ prettyValidationTrace opts = \case hang 2 $ vsep [ annotate (color Red) "leftover elements, closest matching rule:" - , annotate (color Green) $ pretty $ show rule + , annotate (color Green) $ pretty rule , nestContainer $ prettyStepTraceWithFold True opts trc ] ArrayLeftoverRule r -> @@ -616,21 +643,20 @@ prettyValidationTrace opts = \case ] MapInvalidKey k -> vsep - [ "key:" <+> annotate (color Red) "(fail)" + [ "key:" <+> failedDoc , nestContainer $ prettyStepTraceWithFold False opts k ] MapInvalidValue k v -> vsep [ "key:" , nestContainer $ prettyStepTraceWithFold False opts k - , "value:" <+> annotate (color Red) "(fail)" + , "value:" <+> failedDoc , nestContainer $ prettyStepTraceWithFold False opts v ] - MapDuplicateKeys _ -> - vsep - [ "key: " <> annotate (color Red) "(duplicate)" - ] + MapDuplicateKeys _ -> "duplicate keys found" where + failedDoc = annotate (color Red) "(failed)" + prettyGroup :: [Name] -> StepTrace ListBlock v -> [Doc AnsiStyle] prettyGroup refs x = go refs where @@ -639,9 +665,9 @@ prettyValidationTrace opts = \case , nestContainer . vsep $ go ns ] go [] = - [ case traceValidity x of - SValid -> "grp" - SInvalid -> "grp" <+> annotate (color Red) "(fail)" + [ "grp" <+> case traceValidity x of + SValid -> mempty + SInvalid -> failedDoc , nestContainer $ prettyStepTraceWithFold True opts x ] diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs index 305fb43a..5a52c923 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs @@ -181,9 +181,6 @@ genHuddleArrayTerms = do required <- genHuddleArrayRequiredTerms pure $ bools <> required -genHuddleArray :: Gen Term -genHuddleArray = genHuddleArrayTerms >>= genArrayTerm - genBadArrayReversed :: Gen Term genBadArrayReversed = genHuddleArrayTerms >>= genArrayTerm . reverse . (TBool True :) @@ -325,8 +322,6 @@ spec = describe "Validator" $ do describe "Positive" $ do prop "Validates a full map" . forAll genFullMap $ expectValid . validateHuddle huddleMap "a" - prop "Validates array" . forAll genHuddleArray $ - expectValid . validateHuddle huddleArray "a" prop "Validates map with correct number of range elements" . forAll (genHuddleRangeMap (5, 10)) $ expectValid . validateHuddle huddleRangeMap "a" From 42ad61e44c73dfe521c32e6fed4909fd11535091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 27 Nov 2026 13:30:24 +0200 Subject: [PATCH 32/37] Make custom validators overridable --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 39 +++++++++++-------- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 2 +- .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 8 ++-- src/Codec/CBOR/Cuddle/CDDL/Resolve.hs | 24 ++++++------ src/Codec/CBOR/Cuddle/Huddle.hs | 11 ++++-- .../Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs | 2 +- test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs | 9 ++--- 7 files changed, 51 insertions(+), 44 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 49d8be74..279c02a2 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -17,7 +17,7 @@ import Codec.CBOR.Cuddle.CBOR.Canonical (toCanonical) import Codec.CBOR.Cuddle.CDDL hiding (CDDL, Group, Rule) import Codec.CBOR.Cuddle.CDDL.CTree import Codec.CBOR.Cuddle.CDDL.CtlOp -import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) +import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Validator import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase, showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) @@ -88,6 +88,13 @@ validateFromGRef ref term = do Nothing -> fail $ "Unbound generic reference: " <> show ref Just rule -> validateTerm term rule +applyCustomValidator :: + (TermValidator -> TermValidator) -> + CTree ValidatorPhase -> + Term -> + Validator () +applyCustomValidator f x = f (`validateTerm` x) + -------------------------------------------------------------------------------- -- Terms @@ -99,7 +106,7 @@ validateTerm :: Validator () validateTerm term rule | CTreeE (VRuleRef n) <- rule = dereference n $ validateTerm term - | CTreeE (VValidator validator _) <- rule = validator $ SingleTerm term + | CTreeE (VValidator f x) <- rule = applyCustomValidator f x term | otherwise = case term of TInt i -> validateInteger (fromIntegral i) rule @@ -142,7 +149,7 @@ validateInteger :: validateInteger i rule = case rule of CTreeE (VRuleRef n) -> dereference n $ validateInteger i - CTreeE (VValidator validator _) -> validator $ SingleTerm $ TInteger i + CTreeE (VValidator f x) -> f (`validateTerm` x) $ TInteger i -- echo "C24101" | xxd -r -p - example.cbor -- echo "foo = int" > a.cddl -- cddl a.cddl validate example.cbor @@ -304,7 +311,7 @@ validateHalf :: CTree ValidatorPhase -> Validator () validateHalf f (CTreeE (VRuleRef n)) = dereference n $ validateHalf f -validateHalf f (CTreeE (VValidator v _)) = v $ SingleTerm $ THalf f +validateHalf f (CTreeE (VValidator v x)) = applyCustomValidator v x $ THalf f validateHalf f rule = case rule of -- a = any @@ -352,7 +359,7 @@ validateFloat :: CTree ValidatorPhase -> Validator () validateFloat f (CTreeE (VRuleRef n)) = dereference n $ validateFloat f -validateFloat f (CTreeE (VValidator v _)) = v $ SingleTerm $ TFloat f +validateFloat f (CTreeE (VValidator v x)) = applyCustomValidator v x $ TFloat f validateFloat f rule = case rule of -- a = any @@ -411,7 +418,7 @@ validateDouble :: CTree ValidatorPhase -> Validator () validateDouble f (CTreeE (VRuleRef n)) = dereference n $ validateDouble f -validateDouble f (CTreeE (VValidator v _)) = v $ SingleTerm $ TDouble f +validateDouble f (CTreeE (VValidator v x)) = applyCustomValidator v x $ TDouble f validateDouble f rule = case rule of -- a = any @@ -478,7 +485,7 @@ validateBool :: CTree ValidatorPhase -> Validator () validateBool b (CTreeE (VRuleRef n)) = dereference n $ validateBool b -validateBool b (CTreeE (VValidator v _)) = v $ SingleTerm $ TBool b +validateBool b (CTreeE (VValidator v x)) = applyCustomValidator v x $ TBool b validateBool b rule = case rule of -- a = any @@ -521,7 +528,7 @@ validateSimple :: CTree ValidatorPhase -> Validator () validateSimple i (CTreeE (VRuleRef n)) = dereference n $ validateSimple i -validateSimple i (CTreeE (VValidator v _)) = v $ SingleTerm $ TSimple i +validateSimple i (CTreeE (VValidator v x)) = applyCustomValidator v x $ TSimple i validateSimple 23 rule = case rule of -- a = any @@ -540,7 +547,7 @@ validateSimple n _ = error $ "Found simple different to 23! please report this s validateNull :: CTree ValidatorPhase -> Validator () validateNull (CTreeE (VRuleRef n)) = dereference n validateNull -validateNull (CTreeE (VValidator v _)) = v $ SingleTerm TNull +validateNull (CTreeE (VValidator v x)) = applyCustomValidator v x TNull validateNull rule = case rule of -- a = any @@ -559,7 +566,7 @@ validateBytes :: CTree ValidatorPhase -> Validator () validateBytes bs (CTreeE (VRuleRef n)) = dereference n $ validateBytes bs -validateBytes bs (CTreeE (VValidator v _)) = v $ SingleTerm $ TBytes bs +validateBytes bs (CTreeE (VValidator v x)) = applyCustomValidator v x $ TBytes bs validateBytes bs rule = case rule of -- a = any @@ -640,7 +647,7 @@ validateText :: CTree ValidatorPhase -> Validator () validateText txt (CTreeE (VRuleRef n)) = dereference n $ validateText txt -validateText txt (CTreeE (VValidator v _)) = v $ SingleTerm $ TString txt +validateText txt (CTreeE (VValidator v x)) = applyCustomValidator v x $ TString txt validateText txt rule = case rule of -- a = any @@ -701,7 +708,7 @@ validateTagged :: CTree ValidatorPhase -> Validator () validateTagged tag term (CTreeE (VRuleRef n)) = dereference n $ validateTagged tag term -validateTagged tag term (CTreeE (VValidator v _)) = v $ SingleTerm $ TTagged tag term +validateTagged tag term (CTreeE (VValidator v x)) = applyCustomValidator v x $ TTagged tag term validateTagged tag term rule = case rule of Postlude PTAny -> accept rule @@ -763,8 +770,8 @@ validateListBlock terms rules = do matchSingle r [] = failWith $ ArrayLeftoverRule $ mapIndex r matchSingle r (t : ts) = case r of CTreeE (VRuleRef n) -> dereference n $ \ref -> matchSingle ref (t : ts) - CTreeE (VValidator v _) -> do - element $ v $ SingleTerm t + CTreeE (VValidator v x) -> do + element $ applyCustomValidator v x t pure ts KV _ v _ -> matchSingle v (t : ts) Group rs -> matchSeq rs (t : ts) @@ -811,7 +818,7 @@ validateList :: CTree ValidatorPhase -> Validator () validateList terms (CTreeE (VRuleRef n)) = dereference n $ validateList terms -validateList terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TList terms +validateList terms (CTreeE (VValidator v x)) = applyCustomValidator v x $ TList terms validateList terms rule = case rule of Postlude PTAny -> accept rule @@ -905,7 +912,7 @@ validateMap :: CTree ValidatorPhase -> Validator () validateMap terms (CTreeE (VRuleRef n)) = dereference n $ validateMap terms -validateMap terms (CTreeE (VValidator v _)) = v $ SingleTerm $ TMap terms +validateMap terms (CTreeE (VValidator v x)) = applyCustomValidator v x $ TMap terms validateMap terms rule = case rule of Postlude PTAny -> accept rule diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 860cb0f4..4abef261 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -109,7 +109,7 @@ withLocalGenBindings binds = data instance XXCTree GenPhase = GenRef Name | GenGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree GenPhase) - | GenValidator TermValidator (CTree GenPhase) + | GenValidator (TermValidator -> TermValidator) (CTree GenPhase) class HasGenerator a where generatorL :: Lens' a (TermGenerator RuleTerm -> TermGenerator RuleTerm) diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index 88e67933..c2eda435 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -59,7 +59,7 @@ import Codec.CBOR.Cuddle.CBOR.Canonical (CanonicalTerm) import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..)) import Codec.CBOR.Cuddle.CDDL.CTree (CTree (..), CTreeRoot (..), XXCTree (..), foldCTree) import Codec.CBOR.Cuddle.CDDL.CtlOp (CtlOp) -import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm) +import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..)) import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Term (Term) @@ -98,10 +98,10 @@ type data ValidatorPhase data instance XXCTree ValidatorPhase = VRuleRef Name - | VValidator TermValidator (CTree ValidatorPhase) + | VValidator (TermValidator -> TermValidator) (CTree ValidatorPhase) class HasValidator a where - validatorL :: Lens' a (Maybe TermValidator) + validatorL :: Lens' a (TermValidator -> TermValidator) data ValidateEnv = ValidateEnv { veRoot :: CTreeRoot ValidatorPhase @@ -115,7 +115,7 @@ newtype ValidatorT (b :: Block) a type Validator = ValidatorT TermBlock -type TermValidator = RuleTerm -> Validator () +type TermValidator = Term -> Validator () instance MonadCddl (ValidatorT b) where type Phase (ValidatorT b) = ValidatorPhase diff --git a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs index c2ebfe05..a2581628 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Resolve.hs @@ -115,7 +115,7 @@ data instance XCddl CTreePhase = CTreeXCddl deriving (Generic, Show, Eq, Ord) data instance XRule CTreePhase - = CTreeXRule (TermGenerator RuleTerm -> TermGenerator RuleTerm) (Maybe TermValidator) + = CTreeXRule (TermGenerator RuleTerm -> TermGenerator RuleTerm) (TermValidator -> TermValidator) deriving (Generic) data instance XXType2 CTreePhase @@ -128,7 +128,7 @@ newtype PartialCTreeRoot i = PartialCTreeRoot (Map.Map Name (ProvidedParameters data CDDLMapEntry = CDDLMapEntry { cmeProvidedParameters :: ProvidedParameters (TypeOrGroup CTreePhase) , cmeCustomGenerator :: TermGenerator RuleTerm -> TermGenerator RuleTerm - , cmeCustomValidator :: Maybe TermValidator + , cmeCustomValidator :: TermValidator -> TermValidator } deriving (Generic) @@ -178,7 +178,7 @@ asMap cddl = foldl' go Map.empty rules (TOGType _, _) -> error "Attempting to extend a type with a group" (TOGGroup _, _) -> error "Attempting to extend a group with a type" extend tog gps Nothing = - Just $ CDDLMapEntry (toParametrised tog gps) id Nothing + Just $ CDDLMapEntry (toParametrised tog gps) id id -------------------------------------------------------------------------------- -- 2. Conversion to CTree @@ -190,7 +190,7 @@ data instance XXCTree OrReferenced = -- | Reference to another node with possible generic arguments supplied OrRef Name [CTree OrReferenced] | OGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree OrReferenced) - | OValidator TermValidator (CTree OrReferenced) + | OValidator (TermValidator -> TermValidator) (CTree OrReferenced) type data OrReferencedSimple @@ -235,9 +235,7 @@ buildRefCTree rules = PartialCTreeRoot $ toCTreeRule <$> rules applyValidator . applyGenerator . toCTreeTOG <$> cmeProvidedParameters where applyGenerator = CTreeE . OGenerator cmeCustomGenerator - applyValidator = case cmeCustomValidator of - Just v -> CTreeE . OValidator v - Nothing -> id + applyValidator = CTreeE . OValidator cmeCustomValidator toCTreeTOG :: TypeOrGroup CTreePhase -> CTree OrReferenced toCTreeTOG (TOGType t0) = toCTreeT0 t0 @@ -436,7 +434,7 @@ instance Pretty (XXCTree i) => Pretty (DistRef i) where data instance XXCTree DistReferenced = DRef (DistRef DistReferenced) | DGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree DistReferenced) - | DValidator TermValidator (CTree DistReferenced) + | DValidator (TermValidator -> TermValidator) (CTree DistReferenced) type data DistReferencedNoGen @@ -491,7 +489,7 @@ buildResolvedCTree (PartialCTreeRoot ct) = PartialCTreeRoot <$> traverse go ct data instance XXCTree MonoReferenced = MRuleRef Name | MGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree MonoReferenced) - | MValidator TermValidator (CTree MonoReferenced) + | MValidator (TermValidator -> TermValidator) (CTree MonoReferenced) type MonoEnv = BindingEnv DistReferenced MonoReferenced @@ -608,12 +606,12 @@ resolveGenericRef (DGenerator fGen x) = do let TermGenerator newGen m = fGen tg in TermGenerator (withLocalGenBindings bindsGen newGen) m pure . CTreeE $ MGenerator g' body -resolveGenericRef (DValidator v x) = do +resolveGenericRef (DValidator fVal x) = do binds <- ask @"local" body <- resolveGenericCTree x let bindsVal = mapIndex @CTree @MonoReferenced @ValidatorPhase <$> binds - v' = withLocalValidateBindings bindsVal . v - pure . CTreeE $ MValidator v' body + g' tv = withLocalValidateBindings bindsVal . fVal tv + pure . CTreeE $ MValidator g' body resolveGenericCTree :: CTree DistReferenced -> @@ -692,7 +690,7 @@ instance IndexMappable XTerm ParserStage CTreePhase where mapIndex _ = CTreeXTerm instance IndexMappable XRule ParserStage CTreePhase where - mapIndex _ = CTreeXRule id Nothing + mapIndex _ = CTreeXRule id id -- GenPhase -> MonoSimplePhase diff --git a/src/Codec/CBOR/Cuddle/Huddle.hs b/src/Codec/CBOR/Cuddle/Huddle.hs index 91536587..6a3d8052 100644 --- a/src/Codec/CBOR/Cuddle/Huddle.hs +++ b/src/Codec/CBOR/Cuddle/Huddle.hs @@ -171,7 +171,7 @@ newtype instance C.XCddl HuddleStage = HuddleXCddl [C.Comment] data instance C.XRule HuddleStage = HuddleXRule { hxrComment :: C.Comment , hxrGenerator :: TermGenerator RuleTerm -> TermGenerator RuleTerm - , hxrValidator :: Maybe TermValidator + , hxrValidator :: TermValidator -> TermValidator } deriving (Generic) @@ -185,7 +185,7 @@ instance HasGenerator (C.XRule HuddleStage) where generatorL = #hxrGenerator instance Default (XRule HuddleStage) where - def = HuddleXRule def id def + def = HuddleXRule def id id newtype instance C.XXTopLevel HuddleStage = HuddleXXTopLevel C.Comment deriving (Generic, Semigroup, Monoid, Show, Eq) @@ -1162,7 +1162,7 @@ collectFrom topRs = goRanged (Unranged _) = pure () goRanged (Ranged lb ub _) = goRangeBound lb >> goRangeBound ub goRangeBound (RangeBoundLiteral _) = pure () - goRangeBound (RangeBoundRef n r) = goRule . Rule n r $ HuddleXRule mempty id Nothing + goRangeBound (RangeBoundRef n r) = goRule . Rule n r $ HuddleXRule mempty id id -- | Same as `collectFrom`, but the rules passed into this function will be put -- at the top of the Huddle, and all of their dependencies will be added at @@ -1396,7 +1396,10 @@ withOverrideCBORGen :: HasGenerator a => (CBORGen RuleTerm -> CBORGen RuleTerm) withOverrideCBORGen f = withOverrideGenerator $ simpleGen . f . tgGenerator withValidator :: HasValidator a => TermValidator -> a -> a -withValidator p = L.set validatorL $ Just p +withValidator p = withOverrideValidator $ const p + +withOverrideValidator :: HasValidator a => (TermValidator -> TermValidator) -> a -> a +withOverrideValidator = L.set validatorL -- * IndexMappable diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs index 150727c5..32666754 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs @@ -350,7 +350,7 @@ tagRangeExample = _ -> error "tagRangeExample: generic argument must be a single term" validator x = \case - SingleTerm (C.TTagged t inner) + C.TTagged t inner | t >= 1280 && t <= 1400 -> validateFromGRef x inner | otherwise -> fail $ "Tag out of range 1280..1400: " <> show t wt -> fail $ "Expected a tagged term, got: " <> show wt diff --git a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs index 5a52c923..56edcf6e 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs @@ -20,7 +20,6 @@ import Codec.CBOR.Cuddle.CBOR.Validator ( import Codec.CBOR.Cuddle.CDDL (Name (..), mapCDDLDropExt) import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot (..)) import Codec.CBOR.Cuddle.CDDL.CTree qualified as CTree -import Codec.CBOR.Cuddle.CDDL.Custom.Core (RuleTerm (..)) import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( Block (..), @@ -298,13 +297,13 @@ expectInvalid (Evidenced SValid t) = expectInvalid _ = pure () stringValidator :: TermValidator -stringValidator (SingleTerm (TString _)) = pure () -stringValidator (SingleTerm (TStringI _)) = pure () +stringValidator (TString _) = pure () +stringValidator (TStringI _) = pure () stringValidator t = fail $ "Expected a string, got\n" <> show t bytesValidator :: TermValidator -bytesValidator (SingleTerm (TBytes _)) = pure () -bytesValidator (SingleTerm (TBytesI _)) = pure () +bytesValidator (TBytes _) = pure () +bytesValidator (TBytesI _) = pure () bytesValidator t = fail $ "Expected bytes, got\n" <> show t spec :: Spec From b8e69a61acb2d56648e34a19ad781bb649560c67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 27 Nov 2026 14:34:48 +0200 Subject: [PATCH 33/37] Generalize eval functions --- src/Codec/CBOR/Cuddle/CBOR/Generator.hs | 77 +++++------------- src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs | 79 ++++++++++++++++++- .../CBOR/Cuddle/CDDL/Custom/Generator.hs | 5 ++ .../CBOR/Cuddle/CDDL/Custom/Validator.hs | 4 + 4 files changed, 102 insertions(+), 63 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Generator.hs b/src/Codec/CBOR/Cuddle/CBOR/Generator.hs index d28bf49a..3342b9e6 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Generator.hs @@ -23,9 +23,6 @@ module Codec.CBOR.Cuddle.CBOR.Generator ( twiddleMap, twiddleText, twiddleBytes, - evalDouble, - evalInteger, - evalArray, -- * Generator helpers genNBytes, @@ -60,7 +57,13 @@ import Codec.CBOR.Cuddle.CDDL.CTree ( ) import Codec.CBOR.Cuddle.CDDL.CTree qualified as CTree import Codec.CBOR.Cuddle.CDDL.CtlOp qualified as CtlOp -import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) +import Codec.CBOR.Cuddle.CDDL.Custom.Core ( + MonadCddl (..), + RuleTerm (..), + evalDouble, + evalInteger, + evalInterval, + ) import Codec.CBOR.Cuddle.CDDL.Custom.Generator ( CBORGen, GenConfig (..), @@ -87,7 +90,6 @@ import Codec.CBOR.Cuddle.CDDL.Resolve (XXCTree (..)) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) import Codec.CBOR.Cuddle.Interval ( Interval (..), - IntervalBound (..), greaterThanOrEqual, intersect, lessThanOrEqual, @@ -106,7 +108,7 @@ import Data.Char (chr) import Data.Functor ((<&>)) import Data.List (sortOn) import Data.List.NonEmpty qualified as NE -import Data.Maybe (fromMaybe) +import Data.Maybe (fromJust, fromMaybe) import Data.Ord (Down (..)) import Data.Set qualified as Set import Data.Text (Text) @@ -117,7 +119,7 @@ import Data.Text.Lazy qualified as TL import Data.Text.Lazy.Builder (toLazyText) import Data.Text.Lazy.Builder qualified as LB import Data.Word (Word64, Word8) -import GHC.Float (double2Float, float2Double) +import GHC.Float (double2Float) import GHC.Stack (HasCallStack) import Numeric.Half (fromHalf, toHalf) import System.Random.Stateful (Random, StatefulGen (..), runStateGen_, uniformByteStringM) @@ -205,13 +207,13 @@ genHalf = go universe mempty , tgConstrain = \case Gen.Range cRng -> Just $ deferGen $ do -- TODO think about the edges - rng' <- forM cRng $ fmap double2Float . evalDouble + rng' <- forM cRng $ fmap (double2Float . fromJust) . evalDouble pure $ go (rng `intersect` rng') exclude Gen.Eq term -> Just $ deferGen $ do - x <- evalDouble term + x <- fromJust <$> evalDouble term pure $ go (rng `intersect` Interval.singleton (double2Float x)) exclude Gen.Neq term -> Just $ deferGen $ do - x <- evalDouble term + x <- fromJust <$> evalDouble term pure $ go rng $ Set.insert (double2Float x) exclude _ -> Nothing } @@ -290,7 +292,7 @@ genBytes = go Nothing $ greaterThanOrEqual 0 _ -> error "Expected a single term" , tgConstrain = \case Gen.Size rngRule -> Just $ deferGen $ do - newRange <- evalInterval evalInteger rngRule + newRange <- fromJust <$> evalInterval evalInteger rngRule pure $ go mCbor $ szRange `intersect` fmap fromIntegral newRange Gen.Cbor cbor -- Only allow constraining with .cbor once @@ -327,7 +329,7 @@ genText = go $ greaterThanOrEqual 0 genNBytesText n , tgConstrain = \case Gen.Size rngRule -> Just $ deferGen $ do - newRange <- evalInterval evalInteger rngRule + newRange <- fromJust <$> evalInterval evalInteger rngRule pure . go $ sizeRange `intersect` fmap fromIntegral newRange _ -> Nothing } @@ -367,16 +369,16 @@ genInteger validRng invalidRng = go validRng mempty rangeInInterval invalidRng validInterval `suchThat` (`Set.notMember` excluded) , tgConstrain = \case Gen.Size szRule -> Just $ deferGen $ do - sz <- evalInteger szRule + sz <- fromJust <$> evalInteger szRule pure $ go (validInterval `intersect` lessThanOrEqual (2 ^ sz)) excluded Gen.Range intRule -> Just $ deferGen $ do - int <- traverse evalInteger intRule + int <- traverse (fmap fromJust . evalInteger) intRule pure $ go (validInterval `intersect` int) excluded Gen.Eq r -> Just $ deferGen $ do - x <- evalInteger r + x <- fromJust <$> evalInteger r pure $ go (validInterval `intersect` Interval.singleton x) excluded Gen.Neq r -> Just $ deferGen $ do - x <- evalInteger r + x <- fromJust <$> evalInteger r pure $ go validInterval $ Set.insert x excluded _ -> Nothing } @@ -663,49 +665,6 @@ genRange from to bounds = do | a <= b -> choose (range bounds a b) <&> SingleTerm . TDouble (a, b) -> error $ "invalid range (a = " <> show a <> ", b = " <> show b <> ")" -evalDouble :: CTree GenPhase -> CBORGen Double -evalDouble = \case - Literal (Value var _) - | VFloat16 x <- var -> pure $ float2Double x - | VFloat32 x <- var -> pure $ float2Double x - | VFloat64 x <- var -> pure x - CTreeE (GenGenerator _ t) -> evalDouble t - CTreeE (GenValidator _ t) -> evalDouble t - CTreeE (GenRef n) -> evalDouble =<< resolveRef n - _ -> error "Expected double" - -evalInteger :: CTree GenPhase -> CBORGen Integer -evalInteger = \case - Literal (Value var _) - | VUInt x <- var -> pure $ toInteger x - | VNInt x <- var -> pure . negate $ toInteger x - | VBignum x <- var -> pure x - CTreeE (GenGenerator _ t) -> evalInteger t - CTreeE (GenValidator _ t) -> evalInteger t - CTreeE (GenRef n) -> evalInteger =<< resolveRef n - _ -> error "Expected integer" - -evalArray :: (CTree GenPhase -> CBORGen a) -> CTree GenPhase -> CBORGen [a] -evalArray f = \case - Array es -> traverse f es - CTreeE (GenGenerator _ t) -> evalArray f t - CTreeE (GenValidator _ t) -> evalArray f t - CTreeE (GenRef n) -> evalArray f =<< resolveRef n - _ -> error "Expected array" - -evalInterval :: (CTree GenPhase -> CBORGen a) -> CTree GenPhase -> CBORGen (Interval a) -evalInterval f = \case - Range loRule hiRule bound -> do - lo <- f loRule - hi <- f hiRule - pure $ Interval (ClosedBound lo) $ case bound of - ClOpen -> OpenBound hi - Closed -> ClosedBound hi - CTreeE (GenGenerator _ t) -> evalInterval f t - CTreeE (GenValidator _ t) -> evalInterval f t - CTreeE (GenRef n) -> evalInterval f =<< resolveRef n - x -> Interval.singleton <$> f x - -- | Generate a value with a control operator applied genControl :: HasCallStack => diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs index 05382a58..c16a2e88 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs @@ -1,13 +1,24 @@ +{-# LANGUAGE LambdaCase #-} {-# LANGUAGE TypeFamilies #-} -module Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) where +module Codec.CBOR.Cuddle.CDDL.Custom.Core ( + MonadCddl (..), + RuleTerm (..), + evalInteger, + evalDouble, + evalArray, + evalInterval, +) where -import Codec.CBOR.Cuddle.CDDL (GRef, Name) -import Codec.CBOR.Cuddle.CDDL.CTree (CTree) +import Codec.CBOR.Cuddle.CDDL (GRef, Name, RangeBound (..), Value (..), ValueVariant (..)) +import Codec.CBOR.Cuddle.CDDL.CTree (CTree (..), XXCTree) +import Codec.CBOR.Cuddle.Interval (Interval (..), IntervalBound (..)) +import Codec.CBOR.Cuddle.Interval qualified as Interval import Codec.CBOR.Term (Term) import Data.Kind (Type) +import GHC.Float (float2Double) -class MonadCddl m where +class Monad m => MonadCddl m where type Phase m :: Type -- | Look up a top-level rule by name. @@ -18,8 +29,68 @@ class MonadCddl m where -- attached to a generic rule. lookupGRef :: GRef -> m (Maybe (CTree (Phase m))) + resolveExt :: XXCTree (Phase m) -> m (Maybe (CTree (Phase m))) + data RuleTerm = SingleTerm Term | PairTerm Term Term | GroupTerm [RuleTerm] deriving (Eq, Ord, Show) + +evalExt :: + MonadCddl m => + XXCTree (Phase m) -> + (CTree (Phase m) -> m (Maybe a)) -> + m (Maybe a) +evalExt ext f = do + res <- resolveExt ext + case res of + Just x -> f x + Nothing -> pure Nothing + +evalDouble :: MonadCddl m => CTree (Phase m) -> m (Maybe Double) +evalDouble = \case + Literal (Value var _) + | VFloat16 x <- var -> pure $ Just $ float2Double x + | VFloat32 x <- var -> pure $ Just $ float2Double x + | VFloat64 x <- var -> pure $ Just x + CTreeE ext -> evalExt ext evalDouble + _ -> pure Nothing + +evalInteger :: MonadCddl m => CTree (Phase m) -> m (Maybe Integer) +evalInteger = \case + Literal (Value var _) + | VUInt x <- var -> pure $ Just $ toInteger x + | VNInt x <- var -> pure $ Just $ negate $ toInteger x + | VBignum x <- var -> pure $ Just x + CTreeE ext -> evalExt ext evalInteger + _ -> pure Nothing + +evalArray :: + MonadCddl m => + (CTree (Phase m) -> m (Maybe a)) -> + CTree (Phase m) -> + m (Maybe [a]) +evalArray f = \case + Array es -> sequence <$> traverse f es + CTreeE ext -> evalExt ext $ evalArray f + _ -> error "Expected array" + +evalInterval :: + MonadCddl m => + (CTree (Phase m) -> m (Maybe a)) -> + CTree (Phase m) -> + m (Maybe (Interval a)) +evalInterval f = \case + Range loRule hiRule bound -> do + lo <- f loRule + hi <- f hiRule + let + lBound = ClosedBound <$> lo + uBound = case bound of + ClOpen -> OpenBound <$> hi + Closed -> ClosedBound <$> hi + interval = Interval <$> lBound <*> uBound + pure interval + CTreeE ext -> evalExt ext $ evalInterval f + x -> fmap Interval.singleton <$> f x diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs index 4abef261..ed083ef8 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -95,6 +95,11 @@ instance MonadCddl CBORGen where binds <- asks geLocal pure $ Map.lookup (Name t) binds + resolveExt = \case + GenValidator _ x -> pure $ Just x + GenGenerator _ x -> pure $ Just x + GenRef n -> lookupCddl n + withAntiGen :: (AntiGen a -> AntiGen b) -> CBORGen a -> CBORGen b withAntiGen f (CBORGen m) = CBORGen $ mapReaderT f m diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs index c2eda435..570dee5b 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -128,6 +128,10 @@ instance MonadCddl (ValidatorT b) where binds <- asks veLocal pure $ Map.lookup (Name t) binds + resolveExt = \case + VValidator _ x -> pure $ Just x + VRuleRef n -> lookupCddl n + instance MonadFail (ValidatorT b) where fail msg = failWith $ CustomFailure $ T.pack msg From afe75c2f70365aa211078aeb5e06ed4fbdce50e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 27 Nov 2026 15:32:49 +0200 Subject: [PATCH 34/37] Simplify validator --- golden/refTermTooLong.txt | 9 - src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 305 ++++++++-------------- src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs | 31 ++- src/Codec/CBOR/Cuddle/Interval.hs | 4 + 4 files changed, 139 insertions(+), 210 deletions(-) delete mode 100644 golden/refTermTooLong.txt diff --git a/golden/refTermTooLong.txt b/golden/refTermTooLong.txt deleted file mode 100644 index d0a081d6..00000000 --- a/golden/refTermTooLong.txt +++ /dev/null @@ -1,9 +0,0 @@ -array -└ app: 0 - ref: bar - └ failed to apply required rule: - └ array - └ app: 1 - app: 2 - app: 3 - leftover elements not matched by any rule \ No newline at end of file diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 279c02a2..8c516b8d 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -17,10 +17,20 @@ import Codec.CBOR.Cuddle.CBOR.Canonical (toCanonical) import Codec.CBOR.Cuddle.CDDL hiding (CDDL, Group, Rule) import Codec.CBOR.Cuddle.CDDL.CTree import Codec.CBOR.Cuddle.CDDL.CtlOp -import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..)) +import Codec.CBOR.Cuddle.CDDL.Custom.Core ( + MonadCddl (..), + evalBool, + evalBytes, + evalDouble, + evalInteger, + evalInterval, + evalText, + ) import Codec.CBOR.Cuddle.CDDL.Custom.Validator import Codec.CBOR.Cuddle.CDDL.Phase (MonoSimplePhase, showSimple) import Codec.CBOR.Cuddle.IndexMappable (IndexMappable (..)) +import Codec.CBOR.Cuddle.Interval ((...)) +import Codec.CBOR.Cuddle.Interval qualified as Interval import Codec.CBOR.Read import Codec.CBOR.Term import Control.Applicative (Alternative (..), optional) @@ -37,7 +47,7 @@ import Data.Map.Strict qualified as Map import Data.Maybe import Data.Set qualified as Set import Data.Text qualified as T -import Data.Text.Encoding (encodeUtf8) +import Data.Text.Foreign (lengthWord8) import Data.Text.Lazy qualified as TL import Data.Word import GHC.Float @@ -127,6 +137,16 @@ validateTerm term rule TFloat h -> validateFloat h rule TDouble d -> validateDouble d rule +validateRange :: + (HasCallStack, Ord a) => + a -> + CTree ValidatorPhase -> + (CTree ValidatorPhase -> Validator (Maybe a)) -> + Validator () +validateRange v rule evalElem = do + interval <- expectWellFormed <$> evalInterval evalElem rule + ruleVerdict rule $ Interval.contains interval v + -------------------------------------------------------------------------------- -- Ints and integers @@ -174,45 +194,15 @@ validateInteger i rule = Postlude PTNInt | i >= nintMin && i <= -1 -> accept rule -- a = x - Literal (Value (VUInt i') _) | i == fromIntegral i' -> accept rule - -- a = -x - Literal (Value (VNInt i') _) | -i == fromIntegral i' -> accept rule - -- a = - Literal (Value (VBignum i') _) | i == i' -> accept rule + Literal _ -> do + x <- evalInteger rule + ruleVerdict rule $ x == Just i -- a = foo .ctrl bar Control op tgt ctrl -> validateInteger i tgt >> controlInteger i op ctrl -- a = foo / bar Choice opts -> validateChoice (validateInteger i) opts -- a = x..y - Range low high bound -> - case (low, high) of - (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | n <= i && range bound i m -> accept rule - | otherwise -> reject rule - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | -n <= i && range bound i m -> accept rule - | otherwise -> reject rule - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) - | -n <= i && range bound i (-m) -> accept rule - | otherwise -> reject rule - (Literal (Value VUInt {} _), Literal (Value VNInt {} _)) -> error "range types mismatch" - (Literal (Value (VBignum n) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | n <= i && range bound i m -> accept rule - | otherwise -> reject rule - (Literal (Value (VBignum n) _), Literal (Value (VNInt (fromIntegral -> m)) _)) - | n <= i && range bound i (-m) -> accept rule - | otherwise -> reject rule - (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VBignum m) _)) - | n <= i && range bound i m -> accept rule - | otherwise -> reject rule - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VBignum m) _)) - | (-n) <= i && range bound i m -> accept rule - | otherwise -> reject rule - (CTreeE (VRuleRef n), _) -> - dereferenceNoTrace n $ \lo -> validateInteger i (Range lo high bound) - (_, CTreeE (VRuleRef n)) -> do - dereferenceNoTrace n $ \hi -> validateInteger i (Range low hi bound) - (lo, hi) -> error $ "Unable to validate range: (" <> showSimple lo <> ", " <> showSimple hi <> ")" + Range {} -> validateRange i rule evalInteger -- a = &(x, y, z) Enum g -> case g of @@ -247,9 +237,9 @@ controlInteger :: Validator () controlInteger i op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlInteger i op controlInteger i op ctrl = case op of - Size -> case ctrl of - Literal (Value (VUInt sz) _) -> verdict $ 0 <= i && i < 256 ^ sz - _ -> verdict False + Size -> do + sz <- expectWellFormed <$> evalInteger ctrl + verdict $ Interval.contains (0 ... 256 ^ sz) i Bits -> do indices <- case ctrl of Literal (Value (VUInt i') _) -> pure [i'] @@ -264,39 +254,18 @@ controlInteger i op ctrl = case op of let bitSet = testBit n 0 allowed = not bitSet || IS.member idx indices in allowed && go indices (shiftR n 1) (idx + 1) - Lt -> case ctrl of - Literal (Value (VUInt i') _) -> verdict $ i < fromIntegral i' - Literal (Value (VNInt i') _) -> verdict $ i < -fromIntegral i' - Literal (Value (VBignum i') _) -> verdict $ i < i' - _ -> verdict False - Gt -> case ctrl of - Literal (Value (VUInt i') _) -> verdict $ i > fromIntegral i' - Literal (Value (VNInt i') _) -> verdict $ i > -fromIntegral i' - Literal (Value (VBignum i') _) -> verdict $ i > i' - _ -> verdict False - Le -> case ctrl of - Literal (Value (VUInt i') _) -> verdict $ i <= fromIntegral i' - Literal (Value (VNInt i') _) -> verdict $ i <= -fromIntegral i' - Literal (Value (VBignum i') _) -> verdict $ i <= i' - _ -> verdict False - Ge -> case ctrl of - Literal (Value (VUInt i') _) -> verdict $ i >= fromIntegral i' - Literal (Value (VNInt i') _) -> verdict $ i >= -fromIntegral i' - Literal (Value (VBignum i') _) -> verdict $ i >= i' - _ -> verdict False - Eq -> case ctrl of - Literal (Value (VUInt i') _) -> verdict $ i == fromIntegral i' - Literal (Value (VNInt i') _) -> verdict $ i == -fromIntegral i' - Literal (Value (VBignum i') _) -> verdict $ i == i' - _ -> verdict False - Ne -> case ctrl of - Literal (Value (VUInt i') _) -> verdict $ i /= fromIntegral i' - Literal (Value (VNInt i') _) -> verdict $ i /= -fromIntegral i' - Literal (Value (VBignum i') _) -> verdict $ i /= i' - _ -> verdict False + Lt -> verdictOnControl (i <) + Gt -> verdictOnControl (i >) + Le -> verdictOnControl (i <=) + Ge -> verdictOnControl (i >=) + Eq -> verdictOnControl (i ==) + Ne -> verdictOnControl (i /=) _ -> error $ "unexpected control: " <> showSimple ctrl where verdict = controlVerdict op ctrl + verdictOnControl f = do + x <- expectWellFormed <$> evalInteger ctrl + verdict $ f x -------------------------------------------------------------------------------- -- Floating point (Float16, Float32, Float64) @@ -319,18 +288,17 @@ validateHalf f rule = -- a = float16 Postlude PTHalf -> accept rule -- a = 0.5 - Literal (Value (VFloat16 f') _) | f == f' -> accept rule + Literal _ -> do + x <- evalDouble rule + ruleVerdict rule $ x == Just (float2Double f) -- a = foo / bar Choice opts -> validateChoice (validateHalf f) opts -- a = foo .ctrl bar Control op tgt ctrl -> validateHalf f tgt >> controlHalf f op ctrl -- a = x..y - Range (CTreeE (VRuleRef n)) high bound -> do - dereferenceNoTrace n $ \lo -> validateHalf f $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> do - dereferenceNoTrace n $ \hi -> validateHalf f $ Range low hi bound - Range (Literal (Value (VFloat16 n) _)) (Literal (Value (VFloat16 m) _)) bound - | n <= f && range bound f m -> accept rule + Range {} -> do + interval <- expectWellFormed <$> evalInterval evalDouble rule + ruleVerdict rule $ Interval.contains interval $ float2Double f _ -> reject rule -- | Controls for `Float16` @@ -341,16 +309,19 @@ controlHalf :: CTree ValidatorPhase -> Validator () controlHalf f op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlHalf f op -controlHalf f op ctrl = case op of - Eq -> case ctrl of - Literal (Value (VFloat16 f') _) -> verdict $ f == f' - _ -> verdict False - Ne -> case ctrl of - Literal (Value (VFloat16 f') _) -> verdict $ f /= f' - _ -> verdict False +controlHalf (float2Double -> v) op ctrl = case op of + Lt -> verdictOnControl (v <) + Gt -> verdictOnControl (v >) + Le -> verdictOnControl (v <=) + Ge -> verdictOnControl (v >=) + Eq -> verdictOnControl (v ==) + Ne -> verdictOnControl (v /=) _ -> error $ "Not yet implemented for half: " <> show op where verdict = controlVerdict op ctrl + verdictOnControl f = do + x <- expectWellFormed <$> evalDouble ctrl + verdict $ f x -- | Validating a `Float32` validateFloat :: @@ -367,27 +338,17 @@ validateFloat f rule = -- a = float32 Postlude PTFloat -> accept rule -- a = 0.000000005 - -- TODO: it is unclear if smaller floats should also validate - Literal (Value (VFloat32 f') _) | f == f' -> accept rule + Literal _ -> do + x <- evalDouble rule + ruleVerdict rule $ x == Just (float2Double f) -- a = foo / bar Choice opts -> validateChoice (validateFloat f) opts -- a = foo .ctrl bar Control op tgt ctrl -> validateFloat f tgt >> controlFloat f op ctrl -- a = x..y - -- TODO it is unclear if this should mix floating point types too - Range (CTreeE (VRuleRef n)) high bound -> - dereferenceNoTrace n $ \lo -> validateFloat f $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> - dereferenceNoTrace n $ \hi -> validateFloat f $ Range low hi bound - Range (Literal (Value nv _)) (Literal (Value mv _)) bound - | VFloat16 n <- nv - , VFloat16 m <- mv - , n <= f && range bound f m -> - accept rule - | VFloat32 n <- nv - , VFloat32 m <- mv - , n <= f && range bound f m -> - accept rule + Range {} -> do + interval <- expectWellFormed <$> evalInterval evalDouble rule + ruleVerdict rule $ Interval.contains interval $ float2Double f _ -> reject rule -- | Controls for `Float32` @@ -398,18 +359,19 @@ controlFloat :: CTree ValidatorPhase -> Validator () controlFloat f op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlFloat f op -controlFloat f op ctrl = case op of - Eq -> case ctrl of - Literal (Value (VFloat16 f') _) -> verdict $ f == f' - Literal (Value (VFloat32 f') _) -> verdict $ f == f' - _ -> verdict False - Ne -> case ctrl of - Literal (Value (VFloat16 f') _) -> verdict $ f /= f' - Literal (Value (VFloat32 f') _) -> verdict $ f /= f' - _ -> verdict False - _ -> error $ "Not yet implemented for float: " <> show op +controlFloat (float2Double -> v) op ctrl = case op of + Lt -> verdictOnControl (v <) + Gt -> verdictOnControl (v >) + Le -> verdictOnControl (v <=) + Ge -> verdictOnControl (v >=) + Eq -> verdictOnControl (v ==) + Ne -> verdictOnControl (v /=) + _ -> error $ "Not yet implemented for half: " <> show op where verdict = controlVerdict op ctrl + verdictOnControl f = do + x <- expectWellFormed <$> evalDouble ctrl + verdict $ f x -- | Validating a `Float64` validateDouble :: @@ -434,23 +396,7 @@ validateDouble f rule = Control op tgt ctrl -> validateDouble f tgt >> controlDouble f op ctrl -- a = x..y -- TODO it is unclear if this should mix floating point types too - Range (CTreeE (VRuleRef n)) high bound -> - dereferenceNoTrace n $ \lo -> validateDouble f $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> - dereferenceNoTrace n $ \hi -> validateDouble f $ Range low hi bound - Range (Literal (Value nv _)) (Literal (Value mv _)) bound - | VFloat16 n <- nv - , VFloat16 m <- mv - , float2Double n <= f && range bound f (float2Double m) -> - accept rule - | VFloat32 n <- nv - , VFloat32 m <- mv - , float2Double n <= f && range bound f (float2Double m) -> - accept rule - | VFloat64 n <- nv - , VFloat64 m <- mv - , n <= f && range bound f m -> - accept rule + Range {} -> validateRange f rule evalDouble _ -> reject rule -- | Controls for `Float64` @@ -460,27 +406,23 @@ controlDouble :: CtlOp -> CTree ValidatorPhase -> Validator () -controlDouble f op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlDouble f op -controlDouble f op ctrl = case op of - Eq -> case ctrl of - Literal (Value (VFloat16 f') _) -> verdict $ f == float2Double f' - Literal (Value (VFloat32 f') _) -> verdict $ f == float2Double f' - Literal (Value (VFloat64 f') _) -> verdict $ f == f' - _ -> verdict False - Ne -> case ctrl of - Literal (Value (VFloat16 f') _) -> verdict $ f /= float2Double f' - Literal (Value (VFloat32 f') _) -> verdict $ f /= float2Double f' - Literal (Value (VFloat64 f') _) -> verdict $ f /= f' - _ -> verdict False +controlDouble v op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlDouble v op +controlDouble v op ctrl = case op of + Eq -> verdictOnControl (v ==) + Ne -> verdictOnControl (v /=) _ -> error $ "Not yet implmented for double: " <> show op where verdict = controlVerdict op ctrl + verdictOnControl f = do + x <- expectWellFormed <$> evalDouble ctrl + verdict $ f x -------------------------------------------------------------------------------- -- Bool -- | Validating a boolean validateBool :: + HasCallStack => Bool -> CTree ValidatorPhase -> Validator () @@ -493,7 +435,9 @@ validateBool b rule = -- a = bool Postlude PTBool -> accept rule -- a = true - Literal (Value (VBool b') _) | b == b' -> accept rule + Literal _ -> do + x <- evalBool rule + ruleVerdict rule $ x == Just b -- a = foo .ctrl bar Control op tgt ctrl -> validateBool b tgt >> controlBool b op ctrl -- a = foo / bar @@ -509,15 +453,14 @@ controlBool :: Validator () controlBool b op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlBool b op controlBool b op ctrl = case op of - Eq -> case ctrl of - Literal (Value (VBool b') _) -> verdict $ b == b' - _ -> verdict False - Ne -> case ctrl of - Literal (Value (VBool b') _) -> verdict $ b /= b' - _ -> verdict False + Eq -> verdictOnControl (b ==) + Ne -> verdictOnControl (b /=) _ -> error $ "Not yet implemented for bool: " <> show op where verdict = controlVerdict op ctrl + verdictOnControl f = do + x <- expectWellFormed <$> evalBool ctrl + verdict $ f x -------------------------------------------------------------------------------- -- Simple @@ -562,6 +505,7 @@ validateNull rule = -- | Validating a byte sequence validateBytes :: + HasCallStack => BS.ByteString -> CTree ValidatorPhase -> Validator () @@ -574,7 +518,9 @@ validateBytes bs rule = -- a = bytes Postlude PTBytes -> accept rule -- a = h'123456' - Literal (Value (VBytes bs') _) | bs == bs' -> accept rule + Literal _ -> do + x <- evalBytes rule + ruleVerdict rule $ x == Just bs -- a = foo .ctrl bar Control op tgt ctrl -> validateBytes bs tgt >> controlBytes bs op ctrl -- a = foo / bar @@ -590,23 +536,7 @@ controlBytes :: Validator () controlBytes bs op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlBytes bs op controlBytes bs op ctrl = case op of - Size -> case ctrl of - Literal (Value (VUInt sz) _) | fromIntegral (BS.length bs) == sz -> verdict True - Range (CTreeE (VRuleRef n)) high bound -> - dereferenceNoTrace n $ \lo -> controlBytes bs op $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> do - dereferenceNoTrace n $ \hi -> controlBytes bs op $ Range low hi bound - Range low high bound -> - let i = BS.length bs - in case (low, high) of - (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | boundPlacement i (Just n, Just m) bound == WithinBounds -> verdict True - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | boundPlacement i (Just $ -n, Just m) bound == WithinBounds -> verdict True - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) - | boundPlacement i (Just $ -n, Just $ -m) bound == WithinBounds -> verdict True - _ -> verdict False - _ -> verdict False + Size -> validateRange (toInteger $ BS.length bs) ctrl evalInteger Bits -> do indices <- case ctrl of @@ -643,6 +573,7 @@ controlBytes bs op ctrl = case op of -- | Validating text strings validateText :: + HasCallStack => T.Text -> CTree ValidatorPhase -> Validator () @@ -655,7 +586,9 @@ validateText txt rule = -- a = text Postlude PTText -> accept rule -- a = "foo" - Literal (Value (VText txt') _) | txt == txt' -> accept rule + Literal {} -> do + x <- evalText rule + ruleVerdict rule $ x == Just txt -- a = foo .ctrl bar Control op tgt ctrl -> validateText txt tgt >> controlText txt op ctrl -- a = foo / bar @@ -671,24 +604,7 @@ controlText :: Validator () controlText bs op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlText bs op controlText bs op ctrl = case op of - Size -> - let bsSize = BS.length $ encodeUtf8 bs - in case ctrl of - Literal (Value (VUInt (fromIntegral -> sz)) _) -> verdict $ bsSize == sz - Range (CTreeE (VRuleRef n)) high bound -> - dereferenceNoTrace n $ \lo -> controlText bs op $ Range lo high bound - Range low (CTreeE (VRuleRef n)) bound -> - dereferenceNoTrace n $ \hi -> controlText bs op $ Range low hi bound - Range ff tt bound -> - case (ff, tt) of - (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> - verdict $ n <= T.length bs && range bound bsSize m - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) -> - verdict $ -n <= T.length bs && range bound bsSize m - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) -> - verdict $ -n <= T.length bs && range bound bsSize (-m) - _ -> verdict False - _ -> error "Invalid control value in .size" + Size -> validateRange (toInteger $ lengthWord8 bs) ctrl evalInteger Regexp -> case ctrl of Literal (Value (VText rxp) _) -> case bs =~ rxp :: (T.Text, T.Text, T.Text) of ("", bs', "") -> verdict $ bs == bs' @@ -723,21 +639,6 @@ validateTagged tag term rule = -- -------------------------------------------------------------------------------- -- -- Lists -data BoundPlacement - = BelowBounds - | WithinBounds - | AboveBounds - deriving (Eq, Ord, Show) - -boundPlacement :: Ord a => a -> (Maybe a, Maybe a) -> RangeBound -> BoundPlacement -boundPlacement _ (Nothing, Nothing) _ = WithinBounds -boundPlacement x (Just lo, mHi) bounds - | lo > x = BelowBounds - | otherwise = boundPlacement x (Nothing, mHi) bounds -boundPlacement x (Nothing, Just hi) bounds - | range bounds x hi = WithinBounds - | otherwise = AboveBounds - clampedPred :: (Eq a, Num a, Enum a) => a -> a clampedPred 0 = 0 clampedPred x = pred x @@ -990,6 +891,10 @@ dereference n = withRef n . dereferenceNoTrace n -------------------------------------------------------------------------------- -- Utils -range :: Ord a => RangeBound -> a -> a -> Bool -range Closed = (<=) -range ClOpen = (<) +expectWellFormed :: HasCallStack => Maybe a -> a +expectWellFormed (Just x) = x +expectWellFormed Nothing = error "Rules are not well-formed" + +ruleVerdict :: CTree ValidatorPhase -> Bool -> Validator () +ruleVerdict rule True = accept rule +ruleVerdict rule False = reject rule diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs index c16a2e88..9e15e6e2 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs @@ -4,10 +4,13 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Core ( MonadCddl (..), RuleTerm (..), + evalBool, evalInteger, evalDouble, evalArray, evalInterval, + evalBytes, + evalText, ) where import Codec.CBOR.Cuddle.CDDL (GRef, Name, RangeBound (..), Value (..), ValueVariant (..)) @@ -15,7 +18,9 @@ import Codec.CBOR.Cuddle.CDDL.CTree (CTree (..), XXCTree) import Codec.CBOR.Cuddle.Interval (Interval (..), IntervalBound (..)) import Codec.CBOR.Cuddle.Interval qualified as Interval import Codec.CBOR.Term (Term) +import Data.ByteString (ByteString) import Data.Kind (Type) +import Data.Text (Text) import GHC.Float (float2Double) class Monad m => MonadCddl m where @@ -48,6 +53,12 @@ evalExt ext f = do Just x -> f x Nothing -> pure Nothing +evalBool :: MonadCddl m => CTree (Phase m) -> m (Maybe Bool) +evalBool = \case + Literal (Value (VBool b) _) -> pure $ Just b + CTreeE ext -> evalExt ext evalBool + _ -> pure Nothing + evalDouble :: MonadCddl m => CTree (Phase m) -> m (Maybe Double) evalDouble = \case Literal (Value var _) @@ -74,7 +85,25 @@ evalArray :: evalArray f = \case Array es -> sequence <$> traverse f es CTreeE ext -> evalExt ext $ evalArray f - _ -> error "Expected array" + _ -> pure Nothing + +evalBytes :: + MonadCddl m => + CTree (Phase m) -> + m (Maybe ByteString) +evalBytes = \case + Literal (Value (VBytes bs) _) -> pure $ Just bs + CTreeE ext -> evalExt ext evalBytes + _ -> pure Nothing + +evalText :: + MonadCddl m => + CTree (Phase m) -> + m (Maybe Text) +evalText = \case + Literal (Value (VText t) _) -> pure $ Just t + CTreeE ext -> evalExt ext evalText + _ -> pure Nothing evalInterval :: MonadCddl m => diff --git a/src/Codec/CBOR/Cuddle/Interval.hs b/src/Codec/CBOR/Cuddle/Interval.hs index d2731bf5..7043afbc 100644 --- a/src/Codec/CBOR/Cuddle/Interval.hs +++ b/src/Codec/CBOR/Cuddle/Interval.hs @@ -48,9 +48,13 @@ lessThan x = Interval Unbounded (OpenBound x) (...) :: a -> a -> Interval a lo ... hi = Interval (ClosedBound lo) (OpenBound hi) +infix 5 ... + (..=) :: a -> a -> Interval a lo ..= hi = Interval (ClosedBound lo) (ClosedBound hi) +infix 5 ..= + -- | This function checks whether the interval contains any elements. It does -- not take the bounds of the type into account, it only checks whether the -- lower bound is smaller than the upper bound From 5185391e67f51aed867a7a4d7311dca0f3b62e90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 27 Nov 2026 15:58:56 +0200 Subject: [PATCH 35/37] Fix some bugs --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 8c516b8d..aac7679e 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -40,6 +40,7 @@ import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BSL import Data.Foldable (Foldable (..), asum) import Data.Function (on) +import Data.Functor (($>)) import Data.IntSet qualified as IS import Data.List (maximumBy) import Data.List.NonEmpty qualified as NE @@ -218,13 +219,15 @@ validateInteger i rule = _ -> reject rule where validateBigInt x = case x of + CTreeE (VValidator _ r) -> + -- TODO fix this once we have replaced Term + validateBigInt r CTreeE (VRuleRef n) -> dereference n validateBigInt Postlude PTBytes -> accept rule Control op tgt@(Postlude PTBytes) ctrl -> validateBytes bs tgt >> controlBytes bs op ctrl where - -- TODO figure out a way to turn Integer into bytes or figure out why - -- tagged bigints are decoded as integers in the first place + -- TODO fix this once we have replaced Term bs = mempty _ -> reject rule @@ -670,7 +673,9 @@ validateListBlock terms rules = do matchSingle :: CTree ValidatorPhase -> [Term] -> ValidatorT ListBlock [Term] matchSingle r [] = failWith $ ArrayLeftoverRule $ mapIndex r matchSingle r (t : ts) = case r of - CTreeE (VRuleRef n) -> dereference n $ \ref -> matchSingle ref (t : ts) + CTreeE (VRuleRef n) -> dereferenceNoTrace n $ \case + CTreeE (VValidator _ g@Group {}) -> withRef n $ matchSingle g (t : ts) + _ -> element (validateTerm t r) $> ts CTreeE (VValidator v x) -> do element $ applyCustomValidator v x t pure ts From 2b6031168e1d8992dc7b3a969d616ea4325447c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 27 Nov 2026 17:16:57 +0200 Subject: [PATCH 36/37] Minor fixes --- golden/refTermTooLong.txt | 9 +++++++++ src/Codec/CBOR/Cuddle/Huddle.hs | 1 + 2 files changed, 10 insertions(+) create mode 100644 golden/refTermTooLong.txt diff --git a/golden/refTermTooLong.txt b/golden/refTermTooLong.txt new file mode 100644 index 00000000..bd29faa8 --- /dev/null +++ b/golden/refTermTooLong.txt @@ -0,0 +1,9 @@ +array +└ app: 0 + failed to apply required rule: + └ ref: bar + └ array + └ app: 1 + app: 2 + app: 3 + leftover elements not matched by any rule \ No newline at end of file diff --git a/src/Codec/CBOR/Cuddle/Huddle.hs b/src/Codec/CBOR/Cuddle/Huddle.hs index 6a3d8052..ebfd4f4b 100644 --- a/src/Codec/CBOR/Cuddle/Huddle.hs +++ b/src/Codec/CBOR/Cuddle/Huddle.hs @@ -100,6 +100,7 @@ module Codec.CBOR.Cuddle.Huddle ( -- * Validators withValidator, + withOverrideValidator, -- * Name HasName (..), From 91b60d980e57fab531a9e9342664b9eab3a0d78c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joosep=20J=C3=A4=C3=A4ger?= Date: Fri, 27 Nov 2026 17:37:32 +0200 Subject: [PATCH 37/37] Pass length encoding --- src/Codec/CBOR/Cuddle/CBOR/Validator.hs | 69 ++++++++++++++--------- src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs | 5 ++ 2 files changed, 47 insertions(+), 27 deletions(-) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index aac7679e..64527896 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -18,6 +18,7 @@ import Codec.CBOR.Cuddle.CDDL hiding (CDDL, Group, Rule) import Codec.CBOR.Cuddle.CDDL.CTree import Codec.CBOR.Cuddle.CDDL.CtlOp import Codec.CBOR.Cuddle.CDDL.Custom.Core ( + LengthEncoding (..), MonadCddl (..), evalBool, evalBytes, @@ -38,6 +39,7 @@ import Control.Monad (filterM, void) import Data.Bits hiding (And) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BSL +import Data.ByteString.Lazy qualified as LBS import Data.Foldable (Foldable (..), asum) import Data.Function (on) import Data.Functor (($>)) @@ -49,6 +51,7 @@ import Data.Maybe import Data.Set qualified as Set import Data.Text qualified as T import Data.Text.Foreign (lengthWord8) +import Data.Text.Lazy qualified as LT import Data.Text.Lazy qualified as TL import Data.Word import GHC.Float @@ -122,14 +125,14 @@ validateTerm term rule case term of TInt i -> validateInteger (fromIntegral i) rule TInteger i -> validateInteger i rule - TBytes b -> validateBytes b rule - TBytesI b -> validateBytes (BSL.toStrict b) rule - TString s -> validateText s rule - TStringI s -> validateText (TL.toStrict s) rule - TList ts -> validateList ts rule - TListI ts -> validateList ts rule - TMap ts -> validateMap ts rule - TMapI ts -> validateMap ts rule + TBytes b -> validateBytes DefiniteLength b rule + TBytesI b -> validateBytes IndefiniteLength (BSL.toStrict b) rule + TString s -> validateText DefiniteLength s rule + TStringI s -> validateText IndefiniteLength (TL.toStrict s) rule + TList ts -> validateList DefiniteLength ts rule + TListI ts -> validateList IndefiniteLength ts rule + TMap ts -> validateMap DefiniteLength ts rule + TMapI ts -> validateMap IndefiniteLength ts rule TTagged w t -> validateTagged w t rule TBool b -> validateBool b rule TNull -> validateNull rule @@ -225,7 +228,7 @@ validateInteger i rule = CTreeE (VRuleRef n) -> dereference n validateBigInt Postlude PTBytes -> accept rule Control op tgt@(Postlude PTBytes) ctrl -> - validateBytes bs tgt >> controlBytes bs op ctrl + validateBytes DefiniteLength bs tgt >> controlBytes bs op ctrl where -- TODO fix this once we have replaced Term bs = mempty @@ -509,12 +512,15 @@ validateNull rule = -- | Validating a byte sequence validateBytes :: HasCallStack => + LengthEncoding -> BS.ByteString -> CTree ValidatorPhase -> Validator () -validateBytes bs (CTreeE (VRuleRef n)) = dereference n $ validateBytes bs -validateBytes bs (CTreeE (VValidator v x)) = applyCustomValidator v x $ TBytes bs -validateBytes bs rule = +validateBytes le bs (CTreeE (VRuleRef n)) = dereference n $ validateBytes le bs +validateBytes le bs (CTreeE (VValidator v x)) = applyCustomValidator v x $ case le of + DefiniteLength -> TBytes bs + IndefiniteLength -> TBytesI $ LBS.fromStrict bs +validateBytes le bs rule = case rule of -- a = any Postlude PTAny -> accept rule @@ -525,9 +531,9 @@ validateBytes bs rule = x <- evalBytes rule ruleVerdict rule $ x == Just bs -- a = foo .ctrl bar - Control op tgt ctrl -> validateBytes bs tgt >> controlBytes bs op ctrl + Control op tgt ctrl -> validateBytes le bs tgt >> controlBytes bs op ctrl -- a = foo / bar - Choice opts -> validateChoice (validateBytes bs) opts + Choice opts -> validateChoice (validateBytes le bs) opts _ -> reject rule -- | Controls for byte strings @@ -577,12 +583,15 @@ controlBytes bs op ctrl = case op of -- | Validating text strings validateText :: HasCallStack => + LengthEncoding -> T.Text -> CTree ValidatorPhase -> Validator () -validateText txt (CTreeE (VRuleRef n)) = dereference n $ validateText txt -validateText txt (CTreeE (VValidator v x)) = applyCustomValidator v x $ TString txt -validateText txt rule = +validateText le txt (CTreeE (VRuleRef n)) = dereference n $ validateText le txt +validateText le txt (CTreeE (VValidator v x)) = applyCustomValidator v x $ case le of + DefiniteLength -> TString txt + IndefiniteLength -> TStringI $ LT.fromStrict txt +validateText le txt rule = case rule of -- a = any Postlude PTAny -> accept rule @@ -593,9 +602,9 @@ validateText txt rule = x <- evalText rule ruleVerdict rule $ x == Just txt -- a = foo .ctrl bar - Control op tgt ctrl -> validateText txt tgt >> controlText txt op ctrl + Control op tgt ctrl -> validateText le txt tgt >> controlText txt op ctrl -- a = foo / bar - Choice opts -> validateChoice (validateText txt) opts + Choice opts -> validateChoice (validateText le txt) opts _ -> reject rule -- | Controls for text strings @@ -720,16 +729,19 @@ validateListBlock terms rules = do matchSeq rs remainingTerms validateList :: + LengthEncoding -> [Term] -> CTree ValidatorPhase -> Validator () -validateList terms (CTreeE (VRuleRef n)) = dereference n $ validateList terms -validateList terms (CTreeE (VValidator v x)) = applyCustomValidator v x $ TList terms -validateList terms rule = +validateList le terms (CTreeE (VRuleRef n)) = dereference n $ validateList le terms +validateList le terms (CTreeE (VValidator v x)) = applyCustomValidator v x $ case le of + DefiniteLength -> TList terms + IndefiniteLength -> TListI terms +validateList le terms rule = case rule of Postlude PTAny -> accept rule Array rules -> withArray $ validateListBlock terms rules - Choice opts -> validateChoice (validateList terms) opts + Choice opts -> validateChoice (validateList le terms) opts _ -> reject rule -------------------------------------------------------------------------------- @@ -814,16 +826,19 @@ validateMapBlock terms rules = do validateMap :: HasCallStack => + LengthEncoding -> [(Term, Term)] -> CTree ValidatorPhase -> Validator () -validateMap terms (CTreeE (VRuleRef n)) = dereference n $ validateMap terms -validateMap terms (CTreeE (VValidator v x)) = applyCustomValidator v x $ TMap terms -validateMap terms rule = +validateMap le terms (CTreeE (VRuleRef n)) = dereference n $ validateMap le terms +validateMap le terms (CTreeE (VValidator v x)) = applyCustomValidator v x $ case le of + DefiniteLength -> TMap terms + IndefiniteLength -> TMapI terms +validateMap le terms rule = case rule of Postlude PTAny -> accept rule Map rules -> withMap $ validateMapBlock terms rules - Choice opts -> validateChoice (validateMap terms) opts + Choice opts -> validateChoice (validateMap le terms) opts _ -> reject rule -------------------------------------------------------------------------------- diff --git a/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs index 9e15e6e2..886ae3ef 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs @@ -4,6 +4,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Core ( MonadCddl (..), RuleTerm (..), + LengthEncoding (..), evalBool, evalInteger, evalDouble, @@ -42,6 +43,10 @@ data RuleTerm | GroupTerm [RuleTerm] deriving (Eq, Ord, Show) +data LengthEncoding + = DefiniteLength + | IndefiniteLength + evalExt :: MonadCddl m => XXCTree (Phase m) ->