From 10dd3d5927205b12e8ea81259c71d51279c64292 Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 11 Aug 2021 10:35:56 +0200 Subject: [PATCH 01/57] cleaning up compiler warnings Cleaning up compiler warnings (including unneeded Monoid imports) --- src/Ideas/Common/Derivation.hs | 1 - src/Ideas/Common/Examples.hs | 1 - src/Ideas/Common/Traversal/Tests.hs | 1 - src/Ideas/Encoding/EncoderHTML.hs | 1 - src/Ideas/Encoding/EncoderXML.hs | 1 - src/Ideas/Encoding/LinkManager.hs | 1 - src/Ideas/Encoding/ModeXML.hs | 1 - src/Ideas/Encoding/NewEncoderJSON.hs | 255 ++------------------- src/Ideas/Encoding/NewModeJSON.hs | 17 +- src/Ideas/Encoding/RulePresenter.hs | 1 - src/Ideas/Encoding/RulesInfo.hs | 1 - src/Ideas/Encoding/StrategyInfo.hs | 1 - src/Ideas/Main/Default.hs | 1 - src/Ideas/Service/FeedbackScript/Parser.hs | 1 - src/Ideas/Text/HTML.hs | 1 - src/Ideas/Text/HTML/Templates.hs | 1 - src/Ideas/Text/HTML/W3CSS.hs | 1 - 17 files changed, 16 insertions(+), 271 deletions(-) diff --git a/src/Ideas/Common/Derivation.hs b/src/Ideas/Common/Derivation.hs index cdf35ecf..0bc7fc2b 100644 --- a/src/Ideas/Common/Derivation.hs +++ b/src/Ideas/Common/Derivation.hs @@ -28,7 +28,6 @@ module Ideas.Common.Derivation ) where import Data.Maybe -import Data.Monoid import Ideas.Common.Classes import Ideas.Common.Rewriting import qualified Data.Foldable as F diff --git a/src/Ideas/Common/Examples.hs b/src/Ideas/Common/Examples.hs index cc04a8e0..895a27d0 100644 --- a/src/Ideas/Common/Examples.hs +++ b/src/Ideas/Common/Examples.hs @@ -36,7 +36,6 @@ module Ideas.Common.Examples import Data.Char import Data.Maybe -import Data.Semigroup import Ideas.Common.Id import Test.QuickCheck diff --git a/src/Ideas/Common/Traversal/Tests.hs b/src/Ideas/Common/Traversal/Tests.hs index 539ef997..b471a320 100644 --- a/src/Ideas/Common/Traversal/Tests.hs +++ b/src/Ideas/Common/Traversal/Tests.hs @@ -17,7 +17,6 @@ module Ideas.Common.Traversal.Tests import Control.Monad import Data.Maybe -import Data.Semigroup as Sem import Ideas.Common.Traversal.Iterator import Ideas.Common.Traversal.Navigator import Ideas.Common.Traversal.Utils diff --git a/src/Ideas/Encoding/EncoderHTML.hs b/src/Ideas/Encoding/EncoderHTML.hs index 4f768ac7..2eb9b7bb 100644 --- a/src/Ideas/Encoding/EncoderHTML.hs +++ b/src/Ideas/Encoding/EncoderHTML.hs @@ -18,7 +18,6 @@ module Ideas.Encoding.EncoderHTML (HTMLEncoder, htmlEncoder) where import Data.Char import Data.List import Data.Maybe -import Data.Monoid import Ideas.Common.Examples (isEmpty, size, allRandoms) import Ideas.Common.Library hiding (alternatives, isEmpty, left, right, collapse, Medium) import Ideas.Common.Strategy.Symbol diff --git a/src/Ideas/Encoding/EncoderXML.hs b/src/Ideas/Encoding/EncoderXML.hs index ed1588ab..108c06a3 100644 --- a/src/Ideas/Encoding/EncoderXML.hs +++ b/src/Ideas/Encoding/EncoderXML.hs @@ -21,7 +21,6 @@ module Ideas.Encoding.EncoderXML import Data.Char import Data.List import Data.Maybe -import Data.Monoid import Ideas.Common.Library hiding (exerciseId) import Ideas.Encoding.Encoder import Ideas.Encoding.OpenMathSupport diff --git a/src/Ideas/Encoding/LinkManager.hs b/src/Ideas/Encoding/LinkManager.hs index 9221ae67..7127b82e 100644 --- a/src/Ideas/Encoding/LinkManager.hs +++ b/src/Ideas/Encoding/LinkManager.hs @@ -29,7 +29,6 @@ module Ideas.Encoding.LinkManager ) where import Data.Maybe -import Data.Monoid import Ideas.Common.Library import Ideas.Encoding.EncoderXML import Ideas.Encoding.Options diff --git a/src/Ideas/Encoding/ModeXML.hs b/src/Ideas/Encoding/ModeXML.hs index 3754185b..efc50394 100644 --- a/src/Ideas/Encoding/ModeXML.hs +++ b/src/Ideas/Encoding/ModeXML.hs @@ -16,7 +16,6 @@ module Ideas.Encoding.ModeXML (processXML) where import Control.Exception import Control.Monad -import Data.Monoid import Ideas.Common.Library hiding (exerciseId) import Ideas.Encoding.DecoderXML import Ideas.Encoding.EncoderHTML diff --git a/src/Ideas/Encoding/NewEncoderJSON.hs b/src/Ideas/Encoding/NewEncoderJSON.hs index 379e438f..4465f579 100644 --- a/src/Ideas/Encoding/NewEncoderJSON.hs +++ b/src/Ideas/Encoding/NewEncoderJSON.hs @@ -15,31 +15,19 @@ module Ideas.Encoding.NewEncoderJSON (JSONBuilder, builderToJSON, jsonEncoder) where -import Control.Applicative hiding (Const) import Data.Char -import Data.Maybe import Ideas.Common.Library hiding (exerciseId) -import Ideas.Encoding.Encoder hiding (symbol) -import Ideas.Encoding.Request +import Ideas.Encoding.Encoder import Ideas.Service.State import Ideas.Service.Types hiding (String) import Ideas.Text.JSON -import Ideas.Utils.Prelude (distinct) import qualified Ideas.Service.Diagnose as Diagnose -import qualified Ideas.Service.Submit as Submit import qualified Ideas.Service.Types as Tp type JSONBuilder = [(Maybe Key, JSON)] listJSONBuilder :: [JSONBuilder] -> JSONBuilder -listJSONBuilder xs = {- - case mapM isSingleton xs of - Just ys -> ys - Nothing -> -} [(Nothing, Array (map builderToJSON xs))] - -isSingleton :: [a] -> Maybe a -isSingleton [x] = Just x -isSingleton _ = Nothing +listJSONBuilder xs = [(Nothing, Array (map builderToJSON xs))] builderToJSON :: JSONBuilder -> JSON builderToJSON [(Nothing, x)] = x @@ -91,28 +79,6 @@ jsonEncodeConst (val ::: tp) = Tp.Bool -> pure [(Nothing, toJSON val)] _ -> fail $ "Type " ++ show tp ++ " not supported in JSON" -{- - encoderFor $ \(val ::: tp) -> - case tp of - Rule -> encodeRule // val - Location -> encodeLocation // val - Environment -> encodeEnvironment // val - Context -> encodeContext // val - State -> encodeState // val - _ -> pure [(Nothing, toJSON (show tp))] - - {- - SomeExercise -> case val of - Some ex -> pure (exerciseInfo ex) - - Term -> pure (termToJSON val) - Text -> pure (toJSON (show val)) - Int -> pure (toJSON val) - Bool -> pure (toJSON val) - Tp.String -> pure (toJSON val) - _ -> fail $ "Type " ++ show tp ++ " not supported in JSON" --} --} encodeRule :: Rule (Context a) -> EncoderX a JSONBuilder encodeRule r = pure (tagJSON "rule" (toJSON (showId r))) @@ -120,15 +86,7 @@ encodeEnvironment :: Environment -> EncoderX a JSONBuilder encodeEnvironment env = let f a = (showId a, String (showValue a)) in pure $ tagJSON "environment" $ Object [ f a | a <- bindings env ] -{- -{-encodeStateEnvironment :: JSONEncoder a (Context a) -encodeStateEnvironment = makeEncoder $ \ctx -> - let loc = fromLocation (location ctx) - env = (if null loc then id else insertRef (makeRef "location") loc) - $ environment ctx - in Object [ (showId a, String $ showValue a) | a <- bindings env ] - -} --} + encodeContext :: Context a -> EncoderX a JSONBuilder encodeContext ctx = let encValue = case fromContext ctx of @@ -146,10 +104,6 @@ encodeTerm a = (tagJSON "term" . f) <$> getExercise Just jv -> build jv a Nothing -> String (prettyPrinter ex a) - - -- True ex = tagJSON "term" . fromMaybe Null . liftA2 build (hasJSONView ex) . return - -- f False ex = tagJSON "term" . String . prettyPrinter ex - encodeLocation :: Location -> EncoderX a JSONBuilder encodeLocation loc = pure (tagJSON "location" (toJSON (fromLocation loc))) @@ -175,211 +129,28 @@ encodeDiagnosis :: Diagnose.Diagnosis a -> EncoderX a JSONBuilder encodeDiagnosis diagnosis = case diagnosis of Diagnose.Correct b st -> - (\xs ys -> (Just "diagnosetype", toJSON "correct") : xs ++ ys) <$> encodeReady b <*> encodeState st + (\xs ys -> (Just "diagnosetype", toJSON "correct") : xs ++ ys) <$> mkReady b <*> encodeState st Diagnose.Similar b st mr -> - (\xs ys zs -> (Just "diagnosetype", toJSON "similar") : xs ++ ys ++ zs) <$> encodeReady b <*> encodeState st <*> encodeMaybeRule mr + (\xs ys zs -> (Just "diagnosetype", toJSON "similar") : xs ++ ys ++ zs) <$> mkReady b <*> encodeState st <*> mkMaybeRule mr Diagnose.NotEquivalent s -> return [(Just "diagnosetype", toJSON "notequiv"), (Just "message", toJSON s)] Diagnose.Expected b st r -> - (\xs ys zs -> (Just "diagnosetype", toJSON "expected") : xs ++ ys ++ zs) <$> encodeReady b <*> encodeState st <*> encodeRule r + (\xs ys zs -> (Just "diagnosetype", toJSON "expected") : xs ++ ys ++ zs) <$> mkReady b <*> encodeState st <*> mkRule r Diagnose.Buggy env r -> - (\xs ys -> (Just "diagnosetype", toJSON "buggy") : xs ++ ys) <$> encodeEnvironment env <*> encodeRule r + (\xs ys -> (Just "diagnosetype", toJSON "buggy") : xs ++ ys) <$> encodeEnvironment env <*> mkRule r Diagnose.Detour b st env r -> - (\xs ys zs vs -> (Just "diagnosetype", toJSON "detour") : xs ++ ys ++ zs ++ vs) <$> encodeReady b <*> encodeState st <*> encodeEnvironment env <*> encodeRule r + (\xs ys zs vs -> (Just "diagnosetype", toJSON "detour") : xs ++ ys ++ zs ++ vs) <$> mkReady b <*> encodeState st <*> encodeEnvironment env <*> mkRule r Diagnose.WrongRule b st mr -> - (\xs ys zs -> (Just "diagnosetype", toJSON "wrongrule") : xs ++ ys ++ zs) <$> encodeReady b <*> encodeState st <*> encodeMaybeRule mr + (\xs ys zs -> (Just "diagnosetype", toJSON "wrongrule") : xs ++ ys ++ zs) <$> mkReady b <*> encodeState st <*> mkMaybeRule mr Diagnose.SyntaxError msg -> pure [(Just "diagnosetype", toJSON "syntaxerror"), (Just "message", toJSON msg)] - where - encodeReady b = return [(Just "ready", toJSON b)] - encodeRule r = return [(Just "rule", toJSON (showId r))] - encodeMaybeRule mr = return [(Just "rule", maybe Null (toJSON . showId) mr)] - - -- make "correct" [fromReady b, fromState st] - - {- - Diagnose.SyntaxError s -> - pure $ Object [("syntaxerror", String s)] - Diagnose.NotEquivalent s -> - if null s then pure (Object [("notequiv", Null)]) - else make "notequiv" [fromReason s] - Diagnose.Buggy env r -> - make "buggy" [fromEnv env, fromRule r] - Diagnose.Similar b st -> - make "similar" [fromReady b, fromState st] - Diagnose.WrongRule b st mr -> - make "wrongrule" [fromReady b, fromState st, fromMaybeRule mr] - Diagnose.Expected b st r -> - make "expected" [fromReady b, fromState st, fromRule r] - Diagnose.Detour b st env r -> - make "detour" [fromReady b, fromState st, fromEnv env, fromRule r] - Diagnose.Correct b st -> - make "correct" [fromReady b, fromState st] Diagnose.Unknown b st -> - make "unknown" [fromReady b, fromState st] + (\xs ys -> (Just "diagnosetype", toJSON "unknown") : xs ++ ys) <$> mkReady b <*> encodeState st where - make s = fmap (\xs -> Object $ ("diagnosis", toJSON s) : xs) . sequence - fromEnv env = fmap (\x -> ("env", x)) $ jsonEncoder // (env ::: tEnvironment) - fromRule r = pure ("rule", (toJSON (showId r))) - fromMaybeRule mr = pure ("mayberule", (maybe Null (toJSON . showId) mr)) - fromReady b = pure ("ready", toJSON b) - fromState st = fmap (\x -> ("state", x)) $ jsonEncoder // (st ::: tState) - fromReason s = pure ("reason", (Object [("reason", toJSON s)])) --} + mkReady b = return [(Just "ready", toJSON b)] + mkRule = mkMaybeRule . Just + mkMaybeRule mr = return [(Just "rule", maybe Null (toJSON . showId) mr)] -{- -{- - Tp.Tag s t - | s == "Result" -> encodeTyped encodeResult Submit.tResult - | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis - | s == "Derivation" -> (encodeDerivation, tDerivation (tPair tRule tEnvironment) tContext) - encodeTyped encodeDerivationText (tDerivation tString tContext) - | s == "elem" -> jsonEncoder // (val ::: t) - | otherwise -> (\b -> Object [(s, b)]) <$> jsonEncoder // (val ::: t) - Tp.Unit -> pure Null - - Const ctp -> jsonEncodeConst // (val ::: ctp) - _ -> fail $ "Cannot encode type: " ++ show tp --} -{- -jsonEncoder = encoderFor $ \tv@(val ::: tp) -> - case tp of - _ | length (tupleList tv) > 1 -> - jsonTuple <$> sequence [ jsonEncoder // x | x <- tupleList tv ] - Iso p t -> jsonEncoder // (to p val ::: t) - t1 :|: t2 -> case val of - Left x -> jsonEncoder // (x ::: t1) - Right y -> jsonEncoder // (y ::: t2) - Pair t1 t2 -> - let f x y = jsonTuple [x, y] - in liftA2 f (jsonEncoder // (fst val ::: t1)) - (jsonEncoder // (snd val ::: t2)) - List (Const Rule) -> - pure $ Array $ map ruleShortInfo val - Tp.Tag s t - | s == "Result" -> encodeTyped encodeResult Submit.tResult - | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis - | s == "Derivation" -> (encodeDerivation, tDerivation (tPair tRule tEnvironment) tContext) - encodeTyped encodeDerivationText (tDerivation tString tContext) - | s == "elem" -> jsonEncoder // (val ::: t) - | otherwise -> (\b -> Object [(s, b)]) <$> jsonEncoder // (val ::: t) - Tp.Unit -> pure Null - Tp.List t -> Array <$> sequence [ jsonEncoder // (x ::: t) | x <- val ] - Const ctp -> jsonEncodeConst // (val ::: ctp) - _ -> fail $ "Cannot encode type: " ++ show tp - where - tupleList :: TypedValue (TypeRep f) -> [TypedValue (TypeRep f)] - tupleList (x ::: Tp.Iso p t) = tupleList (to p x ::: t) - tupleList (p ::: Tp.Pair t1 t2) = - tupleList (fst p ::: t1) ++ tupleList (snd p ::: t2) - tupleList (x ::: Tag s t) - | s == "Message" = tupleList (x ::: t) - tupleList (ev ::: (t1 :|: t2)) = - either (\x -> tupleList (x ::: t1)) - (\x -> tupleList (x ::: t2)) ev - tupleList tv = [tv] --------------------------- --- legacy representation -encodeEnvironment :: JSONEncoder a Environment -encodeEnvironment = makeEncoder $ \env -> - let f a = Object [(showId a, String (showValue a))] - in Object [("environment", Array [ f a | a <- bindings env ])] -encodeDerivation :: JSONEncoder a (Derivation (Rule (Context a), Environment) (Context a)) -encodeDerivation = encoderFor $ \d -> - let xs = [ (s, a) | (_, s, a) <- triples d ] - in jsonEncoder // (xs ::: tList (tPair (tPair tRule tEnvironment) tContext)) -encodeDerivationText :: JSONEncoder a (Derivation String (Context a)) -encodeDerivationText = encoderFor $ \d -> - let xs = [ (s, a) | (_, s, a) <- triples d ] - in jsonEncoder // (xs ::: tList (tPair tString tContext)) -encodeResult :: JSONEncoder a (Submit.Result a) -encodeResult = encoderFor $ \result -> Object <$> - case result of - Submit.Buggy rs -> pure - [ ("result", String "Buggy") - , ("rules", Array $ map (String . showId) rs) - ] - Submit.NotEquivalent s -> pure $ - ("result", String "NotEquivalent") : - [ ("reason", String s) | not (null s)] - Submit.Ok rs st -> - let f x = - [ ("result", String "Ok") - , ("rules", Array $ map (String . showId) rs) - , ("state", x) - ] - in f <$> jsonEncoder // (st ::: tState) - Submit.Detour rs st -> - let f x = - [ ("result", String "Detour") - , ("rules", Array $ map (String . showId) rs) - , ("state", x) - ] - in f <$> jsonEncoder // (st ::: tState) - Submit.Unknown st -> - let f x = - [ ("result", String "Unknown") - , ("state", x) - ] - in f <$> jsonEncoder // (st ::: tState) -encodeDiagnosis :: JSONEncoder a (Diagnose.Diagnosis a) -encodeDiagnosis = encoderFor $ \diagnosis -> - case diagnosis of - Diagnose.SyntaxError s -> - pure $ Object [("syntaxerror", String s)] - Diagnose.NotEquivalent s -> - if null s then pure (Object [("notequiv", Null)]) - else make "notequiv" [fromReason s] - Diagnose.Buggy env r -> - make "buggy" [fromEnv env, fromRule r] - Diagnose.Similar b st -> - make "similar" [fromReady b, fromState st] - Diagnose.WrongRule b st mr -> - make "wrongrule" [fromReady b, fromState st, fromMaybeRule mr] - Diagnose.Expected b st r -> - make "expected" [fromReady b, fromState st, fromRule r] - Diagnose.Detour b st env r -> - make "detour" [fromReady b, fromState st, fromEnv env, fromRule r] - Diagnose.Correct b st -> - make "correct" [fromReady b, fromState st] - Diagnose.Unknown b st -> - make "unknown" [fromReady b, fromState st] - where - make s = fmap (\xs -> Object $ ("diagnosis", toJSON s) : xs) . sequence - fromEnv env = fmap (\x -> ("env", x)) $ jsonEncoder // (env ::: tEnvironment) - fromRule r = pure ("rule", (toJSON (showId r))) - fromMaybeRule mr = pure ("mayberule", (maybe Null (toJSON . showId) mr)) - fromReady b = pure ("ready", toJSON b) - fromState st = fmap (\x -> ("state", x)) $ jsonEncoder // (st ::: tState) - fromReason s = pure ("reason", (Object [("reason", toJSON s)])) -{- -encodeTree :: Tree JSON -> JSON -encodeTree (Node r ts) = - case r of - Array [x, t] -> Object - [ ("rootLabel", x) - , ("type", t) - , ("subForest", Array $ map encodeTree ts) - ] - _ -> error "ModeJSON: malformed tree!" -} -jsonTuple :: [JSON] -> JSON -jsonTuple xs = - case catMaybes <$> mapM f xs of - Just ys | distinct (map fst ys) -> Object ys - _ -> Array xs - where - f (Object [p]) = Just (Just p) - f Null = Just Nothing - f _ = Nothing -ruleShortInfo :: Rule a -> JSON -ruleShortInfo r = Object - [ ("name", toJSON (showId r)) - , ("buggy", toJSON (isBuggy r)) - , ("arguments", toJSON (length (getRefs r))) - , ("rewriterule", toJSON (isRewriteRule r)) - ] --} --} exerciseInfo :: Exercise a -> JSONBuilder exerciseInfo ex = tagJSON "exercise" $ Object [ ("exerciseid", toJSON (showId ex)) diff --git a/src/Ideas/Encoding/NewModeJSON.hs b/src/Ideas/Encoding/NewModeJSON.hs index 22c61ef9..b1ded0e3 100644 --- a/src/Ideas/Encoding/NewModeJSON.hs +++ b/src/Ideas/Encoding/NewModeJSON.hs @@ -18,7 +18,6 @@ import Control.Applicative import Control.Exception import Control.Monad import System.IO.Error -import Data.Char import Data.Maybe import Data.Semigroup ((<>)) import Ideas.Common.Library hiding (exerciseId) @@ -26,8 +25,7 @@ import qualified Ideas.Encoding.ModeJSON as Legacy import Ideas.Encoding.NewDecoderJSON import Ideas.Encoding.NewEncoderJSON import Ideas.Encoding.Evaluator -import Ideas.Encoding.Logging (changeLog, errormsg) -import Ideas.Encoding.Options (Options, makeOptions, maxTime, cgiBin, logRef) +import Ideas.Encoding.Options (Options, makeOptions, maxTime, cgiBin) import Ideas.Encoding.Request import Ideas.Service.DomainReasoner import Ideas.Text.JSON @@ -47,9 +45,8 @@ processJSON options dr txt = do return (req, f resp, "application/json") jsonRPC2 :: DomainReasoner -> String -> JSON -> RPCHandler -> IO JSON -jsonRPC2 dr serviceName input rpc = do - json <- rpc serviceName input - return (okResponse dr serviceName json) +jsonRPC2 dr serviceName json rpc = do + okResponse dr serviceName <$> rpc serviceName json `catch` handler where handler :: SomeException -> IO JSON @@ -78,14 +75,6 @@ extractExerciseId json = f <$> ( f (String s) = newId s f _ = error "expecting an exercise id" -addVersion :: String -> JSON -> JSON -addVersion str json = - case json of - Object xs -> Object (xs ++ [info]) - _ -> json - where - info = ("version", String str) - jsonRequest :: Monad m => Options -> JSON -> m Request jsonRequest options json = do let exId = extractExerciseId json diff --git a/src/Ideas/Encoding/RulePresenter.hs b/src/Ideas/Encoding/RulePresenter.hs index 47d034ca..973b23c8 100644 --- a/src/Ideas/Encoding/RulePresenter.hs +++ b/src/Ideas/Encoding/RulePresenter.hs @@ -14,7 +14,6 @@ module Ideas.Encoding.RulePresenter (ruleToHTML) where import Data.List import Data.Maybe -import Data.Monoid import Ideas.Common.Library import Ideas.Text.HTML diff --git a/src/Ideas/Encoding/RulesInfo.hs b/src/Ideas/Encoding/RulesInfo.hs index b233615e..23434701 100644 --- a/src/Ideas/Encoding/RulesInfo.hs +++ b/src/Ideas/Encoding/RulesInfo.hs @@ -15,7 +15,6 @@ module Ideas.Encoding.RulesInfo ) where import Data.Char -import Data.Monoid import Ideas.Common.Library import Ideas.Encoding.OpenMathSupport (toOMOBJ) import Ideas.Text.OpenMath.FMP diff --git a/src/Ideas/Encoding/StrategyInfo.hs b/src/Ideas/Encoding/StrategyInfo.hs index 60a55c98..ac8f1167 100644 --- a/src/Ideas/Encoding/StrategyInfo.hs +++ b/src/Ideas/Encoding/StrategyInfo.hs @@ -14,7 +14,6 @@ module Ideas.Encoding.StrategyInfo (strategyToXML) where -import Data.Monoid import Ideas.Common.Id import Ideas.Common.Strategy.Abstract import Ideas.Common.Strategy.Configuration diff --git a/src/Ideas/Main/Default.hs b/src/Ideas/Main/Default.hs index e2cb99c5..e05a6f26 100644 --- a/src/Ideas/Main/Default.hs +++ b/src/Ideas/Main/Default.hs @@ -24,7 +24,6 @@ import Control.Monad import Data.ByteString (ByteString, unpack) import Data.Char import Data.Maybe -import Data.Monoid import Data.String import Ideas.Encoding.NewModeJSON (processJSON) import Ideas.Encoding.ModeXML (processXML) diff --git a/src/Ideas/Service/FeedbackScript/Parser.hs b/src/Ideas/Service/FeedbackScript/Parser.hs index 14fe9de2..f9249828 100644 --- a/src/Ideas/Service/FeedbackScript/Parser.hs +++ b/src/Ideas/Service/FeedbackScript/Parser.hs @@ -20,7 +20,6 @@ import Control.Exception hiding (try) import Control.Monad import Data.Char import Data.List -import Data.Semigroup import Ideas.Common.Id import Ideas.Service.FeedbackScript.Syntax import Ideas.Utils.Parsing diff --git a/src/Ideas/Text/HTML.hs b/src/Ideas/Text/HTML.hs index 09b09f17..f87f10c8 100644 --- a/src/Ideas/Text/HTML.hs +++ b/src/Ideas/Text/HTML.hs @@ -32,7 +32,6 @@ module Ideas.Text.HTML import Data.Char import Data.List -import Data.Monoid import Ideas.Text.XML import qualified Data.Map as M import qualified Ideas.Text.XML as XML diff --git a/src/Ideas/Text/HTML/Templates.hs b/src/Ideas/Text/HTML/Templates.hs index 1e37c136..6859bc5c 100644 --- a/src/Ideas/Text/HTML/Templates.hs +++ b/src/Ideas/Text/HTML/Templates.hs @@ -18,7 +18,6 @@ module Ideas.Text.HTML.Templates , fontAwesome ) where -import Data.Monoid import Ideas.Text.HTML import Ideas.Text.HTML.W3CSS hiding (tag, ul, top, table, content) import Ideas.Text.XML hiding (content) diff --git a/src/Ideas/Text/HTML/W3CSS.hs b/src/Ideas/Text/HTML/W3CSS.hs index 4257c159..d88a6080 100644 --- a/src/Ideas/Text/HTML/W3CSS.hs +++ b/src/Ideas/Text/HTML/W3CSS.hs @@ -16,7 +16,6 @@ module Ideas.Text.HTML.W3CSS where import Data.Char -import Data.Monoid import Ideas.Text.HTML import Ideas.Text.XML import qualified Ideas.Text.XML as XML From ee975521055a3d1ae457568794812ce2d8bc71bd Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 11 Aug 2021 11:41:11 +0200 Subject: [PATCH 02/57] Update ideas.cabal base should be >= 4.11 (for Monoid export by Prelude) --- ideas.cabal | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ideas.cabal b/ideas.cabal index 35762764..4966633b 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -49,7 +49,7 @@ Library ghc-options: -Wall hs-source-dirs: src Build-Depends: - base >= 4.8 && < 5, + base >= 4.11 && < 5, blaze-builder >= 0.4, bytestring, case-insensitive, From c2cd7ca19b16879b388d9a699ab8e8ff7aaf4e44 Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 11 Aug 2021 12:28:56 +0200 Subject: [PATCH 03/57] suppress deprecation warnings (from CGI package) --- src/Ideas/Main/CGI.hs | 1 + src/Ideas/Main/Default.hs | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Ideas/Main/CGI.hs b/src/Ideas/Main/CGI.hs index 187dffd3..14952e2f 100644 --- a/src/Ideas/Main/CGI.hs +++ b/src/Ideas/Main/CGI.hs @@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-} +{-# OPTIONS -Wno-deprecations #-} -- Original source: https://hackage.haskell.org/package/wai-extra-3.0.20.0/docs/Network-Wai-Handler-CGI.html module Ideas.Main.CGI (run) where diff --git a/src/Ideas/Main/Default.hs b/src/Ideas/Main/Default.hs index e05a6f26..e33b85c8 100644 --- a/src/Ideas/Main/Default.hs +++ b/src/Ideas/Main/Default.hs @@ -1,3 +1,4 @@ +{-# OPTIONS -Wno-deprecations #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -27,7 +28,7 @@ import Data.Maybe import Data.String import Ideas.Encoding.NewModeJSON (processJSON) import Ideas.Encoding.ModeXML (processXML) -import Ideas.Encoding.Options (Options, maxTime, optionCgiBin, logRef) +import Ideas.Encoding.Options (Options, optionCgiBin, logRef) import Ideas.Encoding.Request import Ideas.Main.CmdLineOptions hiding (fullVersion) import Ideas.Service.DomainReasoner From 335f468086cc2caf86abae4f326792808947b3c0 Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 11 Aug 2021 12:30:12 +0200 Subject: [PATCH 04/57] stop support for ghc 8.2 (and earlier) base must be >= 4.11 --- .travis.yml | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/.travis.yml b/.travis.yml index e89e5350..7a2c087b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -48,23 +48,28 @@ matrix: # compiler: ": #GHC 7.4.2" # addons: {apt: {packages: [cabal-install-1.16,ghc-7.4.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} #- env: BUILD=cabal GHCVER=7.6.3 CABALVER=1.16 HAPPYVER=1.19.5 ALEXVER=3.1.7 - #compiler: ": #GHC 7.6.3" - #addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} + # compiler: ": #GHC 7.6.3" + # addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} #- env: BUILD=cabal GHCVER=7.8.4 CABALVER=1.18 HAPPYVER=1.19.5 ALEXVER=3.1.7 - #compiler: ": #GHC 7.8.4" - #addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - - env: BUILD=cabal GHCVER=7.10.3 CABALVER=1.22 HAPPYVER=1.19.5 ALEXVER=3.1.7 - compiler: ": #GHC 7.10.3" - addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - - env: BUILD=cabal GHCVER=8.0.2 CABALVER=1.24 HAPPYVER=1.19.5 ALEXVER=3.1.7 - compiler: ": #GHC 8.0.2" - addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - - env: BUILD=cabal GHCVER=8.2.2 CABALVER=2.0 HAPPYVER=1.19.5 ALEXVER=3.1.7 - compiler: ": #GHC 8.2.2" - addons: {apt: {packages: [cabal-install-2.0,ghc-8.2.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - - env: BUILD=cabal GHCVER=8.4.2 CABALVER=2.2 HAPPYVER=1.19.5 ALEXVER=3.1.7 + # compiler: ": #GHC 7.8.4" + # addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} + #- env: BUILD=cabal GHCVER=7.10.3 CABALVER=1.22 HAPPYVER=1.19.5 ALEXVER=3.1.7 + # compiler: ": #GHC 7.10.3" + # addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} + #- env: BUILD=cabal GHCVER=8.0.2 CABALVER=1.24 HAPPYVER=1.19.5 ALEXVER=3.1.7 + # compiler: ": #GHC 8.0.2" + # addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} + #- env: BUILD=cabal GHCVER=8.2.2 CABALVER=2.0 HAPPYVER=1.19.5 ALEXVER=3.1.7 + # compiler: ": #GHC 8.2.2" + # addons: {apt: {packages: [cabal-install-2.0,ghc-8.2.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} + + - env: BUILD=cabal GHCVER=8.4.2 CABALVER=2.2 compiler: ": #GHC 8.4.2" - addons: {apt: {packages: [cabal-install-2.2,ghc-8.4.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} + addons: {apt: {packages: [cabal-install-2.2,ghc-8.4.2], sources: [hvr-ghc]}} + + - env: BUILD=cabal GHCVER=8.6.5 CABALVER=2.4 + compiler: ": #GHC 8.6.5" + addons: {apt: {packages: [cabal-install-2.4,ghc-8.6.5], sources: [hvr-ghc]}} # Build with the newest GHC and cabal-install. This is an accepted failure, # see below. @@ -87,13 +92,9 @@ matrix: #compiler: ": #stack 7.10.2" #addons: {apt: {packages: [ghc-7.10.2], sources: [hvr-ghc]}} - - env: BUILD=cabal GHCVER=8.6.5 CABALVER=2.4 - compiler: ": #GHC 8.6.5" - addons: {apt: {packages: [cabal-install-2.4,ghc-8.6.5], sources: [hvr-ghc]}} - - - env: BUILD=stack ARGS="--resolver lts-6" - compiler: ": #stack 7.10.3" - addons: {apt: {packages: [ghc-7.10.3], sources: [hvr-ghc]}} + #- env: BUILD=stack ARGS="--resolver lts-6" + # compiler: ": #stack 7.10.3" + # addons: {apt: {packages: [ghc-7.10.3], sources: [hvr-ghc]}} # Nightly builds are allowed to fail #- env: BUILD=stack ARGS="--resolver nightly" From d5d585444afbe356fbaa235450a19efbcf1a45f6 Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 11 Aug 2021 12:50:45 +0200 Subject: [PATCH 05/57] Update .travis.yml testing with ghc 8.8.4 --- .travis.yml | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7a2c087b..18cc4525 100644 --- a/.travis.yml +++ b/.travis.yml @@ -71,6 +71,10 @@ matrix: compiler: ": #GHC 8.6.5" addons: {apt: {packages: [cabal-install-2.4,ghc-8.6.5], sources: [hvr-ghc]}} + - env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 + compiler: ": #GHC 8.8.4" + addons: {apt: {packages: [cabal-install-2.4,ghc-8.8.4], sources: [hvr-ghc]}} + # Build with the newest GHC and cabal-install. This is an accepted failure, # see below. @@ -114,19 +118,20 @@ matrix: #compiler: ": #stack 7.10.2 osx" #os: osx - - env: BUILD=stack ARGS="--resolver lts-6" - compiler: ": #stack 7.10.3 osx" - os: osx + #- env: BUILD=stack ARGS="--resolver lts-6" + # compiler: ": #stack 7.10.3 osx" + # os: osx #- env: BUILD=stack ARGS="--resolver nightly" #compiler: ": #stack nightly osx" #os: osx allow_failures: + - env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 #- env: BUILD=cabal GHCVER=head CABALVER=head HAPPYVER=1.19.5 ALEXVER=3.1.7 #- env: BUILD=stack ARGS="--resolver nightly" - - env: BUILD=stack ARGS="--resolver lts-6" - - env: BUILD=cabal GHCVER=8.6.5 + #- env: BUILD=stack ARGS="--resolver lts-6" + #- env: BUILD=cabal GHCVER=8.6.5 before_install: From 2ea0a8589a56a9fa6a02a1a4aacdc2d8b1b682df Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 11 Aug 2021 13:09:18 +0200 Subject: [PATCH 06/57] Update ideas.cabal test relaxing upper bound for QuickCheck --- ideas.cabal | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ideas.cabal b/ideas.cabal index 4966633b..30429134 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -53,7 +53,7 @@ Library blaze-builder >= 0.4, bytestring, case-insensitive, - QuickCheck >= 2.8 && < 2.12, + QuickCheck >= 2.8, Diff, containers, directory, From 3a0cf152846e5fecc4a51b28122b431722d2c6fe Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 11 Aug 2021 13:24:47 +0200 Subject: [PATCH 07/57] fixing cabal and travis stay on base-4 --- .travis.yml | 8 ++++---- ideas.cabal | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 18cc4525..cc90c483 100644 --- a/.travis.yml +++ b/.travis.yml @@ -71,9 +71,9 @@ matrix: compiler: ": #GHC 8.6.5" addons: {apt: {packages: [cabal-install-2.4,ghc-8.6.5], sources: [hvr-ghc]}} - - env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 - compiler: ": #GHC 8.8.4" - addons: {apt: {packages: [cabal-install-2.4,ghc-8.8.4], sources: [hvr-ghc]}} + #- env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 + # compiler: ": #GHC 8.8.4" + # addons: {apt: {packages: [cabal-install-2.4,ghc-8.8.4], sources: [hvr-ghc]}} # Build with the newest GHC and cabal-install. This is an accepted failure, # see below. @@ -127,7 +127,7 @@ matrix: #os: osx allow_failures: - - env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 + #- env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 #- env: BUILD=cabal GHCVER=head CABALVER=head HAPPYVER=1.19.5 ALEXVER=3.1.7 #- env: BUILD=stack ARGS="--resolver nightly" #- env: BUILD=stack ARGS="--resolver lts-6" diff --git a/ideas.cabal b/ideas.cabal index 30429134..4966633b 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -53,7 +53,7 @@ Library blaze-builder >= 0.4, bytestring, case-insensitive, - QuickCheck >= 2.8, + QuickCheck >= 2.8 && < 2.12, Diff, containers, directory, From ad060b3335289cf961323166c51df6473c5c3bbb Mon Sep 17 00:00:00 2001 From: Bastiaan Heeren Date: Mon, 16 Aug 2021 09:54:56 +0200 Subject: [PATCH 08/57] moving apply service to separate module --- ideas.cabal | 1 + src/Ideas/Common/Context.hs | 6 ++- src/Ideas/Service/Apply.hs | 67 ++++++++++++++++++++++++++++++ src/Ideas/Service/BasicServices.hs | 55 +----------------------- src/Ideas/Service/Diagnose.hs | 3 +- src/Ideas/Service/ServiceList.hs | 3 +- 6 files changed, 78 insertions(+), 57 deletions(-) create mode 100644 src/Ideas/Service/Apply.hs diff --git a/ideas.cabal b/ideas.cabal index 4966633b..678afec4 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -143,6 +143,7 @@ Library Ideas.Main.CmdLineOptions Ideas.Main.Default Ideas.Main.Revision + Ideas.Service.Apply Ideas.Service.BasicServices Ideas.Service.Diagnose Ideas.Service.DomainReasoner diff --git a/src/Ideas/Common/Context.hs b/src/Ideas/Common/Context.hs index f7ba6ed7..ba2c47b2 100644 --- a/src/Ideas/Common/Context.hs +++ b/src/Ideas/Common/Context.hs @@ -27,6 +27,7 @@ module Ideas.Common.Context , liftToContext, contextView , use, useC, applyTop , currentTerm, changeTerm, replaceInContext, currentInContext, changeInContext + , setLocation ) where import Data.Maybe @@ -176,4 +177,7 @@ changeInContext :: (a -> a) -> Context a -> Context a changeInContext f (C env a) = C env (changeNavigator f a) replaceInContext :: a -> Context a -> Context a -replaceInContext = changeInContext . const \ No newline at end of file +replaceInContext = changeInContext . const + +setLocation :: Location -> Context a -> Context a +setLocation loc c = fromMaybe c (navigateTo loc c) \ No newline at end of file diff --git a/src/Ideas/Service/Apply.hs b/src/Ideas/Service/Apply.hs new file mode 100644 index 00000000..f78773c1 --- /dev/null +++ b/src/Ideas/Service/Apply.hs @@ -0,0 +1,67 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +module Ideas.Service.Apply + ( apply + ) where + +import Data.List +import Data.Maybe +import Ideas.Common.Library hiding (apply) +import Ideas.Service.State +import Ideas.Service.BasicServices (allfirsts) +import qualified Data.Set as S + +-- Two possible scenarios: either I have a prefix and I can return a new one (i.e., still following the +-- strategy), or I return a new term without a prefix. A final scenario is that the rule cannot be applied +-- to the current term at the given location, in which case the request is invalid. +apply :: Rule (Context a) -> Location -> Environment -> State a -> Either String (State a) +apply r loc env state + | withoutPrefix state = applyOff + | otherwise = applyOn + where + applyOn = -- scenario 1: on-strategy + maybe applyOff Right $ listToMaybe + [ s1 | xs <- either (const []) return (allfirsts state), ((r1, loc1, env1), s1) <- xs, r == r1, loc == loc1, noBindings env || env == env1 ] + + ca = setLocation loc (stateContext state) + applyOff = -- scenario 2: off-strategy + case transApplyWith env (transformation r) ca of + (new, _):_ -> Right (restart (state {stateContext = new, statePrefix = noPrefix})) + [] -> + -- first check the environment (exercise-specific property) + case environmentCheck of + Just msg -> + Left msg + Nothing -> + -- try to find a buggy rule + case siblingsFirst [ (br, envOut) | br <- ruleset (exercise state), isBuggy br, (_, envOut) <- transApplyWith env (transformation br) ca ] of + [] -> Left ("Cannot apply " ++ show r) + brs -> Left ("Buggy rule " ++ intercalate "+" (map pp brs)) + where + pp (br, envOut) + | noBindings envOut = show br + | otherwise = show br ++ " {" ++ show envOut ++ "}" + + siblingsFirst xs = ys ++ zs + where + (ys, zs) = partition (siblingInCommon r . fst) xs + + environmentCheck :: Maybe String + environmentCheck = do + p <- getProperty "environment-check" (exercise state) + p env + +siblingInCommon :: Rule a -> Rule a -> Bool +siblingInCommon r1 r2 = not (S.null (getSiblings r1 `S.intersection` getSiblings r2)) + where + getSiblings r = S.fromList (getId r : ruleSiblings r) diff --git a/src/Ideas/Service/BasicServices.hs b/src/Ideas/Service/BasicServices.hs index 29c52a25..ddd367e4 100644 --- a/src/Ideas/Service/BasicServices.hs +++ b/src/Ideas/Service/BasicServices.hs @@ -13,21 +13,19 @@ module Ideas.Service.BasicServices ( -- * Basic Services stepsremaining, findbuggyrules, allfirsts, solution, solutionMaxSteps - , onefirst, onefinal, applicable, allapplications, apply, generate, create + , onefirst, onefinal, applicable, allapplications, generate, create , StepInfo, tStepInfo, exampleDerivations, recognizeRule ) where import Control.Monad import Data.List -import Data.Maybe import Ideas.Common.Examples import Ideas.Common.Library hiding (applicable, apply, ready) -import Ideas.Common.Traversal.Navigator (downs, navigateTo) +import Ideas.Common.Traversal.Navigator (downs) import Ideas.Service.State import Ideas.Service.Types import Ideas.Utils.Prelude (fst3) import Test.QuickCheck.Random -import qualified Data.Set as S import qualified Ideas.Common.Classes as Apply import qualified Ideas.Common.Library as Library @@ -133,55 +131,6 @@ allapplications state = sortBy cmp (xs ++ ys) EQ -> loc1 `compare` loc2 this -> this --- local helper -setLocation :: Location -> Context a -> Context a -setLocation loc c0 = fromMaybe c0 (navigateTo loc c0) - --- Two possible scenarios: either I have a prefix and I can return a new one (i.e., still following the --- strategy), or I return a new term without a prefix. A final scenario is that the rule cannot be applied --- to the current term at the given location, in which case the request is invalid. -apply :: Rule (Context a) -> Location -> Environment -> State a -> Either String (State a) -apply r loc env state - | withoutPrefix state = applyOff - | otherwise = applyOn - where - applyOn = -- scenario 1: on-strategy - maybe applyOff Right $ listToMaybe - [ s1 | Right xs <- [allfirsts state], ((r1, loc1, env1), s1) <- xs, r==r1, loc==loc1, noBindings env || env==env1 ] - - ca = setLocation loc (stateContext state) - applyOff = -- scenario 2: off-strategy - case transApplyWith env (transformation r) ca of - (new, _):_ -> Right (restart (state {stateContext = new, statePrefix = noPrefix})) - [] -> - -- first check the environment (exercise-specific property) - case environmentCheck of - Just msg -> - Left msg - Nothing -> - -- try to find a buggy rule - case siblingsFirst [ (br, envOut) | br <- ruleset (exercise state), isBuggy br, (_, envOut) <- transApplyWith env (transformation br) ca ] of - [] -> Left ("Cannot apply " ++ show r) - brs -> Left ("Buggy rule " ++ intercalate "+" (map pp brs)) - where - pp (br, envOut) - | noBindings envOut = show br - | otherwise = show br ++ " {" ++ show envOut ++ "}" - - siblingsFirst xs = ys ++ zs - where - (ys, zs) = partition (siblingInCommon r . fst) xs - - environmentCheck :: Maybe String - environmentCheck = do - p <- getProperty "environment-check" (exercise state) - p env - -siblingInCommon :: Rule a -> Rule a -> Bool -siblingInCommon r1 r2 = not (S.null (getSiblings r1 `S.intersection` getSiblings r2)) - where - getSiblings r = S.fromList (getId r : ruleSiblings r) - stepsremaining :: State a -> Either String Int stepsremaining = mapSecond derivationLength . solution Nothing diff --git a/src/Ideas/Service/Diagnose.hs b/src/Ideas/Service/Diagnose.hs index 6f3e0c9b..e901077f 100644 --- a/src/Ideas/Service/Diagnose.hs +++ b/src/Ideas/Service/Diagnose.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -22,7 +21,7 @@ module Ideas.Service.Diagnose import Data.List (find, intercalate, sortBy) import Data.Maybe import Ideas.Common.Library hiding (ready) -import Ideas.Service.BasicServices hiding (apply) +import Ideas.Service.BasicServices import Ideas.Service.State import Ideas.Service.Types import qualified Ideas.Common.Rewriting.Difference as Diff diff --git a/src/Ideas/Service/ServiceList.hs b/src/Ideas/Service/ServiceList.hs index 0cec976c..62b811ac 100644 --- a/src/Ideas/Service/ServiceList.hs +++ b/src/Ideas/Service/ServiceList.hs @@ -22,6 +22,7 @@ import Ideas.Service.State import Ideas.Service.Types import Ideas.Utils.TestSuite hiding (Message) import qualified Ideas.Service.Diagnose as Diagnose +import qualified Ideas.Service.Apply as Apply import qualified Ideas.Service.ProblemDecomposition as ProblemDecomposition import qualified Ideas.Service.Submit as Submit @@ -138,7 +139,7 @@ applyS = makeService "basic.apply" "Apply a rule at a certain location to the current expression. If this rule \ \was not expected by the strategy, we deviate from it. If the rule cannot \ \be applied, this service call results in an error." $ - apply ::: tRule .-> tLocation .-> tEnvironment .-> tState .-> tError tState + Apply.apply ::: tRule .-> tLocation .-> tEnvironment .-> tState .-> tError tState generateS :: Service generateS = makeService "basic.generate" From 929471b92e2fc19c99711d2b5ed685f34fe55bd2 Mon Sep 17 00:00:00 2001 From: Bastiaan Heeren Date: Mon, 16 Aug 2021 11:06:19 +0200 Subject: [PATCH 09/57] ApplyResult encoder More informative result type for apply feedback service --- src/Ideas/Encoding/EncoderJSON.hs | 26 ++++++-- src/Ideas/Encoding/NewDecoderJSON.hs | 8 +-- src/Ideas/Encoding/NewEncoderJSON.hs | 23 ++++++- src/Ideas/Service/Apply.hs | 89 ++++++++++++++++++++-------- src/Ideas/Service/ServiceList.hs | 2 +- 5 files changed, 110 insertions(+), 38 deletions(-) diff --git a/src/Ideas/Encoding/EncoderJSON.hs b/src/Ideas/Encoding/EncoderJSON.hs index 1ea5c2ce..a13c52ab 100644 --- a/src/Ideas/Encoding/EncoderJSON.hs +++ b/src/Ideas/Encoding/EncoderJSON.hs @@ -26,6 +26,7 @@ import Ideas.Service.Types hiding (String) import Ideas.Text.JSON import Ideas.Utils.Prelude (distinct) import qualified Ideas.Service.Diagnose as Diagnose +import qualified Ideas.Service.Apply as Apply import qualified Ideas.Service.Submit as Submit import qualified Ideas.Service.Types as Tp @@ -47,12 +48,13 @@ jsonEncoder tv@(val ::: tp) = List (Const Rule) -> return $ Array $ map ruleShortInfo val Tp.Tag s t - | s == "Result" -> encodeTyped encodeResult Submit.tResult tv - | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis tv - | s == "Derivation" -> ((encodeDerivation, tDerivation tStepInfo tContext) - encodeTyped encodeDerivationText (tDerivation tString tContext)) tv - | s == "first" -> encodeTyped encodeFirst (tPair tStepInfo tState) (val ::: t) - | s == "elem" -> jsonEncoder (val ::: t) + | s == "Result" -> encodeTyped encodeResult Submit.tResult tv + | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis tv + | s == "ApplyResult" -> encodeTyped encodeApplyResult Apply.tApplyResult tv + | s == "Derivation" -> ((encodeDerivation, tDerivation tStepInfo tContext) + encodeTyped encodeDerivationText (tDerivation tString tContext)) tv + | s == "first" -> encodeTyped encodeFirst (tPair tStepInfo tState) (val ::: t) + | s == "elem" -> jsonEncoder (val ::: t) | s `elem` ["step", "accept", "message"] -> jsonEncoder (val ::: t) | otherwise -> (\b -> Object [(s, b)]) <$> jsonEncoder (val ::: t) Tp.Unit -> return Null @@ -205,6 +207,18 @@ encodeDiagnosis diagnosis = fromState st = jsonEncoder (st ::: tState) fromReason s = return (Object [("reason", toJSON s)]) +-- legacy encoder +encodeApplyResult :: Apply.ApplyResult a -> JSONEncoder a +encodeApplyResult result = + jsonEncoder (f result ::: tError tState) + where + f :: Apply.ApplyResult a -> Either String (State a) + f (Apply.SyntaxError msg) = Left $ "Syntax error: " ++ msg + f (Apply.Correct _ st) = Right st + f (Apply.Buggy _ r) = Left $ "Buggy rule: " ++ show r + f Apply.Incorrect = Left $ "Cannot apply rule" + + jsonTuple :: [JSON] -> JSON jsonTuple xs = case catMaybes <$> mapM f xs of diff --git a/src/Ideas/Encoding/NewDecoderJSON.hs b/src/Ideas/Encoding/NewDecoderJSON.hs index d0bdd4dd..949d84e5 100644 --- a/src/Ideas/Encoding/NewDecoderJSON.hs +++ b/src/Ideas/Encoding/NewDecoderJSON.hs @@ -17,16 +17,14 @@ module Ideas.Encoding.NewDecoderJSON ( JSONDecoder, jsonDecoder ) where -import Control.Monad.State (mplus, foldM, get, gets, put) +import Control.Monad.State (mplus, foldM, get, put) import Data.Char -import Data.Maybe import Ideas.Common.Library hiding (exerciseId, symbol) import Ideas.Common.Traversal.Navigator import Ideas.Encoding.Encoder import Ideas.Service.State import Ideas.Service.Types hiding (String) import Ideas.Text.JSON -import Ideas.Utils.Decoding (symbol) import qualified Ideas.Service.Types as Tp type JSONDecoder a t = DecoderX a JSON t @@ -172,8 +170,8 @@ decodeState = do } searchId :: String -> JSON -> Maybe String -searchId s json = - case lookupM s json of +searchId str json = + case lookupM str json of Just (String s) -> Just s _ -> Nothing diff --git a/src/Ideas/Encoding/NewEncoderJSON.hs b/src/Ideas/Encoding/NewEncoderJSON.hs index 4465f579..c72b0c5a 100644 --- a/src/Ideas/Encoding/NewEncoderJSON.hs +++ b/src/Ideas/Encoding/NewEncoderJSON.hs @@ -21,6 +21,7 @@ import Ideas.Encoding.Encoder import Ideas.Service.State import Ideas.Service.Types hiding (String) import Ideas.Text.JSON +import qualified Ideas.Service.Apply as Apply import qualified Ideas.Service.Diagnose as Diagnose import qualified Ideas.Service.Types as Tp @@ -57,8 +58,9 @@ jsonEncoder tv@(val ::: tp) = Pair t1 t2 -> (++) <$> jsonEncoder (fst val ::: t1) <*> jsonEncoder (snd val ::: t2) Tp.List t -> listJSONBuilder <$> sequence [ jsonEncoder (x ::: t) | x <- val ] Tp.Tag s t - | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis tv - | otherwise -> tagJSONBuilder (map toLower s) <$> jsonEncoder (val ::: t) + | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis tv + | s == "ApplyResult" -> encodeTyped encodeApplyResult Apply.tApplyResult tv + | otherwise -> tagJSONBuilder (map toLower s) <$> jsonEncoder (val ::: t) Tp.Unit -> pure [] Const ctp -> jsonEncodeConst (val ::: ctp) _ -> fail $ "Cannot encode type: " ++ show tp @@ -151,6 +153,23 @@ encodeDiagnosis diagnosis = mkRule = mkMaybeRule . Just mkMaybeRule mr = return [(Just "rule", maybe Null (toJSON . showId) mr)] +encodeApplyResult :: Apply.ApplyResult a -> EncoderX a JSONBuilder +encodeApplyResult result = + case result of + Apply.Correct b st -> + (\xs ys -> (Just "diagnosetype", toJSON "correct") : xs ++ ys) <$> mkReady b <*> encodeState st + Apply.SyntaxError msg -> + pure [(Just "diagnosetype", toJSON "syntaxerror"), (Just "message", toJSON msg)] + Apply.Buggy env r -> + (\xs ys -> (Just "diagnosetype", toJSON "buggy") : xs ++ ys) <$> encodeEnvironment env <*> mkRule r + Apply.Incorrect -> + pure [(Just "diagnosetype", toJSON "incorrect")] + + where + mkReady b = return [(Just "ready", toJSON b)] + mkRule = mkMaybeRule . Just + mkMaybeRule mr = return [(Just "rule", maybe Null (toJSON . showId) mr)] + exerciseInfo :: Exercise a -> JSONBuilder exerciseInfo ex = tagJSON "exercise" $ Object [ ("exerciseid", toJSON (showId ex)) diff --git a/src/Ideas/Service/Apply.hs b/src/Ideas/Service/Apply.hs index f78773c1..c94d11c7 100644 --- a/src/Ideas/Service/Apply.hs +++ b/src/Ideas/Service/Apply.hs @@ -11,57 +11,98 @@ ----------------------------------------------------------------------------- module Ideas.Service.Apply - ( apply + ( ApplyResult(..), tApplyResult, apply ) where +import Data.Either import Data.List -import Data.Maybe import Ideas.Common.Library hiding (apply) import Ideas.Service.State import Ideas.Service.BasicServices (allfirsts) +import Ideas.Service.Types import qualified Data.Set as S +---------------------------------------------------------------- +-- Result types for apply service + +data ApplyResult a + = SyntaxError String + | Correct Bool (State a) + | Buggy Environment (Rule (Context a)) + | Incorrect + +instance Show (ApplyResult a) where + show (SyntaxError _) = "SyntaxError" + show (Correct _ _) = "Correct" + show (Buggy _ r) = "Buggy(" ++ show r ++ ")" + show Incorrect = "Incorrect" + +---------------------------------------------------------------- +-- The apply feedback service + -- Two possible scenarios: either I have a prefix and I can return a new one (i.e., still following the -- strategy), or I return a new term without a prefix. A final scenario is that the rule cannot be applied -- to the current term at the given location, in which case the request is invalid. -apply :: Rule (Context a) -> Location -> Environment -> State a -> Either String (State a) -apply r loc env state - | withoutPrefix state = applyOff - | otherwise = applyOn +apply :: Rule (Context a) -> Location -> Environment -> State a -> ApplyResult a +apply r loc env st + | withoutPrefix st = applyOff + | otherwise = applyOn where applyOn = -- scenario 1: on-strategy - maybe applyOff Right $ listToMaybe - [ s1 | xs <- either (const []) return (allfirsts state), ((r1, loc1, env1), s1) <- xs, r == r1, loc == loc1, noBindings env || env == env1 ] + case [ new | (stepInfo, new) <- fromRight [] (allfirsts st), testStep stepInfo ] of + [] -> applyOff + new:_ -> correct new - ca = setLocation loc (stateContext state) applyOff = -- scenario 2: off-strategy case transApplyWith env (transformation r) ca of - (new, _):_ -> Right (restart (state {stateContext = new, statePrefix = noPrefix})) + (new, _):_ -> correct (restart (st {stateContext = new, statePrefix = noPrefix})) [] -> -- first check the environment (exercise-specific property) - case environmentCheck of + case environmentCheck st env of Just msg -> - Left msg + SyntaxError msg Nothing -> -- try to find a buggy rule - case siblingsFirst [ (br, envOut) | br <- ruleset (exercise state), isBuggy br, (_, envOut) <- transApplyWith env (transformation br) ca ] of - [] -> Left ("Cannot apply " ++ show r) - brs -> Left ("Buggy rule " ++ intercalate "+" (map pp brs)) - where - pp (br, envOut) - | noBindings envOut = show br - | otherwise = show br ++ " {" ++ show envOut ++ "}" + case siblingsFirst [ (envOut, br) | br <- ruleset (exercise st), isBuggy br, (_, envOut) <- transApplyWith env (transformation br) ca ] of + [] -> Incorrect + (envOut, br):_ -> Buggy envOut br + + ca = setLocation loc (stateContext st) siblingsFirst xs = ys ++ zs where - (ys, zs) = partition (siblingInCommon r . fst) xs + (ys, zs) = partition (siblingInCommon r . snd) xs + + testStep (r1, loc1, env1) = + r == r1 && loc == loc1 && (noBindings env || env == env1) - environmentCheck :: Maybe String - environmentCheck = do - p <- getProperty "environment-check" (exercise state) - p env +environmentCheck :: State a -> Environment -> Maybe String +environmentCheck st env = do + p <- getProperty "environment-check" (exercise st) + p env + +correct :: State a -> ApplyResult a +correct st = Correct (finished st) st siblingInCommon :: Rule a -> Rule a -> Bool siblingInCommon r1 r2 = not (S.null (getSiblings r1 `S.intersection` getSiblings r2)) where getSiblings r = S.fromList (getId r : ruleSiblings r) + +---------------------------------------------------------------- +-- Helpers + +tApplyResult :: Type a (ApplyResult a) +tApplyResult = Tag "ApplyResult" $ Iso (f <-> g) tp + where + tp = tString :|: tPair tBool tState :|: tPair tEnvironment tRule :|: tUnit + + f (Left msg) = SyntaxError msg + f (Right (Left (b, st))) = Correct b st + f (Right (Right (Left (env, r)))) = Buggy env r + f (Right (Right (Right ()))) = Incorrect + + g (SyntaxError msg) = Left msg + g (Correct b st) = Right (Left (b, st)) + g (Buggy env r) = Right (Right (Left (env, r))) + g Incorrect = Right (Right (Right ())) diff --git a/src/Ideas/Service/ServiceList.hs b/src/Ideas/Service/ServiceList.hs index 62b811ac..bb539db5 100644 --- a/src/Ideas/Service/ServiceList.hs +++ b/src/Ideas/Service/ServiceList.hs @@ -139,7 +139,7 @@ applyS = makeService "basic.apply" "Apply a rule at a certain location to the current expression. If this rule \ \was not expected by the strategy, we deviate from it. If the rule cannot \ \be applied, this service call results in an error." $ - Apply.apply ::: tRule .-> tLocation .-> tEnvironment .-> tState .-> tError tState + Apply.apply ::: tRule .-> tLocation .-> tEnvironment .-> tState .-> Apply.tApplyResult generateS :: Service generateS = makeService "basic.generate" From 0754bd5b1b259acc2c72f724af874324b3cbbef8 Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 17 Aug 2021 09:21:12 +0200 Subject: [PATCH 10/57] Update NewDecoderJSON.hs Making decodeValue more flexible in choosing between parser and json decoder --- src/Ideas/Encoding/NewDecoderJSON.hs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Ideas/Encoding/NewDecoderJSON.hs b/src/Ideas/Encoding/NewDecoderJSON.hs index 949d84e5..d9707d40 100644 --- a/src/Ideas/Encoding/NewDecoderJSON.hs +++ b/src/Ideas/Encoding/NewDecoderJSON.hs @@ -205,9 +205,18 @@ decodeValue :: JSONDecoder a a decodeValue = do this <- get ex <- getExercise - case (lookupM "term" this, hasJSONView ex) of - (Just json, Just jv) -> matchM jv json - (Just (String s), _) -> either fail return (parser ex s) + case lookupM "term" this of + Just json@(String s) -> + case parser ex s of + Left msg -> + case hasJSONView ex of + Just jv -> matchM jv json + Nothing -> fail msg + Right a -> return a + Just json -> + case hasJSONView ex of + Just jv -> matchM jv json + Nothing -> fail "No JSON decoder for term" _ -> fail "Expecting term" decodeEnvironment :: JSONDecoder a Environment From b2ec479379ca7bff22058a3337318f6e1ca563a5 Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 17 Aug 2021 10:46:51 +0200 Subject: [PATCH 11/57] "create" feedback service Create feedback service should work on a term (in context), not a string. This makes it possible to pass a JSON object for the start state. --- src/Ideas/Service/BasicServices.hs | 14 +++++++------- src/Ideas/Service/ServiceList.hs | 2 +- src/Ideas/Service/State.hs | 11 +++++++---- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/Ideas/Service/BasicServices.hs b/src/Ideas/Service/BasicServices.hs index ddd367e4..79c87638 100644 --- a/src/Ideas/Service/BasicServices.hs +++ b/src/Ideas/Service/BasicServices.hs @@ -35,14 +35,14 @@ generate rng ex md userId = Just a -> Right $ startState rng ex userId a Nothing -> Left "No random term" -create :: QCGen -> Exercise a -> String -> Maybe String -> Either String (State a) -create rng ex txt userId = - case parser ex txt of - Left err -> Left err - Right a - | evalPredicate (Library.ready ex) a -> Left "Is ready" - | evalPredicate (Library.suitable ex) a -> Right $ startState rng ex userId a +create :: QCGen -> Exercise a -> Context a -> Maybe String -> Either String (State a) +create rng ex ctx userId = + case fromContext ctx of + Just a + | evalPredicate (Library.ready ex) a -> Left "Is ready" + | evalPredicate (Library.suitable ex) a -> Right $ startStateContext rng ex userId ctx | otherwise -> Left "Not suitable" + Nothing -> Left "Invalid value" -- TODO: add a location to each step solution :: Maybe StrategyCfg -> State a -> Either String (Derivation (StepInfo a) (Context a)) diff --git a/src/Ideas/Service/ServiceList.hs b/src/Ideas/Service/ServiceList.hs index bb539db5..866abcb8 100644 --- a/src/Ideas/Service/ServiceList.hs +++ b/src/Ideas/Service/ServiceList.hs @@ -151,7 +151,7 @@ createS :: Service createS = makeService "basic.create" "Given an expression, this service \ \returns an initial state with the original given expression." $ - create ::: tQCGen .-> tExercise .-> Tag "term" tString .-> tMaybe tUserId .-> tError tState + create ::: tQCGen .-> tExercise .-> tContext .-> tMaybe tUserId .-> tError tState examplesS :: Service examplesS = makeService "basic.examples" diff --git a/src/Ideas/Service/State.hs b/src/Ideas/Service/State.hs index df510150..b6dca538 100644 --- a/src/Ideas/Service/State.hs +++ b/src/Ideas/Service/State.hs @@ -16,7 +16,7 @@ module Ideas.Service.State ( -- * Exercise state - State, startState, makeState, makeNoState, emptyStateContext, emptyState + State, startState, startStateContext, makeState, makeNoState, emptyStateContext, emptyState , exercise, statePrefix, stateContext, stateTerm , stateUser, stateSession, stateStartTerm, restart , withoutPrefix, stateLabels, suitable, finished, firsts, microsteps @@ -97,13 +97,16 @@ emptyState :: Exercise a -> a -> State a emptyState ex = emptyStateContext ex . inContext ex startState :: QCGen -> Exercise a -> Maybe String -> a -> State a -startState gen ex userId a = st +startState gen ex userId = startStateContext gen ex userId . inContext ex + +startStateContext :: QCGen -> Exercise a -> Maybe String -> Context a -> State a +startStateContext gen ex userId ctx = st { stateUser = userId , stateSession = Just sid - , stateStartTerm = Just (prettyPrinter ex a) + , stateStartTerm = fmap (prettyPrinter ex) (fromContext ctx) } where - st = emptyStateContext ex (inContext ex a) + st = emptyStateContext ex ctx sid = newSessionId gen -- Restart the strategy: make sure that the new state has a prefix From f681d18ddbca787a0df37afe5f2e8053587064a8 Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 17 Aug 2021 12:46:09 +0200 Subject: [PATCH 12/57] Update EncoderHTML.hs Fixing html encoder for derivations --- src/Ideas/Encoding/EncoderHTML.hs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Ideas/Encoding/EncoderHTML.hs b/src/Ideas/Encoding/EncoderHTML.hs index 2eb9b7bb..29821434 100644 --- a/src/Ideas/Encoding/EncoderHTML.hs +++ b/src/Ideas/Encoding/EncoderHTML.hs @@ -118,8 +118,8 @@ encodeType dr = (exerciseHeader . encodeExampleList, tList (tPair tDifficulty tContext)) (exerciseHeader . htmlFirsts, tList (tPair tStepInfo tState)) (exerciseHeader . htmlAllApplications, tList (tTuple3 tRule tLocation tState)) - (exerciseHeader . encodeDerivation, tDerivation (tPair tRule tEnvironment) tContext) - (exerciseHeader . encodeDerivationList, tList (tDerivation (tPair tRule tEnvironment) tContext)) + (exerciseHeader . encodeDerivation, tDerivation tStepInfo tContext) + (exerciseHeader . encodeDerivationList, tList (tDerivation tStepInfo tContext)) \(val ::: tp) -> case tp of Iso iso t -> encodeType dr (to iso val ::: t) @@ -456,11 +456,11 @@ encodeExampleList pairs = withExercise $ \ex -> do let st = emptyStateContext ex x in button (escapeInURL (urlForState lm st)) (htmlContext False ex x) -encodeDerivation :: Derivation (Rule (Context a), Environment) (Context a) -> HTMLEncoder a +encodeDerivation :: Derivation (StepInfo a) (Context a) -> HTMLEncoder a encodeDerivation d = h2 "Derivation" <> htmlDerivation d -encodeDerivationList :: [Derivation (Rule (Context a), Environment) (Context a)] -> HTMLEncoder a +encodeDerivationList :: [Derivation (StepInfo a) (Context a)] -> HTMLEncoder a encodeDerivationList ds = h2 "Derivations" <> mconcat @@ -468,7 +468,7 @@ encodeDerivationList ds = | (i, d) <- zip [1::Int ..] ds ] -htmlDerivation :: Derivation (Rule (Context a), Environment) (Context a) -> HTMLEncoder a +htmlDerivation :: Derivation (StepInfo a) (Context a) -> HTMLEncoder a htmlDerivation d = withExercise $ \ex -> do lm <- getLinkManager let before = @@ -476,7 +476,7 @@ htmlDerivation d = withExercise $ \ex -> do <> case fmap (isReady ex) (fromContext (lastTerm d)) of Just True -> mempty _ -> spanClass "error" (string "Final term is not finished") - forStep ((r, env1), env2) = + forStep ((r, _, env1), env2) = let showEnv e = munless (noBindings e) $ string $ "," ++ show e in container $ marginPos CenterLeft $ mconcat [ string [chr 8658, ' '] From 85ff4dba12218bbcc3ceae37627be3327f149cee Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 17 Aug 2021 13:17:34 +0200 Subject: [PATCH 13/57] fixes in html encoder --- src/Ideas/Encoding/EncoderHTML.hs | 6 +++--- src/Ideas/Service/ServiceList.hs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Ideas/Encoding/EncoderHTML.hs b/src/Ideas/Encoding/EncoderHTML.hs index 29821434..f09af575 100644 --- a/src/Ideas/Encoding/EncoderHTML.hs +++ b/src/Ideas/Encoding/EncoderHTML.hs @@ -116,7 +116,7 @@ encodeType dr = (encodeIndex, tDomainReasoner) (exerciseHeader . htmlDiagnosis dr, tDiagnosis) (exerciseHeader . encodeExampleList, tList (tPair tDifficulty tContext)) - (exerciseHeader . htmlFirsts, tList (tPair tStepInfo tState)) + (exerciseHeader . htmlFirsts, tList (Tag "first" (tPair tStepInfo tState))) (exerciseHeader . htmlAllApplications, tList (tTuple3 tRule tLocation tState)) (exerciseHeader . encodeDerivation, tDerivation tStepInfo tContext) (exerciseHeader . encodeDerivationList, tList (tDerivation tStepInfo tContext)) @@ -520,7 +520,7 @@ encodeState dr state = do in return (mconcat [ h2 "Feedback" , submitDiagnose lm state - , tag "p" $ padding Small $ mconcat [ case xs of + , tag "p" $ padding Small $ spaced [ case xs of Right (hd:_) -> linkToState lm (snd hd) $ serviceButton $ string "onefirst" _ -> string "(no onefirst)" , linkToFirsts lm state $ serviceButton $ string $ "allfirsts (" ++ show n ++ ")" @@ -545,7 +545,7 @@ useAllFirstsIO dr st = do srv <- findService dr (newId ("allfirsts" :: String)) case serviceFunction srv of f ::: tp -> do - conv <- equalM tp (tState .-> tError (tList (tPair tStepInfo tState))) + conv <- equalM tp (tState .-> tError (tList (Tag "first" (tPair tStepInfo tState)))) return (conv f st) encodePrefix :: State a -> Prefix (Context a) -> HTMLBuilder diff --git a/src/Ideas/Service/ServiceList.hs b/src/Ideas/Service/ServiceList.hs index 866abcb8..a0fb037f 100644 --- a/src/Ideas/Service/ServiceList.hs +++ b/src/Ideas/Service/ServiceList.hs @@ -319,7 +319,7 @@ stateinfoS = makeService "meta.stateinfo" microstepsS :: Service microstepsS = makeService "meta.microsteps" "Next (minor) steps." $ - (map f . microsteps) ::: tState .-> tList (tPair (tTuple3 tRule tLocation tEnvironment) tState) + (map f . microsteps) ::: tState .-> tList (Tag "first" (tPair tStepInfo tState)) where f ((s, ctx, env), st) = ((s, location ctx, env), st) From cc8613b0c73f1e1d9f542e1552e8307d3c3f5983 Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 18 Aug 2021 09:36:21 +0200 Subject: [PATCH 14/57] Adding split functions to Utils.Prelude --- src/Ideas/Utils/Prelude.hs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/Ideas/Utils/Prelude.hs b/src/Ideas/Utils/Prelude.hs index aedb2f32..6a808dbc 100644 --- a/src/Ideas/Utils/Prelude.hs +++ b/src/Ideas/Utils/Prelude.hs @@ -18,6 +18,7 @@ module Ideas.Utils.Prelude , subsets, isSubsetOf , cartesian, distinct, allsame , fixpoint + , split, split3, split4 , splitAtElem, splitsWithElem , timedSeconds, getDiffTime , fst3, snd3, thd3 @@ -81,6 +82,24 @@ fixpoint f = rec . iterate f | x == head xs = x | otherwise = rec xs +split :: [a] -> [([a], [a])] +split xs = map (`splitAt` xs) [0 .. length xs] + +split3 :: [a] -> [([a], [a], [a])] +split3 as = + [ (xs, ys1, ys2) + | (xs, ys) <- split as + , (ys1, ys2) <- split ys + ] + +split4 :: [a] -> [([a], [a], [a], [a])] +split4 as = + [ (xs1, xs2, ys1, ys2) + | (xs, ys) <- split as + , (xs1, xs2) <- split xs + , (ys1, ys2) <- split ys + ] + splitAtElem :: Eq a => a -> [a] -> Maybe ([a], [a]) splitAtElem c s = case break (==c) s of From 8789d68473f03497e58d741363088d5dbcf5d6c1 Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 18 Aug 2021 09:36:37 +0200 Subject: [PATCH 15/57] Adding subConstraints helper --- src/Ideas/Common/Constraint.hs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/Ideas/Common/Constraint.hs b/src/Ideas/Common/Constraint.hs index c81703d5..e6ee037b 100644 --- a/src/Ideas/Common/Constraint.hs +++ b/src/Ideas/Common/Constraint.hs @@ -16,10 +16,12 @@ module Ideas.Common.Constraint ( Constraint, makeConstraint , isRelevant, isSatisfied, isViolated, getResult , Result(..), relevance + , subConstraints ) where import Control.Applicative import Control.Monad +import Data.List import Ideas.Common.Id import Ideas.Common.View @@ -111,4 +113,21 @@ instance MonadPlus Result where -- | Turn errors into irrelevant results relevance :: Result a -> Result a relevance (Error _) = Irrelevant -relevance r = r \ No newline at end of file +relevance r = r + +-- to do: +-- * alle errors teruggeven +-- * locatie van error bijhouden +subConstraints :: IsId n => (b -> [(String, a)]) -> n -> Constraint a -> Constraint b +subConstraints f n c = makeConstraint n $ \p -> do + let results = [ (loc, getResult c a) | (loc, a) <- f p ] + case filter isError results of + [] | any isOk results -> Ok () + | otherwise -> Irrelevant + errs -> Error $ intercalate "," [ showId c ++ "." ++ loc ++ ":" ++ msg | (loc, Error msg) <- errs ] + where + isError (_, Error _) = True + isError _ = False + + isOk (_, Ok _) = True + isOk _ = False From c4adf755a54d050b3b3a9f0ae3200b2d05a1be9f Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 18 Aug 2021 09:36:54 +0200 Subject: [PATCH 16/57] Adding eqDerivationBy function --- src/Ideas/Common/Derivation.hs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Ideas/Common/Derivation.hs b/src/Ideas/Common/Derivation.hs index 0bc7fc2b..b249788f 100644 --- a/src/Ideas/Common/Derivation.hs +++ b/src/Ideas/Common/Derivation.hs @@ -21,6 +21,8 @@ module Ideas.Common.Derivation , merge, mergeBy, mergeStep -- * Conversion to/from list , derivationToList, derivationFromList + -- * Equality + , eqDerivationBy -- * Querying a derivation , isEmpty, derivationLength, terms, steps, triples , firstTerm, lastTerm, lastStep, withoutLast @@ -91,6 +93,13 @@ derivationFromList f g = rec rec [b] = emptyDerivation <$> g b rec (b1:b2:bs) = curry prepend <$> g b1 <*> f b2 <*> rec bs +----------------------------------------------------------------------------- +-- Equality + +eqDerivationBy :: Eq s => (a -> a -> Bool) -> Derivation s a -> Derivation s a -> Bool +eqDerivationBy f d1 d2 = + and (zipWith f (terms d1) (terms d2)) && steps d1 == steps d2 + ----------------------------------------------------------------------------- -- Querying a derivation From 1e334b1c4d639bd9084f9df9d937b2a312f6025c Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 18 Aug 2021 21:23:33 +0200 Subject: [PATCH 17/57] moving JSONBuilder to JSON library --- src/Ideas/Encoding/NewEncoderJSON.hs | 117 +++++++++++---------------- src/Ideas/Encoding/NewModeJSON.hs | 2 +- src/Ideas/Text/JSON.hs | 49 +++++++++++ src/Ideas/Utils/Decoding.hs | 2 - 4 files changed, 97 insertions(+), 73 deletions(-) diff --git a/src/Ideas/Encoding/NewEncoderJSON.hs b/src/Ideas/Encoding/NewEncoderJSON.hs index c72b0c5a..2bc71b06 100644 --- a/src/Ideas/Encoding/NewEncoderJSON.hs +++ b/src/Ideas/Encoding/NewEncoderJSON.hs @@ -13,7 +13,7 @@ -- ----------------------------------------------------------------------------- -module Ideas.Encoding.NewEncoderJSON (JSONBuilder, builderToJSON, jsonEncoder) where +module Ideas.Encoding.NewEncoderJSON (jsonEncoder) where import Data.Char import Ideas.Common.Library hiding (exerciseId) @@ -25,29 +25,8 @@ import qualified Ideas.Service.Apply as Apply import qualified Ideas.Service.Diagnose as Diagnose import qualified Ideas.Service.Types as Tp -type JSONBuilder = [(Maybe Key, JSON)] - -listJSONBuilder :: [JSONBuilder] -> JSONBuilder -listJSONBuilder xs = [(Nothing, Array (map builderToJSON xs))] - -builderToJSON :: JSONBuilder -> JSON -builderToJSON [(Nothing, x)] = x -builderToJSON xs = - case mapM fst xs of - Just ks -> Object (zip ks (map snd xs)) - Nothing -> Array (map f xs) - where - f (Nothing, a) = a - f (Just k, a) = Object [(k, a)] - -tagJSONBuilder :: String -> JSONBuilder -> JSONBuilder -tagJSONBuilder s = tagJSON (map toLower s) . builderToJSON - -tagJSON :: String -> JSON -> JSONBuilder -tagJSON s a = [(Just s, a)] - ------------------------------------------------------------- --- + jsonEncoder :: TypedValue (Type a) -> EncoderX a JSONBuilder jsonEncoder tv@(val ::: tp) = case tp of @@ -55,13 +34,13 @@ jsonEncoder tv@(val ::: tp) = t1 :|: t2 -> case val of Left x -> jsonEncoder (x ::: t1) Right y -> jsonEncoder (y ::: t2) - Pair t1 t2 -> (++) <$> jsonEncoder (fst val ::: t1) <*> jsonEncoder (snd val ::: t2) - Tp.List t -> listJSONBuilder <$> sequence [ jsonEncoder (x ::: t) | x <- val ] + Pair t1 t2 -> (<>) <$> jsonEncoder (fst val ::: t1) <*> jsonEncoder (snd val ::: t2) + Tp.List t -> arrayBuilder <$> sequence [ jsonEncoder (x ::: t) | x <- val ] Tp.Tag s t | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis tv | s == "ApplyResult" -> encodeTyped encodeApplyResult Apply.tApplyResult tv - | otherwise -> tagJSONBuilder (map toLower s) <$> jsonEncoder (val ::: t) - Tp.Unit -> pure [] + | otherwise -> tagJSON (map toLower s) <$> jsonEncoder (val ::: t) + Tp.Unit -> pure mempty Const ctp -> jsonEncodeConst (val ::: ctp) _ -> fail $ "Cannot encode type: " ++ show tp @@ -75,31 +54,31 @@ jsonEncodeConst (val ::: tp) = State -> encodeState val SomeExercise -> case val of Some ex -> pure (exerciseInfo ex) - Text -> pure [(Nothing, toJSON (show val))] - Tp.String -> pure [(Nothing, toJSON val)] - Tp.Int -> pure [(Nothing, toJSON val)] - Tp.Bool -> pure [(Nothing, toJSON val)] + Text -> pure $ builder (show val) + Tp.String -> pure $ builder val + Tp.Int -> pure $ builder val + Tp.Bool -> pure $ builder val _ -> fail $ "Type " ++ show tp ++ " not supported in JSON" encodeRule :: Rule (Context a) -> EncoderX a JSONBuilder -encodeRule r = pure (tagJSON "rule" (toJSON (showId r))) +encodeRule r = pure $ "rule" .= showId r encodeEnvironment :: Environment -> EncoderX a JSONBuilder encodeEnvironment env = let f a = (showId a, String (showValue a)) - in pure $ tagJSON "environment" $ Object [ f a | a <- bindings env ] + in pure $ "environment" .= Object [ f a | a <- bindings env ] encodeContext :: Context a -> EncoderX a JSONBuilder encodeContext ctx = let encValue = case fromContext ctx of Just a -> encodeTerm a - Nothing -> pure $ tagJSON "term" Null -- todo: merge with encodeTerm + Nothing -> pure $ "term" .= Null -- todo: merge with encodeTerm encEnv = encodeEnvironment (environment ctx) encLoc = encodeLocation (location ctx) - in (\xs ys zs -> tagJSONBuilder "context" $ xs ++ ys ++ zs) <$> encValue <*> encEnv <*> encLoc + in (\xs ys zs -> "context" .= (xs <> ys <> zs)) <$> encValue <*> encEnv <*> encLoc encodeTerm :: a -> EncoderX a JSONBuilder -encodeTerm a = (tagJSON "term" . f) <$> getExercise +encodeTerm a = tagJSON "term" . f <$> getExercise where f ex = case hasJSONView ex of @@ -107,72 +86,70 @@ encodeTerm a = (tagJSON "term" . f) <$> getExercise Nothing -> String (prettyPrinter ex a) encodeLocation :: Location -> EncoderX a JSONBuilder -encodeLocation loc = pure (tagJSON "location" (toJSON (fromLocation loc))) +encodeLocation loc = pure $ "location" .= fromLocation loc encodeState :: State a -> EncoderX a JSONBuilder encodeState st = let ctx = stateContext st get f = maybe Null String (f st) - make ppCtx = - [ (Just "exerciseid", String $ showId (exercise st)) - , (Just "prefix", if withoutPrefix st - then Null - else String (show (statePrefix st)) - ) - ] ++ - ppCtx ++ - [ (Just "userid", get stateUser) - , (Just "sessionid", get stateSession) - , (Just "taskid", get stateStartTerm) + make ppCtx = mconcat + [ "exerciseid" .= showId (exercise st) + , "prefix" .= if withoutPrefix st + then Null + else String (show (statePrefix st)) + , ppCtx + , "userid" .= get stateUser + , "sessionid" .= get stateSession + , "taskid" .= get stateStartTerm ] - in (tagJSONBuilder "state" . make) <$> (encodeContext ctx) + in (tagJSON "state" . make) <$> (encodeContext ctx) encodeDiagnosis :: Diagnose.Diagnosis a -> EncoderX a JSONBuilder encodeDiagnosis diagnosis = case diagnosis of Diagnose.Correct b st -> - (\xs ys -> (Just "diagnosetype", toJSON "correct") : xs ++ ys) <$> mkReady b <*> encodeState st + (\xs ys -> "diagnosetype" .= "correct" <> xs <> ys) <$> mkReady b <*> encodeState st Diagnose.Similar b st mr -> - (\xs ys zs -> (Just "diagnosetype", toJSON "similar") : xs ++ ys ++ zs) <$> mkReady b <*> encodeState st <*> mkMaybeRule mr + (\xs ys zs -> "diagnosetype" .= "similar" <> xs <> ys <> zs) <$> mkReady b <*> encodeState st <*> mkMaybeRule mr Diagnose.NotEquivalent s -> - return [(Just "diagnosetype", toJSON "notequiv"), (Just "message", toJSON s)] + pure $ "diagnosetype" .= "notequiv" <> "message" .= s Diagnose.Expected b st r -> - (\xs ys zs -> (Just "diagnosetype", toJSON "expected") : xs ++ ys ++ zs) <$> mkReady b <*> encodeState st <*> mkRule r + (\xs ys zs -> "diagnosetype" .= "expected" <> xs <> ys <> zs) <$> mkReady b <*> encodeState st <*> mkRule r Diagnose.Buggy env r -> - (\xs ys -> (Just "diagnosetype", toJSON "buggy") : xs ++ ys) <$> encodeEnvironment env <*> mkRule r + (\xs ys -> "diagnosetype" .= "buggy" <> xs <> ys) <$> encodeEnvironment env <*> mkRule r Diagnose.Detour b st env r -> - (\xs ys zs vs -> (Just "diagnosetype", toJSON "detour") : xs ++ ys ++ zs ++ vs) <$> mkReady b <*> encodeState st <*> encodeEnvironment env <*> mkRule r + (\xs ys zs vs -> "diagnosetype" .= "detour" <> xs <> ys <> zs <> vs) <$> mkReady b <*> encodeState st <*> encodeEnvironment env <*> mkRule r Diagnose.WrongRule b st mr -> - (\xs ys zs -> (Just "diagnosetype", toJSON "wrongrule") : xs ++ ys ++ zs) <$> mkReady b <*> encodeState st <*> mkMaybeRule mr + (\xs ys zs -> "diagnosetype" .= "wrongrule" <> xs <> ys <> zs) <$> mkReady b <*> encodeState st <*> mkMaybeRule mr Diagnose.SyntaxError msg -> - pure [(Just "diagnosetype", toJSON "syntaxerror"), (Just "message", toJSON msg)] + pure $ "diagnosetype" .= "syntaxerror" <> "message" .= msg Diagnose.Unknown b st -> - (\xs ys -> (Just "diagnosetype", toJSON "unknown") : xs ++ ys) <$> mkReady b <*> encodeState st + (\xs ys -> "diagnosetype" .= "unknown" <> xs <> ys) <$> mkReady b <*> encodeState st where - mkReady b = return [(Just "ready", toJSON b)] + mkReady b = pure $ "ready" .= b mkRule = mkMaybeRule . Just - mkMaybeRule mr = return [(Just "rule", maybe Null (toJSON . showId) mr)] + mkMaybeRule mr = pure $ "rule" .= maybe Null (toJSON . showId) mr encodeApplyResult :: Apply.ApplyResult a -> EncoderX a JSONBuilder encodeApplyResult result = case result of Apply.Correct b st -> - (\xs ys -> (Just "diagnosetype", toJSON "correct") : xs ++ ys) <$> mkReady b <*> encodeState st + (\xs ys -> "diagnosetype" .= "correct" <> xs <> ys) <$> mkReady b <*> encodeState st Apply.SyntaxError msg -> - pure [(Just "diagnosetype", toJSON "syntaxerror"), (Just "message", toJSON msg)] + pure $ "diagnosetype" .= "syntaxerror" <> "message" .= msg Apply.Buggy env r -> - (\xs ys -> (Just "diagnosetype", toJSON "buggy") : xs ++ ys) <$> encodeEnvironment env <*> mkRule r + (\xs ys -> "diagnosetype" .= "buggy" <> xs <> ys) <$> encodeEnvironment env <*> mkRule r Apply.Incorrect -> - pure [(Just "diagnosetype", toJSON "incorrect")] + pure $ "diagnosetype" .= "incorrect" where - mkReady b = return [(Just "ready", toJSON b)] + mkReady b = pure $ "ready" .= b mkRule = mkMaybeRule . Just - mkMaybeRule mr = return [(Just "rule", maybe Null (toJSON . showId) mr)] + mkMaybeRule mr = pure $ "rule" .= maybe Null (toJSON . showId) mr exerciseInfo :: Exercise a -> JSONBuilder -exerciseInfo ex = tagJSON "exercise" $ Object - [ ("exerciseid", toJSON (showId ex)) - , ("description", toJSON (description ex)) - , ("status", toJSON (show (status ex))) +exerciseInfo ex = "exercise" .= mconcat + [ "exerciseid" .= showId ex + , "description" .= description ex + , "status" .= show (status ex) ] \ No newline at end of file diff --git a/src/Ideas/Encoding/NewModeJSON.hs b/src/Ideas/Encoding/NewModeJSON.hs index b1ded0e3..9c5a5d67 100644 --- a/src/Ideas/Encoding/NewModeJSON.hs +++ b/src/Ideas/Encoding/NewModeJSON.hs @@ -38,7 +38,7 @@ processJSON options dr txt = do if legacy then Legacy.processJSON' options dr json else do req <- jsonRequest options json resp <- jsonRPC2 dr (maybe "result" show $ serviceId req) json $ \fun arg -> - maybe id timedSeconds (maxTime options) (builderToJSON <$> myHandler options dr req fun arg) + maybe id timedSeconds (maxTime options) (toJSON <$> myHandler options dr req fun arg) --unless (responseError resp == Null) $ !!!!!!!!!!!!!! -- changeLog (logRef options) (\r -> r {errormsg = show (responseError resp)}) let f = if compactOutput req then compactJSON else show diff --git a/src/Ideas/Text/JSON.hs b/src/Ideas/Text/JSON.hs index 461522ad..a6bb10b0 100644 --- a/src/Ideas/Text/JSON.hs +++ b/src/Ideas/Text/JSON.hs @@ -19,6 +19,7 @@ module Ideas.Text.JSON , lookupM , parseJSON, compactJSON -- parser and pretty-printers , jsonRPC, RPCHandler, RPCRequest(..), RPCResponse(..) + , JSONBuilder, arrayBuilder, (.=), tagJSON, builder , propEncoding ) where @@ -26,6 +27,7 @@ import Control.Exception import Control.Monad import Data.List (intersperse) import Data.Maybe +import Data.String import Ideas.Utils.Parsing hiding (string, char) import System.IO.Error import Test.QuickCheck @@ -53,6 +55,9 @@ instance Show Number where instance Show JSON where show = show . prettyJSON False +instance IsString JSON where + fromString = String + compactJSON :: JSON -> String compactJSON = show . prettyJSON True @@ -151,6 +156,10 @@ instance (InJSON a, InJSON b, InJSON c, InJSON d) => InJSON (a, b, c, d) where fromJSON (Array [a, b, c, d]) = (,,,) <$> fromJSON a <*> fromJSON b <*> fromJSON c <*> fromJSON d fromJSON _ = fail "expecting an array with 4 elements" +instance InJSON JSON where + toJSON = id + fromJSON = return + -------------------------------------------------------- -- Parser @@ -260,6 +269,46 @@ jsonRPC input rpc = let msg = maybe (show e) ioeGetErrorString (fromException e) in return $ errorResponse (toJSON msg) (requestId req) +-------------------------------------------------------- +-- JSON builder + +newtype JSONBuilder = JB [(Maybe Key, JSON)] + +instance InJSON JSONBuilder where + toJSON = builderToJSON + fromJSON = return . builder + +instance Semigroup JSONBuilder where + JB xs <> JB ys = JB (xs <> ys) + +instance Monoid JSONBuilder where + mempty = JB [] + +arrayBuilder :: [JSONBuilder] -> JSONBuilder +arrayBuilder = builder . Array . map builderToJSON + +infix 7 .= + +(.=) :: InJSON a => String -> a -> JSONBuilder +s .= a = JB [(Just s, toJSON a)] + +tagJSON :: InJSON a => String -> a -> JSONBuilder +tagJSON = (.=) + +builder :: InJSON a => a -> JSONBuilder +builder a = JB [(Nothing, toJSON a)] + +-- local helper +builderToJSON :: JSONBuilder -> JSON +builderToJSON (JB [(Nothing, x)]) = x +builderToJSON (JB xs) = + case mapM fst xs of + Just ks -> Object (zip ks (map snd xs)) + Nothing -> Array (map f xs) + where + f (Nothing, a) = a + f (Just k, a) = Object [(k, a)] + -------------------------------------------------------- -- Testing parser/pretty-printer diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 5292a383..27458cea 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -9,8 +9,6 @@ -- Stability : provisional -- Portability : portable (depends on ghc) -- --- Extensions to the QuickCheck library --- ----------------------------------------------------------------------------- module Ideas.Utils.Decoding From 89869bbf8e29cdcaeb83560a1f0e2ac99b710c50 Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 23 Aug 2021 11:30:41 +0200 Subject: [PATCH 18/57] Using standard Except monad for decoding --- src/Ideas/Encoding/Encoder.hs | 10 ++--- src/Ideas/Encoding/Evaluator.hs | 25 +++++++----- src/Ideas/Encoding/LinkManager.hs | 4 +- src/Ideas/Text/JSON.hs | 25 +++++++++++- src/Ideas/Text/XML.hs | 10 ++--- src/Ideas/Utils/Decoding.hs | 63 +++++++++++-------------------- 6 files changed, 72 insertions(+), 65 deletions(-) diff --git a/src/Ideas/Encoding/Encoder.hs b/src/Ideas/Encoding/Encoder.hs index e6ab36d8..bd7dd53b 100644 --- a/src/Ideas/Encoding/Encoder.hs +++ b/src/Ideas/Encoding/Encoder.hs @@ -73,10 +73,10 @@ withOpenMath = (fmap useOpenMath getRequest >>=) withJSONTerm :: (Bool -> DecoderX a s t) -> DecoderX a s t withJSONTerm = (fmap useJSONTerm getRequest >>=) -(//) :: Decoder env s a -> s -> Decoder env s2 a +(//) :: Decoder env String s a -> s -> Decoder env String s2 a p // a = do env <- ask - runDecoder p env a + either throwError return (runDecoder p env a) ------------------------------------------------------------------- -- JSON terms @@ -165,7 +165,7 @@ latexEncodingWith = setPropertyF latexProperty . F ------------------------------------------------------------------- -- Encoder datatype -type EncoderX a = Encoder (Exercise a, Options) +type EncoderX a = Encoder (Exercise a, Options) String type TypedEncoder a b = TypedValue (Type a) -> EncoderX a b @@ -183,6 +183,6 @@ encodeTyped p t1 tv@(_ ::: t2) = ((p, t1) fail ("Types do not match: " ++ sh ------------------------------------------------------------------- -- Decoder datatype -type DecoderX a = Decoder (Exercise a, Options) +type DecoderX a = Decoder (Exercise a, Options) String -type TypedDecoder a s = forall t . Type a t -> Decoder (Exercise a, Options) s t \ No newline at end of file +type TypedDecoder a s = forall t . Type a t -> Decoder (Exercise a, Options) String s t \ No newline at end of file diff --git a/src/Ideas/Encoding/Evaluator.hs b/src/Ideas/Encoding/Evaluator.hs index fa9be6a0..49c6eb70 100644 --- a/src/Ideas/Encoding/Evaluator.hs +++ b/src/Ideas/Encoding/Evaluator.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE GADTs, RankNTypes #-} +{-# LANGUAGE GADTs, RankNTypes, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -46,10 +46,13 @@ evalService ex opts f srv b = do logType opts res tDiagnosis $ \d r -> r {serviceinfo = show d} return (evalResult res) -eval :: Exercise a -> Options -> Evaluator a b c -> b -> TypedValue (Type a) -> IO (EvalResult a c) +eval :: forall a b c. Exercise a -> Options -> Evaluator a b c -> b -> TypedValue (Type a) -> IO (EvalResult a c) eval ex opts (Evaluator dec enc) b = rec where - rec tv@(val ::: tp) = + env = (ex, opts) + + rec :: TypedValue (Type a) -> IO (EvalResult a c) + rec tv@(val ::: tp) = case tp of -- handle exceptions Const String :|: t -> @@ -57,14 +60,16 @@ eval ex opts (Evaluator dec enc) b = rec -- uncurry function if possible t1 :-> t2 :-> t3 -> rec (uncurry val ::: Pair t1 t2 :-> t3) - t1 :-> t2 -> do - a <- runDecoder (dec t1) (ex, opts) b - res <- rec (val a ::: t2) - return res { inputValues = (a ::: t1) : inputValues res } + -- functions + t1 :-> t2 -> + case runDecoder (dec t1) env b of + Left msg -> fail msg + Right a -> do + res <- rec (val a ::: t2) + return res { inputValues = (a ::: t1) : inputValues res } -- perform IO IO t -> do a <- val rec (a ::: t) - _ -> do - c <- runEncoder (enc tv) (ex, opts) - return $ EvalResult [] tv c \ No newline at end of file + _ -> + either fail (return . EvalResult [] tv) (runEncoder (enc tv) env) \ No newline at end of file diff --git a/src/Ideas/Encoding/LinkManager.hs b/src/Ideas/Encoding/LinkManager.hs index 7127b82e..cf21c4f1 100644 --- a/src/Ideas/Encoding/LinkManager.hs +++ b/src/Ideas/Encoding/LinkManager.hs @@ -28,7 +28,7 @@ module Ideas.Encoding.LinkManager , escapeInURL ) where -import Data.Maybe +import Data.Either import Ideas.Common.Library import Ideas.Encoding.EncoderXML import Ideas.Encoding.Options @@ -187,7 +187,7 @@ stateRequest s state = -- assume nothing goest wrong stateToXML :: State a -> XMLBuilder -stateToXML st = fromMaybe (error "LinkManager: Invalid state") $ +stateToXML st = fromRight (error "LinkManager: Invalid state") $ runEncoder (encodeState st) (exercise st, optionHtml mempty) linkWith :: (a -> String) -> a -> HTMLBuilder -> HTMLBuilder diff --git a/src/Ideas/Text/JSON.hs b/src/Ideas/Text/JSON.hs index a6bb10b0..e5ea0bb5 100644 --- a/src/Ideas/Text/JSON.hs +++ b/src/Ideas/Text/JSON.hs @@ -20,7 +20,8 @@ module Ideas.Text.JSON , parseJSON, compactJSON -- parser and pretty-printers , jsonRPC, RPCHandler, RPCRequest(..), RPCResponse(..) , JSONBuilder, arrayBuilder, (.=), tagJSON, builder - , propEncoding + , builderList, builderObject, isEmptyBuilder + , extractFirst, extractKey, extractKeyAndValues ) where import Control.Exception @@ -298,6 +299,28 @@ tagJSON = (.=) builder :: InJSON a => a -> JSONBuilder builder a = JB [(Nothing, toJSON a)] +builderList :: InJSON a => [a] -> JSONBuilder +builderList = mconcat . map builder + +builderObject :: InJSON a => [(Key, a)] -> JSONBuilder +builderObject = mconcat . map (uncurry (.=)) + +isEmptyBuilder :: JSONBuilder -> Bool +isEmptyBuilder (JB xs) = null xs + +extractFirst :: JSONBuilder -> Maybe (JSON, JSONBuilder) +extractFirst (JB ((Nothing, a):rest)) = Just (a, JB rest) +extractFirst _ = Nothing + +extractKey :: Key -> JSONBuilder -> Maybe (JSON, JSONBuilder) +extractKey k (JB xs) = + case break (maybe False (== k) . fst) xs of + (xs1, (_, v):xs2) -> Just (v, JB (xs1 ++ xs2)) + _ -> Nothing + +extractKeyAndValues :: JSONBuilder -> [(Key, JSON)] +extractKeyAndValues (JB xs) = [ (k, a) | (mk, a) <- xs, k <- maybeToList mk ] + -- local helper builderToJSON :: JSONBuilder -> JSON builderToJSON (JB [(Nothing, x)]) = x diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index 423240f3..166bf9e6 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -142,7 +142,7 @@ class (Sem.Semigroup a, Monoid a) => BuildXML a where element s = tag s . mconcat emptyTag s = tag s mempty -instance BuildXML a => BuildXML (Decoder env s a) where +instance BuildXML a => BuildXML (Decoder env err s a) where n .=. s = pure (n .=. s) string = pure . string builder = pure . builder @@ -251,13 +251,13 @@ expecting s xml = ------------------------------------------------------------------------------- -- Decoding XML -decodeData :: Decoder env XML String +decodeData :: IsString err => Decoder env err XML String decodeData = get >>= \xml -> case content xml of Left s:rest -> put xml {content = rest} >> return s _ -> fail "Could not find data" -decodeAttribute :: String -> Decoder env XML String +decodeAttribute :: IsString err => String -> Decoder env err XML String decodeAttribute s = get >>= \xml -> case break hasName (attributes xml) of (xs, (_ := val):ys) -> put xml {attributes = xs ++ ys } >> return val @@ -265,7 +265,7 @@ decodeAttribute s = get >>= \xml -> where hasName (n := _) = n == s -decodeChild :: Name -> Decoder env XML a -> Decoder env XML a +decodeChild :: IsString err => Name -> Decoder env err XML a -> Decoder env err XML a decodeChild s p = get >>= \xml -> case break hasName (content xml) of (xs, Right y:ys) -> do @@ -277,7 +277,7 @@ decodeChild s p = get >>= \xml -> where hasName = either (const False) ((==s) . name) -decodeFirstChild :: Name -> Decoder env XML a -> Decoder env XML a +decodeFirstChild :: IsString err => Name -> Decoder env err XML a -> Decoder env err XML a decodeFirstChild s p = get >>= \xml -> case content xml of Right y:ys | name y == s -> do diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 27458cea..f7633e61 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -14,76 +14,55 @@ module Ideas.Utils.Decoding ( Decoder, runDecoder, symbol , Encoder, runEncoder - , Error, runError, runErrorM + , Error, runError + , throwError ) where import Control.Applicative import Control.Monad +import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State -import Data.Semigroup as Sem +import Data.String ------------------------------------------------------------------- -newtype Decoder env s a = Dec { runDec :: StateT s (ReaderT env Error) a } - deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadReader env, MonadState s) +newtype Decoder env err s a = Dec { runDec :: StateT s (ReaderT env (Error err)) a } + deriving (Functor, Applicative, Alternative, MonadPlus, MonadReader env, MonadState s, MonadError err) -instance Sem.Semigroup a => Sem.Semigroup (Decoder env s a) where +instance Semigroup a => Semigroup (Decoder env err s a) where (<>) = liftA2 (<>) -instance Monoid a => Monoid (Decoder env s a) where +instance Monoid a => Monoid (Decoder env err s a) where mempty = pure mempty mappend = liftA2 mappend -symbol :: Decoder env [s] s +instance IsString err => Monad (Decoder env err s) where + return a = Dec (return a) + Dec m >>= f = Dec $ m >>= \a -> runDec (f a) + fail s = Dec $ throwError (fromString s) -- ! needed for backwards compatibility + +symbol :: IsString err => Decoder env err [s] s symbol = get >>= \list -> case list of [] -> fail "Empty input" x:xs -> put xs >> return x -runDecoder :: Monad m => Decoder env s a -> env -> s -> m a -runDecoder p env s = runErrorM (runReaderT (evalStateT (runDec p) s) env) +runDecoder :: Decoder env err s a -> env -> s -> Either err a +runDecoder p env s = runError (runReaderT (evalStateT (runDec p) s) env) ------------------------------------------------------------------- -type Encoder env = Decoder env () +type Encoder env err = Decoder env err () -runEncoder :: Monad m => Encoder env a -> env -> m a +runEncoder :: Encoder env err a -> env -> Either err a runEncoder p env = runDecoder p env () ------------------------------------------------------------------- -- Error monad (helper) -newtype Error a = Error { runError :: Either String a } - -instance Functor Error where - fmap f = Error . fmap f . runError - -instance Applicative Error where - pure = Error . Right - p <*> q = Error $ - case (runError p, runError q) of - (Left s, _) -> Left s - (_, Left s) -> Left s - (Right f, Right x) -> Right (f x) - -instance Alternative Error where - empty = Error (Left "empty") - p <|> q = Error $ - case (runError p, runError q) of - (Right a, _) -> Right a - (_, Right a) -> Right a - (Left s, _) -> Left s - -instance Monad Error where - fail = Error . Left - return = pure - m >>= f = Error $ either Left (runError . f) (runError m) - -instance MonadPlus Error where - mzero = fail "mzero" - mplus = (<|>) +type Error err = Except err -runErrorM :: Monad m => Error a -> m a -runErrorM = either fail return . runError \ No newline at end of file +runError :: Error err a -> Either err a +runError = runExcept \ No newline at end of file From 741d45b6592b3702ec0f04b071e7ba8019e77e1f Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 23 Aug 2021 11:47:35 +0200 Subject: [PATCH 19/57] cleaning up Decoding interface --- src/Ideas/Encoding/LinkManager.hs | 4 ++-- src/Ideas/Utils/Decoding.hs | 18 +++++------------- 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/src/Ideas/Encoding/LinkManager.hs b/src/Ideas/Encoding/LinkManager.hs index cf21c4f1..0fac7d54 100644 --- a/src/Ideas/Encoding/LinkManager.hs +++ b/src/Ideas/Encoding/LinkManager.hs @@ -182,8 +182,8 @@ exerciseRequestWith s ex rest = makeRequest s (("exerciseid" .=. showId ex) <> rest) stateRequest :: String -> State a -> XML -stateRequest s state = - exerciseRequestWith s (exercise state) (stateToXML state) +stateRequest s st = + exerciseRequestWith s (exercise st) (stateToXML st) -- assume nothing goest wrong stateToXML :: State a -> XMLBuilder diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index f7633e61..32c1efb1 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -14,8 +14,8 @@ module Ideas.Utils.Decoding ( Decoder, runDecoder, symbol , Encoder, runEncoder - , Error, runError - , throwError + -- re-exports + , Alternative(..), MonadReader(..), MonadState(..), MonadError(..) ) where import Control.Applicative @@ -27,7 +27,7 @@ import Data.String ------------------------------------------------------------------- -newtype Decoder env err s a = Dec { runDec :: StateT s (ReaderT env (Error err)) a } +newtype Decoder env err s a = Dec { runDec :: StateT s (ReaderT env (Except err)) a } deriving (Functor, Applicative, Alternative, MonadPlus, MonadReader env, MonadState s, MonadError err) instance Semigroup a => Semigroup (Decoder env err s a) where @@ -50,19 +50,11 @@ symbol = get >>= \list -> put xs >> return x runDecoder :: Decoder env err s a -> env -> s -> Either err a -runDecoder p env s = runError (runReaderT (evalStateT (runDec p) s) env) +runDecoder p env s = runExcept (runReaderT (evalStateT (runDec p) s) env) ------------------------------------------------------------------- type Encoder env err = Decoder env err () runEncoder :: Encoder env err a -> env -> Either err a -runEncoder p env = runDecoder p env () - -------------------------------------------------------------------- --- Error monad (helper) - -type Error err = Except err - -runError :: Error err a -> Either err a -runError = runExcept \ No newline at end of file +runEncoder p env = runDecoder p env () \ No newline at end of file From f7c0547400f82d41e8b3ce6faa12c1e20e39554c Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 23 Aug 2021 12:05:26 +0200 Subject: [PATCH 20/57] importing JSON decoder from logic tutor --- ideas.cabal | 1 + src/Ideas/Text/JSON/Decoder.hs | 183 +++++++++++++++++++++++++++++++++ 2 files changed, 184 insertions(+) create mode 100644 src/Ideas/Text/JSON/Decoder.hs diff --git a/ideas.cabal b/ideas.cabal index 678afec4..7fc99ad8 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -161,6 +161,7 @@ Library Ideas.Text.HTML.Templates Ideas.Text.HTML.W3CSS Ideas.Text.JSON + Ideas.Text.JSON.Decoder Ideas.Text.Latex Ideas.Text.MathML Ideas.Text.OpenMath.Dictionary.Arith1 diff --git a/src/Ideas/Text/JSON/Decoder.hs b/src/Ideas/Text/JSON/Decoder.hs new file mode 100644 index 00000000..1b0a4c90 --- /dev/null +++ b/src/Ideas/Text/JSON/Decoder.hs @@ -0,0 +1,183 @@ +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +module Ideas.Text.JSON.Decoder + ( EnvDecoderJSON, runEnvDecoderJSON, fromEnvDecoderJSON + , DecoderJSON, runDecoderJSON + , ErrorJSON + , jObject, jKey, jWithObject + , jArray, jWithArray + , jString, jBool, jInteger, jInt, jDouble, jFloat + , jNull, jEmpty + -- re-exports + , Alternative(..), MonadReader(..) + ) where + +import Control.Monad +import Ideas.Text.JSON +import Ideas.Utils.Decoding +import Data.List +import Data.String + +newtype EnvDecoderJSON env a = DJ { fromEnvDecoderJSON :: Decoder env ErrorJSON (Loc, JSONBuilder) a } + deriving (Functor, Applicative, Alternative, Monad, MonadReader env) + +runEnvDecoderJSON :: EnvDecoderJSON env a -> env -> JSON -> Either ErrorJSON a +runEnvDecoderJSON p env json = runDecoder (fromEnvDecoderJSON p) env (Root 0, builder json) + +type DecoderJSON = EnvDecoderJSON () + +runDecoderJSON :: DecoderJSON a -> JSON -> Either ErrorJSON a +runDecoderJSON p = runEnvDecoderJSON p () + +jObject :: EnvDecoderJSON env a -> EnvDecoderJSON env a +jObject p = jNext $ \loc a -> + case a of + Just (Object xs) -> putDJ (loc, builderObject xs) >> p + _ -> errorJSON NotAnObject loc a + +jKey :: Key -> EnvDecoderJSON env a -> EnvDecoderJSON env a +jKey k p = getDJ >>= \(loc, xs) -> + case extractKey k xs of + Just (v, rest) -> putDJ (LocKey 0 k loc, builder v) *> p <* putDJ (loc, rest) + _ -> errorJSON (KeyNotFound k) loc (Just (toJSON xs)) + +jWithObject :: (Key -> EnvDecoderJSON env a) -> EnvDecoderJSON env [a] +jWithObject g = jObject $ getDJ >>= \(loc, xs) -> + mapM (\(k, v) -> putDJ (LocKey 0 k loc, builder v) >> g k) (extractKeyAndValues xs) + +jArray :: EnvDecoderJSON env a -> EnvDecoderJSON env a +jArray p = jNext $ \loc a -> + case a of + Just (Array xs) -> putDJ (LocArray 0 loc, builderList xs) >> p + _ -> errorJSON NotAnArray loc a + +jWithArray :: EnvDecoderJSON env a -> EnvDecoderJSON env [a] +jWithArray p = jArray (many p <* jEmpty) + +jString :: EnvDecoderJSON env String +jString = jNext $ \loc a -> + case a of + Just (String s) -> return s + _ -> errorJSON NotAString loc a + +jBool :: EnvDecoderJSON env Bool +jBool = jNext $ \loc a -> + case a of + Just (Boolean b) -> return b + _ -> errorJSON NotABoolean loc a + +jInteger :: EnvDecoderJSON env Integer +jInteger = jNext $ \loc a -> + case a of + Just (Number (I i)) -> return i + _ -> errorJSON NotAnInteger loc a + +jInt :: EnvDecoderJSON env Int +jInt = fromInteger <$> jInteger + +jDouble :: EnvDecoderJSON env Double +jDouble = jNext $ \loc a -> + case a of + Just (Number (D d)) -> return d + _ -> errorJSON NotADouble loc a + +jFloat :: EnvDecoderJSON env Float +jFloat = realToFrac <$> jDouble + +jNull :: EnvDecoderJSON env () +jNull = jNext $ \loc a -> + case a of + Just (Null) -> return () + _ -> errorJSON NotNull loc a + +jEmpty :: EnvDecoderJSON env () +jEmpty = getDJ >>= \(loc, xs) -> + unless (isEmptyBuilder xs) (errorJSON NotEmpty loc (Just (toJSON xs))) + +-- local helper: not exported +jNext :: (Loc -> Maybe JSON -> EnvDecoderJSON env a) -> EnvDecoderJSON env a +jNext f = getDJ >>= \(loc, xs) -> + case extractFirst xs of + Just (json, rest) -> f loc (Just json) <* putDJ (nextLoc loc, rest) + _ -> f loc Nothing + +-- local helper: not exported +getDJ :: EnvDecoderJSON env (Loc, JSONBuilder) +getDJ = DJ get + +-- local helper: not exported +putDJ :: (Loc, JSONBuilder) -> EnvDecoderJSON env () +putDJ = DJ . put + +-------------------------------------------------------------------------------- +-- Errors + +newtype ErrorJSON = E [Either String (ErrorType, Loc, Maybe JSON)] + +instance Show ErrorJSON where + show (E xs) + | null xs = "Parse error in JSON" + | otherwise = unlines (map (either id f) xs) + where + + f (tp, loc, mjson) = unlines + [ "Parse error: " ++ show tp + , " * Location: " ++ show loc + , " * Found: " ++ maybe "" show mjson + ] + +data ErrorType + = NotAnObject | NotAnArray | NotAString | NotABoolean | NotAnInteger | NotADouble + | NotNull | NotEmpty | KeyNotFound Key + +instance Show ErrorType where + show NotAnObject = "not an object" + show NotAnArray = "not an array" + show NotAString = "not a string" + show NotABoolean = "not a boolean" + show NotAnInteger = "not an integer" + show NotADouble = "not a double" + show NotNull = "not null" + show NotEmpty = "not empty" + show (KeyNotFound k) = "key '" ++ k ++ "'not found" + +instance IsString ErrorJSON where + fromString s = E [Left s] + +instance Semigroup ErrorJSON where + E xs <> E ys = E (xs <> ys) + +instance Monoid ErrorJSON where + mempty = E [] + +data Loc = Root Int | LocArray Int Loc | LocKey Int Key Loc + +instance Show Loc where + show loc + | null parts = "root" + | otherwise = intercalate "." parts + where + parts = collect loc + + collect (Root n) = [ "root+" ++ show n | n > 0 ] + collect (LocArray n l) = collect l ++ [show n] + collect (LocKey n k l) = collect l ++ [k ++ if n==0 then "" else "+" ++ show n] + +nextLoc :: Loc -> Loc +nextLoc (Root n) = Root (n+1) +nextLoc (LocArray n l) = LocArray (n+1) l +nextLoc (LocKey n k l) = LocKey (n+1) k l + +errorJSON :: ErrorType -> Loc -> Maybe JSON -> EnvDecoderJSON env a +errorJSON tp loc a = DJ $ throwError $ E [Right (tp, loc, a)] \ No newline at end of file From e37534ad55d4299ecd8be5b1403bf97289a12022 Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 23 Aug 2021 12:38:45 +0200 Subject: [PATCH 21/57] splitting JSON implementation into several modules --- ideas.cabal | 2 + src/Ideas/Text/JSON.hs | 359 +-------------------------------- src/Ideas/Text/JSON/Builder.hs | 82 ++++++++ src/Ideas/Text/JSON/Data.hs | 303 ++++++++++++++++++++++++++++ src/Ideas/Text/JSON/Decoder.hs | 3 +- 5 files changed, 395 insertions(+), 354 deletions(-) create mode 100644 src/Ideas/Text/JSON/Builder.hs create mode 100644 src/Ideas/Text/JSON/Data.hs diff --git a/ideas.cabal b/ideas.cabal index 7fc99ad8..267f880a 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -161,6 +161,8 @@ Library Ideas.Text.HTML.Templates Ideas.Text.HTML.W3CSS Ideas.Text.JSON + Ideas.Text.JSON.Builder + Ideas.Text.JSON.Data Ideas.Text.JSON.Decoder Ideas.Text.Latex Ideas.Text.MathML diff --git a/src/Ideas/Text/JSON.hs b/src/Ideas/Text/JSON.hs index e5ea0bb5..4bcaa3ef 100644 --- a/src/Ideas/Text/JSON.hs +++ b/src/Ideas/Text/JSON.hs @@ -14,358 +14,11 @@ ----------------------------------------------------------------------------- module Ideas.Text.JSON - ( JSON(..), Key, Number(..) -- types - , InJSON(..) -- type class - , lookupM - , parseJSON, compactJSON -- parser and pretty-printers - , jsonRPC, RPCHandler, RPCRequest(..), RPCResponse(..) - , JSONBuilder, arrayBuilder, (.=), tagJSON, builder - , builderList, builderObject, isEmptyBuilder - , extractFirst, extractKey, extractKeyAndValues + ( module Ideas.Text.JSON.Data + , module Ideas.Text.JSON.Builder + , module Ideas.Text.JSON.Decoder ) where -import Control.Exception -import Control.Monad -import Data.List (intersperse) -import Data.Maybe -import Data.String -import Ideas.Utils.Parsing hiding (string, char) -import System.IO.Error -import Test.QuickCheck -import Text.PrettyPrint.Leijen hiding ((<$>)) -import qualified Ideas.Text.UTF8 as UTF8 -import qualified Text.ParserCombinators.Parsec.Token as P - -data JSON - = Number Number -- integer, real, or floating point - | String String -- double-quoted Unicode with backslash escapement - | Boolean Bool -- true and false - | Array [JSON] -- ordered sequence (comma-separated, square brackets) - | Object [(Key, JSON)] -- collection of key/value pairs (comma-separated, curly brackets - | Null - deriving Eq - -type Key = String - -data Number = I Integer | D Double deriving Eq - -instance Show Number where - show (I n) = show n - show (D d) = show d - -instance Show JSON where - show = show . prettyJSON False - -instance IsString JSON where - fromString = String - -compactJSON :: JSON -> String -compactJSON = show . prettyJSON True - -prettyJSON :: Bool -> JSON -> Doc -prettyJSON compact = rec - where - rec json = - case json of - Number n -> text (show n) - String s -> str (escape s) - Boolean b -> text (if b then "true" else "false") - Null -> text "null" - Array xs -> make lbracket rbracket (map rec xs) - Object xs -> make lbrace rbrace (map (uncurry (<:>)) xs) - - x <:> y | compact = str x <> char ':' <> rec y - | isSimple y = str x <> string ": " <> rec y - | otherwise = align (str x <> char ':' <> line <> indent 2 (rec y)) - - str = dquotes . text - - make open close xs - | compact || length xs < 2 = - enclose open close (hcat (intersperse comma xs)) - | otherwise = - align (vsep (zipWith (<+>) (open:repeat comma) xs ++ [close])) - - isSimple (Array xs) = null xs - isSimple (Object xs) = null xs - isSimple _ = True - --- Escape double quote and backslash, and convert to UTF8 encoding -escape :: String -> String -escape = concatMap f . fromMaybe "invalid UTF8 string" . UTF8.encodeM - where - f '\n' = "\\n" - f '\r' = "" -- carriage return (DOS files) - f '\t' = "\\t" - f '"' = "\\\"" - f '\\' = "\\\\" - f c = [c] - -class InJSON a where - toJSON :: a -> JSON - listToJSON :: [a] -> JSON - fromJSON :: Monad m => JSON -> m a - listFromJSON :: Monad m => JSON -> m [a] - -- default definitions - listToJSON = Array . map toJSON - listFromJSON (Array xs) = mapM fromJSON xs - listFromJSON _ = fail "expecting an array" - -instance InJSON Int where - toJSON = toJSON . toInteger - fromJSON = fmap fromInteger . fromJSON - -instance InJSON Integer where - toJSON = Number . I - fromJSON (Number (I n)) = return n - fromJSON _ = fail "expecting a number" - -instance InJSON Double where - toJSON = Number . D - fromJSON (Number (D n)) = return n - fromJSON _ = fail "expecting a number" - -instance InJSON Char where - toJSON c = String [c] - listToJSON = String - fromJSON (String [c]) = return c - fromJSON _ = fail "expecting a string" - listFromJSON (String s) = return s - listFromJSON _ = fail "expecting a string" - -instance InJSON Bool where - toJSON = Boolean - fromJSON (Boolean b) = return b - fromJSON _ = fail "expecting a boolean" - -instance InJSON a => InJSON [a] where - toJSON = listToJSON - fromJSON = listFromJSON - -instance (InJSON a, InJSON b) => InJSON (a, b) where - toJSON (a, b) = Array [toJSON a, toJSON b] - fromJSON (Array [a, b]) = (,) <$> fromJSON a <*> fromJSON b - fromJSON _ = fail "expecting an array with 2 elements" - -instance (InJSON a, InJSON b, InJSON c) => InJSON (a, b, c) where - toJSON (a, b, c) = Array [toJSON a, toJSON b, toJSON c] - fromJSON (Array [a, b, c]) = (,,) <$> fromJSON a <*> fromJSON b <*> fromJSON c - fromJSON _ = fail "expecting an array with 3 elements" - -instance (InJSON a, InJSON b, InJSON c, InJSON d) => InJSON (a, b, c, d) where - toJSON (a, b, c, d) = Array [toJSON a, toJSON b, toJSON c, toJSON d] - fromJSON (Array [a, b, c, d]) = (,,,) <$> fromJSON a <*> fromJSON b <*> fromJSON c <*> fromJSON d - fromJSON _ = fail "expecting an array with 4 elements" - -instance InJSON JSON where - toJSON = id - fromJSON = return - --------------------------------------------------------- --- Parser - -parseJSON :: String -> Either String JSON -parseJSON = parseSimple json - where - json :: Parser JSON - json = choice - [ Null <$ P.reserved lexer "null" - , Boolean True <$ P.reserved lexer "true" - , Boolean False <$ P.reserved lexer "false" - , Number . either I D <$> naturalOrFloat -- redefined in Ideas.Text.Parsing - , String <$> P.stringLiteral lexer - , Array <$> P.brackets lexer (sepBy json (P.comma lexer)) - , Object <$> P.braces lexer (sepBy keyValue (P.comma lexer)) - ] - - keyValue :: Parser (String, JSON) - keyValue = (,) <$> P.stringLiteral lexer <* P.colon lexer <*> json - - lexer :: P.TokenParser a - lexer = P.makeTokenParser $ emptyDef - { reservedNames = ["true", "false", "null"] } - --------------------------------------------------------- --- JSON-RPC - -data RPCRequest = Request - { requestMethod :: String - , requestParams :: JSON - , requestId :: JSON - } - -data RPCResponse = Response - { responseResult :: JSON - , responseError :: JSON - , responseId :: JSON - } - -instance Show RPCRequest where - show = show . toJSON - -instance Show RPCResponse where - show = show . toJSON - -instance InJSON RPCRequest where - toJSON req = Object - [ ("method", String $ requestMethod req) - , ("params", requestParams req) - , ("id" , requestId req) - ] - fromJSON json = - case lookupM "method" json of - Just (String s) -> - let pj = fromMaybe Null (lookupM "params" json) - ij = fromMaybe Null (lookupM "id" json) - in return (Request s pj ij) - Just _ -> fail "expecting a string as method" - Nothing -> fail "no method specified" - -instance InJSON RPCResponse where - toJSON resp = Object - [ ("result", responseResult resp) - , ("error" , responseError resp) - , ("id" , responseId resp) - ] - fromJSON obj = do - rj <- lookupM "result" obj - ej <- lookupM "error" obj - ij <- lookupM "id" obj - return (Response rj ej ij) - -okResponse :: JSON -> JSON -> RPCResponse -okResponse x y = Response - { responseResult = x - , responseError = Null - , responseId = y - } - -errorResponse :: JSON -> JSON -> RPCResponse -errorResponse x y = Response - { responseResult = Null - , responseError = x - , responseId = y - } - -lookupM :: Monad m => String -> JSON -> m JSON -lookupM x (Object xs) = maybe (fail $ "field " ++ x ++ " not found") return (lookup x xs) -lookupM _ _ = fail "expecting a JSON object" - --------------------------------------------------------- --- JSON-RPC over HTTP - -type RPCHandler = String -> JSON -> IO JSON - -jsonRPC :: JSON -> RPCHandler -> IO RPCResponse -jsonRPC input rpc = - case fromJSON input of - Nothing -> return (errorResponse (String "Invalid request") Null) - Just req -> do - json <- rpc (requestMethod req) (requestParams req) - return (okResponse json (requestId req)) - `catch` handler req - where - handler :: RPCRequest -> SomeException -> IO RPCResponse - handler req e = - let msg = maybe (show e) ioeGetErrorString (fromException e) - in return $ errorResponse (toJSON msg) (requestId req) - --------------------------------------------------------- --- JSON builder - -newtype JSONBuilder = JB [(Maybe Key, JSON)] - -instance InJSON JSONBuilder where - toJSON = builderToJSON - fromJSON = return . builder - -instance Semigroup JSONBuilder where - JB xs <> JB ys = JB (xs <> ys) - -instance Monoid JSONBuilder where - mempty = JB [] - -arrayBuilder :: [JSONBuilder] -> JSONBuilder -arrayBuilder = builder . Array . map builderToJSON - -infix 7 .= - -(.=) :: InJSON a => String -> a -> JSONBuilder -s .= a = JB [(Just s, toJSON a)] - -tagJSON :: InJSON a => String -> a -> JSONBuilder -tagJSON = (.=) - -builder :: InJSON a => a -> JSONBuilder -builder a = JB [(Nothing, toJSON a)] - -builderList :: InJSON a => [a] -> JSONBuilder -builderList = mconcat . map builder - -builderObject :: InJSON a => [(Key, a)] -> JSONBuilder -builderObject = mconcat . map (uncurry (.=)) - -isEmptyBuilder :: JSONBuilder -> Bool -isEmptyBuilder (JB xs) = null xs - -extractFirst :: JSONBuilder -> Maybe (JSON, JSONBuilder) -extractFirst (JB ((Nothing, a):rest)) = Just (a, JB rest) -extractFirst _ = Nothing - -extractKey :: Key -> JSONBuilder -> Maybe (JSON, JSONBuilder) -extractKey k (JB xs) = - case break (maybe False (== k) . fst) xs of - (xs1, (_, v):xs2) -> Just (v, JB (xs1 ++ xs2)) - _ -> Nothing - -extractKeyAndValues :: JSONBuilder -> [(Key, JSON)] -extractKeyAndValues (JB xs) = [ (k, a) | (mk, a) <- xs, k <- maybeToList mk ] - --- local helper -builderToJSON :: JSONBuilder -> JSON -builderToJSON (JB [(Nothing, x)]) = x -builderToJSON (JB xs) = - case mapM fst xs of - Just ks -> Object (zip ks (map snd xs)) - Nothing -> Array (map f xs) - where - f (Nothing, a) = a - f (Just k, a) = Object [(k, a)] - --------------------------------------------------------- --- Testing parser/pretty-printer - -instance Arbitrary JSON where - arbitrary = sized arbJSON - -instance Arbitrary Number where - arbitrary = oneof [ I <$> arbitrary, D . fromInteger <$> arbitrary ] - -arbJSON :: Int -> Gen JSON -arbJSON n - | n == 0 = oneof - [ Number <$> arbitrary, String <$> myStringGen - , Boolean <$> arbitrary, return Null - ] - | otherwise = oneof - [ arbJSON 0 - , do i <- choose (0, 6) - xs <- replicateM i rec - return (Array xs) - , do i <- choose (0, 6) - xs <- replicateM i myStringGen - ys <- replicateM i rec - return (Object (zip xs ys)) - ] - where - rec = arbJSON (n `div` 2) - -myStringGen :: Gen String -myStringGen = do - n <- choose (1, 10) - replicateM n $ elements $ - ['A' .. 'Z'] ++ ['a' .. 'z'] ++ ['0' .. '9'] - -propEncoding :: Property -propEncoding = property $ \a -> - parseJSON (show a) == Right a \ No newline at end of file +import Ideas.Text.JSON.Builder +import Ideas.Text.JSON.Data +import Ideas.Text.JSON.Decoder \ No newline at end of file diff --git a/src/Ideas/Text/JSON/Builder.hs b/src/Ideas/Text/JSON/Builder.hs new file mode 100644 index 00000000..470b3aa9 --- /dev/null +++ b/src/Ideas/Text/JSON/Builder.hs @@ -0,0 +1,82 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +module Ideas.Text.JSON.Builder + ( JSONBuilder, arrayBuilder, (.=), tagJSON, builder + , builderList, builderObject, isEmptyBuilder + , extractFirst, extractKey, extractKeyAndValues + ) where + +import Data.Maybe +import Ideas.Text.JSON.Data + +-------------------------------------------------------- +-- JSON builder + +newtype JSONBuilder = JB [(Maybe Key, JSON)] + +instance InJSON JSONBuilder where + toJSON = builderToJSON + fromJSON = return . builder + +instance Semigroup JSONBuilder where + JB xs <> JB ys = JB (xs <> ys) + +instance Monoid JSONBuilder where + mempty = JB [] + +arrayBuilder :: [JSONBuilder] -> JSONBuilder +arrayBuilder = builder . Array . map builderToJSON + +infix 7 .= + +(.=) :: InJSON a => String -> a -> JSONBuilder +s .= a = JB [(Just s, toJSON a)] + +tagJSON :: InJSON a => String -> a -> JSONBuilder +tagJSON = (.=) + +builder :: InJSON a => a -> JSONBuilder +builder a = JB [(Nothing, toJSON a)] + +builderList :: InJSON a => [a] -> JSONBuilder +builderList = mconcat . map builder + +builderObject :: InJSON a => [(Key, a)] -> JSONBuilder +builderObject = mconcat . map (uncurry (.=)) + +isEmptyBuilder :: JSONBuilder -> Bool +isEmptyBuilder (JB xs) = null xs + +extractFirst :: JSONBuilder -> Maybe (JSON, JSONBuilder) +extractFirst (JB ((Nothing, a):rest)) = Just (a, JB rest) +extractFirst _ = Nothing + +extractKey :: Key -> JSONBuilder -> Maybe (JSON, JSONBuilder) +extractKey k (JB xs) = + case break (maybe False (== k) . fst) xs of + (xs1, (_, v):xs2) -> Just (v, JB (xs1 ++ xs2)) + _ -> Nothing + +extractKeyAndValues :: JSONBuilder -> [(Key, JSON)] +extractKeyAndValues (JB xs) = [ (k, a) | (mk, a) <- xs, k <- maybeToList mk ] + +-- local helper +builderToJSON :: JSONBuilder -> JSON +builderToJSON (JB [(Nothing, x)]) = x +builderToJSON (JB xs) = + case mapM fst xs of + Just ks -> Object (zip ks (map snd xs)) + Nothing -> Array (map f xs) + where + f (Nothing, a) = a + f (Just k, a) = Object [(k, a)] \ No newline at end of file diff --git a/src/Ideas/Text/JSON/Data.hs b/src/Ideas/Text/JSON/Data.hs new file mode 100644 index 00000000..2c1bb8f4 --- /dev/null +++ b/src/Ideas/Text/JSON/Data.hs @@ -0,0 +1,303 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +module Ideas.Text.JSON.Data + ( JSON(..), Key, Number(..) -- types + , InJSON(..) -- type class + , lookupM + , parseJSON, compactJSON -- parser and pretty-printers + , jsonRPC, RPCHandler, RPCRequest(..), RPCResponse(..) + ) where + +import Control.Exception +import Control.Monad +import Data.List (intersperse) +import Data.Maybe +import Data.String +import Ideas.Utils.Parsing hiding (string, char) +import System.IO.Error +import Test.QuickCheck +import Text.PrettyPrint.Leijen hiding ((<$>)) +import qualified Ideas.Text.UTF8 as UTF8 +import qualified Text.ParserCombinators.Parsec.Token as P + +data JSON + = Number Number -- integer, real, or floating point + | String String -- double-quoted Unicode with backslash escapement + | Boolean Bool -- true and false + | Array [JSON] -- ordered sequence (comma-separated, square brackets) + | Object [(Key, JSON)] -- collection of key/value pairs (comma-separated, curly brackets + | Null + deriving Eq + +type Key = String + +data Number = I Integer | D Double deriving Eq + +instance Show Number where + show (I n) = show n + show (D d) = show d + +instance Show JSON where + show = show . prettyJSON False + +instance IsString JSON where + fromString = String + +compactJSON :: JSON -> String +compactJSON = show . prettyJSON True + +prettyJSON :: Bool -> JSON -> Doc +prettyJSON compact = rec + where + rec json = + case json of + Number n -> text (show n) + String s -> str (escape s) + Boolean b -> text (if b then "true" else "false") + Null -> text "null" + Array xs -> make lbracket rbracket (map rec xs) + Object xs -> make lbrace rbrace (map (uncurry (<:>)) xs) + + x <:> y | compact = str x <> char ':' <> rec y + | isSimple y = str x <> string ": " <> rec y + | otherwise = align (str x <> char ':' <> line <> indent 2 (rec y)) + + str = dquotes . text + + make open close xs + | compact || length xs < 2 = + enclose open close (hcat (intersperse comma xs)) + | otherwise = + align (vsep (zipWith (<+>) (open:repeat comma) xs ++ [close])) + + isSimple (Array xs) = null xs + isSimple (Object xs) = null xs + isSimple _ = True + +-- Escape double quote and backslash, and convert to UTF8 encoding +escape :: String -> String +escape = concatMap f . fromMaybe "invalid UTF8 string" . UTF8.encodeM + where + f '\n' = "\\n" + f '\r' = "" -- carriage return (DOS files) + f '\t' = "\\t" + f '"' = "\\\"" + f '\\' = "\\\\" + f c = [c] + +class InJSON a where + toJSON :: a -> JSON + listToJSON :: [a] -> JSON + fromJSON :: Monad m => JSON -> m a + listFromJSON :: Monad m => JSON -> m [a] + -- default definitions + listToJSON = Array . map toJSON + listFromJSON (Array xs) = mapM fromJSON xs + listFromJSON _ = fail "expecting an array" + +instance InJSON Int where + toJSON = toJSON . toInteger + fromJSON = fmap fromInteger . fromJSON + +instance InJSON Integer where + toJSON = Number . I + fromJSON (Number (I n)) = return n + fromJSON _ = fail "expecting a number" + +instance InJSON Double where + toJSON = Number . D + fromJSON (Number (D n)) = return n + fromJSON _ = fail "expecting a number" + +instance InJSON Char where + toJSON c = String [c] + listToJSON = String + fromJSON (String [c]) = return c + fromJSON _ = fail "expecting a string" + listFromJSON (String s) = return s + listFromJSON _ = fail "expecting a string" + +instance InJSON Bool where + toJSON = Boolean + fromJSON (Boolean b) = return b + fromJSON _ = fail "expecting a boolean" + +instance InJSON a => InJSON [a] where + toJSON = listToJSON + fromJSON = listFromJSON + +instance (InJSON a, InJSON b) => InJSON (a, b) where + toJSON (a, b) = Array [toJSON a, toJSON b] + fromJSON (Array [a, b]) = (,) <$> fromJSON a <*> fromJSON b + fromJSON _ = fail "expecting an array with 2 elements" + +instance (InJSON a, InJSON b, InJSON c) => InJSON (a, b, c) where + toJSON (a, b, c) = Array [toJSON a, toJSON b, toJSON c] + fromJSON (Array [a, b, c]) = (,,) <$> fromJSON a <*> fromJSON b <*> fromJSON c + fromJSON _ = fail "expecting an array with 3 elements" + +instance (InJSON a, InJSON b, InJSON c, InJSON d) => InJSON (a, b, c, d) where + toJSON (a, b, c, d) = Array [toJSON a, toJSON b, toJSON c, toJSON d] + fromJSON (Array [a, b, c, d]) = (,,,) <$> fromJSON a <*> fromJSON b <*> fromJSON c <*> fromJSON d + fromJSON _ = fail "expecting an array with 4 elements" + +instance InJSON JSON where + toJSON = id + fromJSON = return + +-------------------------------------------------------- +-- Parser + +parseJSON :: String -> Either String JSON +parseJSON = parseSimple json + where + json :: Parser JSON + json = choice + [ Null <$ P.reserved lexer "null" + , Boolean True <$ P.reserved lexer "true" + , Boolean False <$ P.reserved lexer "false" + , Number . either I D <$> naturalOrFloat -- redefined in Ideas.Text.Parsing + , String <$> P.stringLiteral lexer + , Array <$> P.brackets lexer (sepBy json (P.comma lexer)) + , Object <$> P.braces lexer (sepBy keyValue (P.comma lexer)) + ] + + keyValue :: Parser (String, JSON) + keyValue = (,) <$> P.stringLiteral lexer <* P.colon lexer <*> json + + lexer :: P.TokenParser a + lexer = P.makeTokenParser $ emptyDef + { reservedNames = ["true", "false", "null"] } + +-------------------------------------------------------- +-- JSON-RPC + +data RPCRequest = Request + { requestMethod :: String + , requestParams :: JSON + , requestId :: JSON + } + +data RPCResponse = Response + { responseResult :: JSON + , responseError :: JSON + , responseId :: JSON + } + +instance Show RPCRequest where + show = show . toJSON + +instance Show RPCResponse where + show = show . toJSON + +instance InJSON RPCRequest where + toJSON req = Object + [ ("method", String $ requestMethod req) + , ("params", requestParams req) + , ("id" , requestId req) + ] + fromJSON json = + case lookupM "method" json of + Just (String s) -> + let pj = fromMaybe Null (lookupM "params" json) + ij = fromMaybe Null (lookupM "id" json) + in return (Request s pj ij) + Just _ -> fail "expecting a string as method" + Nothing -> fail "no method specified" + +instance InJSON RPCResponse where + toJSON resp = Object + [ ("result", responseResult resp) + , ("error" , responseError resp) + , ("id" , responseId resp) + ] + fromJSON obj = do + rj <- lookupM "result" obj + ej <- lookupM "error" obj + ij <- lookupM "id" obj + return (Response rj ej ij) + +okResponse :: JSON -> JSON -> RPCResponse +okResponse x y = Response + { responseResult = x + , responseError = Null + , responseId = y + } + +errorResponse :: JSON -> JSON -> RPCResponse +errorResponse x y = Response + { responseResult = Null + , responseError = x + , responseId = y + } + +lookupM :: Monad m => String -> JSON -> m JSON +lookupM x (Object xs) = maybe (fail $ "field " ++ x ++ " not found") return (lookup x xs) +lookupM _ _ = fail "expecting a JSON object" + +-------------------------------------------------------- +-- JSON-RPC over HTTP + +type RPCHandler = String -> JSON -> IO JSON + +jsonRPC :: JSON -> RPCHandler -> IO RPCResponse +jsonRPC input rpc = + case fromJSON input of + Nothing -> return (errorResponse (String "Invalid request") Null) + Just req -> do + json <- rpc (requestMethod req) (requestParams req) + return (okResponse json (requestId req)) + `catch` handler req + where + handler :: RPCRequest -> SomeException -> IO RPCResponse + handler req e = + let msg = maybe (show e) ioeGetErrorString (fromException e) + in return $ errorResponse (toJSON msg) (requestId req) + +-------------------------------------------------------- +-- Testing parser/pretty-printer + +instance Arbitrary JSON where + arbitrary = sized arbJSON + +instance Arbitrary Number where + arbitrary = oneof [ I <$> arbitrary, D . fromInteger <$> arbitrary ] + +arbJSON :: Int -> Gen JSON +arbJSON n + | n == 0 = oneof + [ Number <$> arbitrary, String <$> myStringGen + , Boolean <$> arbitrary, return Null + ] + | otherwise = oneof + [ arbJSON 0 + , do i <- choose (0, 6) + xs <- replicateM i rec + return (Array xs) + , do i <- choose (0, 6) + xs <- replicateM i myStringGen + ys <- replicateM i rec + return (Object (zip xs ys)) + ] + where + rec = arbJSON (n `div` 2) + +myStringGen :: Gen String +myStringGen = do + n <- choose (1, 10) + replicateM n $ elements $ + ['A' .. 'Z'] ++ ['a' .. 'z'] ++ ['0' .. '9'] + +_propEncoding :: Property +_propEncoding = property $ \a -> + parseJSON (show a) == Right a \ No newline at end of file diff --git a/src/Ideas/Text/JSON/Decoder.hs b/src/Ideas/Text/JSON/Decoder.hs index 1b0a4c90..e7540f2d 100644 --- a/src/Ideas/Text/JSON/Decoder.hs +++ b/src/Ideas/Text/JSON/Decoder.hs @@ -24,7 +24,8 @@ module Ideas.Text.JSON.Decoder ) where import Control.Monad -import Ideas.Text.JSON +import Ideas.Text.JSON.Builder +import Ideas.Text.JSON.Data import Ideas.Utils.Decoding import Data.List import Data.String From e8b03b303d8423cef8fb4e7b19d13e72f91306ca Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 24 Aug 2021 13:56:35 +0200 Subject: [PATCH 22/57] updating decoders --- src/Ideas/Encoding/DecoderJSON.hs | 155 ++++++------- src/Ideas/Encoding/DecoderXML.hs | 2 +- src/Ideas/Encoding/Encoder.hs | 27 +-- src/Ideas/Encoding/Evaluator.hs | 2 +- src/Ideas/Encoding/NewDecoderJSON.hs | 328 ++++++--------------------- src/Ideas/Text/JSON/Decoder.hs | 135 ++++++----- src/Ideas/Utils/Decoding.hs | 28 ++- 7 files changed, 255 insertions(+), 422 deletions(-) diff --git a/src/Ideas/Encoding/DecoderJSON.hs b/src/Ideas/Encoding/DecoderJSON.hs index 7601b270..6359c0fb 100644 --- a/src/Ideas/Encoding/DecoderJSON.hs +++ b/src/Ideas/Encoding/DecoderJSON.hs @@ -17,27 +17,29 @@ module Ideas.Encoding.DecoderJSON ( JSONDecoder, jsonDecoder ) where -import Control.Monad.State (mplus, foldM, get, gets, put) +import Control.Monad.State (get, gets) import Data.Char import Data.Maybe import Ideas.Common.Library hiding (exerciseId, symbol) import Ideas.Common.Traversal.Navigator import Ideas.Encoding.Encoder +import Ideas.Encoding.Options import Ideas.Service.State import Ideas.Service.Types hiding (String) import Ideas.Text.JSON -import Ideas.Utils.Decoding (symbol) import qualified Ideas.Service.Types as Tp -type JSONDecoder a t = DecoderX a JSON t +type JSONDecoder a = GDecoderJSON (Exercise a, Options) jsonDecoder :: TypedDecoder a JSON -jsonDecoder tp = get >>= \json -> - case json of - Array xs -> decodeType tp // xs - _ -> fail "expecting an array" - -decodeType :: Type a t -> DecoderX a [JSON] t +jsonDecoder tp = do + env <- reader id + json <- get + case evalGDecoderJSON (jArray (decodeType tp)) env json of + Left err -> throwError (show err) + Right a -> return a + +decodeType :: Type a t -> JSONDecoder a t decodeType tp = case tp of Tag _ t -> decodeType t @@ -47,73 +49,70 @@ decodeType tp = b <- decodeType t2 return (a, b) t1 :|: t2 -> - (Left <$> decodeType t1) `mplus` - (Right <$> decodeType t2) + Left <$> decodeType t1 <|> + Right <$> decodeType t2 Unit -> return () Const QCGen -> getQCGen Const Script -> getScript - Const t -> symbol >>= \a -> decodeConst t // a - _ -> fail $ "No support for argument type: " ++ show tp + Const t -> decodeConst t + _ -> errorStr $ "No support for argument type: " ++ show tp decodeConst :: Const a t -> JSONDecoder a t decodeConst tp = case tp of State -> decodeState Context -> decodeContext - Exercise -> getExercise + Exercise -> getExercise <* jSkip Environment -> decodeEnvironment Location -> decodeLocation - Term -> gets jsonToTerm - Int -> get >>= fromJSON - Tp.String -> get >>= fromJSON + Term -> gets (jsonToTerm . toJSON . snd) + Int -> jInt + Tp.String -> jString Id -> decodeId Rule -> decodeRule - _ -> fail $ "No support for argument type: " ++ show tp + _ -> errorStr $ "No support for argument type: " ++ show tp decodeRule :: JSONDecoder a (Rule (Context a)) decodeRule = do - ex <- getExercise - get >>= \json -> - case json of - String s -> getRule ex (newId s) - _ -> fail "expecting a string for rule" + ex <- getExercise + rid <- newId <$> jString + case getRule ex rid of + Just r -> return r + Nothing -> errorStr ("unknown rule " ++ show rid) decodeId :: JSONDecoder a Id -decodeId = get >>= \json -> - case json of - String s -> return (newId s) - _ -> fail "expecting a string for id" +decodeId = newId <$> jString decodeLocation :: JSONDecoder a Location -decodeLocation = get >>= \json -> - case json of - String s -> toLocation <$> readM s - _ -> fail "expecting a string for a location" +decodeLocation = jString >>= \s -> + case readM s of + Just is -> return (toLocation is) + Nothing -> errorStr "invalid location" decodeState :: JSONDecoder a (State a) -decodeState = do - ex <- getExercise - get >>= \json -> - case json of - Array [a] -> put a >> decodeState - Array (String _code : pref : term : jsonContext : rest) -> do - pts <- decodePaths // pref - a <- decodeExpression // term - env <- decodeEnvironment // jsonContext - let loc = envToLoc env - ctx = navigateTowards loc $ deleteRef locRef $ - setEnvironment env $ inContext ex a - prfx = pts (strategy ex) ctx - case rest of - [] -> return $ makeState ex prfx ctx - [Array [String user, String session, String startterm]] -> - return (makeState ex prfx ctx) - { stateUser = Just user - , stateSession = Just session - , stateStartTerm = Just startterm - } - _ -> fail $ "invalid state" ++ show json - _ -> fail $ "invalid state" ++ show json +decodeState = jArray1 decodeState <|> jArray content + where + content = do + ex <- getExercise + _ <- jString -- exercise id + pts <- decodePaths + a <- decodeExpression + env <- decodeEnvironment + let loc = envToLoc env + ctx = navigateTowards loc $ deleteRef locRef $ + setEnvironment env $ inContext ex a + prfx = pts (strategy ex) ctx + defState = makeState ex prfx ctx + + (extra <|> id <$ jEmpty) <*> pure defState + + extra = jArray3 f jString jString jString + where + f user session startterm st = st + { stateUser = Just user + , stateSession = Just session + , stateStartTerm = Just startterm + } envToLoc :: Environment -> Location envToLoc env = toLocation $ fromMaybe [] $ locRef ? env >>= readM @@ -122,40 +121,32 @@ locRef :: Ref String locRef = makeRef "location" decodePaths :: JSONDecoder a (LabeledStrategy (Context a) -> Context a -> Prefix (Context a)) -decodePaths = - get >>= \json -> - case json of - String p - | p ~= "noprefix" -> return (\_ _ -> noPrefix) - | otherwise -> replayPaths <$> readPaths p - _ -> fail "invalid prefixes" +decodePaths = do + s <- jString + if (s ~= "noprefix") + then return (\_ _ -> noPrefix) + else replayPaths <$> readPaths s where x ~= y = filter isAlphaNum (map toLower x) == y decodeEnvironment :: JSONDecoder a Environment -decodeEnvironment = get >>= \json -> - case json of - String "" -> return mempty - Object xs -> foldM (flip add) mempty xs - _ -> fail $ "invalid context: " ++ show json +decodeEnvironment = foldr ($) mempty <$> jObjectWithKeys f <|> mempty <$ jString {- only accept "" -} where - add (k, String s) = return . insertRef (makeRef k) s - add (k, Number n) = return . insertRef (makeRef k) (show n) - add _ = fail "invalid item in context" + f k = g <$> jString <|> g . show <$> jInt + where + g = insertRef (makeRef k) decodeContext :: JSONDecoder a (Context a) -decodeContext = do - ex <- getExercise - inContext ex <$> decodeExpression +decodeContext = inContext <$> getExercise <*> decodeExpression decodeExpression :: JSONDecoder a a -decodeExpression = withJSONTerm $ \b -> getExercise >>= \ex -> get >>= f b ex - where - f True ex json = - case hasJSONView ex of - Just v -> matchM v json - Nothing -> fail "JSON encoding not supported by exercise" - f False ex json = - case json of - String s -> either fail return (parser ex s) - _ -> fail "Expecting a string when reading a term" \ No newline at end of file +decodeExpression = withJSONTerm $ \b -> + if b + then do + mv <- hasJSONView <$> getExercise + case mv of + Just v -> jNext (matchM v) + Nothing -> errorStr "JSON encoding not supported by exercise" + else do + ex <- getExercise + jString >>= either errorStr return . parser ex \ No newline at end of file diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index 2dd5a716..05409323 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -31,7 +31,7 @@ import Ideas.Text.MathML import Ideas.Text.OpenMath.Object import Ideas.Text.XML -type XMLDecoder a t = DecoderX a XML t +type XMLDecoder a t = DecoderX a String XML t xmlDecoder :: TypedDecoder a XML xmlDecoder tp = diff --git a/src/Ideas/Encoding/Encoder.hs b/src/Ideas/Encoding/Encoder.hs index bd7dd53b..aef42ce7 100644 --- a/src/Ideas/Encoding/Encoder.hs +++ b/src/Ideas/Encoding/Encoder.hs @@ -31,6 +31,7 @@ module Ideas.Encoding.Encoder import Control.Monad.Reader import Data.Maybe +import Data.String import Ideas.Common.Library import Ideas.Encoding.Options import Ideas.Encoding.Request @@ -46,37 +47,37 @@ import qualified Ideas.Text.JSON as JSON ------------------------------------------------------------------- -- Converter type class -getExercise :: DecoderX a s (Exercise a) +getExercise :: IsString err => DecoderX a err s (Exercise a) getExercise = reader fst -getOptions :: DecoderX a s Options +getOptions :: IsString err => DecoderX a err s Options getOptions = reader snd -getRequest :: DecoderX a s Request +getRequest :: IsString err => DecoderX a err s Request getRequest = request <$> getOptions -withExercise :: (Exercise a -> DecoderX a s t) -> DecoderX a s t +withExercise :: IsString err => (Exercise a -> DecoderX a err s t) -> DecoderX a err s t withExercise = (getExercise >>=) -getBaseUrl :: DecoderX a s String +getBaseUrl :: IsString err => DecoderX a err s String getBaseUrl = fromMaybe "https://ideas.science.uu.nl/" . baseUrl <$> getOptions -getQCGen :: DecoderX a s QCGen +getQCGen :: IsString err => DecoderX a err s QCGen getQCGen = fromMaybe (mkQCGen 0) . qcGen <$> getOptions -getScript :: DecoderX a s Script +getScript :: IsString err => DecoderX a err s Script getScript = script <$> getOptions -withOpenMath :: (Bool -> DecoderX a s t) -> DecoderX a s t +withOpenMath :: IsString err => (Bool -> DecoderX a err s t) -> DecoderX a err s t withOpenMath = (fmap useOpenMath getRequest >>=) -withJSONTerm :: (Bool -> DecoderX a s t) -> DecoderX a s t +withJSONTerm :: IsString err => (Bool -> DecoderX a err s t) -> DecoderX a err s t withJSONTerm = (fmap useJSONTerm getRequest >>=) -(//) :: Decoder env String s a -> s -> Decoder env String s2 a +(//) :: IsString err => Decoder env err s a -> s -> Decoder env err s2 a p // a = do env <- ask - either throwError return (runDecoder p env a) + either throwError return (evalDecoder p env a) ------------------------------------------------------------------- -- JSON terms @@ -183,6 +184,6 @@ encodeTyped p t1 tv@(_ ::: t2) = ((p, t1) fail ("Types do not match: " ++ sh ------------------------------------------------------------------- -- Decoder datatype -type DecoderX a = Decoder (Exercise a, Options) String +type DecoderX a = Decoder (Exercise a, Options) -type TypedDecoder a s = forall t . Type a t -> Decoder (Exercise a, Options) String s t \ No newline at end of file +type TypedDecoder a s = forall t . Type a t -> DecoderX a String s t \ No newline at end of file diff --git a/src/Ideas/Encoding/Evaluator.hs b/src/Ideas/Encoding/Evaluator.hs index 49c6eb70..5452d251 100644 --- a/src/Ideas/Encoding/Evaluator.hs +++ b/src/Ideas/Encoding/Evaluator.hs @@ -62,7 +62,7 @@ eval ex opts (Evaluator dec enc) b = rec rec (uncurry val ::: Pair t1 t2 :-> t3) -- functions t1 :-> t2 -> - case runDecoder (dec t1) env b of + case evalDecoder (dec t1) env b of Left msg -> fail msg Right a -> do res <- rec (val a ::: t2) diff --git a/src/Ideas/Encoding/NewDecoderJSON.hs b/src/Ideas/Encoding/NewDecoderJSON.hs index d9707d40..3ad33db0 100644 --- a/src/Ideas/Encoding/NewDecoderJSON.hs +++ b/src/Ideas/Encoding/NewDecoderJSON.hs @@ -17,83 +17,43 @@ module Ideas.Encoding.NewDecoderJSON ( JSONDecoder, jsonDecoder ) where -import Control.Monad.State (mplus, foldM, get, put) +import Control.Monad.State (get) import Data.Char import Ideas.Common.Library hiding (exerciseId, symbol) import Ideas.Common.Traversal.Navigator import Ideas.Encoding.Encoder +import Ideas.Encoding.Options import Ideas.Service.State import Ideas.Service.Types hiding (String) import Ideas.Text.JSON import qualified Ideas.Service.Types as Tp -type JSONDecoder a t = DecoderX a JSON t - -jsonDecoder :: TypedDecoder a JSON -jsonDecoder tp = - case tp of - Tag s t -> do - this <- get - case lookupM (map toLower s) this of - Just json -> do - put json - a <- jsonDecoder t - put this - return a - Nothing -> fail $ "Could not find " ++ s - Iso p t -> from p <$> jsonDecoder t - Pair t1 t2 -> do - a <- jsonDecoder t1 - b <- jsonDecoder t2 - return (a, b) - t1 :|: t2 -> - (Left <$> jsonDecoder t1) `mplus` - (Right <$> jsonDecoder t2) - Unit -> return () - Const t -> decodeConst t - _ -> fail $ "No support for argument type: " ++ show tp - -decodeConst :: Const a t -> JSONDecoder a t -decodeConst tp = - case tp of - State -> decodeState - Context -> decodeContext - Exercise -> getExercise - Environment -> decodeEnvironment - Location -> decodeLocation - --Term -> gets jsonToTerm - Script -> getScript - Int -> get >>= fromJSON - Tp.String -> get >>= fromJSON - Id -> decodeId - Rule -> decodeRule - QCGen -> getQCGen - _ -> fail $ "No support for argument type: " ++ show tp +type JSONDecoder a = GDecoderJSON (Exercise a, Options) +jsonDecoder :: Type a t -> DecoderX a String JSON t +jsonDecoder tp = do + env <- reader id + json <- get + case evalGDecoderJSON (jObject $ decodeType tp) env json of + Left err -> throwError (show err) + Right a -> return a -{- -jsonDecoder tp = get >>= \json -> - case json of - Array xs -> decodeType tp // xs - _ -> fail "expecting an array" - -decodeType :: Type a t -> DecoderX a [JSON] t +decodeType :: Type a t -> JSONDecoder a t decodeType tp = case tp of - Tag _ t -> decodeType t + Tag s t -> + jKey (map toLower s) $ decodeType t Iso p t -> from p <$> decodeType t Pair t1 t2 -> do a <- decodeType t1 b <- decodeType t2 return (a, b) t1 :|: t2 -> - (Left <$> decodeType t1) `mplus` - (Right <$> decodeType t2) + Left <$> decodeType t1 <|> + Right <$> decodeType t2 Unit -> return () - Const QCGen -> getQCGen - Const Script -> getScript - Const t -> symbol >>= \a -> decodeConst t // a - _ -> fail $ "No support for argument type: " ++ show tp + Const t -> decodeConst t + _ -> errorStr $ "No support for argument type: " ++ show tp decodeConst :: Const a t -> JSONDecoder a t decodeConst tp = @@ -103,228 +63,86 @@ decodeConst tp = Exercise -> getExercise Environment -> decodeEnvironment Location -> decodeLocation - Term -> gets jsonToTerm - Int -> get >>= fromJSON - Tp.String -> get >>= fromJSON + Script -> getScript + Int -> jInt + Tp.String -> jString Id -> decodeId Rule -> decodeRule - _ -> fail $ "No support for argument type: " ++ show tp - -decodeRule :: JSONDecoder a (Rule (Context a)) -decodeRule = do - ex <- getExercise - get >>= \json -> - case json of - String s -> getRule ex (newId s) - _ -> fail "expecting a string for rule" - -decodeId :: JSONDecoder a Id -decodeId = get >>= \json -> - case json of - String s -> return (newId s) - _ -> fail "expecting a string for id" - -decodeLocation :: JSONDecoder a Location -decodeLocation = get >>= \json -> - case json of - String s -> toLocation <$> readM s - _ -> fail "expecting a string for a location" --} -{- -{ "service" : "allfirsts" -, "source" : "test.logex" -, "state" : { - "exerciseid" : "logic.propositional.dnf" - , "prefix" : "[]" - , "context" : { - "term" : "~(~x || ~y)" - , "environment" : {} - , "location" : [] - } - , "userid" : null - , "session" : null - , "startterm" : null - } -} --} + QCGen -> getQCGen + _ -> errorStr $ "No support for argument type: " ++ show tp decodeState :: JSONDecoder a (State a) -decodeState = do - this <- get - case lookupM "state" this of - Nothing -> fail "expecting state" - Just json -> do - put json - ex <- getExercise - ps <- decodePaths - ctx <- decodeContext - let prf = maybe noPrefix (\x -> replayPaths x (strategy ex) ctx) ps - uid = searchId "userid" json - sid = searchId "sessionid" json - tid = searchId "taskid" json - put this - return $ (makeState ex prf ctx) - { stateUser = uid - , stateSession = sid - , stateStartTerm = tid - } - -searchId :: String -> JSON -> Maybe String -searchId str json = - case lookupM str json of - Just (String s) -> Just s - _ -> Nothing +decodeState = jKey "state" $ jObject $ do + ex <- getExercise + ps <- decodePaths + ctx <- decodeContext + let prf = maybe noPrefix (\x -> replayPaths x (strategy ex) ctx) ps + uid <- searchKey "userid" + sid <- searchKey "sessionid" + tid <- searchKey "taskid" + return $ (makeState ex prf ctx) + { stateUser = uid + , stateSession = sid + , stateStartTerm = tid + } + +searchKey :: String -> JSONDecoder a (Maybe String) +searchKey k = Just <$> jKey k jString <|> return Nothing decodePaths :: JSONDecoder a (Maybe [Path]) decodePaths = do - this <- get - case lookupM "prefix" this of - Just (String s) - | s ~= "noprefix" -> return Nothing - | otherwise -> Just <$> readPaths s - _ -> fail "expecting prefix" + s <- jKey "prefix" jString + if s ~= "noprefix" + then return Nothing + else Just <$> readPaths s where x ~= y = filter isAlphaNum (map toLower x) == y decodeContext :: JSONDecoder a (Context a) -decodeContext = do - this <- get - case lookupM "context" this of - Just json -> do - put json - ex <- getExercise - val <- decodeValue - env <- decodeEnvironment - loc <- decodeLocation - put this - return $ navigateTowards loc $ deleteRef locRef $ - setEnvironment env $ inContext ex val - _ -> fail $ "expecting context: " ++ show this +decodeContext = jKey "context" $ jObject $ do + ex <- getExercise + val <- decodeValue + env <- decodeEnvironment + loc <- decodeLocation + return $ navigateTowards loc $ deleteRef locRef $ + setEnvironment env $ inContext ex val decodeValue :: JSONDecoder a a -decodeValue = do - this <- get - ex <- getExercise - case lookupM "term" this of - Just json@(String s) -> - case parser ex s of - Left msg -> - case hasJSONView ex of - Just jv -> matchM jv json - Nothing -> fail msg - Right a -> return a - Just json -> - case hasJSONView ex of - Just jv -> matchM jv json - Nothing -> fail "No JSON decoder for term" - _ -> fail "Expecting term" +decodeValue = jKey "term" $ decodeParser <|> decodeJSON + where + decodeParser = do + ex <- getExercise + s <- jString + either errorStr return (parser ex s) + + decodeJSON = do + ex <- getExercise + case hasJSONView ex of + Just jv -> jNext $ maybe (Left "Could not decode term") Right . match jv + Nothing -> errorStr "No JSON decoder for term" decodeEnvironment :: JSONDecoder a Environment -decodeEnvironment = do - this <- get - case lookupM "environment" this of - Just (Object xs) -> foldM (flip add) mempty xs - _ -> fail "Expecting environment" +decodeEnvironment = jKey "environment" $ foldr ($) mempty <$> jObjectWithKeys f where - add (k, String s) = return . insertRef (makeRef k) s - add (k, Number n) = return . insertRef (makeRef k) (show n) - add _ = fail "invalid item in context" + f k = g <$> jString <|> g . show <$> jInt <|> g . show <$> jDouble + where + g = insertRef (makeRef k) decodeLocation :: JSONDecoder a Location -decodeLocation = do - this <- get - case lookupM "location" this of - Just (Array xs) -> toLocation <$> mapM f xs - _ -> fail "Expecting location" - where - f (Number (I n)) = return (fromInteger n) - f _ = fail "invalid int in location" +decodeLocation = jKey "location" $ + toLocation <$> jArrayOf jInt decodeRule :: JSONDecoder a (Rule (Context a)) decodeRule = do ex <- getExercise - get >>= \json -> - case lookupM "rule" json of - Just (String s) -> getRule ex (newId s) - _ -> fail "expecting a string for rule" + jKey "rule" $ do + rid <- newId <$> jString + case getRule ex rid of + Just a -> return a + Nothing -> errorStr ("unknown rule " ++ show rid) decodeId :: JSONDecoder a Id -- fix me -decodeId = do - get >>= \json -> - case lookupM "rule" json of - Just (String s) -> return (newId s) - _ -> fail "expecting a string for rule" - - - - - -- return (toLocation []) +decodeId = jKey "rule" $ newId <$> jString - {- - ex <- getExercise - get >>= \json -> - case json of - Array [a] -> put a >> decodeState - Array (String _code : pref : term : jsonContext : rest) -> do - pts <- decodePaths // pref - a <- decodeExpression // term - env <- decodeEnvironment // jsonContext - let loc = envToLoc env - ctx = navigateTowards loc $ deleteRef locRef $ - setEnvironment env $ inContext ex a - prfx = pts (strategy ex) ctx - case rest of - [] -> return $ makeState ex prfx ctx - [Array [String user, String session, String startterm]] -> - return (makeState ex prfx ctx) - { stateUser = Just user - , stateSession = Just session - , stateStartTerm = Just startterm - } - _ -> fail $ "invalid state" ++ show json - _ -> fail $ "invalid state" ++ show json - -envToLoc :: Environment -> Location -envToLoc env = toLocation $ fromMaybe [] $ locRef ? env >>= readM --} locRef :: Ref String locRef = makeRef "location" -{- -decodePaths :: JSONDecoder a (LabeledStrategy (Context a) -> Context a -> Prefix (Context a)) -decodePaths = - get >>= \json -> - case json of - String p - | p ~= "noprefix" -> return (\_ _ -> noPrefix) - | otherwise -> replayPaths <$> readPaths p - _ -> fail "invalid prefixes" - where - x ~= y = filter isAlphaNum (map toLower x) == y - -decodeEnvironment :: JSONDecoder a Environment -decodeEnvironment = get >>= \json -> - case json of - String "" -> return mempty - Object xs -> foldM (flip add) mempty xs - _ -> fail $ "invalid context: " ++ show json - where - add (k, String s) = return . insertRef (makeRef k) s - add (k, Number n) = return . insertRef (makeRef k) (show n) - add _ = fail "invalid item in context" - -decodeContext :: JSONDecoder a (Context a) -decodeContext = do - ex <- getExercise - inContext ex <$> decodeExpression - -decodeExpression :: JSONDecoder a a -decodeExpression = withJSONTerm $ \b -> getExercise >>= \ex -> get >>= f b ex - where - f True ex json = - case hasJSONView ex of - Just v -> matchM v json - Nothing -> fail "JSON encoding not supported by exercise" - f False ex json = - case json of - String s -> either fail return (parser ex s) - _ -> fail "Expecting a string when reading a term" -} \ No newline at end of file diff --git a/src/Ideas/Text/JSON/Decoder.hs b/src/Ideas/Text/JSON/Decoder.hs index e7540f2d..52deb28d 100644 --- a/src/Ideas/Text/JSON/Decoder.hs +++ b/src/Ideas/Text/JSON/Decoder.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -12,15 +11,16 @@ ----------------------------------------------------------------------------- module Ideas.Text.JSON.Decoder - ( EnvDecoderJSON, runEnvDecoderJSON, fromEnvDecoderJSON - , DecoderJSON, runDecoderJSON - , ErrorJSON - , jObject, jKey, jWithObject - , jArray, jWithArray + ( GDecoderJSON, evalGDecoderJSON + , DecoderJSON, evalDecoderJSON + , ErrorJSON, errorStr + , jObject, jKey, jWithKeys, jObjectWithKeys + , jArray, jArrayOf, jArray0, jArray1, jArray2, jArray3 , jString, jBool, jInteger, jInt, jDouble, jFloat - , jNull, jEmpty + , jNull, jEmpty, jSkip + , jNext -- re-exports - , Alternative(..), MonadReader(..) + , Alternative(..), MonadReader(..), throwError ) where import Control.Monad @@ -30,96 +30,111 @@ import Ideas.Utils.Decoding import Data.List import Data.String -newtype EnvDecoderJSON env a = DJ { fromEnvDecoderJSON :: Decoder env ErrorJSON (Loc, JSONBuilder) a } - deriving (Functor, Applicative, Alternative, Monad, MonadReader env) +type GDecoderJSON env = Decoder env ErrorJSON (Loc, JSONBuilder) -runEnvDecoderJSON :: EnvDecoderJSON env a -> env -> JSON -> Either ErrorJSON a -runEnvDecoderJSON p env json = runDecoder (fromEnvDecoderJSON p) env (Root 0, builder json) +evalGDecoderJSON :: GDecoderJSON env a -> env -> JSON -> Either ErrorJSON a +evalGDecoderJSON p env json = evalDecoder p env (Root 0, builder json) -type DecoderJSON = EnvDecoderJSON () +type DecoderJSON = GDecoderJSON () -runDecoderJSON :: DecoderJSON a -> JSON -> Either ErrorJSON a -runDecoderJSON p = runEnvDecoderJSON p () +evalDecoderJSON :: DecoderJSON a -> JSON -> Either ErrorJSON a +evalDecoderJSON p = evalGDecoderJSON p () -jObject :: EnvDecoderJSON env a -> EnvDecoderJSON env a -jObject p = jNext $ \loc a -> +jObject :: GDecoderJSON env a -> GDecoderJSON env a +jObject p = jFirst $ \loc a -> case a of - Just (Object xs) -> putDJ (loc, builderObject xs) >> p + Just (Object xs) -> put (loc, builderObject xs) >> p _ -> errorJSON NotAnObject loc a -jKey :: Key -> EnvDecoderJSON env a -> EnvDecoderJSON env a -jKey k p = getDJ >>= \(loc, xs) -> +jKey :: Key -> GDecoderJSON env a -> GDecoderJSON env a +jKey k p = get >>= \(loc, xs) -> case extractKey k xs of - Just (v, rest) -> putDJ (LocKey 0 k loc, builder v) *> p <* putDJ (loc, rest) + Just (v, rest) -> put (LocKey 0 k loc, builder v) *> p <* put (loc, rest) _ -> errorJSON (KeyNotFound k) loc (Just (toJSON xs)) -jWithObject :: (Key -> EnvDecoderJSON env a) -> EnvDecoderJSON env [a] -jWithObject g = jObject $ getDJ >>= \(loc, xs) -> - mapM (\(k, v) -> putDJ (LocKey 0 k loc, builder v) >> g k) (extractKeyAndValues xs) +jWithKeys :: (Key -> GDecoderJSON env a) -> GDecoderJSON env [a] +jWithKeys f = get >>= \(loc, xs) -> + mapM (\(k, v) -> put (LocKey 0 k loc, builder v) >> f k) (extractKeyAndValues xs) -jArray :: EnvDecoderJSON env a -> EnvDecoderJSON env a -jArray p = jNext $ \loc a -> +jObjectWithKeys :: (Key -> GDecoderJSON env a) -> GDecoderJSON env [a] +jObjectWithKeys = jObject . jWithKeys + +jArray :: GDecoderJSON env a -> GDecoderJSON env a +jArray p = jFirst $ \loc a -> case a of - Just (Array xs) -> putDJ (LocArray 0 loc, builderList xs) >> p + Just (Array xs) -> put (LocArray 0 loc, builderList xs) >> p _ -> errorJSON NotAnArray loc a -jWithArray :: EnvDecoderJSON env a -> EnvDecoderJSON env [a] -jWithArray p = jArray (many p <* jEmpty) +jArrayOf :: GDecoderJSON env a -> GDecoderJSON env [a] +jArrayOf p = jArray $ many p <* jEmpty + +jArray0 :: GDecoderJSON env () +jArray0 = jArray jEmpty + +jArray1 :: GDecoderJSON env a -> GDecoderJSON env a +jArray1 p = jArray $ p <* jEmpty -jString :: EnvDecoderJSON env String -jString = jNext $ \loc a -> +jArray2 :: (a -> b -> c) -> GDecoderJSON env a -> GDecoderJSON env b -> GDecoderJSON env c +jArray2 f p q = jArray $ f <$> p <*> q <* jEmpty + +jArray3 :: (a -> b -> c -> d) -> GDecoderJSON env a -> GDecoderJSON env b -> GDecoderJSON env c -> GDecoderJSON env d +jArray3 f p q r = jArray $ f <$> p <*> q <*> r <* jEmpty + +jString :: GDecoderJSON env String +jString = jFirst $ \loc a -> case a of Just (String s) -> return s _ -> errorJSON NotAString loc a -jBool :: EnvDecoderJSON env Bool -jBool = jNext $ \loc a -> +jBool :: GDecoderJSON env Bool +jBool = jFirst $ \loc a -> case a of Just (Boolean b) -> return b _ -> errorJSON NotABoolean loc a -jInteger :: EnvDecoderJSON env Integer -jInteger = jNext $ \loc a -> +jInteger :: GDecoderJSON env Integer +jInteger = jFirst $ \loc a -> case a of Just (Number (I i)) -> return i _ -> errorJSON NotAnInteger loc a -jInt :: EnvDecoderJSON env Int +jInt :: GDecoderJSON env Int jInt = fromInteger <$> jInteger -jDouble :: EnvDecoderJSON env Double -jDouble = jNext $ \loc a -> +jDouble :: GDecoderJSON env Double +jDouble = jFirst $ \loc a -> case a of Just (Number (D d)) -> return d _ -> errorJSON NotADouble loc a -jFloat :: EnvDecoderJSON env Float +jFloat :: GDecoderJSON env Float jFloat = realToFrac <$> jDouble -jNull :: EnvDecoderJSON env () -jNull = jNext $ \loc a -> +jNull :: GDecoderJSON env () +jNull = jFirst $ \loc a -> case a of Just (Null) -> return () _ -> errorJSON NotNull loc a -jEmpty :: EnvDecoderJSON env () -jEmpty = getDJ >>= \(loc, xs) -> +jEmpty :: GDecoderJSON env () +jEmpty = get >>= \(loc, xs) -> unless (isEmptyBuilder xs) (errorJSON NotEmpty loc (Just (toJSON xs))) --- local helper: not exported -jNext :: (Loc -> Maybe JSON -> EnvDecoderJSON env a) -> EnvDecoderJSON env a -jNext f = getDJ >>= \(loc, xs) -> - case extractFirst xs of - Just (json, rest) -> f loc (Just json) <* putDJ (nextLoc loc, rest) - _ -> f loc Nothing +jSkip :: GDecoderJSON env () +jSkip = jNext $ const $ return () --- local helper: not exported -getDJ :: EnvDecoderJSON env (Loc, JSONBuilder) -getDJ = DJ get +jNext :: (JSON -> Either String a) -> GDecoderJSON env a +jNext f = jFirst $ \loc mjson -> + case fmap f mjson of + Just res -> either errorStr return res + Nothing -> errorJSON NoNextElement loc Nothing -- local helper: not exported -putDJ :: (Loc, JSONBuilder) -> EnvDecoderJSON env () -putDJ = DJ . put +jFirst :: (Loc -> Maybe JSON -> GDecoderJSON env a) -> GDecoderJSON env a +jFirst f = get >>= \(loc, xs) -> + case extractFirst xs of + Just (json, rest) -> f loc (Just json) <* put (nextLoc loc, rest) + _ -> f loc Nothing -------------------------------------------------------------------------------- -- Errors @@ -140,7 +155,7 @@ instance Show ErrorJSON where data ErrorType = NotAnObject | NotAnArray | NotAString | NotABoolean | NotAnInteger | NotADouble - | NotNull | NotEmpty | KeyNotFound Key + | NotNull | NotEmpty | KeyNotFound Key | NoNextElement instance Show ErrorType where show NotAnObject = "not an object" @@ -151,7 +166,8 @@ instance Show ErrorType where show NotADouble = "not a double" show NotNull = "not null" show NotEmpty = "not empty" - show (KeyNotFound k) = "key '" ++ k ++ "'not found" + show (KeyNotFound k) = "key '" ++ k ++ "' not found" + show NoNextElement = "no next element" instance IsString ErrorJSON where fromString s = E [Left s] @@ -180,5 +196,8 @@ nextLoc (Root n) = Root (n+1) nextLoc (LocArray n l) = LocArray (n+1) l nextLoc (LocKey n k l) = LocKey (n+1) k l -errorJSON :: ErrorType -> Loc -> Maybe JSON -> EnvDecoderJSON env a -errorJSON tp loc a = DJ $ throwError $ E [Right (tp, loc, a)] \ No newline at end of file +errorStr :: String -> GDecoderJSON env a +errorStr = throwError . fromString + +errorJSON :: ErrorType -> Loc -> Maybe JSON -> GDecoderJSON env a +errorJSON tp loc a = throwError $ E [Right (tp, loc, a)] \ No newline at end of file diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 32c1efb1..538da162 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -12,7 +12,7 @@ ----------------------------------------------------------------------------- module Ideas.Utils.Decoding - ( Decoder, runDecoder, symbol + ( Decoder, evalDecoder, runDecoder, mapError , Encoder, runEncoder -- re-exports , Alternative(..), MonadReader(..), MonadState(..), MonadError(..) @@ -27,7 +27,7 @@ import Data.String ------------------------------------------------------------------- -newtype Decoder env err s a = Dec { runDec :: StateT s (ReaderT env (Except err)) a } +newtype Decoder env err s a = Dec { fromDec :: StateT s (ReaderT env (Except err)) a } deriving (Functor, Applicative, Alternative, MonadPlus, MonadReader env, MonadState s, MonadError err) instance Semigroup a => Semigroup (Decoder env err s a) where @@ -39,22 +39,26 @@ instance Monoid a => Monoid (Decoder env err s a) where instance IsString err => Monad (Decoder env err s) where return a = Dec (return a) - Dec m >>= f = Dec $ m >>= \a -> runDec (f a) + Dec m >>= f = Dec $ m >>= fromDec . f fail s = Dec $ throwError (fromString s) -- ! needed for backwards compatibility -symbol :: IsString err => Decoder env err [s] s -symbol = get >>= \list -> - case list of - [] -> fail "Empty input" - x:xs -> - put xs >> return x +runDecoder :: Decoder env err s a -> env -> s -> Either err (a, s) +runDecoder p env s = runExcept (runReaderT (runStateT (fromDec p) s) env) -runDecoder :: Decoder env err s a -> env -> s -> Either err a -runDecoder p env s = runExcept (runReaderT (evalStateT (runDec p) s) env) +evalDecoder :: Decoder env err s a -> env -> s -> Either err a +evalDecoder p env = fmap fst . runDecoder p env + +mapError :: IsString err2 => (err1 -> err2) -> Decoder env err1 s a -> Decoder env err2 s a +mapError f p = do + env <- reader id + s1 <- get + case runDecoder p env s1 of + Left e1 -> throwError (f e1) + Right (a, s2) -> put s2 >> return a ------------------------------------------------------------------- type Encoder env err = Decoder env err () runEncoder :: Encoder env err a -> env -> Either err a -runEncoder p env = runDecoder p env () \ No newline at end of file +runEncoder p env = evalDecoder p env () \ No newline at end of file From c5c294839cdb797aba51985a31a90557f0f38739 Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 24 Aug 2021 14:27:35 +0200 Subject: [PATCH 23/57] cleaning up Removing fail from Decoder and in readM/readPath(s) --- src/Ideas/Common/Strategy/Prefix.hs | 4 ++-- src/Ideas/Encoding/DecoderJSON.hs | 11 ++++++----- src/Ideas/Encoding/DecoderXML.hs | 4 ++-- src/Ideas/Encoding/Encoder.hs | 21 ++++++++++----------- src/Ideas/Encoding/NewDecoderJSON.hs | 8 +++----- src/Ideas/Text/XML.hs | 16 ++++++++-------- src/Ideas/Utils/Decoding.hs | 6 ++---- src/Ideas/Utils/Prelude.hs | 6 +++--- 8 files changed, 36 insertions(+), 40 deletions(-) diff --git a/src/Ideas/Common/Strategy/Prefix.hs b/src/Ideas/Common/Strategy/Prefix.hs index 023293bd..170323a5 100644 --- a/src/Ideas/Common/Strategy/Prefix.hs +++ b/src/Ideas/Common/Strategy/Prefix.hs @@ -196,8 +196,8 @@ instance Show Path where emptyPath :: Path emptyPath = Path [] -readPath :: Monad m => String -> m Path +readPath :: String -> Maybe Path readPath = fmap Path . readM -readPaths :: Monad m => String -> m [Path] +readPaths :: String -> Maybe [Path] readPaths = mapM readPath . splitsWithElem ';' \ No newline at end of file diff --git a/src/Ideas/Encoding/DecoderJSON.hs b/src/Ideas/Encoding/DecoderJSON.hs index 6359c0fb..16bd9957 100644 --- a/src/Ideas/Encoding/DecoderJSON.hs +++ b/src/Ideas/Encoding/DecoderJSON.hs @@ -121,11 +121,12 @@ locRef :: Ref String locRef = makeRef "location" decodePaths :: JSONDecoder a (LabeledStrategy (Context a) -> Context a -> Prefix (Context a)) -decodePaths = do - s <- jString - if (s ~= "noprefix") - then return (\_ _ -> noPrefix) - else replayPaths <$> readPaths s +decodePaths = jString >>= \s -> + case readPaths s of + _ | s ~= "noprefix" + -> return (\_ _ -> noPrefix) + Just ps -> return (replayPaths ps) + Nothing -> errorStr "invalid path" where x ~= y = filter isAlphaNum (map toLower x) == y diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index 05409323..4385a82b 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -113,7 +113,7 @@ decodePaths = do then return [emptyPath] else if prefixText ~= "no prefix" then return [] - else readPaths prefixText + else maybe (fail "invalid paths") return (readPaths prefixText) where a ~= b = g a == g b g = map toLower . filter (not . isSpace) @@ -181,7 +181,7 @@ decodeConfiguration = decodeChild "configuration" $ where decodeAction item = do guard (null (children item)) - action <- readM (name item) + action <- maybe (fail "invalid action") return $ readM (name item) cfgloc <- findAttribute "name" item return (action `byName` newId cfgloc) diff --git a/src/Ideas/Encoding/Encoder.hs b/src/Ideas/Encoding/Encoder.hs index aef42ce7..c69264cc 100644 --- a/src/Ideas/Encoding/Encoder.hs +++ b/src/Ideas/Encoding/Encoder.hs @@ -31,7 +31,6 @@ module Ideas.Encoding.Encoder import Control.Monad.Reader import Data.Maybe -import Data.String import Ideas.Common.Library import Ideas.Encoding.Options import Ideas.Encoding.Request @@ -47,34 +46,34 @@ import qualified Ideas.Text.JSON as JSON ------------------------------------------------------------------- -- Converter type class -getExercise :: IsString err => DecoderX a err s (Exercise a) +getExercise :: DecoderX a err s (Exercise a) getExercise = reader fst -getOptions :: IsString err => DecoderX a err s Options +getOptions :: DecoderX a err s Options getOptions = reader snd -getRequest :: IsString err => DecoderX a err s Request +getRequest :: DecoderX a err s Request getRequest = request <$> getOptions -withExercise :: IsString err => (Exercise a -> DecoderX a err s t) -> DecoderX a err s t +withExercise :: (Exercise a -> DecoderX a err s t) -> DecoderX a err s t withExercise = (getExercise >>=) -getBaseUrl :: IsString err => DecoderX a err s String +getBaseUrl :: DecoderX a err s String getBaseUrl = fromMaybe "https://ideas.science.uu.nl/" . baseUrl <$> getOptions -getQCGen :: IsString err => DecoderX a err s QCGen +getQCGen :: DecoderX a err s QCGen getQCGen = fromMaybe (mkQCGen 0) . qcGen <$> getOptions -getScript :: IsString err => DecoderX a err s Script +getScript :: DecoderX a err s Script getScript = script <$> getOptions -withOpenMath :: IsString err => (Bool -> DecoderX a err s t) -> DecoderX a err s t +withOpenMath :: (Bool -> DecoderX a err s t) -> DecoderX a err s t withOpenMath = (fmap useOpenMath getRequest >>=) -withJSONTerm :: IsString err => (Bool -> DecoderX a err s t) -> DecoderX a err s t +withJSONTerm :: (Bool -> DecoderX a err s t) -> DecoderX a err s t withJSONTerm = (fmap useJSONTerm getRequest >>=) -(//) :: IsString err => Decoder env err s a -> s -> Decoder env err s2 a +(//) :: Decoder env err s a -> s -> Decoder env err s2 a p // a = do env <- ask either throwError return (evalDecoder p env a) diff --git a/src/Ideas/Encoding/NewDecoderJSON.hs b/src/Ideas/Encoding/NewDecoderJSON.hs index 3ad33db0..9bfb5969 100644 --- a/src/Ideas/Encoding/NewDecoderJSON.hs +++ b/src/Ideas/Encoding/NewDecoderJSON.hs @@ -90,12 +90,10 @@ searchKey :: String -> JSONDecoder a (Maybe String) searchKey k = Just <$> jKey k jString <|> return Nothing decodePaths :: JSONDecoder a (Maybe [Path]) -decodePaths = do - s <- jKey "prefix" jString - if s ~= "noprefix" - then return Nothing - else Just <$> readPaths s +decodePaths = f <$> jKey "prefix" jString where + f s | s ~= "noprefix" = Nothing + | otherwise = readPaths s x ~= y = filter isAlphaNum (map toLower x) == y decodeContext :: JSONDecoder a (Context a) diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index 166bf9e6..b3cb1390 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -251,21 +251,21 @@ expecting s xml = ------------------------------------------------------------------------------- -- Decoding XML -decodeData :: IsString err => Decoder env err XML String +decodeData :: Decoder env String XML String decodeData = get >>= \xml -> case content xml of Left s:rest -> put xml {content = rest} >> return s - _ -> fail "Could not find data" + _ -> throwError "Could not find data" -decodeAttribute :: IsString err => String -> Decoder env err XML String +decodeAttribute :: String -> Decoder env String XML String decodeAttribute s = get >>= \xml -> case break hasName (attributes xml) of (xs, (_ := val):ys) -> put xml {attributes = xs ++ ys } >> return val - _ -> fail $ "Could not find attribute " ++ s + _ -> throwError $ "Could not find attribute " ++ s where hasName (n := _) = n == s -decodeChild :: IsString err => Name -> Decoder env err XML a -> Decoder env err XML a +decodeChild :: Name -> Decoder env String XML a -> Decoder env String XML a decodeChild s p = get >>= \xml -> case break hasName (content xml) of (xs, Right y:ys) -> do @@ -273,11 +273,11 @@ decodeChild s p = get >>= \xml -> a <- p put xml { content = xs ++ ys } return a - _ -> fail $ "Could not find child " ++ s + _ -> throwError $ "Could not find child " ++ s where hasName = either (const False) ((==s) . name) -decodeFirstChild :: IsString err => Name -> Decoder env err XML a -> Decoder env err XML a +decodeFirstChild :: Name -> Decoder env String XML a -> Decoder env String XML a decodeFirstChild s p = get >>= \xml -> case content xml of Right y:ys | name y == s -> do @@ -285,7 +285,7 @@ decodeFirstChild s p = get >>= \xml -> a <- p put xml { content = ys } return a - _ -> fail $ "Could not find first child " ++ s + _ -> throwError $ "Could not find first child " ++ s ------------------------------------------------------------------------------- -- Type classes for converting to/from XML diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 538da162..74c59fa4 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -23,7 +23,6 @@ import Control.Monad import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State -import Data.String ------------------------------------------------------------------- @@ -37,10 +36,9 @@ instance Monoid a => Monoid (Decoder env err s a) where mempty = pure mempty mappend = liftA2 mappend -instance IsString err => Monad (Decoder env err s) where +instance Monad (Decoder env err s) where return a = Dec (return a) Dec m >>= f = Dec $ m >>= fromDec . f - fail s = Dec $ throwError (fromString s) -- ! needed for backwards compatibility runDecoder :: Decoder env err s a -> env -> s -> Either err (a, s) runDecoder p env s = runExcept (runReaderT (runStateT (fromDec p) s) env) @@ -48,7 +46,7 @@ runDecoder p env s = runExcept (runReaderT (runStateT (fromDec p) s) env) evalDecoder :: Decoder env err s a -> env -> s -> Either err a evalDecoder p env = fmap fst . runDecoder p env -mapError :: IsString err2 => (err1 -> err2) -> Decoder env err1 s a -> Decoder env err2 s a +mapError :: (err1 -> err2) -> Decoder env err1 s a -> Decoder env err2 s a mapError f p = do env <- reader id s1 <- get diff --git a/src/Ideas/Utils/Prelude.hs b/src/Ideas/Utils/Prelude.hs index 6a808dbc..c58a20bb 100644 --- a/src/Ideas/Utils/Prelude.hs +++ b/src/Ideas/Utils/Prelude.hs @@ -51,10 +51,10 @@ readInt xs | otherwise = Just (foldl' (\a b -> a*10+ord b-48) 0 xs) -- ' {-# INLINE readM #-} -readM :: (Monad m, Read a) => String -> m a +readM :: Read a => String -> Maybe a readM s = case reads s of - [(a, xs)] | all isSpace xs -> return a - _ -> fail ("no read: " ++ s) + [(a, xs)] | all isSpace xs -> Just a + _ -> Nothing subsets :: [a] -> [[a]] subsets = foldr op [[]] From 5281acbfedfda547d659fb8529aa6c0e884f4b43 Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 24 Aug 2021 22:00:49 +0200 Subject: [PATCH 24/57] redesign for Text.JSON --- ideas.cabal | 2 + src/Ideas/Encoding/DecoderJSON.hs | 6 +- src/Ideas/Encoding/DecoderXML.hs | 9 +- src/Ideas/Encoding/ModeJSON.hs | 2 +- src/Ideas/Encoding/NewDecoderJSON.hs | 6 +- src/Ideas/Encoding/NewEncoderJSON.hs | 12 +-- src/Ideas/Encoding/NewModeJSON.hs | 2 +- src/Ideas/Text/JSON.hs | 6 +- src/Ideas/Text/JSON/Builder.hs | 32 ++---- src/Ideas/Text/JSON/Class.hs | 107 ++++++++++++++++++++ src/Ideas/Text/JSON/Data.hs | 145 --------------------------- src/Ideas/Text/JSON/Decoder.hs | 25 +++-- src/Ideas/Text/JSON/RPC.hs | 97 ++++++++++++++++++ src/Ideas/Utils/Decoding.hs | 1 + 14 files changed, 253 insertions(+), 199 deletions(-) create mode 100644 src/Ideas/Text/JSON/Class.hs create mode 100644 src/Ideas/Text/JSON/RPC.hs diff --git a/ideas.cabal b/ideas.cabal index 267f880a..f4fc5c42 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -162,8 +162,10 @@ Library Ideas.Text.HTML.W3CSS Ideas.Text.JSON Ideas.Text.JSON.Builder + Ideas.Text.JSON.Class Ideas.Text.JSON.Data Ideas.Text.JSON.Decoder + Ideas.Text.JSON.RPC Ideas.Text.Latex Ideas.Text.MathML Ideas.Text.OpenMath.Dictionary.Arith1 diff --git a/src/Ideas/Encoding/DecoderJSON.hs b/src/Ideas/Encoding/DecoderJSON.hs index 16bd9957..fe64d8a4 100644 --- a/src/Ideas/Encoding/DecoderJSON.hs +++ b/src/Ideas/Encoding/DecoderJSON.hs @@ -14,7 +14,7 @@ ----------------------------------------------------------------------------- module Ideas.Encoding.DecoderJSON - ( JSONDecoder, jsonDecoder + ( JSONDecoder, jsonTypeDecoder ) where import Control.Monad.State (get, gets) @@ -31,8 +31,8 @@ import qualified Ideas.Service.Types as Tp type JSONDecoder a = GDecoderJSON (Exercise a, Options) -jsonDecoder :: TypedDecoder a JSON -jsonDecoder tp = do +jsonTypeDecoder :: TypedDecoder a JSON +jsonTypeDecoder tp = do env <- reader id json <- get case evalGDecoderJSON (jArray (decodeType tp)) env json of diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index 4385a82b..fb8b70d4 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -37,9 +37,7 @@ xmlDecoder :: TypedDecoder a XML xmlDecoder tp = case tp of Tag s (Const String) -> - decodeChild s decodeData - `mplus` - decodeAttribute s + decodeChild s decodeData <|> decodeAttribute s Tag s t | s == "answer" -> decodeChild "answer" (xmlDecoder t) @@ -54,15 +52,14 @@ xmlDecoder tp = x <- xmlDecoder t xs <- xmlDecoder (List t) return (x:xs) - `mplus` + <|> return [] Pair t1 t2 -> do x <- xmlDecoder t1 y <- xmlDecoder t2 return (x, y) t1 :|: t2 -> - (Left <$> xmlDecoder t1) `mplus` - (Right <$> xmlDecoder t2) + Left <$> xmlDecoder t1 <|> Right <$> xmlDecoder t2 Unit -> return () Const ctp -> case ctp of diff --git a/src/Ideas/Encoding/ModeJSON.hs b/src/Ideas/Encoding/ModeJSON.hs index fb21e4d2..48eec7e0 100644 --- a/src/Ideas/Encoding/ModeJSON.hs +++ b/src/Ideas/Encoding/ModeJSON.hs @@ -114,4 +114,4 @@ myHandler opt1 dr request fun json = do evalService ex options jsonEvaluator srv json jsonEvaluator :: Evaluator a JSON JSON -jsonEvaluator = Evaluator jsonDecoder jsonEncoder \ No newline at end of file +jsonEvaluator = Evaluator jsonTypeDecoder jsonEncoder \ No newline at end of file diff --git a/src/Ideas/Encoding/NewDecoderJSON.hs b/src/Ideas/Encoding/NewDecoderJSON.hs index 9bfb5969..aa4f5de7 100644 --- a/src/Ideas/Encoding/NewDecoderJSON.hs +++ b/src/Ideas/Encoding/NewDecoderJSON.hs @@ -14,7 +14,7 @@ ----------------------------------------------------------------------------- module Ideas.Encoding.NewDecoderJSON - ( JSONDecoder, jsonDecoder + ( JSONDecoder, jsonTypeDecoder ) where import Control.Monad.State (get) @@ -30,8 +30,8 @@ import qualified Ideas.Service.Types as Tp type JSONDecoder a = GDecoderJSON (Exercise a, Options) -jsonDecoder :: Type a t -> DecoderX a String JSON t -jsonDecoder tp = do +jsonTypeDecoder :: Type a t -> DecoderX a String JSON t +jsonTypeDecoder tp = do env <- reader id json <- get case evalGDecoderJSON (jObject $ decodeType tp) env json of diff --git a/src/Ideas/Encoding/NewEncoderJSON.hs b/src/Ideas/Encoding/NewEncoderJSON.hs index 2bc71b06..2f081ae3 100644 --- a/src/Ideas/Encoding/NewEncoderJSON.hs +++ b/src/Ideas/Encoding/NewEncoderJSON.hs @@ -39,7 +39,7 @@ jsonEncoder tv@(val ::: tp) = Tp.Tag s t | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis tv | s == "ApplyResult" -> encodeTyped encodeApplyResult Apply.tApplyResult tv - | otherwise -> tagJSON (map toLower s) <$> jsonEncoder (val ::: t) + | otherwise -> (map toLower s .=) <$> jsonEncoder (val ::: t) Tp.Unit -> pure mempty Const ctp -> jsonEncodeConst (val ::: ctp) _ -> fail $ "Cannot encode type: " ++ show tp @@ -54,10 +54,10 @@ jsonEncodeConst (val ::: tp) = State -> encodeState val SomeExercise -> case val of Some ex -> pure (exerciseInfo ex) - Text -> pure $ builder (show val) - Tp.String -> pure $ builder val - Tp.Int -> pure $ builder val - Tp.Bool -> pure $ builder val + Text -> pure $ jsonBuilder (show val) + Tp.String -> pure $ jsonBuilder val + Tp.Int -> pure $ jsonBuilder val + Tp.Bool -> pure $ jsonBuilder val _ -> fail $ "Type " ++ show tp ++ " not supported in JSON" encodeRule :: Rule (Context a) -> EncoderX a JSONBuilder @@ -102,7 +102,7 @@ encodeState st = , "sessionid" .= get stateSession , "taskid" .= get stateStartTerm ] - in (tagJSON "state" . make) <$> (encodeContext ctx) + in ("state" .=) . make <$> encodeContext ctx encodeDiagnosis :: Diagnose.Diagnosis a -> EncoderX a JSONBuilder encodeDiagnosis diagnosis = diff --git a/src/Ideas/Encoding/NewModeJSON.hs b/src/Ideas/Encoding/NewModeJSON.hs index 9c5a5d67..79a0e20c 100644 --- a/src/Ideas/Encoding/NewModeJSON.hs +++ b/src/Ideas/Encoding/NewModeJSON.hs @@ -123,4 +123,4 @@ myHandler opt1 dr request fun json = do evalService ex options jsonEvaluator srv json jsonEvaluator :: Evaluator a JSON JSONBuilder -jsonEvaluator = Evaluator jsonDecoder jsonEncoder \ No newline at end of file +jsonEvaluator = Evaluator jsonTypeDecoder jsonEncoder \ No newline at end of file diff --git a/src/Ideas/Text/JSON.hs b/src/Ideas/Text/JSON.hs index 4bcaa3ef..08c86bd2 100644 --- a/src/Ideas/Text/JSON.hs +++ b/src/Ideas/Text/JSON.hs @@ -17,8 +17,12 @@ module Ideas.Text.JSON ( module Ideas.Text.JSON.Data , module Ideas.Text.JSON.Builder , module Ideas.Text.JSON.Decoder + , module Ideas.Text.JSON.Class + , module Ideas.Text.JSON.RPC ) where import Ideas.Text.JSON.Builder import Ideas.Text.JSON.Data -import Ideas.Text.JSON.Decoder \ No newline at end of file +import Ideas.Text.JSON.Decoder +import Ideas.Text.JSON.Class +import Ideas.Text.JSON.RPC \ No newline at end of file diff --git a/src/Ideas/Text/JSON/Builder.hs b/src/Ideas/Text/JSON/Builder.hs index 470b3aa9..e60c8204 100644 --- a/src/Ideas/Text/JSON/Builder.hs +++ b/src/Ideas/Text/JSON/Builder.hs @@ -11,8 +11,8 @@ ----------------------------------------------------------------------------- module Ideas.Text.JSON.Builder - ( JSONBuilder, arrayBuilder, (.=), tagJSON, builder - , builderList, builderObject, isEmptyBuilder + ( JSONBuilder, arrayBuilder, jsonToBuilder, tagJSON, builderToJSON + , isEmptyBuilder , extractFirst, extractKey, extractKeyAndValues ) where @@ -24,35 +24,20 @@ import Ideas.Text.JSON.Data newtype JSONBuilder = JB [(Maybe Key, JSON)] -instance InJSON JSONBuilder where - toJSON = builderToJSON - fromJSON = return . builder - instance Semigroup JSONBuilder where JB xs <> JB ys = JB (xs <> ys) instance Monoid JSONBuilder where mempty = JB [] -arrayBuilder :: [JSONBuilder] -> JSONBuilder -arrayBuilder = builder . Array . map builderToJSON - -infix 7 .= - -(.=) :: InJSON a => String -> a -> JSONBuilder -s .= a = JB [(Just s, toJSON a)] +jsonToBuilder :: JSON -> JSONBuilder +jsonToBuilder a = JB [(Nothing, a)] -tagJSON :: InJSON a => String -> a -> JSONBuilder -tagJSON = (.=) +tagJSON :: String -> JSON -> JSONBuilder +tagJSON s a = JB [(Just s, a)] -builder :: InJSON a => a -> JSONBuilder -builder a = JB [(Nothing, toJSON a)] - -builderList :: InJSON a => [a] -> JSONBuilder -builderList = mconcat . map builder - -builderObject :: InJSON a => [(Key, a)] -> JSONBuilder -builderObject = mconcat . map (uncurry (.=)) +arrayBuilder :: [JSONBuilder] -> JSONBuilder +arrayBuilder = jsonToBuilder . Array . map builderToJSON isEmptyBuilder :: JSONBuilder -> Bool isEmptyBuilder (JB xs) = null xs @@ -70,7 +55,6 @@ extractKey k (JB xs) = extractKeyAndValues :: JSONBuilder -> [(Key, JSON)] extractKeyAndValues (JB xs) = [ (k, a) | (mk, a) <- xs, k <- maybeToList mk ] --- local helper builderToJSON :: JSONBuilder -> JSON builderToJSON (JB [(Nothing, x)]) = x builderToJSON (JB xs) = diff --git a/src/Ideas/Text/JSON/Class.hs b/src/Ideas/Text/JSON/Class.hs new file mode 100644 index 00000000..0e073d7f --- /dev/null +++ b/src/Ideas/Text/JSON/Class.hs @@ -0,0 +1,107 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +module Ideas.Text.JSON.Class ( InJSON(..), (.=) ) where + +import Control.Monad.State +import Ideas.Text.JSON.Builder +import Ideas.Text.JSON.Data +import Ideas.Text.JSON.Decoder + +class InJSON a where + toJSON :: a -> JSON + listToJSON :: [a] -> JSON + jsonBuilder :: a -> JSONBuilder + jsonListBuilder :: [a] -> JSONBuilder + fromJSON :: Monad m => JSON -> m a + listFromJSON :: Monad m => JSON -> m [a] + jsonDecoder :: DecoderJSON a + jsonListDecoder :: DecoderJSON [a] + + {-# MINIMAL (toJSON | jsonBuilder), jsonDecoder #-} + + -- default definitions + toJSON = builderToJSON . jsonBuilder + listToJSON = Array . map toJSON + + jsonBuilder = jsonToBuilder . toJSON + jsonListBuilder = mconcat . map jsonBuilder + + fromJSON = either (fail . show) return . evalDecoderJSON jsonDecoder + + listFromJSON (Array xs) = mapM fromJSON xs + listFromJSON _ = fail "expecting an array" + + jsonDecoder = gets snd >>= either throwError return . fromJSON . builderToJSON + jsonListDecoder = jArrayOf jsonDecoder + +instance InJSON Int where + toJSON = toJSON . toInteger + jsonDecoder = jInt + +instance InJSON Integer where + toJSON = Number . I + jsonDecoder = jInteger + +instance InJSON Double where + toJSON = Number . D + jsonDecoder = jDouble + +instance InJSON Char where + toJSON c = String [c] + listToJSON = String + jsonListBuilder = jsonToBuilder . String + fromJSON (String [c]) = return c + fromJSON _ = fail "expecting a string" + listFromJSON (String s) = return s + listFromJSON _ = fail "expecting a string" + jsonDecoder = jChar + jsonListDecoder = jString + +instance InJSON Bool where + toJSON = Boolean + jsonDecoder = jBool + +instance InJSON a => InJSON [a] where + toJSON = listToJSON + jsonBuilder = jsonListBuilder + fromJSON = listFromJSON + jsonDecoder = jsonListDecoder + +instance InJSON () where + jsonBuilder = mempty + jsonDecoder = return () + +instance (InJSON a, InJSON b) => InJSON (a, b) where + jsonBuilder (a, b) = jsonBuilder a <> jsonBuilder b + jsonDecoder = (,) <$> jsonDecoder <*> jsonDecoder + +instance (InJSON a, InJSON b, InJSON c) => InJSON (a, b, c) where + jsonBuilder (a, b, c) = jsonBuilder a <> jsonBuilder b <> jsonBuilder c + jsonDecoder = (,,) <$> jsonDecoder <*> jsonDecoder <*> jsonDecoder + +instance (InJSON a, InJSON b, InJSON c, InJSON d) => InJSON (a, b, c, d) where + jsonBuilder (a, b, c, d) = jsonBuilder a <> jsonBuilder b <> jsonBuilder c <> jsonBuilder d + jsonDecoder = (,,,) <$> jsonDecoder <*> jsonDecoder <*> jsonDecoder <*> jsonDecoder + +instance InJSON JSON where + toJSON = id + jsonDecoder = gets (builderToJSON . snd) + +instance InJSON JSONBuilder where + jsonBuilder = id + jsonDecoder = gets snd + +infix 7 .= + +(.=) :: InJSON a => String -> a -> JSONBuilder +s .= a = tagJSON s (toJSON a) \ No newline at end of file diff --git a/src/Ideas/Text/JSON/Data.hs b/src/Ideas/Text/JSON/Data.hs index 2c1bb8f4..f284dd38 100644 --- a/src/Ideas/Text/JSON/Data.hs +++ b/src/Ideas/Text/JSON/Data.hs @@ -12,19 +12,15 @@ module Ideas.Text.JSON.Data ( JSON(..), Key, Number(..) -- types - , InJSON(..) -- type class , lookupM , parseJSON, compactJSON -- parser and pretty-printers - , jsonRPC, RPCHandler, RPCRequest(..), RPCResponse(..) ) where -import Control.Exception import Control.Monad import Data.List (intersperse) import Data.Maybe import Data.String import Ideas.Utils.Parsing hiding (string, char) -import System.IO.Error import Test.QuickCheck import Text.PrettyPrint.Leijen hiding ((<$>)) import qualified Ideas.Text.UTF8 as UTF8 @@ -95,66 +91,6 @@ escape = concatMap f . fromMaybe "invalid UTF8 string" . UTF8.encodeM f '\\' = "\\\\" f c = [c] -class InJSON a where - toJSON :: a -> JSON - listToJSON :: [a] -> JSON - fromJSON :: Monad m => JSON -> m a - listFromJSON :: Monad m => JSON -> m [a] - -- default definitions - listToJSON = Array . map toJSON - listFromJSON (Array xs) = mapM fromJSON xs - listFromJSON _ = fail "expecting an array" - -instance InJSON Int where - toJSON = toJSON . toInteger - fromJSON = fmap fromInteger . fromJSON - -instance InJSON Integer where - toJSON = Number . I - fromJSON (Number (I n)) = return n - fromJSON _ = fail "expecting a number" - -instance InJSON Double where - toJSON = Number . D - fromJSON (Number (D n)) = return n - fromJSON _ = fail "expecting a number" - -instance InJSON Char where - toJSON c = String [c] - listToJSON = String - fromJSON (String [c]) = return c - fromJSON _ = fail "expecting a string" - listFromJSON (String s) = return s - listFromJSON _ = fail "expecting a string" - -instance InJSON Bool where - toJSON = Boolean - fromJSON (Boolean b) = return b - fromJSON _ = fail "expecting a boolean" - -instance InJSON a => InJSON [a] where - toJSON = listToJSON - fromJSON = listFromJSON - -instance (InJSON a, InJSON b) => InJSON (a, b) where - toJSON (a, b) = Array [toJSON a, toJSON b] - fromJSON (Array [a, b]) = (,) <$> fromJSON a <*> fromJSON b - fromJSON _ = fail "expecting an array with 2 elements" - -instance (InJSON a, InJSON b, InJSON c) => InJSON (a, b, c) where - toJSON (a, b, c) = Array [toJSON a, toJSON b, toJSON c] - fromJSON (Array [a, b, c]) = (,,) <$> fromJSON a <*> fromJSON b <*> fromJSON c - fromJSON _ = fail "expecting an array with 3 elements" - -instance (InJSON a, InJSON b, InJSON c, InJSON d) => InJSON (a, b, c, d) where - toJSON (a, b, c, d) = Array [toJSON a, toJSON b, toJSON c, toJSON d] - fromJSON (Array [a, b, c, d]) = (,,,) <$> fromJSON a <*> fromJSON b <*> fromJSON c <*> fromJSON d - fromJSON _ = fail "expecting an array with 4 elements" - -instance InJSON JSON where - toJSON = id - fromJSON = return - -------------------------------------------------------- -- Parser @@ -179,91 +115,10 @@ parseJSON = parseSimple json lexer = P.makeTokenParser $ emptyDef { reservedNames = ["true", "false", "null"] } --------------------------------------------------------- --- JSON-RPC - -data RPCRequest = Request - { requestMethod :: String - , requestParams :: JSON - , requestId :: JSON - } - -data RPCResponse = Response - { responseResult :: JSON - , responseError :: JSON - , responseId :: JSON - } - -instance Show RPCRequest where - show = show . toJSON - -instance Show RPCResponse where - show = show . toJSON - -instance InJSON RPCRequest where - toJSON req = Object - [ ("method", String $ requestMethod req) - , ("params", requestParams req) - , ("id" , requestId req) - ] - fromJSON json = - case lookupM "method" json of - Just (String s) -> - let pj = fromMaybe Null (lookupM "params" json) - ij = fromMaybe Null (lookupM "id" json) - in return (Request s pj ij) - Just _ -> fail "expecting a string as method" - Nothing -> fail "no method specified" - -instance InJSON RPCResponse where - toJSON resp = Object - [ ("result", responseResult resp) - , ("error" , responseError resp) - , ("id" , responseId resp) - ] - fromJSON obj = do - rj <- lookupM "result" obj - ej <- lookupM "error" obj - ij <- lookupM "id" obj - return (Response rj ej ij) - -okResponse :: JSON -> JSON -> RPCResponse -okResponse x y = Response - { responseResult = x - , responseError = Null - , responseId = y - } - -errorResponse :: JSON -> JSON -> RPCResponse -errorResponse x y = Response - { responseResult = Null - , responseError = x - , responseId = y - } - lookupM :: Monad m => String -> JSON -> m JSON lookupM x (Object xs) = maybe (fail $ "field " ++ x ++ " not found") return (lookup x xs) lookupM _ _ = fail "expecting a JSON object" --------------------------------------------------------- --- JSON-RPC over HTTP - -type RPCHandler = String -> JSON -> IO JSON - -jsonRPC :: JSON -> RPCHandler -> IO RPCResponse -jsonRPC input rpc = - case fromJSON input of - Nothing -> return (errorResponse (String "Invalid request") Null) - Just req -> do - json <- rpc (requestMethod req) (requestParams req) - return (okResponse json (requestId req)) - `catch` handler req - where - handler :: RPCRequest -> SomeException -> IO RPCResponse - handler req e = - let msg = maybe (show e) ioeGetErrorString (fromException e) - in return $ errorResponse (toJSON msg) (requestId req) - -------------------------------------------------------- -- Testing parser/pretty-printer diff --git a/src/Ideas/Text/JSON/Decoder.hs b/src/Ideas/Text/JSON/Decoder.hs index 52deb28d..20eef9db 100644 --- a/src/Ideas/Text/JSON/Decoder.hs +++ b/src/Ideas/Text/JSON/Decoder.hs @@ -16,7 +16,7 @@ module Ideas.Text.JSON.Decoder , ErrorJSON, errorStr , jObject, jKey, jWithKeys, jObjectWithKeys , jArray, jArrayOf, jArray0, jArray1, jArray2, jArray3 - , jString, jBool, jInteger, jInt, jDouble, jFloat + , jString, jChar, jBool, jInteger, jInt, jDouble, jFloat , jNull, jEmpty, jSkip , jNext -- re-exports @@ -33,7 +33,7 @@ import Data.String type GDecoderJSON env = Decoder env ErrorJSON (Loc, JSONBuilder) evalGDecoderJSON :: GDecoderJSON env a -> env -> JSON -> Either ErrorJSON a -evalGDecoderJSON p env json = evalDecoder p env (Root 0, builder json) +evalGDecoderJSON p env json = evalDecoder p env (Root 0, jsonToBuilder json) type DecoderJSON = GDecoderJSON () @@ -43,18 +43,18 @@ evalDecoderJSON p = evalGDecoderJSON p () jObject :: GDecoderJSON env a -> GDecoderJSON env a jObject p = jFirst $ \loc a -> case a of - Just (Object xs) -> put (loc, builderObject xs) >> p + Just (Object xs) -> put (loc, mconcat $ map (uncurry tagJSON) xs) >> p _ -> errorJSON NotAnObject loc a jKey :: Key -> GDecoderJSON env a -> GDecoderJSON env a jKey k p = get >>= \(loc, xs) -> case extractKey k xs of - Just (v, rest) -> put (LocKey 0 k loc, builder v) *> p <* put (loc, rest) - _ -> errorJSON (KeyNotFound k) loc (Just (toJSON xs)) + Just (v, rest) -> put (LocKey 0 k loc, jsonToBuilder v) *> p <* put (loc, rest) + _ -> errorJSON (KeyNotFound k) loc (Just (builderToJSON xs)) jWithKeys :: (Key -> GDecoderJSON env a) -> GDecoderJSON env [a] jWithKeys f = get >>= \(loc, xs) -> - mapM (\(k, v) -> put (LocKey 0 k loc, builder v) >> f k) (extractKeyAndValues xs) + mapM (\(k, v) -> put (LocKey 0 k loc, jsonToBuilder v) >> f k) (extractKeyAndValues xs) jObjectWithKeys :: (Key -> GDecoderJSON env a) -> GDecoderJSON env [a] jObjectWithKeys = jObject . jWithKeys @@ -62,7 +62,7 @@ jObjectWithKeys = jObject . jWithKeys jArray :: GDecoderJSON env a -> GDecoderJSON env a jArray p = jFirst $ \loc a -> case a of - Just (Array xs) -> put (LocArray 0 loc, builderList xs) >> p + Just (Array xs) -> put (LocArray 0 loc, mconcat $ map jsonToBuilder xs) >> p _ -> errorJSON NotAnArray loc a jArrayOf :: GDecoderJSON env a -> GDecoderJSON env [a] @@ -86,6 +86,12 @@ jString = jFirst $ \loc a -> Just (String s) -> return s _ -> errorJSON NotAString loc a +jChar :: GDecoderJSON env Char +jChar = jFirst $ \loc a -> + case a of + Just (String [c]) -> return c + _ -> errorJSON NotAChar loc a + jBool :: GDecoderJSON env Bool jBool = jFirst $ \loc a -> case a of @@ -118,7 +124,7 @@ jNull = jFirst $ \loc a -> jEmpty :: GDecoderJSON env () jEmpty = get >>= \(loc, xs) -> - unless (isEmptyBuilder xs) (errorJSON NotEmpty loc (Just (toJSON xs))) + unless (isEmptyBuilder xs) (errorJSON NotEmpty loc (Just (builderToJSON xs))) jSkip :: GDecoderJSON env () jSkip = jNext $ const $ return () @@ -154,13 +160,14 @@ instance Show ErrorJSON where ] data ErrorType - = NotAnObject | NotAnArray | NotAString | NotABoolean | NotAnInteger | NotADouble + = NotAnObject | NotAnArray | NotAString | NotAChar | NotABoolean | NotAnInteger | NotADouble | NotNull | NotEmpty | KeyNotFound Key | NoNextElement instance Show ErrorType where show NotAnObject = "not an object" show NotAnArray = "not an array" show NotAString = "not a string" + show NotAChar = "not a char" show NotABoolean = "not a boolean" show NotAnInteger = "not an integer" show NotADouble = "not a double" diff --git a/src/Ideas/Text/JSON/RPC.hs b/src/Ideas/Text/JSON/RPC.hs new file mode 100644 index 00000000..4b6ff807 --- /dev/null +++ b/src/Ideas/Text/JSON/RPC.hs @@ -0,0 +1,97 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +module Ideas.Text.JSON.RPC + ( jsonRPC, RPCHandler, RPCRequest(..), RPCResponse(..) + ) where + +import Control.Exception +import Ideas.Text.JSON.Data +import Ideas.Text.JSON.Class +import Ideas.Text.JSON.Decoder +import System.IO.Error + +-------------------------------------------------------- +-- JSON-RPC + +data RPCRequest = Request + { requestMethod :: String + , requestParams :: JSON + , requestId :: JSON + } + +data RPCResponse = Response + { responseResult :: JSON + , responseError :: JSON + , responseId :: JSON + } + +instance InJSON RPCRequest where + toJSON req = Object + [ ("method", String $ requestMethod req) + , ("params", requestParams req) + , ("id" , requestId req) + ] + jsonDecoder = jObject $ + Request <$> jKey "method" jString + <*> (jKey "params" (jNext Right) <|> pure Null) + <*> (jKey "id" (jNext Right) <|> pure Null) + +instance InJSON RPCResponse where + toJSON resp = Object + [ ("result", responseResult resp) + , ("error" , responseError resp) + , ("id" , responseId resp) + ] + jsonDecoder = jObject $ + Response <$> jKey "result" (jNext Right) + <*> jKey "error" (jNext Right) + <*> jKey "id" (jNext Right) + +instance Show RPCRequest where + show = show . toJSON + +instance Show RPCResponse where + show = show . toJSON + +okResponse :: JSON -> JSON -> RPCResponse +okResponse x y = Response + { responseResult = x + , responseError = Null + , responseId = y + } + +errorResponse :: JSON -> JSON -> RPCResponse +errorResponse x y = Response + { responseResult = Null + , responseError = x + , responseId = y + } + +-------------------------------------------------------- +-- JSON-RPC over HTTP + +type RPCHandler = String -> JSON -> IO JSON + +jsonRPC :: JSON -> RPCHandler -> IO RPCResponse +jsonRPC input rpc = + case fromJSON input of + Nothing -> return (errorResponse (String "Invalid request") Null) + Just req -> do + json <- rpc (requestMethod req) (requestParams req) + return (okResponse json (requestId req)) + `catch` handler req + where + handler :: RPCRequest -> SomeException -> IO RPCResponse + handler req e = + let msg = maybe (show e) ioeGetErrorString (fromException e) + in return $ errorResponse (toJSON msg) (requestId req) \ No newline at end of file diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 74c59fa4..18a5f601 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -16,6 +16,7 @@ module Ideas.Utils.Decoding , Encoder, runEncoder -- re-exports , Alternative(..), MonadReader(..), MonadState(..), MonadError(..) + , gets ) where import Control.Applicative From 2c94ea6fed0b593f698d0a57273d4b092cc695cf Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 24 Aug 2021 22:22:33 +0200 Subject: [PATCH 25/57] removing Number from JSON datatype --- src/Ideas/Encoding/Encoder.hs | 12 ++++++------ src/Ideas/Text/JSON/Class.hs | 4 ++-- src/Ideas/Text/JSON/Data.hs | 24 +++++++++--------------- src/Ideas/Text/JSON/Decoder.hs | 4 ++-- 4 files changed, 19 insertions(+), 25 deletions(-) diff --git a/src/Ideas/Encoding/Encoder.hs b/src/Ideas/Encoding/Encoder.hs index c69264cc..1de7df7c 100644 --- a/src/Ideas/Encoding/Encoder.hs +++ b/src/Ideas/Encoding/Encoder.hs @@ -105,9 +105,9 @@ termToJSON term = | s == objectSymbol -> Object (f ts) | otherwise -> Object [("_apply", Array (JSON.String (show s):map termToJSON ts))] TList xs -> Array (map termToJSON xs) - TNum n -> Number (I n) - TFloat d -> Number (D d) - TMeta n -> Object [("_meta", Number (I (toInteger n)))] + TNum n -> Integer n + TFloat d -> Double d + TMeta n -> Object [("_meta", Integer (toInteger n))] where f [] = [] f (TVar s:x:xs) = (s, termToJSON x) : f xs @@ -116,12 +116,12 @@ termToJSON term = jsonToTerm :: JSON -> Term jsonToTerm json = case json of - Number (I n) -> TNum n - Number (D d) -> TFloat d + Integer n -> TNum n + Double d -> TFloat d JSON.String s -> TVar s Boolean b -> Term.symbol (if b then trueSymbol else falseSymbol) Array xs -> TList (map jsonToTerm xs) - Object [("_meta", Number (I n))] -> TMeta (fromInteger n) + Object [("_meta", Integer n)] -> TMeta (fromInteger n) Object [("_apply", Array (JSON.String s:xs))] -> TCon (newSymbol s) (map jsonToTerm xs) Object xs -> TCon objectSymbol (concatMap f xs) Null -> Term.symbol nullSymbol diff --git a/src/Ideas/Text/JSON/Class.hs b/src/Ideas/Text/JSON/Class.hs index 0e073d7f..f9182b89 100644 --- a/src/Ideas/Text/JSON/Class.hs +++ b/src/Ideas/Text/JSON/Class.hs @@ -49,11 +49,11 @@ instance InJSON Int where jsonDecoder = jInt instance InJSON Integer where - toJSON = Number . I + toJSON = Integer jsonDecoder = jInteger instance InJSON Double where - toJSON = Number . D + toJSON = Double jsonDecoder = jDouble instance InJSON Char where diff --git a/src/Ideas/Text/JSON/Data.hs b/src/Ideas/Text/JSON/Data.hs index f284dd38..0118ccd8 100644 --- a/src/Ideas/Text/JSON/Data.hs +++ b/src/Ideas/Text/JSON/Data.hs @@ -11,9 +11,9 @@ ----------------------------------------------------------------------------- module Ideas.Text.JSON.Data - ( JSON(..), Key, Number(..) -- types + ( JSON(..), Key -- types , lookupM - , parseJSON, compactJSON -- parser and pretty-printers + , parseJSON, compactJSON -- parser and pretty-printers ) where import Control.Monad @@ -27,7 +27,8 @@ import qualified Ideas.Text.UTF8 as UTF8 import qualified Text.ParserCombinators.Parsec.Token as P data JSON - = Number Number -- integer, real, or floating point + = Integer Integer -- integer, ... + | Double Double -- ... real, or floating point | String String -- double-quoted Unicode with backslash escapement | Boolean Bool -- true and false | Array [JSON] -- ordered sequence (comma-separated, square brackets) @@ -37,12 +38,6 @@ data JSON type Key = String -data Number = I Integer | D Double deriving Eq - -instance Show Number where - show (I n) = show n - show (D d) = show d - instance Show JSON where show = show . prettyJSON False @@ -57,7 +52,8 @@ prettyJSON compact = rec where rec json = case json of - Number n -> text (show n) + Integer n -> text (show n) + Double d -> text (show d) String s -> str (escape s) Boolean b -> text (if b then "true" else "false") Null -> text "null" @@ -102,7 +98,7 @@ parseJSON = parseSimple json [ Null <$ P.reserved lexer "null" , Boolean True <$ P.reserved lexer "true" , Boolean False <$ P.reserved lexer "false" - , Number . either I D <$> naturalOrFloat -- redefined in Ideas.Text.Parsing + , either Integer Double <$> naturalOrFloat -- redefined in Ideas.Text.Parsing , String <$> P.stringLiteral lexer , Array <$> P.brackets lexer (sepBy json (P.comma lexer)) , Object <$> P.braces lexer (sepBy keyValue (P.comma lexer)) @@ -125,13 +121,11 @@ lookupM _ _ = fail "expecting a JSON object" instance Arbitrary JSON where arbitrary = sized arbJSON -instance Arbitrary Number where - arbitrary = oneof [ I <$> arbitrary, D . fromInteger <$> arbitrary ] - arbJSON :: Int -> Gen JSON arbJSON n | n == 0 = oneof - [ Number <$> arbitrary, String <$> myStringGen + [ Integer <$> arbitrary, Double . fromInteger <$> arbitrary + , String <$> myStringGen , Boolean <$> arbitrary, return Null ] | otherwise = oneof diff --git a/src/Ideas/Text/JSON/Decoder.hs b/src/Ideas/Text/JSON/Decoder.hs index 20eef9db..b6b8f177 100644 --- a/src/Ideas/Text/JSON/Decoder.hs +++ b/src/Ideas/Text/JSON/Decoder.hs @@ -101,7 +101,7 @@ jBool = jFirst $ \loc a -> jInteger :: GDecoderJSON env Integer jInteger = jFirst $ \loc a -> case a of - Just (Number (I i)) -> return i + Just (Integer i) -> return i _ -> errorJSON NotAnInteger loc a jInt :: GDecoderJSON env Int @@ -110,7 +110,7 @@ jInt = fromInteger <$> jInteger jDouble :: GDecoderJSON env Double jDouble = jFirst $ \loc a -> case a of - Just (Number (D d)) -> return d + Just (Double d) -> return d _ -> errorJSON NotADouble loc a jFloat :: GDecoderJSON env Float From 3de9dda79ed6f0009740c679325eab0f6b12404a Mon Sep 17 00:00:00 2001 From: Heeren Date: Fri, 27 Aug 2021 12:46:45 +0200 Subject: [PATCH 26/57] cleaning up functions that use Monads for fail --- .travis.yml | 8 ++++---- src/Ideas/Common/Classes.hs | 8 ++------ src/Ideas/Common/Rewriting/AutoTerm.hs | 6 ++++-- src/Ideas/Main/Default.hs | 3 +-- src/Ideas/Text/JSON/Class.hs | 24 ++++++------------------ src/Ideas/Utils/Prelude.hs | 26 -------------------------- 6 files changed, 17 insertions(+), 58 deletions(-) diff --git a/.travis.yml b/.travis.yml index cc90c483..18cc4525 100644 --- a/.travis.yml +++ b/.travis.yml @@ -71,9 +71,9 @@ matrix: compiler: ": #GHC 8.6.5" addons: {apt: {packages: [cabal-install-2.4,ghc-8.6.5], sources: [hvr-ghc]}} - #- env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 - # compiler: ": #GHC 8.8.4" - # addons: {apt: {packages: [cabal-install-2.4,ghc-8.8.4], sources: [hvr-ghc]}} + - env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 + compiler: ": #GHC 8.8.4" + addons: {apt: {packages: [cabal-install-2.4,ghc-8.8.4], sources: [hvr-ghc]}} # Build with the newest GHC and cabal-install. This is an accepted failure, # see below. @@ -127,7 +127,7 @@ matrix: #os: osx allow_failures: - #- env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 + - env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 #- env: BUILD=cabal GHCVER=head CABALVER=head HAPPYVER=1.19.5 ALEXVER=3.1.7 #- env: BUILD=stack ARGS="--resolver nightly" #- env: BUILD=stack ARGS="--resolver lts-6" diff --git a/src/Ideas/Common/Classes.hs b/src/Ideas/Common/Classes.hs index 593c5b47..9b6fdef9 100644 --- a/src/Ideas/Common/Classes.hs +++ b/src/Ideas/Common/Classes.hs @@ -14,7 +14,7 @@ module Ideas.Common.Classes ( -- * Type class Apply - Apply(applyAll), apply, applicable, applyD, applyM, applyList + Apply(applyAll), apply, applicable, applyD, applyList -- * Type class Container , Container(singleton, getSingleton) -- * Type class BiArrow @@ -54,12 +54,8 @@ applicable ta = isJust . apply ta applyD :: Apply t => t a -> a -> a applyD ta a = fromMaybe a (apply ta a) --- | Same as apply, except that the result (at most one) is returned in some monad -applyM :: (Apply t, Monad m) => t a -> a -> m a -applyM ta = maybe (fail "applyM") return . apply ta - applyList :: Apply t => [t a] -> a -> Maybe a -applyList xs a = foldl (\m r -> m >>= applyM r) (Just a) xs +applyList xs a = foldl (\m r -> m >>= apply r) (Just a) xs ----------------------------------------------------------- -- Type class Container diff --git a/src/Ideas/Common/Rewriting/AutoTerm.hs b/src/Ideas/Common/Rewriting/AutoTerm.hs index 5e67b6f9..d262cac2 100644 --- a/src/Ideas/Common/Rewriting/AutoTerm.hs +++ b/src/Ideas/Common/Rewriting/AutoTerm.hs @@ -15,7 +15,6 @@ module Ideas.Common.Rewriting.AutoTerm (toTermG, fromTermG, testTermFor) where import Control.Monad.State import Data.Data import Ideas.Common.Rewriting.Term -import Ideas.Utils.Prelude (headM) toTermG :: Data a => a -> Term toTermG a = @@ -78,7 +77,10 @@ constructors = dataTypeConstrs . dataTypeOf . fromProxy findConstr :: (Monad m, Data a) => Proxy a -> Symbol -> m Constr findConstr p s = - headM [ c | c <- constructors p, s == constrSymbol c ] + case [ c | c <- constructors p, s == constrSymbol c ] of + [] -> fail "Autoterm.findConstr" + hd:_ -> return hd + fromTermG :: (MonadPlus m, Data a) => Term -> m a fromTermG term = diff --git a/src/Ideas/Main/Default.hs b/src/Ideas/Main/Default.hs index e33b85c8..c87fd1f5 100644 --- a/src/Ideas/Main/Default.hs +++ b/src/Ideas/Main/Default.hs @@ -148,8 +148,7 @@ processDatabase :: DomainReasoner -> FilePath -> IO () processDatabase dr database = do (n, time) <- getDiffTime $ do rows <- Log.selectFrom database "requests" ["input"] $ \row -> do - txt <- headM row - (_, out, _) <- process mempty dr txt + (_, out, _) <- process mempty dr (head row) putStrLn out return (length rows) putStrLn $ "processed " ++ show n ++ " requests in " ++ show time diff --git a/src/Ideas/Text/JSON/Class.hs b/src/Ideas/Text/JSON/Class.hs index f9182b89..ad61eca9 100644 --- a/src/Ideas/Text/JSON/Class.hs +++ b/src/Ideas/Text/JSON/Class.hs @@ -20,10 +20,9 @@ import Ideas.Text.JSON.Decoder class InJSON a where toJSON :: a -> JSON listToJSON :: [a] -> JSON + fromJSON :: JSON -> Maybe a jsonBuilder :: a -> JSONBuilder jsonListBuilder :: [a] -> JSONBuilder - fromJSON :: Monad m => JSON -> m a - listFromJSON :: Monad m => JSON -> m [a] jsonDecoder :: DecoderJSON a jsonListDecoder :: DecoderJSON [a] @@ -32,16 +31,10 @@ class InJSON a where -- default definitions toJSON = builderToJSON . jsonBuilder listToJSON = Array . map toJSON + fromJSON = either (fail . show) return . evalDecoderJSON jsonDecoder jsonBuilder = jsonToBuilder . toJSON - jsonListBuilder = mconcat . map jsonBuilder - - fromJSON = either (fail . show) return . evalDecoderJSON jsonDecoder - - listFromJSON (Array xs) = mapM fromJSON xs - listFromJSON _ = fail "expecting an array" - - jsonDecoder = gets snd >>= either throwError return . fromJSON . builderToJSON + jsonListBuilder = mconcat . map jsonBuilder jsonListDecoder = jArrayOf jsonDecoder instance InJSON Int where @@ -57,14 +50,10 @@ instance InJSON Double where jsonDecoder = jDouble instance InJSON Char where - toJSON c = String [c] - listToJSON = String + toJSON c = String [c] + listToJSON = String jsonListBuilder = jsonToBuilder . String - fromJSON (String [c]) = return c - fromJSON _ = fail "expecting a string" - listFromJSON (String s) = return s - listFromJSON _ = fail "expecting a string" - jsonDecoder = jChar + jsonDecoder = jChar jsonListDecoder = jString instance InJSON Bool where @@ -74,7 +63,6 @@ instance InJSON Bool where instance InJSON a => InJSON [a] where toJSON = listToJSON jsonBuilder = jsonListBuilder - fromJSON = listFromJSON jsonDecoder = jsonListDecoder instance InJSON () where diff --git a/src/Ideas/Utils/Prelude.hs b/src/Ideas/Utils/Prelude.hs index c58a20bb..78b87fcc 100644 --- a/src/Ideas/Utils/Prelude.hs +++ b/src/Ideas/Utils/Prelude.hs @@ -22,9 +22,6 @@ module Ideas.Utils.Prelude , splitAtElem, splitsWithElem , timedSeconds, getDiffTime , fst3, snd3, thd3 - , headM, findIndexM - , elementAt, changeAt, replaceAt - , list , mwhen, munless ) where @@ -132,29 +129,6 @@ snd3 (_, x, _) = x thd3 :: (a, b, c) -> c thd3 (_, _, x) = x --- generalized list functions (results in monad) -headM :: Monad m => [a] -> m a -headM (a:_) = return a -headM _ = fail "headM" - -findIndexM :: Monad m => (a -> Bool) -> [a] -> m Int -findIndexM p = maybe (fail "findIndexM") return . findIndex p - -elementAt :: Monad m => Int -> [a] -> m a -elementAt i = headM . drop i - -changeAt :: Monad m => Int -> (a -> a) -> [a] -> m [a] -changeAt i f as = - case splitAt i as of - (xs, y:ys) -> return (xs ++ f y : ys) - _ -> fail "changeAt" - -replaceAt :: Monad m => Int -> a -> [a] -> m [a] -replaceAt i = changeAt i . const - -list :: b -> ([a] -> b) -> [a] -> b -list b f xs = if null xs then b else f xs - -- Monoids mwhen :: Monoid a => Bool -> a -> a From 36d99f8b59c4602d2f4aa073fe508795e5ebb79a Mon Sep 17 00:00:00 2001 From: Heeren Date: Fri, 27 Aug 2021 16:27:35 +0200 Subject: [PATCH 27/57] Maybe type instead of fail --- ideas.cabal | 2 +- src/Ideas/Common/Context.hs | 12 +++++------- src/Ideas/Common/Exercise.hs | 7 +++---- src/Ideas/Encoding/DecoderXML.hs | 5 +++-- src/Ideas/Utils/Parsing.hs | 4 ++-- 5 files changed, 14 insertions(+), 16 deletions(-) diff --git a/ideas.cabal b/ideas.cabal index f4fc5c42..4c8be927 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -53,7 +53,7 @@ Library blaze-builder >= 0.4, bytestring, case-insensitive, - QuickCheck >= 2.8 && < 2.12, + QuickCheck >= 2.8 && < 2.14, Diff, containers, directory, diff --git a/src/Ideas/Common/Context.hs b/src/Ideas/Common/Context.hs index ba2c47b2..a4305e39 100644 --- a/src/Ideas/Common/Context.hs +++ b/src/Ideas/Common/Context.hs @@ -48,14 +48,13 @@ data Context a = C , getNavigator :: ContextNavigator a } -fromContext :: Monad m => Context a -> m a -fromContext = maybe (fail "fromContext") return . - currentNavigator . getNavigator . top +fromContext :: Context a -> Maybe a +fromContext = currentNavigator . getNavigator . top -fromContextWith :: Monad m => (a -> b) -> Context a -> m b +fromContextWith :: (a -> b) -> Context a -> Maybe b fromContextWith f = fmap f . fromContext -fromContextWith2 :: Monad m => (a -> b -> c) -> Context a -> Context b -> m c +fromContextWith2 :: (a -> b -> c) -> Context a -> Context b -> Maybe c fromContextWith2 f a b = f <$> fromContext a <*> fromContext b instance Eq a => Eq (Context a) where @@ -101,8 +100,7 @@ data ContextNavigator a where Simple :: Uniplate a => UniplateNavigator a -> ContextNavigator a NoNav :: a -> ContextNavigator a -liftCN :: Monad m => (forall b . Navigator b => b -> m b) - -> Context a -> m (Context a) +liftCN :: (forall b . Navigator b => b -> Maybe b) -> Context a -> Maybe (Context a) liftCN f (C env (TermNav a)) = C env . TermNav <$> f a liftCN f (C env (Simple a)) = C env . Simple <$> f a liftCN _ (C _ (NoNav _)) = fail "noNavigator" diff --git a/src/Ideas/Common/Exercise.hs b/src/Ideas/Common/Exercise.hs index 75c90f48..a1cd1df0 100644 --- a/src/Ideas/Common/Exercise.hs +++ b/src/Ideas/Common/Exercise.hs @@ -204,12 +204,11 @@ ruleset ex = nub (sortBy (ruleOrdering ex) list) list = extraRules ex ++ rulesInStrategy (strategy ex) -- | Finds a rule of an exercise based on its identifier. -getRule :: Monad m => Exercise a -> Id -> m (Rule (Context a)) +getRule :: Exercise a -> Id -> Maybe (Rule (Context a)) getRule ex a = case filter ((a ==) . getId) (ruleset ex) of - [hd] -> return hd - [] -> fail $ "Could not find ruleid " ++ showId a - _ -> fail $ "Ambiguous ruleid " ++ showId a + [hd] -> Just hd + _ -> Nothing -- | Makes a rule ordering based on a list of values with identifiers (e.g., -- a list of rules). Rules with identifiers that are not in the list are diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index fb8b70d4..b1b68e31 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -85,8 +85,9 @@ xmlDecoder tp = -- decodeRule :: XMLDecoder a (Rule (Context a)) decodeRule = decodeChild "ruleid" $ do - ex <- getExercise - get >>= getRule ex . newId . getData + ex <- getExercise + xml <- get + maybe (fail "invalid rule") return . getRule ex . newId . getData $ xml -- decodeLocation :: XMLDecoder a Location diff --git a/src/Ideas/Utils/Parsing.hs b/src/Ideas/Utils/Parsing.hs index 21224cb0..8df838f6 100644 --- a/src/Ideas/Utils/Parsing.hs +++ b/src/Ideas/Utils/Parsing.hs @@ -54,7 +54,7 @@ naturalOrFloat = do '-':xs -> return (Left (negate (readInt xs))) xs -> return (Left (readInt xs)) [(d, [])] -> return (Right d) - _ -> fail "not a float" + _ -> unexpected "not a float" where nat = many1 digit num = maybe id (:) <$> optionMaybe (char '-') <*> nat @@ -68,7 +68,7 @@ float = do c <- option "" ((:) <$> oneOf "eE" <*> num) case reads (a++b++c) of [(d, [])] -> return d - _ -> fail "not a float" + _ -> unexpected "not a float" where nat = many1 digit num = (:) <$> char '-' <*> nat From 99eda29958f6a17977a102bba051cedf44eb5407 Mon Sep 17 00:00:00 2001 From: Heeren Date: Fri, 3 Sep 2021 16:19:24 +0200 Subject: [PATCH 28/57] splitting Term interface, removing Monad/fail instances --- ideas.cabal | 3 + src/Ideas/Common/Rewriting/Difference.hs | 2 +- src/Ideas/Common/Rewriting/Term.hs | 320 +-------------------- src/Ideas/Common/Rewriting/Term/Class.hs | 258 +++++++++++++++++ src/Ideas/Common/Rewriting/Term/Data.hs | 84 ++++++ src/Ideas/Common/Rewriting/Term/Decoder.hs | 102 +++++++ src/Ideas/Encoding/DecoderXML.hs | 17 +- src/Ideas/Encoding/EncoderXML.hs | 6 +- src/Ideas/Encoding/OpenMathSupport.hs | 26 +- src/Ideas/Utils/Decoding.hs | 1 + 10 files changed, 481 insertions(+), 338 deletions(-) create mode 100644 src/Ideas/Common/Rewriting/Term/Class.hs create mode 100644 src/Ideas/Common/Rewriting/Term/Data.hs create mode 100644 src/Ideas/Common/Rewriting/Term/Decoder.hs diff --git a/ideas.cabal b/ideas.cabal index 4c8be927..884afb22 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -93,6 +93,9 @@ Library Ideas.Common.Rewriting.RewriteRule Ideas.Common.Rewriting.Substitution Ideas.Common.Rewriting.Term + Ideas.Common.Rewriting.Term.Class + Ideas.Common.Rewriting.Term.Data + Ideas.Common.Rewriting.Term.Decoder Ideas.Common.Rewriting.Unification Ideas.Common.Rule Ideas.Common.Rule.Abstract diff --git a/src/Ideas/Common/Rewriting/Difference.hs b/src/Ideas/Common/Rewriting/Difference.hs index 21652ac9..9044b93c 100644 --- a/src/Ideas/Common/Rewriting/Difference.hs +++ b/src/Ideas/Common/Rewriting/Difference.hs @@ -49,7 +49,7 @@ diffTerm p q = [one] -> Just one _ -> here -getFunctionA :: (Monad m, WithFunctions a) => a -> m (Symbol, [a]) +getFunctionA :: WithFunctions a => a -> Maybe (Symbol, [a]) getFunctionA a = f <$> getFunction a where f (s, xs) = (s, if isAssociative s then collectSym s a else xs) diff --git a/src/Ideas/Common/Rewriting/Term.hs b/src/Ideas/Common/Rewriting/Term.hs index 05060b16..9bf03236 100644 --- a/src/Ideas/Common/Rewriting/Term.hs +++ b/src/Ideas/Common/Rewriting/Term.hs @@ -1,4 +1,3 @@ -{-# OPTIONS -fno-warn-orphans #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -9,321 +8,16 @@ -- Stability : provisional -- Portability : portable (depends on ghc) -- --- A simple data type for term rewriting +-- Generic terms -- ----------------------------------------------------------------------------- module Ideas.Common.Rewriting.Term - ( -- * Symbols - Symbol, newSymbol - , isAssociative, makeAssociative - , nothingSymbol, trueSymbol, falseSymbol - -- * Terms - , Term(..), IsTerm(..), termView - , fromTermM, fromTermWith - -- * Functions and symbols - , WithFunctions(..), isSymbol, isFunction - , unary, binary, ternary, isUnary, isBinary - -- * Variables - , WithVars(..), isVariable - , vars, varSet, hasVar, withoutVar - , hasSomeVar, hasNoVar, variableView - -- * Meta variables - , WithMetaVars(..), isMetaVar - , metaVars, metaVarSet, hasMetaVar, nextMetaVar + ( module Ideas.Common.Rewriting.Term.Data + , module Ideas.Common.Rewriting.Term.Decoder + , module Ideas.Common.Rewriting.Term.Class ) where -import Control.Monad -import Data.Function -import Data.Maybe -import Ideas.Common.Id -import Ideas.Common.View -import Ideas.Utils.Prelude (ShowString(..)) -import Ideas.Utils.QuickCheck hiding (function) -import Ideas.Utils.Uniplate -import qualified Data.IntSet as IS -import qualified Data.Map as M -import qualified Data.Set as S - ------------------------------------------------------------ --- Symbols - -data Symbol = S { isAssociative :: Bool, symbolId :: Id } - -instance Eq Symbol where - (==) = (==) `on` getId -- without associativity property - -instance Ord Symbol where - compare = compareId -- without associativity property - -instance Show Symbol where - show = showId - -instance Read Symbol where - readsPrec n = map f . readsPrec n - where - f :: (Id, String) -> (Symbol, String) - f (a, s) = (newSymbol a, s) - -instance HasId Symbol where - getId = symbolId - changeId f (S b a) = S b (f a) - -newSymbol :: IsId a => a -> Symbol -newSymbol = S False . newId - -makeAssociative :: Symbol -> Symbol -makeAssociative (S _ a) = S True a - ------------------------------------------------------------ --- * Data type for terms - -data Term = TVar String - | TCon Symbol [Term] - | TList [Term] - | TNum Integer - | TFloat Double - | TMeta Int - deriving (Show, Read, Eq, Ord) - -instance Uniplate Term where - uniplate (TCon x xs) = plate (function x) ||* xs - uniplate (TList xs) = plate TList ||* xs - uniplate term = plate term - ------------------------------------------------------------ --- * Type class for conversion to/from terms - -class IsTerm a where - toTerm :: a -> Term - toTermList :: [a] -> Term - fromTerm :: MonadPlus m => Term -> m a - fromTermList :: MonadPlus m => Term -> m [a] - -- default implementation - toTermList = TList . map toTerm - fromTermList (TList xs) = mapM fromTerm xs - fromTermList _ = fail "fromTermList: not a list" - -termView :: IsTerm a => View Term a -termView = makeView fromTerm toTerm - -instance IsTerm Term where - toTerm = id - fromTerm = return - -instance IsTerm ShowString where - toTerm = TVar . fromShowString - fromTerm (TVar s) = return (ShowString s) - fromTerm _ = fail "fromTerm" - -instance (IsTerm a, IsTerm b) => IsTerm (a, b) where - toTerm (a, b) = TList [toTerm a, toTerm b] - fromTerm (TList [a, b]) = (,) <$> fromTerm a <*> fromTerm b - fromTerm _ = fail "fromTerm" - -instance (IsTerm a, IsTerm b, IsTerm c) => IsTerm (a, b, c) where - toTerm (a, b, c) = TList [toTerm a, toTerm b, toTerm c] - fromTerm (TList [a, b, c]) = (,,) <$> fromTerm a <*> fromTerm b <*> fromTerm c - fromTerm _ = fail "fromTerm" - -instance (IsTerm a, IsTerm b) => IsTerm (Either a b) where - toTerm = either toTerm toTerm - fromTerm expr = - fmap Left (fromTerm expr) `mplus` - fmap Right (fromTerm expr) - -instance IsTerm Int where - toTerm = TNum . fromIntegral - fromTerm = fmap fromInteger . fromTerm - -instance IsTerm Integer where - toTerm = TNum - fromTerm (TNum a) = return a - fromTerm _ = fail "fromTerm" - -instance IsTerm Double where - toTerm = TFloat - fromTerm (TFloat a) = return a - fromTerm _ = fail "fromTerm" - -instance IsTerm Char where - toTerm c = TVar [c] - toTermList = TVar - fromTerm (TVar [c]) = return c - fromTerm _ = fail "fromTerm: not a TVar" - fromTermList (TVar s) = return s - fromTermList _ = fail "fromTermList: not a TVar" - -instance IsTerm Bool where - toTerm True = symbol trueSymbol - toTerm False = symbol falseSymbol - fromTerm (TCon s []) - | s == trueSymbol = return True - | s == falseSymbol = return False - fromTerm _ = fail "fromTerm: not a Bool" - -instance IsTerm Id where - toTerm = toTerm . show - fromTerm = fmap (newId :: String -> Id) . fromTerm - -instance IsTerm a => IsTerm [a] where - toTerm = toTermList - fromTerm = fromTermList - -instance (IsTerm a, Ord a) => IsTerm (S.Set a) where - toTerm = toTerm . S.toList - fromTerm = fmap S.fromList . fromTerm - -instance (IsTerm a, IsTerm b, Ord a) => IsTerm (M.Map a b) where - toTerm = toTerm . M.toList - fromTerm = fmap M.fromList . fromTerm - -trueSymbol, falseSymbol, nothingSymbol :: Symbol -trueSymbol = newSymbol "true" -falseSymbol = newSymbol "false" -nothingSymbol = newSymbol "Nothing" - -instance IsTerm a => IsTerm (Maybe a) where - toTerm = maybe (symbol nothingSymbol) toTerm - fromTerm (TCon s []) | s == nothingSymbol = return Nothing - fromTerm t = fmap Just (fromTerm t) - -fromTermM :: (Monad m, IsTerm a) => Term -> m a -fromTermM = maybe (fail "fromTermM") return . fromTerm - -fromTermWith :: (Monad m, IsTerm a) => (Symbol -> [a] -> m a) -> Term -> m a -fromTermWith f a = do - (s, xs) <- getFunction a - ys <- mapM fromTermM xs - f s ys - ------------------------------------------------------------ --- * Functions and symbols - -class WithFunctions a where - -- constructing - symbol :: Symbol -> a - function :: Symbol -> [a] -> a - -- matching - getSymbol :: Monad m => a -> m Symbol - getFunction :: Monad m => a -> m (Symbol, [a]) - -- default definition - symbol s = function s [] - getSymbol a = - case getFunction a of - Just (t, []) -> return t - _ -> fail "Ideas.Common.Term.getSymbol" - -instance WithFunctions Term where - function = TCon - getFunction (TCon s xs) = return (s, xs) - getFunction _ = fail "Ideas.Common.Rewriting.getFunction" - -isSymbol :: WithFunctions a => Symbol -> a -> Bool -isSymbol s = (== Just s) . getSymbol - -isFunction :: (WithFunctions a, Monad m) => Symbol -> a -> m [a] -isFunction s a = - case getFunction a of - Just (t, as) | s == t -> return as - _ -> fail "Ideas.Common.Term.isFunction" - -unary :: WithFunctions a => Symbol -> a -> a -unary s a = function s [a] - -binary :: WithFunctions a => Symbol -> a -> a -> a -binary s a b = function s [a, b] - -ternary :: WithFunctions a => Symbol -> a -> a -> a -> a -ternary s a b c = function s [a, b, c] - -isUnary :: (WithFunctions a, Monad m) => Symbol -> a -> m a -isUnary s a = - case isFunction s a of - Just [x] -> return x - _ -> fail "Ideas.Common.Term.isUnary" - -isBinary :: (WithFunctions a, Monad m) => Symbol -> a -> m (a, a) -isBinary s a = - case isFunction s a of - Just [x, y] -> return (x, y) - _ -> fail "Ideas.Common.Term.isBinary" - ------------------------------------------------------------ --- * Variables - -class WithVars a where - variable :: String -> a - getVariable :: Monad m => a -> m String - -instance WithVars Term where - variable = TVar - getVariable (TVar s) = return s - getVariable _ = fail "Ideas.Common.Rewriting.getVariable" - -isVariable :: WithVars a => a -> Bool -isVariable = isJust . getVariable - -vars :: (Uniplate a, WithVars a) => a -> [String] -vars = concatMap getVariable . universe - -varSet :: (Uniplate a, WithVars a) => a -> S.Set String -varSet = S.fromList . vars - -hasVar :: (Uniplate a, WithVars a) => String -> a -> Bool -hasVar i = (i `elem`) . vars - -withoutVar :: (Uniplate a, WithVars a) => String -> a -> Bool -withoutVar i = not . hasVar i - -hasSomeVar :: (Uniplate a, WithVars a) => a -> Bool -hasSomeVar = not . hasNoVar - -hasNoVar :: (Uniplate a, WithVars a) => a -> Bool -hasNoVar = null . vars - -variableView :: WithVars a => View a String -variableView = makeView getVariable variable - ------------------------------------------------------------ --- * Meta variables - -class WithMetaVars a where - metaVar :: Int -> a - getMetaVar :: Monad m => a -> m Int - -instance WithMetaVars Term where - metaVar = TMeta - getMetaVar (TMeta i) = return i - getMetaVar _ = fail "Ideas.Common.Rewriting.getMetaVar" - -isMetaVar :: WithMetaVars a => a -> Bool -isMetaVar = isJust . getMetaVar - -metaVars :: (Uniplate a, WithMetaVars a) => a -> [Int] -metaVars = concatMap getMetaVar . universe - -metaVarSet :: (Uniplate a, WithMetaVars a) => a -> IS.IntSet -metaVarSet = IS.fromList . metaVars - -hasMetaVar :: (Uniplate a, WithMetaVars a) => Int -> a -> Bool -hasMetaVar i = (i `elem`) . metaVars - -nextMetaVar :: (Uniplate a, WithMetaVars a) => a -> Int -nextMetaVar a - | null is = 0 - | otherwise = maximum is + 1 - where - is = metaVars a - ------------------------------------------------------------ --- * Arbitrary term generator - -instance Arbitrary Term where - arbitrary = generators - [ constGens $ map TVar ["x", "y", "z"] - , arbGen TNum, arbGen TFloat, arbGen TMeta - , constGens $ map (symbol . newSymbol) ["a", "b"] - , unaryGens $ map (unary . newSymbol) ["h", "k"] - , binaryGens $ map (binary . newSymbol) ["f", "g"] - ] \ No newline at end of file +import Ideas.Common.Rewriting.Term.Data +import Ideas.Common.Rewriting.Term.Decoder hiding (Alternative(..)) +import Ideas.Common.Rewriting.Term.Class \ No newline at end of file diff --git a/src/Ideas/Common/Rewriting/Term/Class.hs b/src/Ideas/Common/Rewriting/Term/Class.hs new file mode 100644 index 00000000..478ddbd2 --- /dev/null +++ b/src/Ideas/Common/Rewriting/Term/Class.hs @@ -0,0 +1,258 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +-- Generic terms +-- +----------------------------------------------------------------------------- + +module Ideas.Common.Rewriting.Term.Class + ( -- * Terms + IsTerm(..), termView + , nothingSymbol, trueSymbol, falseSymbol + -- * Functions and symbols + , WithFunctions(..), isSymbol, isFunction + , unary, binary, ternary, isUnary, isBinary + -- * Variables + , WithVars(..), isVariable + , vars, varSet, hasVar, withoutVar + , hasSomeVar, hasNoVar, variableView + -- * Meta variables + , WithMetaVars(..), isMetaVar + , metaVars, metaVarSet, hasMetaVar, nextMetaVar + ) where + +import Data.Maybe +import Ideas.Common.Rewriting.Term.Data +import Ideas.Common.Rewriting.Term.Decoder +import Ideas.Common.Id +import Ideas.Common.View +import Ideas.Utils.Decoding +import Ideas.Utils.Prelude (ShowString(..)) +import Ideas.Utils.Uniplate +import qualified Data.IntSet as IS +import qualified Data.Map as M +import qualified Data.Set as S + +----------------------------------------------------------- +-- * Type class for conversion to/from terms + +class IsTerm a where + toTerm :: a -> Term + toTermList :: [a] -> Term + fromTerm :: Term -> Maybe a + termDecoder :: TermDecoder a + termListDecoder :: TermDecoder [a] + + {-# MINIMAL toTerm, termDecoder #-} + + -- default implementation + toTermList = TList . map toTerm + fromTerm t = either (const Nothing) Just (evalDecoder termDecoder () [t]) + termListDecoder = tListOf termDecoder + + -- temporary + termDecoder = get >>= \xs -> + case xs of + [] -> throwError "termDecoder" + t:rest -> + case fromTerm t of + Just a -> put rest >> return a + Nothing -> throwError "nothing in fromTerm" + +termView :: IsTerm a => View Term a +termView = makeView fromTerm toTerm + +instance IsTerm Term where + toTerm = id + termDecoder = tFirst $ maybe (throwError "not a term") return + +instance IsTerm ShowString where + toTerm = TVar . fromShowString + termDecoder = ShowString <$> tVar + +instance (IsTerm a, IsTerm b) => IsTerm (a, b) where + toTerm (a, b) = TList [toTerm a, toTerm b] + termDecoder = tList2 (,) termDecoder termDecoder + +instance (IsTerm a, IsTerm b, IsTerm c) => IsTerm (a, b, c) where + toTerm (a, b, c) = TList [toTerm a, toTerm b, toTerm c] + termDecoder = tList3 (,,) termDecoder termDecoder termDecoder + +instance (IsTerm a, IsTerm b) => IsTerm (Either a b) where + toTerm = either toTerm toTerm + termDecoder = Left <$> termDecoder <|> Right <$> termDecoder + +instance IsTerm Int where + toTerm = TNum . fromIntegral + termDecoder = fromInteger <$> tInteger + +instance IsTerm Integer where + toTerm = TNum + termDecoder = tInteger + +instance IsTerm Double where + toTerm = TFloat + termDecoder = tDouble + +instance IsTerm Float where + toTerm = TFloat . realToFrac + termDecoder = realToFrac <$> tDouble + +instance IsTerm Char where + toTerm c = TVar [c] + toTermList = TVar + termDecoder = tChar + termListDecoder = tVar + +instance IsTerm Bool where + toTerm True = symbol trueSymbol + toTerm False = symbol falseSymbol + termDecoder = True <$ tCon0 trueSymbol <|> False <$ tCon0 falseSymbol + +instance IsTerm Id where + toTerm = toTerm . show + termDecoder = newId <$> tVar + +instance IsTerm a => IsTerm [a] where + toTerm = toTermList + termDecoder = termListDecoder + +instance (IsTerm a, Ord a) => IsTerm (S.Set a) where + toTerm = toTerm . S.toList + termDecoder = S.fromList <$> termDecoder + +instance (IsTerm a, IsTerm b, Ord a) => IsTerm (M.Map a b) where + toTerm = toTerm . M.toList + termDecoder = M.fromList <$> termDecoder + +trueSymbol, falseSymbol, nothingSymbol :: Symbol +trueSymbol = newSymbol "true" +falseSymbol = newSymbol "false" +nothingSymbol = newSymbol "Nothing" + +instance IsTerm a => IsTerm (Maybe a) where + toTerm = maybe (symbol nothingSymbol) toTerm + termDecoder = Just <$> termDecoder <|> Nothing <$ tCon0 nothingSymbol + +----------------------------------------------------------- +-- * Functions and symbols + +class WithFunctions a where + -- constructing + symbol :: Symbol -> a + function :: Symbol -> [a] -> a + -- matching + getSymbol :: a -> Maybe Symbol + getFunction :: a -> Maybe (Symbol, [a]) + -- default definition + symbol s = function s [] + getSymbol a = fst <$> getFunction a + +instance WithFunctions Term where + function = TCon + getFunction (TCon s xs) = Just (s, xs) + getFunction _ = Nothing + +isSymbol :: WithFunctions a => Symbol -> a -> Bool +isSymbol s = (== Just s) . getSymbol + +isFunction :: WithFunctions a => Symbol -> a -> Maybe [a] +isFunction s a = + case getFunction a of + Just (t, as) | s == t -> Just as + _ -> Nothing + +unary :: WithFunctions a => Symbol -> a -> a +unary s a = function s [a] + +binary :: WithFunctions a => Symbol -> a -> a -> a +binary s a b = function s [a, b] + +ternary :: WithFunctions a => Symbol -> a -> a -> a -> a +ternary s a b c = function s [a, b, c] + +isUnary :: WithFunctions a => Symbol -> a -> Maybe a +isUnary s a = + case isFunction s a of + Just [x] -> Just x + _ -> Nothing + +isBinary :: WithFunctions a => Symbol -> a -> Maybe (a, a) +isBinary s a = + case isFunction s a of + Just [x, y] -> Just (x, y) + _ -> Nothing + +----------------------------------------------------------- +-- * Variables + +class WithVars a where + variable :: String -> a + getVariable :: a -> Maybe String + +instance WithVars Term where + variable = TVar + getVariable (TVar s) = Just s + getVariable _ = Nothing + +isVariable :: WithVars a => a -> Bool +isVariable = isJust . getVariable + +vars :: (Uniplate a, WithVars a) => a -> [String] +vars = mapMaybe getVariable . universe + +varSet :: (Uniplate a, WithVars a) => a -> S.Set String +varSet = S.fromList . vars + +hasVar :: (Uniplate a, WithVars a) => String -> a -> Bool +hasVar i = (i `elem`) . vars + +withoutVar :: (Uniplate a, WithVars a) => String -> a -> Bool +withoutVar i = not . hasVar i + +hasSomeVar :: (Uniplate a, WithVars a) => a -> Bool +hasSomeVar = not . hasNoVar + +hasNoVar :: (Uniplate a, WithVars a) => a -> Bool +hasNoVar = null . vars + +variableView :: WithVars a => View a String +variableView = makeView getVariable variable + +----------------------------------------------------------- +-- * Meta variables + +class WithMetaVars a where + metaVar :: Int -> a + getMetaVar :: a -> Maybe Int + +instance WithMetaVars Term where + metaVar = TMeta + getMetaVar (TMeta i) = Just i + getMetaVar _ = Nothing + +isMetaVar :: WithMetaVars a => a -> Bool +isMetaVar = isJust . getMetaVar + +metaVars :: (Uniplate a, WithMetaVars a) => a -> [Int] +metaVars = mapMaybe getMetaVar . universe + +metaVarSet :: (Uniplate a, WithMetaVars a) => a -> IS.IntSet +metaVarSet = IS.fromList . metaVars + +hasMetaVar :: (Uniplate a, WithMetaVars a) => Int -> a -> Bool +hasMetaVar i = (i `elem`) . metaVars + +nextMetaVar :: (Uniplate a, WithMetaVars a) => a -> Int +nextMetaVar a + | null is = 0 + | otherwise = maximum is + 1 + where + is = metaVars a \ No newline at end of file diff --git a/src/Ideas/Common/Rewriting/Term/Data.hs b/src/Ideas/Common/Rewriting/Term/Data.hs new file mode 100644 index 00000000..f340255d --- /dev/null +++ b/src/Ideas/Common/Rewriting/Term/Data.hs @@ -0,0 +1,84 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +-- A simple data type for term rewriting +-- +----------------------------------------------------------------------------- + +module Ideas.Common.Rewriting.Term.Data + ( -- * Symbols + Symbol, newSymbol + , isAssociative, makeAssociative + -- * Terms + , Term(..) + ) where + +import Data.Function +import Ideas.Common.Id +import Ideas.Utils.QuickCheck hiding (function) +import Ideas.Utils.Uniplate + +----------------------------------------------------------- +-- Symbols + +data Symbol = S { isAssociative :: Bool, symbolId :: Id } + +instance Eq Symbol where + (==) = (==) `on` getId -- without associativity property + +instance Ord Symbol where + compare = compareId -- without associativity property + +instance Show Symbol where + show = showId + +instance Read Symbol where + readsPrec n = map f . readsPrec n + where + f :: (Id, String) -> (Symbol, String) + f (a, s) = (newSymbol a, s) + +instance HasId Symbol where + getId = symbolId + changeId f (S b a) = S b (f a) + +newSymbol :: IsId a => a -> Symbol +newSymbol = S False . newId + +makeAssociative :: Symbol -> Symbol +makeAssociative (S _ a) = S True a + +----------------------------------------------------------- +-- * Data type for terms + +data Term = TVar String + | TCon Symbol [Term] + | TList [Term] + | TNum Integer + | TFloat Double + | TMeta Int + deriving (Show, Read, Eq, Ord) + +instance Uniplate Term where + uniplate (TCon x xs) = plate (TCon x) ||* xs + uniplate (TList xs) = plate TList ||* xs + uniplate term = plate term + +----------------------------------------------------------- +-- * Arbitrary term generator + +instance Arbitrary Term where + arbitrary = generators + [ constGens $ map TVar ["x", "y", "z"] + , arbGen TNum, arbGen TFloat, arbGen TMeta + , constGens $ map (\s -> TCon (newSymbol s) []) ["a", "b"] + , unaryGens $ map (\s x -> TCon (newSymbol s) [x]) ["h", "k"] + , binaryGens $ map (\s x y -> TCon (newSymbol s) [x, y]) ["f", "g"] + ] \ No newline at end of file diff --git a/src/Ideas/Common/Rewriting/Term/Decoder.hs b/src/Ideas/Common/Rewriting/Term/Decoder.hs new file mode 100644 index 00000000..b592c12e --- /dev/null +++ b/src/Ideas/Common/Rewriting/Term/Decoder.hs @@ -0,0 +1,102 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +-- Generic terms +-- +----------------------------------------------------------------------------- + +module Ideas.Common.Rewriting.Term.Decoder + ( TermDecoder + , tCon, tCon0, tCon1, tCon2, tConOf, tInteger, tDouble, tVar, tListOf, tConWithSymbol + , tList2, tList3, tChar, tFirst + -- re-exports + , Alternative(..), MonadReader(..), throwError + ) where + +import Control.Monad +import Ideas.Common.Rewriting.Term.Data +import Ideas.Utils.Decoding + +----------------------------------------------------------- +-- * Type class for conversion to/from terms + +type TermDecoder = Decoder () String [Term] + +tFirst :: (Maybe Term -> TermDecoder a) -> TermDecoder a +tFirst f = get >>= \xs -> + case xs of + t:rest -> f (Just t) <* put rest + _ -> f Nothing + +tVar :: TermDecoder String +tVar = tFirst $ \mt -> + case mt of + Just (TVar s) -> return s + _ -> throwError "not a var" + +tChar :: TermDecoder Char +tChar = tFirst $ \mt -> + case mt of + Just (TVar [c]) -> return c + _ -> throwError "not a char" + +tInteger :: TermDecoder Integer +tInteger = tFirst $ \mt -> + case mt of + Just (TNum i) -> return i + _ -> throwError "not an integer" + +tDouble :: TermDecoder Double +tDouble = tFirst $ \mt -> + case mt of + Just (TFloat f) -> return f + _ -> throwError "not a double" + +tList :: TermDecoder a -> TermDecoder a +tList p = tFirst $ \mt -> + case mt of + Just (TList xs) -> put xs *> p <* tEmpty + _ -> throwError "not a list" + +tCon :: Symbol -> TermDecoder a -> TermDecoder a +tCon s1 p = tFirst $ \mt -> + case mt of + Just (TCon s2 xs) | s1 == s2 -> put xs *> p <* tEmpty + _ -> throwError $ "not con " ++ show s1 + +tEmpty :: TermDecoder () +tEmpty = get >>= \xs -> unless (null xs) (throwError "not empty") + +tCon0 :: Symbol -> TermDecoder () +tCon0 s = tCon s (return ()) + +tCon1 :: Symbol -> (a -> b) -> TermDecoder a -> TermDecoder b +tCon1 s f p = tCon s (f <$> p) + +tCon2 :: Symbol -> (a -> b -> c) -> TermDecoder a -> TermDecoder b -> TermDecoder c +tCon2 s f p q = tCon s (f <$> p <*> q) + +tConOf :: Symbol -> TermDecoder a -> TermDecoder [a] +tConOf s p = tCon s (many p) + +tConWithSymbol :: (Symbol -> [a] -> b) -> TermDecoder a -> TermDecoder b +tConWithSymbol f p = tFirst $ \mt -> + case mt of + Just (TCon s xs) -> f s <$ put xs <*> many p <* tEmpty + _ -> throwError $ "not a con" + +tList2 :: (a -> b -> c) -> TermDecoder a -> TermDecoder b -> TermDecoder c +tList2 f p q = tList $ f <$> p <*> q + +tList3 :: (a -> b -> c -> d) -> TermDecoder a -> TermDecoder b -> TermDecoder c -> TermDecoder d +tList3 f p q r = tList $ f <$> p <*> q <*> r + +tListOf :: TermDecoder a -> TermDecoder [a] +tListOf p = tList $ many p \ No newline at end of file diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index b1b68e31..8843d383 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -67,7 +67,7 @@ xmlDecoder tp = Context -> decodeContext Rule -> decodeRule Environment -> decodeArgEnvironment - Term -> get >>= (fromXML >=> fromOMOBJ) + Term -> get >>= (fromXML >=> maybe (fail "invalid OpenMath") return . fromOMOBJ) Location -> decodeLocation StratCfg -> decodeConfiguration QCGen -> getQCGen @@ -162,10 +162,12 @@ decodeEnvironment = case findChild "OMOBJ" item of -- OpenMath object found inside item tag Just this | useOpenMath req -> - case xml2omobj this >>= fromOMOBJ of + case xml2omobj this of Left err -> fail err - Right term -> - return $ insertRef (makeRef n) (term :: Term) env + Right omobj -> + case fromOMOBJ omobj of + Just term -> return $ insertRef (makeRef n) (term :: Term) env + Nothing -> fail "invalid openmath" -- Simple value in attribute _ -> do value <- findAttribute "value" item @@ -194,9 +196,12 @@ decodeBinding = get >>= \xml -> do case findChild "OMOBJ" xml of -- OpenMath object found inside tag Just this | useOpenMath req -> - case xml2omobj this >>= fromOMOBJ of + case xml2omobj this of Left err -> fail err - Right term -> return (termBinding a term) + Right omobj -> + case fromOMOBJ omobj of + Just term -> return (termBinding a term) + Nothing -> fail "invalid openmath" -- Simple value _ -> return (makeBinding (makeRef a) (getData xml)) where diff --git a/src/Ideas/Encoding/EncoderXML.hs b/src/Ideas/Encoding/EncoderXML.hs index 108c06a3..9498f8c1 100644 --- a/src/Ideas/Encoding/EncoderXML.hs +++ b/src/Ideas/Encoding/EncoderXML.hs @@ -21,7 +21,7 @@ module Ideas.Encoding.EncoderXML import Data.Char import Data.List import Data.Maybe -import Ideas.Common.Library hiding (exerciseId) +import Ideas.Common.Library hiding (exerciseId, tFirst) import Ideas.Encoding.Encoder import Ideas.Encoding.OpenMathSupport import Ideas.Encoding.Request hiding (XML) @@ -132,10 +132,10 @@ encodeContext ctx = do buildExpression :: BuildXML b => Bool -> Exercise a -> a -> b buildExpression useOM ex - | useOM = either msg builderXML . toOpenMath ex + | useOM = maybe msg builderXML . toOpenMath ex | otherwise = tag "expr" . string . prettyPrinter ex where - msg s = error ("Error encoding term in OpenMath: " ++ s) + msg = error "Error encoding term in OpenMath" encodeLocation :: Location -> XMLEncoder a encodeLocation loc = "location" .=. show loc diff --git a/src/Ideas/Encoding/OpenMathSupport.hs b/src/Ideas/Encoding/OpenMathSupport.hs index 19325e64..27d60b67 100644 --- a/src/Ideas/Encoding/OpenMathSupport.hs +++ b/src/Ideas/Encoding/OpenMathSupport.hs @@ -17,7 +17,6 @@ module Ideas.Encoding.OpenMathSupport , toOMOBJ, fromOMOBJ ) where -import Control.Monad import Data.Char import Data.List import Ideas.Common.Library @@ -31,14 +30,14 @@ import qualified Ideas.Text.OpenMath.Symbol as OM ----------------------------------------------------------------------------- -- Utility functions for conversion to/from OpenMath -toOpenMath :: Monad m => Exercise a -> a -> m OMOBJ +toOpenMath :: Exercise a -> a -> Maybe OMOBJ toOpenMath ex a = do - v <- hasTermViewM ex + v <- hasTermView ex return (toOMOBJ (build v a)) -fromOpenMath :: MonadPlus m => Exercise a -> OMOBJ -> m a +fromOpenMath :: Exercise a -> OMOBJ -> Maybe a fromOpenMath ex omobj = do - v <- hasTermViewM ex + v <- hasTermView ex a <- fromOMOBJ omobj matchM v a @@ -60,21 +59,21 @@ toOMOBJ = rec . toTerm OMBIND (OMS s) [x] body make xs = OMA xs -fromOMOBJ :: (MonadPlus m, IsTerm a) => OMOBJ -> m a +fromOMOBJ :: IsTerm a => OMOBJ -> Maybe a fromOMOBJ = (>>= fromTerm) . rec where rec omobj = case omobj of OMV x -> case isMeta x of - Just n -> return (TMeta n) - Nothing -> return (TVar x) - OMS s -> return (symbol (newSymbol (OM.dictionary s, OM.symbolName s))) - OMI n -> return (TNum n) - OMF a -> return (TFloat a) + Just n -> Just (TMeta n) + Nothing -> Just (TVar x) + OMS s -> Just (symbol (newSymbol (OM.dictionary s, OM.symbolName s))) + OMI n -> Just (TNum n) + OMF a -> Just (TFloat a) OMA xs -> case xs of OMS s:ys | s == OM.listSymbol -> TList <$> mapM rec ys | otherwise -> function (newSymbol s) <$> mapM rec ys - _ -> fail "Invalid OpenMath object" + _ -> Nothing OMBIND binder xs body -> rec (OMA (binder:map OMV xs++[body])) @@ -95,8 +94,5 @@ idToSymbol a | otherwise = OM.makeSymbol (qualification a) (unqualified a) -hasTermViewM :: Monad m => Exercise a -> m (View Term a) -hasTermViewM = maybe (fail "No support for terms") return . hasTermView - mfSymbol :: OM.Symbol mfSymbol = OM.makeSymbol "extra" "mixedfraction" \ No newline at end of file diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 18a5f601..ab9274e2 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -40,6 +40,7 @@ instance Monoid a => Monoid (Decoder env err s a) where instance Monad (Decoder env err s) where return a = Dec (return a) Dec m >>= f = Dec $ m >>= fromDec . f + fail msg = error $ "fail in Decoder: " ++ msg runDecoder :: Decoder env err s a -> env -> s -> Either err (a, s) runDecoder p env s = runExcept (runReaderT (runStateT (fromDec p) s) env) From 389a513703809f893e662c65c4ead79a5f7d01c4 Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 12 Oct 2021 17:01:50 +0200 Subject: [PATCH 29/57] Update Decoder.hs --- src/Ideas/Common/Rewriting/Term/Decoder.hs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Ideas/Common/Rewriting/Term/Decoder.hs b/src/Ideas/Common/Rewriting/Term/Decoder.hs index b592c12e..06175d78 100644 --- a/src/Ideas/Common/Rewriting/Term/Decoder.hs +++ b/src/Ideas/Common/Rewriting/Term/Decoder.hs @@ -14,7 +14,7 @@ module Ideas.Common.Rewriting.Term.Decoder ( TermDecoder - , tCon, tCon0, tCon1, tCon2, tConOf, tInteger, tDouble, tVar, tListOf, tConWithSymbol + , tCon, tCon0, tCon1, tCon2, tCon3, tConOf, tInteger, tDouble, tVar, tListOf, tConWithSymbol , tList2, tList3, tChar, tFirst -- re-exports , Alternative(..), MonadReader(..), throwError @@ -83,6 +83,9 @@ tCon1 s f p = tCon s (f <$> p) tCon2 :: Symbol -> (a -> b -> c) -> TermDecoder a -> TermDecoder b -> TermDecoder c tCon2 s f p q = tCon s (f <$> p <*> q) +tCon3 :: Symbol -> (a -> b -> c -> d) -> TermDecoder a -> TermDecoder b -> TermDecoder c -> TermDecoder d +tCon3 s f p q r = tCon s (f <$> p <*> q <*> r) + tConOf :: Symbol -> TermDecoder a -> TermDecoder [a] tConOf s p = tCon s (many p) From 10dd1cfa9a1b712ca4ea610f8c83b29caee7fa6a Mon Sep 17 00:00:00 2001 From: Heeren Date: Wed, 20 Oct 2021 14:39:25 +0200 Subject: [PATCH 30/57] Update NewEncoderJSON.hs encodeConstraint --- src/Ideas/Encoding/NewEncoderJSON.hs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Ideas/Encoding/NewEncoderJSON.hs b/src/Ideas/Encoding/NewEncoderJSON.hs index 2f081ae3..7bfdcd3d 100644 --- a/src/Ideas/Encoding/NewEncoderJSON.hs +++ b/src/Ideas/Encoding/NewEncoderJSON.hs @@ -48,6 +48,7 @@ jsonEncodeConst :: TypedValue (Const a) -> EncoderX a JSONBuilder jsonEncodeConst (val ::: tp) = case tp of Rule -> encodeRule val + Constraint -> encodeConstraint val Location -> encodeLocation val Environment -> encodeEnvironment val Context -> encodeContext val @@ -63,6 +64,9 @@ jsonEncodeConst (val ::: tp) = encodeRule :: Rule (Context a) -> EncoderX a JSONBuilder encodeRule r = pure $ "rule" .= showId r +encodeConstraint :: Constraint (Context a) -> EncoderX a JSONBuilder +encodeConstraint c = pure $ "constraint" .= showId c + encodeEnvironment :: Environment -> EncoderX a JSONBuilder encodeEnvironment env = let f a = (showId a, String (showValue a)) From ca6dc193538127e0e04139221d0e5084df90aaa6 Mon Sep 17 00:00:00 2001 From: Heeren Date: Fri, 21 Jan 2022 10:28:55 +0100 Subject: [PATCH 31/57] Renaming LiftView --- src/Ideas/Common/Constraint.hs | 4 ++-- src/Ideas/Common/Context.hs | 6 +++--- src/Ideas/Common/Exercise.hs | 2 +- src/Ideas/Common/Rule/Abstract.hs | 8 ++++---- src/Ideas/Common/Rule/Recognizer.hs | 8 ++++---- src/Ideas/Common/Rule/Transformation.hs | 5 ++++- src/Ideas/Common/Strategy/Abstract.hs | 8 ++++---- src/Ideas/Common/Strategy/StrategyTree.hs | 14 +++++++------- src/Ideas/Common/View.hs | 18 ++++++++++++------ 9 files changed, 41 insertions(+), 32 deletions(-) diff --git a/src/Ideas/Common/Constraint.hs b/src/Ideas/Common/Constraint.hs index e6ee037b..07a10935 100644 --- a/src/Ideas/Common/Constraint.hs +++ b/src/Ideas/Common/Constraint.hs @@ -46,8 +46,8 @@ instance HasId (Constraint a) where getId = constraintId changeId f r = r { constraintId = f (constraintId r) } -instance LiftView Constraint where - liftViewIn v (C n f) = C n (maybe Irrelevant (f . fst) . match v) +instance Lift Constraint where + liftWithM f (C n p) = C n (maybe Irrelevant (p . fst) . f) makeConstraint :: IsId n => n -> (a -> Result ()) -> Constraint a makeConstraint = C . newId diff --git a/src/Ideas/Common/Context.hs b/src/Ideas/Common/Context.hs index a4305e39..d7e01d9f 100644 --- a/src/Ideas/Common/Context.hs +++ b/src/Ideas/Common/Context.hs @@ -142,7 +142,7 @@ contextView = "views.contextView" @> makeView f g g = uncurry replaceInContext -- | Lift a rule to operate on a term in a context -liftToContext :: LiftView f => f a -> f (Context a) +liftToContext :: Lift f => f a -> f (Context a) liftToContext = liftViewIn contextView -- | Apply a function at top-level. Afterwards, try to return the focus @@ -151,10 +151,10 @@ applyTop :: (a -> a) -> Context a -> Context a applyTop f c = navigateTowards (location c) (changeInContext f (top c)) -use :: (LiftView f, IsTerm a, IsTerm b) => f a -> f (Context b) +use :: (Lift f, IsTerm a, IsTerm b) => f a -> f (Context b) use = useC . liftToContext -useC :: (LiftView f, IsTerm a, IsTerm b) => f (Context a) -> f (Context b) +useC :: (Lift f, IsTerm a, IsTerm b) => f (Context a) -> f (Context b) useC = liftViewIn (makeView f g) where f old@(C env a) = castT a >>= \b -> return (C env b, old) diff --git a/src/Ideas/Common/Exercise.hs b/src/Ideas/Common/Exercise.hs index a1cd1df0..4aceae17 100644 --- a/src/Ideas/Common/Exercise.hs +++ b/src/Ideas/Common/Exercise.hs @@ -397,7 +397,7 @@ showThisDerivation d ex = show (present der) ++ extra Just b | isReady ex b -> "" | otherwise -> "<>" present = biMap (ShowString . f) (ShowString . prettyPrinterContext ex) - f ((r, local), global) = showId r ++ part local ++ part global + f ((r, localEnv), globalEnv) = showId r ++ part localEnv ++ part globalEnv where newl = "\n " part env | noBindings env = "" diff --git a/src/Ideas/Common/Rule/Abstract.hs b/src/Ideas/Common/Rule/Abstract.hs index 453a1e85..f75df8f2 100644 --- a/src/Ideas/Common/Rule/Abstract.hs +++ b/src/Ideas/Common/Rule/Abstract.hs @@ -70,10 +70,10 @@ instance HasId (Rule a) where getId = ruleId changeId f r = r { ruleId = f (ruleId r) } -instance LiftView Rule where - liftViewIn v r = r - { getTrans = transLiftViewIn v (getTrans r) - , getRecognizer = liftViewIn v (getRecognizer r) +instance Lift Rule where + liftWithM l r = r + { getTrans = transLift l (getTrans r) + , getRecognizer = liftWithM l (getRecognizer r) } instance Recognizable Rule where diff --git a/src/Ideas/Common/Rule/Recognizer.hs b/src/Ideas/Common/Rule/Recognizer.hs index 2431eee8..7180e5a2 100644 --- a/src/Ideas/Common/Rule/Recognizer.hs +++ b/src/Ideas/Common/Rule/Recognizer.hs @@ -38,10 +38,10 @@ class Recognizable f where newtype Recognizer a = R { unR :: Trans (a, a) () } -instance LiftView Recognizer where - liftViewIn v r = - let f = fmap fst . match v - in R $ makeTrans f *** makeTrans f >>> unR r +instance Lift Recognizer where + liftWithM f r = + let t = makeTrans (fmap fst . f) + in R (t *** t >>> unR r) instance Sem.Semigroup (Recognizer a) where f <> g = R $ unR f `mappend` unR g diff --git a/src/Ideas/Common/Rule/Transformation.hs b/src/Ideas/Common/Rule/Transformation.hs index 95dde598..4c1f9cf8 100644 --- a/src/Ideas/Common/Rule/Transformation.hs +++ b/src/Ideas/Common/Rule/Transformation.hs @@ -25,7 +25,7 @@ module Ideas.Common.Rule.Transformation , writeRef, writeRef_, writeRefMaybe -- * Lifting transformations , transUseEnvironment - , transLiftView, transLiftViewIn + , transLiftView, transLiftViewIn, transLift , transLiftContext, transLiftContextIn -- * Using transformations , transApply, transApplyWith @@ -163,6 +163,9 @@ transLiftView v = transLiftViewIn (v &&& identity) transLiftViewIn :: View a (b, c) -> Transformation b -> Transformation a transLiftViewIn v f = makeTrans (match v) >>> first f >>^ build v +transLift :: (a -> Maybe (b, b -> a)) -> Transformation b -> Transformation a +transLift f t = makeTrans f >>> first t >>^ (\(x, g) -> g x) + transLiftContext :: Transformation a -> Transformation (Context a) transLiftContext = transLiftContextIn . transUseEnvironment diff --git a/src/Ideas/Common/Strategy/Abstract.hs b/src/Ideas/Common/Strategy/Abstract.hs index 054ac667..260d0843 100644 --- a/src/Ideas/Common/Strategy/Abstract.hs +++ b/src/Ideas/Common/Strategy/Abstract.hs @@ -192,11 +192,11 @@ rulesInStrategy s = concatMap f (toList (toStrategyTree s)) f (LeafRule r) | isMajor r = [r] f _ = [] -instance LiftView LabeledStrategy where - liftViewIn v (LS n s) = LS n (liftViewIn v s) +instance Lift LabeledStrategy where + liftWithM f (LS n s) = LS n (liftWithM f s) -instance LiftView Strategy where - liftViewIn v = S . fmap (liftViewIn v) . toStrategyTree +instance Lift Strategy where + liftWithM f = S . fmap (liftWithM f) . toStrategyTree -- | Apply a function to all the rules that make up a labeled strategy mapRules :: (Rule a -> Rule a) -> LabeledStrategy a -> LabeledStrategy a diff --git a/src/Ideas/Common/Strategy/StrategyTree.hs b/src/Ideas/Common/Strategy/StrategyTree.hs index ddb21e1b..a5d2ac79 100644 --- a/src/Ideas/Common/Strategy/StrategyTree.hs +++ b/src/Ideas/Common/Strategy/StrategyTree.hs @@ -79,9 +79,9 @@ instance Apply Leaf where applyAll (LeafRule r) a = applyAll r a applyAll (LeafDyn d) a = applyAll d a -instance LiftView Leaf where - liftViewIn v (LeafRule r) = LeafRule (liftViewIn v r) - liftViewIn v (LeafDyn d) = LeafDyn (liftViewIn v d) +instance Lift Leaf where + liftWithM f (LeafRule r) = LeafRule (liftWithM f r) + liftWithM f (LeafDyn d) = LeafDyn (liftWithM f d) treeToProcess :: StrategyTree a -> Process (Leaf a) treeToProcess = foldUnwind emptyAlg @@ -128,10 +128,10 @@ instance HasId (Dynamic a) where instance Apply Dynamic where applyAll d a = maybe [] ((`runProcess` a) . treeToProcess) (dynamicTree d a) -instance LiftView Dynamic where - liftViewIn v d = d - { dynamicToTerm = fmap fst . match v >=> dynamicToTerm d - , dynamicFromTerm = fmap (fmap (liftViewIn v)) . dynamicFromTerm d +instance Lift Dynamic where + liftWithM f d = d + { dynamicToTerm = fmap fst . f >=> dynamicToTerm d + , dynamicFromTerm = fmap (fmap (liftWithM f)) . dynamicFromTerm d } makeDynamic :: (IsId n, IsTerm a) => n -> (a -> StrategyTree a) -> Dynamic a diff --git a/src/Ideas/Common/View.hs b/src/Ideas/Common/View.hs index 0d455364..b5d78529 100644 --- a/src/Ideas/Common/View.hs +++ b/src/Ideas/Common/View.hs @@ -29,7 +29,7 @@ module Ideas.Common.View -- * Isomorphisms , Isomorphism, from, to, inverse -- * Lifting with views - , LiftView(..) + , Lift(..), liftView, liftViewIn -- * Some combinators , swapView, listView, traverseView, ($<) -- * Packaging a view @@ -236,11 +236,17 @@ inverse f = to f <-> from f ---------------------------------------------------------------------------------- -- Type class for lifting with Views -class LiftView f where - liftView :: View a b -> f b -> f a - liftViewIn :: View a (b, c) -> f b -> f a - -- default definition - liftView v = liftViewIn (v &&& identity) +liftView :: Lift f => View a b -> f b -> f a +liftView v = liftWithM $ fmap (\b -> (b, build v)) . match v + +liftViewIn :: Lift f => View a (b, c) -> f b -> f a +liftViewIn v = liftWithM $ fmap (\(b, c) -> (b, \x -> build v (x, c))) . match v + +class Lift f where + liftWith :: (a -> (b, b -> a)) -> f b -> f a + liftWithM :: (a -> Maybe (b, b -> a)) -> f b -> f a + -- default + liftWith f = liftWithM (Just . f) ---------------------------------------------------------------------------------- -- Some combinators From a275f52ddb62eee746c3f4cbeee77d3e90cc5eee Mon Sep 17 00:00:00 2001 From: Heeren Date: Fri, 21 Jan 2022 10:29:36 +0100 Subject: [PATCH 32/57] Update Diagnose.hs Add option to diagnose service to keep the user's term (instead of the term from the strategy) --- src/Ideas/Service/Diagnose.hs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/Ideas/Service/Diagnose.hs b/src/Ideas/Service/Diagnose.hs index e901077f..a4e280b8 100644 --- a/src/Ideas/Service/Diagnose.hs +++ b/src/Ideas/Service/Diagnose.hs @@ -13,7 +13,7 @@ ----------------------------------------------------------------------------- module Ideas.Service.Diagnose - ( Diagnosis(..), tDiagnosis, diagnose + ( Diagnosis(..), tDiagnosis, diagnose, diagnoseOption , getState, getStateAndReady , difference ) where @@ -78,7 +78,10 @@ getStateAndReady d = -- The diagnose service diagnose :: State a -> Context a -> Maybe Id -> Diagnosis a -diagnose state new motivationId +diagnose = diagnoseOption False + +diagnoseOption :: Bool -> State a -> Context a -> Maybe Id -> Diagnosis a +diagnoseOption keepUserTerm state new motivationId -- Is the submitted term equivalent? | not (equivalence ex (stateContext state) new) = -- Is the rule used discoverable by trying all known buggy rules? @@ -103,8 +106,10 @@ diagnose state new motivationId -- Was the submitted term expected by the strategy? | isJust expected = -- If yes, return new state and rule - let ((r, _, _), ns) = fromJust expected - in Expected (finished ns) ns r + let ((r, _, _), st) = fromJust expected + newState | keepUserTerm = st { stateContext = new } + | otherwise = st + in Expected (finished newState) newState r -- Is the submitted term (very) similar to the previous one? -- (this check is performed after "expected by strategy". TODO: fix From 339cf1351e3eb5db30a1671ca7e584ec553804af Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 7 Feb 2022 10:48:31 +0100 Subject: [PATCH 33/57] Update Derivation.hs extending derivation interface --- src/Ideas/Common/Derivation.hs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Ideas/Common/Derivation.hs b/src/Ideas/Common/Derivation.hs index b249788f..8c517916 100644 --- a/src/Ideas/Common/Derivation.hs +++ b/src/Ideas/Common/Derivation.hs @@ -26,6 +26,7 @@ module Ideas.Common.Derivation -- * Querying a derivation , isEmpty, derivationLength, terms, steps, triples , firstTerm, lastTerm, lastStep, withoutLast + , updateFirstTerm, updateLastTerm , updateSteps, derivationM, splitStep ) where @@ -139,6 +140,15 @@ withoutLast d@(D a xs) = S.EmptyR -> d ys S.:> _ -> D a ys +updateFirstTerm :: (a -> a) -> Derivation s a -> Derivation s a +updateFirstTerm f (D a xs) = D (f a) xs + +updateLastTerm :: (a -> a) -> Derivation s a -> Derivation s a +updateLastTerm f (D a xs) = + case S.viewr xs of + S.EmptyR -> D (f a) S.empty + ys S.:> (s, b) -> D a (ys S.|> (s, f b)) + updateSteps :: (a -> s -> a -> t) -> Derivation s a -> Derivation t a updateSteps f d = let ts = [ f a b c | (a, b, c) <- triples d ] From 547ac4b252ec0cc26dea83b5a3a10e84efc968b1 Mon Sep 17 00:00:00 2001 From: Heeren Date: Thu, 10 Mar 2022 10:33:57 +0100 Subject: [PATCH 34/57] finishing term decoder --- src/Ideas/Common/Derivation.hs | 16 +++++++++++----- src/Ideas/Common/Rewriting/Term/Class.hs | 9 --------- src/Ideas/Common/Rewriting/Term/Decoder.hs | 13 +++++++------ 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/src/Ideas/Common/Derivation.hs b/src/Ideas/Common/Derivation.hs index 8c517916..2c5db141 100644 --- a/src/Ideas/Common/Derivation.hs +++ b/src/Ideas/Common/Derivation.hs @@ -20,7 +20,7 @@ module Ideas.Common.Derivation , emptyDerivation, prepend, extend , merge, mergeBy, mergeStep -- * Conversion to/from list - , derivationToList, derivationFromList + , derivationToList, derivationFromList, derivationDecoder -- * Equality , eqDerivationBy -- * Querying a derivation @@ -30,6 +30,7 @@ module Ideas.Common.Derivation , updateSteps, derivationM, splitStep ) where +import Control.Applicative import Data.Maybe import Ideas.Common.Classes import Ideas.Common.Rewriting @@ -54,8 +55,7 @@ instance BiFunctor Derivation where instance (IsTerm s, IsTerm a) => IsTerm (Derivation s a) where toTerm = TList . derivationToList toTerm toTerm - fromTerm (TList xs) = derivationFromList fromTerm fromTerm xs - fromTerm _ = fail "not a derivation" + termDecoder = tListWith (derivationDecoder termDecoder termDecoder) ----------------------------------------------------------------------------- -- Constructing a derivation @@ -87,13 +87,19 @@ derivationToList :: (s -> b) -> (a -> b) -> Derivation s a -> [b] derivationToList f g d = g (firstTerm d) : concat [ [f s, g a] | (_, s, a) <- triples d ] -derivationFromList :: Monad m => (b -> m s) -> (b -> m a) -> [b] -> m (Derivation s a) +derivationFromList :: (b -> Maybe s) -> (b -> Maybe a) -> [b] -> Maybe (Derivation s a) derivationFromList f g = rec where - rec [] = fail "derivationFromList" + rec [] = Nothing rec [b] = emptyDerivation <$> g b rec (b1:b2:bs) = curry prepend <$> g b1 <*> f b2 <*> rec bs +derivationDecoder :: Alternative f => f s -> f a -> f (Derivation s a) +derivationDecoder tStep tTerm = f <$> tTerm <*> tSteps + where + f = foldl extend . emptyDerivation + tSteps = many ((,) <$> tStep <*> tTerm) + ----------------------------------------------------------------------------- -- Equality diff --git a/src/Ideas/Common/Rewriting/Term/Class.hs b/src/Ideas/Common/Rewriting/Term/Class.hs index 478ddbd2..dcb972b1 100644 --- a/src/Ideas/Common/Rewriting/Term/Class.hs +++ b/src/Ideas/Common/Rewriting/Term/Class.hs @@ -57,15 +57,6 @@ class IsTerm a where fromTerm t = either (const Nothing) Just (evalDecoder termDecoder () [t]) termListDecoder = tListOf termDecoder - -- temporary - termDecoder = get >>= \xs -> - case xs of - [] -> throwError "termDecoder" - t:rest -> - case fromTerm t of - Just a -> put rest >> return a - Nothing -> throwError "nothing in fromTerm" - termView :: IsTerm a => View Term a termView = makeView fromTerm toTerm diff --git a/src/Ideas/Common/Rewriting/Term/Decoder.hs b/src/Ideas/Common/Rewriting/Term/Decoder.hs index 06175d78..eee8bac0 100644 --- a/src/Ideas/Common/Rewriting/Term/Decoder.hs +++ b/src/Ideas/Common/Rewriting/Term/Decoder.hs @@ -15,7 +15,7 @@ module Ideas.Common.Rewriting.Term.Decoder ( TermDecoder , tCon, tCon0, tCon1, tCon2, tCon3, tConOf, tInteger, tDouble, tVar, tListOf, tConWithSymbol - , tList2, tList3, tChar, tFirst + , tListWith, tList2, tList3, tChar, tFirst -- re-exports , Alternative(..), MonadReader(..), throwError ) where @@ -59,8 +59,9 @@ tDouble = tFirst $ \mt -> Just (TFloat f) -> return f _ -> throwError "not a double" -tList :: TermDecoder a -> TermDecoder a -tList p = tFirst $ \mt -> +-- name tList clashes with service type +tListWith :: TermDecoder a -> TermDecoder a +tListWith p = tFirst $ \mt -> case mt of Just (TList xs) -> put xs *> p <* tEmpty _ -> throwError "not a list" @@ -96,10 +97,10 @@ tConWithSymbol f p = tFirst $ \mt -> _ -> throwError $ "not a con" tList2 :: (a -> b -> c) -> TermDecoder a -> TermDecoder b -> TermDecoder c -tList2 f p q = tList $ f <$> p <*> q +tList2 f p q = tListWith $ f <$> p <*> q tList3 :: (a -> b -> c -> d) -> TermDecoder a -> TermDecoder b -> TermDecoder c -> TermDecoder d -tList3 f p q r = tList $ f <$> p <*> q <*> r +tList3 f p q r = tListWith $ f <$> p <*> q <*> r tListOf :: TermDecoder a -> TermDecoder [a] -tListOf p = tList $ many p \ No newline at end of file +tListOf p = tListWith $ many p \ No newline at end of file From 4bf8239b088c682eb83e25e65336ce2b77d1d24e Mon Sep 17 00:00:00 2001 From: Heeren Date: Thu, 10 Mar 2022 10:34:21 +0100 Subject: [PATCH 35/57] Update EncoderXML.hs xml compatibility for ApplyResult --- src/Ideas/Encoding/EncoderXML.hs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Ideas/Encoding/EncoderXML.hs b/src/Ideas/Encoding/EncoderXML.hs index 9498f8c1..a58a0249 100644 --- a/src/Ideas/Encoding/EncoderXML.hs +++ b/src/Ideas/Encoding/EncoderXML.hs @@ -28,6 +28,7 @@ import Ideas.Encoding.Request hiding (XML) import Ideas.Encoding.RulesInfo (rulesInfoXML) import Ideas.Encoding.StrategyInfo import Ideas.Service.BasicServices (StepInfo, tStepInfo) +import qualified Ideas.Service.Apply as Apply import Ideas.Service.Diagnose import Ideas.Service.FeedbackScript.Syntax import Ideas.Service.State @@ -45,6 +46,7 @@ type XMLEncoder a = EncoderX a XMLBuilder xmlEncoder :: TypedEncoder a XMLBuilder xmlEncoder = (encodeDiagnosis, tDiagnosis) + (encodeApplyResult, Apply.tApplyResult) (encodeDecompositionReply, PD.tReply) (encodeDerivation, tDerivation tStepInfo tContext) (encodeFirsts, tList tFirst) @@ -210,6 +212,14 @@ encodeMessage msg = , encodeText (FeedbackText.text msg) ] +encodeApplyResult :: Apply.ApplyResult a -> XMLEncoder a +encodeApplyResult result = + case result of + Apply.SyntaxError msg -> "error" .=. msg + Apply.Correct _ st -> encodeState st + Apply.Buggy _ r -> "ruleid" .=. show r + Apply.Incorrect -> "error" .=. "incorrect" + encodeDiagnosis :: Diagnosis a -> XMLEncoder a encodeDiagnosis diagnosis = case diagnosis of From abf3180c15b87a688ba2de4cf94a00afc1d37b24 Mon Sep 17 00:00:00 2001 From: Heeren Date: Thu, 10 Mar 2022 10:56:57 +0100 Subject: [PATCH 36/57] simplified utf8 interface --- src/Ideas/Main/Default.hs | 17 +++++++++-------- src/Ideas/Text/JSON/Data.hs | 2 +- src/Ideas/Text/UTF8.hs | 28 ++++++++++------------------ src/Ideas/Text/XML/Unicode.hs | 6 +++--- 4 files changed, 23 insertions(+), 30 deletions(-) diff --git a/src/Ideas/Main/Default.hs b/src/Ideas/Main/Default.hs index c87fd1f5..9222d9c3 100644 --- a/src/Ideas/Main/Default.hs +++ b/src/Ideas/Main/Default.hs @@ -35,7 +35,7 @@ import Ideas.Service.DomainReasoner import Ideas.Service.FeedbackScript.Analysis import Ideas.Service.ServiceList import Ideas.Service.Types (Service) -import Ideas.Text.UTF8 (decode) +import qualified Ideas.Text.UTF8 as UTF8 import Ideas.Text.XML.Unicode (decoding) import Ideas.Utils.BlackBoxTests import Ideas.Utils.Prelude @@ -67,7 +67,7 @@ defaultCGI options dr = CGI.run $ \req respond -> do -- query environment let script = fromMaybe "" (findHeader "CGI-Script-Name" req) -- get name of binary addr = "" -- no IP address of the remote host (GDPR) - input <- inputOrDefault req >>= decoding + input <- inputOrDefault req >>= decodingIO -- process request (preq, txt, ctp) <- process (optionCgiBin script options) dr input @@ -76,7 +76,7 @@ defaultCGI options dr = CGI.run $ \req respond -> do { Log.ipaddress = addr , Log.version = shortVersion , Log.input = input - , Log.output = decode txt + , Log.output = fromMaybe txt (UTF8.decode txt) } -- log request to database when (useLogging preq) $ @@ -123,7 +123,7 @@ defaultCommandLine options dr cmdLineOptions = do processDatabase dr database InputFile file -> withBinaryFile file ReadMode $ \h -> do - input <- hGetContents h >>= decoding + input <- hGetContents h >>= decodingIO (req, txt, _) <- process options dr input putStrLn txt when (PrintLog `elem` cmdLineOptions) $ do @@ -131,7 +131,7 @@ defaultCommandLine options dr cmdLineOptions = do { Log.ipaddress = "command-line" , Log.version = shortVersion , Log.input = input - , Log.output = decode txt + , Log.output = fromMaybe txt (UTF8.decode txt) } Log.printLog (logRef options) -- blackbox tests @@ -166,9 +166,10 @@ process options dr input = do run JSON = processJSON makeTestRunner :: DomainReasoner -> String -> IO String -makeTestRunner dr input = do - (_, out, _) <- decoding input >>= process mempty dr - return out +makeTestRunner dr = decodingIO >=> fmap snd3 . process mempty dr + +decodingIO :: String -> IO String +decodingIO = maybe (fail "unicode decoding failed") return . decoding addVersion :: DomainReasoner -> DomainReasoner addVersion dr = dr diff --git a/src/Ideas/Text/JSON/Data.hs b/src/Ideas/Text/JSON/Data.hs index 0118ccd8..230b2ece 100644 --- a/src/Ideas/Text/JSON/Data.hs +++ b/src/Ideas/Text/JSON/Data.hs @@ -78,7 +78,7 @@ prettyJSON compact = rec -- Escape double quote and backslash, and convert to UTF8 encoding escape :: String -> String -escape = concatMap f . fromMaybe "invalid UTF8 string" . UTF8.encodeM +escape = concatMap f . fromMaybe "invalid UTF8 string" . UTF8.encode where f '\n' = "\\n" f '\r' = "" -- carriage return (DOS files) diff --git a/src/Ideas/Text/UTF8.hs b/src/Ideas/Text/UTF8.hs index 8ae68d47..f2d9f5a2 100644 --- a/src/Ideas/Text/UTF8.hs +++ b/src/Ideas/Text/UTF8.hs @@ -13,7 +13,7 @@ ----------------------------------------------------------------------------- module Ideas.Text.UTF8 - ( encode, encodeM, decode, decodeM + ( encode, decode , isUTF8, allBytes, propEncoding ) where @@ -26,24 +26,16 @@ import Test.QuickCheck -- Interface -- | Encode a string to UTF8 format -encode :: String -> String -encode = either error id . encodeM +encode :: String -> Maybe String +encode = fmap (map chr . concat) . mapM (toUTF8 . ord) -- | Decode an UTF8 format string to unicode points -decode :: String -> String -decode = either error id . decodeM - --- | Encode a string to UTF8 format (monadic) -encodeM :: Monad m => String -> m String -encodeM = fmap (map chr . concat) . mapM (toUTF8 . ord) - --- | Decode an UTF8 format string to unicode points (monadic) -decodeM :: Monad m => String -> m String -decodeM = fmap (map chr) . fromUTF8 . map ord +decode :: String -> Maybe String +decode = fmap (map chr) . fromUTF8 . map ord -- | Test whether the argument is a proper UTF8 string isUTF8 :: String -> Bool -isUTF8 = isJust . decodeM +isUTF8 = isJust . decode -- | Test whether all characters are in the range 0-255 allBytes :: String -> Bool @@ -52,7 +44,7 @@ allBytes = all ((`between` (0, 255)) . ord) ------------------------------------------------------------------ -- Helper functions -toUTF8 :: Monad m => Int -> m [Int] +toUTF8 :: Int -> Maybe [Int] toUTF8 n | n < 128 = -- one byte return [n] @@ -71,7 +63,7 @@ toUTF8 n | otherwise = fail "invalid character in UTF8" -fromUTF8 :: Monad m => [Int] -> m [Int] +fromUTF8 :: [Int] -> Maybe [Int] fromUTF8 xs | null xs = return [] | otherwise = do @@ -119,6 +111,6 @@ propEncoding = forAll (sized gen) valid valid :: String -> Bool valid xs = fromMaybe False $ - do us <- encodeM xs - bs <- decodeM us + do us <- encode xs + bs <- decode us return (xs == bs) \ No newline at end of file diff --git a/src/Ideas/Text/XML/Unicode.hs b/src/Ideas/Text/XML/Unicode.hs index 9e7d1c3c..af6daf7d 100644 --- a/src/Ideas/Text/XML/Unicode.hs +++ b/src/Ideas/Text/XML/Unicode.hs @@ -170,16 +170,16 @@ extenderMap = intpairs [f '\x00B7' , f '\x02D0' , f '\x02D1' , f '\x0387' , f '\x0640' , f '\x0E46' , f '\x0EC6' , f '\x3005' , ('\x3031','\x3035') , ('\x309D','\x309E'), ('\x30FC','\x30FE') ] -decoding :: Monad m => String -> m String +decoding :: String -> Maybe String decoding xs | "\255\254" `isPrefixOf` xs = return (decode16 $ drop 2 xs) | "\254\255" `isPrefixOf` xs = return (decode16X $ drop 2 xs) | "\239\187\191" `isPrefixOf` xs = - UTF8.decodeM (drop 3 xs) + UTF8.decode (drop 3 xs) | otherwise = - UTF8.decodeM xs + UTF8.decode xs decode16 :: String -> String decode16 [] = [] From 2737921702ac815ab9ff8a0e9a7356b55146cddb Mon Sep 17 00:00:00 2001 From: Heeren Date: Thu, 17 Mar 2022 08:50:54 +0100 Subject: [PATCH 37/57] decoders --- ideas.cabal | 3 + src/Ideas/Common/Rewriting/Term/Class.hs | 2 +- src/Ideas/Common/Rewriting/Term/Decoder.hs | 26 +-- src/Ideas/Encoding/DecoderJSON.hs | 2 +- src/Ideas/Encoding/DecoderXML.hs | 33 ++-- src/Ideas/Encoding/ModeXML.hs | 4 +- src/Ideas/Text/JSON/Class.hs | 4 +- src/Ideas/Text/JSON/Decoder.hs | 149 +++++------------- src/Ideas/Text/OpenMath/Object.hs | 75 +++------ src/Ideas/Text/UTF8.hs | 37 +++-- src/Ideas/Text/XML.hs | 175 +++------------------ src/Ideas/Text/XML/Builder.hs | 91 +++++++++++ src/Ideas/Text/XML/Data.hs | 97 ++++++++++++ src/Ideas/Text/XML/Decoder.hs | 72 +++++++++ src/Ideas/Utils/Decoding.hs | 84 +++++++++- 15 files changed, 481 insertions(+), 373 deletions(-) create mode 100644 src/Ideas/Text/XML/Builder.hs create mode 100644 src/Ideas/Text/XML/Data.hs create mode 100644 src/Ideas/Text/XML/Decoder.hs diff --git a/ideas.cabal b/ideas.cabal index 884afb22..480d43a2 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -187,6 +187,9 @@ Library Ideas.Text.OpenMath.Tests Ideas.Text.UTF8 Ideas.Text.XML + Ideas.Text.XML.Builder + Ideas.Text.XML.Data + Ideas.Text.XML.Decoder Ideas.Text.XML.Document Ideas.Text.XML.Parser Ideas.Text.XML.Unicode diff --git a/src/Ideas/Common/Rewriting/Term/Class.hs b/src/Ideas/Common/Rewriting/Term/Class.hs index dcb972b1..cfec6654 100644 --- a/src/Ideas/Common/Rewriting/Term/Class.hs +++ b/src/Ideas/Common/Rewriting/Term/Class.hs @@ -62,7 +62,7 @@ termView = makeView fromTerm toTerm instance IsTerm Term where toTerm = id - termDecoder = tFirst $ maybe (throwError "not a term") return + termDecoder = tFirst $ maybe (errorStr "not a term") return instance IsTerm ShowString where toTerm = TVar . fromShowString diff --git a/src/Ideas/Common/Rewriting/Term/Decoder.hs b/src/Ideas/Common/Rewriting/Term/Decoder.hs index eee8bac0..5fa44eb3 100644 --- a/src/Ideas/Common/Rewriting/Term/Decoder.hs +++ b/src/Ideas/Common/Rewriting/Term/Decoder.hs @@ -27,53 +27,53 @@ import Ideas.Utils.Decoding ----------------------------------------------------------- -- * Type class for conversion to/from terms -type TermDecoder = Decoder () String [Term] +type TermDecoder = Decoder () (Error Term) [Term] tFirst :: (Maybe Term -> TermDecoder a) -> TermDecoder a tFirst f = get >>= \xs -> case xs of - t:rest -> f (Just t) <* put rest + t:rest -> f (Just t) <* changeLoc nextLoc <* put rest _ -> f Nothing tVar :: TermDecoder String tVar = tFirst $ \mt -> case mt of Just (TVar s) -> return s - _ -> throwError "not a var" + _ -> raiseError "not a var" mt tChar :: TermDecoder Char tChar = tFirst $ \mt -> case mt of Just (TVar [c]) -> return c - _ -> throwError "not a char" + _ -> raiseError "not a char" mt tInteger :: TermDecoder Integer tInteger = tFirst $ \mt -> case mt of Just (TNum i) -> return i - _ -> throwError "not an integer" + _ -> raiseError "not an integer" mt tDouble :: TermDecoder Double tDouble = tFirst $ \mt -> case mt of Just (TFloat f) -> return f - _ -> throwError "not a double" + _ -> raiseError "not a double" mt -- name tList clashes with service type tListWith :: TermDecoder a -> TermDecoder a tListWith p = tFirst $ \mt -> case mt of - Just (TList xs) -> put xs *> p <* tEmpty - _ -> throwError "not a list" + Just (TList xs) -> changeLoc (LocByPos 0) >> put xs *> p <* tEmpty + _ -> raiseError "not a list" mt tCon :: Symbol -> TermDecoder a -> TermDecoder a tCon s1 p = tFirst $ \mt -> case mt of - Just (TCon s2 xs) | s1 == s2 -> put xs *> p <* tEmpty - _ -> throwError $ "not con " ++ show s1 + Just (TCon s2 xs) | s1 == s2 -> changeLoc (LocByPos 0) >> put xs *> p <* tEmpty + _ -> raiseError ("not con '" ++ show s1 ++ "'") mt tEmpty :: TermDecoder () -tEmpty = get >>= \xs -> unless (null xs) (throwError "not empty") +tEmpty = get >>= \xs -> unless (null xs) (errorStr "not empty") tCon0 :: Symbol -> TermDecoder () tCon0 s = tCon s (return ()) @@ -93,8 +93,8 @@ tConOf s p = tCon s (many p) tConWithSymbol :: (Symbol -> [a] -> b) -> TermDecoder a -> TermDecoder b tConWithSymbol f p = tFirst $ \mt -> case mt of - Just (TCon s xs) -> f s <$ put xs <*> many p <* tEmpty - _ -> throwError $ "not a con" + Just (TCon s xs) -> f s <$ changeLoc (LocByPos 0) <* put xs <*> many p <* tEmpty + _ -> raiseError "not a con" mt tList2 :: (a -> b -> c) -> TermDecoder a -> TermDecoder b -> TermDecoder c tList2 f p q = tListWith $ f <$> p <*> q diff --git a/src/Ideas/Encoding/DecoderJSON.hs b/src/Ideas/Encoding/DecoderJSON.hs index fe64d8a4..71ec9113 100644 --- a/src/Ideas/Encoding/DecoderJSON.hs +++ b/src/Ideas/Encoding/DecoderJSON.hs @@ -65,7 +65,7 @@ decodeConst tp = Exercise -> getExercise <* jSkip Environment -> decodeEnvironment Location -> decodeLocation - Term -> gets (jsonToTerm . toJSON . snd) + Term -> gets (jsonToTerm . toJSON) Int -> jInt Tp.String -> jString Id -> decodeId diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index 8843d383..c703b2af 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -14,7 +14,7 @@ ----------------------------------------------------------------------------- module Ideas.Encoding.DecoderXML - ( XMLDecoder, xmlDecoder + ( XMLDecoder, xmlTypeDecoder ) where import Control.Applicative hiding (Const) @@ -33,33 +33,33 @@ import Ideas.Text.XML type XMLDecoder a t = DecoderX a String XML t -xmlDecoder :: TypedDecoder a XML -xmlDecoder tp = +xmlTypeDecoder :: TypedDecoder a XML +xmlTypeDecoder tp = case tp of Tag s (Const String) -> decodeChild s decodeData <|> decodeAttribute s Tag s t | s == "answer" -> - decodeChild "answer" (xmlDecoder t) + decodeChild "answer" (xmlTypeDecoder t) | s == "Difficulty" -> do g <- equalM tDifficulty tp a <- decodeAttribute "difficulty" maybe (fail "unknown difficulty level") (return . g) (readDifficulty a) | otherwise -> - decodeChild s (xmlDecoder t) - Iso p t -> from p <$> xmlDecoder t + decodeChild s (xmlTypeDecoder t) + Iso p t -> from p <$> xmlTypeDecoder t List t -> do - x <- xmlDecoder t - xs <- xmlDecoder (List t) + x <- xmlTypeDecoder t + xs <- xmlTypeDecoder (List t) return (x:xs) <|> return [] Pair t1 t2 -> do - x <- xmlDecoder t1 - y <- xmlDecoder t2 + x <- xmlTypeDecoder t1 + y <- xmlTypeDecoder t2 return (x, y) t1 :|: t2 -> - Left <$> xmlDecoder t1 <|> Right <$> xmlDecoder t2 + Left <$> xmlTypeDecoder t1 <|> Right <$> xmlTypeDecoder t2 Unit -> return () Const ctp -> case ctp of @@ -67,7 +67,7 @@ xmlDecoder tp = Context -> decodeContext Rule -> decodeRule Environment -> decodeArgEnvironment - Term -> get >>= (fromXML >=> maybe (fail "invalid OpenMath") return . fromOMOBJ) + Term -> get >>= (fromXML' >=> maybe (fail "invalid OpenMath") return . fromOMOBJ) Location -> decodeLocation StratCfg -> decodeConfiguration QCGen -> getQCGen @@ -141,13 +141,13 @@ decodeExpression = withOpenMath f decodeOMOBJ :: XMLDecoder a a decodeOMOBJ = decodeChild "OMOBJ" $ get >>= \xml -> do ex <- getExercise - omobj <- fromXML xml + omobj <- fromXML' xml case fromOpenMath ex omobj of Just a -> return a Nothing -> fail "Invalid OpenMath object for this exercise" decodeMathML :: XMLDecoder a MathML -decodeMathML = decodeFirstChild "math" $ get >>= fromXML +decodeMathML = decodeFirstChild "math" $ get >>= fromXML' decodeEnvironment :: XMLDecoder a Environment decodeEnvironment = @@ -206,4 +206,7 @@ decodeBinding = get >>= \xml -> do _ -> return (makeBinding (makeRef a) (getData xml)) where termBinding :: String -> Term -> Binding - termBinding = makeBinding . makeRef \ No newline at end of file + termBinding = makeBinding . makeRef + +fromXML' :: (Monad m, InXML a) => XML -> m a +fromXML' = maybe (fail "fromXML'") return . fromXML \ No newline at end of file diff --git a/src/Ideas/Encoding/ModeXML.hs b/src/Ideas/Encoding/ModeXML.hs index efc50394..871b2cf3 100644 --- a/src/Ideas/Encoding/ModeXML.hs +++ b/src/Ideas/Encoding/ModeXML.hs @@ -118,7 +118,7 @@ resultError options msg = do ------------------------------------------------------------ xmlEvaluator :: Evaluator a XML XMLBuilder -xmlEvaluator = Evaluator xmlDecoder xmlEncoder +xmlEvaluator = Evaluator xmlTypeDecoder xmlEncoder htmlEvaluator :: DomainReasoner -> Evaluator a XML HTMLPage -htmlEvaluator dr = Evaluator xmlDecoder (htmlEncoder dr) \ No newline at end of file +htmlEvaluator dr = Evaluator xmlTypeDecoder (htmlEncoder dr) \ No newline at end of file diff --git a/src/Ideas/Text/JSON/Class.hs b/src/Ideas/Text/JSON/Class.hs index ad61eca9..6d4e43f4 100644 --- a/src/Ideas/Text/JSON/Class.hs +++ b/src/Ideas/Text/JSON/Class.hs @@ -83,11 +83,11 @@ instance (InJSON a, InJSON b, InJSON c, InJSON d) => InJSON (a, b, c, d) where instance InJSON JSON where toJSON = id - jsonDecoder = gets (builderToJSON . snd) + jsonDecoder = gets builderToJSON instance InJSON JSONBuilder where jsonBuilder = id - jsonDecoder = gets snd + jsonDecoder = get infix 7 .= diff --git a/src/Ideas/Text/JSON/Decoder.hs b/src/Ideas/Text/JSON/Decoder.hs index b6b8f177..eb1b2c25 100644 --- a/src/Ideas/Text/JSON/Decoder.hs +++ b/src/Ideas/Text/JSON/Decoder.hs @@ -13,7 +13,7 @@ module Ideas.Text.JSON.Decoder ( GDecoderJSON, evalGDecoderJSON , DecoderJSON, evalDecoderJSON - , ErrorJSON, errorStr + , Error, errorStr , jObject, jKey, jWithKeys, jObjectWithKeys , jArray, jArrayOf, jArray0, jArray1, jArray2, jArray3 , jString, jChar, jBool, jInteger, jInt, jDouble, jFloat @@ -27,43 +27,41 @@ import Control.Monad import Ideas.Text.JSON.Builder import Ideas.Text.JSON.Data import Ideas.Utils.Decoding -import Data.List -import Data.String -type GDecoderJSON env = Decoder env ErrorJSON (Loc, JSONBuilder) +type GDecoderJSON env = Decoder env (Error JSON) JSONBuilder -evalGDecoderJSON :: GDecoderJSON env a -> env -> JSON -> Either ErrorJSON a -evalGDecoderJSON p env json = evalDecoder p env (Root 0, jsonToBuilder json) +evalGDecoderJSON :: GDecoderJSON env a -> env -> JSON -> Either (Error JSON) a +evalGDecoderJSON p env = evalDecoder p env . jsonToBuilder type DecoderJSON = GDecoderJSON () -evalDecoderJSON :: DecoderJSON a -> JSON -> Either ErrorJSON a +evalDecoderJSON :: DecoderJSON a -> JSON -> Either (Error JSON) a evalDecoderJSON p = evalGDecoderJSON p () jObject :: GDecoderJSON env a -> GDecoderJSON env a -jObject p = jFirst $ \loc a -> +jObject p = jFirst $ \a -> case a of - Just (Object xs) -> put (loc, mconcat $ map (uncurry tagJSON) xs) >> p - _ -> errorJSON NotAnObject loc a + Just (Object xs) -> put (mconcat $ map (uncurry tagJSON) xs) >> p + _ -> raiseError "not an object" a jKey :: Key -> GDecoderJSON env a -> GDecoderJSON env a -jKey k p = get >>= \(loc, xs) -> +jKey k p = get2 >>= \(loc, xs) -> case extractKey k xs of - Just (v, rest) -> put (LocKey 0 k loc, jsonToBuilder v) *> p <* put (loc, rest) - _ -> errorJSON (KeyNotFound k) loc (Just (builderToJSON xs)) + Just (v, rest) -> put2 (LocByKey 0 k loc, jsonToBuilder v) *> p <* put2 (loc, rest) + _ -> raiseError ("key '" ++ k ++ "' not found") (Just (builderToJSON xs)) jWithKeys :: (Key -> GDecoderJSON env a) -> GDecoderJSON env [a] -jWithKeys f = get >>= \(loc, xs) -> - mapM (\(k, v) -> put (LocKey 0 k loc, jsonToBuilder v) >> f k) (extractKeyAndValues xs) +jWithKeys f = get2 >>= \(loc, xs) -> + mapM (\(k, v) -> put2 (LocByKey 0 k loc, jsonToBuilder v) >> f k) (extractKeyAndValues xs) jObjectWithKeys :: (Key -> GDecoderJSON env a) -> GDecoderJSON env [a] jObjectWithKeys = jObject . jWithKeys jArray :: GDecoderJSON env a -> GDecoderJSON env a -jArray p = jFirst $ \loc a -> +jArray p = jFirst $ \a -> case a of - Just (Array xs) -> put (LocArray 0 loc, mconcat $ map jsonToBuilder xs) >> p - _ -> errorJSON NotAnArray loc a + Just (Array xs) -> changeLoc (LocByPos 0) >> put (mconcat $ map jsonToBuilder xs) >> p + _ -> raiseError "not an array" a jArrayOf :: GDecoderJSON env a -> GDecoderJSON env [a] jArrayOf p = jArray $ many p <* jEmpty @@ -81,130 +79,69 @@ jArray3 :: (a -> b -> c -> d) -> GDecoderJSON env a -> GDecoderJSON env b -> GDe jArray3 f p q r = jArray $ f <$> p <*> q <*> r <* jEmpty jString :: GDecoderJSON env String -jString = jFirst $ \loc a -> +jString = jFirst $ \a -> case a of Just (String s) -> return s - _ -> errorJSON NotAString loc a + _ -> raiseError "not a string" a jChar :: GDecoderJSON env Char -jChar = jFirst $ \loc a -> +jChar = jFirst $ \a -> case a of Just (String [c]) -> return c - _ -> errorJSON NotAChar loc a + _ -> raiseError "not a char" a jBool :: GDecoderJSON env Bool -jBool = jFirst $ \loc a -> +jBool = jFirst $ \a -> case a of Just (Boolean b) -> return b - _ -> errorJSON NotABoolean loc a + _ -> raiseError "not a boolean" a jInteger :: GDecoderJSON env Integer -jInteger = jFirst $ \loc a -> +jInteger = jFirst $ \a -> case a of Just (Integer i) -> return i - _ -> errorJSON NotAnInteger loc a + _ -> raiseError "not an integer" a jInt :: GDecoderJSON env Int jInt = fromInteger <$> jInteger jDouble :: GDecoderJSON env Double -jDouble = jFirst $ \loc a -> +jDouble = jFirst $ \a -> case a of Just (Double d) -> return d - _ -> errorJSON NotADouble loc a + _ -> raiseError "not a double" a jFloat :: GDecoderJSON env Float jFloat = realToFrac <$> jDouble jNull :: GDecoderJSON env () -jNull = jFirst $ \loc a -> +jNull = jFirst $ \a -> case a of - Just (Null) -> return () - _ -> errorJSON NotNull loc a + Just Null -> return () + _ -> raiseError "not null" a jEmpty :: GDecoderJSON env () -jEmpty = get >>= \(loc, xs) -> - unless (isEmptyBuilder xs) (errorJSON NotEmpty loc (Just (builderToJSON xs))) +jEmpty = get >>= \xs -> + unless (isEmptyBuilder xs) (raiseError "not empty" (Just (builderToJSON xs))) jSkip :: GDecoderJSON env () jSkip = jNext $ const $ return () jNext :: (JSON -> Either String a) -> GDecoderJSON env a -jNext f = jFirst $ \loc mjson -> +jNext f = jFirst $ \mjson -> case fmap f mjson of Just res -> either errorStr return res - Nothing -> errorJSON NoNextElement loc Nothing + Nothing -> raiseError "no next element" Nothing -- local helper: not exported -jFirst :: (Loc -> Maybe JSON -> GDecoderJSON env a) -> GDecoderJSON env a -jFirst f = get >>= \(loc, xs) -> +jFirst :: (Maybe JSON -> GDecoderJSON env a) -> GDecoderJSON env a +jFirst f = get >>= \xs -> case extractFirst xs of - Just (json, rest) -> f loc (Just json) <* put (nextLoc loc, rest) - _ -> f loc Nothing - --------------------------------------------------------------------------------- --- Errors - -newtype ErrorJSON = E [Either String (ErrorType, Loc, Maybe JSON)] - -instance Show ErrorJSON where - show (E xs) - | null xs = "Parse error in JSON" - | otherwise = unlines (map (either id f) xs) - where - - f (tp, loc, mjson) = unlines - [ "Parse error: " ++ show tp - , " * Location: " ++ show loc - , " * Found: " ++ maybe "" show mjson - ] - -data ErrorType - = NotAnObject | NotAnArray | NotAString | NotAChar | NotABoolean | NotAnInteger | NotADouble - | NotNull | NotEmpty | KeyNotFound Key | NoNextElement - -instance Show ErrorType where - show NotAnObject = "not an object" - show NotAnArray = "not an array" - show NotAString = "not a string" - show NotAChar = "not a char" - show NotABoolean = "not a boolean" - show NotAnInteger = "not an integer" - show NotADouble = "not a double" - show NotNull = "not null" - show NotEmpty = "not empty" - show (KeyNotFound k) = "key '" ++ k ++ "' not found" - show NoNextElement = "no next element" - -instance IsString ErrorJSON where - fromString s = E [Left s] - -instance Semigroup ErrorJSON where - E xs <> E ys = E (xs <> ys) - -instance Monoid ErrorJSON where - mempty = E [] - -data Loc = Root Int | LocArray Int Loc | LocKey Int Key Loc - -instance Show Loc where - show loc - | null parts = "root" - | otherwise = intercalate "." parts - where - parts = collect loc - - collect (Root n) = [ "root+" ++ show n | n > 0 ] - collect (LocArray n l) = collect l ++ [show n] - collect (LocKey n k l) = collect l ++ [k ++ if n==0 then "" else "+" ++ show n] - -nextLoc :: Loc -> Loc -nextLoc (Root n) = Root (n+1) -nextLoc (LocArray n l) = LocArray (n+1) l -nextLoc (LocKey n k l) = LocKey (n+1) k l - -errorStr :: String -> GDecoderJSON env a -errorStr = throwError . fromString - -errorJSON :: ErrorType -> Loc -> Maybe JSON -> GDecoderJSON env a -errorJSON tp loc a = throwError $ E [Right (tp, loc, a)] \ No newline at end of file + Just (json, rest) -> f (Just json) <* changeLoc nextLoc <* put rest + _ -> f Nothing + +get2 :: GDecoderJSON env (Loc, JSONBuilder) +get2 = (,) <$> getLoc <*> get + +put2 :: (Loc, JSONBuilder) -> GDecoderJSON env () +put2 (loc, xs) = putLoc loc >> put xs \ No newline at end of file diff --git a/src/Ideas/Text/OpenMath/Object.hs b/src/Ideas/Text/OpenMath/Object.hs index f2eeeab4..121b572a 100644 --- a/src/Ideas/Text/OpenMath/Object.hs +++ b/src/Ideas/Text/OpenMath/Object.hs @@ -19,7 +19,9 @@ import Data.Generics.Uniplate.Direct hiding (children) import Data.List (nub) import Data.Maybe import Ideas.Text.OpenMath.Symbol +import Ideas.Text.XML.Decoder import Ideas.Text.XML +import Ideas.Utils.Decoding -- internal representation for OpenMath objects data OMOBJ = OMI Integer @@ -33,9 +35,25 @@ data OMOBJ = OMI Integer instance ToXML OMOBJ where toXML = omobj2xml -instance InXML OMOBJ where - fromXML = either fail return . xml2omobj +-- maf = fromXML (toXML (OMA [OMS (Nothing, "fac"), OMS (Just "arith", "plus"), OMV "f", OMBIND (OMI 13) ["x","y"] (OMI 14), OMF 42])) :: Maybe OMOBJ +instance InXML OMOBJ where +-- fromXML = either fail return . xml2omobj + + xmlDecoder = xTag "OMOBJ" rec + where + rec = xTag "OMA" (OMA <$> many rec) + <|> xTag "OMS" (makeOMS <$> optional (xAttr "cd") <*> xAttr "name") + <|> xTag "OMI" (OMI . fromJust . readInt <$> xString) + <|> xTag "OMF" (OMF . fromJust . readDouble <$> xAttr "dec") + <|> xTag "OMV" (OMV <$> xAttr "name") + <|> xTag "OMBIND" (OMBIND <$> rec <*> recOMBVar <*> rec) + + recOMBVar = xTag "OMBVAR" (many (xTag "OMV" (xAttr "name"))) + + makeOMS (Just "unknown") a = OMS (Nothing, a) + makeOMS cd a = OMS (cd, a) + instance Uniplate OMOBJ where uniplate omobj = case omobj of @@ -50,58 +68,7 @@ getOMVs omobj = nub [ x | OMV x <- universe omobj ] -- conversion functions: XML <-> OMOBJ xml2omobj :: XML -> Either String OMOBJ -xml2omobj xmlTop - | name xmlTop == "OMOBJ" = - case children xmlTop of - [x] -> rec x - _ -> fail "invalid omobj" - | otherwise = fail "expected an OMOBJ tag" - where - rec xml = - case name xml of - "OMA" -> do - ys <- mapM rec (children xml) - return (OMA ys) - - "OMS" | emptyContent xml -> do - let mcd = case findAttribute "cd" xml of - Just "unknown" -> Nothing - this -> this - n <- findAttribute "name" xml - return (OMS (mcd, n)) - - "OMI" | name xml == "OMI" -> - case readInt (getData xml) of - Just i -> return (OMI (toInteger i)) - _ -> fail "invalid integer in OMI" - - "OMF" | emptyContent xml -> do - s <- findAttribute "dec" xml - case readDouble s of - Just nr -> return (OMF nr) - _ -> fail "invalid floating-point in OMF" - - "OMV" | emptyContent xml -> do - s <- findAttribute "name" xml - return (OMV s) - - "OMBIND" -> - case children xml of - [x1, x2, x3] -> do - y1 <- rec x1 - y2 <- recOMBVAR x2 - y3 <- rec x3 - return (OMBIND y1 y2 y3) - _ -> fail "invalid ombind" - _ -> fail ("invalid tag " ++ name xml) - - recOMBVAR xml - | name xml == "OMBVAR" = - let f (Right (OMV s)) = return s - f this = fail $ "expected tag OMV in OMBVAR, but found " ++ show this - in mapM (f . rec) (children xml) - | otherwise = - fail ("expected tag OMVAR, but found " ++ show (name xml)) +xml2omobj = either (Left . show) (Right . fst) . runDecoder xmlDecoder () . builder omobj2xml :: OMOBJ -> XML omobj2xml object = makeXML "OMOBJ" $ mconcat diff --git a/src/Ideas/Text/UTF8.hs b/src/Ideas/Text/UTF8.hs index f2d9f5a2..1b264252 100644 --- a/src/Ideas/Text/UTF8.hs +++ b/src/Ideas/Text/UTF8.hs @@ -47,21 +47,21 @@ allBytes = all ((`between` (0, 255)) . ord) toUTF8 :: Int -> Maybe [Int] toUTF8 n | n < 128 = -- one byte - return [n] + Just [n] | n < 2048 = -- two bytes let (a, d) = n `divMod` 64 - in return [a+192, d+128] + in Just [a+192, d+128] | n < 65536 = -- three bytes let (a, d1) = n `divMod` 4096 (b, d2) = d1 `divMod` 64 - in return [a+224, b+128, d2+128] + in Just [a+224, b+128, d2+128] | n < 1114112 = -- four bytes let (a, d1) = n `divMod` 262144 (b, d2) = d1 `divMod` 4096 (c, d3) = d2 `divMod` 64 - in return [a+240, b+128, c+128, d3+128] + in Just [a+240, b+128, c+128, d3+128] | otherwise = - fail "invalid character in UTF8" + Nothing fromUTF8 :: [Int] -> Maybe [Int] fromUTF8 xs @@ -72,21 +72,20 @@ fromUTF8 xs return (i:is) where f (a:rest) | a < 128 = -- one byte - return (a, rest) - f (a:b:rest) | a `between` (192, 223) = do -- two bytes - unless (isHigh b) $ - fail "invalid UTF8 character (two bytes)" - return ((a-192)*64 + b-128, rest) - f (a:b:c:rest) | a `between` (224, 239) = do -- three bytes - unless (isHigh b && isHigh c) $ - fail "invalid UTF8 character (three bytes)" - return ((a-224)*4096 + (b-128)*64 + c-128, rest) - f (a:b:c:d:rest) | a >= 240 && a < 248 = do -- four bytes + Just (a, rest) + f (a:b:rest) | a `between` (192, 223) = -- two bytes + checked (isHigh b) + ((a-192)*64 + b-128, rest) + f (a:b:c:rest) | a `between` (224, 239) = -- three bytes + checked (isHigh b && isHigh c) + ((a-224)*4096 + (b-128)*64 + c-128, rest) + f (a:b:c:d:rest) | a >= 240 && a < 248 = -- four bytes let value = (a-240)*262144 + (b-128)*4096 + (c-128)*64 + d-128 - unless (isHigh b && isHigh c && isHigh d && value <= 1114111) $ - fail "invalid UTF8 character (four bytes)" - return (value, rest) - f _ = fail "invalid character in UTF8" + in checked (isHigh b && isHigh c && isHigh d && value <= 1114111) (value, rest) + f _ = Nothing + +checked :: Bool -> a -> Maybe a +checked b a = if b then Just a else Nothing isHigh :: Int -> Bool isHigh i = i `between` (128, 191) diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index b3cb1390..d0d80eb4 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -27,7 +27,7 @@ module Ideas.Text.XML -- * Decoding XML , decodeData, decodeAttribute, decodeChild, decodeFirstChild -- * Type classes for converting to/from XML - , ToXML(..), builderXML, InXML(..) + , ToXML(..), builderXML, InXML(..), DecoderXML -- * Processing XML , foldXML, trimXML -- * Deprecated functions @@ -35,42 +35,17 @@ module Ideas.Text.XML ) where import Control.Monad.State -import Data.Char (chr, ord, isSpace) -import Data.Foldable (toList) -import Data.List +import Data.Char (chr) import Data.Maybe -import Data.Semigroup as Sem -import Data.String -import Ideas.Text.XML.Document (escape, Name, prettyElement) +import Ideas.Text.XML.Builder +import Ideas.Text.XML.Data +import Ideas.Text.XML.Document (escape, Name) import Ideas.Text.XML.Parser (document) -import Ideas.Text.XML.Unicode import Ideas.Utils.Decoding import Ideas.Utils.Parsing (parseSimple) import System.IO -import qualified Data.Map as M -import qualified Data.Sequence as Seq import qualified Ideas.Text.XML.Document as D -------------------------------------------------------------------------------- --- XML types - --- invariants content: no two adjacent Lefts, no Left with empty string, --- valid tag/attribute names -data XML = Tag - { name :: Name - , attributes :: Attributes - , content :: [Either String XML] - } - deriving Eq - -instance Show XML where - show = compactXML - -type Attributes = [Attribute] - -data Attribute = Name := String - deriving Eq - ------------------------------------------------------------------------------- -- Parsing XML @@ -121,104 +96,6 @@ fromXMLDoc doc = fromElement (D.root doc) general :: [(String, Char)] general = [("lt",'<'), ("gt",'>'), ("amp",'&'), ("apos",'\''), ("quot",'"')] -------------------------------------------------------------------------------- --- Building/constructing XML - -infix 7 .=. - -class (Sem.Semigroup a, Monoid a) => BuildXML a where - (.=.) :: String -> String -> a -- attribute - string :: String -> a -- (escaped) text - builder :: XML -> a -- (named) xml element - tag :: String -> a -> a -- tag (with content) - -- functions with a default - char :: Char -> a - text :: Show s => s -> a -- escaped text with Show class - element :: String -> [a] -> a - emptyTag :: String -> a - -- implementations - char c = string [c] - text = string . show - element s = tag s . mconcat - emptyTag s = tag s mempty - -instance BuildXML a => BuildXML (Decoder env err s a) where - n .=. s = pure (n .=. s) - string = pure . string - builder = pure . builder - tag = fmap . tag - -data XMLBuilder = BS (Seq.Seq Attribute) (Seq.Seq (Either String XML)) - -instance Sem.Semigroup XMLBuilder where - BS as1 elts1 <> BS as2 elts2 = BS (as1 <> as2) (elts1 <> elts2) - -instance Monoid XMLBuilder where - mempty = BS mempty mempty - mappend = (<>) - -instance BuildXML XMLBuilder where - n .=. s = nameCheck n $ BS (Seq.singleton (n := s)) mempty - string s = BS mempty (if null s then mempty else Seq.singleton (Left s)) - builder = BS mempty . Seq.singleton . Right - tag n = builder . uncurry (Tag n) . fromBS . nameCheck n - -instance IsString XMLBuilder where - fromString = string - -makeXML :: String -> XMLBuilder -> XML -makeXML s = uncurry (Tag s) . fromBS . nameCheck s - -nameCheck :: String -> a -> a -nameCheck s = if isName s then id else fail $ "Invalid name " ++ s - -isName :: String -> Bool -isName [] = False -isName (x:xs) = (isLetter x || x `elem` "_:") && all isNameChar xs - -isNameChar :: Char -> Bool -isNameChar c = any ($ c) [isLetter, isDigit, isCombiningChar, isExtender, (`elem` ".-_:")] - --- local helper: merge attributes, but preserve order -fromBS :: XMLBuilder -> (Attributes, [Either String XML]) -fromBS (BS as elts) = (attrList, merge (toList elts)) - where - attrMap = foldr add M.empty as - add (k := v) = M.insertWith (\x y -> x ++ " " ++ y) k v - attrList = nubBy eqKey (map make (toList as)) - make (k := _) = k := M.findWithDefault "" k attrMap - eqKey (k1 := _) (k2 := _) = k1 == k2 - - merge [] = [] - merge (Left x:Left y:rest) = merge (Left (x++y):rest) - merge (Left x:rest) = Left x : merge rest - merge (Right y:rest) = Right y : merge rest - -------------------------------------------------------------------------------- --- Pretty-printing XML - -prettyXML :: XML -> String -prettyXML = show . prettyElement False . toElement - -compactXML :: XML -> String -compactXML = show . prettyElement True . toElement - -toElement :: XML -> D.Element -toElement = foldXML make mkAttribute mkString - where - make n as = D.Element n as . concatMap (either id (return . D.Tagged)) - - mkAttribute :: Attribute -> D.Attribute - mkAttribute (m := s) = (D.:=) m (map Left s) - - mkString :: String -> [D.XML] - mkString [] = [] - mkString xs@(hd:tl) - | null xs1 = D.Reference (D.CharRef (ord hd)) : mkString tl - | otherwise = D.CharData xs1 : mkString xs2 - where - (xs1, xs2) = break ((> 127) . ord) xs - ------------------------------------------------------------------------------- -- Simple decoding queries @@ -305,34 +182,26 @@ instance ToXML a => ToXML (Maybe a) where builderXML :: (ToXML a, BuildXML b) => a -> b builderXML = builder . toXML -class ToXML a => InXML a where - fromXML :: Monad m => XML -> m a - listFromXML :: Monad m => XML -> m [a] - listFromXML xml - | name xml == "list" && null (attributes xml) = - mapM fromXML (children xml) - | otherwise = fail "expecting a list tag" +type DecoderXML = Decoder () (Error XML) XMLBuilder -------------------------------------------------------------------------------- --- Processing XML - -foldXML :: (Name -> [a] -> [Either s e] -> e) -> (Attribute -> a) -> (String -> s) -> XML -> e -foldXML fe fa fs = rec - where - rec (Tag n as cs) = fe n (map fa as) (map (either (Left . fs) (Right . rec)) cs) - -trimXML :: XML -> XML -trimXML = foldXML make fa (string . trim) - where - fa (n := s) = n .=. trim s +class ToXML a => InXML a where + fromXML :: XML -> Maybe a + --listFromXML :: XML -> Maybe [a] -- to be removed + xmlDecoder :: DecoderXML a - make :: String -> [XMLBuilder] -> [Either XMLBuilder XML] -> XML - make s as = makeXML s . mconcat . (as ++) . map (either id builder) + {-# MINIMAL fromXML | xmlDecoder #-} -trim, trimLeft, trimRight :: String -> String -trim = trimLeft . trimRight -trimLeft = dropWhile isSpace -trimRight = reverse . trimLeft . reverse + -- default definitions + -- listFromXML xml + -- | name xml == "list" && null (attributes xml) = + -- mapM fromXML (children xml) + -- | otherwise = fail "expecting a list tag" + fromXML xml = either (const Nothing) Just $ evalDecoder xmlDecoder () (builder (trimXML xml)) + xmlDecoder = do + b <- get + case fromBS b of + ([], [Right xml]) -> maybe (errorStr "xml-decoder") return (fromXML xml) + _ -> errorStr "xml-decoder" ------------------------------------------------------------------------------- -- Deprecated functions diff --git a/src/Ideas/Text/XML/Builder.hs b/src/Ideas/Text/XML/Builder.hs new file mode 100644 index 00000000..b0a82b93 --- /dev/null +++ b/src/Ideas/Text/XML/Builder.hs @@ -0,0 +1,91 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +-- to do: hide local function fromBS + +module Ideas.Text.XML.Builder + ( BuildXML(..) + , XMLBuilder, makeXML, fromBS + ) where + +import Data.List (nubBy) +import Data.Foldable (toList) +import Data.String +import qualified Data.Sequence as Seq +import qualified Data.Map as M +import Ideas.Text.XML.Data +import Ideas.Utils.Decoding + +infix 7 .=. + +class (Semigroup a, Monoid a) => BuildXML a where + (.=.) :: String -> String -> a -- attribute + string :: String -> a -- (escaped) text + builder :: XML -> a -- (named) xml element + tag :: String -> a -> a -- tag (with content) + -- functions with a default + char :: Char -> a + text :: Show s => s -> a -- escaped text with Show class + element :: String -> [a] -> a + emptyTag :: String -> a + -- implementations + char c = string [c] + text = string . show + element s = tag s . mconcat + emptyTag s = tag s mempty + +instance BuildXML a => BuildXML (Decoder env err s a) where + n .=. s = pure (n .=. s) + string = pure . string + builder = pure . builder + tag = fmap . tag + +------------------------------------------------------------------- + +data XMLBuilder = BS (Seq.Seq Attribute) (Seq.Seq (Either String XML)) + +instance Semigroup XMLBuilder where + BS as1 elts1 <> BS as2 elts2 = BS (as1 <> as2) (elts1 <> elts2) + +instance Monoid XMLBuilder where + mempty = BS mempty mempty + mappend = (<>) + +instance BuildXML XMLBuilder where + n .=. s = nameCheck n $ BS (Seq.singleton (n := s)) mempty + string s = BS mempty (if null s then mempty else Seq.singleton (Left s)) + builder = BS mempty . Seq.singleton . Right + tag n = builder . uncurry (Tag n) . fromBS . nameCheck n + +instance IsString XMLBuilder where + fromString = string + +makeXML :: String -> XMLBuilder -> XML +makeXML s = uncurry (Tag s) . fromBS . nameCheck s + +nameCheck :: String -> a -> a +nameCheck s = if validName s then id else error $ "Invalid name for xml tag: " ++ s + +-- local helper: merge attributes, but preserve order +fromBS :: XMLBuilder -> (Attributes, [Either String XML]) +fromBS (BS as elts) = (attrList, merge (toList elts)) + where + attrMap = foldr add M.empty as + add (k := v) = M.insertWith (\x y -> x ++ " " ++ y) k v + attrList = nubBy eqKey (map make (toList as)) + make (k := _) = k := M.findWithDefault "" k attrMap + eqKey (k1 := _) (k2 := _) = k1 == k2 + + merge [] = [] + merge (Left x:Left y:rest) = merge (Left (x++y):rest) + merge (Left x:rest) = Left x : merge rest + merge (Right y:rest) = Right y : merge rest \ No newline at end of file diff --git a/src/Ideas/Text/XML/Data.hs b/src/Ideas/Text/XML/Data.hs new file mode 100644 index 00000000..c8ccf7ea --- /dev/null +++ b/src/Ideas/Text/XML/Data.hs @@ -0,0 +1,97 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +-- to do: protect constructor Tag and invariant + +module Ideas.Text.XML.Data + ( -- types + XML(..), Attributes, Attribute(..) + , D.Name, validName + -- pretty-printing + , prettyXML, compactXML + -- processing + , foldXML, trimXML + ) where + +import Data.Char (isSpace, ord) +import qualified Ideas.Text.XML.Document as D +import Ideas.Text.XML.Unicode + +------------------------------------------------------------------------------- +-- XML types + +-- invariants content: no two adjacent Lefts, no Left with empty string, +-- valid tag/attribute names +data XML = Tag + { name :: D.Name + , attributes :: Attributes + , content :: [Either String XML] + } + deriving Eq + +instance Show XML where + show = compactXML + +type Attributes = [Attribute] + +data Attribute = D.Name := String + deriving Eq + +validName :: String -> Bool +validName [] = False +validName (x:xs) = (isLetter x || x `elem` "_:") && all validNameChar xs + +validNameChar :: Char -> Bool +validNameChar c = any ($ c) [isLetter, isDigit, isCombiningChar, isExtender, (`elem` ".-_:")] + +------------------------------------------------------------------------------- +-- Pretty-printing XML + +prettyXML :: XML -> String +prettyXML = show . D.prettyElement False . toElement + +compactXML :: XML -> String +compactXML = show . D.prettyElement True . toElement + +toElement :: XML -> D.Element +toElement = foldXML make mkAttribute mkString + where + make n as = D.Element n as . concatMap (either id (return . D.Tagged)) + + mkAttribute :: Attribute -> D.Attribute + mkAttribute (m := s) = (D.:=) m (map Left s) + + mkString :: String -> [D.XML] + mkString [] = [] + mkString xs@(hd:tl) + | null xs1 = D.Reference (D.CharRef (ord hd)) : mkString tl + | otherwise = D.CharData xs1 : mkString xs2 + where + (xs1, xs2) = break ((> 127) . ord) xs + +------------------------------------------------------------------------------- +-- Processing XML + +foldXML :: (D.Name -> [a] -> [Either s e] -> e) -> (Attribute -> a) -> (String -> s) -> XML -> e +foldXML fe fa fs = rec + where + rec (Tag n as cs) = fe n (map fa as) (map (either (Left . fs) (Right . rec)) cs) + +trimXML :: XML -> XML +trimXML = foldXML Tag f trim + where + f (n := s) = n := trim s + +trim, trimLeft, trimRight :: String -> String +trim = trimLeft . trimRight +trimLeft = dropWhile isSpace +trimRight = reverse . trimLeft . reverse \ No newline at end of file diff --git a/src/Ideas/Text/XML/Decoder.hs b/src/Ideas/Text/XML/Decoder.hs new file mode 100644 index 00000000..40f0ebeb --- /dev/null +++ b/src/Ideas/Text/XML/Decoder.hs @@ -0,0 +1,72 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +module Ideas.Text.XML.Decoder + ( DecoderXML, evalDecoderXML + , Error, errorStr + , xTag, xString, xAttr, xEnd + -- re-exports + , Alternative(..), MonadReader(..), throwError + ) where + +import Ideas.Utils.Decoding +import Ideas.Text.XML.Data +import Ideas.Text.XML.Builder + +type DecoderXML = Decoder () (Error XML) XMLBuilder + +evalDecoderXML :: DecoderXML a -> XML -> Either (Error XML) a +evalDecoderXML p = evalDecoder p () . builder + +xTag :: String -> DecoderXML a -> DecoderXML a +xTag s p = do + xml <- get + case fromBS xml of + (as, Right hd:rest) | name hd == s -> do + put (conv (attributes hd) (content hd)) + a <- p + xEnd + put (conv as rest) + return a + _ -> errorStr "xTag" + +xString :: DecoderXML String +xString = do + xml <- get + case fromBS xml of + (as, Left s:rest) -> do + put (conv as rest) + return s + _ -> errorStr "xString" + +xAttr :: String -> DecoderXML String +xAttr s = do + xml <- get + let (as, _) = fromBS xml + case filter (\(n := _) -> n == s) as of + [_ := v] -> return v + _ -> errorStr "xAttr" + +xEnd :: DecoderXML () +xEnd = do + xml <- get + case fromBS xml of + (_, []) -> do + return () + _ -> errorStr "xEnd" + +conv :: Attributes -> [Either String XML] -> XMLBuilder +conv as xs = mconcat (map f as ++ map g xs) + where + f (n := s) = n .=. s + g (Left s) = string s + g (Right a) = builder a \ No newline at end of file diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index ab9274e2..8a6542d8 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances, MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -12,23 +12,27 @@ ----------------------------------------------------------------------------- module Ideas.Utils.Decoding - ( Decoder, evalDecoder, runDecoder, mapError + ( Decoder, evalDecoder, runDecoder, mapError, getLoc, putLoc, changeLoc , Encoder, runEncoder + , Error, ErrorType, Loc(..), nextLoc, raiseError, errorStr -- re-exports - , Alternative(..), MonadReader(..), MonadState(..), MonadError(..) + , Alternative(..), optional, MonadReader(..), MonadState(..), MonadError(..) , gets ) where +import Control.Arrow import Control.Applicative import Control.Monad import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State +import Data.List +import Data.String ------------------------------------------------------------------- -newtype Decoder env err s a = Dec { fromDec :: StateT s (ReaderT env (Except err)) a } - deriving (Functor, Applicative, Alternative, MonadPlus, MonadReader env, MonadState s, MonadError err) +newtype Decoder env err s a = Dec { fromDec :: StateT (Loc, s) (ReaderT env (Except err)) a } + deriving (Functor, Applicative, Alternative, MonadPlus, MonadReader env, MonadError err) instance Semigroup a => Semigroup (Decoder env err s a) where (<>) = liftA2 (<>) @@ -42,8 +46,11 @@ instance Monad (Decoder env err s) where Dec m >>= f = Dec $ m >>= fromDec . f fail msg = error $ "fail in Decoder: " ++ msg +instance MonadState s (Decoder env err s) where + state f = Dec $ state $ \(loc, s) -> let (a, s') = f s in (a, (loc, s')) + runDecoder :: Decoder env err s a -> env -> s -> Either err (a, s) -runDecoder p env s = runExcept (runReaderT (runStateT (fromDec p) s) env) +runDecoder p env s = fmap snd <$> runExcept (runReaderT (runStateT (fromDec p) (Root 0, s)) env) evalDecoder :: Decoder env err s a -> env -> s -> Either err a evalDecoder p env = fmap fst . runDecoder p env @@ -56,9 +63,72 @@ mapError f p = do Left e1 -> throwError (f e1) Right (a, s2) -> put s2 >> return a +getLoc :: Decoder env err s Loc +getLoc = Dec $ gets fst + +putLoc :: Loc -> Decoder env err s () +putLoc = changeLoc . const + +changeLoc :: (Loc -> Loc) -> Decoder env err s () +changeLoc = Dec . modify . first + ------------------------------------------------------------------- type Encoder env err = Decoder env err () runEncoder :: Encoder env err a -> env -> Either err a -runEncoder p env = evalDecoder p env () \ No newline at end of file +runEncoder p env = evalDecoder p env () + +-------------------------------------------------------------------------------- +-- Errors + +newtype Error a = E [Either String (ErrorType, Loc, Maybe a)] + +type ErrorType = String + +instance Show a => Show (Error a) where + show (E xs) + | null xs = "Parse error" + | otherwise = unlines (map (either id f) xs) + where + + f (tp, loc, ma) = unlines + [ "Parse error: " ++ tp + , " * Location: " ++ show loc + , " * Found: " ++ maybe "" show ma + ] + +instance IsString (Error a) where + fromString s = E [Left s] + +instance Semigroup (Error a) where + E xs <> E ys = E (xs <> ys) + +instance Monoid (Error a) where + mempty = E [] + +data Loc = Root Int | LocByPos Int Loc | LocByKey Int String Loc + +instance Show Loc where + show loc + | null parts = "root" + | otherwise = intercalate "." parts + where + parts = collect loc + + collect (Root n) = [ "root+" ++ show n | n > 0 ] + collect (LocByPos n l) = collect l ++ [show n] + collect (LocByKey n k l) = collect l ++ [k ++ if n==0 then "" else "+" ++ show n] + +nextLoc :: Loc -> Loc +nextLoc (Root n) = Root (n+1) +nextLoc (LocByPos n l) = LocByPos (n+1) l +nextLoc (LocByKey n k l) = LocByKey (n+1) k l + +errorStr :: IsString err => String -> Decoder env err s a +errorStr = throwError . fromString + +raiseError :: ErrorType -> Maybe a -> Decoder env (Error a) s b +raiseError tp a = do + loc <- getLoc + throwError $ E [Right (tp, loc, a)] \ No newline at end of file From aa5264b6e9427c88a6e978903774077eefd1c1c9 Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 28 Mar 2022 09:59:44 +0200 Subject: [PATCH 38/57] refactoring / redesign xml --- src/Ideas/Encoding/DecoderXML.hs | 6 +- src/Ideas/Encoding/LinkManager.hs | 2 +- src/Ideas/Encoding/ModeXML.hs | 9 +-- src/Ideas/Encoding/StrategyInfo.hs | 17 ++--- src/Ideas/Text/HTML.hs | 2 +- src/Ideas/Text/MathML.hs | 95 +++++++++++-------------- src/Ideas/Text/OpenMath/Object.hs | 6 +- src/Ideas/Text/XML.hs | 94 ++++++++++++++---------- src/Ideas/Text/XML/Builder.hs | 40 ++++++----- src/Ideas/Text/XML/Data.hs | 110 +++++++++++++++++++++++++---- src/Ideas/Text/XML/Decoder.hs | 42 ++++------- src/Ideas/Text/XML/Document.hs | 58 +++++++++++---- src/Ideas/Text/XML/Parser.hs | 13 ++-- 13 files changed, 298 insertions(+), 196 deletions(-) diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index c703b2af..81c23a61 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -155,8 +155,8 @@ decodeEnvironment = <|> return mempty where add env item = do - unless (name item == "item") $ - fail $ "expecting item tag, found " ++ name item + unless (show (name item) == "item") $ + fail $ "expecting item tag, found " ++ show (name item) n <- findAttribute "name" item req <- getRequest case findChild "OMOBJ" item of @@ -181,7 +181,7 @@ decodeConfiguration = decodeChild "configuration" $ where decodeAction item = do guard (null (children item)) - action <- maybe (fail "invalid action") return $ readM (name item) + action <- maybe (fail "invalid action") return $ readM (show (name item)) cfgloc <- findAttribute "name" item return (action `byName` newId cfgloc) diff --git a/src/Ideas/Encoding/LinkManager.hs b/src/Ideas/Encoding/LinkManager.hs index 0fac7d54..1e12a7eb 100644 --- a/src/Ideas/Encoding/LinkManager.hs +++ b/src/Ideas/Encoding/LinkManager.hs @@ -169,7 +169,7 @@ simpleRequest :: String -> XML simpleRequest s = makeRequest s mempty makeRequest :: String -> XMLBuilder -> XML -makeRequest s rest = makeXML "request" $ +makeRequest s rest = makeXML (fromString "request") $ ("service" .=. s) <> ("encoding" .=. "html") <> rest diff --git a/src/Ideas/Encoding/ModeXML.hs b/src/Ideas/Encoding/ModeXML.hs index 871b2cf3..ad4c0987 100644 --- a/src/Ideas/Encoding/ModeXML.hs +++ b/src/Ideas/Encoding/ModeXML.hs @@ -16,6 +16,7 @@ module Ideas.Encoding.ModeXML (processXML) where import Control.Exception import Control.Monad +import Data.String import Ideas.Common.Library hiding (exerciseId) import Ideas.Encoding.DecoderXML import Ideas.Encoding.EncoderHTML @@ -52,12 +53,12 @@ processXML options dr txt = do addVersion :: String -> XML -> XML addVersion s xml = - let info = [ "version" := s ] + let info = [ fromString "version" := s ] in xml { attributes = attributes xml ++ info } xmlRequest :: Monad m => Maybe String -> XML -> m Request xmlRequest ms xml = do - unless (name xml == "request") $ + unless (show (name xml) == "request") $ fail "expected xml tag request" enc <- case findAttribute "encoding" xml of Just s -> readEncoding s @@ -104,14 +105,14 @@ extractExerciseId :: Monad m => XML -> m Id extractExerciseId = fmap newId . findAttribute "exerciseid" resultOk :: XMLBuilder -> XML -resultOk body = makeXML "reply" $ +resultOk body = makeXML (fromString "reply") $ ("result" .=. "ok") <> body resultError :: Options -> String -> IO XML resultError options msg = do changeLog (logRef options) (\r -> r {errormsg = msg}) - return $ makeXML "reply" $ + return $ makeXML (fromString "reply") $ ("result" .=. "error") <> tag "message" (string msg) diff --git a/src/Ideas/Encoding/StrategyInfo.hs b/src/Ideas/Encoding/StrategyInfo.hs index ac8f1167..8fcec098 100644 --- a/src/Ideas/Encoding/StrategyInfo.hs +++ b/src/Ideas/Encoding/StrategyInfo.hs @@ -14,6 +14,7 @@ module Ideas.Encoding.StrategyInfo (strategyToXML) where +import Data.String import Ideas.Common.Id import Ideas.Common.Strategy.Abstract import Ideas.Common.Strategy.Configuration @@ -31,7 +32,7 @@ nameAttr :: Id -> XMLBuilder nameAttr info = "name" .=. showId info strategyTreeToXML :: StrategyTree a -> XML -strategyTreeToXML tree = makeXML "label" $ +strategyTreeToXML tree = makeXML (fromString "label") $ case isLabel tree of Just (l, a) -> nameAttr l <> strategyTreeBuilder a _ -> strategyTreeBuilder tree @@ -42,21 +43,21 @@ strategyTreeBuilder = builder . fold emptyAlg case xs of [x] | isConfigId def -> addProperty (show def) x - _ -> makeXML (show def) (mconcat (map builder xs)) + _ -> makeXML (fromString (show def)) (mconcat (map builder xs)) , fLeaf = \r -> - makeXML "rule" ("name" .=. show r) + makeXML (fromString "rule") ("name" .=. show r) , fLabel = \l a -> - makeXML "label" (nameAttr l <> builder a) + makeXML (fromString "label") (nameAttr l <> builder a) , fRec = \n a -> - makeXML "rec" (("var" .=. show n) <> builder a) + makeXML (fromString "rec") (("var" .=. show n) <> builder a) , fVar = \n -> - makeXML "var" ("var" .=. show n) + makeXML (fromString "var") ("var" .=. show n) } addProperty :: String -> XML -> XML addProperty s a = - if name a `elem` ["label", "rule"] - then a { attributes = attributes a ++ [s := "true"] } + if show (name a) `elem` ["label", "rule"] + then a { attributes = attributes a ++ [fromString s := "true"] } else a ----------------------------------------------------------------------- diff --git a/src/Ideas/Text/HTML.hs b/src/Ideas/Text/HTML.hs index f87f10c8..7a7cf752 100644 --- a/src/Ideas/Text/HTML.hs +++ b/src/Ideas/Text/HTML.hs @@ -86,7 +86,7 @@ data HTMLPage = HTMLPage } instance ToXML HTMLPage where - toXML page = makeXML "html" $ + toXML page = makeXML (fromString "html") $ element "head" [ tag "title" (string (title page)) , mconcat diff --git a/src/Ideas/Text/MathML.hs b/src/Ideas/Text/MathML.hs index fd216b49..91a5ce79 100644 --- a/src/Ideas/Text/MathML.hs +++ b/src/Ideas/Text/MathML.hs @@ -14,9 +14,10 @@ module Ideas.Text.MathML ( MathML(..), xml2mathml, mathml2xml ) where -import Data.Maybe import Ideas.Text.XML +import Ideas.Text.XML.Decoder import Ideas.Utils.Uniplate hiding (children) +import Ideas.Utils.Decoding data MathML = MRow [MathML] | MId String @@ -54,71 +55,55 @@ instance ToXML MathML where toXML = mathml2xml instance InXML MathML where - fromXML = either fail return . xml2mathml + xmlDecoder = rec + where + rec = xTag "mrow" (MRow <$> many rec) + <|> xTag "msqrt" (MSqrt <$> impliedRow) + <|> xTag "math" impliedRow + <|> xTag "mi" (MId <$> xString) + <|> xTag "mn" (MNumber <$> xString) + <|> xTag "mo" (MOperator <$> xString) + <|> xTag "ms" (MString <$> xString) + <|> xTag "mtext" (MText <$> xString) + <|> xTag "mroot" (MRoot <$> rec <*> rec) + <|> xTag "msup" (MSup <$> rec <*> rec) + <|> xTag "msub" (MSub <$> rec <*> rec) + <|> xTag "msubsup" (MSubSup <$> rec <*> rec <*> rec) + <|> xTag "mfrac" (MFrac <$> rec <*> rec) + <|> xTag "mfenced" (MFenced <$> xAttr "open" <*> xAttr "close" <*> rec) + <|> xTag "mspace" (return MSpace) + <|> xTag "mstyle" (return MStyle) + <|> xTag "mpadded" (return MPadded) + <|> xTag "mphantom" (return MPhantom) + <|> xTag "merror" (return MError) + <|> xTag "menclose" (return MEnclose) + <|> xTag "munder" (return MUnder) + <|> xTag "mover" (return MOver) + <|> xTag "munderover" (return MUnderOver) + <|> xTag "mtable" (return MTable) + <|> xTag "mtr" (return MTableRow) + <|> xTag "mlabeledtr" (return MLabeledTableRow) + <|> xTag "mtd" (return MTableData) + + impliedRow = f <$> many rec + + f [x] = x + f xs = MRow xs instance Uniplate MathML where uniplate math = case math of - MRow xs -> plate MRow ||* xs - _ -> plate math + MRow xs -> plate MRow ||* xs + _ -> plate math ---------------------------------------------------------- -- conversion functions: XML <-> MathML xml2mathml :: XML -> Either String MathML -xml2mathml = rec - where - rec xml = case name xml of - "mrow" -> MRow <$> mapM rec (children xml) - "mi" -> return (MId (getData xml)) - "mn" -> return (MNumber (getData xml)) - "mo" -> return (MOperator (getData xml)) - "ms" -> return (MString (getData xml)) - "mtext" -> return (MText (getData xml)) - "mroot" -> case children xml of - [c, d] -> MRoot <$> rec c <*> rec d - _ -> fail "invalid mroot" - "msup" -> case children xml of - [c, d] -> MSup <$> rec c <*> rec d - _ -> fail "invalid msup" - "msub" -> case children xml of - [c, d] -> MSub <$> rec c <*> rec d - _ -> fail "invalid msub" - "msubsup" -> case children xml of - [c, d, e] -> MSubSup <$> rec c <*> rec d <*> rec e - _ -> fail "invalid msubsup" - "mfrac" -> case children xml of - [c, d] -> MFrac <$> rec c <*> rec d - _ -> fail "invalid mfrac" - "mfenced" -> case children xml of - [c] -> MFenced (fromMaybe "(" (findAttribute "open" xml)) (fromMaybe ")" (findAttribute "close" xml)) <$> rec c - _ -> fail "invalid mfenced" - "mspace" -> return MSpace - "mtable" -> return MTable - "mtr" -> return MTableRow - "mlabeledtr" -> return MLabeledTableRow - "munder" -> return MUnder - "mover" -> return MOver - "munderover" -> return MUnderOver - -- below are cases that have 1* arguments, when none-one an mrow is implied. - "math" -> impliedMRow xml - "msqrt" -> MSqrt <$> impliedMRow xml - "mphantom" -> return MPhantom - "mpadded" -> return MPadded - "mstyle" -> return MStyle - "merror" -> return MError - "mtd" -> return MTableData - "menclose" -> return MEnclose - _ -> fail ("unsupported MathML: " ++ show xml) - - impliedMRow :: XML -> Either String MathML - impliedMRow xml = - case children xml of - [x] -> rec x - xs -> MRow <$> mapM rec xs +xml2mathml = either (Left . show) (Right . fst) . runDecoder xmlDecoder () . builder mathml2xml :: MathML -> XML -mathml2xml = makeXML "math" . rec +mathml2xml = makeXML (fromString "math") . rec where rec :: MathML -> XMLBuilder rec math = diff --git a/src/Ideas/Text/OpenMath/Object.hs b/src/Ideas/Text/OpenMath/Object.hs index 121b572a..5db77184 100644 --- a/src/Ideas/Text/OpenMath/Object.hs +++ b/src/Ideas/Text/OpenMath/Object.hs @@ -35,11 +35,7 @@ data OMOBJ = OMI Integer instance ToXML OMOBJ where toXML = omobj2xml --- maf = fromXML (toXML (OMA [OMS (Nothing, "fac"), OMS (Just "arith", "plus"), OMV "f", OMBIND (OMI 13) ["x","y"] (OMI 14), OMF 42])) :: Maybe OMOBJ - instance InXML OMOBJ where --- fromXML = either fail return . xml2omobj - xmlDecoder = xTag "OMOBJ" rec where rec = xTag "OMA" (OMA <$> many rec) @@ -71,7 +67,7 @@ xml2omobj :: XML -> Either String OMOBJ xml2omobj = either (Left . show) (Right . fst) . runDecoder xmlDecoder () . builder omobj2xml :: OMOBJ -> XML -omobj2xml object = makeXML "OMOBJ" $ mconcat +omobj2xml object = makeXML (fromString "OMOBJ") $ mconcat [ "xmlns" .=. "http://www.openmath.org/OpenMath" , "version" .=. "2.0" , "cdbase" .=. "http://www.openmath.org/cd" diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index d0d80eb4..c7a97d2f 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -14,7 +14,7 @@ module Ideas.Text.XML ( -- * XML types - XML, Name, Attributes, Attribute(..) + XML, Name, fromString, Attributes, Attribute(..) -- * Parsing XML , parseXML, parseXMLFile -- * Building/constructing XML @@ -34,9 +34,11 @@ module Ideas.Text.XML , content, emptyContent, fromBuilder ) where +import Control.Arrow import Control.Monad.State import Data.Char (chr) import Data.Maybe +import Data.String import Ideas.Text.XML.Builder import Ideas.Text.XML.Data import Ideas.Text.XML.Document (escape, Name) @@ -68,7 +70,7 @@ fromXMLDoc doc = fromElement (D.root doc) fromAttributes = mconcat . map fromAttribute fromAttribute (n D.:= v) = - n .=. concatMap (either return refToString) v + show n .=. concatMap (either return refToString) v fromContent :: D.Content -> XMLBuilder fromContent = mconcat . map f @@ -81,35 +83,44 @@ fromXMLDoc doc = fromElement (D.root doc) refToString :: D.Reference -> String refToString (D.CharRef i) = [chr i] - refToString (D.EntityRef s) = maybe "" return (lookup s general) + refToString (D.EntityRef n) = maybe "" return (lookup n general) fromReference :: D.Reference -> XMLBuilder fromReference (D.CharRef i) = char (chr i) - fromReference (D.EntityRef s) = fromMaybe mempty (lookup s entities) + fromReference (D.EntityRef n) = fromMaybe mempty (lookup n entities) - entities :: [(String, XMLBuilder)] + entities :: [(Name, XMLBuilder)] entities = [ (n, fromContent (snd ext)) | (n, ext) <- D.externals doc ] ++ -- predefined entities [ (n, char c) | (n, c) <- general ] - general :: [(String, Char)] - general = [("lt",'<'), ("gt",'>'), ("amp",'&'), ("apos",'\''), ("quot",'"')] + general :: [(Name, Char)] + general = map (first fromString) + [("lt",'<'), ("gt",'>'), ("amp",'&'), ("apos",'\''), ("quot",'"')] ------------------------------------------------------------------------------- -- Simple decoding queries findAttribute :: Monad m => String -> XML -> m String findAttribute s (Tag _ as _) = - case [ t | n := t <- as, s==n ] of + case [ t | n := t <- as, s == show n ] of [hd] -> return hd _ -> fail $ "Invalid attribute: " ++ show s -children :: XML -> [XML] -children e = [ c | Right c <- content e ] +children :: HasContent a => a -> [XML] +children = rec . getContent + where + rec a = + case headIsString a of + Just (_, rest) -> rec rest + Nothing -> + case headIsXML a of + Just (xml, rest) -> xml : rec rest + Nothing -> [] findChildren :: String -> XML -> [XML] -findChildren s = filter ((==s) . name) . children +findChildren s = filter ((==s) . show . name) . children findChild :: Monad m => String -> XML -> m XML findChild s e = @@ -118,21 +129,29 @@ findChild s e = [a] -> return a _ -> fail $ "Multiple children found: " ++ show s -getData :: XML -> String -getData e = concat [ s | Left s <- content e ] +getData :: HasContent a => a -> String +getData = rec . getContent + where + rec a = + case headIsString a of + Just (s, rest) -> s ++ rec rest + Nothing -> + case headIsXML a of + Just (_, rest) -> rec rest + Nothing -> [] expecting :: Monad m => String -> XML -> m () expecting s xml = - unless (name xml == s) $ fail $ "Expecting element " ++ s ++ ", but found " ++ name xml + unless (show (name xml) == s) $ fail $ "Expecting element " ++ s ++ ", but found " ++ show (name xml) ------------------------------------------------------------------------------- -- Decoding XML decodeData :: Decoder env String XML String decodeData = get >>= \xml -> - case content xml of - Left s:rest -> put xml {content = rest} >> return s - _ -> throwError "Could not find data" + case headIsString xml of + Just (s, rest) -> put rest >> return s + _ -> throwError "Could not find data" decodeAttribute :: String -> Decoder env String XML String decodeAttribute s = get >>= \xml -> @@ -140,27 +159,27 @@ decodeAttribute s = get >>= \xml -> (xs, (_ := val):ys) -> put xml {attributes = xs ++ ys } >> return val _ -> throwError $ "Could not find attribute " ++ s where - hasName (n := _) = n == s + hasName (n := _) = show n == s -decodeChild :: Name -> Decoder env String XML a -> Decoder env String XML a +decodeChild :: String -> Decoder env String XML a -> Decoder env String XML a decodeChild s p = get >>= \xml -> - case break hasName (content xml) of + case break hasName (fromContent (content xml)) of (xs, Right y:ys) -> do put y a <- p - put xml { content = xs ++ ys } + put xml { content = toContent (xs ++ ys) } return a _ -> throwError $ "Could not find child " ++ s where - hasName = either (const False) ((==s) . name) + hasName = either (const False) ((==s) . show . name) -decodeFirstChild :: Name -> Decoder env String XML a -> Decoder env String XML a +decodeFirstChild :: String -> Decoder env String XML a -> Decoder env String XML a decodeFirstChild s p = get >>= \xml -> - case content xml of - Right y:ys | name y == s -> do + case headIsXML xml of + Just (y, rest) | show (name y) == s -> do put y a <- p - put xml { content = ys } + put rest return a _ -> throwError $ "Could not find first child " ++ s @@ -171,13 +190,13 @@ class ToXML a where toXML :: a -> XML listToXML :: [a] -> XML -- default definitions - listToXML = makeXML "list" . mconcat . map builderXML + listToXML = makeXML (fromString "list") . mconcat . map builderXML instance ToXML () where - toXML _ = makeXML "Unit" mempty + toXML _ = makeXML (fromString "Unit") mempty instance ToXML a => ToXML (Maybe a) where - toXML = maybe (makeXML "Nothing" mempty) toXML + toXML = maybe (makeXML (fromString "Nothing") mempty) toXML builderXML :: (ToXML a, BuildXML b) => a -> b builderXML = builder . toXML @@ -199,21 +218,22 @@ class ToXML a => InXML a where fromXML xml = either (const Nothing) Just $ evalDecoder xmlDecoder () (builder (trimXML xml)) xmlDecoder = do b <- get - case fromBS b of - ([], [Right xml]) -> maybe (errorStr "xml-decoder") return (fromXML xml) + case fromBuilder b of + Just xml -> maybe (errorStr "xml-decoder") return (fromXML xml) _ -> errorStr "xml-decoder" ------------------------------------------------------------------------------- -- Deprecated functions emptyContent :: XML -> Bool -emptyContent = null . content +emptyContent = contentIsEmpty fromBuilder :: XMLBuilder -> Maybe XML fromBuilder m = - case fromBS m of - ([], [Right a]) -> Just a - _ -> Nothing + case headIsXML m of + Just (a, rest) | null (builderAttributes m) && contentIsEmpty rest + -> Just a + _ -> Nothing ------------------------------------------------------------------------------- -- Tests @@ -253,5 +273,5 @@ _runTests = do mkPD, mkPA, mkBD, mkBA :: String -> XML mkPD s = either error id $ parseXML $ "" ++ escape s ++ "" mkPA s = either error id $ parseXML $ "" - mkBD s = makeXML "a" (string s) - mkBA s = makeXML "t" ("a".=. s) \ No newline at end of file + mkBD s = makeXML (fromString "a") (string s) + mkBA s = makeXML (fromString "t") ("a".=. s) \ No newline at end of file diff --git a/src/Ideas/Text/XML/Builder.hs b/src/Ideas/Text/XML/Builder.hs index b0a82b93..9a87b8ff 100644 --- a/src/Ideas/Text/XML/Builder.hs +++ b/src/Ideas/Text/XML/Builder.hs @@ -14,13 +14,12 @@ module Ideas.Text.XML.Builder ( BuildXML(..) - , XMLBuilder, makeXML, fromBS + , XMLBuilder, makeXML, builderAttributes, xmlToBuilder, fromBS ) where import Data.List (nubBy) import Data.Foldable (toList) import Data.String -import qualified Data.Sequence as Seq import qualified Data.Map as M import Ideas.Text.XML.Data import Ideas.Utils.Decoding @@ -51,7 +50,7 @@ instance BuildXML a => BuildXML (Decoder env err s a) where ------------------------------------------------------------------- -data XMLBuilder = BS (Seq.Seq Attribute) (Seq.Seq (Either String XML)) +data XMLBuilder = BS Attributes Content instance Semigroup XMLBuilder where BS as1 elts1 <> BS as2 elts2 = BS (as1 <> as2) (elts1 <> elts2) @@ -61,31 +60,34 @@ instance Monoid XMLBuilder where mappend = (<>) instance BuildXML XMLBuilder where - n .=. s = nameCheck n $ BS (Seq.singleton (n := s)) mempty - string s = BS mempty (if null s then mempty else Seq.singleton (Left s)) - builder = BS mempty . Seq.singleton . Right - tag n = builder . uncurry (Tag n) . fromBS . nameCheck n + n .=. s = BS [fromString n := s] mempty + string s = BS mempty (if null s then mempty else fromString s) + builder = BS mempty . xmlToContent + tag n = builder . makeXML (fromString n) instance IsString XMLBuilder where fromString = string -makeXML :: String -> XMLBuilder -> XML -makeXML s = uncurry (Tag s) . fromBS . nameCheck s +instance HasContent XMLBuilder where + updateContent (BS as c) = (c, BS as) -nameCheck :: String -> a -> a -nameCheck s = if validName s then id else error $ "Invalid name for xml tag: " ++ s +xmlToBuilder :: XML -> XMLBuilder -- is not builder??? -- !!! fix me +xmlToBuilder xml = BS (attributes xml) (content xml) + +makeXML :: Name -> XMLBuilder -> XML +makeXML n (BS as c) = Tag n (mergeAttributes as) c + +builderAttributes :: XMLBuilder -> Attributes +builderAttributes (BS as _) = as -- local helper: merge attributes, but preserve order fromBS :: XMLBuilder -> (Attributes, [Either String XML]) -fromBS (BS as elts) = (attrList, merge (toList elts)) +fromBS (BS as cont) = (mergeAttributes as, fromContent cont) + +mergeAttributes :: Attributes -> Attributes +mergeAttributes as = nubBy eqKey (map make as) where attrMap = foldr add M.empty as add (k := v) = M.insertWith (\x y -> x ++ " " ++ y) k v - attrList = nubBy eqKey (map make (toList as)) make (k := _) = k := M.findWithDefault "" k attrMap - eqKey (k1 := _) (k2 := _) = k1 == k2 - - merge [] = [] - merge (Left x:Left y:rest) = merge (Left (x++y):rest) - merge (Left x:rest) = Left x : merge rest - merge (Right y:rest) = Right y : merge rest \ No newline at end of file + eqKey (k1 := _) (k2 := _) = k1 == k2 \ No newline at end of file diff --git a/src/Ideas/Text/XML/Data.hs b/src/Ideas/Text/XML/Data.hs index c8ccf7ea..b1f972eb 100644 --- a/src/Ideas/Text/XML/Data.hs +++ b/src/Ideas/Text/XML/Data.hs @@ -14,8 +14,11 @@ module Ideas.Text.XML.Data ( -- types - XML(..), Attributes, Attribute(..) - , D.Name, validName + XML(..) + , Attributes, Attribute(..) + , Name, uncheckedName + , Content, toContent, fromContent, xmlToContent + , HasContent(..), contentIsEmpty, headIsString, headIsXML -- pretty-printing , prettyXML, compactXML -- processing @@ -23,8 +26,9 @@ module Ideas.Text.XML.Data ) where import Data.Char (isSpace, ord) +import Data.String +import Ideas.Text.XML.Document (Name, uncheckedName) import qualified Ideas.Text.XML.Document as D -import Ideas.Text.XML.Unicode ------------------------------------------------------------------------------- -- XML types @@ -32,9 +36,9 @@ import Ideas.Text.XML.Unicode -- invariants content: no two adjacent Lefts, no Left with empty string, -- valid tag/attribute names data XML = Tag - { name :: D.Name + { name :: Name , attributes :: Attributes - , content :: [Either String XML] + , content :: Content } deriving Eq @@ -43,15 +47,93 @@ instance Show XML where type Attributes = [Attribute] -data Attribute = D.Name := String +data Attribute = Name := String deriving Eq -validName :: String -> Bool -validName [] = False -validName (x:xs) = (isLetter x || x `elem` "_:") && all validNameChar xs +data Content = Empty + | CData String + | Cons XML Content + | Mixed String XML Content + deriving Eq -validNameChar :: Char -> Bool -validNameChar c = any ($ c) [isLetter, isDigit, isCombiningChar, isExtender, (`elem` ".-_:")] +instance Show Content where + showsPrec _ = rec + where + rec Empty = id + rec (CData s) = (s ++) + rec (Cons x c) = (show x ++) . rec c + rec (Mixed s x c) = (s ++) . (show x ++) . rec c + +instance Semigroup Content where + Empty <> rest = rest + CData s <> Empty = CData s + CData s <> CData t = CData (s ++ t) + CData s <> Cons x c = Mixed s x c + CData s <> Mixed t x c = Mixed (s ++ t) x c + Cons x c <> rest = Cons x (c <> rest) + Mixed s x c <> rest = Mixed s x (c <> rest) + +instance Monoid Content where + mempty = Empty + +instance IsString Content where + fromString s = if null s then Empty else CData s + +class HasContent a where + getContent :: a -> Content + setContent :: Content -> a -> a + changeContent :: (Content -> Content) -> a -> a + updateContent :: a -> (Content, Content -> a) + + {-# MINIMAL (getContent, changeContent) | updateContent #-} + + -- default definitions + getContent = fst . updateContent + setContent = changeContent . const + changeContent f = (\(c, g) -> g (f c)) . updateContent + updateContent a = (getContent a, (`setContent` a)) + +instance HasContent Content where + updateContent a = (a, id) + +instance HasContent XML where + updateContent xml = (content xml, \new -> xml {content = new}) + +contentIsEmpty :: HasContent a => a -> Bool +contentIsEmpty a = + case getContent a of + Empty -> True + _ -> False + +headIsString :: HasContent a => a -> Maybe (String, a) +headIsString a = + case updateContent a of + (CData s, f) -> Just (s, f Empty) + (Mixed s x c, f) -> Just (s, f (Cons x c)) + _ -> Nothing + +headIsXML :: HasContent a => a -> Maybe (XML, a) +headIsXML a = + case updateContent a of + (Cons x c, f) -> Just (x, f c) + _ -> Nothing + +xmlToContent :: XML -> Content +xmlToContent = (`Cons` Empty) + +toContent :: [Either String XML] -> Content +toContent [] = Empty +toContent (Right x:rest) = Cons x (toContent rest) +toContent (Left s:Left t:rest) = toContent (Left (s ++ t) : rest) +toContent (Left []:rest) = toContent rest +toContent (Left s:[]) = CData s +toContent (Left s:Right x:rest) = Mixed s x (toContent rest) + +fromContent :: Content -> [Either String XML] +fromContent Empty = [] +fromContent (CData s) = [Left s] +fromContent (Cons x c) = Right x : fromContent c +fromContent (Mixed s x c) = Left s : Right x : fromContent c ------------------------------------------------------------------------------- -- Pretty-printing XML @@ -81,13 +163,13 @@ toElement = foldXML make mkAttribute mkString ------------------------------------------------------------------------------- -- Processing XML -foldXML :: (D.Name -> [a] -> [Either s e] -> e) -> (Attribute -> a) -> (String -> s) -> XML -> e +foldXML :: (Name -> [a] -> [Either s e] -> e) -> (Attribute -> a) -> (String -> s) -> XML -> e foldXML fe fa fs = rec where - rec (Tag n as cs) = fe n (map fa as) (map (either (Left . fs) (Right . rec)) cs) + rec (Tag n as cs) = fe n (map fa as) (map (either (Left . fs) (Right . rec)) (fromContent cs)) trimXML :: XML -> XML -trimXML = foldXML Tag f trim +trimXML = foldXML (\n as -> Tag n as . toContent) f trim where f (n := s) = n := trim s diff --git a/src/Ideas/Text/XML/Decoder.hs b/src/Ideas/Text/XML/Decoder.hs index 40f0ebeb..799e965d 100644 --- a/src/Ideas/Text/XML/Decoder.hs +++ b/src/Ideas/Text/XML/Decoder.hs @@ -28,45 +28,31 @@ evalDecoderXML :: DecoderXML a -> XML -> Either (Error XML) a evalDecoderXML p = evalDecoder p () . builder xTag :: String -> DecoderXML a -> DecoderXML a -xTag s p = do - xml <- get - case fromBS xml of - (as, Right hd:rest) | name hd == s -> do - put (conv (attributes hd) (content hd)) +xTag s p = get >>= \xml -> + case headIsXML xml of + Just (hd, rest) | show (name hd) == s -> do + put (xmlToBuilder hd) a <- p xEnd - put (conv as rest) + put rest return a _ -> errorStr "xTag" xString :: DecoderXML String xString = do xml <- get - case fromBS xml of - (as, Left s:rest) -> do - put (conv as rest) - return s - _ -> errorStr "xString" + case headIsString xml of + Just (s, rest) -> put rest >> return s + Nothing -> errorStr "xString" xAttr :: String -> DecoderXML String -xAttr s = do - xml <- get - let (as, _) = fromBS xml - case filter (\(n := _) -> n == s) as of +xAttr s = get >>= \xml -> + case filter (\(n := _) -> show n == s) (builderAttributes xml) of [_ := v] -> return v _ -> errorStr "xAttr" xEnd :: DecoderXML () -xEnd = do - xml <- get - case fromBS xml of - (_, []) -> do - return () - _ -> errorStr "xEnd" - -conv :: Attributes -> [Either String XML] -> XMLBuilder -conv as xs = mconcat (map f as ++ map g xs) - where - f (n := s) = n .=. s - g (Left s) = string s - g (Right a) = builder a \ No newline at end of file +xEnd = get >>= \xml -> + if contentIsEmpty xml + then return () + else errorStr "xEnd" \ No newline at end of file diff --git a/src/Ideas/Text/XML/Document.hs b/src/Ideas/Text/XML/Document.hs index 95d05bb5..df56fd4c 100644 --- a/src/Ideas/Text/XML/Document.hs +++ b/src/Ideas/Text/XML/Document.hs @@ -13,7 +13,8 @@ ----------------------------------------------------------------------------- module Ideas.Text.XML.Document - ( Name, Attributes, Attribute(..), Reference(..), Parameter(..) + ( Name, uncheckedName, fromString + , Attributes, Attribute(..), Reference(..), Parameter(..) , XMLDoc(..), XML(..), Element(..), Content, DTD(..), DocTypeDecl(..) , ContentSpec(..), CP(..), AttType(..), DefaultDecl(..), AttDef , EntityDef, AttValue, EntityValue, ExternalID(..), PublicID @@ -21,25 +22,51 @@ module Ideas.Text.XML.Document , prettyXML, prettyElement, escape ) where +import Data.String import Prelude hiding ((<$>)) - +import Ideas.Text.XML.Unicode import Text.PrettyPrint.Leijen -type Name = String +------------------------------------------------------------------ +-- (checked) names + +newtype Name = N String + deriving (Eq, Ord) + +instance Show Name where + show (N s) = s + +instance IsString Name where + fromString s + | validName s = N s + | otherwise = error $ "Invalid XML name: " ++ s + +uncheckedName :: String -> Name +uncheckedName = N + +validName :: String -> Bool +validName [] = False +validName (x:xs) = (isLetter x || x `elem` "_:") && all validNameChar xs + +validNameChar :: Char -> Bool +validNameChar c = any ($ c) [isLetter, isDigit, isCombiningChar, isExtender, (`elem` ".-_:")] + +------------------------------------------------------------------ +-- (checked) names type Attributes = [Attribute] data Attribute = Name := AttValue -data Reference = CharRef Int | EntityRef String +data Reference = CharRef Int | EntityRef Name -newtype Parameter = Parameter String +newtype Parameter = Parameter Name data XMLDoc = XMLDoc { versionInfo :: Maybe String , encoding :: Maybe String , standalone :: Maybe Bool , dtd :: Maybe DTD - , externals :: [(String, External)] + , externals :: [(Name, External)] , root :: Element } @@ -71,12 +98,12 @@ data ContentSpec = Empty | Any | Mixed Bool [Name] | Children CP data CP = Choice [CP] | Sequence [CP] | QuestionMark CP | Star CP | Plus CP | CPName Name data AttType = IdType | IdRefType | IdRefsType | EntityType | EntitiesType | NmTokenType | NmTokensType - | StringType | EnumerationType [String] | NotationType [String] + | StringType | EnumerationType [String] | NotationType [Name] data DefaultDecl = Required | Implied | Value AttValue | Fixed AttValue type AttDef = (Name, AttType, DefaultDecl) -type EntityDef = Either EntityValue (ExternalID, Maybe String) +type EntityDef = Either EntityValue (ExternalID, Maybe Name) type AttValue = [Either Char Reference] type EntityValue = [Either Char (Either Parameter Reference)] @@ -102,17 +129,20 @@ instance Show Element where show = show . pretty ------------------------------------------------------------------ -- Pretty printing -instance Pretty Attribute where - pretty (n := v) = text n <> char '=' <> prettyAttValue v +instance Pretty Name where + pretty = text . show + +instance Pretty Attribute where + pretty (n := v) = pretty n <> char '=' <> prettyAttValue v instance Pretty Reference where pretty ref = case ref of CharRef n -> text "&#" <> int n <> char ';' - EntityRef s -> char '&' <> text s <> char ';' + EntityRef s -> char '&' <> pretty s <> char ';' instance Pretty Parameter where - pretty (Parameter s) = text "%" <> text s <> text ";" + pretty (Parameter s) = text "%" <> pretty s <> text ";" instance Pretty XML where pretty = prettyXML False @@ -129,7 +159,7 @@ prettyXML compact xml = Reference r -> pretty r prettyElement :: Bool -> Element -> Doc -prettyElement _ (Element n@"script" as [CharData s]) = +prettyElement _ (Element n as [CharData s]) | show n == "script" = -- quick fix for not escaping javascript code in html openTag n as <> text s <> closeTag n prettyElement compact (Element n as c) @@ -151,7 +181,7 @@ closeTag :: Name -> Doc closeTag n = prettyTag (text "') n [] prettyTag :: Doc -> Doc -> Name -> Attributes -> Doc -prettyTag open close n as = open <> hsep (text n:map pretty as) <> close +prettyTag open close n as = open <> hsep (pretty n:map pretty as) <> close prettyAttValue :: AttValue -> Doc prettyAttValue = dquotes . hcat . map (either (text . escapeChar) pretty) diff --git a/src/Ideas/Text/XML/Parser.hs b/src/Ideas/Text/XML/Parser.hs index bde4bb46..71e22c2a 100644 --- a/src/Ideas/Text/XML/Parser.hs +++ b/src/Ideas/Text/XML/Parser.hs @@ -89,13 +89,13 @@ nameChar :: Parser Char nameChar = letter <|> digit <|> combiningChar <|> extender <|> oneOf ".-_:" -- [5] Name ::= (Letter | '_' | ':') (NameChar)* -name :: Parser String +name :: Parser Name name = do c <- letter <|> oneOf "_:" cs <- many nameChar - return (c:cs) + return (uncheckedName (c:cs)) -spacedName :: Parser String +spacedName :: Parser Name spacedName = space *> name <* space {- @@ -173,11 +173,10 @@ pInstr = between (string "") p p = piTarget >> option "" (space >> stopOn ["?>"]) -- [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) -piTarget :: Parser String +piTarget :: Parser () piTarget = do n <- name - when (map toUpper n == "XML") $ fail "XML in piTarget" - return n + when (map toUpper (show n) == "XML") $ fail "XML in piTarget" -------------------------------------------------- -- ** 2.7 CDATA Sections @@ -636,7 +635,7 @@ externalID = (string "SYSTEM" >> space >> fmap System systemLiteral) <|> do return (Public x y) -- [76] NDataDecl ::= S 'NDATA' S Name -nDataDecl :: Parser String +nDataDecl :: Parser Name nDataDecl = space >> string "NDATA" >> space >> name -------------------------------------------------- From dc1997424a9c443005483d294175629b6f82fdad Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 28 Mar 2022 12:40:24 +0200 Subject: [PATCH 39/57] refactoring XML.Data --- src/Ideas/Text/XML.hs | 22 ++++++++++++++++++---- src/Ideas/Text/XML/Builder.hs | 9 +-------- src/Ideas/Text/XML/Data.hs | 33 +++++++++++---------------------- 3 files changed, 30 insertions(+), 34 deletions(-) diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index c7a97d2f..b12ca6ca 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -163,15 +163,29 @@ decodeAttribute s = get >>= \xml -> decodeChild :: String -> Decoder env String XML a -> Decoder env String XML a decodeChild s p = get >>= \xml -> - case break hasName (fromContent (content xml)) of - (xs, Right y:ys) -> do + case extractChild (fromString s) (content xml) of + Just (y, rest) -> do put y a <- p - put xml { content = toContent (xs ++ ys) } + put xml { content = rest } return a _ -> throwError $ "Could not find child " ++ s + +-- local helper +extractChild :: Name -> Content -> Maybe (XML, Content) +extractChild n = rec where - hasName = either (const False) ((==s) . show . name) + rec a = + case headIsXML a of + Just (xml, rest) + | n == name xml -> Just (xml, rest) + | otherwise -> add (xmlToContent xml) (rec rest) + Nothing -> + case headIsString a of + Just (s, rest) -> add (fromString s) (rec rest) + Nothing -> Nothing + + add a = fmap (fmap (a <>)) decodeFirstChild :: String -> Decoder env String XML a -> Decoder env String XML a decodeFirstChild s p = get >>= \xml -> diff --git a/src/Ideas/Text/XML/Builder.hs b/src/Ideas/Text/XML/Builder.hs index 9a87b8ff..f1b28cbe 100644 --- a/src/Ideas/Text/XML/Builder.hs +++ b/src/Ideas/Text/XML/Builder.hs @@ -10,15 +10,12 @@ -- ----------------------------------------------------------------------------- --- to do: hide local function fromBS - module Ideas.Text.XML.Builder ( BuildXML(..) - , XMLBuilder, makeXML, builderAttributes, xmlToBuilder, fromBS + , XMLBuilder, makeXML, builderAttributes, xmlToBuilder ) where import Data.List (nubBy) -import Data.Foldable (toList) import Data.String import qualified Data.Map as M import Ideas.Text.XML.Data @@ -80,10 +77,6 @@ makeXML n (BS as c) = Tag n (mergeAttributes as) c builderAttributes :: XMLBuilder -> Attributes builderAttributes (BS as _) = as --- local helper: merge attributes, but preserve order -fromBS :: XMLBuilder -> (Attributes, [Either String XML]) -fromBS (BS as cont) = (mergeAttributes as, fromContent cont) - mergeAttributes :: Attributes -> Attributes mergeAttributes as = nubBy eqKey (map make as) where diff --git a/src/Ideas/Text/XML/Data.hs b/src/Ideas/Text/XML/Data.hs index b1f972eb..8f65aff3 100644 --- a/src/Ideas/Text/XML/Data.hs +++ b/src/Ideas/Text/XML/Data.hs @@ -17,7 +17,7 @@ module Ideas.Text.XML.Data XML(..) , Attributes, Attribute(..) , Name, uncheckedName - , Content, toContent, fromContent, xmlToContent + , Content, xmlToContent , HasContent(..), contentIsEmpty, headIsString, headIsXML -- pretty-printing , prettyXML, compactXML @@ -121,20 +121,6 @@ headIsXML a = xmlToContent :: XML -> Content xmlToContent = (`Cons` Empty) -toContent :: [Either String XML] -> Content -toContent [] = Empty -toContent (Right x:rest) = Cons x (toContent rest) -toContent (Left s:Left t:rest) = toContent (Left (s ++ t) : rest) -toContent (Left []:rest) = toContent rest -toContent (Left s:[]) = CData s -toContent (Left s:Right x:rest) = Mixed s x (toContent rest) - -fromContent :: Content -> [Either String XML] -fromContent Empty = [] -fromContent (CData s) = [Left s] -fromContent (Cons x c) = Right x : fromContent c -fromContent (Mixed s x c) = Left s : Right x : fromContent c - ------------------------------------------------------------------------------- -- Pretty-printing XML @@ -145,10 +131,8 @@ compactXML :: XML -> String compactXML = show . D.prettyElement True . toElement toElement :: XML -> D.Element -toElement = foldXML make mkAttribute mkString +toElement = foldXML D.Element mkAttribute mkString (return . D.Tagged) where - make n as = D.Element n as . concatMap (either id (return . D.Tagged)) - mkAttribute :: Attribute -> D.Attribute mkAttribute (m := s) = (D.:=) m (map Left s) @@ -163,13 +147,18 @@ toElement = foldXML make mkAttribute mkString ------------------------------------------------------------------------------- -- Processing XML -foldXML :: (Name -> [a] -> [Either s e] -> e) -> (Attribute -> a) -> (String -> s) -> XML -> e -foldXML fe fa fs = rec +foldXML :: Monoid c => (Name -> [a] -> c -> e) -> (Attribute -> a) -> (String -> c) -> (e -> c) -> XML -> e +foldXML f fa fs fc = rec where - rec (Tag n as cs) = fe n (map fa as) (map (either (Left . fs) (Right . rec)) (fromContent cs)) + rec (Tag n as cs) = f n (map fa as) (recContent cs) + + recContent Empty = mempty + recContent (CData s) = fs s + recContent (Cons x c) = fc (rec x) <> recContent c + recContent (Mixed s x c) = fs s <> fc (rec x) <> recContent c trimXML :: XML -> XML -trimXML = foldXML (\n as -> Tag n as . toContent) f trim +trimXML = foldXML Tag f (fromString . trim) xmlToContent where f (n := s) = n := trim s From b25c13892cc0855bf048b2b6e7520e2abbf9d8e2 Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 4 Apr 2022 17:05:55 +0200 Subject: [PATCH 40/57] refactoring XML interface --- ideas.cabal | 1 + src/Ideas/Encoding/DecoderXML.hs | 10 ++-- src/Ideas/Encoding/EncoderHTML.hs | 2 +- src/Ideas/Encoding/EncoderXML.hs | 4 +- src/Ideas/Encoding/LinkManager.hs | 4 +- src/Ideas/Encoding/ModeXML.hs | 7 ++- src/Ideas/Encoding/RulesInfo.hs | 3 +- src/Ideas/Encoding/StrategyInfo.hs | 21 ++++---- src/Ideas/Text/HTML.hs | 3 +- src/Ideas/Text/HTML/Templates.hs | 2 +- src/Ideas/Text/HTML/W3CSS.hs | 1 + src/Ideas/Text/MathML.hs | 58 ++++++++++----------- src/Ideas/Text/OpenMath/Object.hs | 19 +++---- src/Ideas/Text/XML.hs | 83 ++++++++++++------------------ src/Ideas/Text/XML/Attributes.hs | 64 +++++++++++++++++++++++ src/Ideas/Text/XML/Builder.hs | 56 +++++++++----------- src/Ideas/Text/XML/Data.hs | 45 +++++++--------- src/Ideas/Text/XML/Decoder.hs | 34 ++++++------ src/Ideas/Text/XML/Document.hs | 11 ++-- 19 files changed, 236 insertions(+), 192 deletions(-) create mode 100644 src/Ideas/Text/XML/Attributes.hs diff --git a/ideas.cabal b/ideas.cabal index 480d43a2..8c505c46 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -187,6 +187,7 @@ Library Ideas.Text.OpenMath.Tests Ideas.Text.UTF8 Ideas.Text.XML + Ideas.Text.XML.Attributes Ideas.Text.XML.Builder Ideas.Text.XML.Data Ideas.Text.XML.Decoder diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index 81c23a61..6a1df6d9 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE GADTs #-} +{-# LANGUAGE OverloadedStrings, GADTs #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -122,7 +122,7 @@ decodeContext = do expr <- decodeExpression env <- decodeEnvironment let ctx = setEnvironment env (inContext ex expr) - locRef = makeRef "location" + locRef = makeRef ("location" :: String) case locRef ? env of Just s -> maybe (fail "invalid location") return $ do loc <- toLocation <$> readM s @@ -155,8 +155,8 @@ decodeEnvironment = <|> return mempty where add env item = do - unless (show (name item) == "item") $ - fail $ "expecting item tag, found " ++ show (name item) + unless (getName item == "item") $ + fail $ "expecting item tag, found " ++ show (getName item) n <- findAttribute "name" item req <- getRequest case findChild "OMOBJ" item of @@ -181,7 +181,7 @@ decodeConfiguration = decodeChild "configuration" $ where decodeAction item = do guard (null (children item)) - action <- maybe (fail "invalid action") return $ readM (show (name item)) + action <- maybe (fail "invalid action") return $ readM (show (getName item)) cfgloc <- findAttribute "name" item return (action `byName` newId cfgloc) diff --git a/src/Ideas/Encoding/EncoderHTML.hs b/src/Ideas/Encoding/EncoderHTML.hs index f09af575..bed86e39 100644 --- a/src/Ideas/Encoding/EncoderHTML.hs +++ b/src/Ideas/Encoding/EncoderHTML.hs @@ -38,7 +38,7 @@ import Ideas.Text.HTML.Templates import Ideas.Text.HTML.W3CSS hiding (tag, ul, top, table, content) import Ideas.Text.OpenMath.FMP import Ideas.Text.OpenMath.Object -import Ideas.Text.XML hiding (content) +import Ideas.Text.XML import Ideas.Utils.Prelude (munless, mwhen) import Ideas.Utils.TestSuite import System.IO.Unsafe diff --git a/src/Ideas/Encoding/EncoderXML.hs b/src/Ideas/Encoding/EncoderXML.hs index a58a0249..889dd41f 100644 --- a/src/Ideas/Encoding/EncoderXML.hs +++ b/src/Ideas/Encoding/EncoderXML.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE GADTs #-} +{-# LANGUAGE OverloadedStrings, GADTs #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -120,7 +120,7 @@ encodeContext ctx = do loc = fromLocation (location ctx) withLoc | null loc = id - | otherwise = insertRef (makeRef "location") loc + | otherwise = insertRef (makeRef ("location" :: String)) loc in munless (null values) $ element "context" [ element "item" [ "name" .=. showId tb diff --git a/src/Ideas/Encoding/LinkManager.hs b/src/Ideas/Encoding/LinkManager.hs index 1e12a7eb..400d45d4 100644 --- a/src/Ideas/Encoding/LinkManager.hs +++ b/src/Ideas/Encoding/LinkManager.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE OverloadedStrings, RankNTypes #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -169,7 +169,7 @@ simpleRequest :: String -> XML simpleRequest s = makeRequest s mempty makeRequest :: String -> XMLBuilder -> XML -makeRequest s rest = makeXML (fromString "request") $ +makeRequest s rest = makeXML "request" $ ("service" .=. s) <> ("encoding" .=. "html") <> rest diff --git a/src/Ideas/Encoding/ModeXML.hs b/src/Ideas/Encoding/ModeXML.hs index ad4c0987..a62008d0 100644 --- a/src/Ideas/Encoding/ModeXML.hs +++ b/src/Ideas/Encoding/ModeXML.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -52,13 +53,11 @@ processXML options dr txt = do Nothing -> show e addVersion :: String -> XML -> XML -addVersion s xml = - let info = [ fromString "version" := s ] - in xml { attributes = attributes xml ++ info } +addVersion s = changeAttributes (<> attribute "version" s) xmlRequest :: Monad m => Maybe String -> XML -> m Request xmlRequest ms xml = do - unless (show (name xml) == "request") $ + unless (getName xml == "request") $ fail "expected xml tag request" enc <- case findAttribute "encoding" xml of Just s -> readEncoding s diff --git a/src/Ideas/Encoding/RulesInfo.hs b/src/Ideas/Encoding/RulesInfo.hs index 23434701..b84ce7ac 100644 --- a/src/Ideas/Encoding/RulesInfo.hs +++ b/src/Ideas/Encoding/RulesInfo.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -19,7 +20,7 @@ import Ideas.Common.Library import Ideas.Encoding.OpenMathSupport (toOMOBJ) import Ideas.Text.OpenMath.FMP import Ideas.Text.OpenMath.Object -import Ideas.Text.XML hiding (name) +import Ideas.Text.XML import Ideas.Utils.Prelude (munless) import qualified Data.Map as M diff --git a/src/Ideas/Encoding/StrategyInfo.hs b/src/Ideas/Encoding/StrategyInfo.hs index 8fcec098..9e011633 100644 --- a/src/Ideas/Encoding/StrategyInfo.hs +++ b/src/Ideas/Encoding/StrategyInfo.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -32,7 +33,7 @@ nameAttr :: Id -> XMLBuilder nameAttr info = "name" .=. showId info strategyTreeToXML :: StrategyTree a -> XML -strategyTreeToXML tree = makeXML (fromString "label") $ +strategyTreeToXML tree = makeXML "label" $ case isLabel tree of Just (l, a) -> nameAttr l <> strategyTreeBuilder a _ -> strategyTreeBuilder tree @@ -42,22 +43,22 @@ strategyTreeBuilder = builder . fold emptyAlg { fNode = \def xs -> case xs of [x] | isConfigId def - -> addProperty (show def) x + -> addProperty (fromString (show def)) x _ -> makeXML (fromString (show def)) (mconcat (map builder xs)) , fLeaf = \r -> - makeXML (fromString "rule") ("name" .=. show r) + makeXML "rule" ("name" .=. show r) , fLabel = \l a -> - makeXML (fromString "label") (nameAttr l <> builder a) + makeXML "label" (nameAttr l <> builder a) , fRec = \n a -> - makeXML (fromString "rec") (("var" .=. show n) <> builder a) + makeXML "rec" (("var" .=. show n) <> builder a) , fVar = \n -> - makeXML (fromString "var") ("var" .=. show n) + makeXML "var" ("var" .=. show n) } -addProperty :: String -> XML -> XML -addProperty s a = - if show (name a) `elem` ["label", "rule"] - then a { attributes = attributes a ++ [fromString s := "true"] } +addProperty :: Name -> XML -> XML +addProperty n a = + if getName a `elem` ["label", "rule"] + then changeAttributes (<> attribute n "true") a else a ----------------------------------------------------------------------- diff --git a/src/Ideas/Text/HTML.hs b/src/Ideas/Text/HTML.hs index 7a7cf752..3100af89 100644 --- a/src/Ideas/Text/HTML.hs +++ b/src/Ideas/Text/HTML.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -86,7 +87,7 @@ data HTMLPage = HTMLPage } instance ToXML HTMLPage where - toXML page = makeXML (fromString "html") $ + toXML page = makeXML (toName "html") $ element "head" [ tag "title" (string (title page)) , mconcat diff --git a/src/Ideas/Text/HTML/Templates.hs b/src/Ideas/Text/HTML/Templates.hs index 6859bc5c..67b65d2d 100644 --- a/src/Ideas/Text/HTML/Templates.hs +++ b/src/Ideas/Text/HTML/Templates.hs @@ -20,7 +20,7 @@ module Ideas.Text.HTML.Templates import Ideas.Text.HTML import Ideas.Text.HTML.W3CSS hiding (tag, ul, top, table, content) -import Ideas.Text.XML hiding (content) +import Ideas.Text.XML import qualified Ideas.Text.HTML.W3CSS as W3 data WebPage = WebPage diff --git a/src/Ideas/Text/HTML/W3CSS.hs b/src/Ideas/Text/HTML/W3CSS.hs index d88a6080..7616f4a3 100644 --- a/src/Ideas/Text/HTML/W3CSS.hs +++ b/src/Ideas/Text/HTML/W3CSS.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files diff --git a/src/Ideas/Text/MathML.hs b/src/Ideas/Text/MathML.hs index 91a5ce79..0212b139 100644 --- a/src/Ideas/Text/MathML.hs +++ b/src/Ideas/Text/MathML.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -15,7 +16,6 @@ module Ideas.Text.MathML ) where import Ideas.Text.XML -import Ideas.Text.XML.Decoder import Ideas.Utils.Uniplate hiding (children) import Ideas.Utils.Decoding @@ -57,33 +57,33 @@ instance ToXML MathML where instance InXML MathML where xmlDecoder = rec where - rec = xTag "mrow" (MRow <$> many rec) - <|> xTag "msqrt" (MSqrt <$> impliedRow) - <|> xTag "math" impliedRow - <|> xTag "mi" (MId <$> xString) - <|> xTag "mn" (MNumber <$> xString) - <|> xTag "mo" (MOperator <$> xString) - <|> xTag "ms" (MString <$> xString) - <|> xTag "mtext" (MText <$> xString) - <|> xTag "mroot" (MRoot <$> rec <*> rec) - <|> xTag "msup" (MSup <$> rec <*> rec) - <|> xTag "msub" (MSub <$> rec <*> rec) - <|> xTag "msubsup" (MSubSup <$> rec <*> rec <*> rec) - <|> xTag "mfrac" (MFrac <$> rec <*> rec) - <|> xTag "mfenced" (MFenced <$> xAttr "open" <*> xAttr "close" <*> rec) - <|> xTag "mspace" (return MSpace) - <|> xTag "mstyle" (return MStyle) - <|> xTag "mpadded" (return MPadded) - <|> xTag "mphantom" (return MPhantom) - <|> xTag "merror" (return MError) - <|> xTag "menclose" (return MEnclose) - <|> xTag "munder" (return MUnder) - <|> xTag "mover" (return MOver) - <|> xTag "munderover" (return MUnderOver) - <|> xTag "mtable" (return MTable) - <|> xTag "mtr" (return MTableRow) - <|> xTag "mlabeledtr" (return MLabeledTableRow) - <|> xTag "mtd" (return MTableData) + rec = xmlTag "mrow" (MRow <$> many rec) + <|> xmlTag "msqrt" (MSqrt <$> impliedRow) + <|> xmlTag "math" impliedRow + <|> xmlTag "mi" (MId <$> xmlString) + <|> xmlTag "mn" (MNumber <$> xmlString) + <|> xmlTag "mo" (MOperator <$> xmlString) + <|> xmlTag "ms" (MString <$> xmlString) + <|> xmlTag "mtext" (MText <$> xmlString) + <|> xmlTag "mroot" (MRoot <$> rec <*> rec) + <|> xmlTag "msup" (MSup <$> rec <*> rec) + <|> xmlTag "msub" (MSub <$> rec <*> rec) + <|> xmlTag "msubsup" (MSubSup <$> rec <*> rec <*> rec) + <|> xmlTag "mfrac" (MFrac <$> rec <*> rec) + <|> xmlTag "mfenced" (MFenced <$> xmlAttr "open" <*> xmlAttr "close" <*> rec) + <|> xmlTag "mspace" (return MSpace) + <|> xmlTag "mstyle" (return MStyle) + <|> xmlTag "mpadded" (return MPadded) + <|> xmlTag "mphantom" (return MPhantom) + <|> xmlTag "merror" (return MError) + <|> xmlTag "menclose" (return MEnclose) + <|> xmlTag "munder" (return MUnder) + <|> xmlTag "mover" (return MOver) + <|> xmlTag "munderover" (return MUnderOver) + <|> xmlTag "mtable" (return MTable) + <|> xmlTag "mtr" (return MTableRow) + <|> xmlTag "mlabeledtr" (return MLabeledTableRow) + <|> xmlTag "mtd" (return MTableData) impliedRow = f <$> many rec @@ -103,7 +103,7 @@ xml2mathml :: XML -> Either String MathML xml2mathml = either (Left . show) (Right . fst) . runDecoder xmlDecoder () . builder mathml2xml :: MathML -> XML -mathml2xml = makeXML (fromString "math") . rec +mathml2xml = makeXML "math" . rec where rec :: MathML -> XMLBuilder rec math = diff --git a/src/Ideas/Text/OpenMath/Object.hs b/src/Ideas/Text/OpenMath/Object.hs index 5db77184..4532408a 100644 --- a/src/Ideas/Text/OpenMath/Object.hs +++ b/src/Ideas/Text/OpenMath/Object.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -36,16 +37,16 @@ instance ToXML OMOBJ where toXML = omobj2xml instance InXML OMOBJ where - xmlDecoder = xTag "OMOBJ" rec + xmlDecoder = xmlTag "OMOBJ" rec where - rec = xTag "OMA" (OMA <$> many rec) - <|> xTag "OMS" (makeOMS <$> optional (xAttr "cd") <*> xAttr "name") - <|> xTag "OMI" (OMI . fromJust . readInt <$> xString) - <|> xTag "OMF" (OMF . fromJust . readDouble <$> xAttr "dec") - <|> xTag "OMV" (OMV <$> xAttr "name") - <|> xTag "OMBIND" (OMBIND <$> rec <*> recOMBVar <*> rec) + rec = xmlTag "OMA" (OMA <$> many rec) + <|> xmlTag "OMS" (makeOMS <$> optional (xmlAttr "cd") <*> xmlAttr "name") + <|> xmlTag "OMI" (OMI . fromJust . readInt <$> xmlString) + <|> xmlTag "OMF" (OMF . fromJust . readDouble <$> xmlAttr "dec") + <|> xmlTag "OMV" (OMV <$> xmlAttr "name") + <|> xmlTag "OMBIND" (OMBIND <$> rec <*> recOMBVar <*> rec) - recOMBVar = xTag "OMBVAR" (many (xTag "OMV" (xAttr "name"))) + recOMBVar = xmlTag "OMBVAR" (many (xmlTag "OMV" (xmlAttr "name"))) makeOMS (Just "unknown") a = OMS (Nothing, a) makeOMS cd a = OMS (cd, a) @@ -67,7 +68,7 @@ xml2omobj :: XML -> Either String OMOBJ xml2omobj = either (Left . show) (Right . fst) . runDecoder xmlDecoder () . builder omobj2xml :: OMOBJ -> XML -omobj2xml object = makeXML (fromString "OMOBJ") $ mconcat +omobj2xml object = makeXML "OMOBJ" $ mconcat [ "xmlns" .=. "http://www.openmath.org/OpenMath" , "version" .=. "2.0" , "cdbase" .=. "http://www.openmath.org/cd" diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index b12ca6ca..a483b882 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -13,48 +14,44 @@ ----------------------------------------------------------------------------- module Ideas.Text.XML - ( -- * XML types - XML, Name, fromString, Attributes, Attribute(..) + ( Name, toName, uncheckedName + , module Ideas.Text.XML.Attributes + , module Ideas.Text.XML.Data + , module Ideas.Text.XML.Builder + , module Ideas.Text.XML.Decoder -- * Parsing XML , parseXML, parseXMLFile - -- * Building/constructing XML - , BuildXML(..), XMLBuilder, makeXML - -- * Pretty-printing XML - , prettyXML, compactXML -- * Simple decoding queries - , name, attributes, findAttribute, children, findChildren, findChild - , getData, expecting + , findAttribute, children, findChildren, findChild + , getData -- * Decoding XML , decodeData, decodeAttribute, decodeChild, decodeFirstChild -- * Type classes for converting to/from XML - , ToXML(..), builderXML, InXML(..), DecoderXML - -- * Processing XML - , foldXML, trimXML + , ToXML(..), builderXML, InXML(..) -- * Deprecated functions - , content, emptyContent, fromBuilder + , fromBuilder ) where -import Control.Arrow import Control.Monad.State import Data.Char (chr) import Data.Maybe import Data.String +import Ideas.Text.XML.Attributes import Ideas.Text.XML.Builder +import Ideas.Text.XML.Decoder import Ideas.Text.XML.Data -import Ideas.Text.XML.Document (escape, Name) import Ideas.Text.XML.Parser (document) import Ideas.Utils.Decoding import Ideas.Utils.Parsing (parseSimple) import System.IO import qualified Ideas.Text.XML.Document as D +import Ideas.Text.XML.Document (Name, toName, uncheckedName) ------------------------------------------------------------------------------- -- Parsing XML parseXML :: String -> Either String XML -parseXML input = do - doc <- parseSimple document input - return (fromXMLDoc doc) +parseXML input = fromXMLDoc <$> parseSimple document input parseXMLFile :: FilePath -> IO XML parseXMLFile file = @@ -70,7 +67,7 @@ fromXMLDoc doc = fromElement (D.root doc) fromAttributes = mconcat . map fromAttribute fromAttribute (n D.:= v) = - show n .=. concatMap (either return refToString) v + n .=. concatMap (either return refToString) v fromContent :: D.Content -> XMLBuilder fromContent = mconcat . map f @@ -96,16 +93,15 @@ fromXMLDoc doc = fromElement (D.root doc) [ (n, char c) | (n, c) <- general ] general :: [(Name, Char)] - general = map (first fromString) - [("lt",'<'), ("gt",'>'), ("amp",'&'), ("apos",'\''), ("quot",'"')] + general = [("lt",'<'), ("gt",'>'), ("amp",'&'), ("apos",'\''), ("quot",'"')] ------------------------------------------------------------------------------- -- Simple decoding queries findAttribute :: Monad m => String -> XML -> m String -findAttribute s (Tag _ as _) = - case [ t | n := t <- as, s == show n ] of - [hd] -> return hd +findAttribute s xml = + case lookupAttribute (toName s) (getAttributes xml) of + Just hd -> return hd _ -> fail $ "Invalid attribute: " ++ show s children :: HasContent a => a -> [XML] @@ -120,7 +116,7 @@ children = rec . getContent Nothing -> [] findChildren :: String -> XML -> [XML] -findChildren s = filter ((==s) . show . name) . children +findChildren s = filter ((==s) . show . getName) . children findChild :: Monad m => String -> XML -> m XML findChild s e = @@ -140,10 +136,6 @@ getData = rec . getContent Just (_, rest) -> rec rest Nothing -> [] -expecting :: Monad m => String -> XML -> m () -expecting s xml = - unless (show (name xml) == s) $ fail $ "Expecting element " ++ s ++ ", but found " ++ show (name xml) - ------------------------------------------------------------------------------- -- Decoding XML @@ -155,19 +147,17 @@ decodeData = get >>= \xml -> decodeAttribute :: String -> Decoder env String XML String decodeAttribute s = get >>= \xml -> - case break hasName (attributes xml) of - (xs, (_ := val):ys) -> put xml {attributes = xs ++ ys } >> return val + case lookupAttribute (toName s) (getAttributes xml) of + Just val -> return val _ -> throwError $ "Could not find attribute " ++ s - where - hasName (n := _) = show n == s decodeChild :: String -> Decoder env String XML a -> Decoder env String XML a decodeChild s p = get >>= \xml -> - case extractChild (fromString s) (content xml) of + case extractChild (toName s) (getContent xml) of Just (y, rest) -> do put y a <- p - put xml { content = rest } + put (setContent rest xml) return a _ -> throwError $ "Could not find child " ++ s @@ -178,7 +168,7 @@ extractChild n = rec rec a = case headIsXML a of Just (xml, rest) - | n == name xml -> Just (xml, rest) + | n == getName xml -> Just (xml, rest) | otherwise -> add (xmlToContent xml) (rec rest) Nothing -> case headIsString a of @@ -190,7 +180,7 @@ extractChild n = rec decodeFirstChild :: String -> Decoder env String XML a -> Decoder env String XML a decodeFirstChild s p = get >>= \xml -> case headIsXML xml of - Just (y, rest) | show (name y) == s -> do + Just (y, rest) | show (getName y) == s -> do put y a <- p put rest @@ -204,19 +194,17 @@ class ToXML a where toXML :: a -> XML listToXML :: [a] -> XML -- default definitions - listToXML = makeXML (fromString "list") . mconcat . map builderXML + listToXML = makeXML (toName "list") . mconcat . map builderXML instance ToXML () where - toXML _ = makeXML (fromString "Unit") mempty + toXML _ = makeXML (toName "Unit") mempty instance ToXML a => ToXML (Maybe a) where - toXML = maybe (makeXML (fromString "Nothing") mempty) toXML + toXML = maybe (makeXML (toName "Nothing") mempty) toXML builderXML :: (ToXML a, BuildXML b) => a -> b builderXML = builder . toXML -type DecoderXML = Decoder () (Error XML) XMLBuilder - class ToXML a => InXML a where fromXML :: XML -> Maybe a --listFromXML :: XML -> Maybe [a] -- to be removed @@ -239,13 +227,10 @@ class ToXML a => InXML a where ------------------------------------------------------------------------------- -- Deprecated functions -emptyContent :: XML -> Bool -emptyContent = contentIsEmpty - fromBuilder :: XMLBuilder -> Maybe XML fromBuilder m = case headIsXML m of - Just (a, rest) | null (builderAttributes m) && contentIsEmpty rest + Just (a, rest) | noAttributes (getAttributes m) && contentIsEmpty rest -> Just a _ -> Nothing @@ -285,7 +270,7 @@ _runTests = do Right a -> a == xml mkPD, mkPA, mkBD, mkBA :: String -> XML - mkPD s = either error id $ parseXML $ "" ++ escape s ++ "" - mkPA s = either error id $ parseXML $ "" - mkBD s = makeXML (fromString "a") (string s) - mkBA s = makeXML (fromString "t") ("a".=. s) \ No newline at end of file + mkPD s = either error id $ parseXML $ "" ++ D.escape s ++ "" + mkPA s = either error id $ parseXML $ "" + mkBD s = makeXML "a" (string s) + mkBA s = makeXML "t" ("a".=. s) \ No newline at end of file diff --git a/src/Ideas/Text/XML/Attributes.hs b/src/Ideas/Text/XML/Attributes.hs new file mode 100644 index 00000000..1e60a2ef --- /dev/null +++ b/src/Ideas/Text/XML/Attributes.hs @@ -0,0 +1,64 @@ +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- +-- | +-- Maintainer : bastiaan.heeren@ou.nl +-- Stability : provisional +-- Portability : portable (depends on ghc) +-- +----------------------------------------------------------------------------- + +module Ideas.Text.XML.Attributes + ( Attributes, HasAttributes(..) + , attribute + , noAttributes, lookupAttribute + , foldAttributes + ) where + +import Ideas.Text.XML.Document (Name) +import qualified Data.Map as M + +newtype Attributes = A { attributeMap :: M.Map Name String } + deriving Eq + +data Attribute = Name := String + deriving Eq + +instance Semigroup Attributes where + A xs <> A ys = A $ M.unionWith (\x y -> x ++ " " ++ y) xs ys + +instance Monoid Attributes where + mempty = A M.empty + +class HasAttributes a where + getAttributes :: a -> Attributes + setAttributes :: Attributes -> a -> a + changeAttributes :: (Attributes -> Attributes) -> a -> a + updateAttributes :: a -> (Attributes, Attributes -> a) + + {-# MINIMAL (getAttributes, changeAttributes) | updateAttributes #-} + + -- default definitions + getAttributes = fst . updateAttributes + setAttributes = changeAttributes . const + changeAttributes f = (\(c, g) -> g (f c)) . updateAttributes + updateAttributes a = (getAttributes a, (`setAttributes` a)) + +instance HasAttributes Attributes where + updateAttributes a = (a, id) + +attribute :: Name -> String -> Attributes +attribute n s = A $ M.singleton n s + +lookupAttribute :: HasAttributes a => Name -> a -> Maybe String +lookupAttribute n = M.lookup n . attributeMap . getAttributes + +noAttributes :: HasAttributes a => a -> Bool +noAttributes = null . attributeMap . getAttributes + +foldAttributes :: Monoid a => (Name -> String -> a) -> Attributes -> a +foldAttributes fa = M.foldrWithKey f mempty . attributeMap + where + f n s = (fa n s <>) \ No newline at end of file diff --git a/src/Ideas/Text/XML/Builder.hs b/src/Ideas/Text/XML/Builder.hs index f1b28cbe..1152ed0d 100644 --- a/src/Ideas/Text/XML/Builder.hs +++ b/src/Ideas/Text/XML/Builder.hs @@ -12,27 +12,27 @@ module Ideas.Text.XML.Builder ( BuildXML(..) - , XMLBuilder, makeXML, builderAttributes, xmlToBuilder + , XMLBuilder, makeXML, makeXMLBuilder ) where -import Data.List (nubBy) import Data.String -import qualified Data.Map as M import Ideas.Text.XML.Data +import Ideas.Text.XML.Document (Name) +import Ideas.Text.XML.Attributes import Ideas.Utils.Decoding infix 7 .=. class (Semigroup a, Monoid a) => BuildXML a where - (.=.) :: String -> String -> a -- attribute - string :: String -> a -- (escaped) text - builder :: XML -> a -- (named) xml element - tag :: String -> a -> a -- tag (with content) + (.=.) :: Name -> String -> a -- attribute + string :: String -> a -- (escaped) text + builder :: XML -> a -- (named) xml element + tag :: Name -> a -> a -- tag (with content) -- functions with a default char :: Char -> a - text :: Show s => s -> a -- escaped text with Show class - element :: String -> [a] -> a - emptyTag :: String -> a + text :: Show s => s -> a -- escaped text with Show class + element :: Name -> [a] -> a + emptyTag :: Name -> a -- implementations char c = string [c] text = string . show @@ -47,40 +47,32 @@ instance BuildXML a => BuildXML (Decoder env err s a) where ------------------------------------------------------------------- -data XMLBuilder = BS Attributes Content +data XMLBuilder = B Attributes Content instance Semigroup XMLBuilder where - BS as1 elts1 <> BS as2 elts2 = BS (as1 <> as2) (elts1 <> elts2) + B as1 elts1 <> B as2 elts2 = B (as1 <> as2) (elts1 <> elts2) instance Monoid XMLBuilder where - mempty = BS mempty mempty + mempty = B mempty mempty mappend = (<>) instance BuildXML XMLBuilder where - n .=. s = BS [fromString n := s] mempty - string s = BS mempty (if null s then mempty else fromString s) - builder = BS mempty . xmlToContent - tag n = builder . makeXML (fromString n) + n .=. s = B (attribute n s) mempty + string s = B mempty (if null s then mempty else fromString s) + builder = B mempty . xmlToContent + tag n = builder . makeXML n instance IsString XMLBuilder where fromString = string instance HasContent XMLBuilder where - updateContent (BS as c) = (c, BS as) + updateContent (B as c) = (c, B as) -xmlToBuilder :: XML -> XMLBuilder -- is not builder??? -- !!! fix me -xmlToBuilder xml = BS (attributes xml) (content xml) +instance HasAttributes XMLBuilder where + updateAttributes (B as c) = (as, \bs -> B bs c) -makeXML :: Name -> XMLBuilder -> XML -makeXML n (BS as c) = Tag n (mergeAttributes as) c - -builderAttributes :: XMLBuilder -> Attributes -builderAttributes (BS as _) = as +makeXMLBuilder :: Attributes -> Content -> XMLBuilder +makeXMLBuilder = B -mergeAttributes :: Attributes -> Attributes -mergeAttributes as = nubBy eqKey (map make as) - where - attrMap = foldr add M.empty as - add (k := v) = M.insertWith (\x y -> x ++ " " ++ y) k v - make (k := _) = k := M.findWithDefault "" k attrMap - eqKey (k1 := _) (k2 := _) = k1 == k2 \ No newline at end of file +makeXML :: Name -> XMLBuilder -> XML +makeXML n (B as c) = xmlRoot n as c \ No newline at end of file diff --git a/src/Ideas/Text/XML/Data.hs b/src/Ideas/Text/XML/Data.hs index 8f65aff3..5b482f02 100644 --- a/src/Ideas/Text/XML/Data.hs +++ b/src/Ideas/Text/XML/Data.hs @@ -10,13 +10,9 @@ -- ----------------------------------------------------------------------------- --- to do: protect constructor Tag and invariant - module Ideas.Text.XML.Data ( -- types - XML(..) - , Attributes, Attribute(..) - , Name, uncheckedName + XML, xmlRoot, getName , Content, xmlToContent , HasContent(..), contentIsEmpty, headIsString, headIsXML -- pretty-printing @@ -27,29 +23,19 @@ module Ideas.Text.XML.Data import Data.Char (isSpace, ord) import Data.String -import Ideas.Text.XML.Document (Name, uncheckedName) +import Ideas.Text.XML.Attributes +import Ideas.Text.XML.Document (Name) import qualified Ideas.Text.XML.Document as D ------------------------------------------------------------------------------- -- XML types --- invariants content: no two adjacent Lefts, no Left with empty string, --- valid tag/attribute names -data XML = Tag - { name :: Name - , attributes :: Attributes - , content :: Content - } +data XML = Root Name Attributes Content deriving Eq instance Show XML where show = compactXML -type Attributes = [Attribute] - -data Attribute = Name := String - deriving Eq - data Content = Empty | CData String | Cons XML Content @@ -97,7 +83,16 @@ instance HasContent Content where updateContent a = (a, id) instance HasContent XML where - updateContent xml = (content xml, \new -> xml {content = new}) + updateContent (Root n as c) = (c, xmlRoot n as) + +instance HasAttributes XML where + updateAttributes (Root n as c) = (as, \bs -> xmlRoot n bs c) + +xmlRoot :: Name -> Attributes -> Content -> XML +xmlRoot = Root + +getName :: XML -> Name +getName (Root n _ _) = n contentIsEmpty :: HasContent a => a -> Bool contentIsEmpty a = @@ -133,8 +128,8 @@ compactXML = show . D.prettyElement True . toElement toElement :: XML -> D.Element toElement = foldXML D.Element mkAttribute mkString (return . D.Tagged) where - mkAttribute :: Attribute -> D.Attribute - mkAttribute (m := s) = (D.:=) m (map Left s) + mkAttribute :: Name -> String -> D.Attributes + mkAttribute m s = [(D.:=) m (map Left s)] mkString :: String -> [D.XML] mkString [] = [] @@ -147,10 +142,10 @@ toElement = foldXML D.Element mkAttribute mkString (return . D.Tagged) ------------------------------------------------------------------------------- -- Processing XML -foldXML :: Monoid c => (Name -> [a] -> c -> e) -> (Attribute -> a) -> (String -> c) -> (e -> c) -> XML -> e +foldXML :: (Monoid a, Monoid c) => (Name -> a -> c -> e) -> (Name -> String -> a) -> (String -> c) -> (e -> c) -> XML -> e foldXML f fa fs fc = rec where - rec (Tag n as cs) = f n (map fa as) (recContent cs) + rec (Root n as cs) = f n (foldAttributes fa as) (recContent cs) recContent Empty = mempty recContent (CData s) = fs s @@ -158,9 +153,9 @@ foldXML f fa fs fc = rec recContent (Mixed s x c) = fs s <> fc (rec x) <> recContent c trimXML :: XML -> XML -trimXML = foldXML Tag f (fromString . trim) xmlToContent +trimXML = foldXML xmlRoot f (fromString . trim) xmlToContent where - f (n := s) = n := trim s + f n = attribute n . trim trim, trimLeft, trimRight :: String -> String trim = trimLeft . trimRight diff --git a/src/Ideas/Text/XML/Decoder.hs b/src/Ideas/Text/XML/Decoder.hs index 799e965d..a10c6188 100644 --- a/src/Ideas/Text/XML/Decoder.hs +++ b/src/Ideas/Text/XML/Decoder.hs @@ -12,47 +12,47 @@ module Ideas.Text.XML.Decoder ( DecoderXML, evalDecoderXML - , Error, errorStr - , xTag, xString, xAttr, xEnd - -- re-exports - , Alternative(..), MonadReader(..), throwError + , xmlTag, xmlString, xmlAttr, xmlEnd ) where +import Data.String import Ideas.Utils.Decoding +import Ideas.Text.XML.Attributes import Ideas.Text.XML.Data import Ideas.Text.XML.Builder +import Ideas.Text.XML.Document (Name) type DecoderXML = Decoder () (Error XML) XMLBuilder evalDecoderXML :: DecoderXML a -> XML -> Either (Error XML) a evalDecoderXML p = evalDecoder p () . builder -xTag :: String -> DecoderXML a -> DecoderXML a -xTag s p = get >>= \xml -> +xmlTag :: Name -> DecoderXML a -> DecoderXML a +xmlTag n p = get >>= \xml -> case headIsXML xml of - Just (hd, rest) | show (name hd) == s -> do - put (xmlToBuilder hd) + Just (hd, rest) | getName hd == n -> do + put (makeXMLBuilder (getAttributes hd) (getContent hd)) a <- p - xEnd + xmlEnd put rest return a _ -> errorStr "xTag" -xString :: DecoderXML String -xString = do +xmlString :: DecoderXML String +xmlString = do xml <- get case headIsString xml of Just (s, rest) -> put rest >> return s Nothing -> errorStr "xString" -xAttr :: String -> DecoderXML String -xAttr s = get >>= \xml -> - case filter (\(n := _) -> show n == s) (builderAttributes xml) of - [_ := v] -> return v +xmlAttr :: String -> DecoderXML String +xmlAttr s = get >>= \xml -> + case lookupAttribute (fromString s) (getAttributes xml) of + Just v -> return v _ -> errorStr "xAttr" -xEnd :: DecoderXML () -xEnd = get >>= \xml -> +xmlEnd :: DecoderXML () +xmlEnd = get >>= \xml -> if contentIsEmpty xml then return () else errorStr "xEnd" \ No newline at end of file diff --git a/src/Ideas/Text/XML/Document.hs b/src/Ideas/Text/XML/Document.hs index df56fd4c..3425258e 100644 --- a/src/Ideas/Text/XML/Document.hs +++ b/src/Ideas/Text/XML/Document.hs @@ -13,7 +13,7 @@ ----------------------------------------------------------------------------- module Ideas.Text.XML.Document - ( Name, uncheckedName, fromString + ( Name, toName, uncheckedName , Attributes, Attribute(..), Reference(..), Parameter(..) , XMLDoc(..), XML(..), Element(..), Content, DTD(..), DocTypeDecl(..) , ContentSpec(..), CP(..), AttType(..), DefaultDecl(..), AttDef @@ -37,9 +37,12 @@ instance Show Name where show (N s) = s instance IsString Name where - fromString s - | validName s = N s - | otherwise = error $ "Invalid XML name: " ++ s + fromString = toName + +toName :: String -> Name +toName s + | validName s = N s + | otherwise = error $ "Invalid XML name: " ++ s uncheckedName :: String -> Name uncheckedName = N From d67f83b377dd1a7301c5a53f4da30f2ee787c85a Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 11 Apr 2022 14:49:38 +0200 Subject: [PATCH 41/57] interactive command-line option for testing --- src/Ideas/Main/CmdLineOptions.hs | 21 ++++++------ src/Ideas/Main/Default.hs | 7 ++-- src/Ideas/Utils/BlackBoxTests.hs | 55 +++++++++++++++++++++----------- src/Ideas/Utils/TestSuite.hs | 27 ++++++++++------ 4 files changed, 68 insertions(+), 42 deletions(-) diff --git a/src/Ideas/Main/CmdLineOptions.hs b/src/Ideas/Main/CmdLineOptions.hs index a0e72817..3d0c9a6b 100644 --- a/src/Ideas/Main/CmdLineOptions.hs +++ b/src/Ideas/Main/CmdLineOptions.hs @@ -26,14 +26,14 @@ import System.Exit data CmdLineOption = Version | Help | PrintLog - | InputFile String | Rerun String | Test FilePath + | InputFile String | Rerun String | Test FilePath | Interactive | MakeScriptFor String | AnalyzeScript FilePath deriving Eq header :: String header = "IDEAS: Intelligent Domain-specific Exercise Assistants\n" ++ - "Copyright 2019, Open Universiteit Nederland\n" ++ + "Copyright 2022, Open Universiteit\n" ++ versionText ++ "\n\nUsage: ideas [OPTION] (by default, CGI protocol)\n" ++ "\nOptions:" @@ -55,14 +55,15 @@ shortVersion = ideasVersion ++ " (" ++ ideasRevision ++ ")" options :: [OptDescr CmdLineOption] options = - [ Option [] ["version"] (NoArg Version) "show version number" - , Option "?" ["help"] (NoArg Help) "show options" - , Option "" ["print-log"] (NoArg PrintLog) "print log information (for debugging)" - , Option "f" ["file"] fileArg "use input FILE as request" - , Option "" ["rerun"] rerunArg "rerun inputs from database" - , Option "" ["test"] testArg "run tests on directory (default: 'test')" - , Option "" ["make-script"] makeScrArg "generate feedback script for exercise" - , Option "" ["analyze-script"] analyzeScrArg "analyze feedback script and report errors" + [ Option [] ["version"] (NoArg Version) "show version number" + , Option "?" ["help"] (NoArg Help) "show options" + , Option "" ["print-log"] (NoArg PrintLog) "print log information (for debugging)" + , Option "f" ["file"] fileArg "use input FILE as request" + , Option "" ["rerun"] rerunArg "rerun inputs from database" + , Option "" ["test"] testArg "run tests on directory (default: 'test')" + , Option "i" ["interactive"] (NoArg Interactive) "test in interactive mode" + , Option "" ["make-script"] makeScrArg "generate feedback script for exercise" + , Option "" ["analyze-script"] analyzeScrArg "analyze feedback script and report errors" ] fileArg, rerunArg, testArg, makeScrArg, analyzeScrArg :: ArgDescr CmdLineOption diff --git a/src/Ideas/Main/Default.hs b/src/Ideas/Main/Default.hs index 9222d9c3..02071101 100644 --- a/src/Ideas/Main/Default.hs +++ b/src/Ideas/Main/Default.hs @@ -37,7 +37,7 @@ import Ideas.Service.ServiceList import Ideas.Service.Types (Service) import qualified Ideas.Text.UTF8 as UTF8 import Ideas.Text.XML.Unicode (decoding) -import Ideas.Utils.BlackBoxTests +import qualified Ideas.Utils.BlackBoxTests as BB import Ideas.Utils.Prelude import Ideas.Utils.TestSuite import Network.HTTP.Types @@ -136,13 +136,14 @@ defaultCommandLine options dr cmdLineOptions = do Log.printLog (logRef options) -- blackbox tests Test dir -> do - tests <- blackBoxTests (makeTestRunner dr) ["xml", "json"] dir + let mode = if Interactive `elem` cmdLineOptions then BB.Interactive else BB.Report + tests <- BB.blackBoxTests (makeTestRunner dr) mode ["xml", "json"] dir result <- runTestSuiteResult True tests printSummary result -- feedback scripts MakeScriptFor s -> makeScriptFor dr s AnalyzeScript file -> parseAndAnalyzeScript dr file - PrintLog -> return () + _ -> return () processDatabase :: DomainReasoner -> FilePath -> IO () processDatabase dr database = do diff --git a/src/Ideas/Utils/BlackBoxTests.hs b/src/Ideas/Utils/BlackBoxTests.hs index 41e95be5..abf5df92 100644 --- a/src/Ideas/Utils/BlackBoxTests.hs +++ b/src/Ideas/Utils/BlackBoxTests.hs @@ -10,10 +10,12 @@ -- ----------------------------------------------------------------------------- -module Ideas.Utils.BlackBoxTests (blackBoxTests, TestRunner) where +module Ideas.Utils.BlackBoxTests + (blackBoxTests, TestRunner, Mode(..)) where import Control.Monad import Data.Char +import Data.IORef import Data.List import Ideas.Utils.TestSuite import System.Directory @@ -22,9 +24,16 @@ import qualified Data.Algorithm.Diff as Diff type TestRunner = String -> IO String +data Mode = Interactive | Report | Replace + -- Returns the number of tests performed -blackBoxTests :: TestRunner -> [String] -> String -> IO TestSuite -blackBoxTests runner exts = rec +blackBoxTests :: TestRunner -> Mode -> [String] -> String -> IO TestSuite +blackBoxTests runner mode exts path = do + ref <- newIORef mode + blackBoxTestsInMode ref runner exts path + +blackBoxTestsInMode :: IORef Mode -> TestRunner -> [String] -> String -> IO TestSuite +blackBoxTestsInMode ref runner exts = rec where rec path = do -- analyse content @@ -35,12 +44,12 @@ blackBoxTests runner exts = rec subs <- filterM doesDirectoryExist xs2 rest <- mapM rec subs return $ suite ("Directory " ++ simplerDirectory path) $ - [ doBlackBoxTest runner (path x) + [ doBlackBoxTest ref runner (path x) | x <- files ] ++ rest -doBlackBoxTest :: TestRunner -> FilePath -> TestSuite -doBlackBoxTest runner path = +doBlackBoxTest :: IORef Mode -> TestRunner -> FilePath -> TestSuite +doBlackBoxTest ref runner path = assertMessageIO (stripDirectoryPart path) $ -- Comparing output with expected output withFile path ReadMode $ \h1 -> do @@ -57,11 +66,30 @@ doBlackBoxTest runner path = msg = unlines (path : diffs list1 list2) if list1 == list2 then return mempty else do force msg -- force evaluation of message before closing files - return (message msg) + return $ addPostHook (postHook out) $ message msg where expPath = baseOf path ++ ".exp" baseOf = reverse . drop 1 . dropWhile (/= '.') . reverse + postHook out status = do + mode <- readIORef ref + case mode of + _ | isOk status -> return () + Report -> return () + Replace -> replaceExpected + Interactive -> do + putStrLn "Replace expected file: (y)es, (s)kip, (a)lways, or (n)ever?" + putStr "? " + answer <- getLine + case map toLower answer of + "y" -> replaceExpected + "s" -> return () + "a" -> replaceExpected >> writeIORef ref Replace + "n" -> writeIORef ref Report + _ -> postHook out status + where + replaceExpected = writeFile expPath out + elemExts :: FilePath -> [String] -> Bool elemExts s = any (\xs -> ('.':xs) `isSuffixOf` s) @@ -96,15 +124,4 @@ stripDirectoryPart :: String -> String stripDirectoryPart = reverse . takeWhile (/= '/') . reverse () :: FilePath -> FilePath -> FilePath -x y = x ++ "/" ++ y - -{- -logicConfluence :: IO () -logicConfluence = reportTest "logic rules" (isConfluent f rs) - where - f = normalizeWith ops . normalFormWith ops rs - ops = map makeCommutative Logic.logicOperators - rwrs = Logic.logicRules \\ [Logic.ruleOrOverAnd, Logic.ruleCommOr, Logic.ruleCommAnd] - rs = [ r | RewriteRule r <- concatMap transformations rwrs ] - -- eqs = bothWays [ r | RewriteRule r <- concatMap transformations Logic.logicRules ] --} \ No newline at end of file +x y = x ++ "/" ++ y \ No newline at end of file diff --git a/src/Ideas/Utils/TestSuite.hs b/src/Ideas/Utils/TestSuite.hs index 2c938e36..fb34427f 100644 --- a/src/Ideas/Utils/TestSuite.hs +++ b/src/Ideas/Utils/TestSuite.hs @@ -30,7 +30,7 @@ module Ideas.Utils.TestSuite , nrOfTests, nrOfErrors, nrOfWarnings , timeInterval, makeSummary, printSummary -- * Message - , Message, message, warning, messageLines + , Message, message, warning, messageLines, addPostHook -- * Status , Status, HasStatus(..) , isError, isWarning, isOk @@ -193,6 +193,7 @@ runner ref chattyIO = runTS newlineIndent ref print msg reset ref + messagePostHook msg returnStrict (caseResult (s, msg)) where handler :: SomeException -> IO Message @@ -343,11 +344,11 @@ makeSummary result = unlines $ -- Message data Message = M - { messageStatus :: !Status - , messageRating :: !Rating - , messageLines :: [String] + { messageStatus :: !Status + , messageRating :: !Rating + , messageLines :: [String] + , messagePostHook :: IO () } - deriving Eq instance Show Message where show a = st ++ sep ++ msg @@ -360,12 +361,15 @@ instance Show Message where | otherwise = "" instance Sem.Semigroup Message where - M s r xs <> M t q ys = M (s <> t) (r <> q) (xs <> ys) + M s r xs ph1 <> M t q ys ph2 = M (s <> t) (r <> q) (xs <> ys) (ph1 <> ph2) instance Monoid Message where - mempty = M mempty mempty mempty + mempty = M mempty mempty mempty (return ()) mappend = (<>) +instance HasStatus Status where + getStatus = id + instance HasStatus Message where getStatus = messageStatus @@ -374,16 +378,19 @@ instance HasRating Message where rate n a = a {messageRating = Rating n} message :: String -> Message -message = M Error (Rating 0) . return +message s = M Error (Rating 0) [s] (return ()) warning :: String -> Message -warning = M Warning mempty . return +warning s = M Warning mempty [s] (return ()) + +addPostHook :: (Status -> IO ()) -> Message -> Message +addPostHook postHook m = m { messagePostHook = messagePostHook m <> postHook (messageStatus m) } ----------------------------------------------------- -- Status data Status = Ok | Warning | Error - deriving (Eq, Ord) + deriving (Show, Eq, Ord) instance Sem.Semigroup Status where (<>) = max From 3b9905f092b20f8c4461bba7a537dbfef0d215a9 Mon Sep 17 00:00:00 2001 From: Heeren Date: Mon, 11 Apr 2022 17:12:26 +0200 Subject: [PATCH 42/57] writing binary files --- src/Ideas/Utils/BlackBoxTests.hs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Ideas/Utils/BlackBoxTests.hs b/src/Ideas/Utils/BlackBoxTests.hs index abf5df92..a1b745c5 100644 --- a/src/Ideas/Utils/BlackBoxTests.hs +++ b/src/Ideas/Utils/BlackBoxTests.hs @@ -88,7 +88,8 @@ doBlackBoxTest ref runner path = "n" -> writeIORef ref Report _ -> postHook out status where - replaceExpected = writeFile expPath out + replaceExpected = withFile expPath WriteMode $ \h -> + hSetBinaryMode h True >> hPutStr h out elemExts :: FilePath -> [String] -> Bool elemExts s = any (\xs -> ('.':xs) `isSuffixOf` s) From b21d1ee0702d64d3148ab57f331d0b980c9ea07b Mon Sep 17 00:00:00 2001 From: Heeren Date: Tue, 19 Jul 2022 10:54:55 +0200 Subject: [PATCH 43/57] Update Derivation.hs added boolean flag to mergeBy (in Derivation) to indicate which term is to be kept when merging derivations --- src/Ideas/Common/Derivation.hs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Ideas/Common/Derivation.hs b/src/Ideas/Common/Derivation.hs index 2c5db141..44edd257 100644 --- a/src/Ideas/Common/Derivation.hs +++ b/src/Ideas/Common/Derivation.hs @@ -70,12 +70,18 @@ extend :: Derivation s a -> (s, a) -> Derivation s a extend (D a xs) p = D a (xs S.|> p) merge :: Eq a => Derivation s a -> Derivation s a -> Maybe (Derivation s a) -merge = mergeBy (==) - -mergeBy :: (a -> a -> Bool) -> Derivation s a -> Derivation s a -> Maybe (Derivation s a) -mergeBy eq d@(D a xs) (D b ys) - | eq (lastTerm d) b = Just $ D a (xs <> ys) - | otherwise = Nothing +merge = mergeBy True (==) + +-- the 'keepUpper' boolean indicates whether to keep the upper term in the middle (or the lower term) +mergeBy :: Bool -> (a -> a -> Bool) -> Derivation s a -> Derivation s a -> Maybe (Derivation s a) +mergeBy keepUpper eq d@(D a xs) d2@(D b ys) + | not (eq (lastTerm d) b) = Nothing + | keepUpper = Just $ D a (xs <> ys) + | otherwise = Just $ + case S.viewr xs of + S.EmptyR -> d2 + xs' S.:> (s, _) -> mergeStep (D a xs') s d2 + mergeStep :: Derivation s a -> s -> Derivation s a -> Derivation s a mergeStep (D a xs) s (D b ys) = D a (xs <> ((s, b) S.<| ys)) From 25af94ff908a4516ed1e8f25df56bc80e1768b9f Mon Sep 17 00:00:00 2001 From: Heeren Date: Fri, 9 Dec 2022 16:01:40 +0100 Subject: [PATCH 44/57] ghc 9.2.5 Compatibility with ghc 9.2.5, base 4.16.4.0 and cabal 3.6.2.0. Most fixes are related to the MonadFail type class (and its fail method that is no longer part of Monadf) --- .gitignore | 4 +++- ideas.cabal | 10 +++++----- src/Ideas/Common/Constraint.hs | 4 +++- src/Ideas/Common/Rewriting/AutoTerm.hs | 10 +++++----- src/Ideas/Common/Rewriting/RewriteRule.hs | 2 +- src/Ideas/Common/Rewriting/Unification.hs | 2 +- src/Ideas/Common/Strategy/Abstract.hs | 2 +- src/Ideas/Common/View.hs | 2 +- src/Ideas/Encoding/DecoderJSON.hs | 7 +++++-- src/Ideas/Encoding/DecoderXML.hs | 2 +- src/Ideas/Encoding/Encoder.hs | 2 +- src/Ideas/Encoding/EncoderHTML.hs | 2 +- src/Ideas/Encoding/ModeJSON.hs | 10 +++++----- src/Ideas/Encoding/ModeXML.hs | 6 +++--- src/Ideas/Encoding/NewModeJSON.hs | 10 +++++----- src/Ideas/Encoding/Request.hs | 6 +++--- src/Ideas/Service/DomainReasoner.hs | 15 +++++++++------ src/Ideas/Service/Types.hs | 2 +- src/Ideas/Text/JSON/Data.hs | 2 +- src/Ideas/Text/XML.hs | 4 ++-- src/Ideas/Utils/Decoding.hs | 2 ++ src/Ideas/Utils/TestSuite.hs | 2 -- 22 files changed, 59 insertions(+), 49 deletions(-) diff --git a/.gitignore b/.gitignore index 787e4071..e39c6af8 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,6 @@ docs/compile.txt tutorial/Tutorial.hi tutorial/Tutorial.exe tutorial/Tutorial.o -report.html +report.html +cabal.project.local +dist-newstyle/ diff --git a/ideas.cabal b/ideas.cabal index 8c505c46..829eb029 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -49,21 +49,21 @@ Library ghc-options: -Wall hs-source-dirs: src Build-Depends: - base >= 4.11 && < 5, - blaze-builder >= 0.4, + base < 4.17, + blaze-builder, bytestring, case-insensitive, - QuickCheck >= 2.8 && < 2.14, + QuickCheck, Diff, containers, directory, filepath, http-types, mtl, - network < 3.0, + network, parsec, random, - streaming-commons < 0.2, + streaming-commons, time, uniplate, wai, diff --git a/src/Ideas/Common/Constraint.hs b/src/Ideas/Common/Constraint.hs index 07a10935..a00e8d1d 100644 --- a/src/Ideas/Common/Constraint.hs +++ b/src/Ideas/Common/Constraint.hs @@ -101,11 +101,13 @@ instance Alternative Result where instance Monad Result where return = Ok - fail = Error Irrelevant >>= _ = Irrelevant Error msg >>= _ = Error msg Ok a >>= f = f a +instance MonadFail Result where + fail = Error + instance MonadPlus Result where mzero = empty mplus = (<|>) diff --git a/src/Ideas/Common/Rewriting/AutoTerm.hs b/src/Ideas/Common/Rewriting/AutoTerm.hs index d262cac2..b230e00d 100644 --- a/src/Ideas/Common/Rewriting/AutoTerm.hs +++ b/src/Ideas/Common/Rewriting/AutoTerm.hs @@ -75,14 +75,14 @@ constructors = dataTypeConstrs . dataTypeOf . fromProxy fromProxy :: Proxy a -> a fromProxy = error "fromProxy" -findConstr :: (Monad m, Data a) => Proxy a -> Symbol -> m Constr +findConstr :: (MonadFail m, Data a) => Proxy a -> Symbol -> m Constr findConstr p s = case [ c | c <- constructors p, s == constrSymbol c ] of [] -> fail "Autoterm.findConstr" hd:_ -> return hd -fromTermG :: (MonadPlus m, Data a) => Term -> m a +fromTermG :: (MonadPlus m, MonadFail m, Data a) => Term -> m a fromTermG term = case term of TCon s xs -> fromTermTConG Proxy s xs @@ -96,13 +96,13 @@ fromTermG term = cons = binary consSymbol nil = symbol nilSymbol -castM :: (Monad m, Typeable a, Typeable b) => a -> m b +castM :: (MonadFail m, Typeable a, Typeable b) => a -> m b castM = maybe (fail "fromTermG") return . cast doubleToFloat :: Double -> Float doubleToFloat = fromRational . toRational -fromTermTConG :: (MonadPlus m, Data a) => Proxy a -> Symbol -> [Term] -> m a +fromTermTConG :: (MonadPlus m, MonadFail m, Data a) => Proxy a -> Symbol -> [Term] -> m a fromTermTConG p s xs = do c <- findConstr p s evalStateT (gunfold op return c) xs @@ -113,7 +113,7 @@ fromTermTConG p s xs = do a <- lift (fromTermG t) return (f a) -pop :: Monad m => StateT [a] m a +pop :: MonadFail m => StateT [a] m a pop = do ts <- get case ts of diff --git a/src/Ideas/Common/Rewriting/RewriteRule.hs b/src/Ideas/Common/Rewriting/RewriteRule.hs index 5d3bb217..54271f01 100644 --- a/src/Ideas/Common/Rewriting/RewriteRule.hs +++ b/src/Ideas/Common/Rewriting/RewriteRule.hs @@ -214,5 +214,5 @@ renumberRewriteRule n r = r {ruleSpecTerm = fmap f (ruleSpecTerm r)} toTermRR :: RewriteRule a -> a -> Term toTermRR = build . ruleTermView -fromTermRR :: Monad m => RewriteRule a -> Term -> m a +fromTermRR :: MonadFail m => RewriteRule a -> Term -> m a fromTermRR = matchM . ruleTermView \ No newline at end of file diff --git a/src/Ideas/Common/Rewriting/Unification.hs b/src/Ideas/Common/Rewriting/Unification.hs index af2dff2c..f8bdce83 100644 --- a/src/Ideas/Common/Rewriting/Unification.hs +++ b/src/Ideas/Common/Rewriting/Unification.hs @@ -51,7 +51,7 @@ unify term1 term2 = return (s2 @@ s1) rec _ _ = fail "match: no unifier" -match :: MonadPlus m => Term -> Term -> m Substitution +match :: (MonadPlus m, MonadFail m) => Term -> Term -> m Substitution match term1 term2 = case (term1, term2) of (TMeta i, TMeta j) | i == j -> diff --git a/src/Ideas/Common/Strategy/Abstract.hs b/src/Ideas/Common/Strategy/Abstract.hs index 260d0843..9b4c5499 100644 --- a/src/Ideas/Common/Strategy/Abstract.hs +++ b/src/Ideas/Common/Strategy/Abstract.hs @@ -163,7 +163,7 @@ replayPaths paths s a = mconcat -- | Construct a prefix for a path and a labeled strategy. The third argument -- is the initial term. -replayStrategy :: (Monad m, IsStrategy f) => Path -> f a -> a -> m (a, Prefix a) +replayStrategy :: (MonadFail m, IsStrategy f) => Path -> f a -> a -> m (a, Prefix a) replayStrategy path s a = let (xs, f) = replayProcess path (getProcess s) in case applyList xs a of diff --git a/src/Ideas/Common/View.hs b/src/Ideas/Common/View.hs index b5d78529..10971299 100644 --- a/src/Ideas/Common/View.hs +++ b/src/Ideas/Common/View.hs @@ -57,7 +57,7 @@ class IsMatcher f where matcher = makeMatcher . match -- |generalized monadic variant of @match@ -matchM :: (Monad m, IsMatcher f) => f a b -> a -> m b +matchM :: (MonadFail m, IsMatcher f) => f a b -> a -> m b matchM v = maybe (fail "no match") return . match v belongsTo :: IsMatcher f => a -> f a b -> Bool diff --git a/src/Ideas/Encoding/DecoderJSON.hs b/src/Ideas/Encoding/DecoderJSON.hs index 71ec9113..89c07635 100644 --- a/src/Ideas/Encoding/DecoderJSON.hs +++ b/src/Ideas/Encoding/DecoderJSON.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE GADTs #-} +{-# LANGUAGE GADTs, FlexibleInstances #-} ----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files @@ -29,6 +29,9 @@ import Ideas.Service.Types hiding (String) import Ideas.Text.JSON import qualified Ideas.Service.Types as Tp +--instance MonadFail (Either String) where +-- fail = Left + type JSONDecoder a = GDecoderJSON (Exercise a, Options) jsonTypeDecoder :: TypedDecoder a JSON @@ -146,7 +149,7 @@ decodeExpression = withJSONTerm $ \b -> then do mv <- hasJSONView <$> getExercise case mv of - Just v -> jNext (matchM v) + Just v -> jNext (maybe (Left "cannot decode expression from JSON") Right . matchM v) Nothing -> errorStr "JSON encoding not supported by exercise" else do ex <- getExercise diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index 6a1df6d9..43e0d819 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -208,5 +208,5 @@ decodeBinding = get >>= \xml -> do termBinding :: String -> Term -> Binding termBinding = makeBinding . makeRef -fromXML' :: (Monad m, InXML a) => XML -> m a +fromXML' :: (MonadFail m, InXML a) => XML -> m a fromXML' = maybe (fail "fromXML'") return . fromXML \ No newline at end of file diff --git a/src/Ideas/Encoding/Encoder.hs b/src/Ideas/Encoding/Encoder.hs index 1de7df7c..b80a08da 100644 --- a/src/Ideas/Encoding/Encoder.hs +++ b/src/Ideas/Encoding/Encoder.hs @@ -178,7 +178,7 @@ infixr 5 Nothing -> q tv encodeTyped :: (t -> EncoderX a b) -> Type a t -> TypedEncoder a b -encodeTyped p t1 tv@(_ ::: t2) = ((p, t1) fail ("Types do not match: " ++ show t1 ++ " and " ++ show t2)) tv +encodeTyped p t1 tv@(_ ::: t2) = ((p, t1) (\_ -> fail ("Types do not match: " ++ show t1 ++ " and " ++ show t2))) tv ------------------------------------------------------------------- -- Decoder datatype diff --git a/src/Ideas/Encoding/EncoderHTML.hs b/src/Ideas/Encoding/EncoderHTML.hs index bed86e39..3ba407b9 100644 --- a/src/Ideas/Encoding/EncoderHTML.hs +++ b/src/Ideas/Encoding/EncoderHTML.hs @@ -542,7 +542,7 @@ useAllFirsts dr = unsafePerformIO . useAllFirstsIO dr useAllFirstsIO :: DomainReasoner -> State a -> IO (Either String [(StepInfo a, State a)]) useAllFirstsIO dr st = do - srv <- findService dr (newId ("allfirsts" :: String)) + srv <- findServiceM dr (newId ("allfirsts" :: String)) case serviceFunction srv of f ::: tp -> do conv <- equalM tp (tState .-> tError (tList (Tag "first" (tPair tStepInfo tState)))) diff --git a/src/Ideas/Encoding/ModeJSON.hs b/src/Ideas/Encoding/ModeJSON.hs index 48eec7e0..1e898281 100644 --- a/src/Ideas/Encoding/ModeJSON.hs +++ b/src/Ideas/Encoding/ModeJSON.hs @@ -46,7 +46,7 @@ processJSON' options dr json = do return (req, f out, "application/json") -- TODO: Clean-up code -extractExerciseId :: Monad m => JSON -> m Id +extractExerciseId :: MonadFail m => JSON -> m Id extractExerciseId json = case json of String s -> return (newId s) @@ -66,7 +66,7 @@ addVersion str json = where info = ("version", String str) -jsonRequest :: Monad m => Options -> JSON -> m Request +jsonRequest :: MonadFail m => Options -> JSON -> m Request jsonRequest options json = do let exId = lookupM "params" json >>= extractExerciseId srv <- stringOption "method" json newId @@ -93,10 +93,10 @@ defaultSeed options | isJust (cgiBin options) = Nothing | otherwise = Just 2805 -- magic number -stringOption :: Monad m => String -> JSON -> (String -> a) -> m (Maybe a) +stringOption :: MonadFail m => String -> JSON -> (String -> a) -> m (Maybe a) stringOption attr json f = stringOptionM attr json Nothing (return . Just . f) -stringOptionM :: Monad m => String -> JSON -> a -> (String -> m a) -> m a +stringOptionM :: MonadFail m => String -> JSON -> a -> (String -> m a) -> m a stringOptionM attr json a f = case lookupM attr json of Just (String s) -> f s @@ -105,7 +105,7 @@ stringOptionM attr json a f = myHandler :: Options -> DomainReasoner -> Request -> RPCHandler myHandler opt1 dr request fun json = do - srv <- findService dr (newId fun) + srv <- findServiceM dr (newId fun) Some ex <- case exerciseId request of Just a -> findExercise dr a Nothing -> return (Some emptyExercise) diff --git a/src/Ideas/Encoding/ModeXML.hs b/src/Ideas/Encoding/ModeXML.hs index a62008d0..d794ef6b 100644 --- a/src/Ideas/Encoding/ModeXML.hs +++ b/src/Ideas/Encoding/ModeXML.hs @@ -55,7 +55,7 @@ processXML options dr txt = do addVersion :: String -> XML -> XML addVersion s = changeAttributes (<> attribute "version" s) -xmlRequest :: Monad m => Maybe String -> XML -> m Request +xmlRequest :: MonadFail m => Maybe String -> XML -> m Request xmlRequest ms xml = do unless (getName xml == "request") $ fail "expected xml tag request" @@ -84,7 +84,7 @@ defaultSeed _ m = m xmlReply :: Options -> DomainReasoner -> Request -> XML -> IO XML xmlReply opt1 dr request xml = do srv <- case serviceId request of - Just a -> findService dr a + Just a -> findServiceM dr a Nothing -> fail "No service" Some ex <- case exerciseId request of @@ -100,7 +100,7 @@ xmlReply opt1 dr request xml = do -- xml evaluator else resultOk <$> evalService ex options xmlEvaluator srv xml -extractExerciseId :: Monad m => XML -> m Id +extractExerciseId :: MonadFail m => XML -> m Id extractExerciseId = fmap newId . findAttribute "exerciseid" resultOk :: XMLBuilder -> XML diff --git a/src/Ideas/Encoding/NewModeJSON.hs b/src/Ideas/Encoding/NewModeJSON.hs index 79a0e20c..3270f1af 100644 --- a/src/Ideas/Encoding/NewModeJSON.hs +++ b/src/Ideas/Encoding/NewModeJSON.hs @@ -67,7 +67,7 @@ errorResponse dr msg = Object ] -- TODO: Clean-up code -extractExerciseId :: MonadPlus m => JSON -> m Id +extractExerciseId :: (MonadPlus m, MonadFail m) => JSON -> m Id extractExerciseId json = f <$> ( lookupM "exerciseid" json <|> (lookupM "state" json >>= lookupM "exerciseid")) @@ -75,7 +75,7 @@ extractExerciseId json = f <$> ( f (String s) = newId s f _ = error "expecting an exercise id" -jsonRequest :: Monad m => Options -> JSON -> m Request +jsonRequest :: MonadFail m => Options -> JSON -> m Request jsonRequest options json = do let exId = extractExerciseId json srv <- stringOption "service" json newId @@ -102,10 +102,10 @@ defaultSeed options | isJust (cgiBin options) = Nothing | otherwise = Just 2805 -- magic number -stringOption :: Monad m => String -> JSON -> (String -> a) -> m (Maybe a) +stringOption :: MonadFail m => String -> JSON -> (String -> a) -> m (Maybe a) stringOption attr json f = stringOptionM attr json Nothing (return . Just . f) -stringOptionM :: Monad m => String -> JSON -> a -> (String -> m a) -> m a +stringOptionM :: MonadFail m => String -> JSON -> a -> (String -> m a) -> m a stringOptionM attr json a f = case lookupM attr json of Just (String s) -> f s @@ -114,7 +114,7 @@ stringOptionM attr json a f = myHandler :: Options -> DomainReasoner -> Request -> String -> JSON -> IO JSONBuilder myHandler opt1 dr request fun json = do - srv <- findService dr (newId fun) + srv <- findServiceM dr (newId fun) Some ex <- case exerciseId request of Just a -> findExercise dr a Nothing -> return (Some emptyExercise) diff --git a/src/Ideas/Encoding/Request.hs b/src/Ideas/Encoding/Request.hs index 3021e432..d1864333 100644 --- a/src/Ideas/Encoding/Request.hs +++ b/src/Ideas/Encoding/Request.hs @@ -56,7 +56,7 @@ instance Monoid Request where data Schema = V1 | V2 | NoLogging deriving (Show, Eq) -readSchema :: Monad m => String -> m Schema +readSchema :: MonadFail m => String -> m Schema readSchema s0 | s == "v1" = return V1 | s == "v2" = return V2 @@ -112,14 +112,14 @@ useJSONTerm r = useLogging :: Request -> Bool useLogging r = EncHTML `notElem` encoding r && logSchema r /= Just NoLogging -discoverDataFormat :: Monad m => String -> m DataFormat +discoverDataFormat :: MonadFail m => String -> m DataFormat discoverDataFormat xs = case dropWhile isSpace xs of '<':_ -> return XML '{':_ -> return JSON _ -> fail "Unknown data format" -readEncoding :: Monad m => String -> m [Encoding] +readEncoding :: MonadFail m => String -> m [Encoding] readEncoding = mapM (f . map toLower) . splitsWithElem '+' where f "html" = return EncHTML diff --git a/src/Ideas/Service/DomainReasoner.hs b/src/Ideas/Service/DomainReasoner.hs index 717bd3f7..62aa4774 100644 --- a/src/Ideas/Service/DomainReasoner.hs +++ b/src/Ideas/Service/DomainReasoner.hs @@ -13,7 +13,7 @@ module Ideas.Service.DomainReasoner ( DomainReasoner(..), tDomainReasoner, newDomainReasoner , exercisesSorted, servicesSorted - , findExercise, findService + , findExercise, findService, findServiceM , defaultScript ) where @@ -89,7 +89,7 @@ exercisesSorted = sortOn f . exercises servicesSorted :: DomainReasoner -> [Service] servicesSorted = sortOn showId . services -findExercise :: Monad m => DomainReasoner -> Id -> m (Some Exercise) +findExercise :: MonadFail m => DomainReasoner -> Id -> m (Some Exercise) findExercise dr i = case [ a | a@(Some ex) <- exercises dr, getId ex == realName ] of [this] -> return this @@ -97,7 +97,10 @@ findExercise dr i = where realName = fromMaybe i (lookup i (aliases dr)) -findService :: Monad m => DomainReasoner -> Id -> m Service +findServiceM :: MonadFail m => DomainReasoner -> Id -> m Service +findServiceM dr = either fail return . findService dr + +findService :: DomainReasoner -> Id -> Either String Service findService dr a | null (qualifiers a) = -- search for unqualified string findWith (\s -> unqualified s == unqualified a) @@ -106,9 +109,9 @@ findService dr a where findWith p = single $ filter p $ services dr - single [] = fail $ "No service " ++ showId a - single [hd] = return hd - single _ = fail $ "Ambiguous service " ++ showId a + single [] = Left $ "No service " ++ showId a + single [hd] = Right hd + single _ = Left $ "Ambiguous service " ++ showId a defaultScript :: DomainReasoner -> Id -> IO Script defaultScript dr n = diff --git a/src/Ideas/Service/Types.hs b/src/Ideas/Service/Types.hs index 34a75439..8461a251 100644 --- a/src/Ideas/Service/Types.hs +++ b/src/Ideas/Service/Types.hs @@ -68,7 +68,7 @@ deprecate s = s { serviceDeprecated = True } class Equal f where equal :: f a -> f b -> Maybe (a -> b) -equalM :: Monad m => Type a t1 -> Type a t2 -> m (t1 -> t2) +equalM :: MonadFail m => Type a t1 -> Type a t2 -> m (t1 -> t2) equalM t1 t2 = maybe (fail msg) return (equal t1 t2) where msg = "Types not equal: " ++ show t1 ++ " and " ++ show t2 diff --git a/src/Ideas/Text/JSON/Data.hs b/src/Ideas/Text/JSON/Data.hs index 230b2ece..fad25a69 100644 --- a/src/Ideas/Text/JSON/Data.hs +++ b/src/Ideas/Text/JSON/Data.hs @@ -111,7 +111,7 @@ parseJSON = parseSimple json lexer = P.makeTokenParser $ emptyDef { reservedNames = ["true", "false", "null"] } -lookupM :: Monad m => String -> JSON -> m JSON +lookupM :: MonadFail m => String -> JSON -> m JSON lookupM x (Object xs) = maybe (fail $ "field " ++ x ++ " not found") return (lookup x xs) lookupM _ _ = fail "expecting a JSON object" diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index a483b882..3221393d 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -98,7 +98,7 @@ fromXMLDoc doc = fromElement (D.root doc) ------------------------------------------------------------------------------- -- Simple decoding queries -findAttribute :: Monad m => String -> XML -> m String +findAttribute :: MonadFail m => String -> XML -> m String findAttribute s xml = case lookupAttribute (toName s) (getAttributes xml) of Just hd -> return hd @@ -118,7 +118,7 @@ children = rec . getContent findChildren :: String -> XML -> [XML] findChildren s = filter ((==s) . show . getName) . children -findChild :: Monad m => String -> XML -> m XML +findChild :: MonadFail m => String -> XML -> m XML findChild s e = case findChildren s e of [] -> fail $ "Child not found: " ++ show s diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 8a6542d8..1e7b76cf 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -44,6 +44,8 @@ instance Monoid a => Monoid (Decoder env err s a) where instance Monad (Decoder env err s) where return a = Dec (return a) Dec m >>= f = Dec $ m >>= fromDec . f + +instance MonadFail (Decoder env err s) where fail msg = error $ "fail in Decoder: " ++ msg instance MonadState s (Decoder env err s) where diff --git a/src/Ideas/Utils/TestSuite.hs b/src/Ideas/Utils/TestSuite.hs index fb34427f..e08d2e1b 100644 --- a/src/Ideas/Utils/TestSuite.hs +++ b/src/Ideas/Utils/TestSuite.hs @@ -100,8 +100,6 @@ usePropertyWith s args = message "no expected failure" GaveUp {numTests = i} -> warning ("passed only " ++ show i ++ " tests") - InsufficientCoverage {numTests = i} -> - warning ("only performed " ++ show i ++ " tests") assertTrue :: String -> Bool -> TestSuite assertTrue s = assertIO s . return From c5827ea37228253af599229ac980ae596159e53e Mon Sep 17 00:00:00 2001 From: Heeren Date: Thu, 15 Dec 2022 21:57:47 +0100 Subject: [PATCH 45/57] MonadFail compatibility --- Makefile | 2 +- src/Ideas/Common/Constraint.hs | 6 ++++-- src/Ideas/Common/Exercise.hs | 2 +- src/Ideas/Common/Rewriting/AutoTerm.hs | 1 + src/Ideas/Common/Rewriting/RewriteRule.hs | 1 + src/Ideas/Common/Rewriting/Unification.hs | 1 + src/Ideas/Common/Strategy/Abstract.hs | 1 + src/Ideas/Common/Strategy/CyclicTree.hs | 3 +-- src/Ideas/Common/Strategy/Traversal.hs | 1 - src/Ideas/Common/View.hs | 1 + src/Ideas/Encoding/DecoderXML.hs | 1 + src/Ideas/Encoding/Logging.hs | 1 - src/Ideas/Encoding/ModeJSON.hs | 2 +- src/Ideas/Encoding/ModeXML.hs | 1 + src/Ideas/Encoding/NewModeJSON.hs | 2 +- src/Ideas/Encoding/Request.hs | 1 + src/Ideas/Service/DomainReasoner.hs | 1 + src/Ideas/Service/Types.hs | 1 + src/Ideas/Text/JSON/Data.hs | 1 + src/Ideas/Text/XML.hs | 1 + src/Ideas/Utils/Decoding.hs | 8 ++++---- 21 files changed, 25 insertions(+), 14 deletions(-) diff --git a/Makefile b/Makefile index 063d6618..61b2644f 100644 --- a/Makefile +++ b/Makefile @@ -27,7 +27,7 @@ HS-SOURCES = $(wildcard $(SRCDIR)/*/*.hs $(SRCDIR)/*/*/*.hs $(SRCDIR)/*/*/*/*.hs ghci: $(GHCI) -i$(SRCDIR) -odir $(OUTDIR) -hidir $(OUTDIR) $(GHCWARN) -ideas: revision +ideas: # revision $(GHC) -i$(SRCDIR) -odir $(OUTDIR) -hidir $(OUTDIR) $(GHCWARN) $(HS-SOURCES) 2>&1 | tee $(DOCSDIR)/compile.txt #--------------------------------------------------------------------------------------- diff --git a/src/Ideas/Common/Constraint.hs b/src/Ideas/Common/Constraint.hs index a00e8d1d..206d3e0d 100644 --- a/src/Ideas/Common/Constraint.hs +++ b/src/Ideas/Common/Constraint.hs @@ -20,6 +20,7 @@ module Ideas.Common.Constraint ) where import Control.Applicative +import qualified Control.Monad.Fail as Fail import Control.Monad import Data.List import Ideas.Common.Id @@ -100,12 +101,13 @@ instance Alternative Result where Ok a <|> _ = Ok a instance Monad Result where - return = Ok Irrelevant >>= _ = Irrelevant Error msg >>= _ = Error msg Ok a >>= f = f a -instance MonadFail Result where + fail = Fail.fail + +instance Fail.MonadFail Result where fail = Error instance MonadPlus Result where diff --git a/src/Ideas/Common/Exercise.hs b/src/Ideas/Common/Exercise.hs index 4aceae17..590ceac2 100644 --- a/src/Ideas/Common/Exercise.hs +++ b/src/Ideas/Common/Exercise.hs @@ -286,7 +286,7 @@ randomTerm rng ex mdif = randomTerms :: QCGen -> Exercise a -> Maybe Difficulty -> [a] randomTerms rng ex mdif = rec rng where - rec a = maybe id (:) (randomTerm a ex mdif) (rec (snd (next a))) + rec a = maybe id (:) (randomTerm a ex mdif) (rec (snd (split a))) -- | An exercise generator for testing purposes (including corner cases); first generator only. testGenerator :: Exercise a -> Maybe (Gen a) diff --git a/src/Ideas/Common/Rewriting/AutoTerm.hs b/src/Ideas/Common/Rewriting/AutoTerm.hs index b230e00d..66e1e0ea 100644 --- a/src/Ideas/Common/Rewriting/AutoTerm.hs +++ b/src/Ideas/Common/Rewriting/AutoTerm.hs @@ -12,6 +12,7 @@ module Ideas.Common.Rewriting.AutoTerm (toTermG, fromTermG, testTermFor) where +import Control.Monad.Fail (MonadFail) import Control.Monad.State import Data.Data import Ideas.Common.Rewriting.Term diff --git a/src/Ideas/Common/Rewriting/RewriteRule.hs b/src/Ideas/Common/Rewriting/RewriteRule.hs index 54271f01..c2d0043e 100644 --- a/src/Ideas/Common/Rewriting/RewriteRule.hs +++ b/src/Ideas/Common/Rewriting/RewriteRule.hs @@ -25,6 +25,7 @@ module Ideas.Common.Rewriting.RewriteRule , symbolMatcher, symbolBuilder ) where +import Control.Monad.Fail (MonadFail) import Data.Maybe import Ideas.Common.Classes import Ideas.Common.Environment diff --git a/src/Ideas/Common/Rewriting/Unification.hs b/src/Ideas/Common/Rewriting/Unification.hs index f8bdce83..e523c6ec 100644 --- a/src/Ideas/Common/Rewriting/Unification.hs +++ b/src/Ideas/Common/Rewriting/Unification.hs @@ -17,6 +17,7 @@ module Ideas.Common.Rewriting.Unification ) where import Control.Monad +import Control.Monad.Fail (MonadFail) import Data.Maybe import Ideas.Common.Rewriting.AC (pairingsMatchA) import Ideas.Common.Rewriting.Substitution diff --git a/src/Ideas/Common/Strategy/Abstract.hs b/src/Ideas/Common/Strategy/Abstract.hs index 9b4c5499..93c1a49b 100644 --- a/src/Ideas/Common/Strategy/Abstract.hs +++ b/src/Ideas/Common/Strategy/Abstract.hs @@ -32,6 +32,7 @@ module Ideas.Common.Strategy.Abstract , useDecl, decl0, decl1, decl2, declN ) where +import Control.Monad.Fail (MonadFail) import Data.Foldable (toList) import Data.Maybe import Ideas.Common.Classes diff --git a/src/Ideas/Common/Strategy/CyclicTree.hs b/src/Ideas/Common/Strategy/CyclicTree.hs index 916d1d32..5237f5c1 100644 --- a/src/Ideas/Common/Strategy/CyclicTree.hs +++ b/src/Ideas/Common/Strategy/CyclicTree.hs @@ -61,8 +61,7 @@ instance Applicative (CyclicTree d) where p <*> q = fold idAlg {fLeaf = (<$> q)} p instance Monad (CyclicTree d) where - return = leaf - (>>=) = flip replaceLeaf + (>>=) = flip replaceLeaf instance Foldable (CyclicTree d) where foldMap f = fold monoidAlg {fLeaf = f} diff --git a/src/Ideas/Common/Strategy/Traversal.hs b/src/Ideas/Common/Strategy/Traversal.hs index a91b9eb0..dfd27f17 100644 --- a/src/Ideas/Common/Strategy/Traversal.hs +++ b/src/Ideas/Common/Strategy/Traversal.hs @@ -31,7 +31,6 @@ module Ideas.Common.Strategy.Traversal ) where import Data.Monoid hiding ((<>)) -import Data.Semigroup ((<>)) import Ideas.Common.Classes import Ideas.Common.Rule import Ideas.Common.Strategy.Abstract diff --git a/src/Ideas/Common/View.hs b/src/Ideas/Common/View.hs index 10971299..1d3fc482 100644 --- a/src/Ideas/Common/View.hs +++ b/src/Ideas/Common/View.hs @@ -39,6 +39,7 @@ module Ideas.Common.View ) where import Control.Arrow +import Control.Monad.Fail (MonadFail) import Data.Maybe import Ideas.Common.Classes import Ideas.Common.Id diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index 43e0d819..93fa755a 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -19,6 +19,7 @@ module Ideas.Encoding.DecoderXML import Control.Applicative hiding (Const) import Control.Monad.State hiding (State) +import Control.Monad.Fail (MonadFail) import Data.Char import Ideas.Common.Library import Ideas.Common.Traversal.Navigator diff --git a/src/Ideas/Encoding/Logging.hs b/src/Ideas/Encoding/Logging.hs index 6c84ec0f..e88ab8ee 100644 --- a/src/Ideas/Encoding/Logging.hs +++ b/src/Ideas/Encoding/Logging.hs @@ -26,7 +26,6 @@ import Control.Monad import Data.Char import Data.IORef import Data.Maybe -import Data.Semigroup (Semigroup(..)) import Data.Time import Ideas.Encoding.Request (Request, Schema(..)) import Ideas.Service.State diff --git a/src/Ideas/Encoding/ModeJSON.hs b/src/Ideas/Encoding/ModeJSON.hs index 1e898281..afa51775 100644 --- a/src/Ideas/Encoding/ModeJSON.hs +++ b/src/Ideas/Encoding/ModeJSON.hs @@ -15,9 +15,9 @@ module Ideas.Encoding.ModeJSON (processJSON, processJSON') where import Control.Monad +import Control.Monad.Fail (MonadFail) import Data.Char import Data.Maybe -import Data.Semigroup ((<>)) import Ideas.Common.Library hiding (exerciseId) import Ideas.Encoding.DecoderJSON import Ideas.Encoding.EncoderJSON diff --git a/src/Ideas/Encoding/ModeXML.hs b/src/Ideas/Encoding/ModeXML.hs index d794ef6b..e87174d7 100644 --- a/src/Ideas/Encoding/ModeXML.hs +++ b/src/Ideas/Encoding/ModeXML.hs @@ -17,6 +17,7 @@ module Ideas.Encoding.ModeXML (processXML) where import Control.Exception import Control.Monad +import Control.Monad.Fail (MonadFail) import Data.String import Ideas.Common.Library hiding (exerciseId) import Ideas.Encoding.DecoderXML diff --git a/src/Ideas/Encoding/NewModeJSON.hs b/src/Ideas/Encoding/NewModeJSON.hs index 3270f1af..c6367cfa 100644 --- a/src/Ideas/Encoding/NewModeJSON.hs +++ b/src/Ideas/Encoding/NewModeJSON.hs @@ -17,9 +17,9 @@ module Ideas.Encoding.NewModeJSON (processJSON) where import Control.Applicative import Control.Exception import Control.Monad +import Control.Monad.Fail (MonadFail) import System.IO.Error import Data.Maybe -import Data.Semigroup ((<>)) import Ideas.Common.Library hiding (exerciseId) import qualified Ideas.Encoding.ModeJSON as Legacy import Ideas.Encoding.NewDecoderJSON diff --git a/src/Ideas/Encoding/Request.hs b/src/Ideas/Encoding/Request.hs index d1864333..aa097fbc 100644 --- a/src/Ideas/Encoding/Request.hs +++ b/src/Ideas/Encoding/Request.hs @@ -12,6 +12,7 @@ module Ideas.Encoding.Request where +import Control.Monad.Fail (MonadFail) import Control.Applicative import Data.Char import Data.List diff --git a/src/Ideas/Service/DomainReasoner.hs b/src/Ideas/Service/DomainReasoner.hs index 62aa4774..743654cd 100644 --- a/src/Ideas/Service/DomainReasoner.hs +++ b/src/Ideas/Service/DomainReasoner.hs @@ -17,6 +17,7 @@ module Ideas.Service.DomainReasoner , defaultScript ) where +import Control.Monad.Fail (MonadFail) import Data.List import Data.Maybe import Data.Semigroup as Sem diff --git a/src/Ideas/Service/Types.hs b/src/Ideas/Service/Types.hs index 8461a251..b1e05550 100644 --- a/src/Ideas/Service/Types.hs +++ b/src/Ideas/Service/Types.hs @@ -30,6 +30,7 @@ module Ideas.Service.Types ) where import Control.Monad +import Control.Monad.Fail (MonadFail) import Data.Char import Data.List import Data.Maybe diff --git a/src/Ideas/Text/JSON/Data.hs b/src/Ideas/Text/JSON/Data.hs index fad25a69..af5602ce 100644 --- a/src/Ideas/Text/JSON/Data.hs +++ b/src/Ideas/Text/JSON/Data.hs @@ -17,6 +17,7 @@ module Ideas.Text.JSON.Data ) where import Control.Monad +import Control.Monad.Fail (MonadFail) import Data.List (intersperse) import Data.Maybe import Data.String diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index 3221393d..94a2f320 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -32,6 +32,7 @@ module Ideas.Text.XML , fromBuilder ) where +import Control.Monad.Fail (MonadFail) import Control.Monad.State import Data.Char (chr) import Data.Maybe diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 1e7b76cf..61579429 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -26,6 +26,7 @@ import Control.Monad import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State +import qualified Control.Monad.Fail as Fail import Data.List import Data.String @@ -39,13 +40,12 @@ instance Semigroup a => Semigroup (Decoder env err s a) where instance Monoid a => Monoid (Decoder env err s a) where mempty = pure mempty - mappend = liftA2 mappend instance Monad (Decoder env err s) where - return a = Dec (return a) Dec m >>= f = Dec $ m >>= fromDec . f - -instance MonadFail (Decoder env err s) where + fail = Fail.fail + +instance Fail.MonadFail (Decoder env err s) where fail msg = error $ "fail in Decoder: " ++ msg instance MonadState s (Decoder env err s) where From 181a18845d706ce3d3cd014b3229795f0ec50d68 Mon Sep 17 00:00:00 2001 From: Heeren Date: Fri, 6 Jan 2023 16:58:53 +0100 Subject: [PATCH 46/57] Removing dependency on MonadFail and fail --- src/Ideas/Common/Constraint.hs | 56 +++++++------------- src/Ideas/Common/Context.hs | 2 +- src/Ideas/Common/Rewriting/AutoTerm.hs | 29 ++++------ src/Ideas/Common/Rewriting/Confluence.hs | 2 +- src/Ideas/Common/Rewriting/RewriteRule.hs | 11 ++-- src/Ideas/Common/Rewriting/Unification.hs | 19 ++++--- src/Ideas/Common/Strategy/Abstract.hs | 10 ++-- src/Ideas/Common/View.hs | 7 +-- src/Ideas/Encoding/DecoderJSON.hs | 5 +- src/Ideas/Encoding/DecoderXML.hs | 55 ++++++++++--------- src/Ideas/Encoding/Encoder.hs | 2 +- src/Ideas/Encoding/EncoderHTML.hs | 9 ++-- src/Ideas/Encoding/EncoderJSON.hs | 4 +- src/Ideas/Encoding/EncoderXML.hs | 5 +- src/Ideas/Encoding/ModeJSON.hs | 25 +++++---- src/Ideas/Encoding/ModeXML.hs | 28 +++++----- src/Ideas/Encoding/NewEncoderJSON.hs | 4 +- src/Ideas/Encoding/NewModeJSON.hs | 31 +++++------ src/Ideas/Encoding/OpenMathSupport.hs | 2 +- src/Ideas/Encoding/Request.hs | 15 +++--- src/Ideas/Service/DomainReasoner.hs | 13 ++--- src/Ideas/Service/FeedbackScript/Analysis.hs | 4 +- src/Ideas/Service/Types.hs | 5 +- src/Ideas/Text/JSON/Data.hs | 7 ++- src/Ideas/Text/XML.hs | 19 ++++--- src/Ideas/Utils/Decoding.hs | 5 -- 26 files changed, 167 insertions(+), 207 deletions(-) diff --git a/src/Ideas/Common/Constraint.hs b/src/Ideas/Common/Constraint.hs index 206d3e0d..f9bddfc4 100644 --- a/src/Ideas/Common/Constraint.hs +++ b/src/Ideas/Common/Constraint.hs @@ -15,13 +15,10 @@ module Ideas.Common.Constraint ( Constraint, makeConstraint , isRelevant, isSatisfied, isViolated, getResult - , Result(..), relevance + , Result(..), violation, relevance , subConstraints ) where -import Control.Applicative -import qualified Control.Monad.Fail as Fail -import Control.Monad import Data.List import Ideas.Common.Id import Ideas.Common.View @@ -71,52 +68,39 @@ isSatisfied p a = isViolated :: Constraint a -> a -> Maybe String isViolated p a = case getResult p a of - Error s -> Just s - _ -> Nothing + Violation s -> Just s + _ -> Nothing --------------------------------------------------------------------------- -- Result -data Result a = Irrelevant | Error String | Ok a +data Result a = Irrelevant | Violation String | Ok a deriving Show instance Functor Result where - fmap _ Irrelevant = Irrelevant - fmap _ (Error msg) = Error msg - fmap f (Ok a) = Ok (f a) + fmap _ Irrelevant = Irrelevant + fmap _ (Violation msg) = Violation msg + fmap f (Ok a) = Ok (f a) instance Applicative Result where pure = Ok - Irrelevant <*> _ = Irrelevant - Error msg <*> _ = Error msg - Ok _ <*> Irrelevant = Irrelevant - Ok _ <*> Error msg = Error msg - Ok f <*> Ok a = Ok (f a) - -instance Alternative Result where - empty = Error "" - Irrelevant <|> r = r - Error msg <|> Error _ = Error msg -- left-biased - Error _ <|> r = r - Ok a <|> _ = Ok a + Irrelevant <*> _ = Irrelevant + Violation msg <*> _ = Violation msg + Ok _ <*> Irrelevant = Irrelevant + Ok _ <*> Violation msg = Violation msg + Ok f <*> Ok a = Ok (f a) instance Monad Result where - Irrelevant >>= _ = Irrelevant - Error msg >>= _ = Error msg - Ok a >>= f = f a + Irrelevant >>= _ = Irrelevant + Violation msg >>= _ = Violation msg + Ok a >>= f = f a - fail = Fail.fail - -instance Fail.MonadFail Result where - fail = Error - -instance MonadPlus Result where - mzero = empty - mplus = (<|>) +violation :: String -> Result a +violation = Violation -- | Turn errors into irrelevant results relevance :: Result a -> Result a -relevance (Error _) = Irrelevant +relevance (Violation _) = Irrelevant relevance r = r -- to do: @@ -128,9 +112,9 @@ subConstraints f n c = makeConstraint n $ \p -> do case filter isError results of [] | any isOk results -> Ok () | otherwise -> Irrelevant - errs -> Error $ intercalate "," [ showId c ++ "." ++ loc ++ ":" ++ msg | (loc, Error msg) <- errs ] + errs -> violation $ intercalate "," [ showId c ++ "." ++ loc ++ ":" ++ msg | (loc, Violation msg) <- errs ] where - isError (_, Error _) = True + isError (_, Violation _) = True isError _ = False isOk (_, Ok _) = True diff --git a/src/Ideas/Common/Context.hs b/src/Ideas/Common/Context.hs index d7e01d9f..deb2263f 100644 --- a/src/Ideas/Common/Context.hs +++ b/src/Ideas/Common/Context.hs @@ -111,7 +111,7 @@ navLocation (Simple a) = location a navLocation (NoNav _) = mempty currentNavigator :: ContextNavigator a -> Maybe a -currentNavigator (TermNav a) = matchM termView (current a) +currentNavigator (TermNav a) = match termView (current a) currentNavigator (Simple a) = Just (current a) currentNavigator (NoNav a) = Just a diff --git a/src/Ideas/Common/Rewriting/AutoTerm.hs b/src/Ideas/Common/Rewriting/AutoTerm.hs index 66e1e0ea..98210fc8 100644 --- a/src/Ideas/Common/Rewriting/AutoTerm.hs +++ b/src/Ideas/Common/Rewriting/AutoTerm.hs @@ -12,9 +12,9 @@ module Ideas.Common.Rewriting.AutoTerm (toTermG, fromTermG, testTermFor) where -import Control.Monad.Fail (MonadFail) import Control.Monad.State import Data.Data +import Data.List import Ideas.Common.Rewriting.Term toTermG :: Data a => a -> Term @@ -76,34 +76,27 @@ constructors = dataTypeConstrs . dataTypeOf . fromProxy fromProxy :: Proxy a -> a fromProxy = error "fromProxy" -findConstr :: (MonadFail m, Data a) => Proxy a -> Symbol -> m Constr -findConstr p s = - case [ c | c <- constructors p, s == constrSymbol c ] of - [] -> fail "Autoterm.findConstr" - hd:_ -> return hd +findConstr :: Data a => Proxy a -> Symbol -> Maybe Constr +findConstr p s = find (\c -> s == constrSymbol c) (constructors p) - -fromTermG :: (MonadPlus m, MonadFail m, Data a) => Term -> m a +fromTermG :: Data a => Term -> Maybe a fromTermG term = case term of TCon s xs -> fromTermTConG Proxy s xs - TVar [c] -> castM c `mplus` castM [c] - TVar s -> castM s + TVar [c] -> cast c `mplus` cast [c] + TVar s -> cast s TList xs -> fromTermG (foldr cons nil xs) - TNum n -> castM n `mplus` castM (fromInteger n :: Int) - TFloat d -> castM d `mplus` castM (doubleToFloat d) - TMeta _ -> fail "fromTermG: found TMeta" + TNum n -> cast n `mplus` cast (fromInteger n :: Int) + TFloat d -> cast d `mplus` cast (doubleToFloat d) + TMeta _ -> Nothing where cons = binary consSymbol nil = symbol nilSymbol -castM :: (MonadFail m, Typeable a, Typeable b) => a -> m b -castM = maybe (fail "fromTermG") return . cast - doubleToFloat :: Double -> Float doubleToFloat = fromRational . toRational -fromTermTConG :: (MonadPlus m, MonadFail m, Data a) => Proxy a -> Symbol -> [Term] -> m a +fromTermTConG :: Data a => Proxy a -> Symbol -> [Term] -> Maybe a fromTermTConG p s xs = do c <- findConstr p s evalStateT (gunfold op return c) xs @@ -114,7 +107,7 @@ fromTermTConG p s xs = do a <- lift (fromTermG t) return (f a) -pop :: MonadFail m => StateT [a] m a +pop :: StateT [a] Maybe a pop = do ts <- get case ts of diff --git a/src/Ideas/Common/Rewriting/Confluence.hs b/src/Ideas/Common/Rewriting/Confluence.hs index 164cc634..d32f6cc5 100644 --- a/src/Ideas/Common/Rewriting/Confluence.hs +++ b/src/Ideas/Common/Rewriting/Confluence.hs @@ -41,7 +41,7 @@ rewriteTerm :: RewriteRule a -> Term -> [Term] rewriteTerm r t = do let lhs :~> rhs = ruleSpecTerm $ renumberRewriteRule (nextMetaVar t) r - sub <- match lhs t + sub <- maybeToList (match lhs t) return (sub |-> rhs) -- uniplate-like helper-functions diff --git a/src/Ideas/Common/Rewriting/RewriteRule.hs b/src/Ideas/Common/Rewriting/RewriteRule.hs index c2d0043e..53428aa6 100644 --- a/src/Ideas/Common/Rewriting/RewriteRule.hs +++ b/src/Ideas/Common/Rewriting/RewriteRule.hs @@ -25,15 +25,14 @@ module Ideas.Common.Rewriting.RewriteRule , symbolMatcher, symbolBuilder ) where -import Control.Monad.Fail (MonadFail) import Data.Maybe import Ideas.Common.Classes import Ideas.Common.Environment import Ideas.Common.Id import Ideas.Common.Rewriting.Substitution import Ideas.Common.Rewriting.Term -import Ideas.Common.Rewriting.Unification -import Ideas.Common.View hiding (match) +import Ideas.Common.Rewriting.Unification hiding (match) +import Ideas.Common.View import Ideas.Utils.Uniplate (descend) import qualified Data.IntSet as IS import qualified Data.Map as M @@ -182,7 +181,7 @@ applyRewriteRule r a = do (out, xs) <- builder term let env = mconcat (zipWith make xs [1::Int ..]) make t = flip singleBinding t . makeRef . show - b <- fromTermRR r out + b <- maybeToList (fromTermRR r out) return (b, env) ----------------------------------------------------------- @@ -215,5 +214,5 @@ renumberRewriteRule n r = r {ruleSpecTerm = fmap f (ruleSpecTerm r)} toTermRR :: RewriteRule a -> a -> Term toTermRR = build . ruleTermView -fromTermRR :: MonadFail m => RewriteRule a -> Term -> m a -fromTermRR = matchM . ruleTermView \ No newline at end of file +fromTermRR :: RewriteRule a -> Term -> Maybe a +fromTermRR = match . ruleTermView \ No newline at end of file diff --git a/src/Ideas/Common/Rewriting/Unification.hs b/src/Ideas/Common/Rewriting/Unification.hs index e523c6ec..2efef17a 100644 --- a/src/Ideas/Common/Rewriting/Unification.hs +++ b/src/Ideas/Common/Rewriting/Unification.hs @@ -17,7 +17,6 @@ module Ideas.Common.Rewriting.Unification ) where import Control.Monad -import Control.Monad.Fail (MonadFail) import Data.Maybe import Ideas.Common.Rewriting.AC (pairingsMatchA) import Ideas.Common.Rewriting.Substitution @@ -52,30 +51,30 @@ unify term1 term2 = return (s2 @@ s1) rec _ _ = fail "match: no unifier" -match :: (MonadPlus m, MonadFail m) => Term -> Term -> m Substitution +match :: Term -> Term -> Maybe Substitution match term1 term2 = case (term1, term2) of (TMeta i, TMeta j) | i == j -> - return emptySubst + Just emptySubst (TMeta i, _) | not (i `hasMetaVar` term2) -> - return (singletonSubst i term2) + Just (singletonSubst i term2) (_, TMeta _) -> - fail "match: no unifier" + Nothing (TCon s xs, TCon t ys) | s == t -> rec xs ys (TList xs, TList ys) -> rec xs ys _ | term1 == term2 -> - return emptySubst - _ -> fail "match: no unifier" + Just emptySubst + _ -> Nothing where - rec [] [] = return emptySubst + rec [] [] = Just emptySubst rec (x:xs) (y:ys) = do s1 <- match x y s2 <- rec (map (s1 |->) xs) ys guard (composable s1 s2) - return (s1 @@ s2) - rec _ _ = fail "match: no unifier" + Just (s1 @@ s2) + rec _ _ = Nothing ----------------------------------------------------------- -- Matching (or: one-way unification) diff --git a/src/Ideas/Common/Strategy/Abstract.hs b/src/Ideas/Common/Strategy/Abstract.hs index 93c1a49b..2fa1f9b1 100644 --- a/src/Ideas/Common/Strategy/Abstract.hs +++ b/src/Ideas/Common/Strategy/Abstract.hs @@ -32,7 +32,6 @@ module Ideas.Common.Strategy.Abstract , useDecl, decl0, decl1, decl2, declN ) where -import Control.Monad.Fail (MonadFail) import Data.Foldable (toList) import Data.Maybe import Ideas.Common.Classes @@ -164,12 +163,11 @@ replayPaths paths s a = mconcat -- | Construct a prefix for a path and a labeled strategy. The third argument -- is the initial term. -replayStrategy :: (MonadFail m, IsStrategy f) => Path -> f a -> a -> m (a, Prefix a) -replayStrategy path s a = +replayStrategy :: IsStrategy f => Path -> f a -> a -> Maybe (a, Prefix a) +replayStrategy path s a = do let (xs, f) = replayProcess path (getProcess s) - in case applyList xs a of - Just b -> return (b, f b) - Nothing -> fail "Cannot replay strategy" + b <- applyList xs a + return (b, f b) ----------------------------------------------------------- --- Remaining functions diff --git a/src/Ideas/Common/View.hs b/src/Ideas/Common/View.hs index 1d3fc482..8ef53b6c 100644 --- a/src/Ideas/Common/View.hs +++ b/src/Ideas/Common/View.hs @@ -19,7 +19,7 @@ module Ideas.Common.View , Control.Arrow.ArrowZero(..), Control.Arrow.ArrowPlus(..) , (>>>), (<<<) -- * @IsMatch@ type class - , IsMatcher(..), matchM, belongsTo, viewEquivalent, viewEquivalentWith + , IsMatcher(..), belongsTo, viewEquivalent, viewEquivalentWith , Matcher, makeMatcher -- * @IsView@ type class , IsView(..), simplify, simplifyWith, simplifyWithM @@ -39,7 +39,6 @@ module Ideas.Common.View ) where import Control.Arrow -import Control.Monad.Fail (MonadFail) import Data.Maybe import Ideas.Common.Classes import Ideas.Common.Id @@ -57,10 +56,6 @@ class IsMatcher f where match = runKleisli . unM . matcher matcher = makeMatcher . match --- |generalized monadic variant of @match@ -matchM :: (MonadFail m, IsMatcher f) => f a b -> a -> m b -matchM v = maybe (fail "no match") return . match v - belongsTo :: IsMatcher f => a -> f a b -> Bool belongsTo a view = isJust (match view a) diff --git a/src/Ideas/Encoding/DecoderJSON.hs b/src/Ideas/Encoding/DecoderJSON.hs index 89c07635..9e8c3d44 100644 --- a/src/Ideas/Encoding/DecoderJSON.hs +++ b/src/Ideas/Encoding/DecoderJSON.hs @@ -29,9 +29,6 @@ import Ideas.Service.Types hiding (String) import Ideas.Text.JSON import qualified Ideas.Service.Types as Tp ---instance MonadFail (Either String) where --- fail = Left - type JSONDecoder a = GDecoderJSON (Exercise a, Options) jsonTypeDecoder :: TypedDecoder a JSON @@ -149,7 +146,7 @@ decodeExpression = withJSONTerm $ \b -> then do mv <- hasJSONView <$> getExercise case mv of - Just v -> jNext (maybe (Left "cannot decode expression from JSON") Right . matchM v) + Just v -> jNext (maybe (Left "cannot decode expression from JSON") Right . match v) Nothing -> errorStr "JSON encoding not supported by exercise" else do ex <- getExercise diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index 93fa755a..bd3425b7 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -19,7 +19,6 @@ module Ideas.Encoding.DecoderXML import Control.Applicative hiding (Const) import Control.Monad.State hiding (State) -import Control.Monad.Fail (MonadFail) import Data.Char import Ideas.Common.Library import Ideas.Common.Traversal.Navigator @@ -31,6 +30,7 @@ import Ideas.Service.Types import Ideas.Text.MathML import Ideas.Text.OpenMath.Object import Ideas.Text.XML +import Ideas.Utils.Decoding type XMLDecoder a t = DecoderX a String XML t @@ -43,9 +43,9 @@ xmlTypeDecoder tp = | s == "answer" -> decodeChild "answer" (xmlTypeDecoder t) | s == "Difficulty" -> do - g <- equalM tDifficulty tp + g <- either errorStr return (equalM tDifficulty tp) a <- decodeAttribute "difficulty" - maybe (fail "unknown difficulty level") (return . g) (readDifficulty a) + maybe (errorStr "unknown difficulty level") (return . g) (readDifficulty a) | otherwise -> decodeChild s (xmlTypeDecoder t) Iso p t -> from p <$> xmlTypeDecoder t @@ -68,7 +68,7 @@ xmlTypeDecoder tp = Context -> decodeContext Rule -> decodeRule Environment -> decodeArgEnvironment - Term -> get >>= (fromXML' >=> maybe (fail "invalid OpenMath") return . fromOMOBJ) + Term -> get >>= (fromXML' >=> maybe (errorStr "invalid OpenMath") return . fromOMOBJ) Location -> decodeLocation StratCfg -> decodeConfiguration QCGen -> getQCGen @@ -80,15 +80,15 @@ xmlTypeDecoder tp = MathML -> decodeMathML String -> decodeData XML -> get - _ -> fail $ "No support for argument type in XML: " ++ show tp - _ -> fail $ "No support for argument type in XML: " ++ show tp + _ -> errorStr $ "No support for argument type in XML: " ++ show tp + _ -> errorStr $ "No support for argument type in XML: " ++ show tp -- decodeRule :: XMLDecoder a (Rule (Context a)) decodeRule = decodeChild "ruleid" $ do ex <- getExercise xml <- get - maybe (fail "invalid rule") return . getRule ex . newId . getData $ xml + maybe (errorStr "invalid rule") return . getRule ex . newId . getData $ xml -- decodeLocation :: XMLDecoder a Location @@ -107,12 +107,12 @@ decodeState = decodeChild "state" $ do -- decodePaths :: XMLDecoder a [Path] decodePaths = do - prefixText <- gets (maybe "" getData . findChild "prefix") + prefixText <- gets (either (const "") getData . findChild "prefix") if all isSpace prefixText then return [emptyPath] else if prefixText ~= "no prefix" then return [] - else maybe (fail "invalid paths") return (readPaths prefixText) + else maybe (errorStr "invalid paths") return (readPaths prefixText) where a ~= b = g a == g b g = map toLower . filter (not . isSpace) @@ -125,7 +125,7 @@ decodeContext = do let ctx = setEnvironment env (inContext ex expr) locRef = makeRef ("location" :: String) case locRef ? env of - Just s -> maybe (fail "invalid location") return $ do + Just s -> maybe (errorStr "invalid location") return $ do loc <- toLocation <$> readM s navigateTo loc (deleteRef locRef ctx) Nothing -> @@ -137,7 +137,7 @@ decodeExpression = withOpenMath f f True = decodeOMOBJ f False = decodeChild "expr" $ do ex <- getExercise - get >>= either fail return . parser ex . getData + get >>= either errorStr return . parser ex . getData decodeOMOBJ :: XMLDecoder a a decodeOMOBJ = decodeChild "OMOBJ" $ get >>= \xml -> do @@ -145,7 +145,7 @@ decodeOMOBJ = decodeChild "OMOBJ" $ get >>= \xml -> do omobj <- fromXML' xml case fromOpenMath ex omobj of Just a -> return a - Nothing -> fail "Invalid OpenMath object for this exercise" + Nothing -> errorStr "Invalid OpenMath object for this exercise" decodeMathML :: XMLDecoder a MathML decodeMathML = decodeFirstChild "math" $ get >>= fromXML' @@ -157,21 +157,21 @@ decodeEnvironment = where add env item = do unless (getName item == "item") $ - fail $ "expecting item tag, found " ++ show (getName item) - n <- findAttribute "name" item + errorStr $ "expecting item tag, found " ++ show (getName item) + n <- findAttribute' "name" item req <- getRequest case findChild "OMOBJ" item of -- OpenMath object found inside item tag - Just this | useOpenMath req -> + Right this | useOpenMath req -> case xml2omobj this of - Left err -> fail err + Left err -> errorStr err Right omobj -> case fromOMOBJ omobj of Just term -> return $ insertRef (makeRef n) (term :: Term) env - Nothing -> fail "invalid openmath" + Nothing -> errorStr "invalid openmath" -- Simple value in attribute _ -> do - value <- findAttribute "value" item + value <- findAttribute' "value" item return $ insertRef (makeRef n) value env -- @@ -182,8 +182,8 @@ decodeConfiguration = decodeChild "configuration" $ where decodeAction item = do guard (null (children item)) - action <- maybe (fail "invalid action") return $ readM (show (getName item)) - cfgloc <- findAttribute "name" item + action <- maybe (errorStr "invalid action") return $ readM (show (getName item)) + cfgloc <- findAttribute' "name" item return (action `byName` newId cfgloc) decodeArgEnvironment :: XMLDecoder a Environment @@ -192,22 +192,25 @@ decodeArgEnvironment = get >>= decodeBinding :: XMLDecoder a Binding decodeBinding = get >>= \xml -> do - a <- findAttribute "description" xml + a <- findAttribute' "description" xml req <- getRequest case findChild "OMOBJ" xml of -- OpenMath object found inside tag - Just this | useOpenMath req -> + Right this | useOpenMath req -> case xml2omobj this of - Left err -> fail err + Left err -> errorStr err Right omobj -> case fromOMOBJ omobj of Just term -> return (termBinding a term) - Nothing -> fail "invalid openmath" + Nothing -> errorStr "invalid openmath" -- Simple value _ -> return (makeBinding (makeRef a) (getData xml)) where termBinding :: String -> Term -> Binding termBinding = makeBinding . makeRef -fromXML' :: (MonadFail m, InXML a) => XML -> m a -fromXML' = maybe (fail "fromXML'") return . fromXML \ No newline at end of file +fromXML' :: InXML a => XML -> XMLDecoder s a +fromXML' = maybe (errorStr "fromXML'") return . fromXML + +findAttribute' :: String -> XML -> XMLDecoder a String +findAttribute' s = either errorStr return . findAttribute s \ No newline at end of file diff --git a/src/Ideas/Encoding/Encoder.hs b/src/Ideas/Encoding/Encoder.hs index b80a08da..5530a8c9 100644 --- a/src/Ideas/Encoding/Encoder.hs +++ b/src/Ideas/Encoding/Encoder.hs @@ -178,7 +178,7 @@ infixr 5 Nothing -> q tv encodeTyped :: (t -> EncoderX a b) -> Type a t -> TypedEncoder a b -encodeTyped p t1 tv@(_ ::: t2) = ((p, t1) (\_ -> fail ("Types do not match: " ++ show t1 ++ " and " ++ show t2))) tv +encodeTyped p t1 tv@(_ ::: t2) = ((p, t1) (\_ -> errorStr ("Types do not match: " ++ show t1 ++ " and " ++ show t2))) tv ------------------------------------------------------------------- -- Decoder datatype diff --git a/src/Ideas/Encoding/EncoderHTML.hs b/src/Ideas/Encoding/EncoderHTML.hs index 3ba407b9..3ccd8ade 100644 --- a/src/Ideas/Encoding/EncoderHTML.hs +++ b/src/Ideas/Encoding/EncoderHTML.hs @@ -542,11 +542,12 @@ useAllFirsts dr = unsafePerformIO . useAllFirstsIO dr useAllFirstsIO :: DomainReasoner -> State a -> IO (Either String [(StepInfo a, State a)]) useAllFirstsIO dr st = do - srv <- findServiceM dr (newId ("allfirsts" :: String)) + srv <- either fail return $ findService dr (newId ("allfirsts" :: String)) case serviceFunction srv of - f ::: tp -> do - conv <- equalM tp (tState .-> tError (tList (Tag "first" (tPair tStepInfo tState)))) - return (conv f st) + f ::: tp -> + case equalM tp (tState .-> tError (tList (Tag "first" (tPair tStepInfo tState)))) of + Left msg -> fail msg + Right conv -> return (conv f st) encodePrefix :: State a -> Prefix (Context a) -> HTMLBuilder encodePrefix st = diff --git a/src/Ideas/Encoding/EncoderJSON.hs b/src/Ideas/Encoding/EncoderJSON.hs index a13c52ab..669dd239 100644 --- a/src/Ideas/Encoding/EncoderJSON.hs +++ b/src/Ideas/Encoding/EncoderJSON.hs @@ -60,7 +60,7 @@ jsonEncoder tv@(val ::: tp) = Tp.Unit -> return Null Tp.List t -> Array <$> sequence [ jsonEncoder (x ::: t) | x <- val ] Const ctp -> jsonEncodeConst (val ::: ctp) - _ -> fail $ "Cannot encode type: " ++ show tp + _ -> errorStr $ "Cannot encode type: " ++ show tp where tupleList :: TypedValue (TypeRep f) -> [TypedValue (TypeRep f)] tupleList (x ::: Tp.Iso p t) = tupleList (to p x ::: t) @@ -89,7 +89,7 @@ jsonEncodeConst (val ::: tp) = Int -> return (toJSON val) Bool -> return (toJSON val) Tp.String -> return (toJSON val) - _ -> fail $ "Type " ++ show tp ++ " not supported in JSON" + _ -> errorStr $ "Type " ++ show tp ++ " not supported in JSON" -------------------------- diff --git a/src/Ideas/Encoding/EncoderXML.hs b/src/Ideas/Encoding/EncoderXML.hs index 889dd41f..9d059977 100644 --- a/src/Ideas/Encoding/EncoderXML.hs +++ b/src/Ideas/Encoding/EncoderXML.hs @@ -35,6 +35,7 @@ import Ideas.Service.State import Ideas.Service.Types import Ideas.Text.OpenMath.Object import Ideas.Text.XML +import Ideas.Utils.Decoding import Ideas.Utils.Prelude (munless) import qualified Ideas.Service.FeedbackText as FeedbackText import qualified Ideas.Service.ProblemDecomposition as PD @@ -60,7 +61,7 @@ xmlEncoder = Tag "RuleShortInfo" t -> case equal t (Const Rule) of Just f -> ruleShortInfo (f val) - Nothing -> fail "rule short info" + Nothing -> errorStr "rule short info" Tag "RulesInfo" _ -> do ex <- getExercise useOM <- useOpenMath <$> getRequest @@ -82,7 +83,7 @@ xmlEncoder = Right b -> xmlEncoder (b ::: t2) Unit -> mempty Const t -> xmlEncoderConst (val ::: t) - _ -> fail $ show tp + _ -> errorStr $ show tp xmlEncoderConst :: TypedValue (Const a) -> XMLEncoder a xmlEncoderConst tv@(val ::: tp) = diff --git a/src/Ideas/Encoding/ModeJSON.hs b/src/Ideas/Encoding/ModeJSON.hs index afa51775..7c1593a0 100644 --- a/src/Ideas/Encoding/ModeJSON.hs +++ b/src/Ideas/Encoding/ModeJSON.hs @@ -15,7 +15,6 @@ module Ideas.Encoding.ModeJSON (processJSON, processJSON') where import Control.Monad -import Control.Monad.Fail (MonadFail) import Data.Char import Data.Maybe import Ideas.Common.Library hiding (exerciseId) @@ -46,7 +45,7 @@ processJSON' options dr json = do return (req, f out, "application/json") -- TODO: Clean-up code -extractExerciseId :: MonadFail m => JSON -> m Id +extractExerciseId :: JSON -> Maybe Id extractExerciseId json = case json of String s -> return (newId s) @@ -54,7 +53,7 @@ extractExerciseId json = Array [String _, String _, _, a@(Array _)] -> extractExerciseId a Array (String s:tl) | any p s -> extractExerciseId (Array tl) Array (hd:_) -> extractExerciseId hd - _ -> fail "no code" + _ -> Nothing where p c = not (isAlphaNum c || isSpace c || c `elem` ".-_") @@ -66,15 +65,15 @@ addVersion str json = where info = ("version", String str) -jsonRequest :: MonadFail m => Options -> JSON -> m Request +jsonRequest :: Options -> JSON -> IO Request jsonRequest options json = do - let exId = lookupM "params" json >>= extractExerciseId + let exId = (either (const Nothing) Just $ lookupM "params" json) >>= extractExerciseId srv <- stringOption "method" json newId src <- stringOption "source" json id rinf <- stringOption "requestinfo" json id seed <- stringOptionM "randomseed" json (defaultSeed options) (return . readM) enc <- stringOptionM "encoding" json [] readEncoding - sch <- stringOptionM "logging" json Nothing (fmap Just . readSchema) + sch <- stringOptionM "logging" json Nothing (maybe (fail "invalid logging scheme") (return . Just) . readSchema) return mempty { serviceId = srv , exerciseId = exId @@ -93,21 +92,21 @@ defaultSeed options | isJust (cgiBin options) = Nothing | otherwise = Just 2805 -- magic number -stringOption :: MonadFail m => String -> JSON -> (String -> a) -> m (Maybe a) +stringOption :: String -> JSON -> (String -> a) -> IO (Maybe a) stringOption attr json f = stringOptionM attr json Nothing (return . Just . f) -stringOptionM :: MonadFail m => String -> JSON -> a -> (String -> m a) -> m a +stringOptionM :: String -> JSON -> a -> (String -> IO a) -> IO a stringOptionM attr json a f = case lookupM attr json of - Just (String s) -> f s - Just _ -> fail $ "Invalid value for " ++ attr ++ " (expecting string)" - Nothing -> return a + Right (String s) -> f s + Right _ -> fail $ "Invalid value for " ++ attr ++ " (expecting string)" + Left _ -> return a myHandler :: Options -> DomainReasoner -> Request -> RPCHandler myHandler opt1 dr request fun json = do - srv <- findServiceM dr (newId fun) + srv <- either fail return $ findService dr (newId fun) Some ex <- case exerciseId request of - Just a -> findExercise dr a + Just a -> either fail return $ findExercise dr a Nothing -> return (Some emptyExercise) opt2 <- makeOptions dr request let options = opt1 <> opt2 diff --git a/src/Ideas/Encoding/ModeXML.hs b/src/Ideas/Encoding/ModeXML.hs index e87174d7..5f635338 100644 --- a/src/Ideas/Encoding/ModeXML.hs +++ b/src/Ideas/Encoding/ModeXML.hs @@ -17,7 +17,6 @@ module Ideas.Encoding.ModeXML (processXML) where import Control.Exception import Control.Monad -import Control.Monad.Fail (MonadFail) import Data.String import Ideas.Common.Library hiding (exerciseId) import Ideas.Encoding.DecoderXML @@ -56,23 +55,23 @@ processXML options dr txt = do addVersion :: String -> XML -> XML addVersion s = changeAttributes (<> attribute "version" s) -xmlRequest :: MonadFail m => Maybe String -> XML -> m Request +xmlRequest :: Maybe String -> XML -> IO Request xmlRequest ms xml = do unless (getName xml == "request") $ fail "expected xml tag request" - enc <- case findAttribute "encoding" xml of + enc <- case findAttribute' "encoding" xml of Just s -> readEncoding s Nothing -> return [] return mempty - { serviceId = newId <$> findAttribute "service" xml + { serviceId = newId <$> findAttribute' "service" xml , exerciseId = extractExerciseId xml - , source = findAttribute "source" xml + , source = findAttribute' "source" xml , cgiBinary = ms - , requestInfo = findAttribute "requestinfo" xml - , logSchema = findAttribute "logging" xml >>= readSchema - , feedbackScript = findAttribute "script" xml + , requestInfo = findAttribute' "requestinfo" xml + , logSchema = findAttribute' "logging" xml >>= readSchema + , feedbackScript = findAttribute' "script" xml , randomSeed = defaultSeed ms $ - findAttribute "randomseed" xml >>= readM + findAttribute' "randomseed" xml >>= readM , dataformat = Just XML , encoding = enc } @@ -85,11 +84,11 @@ defaultSeed _ m = m xmlReply :: Options -> DomainReasoner -> Request -> XML -> IO XML xmlReply opt1 dr request xml = do srv <- case serviceId request of - Just a -> findServiceM dr a + Just a -> either fail return $ findService dr a Nothing -> fail "No service" Some ex <- case exerciseId request of - Just a -> findExercise dr a + Just a -> either fail return $ findExercise dr a Nothing -> return (Some emptyExercise) opt2 <- makeOptions dr request @@ -101,8 +100,8 @@ xmlReply opt1 dr request xml = do -- xml evaluator else resultOk <$> evalService ex options xmlEvaluator srv xml -extractExerciseId :: MonadFail m => XML -> m Id -extractExerciseId = fmap newId . findAttribute "exerciseid" +extractExerciseId :: XML -> Maybe Id +extractExerciseId = either (const Nothing) (return . newId) . findAttribute "exerciseid" resultOk :: XMLBuilder -> XML resultOk body = makeXML (fromString "reply") $ @@ -116,6 +115,9 @@ resultError options msg = do ("result" .=. "error") <> tag "message" (string msg) +findAttribute' :: String -> XML -> Maybe String +findAttribute' a = either (const Nothing) Just . findAttribute a + ------------------------------------------------------------ xmlEvaluator :: Evaluator a XML XMLBuilder diff --git a/src/Ideas/Encoding/NewEncoderJSON.hs b/src/Ideas/Encoding/NewEncoderJSON.hs index 7bfdcd3d..6cd27cc8 100644 --- a/src/Ideas/Encoding/NewEncoderJSON.hs +++ b/src/Ideas/Encoding/NewEncoderJSON.hs @@ -42,7 +42,7 @@ jsonEncoder tv@(val ::: tp) = | otherwise -> (map toLower s .=) <$> jsonEncoder (val ::: t) Tp.Unit -> pure mempty Const ctp -> jsonEncodeConst (val ::: ctp) - _ -> fail $ "Cannot encode type: " ++ show tp + _ -> errorStr $ "Cannot encode type: " ++ show tp jsonEncodeConst :: TypedValue (Const a) -> EncoderX a JSONBuilder jsonEncodeConst (val ::: tp) = @@ -59,7 +59,7 @@ jsonEncodeConst (val ::: tp) = Tp.String -> pure $ jsonBuilder val Tp.Int -> pure $ jsonBuilder val Tp.Bool -> pure $ jsonBuilder val - _ -> fail $ "Type " ++ show tp ++ " not supported in JSON" + _ -> errorStr $ "Type " ++ show tp ++ " not supported in JSON" encodeRule :: Rule (Context a) -> EncoderX a JSONBuilder encodeRule r = pure $ "rule" .= showId r diff --git a/src/Ideas/Encoding/NewModeJSON.hs b/src/Ideas/Encoding/NewModeJSON.hs index c6367cfa..413619a9 100644 --- a/src/Ideas/Encoding/NewModeJSON.hs +++ b/src/Ideas/Encoding/NewModeJSON.hs @@ -16,9 +16,8 @@ module Ideas.Encoding.NewModeJSON (processJSON) where import Control.Applicative import Control.Exception -import Control.Monad -import Control.Monad.Fail (MonadFail) import System.IO.Error +import Data.Either import Data.Maybe import Ideas.Common.Library hiding (exerciseId) import qualified Ideas.Encoding.ModeJSON as Legacy @@ -34,7 +33,7 @@ import Ideas.Utils.Prelude (timedSeconds) processJSON :: Options -> DomainReasoner -> String -> IO (Request, String, String) processJSON options dr txt = do json <- either fail return (parseJSON txt) - let legacy = isJust $ lookupM "params" json + let legacy = isRight $ lookupM "params" json if legacy then Legacy.processJSON' options dr json else do req <- jsonRequest options json resp <- jsonRPC2 dr (maybe "result" show $ serviceId req) json $ \fun arg -> @@ -67,15 +66,17 @@ errorResponse dr msg = Object ] -- TODO: Clean-up code -extractExerciseId :: (MonadPlus m, MonadFail m) => JSON -> m Id +extractExerciseId :: JSON -> Maybe Id extractExerciseId json = f <$> ( - lookupM "exerciseid" json <|> - (lookupM "state" json >>= lookupM "exerciseid")) + get "exerciseid" json <|> + (get "state" json >>= get "exerciseid")) where f (String s) = newId s f _ = error "expecting an exercise id" -jsonRequest :: MonadFail m => Options -> JSON -> m Request + get s = either (const Nothing) Just . lookupM s + +jsonRequest :: Options -> JSON -> IO Request jsonRequest options json = do let exId = extractExerciseId json srv <- stringOption "service" json newId @@ -83,7 +84,7 @@ jsonRequest options json = do rinf <- stringOption "requestinfo" json id seed <- stringOptionM "randomseed" json (defaultSeed options) (return . readM) enc <- stringOptionM "encoding" json [] readEncoding - sch <- stringOptionM "logging" json Nothing (fmap Just . readSchema) + sch <- stringOptionM "logging" json Nothing (maybe (fail "invalid logging scheme") (return . Just) . readSchema) return mempty { serviceId = srv , exerciseId = exId @@ -102,21 +103,21 @@ defaultSeed options | isJust (cgiBin options) = Nothing | otherwise = Just 2805 -- magic number -stringOption :: MonadFail m => String -> JSON -> (String -> a) -> m (Maybe a) +stringOption :: String -> JSON -> (String -> a) -> IO (Maybe a) stringOption attr json f = stringOptionM attr json Nothing (return . Just . f) -stringOptionM :: MonadFail m => String -> JSON -> a -> (String -> m a) -> m a +stringOptionM :: String -> JSON -> a -> (String -> IO a) -> IO a stringOptionM attr json a f = case lookupM attr json of - Just (String s) -> f s - Just _ -> fail $ "Invalid value for " ++ attr ++ " (expecting string)" - Nothing -> return a + Right (String s) -> f s + Right _ -> fail $ "Invalid value for " ++ attr ++ " (expecting string)" + Left _ -> return a myHandler :: Options -> DomainReasoner -> Request -> String -> JSON -> IO JSONBuilder myHandler opt1 dr request fun json = do - srv <- findServiceM dr (newId fun) + srv <- either fail return $ findService dr (newId fun) Some ex <- case exerciseId request of - Just a -> findExercise dr a + Just a -> either fail return $ findExercise dr a Nothing -> return (Some emptyExercise) opt2 <- makeOptions dr request let options = opt1 <> opt2 diff --git a/src/Ideas/Encoding/OpenMathSupport.hs b/src/Ideas/Encoding/OpenMathSupport.hs index 27d60b67..81e3f226 100644 --- a/src/Ideas/Encoding/OpenMathSupport.hs +++ b/src/Ideas/Encoding/OpenMathSupport.hs @@ -39,7 +39,7 @@ fromOpenMath :: Exercise a -> OMOBJ -> Maybe a fromOpenMath ex omobj = do v <- hasTermView ex a <- fromOMOBJ omobj - matchM v a + match v a toOMOBJ :: IsTerm a => a -> OMOBJ toOMOBJ = rec . toTerm diff --git a/src/Ideas/Encoding/Request.hs b/src/Ideas/Encoding/Request.hs index aa097fbc..16a06247 100644 --- a/src/Ideas/Encoding/Request.hs +++ b/src/Ideas/Encoding/Request.hs @@ -12,7 +12,6 @@ module Ideas.Encoding.Request where -import Control.Monad.Fail (MonadFail) import Control.Applicative import Data.Char import Data.List @@ -57,12 +56,12 @@ instance Monoid Request where data Schema = V1 | V2 | NoLogging deriving (Show, Eq) -readSchema :: MonadFail m => String -> m Schema +readSchema :: String -> Maybe Schema readSchema s0 - | s == "v1" = return V1 - | s == "v2" = return V2 - | s `elem` ["false", "no"] = return NoLogging - | otherwise = fail "Unknown schema" + | s == "v1" = Just V1 + | s == "v2" = Just V2 + | s `elem` ["false", "no"] = Just NoLogging + | otherwise = Nothing where s = map toLower (filter isAlphaNum s0) @@ -113,14 +112,14 @@ useJSONTerm r = useLogging :: Request -> Bool useLogging r = EncHTML `notElem` encoding r && logSchema r /= Just NoLogging -discoverDataFormat :: MonadFail m => String -> m DataFormat +discoverDataFormat :: String -> IO DataFormat discoverDataFormat xs = case dropWhile isSpace xs of '<':_ -> return XML '{':_ -> return JSON _ -> fail "Unknown data format" -readEncoding :: MonadFail m => String -> m [Encoding] +readEncoding :: String -> IO [Encoding] readEncoding = mapM (f . map toLower) . splitsWithElem '+' where f "html" = return EncHTML diff --git a/src/Ideas/Service/DomainReasoner.hs b/src/Ideas/Service/DomainReasoner.hs index 743654cd..25b2db1a 100644 --- a/src/Ideas/Service/DomainReasoner.hs +++ b/src/Ideas/Service/DomainReasoner.hs @@ -13,11 +13,10 @@ module Ideas.Service.DomainReasoner ( DomainReasoner(..), tDomainReasoner, newDomainReasoner , exercisesSorted, servicesSorted - , findExercise, findService, findServiceM + , findExercise, findService , defaultScript ) where -import Control.Monad.Fail (MonadFail) import Data.List import Data.Maybe import Data.Semigroup as Sem @@ -90,17 +89,15 @@ exercisesSorted = sortOn f . exercises servicesSorted :: DomainReasoner -> [Service] servicesSorted = sortOn showId . services -findExercise :: MonadFail m => DomainReasoner -> Id -> m (Some Exercise) +findExercise :: DomainReasoner -> Id -> Either String (Some Exercise) findExercise dr i = case [ a | a@(Some ex) <- exercises dr, getId ex == realName ] of - [this] -> return this - _ -> fail $ "Exercise " ++ show i ++ " not found" + [] -> Left $ "Exercise " ++ show i ++ " not found" + [this] -> Right this + _ -> Left $ "Ambiguous exercise " ++ show i where realName = fromMaybe i (lookup i (aliases dr)) -findServiceM :: MonadFail m => DomainReasoner -> Id -> m Service -findServiceM dr = either fail return . findService dr - findService :: DomainReasoner -> Id -> Either String Service findService dr a | null (qualifiers a) = -- search for unqualified string diff --git a/src/Ideas/Service/FeedbackScript/Analysis.hs b/src/Ideas/Service/FeedbackScript/Analysis.hs index a29fddef..a4d2ee81 100644 --- a/src/Ideas/Service/FeedbackScript/Analysis.hs +++ b/src/Ideas/Service/FeedbackScript/Analysis.hs @@ -30,7 +30,7 @@ import Ideas.Utils.Uniplate makeScriptFor :: IsId a => DomainReasoner -> a -> IO () makeScriptFor dr exId = do - Some ex <- findExercise dr (newId exId) + Some ex <- either fail return $ findExercise dr (newId exId) let (brs, nrs) = partition isBuggy (ruleset ex) print $ makeScript $ Supports [getId ex] : @@ -42,7 +42,7 @@ parseAndAnalyzeScript :: DomainReasoner -> FilePath -> IO () parseAndAnalyzeScript dr file = do putStrLn $ "Parsing " ++ show file script <- parseScript file - let exs = [ maybe unknown Right (findExercise dr a) + let exs = [ either (const unknown) Right (findExercise dr a) | Supports as <- scriptDecls script , a <- as , let unknown = Left (UnknownExercise a) diff --git a/src/Ideas/Service/Types.hs b/src/Ideas/Service/Types.hs index b1e05550..2d76c5f9 100644 --- a/src/Ideas/Service/Types.hs +++ b/src/Ideas/Service/Types.hs @@ -30,7 +30,6 @@ module Ideas.Service.Types ) where import Control.Monad -import Control.Monad.Fail (MonadFail) import Data.Char import Data.List import Data.Maybe @@ -69,8 +68,8 @@ deprecate s = s { serviceDeprecated = True } class Equal f where equal :: f a -> f b -> Maybe (a -> b) -equalM :: MonadFail m => Type a t1 -> Type a t2 -> m (t1 -> t2) -equalM t1 t2 = maybe (fail msg) return (equal t1 t2) +equalM :: Type a t1 -> Type a t2 -> Either String (t1 -> t2) +equalM t1 t2 = maybe (Left msg) Right (equal t1 t2) where msg = "Types not equal: " ++ show t1 ++ " and " ++ show t2 instance Equal f => Equal (TypeRep f) where diff --git a/src/Ideas/Text/JSON/Data.hs b/src/Ideas/Text/JSON/Data.hs index af5602ce..5ca05ecb 100644 --- a/src/Ideas/Text/JSON/Data.hs +++ b/src/Ideas/Text/JSON/Data.hs @@ -17,7 +17,6 @@ module Ideas.Text.JSON.Data ) where import Control.Monad -import Control.Monad.Fail (MonadFail) import Data.List (intersperse) import Data.Maybe import Data.String @@ -112,9 +111,9 @@ parseJSON = parseSimple json lexer = P.makeTokenParser $ emptyDef { reservedNames = ["true", "false", "null"] } -lookupM :: MonadFail m => String -> JSON -> m JSON -lookupM x (Object xs) = maybe (fail $ "field " ++ x ++ " not found") return (lookup x xs) -lookupM _ _ = fail "expecting a JSON object" +lookupM :: String -> JSON -> Either String JSON +lookupM x (Object xs) = maybe (Left $ "field " ++ x ++ " not found") Right (lookup x xs) +lookupM _ _ = Left "expecting a JSON object" -------------------------------------------------------- -- Testing parser/pretty-printer diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index 94a2f320..7e18aba2 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -32,7 +32,6 @@ module Ideas.Text.XML , fromBuilder ) where -import Control.Monad.Fail (MonadFail) import Control.Monad.State import Data.Char (chr) import Data.Maybe @@ -99,11 +98,11 @@ fromXMLDoc doc = fromElement (D.root doc) ------------------------------------------------------------------------------- -- Simple decoding queries -findAttribute :: MonadFail m => String -> XML -> m String +findAttribute :: String -> XML -> Either String String findAttribute s xml = case lookupAttribute (toName s) (getAttributes xml) of - Just hd -> return hd - _ -> fail $ "Invalid attribute: " ++ show s + Just hd -> Right hd + _ -> Left $ "Invalid attribute: " ++ show s children :: HasContent a => a -> [XML] children = rec . getContent @@ -119,12 +118,12 @@ children = rec . getContent findChildren :: String -> XML -> [XML] findChildren s = filter ((==s) . show . getName) . children -findChild :: MonadFail m => String -> XML -> m XML +findChild :: String -> XML -> Either String XML findChild s e = case findChildren s e of - [] -> fail $ "Child not found: " ++ show s - [a] -> return a - _ -> fail $ "Multiple children found: " ++ show s + [] -> Left $ "Child not found: " ++ show s + [a] -> Right a + _ -> Left $ "Multiple children found: " ++ show s getData :: HasContent a => a -> String getData = rec . getContent @@ -260,9 +259,9 @@ _runTests = do testDataP, testAttrP, testDataB, testAttrB :: String -> Bool testDataP s = let xml = mkPD s in getData xml == s - testAttrP s = let xml = mkPA s in findAttribute "a" xml == Just s + testAttrP s = let xml = mkPA s in findAttribute "a" xml == Right s testDataB s = let xml = mkBD s in getData xml == s - testAttrB s = let xml = mkBA s in findAttribute "a" xml == Just s + testAttrB s = let xml = mkBA s in findAttribute "a" xml == Right s testXML :: XML -> Bool testXML xml = diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 61579429..01ff52be 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -26,7 +26,6 @@ import Control.Monad import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State -import qualified Control.Monad.Fail as Fail import Data.List import Data.String @@ -43,10 +42,6 @@ instance Monoid a => Monoid (Decoder env err s a) where instance Monad (Decoder env err s) where Dec m >>= f = Dec $ m >>= fromDec . f - fail = Fail.fail - -instance Fail.MonadFail (Decoder env err s) where - fail msg = error $ "fail in Decoder: " ++ msg instance MonadState s (Decoder env err s) where state f = Dec $ state $ \(loc, s) -> let (a, s') = f s in (a, (loc, s')) From 79453dd2ad3d5fc00d4edf0b4511b4abaff5613a Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Tue, 15 Jul 2025 00:03:51 +0200 Subject: [PATCH 47/57] Compiling with ghc 9.6.7 --- .gitignore | 1 + ideas.cabal | 2 +- src/Ideas/Common/Derivation.hs | 11 ++++++----- src/Ideas/Common/Rewriting/AutoTerm.hs | 3 ++- src/Ideas/Encoding/DecoderXML.hs | 3 ++- src/Ideas/Encoding/EncoderJSON.hs | 3 +-- src/Ideas/Text/XML.hs | 3 ++- src/Ideas/Utils/Decoding.hs | 4 ++-- 8 files changed, 17 insertions(+), 13 deletions(-) diff --git a/.gitignore b/.gitignore index e39c6af8..ae6f6168 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ tutorial/Tutorial.o report.html cabal.project.local dist-newstyle/ +tags diff --git a/ideas.cabal b/ideas.cabal index 829eb029..cf8323e0 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -49,7 +49,7 @@ Library ghc-options: -Wall hs-source-dirs: src Build-Depends: - base < 4.17, + base < 4.19, blaze-builder, bytestring, case-insensitive, diff --git a/src/Ideas/Common/Derivation.hs b/src/Ideas/Common/Derivation.hs index 44edd257..7f409f91 100644 --- a/src/Ideas/Common/Derivation.hs +++ b/src/Ideas/Common/Derivation.hs @@ -162,10 +162,11 @@ updateLastTerm f (D a xs) = ys S.:> (s, b) -> D a (ys S.|> (s, f b)) updateSteps :: (a -> s -> a -> t) -> Derivation s a -> Derivation t a -updateSteps f d = - let ts = [ f a b c | (a, b, c) <- triples d ] - x:xs = terms d - in D x (S.fromList (zip ts xs)) +updateSteps f d = case terms d of + [] -> error "Derivation.hs: the impossible has happened" + x:xs -> D x (S.fromList (zip ts xs)) + where + ts = [ f a b c | (a, b, c) <- triples d ] -- | Apply a monadic function to each term, and to each step derivationM :: Monad m => (s -> m ()) -> (a -> m ()) -> Derivation s a -> m () @@ -177,4 +178,4 @@ splitStep p (D a xs) = S.EmptyL -> Nothing (s, b) S.:< ys -> Just (D a xs1, s, D b ys) where - (xs1, xs2) = S.breakl (p . fst) xs \ No newline at end of file + (xs1, xs2) = S.breakl (p . fst) xs diff --git a/src/Ideas/Common/Rewriting/AutoTerm.hs b/src/Ideas/Common/Rewriting/AutoTerm.hs index 98210fc8..cb83d1a4 100644 --- a/src/Ideas/Common/Rewriting/AutoTerm.hs +++ b/src/Ideas/Common/Rewriting/AutoTerm.hs @@ -12,6 +12,7 @@ module Ideas.Common.Rewriting.AutoTerm (toTermG, fromTermG, testTermFor) where +import Control.Monad (mplus) import Control.Monad.State import Data.Data import Data.List @@ -117,4 +118,4 @@ pop = do -------------- testTermFor :: (Data a, Eq a) => a -> Bool -testTermFor x = fromTermG (toTermG x) == Just x \ No newline at end of file +testTermFor x = fromTermG (toTermG x) == Just x diff --git a/src/Ideas/Encoding/DecoderXML.hs b/src/Ideas/Encoding/DecoderXML.hs index bd3425b7..e335d230 100644 --- a/src/Ideas/Encoding/DecoderXML.hs +++ b/src/Ideas/Encoding/DecoderXML.hs @@ -18,6 +18,7 @@ module Ideas.Encoding.DecoderXML ) where import Control.Applicative hiding (Const) +import Control.Monad ((>=>), foldM, guard, unless) import Control.Monad.State hiding (State) import Data.Char import Ideas.Common.Library @@ -213,4 +214,4 @@ fromXML' :: InXML a => XML -> XMLDecoder s a fromXML' = maybe (errorStr "fromXML'") return . fromXML findAttribute' :: String -> XML -> XMLDecoder a String -findAttribute' s = either errorStr return . findAttribute s \ No newline at end of file +findAttribute' s = either errorStr return . findAttribute s diff --git a/src/Ideas/Encoding/EncoderJSON.hs b/src/Ideas/Encoding/EncoderJSON.hs index 669dd239..f8fecafa 100644 --- a/src/Ideas/Encoding/EncoderJSON.hs +++ b/src/Ideas/Encoding/EncoderJSON.hs @@ -15,7 +15,6 @@ module Ideas.Encoding.EncoderJSON (jsonEncoder) where -import Control.Applicative hiding (Const) import Data.Maybe import Ideas.Common.Library hiding (exerciseId) import Ideas.Encoding.Encoder @@ -242,4 +241,4 @@ exerciseInfo ex = Object [ ("exerciseid", toJSON (showId ex)) , ("description", toJSON (description ex)) , ("status", toJSON (show (status ex))) - ] \ No newline at end of file + ] diff --git a/src/Ideas/Text/XML.hs b/src/Ideas/Text/XML.hs index 7e18aba2..01ffb6c7 100644 --- a/src/Ideas/Text/XML.hs +++ b/src/Ideas/Text/XML.hs @@ -32,6 +32,7 @@ module Ideas.Text.XML , fromBuilder ) where +import Control.Monad (forM_, (>=>)) import Control.Monad.State import Data.Char (chr) import Data.Maybe @@ -273,4 +274,4 @@ _runTests = do mkPD s = either error id $ parseXML $ "" ++ D.escape s ++ "" mkPA s = either error id $ parseXML $ "" mkBD s = makeXML "a" (string s) - mkBA s = makeXML "t" ("a".=. s) \ No newline at end of file + mkBA s = makeXML "t" ("a".=. s) diff --git a/src/Ideas/Utils/Decoding.hs b/src/Ideas/Utils/Decoding.hs index 01ff52be..d09d1f28 100644 --- a/src/Ideas/Utils/Decoding.hs +++ b/src/Ideas/Utils/Decoding.hs @@ -23,7 +23,7 @@ module Ideas.Utils.Decoding import Control.Arrow import Control.Applicative import Control.Monad -import Control.Monad.Except +import Control.Monad.Except hiding (mapError) import Control.Monad.Reader import Control.Monad.State import Data.List @@ -128,4 +128,4 @@ errorStr = throwError . fromString raiseError :: ErrorType -> Maybe a -> Decoder env (Error a) s b raiseError tp a = do loc <- getLoc - throwError $ E [Right (tp, loc, a)] \ No newline at end of file + throwError $ E [Right (tp, loc, a)] From c4c6adeec73c25562a43ebbde35e2aecd028635c Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Tue, 14 Jul 2026 12:14:55 +0200 Subject: [PATCH 48/57] Removing stack yaml file --- stack.yaml | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 stack.yaml diff --git a/stack.yaml b/stack.yaml deleted file mode 100644 index 0ee9f33d..00000000 --- a/stack.yaml +++ /dev/null @@ -1,6 +0,0 @@ -flags: {} -extra-package-dbs: [] -packages: -- '.' -extra-deps: -resolver: lts-6.1 From b4ba1277f7f548cac283061ed2de198843c0cba6 Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Thu, 23 Jul 2026 22:37:52 +0200 Subject: [PATCH 49/57] Converted the tutorial to a cabal project --- .gitignore | 1 + tutorial/Makefile | 33 +++++++++-------- tutorial/Tutorial.lhs | 30 ++++++++++------ tutorial/cabal.project | 6 ++++ tutorial/tutorial.cabal | 79 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 121 insertions(+), 28 deletions(-) create mode 100644 tutorial/cabal.project create mode 100644 tutorial/tutorial.cabal diff --git a/.gitignore b/.gitignore index ae6f6168..f6d159a1 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ report.html cabal.project.local dist-newstyle/ tags +/tutorial/tutorial diff --git a/tutorial/Makefile b/tutorial/Makefile index 1fd754ba..b1f94100 100644 --- a/tutorial/Makefile +++ b/tutorial/Makefile @@ -1,22 +1,21 @@ -default: Tutorial.html Tutorial-solution.html Tutorial.exe +default: tutorial Tutorial.html Tutorial-solution.html -IDEASDIR = .. -SRCDIR = $(IDEASDIR)/src -OUTDIR = $(IDEASDIR)/out -INSTALLDIR = /var/www/tutorial +tutorial: + cabal install --installdir=. --overwrite-policy=always -ghci: - ghci -i$(SRCDIR) -odir$(OUTDIR) -hidir$(OUTDIR) -Wall -fwarn-tabs +%.html: %.lhs + pandoc --from markdown+lhs --to html --template=template.html -o $@ $< -install: - cp Tutorial.html $(INSTALLDIR)/index.html - cp Tutorial-solution.html $(INSTALLDIR)/Tutorial-solution.html - cp Tutorial.css $(INSTALLDIR) - cp ideas.png $(INSTALLDIR) - cp ounl.png $(INSTALLDIR) +ghci: + cabal repl -%.html: %.lhs - pandoc --from markdown+lhs --to html --template=template.html -o $@ $< +docker: + docker build -t ideas-tutorial:latest . + +server: + docker run --rm -it -p 8080:80 ideas-tutorial:latest -Tutorial.exe: - ghc --make -i../src -hidir ../out -odir ../out Tutorial.lhs -o Tutorial.exe +clean: + cabal clean + rm -f Tutorial.html Tutorial-solution.html tutorial + docker rmi ideas-tutorial:latest diff --git a/tutorial/Tutorial.lhs b/tutorial/Tutorial.lhs index e17b0f08..c72d32b2 100644 --- a/tutorial/Tutorial.lhs +++ b/tutorial/Tutorial.lhs @@ -5,10 +5,10 @@ This tutorial shows how to make a simple domain reasoner with the Ideas framewor We start by defining a minimal exercise and show how this can be compiled into an application that can handle feedback requests. Make sure you have installed a Haskell compiler and the cabal package manager -(see [Haskell Platform](http://www.haskell.org/platform/)): we advise -to use one of the following versions of ghc to work with our software: ghc 7.10 -(or Haskell Platform 7.10.3), ghc 8.0.2, ghc 8.2.2, or ghc 8.4.2. -Get the latest version of the [ideas package](http://hackage.haskell.org/package/ideas) +(see [Haskell Platform](http://www.haskell.org/platform/)): this version of the +tutorial works with version 9.6.7, and possibly with later versions. +The tutorial uses Cabal and is tied to a specific version of the [ideas package](http://hackage.haskell.org/package/ideas). + from Hackage and install the library with the following command: ~~~~~~~~ @@ -22,6 +22,7 @@ Ideas package. > module Main where > +> import Control.Applicative > import Ideas.Common.Library > import Ideas.Main.Default @@ -182,11 +183,18 @@ These symbols are used for the `IsTerm` instance: we have to make sure that > toTerm (Con x) = TNum (toInteger x) > > fromTerm (TNum x) = return (Con (fromInteger x)) -> fromTerm term = fromTermWith f term -> where -> f s [x] | s == negateSymbol = return (Negate x) -> f s [x, y] | s == addSymbol = return (Add x y) -> f _ _ = fail "invalid expression" +> fromTerm term +> | isSymbol addSymbol term = do +> (xt, yt) <- isBinary addSymbol term +> x <- fromTerm xt +> y <- fromTerm yt +> return (Add x y) +> | isSymbol negateSymbol term = Negate <$> (isUnary negateSymbol term >>= fromTerm) +> | otherwise = fail "invalid expression" + +> termDecoder = Con . fromInteger <$> tInteger +> <|> Negate <$> termDecoder +> <|> tList2 Add termDecoder termDecoder We can now define an improved strategy that applies `addOrNegate` somewhere: the traversal combinators can only be used on strategies (or rules) that are @@ -296,7 +304,7 @@ two example expressions (of a certain difficulty). > , strategy = evalStrategy > , prettyPrinter = show > , navigation = termNavigator -> , parser = readM +> , parser = maybe (Left "No parse") Right . readM > , equivalence = withoutContext eqExpr > , similarity = withoutContext (==) > , ready = predicate isCon @@ -444,4 +452,4 @@ Suggested exercises * Find the least common multiple of the denominators * Rewrite top-heavy fractions to mixed fractions (e.g. 17/14 becomes 1+3/14) -We have developed [our own solution](Tutorial-solution.html) to these exercises. \ No newline at end of file +We have developed [our own solution](Tutorial-solution.html) to these exercises. diff --git a/tutorial/cabal.project b/tutorial/cabal.project new file mode 100644 index 00000000..29228a54 --- /dev/null +++ b/tutorial/cabal.project @@ -0,0 +1,6 @@ +packages: *.cabal + +source-repository-package + type: git + location: https://github.com/ideas-edu/ideas + tag: 79453dd2ad3d5fc00d4edf0b4511b4abaff5613a diff --git a/tutorial/tutorial.cabal b/tutorial/tutorial.cabal new file mode 100644 index 00000000..bdd3b799 --- /dev/null +++ b/tutorial/tutorial.cabal @@ -0,0 +1,79 @@ +cabal-version: 3.0 +-- The cabal-version field refers to the version of the .cabal specification, +-- and can be different from the cabal-install (the tool) version and the +-- Cabal (the library) version you are using. As such, the Cabal (the library) +-- version used must be equal or greater than the version stated in this field. +-- Starting from the specification version 2.2, the cabal-version field must be +-- the first thing in the cabal file. + +-- Initial package description 'tutorial' generated by +-- 'cabal init'. For further documentation, see: +-- http://haskell.org/cabal/users-guide/ +-- +-- The name of the package. +name: tutorial + +-- The package version. +-- See the Haskell package versioning policy (PVP) for standards +-- guiding when and how versions should be incremented. +-- https://pvp.haskell.org +-- PVP summary: +-+------- breaking API changes +-- | | +----- non-breaking API additions +-- | | | +--- code changes with no API change +version: 0.1.0.0 + +-- A short (one-line) description of the package. +-- synopsis: + +-- A longer description of the package. +-- description: + +-- The license under which the package is released. +license: MIT + +-- The file containing the license text. +license-file: LICENSE + +-- The package author(s). +author: Alex Gerdes + +-- An email address to which users can send suggestions, bug reports, and patches. +maintainer: alexg@chalmers.se + +-- A copyright notice. +-- copyright: +build-type: Simple + +-- Extra doc files to be distributed with the package, such as a CHANGELOG or a README. +extra-doc-files: CHANGELOG.md + +-- Extra source files to be distributed with the package, such as examples, or a tutorial module. +-- extra-source-files: + +common warnings + ghc-options: -Wall + +executable tutorial + -- Import common warning flags. + import: warnings + + -- .hs or .lhs file containing the Main module. + main-is: Tutorial.lhs + + -- Modules included in this executable, other than Main. + -- other-modules: + + -- LANGUAGE extensions used by modules in this package. + -- other-extensions: + + -- Other library packages from which modules are imported. + build-depends: + base >=4.16 && <5, + ideas, + containers ^>= 0.6.7 + + -- Directories containing source files. + hs-source-dirs: . + + -- Base language which the package is written in. + default-language: Haskell2010 From e85d6e939ac2ef330941d073785684b1d1159174 Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Thu, 23 Jul 2026 22:38:24 +0200 Subject: [PATCH 50/57] Extra files for the the cabal project --- tutorial/CHANGELOG.md | 5 +++++ tutorial/LICENSE | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 tutorial/CHANGELOG.md create mode 100644 tutorial/LICENSE diff --git a/tutorial/CHANGELOG.md b/tutorial/CHANGELOG.md new file mode 100644 index 00000000..4984e556 --- /dev/null +++ b/tutorial/CHANGELOG.md @@ -0,0 +1,5 @@ +# Revision history for tutorial + +## 0.1.0.0 -- YYYY-mm-dd + +* First version. Released on an unsuspecting world. diff --git a/tutorial/LICENSE b/tutorial/LICENSE new file mode 100644 index 00000000..73aec800 --- /dev/null +++ b/tutorial/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2026 Alex Gerdes + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. From 7a8d7f726e5a0b309615a844f1d6d4410ce1a1b5 Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Thu, 23 Jul 2026 22:38:54 +0200 Subject: [PATCH 51/57] Added a Dockerfile to build the tutorial --- tutorial/Dockerfile | 25 ++ tutorial/my-httpd.conf | 553 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 578 insertions(+) create mode 100644 tutorial/Dockerfile create mode 100644 tutorial/my-httpd.conf diff --git a/tutorial/Dockerfile b/tutorial/Dockerfile new file mode 100644 index 00000000..d80eaa86 --- /dev/null +++ b/tutorial/Dockerfile @@ -0,0 +1,25 @@ +FROM debian:stable AS build + +# You can set the GHC version via a docker command line argument: --build-arg GHC_VERSION=9.4.6 +ARG GHC_VERSION=9.6.7 +ENV GHC_VERSION=${GHC_VERSION} \ + PATH="/root/.ghcup/bin:$PATH" + +RUN apt update && \ + apt install -y --no-install-recommends \ + build-essential libffi-dev libffi8 libgmp-dev \ + libgmp10 libncurses-dev libncurses6 libtinfo6 pkg-config \ + zlib1g-dev libsqlite3-dev git bash curl ca-certificates + +RUN curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh && \ + ghcup install ghc --set ${GHC_VERSION} + +# Maybe improve with a svn checkout +COPY Tutorial.lhs tutorial.cabal cabal.project CHANGELOG.md LICENSE /workdir/ +WORKDIR /workdir +RUN cabal install -f -logging --installdir=/workdir/ + +FROM httpd + +COPY ./my-httpd.conf /usr/local/apache2/conf/httpd.conf +COPY --from=build "/workdir/tutorial" /usr/local/apache2/cgi-bin/tutorial.cgi diff --git a/tutorial/my-httpd.conf b/tutorial/my-httpd.conf new file mode 100644 index 00000000..763a80da --- /dev/null +++ b/tutorial/my-httpd.conf @@ -0,0 +1,553 @@ +# +# This is the main Apache HTTP server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information. +# In particular, see +# +# for a discussion of each configuration directive. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/access_log" +# with ServerRoot set to "/usr/local/apache2" will be interpreted by the +# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log" +# will be interpreted as '/logs/access_log'. + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# Do not add a slash at the end of the directory path. If you point +# ServerRoot at a non-local disk, be sure to specify a local disk on the +# Mutex directive, if file-based mutexes are used. If you wish to share the +# same ServerRoot for multiple httpd daemons, you will need to change at +# least PidFile. +# +ServerRoot "/usr/local/apache2" + +# +# Mutex: Allows you to set the mutex mechanism and mutex file directory +# for individual mutexes, or change the global defaults +# +# Uncomment and change the directory if mutexes are file-based and the default +# mutex file directory is not on a local disk or is not appropriate for some +# other reason. +# +# Mutex default:logs + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses. +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule mpm_event_module modules/mod_mpm_event.so +# LoadModule mpm_prefork_module modules/mod_mpm_prefork.so +#LoadModule mpm_worker_module modules/mod_mpm_worker.so +LoadModule authn_file_module modules/mod_authn_file.so +#LoadModule authn_dbm_module modules/mod_authn_dbm.so +#LoadModule authn_anon_module modules/mod_authn_anon.so +#LoadModule authn_dbd_module modules/mod_authn_dbd.so +#LoadModule authn_socache_module modules/mod_authn_socache.so +LoadModule authn_core_module modules/mod_authn_core.so +LoadModule authz_host_module modules/mod_authz_host.so +LoadModule authz_groupfile_module modules/mod_authz_groupfile.so +LoadModule authz_user_module modules/mod_authz_user.so +#LoadModule authz_dbm_module modules/mod_authz_dbm.so +#LoadModule authz_owner_module modules/mod_authz_owner.so +#LoadModule authz_dbd_module modules/mod_authz_dbd.so +LoadModule authz_core_module modules/mod_authz_core.so +#LoadModule authnz_ldap_module modules/mod_authnz_ldap.so +#LoadModule authnz_fcgi_module modules/mod_authnz_fcgi.so +LoadModule access_compat_module modules/mod_access_compat.so +LoadModule auth_basic_module modules/mod_auth_basic.so +#LoadModule auth_form_module modules/mod_auth_form.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +#LoadModule allowmethods_module modules/mod_allowmethods.so +#LoadModule isapi_module modules/mod_isapi.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule cache_module modules/mod_cache.so +#LoadModule cache_disk_module modules/mod_cache_disk.so +#LoadModule cache_socache_module modules/mod_cache_socache.so +#LoadModule socache_shmcb_module modules/mod_socache_shmcb.so +#LoadModule socache_dbm_module modules/mod_socache_dbm.so +#LoadModule socache_memcache_module modules/mod_socache_memcache.so +#LoadModule socache_redis_module modules/mod_socache_redis.so +#LoadModule watchdog_module modules/mod_watchdog.so +#LoadModule macro_module modules/mod_macro.so +#LoadModule dbd_module modules/mod_dbd.so +#LoadModule bucketeer_module modules/mod_bucketeer.so +#LoadModule dumpio_module modules/mod_dumpio.so +#LoadModule echo_module modules/mod_echo.so +#LoadModule example_hooks_module modules/mod_example_hooks.so +#LoadModule case_filter_module modules/mod_case_filter.so +#LoadModule case_filter_in_module modules/mod_case_filter_in.so +#LoadModule example_ipc_module modules/mod_example_ipc.so +#LoadModule buffer_module modules/mod_buffer.so +#LoadModule data_module modules/mod_data.so +#LoadModule ratelimit_module modules/mod_ratelimit.so +LoadModule reqtimeout_module modules/mod_reqtimeout.so +#LoadModule ext_filter_module modules/mod_ext_filter.so +#LoadModule request_module modules/mod_request.so +#LoadModule include_module modules/mod_include.so +LoadModule filter_module modules/mod_filter.so +#LoadModule reflector_module modules/mod_reflector.so +#LoadModule substitute_module modules/mod_substitute.so +#LoadModule sed_module modules/mod_sed.so +#LoadModule charset_lite_module modules/mod_charset_lite.so +#LoadModule deflate_module modules/mod_deflate.so +#LoadModule xml2enc_module modules/mod_xml2enc.so +#LoadModule proxy_html_module modules/mod_proxy_html.so +#LoadModule brotli_module modules/mod_brotli.so +LoadModule mime_module modules/mod_mime.so +#LoadModule ldap_module modules/mod_ldap.so +LoadModule log_config_module modules/mod_log_config.so +#LoadModule log_debug_module modules/mod_log_debug.so +#LoadModule log_forensic_module modules/mod_log_forensic.so +#LoadModule logio_module modules/mod_logio.so +#LoadModule lua_module modules/mod_lua.so +LoadModule env_module modules/mod_env.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule expires_module modules/mod_expires.so +LoadModule headers_module modules/mod_headers.so +#LoadModule ident_module modules/mod_ident.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule unique_id_module modules/mod_unique_id.so +LoadModule setenvif_module modules/mod_setenvif.so +LoadModule version_module modules/mod_version.so +#LoadModule remoteip_module modules/mod_remoteip.so +#LoadModule proxy_module modules/mod_proxy.so +#LoadModule proxy_connect_module modules/mod_proxy_connect.so +#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so +#LoadModule proxy_http_module modules/mod_proxy_http.so +#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so +#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so +#LoadModule proxy_uwsgi_module modules/mod_proxy_uwsgi.so +#LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so +#LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so +#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so +#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so +#LoadModule proxy_express_module modules/mod_proxy_express.so +#LoadModule proxy_hcheck_module modules/mod_proxy_hcheck.so +#LoadModule session_module modules/mod_session.so +#LoadModule session_cookie_module modules/mod_session_cookie.so +#LoadModule session_crypto_module modules/mod_session_crypto.so +#LoadModule session_dbd_module modules/mod_session_dbd.so +#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so +#LoadModule slotmem_plain_module modules/mod_slotmem_plain.so +#LoadModule ssl_module modules/mod_ssl.so +#LoadModule optional_hook_export_module modules/mod_optional_hook_export.so +#LoadModule optional_hook_import_module modules/mod_optional_hook_import.so +#LoadModule optional_fn_import_module modules/mod_optional_fn_import.so +#LoadModule optional_fn_export_module modules/mod_optional_fn_export.so +#LoadModule dialup_module modules/mod_dialup.so +#LoadModule http2_module modules/mod_http2.so +#LoadModule proxy_http2_module modules/mod_proxy_http2.so +#LoadModule md_module modules/mod_md.so +#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so +#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so +#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so +#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so +LoadModule unixd_module modules/mod_unixd.so +#LoadModule heartbeat_module modules/mod_heartbeat.so +#LoadModule heartmonitor_module modules/mod_heartmonitor.so +#LoadModule dav_module modules/mod_dav.so +LoadModule status_module modules/mod_status.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule asis_module modules/mod_asis.so +#LoadModule info_module modules/mod_info.so +#LoadModule suexec_module modules/mod_suexec.so + + LoadModule cgid_module modules/mod_cgid.so + + + LoadModule cgi_module modules/mod_cgi.so + +#LoadModule dav_fs_module modules/mod_dav_fs.so +#LoadModule dav_lock_module modules/mod_dav_lock.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule negotiation_module modules/mod_negotiation.so +LoadModule dir_module modules/mod_dir.so +#LoadModule imagemap_module modules/mod_imagemap.so +#LoadModule actions_module modules/mod_actions.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule userdir_module modules/mod_userdir.so +LoadModule alias_module modules/mod_alias.so +#LoadModule rewrite_module modules/mod_rewrite.so + + +# +# If you wish httpd to run as a different user or group, you must run +# httpd as root initially and it will switch. +# +# User/Group: The name (or #number) of the user/group to run httpd as. +# It is usually good practice to create a dedicated user and group for +# running httpd, as with most system services. +# +User www-data +Group www-data + + + +# 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin you@example.com + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# +ServerName localhost:8080 + +# +# Deny access to the entirety of your server's filesystem. You must +# explicitly permit access to web content directories in other +# blocks below. +# + + AllowOverride none + Require all denied + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "/usr/local/apache2/htdocs" + + # + # Possible values for the Options directive are "None", "All", + # or any combination of: + # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews + # + # Note that "MultiViews" must be named *explicitly* --- "Options All" + # doesn't give it to you. + # + # The Options directive is both complicated and important. Please see + # http://httpd.apache.org/docs/2.4/mod/core.html#options + # for more information. + # + Options Indexes FollowSymLinks + + # + # AllowOverride controls what directives may be placed in .htaccess files. + # It can be "All", "None", or any combination of the keywords: + # AllowOverride FileInfo AuthConfig Limit + # + AllowOverride None + + # + # Controls who can get stuff from this server. + # + Require all granted + + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# + + DirectoryIndex index.html + + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Require all denied + + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog /proc/self/fd/2 + +# +# LogLevel: Control the number of messages logged to the error_log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + + + # + # The following directives define some format nicknames for use with + # a CustomLog directive (see below). + # + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined + LogFormat "%h %l %u %t \"%r\" %>s %b" common + + + # You need to enable mod_logio.c to use %I and %O + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + + + # + # The location and format of the access logfile (Common Logfile Format). + # If you do not define any access logfiles within a + # container, they will be logged here. Contrariwise, if you *do* + # define per- access logfiles, transactions will be + # logged therein and *not* in this file. + # + CustomLog /proc/self/fd/1 common + + # + # If you prefer a logfile with access, agent, and referer information + # (Combined Logfile Format) you can use the following directive. + # + #CustomLog "logs/access_log" combined + + + + # + # Redirect: Allows you to tell clients about documents that used to + # exist in your server's namespace, but do not anymore. The client + # will make a new request for the document at its new location. + # Example: + # Redirect permanent /foo http://www.example.com/bar + + # + # Alias: Maps web paths into filesystem paths and is used to + # access content that does not live under the DocumentRoot. + # Example: + # Alias /webpath /full/filesystem/path + # + # If you include a trailing / on /webpath then the server will + # require it to be present in the URL. You will also likely + # need to provide a section to allow access to + # the filesystem path. + + # + # ScriptAlias: This controls which directories contain server scripts. + # ScriptAliases are essentially the same as Aliases, except that + # documents in the target directory are treated as applications and + # run by the server when requested rather than as documents sent to the + # client. The same rules about trailing "/" apply to ScriptAlias + # directives as to Alias. + # + ScriptAlias /cgi-bin/ "/usr/local/apache2/cgi-bin/" + + + + + # + # ScriptSock: On threaded servers, designate the path to the UNIX + # socket used to communicate with the CGI daemon of mod_cgid. + # + #Scriptsock cgisock + + +# +# "/usr/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Require all granted + Options +ExecCGI + AddHandler cgi-script .cgi + + + + # + # Avoid passing HTTP_PROXY environment to CGI's on this or any proxied + # backend servers which have lingering "httpoxy" defects. + # 'Proxy' request header is undefined by the IETF, not listed by IANA + # + RequestHeader unset Proxy early + + + + # + # TypesConfig points to the file containing the list of mappings from + # filename extension to MIME-type. + # + TypesConfig conf/mime.types + + # + # AddType allows you to add to or override the MIME configuration + # file specified in TypesConfig for specific file types. + # + #AddType application/x-gzip .tgz + # + # AddEncoding allows you to have certain browsers uncompress + # information on the fly. Note: Not all browsers support this. + # + #AddEncoding x-compress .Z + #AddEncoding x-gzip .gz .tgz + # + # If the AddEncoding directives above are commented-out, then you + # probably should define those extensions to indicate media types: + # + AddType application/x-compress .Z + AddType application/x-gzip .gz .tgz + + # + # AddHandler allows you to map certain file extensions to "handlers": + # actions unrelated to filetype. These can be either built into the server + # or added with the Action directive (see below) + # + # To use CGI scripts outside of ScriptAliased directories: + # (You will also need to add "ExecCGI" to the "Options" directive.) + # + #AddHandler cgi-script .cgi + + # For type maps (negotiated resources): + #AddHandler type-map var + + # + # Filters allow you to process content before it is sent to the client. + # + # To parse .shtml files for server-side includes (SSI): + # (You will also need to add "Includes" to the "Options" directive.) + # + #AddType text/html .shtml + #AddOutputFilter INCLUDES .shtml + + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# +#MIMEMagicFile conf/magic + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# MaxRanges: Maximum number of Ranges in a request before +# returning the entire resource, or one of the special +# values 'default', 'none' or 'unlimited'. +# Default setting is to accept 200 Ranges. +#MaxRanges unlimited + +# +# EnableMMAP and EnableSendfile: On systems that support it, +# memory-mapping or the sendfile syscall may be used to deliver +# files. This usually improves server performance, but must +# be turned off when serving from networked-mounted +# filesystems or if support for these functions is otherwise +# broken on your system. +# Defaults: EnableMMAP On, EnableSendfile Off +# +#EnableMMAP off +#EnableSendfile on + +# Supplemental configuration +# +# The configuration files in the conf/extra/ directory can be +# included to add extra features or to modify the default configuration of +# the server, or you may simply copy their contents here and change as +# necessary. + +# Server-pool management (MPM specific) +#Include conf/extra/httpd-mpm.conf + +# Multi-language error messages +#Include conf/extra/httpd-multilang-errordoc.conf + +# Fancy directory listings +#Include conf/extra/httpd-autoindex.conf + +# Language settings +#Include conf/extra/httpd-languages.conf + +# User home directories +#Include conf/extra/httpd-userdir.conf + +# Real-time info on requests and configuration +#Include conf/extra/httpd-info.conf + +# Virtual hosts +#Include conf/extra/httpd-vhosts.conf + +# Local access to the Apache HTTP Server Manual +#Include conf/extra/httpd-manual.conf + +# Distributed authoring and versioning (WebDAV) +#Include conf/extra/httpd-dav.conf + +# Various default settings +#Include conf/extra/httpd-default.conf + +# Configure mod_proxy_html to understand HTML4/XHTML1 + +Include conf/extra/proxy-html.conf + + +# Secure (SSL/TLS) connections +#Include conf/extra/httpd-ssl.conf +# +# Note: The following must must be present to support +# starting without SSL on platforms with no /dev/random equivalent +# but a statically compiled-in mod_ssl. +# + +SSLRandomSeed startup builtin +SSLRandomSeed connect builtin + + From ebbaf96d9c08f6bd2ae84a09d34c6766264ef24f Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Thu, 23 Jul 2026 22:39:21 +0200 Subject: [PATCH 52/57] Regenerated the tutorial documentation --- tutorial/Tutorial-solution.html | 484 ++++++++++++--------- tutorial/Tutorial-solution.lhs | 49 ++- tutorial/Tutorial.html | 731 ++++++++++++++++++++------------ 3 files changed, 771 insertions(+), 493 deletions(-) diff --git a/tutorial/Tutorial-solution.html b/tutorial/Tutorial-solution.html index de86ec65..06ab7867 100644 --- a/tutorial/Tutorial-solution.html +++ b/tutorial/Tutorial-solution.html @@ -1,207 +1,279 @@ - - - -Ideas tutorial - - - - - - - -
-
Ideas tutorial (version 1.8)
-
-
-
- -

Solutions to suggested exercises

-

This document shows a possible solution to the suggested exercises in the tutorial.

-
module Main where
-
-import Ideas.Common.Library
-import Ideas.Main.Default
-

We extend the expression datatype with constructors for multiplication and division. The term instance needs to be extended with new symbols for multiplication and division.

-
data Expr  =  Con Int
-           |  Negate Expr 
-           |  Add Expr Expr 
-           |  Mul Expr Expr 
-           |  Div Expr Expr
-   deriving (Eq, Show, Read)
-
-negateSymbol, addSymbol, mulSymbol, divSymbol :: Symbol
-negateSymbol = newSymbol "negate"
-addSymbol    = newSymbol "add"
-mulSymbol    = newSymbol "mul"
-divSymbol    = newSymbol "div"
-
-instance IsTerm Expr where
-   toTerm (Con x)    = TNum (toInteger x)
-   toTerm (Negate x) = unary negateSymbol (toTerm x)
-   toTerm (Add x y)  = binary addSymbol (toTerm x) (toTerm y)
-   toTerm (Mul x y)  = binary mulSymbol (toTerm x) (toTerm y)
-   toTerm (Div x y)  = binary divSymbol (toTerm x) (toTerm y)
-   
-   fromTerm (TNum x) = return (Con (fromInteger x))
-   fromTerm term     = fromTermWith f term
-    where
-      f s [x]    | s == negateSymbol = return (Negate x)
-      f s [x, y] | s == addSymbol    = return (Add x y)
-      f s [x, y] | s == mulSymbol    = return (Mul x y)
-      f s [x, y] | s == divSymbol    = return (Div x y)
-      f _ _ = fail "invalid expression"
-

We add some examples in which we use multiplication and division.

-
-- expression 
-expr1, expr2, expr3, expr4, expr5, expr6, expr7 :: Expr
-expr1 = Add (Con 5) (Negate (Con 2))                                      -- 5+(-2)
-expr2 = Add (Negate (Con 2)) (Add (Con 3) (Con 5))                        -- (-2)+(3+5)
-expr3 = Mul (Con 3) (Add (Mul (Con 2) (Con 5)) (Negate (Con 3)))          -- 3 * (2*5 - 3)
-expr4 = Mul (Div (Con 3) (Con 6)) (Add (Con 1) (Con 1))                   -- 3/6 * 1+1
-expr5 = Add (Con 7) (Negate (Mul (Con 5) (Negate (Div (Con 1) (Con 2))))) -- 7 + -(5*-(1/2))
-expr6 = Div (Div (Con 4) (Con 5)) (Div (Con 9) (Con 8))                   -- (4/5)/(9/8)
-expr7 = Mul (Div (Div (Con 3) (Con 4)) (Con 7)) (Div (Con 1) (Div (Con 2) (Con 3))) 
-                                                                          -- ((3/4)/7)*(1/(2/3)
-

We copy the negateRule and addRule from the tutorial,

-
negateRule :: Rule Expr
-negateRule = describe "Negate number" $ makeRule "eval.negate" f
- where
-   f :: Expr -> Maybe Expr
-   f (Negate (Con x))  =  Just $ Con (-x)
-   f _                 =  Nothing
-
-addRule :: Rule Expr
-addRule = describe "Add two numbers" $ makeRule "eval.add" f
- where
-   f :: Expr -> Maybe Expr
-   f (Add (Con x) (Con y))  =  Just $ Con (x+y)
-   f _                      =  Nothing
-

and add a rule for multiplication.

-
mulRule :: Rule Expr
-mulRule = describe "Multiply two numbers" $ makeRule "eval.mul" f
- where
-   f :: Expr -> Maybe Expr
-   f (Mul (Con x) (Con y))  =  Just $ Con (x*y)
-   f _                      =  Nothing
-

Multiplication distributes over addition. This can be viewed as pushing multiplications as far as possible downwards in the expression.

-
mulAddRule :: Rule Expr
-mulAddRule = describe "Distribute multiplication over addition" $ makeRule "eval.dist" f
- where
-   f :: Expr -> Maybe Expr
-   f (Mul x (Add y z))  =  Just $ Add (Mul x y) (Mul x z)
-   f (Mul (Add x y) z)  =  Just $ Add (Mul x z) (Mul y z)
-   f _                  =  Nothing
-

When we evaluate an expression, we no longer return an integer, but an expression in which divisions still may appear. Alternatively, we can use the type Ratio as the result type, but that might look slightly less attractive when there are no divisions in the argument.

-

We introduce a number of rules that push divisions as far as possible upwards.

-
divNegateRule :: Rule Expr
-divNegateRule = describe "Push negation through division" $ makeRule "eval.divNegate" f
- where
-   f :: Expr -> Maybe Expr
-   f (Negate (Div x y))  =  Just $ Div (Negate x) y
-   f _                   =  Nothing
-
-divAddRule :: Rule Expr
-divAddRule = describe "Push add through divisions" $ makeRule "eval.divAdd" f
- where 
-   f :: Expr -> Maybe Expr
-   f (Add (Div x y) (Div v w))  =  Just $ Div (Add (Mul x w) (Mul v y)) (Mul y w)
-   f (Add (Div x y) v)          =  Just $ Div (Add x (Mul v y)) y
-   f (Add x (Div y v))          =  Just $ Div (Add (Mul x v) y) v
-   f _                          =  Nothing
-
-divMulRule :: Rule Expr
-divMulRule = describe "Push multiply through divisions" $ makeRule "eval.divMul" f
- where 
-   f :: Expr -> Maybe Expr
-   f (Mul (Div x y) (Div v w))  =  Just $ Div (Mul x v) (Mul y w)
-   f (Mul (Div x y) v)          =  Just $ Div (Mul x v) y
-   f (Mul x (Div v w))          =  Just $ Div (Mul x v) w
-   f _                          =  Nothing
-

The divDivRule is the only rule where Div is not pushed to top-level. These are the standard rules for calculating divisions of divisions. Since the Mul and Add rules do not produce divisions of divisions, there is no risk for a loop in the final evaluation strategy.

-
divDivRule :: Rule Expr
-divDivRule = describe "Push divisions through divisions" $ makeRule "eval.divDiv" f
- where 
-   f :: Expr -> Maybe Expr
-   f (Div (Div x y) (Div v w))  =  Just $ Mul (Div x y) (Div w v)
-   f (Div (Div x y) v)          =  Just $ Div x (Mul y v)
-   f (Div x (Div v w))          =  Just $ Mul x (Div w v)
-   f _                          =  Nothing
-

I have two simplification rules for divisions; the topHeavyRule splits a division into an addition and a division. I cannot combine the topHeavyRule with the other division rules (in particular: divAdd) since evaluation will loop otherwise.

-
divSimplificationRule :: Rule Expr
-divSimplificationRule = describe "Simplify a division" $ makeRule "eval.divSimplification" f
- where 
-   f :: Expr -> Maybe Expr
-   f (Div (Con x) (Con y)) 
-     | x == 0    = Just $ Con 0
-     | x == y    = Just $ Con 1
-     | g >  1    = Just $ Div (Con (div x g)) (Con (div y g)) 
-     where g = gcd x y
-   f _ = Nothing
-
-topHeavyRule :: Rule Expr
-topHeavyRule = describe "Simplify a top heavy division" $ makeRule "eval.topHeavy" f
- where 
-   f :: Expr -> Maybe Expr
-   f (Div (Con x) (Con y)) 
-     | x > y  =  Just $ Add (Con (div x y)) (Div (Con (mod x y)) (Con y))
-   f _ = Nothing
-

allEvaluationRules is the strategy that combines all rules that move multiplications downwards, and divisions upwards, and evaluates all expressions with constants. I do not apply divSimplificationRule, but this could be done.

-
allEvaluationRules :: LabeledStrategy Expr
-allEvaluationRules = label "all rules" $
-   negateRule .|. addRule .|. mulRule .|. mulAddRule .|. divNegateRule .|. divAddRule .|. divMulRule .|. divDivRule 
-   -- .|. divSimplificationRule this simplification can also be done during evaluation
-

allSimplificationRules is the strategy that combines all simplification rules.

-
allSimplificationRules :: LabeledStrategy Expr
-allSimplificationRules = label "all rules" $
-   topHeavyRule .|. divSimplificationRule .|. addRule
-

Evaluation consists of applying allEvaluationRules as often as possible, resulting in pushing divisions up as much as possible, followed by applying allSimplificationRules, which simplifies the divisions, replaces top heavy divisions by additions, and does some additional simplications using the addRule in the resulting expression.

-
evalStrategy :: LabeledStrategy (Context Expr)
-evalStrategy = label "eval" $
-   repeatS (somewhere (liftToContext allEvaluationRules)) .*. repeatS (somewhere (liftToContext allSimplificationRules))
-

Evaluation has been extended with a case for Mul, but not for Div.

-
eval :: Expr -> Int
-eval (Add x y)  = eval x + eval y
-eval (Mul x y)  = eval x * eval y
-eval (Negate x) = -eval x
-eval (Con x)    = x 
-

An expression is in normal form if it is a Con, a non-top heavy division, or the addition of a constant and a division.

-
isConOrAddDivOrDiv                          :: Expr -> Bool
-isConOrAddDivOrDiv (Con _)                  =  True
-isConOrAddDivOrDiv (Add (Con _) (Div _ _))  =  True
-isConOrAddDivOrDiv (Div (Con _) (Con _))    =  True
-isConOrAddDivOrDiv _                        =  False
-
-evalExercise :: Exercise Expr
-evalExercise = emptyExercise
-   { exerciseId    = describe "Evaluate an expression (full)" $
-                        newId "eval.full"
-   , status        = Experimental
-   , strategy      = evalStrategy
-   , prettyPrinter = show
-   , navigation    = termNavigator
-   , parser        = readM
-   , equivalence   = withoutContext eqExpr
-   , similarity    = withoutContext (==)
-   , ready         = predicate isConOrAddDivOrDiv
-   , examples      = examplesFor Easy [expr1, expr2, expr3]
-   }
-
-eqExpr :: Expr -> Expr -> Bool
-eqExpr x y = eval x == eval y
-
-dr :: DomainReasoner
-dr = describe "Domain reasoner for tutorial" (newDomainReasoner "eval") 
-   { exercises = [Some evalExercise]
-   , services  = myServices
-   }
-
-myServices :: [Service]
-myServices = metaServiceList dr ++ serviceList
-
-main :: IO ()
-main = defaultMain dr
- -
-
-This tutorial is based on ideas-1.8. Last changed: September 2019 -
+ + + +Ideas tutorial + + + + + + + +
+
Ideas tutorial (version 1.8)
+
+
+
+ +

Solutions to suggested +exercises

+

This document shows a possible solution to the suggested exercises in +the tutorial.

+
module Main where
+
+import Control.Applicative ((<|>))
+import Ideas.Common.Library
+import Ideas.Service.State (State, makeState, stateContext, exercise)
+import Ideas.Main.Default
+

We extend the expression datatype with constructors for +multiplication and division. The term instance needs to be extended with +new symbols for multiplication and division.

+
data Expr  =  Con Int
+           |  Negate Expr 
+           |  Add Expr Expr 
+           |  Mul Expr Expr 
+           |  Div Expr Expr
+   deriving (Eq, Show, Read)
+
+negateSymbol, addSymbol, mulSymbol, divSymbol :: Symbol
+negateSymbol = newSymbol "negate"
+addSymbol    = newSymbol "add"
+mulSymbol    = newSymbol "mul"
+divSymbol    = newSymbol "div"
+
+instance IsTerm Expr where
+   toTerm (Con x)    = TNum (toInteger x)
+   toTerm (Negate x) = unary negateSymbol (toTerm x)
+   toTerm (Add x y)  = binary addSymbol (toTerm x) (toTerm y)
+   toTerm (Mul x y)  = binary mulSymbol (toTerm x) (toTerm y)
+   toTerm (Div x y)  = binary divSymbol (toTerm x) (toTerm y)
+   
+   termDecoder =  Con . fromInteger <$> tInteger
+              <|> tCon1 negateSymbol Negate termDecoder
+              <|> tCon2 addSymbol    Add    termDecoder termDecoder
+              <|> tCon2 mulSymbol    Mul    termDecoder termDecoder
+              <|> tCon2 divSymbol    Div    termDecoder termDecoder
+

We add some examples in which we use multiplication and division.

+
-- expression 
+expr1, expr2, expr3, expr4, expr5, expr6, expr7 :: Expr
+expr1 = Add (Con 5) (Negate (Con 2))                                      -- 5+(-2)
+expr2 = Add (Negate (Con 2)) (Add (Con 3) (Con 5))                        -- (-2)+(3+5)
+expr3 = Mul (Con 3) (Add (Mul (Con 2) (Con 5)) (Negate (Con 3)))          -- 3 * (2*5 - 3)
+expr4 = Mul (Div (Con 3) (Con 6)) (Add (Con 1) (Con 1))                   -- 3/6 * 1+1
+expr5 = Add (Con 7) (Negate (Mul (Con 5) (Negate (Div (Con 1) (Con 2))))) -- 7 + -(5*-(1/2))
+expr6 = Div (Div (Con 4) (Con 5)) (Div (Con 9) (Con 8))                   -- (4/5)/(9/8)
+expr7 = Mul (Div (Div (Con 3) (Con 4)) (Con 7)) (Div (Con 1) (Div (Con 2) (Con 3))) 
+                                                                          -- ((3/4)/7)*(1/(2/3)
+

We copy the negateRule and addRule from the +tutorial,

+
negateRule :: Rule Expr
+negateRule = describe "Negate number" $ makeRule "eval.negate" f
+ where
+   f :: Expr -> Maybe Expr
+   f (Negate (Con x))  =  Just $ Con (-x)
+   f _                 =  Nothing
+
+addRule :: Rule Expr
+addRule = describe "Add two numbers" $ makeRule "eval.add" f
+ where
+   f :: Expr -> Maybe Expr
+   f (Add (Con x) (Con y))  =  Just $ Con (x+y)
+   f _                      =  Nothing
+

and add a rule for multiplication.

+
mulRule :: Rule Expr
+mulRule = describe "Multiply two numbers" $ makeRule "eval.mul" f
+ where
+   f :: Expr -> Maybe Expr
+   f (Mul (Con x) (Con y))  =  Just $ Con (x*y)
+   f _                      =  Nothing
+

Multiplication distributes over addition. This can be viewed as +pushing multiplications as far as possible downwards in the +expression.

+
mulAddRule :: Rule Expr
+mulAddRule = describe "Distribute multiplication over addition" $ makeRule "eval.dist" f
+ where
+   f :: Expr -> Maybe Expr
+   f (Mul x (Add y z))  =  Just $ Add (Mul x y) (Mul x z)
+   f (Mul (Add x y) z)  =  Just $ Add (Mul x z) (Mul y z)
+   f _                  =  Nothing
+

When we evaluate an expression, we no longer return an integer, but +an expression in which divisions still may appear. Alternatively, we can +use the type Ratio as the result type, but that might look +slightly less attractive when there are no divisions in the +argument.

+

We introduce a number of rules that push divisions as far as possible +upwards.

+
divNegateRule :: Rule Expr
+divNegateRule = describe "Push negation through division" $ makeRule "eval.divNegate" f
+ where
+   f :: Expr -> Maybe Expr
+   f (Negate (Div x y))  =  Just $ Div (Negate x) y
+   f _                   =  Nothing
+
+divAddRule :: Rule Expr
+divAddRule = describe "Push add through divisions" $ makeRule "eval.divAdd" f
+ where 
+   f :: Expr -> Maybe Expr
+   f (Add (Div x y) (Div v w))  =  Just $ Div (Add (Mul x w) (Mul v y)) (Mul y w)
+   f (Add (Div x y) v)          =  Just $ Div (Add x (Mul v y)) y
+   f (Add x (Div y v))          =  Just $ Div (Add (Mul x v) y) v
+   f _                          =  Nothing
+
+divMulRule :: Rule Expr
+divMulRule = describe "Push multiply through divisions" $ makeRule "eval.divMul" f
+ where 
+   f :: Expr -> Maybe Expr
+   f (Mul (Div x y) (Div v w))  =  Just $ Div (Mul x v) (Mul y w)
+   f (Mul (Div x y) v)          =  Just $ Div (Mul x v) y
+   f (Mul x (Div v w))          =  Just $ Div (Mul x v) w
+   f _                          =  Nothing
+

The divDivRule is the only rule where Div +is not pushed to top-level. These are the standard rules for calculating +divisions of divisions. Since the Mul and Add +rules do not produce divisions of divisions, there is no risk for a loop +in the final evaluation strategy.

+
divDivRule :: Rule Expr
+divDivRule = describe "Push divisions through divisions" $ makeRule "eval.divDiv" f
+ where 
+   f :: Expr -> Maybe Expr
+   f (Div (Div x y) (Div v w))  =  Just $ Mul (Div x y) (Div w v)
+   f (Div (Div x y) v)          =  Just $ Div x (Mul y v)
+   f (Div x (Div v w))          =  Just $ Mul x (Div w v)
+   f _                          =  Nothing
+

I have two simplification rules for divisions; the topHeavyRule +splits a division into an addition and a division. I cannot combine the +topHeavyRule with the other division rules (in particular: +divAdd) since evaluation will loop otherwise.

+
divSimplificationRule :: Rule Expr
+divSimplificationRule = describe "Simplify a division" $ makeRule "eval.divSimplification" f
+ where 
+   f :: Expr -> Maybe Expr
+   f (Div (Con x) (Con y)) 
+     | x == 0    = Just $ Con 0
+     | x == y    = Just $ Con 1
+     | g >  1    = Just $ Div (Con (div x g)) (Con (div y g)) 
+     where g = gcd x y
+   f _ = Nothing
+
+topHeavyRule :: Rule Expr
+topHeavyRule = describe "Simplify a top heavy division" $ makeRule "eval.topHeavy" f
+ where 
+   f :: Expr -> Maybe Expr
+   f (Div (Con x) (Con y)) 
+     | x > y  =  Just $ Add (Con (div x y)) (Div (Con (mod x y)) (Con y))
+   f _ = Nothing
+

allEvaluationRules is the strategy that combines all +rules that move multiplications downwards, and divisions upwards, and +evaluates all expressions with constants. I do not apply +divSimplificationRule, but this could be done.

+
allEvaluationRules :: LabeledStrategy Expr
+allEvaluationRules = label "all rules" $
+   negateRule .|. addRule .|. mulRule .|. mulAddRule .|. divNegateRule .|. divAddRule .|. divMulRule .|. divDivRule .|. madRule .|. twiceRule
+   -- .|. divSimplificationRule this simplification can also be done during evaluation
+

allSimplificationRules is the strategy that combines all +simplification rules.

+
allSimplificationRules :: LabeledStrategy Expr
+allSimplificationRules = label "all rules" $
+   topHeavyRule .|. divSimplificationRule .|. addRule
+

Evaluation consists of applying allEvaluationRules as +often as possible, resulting in pushing divisions up as much as +possible, followed by applying allSimplificationRules, +which simplifies the divisions, replaces top heavy divisions by +additions, and does some additional simplications using the +addRule in the resulting expression.

+
evalStrategy :: LabeledStrategy (Context Expr)
+evalStrategy = label "eval" $
+   repeatS (somewhere (liftToContext allEvaluationRules)) .*. repeatS (somewhere (liftToContext allSimplificationRules))
+

Evaluation has been extended with a case for Mul, but +not for Div.

+
eval :: Expr -> Int
+eval (Add x y)  = eval x + eval y
+eval (Mul x y)  = eval x * eval y
+eval (Negate x) = -eval x
+eval (Con x)    = x 
+

An expression is in normal form if it is a Con, a +non-top heavy division, or the addition of a constant and a +division.

+
isConOrAddDivOrDiv                          :: Expr -> Bool
+isConOrAddDivOrDiv (Con _)                  =  True
+isConOrAddDivOrDiv (Add (Con _) (Div _ _))  =  True
+isConOrAddDivOrDiv (Div (Con _) (Con _))    =  True
+isConOrAddDivOrDiv _                        =  False
+
+evalExercise :: Exercise Expr
+evalExercise = emptyExercise
+   { exerciseId    = describe "Evaluate an expression (full)" $
+                        newId "eval.full"
+   , status        = Experimental
+   , strategy      = evalStrategy
+   , prettyPrinter = show
+   , navigation    = termNavigator
+   , parser        = maybe (Left "No parse") Right . readM
+   , equivalence   = withoutContext eqExpr
+   , similarity    = withoutContext (==)
+   , ready         = predicate isConOrAddDivOrDiv
+   , examples      = examplesFor Easy [expr1, expr2, expr3]
+   }
+
+eqExpr :: Expr -> Expr -> Bool
+eqExpr x y = eval x == eval y
+
+dr :: DomainReasoner
+dr = describe "Domain reasoner for tutorial" (newDomainReasoner "eval") 
+   { exercises = [Some evalExercise]
+   , services  = myServices
+   }
+
+myServices :: [Service]
+myServices = metaServiceList dr ++ serviceList
+
+main :: IO ()
+main = defaultMain dr
+
readState :: Exercise a -> String -> String -> Maybe (State a)
+readState ex term path = do
+  p          <- readPath path
+  x          <- either (const Nothing) return (parser ex term)
+  (ctx, pfx) <- replayStrategy p (strategy ex) (inContext ex x)
+  return (makeState ex pfx ctx)
+
setTerm :: a -> State a -> State a
+setTerm t s = s { stateContext = inContext ex t }
+ where
+  ex = exercise s 
+
madRule :: Rule Expr
+madRule = makeRule "eval.mad" f
+ where
+  f (Mul (Add a b) (Add c d)) = [ Add (Add (Mul a c) (Mul a d))
+                                      (Add (Mul b c) (Mul b d))
+                                , Add (Add (Mul a d) (Mul a c))
+                                      (Add (Mul b d) (Mul b c))
+                                ]
+  f _ = []
+
twiceRule :: Rule Expr
+twiceRule = makeRule "eval.twice" f
+ where
+  f (Add x y) | x == y = [ Mul (Con 2) x ] --, Mul x (Con 2) ]
+  f _                  = []
+ +
+
+This tutorial is based on ideas-1.8. Last changed: September 2019 +
\ No newline at end of file diff --git a/tutorial/Tutorial-solution.lhs b/tutorial/Tutorial-solution.lhs index 618349de..b145d5aa 100644 --- a/tutorial/Tutorial-solution.lhs +++ b/tutorial/Tutorial-solution.lhs @@ -5,7 +5,9 @@ This document shows a possible solution to the suggested exercises in the tutori > module Main where > +> import Control.Applicative ((<|>)) > import Ideas.Common.Library +> import Ideas.Service.State (State, makeState, stateContext, exercise) > import Ideas.Main.Default We extend the expression datatype with constructors for multiplication and division. @@ -31,14 +33,11 @@ The term instance needs to be extended with new symbols for multiplication and d > toTerm (Mul x y) = binary mulSymbol (toTerm x) (toTerm y) > toTerm (Div x y) = binary divSymbol (toTerm x) (toTerm y) > -> fromTerm (TNum x) = return (Con (fromInteger x)) -> fromTerm term = fromTermWith f term -> where -> f s [x] | s == negateSymbol = return (Negate x) -> f s [x, y] | s == addSymbol = return (Add x y) -> f s [x, y] | s == mulSymbol = return (Mul x y) -> f s [x, y] | s == divSymbol = return (Div x y) -> f _ _ = fail "invalid expression" +> termDecoder = Con . fromInteger <$> tInteger +> <|> tCon1 negateSymbol Negate termDecoder +> <|> tCon2 addSymbol Add termDecoder termDecoder +> <|> tCon2 mulSymbol Mul termDecoder termDecoder +> <|> tCon2 divSymbol Div termDecoder termDecoder We add some examples in which we use multiplication and division. @@ -162,7 +161,7 @@ I do not apply `divSimplificationRule`, but this could be done. > allEvaluationRules :: LabeledStrategy Expr > allEvaluationRules = label "all rules" $ -> negateRule .|. addRule .|. mulRule .|. mulAddRule .|. divNegateRule .|. divAddRule .|. divMulRule .|. divDivRule +> negateRule .|. addRule .|. mulRule .|. mulAddRule .|. divNegateRule .|. divAddRule .|. divMulRule .|. divDivRule .|. madRule .|. twiceRule > -- .|. divSimplificationRule this simplification can also be done during evaluation `allSimplificationRules` is the strategy that combines all simplification rules. @@ -202,7 +201,7 @@ An expression is in normal form if it is a `Con`, a non-top heavy division, or t > , strategy = evalStrategy > , prettyPrinter = show > , navigation = termNavigator -> , parser = readM +> , parser = maybe (Left "No parse") Right . readM > , equivalence = withoutContext eqExpr > , similarity = withoutContext (==) > , ready = predicate isConOrAddDivOrDiv @@ -222,4 +221,32 @@ An expression is in normal form if it is a `Con`, a non-top heavy division, or t > myServices = metaServiceList dr ++ serviceList > > main :: IO () -> main = defaultMain dr \ No newline at end of file +> main = defaultMain dr + +> readState :: Exercise a -> String -> String -> Maybe (State a) +> readState ex term path = do +> p <- readPath path +> x <- either (const Nothing) return (parser ex term) +> (ctx, pfx) <- replayStrategy p (strategy ex) (inContext ex x) +> return (makeState ex pfx ctx) + +> setTerm :: a -> State a -> State a +> setTerm t s = s { stateContext = inContext ex t } +> where +> ex = exercise s + +> madRule :: Rule Expr +> madRule = makeRule "eval.mad" f +> where +> f (Mul (Add a b) (Add c d)) = [ Add (Add (Mul a c) (Mul a d)) +> (Add (Mul b c) (Mul b d)) +> , Add (Add (Mul a d) (Mul a c)) +> (Add (Mul b d) (Mul b c)) +> ] +> f _ = [] + +> twiceRule :: Rule Expr +> twiceRule = makeRule "eval.twice" f +> where +> f (Add x y) | x == y = [ Mul (Con 2) x ] --, Mul x (Con 2) ] +> f _ = [] diff --git a/tutorial/Tutorial.html b/tutorial/Tutorial.html index c95758f6..f527f47f 100644 --- a/tutorial/Tutorial.html +++ b/tutorial/Tutorial.html @@ -1,277 +1,456 @@ - - - -Ideas tutorial - - - - - - - -
-
Ideas tutorial (version 1.8)
-
-
-
- -

Making a domain reasoner

-

This tutorial shows how to make a simple domain reasoner with the Ideas framework. We start by defining a minimal exercise and show how this can be compiled into an application that can handle feedback requests. Make sure you have installed a Haskell compiler and the cabal package manager (see Haskell Platform): we advise to use one of the following versions of ghc to work with our software: ghc 7.10 (or Haskell Platform 7.10.3), ghc 8.0.2, ghc 8.2.2, or ghc 8.4.2. Get the latest version of the ideas package from Hackage and install the library with the following command:

-
cabal install ideas -f -logging
-

The -logging flag installs the package without support for logging: enabling logging would require installing sqlite3 for HDBC. We can now start writing a new Haskell module and import some modules from the Ideas package.

-
module Main where
-
-import Ideas.Common.Library
-import Ideas.Main.Default
-

This will import basic functionality (Ideas.Common.Library) for defining your own exercise. The other import (Ideas.Main.Default) is needed for step 4 of this tutorial.

-

In this tutorial we will develop a domain reasoner for a simple arithmetic expression language. The goal of the domain reasoner is to evaluate expressions. We define a data type for expressions with addition, (unary) negation, and integer constants.

-
data Expr = Add Expr Expr | Negate Expr | Con Int
-   deriving (Eq, Show, Read)
-

For now we will use derived instances for testing equality, showing, and reading expressions. We define two examples of expressions in this data type.

-
-- expression 5+(-2)
-expr1 :: Expr
-expr1 = Add (Con 5) (Negate (Con 2))
-
--- expression (-2)+(3+5)
-expr2 :: Expr
-expr2 = Add (Negate (Con 2)) (Add (Con 3) (Con 5))
-

Step 1: defining an exercise

-

We define rules to calculate the addition of two constants and to negate a constant. The Rule data type is parameterized over the values that are transformed (which is in our case the Expr data type). The function makeRule takes a name for the rule (an identifier) and a function of type a -> Maybe a as its arguments. Constructor Nothing of the Maybe data type is used to indicate that the rule cannot be applied.

-
addRule :: Rule Expr
-addRule = describe "Add two numbers" $ makeRule "eval.add" f
- where
-   f :: Expr -> Maybe Expr
-   f (Add (Con x) (Con y)) = Just $ Con (x+y)
-   f _ = Nothing
-
-negateRule :: Rule Expr
-negateRule = describe "Negate number" $ makeRule "eval.negate" f
- where
-   f :: Expr -> Maybe Expr
-   f (Negate (Con x)) = Just $ Con (-x)
-   f _ = Nothing
-

Have a look at the type of the makeRule function in the documentation, and observe that the function is overloaded in both arguments. The first argument is the rule’s identifier, which has to be part of the IsId type class. The String type is an instance of this class as can be seen from the example. This type class helps in creating identifiers for concepts. The Rule data type carries an identifier of type Id; later we will see that many other concepts also have an identifier (including Strategy and Exercise). Identifiers should have a unique name, and this name can be hierarchical. Hierarchical names can be created with the '.' character in the name, or by using the (#) combinator. Values that carry an identifier can be given a more elaborate description with the describe function.

-

The transformations in the rules above use a function of type a -> Maybe a, but sometimes you want a rule to return multiple results. In these situations you can use a function of type a -> [a]. The MakeTrans type class that is part of makeRule’s type generalizes over the type of a transformation function, and has Maybe and [] as instances.

-

We first test the rules we defined in a Haskell interpreter by applying the rules to some expressions. For this, we use function apply from the Apply type class.

-
Main> apply addRule (Add (Con 5) (Con 3))
-Just (Con 8)
-
-Main> apply negateRule (Negate (Con 5))
-Just (Con (-5))
-
-Main> apply addRule expr1
-Nothing
-
-Main> apply negateRule expr2
-Nothing
-

The last example shows that rules are only applied at top-level, and not automatically to some arbitrary sub-expression. The rules can be combined into a strategy: the strategy combinator .|. denotes choice. We label the strategy with an identifier.

-
addOrNegate :: LabeledStrategy Expr
-addOrNegate = label "add-or-negate" $
-   addRule .|. negateRule
-

Also strategies can be applied to a term.

-
Main> apply addOrNegate (Add (Con 5) (Con 3))
-Just (Con 8)
-
-Main> apply addOrNegate expr1
-Nothing
-

We can now make a minimal exercise that uses the addOrNegate strategy for solving: why we need to lift the strategy to a Context is explained in step 2 of this tutorial. Exercises should have a unique identifier for identification. We use show for pretty-printing expressions. See the documentation of the Exercise data type for the other components of an exercise: emptyExercise provides sensible defaults so we do not have to worry about these fields yet.

-
minimalExercise :: Exercise Expr
-minimalExercise = emptyExercise
-   { exerciseId    = describe "Evaluate an expression (minimal)" $
-                        newId "eval.minimal"
-   , strategy      = liftToContext addOrNegate
-   , prettyPrinter = show
-   }
-

Again, we can apply an exercise to a given expression:

-
Main> apply minimalExercise (Add (Con 5) (Con 3))
-Just (Con 8)
-

For an Exercise, however, function printDerivation is more interesting because it shows a worked-out example and not just the final answer.

-
Main> printDerivation minimalExercise (Add (Con 5) (Con 3))
-Add (Con 5) (Con 3)
-   => eval.add
-Con 8
-

Step 2: adding traversals

-

For arithmetic expressions we want to apply the rules somewhere, i.e., possibly also to the sub-expressions. We want to use traversal functions such as somewhere in our strategy definitions, but this is only possible if we know the structure of the terms we want to traverse. We use a zipper data structure for keeping a point of focus. Instead of defining a zipper on the Expr data type, we define a translation to the Term data type in the Ideas library and use a zipper on Terms. Besides the zipper, some more untyped, generic functions are offered for the Term data type.

-

Two symbols are defined for the two constructors of Expr.

-
addSymbol, negateSymbol :: Symbol
-addSymbol    = newSymbol "add"
-negateSymbol = newSymbol "negate"
-

These symbols are used for the IsTerm instance: we have to make sure that fromTerm after toTerm is the identity function.

-
instance IsTerm Expr where
-   toTerm (Add x y)  = binary addSymbol (toTerm x) (toTerm y)
-   toTerm (Negate x) = unary negateSymbol (toTerm x)
-   toTerm (Con x)    = TNum (toInteger x)
-   
-   fromTerm (TNum x) = return (Con (fromInteger x))
-   fromTerm term     = fromTermWith f term
-    where
-      f s [x]    | s == negateSymbol = return (Negate x)
-      f s [x, y] | s == addSymbol    = return (Add x y)
-      f _ _ = fail "invalid expression"
-

We can now define an improved strategy that applies addOrNegate somewhere: the traversal combinators can only be used on strategies (or rules) that are lifted to a Context (or some other data type with a zipper). Therefore we have to lift the addOrNegate strategy to a Context before using somewhere. We repeat the strategy until it can no longer be applied. Observe that the evalStrategy works on Context Exprs.

-
evalStrategy :: LabeledStrategy (Context Expr)
-evalStrategy = label "eval" $
-   repeatS (somewhere (liftToContext addOrNegate))
-

Testing this strategy is more involved because we first have to put an Expr into a Context: for this context we use the termNavigator.

-
Main> apply evalStrategy $ newContext $ termNavigator expr1
-Just Con 3 @ []
-

In the output, @ [] prints the current focus of the zipper, which is here the top-level node of the expression. For expr2, the strategy can start evaluating sub-expression Negate (Con 2) or sub-expression Add (Con 3) (Con 5). Therefore, evaluating this expression gives two solution paths (with the same result). This can be inspected by using applyAll, which returns all results of application in a list.

-
Main> applyAll evalStrategy $ newContext $ termNavigator expr2
-[Con 6 @ [],Con 6 @ []]
-

We define an extended exercise that is based on evalStrategy. In the exercise definition, we have to declare that navigation is based on the termNavigator.

-
basicExercise :: Exercise Expr
-basicExercise = emptyExercise
-   { exerciseId    = describe "Evaluate an expression (basic)" $
-                        newId "eval.basic"
-   , strategy      = evalStrategy
-   , navigation    = termNavigator
-   , prettyPrinter = show
-   }
-

We can now print worked-out solutions for expr1 and expr2. Note that printDerivations prints all solutions (and printDerivation only shows one).

-
Main> printDerivations basicExercise expr1
-Derivation #1
-Add (Con 5) (Negate (Con 2))
-   => eval.negate
-Add (Con 5) (Con (-2))
-   => eval.add
-Con 3
-
-Main> printDerivations basicExercise expr2
-Derivation #1
-Add (Negate (Con 2)) (Add (Con 3) (Con 5))
-   => eval.add
-Add (Negate (Con 2)) (Con 8)
-   => eval.negate
-Add (Con (-2)) (Con 8)
-   => eval.add
-Con 6
-
-Derivation #2
-Add (Negate (Con 2)) (Add (Con 3) (Con 5))
-   => eval.negate
-Add (Con (-2)) (Add (Con 3) (Con 5))
-   => eval.add
-Add (Con (-2)) (Con 8)
-   => eval.add
-Con 6
-

Step 3: equivalence, similarity and ready

-

For diagnosing a student step, we have to define which expressions are semantically equivalent (have the same value after evaluation), and which expressions are similar (syntactically equal, or slightly more flexible, for example taking commutativity of Add into account). When left undefined in an exercise, all expressions are equivalent and similar, which is not very helpful. For the Expr data type, we specify that two values are equivalent when they evaluate to the same Int value.

-
eqExpr :: Expr -> Expr -> Bool
-eqExpr x y = eval x == eval y
-
-eval :: Expr -> Int
-eval (Add x y)  = eval x + eval y
-eval (Negate x) = -eval x
-eval (Con x)    = x 
-

We also want to define the goal of an exercise: we are ready rewriting an expression when we have reached a constant value.

-
isCon :: Expr -> Bool
-isCon (Con _) = True
-isCon _       = False
-

We give an extended definition for the exercise with equivalence and ready. We also specify its status, the parser for expressions, and two example expressions (of a certain difficulty).

-
evalExercise :: Exercise Expr
-evalExercise = emptyExercise
-   { exerciseId    = describe "Evaluate an expression (full)" $
-                        newId "eval.full"
-   , status        = Experimental
-   , strategy      = evalStrategy
-   , prettyPrinter = show
-   , navigation    = termNavigator
-   , parser        = readM
-   , equivalence   = withoutContext eqExpr
-   , similarity    = withoutContext (==)
-   , ready         = predicate isCon
-   , examples      = examplesFor Easy [expr1, expr2]
-   }
-

The readM function is defined in the Ideas library and provides a simple parser for values (here: a parser for Exprs) based on an instance for the Read type class. We now have a somewhat simple, but fully functional exercise for evaluating expressions.

-

Step 4: making a CGI-webservice

-

An exercise can be used by external tools by turning it into a domain reasoner: such a reasoner supports some exercises, and provides a number of (standard) feedback services. We use the three exercises we have defined so far, together with the standard set of services.

-
dr :: DomainReasoner
-dr = describe "Domain reasoner for tutorial" (newDomainReasoner "eval") 
-   { exercises = [Some minimalExercise, Some basicExercise, Some evalExercise]
-   , services  = myServices
-   }
-
-myServices :: [Service]
-myServices = metaServiceList dr ++ serviceList
-

A default main function is provided by the Ideas framework.

-
main :: IO ()
-main = defaultMain dr
-

Compile the module to get an executable. In this tutorial we assume that the code is placed in a file called Tutorial.hs, and the result of compilation is an executable Tutorial.exe (on Windows). The software, however, is portable and can also be compiled for other platforms (including Mac OS and Linux).

-
$ ghc --make Tutorial.hs
-

Running the executable with the --help flag gives the options.

-
$ Tutorial.exe --help
-IDEAS: Intelligent Domain-specific Exercise Assistants
-Copyright 2018, Open Universiteit Nederland
-version 1.8, revision 26fe80.., logging disabled
-
-Usage: ideas [OPTION]     (by default, CGI protocol)
-
-Options:
-           --version              show version number
-  -?       --help                 show options
-           --print-log            print log information (for debugging)
-  -f FILE  --file=FILE            use input FILE as request
-           --test[=DIR]           run tests on directory (default: 'test')
-           --make-script=ID       generate feedback script for exercise
-           --analyze-script=FILE  analyze feedback script and report errors
-

The application handles requests: one way is to place the request in a file and to pass the file name to the application. In the example requests we use XML, but also other encodings are supported. If we want to know the list of supported exercises, we place the following request in a file exerciselist.xml

-
<request service="exerciselist" source="tutorial"/>
-

It is a good custom to always include the source of the request to let the domain reasoner know where the request came from. The result of this request is:

-
$ Tutorial.exe --file=exerciselist.xml                                          
-<reply result="ok" version="1.8 (26fe80..)">
-  <list>
-    <elem exerciseid="eval.basic" description="Evaluate an expression (basic)" status="Experimental"/>
-    <elem exerciseid="eval.full" description="Evaluate an expression (full)" status="Experimental"/>
-    <elem exerciseid="eval.minimal" description="Evaluate an expression (minimal)" status="Experimental"/>
-  </list>
-</reply>                                         
-

Or we request a worked-out solution for Add (Con 5) (Negate (Con 2)).

-
<request exerciseid="eval.full" service="derivation" encoding="string" source="tutorial">
-    <state>                
-        <expr>Add (Con 5) (Negate (Con 2))</expr>
-    </state>
-</request>
-

In this request we have to specify that the encoding of expressions is a plain string and that we want to use the parser/pretty-printer defined for the exercise. The default encoding follows the OpenMath standard for representing mathematical objects. The result of this request is:

-
$ Tutorial.exe --file=solution.xml
-<reply result="ok" version="1.8 (26fe80..)">
-  <list>
-    <elem ruleid="eval.negate">
-      <expr>
-        Add (Con 5) (Con (-2))
-      </expr>
-      <context>
-        <item name="location" value="[1]"/>
-      </context>
-    </elem>
-    <elem ruleid="eval.add">
-      <expr>
-        Con 3
-      </expr>
-    </elem>
-  </list>
-</reply>
-

The executable Tutorial.exe is also a cgi-binary that can be deployed on a web-server. Because there is support for generating HTML as output, it is possible to interactively explore the domain reasoner with a browser and a local server.

-
    -
  • Install a webserver, such as WampServer for Windows.
  • -
  • Make sure you enable the execution of CGI scripts (in httpd.conf)
  • -
  • Rename the executable to Tutorial.cgi and place it in the directory for cgi scripts
  • -
  • Start a browser and type in the URL http://localhost/Tutorial.cgi
  • -
-

You can now start exploring the supported exercises and feedback services. For instance, go to the exercise eval.full and click on derivations in the yellow box to see the worked-out solutions for two examples.

-

Suggested exercises

-
    -
  • Add multiplication to the expression language (and extend the evaluation strategy)
  • -
  • Add distribution rules to the strategy
  • -
  • Add support for calculating with fractions (e.g. 5/7 + 1/2) -
      -
    • Find the least common multiple of the denominators
    • -
    • Rewrite top-heavy fractions to mixed fractions (e.g. 17/14 becomes 1+3/14)
    • -
  • -
-

We have developed our own solution to these exercises.

- -
-
-This tutorial is based on ideas-1.8. Last changed: September 2019 -
+ + + +Ideas tutorial + + + + + + + +
+
Ideas tutorial (version 1.8)
+
+
+
+ +

Making a domain reasoner

+

This tutorial shows how to make a simple domain reasoner with the +Ideas framework. We start by defining a minimal exercise and show how +this can be compiled into an application that can handle feedback +requests. Make sure you have installed a Haskell compiler and the cabal +package manager (see Haskell +Platform): this version of the tutorial works with version 9.6.7, +and possibly with later versions. The tutorial uses Cabal and is tied to +a specific version of the ideas package.

+

from Hackage and install the library with the following command:

+
cabal install ideas -f -logging
+

The -logging flag installs the package without support +for logging: enabling logging would require installing +sqlite3 for HDBC. We can now start writing a new Haskell +module and import some modules from the Ideas package.

+
module Main where
+
+import Control.Applicative
+import Ideas.Common.Library
+import Ideas.Main.Default
+

This will import basic functionality +(Ideas.Common.Library) for defining your own exercise. The +other import (Ideas.Main.Default) is needed for step 4 of +this tutorial.

+

In this tutorial we will develop a domain reasoner for a simple +arithmetic expression language. The goal of the domain reasoner is to +evaluate expressions. We define a data type for expressions with +addition, (unary) negation, and integer constants.

+
data Expr = Add Expr Expr | Negate Expr | Con Int
+   deriving (Eq, Show, Read)
+

For now we will use derived instances for testing equality, showing, +and reading expressions. We define two examples of expressions in this +data type.

+
-- expression 5+(-2)
+expr1 :: Expr
+expr1 = Add (Con 5) (Negate (Con 2))
+
+-- expression (-2)+(3+5)
+expr2 :: Expr
+expr2 = Add (Negate (Con 2)) (Add (Con 3) (Con 5))
+

Step 1: defining an exercise

+

We define rules to calculate the addition of two constants and to +negate a constant. The Rule data type is parameterized over +the values that are transformed (which is in our case the +Expr data type). The function makeRule takes a +name for the rule (an identifier) and a function of type +a -> Maybe a as its arguments. Constructor +Nothing of the Maybe data type is used to +indicate that the rule cannot be applied.

+
addRule :: Rule Expr
+addRule = describe "Add two numbers" $ makeRule "eval.add" f
+ where
+   f :: Expr -> Maybe Expr
+   f (Add (Con x) (Con y)) = Just $ Con (x+y)
+   f _ = Nothing
+
+negateRule :: Rule Expr
+negateRule = describe "Negate number" $ makeRule "eval.negate" f
+ where
+   f :: Expr -> Maybe Expr
+   f (Negate (Con x)) = Just $ Con (-x)
+   f _ = Nothing
+

Have a look at the type of the makeRule function in the +documentation, +and observe that the function is overloaded in both arguments. The first +argument is the rule’s identifier, which has to be part of the +IsId type class. The String type is an +instance of this class as can be seen from the example. This type class +helps in creating identifiers for concepts. The Rule data +type carries an identifier of type Id; later we will see +that many other concepts also have an identifier (including +Strategy and Exercise). Identifiers should +have a unique name, and this name can be hierarchical. Hierarchical +names can be created with the '.' character in the name, or +by using the (#) combinator. Values that carry an +identifier can be given a more elaborate description with the +describe function.

+

The transformations in the rules above use a function of type +a -> Maybe a, but sometimes you want a rule to return +multiple results. In these situations you can use a function of type +a -> [a]. The MakeTrans type class that is +part of makeRule’s type generalizes over the type of a +transformation function, and has Maybe and [] +as instances.

+

We first test the rules we defined in a Haskell interpreter by +applying the rules to some expressions. For this, we use function +apply from the Apply type class.

+
Main> apply addRule (Add (Con 5) (Con 3))
+Just (Con 8)
+
+Main> apply negateRule (Negate (Con 5))
+Just (Con (-5))
+
+Main> apply addRule expr1
+Nothing
+
+Main> apply negateRule expr2
+Nothing
+

The last example shows that rules are only applied at top-level, and +not automatically to some arbitrary sub-expression. The rules can be +combined into a strategy: the strategy combinator .|. +denotes choice. We label the strategy with an +identifier.

+
addOrNegate :: LabeledStrategy Expr
+addOrNegate = label "add-or-negate" $
+   addRule .|. negateRule
+

Also strategies can be applied to a term.

+
Main> apply addOrNegate (Add (Con 5) (Con 3))
+Just (Con 8)
+
+Main> apply addOrNegate expr1
+Nothing
+

We can now make a minimal exercise that uses the +addOrNegate strategy for solving: why we need to lift the +strategy to a Context is explained in step 2 of this +tutorial. Exercises should have a unique identifier for identification. +We use show for pretty-printing expressions. See the documentation +of the Exercise data type for the other components of an +exercise: emptyExercise provides sensible defaults so we do +not have to worry about these fields yet.

+
minimalExercise :: Exercise Expr
+minimalExercise = emptyExercise
+   { exerciseId    = describe "Evaluate an expression (minimal)" $
+                        newId "eval.minimal"
+   , strategy      = liftToContext addOrNegate
+   , prettyPrinter = show
+   }
+

Again, we can apply an exercise to a given expression:

+
Main> apply minimalExercise (Add (Con 5) (Con 3))
+Just (Con 8)
+

For an Exercise, however, function +printDerivation is more interesting because it shows a +worked-out example and not just the final answer.

+
Main> printDerivation minimalExercise (Add (Con 5) (Con 3))
+Add (Con 5) (Con 3)
+   => eval.add
+Con 8
+

Step 2: adding traversals

+

For arithmetic expressions we want to apply the rules +somewhere, i.e., possibly also to the sub-expressions. We +want to use traversal functions such as somewhere in our +strategy definitions, but this is only possible if we know the structure +of the terms we want to traverse. We use a zipper data structure for +keeping a point of focus. Instead of defining a zipper on the +Expr data type, we define a translation to the +Term data type in the Ideas library and use a zipper on +Terms. Besides the zipper, some more untyped, generic +functions are offered for the Term data type.

+

Two symbols are defined for the two constructors of +Expr.

+
addSymbol, negateSymbol :: Symbol
+addSymbol    = newSymbol "add"
+negateSymbol = newSymbol "negate"
+

These symbols are used for the IsTerm instance: we have +to make sure that fromTerm after toTerm is the +identity function.

+
instance IsTerm Expr where
+   toTerm (Add x y)  = binary addSymbol (toTerm x) (toTerm y)
+   toTerm (Negate x) = unary negateSymbol (toTerm x)
+   toTerm (Con x)    = TNum (toInteger x)
+   
+   fromTerm (TNum x) = return (Con (fromInteger x))
+   fromTerm term
+     | isSymbol addSymbol term    = do
+         (xt, yt) <- isBinary addSymbol term
+         x        <- fromTerm xt
+         y        <- fromTerm yt
+         return (Add x y)
+     | isSymbol negateSymbol term = Negate <$> (isUnary negateSymbol term >>= fromTerm)
+     | otherwise                  = fail "invalid expression"
+
   termDecoder =  Con . fromInteger <$> tInteger
+              <|> Negate <$> termDecoder
+              <|> tList2 Add termDecoder termDecoder
+

We can now define an improved strategy that applies +addOrNegate somewhere: the traversal combinators can only +be used on strategies (or rules) that are lifted to a +Context (or some other data type with a zipper). Therefore +we have to lift the addOrNegate strategy to a +Context before using somewhere. We repeat the +strategy until it can no longer be applied. Observe that the +evalStrategy works on Context Exprs.

+
evalStrategy :: LabeledStrategy (Context Expr)
+evalStrategy = label "eval" $
+   repeatS (somewhere (liftToContext addOrNegate))
+

Testing this strategy is more involved because we first have to put +an Expr into a Context: for this context we +use the termNavigator.

+
Main> apply evalStrategy $ newContext $ termNavigator expr1
+Just Con 3 @ []
+

In the output, @ [] prints the current focus of the +zipper, which is here the top-level node of the expression. For +expr2, the strategy can start evaluating sub-expression +Negate (Con 2) or sub-expression +Add (Con 3) (Con 5). Therefore, evaluating this expression +gives two solution paths (with the same result). This can be inspected +by using applyAll, which returns all results of application +in a list.

+
Main> applyAll evalStrategy $ newContext $ termNavigator expr2
+[Con 6 @ [],Con 6 @ []]
+

We define an extended exercise that is based on +evalStrategy. In the exercise definition, we have to +declare that navigation is based on the termNavigator.

+
basicExercise :: Exercise Expr
+basicExercise = emptyExercise
+   { exerciseId    = describe "Evaluate an expression (basic)" $
+                        newId "eval.basic"
+   , strategy      = evalStrategy
+   , navigation    = termNavigator
+   , prettyPrinter = show
+   }
+

We can now print worked-out solutions for expr1 and +expr2. Note that printDerivations prints all +solutions (and printDerivation only shows one).

+
Main> printDerivations basicExercise expr1
+Derivation #1
+Add (Con 5) (Negate (Con 2))
+   => eval.negate
+Add (Con 5) (Con (-2))
+   => eval.add
+Con 3
+
+Main> printDerivations basicExercise expr2
+Derivation #1
+Add (Negate (Con 2)) (Add (Con 3) (Con 5))
+   => eval.add
+Add (Negate (Con 2)) (Con 8)
+   => eval.negate
+Add (Con (-2)) (Con 8)
+   => eval.add
+Con 6
+
+Derivation #2
+Add (Negate (Con 2)) (Add (Con 3) (Con 5))
+   => eval.negate
+Add (Con (-2)) (Add (Con 3) (Con 5))
+   => eval.add
+Add (Con (-2)) (Con 8)
+   => eval.add
+Con 6
+

Step 3: equivalence, +similarity and ready

+

For diagnosing a student step, we have to define which expressions +are semantically equivalent (have the same value after evaluation), and +which expressions are similar (syntactically equal, or slightly more +flexible, for example taking commutativity of Add into +account). When left undefined in an exercise, all expressions are +equivalent and similar, which is not very helpful. For the +Expr data type, we specify that two values are equivalent +when they evaluate to the same Int value.

+
eqExpr :: Expr -> Expr -> Bool
+eqExpr x y = eval x == eval y
+
+eval :: Expr -> Int
+eval (Add x y)  = eval x + eval y
+eval (Negate x) = -eval x
+eval (Con x)    = x 
+

We also want to define the goal of an exercise: we are ready +rewriting an expression when we have reached a constant value.

+
isCon :: Expr -> Bool
+isCon (Con _) = True
+isCon _       = False
+

We give an extended definition for the exercise with +equivalence and ready. We also specify its +status, the parser for expressions, and two +example expressions (of a certain difficulty).

+
evalExercise :: Exercise Expr
+evalExercise = emptyExercise
+   { exerciseId    = describe "Evaluate an expression (full)" $
+                        newId "eval.full"
+   , status        = Experimental
+   , strategy      = evalStrategy
+   , prettyPrinter = show
+   , navigation    = termNavigator
+   , parser        = maybe (Left "No parse") Right . readM
+   , equivalence   = withoutContext eqExpr
+   , similarity    = withoutContext (==)
+   , ready         = predicate isCon
+   , examples      = examplesFor Easy [expr1, expr2]
+   }
+

The readM function is defined in the Ideas library and +provides a simple parser for values (here: a parser for +Exprs) based on an instance for the Read type +class. We now have a somewhat simple, but fully functional exercise for +evaluating expressions.

+

Step 4: making a +CGI-webservice

+

An exercise can be used by external tools by turning it into a domain +reasoner: such a reasoner supports some exercises, and provides a number +of (standard) feedback services. We use the three exercises we have +defined so far, together with the standard set of services.

+
dr :: DomainReasoner
+dr = describe "Domain reasoner for tutorial" (newDomainReasoner "eval") 
+   { exercises = [Some minimalExercise, Some basicExercise, Some evalExercise]
+   , services  = myServices
+   }
+
+myServices :: [Service]
+myServices = metaServiceList dr ++ serviceList
+

A default main function is provided by the Ideas framework.

+
main :: IO ()
+main = defaultMain dr
+

Compile the module to get an executable. In this tutorial we assume +that the code is placed in a file called Tutorial.hs, and +the result of compilation is an executable Tutorial.exe (on +Windows). The software, however, is portable and can also be compiled +for other platforms (including Mac OS and Linux).

+
$ ghc --make Tutorial.hs
+

Running the executable with the --help flag gives the +options.

+
$ Tutorial.exe --help
+IDEAS: Intelligent Domain-specific Exercise Assistants
+Copyright 2018, Open Universiteit Nederland
+version 1.8, revision 26fe80.., logging disabled
+
+Usage: ideas [OPTION]     (by default, CGI protocol)
+
+Options:
+           --version              show version number
+  -?       --help                 show options
+           --print-log            print log information (for debugging)
+  -f FILE  --file=FILE            use input FILE as request
+           --test[=DIR]           run tests on directory (default: 'test')
+           --make-script=ID       generate feedback script for exercise
+           --analyze-script=FILE  analyze feedback script and report errors
+

The application handles requests: one way is to place the request in +a file and to pass the file name to the application. In the example +requests we use XML, but also other encodings are supported. If we want +to know the list of supported exercises, we place the following request +in a file exerciselist.xml

+
<request service="exerciselist" source="tutorial"/>
+

It is a good custom to always include the source of the request to +let the domain reasoner know where the request came from. The result of +this request is:

+
$ Tutorial.exe --file=exerciselist.xml                                          
+<reply result="ok" version="1.8 (26fe80..)">
+  <list>
+    <elem exerciseid="eval.basic" description="Evaluate an expression (basic)" status="Experimental"/>
+    <elem exerciseid="eval.full" description="Evaluate an expression (full)" status="Experimental"/>
+    <elem exerciseid="eval.minimal" description="Evaluate an expression (minimal)" status="Experimental"/>
+  </list>
+</reply>                                         
+

Or we request a worked-out solution for +Add (Con 5) (Negate (Con 2)).

+
<request exerciseid="eval.full" service="derivation" encoding="string" source="tutorial">
+    <state>                
+        <expr>Add (Con 5) (Negate (Con 2))</expr>
+    </state>
+</request>
+

In this request we have to specify that the encoding of expressions +is a plain string and that we want to use the parser/pretty-printer +defined for the exercise. The default encoding follows the OpenMath standard for +representing mathematical objects. The result of this request is:

+
$ Tutorial.exe --file=solution.xml
+<reply result="ok" version="1.8 (26fe80..)">
+  <list>
+    <elem ruleid="eval.negate">
+      <expr>
+        Add (Con 5) (Con (-2))
+      </expr>
+      <context>
+        <item name="location" value="[1]"/>
+      </context>
+    </elem>
+    <elem ruleid="eval.add">
+      <expr>
+        Con 3
+      </expr>
+    </elem>
+  </list>
+</reply>
+

The executable Tutorial.exe is also a cgi-binary that +can be deployed on a web-server. Because there is support for generating +HTML as output, it is possible to interactively explore the domain +reasoner with a browser and a local server.

+
    +
  • Install a webserver, such as WampServer for Windows.
  • +
  • Make sure you enable the execution of CGI scripts (in +httpd.conf)
  • +
  • Rename the executable to Tutorial.cgi and place it in +the directory for cgi scripts
  • +
  • Start a browser and type in the URL +http://localhost/Tutorial.cgi
  • +
+

You can now start exploring the supported exercises and feedback +services. For instance, go to the exercise eval.full and +click on derivations in the yellow box to see the +worked-out solutions for two examples.

+

Suggested exercises

+
    +
  • Add multiplication to the expression language (and extend the +evaluation strategy)
  • +
  • Add distribution rules to the strategy
  • +
  • Add support for calculating with fractions (e.g. 5/7 + 1/2) +
      +
    • Find the least common multiple of the denominators
    • +
    • Rewrite top-heavy fractions to mixed fractions (e.g. 17/14 becomes +1+3/14)
    • +
  • +
+

We have developed our own +solution to these exercises.

+ +
+
+This tutorial is based on ideas-1.8. Last changed: September 2019 +
\ No newline at end of file From f35f8328bbd7778b6b34e7a661e64dca501b2718 Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Thu, 23 Jul 2026 22:39:53 +0200 Subject: [PATCH 53/57] Added some example service requests in XML format --- tutorial/exerciselist.xml | 1 + tutorial/solution.xml | 5 +++++ 2 files changed, 6 insertions(+) create mode 100644 tutorial/exerciselist.xml create mode 100644 tutorial/solution.xml diff --git a/tutorial/exerciselist.xml b/tutorial/exerciselist.xml new file mode 100644 index 00000000..4f07c9d8 --- /dev/null +++ b/tutorial/exerciselist.xml @@ -0,0 +1 @@ + diff --git a/tutorial/solution.xml b/tutorial/solution.xml new file mode 100644 index 00000000..f1806f62 --- /dev/null +++ b/tutorial/solution.xml @@ -0,0 +1,5 @@ + + + Add (Con 5) (Negate (Con 2)) + + From 12dc4e9e1abea422b17ce0c09bf541a3f73e58f9 Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Thu, 23 Jul 2026 22:55:48 +0200 Subject: [PATCH 54/57] Fixed a warning, using `splitGen` instead of `split` --- ideas.cabal | 4 +- src/Ideas/Common/Exercise.hs | 897 +++++++++++++++++++---------------- 2 files changed, 479 insertions(+), 422 deletions(-) diff --git a/ideas.cabal b/ideas.cabal index cf8323e0..abe4b703 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -28,7 +28,7 @@ stability: provisional extra-source-files: NOTICE.txt, CHANGELOG.txt build-type: Simple cabal-version: >= 1.8.0.2 -tested-with: GHC == 7.10.3, GHC == 8.0.2, GHC == 8.2.2, GHC == 8.4.2 +tested-with: GHC == 8.0.2, GHC == 8.2.2, GHC == 8.4.2 source-repository head type: git @@ -62,7 +62,7 @@ Library mtl, network, parsec, - random, + random >= 1.3, streaming-commons, time, uniplate, diff --git a/src/Ideas/Common/Exercise.hs b/src/Ideas/Common/Exercise.hs index 590ceac2..df1b70a5 100644 --- a/src/Ideas/Common/Exercise.hs +++ b/src/Ideas/Common/Exercise.hs @@ -1,420 +1,477 @@ -{-# LANGUAGE Rank2Types, ExistentialQuantification #-} ------------------------------------------------------------------------------ --- Copyright 2019, Ideas project team. This file is distributed under the --- terms of the Apache License 2.0. For more information, see the files --- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. ------------------------------------------------------------------------------ --- | --- Maintainer : bastiaan.heeren@ou.nl --- Stability : provisional --- Portability : portable (depends on ghc) --- --- The 'Exercise' record defines all the components that are needed for --- calculating feedback for one class of exercises. The fields of an exercise --- have to be consistent; consistency can be checked with the --- "Ideas.Common.ExerciseTests" module. --- ------------------------------------------------------------------------------ - -module Ideas.Common.Exercise - ( -- * Exercise record - Exercise(..), emptyExercise, makeExercise - -- * Convenience functions - , prettyPrinterContext, isReady, isSuitable - , ruleset, getRule, ruleOrderingWith, violations - -- * Status - , Status(..), isPublic, isPrivate - -- * Examples - , Examples, Difficulty(..), readDifficulty - , examplesFor, examplesWithDifficulty, examplesContext, examplesAsList - , testGenerator, randomTerm, randomTerms - -- * Context - , inContext, withoutContext - -- * Type casting - , useTypeable, castFrom, castTo - -- * Exercise properties - , setProperty, getProperty, setPropertyF, getPropertyF - -- * Derivations - , showDerivation, showDerivations, printDerivation, printDerivations - , diffEnvironment, defaultDerivation, allDerivations - ) where - -import Data.List -import Data.Maybe -import Data.Ord -import Ideas.Common.Classes -import Ideas.Common.Constraint -import Ideas.Common.Context -import Ideas.Common.Derivation -import Ideas.Common.Environment -import Ideas.Common.Examples -import Ideas.Common.Id -import Ideas.Common.Predicate -import Ideas.Common.Rewriting -import Ideas.Common.Rule -import Ideas.Common.Strategy hiding (not, fail, repeat, replicate) -import Ideas.Common.View -import Ideas.Utils.Prelude (ShowString(..)) -import Ideas.Utils.Typeable -import System.Random -import Test.QuickCheck hiding (label) -import Test.QuickCheck.Gen -import Test.QuickCheck.Random (QCGen) -import qualified Data.Map as M -import qualified Ideas.Common.Strategy as S - ------------------------------------------------------------------------------ --- Exercise record - --- | For constructing an empty exercise, use function 'emptyExercise' or --- 'makeExercise'. -data Exercise a = - NewExercise - { -- | Identifier that uniquely determines the exercise: see 'HasId' for - -- how to use values with identifiers. - exerciseId :: Id - -- | The status of the exercise. - , status :: Status - -- | Parser for expressions of the exercise class, which either results - -- in an error ('Left') or a result ('Right'). - , parser :: String -> Either String a - -- | Pretty-printer for expressions of the exercise class. Pretty-printing - -- should be the inverse of parsing. - , prettyPrinter :: a -> String - -- | Tests wether two expressions (with their contexts) are semantically - -- equivalent. Use 'withoutContext' for defining the equivalence check - -- when the context is not relevant. - , equivalence :: Context a -> Context a -> Bool - -- | Tests wether two expressions (with their contexts) are syntactically - -- the same, or nearly so. Expressions that are similar must also be - -- equivalent. Use 'withoutContext' if the context is not relevant for the - -- similarity check. - , similarity :: Context a -> Context a -> Bool - -- | Predicate suitable identifies which expressions can be solved by the - -- strategy of the exercise class. It acts as the pre-condition of the - -- strategy. - , suitable :: Predicate a - -- | Predicate ready checks if an expression is in a solved form (accepted - -- as a final solution). It acts as the post-condition of the strategy. - , ready :: Predicate a - -- | The rewrite strategy that specifies how to solve an exercise. - , strategy :: LabeledStrategy (Context a) - -- | Is it possible to restart the rewrite strategy at any point in time? - -- Restarting the strategy is needed when a student deviates from the - -- strategy (detour). By default, restarting is assumed to be possible. - , canBeRestarted :: Bool - -- | Are there extra rules, possibly buggy, that do not appear in the - -- strategy? Use 'ruleset' to get all rules. - , extraRules :: [Rule (Context a)] - -- | The rule ordering is a tiebreaker in situations where more than one - -- rule can be used (e.g. feedback services onefirst and derivation; other - -- feedback services return all possible rules). - , ruleOrdering :: Rule (Context a) -> Rule (Context a) -> Ordering - -- | Constraints for constraint-based tutors. A constraint contains a - -- relevance condition and a satisfaction condition. - , constraints :: [Constraint (Context a)] - -- | A navigator is needed for traversing the expression and for using the - -- traversal strategy combinators. By default, an exercise has no - -- navigator. - , navigation :: a -> ContextNavigator a - -- | A finite list of examples, each with an assigned difficulty. - , examples :: Examples a - -- | Conversion to and from the (generic) 'Term' datatype. Needed for - -- representing the expression in the OpenMath standard. - , hasTermView :: Maybe (View Term a) - -- | Representation of the type of expression: this provides a back door - -- for exercise-specific functionality. - , hasTypeable :: Maybe (IsTypeable a) - -- | Extra exercise-specific properties, not used by the default - -- feedback services. - , properties :: M.Map Id (Dynamic a) -- extra, domain-specific properties - } - -instance Eq (Exercise a) where - e1 == e2 = getId e1 == getId e2 - -instance Ord (Exercise a) where - compare = comparing getId - -instance Apply Exercise where - applyAll ex = mapMaybe fromContext . applyAll (strategy ex) . inContext ex - -instance HasId (Exercise a) where - getId = exerciseId - changeId f ex = ex { exerciseId = f (exerciseId ex) } - --- | The 'emptyExercise' constructor function provides sensible defaults for --- all fields of the 'Exercise' record. -emptyExercise :: Exercise a -emptyExercise = NewExercise - { -- identification and meta-information - exerciseId = mempty - , status = Experimental - -- parsing and pretty-printing - , parser = const (Left "<>") - , prettyPrinter = const "<>" - -- syntactic and semantic checks - , equivalence = \_ _ -> True - , similarity = \_ _ -> True - , ready = true - , suitable = true - , hasTermView = Nothing - , hasTypeable = Nothing - , properties = M.empty - -- strategies and rules - , strategy = label "Fail" S.fail - , constraints = [] - , navigation = noNavigator - , canBeRestarted = True - , extraRules = [] - , ruleOrdering = compareId - -- examples - , examples = mempty - } - --- | In addition to the defaults of 'emptyExercise', this constructor sets --- the fields 'prettyPrinter', 'similarity', and 'hasTermView'. -makeExercise :: (Show a, Eq a, IsTerm a) => Exercise a -makeExercise = emptyExercise - { prettyPrinter = show - , similarity = (==) - , hasTermView = Just termView - } - ------------------------------------------------------------------------------ --- Convenience functions - --- | Pretty print a value in its context. -prettyPrinterContext :: Exercise a -> Context a -> String -prettyPrinterContext ex = - maybe "<>" (prettyPrinter ex) . fromContext - --- | Checks if an expression is in a solved form. -isReady :: Exercise a -> a -> Bool -isReady = evalPredicate . ready - --- | Checks if the expression is suitable and can be solved by the strategy. -isSuitable :: Exercise a -> a -> Bool -isSuitable = evalPredicate . suitable - --- | Returns a sorted list of rules, without duplicates. -ruleset :: Exercise a -> [Rule (Context a)] -ruleset ex = nub (sortBy (ruleOrdering ex) list) - where - list = extraRules ex ++ rulesInStrategy (strategy ex) - --- | Finds a rule of an exercise based on its identifier. -getRule :: Exercise a -> Id -> Maybe (Rule (Context a)) -getRule ex a = - case filter ((a ==) . getId) (ruleset ex) of - [hd] -> Just hd - _ -> Nothing - --- | Makes a rule ordering based on a list of values with identifiers (e.g., --- a list of rules). Rules with identifiers that are not in the list are --- considered after the rules in the list, and are sorted based on their --- identifier. -ruleOrderingWith :: HasId b => [b] -> Rule a -> Rule a -> Ordering -ruleOrderingWith bs r1 r2 = - let xs = map getId bs in - case (elemIndex (getId r1) xs, elemIndex (getId r2) xs) of - (Just i, Just j ) -> i `compare` j - (Just _, Nothing) -> LT - (Nothing, Just _ ) -> GT - (Nothing, Nothing) -> compareId r1 r2 - --- | Get all constraint violations -violations :: Exercise a -> Context a -> [(Constraint (Context a), String)] -violations ex ctx = - [ (c, msg) - | c <- constraints ex - , msg <- maybeToList (isViolated c ctx) - ] - ------------------------------------------------------------------------------ --- Status - --- | The status of an exercise class. -data Status - = Stable -- ^ A released exercise that has undergone some thorough testing - | Provisional -- ^ A released exercise, possibly with some deficiencies - | Alpha -- ^ An exercise that is under development - | Experimental -- ^ An exercise for experimentation purposes only - deriving (Show, Eq) - --- | An exercise with the status 'Stable' or 'Provisional' -isPublic :: Exercise a -> Bool -isPublic ex = status ex `elem` [Stable, Provisional] - --- | An exercise that is not public -isPrivate :: Exercise a -> Bool -isPrivate = not . isPublic - ------------------------------------------------------------------------------ --- Examples - --- | Returns the examples of an exercise class lifted to a context. -examplesContext :: Exercise a -> Examples (Context a) -examplesContext ex = fmap (inContext ex) (examples ex) - -examplesAsList :: Exercise a -> [a] -examplesAsList = map snd . allExamples . examples - -fromGen :: QCGen -> Gen a -> a -fromGen rng (MkGen f) = a - where - (sz, r) = randomR (0, 100) rng - a = f r sz - --- | Returns a random exercise of a certain difficulty with some random --- number generator. The field 'randomExercise' is used; if this is not --- defined (i.e., Nothing), one of the examples is used instead. -randomTerm :: QCGen -> Exercise a -> Maybe Difficulty -> Maybe a -randomTerm rng ex mdif = - case filter ((== mdif) . fst) (allRandoms (examples ex)) of - (_, g):_ -> Just (fromGen rng g) - [] - | null xs -> Nothing - | otherwise -> Just (snd (xs !! i)) - where - xs = filter p (allExamples (examples ex)) -- improve - p (Just d, _) = maybe True (==d) mdif - p _ = False - i = fst (randomR (0, length xs - 1) rng) - --- | Returns a list of randomly generated terms of a certain difficulty. -randomTerms :: QCGen -> Exercise a -> Maybe Difficulty -> [a] -randomTerms rng ex mdif = rec rng - where - rec a = maybe id (:) (randomTerm a ex mdif) (rec (snd (split a))) - --- | An exercise generator for testing purposes (including corner cases); first generator only. -testGenerator :: Exercise a -> Maybe (Gen a) -testGenerator = listToMaybe . allRandomTests . examples - ------------------------------------------------------------------------------ --- Context - --- | Puts a value into a context with an empty environment. -inContext :: Exercise a -> a -> Context a -inContext ex = newContext . navigation ex - --- | Function for defining equivalence or similarity without taking --- the context into account. -withoutContext :: (a -> a -> Bool) -> Context a -> Context a -> Bool -withoutContext f a b = fromMaybe False (fromContextWith2 f a b) - ------------------------------------------------------------------------------ --- Type casting - -instance HasTypeable Exercise where - getTypeable = hasTypeable - --- | Encapsulates a type representation (use for 'hasTypeable' field). -useTypeable :: Typeable a => Maybe (IsTypeable a) -useTypeable = Just typeable - ------------------------------------------------------------------------------ --- Exercise-specific properties - --- | Set an exercise-specific property (with a dynamic type) -setProperty :: (IsId n, Typeable val) => n -> val -> Exercise a -> Exercise a -setProperty key a = insertProperty key (Dyn (cast a)) - --- | Set an exercise-specific property (with a dynamic type) that is --- parameterized over the exercise term. -setPropertyF :: (IsId n, Typeable f) => n -> f a -> Exercise a -> Exercise a -setPropertyF key a = insertProperty key (DynF (castF a)) - -insertProperty :: IsId n => n -> Dynamic a -> Exercise a -> Exercise a -insertProperty key d ex = - ex { properties = M.insert (newId key) d (properties ex) } - --- | Get an exercise-specific property (of a dynamic type) -getProperty :: (IsId n, Typeable val) => n -> Exercise a -> Maybe val -getProperty key ex = lookupProperty key ex >>= \d -> - case d of - Dyn m -> m - _ -> Nothing - --- | Get an exercise-specific property (of a dynamic type) that is --- parameterized over the exercise term. -getPropertyF :: (IsId n, Typeable f) => n -> Exercise a -> Maybe (f a) -getPropertyF key ex = lookupProperty key ex >>= \d -> - case d of - DynF m -> m - _ -> Nothing - -lookupProperty :: IsId n => n -> Exercise a -> Maybe (Dynamic a) -lookupProperty key = M.lookup (newId key) . properties - --- | Values with a dynamic type that is parameterized over the exercise term. -data Dynamic a = Dyn (forall b . Typeable b => Maybe b) - | DynF (forall f . Typeable f => Maybe (f a)) - -castF :: (Typeable f, Typeable g) => f a -> Maybe (g a) -castF = fmap fromIdentity . gcast1 . Identity - -newtype Identity a = Identity { fromIdentity :: a} - ---------------------------------------------------------------- --- Derivations - --- | Shows the default derivation for a given start term. The specified rule ordering --- is used for selection. -showDerivation :: Exercise a -> a -> String -showDerivation ex a = - case defaultDerivation ex a of - Just d -> showThisDerivation d ex - Nothing -> "no derivation" - --- | Shows all derivations for a given start term. Warning: there can be many --- derivations. -showDerivations :: Exercise a -> a -> String -showDerivations ex a = unlines - [ "Derivation #" ++ show i ++ "\n" ++ showThisDerivation d ex - | (i, d) <- zip [1::Int ..] (allDerivations ex a) - ] - --- | Prints the default derivation for a given start term. The specified rule ordering --- is used for selection. -printDerivation :: Exercise a -> a -> IO () -printDerivation ex = putStrLn . showDerivation ex - --- | Prints all derivations for a given start term. Warning: there can be many --- derivations. -printDerivations :: Exercise a -> a -> IO () -printDerivations ex = putStrLn . showDerivations ex - --- also pass derivation as an argument -showThisDerivation :: Derivation (Rule b, Environment) (Context a) -> Exercise a -> String -showThisDerivation d ex = show (present der) ++ extra - where - der = diffEnvironment d - extra = - case fromContext (lastTerm der) of - Nothing -> "<>" - Just b | isReady ex b -> "" - | otherwise -> "<>" - present = biMap (ShowString . f) (ShowString . prettyPrinterContext ex) - f ((r, localEnv), globalEnv) = showId r ++ part localEnv ++ part globalEnv - where - newl = "\n " - part env | noBindings env = "" - | otherwise = newl ++ show env - --- | Adds the difference of the environments in a derivation to the steps. --- Bindings with identifier @location@ are ignored. This utility function is --- useful for printing derivations. -diffEnvironment :: HasEnvironment a => Derivation s a -> Derivation (s, Environment) a -diffEnvironment = updateSteps $ \old a new -> - let keep x = not (getId x == newId "location" || x `elem` list) - list = bindings old - in (a, makeEnvironment $ filter keep $ bindings new) - -defaultDerivation :: Exercise a -> a -> Maybe (Derivation (Rule (Context a), Environment) (Context a)) -defaultDerivation ex = listToMaybe . allDerivations ex - -allDerivations :: Exercise a -> a -> [Derivation (Rule (Context a), Environment) (Context a)] -allDerivations ex = - derivationList (ruleOrdering ex) (strategy ex) . inContext ex \ No newline at end of file +{-# LANGUAGE ExistentialQuantification #-} +{-# LANGUAGE Rank2Types #-} + +----------------------------------------------------------------------------- +-- Copyright 2019, Ideas project team. This file is distributed under the +-- terms of the Apache License 2.0. For more information, see the files +-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- + +{- | +Maintainer : bastiaan.heeren@ou.nl +Stability : provisional +Portability : portable (depends on ghc) + +The 'Exercise' record defines all the components that are needed for +calculating feedback for one class of exercises. The fields of an exercise +have to be consistent; consistency can be checked with the +"Ideas.Common.ExerciseTests" module. +-} +module Ideas.Common.Exercise + ( -- * Exercise record + Exercise (..) + , emptyExercise + , makeExercise + + -- * Convenience functions + , prettyPrinterContext + , isReady + , isSuitable + , ruleset + , getRule + , ruleOrderingWith + , violations + + -- * Status + , Status (..) + , isPublic + , isPrivate + + -- * Examples + , Examples + , Difficulty (..) + , readDifficulty + , examplesFor + , examplesWithDifficulty + , examplesContext + , examplesAsList + , testGenerator + , randomTerm + , randomTerms + + -- * Context + , inContext + , withoutContext + + -- * Type casting + , useTypeable + , castFrom + , castTo + + -- * Exercise properties + , setProperty + , getProperty + , setPropertyF + , getPropertyF + + -- * Derivations + , showDerivation + , showDerivations + , printDerivation + , printDerivations + , diffEnvironment + , defaultDerivation + , allDerivations + ) where + +import Data.List +import qualified Data.Map as M +import Data.Maybe +import Data.Ord +import System.Random +import Test.QuickCheck hiding (label) +import Test.QuickCheck.Gen +import Test.QuickCheck.Random (QCGen) + +import Ideas.Common.Classes +import Ideas.Common.Constraint +import Ideas.Common.Context +import Ideas.Common.Derivation +import Ideas.Common.Environment +import Ideas.Common.Examples +import Ideas.Common.Id +import Ideas.Common.Predicate +import Ideas.Common.Rewriting +import Ideas.Common.Rule +import Ideas.Common.Strategy hiding (fail, not, repeat, replicate) +import qualified Ideas.Common.Strategy as S +import Ideas.Common.View +import Ideas.Utils.Prelude (ShowString (..)) +import Ideas.Utils.Typeable + +----------------------------------------------------------------------------- +-- Exercise record + +-- | For constructing an empty exercise, use function 'emptyExercise' or +-- 'makeExercise'. +data Exercise a + = NewExercise + { exerciseId :: Id + -- ^ Identifier that uniquely determines the exercise: see 'HasId' for + -- how to use values with identifiers. + , status :: Status + -- ^ The status of the exercise. + , parser :: String -> Either String a + -- ^ Parser for expressions of the exercise class, which either results + -- in an error ('Left') or a result ('Right'). + , prettyPrinter :: a -> String + -- ^ Pretty-printer for expressions of the exercise class. Pretty-printing + -- should be the inverse of parsing. + , equivalence :: Context a -> Context a -> Bool + -- ^ Tests wether two expressions (with their contexts) are semantically + -- equivalent. Use 'withoutContext' for defining the equivalence check + -- when the context is not relevant. + , similarity :: Context a -> Context a -> Bool + -- ^ Tests wether two expressions (with their contexts) are syntactically + -- the same, or nearly so. Expressions that are similar must also be + -- equivalent. Use 'withoutContext' if the context is not relevant for the + -- similarity check. + , suitable :: Predicate a + -- ^ Predicate suitable identifies which expressions can be solved by the + -- strategy of the exercise class. It acts as the pre-condition of the + -- strategy. + , ready :: Predicate a + -- ^ Predicate ready checks if an expression is in a solved form (accepted + -- as a final solution). It acts as the post-condition of the strategy. + , strategy :: LabeledStrategy (Context a) + -- ^ The rewrite strategy that specifies how to solve an exercise. + , canBeRestarted :: Bool + -- ^ Is it possible to restart the rewrite strategy at any point in time? + -- Restarting the strategy is needed when a student deviates from the + -- strategy (detour). By default, restarting is assumed to be possible. + , extraRules :: [Rule (Context a)] + -- ^ Are there extra rules, possibly buggy, that do not appear in the + -- strategy? Use 'ruleset' to get all rules. + , ruleOrdering :: Rule (Context a) -> Rule (Context a) -> Ordering + -- ^ The rule ordering is a tiebreaker in situations where more than one + -- rule can be used (e.g. feedback services onefirst and derivation; other + -- feedback services return all possible rules). + , constraints :: [Constraint (Context a)] + -- ^ Constraints for constraint-based tutors. A constraint contains a + -- relevance condition and a satisfaction condition. + , navigation :: a -> ContextNavigator a + -- ^ A navigator is needed for traversing the expression and for using the + -- traversal strategy combinators. By default, an exercise has no + -- navigator. + , examples :: Examples a + -- ^ A finite list of examples, each with an assigned difficulty. + , hasTermView :: Maybe (View Term a) + -- ^ Conversion to and from the (generic) 'Term' datatype. Needed for + -- representing the expression in the OpenMath standard. + , hasTypeable :: Maybe (IsTypeable a) + -- ^ Representation of the type of expression: this provides a back door + -- for exercise-specific functionality. + , properties :: M.Map Id (Dynamic a) -- extra, domain-specific properties + + -- ^ Extra exercise-specific properties, not used by the default + -- feedback services. + } + +instance Eq (Exercise a) where + e1 == e2 = getId e1 == getId e2 + +instance Ord (Exercise a) where + compare = comparing getId + +instance Apply Exercise where + applyAll ex = mapMaybe fromContext . applyAll (strategy ex) . inContext ex + +instance HasId (Exercise a) where + getId = exerciseId + changeId f ex = ex{exerciseId = f (exerciseId ex)} + +-- | The 'emptyExercise' constructor function provides sensible defaults for +-- all fields of the 'Exercise' record. +emptyExercise :: Exercise a +emptyExercise = + NewExercise + { -- identification and meta-information + exerciseId = mempty + , status = Experimental + , -- parsing and pretty-printing + parser = const (Left "<>") + , prettyPrinter = const "<>" + , -- syntactic and semantic checks + equivalence = \_ _ -> True + , similarity = \_ _ -> True + , ready = true + , suitable = true + , hasTermView = Nothing + , hasTypeable = Nothing + , properties = M.empty + , -- strategies and rules + strategy = label "Fail" S.fail + , constraints = [] + , navigation = noNavigator + , canBeRestarted = True + , extraRules = [] + , ruleOrdering = compareId + , -- examples + examples = mempty + } + +-- | In addition to the defaults of 'emptyExercise', this constructor sets +-- the fields 'prettyPrinter', 'similarity', and 'hasTermView'. +makeExercise :: (Eq a, IsTerm a, Show a) => Exercise a +makeExercise = + emptyExercise + { prettyPrinter = show + , similarity = (==) + , hasTermView = Just termView + } + +----------------------------------------------------------------------------- +-- Convenience functions + +-- | Pretty print a value in its context. +prettyPrinterContext :: Exercise a -> Context a -> String +prettyPrinterContext ex = + maybe "<>" (prettyPrinter ex) . fromContext + +-- | Checks if an expression is in a solved form. +isReady :: Exercise a -> a -> Bool +isReady = evalPredicate . ready + +-- | Checks if the expression is suitable and can be solved by the strategy. +isSuitable :: Exercise a -> a -> Bool +isSuitable = evalPredicate . suitable + +-- | Returns a sorted list of rules, without duplicates. +ruleset :: Exercise a -> [Rule (Context a)] +ruleset ex = nub (sortBy (ruleOrdering ex) list) + where + list = extraRules ex ++ rulesInStrategy (strategy ex) + +-- | Finds a rule of an exercise based on its identifier. +getRule :: Exercise a -> Id -> Maybe (Rule (Context a)) +getRule ex a = + case filter ((a ==) . getId) (ruleset ex) of + [hd] -> Just hd + _ -> Nothing + +-- | Makes a rule ordering based on a list of values with identifiers (e.g., +-- a list of rules). Rules with identifiers that are not in the list are +-- considered after the rules in the list, and are sorted based on their +-- identifier. +ruleOrderingWith :: HasId b => [b] -> Rule a -> Rule a -> Ordering +ruleOrderingWith bs r1 r2 = + let xs = map getId bs + in case (elemIndex (getId r1) xs, elemIndex (getId r2) xs) of + (Just i, Just j) -> i `compare` j + (Just _, Nothing) -> LT + (Nothing, Just _) -> GT + (Nothing, Nothing) -> compareId r1 r2 + +-- | Get all constraint violations +violations :: Exercise a -> Context a -> [(Constraint (Context a), String)] +violations ex ctx = + [ (c, msg) + | c <- constraints ex + , msg <- maybeToList (isViolated c ctx) + ] + +----------------------------------------------------------------------------- +-- Status + +-- | The status of an exercise class. +data Status + = -- | A released exercise that has undergone some thorough testing + Stable + | -- | A released exercise, possibly with some deficiencies + Provisional + | -- | An exercise that is under development + Alpha + | -- | An exercise for experimentation purposes only + Experimental + deriving (Eq, Show) + +-- | An exercise with the status 'Stable' or 'Provisional' +isPublic :: Exercise a -> Bool +isPublic ex = status ex `elem` [Stable, Provisional] + +-- | An exercise that is not public +isPrivate :: Exercise a -> Bool +isPrivate = not . isPublic + +----------------------------------------------------------------------------- +-- Examples + +-- | Returns the examples of an exercise class lifted to a context. +examplesContext :: Exercise a -> Examples (Context a) +examplesContext ex = fmap (inContext ex) (examples ex) + +examplesAsList :: Exercise a -> [a] +examplesAsList = map snd . allExamples . examples + +fromGen :: QCGen -> Gen a -> a +fromGen rng (MkGen f) = a + where + (sz, r) = randomR (0, 100) rng + a = f r sz + +-- | Returns a random exercise of a certain difficulty with some random +-- number generator. The field 'randomExercise' is used; if this is not +-- defined (i.e., Nothing), one of the examples is used instead. +randomTerm :: QCGen -> Exercise a -> Maybe Difficulty -> Maybe a +randomTerm rng ex mdif = + case filter ((== mdif) . fst) (allRandoms (examples ex)) of + (_, g) : _ -> Just (fromGen rng g) + [] + | null xs -> Nothing + | otherwise -> Just (snd (xs !! i)) + where + xs = filter p (allExamples (examples ex)) -- improve + p (Just d, _) = maybe True (== d) mdif + p _ = False + i = fst (randomR (0, length xs - 1) rng) + +-- | Returns a list of randomly generated terms of a certain difficulty. +randomTerms :: QCGen -> Exercise a -> Maybe Difficulty -> [a] +randomTerms rng ex mdif = rec rng + where + rec a = maybe id (:) (randomTerm a ex mdif) (rec (snd (splitGen a))) + +-- | An exercise generator for testing purposes (including corner cases); first generator only. +testGenerator :: Exercise a -> Maybe (Gen a) +testGenerator = listToMaybe . allRandomTests . examples + +----------------------------------------------------------------------------- +-- Context + +-- | Puts a value into a context with an empty environment. +inContext :: Exercise a -> a -> Context a +inContext ex = newContext . navigation ex + +-- | Function for defining equivalence or similarity without taking +-- the context into account. +withoutContext :: (a -> a -> Bool) -> Context a -> Context a -> Bool +withoutContext f a b = fromMaybe False (fromContextWith2 f a b) + +----------------------------------------------------------------------------- +-- Type casting + +instance HasTypeable Exercise where + getTypeable = hasTypeable + +-- | Encapsulates a type representation (use for 'hasTypeable' field). +useTypeable :: Typeable a => Maybe (IsTypeable a) +useTypeable = Just typeable + +----------------------------------------------------------------------------- +-- Exercise-specific properties + +-- | Set an exercise-specific property (with a dynamic type) +setProperty :: (IsId n, Typeable val) => n -> val -> Exercise a -> Exercise a +setProperty key a = insertProperty key (Dyn (cast a)) + +-- | Set an exercise-specific property (with a dynamic type) that is +-- parameterized over the exercise term. +setPropertyF :: (IsId n, Typeable f) => n -> f a -> Exercise a -> Exercise a +setPropertyF key a = insertProperty key (DynF (castF a)) + +insertProperty :: IsId n => n -> Dynamic a -> Exercise a -> Exercise a +insertProperty key d ex = + ex{properties = M.insert (newId key) d (properties ex)} + +-- | Get an exercise-specific property (of a dynamic type) +getProperty :: (IsId n, Typeable val) => n -> Exercise a -> Maybe val +getProperty key ex = + lookupProperty key ex >>= \d -> + case d of + Dyn m -> m + _ -> Nothing + +-- | Get an exercise-specific property (of a dynamic type) that is +-- parameterized over the exercise term. +getPropertyF :: (IsId n, Typeable f) => n -> Exercise a -> Maybe (f a) +getPropertyF key ex = + lookupProperty key ex >>= \d -> + case d of + DynF m -> m + _ -> Nothing + +lookupProperty :: IsId n => n -> Exercise a -> Maybe (Dynamic a) +lookupProperty key = M.lookup (newId key) . properties + +-- | Values with a dynamic type that is parameterized over the exercise term. +data Dynamic a + = Dyn (forall b. Typeable b => Maybe b) + | DynF (forall f. Typeable f => Maybe (f a)) + +castF :: (Typeable f, Typeable g) => f a -> Maybe (g a) +castF = fmap fromIdentity . gcast1 . Identity + +newtype Identity a = Identity {fromIdentity :: a} + +--------------------------------------------------------------- +-- Derivations + +-- | Shows the default derivation for a given start term. The specified rule ordering +-- is used for selection. +showDerivation :: Exercise a -> a -> String +showDerivation ex a = + case defaultDerivation ex a of + Just d -> showThisDerivation d ex + Nothing -> "no derivation" + +-- | Shows all derivations for a given start term. Warning: there can be many +-- derivations. +showDerivations :: Exercise a -> a -> String +showDerivations ex a = + unlines + [ "Derivation #" ++ show i ++ "\n" ++ showThisDerivation d ex + | (i, d) <- zip [1 :: Int ..] (allDerivations ex a) + ] + +-- | Prints the default derivation for a given start term. The specified rule ordering +-- is used for selection. +printDerivation :: Exercise a -> a -> IO () +printDerivation ex = putStrLn . showDerivation ex + +-- | Prints all derivations for a given start term. Warning: there can be many +-- derivations. +printDerivations :: Exercise a -> a -> IO () +printDerivations ex = putStrLn . showDerivations ex + +-- also pass derivation as an argument +showThisDerivation + :: Derivation (Rule b, Environment) (Context a) -> Exercise a -> String +showThisDerivation d ex = show (present der) ++ extra + where + der = diffEnvironment d + extra = + case fromContext (lastTerm der) of + Nothing -> "<>" + Just b + | isReady ex b -> "" + | otherwise -> "<>" + present = biMap (ShowString . f) (ShowString . prettyPrinterContext ex) + f ((r, localEnv), globalEnv) = showId r ++ part localEnv ++ part globalEnv + where + newl = "\n " + part env + | noBindings env = "" + | otherwise = newl ++ show env + +-- | Adds the difference of the environments in a derivation to the steps. +-- Bindings with identifier @location@ are ignored. This utility function is +-- useful for printing derivations. +diffEnvironment + :: HasEnvironment a => Derivation s a -> Derivation (s, Environment) a +diffEnvironment = updateSteps $ \old a new -> + let keep x = not (getId x == newId "location" || x `elem` list) + list = bindings old + in (a, makeEnvironment $ filter keep $ bindings new) + +defaultDerivation + :: Exercise a + -> a + -> Maybe (Derivation (Rule (Context a), Environment) (Context a)) +defaultDerivation ex = listToMaybe . allDerivations ex + +allDerivations + :: Exercise a -> a -> [Derivation (Rule (Context a), Environment) (Context a)] +allDerivations ex = + derivationList (ruleOrdering ex) (strategy ex) . inContext ex From cef2e8ecd6e01b2533225fa39b0c8bbad9c81da2 Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Fri, 4 Sep 2026 23:28:20 +0200 Subject: [PATCH 55/57] Fix OpenMath decoding of formatted XML --- src/Ideas/Text/OpenMath/Object.hs | 9 ++++++++- src/Ideas/Text/OpenMath/Tests.hs | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Ideas/Text/OpenMath/Object.hs b/src/Ideas/Text/OpenMath/Object.hs index 4532408a..e81e7486 100644 --- a/src/Ideas/Text/OpenMath/Object.hs +++ b/src/Ideas/Text/OpenMath/Object.hs @@ -65,7 +65,14 @@ getOMVs omobj = nub [ x | OMV x <- universe omobj ] -- conversion functions: XML <-> OMOBJ xml2omobj :: XML -> Either String OMOBJ -xml2omobj = either (Left . show) (Right . fst) . runDecoder xmlDecoder () . builder +xml2omobj = either (Left . show) (Right . fst) . runDecoder xmlDecoder () . builder . removeLayout + +removeLayout :: XML -> XML +removeLayout = foldXML (\n as cs -> makeXML n (as <> cs)) (.=.) keepText builder + where + keepText s + | all isSpace s = mempty + | otherwise = string s omobj2xml :: OMOBJ -> XML omobj2xml object = makeXML "OMOBJ" $ mconcat diff --git a/src/Ideas/Text/OpenMath/Tests.hs b/src/Ideas/Text/OpenMath/Tests.hs index c54f6499..8e952fb2 100644 --- a/src/Ideas/Text/OpenMath/Tests.hs +++ b/src/Ideas/Text/OpenMath/Tests.hs @@ -24,6 +24,7 @@ import Ideas.Text.OpenMath.Dictionary.Quant1 import Ideas.Text.OpenMath.Dictionary.Relation1 import Ideas.Text.OpenMath.Dictionary.Transc1 import Ideas.Text.OpenMath.Object +import Ideas.Text.XML import Test.QuickCheck arbOMOBJ :: Gen OMOBJ @@ -48,4 +49,10 @@ arbOMOBJ = sized rec f = rec (n `div` 2) propEncoding :: Property -propEncoding = forAll arbOMOBJ $ \x -> xml2omobj (omobj2xml x) == Right x \ No newline at end of file +propEncoding = forAll arbOMOBJ $ \x -> + let expected = Right x + parsed = parseXML (prettyXML (omobj2xml x)) >>= xml2omobj + in conjoin + [ xml2omobj (omobj2xml x) === expected + , parsed === expected + ] \ No newline at end of file From 68f7211fecd5eac9d606393e36f86341fa8b7eaf Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Sat, 5 Sep 2026 14:11:14 +0200 Subject: [PATCH 56/57] Build with recent GHC versions --- .travis.yml | 221 +++++++--------------------------------------------- ideas.cabal | 4 +- 2 files changed, 30 insertions(+), 195 deletions(-) diff --git a/.travis.yml b/.travis.yml index 18cc4525..4d814345 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,211 +1,46 @@ -# Copy these contents into the root directory of your Github project in a file -# named .travis.yml - -# Send notifications notifications: email: recipients: - J.T.Jeuring@uu.nl - - Bastiaan.Heeren@ou.nl - agerdes@me.com on_success: always on_failure: always -# Use new container infrastructure to enable caching -sudo: false - -# Choose a lightweight base image; we provide our own build tools. language: c +os: linux +dist: focal -# Caching so the next build will be fast too. -cache: - directories: - - $HOME/.ghc - - $HOME/.cabal - - $HOME/.stack - -# The different configurations we want to test. We have BUILD=cabal which uses -# cabal-install, and BUILD=stack which uses Stack. More documentation on each -# of those below. -# -# We set the compiler values here to tell Travis to use a different -# cache file per set of arguments. -# -# If you need to have different apt packages for each combination in the -# matrix, you can use a line such as: -# addons: {apt: {packages: [libfcgi-dev,libgmp-dev]}} matrix: include: - # We grab the appropriate GHC and cabal-install versions from hvr's PPA. See: - # https://github.com/hvr/multi-ghc-travis - #- env: BUILD=cabal GHCVER=7.0.4 CABALVER=1.16 HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC 7.0.4" - # addons: {apt: {packages: [cabal-install-1.16,ghc-7.0.4,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - #- env: BUILD=cabal GHCVER=7.2.2 CABALVER=1.16 HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC 7.2.2" - # addons: {apt: {packages: [cabal-install-1.16,ghc-7.2.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - #- env: BUILD=cabal GHCVER=7.4.2 CABALVER=1.16 HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC 7.4.2" - # addons: {apt: {packages: [cabal-install-1.16,ghc-7.4.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - #- env: BUILD=cabal GHCVER=7.6.3 CABALVER=1.16 HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC 7.6.3" - # addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - #- env: BUILD=cabal GHCVER=7.8.4 CABALVER=1.18 HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC 7.8.4" - # addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - #- env: BUILD=cabal GHCVER=7.10.3 CABALVER=1.22 HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC 7.10.3" - # addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - #- env: BUILD=cabal GHCVER=8.0.2 CABALVER=1.24 HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC 8.0.2" - # addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - #- env: BUILD=cabal GHCVER=8.2.2 CABALVER=2.0 HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC 8.2.2" - # addons: {apt: {packages: [cabal-install-2.0,ghc-8.2.2,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - - - env: BUILD=cabal GHCVER=8.4.2 CABALVER=2.2 - compiler: ": #GHC 8.4.2" - addons: {apt: {packages: [cabal-install-2.2,ghc-8.4.2], sources: [hvr-ghc]}} - - - env: BUILD=cabal GHCVER=8.6.5 CABALVER=2.4 - compiler: ": #GHC 8.6.5" - addons: {apt: {packages: [cabal-install-2.4,ghc-8.6.5], sources: [hvr-ghc]}} - - - env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 - compiler: ": #GHC 8.8.4" - addons: {apt: {packages: [cabal-install-2.4,ghc-8.8.4], sources: [hvr-ghc]}} - - # Build with the newest GHC and cabal-install. This is an accepted failure, - # see below. - - #- env: BUILD=cabal GHCVER=head CABALVER=head HAPPYVER=1.19.5 ALEXVER=3.1.7 - # compiler: ": #GHC HEAD" - # addons: {apt: {packages: [cabal-install-head,ghc-head,happy-1.19.5,alex-3.1.7], sources: [hvr-ghc]}} - - # The Stack builds. We can pass in arbitrary Stack arguments via the ARGS - # variable, such as using --stack-yaml to point to a different file. - #- env: BUILD=stack ARGS="" - #compiler: ": #stack default" - #addons: {apt: {packages: [ghc-7.10.3], sources: [hvr-ghc]}} - - #- env: BUILD=stack ARGS="--resolver lts-2" - #compiler: ": #stack 7.8.4" - #addons: {apt: {packages: [ghc-7.8.4], sources: [hvr-ghc]}} - - #- env: BUILD=stack ARGS="--resolver lts-3" - #compiler: ": #stack 7.10.2" - #addons: {apt: {packages: [ghc-7.10.2], sources: [hvr-ghc]}} - - #- env: BUILD=stack ARGS="--resolver lts-6" - # compiler: ": #stack 7.10.3" - # addons: {apt: {packages: [ghc-7.10.3], sources: [hvr-ghc]}} - - # Nightly builds are allowed to fail - #- env: BUILD=stack ARGS="--resolver nightly" - # compiler: ": #stack nightly" - # addons: {apt: {packages: [libgmp-dev]}} - - # Build on OS X in addition to Linux - #- env: BUILD=stack ARGS="" - #compiler: ": #stack default osx" - #os: osx + - env: GHCVER=9.6.7 + - env: GHCVER=9.10.3 + - env: GHCVER=9.12.4 - #- env: BUILD=stack ARGS="--resolver lts-2" - #compiler: ": #stack 7.8.4 osx" - #os: osx - - #- env: BUILD=stack ARGS="--resolver lts-3" - #compiler: ": #stack 7.10.2 osx" - #os: osx - - #- env: BUILD=stack ARGS="--resolver lts-6" - # compiler: ": #stack 7.10.3 osx" - # os: osx - - #- env: BUILD=stack ARGS="--resolver nightly" - #compiler: ": #stack nightly osx" - #os: osx - - allow_failures: - - env: BUILD=cabal GHCVER=8.8.4 CABALVER=2.4 - #- env: BUILD=cabal GHCVER=head CABALVER=head HAPPYVER=1.19.5 ALEXVER=3.1.7 - #- env: BUILD=stack ARGS="--resolver nightly" - #- env: BUILD=stack ARGS="--resolver lts-6" - #- env: BUILD=cabal GHCVER=8.6.5 +addons: + apt: + packages: + - libgmp-dev + - libsqlite3-dev +cache: + directories: + - $HOME/.cabal/store + - $HOME/.ghcup before_install: -# Using compiler above sets CC to an invalid value, so unset it -- unset CC - -# We want to always allow newer versions of packages when building on GHC HEAD -- CABALARGS="" -- if [ "x$GHCVER" = "xhead" ]; then CABALARGS=--allow-newer; fi - -# Download and unpack the stack executable -- export PATH=/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:$HOME/.local/bin:/opt/alex/$ALEXVER/bin:/opt/happy/$HAPPYVER/bin:$HOME/.cabal/bin:$PATH -- mkdir -p ~/.local/bin -- | - if [ `uname` = "Darwin" ] - then - travis_retry curl --insecure -L https://www.stackage.org/stack/osx-x86_64 | tar xz --strip-components=1 --include '*/stack' -C ~/.local/bin - else - travis_retry curl -L https://www.stackage.org/stack/linux-x86_64 | tar xz --wildcards --strip-components=1 -C ~/.local/bin '*/stack' - fi - - # Use the more reliable S3 mirror of Hackage - mkdir -p $HOME/.cabal - echo 'remote-repo: hackage.haskell.org:http://hackage.fpcomplete.com/' > $HOME/.cabal/config - echo 'remote-repo-cache: $HOME/.cabal/packages' >> $HOME/.cabal/config - - if [ "$CABALVER" != "1.16" ] - then - echo 'jobs: $ncpus' >> $HOME/.cabal/config - fi - -# Get the list of packages from the stack.yaml file -- PACKAGES=$(stack --install-ghc query locals | grep '^ *path' | sed 's@^ *path:@@') - -install: -- echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]" -- if [ -f configure.ac ]; then autoreconf -i; fi -- | - set -ex - case "$BUILD" in - stack) - stack --no-terminal --install-ghc $ARGS test --bench --only-dependencies - ;; - cabal) - cabal --version - travis_retry cabal update - cabal install --only-dependencies --enable-tests --enable-benchmarks --force-reinstalls --ghc-options=-O0 --reorder-goals --max-backjumps=-1 $CABALARGS $PACKAGES - ;; - esac - set +ex - -before_script: - - make revision + - export BOOTSTRAP_HASKELL_NONINTERACTIVE=1 + - export BOOTSTRAP_HASKELL_INSTALL_NO_STACK=1 + - export BOOTSTRAP_HASKELL_ADJUST_BASHRC=P + - curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh + - source "$HOME/.ghcup/env" + - ghcup install ghc "$GHCVER" + - ghcup set ghc "$GHCVER" + - ghcup install cabal 3.12.1.0 + - ghcup set cabal 3.12.1.0 + - cabal update script: -- | - set -ex - case "$BUILD" in - stack) - stack --no-terminal $ARGS test --bench --no-run-benchmarks --haddock --no-haddock-deps - ;; - cabal) - cabal install --enable-tests --enable-benchmarks --force-reinstalls --ghc-options=-O0 --reorder-goals --max-backjumps=-1 $CABALARGS $PACKAGES - - ORIGDIR=$(pwd) - for dir in $PACKAGES - do - cd $dir - cabal check || [ "$CABALVER" == "1.16" ] - cabal sdist - SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz && \ - (cd dist && cabal install --force-reinstalls "$SRC_TGZ") - cd $ORIGDIR - done - ;; - esac - set +ex + - ghc --version + - cabal --version + - cabal build all --enable-tests --enable-benchmarks + - cabal test all diff --git a/ideas.cabal b/ideas.cabal index abe4b703..e5dc2b43 100644 --- a/ideas.cabal +++ b/ideas.cabal @@ -28,7 +28,7 @@ stability: provisional extra-source-files: NOTICE.txt, CHANGELOG.txt build-type: Simple cabal-version: >= 1.8.0.2 -tested-with: GHC == 8.0.2, GHC == 8.2.2, GHC == 8.4.2 +tested-with: GHC == 9.6.7, GHC == 9.10.3, GHC == 9.12.4 source-repository head type: git @@ -49,7 +49,7 @@ Library ghc-options: -Wall hs-source-dirs: src Build-Depends: - base < 4.19, + base < 4.22, blaze-builder, bytestring, case-insensitive, From cff86e4372134fb2ead9f87d499cb4c84519d503 Mon Sep 17 00:00:00 2001 From: Alex Gerdes Date: Sat, 5 Sep 2026 17:07:56 +0200 Subject: [PATCH 57/57] Switch CI to GitHub Actions --- .github/workflows/ci.yml | 35 ++++++++++++++++++++++++++++++ .travis.yml | 46 ---------------------------------------- README.md | 2 +- 3 files changed, 36 insertions(+), 47 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..daaedd32 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,35 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + name: GHC ${{ matrix.ghc }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + ghc: [9.6.7, 9.10.3, 9.12.4] + + steps: + - uses: actions/checkout@v4 + - uses: haskell-actions/setup@v2 + with: + ghc-version: ${{ matrix.ghc }} + cabal-version: 3.12.1.0 + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install --yes libgmp-dev libsqlite3-dev + - uses: actions/cache@v4 + with: + path: ~/.cabal/store + key: ${{ runner.os }}-ghc-${{ matrix.ghc }}-${{ hashFiles('**/*.cabal') }} + - run: cabal build all --enable-tests --enable-benchmarks + - run: cabal test all diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 4d814345..00000000 --- a/.travis.yml +++ /dev/null @@ -1,46 +0,0 @@ -notifications: - email: - recipients: - - J.T.Jeuring@uu.nl - - agerdes@me.com - on_success: always - on_failure: always - -language: c -os: linux -dist: focal - -matrix: - include: - - env: GHCVER=9.6.7 - - env: GHCVER=9.10.3 - - env: GHCVER=9.12.4 - -addons: - apt: - packages: - - libgmp-dev - - libsqlite3-dev - -cache: - directories: - - $HOME/.cabal/store - - $HOME/.ghcup - -before_install: - - export BOOTSTRAP_HASKELL_NONINTERACTIVE=1 - - export BOOTSTRAP_HASKELL_INSTALL_NO_STACK=1 - - export BOOTSTRAP_HASKELL_ADJUST_BASHRC=P - - curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh - - source "$HOME/.ghcup/env" - - ghcup install ghc "$GHCVER" - - ghcup set ghc "$GHCVER" - - ghcup install cabal 3.12.1.0 - - ghcup set cabal 3.12.1.0 - - cabal update - -script: - - ghc --version - - cabal --version - - cabal build all --enable-tests --enable-benchmarks - - cabal test all diff --git a/README.md b/README.md index 071c312e..c0d391a6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # IDEAS -[![Build Status](https://travis-ci.org/ideas-edu/ideas.svg?branch=master)](https://travis-ci.org/ideas-edu/ideas) +[![CI](https://github.com/ideas-edu/ideas/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/ideas-edu/ideas/actions/workflows/ci.yml) ## Feedback services for intelligent tutoring systems