module Prolog.Programming.CodeAnalysis.Rules.SingletonVariables (singletonVariablesChecker) where

import qualified Data.Map as Map (filter, keys)
import Data.Text.Lazy (pack)
import Language.Prolog (Clause (..), prettifyClause)
import Prolog.Programming.CodeAnalysis.Helper (countVariables)
import Prolog.Programming.CodeAnalysis.Types (ClauseRule, Problem (..))
import Text.PrettyPrint.Leijen.Text (indent, linebreak, string, vsep)

singletonVariablesChecker :: ClauseRule
singletonVariablesChecker :: ClauseRule
singletonVariablesChecker (Atom
name, [Term]
args, [Term]
goals) = (Atom -> Problem) -> [Atom] -> [Problem]
forall a b. (a -> b) -> [a] -> [b]
map (Clause -> Atom -> Problem
toProblem Clause
clause) [Atom]
singletonVariables
  where
    clause :: Clause
clause = Atom -> [Term] -> [Term] -> Clause
Clause Atom
name [Term]
args [Term]
goals
    singletonVariables :: [Atom]
singletonVariables = Map Atom Int -> [Atom]
forall k a. Map k a -> [k]
Map.keys (Map Atom Int -> [Atom])
-> (Map Atom Int -> Map Atom Int) -> Map Atom Int -> [Atom]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int -> Bool) -> Map Atom Int -> Map Atom Int
forall a k. (a -> Bool) -> Map k a -> Map k a
Map.filter (Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1) (Map Atom Int -> [Atom]) -> Map Atom Int -> [Atom]
forall a b. (a -> b) -> a -> b
$ Clause -> Map Atom Int
forall a. Data a => a -> Map Atom Int
countVariables Clause
clause

toProblem :: Clause -> String -> Problem
toProblem :: Clause -> Atom -> Problem
toProblem Clause
clause Atom
var =
  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
clause
        , Text -> Doc
string (Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ Atom
"includes the singleton variable " Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
var Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
".") Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
linebreak
        , Text -> Doc
string (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack Atom
"You can safely replace it with a wildcard (_)."
        ]
    }