module Prolog.Programming.CodeAnalysis.Rules.Inlining (inliningChecker) where

import Control.Applicative (asum)
import Data.Generics (listify)
import Data.Map (Map)
import qualified Data.Map as Map (
  differenceWith,
  disjoint,
  empty,
  lookup,
  notMember,
  unionWith,
 )
import Data.Maybe (isNothing)
import Data.Text.Lazy (pack)
import Language.Prolog (
  Clause (..),
  Term (..),
  VariableName (VariableName),
  prettifyClause,
  prettifyTerm,
  substitute,
 )
import Prolog.Programming.CodeAnalysis.Helper (containsCut, countVariables)
import Prolog.Programming.CodeAnalysis.Types (ClauseRule, Problem (..))
import Text.PrettyPrint.Leijen.Text (indent, string, vsep)

inliningChecker :: ClauseRule
inliningChecker :: ClauseRule
inliningChecker (Atom
name, [Term]
args, [Term]
goals) =
  ((Term, (Atom, Term), [Term]) -> Problem)
-> [(Term, (Atom, Term), [Term])] -> [Problem]
forall a b. (a -> b) -> [a] -> [b]
map
    ( \(Term
u, (Atom, Term)
replacement, [Term]
goals') ->
        Clause -> Term -> Clause -> Problem
toProblem Clause
clause Term
u (Clause -> Problem) -> Clause -> Problem
forall a b. (a -> b) -> a -> b
$ (Atom, Term) -> [Term] -> Clause
fixedClause (Atom, Term)
replacement [Term]
goals'
    )
    ([(Term, (Atom, Term), [Term])] -> [Problem])
-> [(Term, (Atom, Term), [Term])] -> [Problem]
forall a b. (a -> b) -> a -> b
$ Map Atom Int -> [Term] -> [(Term, (Atom, Term), [Term])]
collectUnifications ([Term] -> Map Atom Int
forall a. Data a => a -> Map Atom Int
countVariables [Term]
args) [Term]
goals
  where
    clause :: Clause
clause = Atom -> [Term] -> [Term] -> Clause
Clause Atom
name [Term]
args [Term]
goals
    clauseHead :: Term
clauseHead = Atom -> [Term] -> Term
Struct Atom
name [Term]
args

    fixedClause :: (Atom, Term) -> [Term] -> Clause
fixedClause (Atom
x, Term
term) =
      let
        sub :: (VariableName, Term)
sub = (Int -> Atom -> VariableName
VariableName Int
0 Atom
x, Term
term)
        substitutedHead :: Term
substitutedHead = (VariableName, Term) -> Term -> Term
substitute (VariableName, Term)
sub Term
clauseHead
      in
        case Term
substitutedHead of
          Struct Atom
newName [Term]
newArgs -> Atom -> [Term] -> [Term] -> Clause
Clause Atom
newName [Term]
newArgs ([Term] -> Clause) -> ([Term] -> [Term]) -> [Term] -> Clause
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Term -> Term) -> [Term] -> [Term]
forall a b. (a -> b) -> [a] -> [b]
map ((VariableName, Term) -> Term -> Term
substitute (VariableName, Term)
sub)
          Term
_ -> Atom -> [Term] -> Clause
forall a. HasCallStack => Atom -> a
error Atom
"should not happen"

{- | Collect unifications that can be inlined.

For each unification whose two sides have disjoint variables and which satisfies
one of the inlining rules, the result records the unification goal,
the selected variable and replacement term, and the goals
besides it.
-}
collectUnifications
  :: Map String Int
  -- ^ Number of occurrences of each variable in the clause head.
  -> [Term]
  -- ^ Goals in the clause's right-hand side.
  -> [(Term, (String, Term), [Term])]
  -- ^ Unifications together with the goals besides them.
collectUnifications :: Map Atom Int -> [Term] -> [(Term, (Atom, Term), [Term])]
collectUnifications Map Atom Int
headVars [Term]
goals = [Term]
-> Map Atom Int
-> Bool
-> Bool
-> Map Atom Int
-> ([Term] -> [Term])
-> [(Term, (Atom, Term), [Term])]
forall {c}.
[Term]
-> Map Atom Int
-> Bool
-> Bool
-> Map Atom Int
-> ([Term] -> c)
-> [(Term, (Atom, Term), c)]
go [Term]
goals Map Atom Int
forall k a. Map k a
Map.empty Bool
True Bool
True ([Term] -> Map Atom Int
forall a. Data a => a -> Map Atom Int
countVariables [Term]
goals) [Term] -> [Term]
forall a. a -> a
id
  where
    go :: [Term]
-> Map Atom Int
-> Bool
-> Bool
-> Map Atom Int
-> ([Term] -> c)
-> [(Term, (Atom, Term), c)]
go [] Map Atom Int
_ Bool
_ Bool
_ Map Atom Int
_ [Term] -> c
_ = []
    go (Term
g : [Term]
gs) Map Atom Int
prefixVars Bool
prefixHasOnlyUnifications Bool
onlyAllowedOccurrencesInPrefixOtherwise Map Atom Int
suffixVars [Term] -> c
addPrefix =
      case Term
