{-# LANGUAGE OverloadedStrings #-}

module Prolog.Programming.CodeAnalysis.Rules.Cuts (cutsChecker) where

import Data.Text.Lazy (pack)
import Language.Prolog (Clause (..), prettifyClause)
import Prolog.Programming.CodeAnalysis.Helper (containsCut)
import Prolog.Programming.CodeAnalysis.Types (AdditionalMessage (..), ClauseRule, Problem (..))
import Text.PrettyPrint.Leijen.Text (empty, indent, linebreak, string, vsep)

cutsChecker :: AdditionalMessage -> ClauseRule
cutsChecker :: AdditionalMessage -> ClauseRule
cutsChecker (AdditionalMessage Maybe String
cMsg) (String
name, [Goal]
args, [Goal]
goals)
  | (Goal -> Bool) -> [Goal] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Goal -> Bool
forall a. Data a => a -> Bool
containsCut [Goal]
goals = [Maybe String -> Clause -> Problem
toProblem Maybe String
cMsg (Clause -> Problem) -> Clause -> Problem
forall a b. (a -> b) -> a -> b
$ String -> [Goal] -> [Goal] -> Clause
Clause String
name [Goal]
args [Goal]
goals]
  | Bool
otherwise = []

toProblem :: Maybe String -> Clause -> Problem
toProblem :: Maybe String -> Clause -> Problem
toProblem Maybe String
cMsg Clause
clause =
  Problem {
    problemDisplay :: Doc
problemDisplay =
      [Doc] -> Doc
vsep
        [ Text -> Doc
string Text
"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
$ String -> Text
pack (String -> Text) -> String -> Text
forall a b. (a -> b) -> a -> b
$ Clause -> String
prettifyClause Clause
clause
        , Text -> Doc
string Text
"makes use of the cut (!) operator." Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
linebreak
        , Doc -> (String -> Doc) -> Maybe String -> Doc
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Doc
empty (Text -> Doc
string (Text -> Doc) -> (String -> Text) -> String -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
pack) Maybe String
cMsg
        ]
    }