packages feed

hsmt-0.1.0.0: test/HSMT/RegexSpec.hs

-- | Regular expressions: derivatives against a naive matcher, automata
-- against derivatives, and the language measures against enumeration.
module HSMT.RegexSpec (tests) where

import qualified Data.IntMap.Strict as IntMap
import qualified Data.IntSet as IntSet
import Data.List (inits, tails)
import Data.Maybe (isJust)
import qualified Data.Text as T
import Test.QuickCheck
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck (testProperty)

import HSMT.Core.Regex

-- | Expressions as written, before normalization.
data Raw
  = Lit String
  | Range Char Char
  | AnyChar
  | Nothing'
  | All
  | Cat Raw Raw
  | Alt Raw Raw
  | And Raw Raw
  | Star Raw
  | Plus Raw
  | Opt Raw
  | Comp Raw
  | Diff Raw Raw
  | Loop Int Int Raw
  deriving (Show)

-- | The characters of the generated expressions; @z@ stands for every
-- other character in enumerations.
alphabet :: String
alphabet = "abcz"

instance Arbitrary Raw where
  arbitrary = sized gen
    where
      gen n
        | n <= 1 =
            frequency
              [ (4, Lit <$> listOf1' 2)
              , (2, Range <$> elements "abc" <*> elements "abc")
              , (1, pure AnyChar)
              , (1, pure Nothing')
              , (1, pure All)
              , (1, pure (Lit ""))
              ]
        | otherwise =
            let sub = gen (n `div` 2)
             in frequency
                  [ (2, gen 1)
                  , (3, Cat <$> sub <*> sub)
                  , (3, Alt <$> sub <*> sub)
                  , (2, And <$> sub <*> sub)
                  , (2, Star <$> sub)
                  , (1, Plus <$> sub)
                  , (1, Opt <$> sub)
                  , (2, Comp <$> sub)
                  , (1, Diff <$> sub <*> sub)
                  , (1, Loop <$> choose (0, 2) <*> choose (0, 3) <*> sub)
                  ]
      listOf1' k = choose (1, k) >>= \m -> vectorOf m (elements "abc")
  shrink = \case
    Cat a b -> [a, b] <> [Cat a' b | a' <- shrink a] <> [Cat a b' | b' <- shrink b]
    Alt a b -> [a, b] <> [Alt a' b | a' <- shrink a] <> [Alt a b' | b' <- shrink b]
    And a b -> [a, b] <> [And a' b | a' <- shrink a] <> [And a b' | b' <- shrink b]
    Diff a b -> [a, b] <> [Diff a' b | a' <- shrink a] <> [Diff a b' | b' <- shrink b]
    Star a -> a : map Star (shrink a)
    Plus a -> a : map Plus (shrink a)
    Opt a -> a : map Opt (shrink a)
    Comp a -> a : map Comp (shrink a)
    Loop i j a -> a : map (Loop i j) (shrink a)
    _ -> []

build :: Raw -> Regex
build = \case
  Lit s -> literal (T.pack s)
  Range a b -> range (T.singleton a) (T.singleton b)
  AnyChar -> allChar
  Nothing' -> none
  All -> everything
  Cat a b -> cat (build a) (build b)
  Alt a b -> union [build a, build b]
  And a b -> inter [build a, build b]
  Star a -> star (build a)
  Plus a -> plus (build a)
  Opt a -> opt (build a)
  Comp a -> complement (build a)
  Diff a b -> difference (build a) (build b)
  Loop i j a -> loop i j (build a)

-- | Membership by the definition of each operator.
naive :: Raw -> String -> Bool
naive r w = case r of
  Lit s -> w == s
  Range a b -> case w of
    [c] -> a <= c && c <= b
    _ -> False
  AnyChar -> length w == 1
  Nothing' -> False
  All -> True
  Cat a b -> or [naive a x && naive b y | (x, y) <- splits w]
  Alt a b -> naive a w || naive b w
  And a b -> naive a w && naive b w
  Star a -> null w || or [naive a x && naive (Star a) y | (x, y) <- splits w, not (null x)]
  Plus a -> naive (Cat a (Star a)) w
  Opt a -> null w || naive a w
  Comp a -> not (naive a w)
  Diff a b -> naive a w && not (naive b w)
  Loop i j a
    | j < i -> False
    | otherwise -> any (\k -> naive (power' k a) w) [i .. j]
  where
    splits s = zip (inits s) (tails s)
    power' k a = foldr Cat (Lit "") (replicate k a)

strings :: Int -> [String]
strings n = concatMap (\k -> sequence (replicate k alphabet)) [0 .. n]

runDfa :: Dfa -> String -> Bool
runDfa dfa = go 0
  where
    go q = \case
      [] -> IntSet.member q (dfaAccepting dfa)
      (c : cs) -> case [j | (set, j) <- IntMap.findWithDefault [] q (dfaDelta dfa), memberSet (fromEnum c) set] of
        [j] -> go j cs
        _ -> False

tests :: TestTree
tests =
  testGroup
    "regular expressions"
    [ testProperty "derivatives agree with the definitions" $ \raw ->
        forAll (elements (strings 5)) $ \w ->
          counterexample (show (build raw)) $ matches (build raw) (T.pack w) === naive raw w
    , testProperty "automata agree with derivatives" $ \raw ->
        let r = build raw
         in isJust (toDfa r) ==>
              case toDfa r of
                Just dfa -> conjoin [counterexample w (runDfa dfa w === matches r (T.pack w)) | w <- strings 4]
                Nothing -> property False
    , testProperty "shortest and longest members" $ \raw ->
        let r = build raw
            members = [w | w <- strings 6, matches r (T.pack w)]
         in case toDfa r of
              Nothing -> property Discard
              Just dfa ->
                conjoin
                  [ case members of
                      w : _ -> minLength dfa === Just (length w)
                      [] -> property (maybe True (> 6) (minLength dfa))
                  , case maxLength dfa of
                      Just m ->
                        counterexample ("max " <> show m) $
                          m <= 6 ==> maximum (map length members) === m
                      Nothing -> property True
                  ]
    , testProperty "equivalence agrees with enumeration" $ \a b ->
        let (ra, rb) = (build a, build b)
         in case equivalent ra rb of
              Just True -> conjoin [counterexample w (matches ra (T.pack w) === matches rb (T.pack w)) | w <- strings 4]
              _ -> property True
    , testCase "identities" $ do
        star (star (literal "a")) @?= star (literal "a")
        complement (complement (literal "ab")) @?= literal "ab"
        union [allChar, literal "a"] @?= allChar
        equivalent (star (union [literal "a", literal "b"])) (star (cat (star (literal "a")) (star (literal "b")))) @?= Just True
        equivalent (plus (literal "ab")) (cat (literal "ab") (star (literal "ab"))) @?= Just True
        equivalent (star (literal "aa")) (star (literal "a")) @?= Just False
        fmap minLength (toDfa (inter [plus (literal "ab"), power 3 allChar])) @?= Just Nothing
        (toDfa (loop 2 5 (literal "ab")) >>= maxLength) @?= Just 10
    ]