{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# HLINT ignore "Use unless" #-}
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}

module Prolog.Programming.Task (
  checkTask,
  displaySampleSolution,
  exampleConfig,
  verifyConfig,
  describeTask,
  taskDefinitions,
  taskDefinitionsIncluded,
  initialTask,
  displaySWISHButton,
  TaskInstance,
  toInstance,
) where

import Prolog.Programming.Data
import Prolog.Programming.ExampleConfig
import Prolog.Programming.Helper (Arity, escalateSeverity)
import Prolog.Programming.Parser (parseInstance)
import Prolog.Programming.TestRunner

import Control.Monad (when)
import Control.Monad.Trans (MonadIO (liftIO))

import Data.ByteString (ByteString)
import Data.Either (fromRight)
import Data.List (intercalate)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Maybe (mapMaybe)
import Data.Text.Lazy (pack)
import Data.Void (absurd)

import Language.Prolog (
  Atom,
  Clause (..),
  ProgramClause,
  Term (..),
  Unifier,
  prettifyClause,
  prettifyTerm,
  prettifyVariableName,
 )
import Language.Prolog.GraphViz (Graph, asInlineSvgWith)
import Language.Prolog.GraphViz.Formatting (GraphFormatting, queryStyle, resolutionStyle)

import Data.Generics (Data, everywhere, mkT)
import Data.List.Extra (notNull, nubOrd)
import Data.Tuple.Extra (uncurry3)
import GHC.Utils.Misc (partitionWith)
import Prolog.Programming.CodeAnalysis (checkForProblems, displayProblems)
import Prolog.Programming.CodeAnalysis.Config (configuredRules)
import Prolog.Programming.CodeAnalysis.Other.RedundantCode (checkForRedundantCode)
import Prolog.Programming.CodeAnalysis.Types (
  CheckStage (..),
  CodeAnalysisConfig (..),
  EarlyRecursionConfig (..),
  IgnoredPredicates (IgnoredPredicates),
  InconsistentAritiesConfig (InconsistentAritiesConfig),
  RecursionConfig (..),
  RedundantCodeConfig (RedundantCodeConfig),
  Severity (..),
  SingletonVariablesConfig (SingletonVariablesConfig),
  SymbolOverloadConfig (SymbolOverloadConfig),
  TimeoutDivisor (..),
  UngroupedDefinitionsConfig (UngroupedDefinitionsConfig),
  WithSeverity (..),
 )
import Prolog.Programming.Types (
  Expection (..),
  Include (..),
  IncludeHidden,
  IncludeTask,
  Requirement (..),
  Spec (..),
  TaskConfig (..),
  TaskInstance (..),
  TreeStyle (..),
  Visibility (..),
 )
import Text.PrettyPrint.Leijen.Text (
  Doc,
  align,
  empty,
  indent,
  line,
  linebreak,
  nest,
  parens,
  text,
  vcat,
  vsep,
  (<$$>),
  (<+>),
 )

verifyConfig :: (MonadFail m, MonadIO m) => Config -> m ()
verifyConfig :: forall (m :: * -> *). (MonadFail m, MonadIO m) => Atom -> m ()
verifyConfig Atom
cfg = case Atom -> Either ParseError TaskInstance
parseInstance Atom
cfg of
  Left ParseError
err -> Atom -> m ()
forall a. Atom -> m a
forall (m :: * -> *) a. MonadFail m => Atom -> m a
fail (Atom -> m ()) -> Atom -> m ()
forall a b. (a -> b) -> a -> b
$ ParseError -> Atom
forall a. Show a => a -> Atom
show ParseError
err
  Right inst :: TaskInstance
inst@TaskInstance {taskConfig :: TaskInstance -> TaskConfig
taskConfig = taskCfg :: TaskConfig
taskCfg@TaskConfig {Bool
Arity
[Spec]
CodeAnalysisConfig
IncludeHidden
IncludeTask
TreeStyle
mainTestTimeout :: Arity
treeStyle :: TreeStyle
includeTaskDefinitions :: IncludeTask
includeHiddenDefinitions :: IncludeHidden
allowListPatternMatching :: Bool
showSWISHButton :: Bool
codeAnalysis :: CodeAnalysisConfig
specifications :: [Spec]
rigorousValidation :: Bool
errorOnFirstTimeout :: Bool
allowListPatternMatching :: TaskConfig -> Bool
codeAnalysis :: TaskConfig -> CodeAnalysisConfig
errorOnFirstTimeout :: TaskConfig -> Bool
includeHiddenDefinitions :: TaskConfig -> IncludeHidden
includeTaskDefinitions :: TaskConfig -> IncludeTask
mainTestTimeout :: TaskConfig -> Arity
rigorousValidation :: TaskConfig -> Bool
showSWISHButton :: TaskConfig -> Bool
specifications :: TaskConfig -> [Spec]
treeStyle :: TaskConfig -> TreeStyle
..}, Atom
[ProgramClause]
sampleSolution :: [ProgramClause]
taskDescription :: Atom
visiblePredicates :: [ProgramClause]
hiddenPredicates :: [ProgramClause]
hiddenPredicates :: TaskInstance -> [ProgramClause]
sampleSolution :: TaskInstance -> [ProgramClause]
taskDescription :: TaskInstance -> Atom
visiblePredicates :: TaskInstance -> [ProgramClause]
..} ->
    let solutionErrorDisplay :: a -> m a
solutionErrorDisplay a
err = Atom -> m a
forall a. Atom -> m a
forall (m :: * -> *) a. MonadFail m => Atom -> m a
fail (Atom -> m a) -> Atom -> m a
forall a b. (a -> b) -> a -> b
$ Atom
"Failure during check of sample solution:\n" Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ a -> Atom
forall a. Show a => a -> Atom
show a
err
    in do
         Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (IncludeHidden
includeHiddenDefinitions IncludeHidden -> IncludeHidden -> Bool
forall a. Eq a => a -> a -> Bool
== IncludeHidden
forall a. Include a
Yes Bool -> Bool -> Bool
&& Bool
showSWISHButton Bool -> Bool -> Bool
&& [ProgramClause] -> Bool
forall a. [a] -> Bool
notNull [ProgramClause]
hiddenPredicates) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
           Atom -> m ()
