{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

-- | Write generated conformance test cases shared by the builtin property suites.
module Evaluation.Builtins.Conformance
  ( OutputFormat (..)
  , CheckMode (..)
  , checkModeName
  , PropertyFilter
  , PropertyId (..)
  , PropertySpec (..)
  , caseNumberDigits
  , checkUniqueIds
  , propertyIdPath
  , propertyIdText
  , propertySpecPropertyIds
  , TermCase (..)
  , Generated (..)
  , PropertyReport (..)
  , Check (..)
  , formatName
  , caseTerms
  , caseTermsUnchecked
  , checkHolds
  , guardCheck
  , isCekSuccess
  , evaluationFailureText
  , generateTermFiles
  , propertySeed
  , samplingSize
  ) where

import Evaluation.Builtins.Common
  ( PlcTerm
  , TypeErrorOrCekResult (..)
  , UplcTerm
  , cekSuccessTrue
  , evalOkEq
  , evalOkTrue
  , evalTerm
  , fails
  , ok
  )

import PlutusCore.Compiler.Erase (eraseTerm)
import PlutusCore.Evaluation.Machine.ExBudgetingDefaults (defaultCekParametersForTesting)
import PlutusCore.Flat (flat)
import PlutusCore.Version (plcVersion100)
import PlutusPrelude (display)
import UntypedPlutusCore qualified as UPLC
import UntypedPlutusCore.Evaluation.Machine.Cek (CountingSt (..), counting, runCekNoEmit)

import Control.Exception (Exception, displayException, throwIO)
import Control.Monad (foldM, forM_, when)
import Control.Monad.Except (runExcept)
import Data.Bits (xor)
import Data.ByteString qualified as BS
import Data.Char (ord)
import Data.List as List (foldl', group, intercalate, nub, sort)
import Data.Maybe (isNothing)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as Text
import Data.Text.IO qualified as Text
import Data.Word (Word64)
import System.Directory (createDirectoryIfMissing)
import System.FilePath (joinPath, (<.>), (</>))
import Test.QuickCheck (Gen, Testable (property), chooseAny, counterexample, (.&&.), (===), (==>))
import Test.QuickCheck.Gen (unGen)
import Test.QuickCheck.Random (QCGen, mkQCGen)
import Test.Tasty (TestName)
import Text.Printf (printf)

-- | Representations to write for each generated case. Both formats share a budget.
data OutputFormat = Flat | Uplc | Both

{-| How thoroughly a sampled case is checked against its property before it is
written.

* 'FastCheck' evaluates the terms with the untyped CEK machine, as the exporter
  does to record results. It confirms that the reference implementation
  satisfies the property but does not typecheck the terms.
* 'FullCheck' uses 'evalTerm', exactly as the normal tests do: it typechecks the
  terms and evaluates them with a freshly built typed evaluator. That setup is
  repeated for every case, which makes it much slower. -}
data CheckMode = FastCheck | FullCheck

-- | Name of a mode, as recorded in the info file.
checkModeName :: CheckMode -> String
checkModeName :: CheckMode -> String
checkModeName CheckMode
FastCheck = String
"fast"
checkModeName CheckMode
FullCheck = String
"full"

-- | Name of a format, as accepted on the command line and recorded in the info file.
formatName :: OutputFormat -> String
formatName :: OutputFormat -> String
formatName OutputFormat
Flat = String
"flat"
formatName OutputFormat
Uplc = String
"uplc"
formatName OutputFormat
Both = String
"both"

-- | What was written for one property.
data Generated = Generated
  { Generated -> Int
generatedNumberedCases :: Int
  {-^ Numbered cases written. Each holds one program, or two for an equality
  check; a check that combines several terms uses several numbers. -}
  , Generated -> Int
generatedPrograms :: Int
  , Generated -> Int
generatedFiles :: Int
  }
  deriving stock (Generated -> Generated -> Bool
(Generated -> Generated -> Bool)
-> (Generated -> Generated -> Bool) -> Eq Generated
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Generated -> Generated -> Bool
== :: Generated -> Generated -> Bool
$c/= :: Generated -> Generated -> Bool
/= :: Generated -> Generated -> Bool
Eq, Int -> Generated -> ShowS
[Generated] -> ShowS
Generated -> String
(Int -> Generated -> ShowS)
-> (Generated -> String)
-> ([Generated] -> ShowS)
-> Show Generated
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Generated -> ShowS
showsPrec :: Int -> Generated -> ShowS
$cshow :: Generated -> String
show :: Generated -> String
$cshowList :: [Generated] -> ShowS
showList :: [Generated] -> ShowS
Show)

-- | A property together with the cases written for it.
data PropertyReport = PropertyReport
  { PropertyReport -> PropertyId
propertyReportId :: PropertyId
  , PropertyReport -> Generated
propertyReportGenerated :: Generated
  }
  deriving stock (PropertyReport -> PropertyReport -> Bool
(PropertyReport -> PropertyReport -> Bool)
-> (PropertyReport -> PropertyReport -> Bool) -> Eq PropertyReport
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PropertyReport -> PropertyReport -> Bool
== :: PropertyReport -> PropertyReport -> Bool
$c/= :: PropertyReport -> PropertyReport -> Bool
/= :: PropertyReport -> PropertyReport -> Bool
Eq, Int -> PropertyReport -> ShowS
[PropertyReport] -> ShowS
PropertyReport -> String
(Int -> PropertyReport -> ShowS)
-> (PropertyReport -> String)
-> ([PropertyReport] -> ShowS)
-> Show PropertyReport
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PropertyReport -> ShowS
showsPrec :: Int -> PropertyReport -> ShowS
$cshow :: PropertyReport -> String
show :: PropertyReport -> String
$cshowList :: [PropertyReport] -> ShowS
showList :: [PropertyReport] -> ShowS
Show)

-- | Number of digits used to number cases, for example @00001@.
caseNumberDigits :: Int
caseNumberDigits :: Int
caseNumberDigits = Int
5

-- | Size passed to the generators when sampling inputs.
samplingSize :: Int
samplingSize :: Int
samplingSize = Int
30

{-| The random generator for one property, derived from the run's seed and the
property's identifier. Using the seed directly for every property would give
them all the same stream of random numbers, and so correlated inputs. Deriving
it from the identifier also means that the cases generated for a property do not
depend on which other properties are selected. -}
propertySeed :: QCGen -> PropertyId -> QCGen
propertySeed :: QCGen -> PropertyId -> QCGen
propertySeed QCGen
seed PropertyId
propertyId = Int -> QCGen
mkQCGen (Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word64
base Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` String -> Word64
fnv1a (PropertyId -> String
propertyIdText PropertyId
propertyId)))
  where
    base :: Word64
base = Gen Word64 -> QCGen -> Int -> Word64
forall a. Gen a -> QCGen -> Int -> a
unGen (Gen Word64
forall a. Random a => Gen a
chooseAny :: Gen Word64) QCGen
seed Int
0
    -- FNV-1a, 64 bit.
    fnv1a :: String -> Word64
    fnv1a :: String -> Word64
fnv1a = (Word64 -> Char -> Word64) -> Word64 -> String -> Word64
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
List.foldl' (\Word64
h Char
c -> (Word64
h Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Char -> Int
ord Char
c)) Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
1099511628211) Word64
14695981039346656037

{-| Location of a property relative to the output root, for example
@integer/RingProperties/addition_associative@. Keeping the segments apart lets
match keys use @/@ on every platform while file paths use the native separator. -}
data PropertyId = PropertyId
  { PropertyId -> [String]
propertyIdDirectory :: [String]
  -- ^ Segments above the property, for example @["integer", "RingProperties"]@.
  , PropertyId -> String
propertyIdName :: String
  -- ^ The property's own identifier, also used to name case directories and files.
  }
  deriving stock (PropertyId -> PropertyId -> Bool
(PropertyId -> PropertyId -> Bool)
-> (PropertyId -> PropertyId -> Bool) -> Eq PropertyId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PropertyId -> PropertyId -> Bool
== :: PropertyId -> PropertyId -> Bool
$c/= :: PropertyId -> PropertyId -> Bool
/= :: PropertyId -> PropertyId -> Bool
Eq, Eq PropertyId
Eq PropertyId =>
(PropertyId -> PropertyId -> Ordering)
-> (PropertyId -> PropertyId -> Bool)
-> (PropertyId -> PropertyId -> Bool)
-> (PropertyId -> PropertyId -> Bool)
-> (PropertyId -> PropertyId -> Bool)
-> (PropertyId -> PropertyId -> PropertyId)
-> (PropertyId -> PropertyId -> PropertyId)
-> Ord PropertyId
PropertyId -> PropertyId -> Bool
PropertyId -> PropertyId -> Ordering
PropertyId -> PropertyId -> PropertyId
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: PropertyId -> PropertyId -> Ordering
compare :: PropertyId -> PropertyId -> Ordering
$c< :: PropertyId -> PropertyId -> Bool
< :: PropertyId -> PropertyId -> Bool
$c<= :: PropertyId -> PropertyId -> Bool
<= :: PropertyId -> PropertyId -> Bool
$c> :: PropertyId -> PropertyId -> Bool
> :: PropertyId -> PropertyId -> Bool
$c>= :: PropertyId -> PropertyId -> Bool
>= :: PropertyId -> PropertyId -> Bool
$cmax :: PropertyId -> PropertyId -> PropertyId
max :: PropertyId -> PropertyId -> PropertyId
$cmin :: PropertyId -> PropertyId -> PropertyId
min :: PropertyId -> PropertyId -> PropertyId
Ord)

-- | Identifier used for matching and display: segments joined by @/@.
propertyIdText :: PropertyId -> String
propertyIdText :: PropertyId -> String
propertyIdText (PropertyId [String]
directory String
name) = String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"/" ([String]
directory [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String
name])

instance Show PropertyId where
  show :: PropertyId -> String
show = PropertyId -> String
propertyIdText

-- | Directory for the property, relative to the output root.
propertyIdPath :: PropertyId -> FilePath
propertyIdPath :: PropertyId -> String
propertyIdPath (PropertyId [String]
directory String
name) = [String] -> String
joinPath ([String]
directory [String] -> [String] -> [String]
forall a. Semigroup a => a -> a -> a
<> [String
name])

{-| A property with the identifier and description shared by the normal test
suite and the conformance generator, together with the sampler that produces
its inputs. -}
data PropertySpec gen = PropertySpec
  { forall gen. PropertySpec gen -> String
propertySpecId :: String
  -- ^ Stable identifier: used in generated test case paths.
  , forall gen. PropertySpec gen -> String
propertySpecDescription :: TestName
  -- ^ Human-readable name shown by the test runner.
  , forall gen. PropertySpec gen -> gen
propertySpecCheck :: gen
  -- ^ Sampler for unevaluated checks.
  }

-- | Generated test case identifiers for a suite's properties, in declaration order.
propertySpecPropertyIds :: [String] -> [PropertySpec gen] -> [PropertyId]
propertySpecPropertyIds :: forall gen. [String] -> [PropertySpec gen] -> [PropertyId]
propertySpecPropertyIds [String]
suiteDirectory =
  (PropertySpec gen -> PropertyId)
-> [PropertySpec gen] -> [PropertyId]
forall a b. (a -> b) -> [a] -> [b]
map (\PropertySpec gen
spec -> [String] -> String -> PropertyId
PropertyId [String]
suiteDirectory (PropertySpec gen -> String
forall gen. PropertySpec gen -> String
propertySpecId PropertySpec gen
spec))

{-| Fail if two properties in a suite share an identifier: their cases would be
written to the same directories, silently overwriting each other. -}
checkUniqueIds :: [String] -> [PropertySpec gen] -> IO ()
checkUniqueIds :: forall gen. [String] -> [PropertySpec gen] -> IO ()
checkUniqueIds [String]
suiteDirectory [PropertySpec gen]
specs =
  case [String
identifier | String
identifier : String
_ : [String]
_ <- [String] -> [[String]]
forall a. Eq a => [a] -> [[a]]
group ([String] -> [String]
forall a. Ord a => [a] -> [a]
sort ((PropertySpec gen -> String) -> [PropertySpec gen] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map PropertySpec gen -> String
forall gen. PropertySpec gen -> String
propertySpecId [PropertySpec gen]
specs))] of
    [] -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    [String]
duplicates ->
      ConformanceError -> IO ()
forall e a. Exception e => e -> IO a
throwIO (ConformanceError -> IO ()) -> ConformanceError -> IO ()
forall a b. (a -> b) -> a -> b
$
        String -> String -> ConformanceError
ConformanceError
          (String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"/" [String]
suiteDirectory)
          (String
"duplicate property identifiers: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " [String]
duplicates)

{-| Select a property by its path relative to the output root, without case
numbers or filename extensions (for example, integer/RingProperties/addition_associative). -}
type PropertyFilter = PropertyId -> Bool

-- | Keep the terms of an equality check together until their filenames are assigned.
data TermCase
  = SingleTerm PlcTerm
  | EqualTerms PlcTerm PlcTerm
  | {-| Why the reference implementation does not satisfy the property for this
    input. No files are written for such a case. -}
    ViolatedCase String

{-| A property check expressed without performing it. Normal QuickCheck suites
interpret it as an assertion, the Hedgehog suites have their own interpreter,
and the test generator extracts its terms, first checking with 'checkHolds' that
the reference implementation satisfies the property for the sampled input. -}
data Check
  = -- | Both terms evaluate successfully to equal results.
    CheckEq PlcTerm PlcTerm
  | -- | The term evaluates to the given result.
    CheckEvaluatesTo PlcTerm TypeErrorOrCekResult
  | -- | The term evaluates successfully to @True@.
    CheckTrue PlcTerm
  | -- | The term evaluates successfully.
    CheckOk PlcTerm
  | -- | The term fails to evaluate.
    CheckFails PlcTerm
  | {-| Both checks must hold. When generating, each check contributes its
    own numbered cases, so one sampled input can use several numbers. -}
    CheckBoth Check Check
  | CheckImplies Bool Check
  | -- | All terms evaluate successfully to pairwise distinct results.
    CheckDistinct [PlcTerm]
  | -- | The term's result satisfies the predicate, labelled for failure reports.
    CheckSatisfies String PlcTerm (TypeErrorOrCekResult -> Bool)

instance Testable Check where
  property :: Check -> Property
property (CheckEq PlcTerm
t1 PlcTerm
t2) = PlcTerm -> PlcTerm -> Property
evalOkEq PlcTerm
t1 PlcTerm
t2
  property (CheckEvaluatesTo PlcTerm
t TypeErrorOrCekResult
expected) = PlcTerm -> TypeErrorOrCekResult
evalTerm PlcTerm
t TypeErrorOrCekResult -> TypeErrorOrCekResult -> Property
forall a. (Eq a, Show a) => a -> a -> Property
=== TypeErrorOrCekResult
expected
  property (CheckTrue PlcTerm
t) = PlcTerm -> Property
evalOkTrue PlcTerm
t
  property (CheckOk PlcTerm
t) = PlcTerm -> Property
ok PlcTerm
t
  property (CheckFails PlcTerm
t) = PlcTerm -> Property
fails PlcTerm
t
  property (CheckBoth Check
a Check
b) = Check
a Check -> Check -> Property
forall prop1 prop2.
(Testable prop1, Testable prop2) =>
prop1 -> prop2 -> Property
.&&. Check
b
  property (CheckImplies Bool
condition Check
check) = Bool
condition Bool -> Check -> Property
forall prop. Testable prop => Bool -> prop -> Property
==> Check
check
  property (CheckDistinct [PlcTerm]
terms) =
    let results :: [TypeErrorOrCekResult]
results = (PlcTerm -> TypeErrorOrCekResult)
-> [PlcTerm] -> [TypeErrorOrCekResult]
forall a b. (a -> b) -> [a] -> [b]
map PlcTerm -> TypeErrorOrCekResult
evalTerm [PlcTerm]
terms
     in String -> Property -> Property
forall prop. Testable prop => String -> prop -> Property
counterexample ([TypeErrorOrCekResult] -> String
forall a. Show a => a -> String
show [TypeErrorOrCekResult]
results) (Property -> Property) -> Property -> Property
forall a b. (a -> b) -> a -> b
$
          Bool -> Property
forall prop. Testable prop => prop -> Property
property ((TypeErrorOrCekResult -> Bool) -> [TypeErrorOrCekResult] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all TypeErrorOrCekResult -> Bool
isCekSuccess [TypeErrorOrCekResult]
results)
            Property -> Property -> Property
forall prop1 prop2.
(Testable prop1, Testable prop2) =>
prop1 -> prop2 -> Property
.&&. ([TypeErrorOrCekResult] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TypeErrorOrCekResult]
results Int -> Int -> Property
forall a. (Eq a, Show a) => a -> a -> Property
=== [TypeErrorOrCekResult] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([TypeErrorOrCekResult] -> [TypeErrorOrCekResult]
forall a. Eq a => [a] -> [a]
nub [TypeErrorOrCekResult]
results))
  property (CheckSatisfies String
label PlcTerm
term TypeErrorOrCekResult -> Bool
predicate) =
    String -> Property -> Property
forall prop. Testable prop => String -> prop -> Property
counterexample String
label (Property -> Property) -> Property -> Property
forall a b. (a -> b) -> a -> b
$ Bool -> Property
forall prop. Testable prop => prop -> Property
property (TypeErrorOrCekResult -> Bool
predicate (PlcTerm -> TypeErrorOrCekResult
evalTerm PlcTerm
term))

-- | Successful evaluations only.
isCekSuccess :: TypeErrorOrCekResult -> Bool
isCekSuccess :: TypeErrorOrCekResult -> Bool
isCekSuccess (CekSuccess UplcTerm
_) = Bool
True
isCekSuccess TypeErrorOrCekResult
_ = Bool
False

-- | Shows the terms of a check; the predicate of 'CheckSatisfies' is omitted.
instance Show Check where
  show :: Check -> String
show (CheckEq PlcTerm
t1 PlcTerm
t2) = String
"CheckEq " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> PlcTerm -> String
forall a. Show a => a -> String
show PlcTerm
t1 String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> PlcTerm -> String
forall a. Show a => a -> String
show PlcTerm
t2
  show (CheckEvaluatesTo PlcTerm
t TypeErrorOrCekResult
expected) = String
"CheckEvaluatesTo " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> PlcTerm -> String
forall a. Show a => a -> String
show PlcTerm
t String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
forall a. Show a => a -> String
show TypeErrorOrCekResult
expected
  show (CheckTrue PlcTerm
t) = String
"CheckTrue " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> PlcTerm -> String
forall a. Show a => a -> String
show PlcTerm
t
  show (CheckOk PlcTerm
t) = String
"CheckOk " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> PlcTerm -> String
forall a. Show a => a -> String
show PlcTerm
t
  show (CheckFails PlcTerm
t) = String
"CheckFails " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> PlcTerm -> String
forall a. Show a => a -> String
show PlcTerm
t
  show (CheckBoth Check
a Check
b) = String
"CheckBoth (" String -> ShowS
forall a. Semigroup a => a -> a -> a
<> Check -> String
forall a. Show a => a -> String
show Check
a String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
") (" String -> ShowS
forall a. Semigroup a => a -> a -> a
<> Check -> String
forall a. Show a => a -> String
show Check
b String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
")"
  show (CheckImplies Bool
condition Check
inner) = String
"CheckImplies " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> Bool -> String
forall a. Show a => a -> String
show Bool
condition String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" (" String -> ShowS
forall a. Semigroup a => a -> a -> a
<> Check -> String
forall a. Show a => a -> String
show Check
inner String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
")"
  show (CheckDistinct [PlcTerm]
terms) = String
"CheckDistinct " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> [PlcTerm] -> String
forall a. Show a => a -> String
show [PlcTerm]
terms
  show (CheckSatisfies String
label PlcTerm
t TypeErrorOrCekResult -> Bool
_) = String
"CheckSatisfies " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ShowS
forall a. Show a => a -> String
show String
label String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> PlcTerm -> String
forall a. Show a => a -> String
show PlcTerm
t

{-| Evaluate a term with the untyped CEK machine, using the same parameters the
exporter uses to record expected results. No typechecking is done. -}
fastEvalTerm :: PlcTerm -> TypeErrorOrCekResult
fastEvalTerm :: PlcTerm -> TypeErrorOrCekResult
fastEvalTerm PlcTerm
term =
  case MachineParameters
  CekMachineCosts DefaultFun (CekValue DefaultUni DefaultFun ())
-> ExBudgetMode CountingSt DefaultUni DefaultFun
-> UplcTerm
-> (Either
      (CekEvaluationException Name DefaultUni DefaultFun) UplcTerm,
    CountingSt)
forall (uni :: * -> *) fun ann cost.
ThrowableBuiltins uni fun =>
MachineParameters CekMachineCosts fun (CekValue uni fun ann)
-> ExBudgetMode cost uni fun
-> Term Name uni fun ann
-> (Either
      (CekEvaluationException Name uni fun) (Term Name uni fun ()),
    cost)
runCekNoEmit MachineParameters
  CekMachineCosts DefaultFun (CekValue DefaultUni DefaultFun ())
forall ann.
Typeable ann =>
MachineParameters
  CekMachineCosts DefaultFun (CekValue DefaultUni DefaultFun ann)
defaultCekParametersForTesting ExBudgetMode CountingSt DefaultUni DefaultFun
forall (uni :: * -> *) fun. ExBudgetMode CountingSt uni fun
counting (PlcTerm -> UplcTerm
forall name tyname (uni :: * -> *) fun ann.
HasUnique name TermUnique =>
Term tyname name uni fun ann -> Term name uni fun ann
eraseTerm PlcTerm
term) of
    (Left CekEvaluationException Name DefaultUni DefaultFun
_, CountingSt
_) -> TypeErrorOrCekResult
CekError
    (Right UplcTerm
result, CountingSt
_) -> UplcTerm -> TypeErrorOrCekResult
CekSuccess UplcTerm
result

{-| Whether the reference implementation satisfies a check. This mirrors the
'Testable' instance, so the cases written out are those the normal tests would
accept. With 'FullCheck' the terms are evaluated, and typechecked, exactly as
the normal tests do; with 'FastCheck' they are evaluated by the untyped machine
alone. A false precondition counts as satisfied, since such inputs are discarded
rather than tested. -}
checkHolds :: CheckMode -> Check -> Bool
checkHolds :: CheckMode -> Check -> Bool
checkHolds CheckMode
mode = Maybe String -> Bool
forall a. Maybe a -> Bool
isNothing (Maybe String -> Bool) -> (Check -> Maybe String) -> Check -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CheckMode -> Check -> Maybe String
checkFailure CheckMode
mode

{-| Why the reference implementation does not satisfy a check, if it does not.
Evaluates the terms exactly as 'checkHolds' does, but reports what happened
rather than only whether it passed. Rendered terms are shortened so that a
failure in a case with large inputs stays readable. -}
checkFailure :: CheckMode -> Check -> Maybe String
checkFailure :: CheckMode -> Check -> Maybe String
checkFailure CheckMode
mode = Check -> Maybe String
go
  where
    eval :: PlcTerm -> TypeErrorOrCekResult
eval = case CheckMode
mode of
      CheckMode
FastCheck -> PlcTerm -> TypeErrorOrCekResult
fastEvalTerm
      CheckMode
FullCheck -> PlcTerm -> TypeErrorOrCekResult
evalTerm
    go :: Check -> Maybe String
go (CheckEq PlcTerm
t1 PlcTerm
t2) = case (PlcTerm -> TypeErrorOrCekResult
eval PlcTerm
t1, PlcTerm -> TypeErrorOrCekResult
eval PlcTerm
t2) of
      (CekSuccess UplcTerm
r1, CekSuccess UplcTerm
r2)
        | UplcTerm
r1 UplcTerm -> UplcTerm -> Bool
forall a. Eq a => a -> a -> Bool
== UplcTerm
r2 -> Maybe String
forall a. Maybe a
Nothing
        | Bool
otherwise ->
            String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$
              String
"the terms evaluated to different results: "
                String -> ShowS
forall a. Semigroup a => a -> a -> a
<> UplcTerm -> String
forall {a}. Pretty a => a -> String
renderTerm UplcTerm
r1
                String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" and "
                String -> ShowS
forall a. Semigroup a => a -> a -> a
<> UplcTerm -> String
forall {a}. Pretty a => a -> String
renderTerm UplcTerm
r2
      (TypeErrorOrCekResult
r1, TypeErrorOrCekResult
r2) ->
        String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$
          String
"the terms were expected to evaluate successfully to the same result, but the first "
            String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
outcome TypeErrorOrCekResult
r1
            String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" and the second "
            String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
outcome TypeErrorOrCekResult
r2
    go (CheckEvaluatesTo PlcTerm
t TypeErrorOrCekResult
expected) =
      let actual :: TypeErrorOrCekResult
actual = PlcTerm -> TypeErrorOrCekResult
eval PlcTerm
t
       in if TypeErrorOrCekResult
actual TypeErrorOrCekResult -> TypeErrorOrCekResult -> Bool
forall a. Eq a => a -> a -> Bool
== TypeErrorOrCekResult
expected
            then Maybe String
forall a. Maybe a
Nothing
            else
              String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$
                String
"the term "
                  String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
outcome TypeErrorOrCekResult
actual
                  String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
", but "
                  String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
describeExpected TypeErrorOrCekResult
expected
                  String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" was expected"
    go (CheckTrue PlcTerm
t) =
      let actual :: TypeErrorOrCekResult
actual = PlcTerm -> TypeErrorOrCekResult
eval PlcTerm
t
       in if TypeErrorOrCekResult
actual TypeErrorOrCekResult -> TypeErrorOrCekResult -> Bool
forall a. Eq a => a -> a -> Bool
== TypeErrorOrCekResult
cekSuccessTrue
            then Maybe String
forall a. Maybe a
Nothing
            else String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
"the term " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
outcome TypeErrorOrCekResult
actual String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
", but it was expected to evaluate to true"
    go (CheckOk PlcTerm
t) = case PlcTerm -> TypeErrorOrCekResult
eval PlcTerm
t of
      CekSuccess UplcTerm
_ -> Maybe String
forall a. Maybe a
Nothing
      TypeErrorOrCekResult
actual -> String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
"the term was expected to evaluate successfully, but it " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
outcome TypeErrorOrCekResult
actual
    go (CheckFails PlcTerm
t) =
      let actual :: TypeErrorOrCekResult
actual = PlcTerm -> TypeErrorOrCekResult
eval PlcTerm
t
       in if TypeErrorOrCekResult
actual TypeErrorOrCekResult -> TypeErrorOrCekResult -> Bool
forall a. Eq a => a -> a -> Bool
== TypeErrorOrCekResult
CekError
            then Maybe String
forall a. Maybe a
Nothing
            else String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
"the term was expected to fail, but it " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
outcome TypeErrorOrCekResult
actual
    go (CheckBoth Check
a Check
b) = case Check -> Maybe String
go Check
a of
      Just String
reason -> String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
"the first part of the check failed: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
reason
      Maybe String
Nothing -> ShowS -> Maybe String -> Maybe String
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String
"the second part of the check failed: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<>) (Check -> Maybe String
go Check
b)
    go (CheckImplies Bool
condition Check
check) = if Bool
condition then Check -> Maybe String
go Check
check else Maybe String
forall a. Maybe a
Nothing
    go (CheckDistinct [PlcTerm]
terms) =
      let results :: [TypeErrorOrCekResult]
results = (PlcTerm -> TypeErrorOrCekResult)
-> [PlcTerm] -> [TypeErrorOrCekResult]
forall a b. (a -> b) -> [a] -> [b]
map PlcTerm -> TypeErrorOrCekResult
eval [PlcTerm]
terms
       in case [TypeErrorOrCekResult
actual | TypeErrorOrCekResult
actual <- [TypeErrorOrCekResult]
results, Bool -> Bool
not (TypeErrorOrCekResult -> Bool
isCekSuccess TypeErrorOrCekResult
actual)] of
            TypeErrorOrCekResult
actual : [TypeErrorOrCekResult]
_ ->
              String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$
                String
"the terms were expected to evaluate successfully, but one "
                  String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
outcome TypeErrorOrCekResult
actual
            [] ->
              if [TypeErrorOrCekResult] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TypeErrorOrCekResult]
results Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [TypeErrorOrCekResult] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([TypeErrorOrCekResult] -> [TypeErrorOrCekResult]
forall a. Eq a => [a] -> [a]
nub [TypeErrorOrCekResult]
results)
                then Maybe String
forall a. Maybe a
Nothing
                else
                  String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$
                    String
"the terms were expected to evaluate to distinct results, but some were equal: "
                      String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ShowS
abbreviate (String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " [UplcTerm -> String
forall {a}. Pretty a => a -> String
renderTerm UplcTerm
term | CekSuccess UplcTerm
term <- [TypeErrorOrCekResult]
results])
    go (CheckSatisfies String
label PlcTerm
t TypeErrorOrCekResult -> Bool
predicate) =
      let actual :: TypeErrorOrCekResult
actual = PlcTerm -> TypeErrorOrCekResult
eval PlcTerm
t
       in if TypeErrorOrCekResult -> Bool
predicate TypeErrorOrCekResult
actual
            then Maybe String
forall a. Maybe a
Nothing
            else String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
"the result did not satisfy the check " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ShowS
forall a. Show a => a -> String
show String
label String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
": it " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> TypeErrorOrCekResult -> String
outcome TypeErrorOrCekResult
actual

    renderTerm :: a -> String
renderTerm a
term = ShowS
abbreviate (ShowS
singleLine (Text -> String
T.unpack (a -> Text
forall str a. (Pretty a, Render str) => a -> str
display a
term)))
    outcome :: TypeErrorOrCekResult -> String
outcome (CekSuccess UplcTerm
term) = String
"evaluated to " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> UplcTerm -> String
forall {a}. Pretty a => a -> String
renderTerm UplcTerm
term
    outcome TypeErrorOrCekResult
CekError = String
"failed to evaluate"
    outcome (TypeCheckError PlcError
err) = String
"failed to typecheck: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ShowS
abbreviate (ShowS
singleLine (PlcError -> String
forall a. Show a => a -> String
show PlcError
err))
    describeExpected :: TypeErrorOrCekResult -> String
describeExpected (CekSuccess UplcTerm
term) = UplcTerm -> String
forall {a}. Pretty a => a -> String
renderTerm UplcTerm
term
    describeExpected TypeErrorOrCekResult
CekError = String
"an evaluation failure"
    describeExpected (TypeCheckError PlcError
_) = String
"a type error"

-- | Maximum length of a rendered term in a failure message.
maxDetail :: Int
maxDetail :: Int
maxDetail = Int
300

-- | Put a multi-line rendering on one line.
singleLine :: String -> String
singleLine :: ShowS
singleLine = [String] -> String
unwords ([String] -> String) -> (String -> [String]) -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
words

-- | Shorten a string, marking that it has been cut.
abbreviate :: String -> String
abbreviate :: ShowS
abbreviate String
s
  | String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
s Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
maxDetail = String
s
  | Bool
otherwise = Int -> ShowS
forall a. Int -> [a] -> [a]
take Int
maxDetail String
s String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" ... (truncated)"

{-| Replace the terms of a check by a violation if the reference implementation
does not satisfy it. Writing such a case would record behaviour that
contradicts the property as if it were the expected result. -}
guardCheck :: CheckMode -> Check -> [TermCase] -> [TermCase]
guardCheck :: CheckMode -> Check -> [TermCase] -> [TermCase]
guardCheck CheckMode
mode Check
check [TermCase]
terms
  | Just String
reason <- CheckMode -> Check -> Maybe String
checkFailure CheckMode
mode Check
check = [String -> TermCase
ViolatedCase String
reason]
  | Bool
otherwise = [TermCase]
terms

{-| The terms to write for a check, after confirming that it holds. Preconditions
still select suitable inputs. Kept lazy so reaching the case limit need not
inspect later checks. -}
caseTerms :: CheckMode -> Check -> [TermCase]
caseTerms :: CheckMode -> Check -> [TermCase]
caseTerms CheckMode
mode Check
check = CheckMode -> Check -> [TermCase] -> [TermCase]
guardCheck CheckMode
mode Check
check (Check -> [TermCase]
caseTermsUnchecked Check
check)

-- | As 'caseTerms', but without checking that the property holds.
caseTermsUnchecked :: Check -> [TermCase]
caseTermsUnchecked :: Check -> [TermCase]
caseTermsUnchecked (CheckEq PlcTerm
t1 PlcTerm
t2) = [PlcTerm -> PlcTerm -> TermCase
EqualTerms PlcTerm
t1 PlcTerm
t2]
caseTermsUnchecked (CheckEvaluatesTo PlcTerm
t TypeErrorOrCekResult
_) = [PlcTerm -> TermCase
SingleTerm PlcTerm
t]
caseTermsUnchecked (CheckTrue PlcTerm
t) = [PlcTerm -> TermCase
SingleTerm PlcTerm
t]
caseTermsUnchecked (CheckOk PlcTerm
t) = [PlcTerm -> TermCase
SingleTerm PlcTerm
t]
caseTermsUnchecked (CheckFails PlcTerm
t) = [PlcTerm -> TermCase
SingleTerm PlcTerm
t]
caseTermsUnchecked (CheckBoth Check
a Check
b) = Check -> [TermCase]
caseTermsUnchecked Check
a [TermCase] -> [TermCase] -> [TermCase]
forall a. Semigroup a => a -> a -> a
<> Check -> [TermCase]
caseTermsUnchecked Check
b
caseTermsUnchecked (CheckImplies Bool
condition Check
check) =
  if Bool
condition then Check -> [TermCase]
caseTermsUnchecked Check
check else []
caseTermsUnchecked (CheckDistinct [PlcTerm]
terms) = (PlcTerm -> TermCase) -> [PlcTerm] -> [TermCase]
forall a b. (a -> b) -> [a] -> [b]
map PlcTerm -> TermCase
SingleTerm [PlcTerm]
terms
caseTermsUnchecked (CheckSatisfies String
_ PlcTerm
t TypeErrorOrCekResult -> Bool
_) = [PlcTerm -> TermCase
SingleTerm PlcTerm
t]

{-| Text recorded in @.expected@ and @.budget.expected@ files when evaluation
fails. The conformance harness compares those files verbatim against its own
@shownEvaluationFailure@; that constant lives in @PlutusConformance.Common@,
which depends on this library, so it cannot be imported here. Keep them in step. -}
evaluationFailureText :: Text
evaluationFailureText :: Text
evaluationFailureText = Text
"evaluation failure"

-- | A case that could not be encoded, reported with the case that caused it.
data ConformanceError = ConformanceError String String

instance Show ConformanceError where
  show :: ConformanceError -> String
show (ConformanceError String
caseName String
message) = String
caseName String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
": " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
message

instance Exception ConformanceError where
  displayException :: ConformanceError -> String
displayException (ConformanceError String
caseName String
message) = String
caseName String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
": " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
message

{-| Consume at most the requested number of cases, writing each one as it is
produced so that memory use does not grow with the number of cases. The count is
a number of terms, not of sampled inputs: an equality check emits both terms
under one number with -A/-B suffixes, while a check that combines several terms
(for example 'CheckBoth') supplies one numbered case per term. Each term has its
own result and budget files. A case that violates its property, or a stream with
fewer cases than requested, is an error. -}
generateTermFiles
  :: OutputFormat
  -> FilePath
  -> Int
  -> PropertyId
  -> String
  -> [TermCase]
  -> IO Generated
generateTermFiles :: OutputFormat
-> String
-> Int
-> PropertyId
-> String
-> [TermCase]
-> IO Generated
generateTermFiles OutputFormat
format String
outputDir Int
numFiles PropertyId
propertyId String
description [TermCase]
cases = do
  (Int
available, Int
programs) <- ((Int, Int) -> (Integer, TermCase) -> IO (Int, Int))
-> (Int, Int) -> [(Integer, TermCase)] -> IO (Int, Int)
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (Int, Int) -> (Integer, TermCase) -> IO (Int, Int)
forall {a} {a}.
(Show a, Num a, PrintfArg a) =>
(a, Int) -> (a, TermCase) -> IO (a, Int)
writeCase (Int
0, Int
0) ([Integer] -> [TermCase] -> [(Integer, TermCase)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Integer
1 :: Integer .. Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
numFiles] [TermCase]
cases)
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
available Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
numFiles) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    ConformanceError -> IO ()
forall e a. Exception e => e -> IO a
throwIO (ConformanceError -> IO ()) -> ConformanceError -> IO ()
forall a b. (a -> b) -> a -> b
$
      String -> String -> ConformanceError
ConformanceError
        (PropertyId -> String
propertyIdText PropertyId
propertyId)
        (String -> Int -> Int -> String
forall r. PrintfType r => String -> r
printf String
"only %d of %d requested cases were available" Int
available Int
numFiles)
  Generated -> IO Generated
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
    Generated
      { generatedNumberedCases :: Int
generatedNumberedCases = Int
available
      , generatedPrograms :: Int
generatedPrograms = Int
programs
      , generatedFiles :: Int
generatedFiles = Int
programs Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
filesPerProgram
      }
  where
    writeCase :: (a, Int) -> (a, TermCase) -> IO (a, Int)
writeCase (!a
count, Int
_) (a
_, ViolatedCase String
reason) =
      ConformanceError -> IO (a, Int)
forall e a. Exception e => e -> IO a
throwIO (ConformanceError -> IO (a, Int))
-> ConformanceError -> IO (a, Int)
forall a b. (a -> b) -> a -> b
$
        String -> String -> ConformanceError
ConformanceError
          (PropertyId -> String
propertyIdText PropertyId
propertyId String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
" (case " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> a -> String
forall a. Show a => a -> String
show (a
count a -> a -> a
forall a. Num a => a -> a -> a
+ a
1) String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
")")
          (String
description String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
"\n  " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
reason)
    writeCase (!a
count, !Int
programs) (a
n, TermCase
termCase) = do
      let terms :: [(String, PlcTerm)]
terms = TermCase -> [(String, PlcTerm)]
forall {a}. IsString a => TermCase -> [(a, PlcTerm)]
termSuffixes TermCase
termCase
      [(String, PlcTerm)] -> ((String, PlcTerm) -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [(String, PlcTerm)]
terms (((String, PlcTerm) -> IO ()) -> IO ())
-> ((String, PlcTerm) -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \(String
suffix, PlcTerm
term) -> do
        let caseName :: String
caseName = PropertyId -> String
propertyIdName PropertyId
propertyId String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
"-" String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String -> Int -> a -> String
forall r. PrintfType r => String -> r
printf String
"%0*d" Int
caseNumberDigits a
n String -> ShowS
forall a. Semigroup a => a -> a -> a
<> String
suffix
            dir :: String
dir = String
outputDir String -> ShowS
</> PropertyId -> String
propertyIdPath PropertyId
propertyId String -> ShowS
</> String
caseName
            basePath :: String
basePath = String
dir String -> ShowS
</> String
caseName
            input :: UplcTerm
input = PlcTerm -> UplcTerm
forall name tyname (uni :: * -> *) fun ann.
HasUnique name TermUnique =>
Term tyname name uni fun ann -> Term name uni fun ann
eraseTerm PlcTerm
term
            (Either Text UplcTerm
expected, Text
expectedBudget) =
              case MachineParameters
  CekMachineCosts DefaultFun (CekValue DefaultUni DefaultFun ())
-> ExBudgetMode CountingSt DefaultUni DefaultFun
-> UplcTerm
-> (Either
      (CekEvaluationException Name DefaultUni DefaultFun) UplcTerm,
    CountingSt)
forall (uni :: * -> *) fun ann cost.
ThrowableBuiltins uni fun =>
MachineParameters CekMachineCosts fun (CekValue uni fun ann)
-> ExBudgetMode cost uni fun
-> Term Name uni fun ann
-> (Either
      (CekEvaluationException Name uni fun) (Term Name uni fun ()),
    cost)
runCekNoEmit MachineParameters
  CekMachineCosts DefaultFun (CekValue DefaultUni DefaultFun ())
forall ann.
Typeable ann =>
MachineParameters
  CekMachineCosts DefaultFun (CekValue DefaultUni DefaultFun ann)
defaultCekParametersForTesting ExBudgetMode CountingSt DefaultUni DefaultFun
forall (uni :: * -> *) fun. ExBudgetMode CountingSt uni fun
counting UplcTerm
input of
                (Left CekEvaluationException Name DefaultUni DefaultFun
_, CountingSt
_) -> (Text -> Either Text UplcTerm
forall a b. a -> Either a b
Left Text
evaluationFailureText, Text
evaluationFailureText)
                (Right UplcTerm
result, CountingSt ExBudget
budget) -> (UplcTerm -> Either Text UplcTerm
forall a b. b -> Either a b
Right UplcTerm
result, ExBudget -> Text
forall str a. (Pretty a, Render str) => a -> str
display ExBudget
budget)
        Bool -> String -> IO ()
createDirectoryIfMissing Bool
True String
dir
        [(String, UplcTerm -> Either String ByteString)]
-> ((String, UplcTerm -> Either String ByteString) -> IO ())
-> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [(String, UplcTerm -> Either String ByteString)]
encodings (((String, UplcTerm -> Either String ByteString) -> IO ())
 -> IO ())
-> ((String, UplcTerm -> Either String ByteString) -> IO ())
-> IO ()
forall a b. (a -> b) -> a -> b
$ \(String
extension, UplcTerm -> Either String ByteString
encode) -> do
          ByteString
inputBytes <- String
-> (UplcTerm -> Either String ByteString)
-> UplcTerm
-> IO ByteString
encodeOrFail String
caseName UplcTerm -> Either String ByteString
encode UplcTerm
input
          let path :: String
path = String
basePath String -> ShowS
<.> String
extension
          String -> ByteString -> IO ()
BS.writeFile String
path ByteString
inputBytes
          ByteString
expectedBytes <- (Text -> IO ByteString)
-> (UplcTerm -> IO ByteString)
-> Either Text UplcTerm
-> IO ByteString
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> IO ByteString)
-> (Text -> ByteString) -> Text -> IO ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
Text.encodeUtf8) (String
-> (UplcTerm -> Either String ByteString)
-> UplcTerm
-> IO ByteString
encodeOrFail String
caseName UplcTerm -> Either String ByteString
encode) Either Text UplcTerm
expected
          String -> ByteString -> IO ()
BS.writeFile (String
path String -> ShowS
<.> String
"expected") ByteString
expectedBytes
        String -> Text -> IO ()
Text.writeFile (String
basePath String -> ShowS
<.> String
"budget" String -> ShowS
<.> String
"expected") Text
expectedBudget
      (a, Int) -> IO (a, Int)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (a
count a -> a -> a
forall a. Num a => a -> a -> a
+ a
1, Int
programs Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [(String, PlcTerm)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(String, PlcTerm)]
terms)

    filesPerProgram :: Int
filesPerProgram = Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* [(String, UplcTerm -> Either String ByteString)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(String, UplcTerm -> Either String ByteString)]
encodings Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
    termSuffixes :: TermCase -> [(a, PlcTerm)]
termSuffixes (SingleTerm PlcTerm
term) = [(a
"", PlcTerm
term)]
    termSuffixes (EqualTerms PlcTerm
lhs PlcTerm
rhs) = [(a
"-A", PlcTerm
lhs), (a
"-B", PlcTerm
rhs)]
    termSuffixes (ViolatedCase String
_) = []

    encodings :: [(String, UplcTerm -> Either String BS.ByteString)]
    encodings :: [(String, UplcTerm -> Either String ByteString)]
encodings = case OutputFormat
format of
      OutputFormat
Flat -> [(String, UplcTerm -> Either String ByteString)
flatEncoding]
      OutputFormat
Uplc -> [(String, UplcTerm -> Either String ByteString)
forall {a}. (String, UplcTerm -> Either a ByteString)
textualEncoding]
      OutputFormat
Both -> [(String, UplcTerm -> Either String ByteString)
flatEncoding, (String, UplcTerm -> Either String ByteString)
forall {a}. (String, UplcTerm -> Either a ByteString)
textualEncoding]
    textualEncoding :: (String, UplcTerm -> Either a ByteString)
textualEncoding = (String
"uplc", ByteString -> Either a ByteString
forall a b. b -> Either a b
Right (ByteString -> Either a ByteString)
-> (UplcTerm -> ByteString) -> UplcTerm -> Either a ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
Text.encodeUtf8 (Text -> ByteString)
-> (UplcTerm -> Text) -> UplcTerm -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UplcTerm -> Text
renderProgram)
    flatEncoding :: (String, UplcTerm -> Either String ByteString)
flatEncoding = (String
"flat", UplcTerm -> Either String ByteString
encodeFlatTerm)

    renderProgram :: UplcTerm -> Text
    renderProgram :: UplcTerm -> Text
renderProgram = Program Name DefaultUni DefaultFun () -> Text
forall str a. (Pretty a, Render str) => a -> str
display (Program Name DefaultUni DefaultFun () -> Text)
-> (UplcTerm -> Program Name DefaultUni DefaultFun ())
-> UplcTerm
-> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. () -> Version -> UplcTerm -> Program Name DefaultUni DefaultFun ()
forall name (uni :: * -> *) fun ann.
ann -> Version -> Term name uni fun ann -> Program name uni fun ann
UPLC.Program () Version
plcVersion100

    encodeOrFail
      :: String
      -> (UplcTerm -> Either String BS.ByteString)
      -> UplcTerm
      -> IO BS.ByteString
    encodeOrFail :: String
-> (UplcTerm -> Either String ByteString)
-> UplcTerm
-> IO ByteString
encodeOrFail String
caseName UplcTerm -> Either String ByteString
encode UplcTerm
term =
      (String -> IO ByteString)
-> (ByteString -> IO ByteString)
-> Either String ByteString
-> IO ByteString
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (ConformanceError -> IO ByteString
forall e a. Exception e => e -> IO a
throwIO (ConformanceError -> IO ByteString)
-> (String -> ConformanceError) -> String -> IO ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String -> ConformanceError
ConformanceError String
caseName) ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (UplcTerm -> Either String ByteString
encode UplcTerm
term)

{-| Match plutus-conformance's Flat representation: a de Bruijn program without
CBOR wrapping. Expected successful results use exactly the same encoding. -}
encodeFlatTerm :: UplcTerm -> Either String BS.ByteString
encodeFlatTerm :: UplcTerm -> Either String ByteString
encodeFlatTerm UplcTerm
term =
  case Except
  FreeVariableError (Term NamedDeBruijn DefaultUni DefaultFun ())
-> Either
     FreeVariableError (Term NamedDeBruijn DefaultUni DefaultFun ())
forall e a. Except e a -> Either e a
runExcept (UplcTerm
-> Except
     FreeVariableError (Term NamedDeBruijn DefaultUni DefaultFun ())
forall (m :: * -> *) (uni :: * -> *) fun ann.
MonadError FreeVariableError m =>
Term Name uni fun ann -> m (Term NamedDeBruijn uni fun ann)
UPLC.deBruijnTerm UplcTerm
term) of
    Left FreeVariableError
err -> String -> Either String ByteString
forall a b. a -> Either a b
Left (String -> Either String ByteString)
-> String -> Either String ByteString
forall a b. (a -> b) -> a -> b
$ String
"cannot encode a term with free variables: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> FreeVariableError -> String
forall a. Show a => a -> String
show FreeVariableError
err
    Right Term NamedDeBruijn DefaultUni DefaultFun ()
namedDbTerm ->
      ByteString -> Either String ByteString
forall a b. b -> Either a b
Right (ByteString -> Either String ByteString)
-> ByteString -> Either String ByteString
forall a b. (a -> b) -> a -> b
$
        UnrestrictedProgram DeBruijn DefaultUni DefaultFun () -> ByteString
forall a. Flat a => a -> ByteString
flat (UnrestrictedProgram DeBruijn DefaultUni DefaultFun ()
 -> ByteString)
-> UnrestrictedProgram DeBruijn DefaultUni DefaultFun ()
-> ByteString
forall a b. (a -> b) -> a -> b
$
          Program DeBruijn DefaultUni DefaultFun ()
-> UnrestrictedProgram DeBruijn DefaultUni DefaultFun ()
forall name (uni :: * -> *) fun ann.
Program name uni fun ann -> UnrestrictedProgram name uni fun ann
UPLC.UnrestrictedProgram (Program DeBruijn DefaultUni DefaultFun ()
 -> UnrestrictedProgram DeBruijn DefaultUni DefaultFun ())
-> Program DeBruijn DefaultUni DefaultFun ()
-> UnrestrictedProgram DeBruijn DefaultUni DefaultFun ()
forall a b. (a -> b) -> a -> b
$
            (NamedDeBruijn -> DeBruijn)
-> Program NamedDeBruijn DefaultUni DefaultFun ()
-> Program DeBruijn DefaultUni DefaultFun ()
forall name name' (uni :: * -> *) fun ann.
(name -> name')
-> Program name uni fun ann -> Program name' uni fun ann
UPLC.programMapNames NamedDeBruijn -> DeBruijn
UPLC.unNameDeBruijn (()
-> Version
-> Term NamedDeBruijn DefaultUni DefaultFun ()
-> Program NamedDeBruijn DefaultUni DefaultFun ()
forall name (uni :: * -> *) fun ann.
ann -> Version -> Term name uni fun ann -> Program name uni fun ann
UPLC.Program () Version
plcVersion100 Term NamedDeBruijn DefaultUni DefaultFun ()
namedDbTerm)