packages feed

tavro-0.1.0.2: src/Tavro/Regex.hs

-- | the regexes in a template's @match=@ fields.
--
-- they're written for java.util.regex, and Spdx-Java-Library compiles them
-- with CASE_INSENSITIVE and DOTALL. what the license list actually uses is a
-- small subset: literals, @.@, classes, @\\s@ and friends, groups,
-- alternation, and counted repeats like @.{0,5000}@. anything else is a
-- compile error, and the caller falls back to the var's original text.
--
-- matching doesn't return one match. it returns every position a match
-- starting at a given offset could end at, because the template matcher
-- wants to know which token boundaries a var can stretch to. that's done on
-- sets of positions instead of by backtracking, so a var like @.{0,5000}@
-- costs one pass and not 5000 retries
module Tavro.Regex
  ( Regex,
    compile,
    matchEnds,
    Ends,
    endsUpTo,
    anyEndIn,
    lastEnd,
    maxLength,
    spansToEnd,
  )
where

import Data.Char (chr, isAlphaNum, isDigit, isHexDigit, isSpace, toLower, toUpper)
import Data.IntSet (IntSet)
import Data.IntSet qualified as IS
import Data.List qualified as L
import Data.Text (Text)
import Data.Text qualified as T
import Data.Vector.Unboxed qualified as VU
import Numeric (readHex)

data Node
  = -- | one character. the predicate already ignores case
    One (Char -> Bool)
  | -- | @.@, which matches anything since Java's matcher runs with DOTALL
    Any
  | -- | @^@, only where the match started
    Start
  | Assert Boundary
  | Alt [Node]
  | Seq [Node]
  | Repeat Int (Maybe Int) Node

data Boundary = WordBoundary | NotWordBoundary
  deriving stock (Eq)

data Escape = Class (Char -> Bool) | Assertion Boundary

newtype Regex = Regex Node

compile :: Text -> Either String Regex
compile src = maybe (compileUncached src) Right (lookup src common)

-- | the patterns nearly every template uses, compiled once. .{0,20} alone
-- is ten thousand bullets
common :: [(Text, Regex)]
common = [(p, r) | p <- [".{0,20}", ".+", ".{0,5000}", ".*", "-{1,2}"], Right r <- [compileUncached p]]

compileUncached :: Text -> Either String Regex
compileUncached src = case parseAlt (T.unpack src) of
  Right (n, []) -> Right (Regex (simplify n))
  Right (_, rest) -> Left ("unexpected " <> take 10 rest)
  Left e -> Left e

-- | every offset @e@ such that the regex matches @chars[s..e)@ for one of
-- the starts @s@
matchEnds :: Regex -> VU.Vector Char -> IntSet -> IntSet
matchEnds re chars starts = fst (matchEndsAtEdge re chars starts)

matchEndsAtEdge :: Regex -> VU.Vector Char -> IntSet -> (IntSet, Bool)
matchEndsAtEdge (Regex n) chars starts = step chars starts n starts

-- | where matches can end, as a set or, for the usual @.{m,n}@ and @.+@
-- vars, one interval worked out without visiting it
data Ends
  = Points IntSet
  | -- | inclusive
    Span Int Int

-- | the ends of matches that start in @[from, to]@ and stay within the first
-- @hi@ characters. ends past @hi@ can't change what's before it, so a var
-- only looks as far as the template search does
endsUpTo :: Int -> Regex -> VU.Vector Char -> Int -> Int -> (Ends, Bool)
endsUpTo hi0 re@(Regex node) chars from to = case node of
  -- with DOTALL, . matches anything, so from a range of starts the ends are
  -- a range too
  Repeat mn mx Any -> (Span (from + mn) (maybe hi (min hi . (to +)) mx), maybe False (\m -> to + m <= hi) mx)
  _ ->
    let (ends, atEdge) = matchEndsAtEdge re (VU.take hi chars) (IS.fromDistinctAscList [from .. to])
     in (Points ends, not atEdge)
  where
    hi = min hi0 (VU.length chars)

lastEnd :: Ends -> Int
lastEnd = \case
  Span _ hi -> hi
  Points set -> maybe (-1) fst (IS.maxView set)

-- | is there an end in @[a, b]@
anyEndIn :: Ends -> Int -> Int -> Bool
anyEndIn ends a b = case ends of
  Span lo hi -> max a lo <= min b hi
  Points set -> maybe False (<= b) (IS.lookupGE a set)