forall a. Atom -> m a
forall (m :: * -> *) a. MonadFail m => Atom -> m a
fail Atom
"SWISH Button must not be enabled together with unfiltered hidden predicates."

         Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when
           ( ((WithSeverity ProgramRule, CheckStage) -> Bool)
-> [(WithSeverity ProgramRule, CheckStage)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any
               ( \case
                   (WithSeverity Severity
Hint ProgramRule
_, CheckStage
BeforeTests) -> Bool
True
                   (WithSeverity Severity
Warn ProgramRule
_, CheckStage
BeforeTests) -> Bool
True
                   (WithSeverity ProgramRule, CheckStage)
_ -> Bool
False
               )
               ([(WithSeverity ProgramRule, CheckStage)] -> Bool)
-> [(WithSeverity ProgramRule, CheckStage)] -> Bool
forall a b. (a -> b) -> a -> b
$ CodeAnalysisConfig
-> [ProgramClause] -> [(WithSeverity ProgramRule, CheckStage)]
configuredRules CodeAnalysisConfig
codeAnalysis [ProgramClause]
forall a. HasCallStack => a
undefined
           )
           (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ Atom -> m ()
forall a. Atom -> m a
forall (m :: * -> *) a. MonadFail m => Atom -> m a
fail Atom
"Code analysis configs using the 'before-tests' stage must use the 'reject' status"

         case (CodeAnalysisConfig -> RecursionConfig
recursion CodeAnalysisConfig
codeAnalysis, CodeAnalysisConfig -> EarlyRecursionConfig
earlyRecursion CodeAnalysisConfig
codeAnalysis) of
           ( RecursionConfig (Just (WithSeverity Severity
Error AdditionalMessage
_, CheckStage
_))
             , EarlyRecursionConfig (Just (WithSeverity AdditionalMessage, CheckStage)
_)
             ) -> Atom -> m ()
forall a. Atom -> m a
forall (m :: * -> *) a. MonadFail m => Atom -> m a
fail Atom
"You cannot enable the earlyRecursion checker when recursion is forbidden."
           (RecursionConfig, EarlyRecursionConfig)
_ -> () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

         Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
rigorousValidation (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
           (forall a. Doc -> m a)
-> (Doc -> m ())
-> (ByteString -> m ())
-> TaskInstance
-> [ProgramClause]
-> m ()
forall (m :: * -> *).
MonadIO m =>
(forall a. Doc -> m a)
-> (Doc -> m ())
-> (ByteString -> m ())
-> TaskInstance
-> [ProgramClause]
-> m ()
checkTask
             Doc -> m a
forall a. Doc -> m a
forall {m :: * -> *} {a} {a}. (MonadFail m, Show a) => a -> m a
solutionErrorDisplay
             (m () -> Doc -> m ()
forall a b. a -> b -> a
const (m () -> Doc -> m ()) -> m () -> Doc -> m ()
forall a b. (a -> b) -> a -> b
$ () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
             (m () -> ByteString -> m ()
forall a b. a -> b -> a
const (m () -> ByteString -> m ()) -> m () -> ByteString -> m ()
forall a b. (a -> b) -> a -> b
$ () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
             ( TaskInstance
inst {
                 taskConfig =
                   taskCfg {
                     codeAnalysis = escalateAndEnableSelectedChecks codeAnalysis
                     }
                 , sampleSolution = undefined
                 }
             )
             [ProgramClause]
sampleSolution
  where
    withError :: a -> Maybe (WithSeverity a, CheckStage)
withError a
a = (WithSeverity a, CheckStage) -> Maybe (WithSeverity a, CheckStage)
forall a. a -> Maybe a
Just (Severity -> a -> WithSeverity a
forall a. Severity -> a -> WithSeverity a
WithSeverity Severity
Error a
a, CheckStage
BeforeTests)

    escalate :: Data a => a -> a
    escalate :: forall a. Data a => a -> a
escalate = (forall a. Data a => a -> a) -> forall a. Data a => a -> a
everywhere ((CheckStage -> CheckStage) -> a -> a
forall a b. (Typeable a, Typeable b) => (b -> b) -> a -> a
mkT (\(CheckStage
_ :: CheckStage) -> CheckStage
BeforeTests)) (a -> a) -> (a -> a) -> a -> a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> a
forall a. Data a => a -> a
escalateSeverity

    escalateAndEnableSelectedChecks :: CodeAnalysisConfig -> CodeAnalysisConfig
escalateAndEnableSelectedChecks CodeAnalysisConfig {CutUsageConfig
EarlyRecursionConfig
ForbiddenPredicatesConfig
InconsistentAritiesConfig
InliningConfig
RecursionConfig
RedundantCodeConfig
SingletonVariablesConfig
SymbolOverloadConfig
UngroupedDefinitionsConfig
recursion :: CodeAnalysisConfig -> RecursionConfig
earlyRecursion :: CodeAnalysisConfig -> EarlyRecursionConfig
singletonVariables :: SingletonVariablesConfig
cutUsage :: CutUsageConfig
inconsistentArities :: InconsistentAritiesConfig
ungroupedDefinitions :: UngroupedDefinitionsConfig
recursion :: RecursionConfig
forbiddenPredicates :: ForbiddenPredicatesConfig
earlyRecursion :: EarlyRecursionConfig
inlining :: InliningConfig
symbolOverload :: SymbolOverloadConfig
redundantCode :: RedundantCodeConfig
cutUsage :: CodeAnalysisConfig -> CutUsageConfig
forbiddenPredicates :: CodeAnalysisConfig -> ForbiddenPredicatesConfig
inconsistentArities :: CodeAnalysisConfig -> InconsistentAritiesConfig
inlining :: CodeAnalysisConfig -> InliningConfig
redundantCode :: CodeAnalysisConfig -> RedundantCodeConfig
singletonVariables :: CodeAnalysisConfig -> SingletonVariablesConfig
symbolOverload :: CodeAnalysisConfig -> SymbolOverloadConfig
ungroupedDefinitions :: CodeAnalysisConfig -> UngroupedDefinitionsConfig
..} =
      CodeAnalysisConfig {
        singletonVariables :: SingletonVariablesConfig
singletonVariables = CodeAnalysisRuleConfig () -> SingletonVariablesConfig
SingletonVariablesConfig (CodeAnalysisRuleConfig () -> SingletonVariablesConfig)
-> CodeAnalysisRuleConfig () -> SingletonVariablesConfig
forall a b. (a -> b) -> a -> b
$ () -> CodeAnalysisRuleConfig ()
forall {a}. a -> Maybe (WithSeverity a, CheckStage)
withError ()
        , cutUsage :: CutUsageConfig
cutUsage = CutUsageConfig -> CutUsageConfig
forall a. Data a => a -> a
escalate CutUsageConfig
cutUsage
        , inconsistentArities :: InconsistentAritiesConfig
inconsistentArities = CodeAnalysisRuleConfig IgnoredPredicates
-> InconsistentAritiesConfig
InconsistentAritiesConfig (CodeAnalysisRuleConfig IgnoredPredicates
 -> InconsistentAritiesConfig)
-> CodeAnalysisRuleConfig IgnoredPredicates
-> InconsistentAritiesConfig
forall a b. (a -> b) -> a -> b
$ IgnoredPredicates -> CodeAnalysisRuleConfig IgnoredPredicates
forall {a}. a -> Maybe (WithSeverity a, CheckStage)
withError (IgnoredPredicates -> CodeAnalysisRuleConfig IgnoredPredicates)
-> IgnoredPredicates -> CodeAnalysisRuleConfig IgnoredPredicates
forall a b. (a -> b) -> a -> b
$ [Atom] -> IgnoredPredicates
IgnoredPredicates []
        , ungroupedDefinitions :: UngroupedDefinitionsConfig
ungroupedDefinitions = CodeAnalysisRuleConfig () -> UngroupedDefinitionsConfig
UngroupedDefinitionsConfig (CodeAnalysisRuleConfig () -> UngroupedDefinitionsConfig)
-> CodeAnalysisRuleConfig () -> UngroupedDefinitionsConfig
forall a b. (a -> b) -> a -> b
$ () -> CodeAnalysisRuleConfig ()
forall {a}. a -> Maybe (WithSeverity a, CheckStage)
withError ()
        , recursion :: RecursionConfig
recursion = RecursionConfig -> RecursionConfig
forall a. Data a => a -> a
escalate RecursionConfig
recursion
        , ForbiddenPredicatesConfig
forbiddenPredicates :: ForbiddenPredicatesConfig
forbiddenPredicates :: ForbiddenPredicatesConfig
forbiddenPredicates
        , earlyRecursion :: EarlyRecursionConfig
earlyRecursion = EarlyRecursionConfig -> EarlyRecursionConfig
forall a. Data a => a -> a
escalate EarlyRecursionConfig
earlyRecursion
        , inlining :: InliningConfig
inlining = InliningConfig -> InliningConfig
forall a. Data a => a -> a
escalate InliningConfig
inlining
        , symbolOverload :: SymbolOverloadConfig
symbolOverload = CodeAnalysisRuleConfig () -> SymbolOverloadConfig
SymbolOverloadConfig (CodeAnalysisRuleConfig () -> SymbolOverloadConfig)
-> CodeAnalysisRuleConfig () -> SymbolOverloadConfig
forall a b. (a -> b) -> a -> b
$ () -> CodeAnalysisRuleConfig ()
forall {a}. a -> Maybe (WithSeverity a, CheckStage)
withError ()
        , redundantCode :: RedundantCodeConfig
redundantCode = CodeAnalysisRuleConfig TimeoutDivisor -> RedundantCodeConfig
RedundantCodeConfig (CodeAnalysisRuleConfig TimeoutDivisor -> RedundantCodeConfig)
-> CodeAnalysisRuleConfig TimeoutDivisor -> RedundantCodeConfig
forall a b. (a -> b) -> a -> b
$ (WithSeverity TimeoutDivisor, CheckStage)
-> CodeAnalysisRuleConfig TimeoutDivisor
forall a. a -> Maybe a
Just (Severity -> TimeoutDivisor -> WithSeverity TimeoutDivisor
forall a. Severity -> a -> WithSeverity a
WithSeverity Severity
Error (Arity -> TimeoutDivisor
TimeoutDivisor Arity
1), CheckStage
AfterTests)
        }

toInstance :: Config -> TaskInstance
toInstance :: Atom -> TaskInstance
toInstance = TaskInstance -> Either ParseError TaskInstance -> TaskInstance
forall b a. b -> Either a b -> b
fromRight (Atom -> TaskInstance
forall a. HasCallStack => Atom -> a
error Atom
"config should have been validated before") (Either ParseError TaskInstance -> TaskInstance)
-> (Atom -> Either ParseError TaskInstance) -> Atom -> TaskInstance
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Atom -> Either ParseError TaskInstance
parseInstance

describeTask :: TaskInstance -> Doc
describeTask :: TaskInstance -> Doc
describeTask TaskInstance {Atom
taskDescription :: TaskInstance -> Atom
taskDescription :: Atom
taskDescription} =
  Text -> Doc
text (Text -> Doc) -> Text -> Doc
forall a b. (a -> b) -> a -> b
$ Atom -> Text
pack Atom
taskDescription

initialTask :: TaskInstance -> Code
initialTask :: TaskInstance -> Atom
initialTask TaskInstance {taskConfig :: TaskInstance -> TaskConfig
taskConfig = TaskConfig {[Spec]
specifications :: TaskConfig -> [Spec]
specifications :: [Spec]
specifications}} =
  if [Atom] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Atom]
newDecls
    then Atom
""
    else
      (Atom -> Atom -> Atom) -> Atom -> [Atom] -> Atom
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr
        ( \Atom
desc Atom
s ->
            Atom
"% Define predicate for '"
              Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
desc
              Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
"' below this line\n \n\n"
              Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
s
        )
        Atom
"% Any additional definitions can go below this line"
        [Atom]
newDecls
  where
    newDecls :: [Atom]
newDecls = (Spec -> Maybe Atom) -> [Spec] -> [Atom]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (\(Spec Visibility
_ Visualize
_ Expection
_ Timeout
_ Requirement
r) -> Requirement -> Maybe Atom
newPredDesc Requirement
r) [Spec]
specifications
    newPredDesc :: Requirement -> Maybe Atom
newPredDesc (NewPredDecl Term
_ Atom
desc) = Atom -> Maybe Atom
forall a. a -> Maybe a
Just Atom
desc
    newPredDesc StatementToCheck {} = Maybe Atom
forall a. Maybe a
Nothing
    newPredDesc QueryWithAnswers {} = Maybe Atom
forall a. Maybe a
Nothing

taskDefinitions :: TaskInstance -> [Clause]
taskDefinitions :: TaskInstance -> [Clause]
taskDefinitions TaskInstance {[ProgramClause]
visiblePredicates :: TaskInstance -> [ProgramClause]
visiblePredicates :: [ProgramClause]
visiblePredicates} = (ProgramClause -> Clause) -> [ProgramClause] -> [Clause]
forall a b. (a -> b) -> [a] -> [b]
map ((Atom -> [Term] -> [Term] -> Clause) -> ProgramClause -> Clause
forall a b c d. (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 Atom -> [Term] -> [Term] -> Clause
Clause) [ProgramClause]
visiblePredicates

taskDefinitionsIncluded :: TaskInstance -> Bool
taskDefinitionsIncluded :: TaskInstance -> Bool
taskDefinitionsIncluded TaskInstance {taskConfig :: TaskInstance -> TaskConfig
taskConfig = TaskConfig {Bool
Arity
[Spec]
CodeAnalysisConfig
IncludeHidden
IncludeTask
TreeStyle
allowListPatternMatching :: TaskConfig -> Bool
codeAnalysis :: TaskConfig -> CodeAnalysisConfig
errorOnFirstTimeout :: TaskConfig -> Bool
includeHiddenDefinitions :: TaskConfig -> IncludeHidden
includeTaskDefinitions :: TaskConfig -> IncludeTask
mainTestTimeout :: TaskConfig -> Arity
rigorousValidation :: TaskConfig -> Bool
showSWISHButton :: TaskConfig -> Bool
specifications :: TaskConfig -> [Spec]
treeStyle :: TaskConfig -> TreeStyle
mainTestTimeout :: Arity
treeStyle :: TreeStyle
includeTaskDefinitions :: IncludeTask
includeHiddenDefinitions :: IncludeHidden
allowListPatternMatching :: Bool
showSWISHButton :: Bool
codeAnalysis :: CodeAnalysisConfig
specifications :: [Spec]
rigorousValidation :: Bool
errorOnFirstTimeout :: Bool
..}} = case IncludeTask
includeTaskDefinitions of
  IncludeTask
Yes -> Bool
True
  IncludeTask
Filtered -> Bool
True
  No () -> Bool
False

displaySWISHButton :: TaskInstance -> Bool
displaySWISHButton :: TaskInstance -> Bool
displaySWISHButton TaskInstance {taskConfig :: TaskInstance -> TaskConfig
taskConfig = TaskConfig {Bool
Arity
[Spec]
CodeAnalysisConfig
IncludeHidden
IncludeTask
TreeStyle
allowListPatternMatching :: TaskConfig -> Bool
codeAnalysis :: TaskConfig -> CodeAnalysisConfig
errorOnFirstTimeout :: TaskConfig -> Bool
includeHiddenDefinitions :: TaskConfig -> IncludeHidden
includeTaskDefinitions :: TaskConfig -> IncludeTask
mainTestTimeout :: TaskConfig -> Arity
rigorousValidation :: TaskConfig -> Bool
showSWISHButton :: TaskConfig -> Bool
specifications :: TaskConfig -> [Spec]
treeStyle :: TaskConfig -> TreeStyle
mainTestTimeout :: Arity
treeStyle :: TreeStyle
includeTaskDefinitions :: IncludeTask
includeHiddenDefinitions :: IncludeHidden
allowListPatternMatching :: Bool
showSWISHButton :: Bool
codeAnalysis :: CodeAnalysisConfig
specifications :: [Spec]
rigorousValidation :: Bool
errorOnFirstTimeout :: Bool
..}} = Bool
showSWISHButton

{- | Runs the following checks in this order:

1. Does the program parse?
2. Does the program respect a configured ban of head/tail pattern-matching on lists?
3. Are all required predicates-to-be-defined present?
4. Is the specification (the tests) fulfilled by the program together with task and hidden predicates?
5. Does the code analysis - minus dead code detection - run through without rejections?
6. Is there no dead code?

The procedure aborts once the first check fails.
-}
checkTask
  :: MonadIO m
  => (forall a. Doc -> m a)
  -> (Doc -> m ())
  -> (ByteString -> m ())
  -> TaskInstance
  -> [ProgramClause]
  -> m ()
checkTask :: forall (m :: * -> *).
MonadIO m =>
(forall a. Doc -> m a)
-> (Doc -> m ())
-> (ByteString -> m ())
-> TaskInstance
-> [ProgramClause]
-> m ()
checkTask forall a. Doc -> m a
reject Doc -> m ()
inform ByteString -> m ()
drawPicture TaskInstance {taskConfig :: TaskInstance -> TaskConfig
taskConfig = TaskConfig {Bool
Arity
[Spec]
CodeAnalysisConfig
IncludeHidden
IncludeTask
TreeStyle
allowListPatternMatching :: TaskConfig -> Bool
codeAnalysis :: TaskConfig -> CodeAnalysisConfig
errorOnFirstTimeout :: TaskConfig -> Bool
includeHiddenDefinitions :: TaskConfig -> IncludeHidden
includeTaskDefinitions :: TaskConfig -> IncludeTask
mainTestTimeout :: TaskConfig -> Arity
rigorousValidation :: TaskConfig -> Bool
showSWISHButton :: TaskConfig -> Bool
specifications :: TaskConfig -> [Spec]
treeStyle :: TaskConfig -> TreeStyle
mainTestTimeout :: Arity
treeStyle :: TreeStyle
includeTaskDefinitions :: IncludeTask
includeHiddenDefinitions :: IncludeHidden
allowListPatternMatching :: Bool
showSWISHButton :: Bool
codeAnalysis :: CodeAnalysisConfig
specifications :: [Spec]
rigorousValidation :: Bool
errorOnFirstTimeout :: Bool
..}, Atom
[ProgramClause]
hiddenPredicates :: TaskInstance -> [ProgramClause]
sampleSolution :: TaskInstance -> [ProgramClause]
taskDescription :: TaskInstance -> Atom
visiblePredicates :: TaskInstance -> [ProgramClause]
sampleSolution :: [ProgramClause]
taskDescription :: Atom
visiblePredicates :: [ProgramClause]
hiddenPredicates :: [ProgramClause]
..} [ProgramClause]
inProg =
  let
    drawTree :: Graph -> m ()
drawTree Graph
tree = do
      svg <- IO ByteString -> m ByteString
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO ByteString -> m ByteString) -> IO ByteString -> m ByteString
forall a b. (a -> b) -> a -> b
$ GraphFormatting -> Graph -> IO ByteString
asInlineSvgWith (TreeStyle -> GraphFormatting
grabFormatting TreeStyle
treeStyle) Graph
tree
      drawPicture svg

    factProg :: [ProgramClause]
factProg =
      (ProgramClause -> Bool) -> [ProgramClause] -> [ProgramClause]
forall a. (a -> Bool) -> [a] -> [a]
filter (IncludeTask -> [ProgramClause] -> ProgramClause -> Bool
taskFilter IncludeTask
includeTaskDefinitions [ProgramClause]
inProg) [ProgramClause]
visiblePredicates
        [ProgramClause] -> [ProgramClause] -> [ProgramClause]
forall a. [a] -> [a] -> [a]
++ (ProgramClause -> Bool) -> [ProgramClause] -> [ProgramClause]
forall a. (a -> Bool) -> [a] -> [a]
filter (IncludeHidden -> [ProgramClause] -> ProgramClause -> Bool
hiddenFilter IncludeHidden
includeHiddenDefinitions [ProgramClause]
inProg) [ProgramClause]
hiddenPredicates
  in
    do
      Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not Bool
allowListPatternMatching) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
        case [ProgramClause] -> Maybe Clause
containsHeadTailPattern [ProgramClause]
inProg of
          Maybe Clause
Nothing -> () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
          Just Clause
t -> Doc -> m ()
forall a. Doc -> m a
reject (Doc -> m ()) -> (Atom -> Doc) -> Atom -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Doc
text (Text -> Doc) -> (Atom -> Text) -> Atom -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Atom -> Text
pack (Atom -> m ()) -> Atom -> m ()
forall a b. (a -> b) -> a -> b
$ Atom
"forbidden use of head/tail-list-matching in " Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Clause -> Atom
prettifyClause Clause
t

      newDefs <- case [Spec] -> [ProgramClause] -> (Doc, Maybe [(Atom, Atom)])
findNewPredicateDefs [Spec]
specifications [ProgramClause]
inProg of
        (Doc
matchReport, Maybe [(Atom, Atom)]
Nothing) -> do
          let errMsg :: Doc
errMsg =
                Text -> Doc
text Text
"Error while looking for required predicates."
                  Doc -> Doc -> Doc
<$$> Text -> Doc
text Text
"Using the following definitions for required predicates:"
                  Doc -> Doc -> Doc
<$$> Doc
matchReport
          [] [(Atom, Atom)] -> m (ZonkAny 0) -> m [(Atom, Atom)]
forall a b. a -> m b -> m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Doc -> m (ZonkAny 0)
forall a. Doc -> m a
reject Doc
errMsg
        (Doc
matchReport, Just [(Atom, Atom)]
newDefs) -> do
          Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ([Spec] -> Bool
requiresNewPredicates [Spec]
specifications)
            (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ Doc -> m ()
inform
            (Doc -> m ()) -> Doc -> m ()
forall a b. (a -> b) -> a -> b
$ Text -> Doc
text Text
"Using the following definitions for required predicates:"
              Doc -> Doc -> Doc
<$$> Doc
matchReport
          [(Atom, Atom)] -> m [(Atom, Atom)]
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [(Atom, Atom)]
newDefs

      let (rulesBeforeTests, rulesAfterTests) =
            partitionWith
              (\(WithSeverity ProgramRule
rule, CheckStage
stage) -> (if CheckStage
stage CheckStage -> CheckStage -> Bool
forall a. Eq a => a -> a -> Bool
== CheckStage
BeforeTests then WithSeverity ProgramRule
-> Either (WithSeverity ProgramRule) (WithSeverity ProgramRule)
forall a b. a -> Either a b
Left else WithSeverity ProgramRule
-> Either (WithSeverity ProgramRule) (WithSeverity ProgramRule)
forall a b. b -> Either a b
Right) WithSeverity ProgramRule
rule)
              $ configuredRules codeAnalysis factProg

      case checkForProblems inProg rulesBeforeTests of
        [] -> () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        [WithSeverity Problem]
pbs -> (Doc -> m ()) -> (Doc -> m ()) -> Either Doc Doc -> m ()
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either Doc -> m ()
forall a. Doc -> m a
reject Doc -> m ()
forall a. HasCallStack => a
undefined (Either Doc Doc -> m ()) -> Either Doc Doc -> m ()
forall a b. (a -> b) -> a -> b
$ [WithSeverity Problem] -> Either Doc Doc
displayProblems [WithSeverity Problem]
pbs

      testResult <-
        liftIO $
          testRunner
            mainTestTimeout
            (TimeoutDivisor 1)
            errorOnFirstTimeout
            factProg
            inProg
            specifications
            newDefs
      case testResult of
        (Finished AreAllOk Spec
AllOk, (Arity
passed, Arity
_)) ->
          Doc -> m ()
inform (Doc -> m ()) -> Doc -> m ()
forall a b. (a -> b) -> a -> b
$
            [Doc] -> Doc
vcat
              [ Text -> Doc
text Text
"Ok"
              , Text -> Doc
text (Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ [Atom] -> Atom
unwords [Arity -> Atom
forall a. Show a => a -> Atom
show Arity
passed, Arity -> Atom -> Atom -> Atom
forall a b. (Eq a, Num a) => a -> b -> b -> b
plural Arity
passed Atom
"test was" Atom
"tests were", Atom
"run"])
              ]
        (Finished (SomeTimeouts (Spec
t :| [Spec]
ts)), (Arity
passed, Arity
_)) -> do
          let testsRun :: Arity
testsRun = Arity
passed Arity -> Arity -> Arity
forall a. Num a => a -> a -> a
+ Arity
1 Arity -> Arity -> Arity
forall a. Num a => a -> a -> a
+ [Spec] -> Arity
forall a. [a] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Spec]
ts
          Doc -> m ()
forall a. Doc -> m a
reject (Doc -> m ()) -> Doc -> m ()
forall a b. (a -> b) -> a -> b
$
            [Doc] -> Doc
vcat
              [ Text -> Doc
text Text
"No."
              , Text -> Doc
text (Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ [Atom] -> Atom
unwords [Arity -> Atom
forall a. Show a => a -> Atom
show Arity
testsRun, Arity -> Atom -> Atom -> Atom
forall a b. (Eq a, Num a) => a -> b -> b -> b
plural Arity
testsRun Atom
"test was" Atom
"tests were", Atom
"run"])
              ]
              Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc -> Doc
nested
                ( Doc
line
                    Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Spec -> Doc
describeSpec Spec
t
                    Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc -> Doc
nested (Doc
line Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Text -> Doc
text Text
"*it appears to be non-terminating* (test case timeout)")
                    Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
line
                    Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> if Bool -> Bool
not ([Spec] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Spec]
ts)
                      then
                        Text -> Doc
text
                          ( Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$
                              Arity -> Atom
forall a. Show a => a -> Atom
show ([Spec] -> Arity
forall a. [a] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Spec]
ts)
                                Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
" additional test "
                                Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Arity -> Atom -> Atom -> Atom
forall a b. (Eq a, Num a) => a -> b -> b -> b
plural ([Spec] -> Arity
forall a. [a] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Spec]
ts) Atom
"case" Atom
"cases"
                                Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
" also timed out"
                          )
                      else Doc
empty
                )
        (Aborted AbortReason Spec (Maybe [Unifier])
reason, (Arity
passed, Arity
notRun)) -> do
          let (Doc
reasonDoc, Maybe Graph
mTree) = AbortReason Spec (Maybe [Unifier]) -> (Doc, Maybe Graph)
explainReason AbortReason Spec (Maybe [Unifier])
reason
          Doc -> m ()
