tilia-0.2.0.0: tests/Tilia/Cpp/PropertiesSpec.hs
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Properties that should hold of every module the preprocessor is
-- involved in.
module Tilia.Cpp.PropertiesSpec (spec) where
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import Test.Hspec hiding (after, before)
import Test.Hspec.QuickCheck (modifyMaxSuccess)
import Test.QuickCheck
import Tilia.Cpp (formatWithCpp, withoutRuledOut)
import Tilia.Cpp.Directives (answeredLeaves)
import Tilia.Cpp.Macros (Macros (..))
import Tilia.Equivalence (syntaxDifference)
import Tilia.Parser (parseModule, pmModule)
import Tilia.Render (RenderConfig (..), defaultRenderConfig)
import Tilia.Settings (CommaStyle (..), Settings)
import Tilia.TestUtils (defaultParserConfig, parses, withEachSettings)
import Tilia.Utils (tshow)
spec :: Spec
spec = modifyMaxSuccess (const 5000) . parallel $ do
withEachSettings $ \settings ->
describe "a module the preprocessor runs over" $ do
it "reaches its answer in one pass" $
property $ \m -> formatted settings m $ \out ->
case format settings out of
Left why ->
counterexample (T.unpack ("re-formatting refused: " <> why)) False
Right settled ->
counterexample (T.unpack (diffed out settled)) (settled == out)
it "comes out parseable in every configuration" $
property $ \m -> formatted settings m $ \out ->
case answeredLeaves out of
Left _ -> property Discard
Right configurations ->
conjoin
[ counterexample
(T.unpack ("this configuration does not parse:\n" <> t))
(parses t)
| (_, t) <- configurations
]
it "keeps what its directives say after their keyword" $
property $ \m -> formatted settings m $ \out ->
let remarked = Set.fromList . filter ("/*" `T.isInfixOf`) . T.lines
lost = Set.difference (remarked (sourceOf m)) (remarked out)
in counterexample
(T.unpack (T.unlines ("lost:" : Set.toList lost)))
(Set.null lost)
it "is the same program in every configuration it went in as" $
property $ \m -> formatted settings m $ \out ->
case (answeredLeaves (sourceOf m), answeredLeaves out) of
(Right went, Right came) ->
conjoin
[ counterexample
(T.unpack (T.unlines [before, "became", after, why]))
False
| (answers, before) <- went,
Just after <- [lookup answers came],
Just why <- [difference before after]
]
_ -> property Discard
describe "a module the preprocessor runs over" $
it "is read as configurations it already had, once a plan rules some out" $
property $ \m ->
let source = sourceOf m
in case ( answeredLeaves source,
answeredLeaves (withoutRuledOut macros source)
) of
(Right went, Right came) ->
let had = Set.fromList (fmap snd went)
in conjoin $
-- Selecting a branch with #error may intentionally
-- leave no compilable configuration.
counterexample
"nothing was left to read"
(not (null came) || "#error" `T.isInfixOf` source)
: [ counterexample
( T.unpack
("not a configuration the module had:\n" <> t)
)
(Set.member t had)
| (_, t) <- came
]
_ -> property Discard
----------------------------------------------------------------------------
-- Running the formatter
-- | A plan that settles the version the generator asks about and nothing
-- else, so that a module comes out with some of its conditionals answered
-- and some of them left open.
macros :: Macros
macros =
mempty{macroExactVersions = Map.fromList [("MIN_VERSION_thing", [1, 2, 3])]}
-- | A module formatted with some settings, or why it was not.
format ::
-- | The settings.
Settings ->
-- | The module.
Text ->
Either Text Text
format settings source = case result of
Left _ -> Left "declined"
Right out -> Right out
where
result =
formatWithCpp
defaultParserConfig
defaultRenderConfig{rcSettings = settings}
"M.hs"
source
-- | Whatever holds of a module the formatter did not decline.
--
-- Declining is an answer the formatter is allowed to give—a @#include@ it
-- cannot expand, a module with more configurations than its budget—and says
-- nothing about the properties below, so those runs are thrown away rather
-- than counted as passes.
formatted ::
Testable p =>
-- | The settings.
Settings ->
-- | The module.
CppModule ->
-- | What holds of what it formats to.
(Text -> p) ->
Property
formatted settings m k = case format settings (sourceOf m) of
Left _ -> property Discard
Right out -> property (k out)
difference :: Text -> Text -> Maybe Text
difference before after = do
b <-
either (const Nothing) Just (parseModule defaultParserConfig "M.hs" before)
a <-
either (const Nothing) Just (parseModule defaultParserConfig "M.hs" after)
syntaxDifference (pmModule b) (pmModule a)
diffed :: Text -> Text -> Text
diffed a b = T.unlines ["first pass:", a, "second pass:", b]
----------------------------------------------------------------------------
-- Generating a module
-- | One line, or one run of lines, of a generated module.
data Item
= -- | A declaration, named after the number so that a counterexample can
-- be read.
Decl Int
| -- | A comment written on a line of its own.
Note Text
| -- | An empty line, which is the point of half of these properties.
Blank
| -- | A directive that introduces no configuration of its own—@#define@
-- and the rest of what "Tilia.Cpp" calls opaque.
Opaque Text
| -- | A conditional, and what it holds either side of the @#else@.
Cond Text [Item] [Item]
| -- | A list bound to the name of the number, written with these commas.
List Int CommaStyle [Element]
deriving (Eq, Show)
-- | An item of a list.
data Element
= -- | One named after the number.
Named Int
| -- | Ones named after the numbers, behind a conditional asking this.
Optional Text [Int]
deriving (Eq, Show)
-- | A module that uses the preprocessor, with its export list and the
-- commas it is written with, if it has one.
--
-- Conditionals wrap whole items, or items of a list with their commas, and
-- nothing smaller, which is what keeps every configuration of the module a
-- module: a branch that took half a declaration away would leave the other
-- half behind.
data CppModule = CppModule (Maybe (CommaStyle, [Element])) [Item]
deriving (Eq)
-- | Shown as the source, since that is what a counterexample is read as.
instance Show CppModule where
show m = T.unpack ("\n" <> sourceOf m)
instance Arbitrary CppModule where
arbitrary =
CppModule
<$> frequency [(3, pure Nothing), (1, Just <$> listed)]
<*> sized (items 2)
shrink (CppModule exports xs) =
[CppModule Nothing xs | Just _ <- [exports]]
<> [ CppModule (Just (c, es')) xs
| Just (c, es) <- [exports],
es' <- fewer es
]
<> (CppModule exports <$> smaller xs)
-- | The items of a module, given how deep a conditional may still nest.
items :: Int -> Int -> Gen [Item]
items depth size' = do
n <- choose (1, max 1 (min 6 size'))
mapM (const (item depth)) [1 .. n :: Int]
item :: Int -> Gen Item
item depth =
frequency $
[ (4, Decl <$> choose (1, 9)),
(3, Note <$> elements ["-- a remark", "-- | documentation", "{- a block -}", "-- * a heading"]),
(3, pure Blank),
(1, Opaque <$> elements ["define WIDE 1", "error \"no\"", "undef WIDE"]),
(1, uncurry . List <$> choose (1, 9) <*> listed)
]
<> [(3, conditional depth) | depth > 0]
conditional :: Int -> Gen Item
conditional depth = do
guard' <-
elements
[ "if FLAG",
"ifdef OTHER",
"if FLAG",
"if MIN_VERSION_thing(1,0,0)",
"if MIN_VERSION_thing(9,0,0)"
]
yes <- items (depth - 1) 3
no <- frequency [(1, pure []), (1, items (depth - 1) 2)]
pure (Cond guard' yes no)
-- | The items of a list and the commas it is written with, the first and
-- the last item outside conditionals, so that every configuration has a
-- list of items with a comma between each two.
listed :: Gen (CommaStyle, [Element])
listed = do
commas <- elements [TrailingCommas, LeadingCommas]
first <- choose (1, 9)
middle <-
resize 3 . listOf $
oneof
[ Named <$> choose (1, 9),
Optional
<$> elements ["if FLAG", "ifdef OTHER"]
<*> resize 2 (listOf1 (choose (1, 9)))
]
final <- choose (1, 9)
pure (commas, [Named first] <> middle <> [Named final])
-- | Every way of making the items of a list fewer: drop one between the
-- first and the last, or take the ones behind a conditional out of it.
fewer :: [Element] -> [[Element]]
fewer es =
[take i es <> drop (i + 1) es | i <- [1 .. length es - 2]]
<> [ take i es <> fmap Named ns <> drop (i + 1) es
| (i, Optional _ ns) <- zip [0 ..] es
]
-- | Every way of making a module smaller: drop an item, replace a
-- conditional by one of the branches it was holding, or make the items of
-- a list fewer.
smaller :: [Item] -> [[Item]]
smaller xs =
[take i xs <> drop (i + 1) xs | i <- positions]
<> [ take i xs <> branch <> drop (i + 1) xs
| (i, Cond _ a b) <- indexed,
branch <- [a, b]
]
<> [ take i xs <> [x'] <> drop (i + 1) xs
| (i, x) <- indexed,
x' <- inside x
]
where
positions = [0 .. length xs - 1]
indexed = zip positions xs
inside = \case
Cond g a b ->
[Cond g a' b | a' <- smaller a] <> [Cond g a b' | b' <- smaller b]
List n c es -> List n c <$> fewer es
_ -> []
-- | The module as it is written out.
sourceOf :: CppModule -> Text
sourceOf (CppModule exports xs) =
T.unlines
(["{-# LANGUAGE CPP #-}", ""] <> header <> [""] <> concatMap written xs)
where
header = case exports of
Nothing -> ["module M where"]
Just (c, es) ->
["module M"]
<> bracketed ("(", ")") c (("f" <>) . tshow) es
<> ["where"]
written :: Item -> [Text]
written = \case
Decl n -> ["f" <> tshow n <> " = " <> tshow n]
Note t -> [t]
Blank -> [""]
Opaque t -> ["#" <> t]
Cond g yes no ->
["#" <> g]
<> concatMap written yes
<> ( if null no && T.null (remark g)
then []
else ("#else" <> remark g) : concatMap written no
)
<> ["#endif" <> remark g]
List n c es -> ("xs" <> tshow n <> " =") : bracketed ("[", "]") c tshow es
-- | The lines of the items of a list between brackets, written with some
-- commas.
bracketed ::
-- | The brackets.
(Text, Text) ->
-- | The commas.
CommaStyle ->
-- | How an item is named after its number.
(Int -> Text) ->
-- | The items.
[Element] ->
[Text]
bracketed (open, close) commas named es =
zipWith line [0 :: Int ..] spelled <> [" " <> close]
where
spelled = concatMap spell es
spell = \case
Named n -> [Right n]
Optional g ns -> [Left ("#" <> g)] <> fmap Right ns <> [Left "#endif"]
count = length [() | Right _ <- spelled]
line i = \case
Left directive -> directive
Right n ->
let k = length [() | Right _ <- take i spelled]
in case commas of
TrailingCommas ->
(if k == 0 then " " <> open <> " " else " ")
<> named n
<> (if k == count - 1 then "" else ",")
LeadingCommas ->
(if k == 0 then " " <> open <> " " else " , ") <> named n
-- | What a conditional asking this writes after its @#else@ and @#endif@,
-- the same for every one of them, since the merge can print several as one.
remark :: Text -> Text
remark = \case
"ifdef OTHER" -> " /* OTHER */"
_ -> ""