packages feed

tavro-0.1.0.2: src/Tavro/Template.hs

-- | SPDX license templates (spec annex B.15), the @standardLicenseTemplate@
-- form that license-list-data ships as @template/*.template.txt@:
--
-- > <<var;name="copyright";original="Copyright (c) <year>";match=".{0,5000}">>
-- > <<beginOptional>> text that may be left out <<endOptional>>
--
-- the spec says rules don't nest, but the license list nests optionals three
-- deep, and a few templates have an extra beginOptional or endOptional. an
-- unclosed optional ends with the template and a stray endOptional is
-- dropped, which is what Spdx-Java-Library ends up doing too
module Tavro.Template
  ( Node (..),
    parseTemplate,
  )
where

import Data.Char (isAlpha, isSpace)
import Data.Containers.ListUtils (nubOrd)
import Data.Text (Text)
import Data.Text qualified as T

data Node
  = Lit Text
  | Var
      { varName :: Text,
        varOriginal :: Text,
        varMatch :: Text
      }
  | -- | the first alternative that leads to a match wins. an optional is a
    -- choice between its body and nothing
    Choice [[Node]]
  deriving stock (Eq, Show)

data Tag = TVar Text Text Text | TBegin | TEnd

parseTemplate :: Text -> [Node]
parseTemplate = glue . build [] [] . chunks

chunks :: Text -> [Either Text Tag]
chunks t
  | T.null t = []
  | otherwise =
      let (before, rest) = T.breakOn "<<" t
          lit = [Left before | not (T.null before)]
       in if T.null rest
            then lit
            else case parseTag (T.drop 2 rest) of
              Just (tag, after) -> lit <> (Right tag : chunks after)
              -- not a tag here. keep one < as text and look again from the
              -- next character, for a literal < right before a tag, like
              -- GPL-2.0's <<beginOptional>><<<endOptional>>
              Nothing -> lit <> (Left "<" : chunks (T.drop 1 rest))

parseTag :: Text -> Maybe (Tag, Text)
parseTag t = do
  let (kind, rest) = T.span isAlpha t
  (fields, after) <- fieldsThenClose rest
  let field k = lookup k fields
  case kind of
    "var" -> do
      name <- field "name"
      let original = maybe "" id (field "original")
      match <- field "match"
      pure (TVar name original match, after)
    "beginOptional" -> pure (TBegin, after)
    "endOptional" -> pure (TEnd, after)
    _ -> Nothing

-- | @;key="value"@ pairs up to the closing @>>@
fieldsThenClose :: Text -> Maybe ([(Text, Text)], Text)
fieldsThenClose t0 = case T.stripPrefix ">>" (T.stripStart t0) of
  Just after -> Just ([], after)
  Nothing -> do
    rest <- T.stripPrefix ";" (T.stripStart t0)
    let (key, r1) = T.breakOn "=" (T.stripStart rest)
    r2 <- T.stripPrefix "=" r1
    (value, r3) <- fieldValue r2
    (more, after) <- fieldsThenClose r3
    pure ((T.strip key, value) : more, after)

-- | a quoted value ends at the first quote followed by @;@ or @>>@, since
-- match regexes have quotes of their own in them. a bare one ends at the
-- first @;@ or @>>@
fieldValue :: Text -> Maybe (Text, Text)
fieldValue t = case T.uncons t of
  Just ('"', rest) -> closeQuote "" rest
  _ ->
    let (v, rest) = T.break (`elem` (";>" :: String)) t
     in Just (T.strip v, rest)
  where
    closeQuote acc s = do
      let (piece, r) = T.breakOn "\"" s
      r' <- T.stripPrefix "\"" r
      let next = T.stripStart r'
      if ";" `T.isPrefixOf` next || ">>" `T.isPrefixOf` next
        then Just (unescape (acc <> piece), r')
        else closeQuote (acc <> piece <> "\"") r'
    unescape = T.replace "\\;" ";"

-- | nest optionals. the stack holds the enclosing sequences, reversed
build :: [[Node]] -> [Node] -> [Either Text Tag] -> [Node]
build stack cur items = case items of
  [] -> case stack of
    [] -> reverse cur
    parent : up -> build up (optional cur : parent) []
  Left txt : rest -> build stack (Lit txt : cur) rest
  Right (TVar n o m) : rest -> build stack (Var n o m : cur) rest
  Right TBegin : rest -> build (cur : stack) [] rest
  Right TEnd : rest -> case stack of
    [] -> build stack cur rest
    parent : up -> build up (optional cur : parent) rest
  where
    optional body = Choice [reverse body, []]

-- | an optional can start or end in the middle of a word:
-- @license<<beginOptional>>s<<endOptional>>@, or
-- @attorney<<beginOptional>>'<<endOptional>>s@. text is tokenized a piece at
-- a time, so @license@ and @s@ would be separate tokens where the license
-- has one.
--
-- so when a choice of short text (no whitespace in it) touches the text
-- around it, the touching pieces move into the choice. whether each
-- junction joins is left open, since templates also drop spaces by
-- accident, like NTP-0's @name<<beginOptional>>s<<endOptional>>of@: that
-- becomes a choice of @namesof@, @names of@, @name sof@, @name s of@,
-- @nameof@ and @name of@, and matching picks whichever fits
glue :: [Node] -> [Node]
glue = \case
  Lit a : Choice alts : rest
    | Just texts <- mapM plainText alts,
      (a', w) <- trailingPiece a,
      (v, rest') <- leadingPiece rest,
      not (T.null w && T.null v) ->
        [Lit a' | not (T.null a')] <> (joinings w texts v : glue rest')
  Choice alts : rest
    | Just texts <- mapM plainText alts,
      (v, rest') <- leadingPiece rest,
      not (T.null v) ->
        joinings "" texts v : glue rest'
  Choice alts : rest -> Choice (map glue alts) : glue rest
  n : rest -> n : glue rest
  [] -> []
  where
    plainText = \case
      [] -> Just ""
      [Lit t] | not (T.any isSpace t) -> Just t
      _ -> Nothing
    trailingPiece a =
      let w = T.takeWhileEnd (not . isSpace) a
       in (T.dropEnd (T.length w) a, w)
    leadingPiece = \case
      Lit b : r ->
        let v = T.takeWhile (not . isSpace) b
            b' = T.drop (T.length v) b
         in (v, [Lit b' | not (T.null b')] <> r)
      r -> ("", r)

-- | each alternative with each junction joined or not, joined first
joinings :: Text -> [Text] -> Text -> Node
joinings w texts v = Choice [[Lit x] | x <- nubOrd (concatMap variants texts)]
  where
    variants t
      | T.null t = [w <> l <> v | l <- if T.null w || T.null v then [""] else ["", " "]]
      | otherwise = [w <> l <> t <> r <> v | l <- seps w, r <- seps v]
    seps x = if T.null x then [""] else ["", " "]