inform (Doc -> m ()) -> Doc -> m ()
forall a b. (a -> b) -> a -> b
$
            [Doc] -> Doc
vcat
              [ Text -> Doc
text Text
"No."
              , Text -> Doc
text (Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ [Atom] -> Atom
unwords [Arity -> Atom
forall a. Show a => a -> Atom
show (Arity
passed Arity -> Arity -> Arity
forall a. Num a => a -> a -> a
+ Arity
1), Arity -> Atom -> Atom -> Atom
forall a b. (Eq a, Num a) => a -> b -> b -> b
plural (Arity
passed Arity -> Arity -> Arity
forall a. Num a => a -> a -> a
+ Arity
1) Atom
"test was" Atom
"tests were", Atom
"run"])
              , Text -> Doc
text Text
"The following test case failed:"
              ]
              Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
reasonDoc
          m () -> (Graph -> m ()) -> Maybe Graph -> m ()
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (() -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()) Graph -> m ()
drawTree Maybe Graph
mTree
          Doc -> m ()
forall a. Doc -> m a
reject
            ( Text -> Doc
text (Text -> Doc) -> (Atom -> Text) -> Atom -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Atom -> Text
pack (Atom -> Doc) -> Atom -> Doc
forall a b. (a -> b) -> a -> b
$
                Atom
"tests passed: "
                  Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Arity -> Atom
forall a. Show a => a -> Atom
show Arity
passed
                  Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ if Arity
notRun Arity -> Arity -> Bool
forall a. Ord a => a -> a -> Bool
> Arity
0 -- only show remaining tests if there is at least one test that was not run
                    then Atom
", tests not run: " Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Arity -> Atom
forall a. Show a => a -> Atom
show Arity
notRun
                    else Atom
""
            )

      case checkForProblems inProg rulesAfterTests of
        [] -> () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        [WithSeverity Problem]
