diff --git a/bin/Main.hs b/bin/Main.hs index 26c57393..6078569c 100644 --- a/bin/Main.hs +++ b/bin/Main.hs @@ -6,27 +6,25 @@ 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 (..), - 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, - twiddleAll, - twiddleNothing, + ) +import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( + Evidenced (..), + SValidity (..), + TraceOptions (..), + prettyStepTrace, ) 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) @@ -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 @@ -456,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/cuddle.cabal b/cuddle.cabal index 5aa377a1..ad218c68 100644 --- a/cuddle.cabal +++ b/cuddle.cabal @@ -39,21 +39,21 @@ 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 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 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/example/Main.hs b/example/Main.hs index 7e0c08bb..ee7118a8 100644 --- a/example/Main.hs +++ b/example/Main.hs @@ -5,12 +5,13 @@ 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.Resolve (MonoSimplePhase, fullResolveCDDL) +import Codec.CBOR.Cuddle.CBOR.Generator (generateFromName) +import Codec.CBOR.Cuddle.CDDL (Name (..), mapCDDLDropExt) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) +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) @@ -49,7 +50,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/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/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/Generator.hs similarity index 60% rename from src/Codec/CBOR/Cuddle/CBOR/Gen.hs rename to src/Codec/CBOR/Cuddle/CBOR/Generator.hs index 1eaec336..3342b9e6 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, @@ -23,12 +23,24 @@ module Codec.CBOR.Cuddle.CBOR.Gen ( twiddleMap, twiddleText, twiddleBytes, + + -- * Generator helpers + genNBytes, + genNBytesText, + genBytes, + genText, + genInteger, + genTerm, ) where #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.CBOR.Canonical ( + nintMin, + toCanonical, + uintMax, + ) +import Codec.CBOR.Cuddle.CBOR.Validator (validateTerm) import Codec.CBOR.Cuddle.CDDL ( GRef (..), Name (..), @@ -45,29 +57,50 @@ 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 (..), GenEnv (..), GenPhase, - TwiddleConfig (..), - TwiddlePolicy (..), - isDefiniteAllowed, - isIndefiniteAllowed, - withTwiddle, + TermGenerator (..), + bindGen, + constrain, + deferGen, + genFromInterval, + rangeInInterval, + simpleGen, ) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator qualified as Gen import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( - CustomValidatorResult (..), + Evidenced (..), + SValidity (..), + ValidateEnv (..), 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 (..), + 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 -import Control.Monad (zipWithM, (<=<)) +import Control.Monad (forM, zipWithM) import Control.Monad.Reader (asks) import Data.ByteString (ByteString) import Data.ByteString.Lazy qualified as LBS @@ -75,8 +108,9 @@ 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) import Data.Text qualified as T import Data.Text.Internal.Encoding.Utf8 (utf8Length) @@ -85,10 +119,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) import GHC.Stack (HasCallStack) -import Numeric.Half (Half (..), fromHalf) -import Prettyprinter (Pretty (..), layoutCompact) -import Prettyprinter.Render.Text (renderStrict) +import Numeric.Half (fromHalf, toHalf) import System.Random.Stateful (Random, StatefulGen (..), runStateGen_, uniformByteStringM) import Test.AntiGen ( MonadAntiGen (..), @@ -159,30 +192,51 @@ 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 - -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] +genHalf :: TermGenerator Float +genHalf = go universe mempty + where + go rng exclude = + TermGenerator + { tgGenerator = + let gen = do + 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 $ deferGen $ do + -- TODO think about the edges + rng' <- forM cRng $ fmap (double2Float . fromJust) . evalDouble + pure $ go (rng `intersect` rng') exclude + Gen.Eq term -> Just $ deferGen $ do + x <- fromJust <$> evalDouble term + pure $ go (rng `intersect` Interval.singleton (double2Float x)) exclude + Gen.Neq term -> Just $ deferGen $ do + x <- fromJust <$> evalDouble term + pure $ go rng $ Set.insert (double2Float x) exclude + _ -> Nothing + } + +genTwiddled :: + (a -> Term) -> + (a -> Term) -> + a -> + CBORGen Term +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 = @@ -201,7 +255,7 @@ genTerm = , TBool <$> arbitrary , pure TNull , TSimple <$> elements simple - , THalf <$> genHalf + , THalf <$> tgGenerator genHalf , TFloat <$> arbitrary , TDouble <$> arbitrary ] @@ -212,10 +266,39 @@ 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 +-- | 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 `intersect` lessThanOrEqual sz + +genBytes :: TermGenerator ByteString +genBytes = go Nothing $ greaterThanOrEqual 0 + where + go mCbor szRange = + TermGenerator + { tgGenerator = + 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 <- fromJust <$> evalInterval evalInteger rngRule + pure $ go mCbor $ szRange `intersect` fmap fromIntegral newRange + Gen.Cbor cbor + -- Only allow constraining with .cbor once + | Nothing <- mCbor -> Just $ go (Just cbor) szRange + _ -> Nothing + } genCharAtMostBytes :: MonadGen m => Int -> m Char genCharAtMostBytes 1 = chr <$> choose (0x00, 0x7F) @@ -236,18 +319,39 @@ genNBytesText n = do builder <- go n mempty pure . LT.toStrict $ toLazyText builder -genText :: MonadGen m => m Text -genText = sized $ \sz -> genNBytesText =<< choose (0, sz) +genText :: TermGenerator Text +genText = go $ greaterThanOrEqual 0 + where + go sizeRange = + TermGenerator + { tgGenerator = sized $ \sz -> do + n <- genFromInterval $ capAtSize sz sizeRange + genNBytesText n + , tgConstrain = \case + Gen.Size rngRule -> Just $ deferGen $ do + newRange <- fromJust <$> evalInterval evalInteger rngRule + pure . go $ sizeRange `intersect` fmap fromIntegral newRange + _ -> Nothing + } -- | Primitive types defined by the CDDL specification, with their generators -genPostlude :: PTerm -> CBORGen Term -genPostlude pt = genPTerm =<< faultyPTerm pt +genPostlude :: PTerm -> TermGenerator Term +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 @@ -255,26 +359,55 @@ 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 -> 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 -> twiddleBytes =<< genBytes - PTText -> twiddleText =<< genText - PTAny -> genTerm - PTNil -> pure TNull - PTUndefined -> pure $ TSimple 23 + +genInteger :: Interval Integer -> (Integer, Integer) -> TermGenerator Integer +genInteger validRng invalidRng = go validRng mempty + where + go validInterval excluded = + TermGenerator + { tgGenerator = + rangeInInterval invalidRng validInterval `suchThat` (`Set.notMember` excluded) + , tgConstrain = \case + Gen.Size szRule -> Just $ deferGen $ do + sz <- fromJust <$> evalInteger szRule + pure $ go (validInterval `intersect` lessThanOrEqual (2 ^ sz)) excluded + Gen.Range intRule -> Just $ deferGen $ do + int <- traverse (fmap fromJust . evalInteger) intRule + pure $ go (validInterval `intersect` int) excluded + Gen.Eq r -> Just $ deferGen $ do + x <- fromJust <$> evalInteger r + pure $ go (validInterval `intersect` Interval.singleton x) excluded + Gen.Neq r -> Just $ deferGen $ do + x <- fromJust <$> evalInteger r + pure $ go validInterval $ Set.insert x excluded + _ -> Nothing + } + +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 -> 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 -> bindGen twiddleBytes genBytes + PTText -> bindGen twiddleText genText + PTAny -> simpleGen genTerm + PTNil -> simpleGen $ pure TNull + PTUndefined -> simpleGen $ pure $ TSimple 23 + where + outOfBounds = (2 * nintMin, 2 * uintMax) -------------------------------------------------------------------------------- -- Kinds of terms @@ -304,13 +437,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) @@ -329,59 +455,40 @@ 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 :: CTree GenPhase -> CBORGen a -> CBORGen 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 -> CBORGen RuleTerm -genForCTree node = annotateTerm node $ case node of +genForCTree :: HasCallStack => CTree GenPhase -> TermGenerator RuleTerm +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) - 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 _) -> gen + CTree.CTreeE (GenGenerator gen n) -> gen $ genForCTree n 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 + 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 :: - 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 @@ -402,7 +509,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" @@ -492,34 +599,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 _ -> @@ -537,8 +647,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 @@ -561,74 +671,58 @@ 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 = deferGen $ do + pure $ constrain (constraint controller) (genForCTree target) + where + 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 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 -> 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 + 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}) $ genForCTree node - _ -> 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 + | 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 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 -- | Take a reference and resolve it to the relevant Tree, following multiple -- links if necessary. @@ -655,7 +749,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 $ @@ -671,7 +765,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) @@ -689,26 +783,25 @@ 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 + 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 :: ValueVariant -> CBORGen Term valueVariantToTerm (VUInt i) diff --git a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs index 5999860f..64527896 100644 --- a/src/Codec/CBOR/Cuddle/CBOR/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CBOR/Validator.hs @@ -2,68 +2,61 @@ {-# 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 ( - ControlInfo (..), - Evidenced (..), - IsValidationTrace (..), - ListValidationTrace (..), - MapValidationTrace (..), - SValidity (..), - ValidationTrace (..), - compareEvidencedProgress, - evidence, - isValid, - mapTrace, - ) +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.Validator ( - CustomValidatorResult (..), - TermValidator, - ValidateEnv (..), - Validator, - ValidatorPhase, - XXCTree (..), - runValidator, +import Codec.CBOR.Cuddle.CDDL.Custom.Core ( + LengthEncoding (..), + MonadCddl (..), + evalBool, + evalBytes, + evalDouble, + evalInteger, + evalInterval, + evalText, ) -import Codec.CBOR.Cuddle.CDDL.Resolve (showSimple) +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.Monad.Reader (asks) -import Data.Bifunctor (Bifunctor (..)) +import Control.Applicative (Alternative (..), optional) +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.Function (on, (&)) +import Data.ByteString.Lazy qualified as LBS +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 (NonEmpty (..)) 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.Foreign (lengthWord8) +import Data.Text.Lazy qualified as LT 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 @@ -78,13 +71,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 (validateTerm term rule) $ ValidateEnv cddl mempty Nothing -> Left $ RuleDoesNotExist ruleName | otherwise -> Left $ LeftoverBytes rest @@ -96,7 +89,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 @@ -107,15 +100,14 @@ validateFromGRef ref term = do mRule <- lookupGRef ref case mRule of Nothing -> fail $ "Unbound generic reference: " <> show ref - Just rule -> validateAgainst term rule + Just rule -> validateTerm 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 +applyCustomValidator :: + (TermValidator -> TermValidator) -> + CTree ValidatorPhase -> + Term -> + Validator () +applyCustomValidator f x = f (`validateTerm` x) -------------------------------------------------------------------------------- -- Terms @@ -123,52 +115,41 @@ 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 = - runCustomValidator cddl (SingleTerm term) v + Validator () +validateTerm term rule + | CTreeE (VRuleRef n) <- rule = dereference n $ validateTerm term + | CTreeE (VValidator f x) <- rule = applyCustomValidator f x 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 - --- | 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 + TInt i -> validateInteger (fromIntegral i) rule + TInteger i -> validateInteger i 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 + TSimple s -> validateSimple s rule + THalf h -> validateHalf h 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 @@ -186,14 +167,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 _) -> runCustomValidator cddl (SingleTerm $ TInteger i) v + CTreeE (VRuleRef n) -> dereference n $ validateInteger 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 @@ -207,147 +187,91 @@ 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 - -- a = -x - Literal (Value (VNInt i') _) | -i == fromIntegral i' -> terminal rule - -- a = - Literal (Value (VBignum i') _) | i == i' -> terminal rule + Literal _ -> do + x <- evalInteger rule + ruleVerdict rule $ x == Just i -- 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 - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VUInt (fromIntegral -> m)) _)) - | -n <= i && range bound i m -> terminal rule - | otherwise -> unapplicable rule - (Literal (Value (VNInt (fromIntegral -> n)) _), Literal (Value (VNInt (fromIntegral -> m)) _)) - | -n <= i && range bound i (-m) -> terminal rule - | otherwise -> unapplicable 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 - (Literal (Value (VBignum n) _), Literal (Value (VNInt (fromIntegral -> m)) _)) - | n <= i && range bound i (-m) -> terminal rule - | otherwise -> unapplicable rule - (Literal (Value (VUInt (fromIntegral -> n)) _), Literal (Value (VBignum m) _)) - | n <= i && range bound i m -> terminal rule - | otherwise -> unapplicable 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) - (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 - CTreeE (VRuleRef n) -> dereferenceAndValidate cddl n $ validateInteger cddl i - Group g' -> validateInteger cddl i (Choice (NE.fromList g')) + CTreeE (VRuleRef n) -> dereference n $ validateInteger i + 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 (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 -> - ctrlDispatch (validateBytes cddl bs) op tgt ctrl (controlBytes cddl bs) + validateBytes DefiniteLength 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 - _ -> 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)) = dereferenceNoTrace n $ controlInteger i op +controlInteger i op ctrl = case op of + 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'] + 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 -> verdictOnControl (i <) + Gt -> verdictOnControl (i >) + Le -> verdictOnControl (i <=) + Ge -> verdictOnControl (i >=) + Eq -> verdictOnControl (i ==) + Ne -> verdictOnControl (i /=) + _ -> 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 + verdictOnControl f = do + x <- expectWellFormed <$> evalInteger ctrl + verdict $ f x -------------------------------------------------------------------------------- -- Floating point (Float16, Float32, Float64) @@ -358,334 +282,284 @@ 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 _)) = runCustomValidator cddl (SingleTerm $ THalf f) v -validateHalf cddl f rule = + Validator () +validateHalf f (CTreeE (VRuleRef n)) = dereference n $ validateHalf f +validateHalf f (CTreeE (VValidator v x)) = applyCustomValidator v x $ 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 _ -> do + x <- evalDouble rule + ruleVerdict rule $ x == Just (float2Double f) -- 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 (Literal (Value (VFloat16 n) _)) (Literal (Value (VFloat16 m) _)) bound - | n <= f && range bound f m -> terminal rule - _ -> unapplicable rule + Range {} -> do + interval <- expectWellFormed <$> evalInterval evalDouble rule + ruleVerdict rule $ Interval.contains interval $ float2Double f + _ -> 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)) = dereferenceNoTrace n $ controlHalf f op +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 :: 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 _)) = runCustomValidator cddl (SingleTerm $ TFloat f) v -validateFloat cddl f rule = + Validator () +validateFloat f (CTreeE (VRuleRef n)) = dereference n $ validateFloat f +validateFloat f (CTreeE (VValidator v x)) = applyCustomValidator v x $ 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 _ -> do + x <- evalDouble rule + ruleVerdict rule $ x == Just (float2Double f) -- 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 (Literal (Value nv _)) (Literal (Value mv _)) bound - | VFloat16 n <- nv - , VFloat16 m <- mv - , n <= f && range bound f m -> - terminal rule - | VFloat32 n <- nv - , VFloat32 m <- mv - , n <= f && range bound f m -> - terminal rule - _ -> unapplicable rule + Range {} -> do + interval <- expectWellFormed <$> evalInterval evalDouble rule + ruleVerdict rule $ Interval.contains interval $ float2Double f + _ -> 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)) = dereferenceNoTrace n $ controlFloat f 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 :: 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 _)) = runCustomValidator cddl (SingleTerm $ TDouble f) v -validateDouble cddl f rule = + Validator () +validateDouble f (CTreeE (VRuleRef n)) = dereference n $ validateDouble f +validateDouble f (CTreeE (VValidator v x)) = applyCustomValidator v x $ 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 (Literal (Value nv _)) (Literal (Value mv _)) bound - | VFloat16 n <- nv - , VFloat16 m <- mv - , float2Double n <= f && range bound f (float2Double m) -> - terminal rule - | VFloat32 n <- nv - , VFloat32 m <- mv - , float2Double n <= f && range bound f (float2Double m) -> - terminal rule - | VFloat64 n <- nv - , VFloat64 m <- mv - , n <= f && range bound f m -> - terminal rule - _ -> unapplicable rule + Range {} -> validateRange f rule evalDouble + _ -> 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 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 :: - CTreeRoot ValidatorPhase -> + HasCallStack => Bool -> CTree ValidatorPhase -> - 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 rule = + Validator () +validateBool b (CTreeE (VRuleRef n)) = dereference n $ validateBool b +validateBool b (CTreeE (VValidator v x)) = applyCustomValidator v x $ 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 _ -> do + x <- evalBool rule + ruleVerdict rule $ x == Just b -- 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)) = dereferenceNoTrace n $ controlBool b op +controlBool b op ctrl = case op of + 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 -- | 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 _)) = runCustomValidator cddl (SingleTerm $ TSimple i) v -validateSimple cddl 23 rule = + Validator () +validateSimple i (CTreeE (VRuleRef n)) = dereference n $ validateSimple i +validateSimple i (CTreeE (VValidator v x)) = applyCustomValidator v x $ 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 _)) = runCustomValidator cddl (SingleTerm TNull) v -validateNull cddl rule = +validateNull :: + CTree ValidatorPhase -> Validator () +validateNull (CTreeE (VRuleRef n)) = dereference n validateNull +validateNull (CTreeE (VValidator v x)) = applyCustomValidator v x 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 _)) = runCustomValidator cddl (SingleTerm $ TBytes bs) v -validateBytes cddl bs rule = + HasCallStack => + LengthEncoding -> + BS.ByteString -> + CTree ValidatorPhase -> + Validator () +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 -> 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 _ -> do + x <- evalBytes rule + ruleVerdict rule $ x == Just bs -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateBytes cddl bs) op tgt ctrl (controlBytes cddl bs) + Control op tgt ctrl -> validateBytes le bs tgt >> controlBytes bs op ctrl -- a = foo / bar - Choice opts -> validateChoice (validateBytes cddl bs) opts - _ -> unapplicable rule + Choice opts -> validateChoice (validateBytes le 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 - 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 = + Validator () +controlBytes bs op (CTreeE (VRuleRef n)) = dereferenceNoTrace n $ controlBytes bs op +controlBytes bs op ctrl = case op of + Size -> validateRange (toInteger $ BS.length bs) ctrl evalInteger + 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 @@ -693,426 +567,354 @@ 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) -> 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) -> withCborseqControl ctrl $ validateListBlock terms [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 -> + HasCallStack => + LengthEncoding -> T.Text -> CTree ValidatorPhase -> - 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 rule = + Validator () +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 -> 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 {} -> do + x <- evalText rule + ruleVerdict rule $ x == Just txt -- a = foo .ctrl bar - Control op tgt ctrl -> ctrlDispatch (validateText cddl txt) op tgt ctrl (controlText cddl txt) + Control op tgt ctrl -> validateText le txt tgt >> controlText txt op ctrl -- a = foo / bar - Choice opts -> validateChoice (validateText cddl txt) opts - _ -> unapplicable rule + Choice opts -> validateChoice (validateText le 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)) = dereferenceNoTrace n $ controlText bs op +controlText bs op ctrl = case op of + 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' + _ -> 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 _)) = runCustomValidator cddl (SingleTerm $ TTagged tag term) v -validateTagged cddl tag term rule = + Word64 -> + Term -> + CTree ValidatorPhase -> + Validator () +validateTagged tag term (CTreeE (VRuleRef n)) = dereference n $ validateTagged tag term +validateTagged tag term (CTreeE (VValidator v x)) = applyCustomValidator v x $ 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 -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 - | 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 + +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 -decrementBounds :: (Maybe Word64, Maybe Word64) -> OccurrenceIndicator -decrementBounds (lb, ub) = OIBounded (clampedPred <$> lb) (clampedPred <$> ub) +validateListBlock :: + [Term] -> + [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 - clampedPred 0 = 0 - clampedPred x = pred x + matchSingle :: CTree ValidatorPhase -> [Term] -> ValidatorT ListBlock [Term] + matchSingle r [] = failWith $ ArrayLeftoverRule $ mapIndex r + matchSingle r (t : ts) = case r of + 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 + KV _ v _ -> matchSingle v (t : ts) + Group rs -> matchSeq rs (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 + | otherwise = do + remainingTerms <- matchSingle r ts + matchBounded newLo newHi r remainingTerms + where + withinBounds = lo == 0 + canConsumeMore = maybe True (> 0) mHi + + newLo = clampedPred lo + newHi = clampedPred <$> 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 validateList :: - CTreeRoot ValidatorPhase -> + LengthEncoding -> [Term] -> CTree ValidatorPhase -> - 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 rule = + Validator () +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 -> terminal 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 - _ -> unapplicable rule - where - validate :: - ([CTree ValidatorPhase] -> [Term] -> Evidenced ListValidationTrace) -> - [CTree ValidatorPhase] -> - [Term] -> - [CTree ValidatorPhase] -> - (Evidenced ListValidationTrace, [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 + Postlude PTAny -> accept rule + Array rules -> withArray $ validateListBlock terms rules + Choice opts -> validateChoice (validateList le terms) opts + _ -> reject rule - 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) +-------------------------------------------------------------------------------- +-- Maps - 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) +validateMapBlock :: + [(Term, Term)] -> + [CTree ValidatorPhase] -> + ValidatorT MapBlock () +validateMapBlock terms rules = do + checkDuplicates $ toCanonical . fst <$> terms + _ <- matchSeq [] rules terms + pure () + 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 - 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, 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 + 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" + KV kr vr _ -> do + entry (validateTerm k kr) (validateTerm v vr) + pure tt + Group rs -> matchSeq [] rs 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) --------------------------------------------------------------------------------- --- Maps + matchSeq :: + [CTree ValidatorPhase] -> + [CTree ValidatorPhase] -> + [(Term, Term)] -> + ValidatorT MapBlock [(Term, Term)] + matchSeq tried rs [] = do + let + checkUnsatisfied = \case + CTreeE (VRuleRef n) -> dereference n checkUnsatisfied + 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 <> rs) + case unappliedRules of + [] -> pure [] + x : xs -> failWith $ MapUnappliedRules $ mapIndex <$> x NE.:| xs + 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 + matchSeq [] (reverse tried <> maybeToList r' <> rs) rest + ) + <|> matchSeq (r : tried) rs ts validateMap :: HasCallStack => - CTreeRoot ValidatorPhase -> + LengthEncoding -> [(Term, Term)] -> CTree ValidatorPhase -> - 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 rule = + Validator () +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 -> terminal rule - Map rules -> mapTrace MapTrace $ validate [] terms rules mempty - Choice opts -> validateChoice (validateMap cddl terms) opts - _ -> unapplicable rule - where - validate :: - [CTree ValidatorPhase] -> - [(Term, Term)] -> - [CTree ValidatorPhase] -> - Set CanonicalTerm -> - Evidenced MapValidationTrace - 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 + Postlude PTAny -> accept rule + Map rules -> withMap $ validateMapBlock terms rules + Choice opts -> validateChoice (validateMap le terms) opts + _ -> reject 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 = withChoice i . f -------------------------------------------------------------------------------- -- 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) -> dereferenceNoTrace n go + 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 = + dereferenceNoTrace n $ \ff -> getIndicesOfRange ff tt incl +getIndicesOfRange ff (CTreeE (VRuleRef n)) incl = + dereferenceNoTrace n $ \tt -> 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)) = dereferenceNoTrace n getIndicesOfEnum +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) +dereferenceNoTrace :: Name -> (CTree ValidatorPhase -> ValidatorT b a) -> ValidatorT b a +dereferenceNoTrace n act = do + mRes <- lookupCddl n + case mRes of + Just x -> act x + Nothing -> fail "Rule does not exist" -dereferenceAndValidate :: - CTreeRoot ValidatorPhase -> - Name -> - (CTree ValidatorPhase -> Evidenced ValidationTrace) -> - Evidenced ValidationTrace -dereferenceAndValidate cddl n f = - mapTrace (ReferenceRule n) . f $ dereference cddl n +dereference :: Name -> (CTree ValidatorPhase -> ValidatorT b a) -> ValidatorT b a +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/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 b17fbc63..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 (CBORGen) -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 (Maybe (CBORGen 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/Core.hs b/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs index 05382a58..886ae3ef 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Core.hs @@ -1,13 +1,30 @@ +{-# LANGUAGE LambdaCase #-} {-# LANGUAGE TypeFamilies #-} -module Codec.CBOR.Cuddle.CDDL.Custom.Core (MonadCddl (..), RuleTerm (..)) where +module Codec.CBOR.Cuddle.CDDL.Custom.Core ( + MonadCddl (..), + RuleTerm (..), + LengthEncoding (..), + evalBool, + evalInteger, + evalDouble, + evalArray, + evalInterval, + evalBytes, + evalText, +) 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.ByteString (ByteString) import Data.Kind (Type) +import Data.Text (Text) +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 +35,96 @@ 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) + +data LengthEncoding + = DefiniteLength + | IndefiniteLength + +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 + +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 _) + | 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 + _ -> 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 => + (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 5c9f2f39..ed083ef8 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Generator.hs @@ -1,5 +1,8 @@ +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeData #-} {-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE UndecidableInstances #-} module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( GenPhase, @@ -12,73 +15,45 @@ module Codec.CBOR.Cuddle.CDDL.Custom.Generator ( withAntiGen, withLocalGenBindings, - -- * Twiddling - TwiddleConfig (..), - TwiddlePolicy (..), - isIndefiniteAllowed, - isDefiniteAllowed, - twiddleUniform, - twiddleAll, - twiddleNothing, - withTwiddle, - disableTwiddle, + -- * Term generator + TermGenerator (..), + simpleGen, + constrain, + deferGen, + bindGen, + genFromInterval, + rangeInInterval, + + -- * Contstraints + GenConstraint (..), + showConstraint, ) 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 +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') +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 -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) @@ -120,24 +95,14 @@ 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 -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. @@ -148,8 +113,121 @@ withLocalGenBindings binds = data instance XXCTree GenPhase = GenRef Name - | GenGenerator (CBORGen RuleTerm) (CTree GenPhase) - | GenValidator TermValidator (CTree GenPhase) + | GenGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree GenPhase) + | GenValidator (TermValidator -> TermValidator) (CTree GenPhase) class HasGenerator a where - generatorL :: Lens' a (Maybe (CBORGen RuleTerm)) + generatorL :: Lens' a (TermGenerator RuleTerm -> TermGenerator RuleTerm) + +genFromInterval :: + ( 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 :: + ( HasCallStack + , MonadGen m + , Random a + , Ord a + , Show a + ) => + (a, a) -> + Interval a -> + m a +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 + +data GenConstraint + = -- | Constrains the size of a string or bytestring in bytes + Size (CTree GenPhase) + | -- | Constrains the range of allowed values to the interval. This also covers + -- the .gt and .lt operators. + 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 Integer) + | -- | 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 (CTree GenPhase) + | 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. +simpleGen :: CBORGen a -> TermGenerator a +simpleGen gen = + TermGenerator + { tgGenerator = gen + , tgConstrain = const Nothing + } + +constrain :: GenConstraint -> TermGenerator a -> TermGenerator a +constrain c (TermGenerator _ f) = case f c of + Just g -> g + 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 +-- 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 + } + +-- | 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" + Range _ -> ".range" + Eq _ -> ".eq" + Neq _ -> ".neq" + Default _ -> ".default" + Bits _ -> ".bits" + Regexp _ -> ".regexp" + Cbor _ -> ".cbor" + Cborseq _ -> ".cborseq" + 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..570dee5b 100644 --- a/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs +++ b/src/Codec/CBOR/Cuddle/CDDL/Custom/Validator.hs @@ -1,55 +1,124 @@ +{-# 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 (..), + ValidatorT, XXCTree (..), HasValidator (..), ValidateEnv (..), withLocalValidateBindings, runValidator, + mapTrace, + isValid, + compareEvidencedProgress, + nestContainer, + TraceOptions (..), + defaultTraceOptions, + showValidationTrace, + accept, + reject, + failWith, + withRef, + withChoice, + withTag, + withArray, + withMap, + withCborControl, + withCborseqControl, + controlVerdict, + element, + entry, + runBlock, + + -- * Trace + SValidity (..), + Validity (..), + Progress (..), + Evidenced (..), + ControlInfo (..), + ValidationTrace (..), + StepTrace (..), + Block (..), + evidence, + fromEither, + foldEvidenced, + measureProgress, + prettyValidationTrace, + prettyStepTrace, ) 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) +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 (..)) +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) +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 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 data instance XXCTree ValidatorPhase = VRuleRef Name - | VValidator TermValidator (CTree ValidatorPhase) + | VValidator (TermValidator -> TermValidator) (CTree ValidatorPhase) class HasValidator a where - validatorL :: Lens' a (Maybe TermValidator) - -data CustomValidatorResult - = CustomValidatorSuccess - | CustomValidatorFailure Text - deriving (Generic, Show, Eq) + validatorL :: Lens' a (TermValidator -> TermValidator) data ValidateEnv = ValidateEnv { veRoot :: CTreeRoot ValidatorPhase , veLocal :: Map Name (CTree ValidatorPhase) } -newtype Validator a = Validator (ReaderT ValidateEnv (Either Text) a) +newtype ValidatorT (b :: Block) a + = Validator + (ReaderT ValidateEnv (ExceptT (ValidationTrace b IsInvalid) (State [ValidationTrace b IsValid])) a) deriving (Functor, Applicative, Monad, MonadReader ValidateEnv) -type TermValidator = RuleTerm -> Validator () +type Validator = ValidatorT TermBlock + +type TermValidator = Term -> 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 @@ -59,8 +128,122 @@ instance MonadCddl Validator where binds <- asks veLocal pure $ Map.lookup (Name t) binds -instance MonadFail Validator where - fail msg = Validator . ReaderT $ \_ -> Left $ T.pack msg + resolveExt = \case + VValidator _ x -> pure $ Just x + VRuleRef n -> lookupCddl n + +instance MonadFail (ValidatorT b) where + fail msg = failWith $ CustomFailure $ T.pack msg + +instance Alternative (ValidatorT b) 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 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 = 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 + +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 + +withMap :: ValidatorT MapBlock () -> Validator () +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 + 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 + False -> failWith $ ControlTrace info SInvalid + where + info = ControlInfo op $ mapIndex ctrl + +wrapBlock :: + (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 :: @@ -68,8 +251,442 @@ withLocalValidateBindings :: withLocalValidateBindings binds = local (\env -> env {veLocal = binds `Map.union` veLocal env}) -runValidator :: - Validator () -> CTreeRoot ValidatorPhase -> CustomValidatorResult -runValidator (Validator m) cddl = - either CustomValidatorFailure (const CustomValidatorSuccess) $ - runReaderT m ValidateEnv {veRoot = cddl, veLocal = Map.empty} +runValidator :: ValidatorT b a -> ValidateEnv -> Evidenced (StepTrace b) +runValidator m env = mkStepTrace $ runBlockWith m env + where + mkStepTrace eFail = + case eFail of + Right (_, trc) -> evidence trc + Left trc -> evidence trc + +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 + +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 + 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 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 b v) + +instance IsValidationTrace (StepTrace b) where + traceValidity = \case + StepsDone -> SValid + StepFailed _ -> SInvalid + Step _ next -> traceValidity next + measureProgress = \case + StepsDone -> mempty + StepFailed x -> measureProgress x + Step this next -> measureProgress this <> measureProgress next + +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 -> 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 + 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 :: + StepTrace TermBlock IsValid -> + ValidationTrace ListBlock IsValid + ArrayLeftoverTerms :: + NonEmpty Term -> + Maybe (CTree MonoSimplePhase, StepTrace TermBlock IsInvalid) -> + ValidationTrace ListBlock IsInvalid + ArrayLeftoverRule :: + CTree MonoSimplePhase -> + ValidationTrace ListBlock IsInvalid + ArrayMissingRequired :: + StepTrace TermBlock IsInvalid -> + ValidationTrace ListBlock IsInvalid + ArrayConsumeGroup :: + [Name] -> + StepTrace ListBlock v -> + ValidationTrace ListBlock v + MapTrace :: StepTrace MapBlock v -> ValidationTrace TermBlock v + MapEntry :: + StepTrace TermBlock IsValid -> + StepTrace TermBlock IsValid -> + ValidationTrace MapBlock IsValid + MapInvalidKey :: + StepTrace TermBlock IsInvalid -> + ValidationTrace MapBlock IsInvalid + MapInvalidValue :: + StepTrace TermBlock IsValid -> + StepTrace TermBlock IsInvalid -> + ValidationTrace MapBlock IsInvalid + MapDuplicateKeys :: + CanonicalTerm -> + ValidationTrace MapBlock IsInvalid + MapUnappliedRules :: NonEmpty (CTree MonoSimplePhase) -> ValidationTrace MapBlock IsInvalid + MapLeftoverEntries :: + NonEmpty (Term, Term) -> + Maybe (CTree MonoSimplePhase, StepTrace MapBlock IsInvalid) -> + ValidationTrace MapBlock IsInvalid + +deriving instance Show (ValidationTrace b v) + +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 + CustomSuccess -> SValid + CustomFailure {} -> SInvalid + UnsatisfiedControl {} -> SInvalid + ChoiceBranch {} -> SValid + TagTrace _ x -> traceValidity x + InvalidTag {} -> SInvalid + ArrayTrace x -> traceValidity x + ArrayElement {} -> SValid + ArrayLeftoverTerms {} -> SInvalid + ArrayLeftoverRule {} -> SInvalid + ArrayMissingRequired {} -> SInvalid + ArrayConsumeGroup _ x -> traceValidity x + MapTrace x -> traceValidity x + MapEntry {} -> SValid + MapInvalidKey {} -> SInvalid + MapInvalidValue {} -> SInvalid + MapDuplicateKeys {} -> SInvalid + MapUnappliedRules {} -> SInvalid + MapLeftoverEntries {} -> SInvalid + + measureProgress = \case + 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 + CustomSuccess -> Progress 1 0 + CustomFailure {} -> mempty + UnsatisfiedControl {} -> mempty + ChoiceBranch _ x -> measureProgress x + TagTrace _ x -> increaseTermProgress $ measureProgress x + 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 + MapInvalidKey k -> measureProgress k + MapInvalidValue k v -> measureProgress k <> measureProgress v + MapDuplicateKeys _ -> mempty + 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 + +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} + +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" + | not $ null validInit + ] + <> [ prettyValidationTrace opts f + | f <- maybeToList $ stepFailure steps + ] + | otherwise = + vsep $ foldEvidenced (prettyValidationTrace opts) <$> toEvidencedList steps + where + validInit = stepsTakeValid steps + +prettyValidationTrace :: TraceOptions -> ValidationTrace b v -> Doc AnsiStyle +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 v -> + "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 <> ")" + , nestContainer $ prettyStepTraceWithFold False opts c + ] + ReferenceRule (Name n) x -> + vsep + [ "ref: " <> annotate (color Blue) (pretty n) + , nestContainer $ prettyStepTraceWithFold False opts x + ] + CustomSuccess -> "" + CustomFailure e -> annotate (color Red) $ pretty e + UnsatisfiedControl op ctl -> + annotate (color Red) $ + vsep + [ "unsatisfied control:" + , indent 2 $ "." <> pretty op <+> pretty ctl + ] + ArrayTrace l -> + vsep + [ "array" + , nestContainer $ prettyStepTraceWithFold False opts l + ] + MapTrace m -> + vsep + [ "map" + , nestContainer $ prettyStepTraceWithFold False opts m + ] + TagTrace t x -> + vsep + [ "tag:" <+> annotate (color Green) ("#6." <> pretty t) + , nestContainer $ prettyStepTraceWithFold False opts x + ] + InvalidTag expected actual -> + "expected tag #6." <> pretty expected <> ", got #6." <> pretty actual + 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 rule + , nestContainer $ prettyStepTraceWithFold True opts trc + ] + ArrayLeftoverRule r -> + hang 2 $ + vsep + [ annotate (color Red) "required rule not satisfied:" + , pretty r + ] + ArrayElement steps -> vsep [prettyStepTraceWithFold True opts steps] + ArrayMissingRequired t -> + vsep + [ annotate (color Red) "failed to apply required rule:" + , nestContainer $ prettyStepTraceWithFold 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 $ prettyStepTraceWithFold 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 $ prettyStepTraceWithFold True opts k + , "value:" + , nestContainer $ prettyStepTraceWithFold True opts v + ] + MapInvalidKey k -> + vsep + [ "key:" <+> failedDoc + , nestContainer $ prettyStepTraceWithFold False opts k + ] + MapInvalidValue k v -> + vsep + [ "key:" + , nestContainer $ prettyStepTraceWithFold False opts k + , "value:" <+> failedDoc + , nestContainer $ prettyStepTraceWithFold False opts v + ] + MapDuplicateKeys _ -> "duplicate keys found" + where + failedDoc = annotate (color Red) "(failed)" + + prettyGroup :: [Name] -> StepTrace ListBlock v -> [Doc AnsiStyle] + prettyGroup refs x = go refs + where + go (n : ns) = + [ "ref" <+> pretty n + , nestContainer . vsep $ go ns + ] + go [] = + [ "grp" <+> case traceValidity x of + SValid -> mempty + SInvalid -> failedDoc + , nestContainer $ prettyStepTraceWithFold True opts x + ] + +showValidationTrace :: ValidationTrace b v -> String +showValidationTrace = + T.unpack + . 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 + +instance IndexMappable CTreeRoot ValidatorPhase MonoSimplePhase where + mapIndex (CTreeRoot m) = CTreeRoot $ mapIndex <$> m 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 + } 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 77eac173..a2581628 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 @@ -63,14 +63,13 @@ 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 ( - CBORGen, GenPhase, + TermGenerator (..), XXCTree (..), withLocalGenBindings, ) @@ -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,13 +104,31 @@ 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) (TermValidator -> 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) data CDDLMapEntry = CDDLMapEntry { cmeProvidedParameters :: ProvidedParameters (TypeOrGroup CTreePhase) - , cmeCustomGenerator :: Maybe (CBORGen RuleTerm) - , cmeCustomValidator :: Maybe TermValidator + , cmeCustomGenerator :: TermGenerator RuleTerm -> TermGenerator RuleTerm + , cmeCustomValidator :: TermValidator -> TermValidator } deriving (Generic) @@ -157,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) Nothing Nothing + Just $ CDDLMapEntry (toParametrised tog gps) id id -------------------------------------------------------------------------------- -- 2. Conversion to CTree @@ -168,8 +189,8 @@ 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) - | OValidator TermValidator (CTree OrReferenced) + | OGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree OrReferenced) + | OValidator (TermValidator -> TermValidator) (CTree OrReferenced) type data OrReferencedSimple @@ -213,12 +234,8 @@ buildRefCTree rules = PartialCTreeRoot $ toCTreeRule <$> rules toCTreeRule CDDLMapEntry {..} = applyValidator . applyGenerator . toCTreeTOG <$> cmeProvidedParameters where - applyGenerator = case cmeCustomGenerator of - Just g -> CTreeE . OGenerator g - Nothing -> id - applyValidator = case cmeCustomValidator of - Just v -> CTreeE . OValidator v - Nothing -> id + applyGenerator = CTreeE . OGenerator cmeCustomGenerator + applyValidator = CTreeE . OValidator cmeCustomValidator toCTreeTOG :: TypeOrGroup CTreePhase -> CTree OrReferenced toCTreeTOG (TOGType t0) = toCTreeT0 t0 @@ -416,13 +433,14 @@ instance Pretty (XXCTree i) => Pretty (DistRef i) where data instance XXCTree DistReferenced = DRef (DistRef DistReferenced) - | DGenerator (CBORGen RuleTerm) (CTree DistReferenced) - | DValidator TermValidator (CTree DistReferenced) + | DGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree DistReferenced) + | DValidator (TermValidator -> TermValidator) (CTree 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 :: @@ -468,69 +486,16 @@ buildResolvedCTree (PartialCTreeRoot ct) = PartialCTreeRoot <$> traverse go ct -- 4. Monomorphisation -------------------------------------------------------------------------------- -type data MonoReferenced - data instance XXCTree MonoReferenced = MRuleRef Name - | MGenerator (CBORGen RuleTerm) (CTree MonoReferenced) - | MValidator TermValidator (CTree MonoReferenced) + | MGenerator (TermGenerator RuleTerm -> TermGenerator RuleTerm) (CTree MonoReferenced) + | MValidator (TermValidator -> TermValidator) (CTree MonoReferenced) 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 @@ -540,7 +505,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 @@ -633,18 +598,20 @@ 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 fGen x) = do binds <- ask @"local" body <- resolveGenericCTree x let bindsGen = mapIndex @CTree @MonoReferenced @GenPhase <$> binds - g' = withLocalGenBindings bindsGen g + g' tg = + 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 -> @@ -684,6 +651,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 +665,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 id + +-- 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 a11abddc..ebfd4f4b 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 (..), @@ -94,9 +94,13 @@ module Codec.CBOR.Cuddle.Huddle ( -- * Generators withCBORGen, + withOverrideCBORGen, + withGenerator, + withOverrideGenerator, -- * Validators withValidator, + withOverrideValidator, -- * Name HasName (..), @@ -115,15 +119,27 @@ 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 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.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) @@ -147,8 +163,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) @@ -157,8 +171,8 @@ newtype instance C.XCddl HuddleStage = HuddleXCddl [C.Comment] data instance C.XRule HuddleStage = HuddleXRule { hxrComment :: C.Comment - , hxrGenerator :: Maybe (CBORGen RuleTerm) - , hxrValidator :: Maybe TermValidator + , hxrGenerator :: TermGenerator RuleTerm -> TermGenerator RuleTerm + , hxrValidator :: TermValidator -> TermValidator } deriving (Generic) @@ -171,7 +185,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 id newtype instance C.XXTopLevel HuddleStage = HuddleXXTopLevel C.Comment deriving (Generic, Semigroup, Monoid, Show, Eq) @@ -475,18 +490,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 @@ -512,7 +518,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 @@ -604,8 +610,8 @@ sized v sz = 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 _ _) = @@ -623,7 +629,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 @@ -1144,7 +1149,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 @@ -1158,7 +1163,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 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 @@ -1377,10 +1382,38 @@ 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 RuleTerm -> a -> a +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 gen = L.set generatorL $ Just gen +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 +withValidator p = withOverrideValidator $ const p + +withOverrideValidator :: HasValidator a => (TermValidator -> TermValidator) -> a -> a +withOverrideValidator = L.set validatorL + +-- * 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 a4804b6b..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 Nothing 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/Interval.hs b/src/Codec/CBOR/Cuddle/Interval.hs new file mode 100644 index 00000000..7043afbc --- /dev/null +++ b/src/Codec/CBOR/Cuddle/Interval.hs @@ -0,0 +1,107 @@ +{-# 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) + +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 +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 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 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/Examples/Huddle.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/Examples/Huddle.hs index 582cf5d1..32666754 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 (..)) @@ -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/GeneratorSpec.hs b/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs index e061b5e7..8917c47c 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/GeneratorSpec.hs @@ -4,13 +4,14 @@ 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.CBOR.Generator (GenPhase, generateFromName) +import Codec.CBOR.Cuddle.CDDL (Name, mapCDDLDropExt) import Codec.CBOR.Cuddle.CDDL.CTree (CTreeRoot (..)) -import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen, twiddleAll) -import Codec.CBOR.Cuddle.CDDL.Resolve (MonoReferenced, MonoSimplePhase, fullResolveCDDL) +import Codec.CBOR.Cuddle.CDDL.Custom.Generator (GenConfig (..), runCBORGen) +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) @@ -40,13 +41,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 +51,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 +147,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..56edcf6e 100644 --- a/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs +++ b/test/Test/Codec/CBOR/Cuddle/CDDL/Validator.hs @@ -12,24 +12,24 @@ 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 (XXCTree (..), generateFromName) import Codec.CBOR.Cuddle.CBOR.Validator ( ValidatorPhase, validateCBOR, ) -import Codec.CBOR.Cuddle.CBOR.Validator.Trace ( +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.Generator (GenConfig (..), runCBORGen) +import Codec.CBOR.Cuddle.CDDL.Custom.Validator ( + Block (..), Evidenced (..), SValidity (..), - ValidationTrace, + StepTrace, + TermValidator, defaultTraceOptions, - prettyValidationTrace, + prettyStepTrace, ) -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.Validator (TermValidator) import Codec.CBOR.Cuddle.CDDL.Postlude (appendPostlude) import Codec.CBOR.Cuddle.CDDL.Resolve (MonoReferenced, fullResolveCDDL) import Codec.CBOR.Cuddle.Huddle ( @@ -49,7 +49,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 +108,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 @@ -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 @@ -136,6 +133,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 @@ -181,9 +180,6 @@ genHuddleArrayTerms = do required <- genHuddleArrayRequiredTerms pure $ bools <> required -genHuddleArray :: Gen Term -genHuddleArray = genHuddleArrayTerms >>= genArrayTerm - genBadArrayReversed :: Gen Term genBadArrayReversed = genHuddleArrayTerms >>= genArrayTerm . reverse . (TBool True :) @@ -277,7 +273,7 @@ validateHuddle :: Huddle -> Name -> Term -> - Evidenced ValidationTrace + Evidenced (StepTrace TermBlock) validateHuddle huddle name term = do let resolvedCddl = case fullResolveCDDL . mapCDDLDropExt $ toCDDL huddle of @@ -286,28 +282,28 @@ 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 -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 @@ -325,8 +321,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" 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 (..))