Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cabal.project
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ test-show-details: streaming
program-options
ghc-options: -Werror

source-repository-package
type: git
location: https://github.com/IntersectMBO/antigen.git
tag: 904fa627b65095ebc128e9e931006fe49e30b991

-- cabal-allow-newer
if impl (ghc >= 9.14)
allow-newer:
Expand Down
140 changes: 113 additions & 27 deletions src/Codec/CBOR/Cuddle/CBOR/Gen.hs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wno-orphans #-}

-- | Generate example CBOR given a CDDL specification
module Codec.CBOR.Cuddle.CBOR.Gen (
Expand All @@ -27,6 +28,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.Validator (validateAgainst)
import Codec.CBOR.Cuddle.CDDL (
GRef (..),
Name (..),
Expand All @@ -37,7 +39,9 @@ import Codec.CBOR.Cuddle.CDDL (
)
import Codec.CBOR.Cuddle.CDDL.CTree (
CTree (..),
CTreeRoot (..),
PTerm (..),
foldCTree,
)
import Codec.CBOR.Cuddle.CDDL.CTree qualified as CTree
import Codec.CBOR.Cuddle.CDDL.CtlOp qualified as CtlOp
Expand All @@ -53,7 +57,13 @@ import Codec.CBOR.Cuddle.CDDL.Custom.Generator (
isIndefiniteAllowed,
withTwiddle,
)
import Codec.CBOR.Cuddle.CDDL.Custom.Validator (
CustomValidatorResult (..),
ValidatorPhase,
runValidator,
)
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
Expand All @@ -65,7 +75,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.Text (Text)
Expand All @@ -89,15 +98,18 @@ import Test.AntiGen (
faultyNum,
reweigh,
runAntiGen,
(#!),
(|!),
(||!),
)
import Test.QuickCheck (
Arbitrary,
NonNegative (..),
shuffle,
)
import Test.QuickCheck qualified as QC
import Test.QuickCheck.Gen (Gen (..), getSize)
import Test.QuickCheck.GenT (MonadGen (..), elements, frequency, listOf, oneof, suchThat, vectorOf)
import Test.QuickCheck.GenT (MonadGen (..), elements, frequency, listOf, oneof, vectorOf)

-- TODO remove this once QuickCheck gets QC
data QC = QC
Expand All @@ -123,6 +135,15 @@ arbitrary = liftGen QC.arbitrary
scale :: MonadGen m => (Int -> Int) -> m a -> m a
scale f m = sized $ \n -> resize (f n) m

suchThat :: Monad m => m a -> (a -> Bool) -> m a
suchThat gen p = go 100
where
go (n :: Int)
| n > 0 = do
v <- gen
if p v then pure v else go $ pred n
| otherwise = error "Failed to generate a fitting value after 100 tries"
Comment thread
Soupstraw marked this conversation as resolved.
Resolved

--------------------------------------------------------------------------------
-- Generator infrastructure
--------------------------------------------------------------------------------
Expand Down Expand Up @@ -327,6 +348,7 @@ annotateTerm = \case
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 -> CBORGen RuleTerm
genForCTree node = annotateTerm node $ case node of
Expand All @@ -348,6 +370,13 @@ genForCTree node = annotateTerm node $ case node of
CTree.Tag t n -> genTag t n
CTree.CTreeE (GenRef n) -> genForNode n
CTree.CTreeE (GenGenerator gen _) -> gen
CTree.CTreeE (GenValidator _ x) -> genForCTree x

isInvalidAgainstNode :: CTreeRoot GenPhase -> Term -> CTree GenPhase -> Bool
isInvalidAgainstNode cTreeRoot term node =
case runValidator (validateAgainst term $ mapIndex node) (mapIndex cTreeRoot) of
CustomValidatorSuccess -> False
CustomValidatorFailure {} -> True

-- | Generate a map from a list of nodes
genMap ::
Expand All @@ -360,26 +389,40 @@ genMap nodes = do
elemsNeeded _ = 0

tryGenKV ::
Int -> Map.Map Term a -> CTree GenPhase -> CTree GenPhase -> CBORGen (Maybe (Term, Term))
tryGenKV nTries m kNode vNode = go nTries
Int -> [(Term, Term)] -> CTree GenPhase -> CTree GenPhase -> CBORGen (Maybe (Term, Term))
tryGenKV nTries m kNode vNode
| null m = go nTries
| otherwise =
go nTries
||! oneof
[ reuseKey #! "duplicateKey"
, reuseKeyValue #! "duplicateKV"
]
where
canonicalKeys = toCanonical <$> Map.keys m
canonicalKeys = toCanonical . fst <$> m
unS (SingleTerm x) = x
unS x = error $ "Expected single, got " <> show x
genFromNode n = unS <$> scale (`div` 2) (genForCTree n)
go !n
| n > 0 = do
k <- unS <$> scale (`div` 2) (annotate "key" $ genForCTree kNode)
k <- genFromNode kNode #! "key"
if toCanonical k `notElem` canonicalKeys
then do
v <- unS <$> scale (`div` 2) (annotate "value" $ genForCTree vNode)
v <- genFromNode vNode #! "value"
pure $ Just (k, v)
else go (n - 1)
| otherwise = pure Nothing
reuseKey = do
k <- elements $ fst <$> m
v <- genFromNode vNode #! "value"
pure $ Just (k, v)
reuseKeyValue = Just <$> elements m

genNodes :: Int -> Map.Map Term Term -> [CTree GenPhase] -> CBORGen (Maybe (Map.Map Term Term))
genNodes :: Int -> [(Term, Term)] -> [CTree GenPhase] -> CBORGen (Maybe [(Term, Term)])
genNodes _ m [] = pure $ Just m
genNodes !i !m (n : ns) =
let
ann :: CBORGen a -> CBORGen a
ann = annotate (T.pack $ show i)
-- A term was produced, advance the index
next x y = scale (\s -> max 0 (s - 1)) $ genNodes (i + 1) x y
Expand All @@ -392,39 +435,60 @@ genMap nodes = do
KV kNode vNode _ -> do
mKV <- ann $ tryGenKV 100 m kNode vNode
case mKV of
Just (k, v) -> next (Map.insert k v m) ns
Just (k, v) -> next ((k, v) : m) ns ||! same m ns
Nothing -> pure Nothing
Occur kv@(KV kNode vNode _) oi -> case oi of
OIOptional -> do
mt <- optGenKV kNode vNode
case mt of
Just (k, v) -> next (Map.insert k v m) ns
Just (k, v) -> next ((k, v) : m) ns
Nothing -> same m ns
OIZeroOrMore -> do
mt <- optGenKV kNode vNode
case mt of
Just (k, v) -> next (Map.insert k v m) (n : ns)
Just (k, v) -> next ((k, v) : m) (n : ns)
Nothing -> same m ns
OIOneOrMore -> genNodes i m (kv : Occur kv OIZeroOrMore : ns)
OIOneOrMore ->
( do
mKV <- ann $ tryGenKV 100 m kNode vNode
case mKV of
Just (k, v) -> next ((k, v) : m) (Occur kv OIZeroOrMore : ns)
Nothing -> pure Nothing
)
||! same m ns
OIBounded mlb mub -> do
sz <- fromIntegral <$> liftGen getSize
let
clampedPred 0 = 0
clampedPred x = x - 1
newLow = clampedPred <$> mlb
newHigh = clampedPred <$> mub
res
| maybe False (> 0) mlb = genNodes i m (kv : Occur kv (OIBounded newLow newHigh) : ns)
| maybe False (< 1) mub = same m ns
lowerBound = fromMaybe 0 mlb
upperBound = fromMaybe (max lowerBound sz) mub
outerBound = maybe upperBound (max sz . succ) mub
genElems i' m' nElems
| nElems <= 0 =
scale (\s -> max 0 (s - 1)) $ genNodes (i' + 1) m' ns
| otherwise = do
mt <- optGenKV kNode vNode
case mt of
Just (k, v) -> next (Map.insert k v m) (Occur kv (OIBounded newLow newHigh) : ns)
Nothing -> same m ns
res
mKV <- annotate (T.pack $ show i') $ tryGenKV 100 m' kNode vNode
case mKV of
Just (k, v) -> genElems (i' + 1) ((k, v) : m') $ nElems - 1
Nothing -> pure Nothing

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Return what we have if we are inside valid range

nElems <- antiChoose (lowerBound, upperBound) (0, outerBound)
genElems i m nElems
node -> error $ "Unexpected node: " <> showSimple node
mItems <- genNodes 0 Map.empty $ sortOn (Down . elemsNeeded) nodes
mItems <- genNodes 0 [] $ sortOn (Down . elemsNeeded) nodes
case mItems of
Just items -> SingleTerm <$> twiddleMap (Map.toList items)
Just items -> do
cTreeRoot <- asks $ gcRoot . geConfig
items' <-
pure items ||! do
let
keyIsInvalidAgainstNode term = \case
KV kNode _ _ -> isInvalidAgainstNode cTreeRoot term kNode
Occur x _ -> keyIsInvalidAgainstNode term x
node -> error $ "Unexpected node: " <> showSimple node
junkKV <-
(,) <$> (genTerm `suchThat` \t -> all (keyIsInvalidAgainstNode t) nodes) <*> genTerm
pure $ junkKV : items
shuffledItems <- liftGen $ shuffle items'
Comment thread
Soupstraw marked this conversation as resolved.
Resolved
SingleTerm <$> twiddleMap shuffledItems
Nothing -> error "Failed to generate unique keys for map after max retries"

-- | Generate an array from a list of nodes
Expand All @@ -437,7 +501,18 @@ genArray nodes = do
[0 :: Int ..]
nodes
case items of
Just ts -> SingleTerm <$> twiddleArray ts
Just ts -> do
cTreeRoot <- asks $ gcRoot . geConfig
SingleTerm
<$> twiddleArray ts ||! do
let
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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recheck only against the unused rules, not against all the rules

Nothing -> error "Something weird happened which shouldn't be possible"

-- | Generate a key-value pair
Expand Down Expand Up @@ -649,3 +724,14 @@ valueVariantToTerm (VFloat64 i) = pure $ TDouble i
valueVariantToTerm (VText t) = twiddleText t
valueVariantToTerm (VBytes b) = twiddleBytes b
valueVariantToTerm (VBool b) = pure $ TBool b

instance IndexMappable CTree GenPhase ValidatorPhase where
mapIndex = foldCTree mapExt mapIndex
where
mapExt = \case
GenRef n -> CTreeE $ VRuleRef n
GenGenerator _ x -> mapIndex x
GenValidator v x -> CTreeE . VValidator v $ mapIndex x

instance IndexMappable CTreeRoot GenPhase ValidatorPhase where
mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m
1 change: 1 addition & 0 deletions src/Codec/CBOR/Cuddle/CBOR/Validator.hs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ module Codec.CBOR.Cuddle.CBOR.Validator (
validateCBOR,
validateFromName,
validateFromGRef,
validateAgainst,
ValidatorPhase,
ValidateCBORError (..),
) where
Expand Down
2 changes: 2 additions & 0 deletions src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator (
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 Control.Monad.Reader (MonadReader (..), MonadTrans (..), ReaderT (..), asks, mapReaderT)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
Expand Down Expand Up @@ -148,6 +149,7 @@ withLocalGenBindings binds =
data instance XXCTree GenPhase
= GenRef Name
| GenGenerator (CBORGen RuleTerm) (CTree GenPhase)
| GenValidator TermValidator (CTree GenPhase)

class HasGenerator a where
generatorL :: Lens' a (Maybe (CBORGen RuleTerm))
3 changes: 1 addition & 2 deletions src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Validator (
) where

import Codec.CBOR.Cuddle.CDDL (GRef (..), Name (..))
import Codec.CBOR.Cuddle.CDDL.CTree (CTree, CTreeRoot (..))
import Codec.CBOR.Cuddle.CDDL.CTree (CTree, CTreeRoot (..), XXCTree)
import Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm)
import Codec.CBOR.Cuddle.CDDL.Custom.Generator (XXCTree)
import Control.Monad.Reader (MonadReader (..), ReaderT (..), asks)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
Expand Down
7 changes: 4 additions & 3 deletions src/Codec/CBOR/Cuddle/CDDL/Resolve.hs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ instance IndexMappable CTree MonoReferenced GenPhase where
where
mapExt (MRuleRef n) = CTreeE $ GenRef n
mapExt (MGenerator g x) = CTreeE $ GenGenerator g (mapIndex x)
mapExt (MValidator _ x) = mapIndex x
mapExt (MValidator v x) = CTreeE $ GenValidator v (mapIndex x)

instance IndexMappable CTreeRoot MonoReferenced GenPhase where
mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m
Expand Down Expand Up @@ -387,9 +387,9 @@ postludeBinding =
]

data BindingEnv i j = BindingEnv
{ global :: Map.Map (Name) (ProvidedParameters (CTree i))
{ global :: Map.Map Name (ProvidedParameters (CTree i))
-- ^ Global name bindings via 'RuleDef'
, local :: Map.Map (Name) (CTree j)
, local :: Map.Map Name (CTree j)
-- ^ Local bindings for generic parameters
}
deriving (Generic)
Expand Down Expand Up @@ -507,6 +507,7 @@ instance IndexMappable CTree GenPhase MonoSimplePhase where
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
Expand Down
Loading