pbs -> (Doc -> m ()) -> (Doc -> m ()) -> Either Doc Doc -> m ()
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either Doc -> m ()
forall a. Doc -> m a
reject Doc -> m ()
inform (Either Doc Doc -> m ()) -> Either Doc Doc -> m ()
forall a b. (a -> b) -> a -> b
$ [WithSeverity Problem] -> Either Doc Doc
displayProblems [WithSeverity Problem]
pbs

      case redundantCode codeAnalysis of
        RedundantCodeConfig CodeAnalysisRuleConfig TimeoutDivisor
Nothing -> () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        RedundantCodeConfig (Just (WithSeverity Severity
severity TimeoutDivisor
timeoutDivisor, CheckStage
AfterTests)) -> do
          let checker :: [ProgramClause] -> IO Bool
checker [ProgramClause]
p =
                TestSuiteResult Spec (Maybe [Unifier]) -> Bool
forall a res. TestSuiteResult a res -> Bool
allTestResultsAreOkay (TestSuiteResult Spec (Maybe [Unifier]) -> Bool)
-> ((TestSuiteResult Spec (Maybe [Unifier]), (Arity, Arity))
    -> TestSuiteResult Spec (Maybe [Unifier]))
-> (TestSuiteResult Spec (Maybe [Unifier]), (Arity, Arity))
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TestSuiteResult Spec (Maybe [Unifier]), (Arity, Arity))
-> TestSuiteResult Spec (Maybe [Unifier])
forall a b. (a, b) -> a
fst
                  ((TestSuiteResult Spec (Maybe [Unifier]), (Arity, Arity)) -> Bool)