step :: VU.Vector Char -> IntSet -> Node -> IntSet -> (IntSet, Bool)
step chars lo node set
  | IS.null set = (set, False)
  | otherwise = case node of
      One p -> (IS.fromDistinctAscList [i + 1 | i <- IS.toAscList set, i < len, p (chars VU.! i)], waitsAtEdge)
      Any -> (IS.fromDistinctAscList [i + 1 | i <- IS.toAscList set, i < len], waitsAtEdge)
      Start -> (IS.intersection lo set, False)
      Assert b -> (IS.filter (\i -> boundaryAt i == b) set, False)
      Alt ns ->
        let rs = map (\n -> step chars lo n set) ns
         in (IS.unions (map fst rs), any snd rs)
      Seq ns -> L.foldl' (\(s, edge) n -> let (s', edge') = step chars lo n s in (s', edge || edge')) (set, False) ns
      Repeat mn mx (One p) -> runs (Just p) mn mx set
      Repeat mn mx Any -> runs Nothing mn mx set
      Repeat mn mx n -> repeatN mn mx n set
  where
    len = VU.length chars
    waitsAtEdge = IS.member len set
    wordAt i = i >= 0 && i < len && isWord (chars VU.! i)
    boundaryAt i = if wordAt (i - 1) /= wordAt i then WordBoundary else NotWordBoundary

    -- a repeated single character: from each start the run of matching
    -- characters gives a whole interval of ends at once
    runs p mn mx s =
      ( IS.fromDistinctAscList (concatMap expand (merge (intervals (IS.toAscList s) 0))),
        scan (IS.findMax s) >= len
      )
      where
        intervals [] _ = []
        intervals (i : is) prevEnd =
          let runEnd = if i < prevEnd then prevEnd else scan i
              hi = maybe runEnd (min runEnd . (i +)) mx
           in if hi - i >= mn then (i + mn, hi) : intervals is runEnd else intervals is runEnd
        -- a run of . goes to the end without looking
        scan i = case p of
          Nothing -> len
          Just q -> if i < len && q (chars VU.! i) then scan (i + 1) else i
        merge ((a, b) : (c, d) : rest)
          | c <= b + 1 = merge ((a, max b d) : rest)
          | otherwise = (a, b) : merge ((c, d) : rest)
        merge xs = xs
        expand (a, b) = [a .. b]

    -- apply n at least mn times, then keep going while that reaches positions
    -- it hasn't yet. a position reached again later has less budget left, so
    -- anything it leads to was already found
    repeatN mn mx n s0 = go (min mn 100000) s0 False
      where
        go 0 s edge = more mn s s edge
        go k s edge =
          let (s', edge') = step chars lo n s
           in if IS.null s' then (s', edge || edge') else go (k - 1 :: Int) s' (edge || edge')
        more k acc frontier edge
          | IS.null frontier || maybe False (k >=) mx = (acc, edge)
          | otherwise =
              let (reached, edge') = step chars lo n frontier
                  new = reached `IS.difference` acc
               in more (k + 1) (acc `IS.union` new) new (edge || edge')

spansToEnd :: Regex -> Bool
spansToEnd (Regex node) = case node of
  Repeat _ Nothing Any -> True
  _ -> False

maxLength :: Regex -> Maybe Int
maxLength (Regex node) = go node
  where
    go = \case
      One _ -> Just 1
      Any -> Just 1
      Start -> Just 0
      Assert _ -> Just 0
      Alt ns -> maximum <$> traverse go ns
      Seq ns -> sum <$> traverse go ns
      Repeat _ mx n -> (*) <$> mx <*> go n

-- | drop the one-element sequences the parser builds, so endsUpTo can see
-- a bare .{m,n}
simplify :: Node -> Node
simplify = \case
  Seq [n] -> simplify n
  Seq ns -> Seq (map simplify ns)
  Alt [n] -> simplify n
  Alt ns -> Alt (map simplify ns)
  Repeat mn mx n -> Repeat mn mx (simplify n)
  n -> n

isWord :: Char -> Bool
isWord c = isAlphaNum c || c == '_'

type P a = String -> Either String (a, String)

parseAlt :: P Node
parseAlt s = do
  (first, rest) <- parseSeq s
  case rest of
    '|' : more -> do
      (other, rest') <- parseAlt more
      pure (Alt (first : alts other), rest')
    _ -> pure (first, rest)
  where
    alts (Alt ns) = ns
    alts n = [n]

parseSeq :: P Node
parseSeq = go []
  where
    go acc s = case s of
      [] -> done
      '|' : _ -> done
      ')' : _ -> done
      _ -> do
        (atom, rest) <- parseAtom s
        (quantified, rest') <- parseQuantifiers atom rest
        go (quantified : acc) rest'
      where
        done = pure (Seq (reverse acc), s)

parseQuantifiers :: Node -> P Node
parseQuantifiers atom s = case s of
  '*' : rest -> again (Repeat 0 Nothing atom) rest
  '+' : rest -> again (Repeat 1 Nothing atom) rest
  '?' : rest -> again (Repeat 0 (Just 1) atom) rest
  '{' : rest | Just (mn, mx, rest') <- counted rest -> again (Repeat mn mx atom) rest'
  _ -> pure (atom, s)
  where
    -- lazy and possessive suffixes change which match is found first, and
    -- this finds all of them, so they can be dropped
    again n rest = parseQuantifiers n (dropLazy rest)
    dropLazy ('?' : r) = r
    dropLazy ('+' : r) = r
    dropLazy r = r
    counted r = do
      let (a, r1) = span isDigit r
      mn <- readNat a
      case r1 of
        '}' : r2 -> Just (mn, Just mn, r2)
        ',' : '}' : r2 -> Just (mn, Nothing, r2)
        ',' : r2 -> do
          let (b, r3) = span isDigit r2
          mx <- readNat b
          case r3 of
            '}' : r4 | mx >= mn -> Just (mn, Just mx, r4)
            _ -> Nothing
        _ -> Nothing
    readNat ds = if null ds then Nothing else Just (read ds)

parseAtom :: P Node
parseAtom s = case s of
  '(' : '?' : ':' : rest -> group rest
  '(' : '?' : _ -> Left "unsupported group syntax"
  '(' : rest -> group rest
  '[' : rest -> parseClass rest
  '.' : rest -> pure (Any, rest)
  '^' : rest -> pure (Start, rest)
  -- the slice a var is matched against ends wherever the match does, so $
  -- at the end of a pattern always holds
  '$' : rest -> pure (Seq [], rest)
  '\\' : rest -> do
    (e, rest') <- parseEscape rest
    pure (escapeNode e, rest')
  ' ' : rest -> pure (Repeat 1 Nothing (One isSpace), dropWhile (== ' ') rest)
  c : rest -> pure (One (literal c), rest)
  [] -> Left "unexpected end"
  where
    group rest = do
      (n, rest') <- parseAlt rest
      case rest' of
        ')' : more -> pure (n, more)
        _ -> Left "unclosed group"

escapeNode :: Escape -> Node
escapeNode = \case
  Class p -> One p
  Assertion b -> Assert b

parseEscape :: String -> Either String (Escape, String)
parseEscape s = case s of
  'd' : r -> cls isDigit r
  'D' : r -> cls (not . isDigit) r
  's' : r -> cls isJavaSpace r
  'S' : r -> cls (not . isJavaSpace) r
  'w' : r -> cls isWord r
  'W' : r -> cls (not . isWord) r
  'b' : r -> pure (Assertion WordBoundary, r)
  'B' : r -> pure (Assertion NotWordBoundary, r)
  _ -> do
    (c, r) <- escapedChar s
    pure (Class (literal c), r)
  where
    cls p r = pure (Class p, r)

escapedChar :: String -> Either String (Char, String)
escapedChar s = case s of
  't' : r -> pure ('\t', r)
  'n' : r -> pure ('\n', r)
  'r' : r -> pure ('\r', r)
  'f' : r -> pure ('\f', r)
  'e' : r -> pure ('\ESC', r)
  'x' : a : b : r | all isHexDigit [a, b] -> pure (hex [a, b], r)
  'u' : a : b : c : d : r | all isHexDigit [a, b, c, d] -> pure (hex [a, b, c, d], r)
  c : r -> pure (c, r)
  [] -> Left "trailing backslash"
  where
    hex ds = case readHex ds of
      (v, _) : _ -> chr v
      [] -> '\0'

parseClass :: P Node
parseClass s0 = do
  let (negated, s1) = case s0 of
        '^' : r -> (True, r)
        r -> (False, r)
  (preds, rest) <- items True s1
  let p c = any ($ c) preds
  pure (One (if negated then not . ignoringCase p else ignoringCase p), rest)
  where
    -- a ] right after [ or [^ is a literal
    items first s = case s of
      ']' : r | not first -> pure ([], r)
      [] -> Left "unclosed character class"
      '\\' : r -> do
        (e, r') <- parseEscape r
        case e of
          Class p -> continue p r'
          Assertion _ -> Left "boundary inside a class"
      c : '-' : d : r | d /= ']' -> do
        (hi, r') <- if d == '\\' then escapedChar r else pure (d, r)
        continue (\x -> x >= c && x <= hi) r'
      c : r -> continue (== c) r
    continue p r = do
      (ps, r') <- items False r
      pure (p : ps, r')

literal :: Char -> Char -> Bool
literal c = ignoringCase (== c)

ignoringCase :: (Char -> Bool) -> Char -> Bool
ignoringCase p x = p x || p (toLower x) || p (toUpper x)

isJavaSpace :: Char -> Bool
isJavaSpace c = c `elem` (" \t\n\x0B\f\r" :: String)