hsmt-0.1.0.0: src/HSMT/Core/Regex.hs
-- | Regular expressions over the SMT-LIB 2.6 alphabet (code points @0@ to
-- @0x2FFFF@), as the values of the sort @RegLan@.
--
-- Expressions are kept in a normal form by the smart constructors in this
-- module (as in Owens, Reppy and Turon, "Regular-expression derivatives
-- re-examined", 2009): concatenation is right-nested, unions and
-- intersections are sets, the characters of a union are merged into one
-- character set, and the usual identities (@none . r = none@, @(r*)* =
-- r*@, @~~r = r@...) are applied. With this normal form, the Brzozowski
-- derivatives of an expression are finitely many, so they give a
-- deterministic automaton; complement and intersection need no special
-- construction.
--
-- Membership ('matches') follows the derivatives along the string; the
-- automaton ('toDfa') groups characters into classes that have the same
-- derivative everywhere ('charClasses').
module HSMT.Core.Regex
( -- * Character sets
CharSet
, maxChar
, fullSet
, memberSet
, -- * Expressions
Regex (..)
, none
, epsilon
, allChar
, everything
, charSet
, range
, literal
, cat
, union
, inter
, star
, plus
, opt
, loop
, power
, complement
, difference
-- * Semantics
, nullable
, derivative
, matches
, charClasses
-- * Automata
, Dfa (..)
, maxStates
, toDfa
, isEmpty
, equivalent
, minLength
, maxLength
, liveStates
-- * Rendering
, prettyRegex
) where
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.IntSet as IntSet
import Data.List (sortOn)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Numeric (showHex)
-------------------------------------------------------------------------------
-- Character sets
-- | A set of code points: sorted, disjoint and non-adjacent inclusive
-- ranges.
type CharSet = [(Int, Int)]
-- | The largest code point of SMT-LIB strings.
maxChar :: Int
maxChar = 0x2FFFF
-- | Every code point.
fullSet :: CharSet
fullSet = [(0, maxChar)]
-- | Whether a code point belongs to a set.
memberSet :: Int -> CharSet -> Bool
memberSet c = any (\(lo, hi) -> lo <= c && c <= hi)
normalizeSet :: [(Int, Int)] -> CharSet
normalizeSet = merge . sortOn fst . filter (uncurry (<=)) . map clip
where
clip (lo, hi) = (max 0 lo, min maxChar hi)
merge ((a, b) : (c, d) : rest)
| c <= b + 1 = merge ((a, max b d) : rest)
| otherwise = (a, b) : merge ((c, d) : rest)
merge rs = rs
unionSet :: CharSet -> CharSet -> CharSet
unionSet a b = normalizeSet (a <> b)
interSet :: CharSet -> CharSet -> CharSet
interSet a b = normalizeSet [(max lo lo', min hi hi') | (lo, hi) <- a, (lo', hi') <- b]
complementSet :: CharSet -> CharSet
complementSet cs = normalizeSet (go 0 cs)
where
go next [] = [(next, maxChar)]
go next ((lo, hi) : rest) = (next, lo - 1) : go (hi + 1) rest
-------------------------------------------------------------------------------
-- Expressions
-- | A regular expression in normal form. Build expressions with the smart
-- constructors, which keep the invariants documented on each constructor.
data Regex
= RSet CharSet
-- ^ One character of the set (the empty set is the empty language).
| REps
-- ^ The empty string.
| RCat Regex Regex
-- ^ Concatenation; neither part is empty, the empty string or a
-- concatenation itself (concatenation is right-nested).
| RAlt (Set Regex)
-- ^ Union of at least two expressions, none a union itself or empty,
-- with at most one character set.
| RAnd (Set Regex)
-- ^ Intersection of at least two expressions, none an intersection
-- itself or the universal language.
| RStar Regex
-- ^ Kleene star of an expression that is not a star, the empty string
-- or empty.
| RNot Regex
-- ^ Complement of an expression that is not a complement.
deriving (Eq, Ord, Show)
-- | The empty language.
none :: Regex
none = RSet []
-- | The language of the empty string.
epsilon :: Regex
epsilon = REps
-- | Every string of one character.
allChar :: Regex
allChar = RSet fullSet
-- | Every string.
everything :: Regex
everything = RNot none
-- | One character of a set.
charSet :: [(Int, Int)] -> Regex
charSet = RSet . normalizeSet
-- | @re.range@: the characters between two one-character strings, or the
-- empty language when an argument is not a single character.
range :: Text -> Text -> Regex
range a b = case (T.unpack a, T.unpack b) of
([x], [y]) -> charSet [(fromEnum x, fromEnum y)]
_ -> none
-- | @str.to_re@: the language of one string.
literal :: Text -> Regex
literal = foldr (\ch r -> cat (charSet [(fromEnum ch, fromEnum ch)]) r) REps . T.unpack
-- | Concatenation.
cat :: Regex -> Regex -> Regex
cat a b
| a == none || b == none = none
| otherwise = case (a, b) of
(REps, _) -> b
(_, REps) -> a
(RCat x y, _) -> cat x (cat y b)
_ -> RCat a b
-- | Union of a list (the empty language when empty).
union :: [Regex] -> Regex
union rs
| everything `Set.member` members = everything
| otherwise = case Set.toList (withSet members) of
[] -> none
[r] -> r
_ -> RAlt (withSet members)
where
members = Set.fromList (filter (/= none) (concatMap flat rs))
flat = \case
RAlt xs -> Set.toList xs
r -> [r]
-- All character sets merged into one.
withSet xs =
let (sets, others) = Set.partition isSet xs
merged = foldl' unionSet [] [cs | RSet cs <- Set.toList sets]
in if null merged then others else Set.insert (RSet merged) others
isSet = \case
RSet _ -> True
_ -> False
-- | Intersection of a list (every string when empty).
inter :: [Regex] -> Regex
inter rs
| none `Set.member` members = none
| otherwise = case Set.toList (withSet members) of
[] -> everything
[r] -> r
_ -> RAnd (withSet members)
where
members = Set.fromList (filter (/= everything) (concatMap flat rs))
flat = \case
RAnd xs -> Set.toList xs
r -> [r]
withSet xs =
let (sets, others) = Set.partition isSet xs
in case [cs | RSet cs <- Set.toList sets] of
[] -> others
css -> case foldl1 interSet css of
[] -> Set.singleton none
cs -> Set.insert (RSet cs) others
isSet = \case
RSet _ -> True
_ -> False
-- | Kleene star.
star :: Regex -> Regex
star = \case
r@(RStar _) -> r
REps -> REps
RSet [] -> REps
RSet cs | cs == fullSet -> everything
r -> RStar r
-- | One or more repetitions.
plus :: Regex -> Regex
plus r = cat r (star r)
-- | Zero or one occurrence.
opt :: Regex -> Regex
opt r = union [REps, r]
-- | @(_ re.loop i j)@: between @i@ and @j@ repetitions (the empty language
-- when @j < i@).
loop :: Int -> Int -> Regex -> Regex
loop i j r
| j < i = none
| otherwise = foldr cat optional (replicate i r)
where
optional = foldr (\_ acc -> opt (cat r acc)) REps [1 .. j - i]
-- | @(_ re.^ n)@: exactly @n@ repetitions.
power :: Int -> Regex -> Regex
power n = loop n n
-- | Complement.
complement :: Regex -> Regex
complement = \case
RNot r -> r
r -> RNot r
-- | @re.diff@: the strings of the first language not in the second.
difference :: Regex -> Regex -> Regex
difference a b = inter [a, complement b]
-------------------------------------------------------------------------------
-- Semantics
-- | Whether the language contains the empty string.
nullable :: Regex -> Bool
nullable = \case
RSet _ -> False
REps -> True
RCat a b -> nullable a && nullable b
RAlt xs -> any nullable xs
RAnd xs -> all nullable xs
RStar _ -> True
RNot r -> not (nullable r)
-- | The Brzozowski derivative by a code point: the strings @w@ such that
-- @c w@ is in the language.
derivative :: Int -> Regex -> Regex
derivative c = \case
RSet cs -> if memberSet c cs then REps else none
REps -> none
RCat a b ->
let first = cat (derivative c a) b
in if nullable a then union [first, derivative c b] else first
RAlt xs -> union (map (derivative c) (Set.toList xs))
RAnd xs -> inter (map (derivative c) (Set.toList xs))
r@(RStar a) -> cat (derivative c a) r
RNot a -> complement (derivative c a)
-- | Whether a string belongs to the language.
matches :: Regex -> Text -> Bool
matches r = nullable . T.foldl' (\acc ch -> derivative (fromEnum ch) acc) r
-- | A partition of the alphabet into classes of code points whose
-- derivatives are equal.
charClasses :: Regex -> [CharSet]
charClasses = \case
RSet cs -> filter (not . null) [cs, complementSet cs]
REps -> [fullSet]
RCat a b
| nullable a -> meet (charClasses a) (charClasses b)
| otherwise -> charClasses a
RAlt xs -> foldl' meet [fullSet] (map charClasses (Set.toList xs))
RAnd xs -> foldl' meet [fullSet] (map charClasses (Set.toList xs))
RStar a -> charClasses a
RNot a -> charClasses a
where
meet p q = [s | x <- p, y <- q, let s = interSet x y, not (null s)]
-------------------------------------------------------------------------------
-- Automata
-- | A deterministic automaton. States are @0 .. n-1@ and @0@ is the initial
-- state; the transitions of each state are labelled with disjoint
-- character sets that cover the alphabet.
data Dfa = Dfa
{ dfaStates :: !Int
, dfaDelta :: !(IntMap [(CharSet, Int)])
, dfaAccepting :: !IntSet.IntSet
}
deriving (Show)
-- | The largest automaton 'toDfa' builds.
maxStates :: Int
maxStates = 2000
-- | The automaton of the derivatives of an expression, or 'Nothing' when it
-- has more than 'maxStates' states.
toDfa :: Regex -> Maybe Dfa
toDfa r0 = go (Map.singleton r0 0) [r0] IntMap.empty
where
go known [] delta =
let accepting = IntSet.fromList [i | (r, i) <- Map.toList known, nullable r]
in Just (Dfa (Map.size known) delta accepting)
go known (r : todo) delta
| Map.size known > maxStates = Nothing
| otherwise =
let i = known Map.! r
step (k, new, edges) cls =
let d = derivative (representative cls) r
in case Map.lookup d k of
Just j -> (k, new, (cls, j) : edges)
Nothing ->
let j = Map.size k
in (Map.insert d j k, d : new, (cls, j) : edges)
(known', new', edges') = foldl' step (known, [], []) (charClasses r)
in go known' (todo <> reverse new') (IntMap.insert i (mergeEdges edges') delta)
representative = \case
(lo, _) : _ -> lo
[] -> 0
-- One transition per target state.
mergeEdges edges =
[(cs, j) | (j, cs) <- Map.toList (Map.fromListWith unionSet [(j, cs) | (cs, j) <- edges])]
-- | States from which an accepting state can be reached.
liveStates :: Dfa -> IntSet.IntSet
liveStates dfa = fixpoint (dfaAccepting dfa)
where
fixpoint live =
let live' =
IntSet.union live $
IntSet.fromList
[i | (i, edges) <- IntMap.toList (dfaDelta dfa), any ((`IntSet.member` live) . snd) edges]
in if live' == live then live else fixpoint live'
-- | Whether the language is empty ('Nothing' when the automaton is too
-- large).
isEmpty :: Regex -> Maybe Bool
isEmpty r = IntSet.null . dfaAccepting <$> toDfa r
-- | Whether two expressions denote the same language ('Nothing' when the
-- automaton of their symmetric difference is too large).
equivalent :: Regex -> Regex -> Maybe Bool
equivalent a b
| a == b = Just True
| otherwise = isEmpty (union [difference a b, difference b a])
-- | Length of the shortest string of the language, if it is not empty.
minLength :: Dfa -> Maybe Int
minLength dfa = bfs (IntSet.singleton 0) [0] 0
where
bfs seen frontier d
| null frontier = Nothing
| any (`IntSet.member` dfaAccepting dfa) frontier = Just d
| otherwise =
let next = IntSet.toList (IntSet.fromList [j | i <- frontier, (_, j) <- edgesOf i, not (IntSet.member j seen)])
in bfs (IntSet.union seen (IntSet.fromList next)) next (d + 1)
edgesOf i = fromMaybe [] (IntMap.lookup i (dfaDelta dfa))
-- | Length of the longest string of the language, when the language is
-- finite and not empty.
maxLength :: Dfa -> Maybe Int
maxLength dfa
| not (IntSet.member 0 live) = Nothing
| otherwise = longest IntMap.empty [] 0 >>= \(_, l) -> l
where
live = liveStates dfa
edgesOf i = [j | (_, j) <- fromMaybe [] (IntMap.lookup i (dfaDelta dfa)), IntSet.member j live]
-- Longest path to an accepting state from each live state, by depth-first
-- search; a cycle through live states makes the language infinite.
longest memo path i
| i `elem` path = Nothing
| Just l <- IntMap.lookup i memo = Just (memo, Just l)
| otherwise = do
(memo', ls) <- foldlM (\(m, acc) j -> fmap (\(m', l) -> (m', l : acc)) (longest m (i : path) j)) (memo, []) (edgesOf i)
let here = if IntSet.member i (dfaAccepting dfa) then Just 0 else Nothing
best = maximumMaybe (here : [(+ 1) <$> l | l <- ls])
pure (maybe memo' (\b -> IntMap.insert i b memo') best, best)
maximumMaybe xs = case [x | Just x <- xs] of
[] -> Nothing
ys -> Just (maximum ys)
foldlM f z = \case
[] -> Just z
(y : ys) -> f z y >>= \z' -> foldlM f z' ys
-------------------------------------------------------------------------------
-- Rendering
-- | The expression in SMT-LIB syntax.
prettyRegex :: Regex -> Text
prettyRegex = \case
RSet [] -> "re.none"
RSet cs
| cs == fullSet -> "re.allchar"
| otherwise -> case map rangeText cs of
[t] -> t
ts -> app "re.union" ts
REps -> app "str.to_re" ["\"\""]
RCat a b -> app "re.++" [prettyRegex a, prettyRegex b]
RAlt xs -> app "re.union" (map prettyRegex (Set.toList xs))
RAnd xs -> app "re.inter" (map prettyRegex (Set.toList xs))
RStar r -> app "re.*" [prettyRegex r]
RNot (RSet []) -> "re.all"
RNot r -> app "re.comp" [prettyRegex r]
where
app f args = "(" <> T.unwords (f : args) <> ")"
rangeText (lo, hi)
| lo == hi = app "str.to_re" [charLit lo]
| otherwise = app "re.range" [charLit lo, charLit hi]
charLit c
| c >= 32 && c < 127 && c /= 34 && c /= 92 = T.pack ['"', toEnum c, '"']
| otherwise = "\"\\u{" <> T.pack (showHex c "") <> "}\""