-> IO (TestSuiteResult Spec (Maybe [Unifier]), (Arity, Arity))
-> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Arity
-> TimeoutDivisor
-> Bool
-> [ProgramClause]
-> [ProgramClause]
-> [Spec]
-> [(Atom, Atom)]
-> IO (TestSuiteResult Spec (Maybe [Unifier]), (Arity, Arity))
testRunner Arity
mainTestTimeout TimeoutDivisor
timeoutDivisor Bool
True [ProgramClause]
factProg [ProgramClause]
p [Spec]
specifications [(Atom, Atom)]
newDefs
          redundantCodeProblem <- IO (Maybe Problem) -> m (Maybe Problem)
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Maybe Problem) -> m (Maybe Problem))
-> IO (Maybe Problem) -> m (Maybe Problem)
forall a b. (a -> b) -> a -> b
$ ([ProgramClause] -> IO Bool)
-> [ProgramClause] -> IO (Maybe Problem)
checkForRedundantCode [ProgramClause] -> IO Bool
checker [ProgramClause]
inProg

          case redundantCodeProblem of
            Maybe Problem
Nothing -> () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
            Just Problem
problem -> (Doc -> m ()) -> (Doc -> m ()) -> Either Doc Doc -> m ()
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either Doc -> m ()
forall a. Doc -> m a
reject Doc -> m ()
inform (Either Doc Doc -> m ()) -> Either Doc Doc -> m ()
forall a b. (a -> b) -> a -> b
$ [WithSeverity Problem] -> Either Doc Doc
displayProblems [Severity -> Problem -> WithSeverity Problem
forall a. Severity -> a -> WithSeverity a
WithSeverity Severity
severity Problem
problem]
        RedundantCodeConfig CodeAnalysisRuleConfig TimeoutDivisor