g of
        (Struct Atom
"=" [Term
l, Term
r]) -> case [Maybe (Atom, Term)] -> Maybe (Atom, Term)
forall (t :: * -> *) (f :: * -> *) a.
(Foldable t, Alternative f) =>
t (f a) -> f a
asum ([Maybe (Atom, Term)] -> Maybe (Atom, Term))
-> [Maybe (Atom, Term)] -> Maybe (Atom, Term)
forall a b. (a -> b) -> a -> b
$ ((Atom, Term) -> Maybe (Atom, Term))
-> [(Atom, Term)] -> [Maybe (Atom, Term)]
forall a b. (a -> b) -> [a] -> [b]
map (Atom, Term) -> Maybe (Atom, Term)
forall {b}. Data b => (Atom, b) -> Maybe (Atom, b)
checkMaybe ([(Atom, Term)] -> [Maybe (Atom, Term)])
-> [(Atom, Term)] -> [Maybe (Atom, Term)]
forall a b. (a -> b) -> a -> b
$ Term -> Term -> [(Atom, Term)]
unificationCandidates Term
l Term
r of
          Maybe (Atom, Term)
Nothing -> [(Term, (Atom, Term), c)]
restResult
          Just (Atom, Term)
uc -> (Term
g, (Atom, Term)
uc, [Term] -> c
addPrefix [Term]
gs) (Term, (Atom, Term), c)
-> [(Term, (Atom, Term), c)] -> [(Term, (Atom, Term), c)]
forall a. a -> [a] -> [a]
: [(Term, (Atom, Term), c)]
restResult
        Term
_ -> [(Term, (Atom, Term), c)]
restResult
      where
        gVars :: Map Atom Int
gVars = Term -> Map Atom Int
forall a. Data a => a -> Map Atom Int
countVariables Term
g

        newSuffixVars :: Map Atom Int
newSuffixVars =
          (Int -> Int -> Maybe Int)
-> Map Atom Int -> Map Atom Int -> Map Atom Int
forall k a b.
Ord k =>
(a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
Map.differenceWith
            (\Int
x Int
y -> let res :: Int
res = Int
x Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
y in if Int
res Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 then Int -> Maybe Int
forall a. a -> Maybe a
Just Int
res else Maybe Int
forall a. Maybe a
Nothing)
            Map Atom Int
suffixVars
            Map Atom Int
gVars

        restResult :: [(Term, (Atom, Term), c)]
restResult =
          [Term]
-> Map Atom Int
-> Bool
-> Bool
-> Map Atom Int
-> ([Term] -> c)
-> [(Term, (Atom, Term), c)]
go
            [Term]
gs
            ((Int -> Int -> Int) -> Map Atom Int -> Map Atom Int -> Map Atom Int
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
Map.unionWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) Map Atom Int
gVars Map Atom Int
prefixVars)
            Bool
newPrefixHasOnlyUnifications
            Bool
newOnlyAllowedOccurrencesInPrefixOtherwise
            Map Atom Int
newSuffixVars
            ([Term] -> c
addPrefix ([Term] -> c) -> ([Term] -> [Term]) -> [Term] -> c
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Term
g Term -> [Term] -> [Term]
forall a. a -> [a] -> [a]
:))

        newPrefixHasOnlyUnifications :: Bool
newPrefixHasOnlyUnifications =
          Bool
prefixHasOnlyUnifications Bool -> Bool -> Bool
&& case Term
g of
            (Struct Atom
"=" [Term]
_) -> Bool
True
            Term
_ -> Bool
False

        newOnlyAllowedOccurrencesInPrefixOtherwise :: Bool
newOnlyAllowedOccurrencesInPrefixOtherwise =
          Bool
onlyAllowedOccurrencesInPrefixOtherwise
            Bool -> Bool -> Bool
&& Map Atom Int -> Map Atom Int -> Bool
forall k a b. Ord k => Map k a -> Map k b -> Bool
Map.disjoint Map Atom Int
gVars Map Atom Int
headVars
            Bool -> Bool -> Bool
&& Bool -> Bool
not (Term -> Bool
forall a. Data a => a -> Bool
containsCut Term
g)
            Bool -> Bool -> Bool
&& [Term] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ((Term -> Bool) -> GenericQ [Term]
forall r. Typeable r => (r -> Bool) -> GenericQ [r]
listify Term -> Bool
isDisjunction Term
g)

        isDisjunction :: Term -> Bool
isDisjunction (Struct Atom
";" [Term]
_) = Bool
True
        isDisjunction Term
_ = Bool
False

        checkMaybe :: (Atom, b) -> Maybe (Atom, b)
checkMaybe (Atom, b)
uv
          | (Atom, b) -> Bool
forall {b}. Data b => (Atom, b) -> Bool
check (Atom, b)
uv = (Atom, b) -> Maybe (Atom, b)
forall a. a -> Maybe a
Just (Atom, b)
uv
          | Bool
