packages feed

tavro-0.1.0.2: src/Tavro/Text.hs

{-# LANGUAGE MultiWayIf #-}

-- | normalizing and tokenizing license text, after Spdx-Java-Library's
-- LicenseTextHelper and the SPDX matching guidelines (spec annex B).
--
-- two steps:
--
-- * 'prepare' rewrites the text one character for one, so offsets into the
--   result are offsets into the original. it unifies quotes, dashes, and odd
--   spaces (B.4, B.6) and blanks out comment markers at the start and end of
--   lines (B.7) and separator lines like @-----@.
--
-- * 'tokenize' splits that into words and punctuation and gives each token a
--   key. tokens are equivalent when their keys are equal, which covers case
--   (B.5), dashes, varietal spellings (B.9), @(c)@/@©@/@copyright@ (B.10) and
--   http/https (B.14). comment-ish tokens like @*@ and @#@ are dropped.
--
-- Java does some of the key work by rewriting the whole text first (@per
-- cent@ to @percent@ and so on). here it happens on tokens instead, so the
-- character offsets stay put. var regexes run on the prepared text
module Tavro.Text
  ( Token (..),
    prepare,
    prepareTemplate,
    tokenize,
    tokenKeys,
    isSeparator,
    decodeLenient,
  )
where

import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Char (isSpace, toLower)
import Data.HashMap.Strict qualified as HM
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Data.Text.Unsafe qualified as TU

data Token = Token
  { -- | what equivalence compares
    tokKey :: !Text,
    -- | character offsets into the prepared text, end exclusive
    tokStart :: !Int,
    tokEnd :: !Int
  }
  deriving stock (Eq, Show)

decodeLenient :: ByteString -> Text
decodeLenient bytes = case TE.decodeUtf8' bytes of
  Right t -> t
  Left _ -> T.intercalate "\n" (map line (BS.split 10 bytes))
  where
    line l = either (const (TE.decodeLatin1 l)) id (TE.decodeUtf8' l)

prepare :: Text -> Text
prepare = T.intercalate "\n" . map stripLine . T.splitOn "\n" . T.map normChar

-- | 'prepare' for a template, where a line can start with a tag. a comment
-- marker right after a leading beginOptional is blanked out too, like
-- Java's BEGIN_OPTIONAL_COMMENT_PATTERN does
prepareTemplate :: Text -> Text
prepareTemplate = T.intercalate "\n" . map line . T.splitOn "\n" . T.map normChar
  where
    line l =
      let (ws, body) = T.span isSpace l
       in case T.stripPrefix "<<beginOptional>>" body of
            Just after -> ws <> "<<beginOptional>>" <> stripLine after
            Nothing -> stripLine l

normChar :: Char -> Char
normChar c
  | c < '\x80' = case c of
      '`' -> '\''
      '\r' -> ' '
      _ -> c
  | otherwise = case c of
      '\x2018' -> '\''
      '\x2019' -> '\''
      '\x201B' -> '\''
      '\x201A' -> '\''
      '\x201C' -> '"'
      '\x201D' -> '"'
      '\x201F' -> '"'
      '\x201E' -> '"'
      '\x00A0' -> ' '
      '\x202F' -> ' '
      '\x2007' -> ' '
      '\x2060' -> ' '
      '\xFEFF' -> ' '
      '\x200B' -> ' '
      '\x2009' -> ' '
      '\xFF0C' -> ','
      '\xFE10' -> ','
      '\xFE50' -> ','
      '\xFE58' -> '-'
      '\xFF0D' -> '-'
      '\x2028' -> '\n'
      _
        | c >= '\x2010' && c <= '\x2015' -> '-'
        | otherwise -> c

-- | blank out a leading comment marker, a trailing one, and a trailing
-- separator run, like LicenseCompareHelper.removeCommentChars and
-- LicenseTextHelper.removeLineSeparators
stripLine :: Text -> Text
stripLine = separators . start . end
  where
    blank t = T.replicate (T.length t) " "
    end l =
      let (body, trailing) = splitTrailingSpace l
       in case [m | m <- ["*/", "-->", "-}", "*)"], m `T.isSuffixOf` body] of
            m : _ -> T.dropEnd (T.length m) body <> blank m <> trailing
            [] | Just (b, '*') <- T.unsnoc body, Just (_, w) <- T.unsnoc b, isSpace w -> b <> " " <> trailing
            _ -> l
    start l =
      let (ws, body) = T.span isSpace l
       in case [m | m <- startMarkers, m `T.isPrefixOf` body] of
            m : _ -> ws <> blank m <> T.drop (T.length m) body
            [] -> l
    separators l =
      let (body, trailing) = splitTrailingSpace l
          run = T.takeWhileEnd (`elem` ("-=*" :: String)) body
       in if T.length run >= 3 then T.dropEnd (T.length run) body <> blank run <> trailing else l

-- | in the order Java's alternation tries them
startMarkers :: [Text]
startMarkers = ["//", "/*", "*", "#", "' ", "REM ", "<!--", "--", ";", "(*", "{-"]

splitTrailingSpace :: Text -> (Text, Text)
splitTrailingSpace l = let body = T.dropWhileEnd isSpace l in (body, T.drop (T.length body) l)

-- | the separators Java's TOKEN_SPLIT_PATTERN splits on, besides whitespace.
-- each one is a token of its own
isSeparator :: Char -> Bool
isSeparator = \case
  '.' -> True
  ',' -> True
  '?' -> True
  '\'' -> True
  '"' -> True
  '(' -> True
  ')' -> True
  ';' -> True
  ':' -> True
  '/' -> True
  '[' -> True
  ']' -> True
  '<' -> True
  '>' -> True
  _ -> False

-- | tokens of already 'prepare'd text
tokenize :: Text -> [Token]
tokenize = keyed . rawTokens

rawTokens :: Text -> [Token]
rawTokens txt = between 0 0
  where
    size = TU.lengthWord8 txt
    between !byte !char
      | byte >= size = []
      | otherwise =
          let TU.Iter c width = TU.iter txt byte
           in if
                | isSpaceFast c -> between (byte + width) (char + 1)
                | Just key <- separatorKey c -> Token key char (char + 1) : between (byte + width) (char + 1)
                | otherwise -> word byte char (byte + width) (char + 1) (hasUpper c)
    word !startByte !startChar !byte !char !upper
      | byte < size,
        TU.Iter c width <- TU.iter txt byte,
        not (isSpaceFast c),
        not (isSeparator c) =
          word startByte startChar (byte + width) (char + 1) (upper || hasUpper c)
      | otherwise =
          let w = TU.takeWord8 (byte - startByte) (TU.dropWord8 startByte txt)
           in Token (if upper then T.toLower w else w) startChar char : between byte char

isSpaceFast :: Char -> Bool
isSpaceFast c
  | c <= ' ' = c == ' ' || (c >= '\t' && c <= '\r')
  | c < '\x80' = False
  | otherwise = isSpace c

hasUpper :: Char -> Bool
hasUpper c
  | c < '\x80' = c >= 'A' && c <= 'Z'
  | otherwise = toLower c /= c

separatorKey :: Char -> Maybe Text
separatorKey = \case
  '.' -> Just "."
  ',' -> Just ","
  '?' -> Just "?"
  '\'' -> Just "'"
  '"' -> Just "\""
  '(' -> Just "("
  ')' -> Just ")"
  ';' -> Just ";"
  ':' -> Just ":"
  '/' -> Just "/"
  '[' -> Just "["
  ']' -> Just "]"
  '<' -> Just "<"
  '>' -> Just ">"
  _ -> Nothing

-- | the multi-word equivalences, then dropping comment-ish tokens and
-- normalizing the rest, in one pass
keyed :: [Token] -> [Token]
keyed ts = case ts of
  Token "(" s _ : Token "c" _ _ : Token ")" _ e : rest | e - s == 3 -> Token "-c-" s e : keyed rest
  Token "'" s e1 : Token "'" s2 e : rest | s2 == e1 -> Token "'" s e : keyed rest
  Token "copyright" s _ : Token w _ e : rest
    | Just k <- lookup w holders -> Token k s e : keyed rest
  Token "per" s _ : Token "cent" _ e : rest -> Token "percent" s e : keyed rest
  Token "sub" s _ : Token "license" _ e : rest -> Token "sub-license" s e : keyed rest
  t : rest
    | skippable (tokKey t) -> keyed rest
    | otherwise -> t {tokKey = normalizeKey (tokKey t)} : keyed rest
  [] -> []
  where
    holders =
      [ ("holder", "copyright-holder"),
        ("holders", "copyright-holders"),
        ("owner", "copyright-holder"),
        ("owners", "copyright-holders")
      ]

-- | keys come from tokenize already lowercased
normalizeKey :: Text -> Text
normalizeKey k =
  let k' = if "--" `T.isInfixOf` k then collapseDashes k else k
   in HM.lookupDefault k' k' equivalents
  where
    -- Java maps each run of one or two dashes to one dash
    collapseDashes = T.pack . squash . T.unpack
    squash ('-' : '-' : r) = squash ('-' : r)
    squash (c : r) = c : squash r
    squash [] = []

-- | comment markers, a page break written out as ^L like in some old copies
-- of the GPL, and separator runs like ===== that removeLineSeparators
-- would have taken off the end of a line. a run in the middle of a line, or
-- before a tag in a template, would otherwise collapse into a dash
skippable :: Text -> Bool
skippable k = case T.uncons k of
  Just (c, _)
    | c `elem` ("/*#\"=^-" :: String) ->
        k `Set.member` skippableKeys
          || (T.length k >= 3 && T.all (\x -> x == '-' || x == '=' || x == '*') k)
  _ -> False

skippableKeys :: Set.Set Text
skippableKeys = Set.fromList ["//", "/*", "*/", "/**", "#", "##", "*", "**", "\"\"\"", "/", "=begin", "=end", "^l"]

-- | LicenseTextHelper.NORMALIZE_TOKENS and spdx.org/licenses/equivalentwords.txt
equivalents :: HM.HashMap Text Text
equivalents =
  HM.fromList
    [ ("&", "and"),
      ("acknowledgment", "acknowledgement"),
      ("analogue", "analog"),
      ("analyse", "analyze"),
      ("artefact", "artifact"),
      ("authorisation", "authorization"),
      ("authorised", "authorized"),
      ("calibre", "caliber"),
      ("cancelled", "canceled"),
      ("capitalisations", "capitalizations"),
      ("catalogue", "catalog"),
      ("categorise", "categorize"),
      ("centre", "center"),
      ("emphasised", "emphasized"),
      ("favour", "favor"),
      ("favourite", "favorite"),
      ("fulfil", "fulfill"),
      ("fulfilment", "fulfillment"),
      ("initialise", "initialize"),
      ("judgment", "judgement"),
      ("labelling", "labeling"),
      ("labour", "labor"),
      ("licence", "license"),
      ("maximise", "maximize"),
      ("merchantibility", "merchantability"),
      ("modelled", "modeled"),
      ("modelling", "modeling"),
      ("offence", "offense"),
      ("optimise", "optimize"),
      ("organisation", "organization"),
      ("organise", "organize"),
      ("practise", "practice"),
      ("programme", "program"),
      ("realise", "realize"),
      ("recognise", "recognize"),
      ("signalling", "signaling"),
      ("utilisation", "utilization"),
      ("whilst", "while"),
      ("wilful", "willful"),
      ("wilfull", "willful"),
      ("non-commercial", "noncommercial"),
      ("sublicense", "sub-license"),
      ("non-infringement", "noninfringement"),
      ("©", "-c-"),
      ("copyright", "-c-"),
      ("\"", "'"),
      ("http", "https")
    ]

tokenKeys :: Text -> [Text]
tokenKeys = map tokKey . tokenize . prepare