_ -> Atom -> m ()
forall a. HasCallStack => Atom -> a
error Atom
"BeforeTests cannot possibly occur here"

displaySampleSolution
  :: (Doc -> m ())
  -> TaskInstance
  -> m ()
displaySampleSolution :: forall (m :: * -> *). (Doc -> m ()) -> TaskInstance -> m ()
displaySampleSolution Doc -> m ()
inform TaskInstance {[ProgramClause]
sampleSolution :: TaskInstance -> [ProgramClause]
sampleSolution :: [ProgramClause]
sampleSolution} =
  Doc -> m ()
inform
    (Doc -> m ()) -> Doc -> m ()
forall a b. (a -> b) -> a -> b
$ [Doc] -> Doc
vsep
    ([Doc] -> Doc) -> [Doc] -> Doc
forall a b. (a -> b) -> a -> b
$ (Text -> Doc
text (Atom -> Text
pack Atom
"A sample solution for this task is:") Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
linebreak)
      Doc -> [Doc] -> [Doc]
forall a. a -> [a] -> [a]
: (ProgramClause -> Doc) -> [ProgramClause] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Doc
text (Text -> Doc) -> (ProgramClause -> Text) -> ProgramClause -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Atom -> Text
pack (Atom -> Text) -> (ProgramClause -> Atom) -> ProgramClause -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Clause -> Atom
prettifyClause (Clause -> Atom)
-> (ProgramClause -> Clause) -> ProgramClause -> Atom
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Atom -> [Term] -> [Term] -> Clause) -> ProgramClause -> Clause
forall a b c d. (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 Atom -> [Term] -> [Term] -> Clause
Clause) [ProgramClause]
sampleSolution

taskFilter :: IncludeTask -> [ProgramClause] -> ProgramClause -> Bool
taskFilter :: IncludeTask -> [ProgramClause] -> ProgramClause -> Bool
taskFilter IncludeTask
Yes [ProgramClause]
_ = Bool -> ProgramClause -> Bool
forall a b. a -> b -> a
const Bool
True
taskFilter No {} [ProgramClause]
_ = Bool -> ProgramClause -> Bool
forall a b. a -> b -> a
const Bool
False
taskFilter IncludeTask
Filtered [ProgramClause]
prog = (ProgramClause -> [ProgramClause] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [ProgramClause]
prog)

hiddenFilter :: IncludeHidden -> [ProgramClause] -> ProgramClause -> Bool
hiddenFilter :: IncludeHidden -> [ProgramClause] -> ProgramClause -> Bool
hiddenFilter IncludeHidden
Yes [ProgramClause]
_ = Bool -> ProgramClause -> Bool
forall a b. a -> b -> a
const Bool
True
hiddenFilter (No Void
x) [ProgramClause]
_ = Void -> ProgramClause -> Bool
forall a. Void -> a
absurd Void
x
hiddenFilter IncludeHidden
Filtered [ProgramClause]
prog = \(Atom
name, [Term]
args, [Term]
_) ->
  let lengthArgs :: Arity
lengthArgs = [Term] -> Arity
forall a. [a] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Term]
args
  in (ProgramClause -> Bool) -> [ProgramClause] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (\(Atom
name', [Term]
args', [Term]
_) -> Atom
name Atom -> Atom -> Bool
forall a. Eq a => a -> a -> Bool
/= Atom
name' Bool -> Bool -> Bool
|| Arity
lengthArgs Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
/= [Term] -> Arity
forall a. [a] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Term]
args') [ProgramClause]
prog

plural :: (Eq a, Num a) => a -> b -> b -> b
plural :: forall a b. (Eq a, Num a) => a -> b -> b -> b
plural a
1 b
x b
_ = b
x
plural a
_ b
_ b
y = b
y

explainReason :: AbortReason Spec (Maybe [Unifier]) -> (Doc, Maybe Graph)
explainReason :: AbortReason Spec (Maybe [Unifier]) -> (Doc, Maybe Graph)
explainReason = AbortReason Spec (Maybe [Unifier]) -> (Doc, Maybe Graph)
explainResult
  where
    explainResult :: AbortReason Spec (Maybe [Unifier]) -> (Doc, Maybe Graph)
