packages feed

tavro-0.1.0.2: src/Tavro/Match.hs

-- | matching text against a compiled template.
--
-- Spdx-Java-Library's CompareTemplateOutputHandler walks the template tree
-- greedily: each var or optional looks ahead for the next 15 tokens of
-- normal text and commits to the first place they line up. that's fast but
-- can commit to the wrong place, like a var whose next words also show up
-- inside it.
--
-- here the template becomes a little program over tokens (literal, var,
-- split, jump) and the search tries every way through it, backtracking
-- with a visited set of (instruction, token) pairs, so no pair is explored
-- twice. a var can end at any token boundary its regex allows, but when a
-- literal follows it only the boundaries where that literal shows up are
-- worth trying, which keeps the search close to linear on real licenses
module Tavro.Match
  ( Matcher,
    Subject,
    Mode (..),
    Result (..),
    compileMatcher,
    matcherWarnings,
    matcherRequired,
    subject,
    subjectKeys,
    subjectHas,
    subjectText,
    subjectTokens,
    subjectSize,
    lineOfToken,
    run,
    expectedAt,
  )
where

import Control.Monad.ST (runST)
import Data.Char (isSpace)
import Data.Containers.ListUtils (nubOrd)
import Data.HashMap.Strict qualified as HM
import Data.Int (Int32)
import Data.IntSet qualified as IS
import Data.List (sortOn)
import Data.Map.Strict qualified as Map
import Data.Set (Set)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Vector qualified as V
import Data.Vector.Unboxed qualified as VU
import Data.Vector.Unboxed.Mutable qualified as MVU
import Tavro.Regex (Regex)
import Tavro.Regex qualified as Re
import Tavro.Template
import Tavro.Text

data Instr
  = ILit !Text
  | -- | name, regex
    IVar !Text !Regex
  | -- | try the first target, then the second
    ISplit !Int !Int
  | IJmp !Int
  | IDone

data Matcher = Matcher
  { mProg :: V.Vector Instr,
    -- | keys every match has to contain: the literals outside optionals
    mRequired :: [Text],
    -- | the pc of the first required literal, where a search inside a
    -- larger text can start
    mAnchor :: Maybe Int,
    mWarnings :: [Text]
  }

matcherWarnings :: Matcher -> [Text]
matcherWarnings = mWarnings

matcherRequired :: Matcher -> [Text]
matcherRequired = mRequired

compileMatcher :: [Node] -> Matcher
compileMatcher nodes =
  Matcher
    { mProg = V.fromList (code <> [IDone]),
      mRequired = nubOrd [k | ILit k <- topLevel],
      mAnchor = case [pc | (pc, ILit _, True) <- zip3 [0 ..] code topFlags] of
        pc : _ -> Just pc
        [] -> Nothing,
      mWarnings = warnings
    }
  where
    (code, warnings, topFlags) = genSeq 0 True nodes
    topLevel = [i | (i, True) <- zip code topFlags]

