diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index 9406d9a..21d9547 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -3,6 +3,7 @@ autotool Bifunctor concat elems +FCase finalise fmap fmidue @@ -21,8 +22,14 @@ mempty mplus msum mzero +PApp +QName +QOp +QVar +scrutinee snd thd uncurry unlines +Utf yml diff --git a/.github/actions/spelling/patterns.txt b/.github/actions/spelling/patterns.txt index b7106d6..a7084b7 100644 --- a/.github/actions/spelling/patterns.txt +++ b/.github/actions/spelling/patterns.txt @@ -6,6 +6,8 @@ \b[Ll]og in to\b # acceptable duplicates +linebreak linebreak +False False # ls directory listings [-bcdlpsw](?:[-r][-w][-Ssx]){3}\s+\d+\s+\S+\s+\S+\s+\d+\s+ @@ -39,3 +41,4 @@ https?://[-+0-9a-zA-Z?&=_\/%.]* # marker to ignore all code on line ^.*-- no-spell-check$ +^.*# no-spell-check$ diff --git a/.hlint.yaml b/.hlint.yaml new file mode 100644 index 0000000..0c3bb35 --- /dev/null +++ b/.hlint.yaml @@ -0,0 +1,6 @@ +--- +# HLint configuration file +# https://github.com/ndmitchell/hlint +########################## + +- hint: {lhs: "maybe [] singleton", rhs: "maybeToList"} diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index 8a6da58..8d0a894 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -27,6 +27,7 @@ source-repository head library exposed-modules: + Haskell.Template.Detection.Maybe Haskell.Template.Match Haskell.Template.Task other-modules: @@ -39,9 +40,11 @@ library , aeson , base >=4.7 && <5 , bytestring + , containers , extra , file-embed , filepath + , haskell-names , haskell-src-exts , haskell-template-task-raw , hint @@ -60,6 +63,8 @@ test-suite haskell-template-task-test type: exitcode-stdio-1.0 main-is: Spec.hs other-modules: + Haskell.Template.ConfigSpec + Haskell.Template.GradingSpec Haskell.Template.MatchSpec Haskell.Template.TaskSpec Paths_haskell_template_task @@ -73,12 +78,14 @@ test-suite haskell-template-task-test , aeson , base >=4.7 && <5 , bytestring + , containers , deepseq , directory , exceptions , extra , file-embed , filepath + , haskell-names , haskell-src-exts , haskell-template-task , haskell-template-task-raw diff --git a/package.yaml b/package.yaml index 7c337de..d6128a1 100644 --- a/package.yaml +++ b/package.yaml @@ -35,6 +35,8 @@ dependencies: - wl-pprint-text - yaml - aeson + - containers + - haskell-names - transformers ghc-options: diff --git a/src/Haskell/Template/Detection/Maybe.hs b/src/Haskell/Template/Detection/Maybe.hs new file mode 100644 index 0000000..dd10690 --- /dev/null +++ b/src/Haskell/Template/Detection/Maybe.hs @@ -0,0 +1,155 @@ +module Haskell.Template.Detection.Maybe (collectIfsWithMaybeChecks) where + +import Control.Monad (void) +import Data.Data (Data) +import Data.Generics (everything, everywhere', listify, mkQ, mkT) +import Data.List.Extra (notNull) +import Data.Maybe (listToMaybe, mapMaybe, maybeToList) +import Data.Set (Set) +import qualified Data.Set as Set (empty, fromList, member, singleton, union) +import Language.Haskell.Exts ( + Alt (..), + Decl (..), + Exp (..), + FieldDecl (..), + Match (..), + Module (..), + ModuleName (..), + Name (..), + Pat (..), + QName (..), + QOp (..), + Rhs (..), + SrcSpanInfo, + ) +import Language.Haskell.Names (NameInfo (..), Scoped (..), symbolModule) + +collectIfsWithMaybeChecks :: Module (Scoped SrcSpanInfo) -> [(Exp (Scoped SrcSpanInfo), Exp ())] +collectIfsWithMaybeChecks (Module _ _ _ _ decls) = concat $ mapMaybe process decls + where + -- Imports are disregarded as no module (available to the students) exports a 'value'-named symbol. + -- This also assumes that the modules provided by the lecturer don't expose such a symbol. + moduleNames = + Set.fromList (mapMaybe declName decls) + `Set.union` recordFieldNames decls + + process d = do + let + allSymbols = moduleNames `Set.union` allNames d + freeName n + | Set.member n allSymbols = freeName (n ++ "'") + | otherwise = n + + pure $ everything (++) (mkQ [] (maybeToList . exprToIfInfo (freeName "value"))) d +collectIfsWithMaybeChecks _ = [] + +declName :: Decl a -> Maybe String +declName (FunBind _ ms) = listToMaybe $ map fromMatch ms + where + fromMatch (Match _ (Ident _ n) _ _ _) = n + fromMatch (Match _ (Symbol _ n) _ _ _) = n + fromMatch (InfixMatch _ _ (Ident _ n) _ _ _) = n + fromMatch (InfixMatch _ _ (Symbol _ n) _ _ _) = n +declName (PatBind _ (PVar _ pn) _ _) = Just $ fromName pn + where + fromName (Ident _ n) = n + fromName (Symbol _ n) = n +declName _ = Nothing + +exprToIfInfo :: String -> Exp (Scoped SrcSpanInfo) -> Maybe (Exp (Scoped SrcSpanInfo), Exp ()) +exprToIfInfo valueName expr@(If _ cond t e) = case removeParens cond of + (App _ (Var _ vn) maybeVal) + | hasName maybeMod "isJust" vn -> transform maybeVal t e + | hasName maybeMod "isNothing" vn -> transform maybeVal e t + (InfixApp _ l (QVarOp _ opName) r) -> case getMaybeVal l r of + Just maybeVal + | hasName eqMod "==" opName -> transform maybeVal e t + | hasName eqMod "/=" opName -> transform maybeVal t e + _ -> Nothing + _ -> Nothing + where + eqMod = Just "GHC.Classes" + maybeMod = Just "Data.Maybe" + isNothingExpression (Con _ vName) = hasName maybeMod "Nothing" vName + isNothingExpression _ = False + + getMaybeVal l r + | isNothingExpression l && isNothingExpression r = Nothing + | isNothingExpression l = Just r + | isNothingExpression r = Just l + | otherwise = Nothing + + transform mValExpr j n = case removeParens mValExpr of + mVal@(Var _ _) + | hasFromJust mVal j -> Just (expr, asCaseExpression valueName mVal j n) + | otherwise -> Nothing + _ -> Nothing +exprToIfInfo _ _ = Nothing + +allNames :: Data a => a -> Set String +allNames = everything Set.union $ mkQ Set.empty extract + where + extract :: Name (Scoped SrcSpanInfo) -> Set String + extract (Ident _ n) = Set.singleton n + extract (Symbol _ n) = Set.singleton n + +recordFieldNames :: Data a => a -> Set String +recordFieldNames = everything Set.union $ mkQ Set.empty extract + where + extract :: FieldDecl (Scoped SrcSpanInfo) -> Set String + extract (FieldDecl _ names _) = Set.fromList $ map nameToString names + + nameToString (Ident _ n) = n + nameToString (Symbol _ n) = n + +hasFromJust :: Exp (Scoped SrcSpanInfo) -> Exp (Scoped SrcSpanInfo) -> Bool +hasFromJust mExpr expr = notNull $ listify isFromJustApp expr + where + isFromJustApp :: Exp (Scoped SrcSpanInfo) -> Bool + isFromJustApp (App _ (Var _ vn) maybeVal) = + hasName (Just "Data.Maybe") "fromJust" vn && fmap void (removeParens maybeVal) == fmap void mExpr + isFromJustApp _ = False + +asCaseExpression + :: String + -> Exp (Scoped SrcSpanInfo) + -> Exp (Scoped SrcSpanInfo) + -> Exp (Scoped SrcSpanInfo) + -> Exp () +asCaseExpression valueName maybeValue justCase nothingCase = + Case + () + (void maybeValue) + [ Alt () (PApp () (UnQual () (Ident () "Nothing")) []) (UnGuardedRhs () $ void nothingCase) Nothing + , Alt + () + (PApp () (UnQual () (Ident () "Just")) [PVar () (Ident () valueName)]) + (UnGuardedRhs () $ replaceFromJustWithValue valueName maybeValue justCase) + Nothing + ] + +replaceFromJustWithValue :: String -> Exp (Scoped SrcSpanInfo) -> Exp (Scoped SrcSpanInfo) -> Exp () +replaceFromJustWithValue valueName maybeValue = void . everywhere' (mkT replace) + where + replace :: Exp (Scoped SrcSpanInfo) -> Exp (Scoped SrcSpanInfo) + replace expr = case removeParens expr of + App l (Var _ vn) fnBody + | hasName (Just "Data.Maybe") "fromJust" vn && fmap void (removeParens fnBody) == fmap void maybeValue -> + Var l (UnQual l (Ident l valueName)) + _ -> expr + +removeParens :: Exp a -> Exp a +removeParens (Paren _ e) = removeParens e +removeParens e = e + +hasName :: Maybe String -> String -> QName (Scoped l) -> Bool +hasName mModuleName qName (UnQual scope (Ident _ n)) = n == qName && isGloballyScopedInModule mModuleName scope +hasName mModuleName qName (Qual scope _ (Ident _ n)) = n == qName && isGloballyScopedInModule mModuleName scope +hasName mModuleName qName (UnQual scope (Symbol _ n)) = n == qName && isGloballyScopedInModule mModuleName scope +hasName mModuleName qName (Qual scope _ (Symbol _ n)) = n == qName && isGloballyScopedInModule mModuleName scope +hasName _ _ _ = False + +isGloballyScopedInModule :: Maybe String -> Scoped l -> Bool +isGloballyScopedInModule Nothing _ = True +isGloballyScopedInModule (Just modName) (Scoped (GlobalSymbol sym _) _) = symbolModule sym == ModuleName () modName +isGloballyScopedInModule (Just _) _ = False diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 5c3fd7e..b695b6b 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -28,6 +28,10 @@ module Haskell.Template.Task ( toSolutionConfigOpt, toMaybeSolutionConfig, unsafeTemplateSegment, + getMaybeFeedback, + FCaseOfWithMaybeConfig (..), + CaseOfWithMaybeConfigOpt, + Status (..), ) where import qualified Data.ByteString.Char8 as BS @@ -56,7 +60,7 @@ import Data.List ) import Data.List.Extra (genericTake, nubOrd, replace, takeEnd, takeWhileEnd) -import Data.Maybe (fromMaybe) +import Data.Maybe (fromJust, fromMaybe, isJust) import Data.Text.Lazy (pack) import Data.Typeable (Typeable) import Data.Yaml @@ -81,9 +85,11 @@ import System.FilePath ( ) import Test.HUnit (Counts (..)) import Text.PrettyPrint.Leijen.Text - (Doc, (<+>), empty, int, linebreak, nest, punctuate, text, vcat) + (Doc, (<+>), empty, int, linebreak, nest, punctuate, text, vcat, indent, (<$$>), enclose) import Text.Read (readMaybe) import Text.Regex.PCRE.Heavy (re, sub, (=~)) +import Language.Haskell.Names (loadBase, annotate) +import Haskell.Template.Detection.Maybe (collectIfsWithMaybeChecks) encode :: ToJSON a => a -> BS.ByteString encode = encodePretty $ setConfCompare compare defConfig @@ -95,6 +101,11 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], + detectOpportunitiesToUseCaseOfWithMaybe = + Just $ + (fromJust $ detectOpportunitiesToUseCaseOfWithMaybe defaultSolutionConfig) { + status = Just Hint + }, rigorousValidation = Just True } )) ++ [SI.i|\#\#\#\#\# parameter description: \# allowAdding - allow adding program parts; defaults to true @@ -111,12 +122,27 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { \# configGhcErrors - GHC warnings to enforce \# configGhcWarnings - GHC warnings to provide as hints \# configHlintSuggestionsLimit - caps amount of hlint suggestions to display; defaults to no cap -\# configHlintErrors - hlint hints to enforce, only first one encountered is displayed +\# configHlintErrors - hlint hints to enforce; only the first one encountered is displayed \# configHlintGroups - hlint extra hint groups to use; defaults to none \# configHlintRules - hlint extra hint rules to use; defaults to none \# configHlintSuggestions - hlint hints to provide as suggestions \# configLanguageExtensions - this sets LanguageExtensions for hlint as well; \# defaults to NPlusKPatterns + ScopedTypeVariables +\# +\# detectOpportunitiesToUseCaseOfWithMaybe - configuration for detection of opportunities to use +\# case-of expressions with Maybe values (instead of if-expressions); +\# this is part of the phase(s) including hlint checks +\# status - status of the checker; can be one of: +\# Ignore: disable the detection +\# Hint: display the opportunities (directly after hlint suggestions) but don't reject +\# Reject: reject the submission and show the first detection, but only if +\# no errors were reported by hlint, and then at that point +\# offerReplacement - whether to offer the replacement expression; +\# defaults to true if status is not set to Ignore, +\# otherwise is optional but can only be set to false +\# additionalMessage - potential message to show; defaults to no message, +\# and cannot be set to anything if status is set to Ignore +\# \# maxLineLength - submissions with lines longer than this value are rejected; defaults to no limit \# syntaxCutoff - determines the last step in the syntax phase (later steps are considered semantics); \# possible values (and also the order of steps): @@ -223,6 +249,56 @@ data FeedbackPhase | TestSuite deriving (Enum, Eq, Generic, Ord, Show, FromJSON, ToJSON) +data Status = Ignore | Hint | Reject + deriving (Eq, Generic, Show, FromJSON, ToJSON) + +data FCaseOfWithMaybeConfig m = CaseOfWithMaybeConfig { + status :: m Status, + offerReplacement :: m Bool, + additionalMessage :: m (Maybe String) + } deriving (Generic) + +type CaseOfWithMaybeConfigOpt = FCaseOfWithMaybeConfig Maybe + +deriving instance Show CaseOfWithMaybeConfigOpt +deriving instance ToJSON CaseOfWithMaybeConfigOpt + +instance FromJSON CaseOfWithMaybeConfigOpt where + parseJSON = genericParseJSON defaultOptions {rejectUnknownFields = True} + +type CaseOfWithMaybeConfig = FCaseOfWithMaybeConfig Identity + +deriving instance Show CaseOfWithMaybeConfig + +toCaseOfWithMaybeConfigOpt + :: CaseOfWithMaybeConfig + -> CaseOfWithMaybeConfigOpt +toCaseOfWithMaybeConfigOpt CaseOfWithMaybeConfig{..} = runIdentity $ + CaseOfWithMaybeConfig + <$> fmap Just status + <*> fmap Just offerReplacement + <*> fmap Just additionalMessage + +toMaybeCaseOfWithMaybeConfig + :: CaseOfWithMaybeConfigOpt + -> Maybe CaseOfWithMaybeConfig +toMaybeCaseOfWithMaybeConfig CaseOfWithMaybeConfig{..} = + CaseOfWithMaybeConfig + <$> fmap Identity status + <*> fmap Identity offerReplacement + <*> fmap Identity additionalMessage + +combineCaseOfWithMaybeConfigs + :: CaseOfWithMaybeConfigOpt + -> CaseOfWithMaybeConfigOpt + -> CaseOfWithMaybeConfigOpt +combineCaseOfWithMaybeConfigs x y = CaseOfWithMaybeConfig { + status = status x <|> status y, + -- automatically ignore default values when status was explicitly set to ignore + offerReplacement = offerReplacement x <|> (if status x == Just Ignore then Just False else offerReplacement y), + additionalMessage = additionalMessage x <|> (if status x == Just Ignore then Just Nothing else additionalMessage y) + } + data FSolutionConfig m = SolutionConfig { allowAdding :: m Bool, allowModifying :: m Bool, @@ -239,6 +315,7 @@ data FSolutionConfig m = SolutionConfig { configHlintRules :: m [String], configHlintSuggestions :: m [String], configLanguageExtensions :: m [String], + detectOpportunitiesToUseCaseOfWithMaybe :: m (FCaseOfWithMaybeConfig m), maxLineLength :: m (Maybe Natural), provideSampleSolution :: m Bool, messageOnCloningSampleSolution :: m (Maybe String), @@ -276,6 +353,11 @@ defaultSolutionConfig = SolutionConfig { configHlintRules = Just [], configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], + detectOpportunitiesToUseCaseOfWithMaybe = Just $ CaseOfWithMaybeConfig { + status = Nothing, + offerReplacement = Just True, + additionalMessage = Just Nothing + }, maxLineLength = Just Nothing, provideSampleSolution = Just False, messageOnCloningSampleSolution = Just Nothing, @@ -301,6 +383,7 @@ toSolutionConfigOpt SolutionConfig {..} = runIdentity $ SolutionConfig <*> fmap Just configHlintRules <*> fmap Just configHlintSuggestions <*> fmap Just configLanguageExtensions + <*> fmap (Just . toCaseOfWithMaybeConfigOpt) detectOpportunitiesToUseCaseOfWithMaybe <*> fmap Just maxLineLength <*> fmap Just provideSampleSolution <*> fmap Just messageOnCloningSampleSolution @@ -325,6 +408,7 @@ toMaybeSolutionConfig SolutionConfig{..} = SolutionConfig <*> fmap Identity configHlintRules <*> fmap Identity configHlintSuggestions <*> fmap Identity configLanguageExtensions + <*> fmap Identity (detectOpportunitiesToUseCaseOfWithMaybe >>= toMaybeCaseOfWithMaybeConfig) <*> fmap Identity maxLineLength <*> fmap Identity provideSampleSolution <*> fmap Identity messageOnCloningSampleSolution @@ -349,6 +433,10 @@ combineConfigs x y = SolutionConfig { configHlintRules = configHlintRules x <|> configHlintRules y, configHlintSuggestions = configHlintSuggestions x <|> configHlintSuggestions y, configLanguageExtensions = configLanguageExtensions x <|> configLanguageExtensions y, + detectOpportunitiesToUseCaseOfWithMaybe + = combineDetectOpportunitiesToUseCaseOfWithMaybe + (detectOpportunitiesToUseCaseOfWithMaybe x) + (detectOpportunitiesToUseCaseOfWithMaybe y), maxLineLength = maxLineLength x <|> maxLineLength y, provideSampleSolution = provideSampleSolution x <|> provideSampleSolution y, messageOnCloningSampleSolution = messageOnCloningSampleSolution x <|> messageOnCloningSampleSolution y, @@ -356,6 +444,11 @@ combineConfigs x y = SolutionConfig { rigorousValidation = rigorousValidation x <|> rigorousValidation y, syntaxCutoff = syntaxCutoff x <|> syntaxCutoff y } + where + combineDetectOpportunitiesToUseCaseOfWithMaybe (Just a) (Just b) + = Just $ combineCaseOfWithMaybeConfigs a b + combineDetectOpportunitiesToUseCaseOfWithMaybe Nothing b = b + combineDetectOpportunitiesToUseCaseOfWithMaybe a Nothing = a string :: String -> Doc string = text . pack @@ -370,6 +463,20 @@ check check reject inform path i = do checkUnsafe reject i (config@SolutionConfig{..}, exts, (m,s), ms) <- processConfig reject inform i + + let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe + case runIdentity $ status maybeDetectionConfig of + Ignore + | runIdentity $ offerReplacement maybeDetectionConfig -> + reject + $ "Cannot set 'offerReplacement' to true when 'status' is 'Ignore'" + <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." + | isJust (runIdentity $ additionalMessage maybeDetectionConfig) -> + reject + $ "Cannot set an 'additionalMessage' when 'status' is 'Ignore'" + <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." + _ -> pure () + checkUniqueness (m : map fst ms) inform $ string $ "Parsing template module " <> m void $ parse reject exts s @@ -575,6 +682,27 @@ getHlintFeedback documentInfo config dir file selectHints = case hints of hlintFeedback feedbackIdeas = hintLimit [documentInfo $ string $ editFeedback $ show comment | comment <- feedbackIdeas] +getMaybeFeedback + :: MonadIO m + => (Doc -> m a) + -> CaseOfWithMaybeConfig + -> [E.Extension] + -> E.Module E.SrcSpanInfo + -> m [a] +getMaybeFeedback documentInfo CaseOfWithMaybeConfig{..} exts (E.Module l mHead pragmas imports decls) = do + env <- liftIO loadBase + let newPragmas = E.LanguagePragma l (map (E.Ident l . E.prettyExtension) exts) : pragmas + let ast = E.Module l mHead newPragmas imports decls + sequence $ flip map (collectIfsWithMaybeChecks (annotate env ast)) $ \(foundIf,caseReplacement) -> + documentInfo $ vcat + [ string "Found:" <$$> indent 2 (text $ pack $ E.prettyPrint foundIf) + , if runIdentity offerReplacement + then string "Perhaps:" <$$> indent 2 (text $ pack $ E.prettyPrint caseReplacement) + else empty + , maybe empty (enclose linebreak linebreak . string) $ runIdentity additionalMessage + ] +getMaybeFeedback _ _ _ _ = error "unexpected Module type at getMaybeFeedback" + editFeedback :: String -> String editFeedback xs = case elemIndex ':' xs of Just index -> @@ -975,8 +1103,13 @@ testPhases reject inform template submissionFile modules config exts submission -- Reject if GHC warnings configured as errors are triggered by submission. lift $ compileWithArgsAndCheck dirname reject rejectWithHint config noTest configGhcErrors , + do -- Reject if HLint warnings configured as errors are triggered by submission. lift $ void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors + + -- Reject if checks on maybe values encounter a hit and were configured to reject. + when (Reject == runIdentity (status maybeDetectionConfig)) $ + get >>= lift . void . getMaybeFeedback rejectWithHint maybeDetectionConfig exts , -- Reject on task template violations according to settings (modifying, adding, deleting). get >>= lift . matchTemplate reject config 2 exts template submission @@ -992,8 +1125,13 @@ testPhases reject inform template submissionFile modules config exts submission -- Displays HLint suggestions configured as non-errors triggered by submission. lift $ void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions + + -- Display suggestions involving checks on maybe values if configured as hints. + when (Hint == runIdentity (status maybeDetectionConfig)) $ + get >>= lift . void . getMaybeFeedback inform maybeDetectionConfig exts ] where + maybeDetectionConfig = runIdentity $ detectOpportunitiesToUseCaseOfWithMaybe config noTest = delete "Test" modules rejectWithHint = rejectWithMessage reject rejectHint diff --git a/stack.yaml b/stack.yaml index ceaaecf..f87719a 100644 --- a/stack.yaml +++ b/stack.yaml @@ -10,3 +10,4 @@ extra-deps: - git: https://github.com/owestphal/type-match commit: e1afab43d2e8bfa5e2006492ed34060036e7be51 - raw + - haskell-names-0.9.9.1@sha256:79bb41850a7832543731bdbcaf7aace6ddfe121d78656c3c8b184c9ebf36ea18,12681 diff --git a/test/Haskell/Template/ConfigSpec.hs b/test/Haskell/Template/ConfigSpec.hs new file mode 100644 index 0000000..1b01163 --- /dev/null +++ b/test/Haskell/Template/ConfigSpec.hs @@ -0,0 +1,180 @@ +{-# LANGUAGE QuasiQuotes #-} +{-# LANGUAGE ScopedTypeVariables #-} + +module Haskell.Template.ConfigSpec where + +import Control.Exception (IOException, try) +import Control.Monad.Identity (Identity (Identity)) +import Data.Aeson (ToJSON) +import Data.Either (isRight) +import Data.IORef (modifyIORef, newIORef, readIORef) +import Data.List (isInfixOf, isPrefixOf) +import Data.Text (unpack) +import Data.Text.Encoding (decodeUtf8Lenient) +import Data.Yaml.Pretty (defConfig, encodePretty, setConfCompare) +import Haskell.Template.Task ( + FCaseOfWithMaybeConfig (..), + FSolutionConfig (..), + SolutionConfigOpt, + Status (..), + check, + defaultCode, + defaultSolutionConfig, + ) +import System.IO.Temp (withSystemTempDirectory) +import Test.Hspec (Spec, describe, it, shouldSatisfy) + +import Data.Either.Extra (mapLeft) +import Data.Maybe (fromMaybe) +import qualified Data.String.Interpolate as SI (i) + +adjustedDefaultConfig :: SolutionConfigOpt +adjustedDefaultConfig = + defaultSolutionConfig { + addCodeWorldRenderButton = Just False + , configGhcErrors = Just [] + , configGhcWarnings = Just [] + , configHlintErrors = Just [] + , configHlintSuggestions = Just [] + , rigorousValidation = Just False + , detectOpportunitiesToUseCaseOfWithMaybe = Nothing + } + +encode :: ToJSON a => a -> Maybe String -> String +encode doc override = encodedConfig ++ "\n" ++ fromMaybe "" override ++ "\n" ++ defaultCodeModules + where + encodedConfig = unpack $ decodeUtf8Lenient $ encodePretty (setConfCompare compare defConfig) doc + defaultCodeModules = unlines $ dropWhile (not . isPrefixOf "---") (lines defaultCode) + +evaluateCheck :: String -> IO (Either String (), [String]) +evaluateCheck configString = withSystemTempDirectory "haskell-template-task" $ \dir -> do + ref <- newIORef id + + let updateInform doc = modifyIORef ref (\is -> is . (show doc :)) + + result <- try (check (fail . show) updateInform dir configString) :: IO (Either IOException ()) + + infos <- readIORef ref + + pure (mapLeft show result, infos []) + +spec :: Spec +spec = describe "Task config" $ do + describe "detectOpportunitiesToUseCaseOfWithMaybe" $ do + it "should reject config where status is not specified" $ do + result <- + evaluateCheck + $ flip encode Nothing + $ adjustedDefaultConfig { + detectOpportunitiesToUseCaseOfWithMaybe = detectOpportunitiesToUseCaseOfWithMaybe defaultSolutionConfig + } + + result `shouldSatisfy` \(mRejection, _) -> case mRejection of + Right () -> False + Left errorMsg -> "There is a required configuration parameter missing" `isInfixOf` errorMsg + it "provides default values for 'offerReplacement' and 'additionalMessage'" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + status: Reject +|] + + let expectedConfig = CaseOfWithMaybeConfig (Identity Reject) (Identity True) (Identity Nothing) + + result `shouldSatisfy` \(mRejection, infos) -> + isRight mRejection && any (isInfixOf (show expectedConfig)) infos + it "should not allow to provide offerReplacement without setting status" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + offerReplacement: false +|] + result `shouldSatisfy` \(mRejection, _) -> case mRejection of + Right () -> False + Left errorMsg -> "There is a required configuration parameter missing" `isInfixOf` errorMsg + it "should not allow to provide additionalMessage without setting status" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + additionalMessage: "hello world" +|] + result `shouldSatisfy` \(mRejection, _) -> case mRejection of + Right () -> False + Left errorMsg -> "There is a required configuration parameter missing" `isInfixOf` errorMsg + it "should prefer explicit value over default" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + status: Reject + offerReplacement: false +|] + + let expectedConfig = CaseOfWithMaybeConfig (Identity Reject) (Identity False) (Identity Nothing) + + result `shouldSatisfy` \(mRejection, infos) -> + isRight mRejection && any (isInfixOf (show expectedConfig)) infos + it "should correctly handle explicit Ignore status without other overrides" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + status: Ignore +|] + + let expectedConfig = CaseOfWithMaybeConfig (Identity Ignore) (Identity False) (Identity Nothing) + + result `shouldSatisfy` \(mRejection, infos) -> + isRight mRejection && any (isInfixOf (show expectedConfig)) infos + it "should not allow to set offerReplacement to true when status is set to Ignore" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + status: Ignore + offerReplacement: true +|] + result `shouldSatisfy` \(mRejection, _) -> case mRejection of + Right () -> False + Left errorMsg -> "Cannot set 'offerReplacement' to true when 'status' is 'Ignore'" `isInfixOf` errorMsg + it "should not allow to provide an additionalMessage when status is set to Ignore" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + status: Ignore + additionalMessage: "hello world" +|] + result `shouldSatisfy` \(mRejection, _) -> case mRejection of + Right () -> False + Left errorMsg -> "Cannot set an 'additionalMessage' when 'status' is 'Ignore'" `isInfixOf` errorMsg + it "should reject config with misspelled field" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + status: Hint + aditionalMessage: "hello world" \# no-spell-check +|] + result `shouldSatisfy` \(mRejection, _) -> case mRejection of + Right () -> False + Left errorMsg -> "unknown fields: [\\\"aditionalMessage\\\"]" `isInfixOf` errorMsg -- no-spell-check diff --git a/test/Haskell/Template/GradingSpec.hs b/test/Haskell/Template/GradingSpec.hs new file mode 100644 index 0000000..4fe237d --- /dev/null +++ b/test/Haskell/Template/GradingSpec.hs @@ -0,0 +1,226 @@ +{-# LANGUAGE QuasiQuotes #-} + +module Haskell.Template.GradingSpec where + +import Control.Exception (IOException, try) +import Data.Aeson (ToJSON) +import Data.Either.Extra (isRight, mapLeft) +import Data.IORef (modifyIORef, newIORef, readIORef) +import Data.List (isInfixOf, isPrefixOf) +import Data.Maybe (fromMaybe) +import qualified Data.String.Interpolate as SI (i) +import Data.Text (unpack) +import Data.Text.Encoding (decodeUtf8Lenient) +import Data.Yaml.Pretty (defConfig, encodePretty, setConfCompare) +import Haskell.Template.Task ( + FCaseOfWithMaybeConfig (..), + FSolutionConfig (..), + SolutionConfigOpt, + Status (..), + defaultCode, + defaultSolutionConfig, + grade, + ) +import System.IO.Temp (withSystemTempDirectory) +import Test.Hspec (Spec, describe, it, shouldSatisfy) + +adjustedDefaultConfig :: SolutionConfigOpt +adjustedDefaultConfig = + defaultSolutionConfig { + addCodeWorldRenderButton = Just False + , configGhcErrors = Just [] + , configGhcWarnings = Just [] + , configHlintErrors = Just [] + , configHlintSuggestions = Just [] + , rigorousValidation = Just False + , detectOpportunitiesToUseCaseOfWithMaybe = + Just $ + CaseOfWithMaybeConfig { + status = Just Ignore + , offerReplacement = Just False + , additionalMessage = Just Nothing + } + } + +encode :: ToJSON a => a -> Maybe String -> String +encode doc override = + encodeConfig doc ++ "\n" ++ fromMaybe "" override ++ "\n" ++ defaultCodeModules + where + defaultCodeModules = unlines $ dropWhile (not . isPrefixOf "---") (lines defaultCode) + +encodeConfig :: ToJSON a => a -> String +encodeConfig = unpack . decodeUtf8Lenient . encodePretty (setConfCompare compare defConfig) + +maybeTaskConfig :: Status -> String +maybeTaskConfig maybeStatus = + encodeConfig (maybeConfig maybeStatus) + ++ [SI.i| +--- +module Solution where + +import Prelude +import Data.Maybe +import Test.HUnit (Test (..), assertFailure) + +value :: Maybe Int -> Int +value mVal = undefined + +test :: [Test] +test = undefined +--- +module SampleSolution where + +import Prelude +import Data.Maybe +import Test.HUnit (Test (..), assertFailure) + +value :: Maybe Int -> Int +value mVal = if isJust mVal then fromJust mVal else 0 + +test :: [Test] +test = [] +|] + +maybeConfig :: Status -> SolutionConfigOpt +maybeConfig maybeStatus = + adjustedDefaultConfig { + detectOpportunitiesToUseCaseOfWithMaybe = + Just $ + CaseOfWithMaybeConfig { + status = Just maybeStatus + , offerReplacement = Just $ case maybeStatus of + Ignore -> False + _ -> True + , additionalMessage = Just Nothing + } + } + +maybeModule :: String -> String +maybeModule testBody = + [SI.i|module Solution where +import Prelude +import Data.Maybe +import Test.HUnit (Test (..), assertFailure) + +value :: Maybe Int -> Int +value mVal = if isJust mVal then fromJust mVal else 0 + +test :: [Test] +test = #{testBody}|] + +evaluateGrade :: String -> String -> IO (Either String Bool, [String]) +evaluateGrade configString submission = withSystemTempDirectory "haskell-template-task" $ \dir -> do + ref <- newIORef id + + let updateInform doc = modifyIORef ref (\is -> is . (show doc :)) + + result <- try (grade id id (fail . show) updateInform dir configString submission) :: IO (Either IOException Bool) + + infos <- readIORef ref + + pure (mapLeft show result, infos []) + +spec :: Spec +spec = describe "Grading" $ do + it "doesn't parse the submission when syntaxCutoff is set to 'CodeWidth' and disableSemantics is true" $ do + result <- + evaluateGrade + (encode adjustedDefaultConfig $ Just $ unlines ["syntaxCutoff: CodeWidth", "disableSemantics: true"]) + [SI.i|module Main where + +main :: +|] + + result `shouldSatisfy` \(mResult, _) -> isRight mResult + it "parses the submission" $ do + result <- + evaluateGrade + (encode adjustedDefaultConfig Nothing) + [SI.i|module Main where + +main :: +|] + + result `shouldSatisfy` \(mResult, _) -> case mResult of + Left err -> "your submission is no Haskell program" `isInfixOf` err + Right _ -> False + it "provides maybe suggestions when configured" $ do + let source = maybeModule "[]" + result <- evaluateGrade (maybeTaskConfig Hint) source + + result `shouldSatisfy` \(mResult, infos) -> + isRight mResult + && any + ( \info -> + "Perhaps:" `isInfixOf` info + && "case mVal of" `isInfixOf` info + ) + infos + it "doesn't provide maybe suggestions when configured to Ignore" $ do + let source = maybeModule "[]" + result <- evaluateGrade (maybeTaskConfig Ignore) source + + result `shouldSatisfy` \(mResult, infos) -> + isRight mResult + && not + ( any + ( \info -> + "Found:" `isInfixOf` info || "Perhaps:" `isInfixOf` info + ) + infos + ) + it "rejects maybe checks before running further checks when configured to Reject" $ do + let source = maybeModule "[TestCase (assertFailure \"later test ran\")]" + result <- evaluateGrade (maybeTaskConfig Reject) source + + result `shouldSatisfy` \(mResult, _) -> case mResult of + Left err -> + "Found:" `isInfixOf` err + && not ("later test ran" `isInfixOf` err) + Right _ -> False + it "respects default language extensions" $ do + let settings = encodeConfig ((maybeConfig Hint) {configLanguageExtensions = Just ["NoImplicitPrelude"]}) + let taskConfig = + [SI.i|#{settings} +--- +module Solution where +import Data.Maybe +import Test.HUnit (Test (..), assertFailure) +import Helper + +value mVal = undefined + +test :: [Test] +test = undefined +--- +module SampleSolution where +import Data.Maybe +import Test.HUnit (Test (..), assertFailure) +import Helper + +value mVal = if isJust mVal then fromJust mVal else 0 + +test :: [Test] +test = [] +--- +module Helper where +import Prelude (Bool (..)) + +(/=) :: a -> a -> Bool +_ /= _ = False +|] + + let source = + [SI.i|module Solution where +import Data.Maybe +import Test.HUnit (Test (..), assertFailure) +import Helper + +value mVal = if mVal /= Nothing then fromJust mVal else 0 + +test :: [Test] +test = []|] + + result <- evaluateGrade taskConfig source + + result `shouldSatisfy` \(mResult, infos) -> isRight mResult && null infos diff --git a/test/Haskell/Template/MatchSpec.hs b/test/Haskell/Template/MatchSpec.hs index 1694865..124d31b 100644 --- a/test/Haskell/Template/MatchSpec.hs +++ b/test/Haskell/Template/MatchSpec.hs @@ -28,6 +28,11 @@ completedDefaultSolutionConfig = configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], + detectOpportunitiesToUseCaseOfWithMaybe = Just $ CaseOfWithMaybeConfig { + status = Just Hint, + offerReplacement = Just True, + additionalMessage = Just Nothing + }, rigorousValidation = Just True } withAdding :: SolutionConfig diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 84d2e26..3599fc7 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -1,4 +1,5 @@ {-# LANGUAGE QuasiQuotes #-} +{-# LANGUAGE NamedFieldPuns #-} module Haskell.Template.TaskSpec where import qualified Data.ByteString.Char8 as BS (unpack) @@ -15,7 +16,7 @@ import Control.Monad.Catch ( ) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Writer (runWriterT, tell) -import Data.Functor.Identity (Identity) +import Data.Functor.Identity (Identity (..)) import Data.List (intercalate, isPrefixOf) import Data.List.Extra (split) import Data.Maybe (fromJust) @@ -40,6 +41,11 @@ defaultConfig = fromJust $ toMaybeSolutionConfig configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], + detectOpportunitiesToUseCaseOfWithMaybe = Just $ CaseOfWithMaybeConfig { + status = Just Hint, + offerReplacement = Just True, + additionalMessage = Just Nothing + }, provideSampleSolution = Just True, rigorousValidation = Just True } ) @@ -79,6 +85,349 @@ spec = do it "allows specifying fixity" $ hlintIO dilatedWithFixity useDilated errorP configHlintErrors `shouldReturn` [Left "Warning: Use dilated"] + describe "maybe feedback" $ do + it "should suggest replacing if with case-of when applicable (isNothing)" $ do + result <- maybeCheckIO False False (Just "Is there maybe a better way to express this?") [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if isNothing mVal then -3 else fromJust mVal|] + + result `shouldBe` [ + [SI.i|Found: + if isNothing mVal then -3 else fromJust mVal + +Is there maybe a better way to express this? +|] + ] + it "should suggest replacing if with case-of when applicable (== Nothing)" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if mVal == Nothing then -3 else fromJust mVal|] + + length result `shouldBe` 1 + it "should suggest replacing if with case-of when applicable (/= Nothing)" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if mVal /= Nothing then fromJust mVal else -3|] + + length result `shouldBe` 1 + it "should suggest replacing if with case-of when applicable (isJust)" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if isJust mVal then fromJust mVal else -3|] + + length result `shouldBe` 1 + it "should not suggest replacing if with case-of when condition is mixed" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if isJust mVal && True then fromJust mVal else -3|] + + length result `shouldBe` 0 + it "should not suggest replacing if with case-of when condition is comparison with Just value" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if mVal == Just 5 then fromJust mVal else -3|] + + length result `shouldBe` 0 + it "should not suggest replacing if with case-of when value is not used" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if isJust mVal then 5 else -3|] + + length result `shouldBe` 0 + it "replacement should not introduce variable names that are already used or will be used later" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def mVal = let value = -3 in if isJust mVal then fromJust mVal else value + + def2 mVal = if isJust mVal then let value = 5 in fromJust mVal else -3 + + def3 mVal = if isJust mVal then fromJust mVal * value else 0 + where value = 17 + + def4 val = case val of + [value] -> if isJust value then 2 * fromJust value else -1 + _ -> 0 + + def5 mVal f = if isJust mVal then f (\\value -> fromJust mVal value) else undefined + + def6 mVal x = if isJust mVal then 2 - fromJust mVal else process x + where + process value = 3 * abs value + + def7 mVal xs = if isJust mVal then [fromJust mVal value | value <- xs] else xs + + def8 mVal xs = if isJust mVal + then do + value <- xs + pure $ fromJust mVal value + else xs + |] + + result `shouldBe` [ + [SI.i|Found: + if isJust mVal then fromJust mVal else value +Perhaps: + case mVal of + Nothing -> value + Just value' -> value'|], + [SI.i|Found: + if isJust mVal then let value = 5 in fromJust mVal else -3 +Perhaps: + case mVal of + Nothing -> -3 + Just value' -> let value = 5 in value'|], + [SI.i|Found: + if isJust mVal then fromJust mVal * value else 0 +Perhaps: + case mVal of + Nothing -> 0 + Just value' -> value' * value|], + [SI.i|Found: + if isJust value then 2 * fromJust value else -1 +Perhaps: + case value of + Nothing -> -1 + Just value' -> 2 * value'|], + [SI.i|Found: + if isJust mVal then f (\\ value -> fromJust mVal value) else + undefined +Perhaps: + case mVal of + Nothing -> undefined + Just value' -> f (\\ value -> value' value)|], + [SI.i|Found: + if isJust mVal then 2 - fromJust mVal else process x +Perhaps: + case mVal of + Nothing -> process x + Just value' -> 2 - value'|], + [SI.i|Found: + if isJust mVal then [fromJust mVal value | value <- xs] else xs +Perhaps: + case mVal of + Nothing -> xs + Just value' -> [value' value | value <- xs]|], + [SI.i|Found: + if isJust mVal then + do value <- xs + pure $ fromJust mVal value + else xs +Perhaps: + case mVal of + Nothing -> xs + Just value' -> do value <- xs + pure $ value' value|] + ] + it "replacement should avoid record field names" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + data Record = Record { value :: Int } + + def mVal = if isJust mVal then fromJust mVal else 0 + |] + + result `shouldBe` [[SI.i|Found: + if isJust mVal then fromJust mVal else 0 +Perhaps: + case mVal of + Nothing -> 0 + Just value' -> value'|]] + it "should suggest replacement even when nested" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Maybe Int -> Int + def mVal1 mVal2 = if isJust mVal1 then fromJust mVal1 + if isJust mVal2 then 2 * fromJust mVal2 else 0 else -1|] + + result `shouldBe` [ + [SI.i|Found: + if isJust mVal1 then + fromJust mVal1 + if isJust mVal2 then 2 * fromJust mVal2 else 0 + else -1 +Perhaps: + case mVal1 of + Nothing -> -1 + Just value -> value + + if isJust mVal2 then 2 * fromJust mVal2 else 0|], + [SI.i|Found: + if isJust mVal2 then 2 * fromJust mVal2 else 0 +Perhaps: + case mVal2 of + Nothing -> 0 + Just value -> 2 * value|] + ] + it "should not suggest replacing if with case-of when isJust, fromJust, etc. are not from Data.Maybe" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if isJust mVal then fromJust mVal else -3 + where isJust _ = False + + def2 :: Maybe Int -> Int + def2 mVal = if isJust mVal then fromJust mVal else -3 + where fromJust _ = 99 + + def3 :: Maybe Int -> Int + def3 mVal = if mVal /= Nothing then fromJust mVal else -3 + where (/=) _ _ = True|] + + length result `shouldBe` 0 + it "should not suggest replacing if with case-of when scrutinee is not a variable" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: a -> (a -> Maybe Int) -> Int + def val f = if isJust (f val) then fromJust (f val) else -3|] + + length result `shouldBe` 0 + it "should not suggest replacing if with case-of when fromJust is used on shadowed maybe value" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if isJust mVal then let mVal = Just 99 in fromJust mVal else -3|] + + length result `shouldBe` 0 + it "replacement should not use redundant brackets" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = if (isJust (mVal)) then 1 + (fromJust ((mVal))) else -3|] + + result `shouldBe` [ + [SI.i|Found: + if (isJust (mVal)) then 1 + (fromJust ((mVal))) else -3 +Perhaps: + case mVal of + Nothing -> -3 + Just value -> 1 + value|] + ] + it "replacement should not replace unrelated fromJust expressions" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def m = if isJust m then fromJust m + (let m = Just 99 in fromJust m) else 0|] + + result `shouldBe` [ + [SI.i|Found: + if isJust m then fromJust m + (let m = Just 99 in fromJust m) else + 0 +Perhaps: + case m of + Nothing -> 0 + Just value -> value + (let m = Just 99 in fromJust m)|] + ] + it "replacement should not replace shadowed fromJust call" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + + def :: Maybe Int -> Int + def m = if isJust m then fromJust m + (let fromJust x = 99 in fromJust m) else 0|] + + result `shouldBe` [ + [SI.i|Found: + if isJust m then fromJust m + (let fromJust x = 99 in fromJust m) + else 0 +Perhaps: + case m of + Nothing -> 0 + Just value -> value + (let fromJust x = 99 in fromJust m)|] + ] + it "doesn't get misled by qualified imports" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import qualified SomeModule as Data.Maybe + + def :: Maybe Int -> Int + def m = if Data.Maybe.isJust m then Data.Maybe.fromJust m else 0|] + + result `shouldBe` [] + describe "documented edge cases where the current detection goes off track" $ do + it "it suggests replacement even though Maybe constructors are not in scope" $ do + result <- maybeCheckIO False True Nothing [SI.i| + {-\# LANGUAGE NoImplicitPrelude \#-} + module Solution where + import Data.Maybe (isJust, fromJust) + + def m = if isJust m then fromJust m else 0|] + + result `shouldBe` [ + [SI.i|Found: + if isJust m then fromJust m else 0 +Perhaps: + case m of + Nothing -> 0 + Just value -> value|] + ] + it "replacement doesn't use qualified constructor names" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Prelude (Int) + import qualified Data.Maybe as M (Maybe (..), isJust, fromJust) + + def :: M.Maybe Int -> Int + def m = if M.isJust m then M.fromJust m else 0|] + + result `shouldBe` [ + [SI.i|Found: + if M.isJust m then M.fromJust m else 0 +Perhaps: + case m of + Nothing -> 0 + Just value -> value|] + ] + it "replacement doesn't take imports into account" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Solution where + import Data.Maybe + import Helper (value) + + def :: Maybe Int -> Int + def m = if isJust m then fromJust m else 0|] + + result `shouldBe` [ + [SI.i|Found: + if isJust m then fromJust m else 0 +Perhaps: + case m of + Nothing -> 0 + Just value -> value|] + ] describe "grade" $ do it "is running" $ gradeIO completedDefaultCode useImport `shouldReturn` "" @@ -271,6 +620,16 @@ hlintIO config content display selectHints = do firstLineOf (y:ys) = y : firstLineOf ys firstLineOf [] = [] +maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] +maybeCheckIO asError offerReplacement additionalMessage code = do + codeAST <- parse (fail . show) [] code + let config = CaseOfWithMaybeConfig { + status = Identity $ if asError then Reject else Hint, + offerReplacement = Identity offerReplacement, + additionalMessage = Identity additionalMessage + } + getMaybeFeedback (pure . show) config [] codeAST + render :: PP.Doc -> String render = unpack . PP.displayT . PP.renderPretty 1.0 100