explainResult (OnErrorMsg Spec
x Atom
msg) =
      ( Doc -> Doc
nested (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$
          Doc
line
            Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> [Doc] -> Doc
vcat
              [ Spec -> Doc
describeSpec Spec
x
              , Text -> Doc
text Text
"The following error occurred:" Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc -> Doc
nested (Doc
line Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Text -> Doc
text (Atom -> Text
pack Atom
msg))
              ]
      , Maybe Graph
forall a. Maybe a
Nothing
      )
    explainResult (OnWrong x :: Spec
x@(Spec (Hidden Atom
_) Visualize
_ Expection
_ Timeout
_ Requirement
_) Maybe Graph
_ Maybe [Unifier]
_) =
      (Doc -> Doc
nested (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ Doc
line Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Spec -> Doc
describeSpec Spec
x, Maybe Graph
forall a. Maybe a
Nothing)
    explainResult (OnWrong Spec
x Maybe Graph
mTree Maybe [Unifier]
mActual) =
      ( Doc -> Doc
nested (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$
          Doc
line
            Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Spec -> Doc
describeSpec Spec
x
            Doc -> Doc -> Doc
<$$> Maybe [Unifier] -> Doc
resultMsg Maybe [Unifier]
mActual
              Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Maybe Graph -> Doc
treeMsg Maybe Graph
mTree
      , Maybe Graph
mTree
      )
    explainResult (FirstTimeout Spec
x) =
      ( Doc -> Doc
nested (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$
          Doc
line
            Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> [Doc] -> Doc
vcat
              [ Spec -> Doc
describeSpec Spec
x
              , Text -> Doc
text Text
"The test case timed out."
              ]
      , Maybe Graph
forall a. Maybe a
Nothing
      )

treeMsg :: Maybe Graph -> Doc
treeMsg :: Maybe Graph -> Doc
treeMsg = Doc -> (Graph -> Doc) -> Maybe Graph -> Doc
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Doc
empty (Doc -> Graph -> Doc
forall a b. a -> b -> a
const (Doc
line Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Text -> Doc
text Text
"Derivation tree:"))

resultMsg :: Maybe [Unifier] -> Doc
resultMsg :: Maybe [Unifier] -> Doc
resultMsg Maybe [Unifier]
Nothing =
  Text -> Doc
text Text
"Your submission is not general enough."
    Doc -> Doc -> Doc
<$$> Text -> Doc
text Text
"(Your program does not work correctly on arbitrary data.)"
resultMsg (Just [Unifier]
actual) =
  Text -> Doc
text Text
"Your"
    Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc -> Doc
align
      ( Text -> Doc
text Text
" submission gives:"
          Doc -> Doc -> Doc
<$$> if [Unifier] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Unifier]
actual then Text -> Doc
text Text
"false" else ([Doc] -> Doc
vcat ([Doc] -> Doc) -> ([Unifier] -> [Doc]) -> [Unifier] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Unifier -> Doc) -> [Unifier] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Doc
text (Text -> Doc) -> (Unifier -> Text) -> Unifier -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Atom -> Text
pack (Atom -> Text) -> (Unifier -> Atom) -> Unifier -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Unifier -> Atom
printUnifier)) [Unifier]
actual
      )

nested :: Doc -> Doc
nested :: Doc -> Doc
nested = Arity -> Doc -> Doc
nest Arity
4

{- |
pretty-print the interpreter result
-}

-- printResult :: [Unifier] -> String
-- printResult [] = "false"
-- printResult us = intercalate ";\n" $
--   map printUnifier $ nub us

printUnifier :: Unifier -> String
printUnifier :: Unifier -> Atom
printUnifier [] = Atom
"true"
printUnifier Unifier
xs = Atom -> [Atom] -> Atom
forall a. [a] -> [[a]] -> [a]
intercalate Atom
", " ([Atom] -> Atom) -> [Atom] -> Atom
forall a b. (a -> b) -> a -> b
$ ((VariableName, Term) -> Atom) -> Unifier -> [Atom]
forall a b. (a -> b) -> [a] -> [b]
map (\(VariableName
x, Term
t) -> VariableName -> Atom
prettifyVariableName VariableName
x Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
" = " Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Term -> Atom
prettifyTerm Term
t) Unifier
xs

describeSpec :: Spec -> Doc
describeSpec :: Spec -> Doc
describeSpec (Spec (Hidden Atom
str) Visualize
_ Expection
_ Timeout
_ Requirement
_) =
  Text -> Doc
text (Text -> Doc) -> (Atom -> Text) -> Atom -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Atom -> Text
pack (Atom -> Doc) -> Atom -> Doc
forall a b. (a -> b) -> a -> b
$
    Atom
"(a hidden test" Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
str Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
")"
describeSpec (Spec Visibility
Visible Visualize
_ Expection
e Timeout
_ (StatementToCheck [Term]
query)) =
  Text -> Doc
text (Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ [Term] -> Atom
showQuery [Term]
query)
    Doc -> Doc -> Doc
<+> Doc -> Doc
parens (Text -> Doc
text (Atom -> Text
pack Atom
"expected") Doc -> Doc -> Doc
<+> Expection -> Doc
describeExp Expection
e)
  where
    describeExp :: Expection -> Doc
describeExp Expection
PositiveResult = Text -> Doc
text Text
"a positive result"
    describeExp Expection
NegativeResult = Text -> Doc
text Text
"false"
describeSpec (Spec Visibility
Visible Visualize
_ Expection
_ Timeout
_ (QueryWithAnswers [Term]
query [[Term]]
_)) =
  Text -> Doc
text (Text -> Doc) -> (Atom -> Text) -> Atom -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Atom -> Text
pack (Atom -> Doc) -> Atom -> Doc
forall a b. (a -> b) -> a -> b
$
    Atom
"The result of the query " Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom -> Atom
forall a. Show a => a -> Atom
show ([Term] -> Atom
showQuery [Term]
query) Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
" is incorrect."
describeSpec (Spec Visibility
Visible Visualize
_ Expection
_ Timeout
_ (NewPredDecl Term
_ Atom
_)) = Atom -> Doc
forall a. HasCallStack => Atom -> a
error Atom
"NewPredDecl should not be passed to describeSpec"

showQuery :: [Term] -> String
showQuery :: [Term] -> Atom
showQuery [Term]
query = Atom
"?- " Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom -> [Atom] -> Atom
forall a. [a] -> [[a]] -> [a]
intercalate Atom
", " ((Term -> Atom) -> [Term] -> [Atom]
forall a b. (a -> b) -> [a] -> [b]
map Term -> Atom
prettifyTerm [Term]
query) Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
"."

-- | Working with predicates whose name is unknown at configuration time
isNewPredDecl :: Spec -> Bool
isNewPredDecl :: Spec -> Bool
isNewPredDecl (Spec Visibility
_ Visualize
_ Expection
_ Timeout
_ NewPredDecl {}) = Bool
True
isNewPredDecl Spec
_ = Bool
False

requiresNewPredicates :: [Spec] -> Bool
requiresNewPredicates :: [Spec] -> Bool
requiresNewPredicates = (Spec -> Bool) -> [Spec] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Spec -> Bool
isNewPredDecl

findNewPredicateDefs :: [Spec] -> [ProgramClause] -> (Doc, Maybe [(Atom, Atom)])
findNewPredicateDefs :: [Spec] -> [ProgramClause] -> (Doc, Maybe [(Atom, Atom)])
findNewPredicateDefs [Spec]
specs [ProgramClause]
clauses = (Doc
report, Maybe [(Atom, Atom)]
result)
  where
    newDecls :: [(Term, Atom)]
newDecls = (Spec -> Maybe (Term, Atom)) -> [Spec] -> [(Term, Atom)]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe Spec -> Maybe (Term, Atom)
extractNewDeclArgs [Spec]
specs
    extractNewDeclArgs :: Spec -> Maybe (Term, Atom)
extractNewDeclArgs (Spec Visibility
_ Visualize
_ Expection
_ Timeout
_ (NewPredDecl Term
tl Atom
desc)) = (Term, Atom) -> Maybe (Term, Atom)
forall a. a -> Maybe a
Just (Term
tl, Atom
desc)
    extractNewDeclArgs (Spec Visibility
_ Visualize
_ Expection
_ Timeout
_ QueryWithAnswers {}) = Maybe (Term, Atom)
forall a. Maybe a
Nothing
    extractNewDeclArgs (Spec Visibility
_ Visualize
_ Expection
_ Timeout
_ StatementToCheck {}) = Maybe (Term, Atom)
forall a. Maybe a
Nothing

    clauseHeads :: [(Atom, Arity)]
clauseHeads = [(Atom, Arity)] -> [(Atom, Arity)]
forall a. Ord a => [a] -> [a]
nubOrd ([(Atom, Arity)] -> [(Atom, Arity)])
-> [(Atom, Arity)] -> [(Atom, Arity)]
forall a b. (a -> b) -> a -> b
$ (ProgramClause -> (Atom, Arity))
-> [ProgramClause] -> [(Atom, Arity)]
forall a b. (a -> b) -> [a] -> [b]
map (\(Atom
name, [Term]
args, [Term]
_) -> (Atom
name, [Term] -> Arity
forall a. [a] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Term]
args)) [ProgramClause]
clauses

    matching :: [MatchResult]
matching = ((Term, Atom) -> Maybe (Atom, Arity) -> MatchResult)
-> [(Term, Atom)] -> [Maybe (Atom, Arity)] -> [MatchResult]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith (Term, Atom) -> Maybe (Atom, Arity) -> MatchResult
match [(Term, Atom)]
newDecls (((Atom, Arity) -> Maybe (Atom, Arity))
-> [(Atom, Arity)] -> [Maybe (Atom, Arity)]
forall a b. (a -> b) -> [a] -> [b]
map (Atom, Arity) -> Maybe (Atom, Arity)
forall a. a -> Maybe a
Just [(Atom, Arity)]
clauseHeads [Maybe (Atom, Arity)]
-> [Maybe (Atom, Arity)] -> [Maybe (Atom, Arity)]
forall a. [a] -> [a] -> [a]
++ Maybe (Atom, Arity) -> [Maybe (Atom, Arity)]
forall a. a -> [a]
repeat Maybe (Atom, Arity)
forall a. Maybe a
Nothing)
    report :: Doc
report = [Doc] -> Doc
vcat ([Doc] -> Doc) -> [Doc] -> Doc
forall a b. (a -> b) -> a -> b
$ (MatchResult -> Doc) -> [MatchResult] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map MatchResult -> Doc
reportMatch [MatchResult]
matching
    result :: Maybe [(Atom, Atom)]
