packages feed

tavro-0.1.0.2: src/Tavro/Identify.hs

-- | which licenses a text is, or has in it.
--
-- like LicenseCompareHelper.matchingStandardLicenseIds, every listed
-- template is tried against the text. a template whose required words
-- aren't all in the text is skipped before any matching, which rules out
-- nearly the whole list for any one file. the rest run in parallel
module Tavro.Identify
  ( Search (..),
    Options (..),
    defaultOptions,
    Hit (..),
    How (..),
    identify,
    selectEntries,
    Explanation (..),
    explain,
  )
where

import Data.List (sortOn)
import Data.Ord (Down (..))
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Conc (par, pseq)
import Tavro.LicenseList
import Tavro.Match
import Tavro.Text (Token (..))

data Search
  = -- | whole-text matches, or if there are none, licenses and license
    -- headers inside the text
    Auto
  | -- | only whole-text matches
    WholeOnly
  | -- | whole-text matches, and licenses and headers inside the text
    Everything
  deriving stock (Eq, Show)

data How
  = -- | the license is the whole text, give or take what the matching
    -- guidelines let differ
    Whole
  | -- | the license's text is somewhere in the text
    Inside
  | -- | the license's standard header is somewhere in the text, like at
    -- the top of a source file
    Header
  deriving stock (Eq, Ord, Show)

data Options = Options
  { oSearch :: Search,
    oDeprecated :: Bool,
    oExceptions :: Bool,
    -- | only these ids, when not empty
    oOnly :: [Text],
    -- | try templates in parallel, for when only one text is being looked at
    oParallel :: Bool
  }

defaultOptions :: Options
defaultOptions = Options {oSearch = Auto, oDeprecated = False, oExceptions = True, oOnly = [], oParallel = True}

data Hit = Hit
  { hEntry :: Entry,
    hHow :: How,
    -- | first and last line of the match
    hLines :: (Int, Int),
    -- | first and one-past-last token, for overlap
    hSpan :: (Int, Int)
  }

selectEntries :: Options -> LicenseList -> [Entry]
selectEntries Options {..} ll = filter wanted (llEntries ll)
  where
    wanted e =
      (oDeprecated || not (eDeprecated e) || eId e `elem` oOnly)
        && (oExceptions || eKind e /= Exception)
        && (null oOnly || eId e `elem` oOnly)

identify :: Options -> LicenseList -> Text -> [Hit]
identify opts ll raw = case oSearch opts of
  WholeOnly -> whole
  Auto -> if null whole then partial else whole
  Everything -> whole <> [h | h <- partial, eId (hEntry h) `notElem` map (eId . hEntry) whole]
  where
    s = subject raw
    entries = selectEntries opts ll
    n = subjectSize s
    mapping = if oParallel opts then parallelMap else map
    tried mode matcher = [(e, r) | (e, Just r) <- zip entries (mapping (try mode . matcher) entries)]
    -- forced inside the Just, or sparking it would only build the Just
    try mode = \case
      Just (required, m) | all (subjectHas s) required -> let r = run mode m s in r `seq` Just r
      _ -> Nothing

    whole =
      sortOn
        (\h -> (Down (length (eRequired (hEntry h))), eId (hEntry h)))
        [hit Whole e 0 n | (e, Matched _ _) <- tried Exactly wholeLicense]

    -- a license's text and its header can both be in a file, like a GPL
    -- with its how-to-apply notice. the header is part of the text then
    partial =
      sortOn (\h -> (fst (hSpan h), Down (snd (hSpan h)), eId (hEntry h))) . dropContained $
        [hit Inside e a b | (e, Matched a b) <- tried Within wholeLicense]
          <> [hit Header e a b | (e, Matched a b) <- tried Within eHeader]

    wholeLicense e = Just (eRequired e, eMatcher e)

    hit how e a b =
      Hit
        { hEntry = e,
          hHow = how,
          hLines = (lineOfToken s a, lineOfToken s (max a (b - 1))),
          hSpan = (a, b)
        }

-- | a short license found inside a longer one that matched is part of it,
-- not a license of its own
dropContained :: [Hit] -> [Hit]
dropContained hs = [h | h <- hs, not (any (`strictlyContains` h) hs)]
  where
    strictlyContains g h =
      let (ga, gb) = hSpan g
          (ha, hb) = hSpan h
       in ga <= ha && hb <= gb && (ga, gb) /= (ha, hb)

-- | evaluate in parallel. a Result is strict, so weak head normal form is
-- the whole search
parallelMap :: (a -> b) -> [a] -> [b]
parallelMap f xs = let ys = map f xs in foldr par () ys `pseq` ys

data Explanation
  = Matches
  | -- | the template's required words that the text doesn't have at all
    MissingWords [Text]
  | -- | where the furthest attempt got stuck
    Differs
      { xLine :: Int,
        xExpected :: [Text],
        xFound :: Text
      }
  deriving stock (Eq, Show)

-- | why a text isn't one license, for --explain
explain :: Entry -> Text -> Explanation
explain e raw =
  let s = subject raw
      m = eMatcher e
   in case [k | k <- matcherRequired m, k `notElem` subjectKeys s] of
        missing@(_ : _) -> MissingWords missing
        [] -> case run Exactly m s of
          Matched _ _ -> Matches
          NoMatch pos pc ->
            Differs
              { xLine = lineOfToken s pos,
                xExpected = expectedAt m pc 12,
                xFound = snippet s pos
              }

snippet :: Subject -> Int -> Text
snippet s pos = case drop pos (subjectTokens s) of
  [] -> "<end of text>"
  t : _ -> T.unwords (T.words (T.take 100 (T.drop (tokStart t) (subjectText s))))