otherwise = Maybe (Atom, b)
forall a. Maybe a
Nothing

        -- Rule 1: If, on the right-hand side of a clause, following at most literals in which neither X
        -- nor variables from term/Y appear and the variables in the prefix are disjoint to
        -- the variables in the head — or the literals themselves consist only of equalities in which X
        -- does not appear — there is something like X = term or X = Y or Y = X or term = X,
        -- and X appears exactly once in the head and appears neither in term nor in the rest of the
        -- right-hand side (and X and Y are different variables), then this equality may be inlined.

        -- Rule 2: If something like this appears somewhere on the right-hand side of a clause
        -- (not necessarily right at the beginning), and X does not appear in the head, nor in
        -- the initial part of the right-hand side up to this equation (and, of course, not in term/Y either),
        -- and if X appears exactly once in the remaining part of the right-hand side,
        -- then this equality may be inlined.

        check :: (Atom, b) -> Bool
check (Atom
v, b
t) =
          let
            tVars :: Map Atom Int
tVars = b -> Map Atom Int
forall a. Data a => a -> Map Atom Int
countVariables b
t
            varNotInTerm :: Bool
varNotInTerm = Atom -> Map Atom Int -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.notMember Atom
v Map Atom Int
tVars
            varNotInPrefix :: Bool
varNotInPrefix = Atom -> Map Atom Int -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.notMember Atom
v Map Atom Int
prefixVars
            maybeVarCountInHead :: Maybe Int
maybeVarCountInHead = Atom -> Map Atom Int -> Maybe Int
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Atom
v Map Atom Int
headVars
            maybeVarCountInSuffix :: Maybe Int
maybeVarCountInSuffix = Atom -> Map Atom Int -> Maybe Int
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Atom
v Map Atom Int
newSuffixVars

            rule1 :: Bool
rule1 =
              Maybe Int
maybeVarCountInHead Maybe Int -> Maybe Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int -> Maybe Int
forall a. a -> Maybe a
Just Int
1
                Bool -> Bool -> Bool
&& ( Bool
prefixHasOnlyUnifications
                       Bool -> Bool -> Bool
|| (Bool
onlyAllowedOccurrencesInPrefixOtherwise Bool -> Bool -> Bool
&& Map Atom Int -> Map Atom Int -> Bool
forall k a b. Ord k => Map k a -> Map k b -> Bool
Map.disjoint Map Atom Int
tVars Map Atom Int
prefixVars)
                   )
                Bool -> Bool -> Bool
&& Maybe Int -> Bool
forall a. Maybe a -> Bool
isNothing Maybe Int
maybeVarCountInSuffix

            rule2 :: Bool
rule2 =
              Maybe Int -> Bool
forall a. Maybe a -> Bool
isNothing Maybe Int
maybeVarCountInHead
                Bool -> Bool -> Bool
&& Maybe Int
maybeVarCountInSuffix Maybe Int -> Maybe Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int -> Maybe Int
forall a. a -> Maybe a
Just Int
1
          in
            Bool
varNotInTerm
              Bool -> Bool -> Bool
&& Bool
varNotInPrefix
              Bool -> Bool -> Bool
&& (Bool
rule1 Bool -> Bool -> Bool
|| Bool
rule2)

{- | Give the variable sides of a unification and the terms that substitute
for them.
-}
unificationCandidates
  :: Term
  -- ^ Left side of unification to select from.
  -> Term
  -- ^ Right side of unification to select from.
  -> [(String, Term)]
  -- ^ Possible selected variables and the terms that replace them.
unificationCandidates :: Term -> Term -> [(Atom, Term)]
unificationCandidates Term
left Term
right = Term -> Term -> [(Atom, Term)]
forall {b}. Term -> b -> [(Atom, b)]
pair Term
left Term
right [(Atom, Term)] -> [(Atom, Term)] -> [(Atom, Term)]
forall a. [a] -> [a] -> [a]
++ Term -> Term -> [(Atom, Term)]
forall {b}. Term -> b -> [(Atom, b)]
pair Term
right Term
left
  where
    pair :: Term -> b -> [(Atom, b)]
pair (Var (VariableName Int
_ Atom
name)) b
other = [(Atom
name, b
other)]
    pair Term
_ b
_ = []

toProblem :: Clause -> Term -> Clause -> Problem
toProblem :: Clause -> Term -> Clause -> Problem
toProblem Clause
originalClause Term
equality Clause
fixedClause =
  Problem {
    problemDisplay :: Doc
problemDisplay =
      [Doc] -> Doc
vsep
        [ Text -> Doc
string (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack Atom
"Your clause"
        , Int -> Doc -> Doc
indent Int
2 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ Text -> Doc
string (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ Clause -> Atom
prettifyClause Clause
originalClause
        , Text -> Doc
string (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack Atom
"uses the unification"
        , Int -> Doc -> Doc
indent Int
2 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ Text -> Doc
string (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ Term -> Atom
prettifyTerm Term
equality
        , Text -> Doc
string (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack Atom
"as a goal that can also directly be applied to the clause."
        , Text -> Doc
string (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack Atom
"Doing that would result in:"
        , Int -> Doc -> Doc
indent Int
2 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ Text -> Doc
string (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ Clause -> Atom
prettifyClause Clause
fixedClause
        ]
    }