result = (MatchResult -> Maybe (Atom, Atom))
-> [MatchResult] -> Maybe [(Atom, Atom)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse MatchResult -> Maybe (Atom, Atom)
fromSuccess [MatchResult]
matching

    match :: (Term, String) -> Maybe (Atom, Int) -> MatchResult
    match :: (Term, Atom) -> Maybe (Atom, Arity) -> MatchResult
match (tl :: Term
tl@(Struct Atom
_ [Term]
args), Atom
desc) (Just (Atom
tr, Arity
ar))
      | Arity
expectedAr Arity -> Arity -> Bool
forall a. Eq a => a -> a -> Bool
/= Arity
ar = (Atom, Arity) -> (Atom, Arity) -> MatchResult
WrongArity (Atom
desc, Arity
expectedAr) (Atom
tr, Arity
ar)
      | Bool
otherwise = Term -> Atom -> Atom -> MatchResult
MatchSuccess Term
tl Atom
tr Atom
desc
      where
        expectedAr :: Arity
expectedAr = [Term] -> Arity
forall a. [a] -> Arity
forall (t :: * -> *) a. Foldable t => t a -> Arity
length [Term]
args
    match (Struct {}, Atom
desc) Maybe (Atom, Arity)
Nothing = Atom -> MatchResult
MissingPredicate Atom
desc
    match (Term, Atom)
_ Maybe (Atom, Arity)
_ = Atom -> MatchResult
forall a. HasCallStack => Atom -> a
error Atom
"can't match definitions: term is not a predicate"

data MatchResult
  = MatchSuccess Term Atom String
  | WrongArity (String, Arity) (Atom, Arity)
  | MissingPredicate String

fromSuccess :: MatchResult -> Maybe (Atom, Atom)
fromSuccess :: MatchResult -> Maybe (Atom, Atom)
fromSuccess (MatchSuccess (Struct Atom
name [Term]
_) Atom
tr Atom
_) = (Atom, Atom) -> Maybe (Atom, Atom)
forall a. a -> Maybe a
Just (Atom
name, Atom
tr)
fromSuccess MatchResult
_ = Maybe (Atom, Atom)
forall a. Maybe a
Nothing

reportMatch :: MatchResult -> Doc
reportMatch :: MatchResult -> Doc
reportMatch (MatchSuccess Term
_ Atom
tr Atom
desc) = Text -> Doc
text (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
$ Atom
"- " Atom -> Atom -> Atom
forall a. Semigroup a => a -> a -> a
<> Atom
desc Atom -> Atom -> Atom
forall a. Semigroup a => a -> a -> a
<> Atom
": " Atom -> Atom -> Atom
forall a. Semigroup a => a -> a -> a
<> Atom
tr
reportMatch (WrongArity (Atom
desc, Arity
expectedAr) (Atom
tr, Arity
ar)) =
  Text -> Doc
text (Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$ Atom
"- " Atom -> Atom -> Atom
forall a. Semigroup a => a -> a -> a
<> Atom
desc Atom -> Atom -> Atom
forall a. Semigroup a => a -> a -> a
<> Atom
":")
    Doc -> Doc -> Doc
<$$> Arity -> Doc -> Doc
indent
      Arity
4
      ( Text -> Doc
text
          ( Text
"Trying to use your definition "
              Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Atom -> Text
pack (Atom -> Atom
forall a. Show a => a -> Atom
show Atom
tr)
              Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" but the predicate does not have the correct arity."
          )
          Doc -> Doc -> Doc
<$$> Text -> Doc
text
            ( Atom -> Text
pack (Atom -> Text) -> Atom -> Text
forall a b. (a -> b) -> a -> b
$
                [Atom] -> Atom
unwords
                  [ Atom
"Expected a predicate with"
                  , Arity -> Atom
forall a. Show a => a -> Atom
show Arity
expectedAr
                  , Arity -> Atom -> Atom -> Atom
forall a b. (Eq a, Num a) => a -> b -> b -> b
plural Arity
expectedAr Atom
"argument," Atom
"arguments,"
                  , Atom
"but"
                  , Atom -> Atom
forall a. Show a => a -> Atom
show Atom
tr
                  , Atom
"has"
                  , Arity -> Atom
forall a. Show a => a -> Atom
show Arity
ar Atom -> Atom -> Atom
forall a. [a] -> [a] -> [a]
++ Atom
"."
                  ]
            )
      )
reportMatch (MissingPredicate Atom
desc) = Text -> Doc
text (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
$ Atom
"- " Atom -> Atom -> Atom
forall a. Semigroup a => a -> a -> a
<> Atom
desc Atom -> Atom -> Atom
forall a. Semigroup a => a -> a -> a
<> Atom
": no definition found"

grabFormatting :: TreeStyle -> GraphFormatting
grabFormatting :: TreeStyle -> GraphFormatting
grabFormatting TreeStyle
QueryStyle = GraphFormatting
queryStyle
grabFormatting TreeStyle
ResolutionStyle = GraphFormatting
resolutionStyle

containsHeadTailPattern :: [ProgramClause] -> Maybe Clause
containsHeadTailPattern :: [ProgramClause] -> Maybe Clause
containsHeadTailPattern [] = Maybe Clause
forall a. Maybe a
Nothing
containsHeadTailPattern ((Atom
name, [Term]
args, [Term]
goals) : [ProgramClause]
clauses) =
  case Term -> HasHeadTailPattern
hasHeadTailPattern (Atom -> [Term] -> Term
Struct Atom
name [Term]
args) HasHeadTailPattern -> HasHeadTailPattern -> HasHeadTailPattern
forall a. Semigroup a => a -> a -> a
<> [HasHeadTailPattern] -> HasHeadTailPattern
forall a. Monoid a => [a] -> a
mconcat ((Term -> HasHeadTailPattern) -> [Term] -> [HasHeadTailPattern]
forall a b. (a -> b) -> [a] -> [b]
map Term -> HasHeadTailPattern
hasHeadTailPattern [Term]
goals) of
    HasHeadTailPattern
PatternFound -> Clause -> Maybe Clause
forall a. a -> Maybe a
Just (Clause -> Maybe Clause) -> Clause -> Maybe Clause
forall a b. (a -> b) -> a -> b
$ Atom -> [Term] -> [Term] -> Clause
Clause Atom
name [Term]
args [Term]
goals
    HasHeadTailPattern
DontKnow -> [ProgramClause] -> Maybe Clause
containsHeadTailPattern [ProgramClause]
clauses

hasHeadTailPattern :: Term -> HasHeadTailPattern
hasHeadTailPattern :: Term -> HasHeadTailPattern
hasHeadTailPattern (Struct Atom
"." [Term
_, Var VariableName
_]) = HasHeadTailPattern
PatternFound
hasHeadTailPattern (Struct Atom
_ [Term]
xs) = [HasHeadTailPattern] -> HasHeadTailPattern
forall a. Monoid a => [a] -> a
mconcat ([HasHeadTailPattern] -> HasHeadTailPattern)
-> [HasHeadTailPattern] -> HasHeadTailPattern
forall a b. (a -> b) -> a -> b
$ (Term -> HasHeadTailPattern) -> [Term] -> [HasHeadTailPattern]
forall a b. (a -> b) -> [a] -> [b]
map Term -> HasHeadTailPattern
hasHeadTailPattern [Term]
xs
hasHeadTailPattern Var {} = HasHeadTailPattern
DontKnow
hasHeadTailPattern Cut {} = HasHeadTailPattern
DontKnow

data HasHeadTailPattern = PatternFound | DontKnow

instance Semigroup HasHeadTailPattern where
  HasHeadTailPattern
PatternFound <> :: HasHeadTailPattern -> HasHeadTailPattern -> HasHeadTailPattern
<> HasHeadTailPattern
_ = HasHeadTailPattern
PatternFound
  HasHeadTailPattern
DontKnow <> HasHeadTailPattern
x = HasHeadTailPattern
x

instance Monoid HasHeadTailPattern where
  mempty :: HasHeadTailPattern
mempty = HasHeadTailPattern
DontKnow