-- | the instructions for a sequence starting at pc, any warnings, and for
-- each instruction whether it's outside every choice
genSeq :: Int -> Bool -> [Node] -> ([Instr], [Text], [Bool])
genSeq _ _ [] = ([], [], [])
genSeq pc top (n : ns) =
  let (is, ws, fs) = gen pc top n
      (is', ws', fs') = genSeq (pc + length is) top ns
   in (is <> is', ws <> ws', fs <> fs')

gen :: Int -> Bool -> Node -> ([Instr], [Text], [Bool])
gen pc top = \case
  Lit t -> lits (map tokKey (tokenize t))
  Var name original match -> case Re.compile match of
    Right re -> ([IVar name re], [], [False])
    -- an unusable regex can still match the text it stands for
    Left err ->
      let (is, _, fs) = lits (map tokKey (tokenize original))
       in (is, ["var " <> name <> ": " <> T.pack err <> ", matching its original text instead"], fs)
  Choice alts -> choice pc alts
  where
    lits ks = (map ILit ks, [], map (const top) ks)

-- | split to each alternative in turn, every one but the last jumping to the
-- end when it's done
choice :: Int -> [[Node]] -> ([Instr], [Text], [Bool])
choice _ [] = ([], [], [])
choice pc [alt] = genSeq pc False alt
choice pc (alt : alts) =
  let (body, ws, _) = genSeq (pc + 1) False alt
      restPc = pc + 1 + length body + 1
      (rest, ws', _) = choice restPc alts
      end = restPc + length rest
      is = ISplit (pc + 1) restPc : body <> [IJmp end] <> rest
   in (is, ws <> ws', map (const False) is)

data Subject = Subject
  { sText :: Text,
    sChars :: VU.Vector Char,
    sKeyIds :: Map.Map Text Int,
    sKeys :: VU.Vector Int32,
    sStarts :: VU.Vector Int32,
    sEnds :: VU.Vector Int32,
    -- | the token positions of key i are sOccurrences[sOccurrenceStart[i] .. sOccurrenceStart[i + 1]), ascending
    sOccurrenceStart :: VU.Vector Int,
    sOccurrences :: VU.Vector Int32,
    sNewlines :: VU.Vector Int,
    sParagraphBreaks :: VU.Vector Int
  }

subject :: Text -> Subject
subject raw =
  Subject
    { sText = txt,
      sChars = chars,
      sKeyIds = keyIds,
      sKeys = keys,
      sStarts = starts,
      sEnds = ends,
      sOccurrenceStart = occurrenceStart,
      sOccurrences = occurrences,
      sNewlines = newlines,
      sParagraphBreaks = VU.fromList [a | (a, b) <- zip (VU.toList newlines) (drop 1 (VU.toList newlines)), VU.all isSpace (VU.slice a (b - a) chars)]
    }
  where
    txt = prepare raw
    chars = VU.fromListN (T.length txt) (T.unpack txt)
    newlines = VU.elemIndices '\n' chars
    (keyIds, keys, starts, ends) = internTokens (tokenize txt)
    (occurrenceStart, occurrences) = groupByKey (Map.size keyIds) keys

internTokens :: [Token] -> (Map.Map Text Int, VU.Vector Int32, VU.Vector Int32, VU.Vector Int32)
internTokens toks = runST $ do
  let capacity = 1024
  ks <- MVU.new capacity
  ss <- MVU.new capacity
  es <- MVU.new capacity
  let go !ids !count ks' ss' es' = \case
        [] -> do
          k <- VU.freeze (MVU.take count ks')
          st <- VU.freeze (MVU.take count ss')
          en <- VU.freeze (MVU.take count es')
          pure (Map.fromList (HM.toList ids), k, st, en)
        Token key st en : rest -> do
          (ks'', ss'', es'') <-
            if count == MVU.length ks'
              then (,,) <$> MVU.grow ks' count <*> MVU.grow ss' count <*> MVU.grow es' count
              else pure (ks', ss', es')
          let (i, ids') = case HM.lookup key ids of
                Just known -> (known, ids)
                Nothing -> let new = HM.size ids in (new, HM.insert key new ids)
          MVU.write ks'' count (fromIntegral i)
          MVU.write ss'' count (fromIntegral st)
          MVU.write es'' count (fromIntegral en)
          go ids' (count + 1) ks'' ss'' es'' rest
  go HM.empty 0 ks ss es toks

groupByKey :: Int -> VU.Vector Int32 -> (VU.Vector Int, VU.Vector Int32)
groupByKey keyCount keys = runST $ do
  let counts = VU.accumulate (+) (VU.replicate keyCount 0) (VU.map (\k -> (fromIntegral k, 1)) keys)
      offsets = VU.prescanl' (+) 0 counts `VU.snoc` VU.length keys
  cursor <- VU.thaw (VU.take keyCount offsets)
  out <- MVU.new (VU.length keys)
  VU.iforM_ keys $ \pos key -> do
    let k = fromIntegral key
    at <- MVU.read cursor k
    MVU.write out at (fromIntegral pos)
    MVU.write cursor k (at + 1)
  (,) offsets <$> VU.freeze out

subjectHas :: Subject -> Text -> Bool
subjectHas s k = Map.member k (sKeyIds s)

subjectKeys :: Subject -> Set Text
subjectKeys = Map.keysSet . sKeyIds

subjectText :: Subject -> Text
subjectText = sText

subjectSize :: Subject -> Int
subjectSize = VU.length . sKeys

-- | the 1-based line a token starts on. one past the last token is the
-- last line
lineOfToken :: Subject -> Int -> Int
lineOfToken s i = 1 + newlinesBefore 0 (VU.length nls)
  where
    nls = sNewlines s
    off
      | i < VU.length (sKeys s) = fromIntegral (sStarts s VU.! i)
      | otherwise = max 0 (VU.length (sChars s) - 1)
    newlinesBefore lo hi
      | lo >= hi = lo
      | nls VU.! mid < off = newlinesBefore (mid + 1) hi
      | otherwise = newlinesBefore lo mid
      where
        mid = (lo + hi) `div` 2

subjectTokens :: Subject -> [Token]
subjectTokens s = zipWith3 Token (map ((keyTexts V.!) . fromIntegral) (VU.toList (sKeys s))) (map fromIntegral (VU.toList (sStarts s))) (map fromIntegral (VU.toList (sEnds s)))
  where
    keyTexts = V.fromList (map fst (sortOn snd (Map.toList (sKeyIds s))))

data Mode
  = -- | the whole text is the license (B.3.3: no additional text)
    Exactly
  | -- | the license is somewhere inside the text
    Within
  deriving stock (Eq, Show)

data Result
  = -- | first and one-past-last token of the match
    Matched !Int !Int
  | -- | the furthest token any attempt got to, and the instruction it was
    -- stuck on, for explaining the failure
    NoMatch !Int !Int
  deriving stock (Eq, Show)

run :: Mode -> Matcher -> Subject -> Result
run mode m s
  | not (all (`Map.member` sKeyIds s) (mRequired m)) = NoMatch 0 0
  | otherwise = case mode of
      Exactly -> fst (search (== n) IS.empty (0, 0) 0 [(0, 0)])
      Within -> case firstStart (const True) IS.empty (0, 0) starts of
        (Matched a b, pc) -> tighten pc a b
        (r, _) -> r
  where
    prog = mProg m
    n = VU.length (sKeys s)
    width = n + 1
    keyAt i = fromIntegral (sKeys s VU.! i) :: Int
    litIds = V.map (\case ILit k -> Map.findWithDefault (-1) k (sKeyIds s); _ -> -1) prog
    occurrencesFrom :: Int -> Int -> [Int]
    occurrencesFrom k from
      | k < 0 = []
      | otherwise =
          let lo = sOccurrenceStart s VU.! k
              ps = VU.slice lo (sOccurrenceStart s VU.! (k + 1) - lo) (sOccurrences s)
           in map fromIntegral (VU.toList (VU.drop (firstAtLeast ps (fromIntegral from) 0 (VU.length ps)) ps))
    firstAtLeast ps x lo hi
      | lo >= hi = lo
      | ps VU.! mid < x = firstAtLeast ps x (mid + 1) hi
      | otherwise = firstAtLeast ps x lo mid
      where
        mid = (lo + hi) `div` 2
    startOff i = if i < n then fromIntegral (sStarts s VU.! i) else VU.length (sChars s)
    gapStart i = if i > 0 then fromIntegral (sEnds s VU.! (i - 1)) else 0

    -- inside a larger text, a match starts at a literal that can come first
    -- (after leaving out leading optionals), or at the first required one.
    -- vars before that, like a copyright line, are left unmatched
    starts =
      sortOn
        fst
        [ (pos, pc)
        | pc <- IS.toList (IS.fromList (maybe id (:) (mAnchor m) (leadingLits 0 IS.empty))),
          ILit _ <- [prog V.! pc],
          pos <- occurrencesFrom (litIds V.! pc) 0
        ]
    leadingLits pc seen
      | pc `IS.member` seen = []
      | otherwise = case prog V.! pc of
          ILit _ -> [pc]
          ISplit a b -> leadingLits a seen' <> leadingLits b seen'
          IJmp a -> leadingLits a seen'
          _ -> []
      where
        seen' = IS.insert pc seen

    -- states that failed once fail from any start, as long as what counts
    -- as done stays the same, so the visited set carries over
    firstStart done visited best = \case
      [] -> (uncurry NoMatch best, 0)
      (pos, pc) : rest -> case search done visited best pos [(pc, pos)] of
        (r@Matched {}, _) -> (r, pc)
        (NoMatch bp bpc, visited') -> firstStart done visited' (bp, bpc) rest

    -- the leftmost match can start too early: a header's
    -- Copyright <<var .+>> matches from the first "copyright" anywhere above
    -- it. so try later places for the same first literal inside the match,
    -- last first, for one that ends in the same place. only the same
    -- literal, so a title the match starts with isn't traded for the first
    -- required words after it
    tighten pc a b =
      let later = reverse [st | st@(pos, pc') <- starts, pc' == pc, pos > a, pos < b]
       in case firstStart (== b) IS.empty (0, 0) later of
            (r@Matched {}, _) -> r
            (NoMatch _ _, _) -> Matched a b

    search done visited best@(bestPos, _) origin = \case
      [] -> (uncurry NoMatch best, visited)
      (pc, pos) : stack
        | IS.member key visited -> search done visited best origin stack
        | otherwise -> case prog V.! pc of
            ILit _
              | pos < n && keyAt pos == litIds V.! pc -> continue [(pc + 1, pos + 1)]
              | otherwise -> stuck
            IJmp a -> continue [(a, pos)]
            ISplit a b -> continue [(a, pos), (b, pos)]
            IDone
              | done pos -> (Matched origin pos, visited')
              | otherwise -> stuck
            IVar _ re -> case varEnds re pc pos of
              [] -> stuck
              js -> continue [(pc + 1, j) | j <- js]
        where
          key = pc * width + pos
          visited' = IS.insert key visited
          continue next = search done visited' best' origin (next <> stack)
          stuck = search done visited' best' origin stack
          !best' = if pos > bestPos then (pos, pc) else best

    -- the token positions a var starting at pos can end at, nearest first.
    -- the list is lazy: candidates are checked in groups of 1, 2, 4, ...,
    -- each with the regex run only as far as the group's last candidate, so
    -- a .+ var whose match comes early never scans the rest of the text
    varEnds re pc pos =
      let follow = nextReal (pc + 1)
          reachable = case Re.maxLength re of
            Just len -> takeWhile (\j -> lowestEnd j <= startOff pos + len)
            Nothing
              | Re.spansToEnd re && not commitsLikeJava -> takeWhile (\j -> lowestEnd j <= paragraphEnd (startOff pos))
              | otherwise -> id
          candidates = reachable $ case prog V.! follow of
            ILit _ -> occurrencesFrom (litIds V.! follow) pos
            _ -> [pos .. n]
          lowestEnd j = if j > pos then fromIntegral (sStarts s VU.! (j - 1)) + 1 else gapStart j
          -- a var can start anywhere between the token before it and its
          -- first token, since the gap can hold punctuation that was
          -- dropped, like the // in https://
          inGroups size cs = case splitAt size cs of
            ([], _) -> []
            (group, rest) ->
              let (ends, complete) = Re.endsUpTo (startOff (last group)) re (sChars s) (gapStart pos) (startOff pos)
                  later
                    | complete = filter (fits ends) (takeWhile (\j -> lowestEnd j <= Re.lastEnd ends) rest)
                    | otherwise = inGroups (size * 2) rest
               in filter (fits ends) group <> later
          -- like Java, which counts the tokens in what the regex matched,
          -- a match can end partway into the var's last token: (\*or\*|or)
          -- covers a token or* whose leading * went with the comment markers
          fits ends j = Re.anyEndIn ends (lowestEnd j) (startOff j)
          followingText = map (litIds V.!) (takeWhile isLit (take 15 [follow .. V.length prog - 1]))
          commitsLikeJava = Re.spansToEnd re && length followingText >= 3
          linesUp j = and [j + d < n && keyAt (j + d) == k | (d, k) <- zip [0 ..] followingText]
          firstFit
            | commitsLikeJava = take 1 . filter linesUp
            | otherwise = id
       in firstFit (inGroups 1 candidates)
    isLit pc = case prog V.! pc of
      ILit _ -> True
      _ -> False
    paragraphEnd off =
      let breaks = sParagraphBreaks s
          i = firstAtLeastInt breaks off 0 (VU.length breaks)
       in if i < VU.length breaks then breaks VU.! i else VU.length (sChars s)
    firstAtLeastInt ps x lo hi
      | lo >= hi = lo
      | ps VU.! mid < x = firstAtLeastInt ps x (mid + 1) hi
      | otherwise = firstAtLeastInt ps x lo mid
      where
        mid = (lo + hi) `div` 2
    nextReal pc = case prog V.! pc of
      IJmp a -> nextReal a
      _ -> pc

-- | what the template expects from a pc on: literal keys and var names,
-- following the first alternative of each choice
expectedAt :: Matcher -> Int -> Int -> [Text]
expectedAt m pc0 count = go pc0 count (IS.empty :: IS.IntSet)
  where
    prog = mProg m
    go pc k seen
      | k <= 0 || pc >= V.length prog || IS.member pc seen = []
      | otherwise =
          let seen' = IS.insert pc seen
           in case prog V.! pc of
                ILit t -> t : go (pc + 1) (k - 1) seen'
                IVar name _ -> ("<" <> name <> ">") : go (pc + 1) (k - 1) seen'
                ISplit a _ -> go a k seen'
                IJmp a -> go a k seen'
                IDone -> ["<end of license>"]