From 71bb26588df04e4253a68d5960981c8caa1866a5 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:21:09 +0000 Subject: [PATCH 01/99] suggest replacing if statements with maybe checks with case-of expression --- src/Haskell/Template/Match.hs | 66 +++++++++++++++++++++++++++++-- src/Haskell/Template/Task.hs | 41 ++++++++++++++++--- test/Haskell/Template/TaskSpec.hs | 57 ++++++++++++++++++++++++++ 3 files changed, 156 insertions(+), 8 deletions(-) diff --git a/src/Haskell/Template/Match.hs b/src/Haskell/Template/Match.hs index 44a71aa..64cff2d 100644 --- a/src/Haskell/Template/Match.hs +++ b/src/Haskell/Template/Match.hs @@ -23,9 +23,20 @@ import Control.Monad ( ) import Control.Monad.State (State, evalState, gets, put) import Data.Function (on) -import Data.Generics - (Data (..), GenericM, GenericM' (..), GenericQ, cast, gfoldlAccum, gmapQ) -import Data.List (insertBy) +import Data.Generics ( + Data (..), + GenericM, + GenericM' (..), + GenericQ, + cast, + gfoldlAccum, + gmapQ, + everything, + mkQ, + everywhere, + mkT, + ) +import Data.List (insertBy, singleton) import Data.Maybe (isJust) import Language.Haskell.Exts.Syntax @@ -328,6 +339,55 @@ test m1 m2 = -- ParseOk m1' = parseModule m1 -- ParseOk m2' = parseModule m2 evalState (runM (matchModule m1 m2)) $ SrcSpanInfoPair CompleteModule S.noSrcSpan S.noSrcSpan + +collectIfsWithMaybeChecks :: Module S.SrcSpanInfo -> [(Exp S.SrcSpanInfo, Exp ())] +collectIfsWithMaybeChecks = everything (++) $ mkQ [] (maybe [] singleton . exprToIfInfo) + +exprToIfInfo :: Exp S.SrcSpanInfo -> Maybe (Exp S.SrcSpanInfo, Exp ()) +exprToIfInfo expr@(If _ cond t e) = case removeParens cond of + (App _ (Var _ vn) maybeVal) + | hasName "isJust" vn -> Just (expr,asCaseExpression maybeVal t e) + | hasName "isNothing" vn -> Just (expr,asCaseExpression maybeVal e t) + (InfixApp _ l (QVarOp _ opName) r) + | hasName "==" opName -> (\maybeVal -> (expr, asCaseExpression maybeVal e t)) <$> getMaybeVal l r + | hasName "/=" opName -> (\maybeVal -> (expr, asCaseExpression maybeVal t e)) <$> getMaybeVal l r + _ -> Nothing + where + isNothingExpression (Con _ vName) = hasName "Nothing" vName + isNothingExpression _ = False + + getMaybeVal l r + | isNothingExpression l && isNothingExpression r = Nothing + | isNothingExpression l = Just r + | isNothingExpression r = Just l + | otherwise = Nothing +exprToIfInfo _ = Nothing + +asCaseExpression :: Exp a -> Exp a -> Exp a -> Exp () +asCaseExpression maybeValue justCase nothingCase = Case () (void maybeValue) + [ Alt () (PApp () (UnQual () (Ident () "Nothing")) []) (UnGuardedRhs () $ void nothingCase) Nothing + , Alt () (PApp () (UnQual () (Ident () "Just")) [PVar () (Ident () "value")]) + (UnGuardedRhs () $ replaceFromJustWithValue (void maybeValue) (void justCase)) Nothing + ] + +replaceFromJustWithValue :: Exp () -> Exp () -> Exp () +replaceFromJustWithValue maybeValue = everywhere $ mkT replace + where + replace (App () (Var () (UnQual _ (Ident () "fromJust"))) fnBody) + | fnBody == maybeValue = Var () (UnQual () (Ident () "value")) + replace expr = expr + +removeParens :: Exp a -> Exp a +removeParens (Paren _ e) = removeParens e +removeParens e = e + +hasName :: String -> QName l -> Bool +hasName qName (UnQual _ (Ident _ n)) = n == qName +hasName qName (Qual _ _ (Ident _ n)) = n == qName +hasName qName (UnQual _ (Symbol _ n)) = n == qName +hasName qName (Qual _ _ (Symbol _ n)) = n == qName +hasName _ _ = False + ------------------------------------------------------------------------------ -- | Twin map for monadic transformation -- diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 92eae96..f768251 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -28,6 +28,7 @@ module Haskell.Template.Task ( toSolutionConfigOpt, toMaybeSolutionConfig, unsafeTemplateSegment, + getMaybeFeedback, ) where import qualified Data.ByteString.Char8 as BS @@ -38,7 +39,7 @@ import qualified Data.String.Interpolate as SI (i, iii) import Haskell.Template.FileContents (testHelperContents, testHarnessContents) import Haskell.Template.Match - (Location (..), Result (..), What (..), Where (..), highlight_ssi) + (Location (..), Result (..), What (..), Where (..), highlight_ssi, collectIfsWithMaybeChecks) import qualified Haskell.Template.Match as Match (test) import Control.Applicative ((<|>)) @@ -78,7 +79,7 @@ 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) import Text.Read (readMaybe) import Text.Regex.PCRE.Heavy (re, sub) @@ -108,6 +109,8 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# configHlintSuggestions - hlint hints to provide as suggestions \# configLanguageExtensions - this sets LanguageExtensions for hlint as well; \# defaults to NPlusKPatterns + ScopedTypeVariables +\# suggestMaybeCaseOfUsage - suggest if-statements containing checks on maybe values to be replaces with +\# case-of expressions \# 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): @@ -233,7 +236,8 @@ data FSolutionConfig m = SolutionConfig { messageOnCloningSampleSolution :: m (Maybe String), disableSemantics :: m Bool, rigorousValidation :: m Bool, - syntaxCutoff :: m FeedbackPhase + syntaxCutoff :: m FeedbackPhase, + suggestMaybeCaseOfUsage :: m Bool } deriving Generic type SolutionConfigOpt = FSolutionConfig Maybe @@ -268,7 +272,8 @@ defaultSolutionConfig = SolutionConfig { messageOnCloningSampleSolution = Just Nothing, disableSemantics = Just False, rigorousValidation = Nothing, - syntaxCutoff = Just TemplateMatch + syntaxCutoff = Just TemplateMatch, + suggestMaybeCaseOfUsage = Just False } toSolutionConfigOpt :: SolutionConfig -> SolutionConfigOpt @@ -294,6 +299,7 @@ toSolutionConfigOpt SolutionConfig {..} = runIdentity $ SolutionConfig <*> fmap Just disableSemantics <*> fmap Just rigorousValidation <*> fmap Just syntaxCutoff + <*> fmap Just suggestMaybeCaseOfUsage toMaybeSolutionConfig :: SolutionConfigOpt -> Maybe SolutionConfig toMaybeSolutionConfig SolutionConfig{..} = SolutionConfig @@ -318,6 +324,7 @@ toMaybeSolutionConfig SolutionConfig{..} = SolutionConfig <*> fmap Identity disableSemantics <*> fmap Identity rigorousValidation <*> fmap Identity syntaxCutoff + <*> fmap Identity suggestMaybeCaseOfUsage combineConfigs :: SolutionConfigOpt -> SolutionConfigOpt -> SolutionConfigOpt combineConfigs x y = SolutionConfig { @@ -341,7 +348,8 @@ combineConfigs x y = SolutionConfig { messageOnCloningSampleSolution = messageOnCloningSampleSolution x <|> messageOnCloningSampleSolution y, disableSemantics = disableSemantics x <|> disableSemantics y, rigorousValidation = rigorousValidation x <|> rigorousValidation y, - syntaxCutoff = syntaxCutoff x <|> syntaxCutoff y + syntaxCutoff = syntaxCutoff x <|> syntaxCutoff y, + suggestMaybeCaseOfUsage = suggestMaybeCaseOfUsage x <|> suggestMaybeCaseOfUsage y } string :: String -> Doc @@ -564,6 +572,25 @@ 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) + -> String + -> m [a] +getMaybeFeedback documentInfo file = do + code <- liftIO $ readFile file + + case P.parse code of + P.ParseOk mod' -> do + sequence $ flip map (collectIfsWithMaybeChecks mod') $ \(foundIf,caseReplacement) -> + documentInfo $ vcat + [ "Found:" + , indent 2 $ text $ pack $ E.prettyPrint foundIf + , "Perhaps:" + , indent 2 $ text $ pack $ E.prettyPrint caseReplacement + ] + _ -> error "This really should not happen as GHC was able to compile the submission." + editFeedback :: String -> String editFeedback xs = case elemIndex ':' xs of Just index -> @@ -967,6 +994,10 @@ testPhases reject inform template submissionFile modules config exts submission -- Displays HLint suggestions configured as non-errors triggered by submission. void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions + + -- Display suggestions involving checks on maybe values + when (runIdentity $ suggestMaybeCaseOfUsage config) $ do + void $ getMaybeFeedback inform submissionFile ] where noTest = delete "Test" modules diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 6e862f0..d22e0b7 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -79,6 +79,55 @@ 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 (isJust)" $ do + result <- maybeCheckIO [SI.i| + module Main where + + def :: Maybe Int -> Int + def mVal = if isNothing mVal then -3 else fromJust mVal|] + + length result `shouldBe` 1 + it "should suggest replacing if with case-of when applicable (isNothing)" $ do + result <- maybeCheckIO [SI.i| + module Main where + + 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 [SI.i| + module Main where + + 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 (/= Nothing)" $ do + result <- maybeCheckIO [SI.i| + module Main where + + 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 [SI.i| + module Main where + + 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 [SI.i| + module Main where + + def :: Maybe Int -> Int + def mVal = if mVal == Just 5 then fromJust mVal else -3|] + + length result `shouldBe` 0 describe "grade" $ do it "is running" $ gradeIO completedDefaultCode useImport `shouldReturn` "" @@ -235,6 +284,14 @@ hlintIO config content display selectHints = do firstLineOf (y:ys) = y : firstLineOf ys firstLineOf [] = [] +maybeCheckIO :: String -> IO [String] +maybeCheckIO code = do + tmp <- getTemporaryDirectory + withTempDirectory tmp "maybe-feedback-test" $ \dir -> do + let file = dir "Main.hs" + writeFile file code + liftIO $ getMaybeFeedback (pure . show) file + render :: PP.Doc -> String render = unpack . PP.displayT . PP.renderPretty 1.0 100 From 777310fc845eb395ee6e14c7c409df9c853f1f64 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:24:53 +0000 Subject: [PATCH 02/99] allow words --- .github/actions/spelling/allow.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index d91da89..6a7a602 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -20,6 +20,9 @@ mempty mplus msum mzero +PApp +QName +QVar snd thd uncurry From 5a00050ee6992030f4355a8214b93d41c707188c Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:25:35 +0000 Subject: [PATCH 03/99] remove trailing whitespace --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index f768251..9ed6ea5 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -109,7 +109,7 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# configHlintSuggestions - hlint hints to provide as suggestions \# configLanguageExtensions - this sets LanguageExtensions for hlint as well; \# defaults to NPlusKPatterns + ScopedTypeVariables -\# suggestMaybeCaseOfUsage - suggest if-statements containing checks on maybe values to be replaces with +\# suggestMaybeCaseOfUsage - suggest if-statements containing checks on maybe values to be replaces with \# case-of expressions \# 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); From 24e8a1505748e55652474719801ec33129fb1419 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:35:28 +0000 Subject: [PATCH 04/99] use ubuntu-24.04 --- .github/workflows/haddock.yml | 4 ++-- .github/workflows/haskell.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/haddock.yml b/.github/workflows/haddock.yml index 4f59389..10e28ae 100644 --- a/.github/workflows/haddock.yml +++ b/.github/workflows/haddock.yml @@ -14,7 +14,7 @@ jobs: permissions: contents: read - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v6 @@ -24,7 +24,7 @@ jobs: uses: actions/cache@v5 with: path: ~/.stack - key: ubuntu-latest-stack-stack-home-${{ hashFiles('stack.yaml') }}-${{ hashFiles('**/package.yaml') }} + key: ubuntu-24.04-stack-stack-home-${{ hashFiles('stack.yaml') }}-${{ hashFiles('**/package.yaml') }} - name: Setup stack uses: haskell-actions/setup@v2 diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 77d462e..7897374 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -14,7 +14,7 @@ jobs: strategy: matrix: os: - - ubuntu-latest + - ubuntu-24.04 plan: - {build: stack} From 17119adb220a87890c045149e803b83f90cf4a26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Fri, 6 Nov 2026 11:00:35 +0100 Subject: [PATCH 05/99] Fix typo in comment for suggestMaybeCaseOfUsage --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index df4a208..3fb17bb 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -110,7 +110,7 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# configHlintSuggestions - hlint hints to provide as suggestions \# configLanguageExtensions - this sets LanguageExtensions for hlint as well; \# defaults to NPlusKPatterns + ScopedTypeVariables -\# suggestMaybeCaseOfUsage - suggest if-statements containing checks on maybe values to be replaces with +\# suggestMaybeCaseOfUsage - suggest if-statements containing checks on maybe values to be replaced with \# case-of expressions \# 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); From ee67b5d0089f411b0fa1c5a116280a21af8de9c8 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:10:24 +0000 Subject: [PATCH 06/99] add HLint config --- .hlint.yaml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .hlint.yaml diff --git a/.hlint.yaml b/.hlint.yaml new file mode 100644 index 0000000..84acae7 --- /dev/null +++ b/.hlint.yaml @@ -0,0 +1,5 @@ +# HLint configuration file +# https://github.com/ndmitchell/hlint +########################## + +- hint: {lhs: "maybe [] singleton", rhs: "maybeToList"} From 547c16d54b2c7366e86f96940ea9f7b097671bf4 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:12:01 +0000 Subject: [PATCH 07/99] use maybeToList --- src/Haskell/Template/Match.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Haskell/Template/Match.hs b/src/Haskell/Template/Match.hs index 64cff2d..b544117 100644 --- a/src/Haskell/Template/Match.hs +++ b/src/Haskell/Template/Match.hs @@ -37,7 +37,7 @@ import Data.Generics ( mkT, ) import Data.List (insertBy, singleton) -import Data.Maybe (isJust) +import Data.Maybe (isJust, maybeToList) import Language.Haskell.Exts.Syntax data Where = OnlyTemplate | OnlySubmission @@ -341,7 +341,7 @@ test m1 m2 = evalState (runM (matchModule m1 m2)) $ SrcSpanInfoPair CompleteModule S.noSrcSpan S.noSrcSpan collectIfsWithMaybeChecks :: Module S.SrcSpanInfo -> [(Exp S.SrcSpanInfo, Exp ())] -collectIfsWithMaybeChecks = everything (++) $ mkQ [] (maybe [] singleton . exprToIfInfo) +collectIfsWithMaybeChecks = everything (++) $ mkQ [] (maybeToList . exprToIfInfo) exprToIfInfo :: Exp S.SrcSpanInfo -> Maybe (Exp S.SrcSpanInfo, Exp ()) exprToIfInfo expr@(If _ cond t e) = case removeParens cond of From 02ca68b5279f80f1f76901216003a3fe140e8cae Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:14:53 +0000 Subject: [PATCH 08/99] move position of config setting --- src/Haskell/Template/Task.hs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 3fb17bb..b1754e4 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -232,13 +232,13 @@ data FSolutionConfig m = SolutionConfig { configHlintRules :: m [String], configHlintSuggestions :: m [String], configLanguageExtensions :: m [String], + suggestMaybeCaseOfUsage :: m Bool, maxLineLength :: m (Maybe Natural), provideSampleSolution :: m Bool, messageOnCloningSampleSolution :: m (Maybe String), disableSemantics :: m Bool, rigorousValidation :: m Bool, - syntaxCutoff :: m FeedbackPhase, - suggestMaybeCaseOfUsage :: m Bool + syntaxCutoff :: m FeedbackPhase } deriving Generic type SolutionConfigOpt = FSolutionConfig Maybe @@ -270,13 +270,13 @@ defaultSolutionConfig = SolutionConfig { configHlintRules = Just [], configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], + suggestMaybeCaseOfUsage = Just False, maxLineLength = Just Nothing, provideSampleSolution = Nothing, messageOnCloningSampleSolution = Just Nothing, disableSemantics = Just False, rigorousValidation = Nothing, - syntaxCutoff = Just TemplateMatch, - suggestMaybeCaseOfUsage = Just False + syntaxCutoff = Just TemplateMatch } toSolutionConfigOpt :: SolutionConfig -> SolutionConfigOpt @@ -296,13 +296,13 @@ toSolutionConfigOpt SolutionConfig {..} = runIdentity $ SolutionConfig <*> fmap Just configHlintRules <*> fmap Just configHlintSuggestions <*> fmap Just configLanguageExtensions + <*> fmap Just suggestMaybeCaseOfUsage <*> fmap Just maxLineLength <*> fmap Just provideSampleSolution <*> fmap Just messageOnCloningSampleSolution <*> fmap Just disableSemantics <*> fmap Just rigorousValidation <*> fmap Just syntaxCutoff - <*> fmap Just suggestMaybeCaseOfUsage toMaybeSolutionConfig :: SolutionConfigOpt -> Maybe SolutionConfig toMaybeSolutionConfig SolutionConfig{..} = SolutionConfig @@ -321,13 +321,13 @@ toMaybeSolutionConfig SolutionConfig{..} = SolutionConfig <*> fmap Identity configHlintRules <*> fmap Identity configHlintSuggestions <*> fmap Identity configLanguageExtensions + <*> fmap Identity suggestMaybeCaseOfUsage <*> fmap Identity maxLineLength <*> fmap Identity provideSampleSolution <*> fmap Identity messageOnCloningSampleSolution <*> fmap Identity disableSemantics <*> fmap Identity rigorousValidation <*> fmap Identity syntaxCutoff - <*> fmap Identity suggestMaybeCaseOfUsage combineConfigs :: SolutionConfigOpt -> SolutionConfigOpt -> SolutionConfigOpt combineConfigs x y = SolutionConfig { From 4befb133cf3b9dcfa47c90bb0b8eda3742bd93df Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:03:04 +0000 Subject: [PATCH 09/99] provide suggestion earlier --- src/Haskell/Template/Task.hs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index b1754e4..73715c0 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -976,6 +976,10 @@ testPhases reject inform template submissionFile modules config exts submission , -- Reject if HLint warnings configured as errors are triggered by submission. void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors + , + -- Reject if suggestions involving checks on maybe values are present + when (runIdentity $ suggestMaybeCaseOfUsage config) $ do + void $ getMaybeFeedback inform submissionFile , -- Reject on task template violations according to settings (modifying, adding, deleting). matchTemplate reject config 2 exts template submission @@ -991,10 +995,6 @@ testPhases reject inform template submissionFile modules config exts submission -- Displays HLint suggestions configured as non-errors triggered by submission. void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions - - -- Display suggestions involving checks on maybe values - when (runIdentity $ suggestMaybeCaseOfUsage config) $ do - void $ getMaybeFeedback inform submissionFile ] where noTest = delete "Test" modules From af5488592d7349dfa149222ba27e2dfcf0ee3f60 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:38:12 +0000 Subject: [PATCH 10/99] add more tests --- test/Haskell/Template/TaskSpec.hs | 53 +++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index d22e0b7..d88f0f2 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -127,6 +127,59 @@ spec = do 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 [SI.i| + module Main where + + 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 user later" $ do + result <- maybeCheckIO [SI.i| + module Main where + + def :: Maybe Int -> Int + def mVal = let value = -3 in if isJust mVal then fromJust mVal else value + + def2 :: Maybe Int -> Int + def2 mVal = if isJust mVal then let value = 5 in fromJust mVal else -3|] + + 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'|] + ] + it "should not suggest replacing if with case-of when isJust, fromJust, etc. are not from Data.Maybe" $ do + result <- maybeCheckIO [SI.i| + module Main where + + def :: Maybe Int -> Int + def mVal = if isJust mVal then 5 else -3 + where isJust _ = False + + def2 :: Maybe Int -> Int + def2 mVal = if isJust mVal then fromJust mVal else -3 + where fromJust _ = 99|] + + length result `shouldBe` 0 + it "should not suggest replacing if with case-of when fromJust is used on shadowed maybe value" $ do + result <- maybeCheckIO [SI.i| + module Main where + + def :: Maybe Int -> Int + def mVal = if isJust mVal then let mVal = Just 99 in fromJust mVal else -3|] + length result `shouldBe` 0 describe "grade" $ do it "is running" $ From c19880ec63684a50461100ce7f43df8b0e522d24 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:46:34 +0000 Subject: [PATCH 11/99] only suggest when fromJust is used and make newly introduced variable not clash with others --- haskell-template-task.cabal | 2 + package.yaml | 1 + src/Haskell/Template/Match.hs | 86 +++++++++++++++++++++++++++++------ 3 files changed, 74 insertions(+), 15 deletions(-) diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index b8bd804..a6f8fcd 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -39,6 +39,7 @@ library , aeson , base >=4.7 && <5 , bytestring + , containers , extra , file-embed , filepath @@ -72,6 +73,7 @@ test-suite haskell-template-task-test , aeson , base >=4.7 && <5 , bytestring + , containers , deepseq , directory , exceptions diff --git a/package.yaml b/package.yaml index ed23d36..3bf9d32 100644 --- a/package.yaml +++ b/package.yaml @@ -35,6 +35,7 @@ dependencies: - wl-pprint-text - yaml - aeson + - containers ghc-options: - -Wall diff --git a/src/Haskell/Template/Match.hs b/src/Haskell/Template/Match.hs index b544117..129a26a 100644 --- a/src/Haskell/Template/Match.hs +++ b/src/Haskell/Template/Match.hs @@ -20,6 +20,7 @@ import Control.Monad ( unless, void, when, + guard, ) import Control.Monad.State (State, evalState, gets, put) import Data.Function (on) @@ -35,10 +36,14 @@ import Data.Generics ( mkQ, everywhere, mkT, + listify, ) -import Data.List (insertBy, singleton) -import Data.Maybe (isJust, maybeToList) +import Data.List (insertBy) +import Data.Maybe (isJust, maybeToList, mapMaybe, listToMaybe) import Language.Haskell.Exts.Syntax +import Data.List.Extra (notNull) +import Data.Set (Set) +import qualified Data.Set as Set (singleton, empty, union, fromList, member) data Where = OnlyTemplate | OnlySubmission deriving (Eq, Ord, Show) @@ -341,16 +346,47 @@ test m1 m2 = evalState (runM (matchModule m1 m2)) $ SrcSpanInfoPair CompleteModule S.noSrcSpan S.noSrcSpan collectIfsWithMaybeChecks :: Module S.SrcSpanInfo -> [(Exp S.SrcSpanInfo, Exp ())] -collectIfsWithMaybeChecks = everything (++) $ mkQ [] (maybeToList . exprToIfInfo) +collectIfsWithMaybeChecks (Module _ _ _ _ decls) = concat $ mapMaybe process decls + where + process d = do + let opportunities = everything (++) (mkQ [] (maybeToList . exprToIfInfo)) d + guard $ notNull opportunities + + let allSymbols = Set.fromList (mapMaybe declName decls) `Set.union` allNames d + freeName n symbs + | Set.member n symbs = freeName (n ++ "'") symbs + | otherwise = n + rename :: String -> Name () -> Name () + rename n (Ident l "_valueNamePlaceholder") = Ident l n + rename _ nExpr = nExpr + + pure $ map (everywhere $ mkT (rename $ freeName "value" allSymbols)) opportunities +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 :: Exp S.SrcSpanInfo -> Maybe (Exp S.SrcSpanInfo, Exp ()) exprToIfInfo expr@(If _ cond t e) = case removeParens cond of (App _ (Var _ vn) maybeVal) - | hasName "isJust" vn -> Just (expr,asCaseExpression maybeVal t e) - | hasName "isNothing" vn -> Just (expr,asCaseExpression maybeVal e t) - (InfixApp _ l (QVarOp _ opName) r) - | hasName "==" opName -> (\maybeVal -> (expr, asCaseExpression maybeVal e t)) <$> getMaybeVal l r - | hasName "/=" opName -> (\maybeVal -> (expr, asCaseExpression maybeVal t e)) <$> getMaybeVal l r + | hasName "isJust" vn -> transform maybeVal t e + | hasName "isNothing" vn -> transform maybeVal e t + (InfixApp _ l (QVarOp _ opName) r) -> case getMaybeVal l r of + Just maybeVal + | hasName "==" opName -> transform maybeVal e t + | hasName "/=" opName -> transform maybeVal t e + _ -> Nothing _ -> Nothing where isNothingExpression (Con _ vName) = hasName "Nothing" vName @@ -361,20 +397,40 @@ exprToIfInfo expr@(If _ cond t e) = case removeParens cond of | isNothingExpression l = Just r | isNothingExpression r = Just l | otherwise = Nothing + + transform mVal j n + | hasFromJust mVal j = Just (expr, asCaseExpression "_valueNamePlaceholder" mVal j n) + | otherwise = Nothing + exprToIfInfo _ = Nothing -asCaseExpression :: Exp a -> Exp a -> Exp a -> Exp () -asCaseExpression maybeValue justCase nothingCase = Case () (void maybeValue) +allNames :: Data a => a -> Set String +allNames = everything Set.union $ mkQ Set.empty extract + where + extract :: Name S.SrcSpanInfo -> Set String + extract (Ident _ n) = Set.singleton n + extract (Symbol _ n) = Set.singleton n + + +hasFromJust :: Exp S.SrcSpanInfo -> Exp S.SrcSpanInfo -> Bool +hasFromJust mExpr expr = notNull $ listify isFromJustApp expr + where + isFromJustApp :: Exp S.SrcSpanInfo -> Bool + isFromJustApp (App _ (Var _ vn) maybeVal) = hasName "fromJust" vn && void maybeVal == void mExpr + isFromJustApp _ = False + +asCaseExpression :: String -> Exp a -> Exp a -> Exp a -> 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 () "value")]) - (UnGuardedRhs () $ replaceFromJustWithValue (void maybeValue) (void justCase)) Nothing + , Alt () (PApp () (UnQual () (Ident () "Just")) [PVar () (Ident () valueName)]) + (UnGuardedRhs () $ replaceFromJustWithValue valueName (void maybeValue) (void justCase)) Nothing ] -replaceFromJustWithValue :: Exp () -> Exp () -> Exp () -replaceFromJustWithValue maybeValue = everywhere $ mkT replace +replaceFromJustWithValue :: String -> Exp () -> Exp () -> Exp () +replaceFromJustWithValue valueName maybeValue = everywhere $ mkT replace where replace (App () (Var () (UnQual _ (Ident () "fromJust"))) fnBody) - | fnBody == maybeValue = Var () (UnQual () (Ident () "value")) + | fnBody == maybeValue = Var () (UnQual () (Ident () valueName)) replace expr = expr removeParens :: Exp a -> Exp a From dd6d2800bbda451b2b70fadf7f65590cbb8b99d8 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:34:21 +0000 Subject: [PATCH 12/99] import Data.Maybe in test cases --- test/Haskell/Template/TaskSpec.hs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index d88f0f2..2d6145d 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -83,6 +83,7 @@ spec = do it "should suggest replacing if with case-of when applicable (isJust)" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if isNothing mVal then -3 else fromJust mVal|] @@ -91,6 +92,7 @@ spec = do it "should suggest replacing if with case-of when applicable (isNothing)" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if mVal == Nothing then -3 else fromJust mVal|] @@ -99,6 +101,7 @@ spec = do it "should suggest replacing if with case-of when applicable (== Nothing)" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if mVal /= Nothing then fromJust mVal else -3|] @@ -107,6 +110,7 @@ spec = do it "should suggest replacing if with case-of when applicable (/= Nothing)" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if isJust mVal then fromJust mVal else -3|] @@ -115,6 +119,7 @@ spec = do it "should not suggest replacing if with case-of when condition is mixed" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if isJust mVal && True then fromJust mVal else -3|] @@ -123,6 +128,7 @@ spec = do it "should not suggest replacing if with case-of when condition is comparison with Just value" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if mVal == Just 5 then fromJust mVal else -3|] @@ -131,6 +137,7 @@ spec = do it "should not suggest replacing if with case-of when value is not used" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if isJust mVal then 5 else -3|] @@ -139,10 +146,11 @@ spec = do it "replacement should not introduce variable names that are already used or will be user later" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = let value = -3 in if isJust mVal then fromJust mVal else value - + def2 :: Maybe Int -> Int def2 mVal = if isJust mVal then let value = 5 in fromJust mVal else -3|] @@ -163,11 +171,12 @@ Perhaps: it "should not suggest replacing if with case-of when isJust, fromJust, etc. are not from Data.Maybe" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if isJust mVal then 5 else -3 where isJust _ = False - + def2 :: Maybe Int -> Int def2 mVal = if isJust mVal then fromJust mVal else -3 where fromJust _ = 99|] @@ -176,6 +185,7 @@ Perhaps: it "should not suggest replacing if with case-of when fromJust is used on shadowed maybe value" $ do result <- maybeCheckIO [SI.i| module Main where + import Data.Maybe def :: Maybe Int -> Int def mVal = if isJust mVal then let mVal = Just 99 in fromJust mVal else -3|] From 4cca77a7ffcde3c7385965fa0ee12d57c29e866a Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:40:06 +0000 Subject: [PATCH 13/99] make checks dependent on name scopes --- haskell-template-task.cabal | 2 ++ package.yaml | 1 + src/Haskell/Template/Match.hs | 42 +++++++++++++++++++++-------------- src/Haskell/Template/Task.hs | 4 +++- stack.yaml | 1 + 5 files changed, 32 insertions(+), 18 deletions(-) diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index a6f8fcd..e6f2812 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -43,6 +43,7 @@ library , extra , file-embed , filepath + , haskell-names , haskell-src-exts , haskell-template-task-raw , hint @@ -80,6 +81,7 @@ test-suite haskell-template-task-test , 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 3bf9d32..ecb54a0 100644 --- a/package.yaml +++ b/package.yaml @@ -36,6 +36,7 @@ dependencies: - yaml - aeson - containers + - haskell-names ghc-options: - -Wall diff --git a/src/Haskell/Template/Match.hs b/src/Haskell/Template/Match.hs index 129a26a..0fc50ed 100644 --- a/src/Haskell/Template/Match.hs +++ b/src/Haskell/Template/Match.hs @@ -44,6 +44,7 @@ import Language.Haskell.Exts.Syntax import Data.List.Extra (notNull) import Data.Set (Set) import qualified Data.Set as Set (singleton, empty, union, fromList, member) +import Language.Haskell.Names (Scoped (..), NameInfo (..), Symbol (..)) data Where = OnlyTemplate | OnlySubmission deriving (Eq, Ord, Show) @@ -345,7 +346,7 @@ test m1 m2 = -- ParseOk m2' = parseModule m2 evalState (runM (matchModule m1 m2)) $ SrcSpanInfoPair CompleteModule S.noSrcSpan S.noSrcSpan -collectIfsWithMaybeChecks :: Module S.SrcSpanInfo -> [(Exp S.SrcSpanInfo, Exp ())] +collectIfsWithMaybeChecks :: Module (Scoped S.SrcSpanInfo) -> [(Exp (Scoped S.SrcSpanInfo), Exp ())] collectIfsWithMaybeChecks (Module _ _ _ _ decls) = concat $ mapMaybe process decls where process d = do @@ -377,19 +378,20 @@ declName (PatBind _ (PVar _ pn) _ _) = Just $ fromName pn declName _ = Nothing -exprToIfInfo :: Exp S.SrcSpanInfo -> Maybe (Exp S.SrcSpanInfo, Exp ()) +exprToIfInfo :: Exp (Scoped S.SrcSpanInfo) -> Maybe (Exp (Scoped S.SrcSpanInfo), Exp ()) exprToIfInfo expr@(If _ cond t e) = case removeParens cond of (App _ (Var _ vn) maybeVal) - | hasName "isJust" vn -> transform maybeVal t e - | hasName "isNothing" vn -> transform maybeVal e t + | 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 "==" opName -> transform maybeVal e t - | hasName "/=" opName -> transform maybeVal t e + | hasName Nothing "==" opName -> transform maybeVal e t + | hasName Nothing "/=" opName -> transform maybeVal t e _ -> Nothing _ -> Nothing where - isNothingExpression (Con _ vName) = hasName "Nothing" vName + maybeMod = Just "Data.Maybe" + isNothingExpression (Con _ vName) = hasName maybeMod "Nothing" vName isNothingExpression _ = False getMaybeVal l r @@ -407,16 +409,17 @@ exprToIfInfo _ = Nothing allNames :: Data a => a -> Set String allNames = everything Set.union $ mkQ Set.empty extract where - extract :: Name S.SrcSpanInfo -> Set String + extract :: Name (Scoped S.SrcSpanInfo) -> Set String extract (Ident _ n) = Set.singleton n extract (Symbol _ n) = Set.singleton n -hasFromJust :: Exp S.SrcSpanInfo -> Exp S.SrcSpanInfo -> Bool +hasFromJust :: Exp (Scoped S.SrcSpanInfo) -> Exp (Scoped S.SrcSpanInfo) -> Bool hasFromJust mExpr expr = notNull $ listify isFromJustApp expr where - isFromJustApp :: Exp S.SrcSpanInfo -> Bool - isFromJustApp (App _ (Var _ vn) maybeVal) = hasName "fromJust" vn && void maybeVal == void mExpr + isFromJustApp :: Exp (Scoped S.SrcSpanInfo) -> Bool + isFromJustApp (App _ (Var _ vn) maybeVal) = + hasName (Just "Data.Maybe") "fromJust" vn && fmap void maybeVal == fmap void mExpr isFromJustApp _ = False asCaseExpression :: String -> Exp a -> Exp a -> Exp a -> Exp () @@ -437,12 +440,17 @@ removeParens :: Exp a -> Exp a removeParens (Paren _ e) = removeParens e removeParens e = e -hasName :: String -> QName l -> Bool -hasName qName (UnQual _ (Ident _ n)) = n == qName -hasName qName (Qual _ _ (Ident _ n)) = n == qName -hasName qName (UnQual _ (Symbol _ n)) = n == qName -hasName qName (Qual _ _ (Symbol _ n)) = n == qName -hasName _ _ = False +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 ------------------------------------------------------------------------------ -- | Twin map for monadic transformation diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 73715c0..c60e0ff 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -83,6 +83,7 @@ import Text.PrettyPrint.Leijen.Text (Doc, (<+>), empty, int, linebreak, nest, punctuate, text, vcat, indent) import Text.Read (readMaybe) import Text.Regex.PCRE.Heavy (re, sub) +import Language.Haskell.Names (loadBase, annotate) encode :: ToJSON a => a -> BS.ByteString encode = encodePretty $ setConfCompare compare defConfig @@ -576,10 +577,11 @@ getMaybeFeedback -> m [a] getMaybeFeedback documentInfo file = do code <- liftIO $ readFile file + env <- liftIO loadBase case P.parse code of P.ParseOk mod' -> do - sequence $ flip map (collectIfsWithMaybeChecks mod') $ \(foundIf,caseReplacement) -> + sequence $ flip map (collectIfsWithMaybeChecks (annotate env mod')) $ \(foundIf,caseReplacement) -> documentInfo $ vcat [ "Found:" , indent 2 $ text $ pack $ E.prettyPrint foundIf 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 From ba0c4bb9fc02847b704a3a2d63c0053f34839ab9 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:23:24 +0000 Subject: [PATCH 14/99] share parsed AST of submission --- src/Haskell/Template/Task.hs | 50 ++++++++++++++---------------- test/Haskell/Template/MatchSpec.hs | 10 +++--- test/Haskell/Template/TaskSpec.hs | 7 ++--- 3 files changed, 32 insertions(+), 35 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index c60e0ff..8502dfa 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -388,7 +388,8 @@ check reject inform path i = do let content = replace "SampleSolution" m sampleSolution mapM_ (checkLineLength reject content) $ runIdentity maxLineLength (modules, solutionFile) <- writeModules (m, content) others path - sequence_ $ testPhases reject inform s solutionFile modules stricterConfig exts content path + contentAST <- parse reject exts content + sequence_ $ testPhases reject inform s solutionFile modules stricterConfig exts content contentAST path where parseModule exts (m, s) = do inform $ string $ "Parsing module " <> m @@ -503,9 +504,10 @@ grade withSyntax withSemantics reject inform dirname task submission = do -- and semantics phase is disabled. then pure (undefined, undefined) else writeModules (moduleName', submission) others dirname + submissionAST <- parse reject exts submission let (syntax, semantics) = splitAt (fromEnum syntaxCutoff) - $ testPhases reject inform template submissionFile modules config exts submission dirname + $ testPhases reject inform template submissionFile modules config exts submission submissionAST dirname withSyntax $ sequence_ syntax if runIdentity disableSemantics then pure False @@ -521,7 +523,7 @@ grade withSyntax withSemantics reject inform dirname task submission = do (inform $ string message) exts (replace "SampleSolution" moduleName' sampleSolution) - submission + submissionAST rejectHint :: Doc rejectHint = [SI.iii| @@ -573,22 +575,17 @@ getHlintFeedback documentInfo config dir file selectHints = case hints of getMaybeFeedback :: MonadIO m => (Doc -> m a) - -> String + -> E.Module E.SrcSpanInfo -> m [a] -getMaybeFeedback documentInfo file = do - code <- liftIO $ readFile file +getMaybeFeedback documentInfo ast = do env <- liftIO loadBase - - case P.parse code of - P.ParseOk mod' -> do - sequence $ flip map (collectIfsWithMaybeChecks (annotate env mod')) $ \(foundIf,caseReplacement) -> - documentInfo $ vcat - [ "Found:" - , indent 2 $ text $ pack $ E.prettyPrint foundIf - , "Perhaps:" - , indent 2 $ text $ pack $ E.prettyPrint caseReplacement - ] - _ -> error "This really should not happen as GHC was able to compile the submission." + sequence $ flip map (collectIfsWithMaybeChecks (annotate env ast)) $ \(foundIf,caseReplacement) -> + documentInfo $ vcat + [ "Found:" + , indent 2 $ text $ pack $ E.prettyPrint foundIf + , "Perhaps:" + , indent 2 $ text $ pack $ E.prettyPrint caseReplacement + ] editFeedback :: String -> String editFeedback xs = case elemIndex ':' xs of @@ -628,9 +625,10 @@ matchTemplate -> [E.Extension] -> String -> String + -> E.Module E.SrcSpanInfo -> m () -matchTemplate reject config context exts template submission = - runMatchTestOn reject exts template submission $ \case +matchTemplate reject config context exts template submission submissionAST = + runMatchTestOn reject exts template submissionAST $ \case Fail loc -> mapM_ (rejectMatch rejectWithHint config context template submission) loc where rejectWithHint = rejectWithMessage reject rejectHint @@ -642,7 +640,7 @@ catchSampleSolutionClone -> m () -> [E.Extension] -> String - -> String + -> E.Module E.SrcSpanInfo -> m Bool catchSampleSolutionClone reject displayMessage exts sample submission = runMatchTestOn reject exts sample submission $ \case @@ -658,12 +656,11 @@ runMatchTestOn => (forall a. Doc -> m a) -> [E.Extension] -> String - -> String + -> E.Module E.SrcSpanInfo -> (Result () -> m b) -> m b -runMatchTestOn reject exts rawTemplate rawSubmission whatToDo = do +runMatchTestOn reject exts rawTemplate submission whatToDo = do template <- parse reject exts rawTemplate - submission <- parse reject exts rawSubmission case Match.test template submission of Continue -> reject [SI.i|Haskell.Template.Central.matchTemplate: #{informTutorMessage}|] @@ -952,9 +949,10 @@ testPhases -> SolutionConfig -> [E.Extension] -> String + -> E.Module E.SrcSpanInfo -> FilePath -> [m ()] -testPhases reject inform template submissionFile modules config exts submission dirname = +testPhases reject inform template submissionFile modules config exts submission submissionAST dirname = [ do -- Reject if submission does not compile with provided hidden modules, @@ -981,10 +979,10 @@ testPhases reject inform template submissionFile modules config exts submission , -- Reject if suggestions involving checks on maybe values are present when (runIdentity $ suggestMaybeCaseOfUsage config) $ do - void $ getMaybeFeedback inform submissionFile + void $ getMaybeFeedback inform submissionAST , -- Reject on task template violations according to settings (modifying, adding, deleting). - matchTemplate reject config 2 exts template submission + matchTemplate reject config 2 exts template submission submissionAST , do -- Reject if test suite fails for submission. diff --git a/test/Haskell/Template/MatchSpec.hs b/test/Haskell/Template/MatchSpec.hs index 7808f20..5645eb0 100644 --- a/test/Haskell/Template/MatchSpec.hs +++ b/test/Haskell/Template/MatchSpec.hs @@ -41,8 +41,9 @@ noEdits = fromJust $ toMaybeSolutionConfig spec :: Spec spec = describe "template match" $ do - it "accepts identical code" $ - matchTemplate errorP withAdding 0 [] modUndefined modUndefined + it "accepts identical code" $ do + modUndefinedAST <- parse (error . show) [] modUndefined + matchTemplate errorP withAdding 0 [] modUndefined modUndefined modUndefinedAST `shouldBe` Right () it "accepts identical code without comment" $ getComment withAdding modUndefined modUndefined @@ -72,8 +73,9 @@ spec = it "accepts code with guards and parameter" $ getComment withAdding modUndefinedParameter modGuardsParameter `shouldBe` Right [] - it "rejects code where parts beside undefined are changed" $ - matchTemplate errorP withAdding 0 [] mod42 mod43 `shouldSatisfy` isLeft + it "rejects code where parts beside undefined are changed" $ do + mod43AST <- parse (fail . show) [] mod43 + matchTemplate errorP withAdding 0 [] mod42 mod43 mod43AST `shouldSatisfy` isLeft it "marks not matching parts within functions" $ getComment withAdding mod42 mod43 `shouldBe` Right [Mismatch ["foo = 42" diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 2d6145d..7e3fe46 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -349,11 +349,8 @@ hlintIO config content display selectHints = do maybeCheckIO :: String -> IO [String] maybeCheckIO code = do - tmp <- getTemporaryDirectory - withTempDirectory tmp "maybe-feedback-test" $ \dir -> do - let file = dir "Main.hs" - writeFile file code - liftIO $ getMaybeFeedback (pure . show) file + codeAST <- parse (fail . show) [] code + getMaybeFeedback (pure . show) codeAST render :: PP.Doc -> String render = unpack . PP.displayT . PP.renderPretty 1.0 100 From 552be15dbee043923acf74602d056382f2f130fa Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:35:18 +0000 Subject: [PATCH 15/99] directly access value --- src/Haskell/Template/Match.hs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Haskell/Template/Match.hs b/src/Haskell/Template/Match.hs index 0fc50ed..08c5761 100644 --- a/src/Haskell/Template/Match.hs +++ b/src/Haskell/Template/Match.hs @@ -354,14 +354,14 @@ collectIfsWithMaybeChecks (Module _ _ _ _ decls) = concat $ mapMaybe process dec guard $ notNull opportunities let allSymbols = Set.fromList (mapMaybe declName decls) `Set.union` allNames d - freeName n symbs - | Set.member n symbs = freeName (n ++ "'") symbs + freeName n + | Set.member n allSymbols = freeName (n ++ "'") | otherwise = n rename :: String -> Name () -> Name () rename n (Ident l "_valueNamePlaceholder") = Ident l n rename _ nExpr = nExpr - pure $ map (everywhere $ mkT (rename $ freeName "value" allSymbols)) opportunities + pure $ map (everywhere $ mkT (rename $ freeName "value")) opportunities collectIfsWithMaybeChecks _ = [] declName :: Decl a -> Maybe String From 15b9ed91d67ec6edb4b920e8cb7f64f66a9f17f4 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:37:37 +0000 Subject: [PATCH 16/99] add document start --- .hlint.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.hlint.yaml b/.hlint.yaml index 84acae7..0c3bb35 100644 --- a/.hlint.yaml +++ b/.hlint.yaml @@ -1,3 +1,4 @@ +--- # HLint configuration file # https://github.com/ndmitchell/hlint ########################## From 62aa9a1791709f3c0e4d5175d5ac0da57c974e36 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:16:31 +0000 Subject: [PATCH 17/99] use errorP --- test/Haskell/Template/MatchSpec.hs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/Haskell/Template/MatchSpec.hs b/test/Haskell/Template/MatchSpec.hs index 5645eb0..a5c7a3f 100644 --- a/test/Haskell/Template/MatchSpec.hs +++ b/test/Haskell/Template/MatchSpec.hs @@ -42,7 +42,7 @@ spec :: Spec spec = describe "template match" $ do it "accepts identical code" $ do - modUndefinedAST <- parse (error . show) [] modUndefined + modUndefinedAST <- parse errorP [] modUndefined matchTemplate errorP withAdding 0 [] modUndefined modUndefined modUndefinedAST `shouldBe` Right () it "accepts identical code without comment" $ @@ -73,9 +73,10 @@ spec = it "accepts code with guards and parameter" $ getComment withAdding modUndefinedParameter modGuardsParameter `shouldBe` Right [] - it "rejects code where parts beside undefined are changed" $ do - mod43AST <- parse (fail . show) [] mod43 - matchTemplate errorP withAdding 0 [] mod42 mod43 mod43AST `shouldSatisfy` isLeft + it "rejects code where parts beside undefined are changed" $ (do + mod43AST <- parse errorP [] mod43 + matchTemplate errorP withAdding 0 [] mod42 mod43 mod43AST + ) `shouldSatisfy` isLeft it "marks not matching parts within functions" $ getComment withAdding mod42 mod43 `shouldBe` Right [Mismatch ["foo = 42" From 44b38e139546020c32460edc7c5b71627a58ca1c Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:19:11 +0000 Subject: [PATCH 18/99] reduce diff --- src/Haskell/Template/Task.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 1825b57..9e5a015 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -347,13 +347,13 @@ combineConfigs x y = SolutionConfig { configHlintRules = configHlintRules x <|> configHlintRules y, configHlintSuggestions = configHlintSuggestions x <|> configHlintSuggestions y, configLanguageExtensions = configLanguageExtensions x <|> configLanguageExtensions y, + suggestMaybeCaseOfUsage = suggestMaybeCaseOfUsage x <|> suggestMaybeCaseOfUsage y, maxLineLength = maxLineLength x <|> maxLineLength y, provideSampleSolution = provideSampleSolution x <|> provideSampleSolution y, messageOnCloningSampleSolution = messageOnCloningSampleSolution x <|> messageOnCloningSampleSolution y, disableSemantics = disableSemantics x <|> disableSemantics y, rigorousValidation = rigorousValidation x <|> rigorousValidation y, - syntaxCutoff = syntaxCutoff x <|> syntaxCutoff y, - suggestMaybeCaseOfUsage = suggestMaybeCaseOfUsage x <|> suggestMaybeCaseOfUsage y + syntaxCutoff = syntaxCutoff x <|> syntaxCutoff y } string :: String -> Doc From 5a47f3b60364df327754d9dc6abaa31ce6e2e083 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:42:51 +0000 Subject: [PATCH 19/99] put detection into separate module --- haskell-template-task.cabal | 1 + src/Haskell/Template/Detection.hs | 134 ++++++++++++++++++++++++++++++ src/Haskell/Template/Match.hs | 130 +---------------------------- src/Haskell/Template/Task.hs | 3 +- 4 files changed, 140 insertions(+), 128 deletions(-) create mode 100644 src/Haskell/Template/Detection.hs diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index e6f2812..1f44d4c 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -27,6 +27,7 @@ source-repository head library exposed-modules: + Haskell.Template.Detection Haskell.Template.Match Haskell.Template.Task other-modules: diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs new file mode 100644 index 0000000..5fdad1f --- /dev/null +++ b/src/Haskell/Template/Detection.hs @@ -0,0 +1,134 @@ +module Haskell.Template.Detection (collectIfsWithMaybeChecks) where + +import Control.Monad (guard, 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 (..), + 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 + process d = do + let opportunities = everything (++) (mkQ [] (maybeToList . exprToIfInfo)) d + guard $ notNull opportunities + + let + allSymbols = Set.fromList (mapMaybe declName decls) `Set.union` allNames d + freeName n + | Set.member n allSymbols = freeName (n ++ "'") + | otherwise = n + rename :: String -> Name () -> Name () + rename n (Ident l "_valueNamePlaceholder") = Ident l n + rename _ nExpr = nExpr + + pure $ map (everywhere $ mkT (rename $ freeName "value")) opportunities +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 :: Exp (Scoped SrcSpanInfo) -> Maybe (Exp (Scoped SrcSpanInfo), Exp ()) +exprToIfInfo 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 Nothing "==" opName -> transform maybeVal e t + | hasName Nothing "/=" opName -> transform maybeVal t e + _ -> Nothing + _ -> Nothing + where + 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 mVal j n + | hasFromJust mVal j = Just (expr, asCaseExpression "_valueNamePlaceholder" mVal j n) + | otherwise = 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 + +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 maybeVal == fmap void mExpr + isFromJustApp _ = False + +asCaseExpression :: String -> Exp a -> Exp a -> Exp a -> 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 (void maybeValue) (void justCase)) + Nothing + ] + +replaceFromJustWithValue :: String -> Exp () -> Exp () -> Exp () +replaceFromJustWithValue valueName maybeValue = everywhere $ mkT replace + where + replace (App () (Var () (UnQual _ (Ident () "fromJust"))) fnBody) + | fnBody == maybeValue = Var () (UnQual () (Ident () valueName)) + replace expr = 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/Match.hs b/src/Haskell/Template/Match.hs index 08c5761..44a71aa 100644 --- a/src/Haskell/Template/Match.hs +++ b/src/Haskell/Template/Match.hs @@ -20,31 +20,14 @@ import Control.Monad ( unless, void, when, - guard, ) import Control.Monad.State (State, evalState, gets, put) import Data.Function (on) -import Data.Generics ( - Data (..), - GenericM, - GenericM' (..), - GenericQ, - cast, - gfoldlAccum, - gmapQ, - everything, - mkQ, - everywhere, - mkT, - listify, - ) +import Data.Generics + (Data (..), GenericM, GenericM' (..), GenericQ, cast, gfoldlAccum, gmapQ) import Data.List (insertBy) -import Data.Maybe (isJust, maybeToList, mapMaybe, listToMaybe) +import Data.Maybe (isJust) import Language.Haskell.Exts.Syntax -import Data.List.Extra (notNull) -import Data.Set (Set) -import qualified Data.Set as Set (singleton, empty, union, fromList, member) -import Language.Haskell.Names (Scoped (..), NameInfo (..), Symbol (..)) data Where = OnlyTemplate | OnlySubmission deriving (Eq, Ord, Show) @@ -345,113 +328,6 @@ test m1 m2 = -- ParseOk m1' = parseModule m1 -- ParseOk m2' = parseModule m2 evalState (runM (matchModule m1 m2)) $ SrcSpanInfoPair CompleteModule S.noSrcSpan S.noSrcSpan - -collectIfsWithMaybeChecks :: Module (Scoped S.SrcSpanInfo) -> [(Exp (Scoped S.SrcSpanInfo), Exp ())] -collectIfsWithMaybeChecks (Module _ _ _ _ decls) = concat $ mapMaybe process decls - where - process d = do - let opportunities = everything (++) (mkQ [] (maybeToList . exprToIfInfo)) d - guard $ notNull opportunities - - let allSymbols = Set.fromList (mapMaybe declName decls) `Set.union` allNames d - freeName n - | Set.member n allSymbols = freeName (n ++ "'") - | otherwise = n - rename :: String -> Name () -> Name () - rename n (Ident l "_valueNamePlaceholder") = Ident l n - rename _ nExpr = nExpr - - pure $ map (everywhere $ mkT (rename $ freeName "value")) opportunities -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 :: Exp (Scoped S.SrcSpanInfo) -> Maybe (Exp (Scoped S.SrcSpanInfo), Exp ()) -exprToIfInfo 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 Nothing "==" opName -> transform maybeVal e t - | hasName Nothing "/=" opName -> transform maybeVal t e - _ -> Nothing - _ -> Nothing - where - 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 mVal j n - | hasFromJust mVal j = Just (expr, asCaseExpression "_valueNamePlaceholder" mVal j n) - | otherwise = Nothing - -exprToIfInfo _ = Nothing - -allNames :: Data a => a -> Set String -allNames = everything Set.union $ mkQ Set.empty extract - where - extract :: Name (Scoped S.SrcSpanInfo) -> Set String - extract (Ident _ n) = Set.singleton n - extract (Symbol _ n) = Set.singleton n - - -hasFromJust :: Exp (Scoped S.SrcSpanInfo) -> Exp (Scoped S.SrcSpanInfo) -> Bool -hasFromJust mExpr expr = notNull $ listify isFromJustApp expr - where - isFromJustApp :: Exp (Scoped S.SrcSpanInfo) -> Bool - isFromJustApp (App _ (Var _ vn) maybeVal) = - hasName (Just "Data.Maybe") "fromJust" vn && fmap void maybeVal == fmap void mExpr - isFromJustApp _ = False - -asCaseExpression :: String -> Exp a -> Exp a -> Exp a -> 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 (void maybeValue) (void justCase)) Nothing - ] - -replaceFromJustWithValue :: String -> Exp () -> Exp () -> Exp () -replaceFromJustWithValue valueName maybeValue = everywhere $ mkT replace - where - replace (App () (Var () (UnQual _ (Ident () "fromJust"))) fnBody) - | fnBody == maybeValue = Var () (UnQual () (Ident () valueName)) - replace expr = 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 - ------------------------------------------------------------------------------ -- | Twin map for monadic transformation -- diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 9e5a015..84293d7 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -39,7 +39,7 @@ import qualified Data.String.Interpolate as SI (i, iii) import Haskell.Template.FileContents (testHelperContents, testHarnessContents) import Haskell.Template.Match - (Location (..), Result (..), What (..), Where (..), highlight_ssi, collectIfsWithMaybeChecks) + (Location (..), Result (..), What (..), Where (..), highlight_ssi) import qualified Haskell.Template.Match as Match (test) import Control.Applicative ((<|>)) @@ -84,6 +84,7 @@ import Text.PrettyPrint.Leijen.Text import Text.Read (readMaybe) import Text.Regex.PCRE.Heavy (re, sub, (=~)) import Language.Haskell.Names (loadBase, annotate) +import Haskell.Template.Detection (collectIfsWithMaybeChecks) encode :: ToJSON a => a -> BS.ByteString encode = encodePretty $ setConfCompare compare defConfig From 62442933c8b0b6f4330fc0b2ca17e538bcbd6fcb Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:15:17 +0000 Subject: [PATCH 20/99] add more configuration options --- src/Haskell/Template/Task.hs | 61 ++++++++++++++++++++++--------- test/Haskell/Template/TaskSpec.hs | 40 +++++++++++++------- 2 files changed, 70 insertions(+), 31 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 84293d7..cde5e14 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -29,6 +29,7 @@ module Haskell.Template.Task ( toMaybeSolutionConfig, unsafeTemplateSegment, getMaybeFeedback, + MaybeCaseOfOpportunityDetectionSetting (..) ) where import qualified Data.ByteString.Char8 as BS @@ -80,7 +81,7 @@ import System.FilePath ( ) import Test.HUnit (Counts (..)) import Text.PrettyPrint.Leijen.Text - (Doc, (<+>), empty, int, linebreak, nest, punctuate, text, vcat, indent) + (Doc, (<+>), empty, int, linebreak, nest, punctuate, text, vcat, indent, (<$$>)) import Text.Read (readMaybe) import Text.Regex.PCRE.Heavy (re, sub, (=~)) import Language.Haskell.Names (loadBase, annotate) @@ -112,8 +113,14 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# configHlintSuggestions - hlint hints to provide as suggestions \# configLanguageExtensions - this sets LanguageExtensions for hlint as well; \# defaults to NPlusKPatterns + ScopedTypeVariables -\# suggestMaybeCaseOfUsage - suggest if-statements containing checks on maybe values to be replaced with -\# case-of expressions +\# +\# detectOpportunitiesToUseCaseOfWithMaybe - configuration for detection of opportunities to use +\# case-of expressions with Maybe values (instead of if-expressions) +\# enabled - whether the detection of opportunities should apply +\# rejectOnOpportunity - whether to reject the submission when an opportunity is found +\# provideSuggestion - whether to show the replacement using a case-of expression +\# additionalMessage - optional message to show; defaults to no message +\# \# 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): @@ -218,6 +225,13 @@ data FeedbackPhase | TestSuite deriving (Enum, Eq, Generic, Show, FromJSON, ToJSON) +data MaybeCaseOfOpportunityDetectionSetting = MaybeCaseOfOpportunityDetectionSetting { + enabled :: Bool, + rejectOnOpportunity :: Bool, + provideSuggestion :: Bool, + additionalMessage :: Maybe String + } deriving (Generic, Show, FromJSON, ToJSON) + data FSolutionConfig m = SolutionConfig { allowAdding :: m Bool, allowModifying :: m Bool, @@ -234,7 +248,7 @@ data FSolutionConfig m = SolutionConfig { configHlintRules :: m [String], configHlintSuggestions :: m [String], configLanguageExtensions :: m [String], - suggestMaybeCaseOfUsage :: m Bool, + detectOpportunitiesToUseCaseOfWithMaybe :: m MaybeCaseOfOpportunityDetectionSetting, maxLineLength :: m (Maybe Natural), provideSampleSolution :: m Bool, messageOnCloningSampleSolution :: m (Maybe String), @@ -272,7 +286,12 @@ defaultSolutionConfig = SolutionConfig { configHlintRules = Just [], configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], - suggestMaybeCaseOfUsage = Just False, + detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { + enabled = False, + rejectOnOpportunity = False, + provideSuggestion = True, + additionalMessage = Nothing + }, maxLineLength = Just Nothing, provideSampleSolution = Nothing, messageOnCloningSampleSolution = Just Nothing, @@ -298,7 +317,7 @@ toSolutionConfigOpt SolutionConfig {..} = runIdentity $ SolutionConfig <*> fmap Just configHlintRules <*> fmap Just configHlintSuggestions <*> fmap Just configLanguageExtensions - <*> fmap Just suggestMaybeCaseOfUsage + <*> fmap Just detectOpportunitiesToUseCaseOfWithMaybe <*> fmap Just maxLineLength <*> fmap Just provideSampleSolution <*> fmap Just messageOnCloningSampleSolution @@ -323,7 +342,7 @@ toMaybeSolutionConfig SolutionConfig{..} = SolutionConfig <*> fmap Identity configHlintRules <*> fmap Identity configHlintSuggestions <*> fmap Identity configLanguageExtensions - <*> fmap Identity suggestMaybeCaseOfUsage + <*> fmap Identity detectOpportunitiesToUseCaseOfWithMaybe <*> fmap Identity maxLineLength <*> fmap Identity provideSampleSolution <*> fmap Identity messageOnCloningSampleSolution @@ -348,7 +367,8 @@ combineConfigs x y = SolutionConfig { configHlintRules = configHlintRules x <|> configHlintRules y, configHlintSuggestions = configHlintSuggestions x <|> configHlintSuggestions y, configLanguageExtensions = configLanguageExtensions x <|> configLanguageExtensions y, - suggestMaybeCaseOfUsage = suggestMaybeCaseOfUsage x <|> suggestMaybeCaseOfUsage y, + detectOpportunitiesToUseCaseOfWithMaybe + = detectOpportunitiesToUseCaseOfWithMaybe x <|> detectOpportunitiesToUseCaseOfWithMaybe y, maxLineLength = maxLineLength x <|> maxLineLength y, provideSampleSolution = provideSampleSolution x <|> provideSampleSolution y, messageOnCloningSampleSolution = messageOnCloningSampleSolution x <|> messageOnCloningSampleSolution y, @@ -576,16 +596,18 @@ getHlintFeedback documentInfo config dir file selectHints = case hints of getMaybeFeedback :: MonadIO m => (Doc -> m a) + -> MaybeCaseOfOpportunityDetectionSetting -> E.Module E.SrcSpanInfo -> m [a] -getMaybeFeedback documentInfo ast = do +getMaybeFeedback documentInfo MaybeCaseOfOpportunityDetectionSetting{..} ast = do env <- liftIO loadBase sequence $ flip map (collectIfsWithMaybeChecks (annotate env ast)) $ \(foundIf,caseReplacement) -> documentInfo $ vcat - [ "Found:" - , indent 2 $ text $ pack $ E.prettyPrint foundIf - , "Perhaps:" - , indent 2 $ text $ pack $ E.prettyPrint caseReplacement + [ string "Found:" <$$> indent 2 (text $ pack $ E.prettyPrint foundIf) + , if provideSuggestion + then string "Perhaps:" <$$> indent 2 (text $ pack $ E.prettyPrint caseReplacement) + else empty + , maybe empty ((linebreak <>). string) additionalMessage ] editFeedback :: String -> String @@ -985,13 +1007,13 @@ testPhases reject inform template submissionFile modules config exts submission , -- Reject if GHC warnings configured as errors are triggered by submission. compileWithArgsAndCheck dirname reject rejectWithHint config noTest configGhcErrors - , + , do -- Reject if HLint warnings configured as errors are triggered by submission. void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors - , + -- Reject if suggestions involving checks on maybe values are present - when (runIdentity $ suggestMaybeCaseOfUsage config) $ do - void $ getMaybeFeedback inform submissionAST + when (enabled maybeDetectionConfig && rejectOnOpportunity maybeDetectionConfig) $ do + void $ getMaybeFeedback reject maybeDetectionConfig submissionAST , -- Reject on task template violations according to settings (modifying, adding, deleting). matchTemplate reject config 2 exts template submission submissionAST @@ -1007,8 +1029,13 @@ testPhases reject inform template submissionFile modules config exts submission -- Displays HLint suggestions configured as non-errors triggered by submission. void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions + + -- Reject if suggestions involving checks on maybe values are present + when (enabled maybeDetectionConfig) $ do + void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] where + maybeDetectionConfig = runIdentity $ detectOpportunitiesToUseCaseOfWithMaybe config noTest = delete "Test" modules rejectWithHint = rejectWithMessage reject rejectHint diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 70af941..adce363 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) @@ -81,16 +82,21 @@ spec = do `shouldReturn` [Left "Warning: Use dilated"] describe "maybe feedback" $ do it "should suggest replacing if with case-of when applicable (isJust)" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO False (Just "Is there maybe a better way to express this?") [SI.i| module Main where import Data.Maybe def :: Maybe Int -> Int def mVal = if isNothing mVal then -3 else fromJust mVal|] - length result `shouldBe` 1 + 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 (isNothing)" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -99,7 +105,7 @@ spec = do length result `shouldBe` 1 it "should suggest replacing if with case-of when applicable (== Nothing)" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -108,7 +114,7 @@ spec = do length result `shouldBe` 1 it "should suggest replacing if with case-of when applicable (/= Nothing)" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -117,7 +123,7 @@ spec = do length result `shouldBe` 1 it "should not suggest replacing if with case-of when condition is mixed" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -126,7 +132,7 @@ spec = do length result `shouldBe` 0 it "should not suggest replacing if with case-of when condition is comparison with Just value" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -135,7 +141,7 @@ spec = do length result `shouldBe` 0 it "should not suggest replacing if with case-of when value is not used" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -144,7 +150,7 @@ spec = do length result `shouldBe` 0 it "replacement should not introduce variable names that are already used or will be user later" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -169,7 +175,7 @@ Perhaps: Just value' -> let value = 5 in value'|] ] it "should not suggest replacing if with case-of when isJust, fromJust, etc. are not from Data.Maybe" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -183,7 +189,7 @@ Perhaps: length result `shouldBe` 0 it "should not suggest replacing if with case-of when fromJust is used on shadowed maybe value" $ do - result <- maybeCheckIO [SI.i| + result <- maybeCheckIO True Nothing [SI.i| module Main where import Data.Maybe @@ -383,10 +389,16 @@ hlintIO config content display selectHints = do firstLineOf (y:ys) = y : firstLineOf ys firstLineOf [] = [] -maybeCheckIO :: String -> IO [String] -maybeCheckIO code = do +maybeCheckIO :: Bool -> Maybe String -> String -> IO [String] +maybeCheckIO provideSuggestion additionalMessage code = do codeAST <- parse (fail . show) [] code - getMaybeFeedback (pure . show) codeAST + let config = MaybeCaseOfOpportunityDetectionSetting { + enabled = True, + rejectOnOpportunity = False, + provideSuggestion, + additionalMessage + } + getMaybeFeedback (pure . show) config codeAST render :: PP.Doc -> String render = unpack . PP.displayT . PP.renderPretty 1.0 100 From ce5bbba763b606cd628c31e0cd804c58254bfe95 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:55:02 +0000 Subject: [PATCH 21/99] reject with hint --- src/Haskell/Template/Task.hs | 6 +++--- test/Haskell/Template/TaskSpec.hs | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index cde5e14..94575ca 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -81,7 +81,7 @@ import System.FilePath ( ) import Test.HUnit (Counts (..)) import Text.PrettyPrint.Leijen.Text - (Doc, (<+>), empty, int, linebreak, nest, punctuate, text, vcat, indent, (<$$>)) + (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) @@ -607,7 +607,7 @@ getMaybeFeedback documentInfo MaybeCaseOfOpportunityDetectionSetting{..} ast = d , if provideSuggestion then string "Perhaps:" <$$> indent 2 (text $ pack $ E.prettyPrint caseReplacement) else empty - , maybe empty ((linebreak <>). string) additionalMessage + , maybe empty (enclose linebreak linebreak . string) additionalMessage ] editFeedback :: String -> String @@ -1013,7 +1013,7 @@ testPhases reject inform template submissionFile modules config exts submission -- Reject if suggestions involving checks on maybe values are present when (enabled maybeDetectionConfig && rejectOnOpportunity maybeDetectionConfig) $ do - void $ getMaybeFeedback reject maybeDetectionConfig submissionAST + void $ getMaybeFeedback rejectWithHint maybeDetectionConfig submissionAST , -- Reject on task template violations according to settings (modifying, adding, deleting). matchTemplate reject config 2 exts template submission submissionAST diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index adce363..494fc88 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -93,7 +93,8 @@ spec = do [SI.i|Found: if isNothing mVal then -3 else fromJust mVal -Is there maybe a better way to express this?|] +Is there maybe a better way to express this? +|] ] it "should suggest replacing if with case-of when applicable (isNothing)" $ do result <- maybeCheckIO True Nothing [SI.i| From bd7e4200478d734481ddbac4d3d6c77794d9e512 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:05:03 +0000 Subject: [PATCH 22/99] allow word --- .github/actions/spelling/allow.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index e7e877e..dd954e4 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -23,6 +23,7 @@ msum mzero PApp QName +QOp QVar snd thd From e3d63bd3483d32178c797c6870322c74ccb5a1cd Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:07:04 +0000 Subject: [PATCH 23/99] allow pattern --- .github/actions/spelling/patterns.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/spelling/patterns.txt b/.github/actions/spelling/patterns.txt index b7106d6..45d90dc 100644 --- a/.github/actions/spelling/patterns.txt +++ b/.github/actions/spelling/patterns.txt @@ -6,6 +6,7 @@ \b[Ll]og in to\b # acceptable duplicates +linebreak linebreak # ls directory listings [-bcdlpsw](?:[-r][-w][-Ssx]){3}\s+\d+\s+\S+\s+\S+\s+\d+\s+ From 42968c5b90dd07fa6191988baae95dbd2f92de42 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 20:17:28 +0000 Subject: [PATCH 24/99] don't run check again when check was run before --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 94575ca..3157512 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -1031,7 +1031,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions -- Reject if suggestions involving checks on maybe values are present - when (enabled maybeDetectionConfig) $ do + when (enabled maybeDetectionConfig && not (rejectOnOpportunity maybeDetectionConfig)) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] where From d219ef47078fc3490fdb3a256290bb8d5178a02b Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:17:36 +0000 Subject: [PATCH 25/99] add more test cases --- test/Haskell/Template/TaskSpec.hs | 93 +++++++++++++++++++++++++++++-- 1 file changed, 89 insertions(+), 4 deletions(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 494fc88..6f34b4e 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -155,11 +155,31 @@ Is there maybe a better way to express this? module Main where import Data.Maybe - def :: Maybe Int -> Int def mVal = let value = -3 in if isJust mVal then fromJust mVal else value - def2 :: Maybe Int -> Int - def2 mVal = if isJust mVal then let value = 5 in fromJust mVal else -3|] + 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: @@ -173,7 +193,72 @@ Perhaps: Perhaps: case mVal of Nothing -> -3 - Just value' -> let value = 5 in value'|] + 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 "should suggest replacement even when nested" $ do + result <- maybeCheckIO True Nothing [SI.i| + module Main where + import Data.Maybe + + def :: Maybe (Maybe Int) -> Int + def mVal = if isJust mVal then if isJust (fromJust mVal) then 2 * fromJust (fromJust mVal) else 0 else -1|] + + result `shouldBe` [ + [SI.i|Found: + if isJust mVal then + if isJust (fromJust mVal) then 2 * fromJust (fromJust mVal) else 0 + else -1 +Perhaps: + case mVal of + Nothing -> -1 + Just value -> if isJust (value) then 2 * fromJust (value) else 0|], + [SI.i|Found: + if isJust (fromJust mVal) then 2 * fromJust (fromJust mVal) else 0 +Perhaps: + case (fromJust mVal) 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 True Nothing [SI.i| From d6c5a9c6e4b870d02c2092463609de7e239b0d8c Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:23:35 +0000 Subject: [PATCH 26/99] update documentation of config settings --- src/Haskell/Template/Task.hs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 3157512..926e26d 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -115,9 +115,11 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# defaults to NPlusKPatterns + ScopedTypeVariables \# \# detectOpportunitiesToUseCaseOfWithMaybe - configuration for detection of opportunities to use -\# case-of expressions with Maybe values (instead of if-expressions) +\# case-of expressions with Maybe values (instead of if-expressions); +\# this is part of the phase including hlint checks \# enabled - whether the detection of opportunities should apply -\# rejectOnOpportunity - whether to reject the submission when an opportunity is found +\# rejectOnOpportunity - whether to reject the submission when an opportunity is found; +\# the error will only surface if there are no hlint errors present \# provideSuggestion - whether to show the replacement using a case-of expression \# additionalMessage - optional message to show; defaults to no message \# From f6601c21a6c125221b81ea444a3cb6316f520990 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sun, 8 Nov 2026 09:04:39 +0100 Subject: [PATCH 27/99] Fix comments in Task.hs for clarity --- src/Haskell/Template/Task.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 926e26d..bfa3063 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -116,10 +116,10 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# \# detectOpportunitiesToUseCaseOfWithMaybe - configuration for detection of opportunities to use \# case-of expressions with Maybe values (instead of if-expressions); -\# this is part of the phase including hlint checks +\# this is part of the phase(s) including hlint checks \# enabled - whether the detection of opportunities should apply \# rejectOnOpportunity - whether to reject the submission when an opportunity is found; -\# the error will only surface if there are no hlint errors present +\# an error will only surface if there are no hlint errors present \# provideSuggestion - whether to show the replacement using a case-of expression \# additionalMessage - optional message to show; defaults to no message \# From 0e3fd0b0ae0913d11da841d5a967a967cd0b9f04 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:10:26 +0000 Subject: [PATCH 28/99] only suggest if scrutinee is variable --- src/Haskell/Template/Detection.hs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index 5fdad1f..8ad35a0 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -77,9 +77,11 @@ exprToIfInfo expr@(If _ cond t e) = case removeParens cond of | isNothingExpression r = Just l | otherwise = Nothing - transform mVal j n - | hasFromJust mVal j = Just (expr, asCaseExpression "_valueNamePlaceholder" mVal j n) - | otherwise = Nothing + transform mValExpr j n = case removeParens mValExpr of + mVal@(Var _ _) + | hasFromJust mVal j -> Just (expr, asCaseExpression "_valueNamePlaceholder" mVal j n) + | otherwise -> Nothing + _ -> Nothing exprToIfInfo _ = Nothing allNames :: Data a => a -> Set String From a06535e7e525e122228d26a94342b7396e505d47 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:10:43 +0000 Subject: [PATCH 29/99] update tests --- test/Haskell/Template/TaskSpec.hs | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 6f34b4e..00fb833 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -241,22 +241,23 @@ Perhaps: module Main where import Data.Maybe - def :: Maybe (Maybe Int) -> Int - def mVal = if isJust mVal then if isJust (fromJust mVal) then 2 * fromJust (fromJust mVal) else 0 else -1|] + def :: Maybe Int -> Maybe Int -> Int + def mVal1 mVal 2 = if isJust mVal1 then fromJust mVal1 + if isJust mVal2 then 2 * fromJust mVal2 else 0 else -1|] result `shouldBe` [ [SI.i|Found: - if isJust mVal then - if isJust (fromJust mVal) then 2 * fromJust (fromJust mVal) else 0 + if isJust mVal1 then + fromJust mVal1 + if isJust mVal2 then 2 * fromJust mVal2 else 0 else -1 Perhaps: - case mVal of + case mVal1 of Nothing -> -1 - Just value -> if isJust (value) then 2 * fromJust (value) else 0|], + Just value -> value + + if isJust mVal2 then 2 * fromJust mVal2 else 0|], [SI.i|Found: - if isJust (fromJust mVal) then 2 * fromJust (fromJust mVal) else 0 + if isJust mVal2 then 2 * fromJust mVal2 else 0 Perhaps: - case (fromJust mVal) of + case mVal2 of Nothing -> 0 Just value -> 2 * value|] ] @@ -266,13 +267,22 @@ Perhaps: import Data.Maybe def :: Maybe Int -> Int - def mVal = if isJust mVal then 5 else -3 + 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|] + length result `shouldBe` 0 + it "should not suggest replacing if with case-of when scrutinee is not a variable" $ do + result <- maybeCheckIO True Nothing [SI.i| + module Main where + import Data.Maybe + + def :: a -> (a -> Maybe Int) -> Int + def val f = if isJust (f val) then fromMaybe (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 True Nothing [SI.i| From 023683823a090886736b98ce713e877c907ffd07 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:32:29 +0000 Subject: [PATCH 30/99] update handling of redundant brackets --- src/Haskell/Template/Detection.hs | 13 +++++++------ test/Haskell/Template/TaskSpec.hs | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index 8ad35a0..dfc17fa 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -2,7 +2,7 @@ module Haskell.Template.Detection (collectIfsWithMaybeChecks) where import Control.Monad (guard, void) import Data.Data (Data) -import Data.Generics (everything, everywhere, listify, mkQ, mkT) +import Data.Generics (everything, everywhere, listify, mkQ, mkT, everywhere') import Data.List.Extra (notNull) import Data.Maybe (listToMaybe, mapMaybe, maybeToList) import Data.Set (Set) @@ -96,7 +96,7 @@ 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 maybeVal == fmap void mExpr + hasName (Just "Data.Maybe") "fromJust" vn && fmap void (removeParens maybeVal) == fmap void mExpr isFromJustApp _ = False asCaseExpression :: String -> Exp a -> Exp a -> Exp a -> Exp () @@ -113,11 +113,12 @@ asCaseExpression valueName maybeValue justCase nothingCase = ] replaceFromJustWithValue :: String -> Exp () -> Exp () -> Exp () -replaceFromJustWithValue valueName maybeValue = everywhere $ mkT replace +replaceFromJustWithValue valueName maybeValue = everywhere' $ mkT replace where - replace (App () (Var () (UnQual _ (Ident () "fromJust"))) fnBody) - | fnBody == maybeValue = Var () (UnQual () (Ident () valueName)) - replace expr = expr + replace expr = case removeParens expr of + App () (Var () (UnQual _ (Ident () "fromJust"))) fnBody + | removeParens fnBody == maybeValue -> Var () (UnQual () (Ident () valueName)) + _ -> expr removeParens :: Exp a -> Exp a removeParens (Paren _ e) = removeParens e diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 00fb833..787b24a 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -293,6 +293,22 @@ Perhaps: 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 True Nothing [SI.i| + module Main 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|] + ] describe "grade" $ do it "is running" $ gradeIO completedDefaultCode useImport `shouldReturn` "" From 90ceaa99f15a467a9850a0f0dc46d5a929e708e0 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:56:34 +0000 Subject: [PATCH 31/99] refactor config options --- src/Haskell/Template/Task.hs | 23 ++++++++++++-------- test/Haskell/Template/TaskSpec.hs | 36 +++++++++++++++---------------- 2 files changed, 32 insertions(+), 27 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index bfa3063..0c0dd20 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -228,9 +228,9 @@ data FeedbackPhase deriving (Enum, Eq, Generic, Show, FromJSON, ToJSON) data MaybeCaseOfOpportunityDetectionSetting = MaybeCaseOfOpportunityDetectionSetting { - enabled :: Bool, - rejectOnOpportunity :: Bool, - provideSuggestion :: Bool, + asSuggestion :: Maybe Bool, + asError :: Maybe Bool, + provideSuggestion :: Maybe Bool, additionalMessage :: Maybe String } deriving (Generic, Show, FromJSON, ToJSON) @@ -289,9 +289,9 @@ defaultSolutionConfig = SolutionConfig { configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { - enabled = False, - rejectOnOpportunity = False, - provideSuggestion = True, + asSuggestion = Just True, + asError = Nothing, + provideSuggestion = Just True, additionalMessage = Nothing }, maxLineLength = Just Nothing, @@ -392,6 +392,11 @@ check check reject inform path i = do checkUnsafe reject i (config@SolutionConfig{..}, exts, (m,s), ms) <- processConfig reject inform i + + let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe + when (Just True == asSuggestion maybeDetectionConfig && Just True == asError maybeDetectionConfig) + $ reject "Cannot set both 'asSuggestion' and 'asError' to 'true' at 'detectOpportunitiesToUseCaseOfWithMaybe'." + checkUniqueness (m : map fst ms) inform $ string $ "Parsing template module " <> m void $ parse reject exts s @@ -606,7 +611,7 @@ getMaybeFeedback documentInfo MaybeCaseOfOpportunityDetectionSetting{..} ast = d sequence $ flip map (collectIfsWithMaybeChecks (annotate env ast)) $ \(foundIf,caseReplacement) -> documentInfo $ vcat [ string "Found:" <$$> indent 2 (text $ pack $ E.prettyPrint foundIf) - , if provideSuggestion + , if fromMaybe False provideSuggestion then string "Perhaps:" <$$> indent 2 (text $ pack $ E.prettyPrint caseReplacement) else empty , maybe empty (enclose linebreak linebreak . string) additionalMessage @@ -1014,7 +1019,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors -- Reject if suggestions involving checks on maybe values are present - when (enabled maybeDetectionConfig && rejectOnOpportunity maybeDetectionConfig) $ do + when (fromMaybe False $ asError maybeDetectionConfig) $ do void $ getMaybeFeedback rejectWithHint maybeDetectionConfig submissionAST , -- Reject on task template violations according to settings (modifying, adding, deleting). @@ -1033,7 +1038,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions -- Reject if suggestions involving checks on maybe values are present - when (enabled maybeDetectionConfig && not (rejectOnOpportunity maybeDetectionConfig)) $ do + when (fromMaybe False $ asSuggestion maybeDetectionConfig) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] where diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 787b24a..c4380be 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -82,7 +82,7 @@ spec = do `shouldReturn` [Left "Warning: Use dilated"] describe "maybe feedback" $ do it "should suggest replacing if with case-of when applicable (isJust)" $ do - result <- maybeCheckIO False (Just "Is there maybe a better way to express this?") [SI.i| + result <- maybeCheckIO False False (Just "Is there maybe a better way to express this?") [SI.i| module Main where import Data.Maybe @@ -97,7 +97,7 @@ Is there maybe a better way to express this? |] ] it "should suggest replacing if with case-of when applicable (isNothing)" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -106,7 +106,7 @@ Is there maybe a better way to express this? length result `shouldBe` 1 it "should suggest replacing if with case-of when applicable (== Nothing)" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -115,7 +115,7 @@ Is there maybe a better way to express this? length result `shouldBe` 1 it "should suggest replacing if with case-of when applicable (/= Nothing)" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -124,7 +124,7 @@ Is there maybe a better way to express this? length result `shouldBe` 1 it "should not suggest replacing if with case-of when condition is mixed" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -133,7 +133,7 @@ Is there maybe a better way to express this? length result `shouldBe` 0 it "should not suggest replacing if with case-of when condition is comparison with Just value" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -142,7 +142,7 @@ Is there maybe a better way to express this? length result `shouldBe` 0 it "should not suggest replacing if with case-of when value is not used" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -151,7 +151,7 @@ Is there maybe a better way to express this? length result `shouldBe` 0 it "replacement should not introduce variable names that are already used or will be user later" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -237,7 +237,7 @@ Perhaps: pure $ value' value|] ] it "should suggest replacement even when nested" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -262,7 +262,7 @@ Perhaps: 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 True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -276,7 +276,7 @@ Perhaps: length result `shouldBe` 0 it "should not suggest replacing if with case-of when scrutinee is not a variable" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -285,7 +285,7 @@ Perhaps: length result `shouldBe` 0 it "should not suggest replacing if with case-of when fromJust is used on shadowed maybe value" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -294,7 +294,7 @@ Perhaps: length result `shouldBe` 0 it "replacement should not use redundant brackets" $ do - result <- maybeCheckIO True Nothing [SI.i| + result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -501,13 +501,13 @@ hlintIO config content display selectHints = do firstLineOf (y:ys) = y : firstLineOf ys firstLineOf [] = [] -maybeCheckIO :: Bool -> Maybe String -> String -> IO [String] -maybeCheckIO provideSuggestion additionalMessage code = do +maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] +maybeCheckIO asError provideSuggestion additionalMessage code = do codeAST <- parse (fail . show) [] code let config = MaybeCaseOfOpportunityDetectionSetting { - enabled = True, - rejectOnOpportunity = False, - provideSuggestion, + asSuggestion = Just $ not asError, + asError = Just asError, + provideSuggestion = Just provideSuggestion, additionalMessage } getMaybeFeedback (pure . show) config codeAST From cef905aa4064060f99a40441db4654fccfd860c1 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:16:33 +0000 Subject: [PATCH 32/99] update documentation for default config --- src/Haskell/Template/Task.hs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 0c0dd20..65cf40c 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -117,11 +117,15 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# 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 -\# enabled - whether the detection of opportunities should apply -\# rejectOnOpportunity - whether to reject the submission when an opportunity is found; -\# an error will only surface if there are no hlint errors present -\# provideSuggestion - whether to show the replacement using a case-of expression -\# additionalMessage - optional message to show; defaults to no message +\# asSuggestion - whether detected opportunities should be reported as suggestions; +\# defaults to true +\# asError - whether detected opportunities should be reported as errors; +\# optional; defaults to false; cannot be enabled together +\# with 'asSuggestion'; +\# an error will only surface if there are no hlint errors present +\# provideSuggestion - whether to show the replacement using a case-of expression; +\# optional; defaults to true +\# additionalMessage - optional message to show; defaults to no message \# \# 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); From 2d2c1a6800598e50448d8109968bc3039dd4de60 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:34:21 +0000 Subject: [PATCH 33/99] allow word --- .github/actions/spelling/allow.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index dd954e4..8c072ee 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -25,6 +25,7 @@ PApp QName QOp QVar +scrutinee snd thd uncurry From 50614b511a8c9f4e8ddc4c6a12cd4fa8ffd788c6 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:35:09 +0000 Subject: [PATCH 34/99] trailing whitespace --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 65cf40c..14d7f6e 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -120,7 +120,7 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# asSuggestion - whether detected opportunities should be reported as suggestions; \# defaults to true \# asError - whether detected opportunities should be reported as errors; -\# optional; defaults to false; cannot be enabled together +\# optional; defaults to false; cannot be enabled together \# with 'asSuggestion'; \# an error will only surface if there are no hlint errors present \# provideSuggestion - whether to show the replacement using a case-of expression; From 79f8e784de1b3dedb8be546fd27a33cfd36437c3 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:37:26 +0000 Subject: [PATCH 35/99] allow pattern --- .github/actions/spelling/patterns.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/spelling/patterns.txt b/.github/actions/spelling/patterns.txt index 45d90dc..4d0dba3 100644 --- a/.github/actions/spelling/patterns.txt +++ b/.github/actions/spelling/patterns.txt @@ -7,6 +7,7 @@ # acceptable duplicates linebreak linebreak +False False # ls directory listings [-bcdlpsw](?:[-r][-w][-Ssx]){3}\s+\d+\s+\S+\s+\S+\s+\d+\s+ From f39f54d97e6e8fb6454f15b81667fbe0d3a198b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sun, 8 Nov 2026 16:36:34 +0100 Subject: [PATCH 36/99] Fix typo in comments for hlint configuration --- src/Haskell/Template/Task.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 14d7f6e..64ace2a 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -107,7 +107,7 @@ 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 @@ -122,7 +122,7 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# asError - whether detected opportunities should be reported as errors; \# optional; defaults to false; cannot be enabled together \# with 'asSuggestion'; -\# an error will only surface if there are no hlint errors present +\# an error (the first one) will only surface if there are no hlint errors present \# provideSuggestion - whether to show the replacement using a case-of expression; \# optional; defaults to true \# additionalMessage - optional message to show; defaults to no message From ce021f735670c08ddc116789954d8af01d705770 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:23:20 +0000 Subject: [PATCH 37/99] make asSuggestion required --- src/Haskell/Template/Task.hs | 8 ++++---- test/Haskell/Template/TaskSpec.hs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 64ace2a..1ca6a8a 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -232,7 +232,7 @@ data FeedbackPhase deriving (Enum, Eq, Generic, Show, FromJSON, ToJSON) data MaybeCaseOfOpportunityDetectionSetting = MaybeCaseOfOpportunityDetectionSetting { - asSuggestion :: Maybe Bool, + asSuggestion :: Bool, asError :: Maybe Bool, provideSuggestion :: Maybe Bool, additionalMessage :: Maybe String @@ -293,7 +293,7 @@ defaultSolutionConfig = SolutionConfig { configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { - asSuggestion = Just True, + asSuggestion = True, asError = Nothing, provideSuggestion = Just True, additionalMessage = Nothing @@ -398,7 +398,7 @@ check reject inform path i = do (config@SolutionConfig{..}, exts, (m,s), ms) <- processConfig reject inform i let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe - when (Just True == asSuggestion maybeDetectionConfig && Just True == asError maybeDetectionConfig) + when (asSuggestion maybeDetectionConfig && Just True == asError maybeDetectionConfig) $ reject "Cannot set both 'asSuggestion' and 'asError' to 'true' at 'detectOpportunitiesToUseCaseOfWithMaybe'." checkUniqueness (m : map fst ms) @@ -1042,7 +1042,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions -- Reject if suggestions involving checks on maybe values are present - when (fromMaybe False $ asSuggestion maybeDetectionConfig) $ do + when (asSuggestion maybeDetectionConfig) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] where diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index c4380be..4618844 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -505,7 +505,7 @@ maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] maybeCheckIO asError provideSuggestion additionalMessage code = do codeAST <- parse (fail . show) [] code let config = MaybeCaseOfOpportunityDetectionSetting { - asSuggestion = Just $ not asError, + asSuggestion = not asError, asError = Just asError, provideSuggestion = Just provideSuggestion, additionalMessage From 5d21071cd613ab469d45ae8eadd2fc6aeecf7975 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:31:41 +0000 Subject: [PATCH 38/99] more config checks --- src/Haskell/Template/Task.hs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 1ca6a8a..50960b4 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -56,7 +56,7 @@ import Data.List ) import Data.List.Extra (genericTake, nubOrd, replace, takeEnd, takeWhileEnd) -import Data.Maybe (fromMaybe) +import Data.Maybe (fromMaybe, isJust) import Data.Text.Lazy (pack) import Data.Typeable (Typeable) import Data.Yaml @@ -398,8 +398,19 @@ check reject inform path i = do (config@SolutionConfig{..}, exts, (m,s), ms) <- processConfig reject inform i let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe - when (asSuggestion maybeDetectionConfig && Just True == asError maybeDetectionConfig) - $ reject "Cannot set both 'asSuggestion' and 'asError' to 'true' at 'detectOpportunitiesToUseCaseOfWithMaybe'." + case (asSuggestion maybeDetectionConfig, fromMaybe False $ asError maybeDetectionConfig) of + (True, True) -> + reject "Cannot set both 'asSuggestion' and 'asError' to 'true' at 'detectOpportunitiesToUseCaseOfWithMaybe'." + (False,False) + | isJust (provideSuggestion maybeDetectionConfig) -> + reject + $ "Cannot set 'provideSuggestion' to true when neither 'asSuggestion' nor 'asError'" + <> " is set to true at 'detectOpportunitiesToUseCaseOfWithMaybe'." + | isJust (additionalMessage maybeDetectionConfig) -> + reject + $ "Cannot set value for 'additionalMessage' neither 'asSuggestion' nor 'asError'" + <> " is set to true at 'detectOpportunitiesToUseCaseOfWithMaybe'." + _ -> pure () checkUniqueness (m : map fst ms) inform $ string $ "Parsing template module " <> m From 2018097e2afb19ef47a5cc2598c393d73b9f68b9 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:32:50 +0000 Subject: [PATCH 39/99] update comment --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 50960b4..b869e0b 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -1052,7 +1052,7 @@ testPhases reject inform template submissionFile modules config exts submission -- Displays HLint suggestions configured as non-errors triggered by submission. void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions - -- Reject if suggestions involving checks on maybe values are present + -- Display suggestions involving checks on maybe values are present when (asSuggestion maybeDetectionConfig) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] From 3f88a485dffc60e1676d2e0f518409dbc4e1b276 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:45:07 +0000 Subject: [PATCH 40/99] add new status datatype and replace asSuggestion and asError --- src/Haskell/Template/Task.hs | 41 +++++++++++++++---------------- test/Haskell/Template/TaskSpec.hs | 3 +-- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index b869e0b..3d0825d 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -29,7 +29,8 @@ module Haskell.Template.Task ( toMaybeSolutionConfig, unsafeTemplateSegment, getMaybeFeedback, - MaybeCaseOfOpportunityDetectionSetting (..) + MaybeCaseOfOpportunityDetectionSetting (..), + Status (..), ) where import qualified Data.ByteString.Char8 as BS @@ -117,12 +118,11 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# 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 -\# asSuggestion - whether detected opportunities should be reported as suggestions; -\# defaults to true -\# asError - whether detected opportunities should be reported as errors; -\# optional; defaults to false; cannot be enabled together -\# with 'asSuggestion'; -\# an error (the first one) will only surface if there are no hlint errors present +\# status - status of the checker; can be one of: +\# `Ignore`: disable the detection +\# `Hint`: display the opportunities but don't reject +\# `Reject`: reject the submission and show the first suggestion +\# defaults to `Hint`. \# provideSuggestion - whether to show the replacement using a case-of expression; \# optional; defaults to true \# additionalMessage - optional message to show; defaults to no message @@ -231,9 +231,11 @@ data FeedbackPhase | TestSuite deriving (Enum, Eq, Generic, Show, FromJSON, ToJSON) +data Status = Ignore | Hint | Reject + deriving (Eq, Generic, Show, FromJSON, ToJSON) + data MaybeCaseOfOpportunityDetectionSetting = MaybeCaseOfOpportunityDetectionSetting { - asSuggestion :: Bool, - asError :: Maybe Bool, + status :: Status, provideSuggestion :: Maybe Bool, additionalMessage :: Maybe String } deriving (Generic, Show, FromJSON, ToJSON) @@ -293,8 +295,7 @@ defaultSolutionConfig = SolutionConfig { configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { - asSuggestion = True, - asError = Nothing, + status = Hint, provideSuggestion = Just True, additionalMessage = Nothing }, @@ -398,18 +399,16 @@ check reject inform path i = do (config@SolutionConfig{..}, exts, (m,s), ms) <- processConfig reject inform i let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe - case (asSuggestion maybeDetectionConfig, fromMaybe False $ asError maybeDetectionConfig) of - (True, True) -> - reject "Cannot set both 'asSuggestion' and 'asError' to 'true' at 'detectOpportunitiesToUseCaseOfWithMaybe'." - (False,False) + case status maybeDetectionConfig of + Ignore | isJust (provideSuggestion maybeDetectionConfig) -> reject - $ "Cannot set 'provideSuggestion' to true when neither 'asSuggestion' nor 'asError'" - <> " is set to true at 'detectOpportunitiesToUseCaseOfWithMaybe'." + $ "Cannot set 'provideSuggestion' to true when 'status' is 'Ignore'" + <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." | isJust (additionalMessage maybeDetectionConfig) -> reject - $ "Cannot set value for 'additionalMessage' neither 'asSuggestion' nor 'asError'" - <> " is set to true at 'detectOpportunitiesToUseCaseOfWithMaybe'." + $ "Cannot set 'provideSuggestion' to true when 'status' is 'Ignore'" + <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." _ -> pure () checkUniqueness (m : map fst ms) @@ -1034,7 +1033,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors -- Reject if suggestions involving checks on maybe values are present - when (fromMaybe False $ asError maybeDetectionConfig) $ do + when (Reject == status maybeDetectionConfig) $ do void $ getMaybeFeedback rejectWithHint maybeDetectionConfig submissionAST , -- Reject on task template violations according to settings (modifying, adding, deleting). @@ -1053,7 +1052,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions -- Display suggestions involving checks on maybe values are present - when (asSuggestion maybeDetectionConfig) $ do + when (Hint == status maybeDetectionConfig) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] where diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 4618844..e758efb 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -505,8 +505,7 @@ maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] maybeCheckIO asError provideSuggestion additionalMessage code = do codeAST <- parse (fail . show) [] code let config = MaybeCaseOfOpportunityDetectionSetting { - asSuggestion = not asError, - asError = Just asError, + status = if asError then Reject else Hint, provideSuggestion = Just provideSuggestion, additionalMessage } From c147db05d84ffbd58f930943ef10d69a62fa791b Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:51:32 +0000 Subject: [PATCH 41/99] re-add information regarding dependence on hlint --- src/Haskell/Template/Task.hs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 3d0825d..b918bff 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -121,8 +121,9 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# status - status of the checker; can be one of: \# `Ignore`: disable the detection \# `Hint`: display the opportunities but don't reject -\# `Reject`: reject the submission and show the first suggestion -\# defaults to `Hint`. +\# `Reject`: reject the submission and show the first suggestion if +\# there are no hlint errors present +\# defaults to `Hint`. \# provideSuggestion - whether to show the replacement using a case-of expression; \# optional; defaults to true \# additionalMessage - optional message to show; defaults to no message From 95736270a8098dc2156f06c11dec89d02879616c Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:51:41 +0000 Subject: [PATCH 42/99] fix error message --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index b918bff..c5fa694 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -408,7 +408,7 @@ check reject inform path i = do <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." | isJust (additionalMessage maybeDetectionConfig) -> reject - $ "Cannot set 'provideSuggestion' to true when 'status' is 'Ignore'" + $ "Cannot set 'additionalMessage' to true when 'status' is 'Ignore'" <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." _ -> pure () From a03422cbe8e1da2e18dbacc439930cd5e09b14b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sun, 8 Nov 2026 19:21:40 +0100 Subject: [PATCH 43/99] Clarify comments regarding hlint and maybe checks --- src/Haskell/Template/Task.hs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index c5fa694..89efe5a 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -108,7 +108,7 @@ 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 the 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 @@ -120,13 +120,13 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# 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 but don't reject -\# `Reject`: reject the submission and show the first suggestion if -\# there are no hlint errors present -\# defaults to `Hint`. +\# `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; +\# defaults to `Hint` \# provideSuggestion - whether to show the replacement using a case-of expression; -\# optional; defaults to true -\# additionalMessage - optional message to show; defaults to no message +\# defaults to true +\# additionalMessage - potential message to show; defaults to no message \# \# 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); @@ -408,7 +408,7 @@ check reject inform path i = do <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." | isJust (additionalMessage maybeDetectionConfig) -> reject - $ "Cannot set 'additionalMessage' to true when 'status' is 'Ignore'" + $ "Cannot set an 'additionalMessage' when 'status' is 'Ignore'" <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." _ -> pure () @@ -1033,7 +1033,7 @@ testPhases reject inform template submissionFile modules config exts submission -- Reject if HLint warnings configured as errors are triggered by submission. void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors - -- Reject if suggestions involving checks on maybe values are present + -- Reject if checks on maybe values encounter a hit and were configured to reject. when (Reject == status maybeDetectionConfig) $ do void $ getMaybeFeedback rejectWithHint maybeDetectionConfig submissionAST , @@ -1052,7 +1052,7 @@ testPhases reject inform template submissionFile modules config exts submission -- Displays HLint suggestions configured as non-errors triggered by submission. void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions - -- Display suggestions involving checks on maybe values are present + -- Display suggestions involving checks on maybe values if configured as hints. when (Hint == status maybeDetectionConfig) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] From e8c2f63e2f5860c2e7b6d1249d8c3ea0d655179b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sun, 8 Nov 2026 19:24:23 +0100 Subject: [PATCH 44/99] Fix typo --- test/Haskell/Template/TaskSpec.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index e758efb..86c83f8 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -150,7 +150,7 @@ Is there maybe a better way to express this? 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 user later" $ do + 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 Main where import Data.Maybe From a55238dcf147f220d7d48cf52c94e4db0cefe9f4 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:49:09 +0000 Subject: [PATCH 45/99] overhaul implementation of new config type --- src/Haskell/Template/Task.hs | 89 ++++++++++++++++++++++++------- test/Haskell/Template/TaskSpec.hs | 8 +-- 2 files changed, 73 insertions(+), 24 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 89efe5a..437b55e 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -29,7 +29,8 @@ module Haskell.Template.Task ( toMaybeSolutionConfig, unsafeTemplateSegment, getMaybeFeedback, - MaybeCaseOfOpportunityDetectionSetting (..), + FMaybeCaseOfOpportunityDetectionSetting (..), + MaybeCaseOfOpportunityDetectionSettingOpt, Status (..), ) where @@ -125,7 +126,8 @@ defaultCode = BS.unpack (encode defaultSolutionConfig) ++ \# no errors were reported by hlint, and then at that point; \# defaults to `Hint` \# provideSuggestion - whether to show the replacement using a case-of expression; -\# defaults to true +\# defaults to true if status is not set to `Ignore`; +\# otherwise defaults to false \# additionalMessage - potential message to show; defaults to no message \# \# maxLineLength - submissions with lines longer than this value are rejected; defaults to no limit @@ -235,11 +237,51 @@ data FeedbackPhase data Status = Ignore | Hint | Reject deriving (Eq, Generic, Show, FromJSON, ToJSON) -data MaybeCaseOfOpportunityDetectionSetting = MaybeCaseOfOpportunityDetectionSetting { - status :: Status, - provideSuggestion :: Maybe Bool, - additionalMessage :: Maybe String - } deriving (Generic, Show, FromJSON, ToJSON) +data FMaybeCaseOfOpportunityDetectionSetting m = MaybeCaseOfOpportunityDetectionSetting { + status :: m Status, + provideSuggestion :: m Bool, + additionalMessage :: m (Maybe String) + } deriving (Generic) + +type MaybeCaseOfOpportunityDetectionSettingOpt = FMaybeCaseOfOpportunityDetectionSetting Maybe + +deriving instance Show MaybeCaseOfOpportunityDetectionSettingOpt +deriving instance ToJSON MaybeCaseOfOpportunityDetectionSettingOpt +deriving instance FromJSON MaybeCaseOfOpportunityDetectionSettingOpt + +type MaybeCaseOfOpportunityDetectionSetting = FMaybeCaseOfOpportunityDetectionSetting Identity + +deriving instance Show MaybeCaseOfOpportunityDetectionSetting + +toMaybeCaseOfOpportunityDetectionSettingOpt + :: MaybeCaseOfOpportunityDetectionSetting + -> MaybeCaseOfOpportunityDetectionSettingOpt +toMaybeCaseOfOpportunityDetectionSettingOpt MaybeCaseOfOpportunityDetectionSetting{..} = runIdentity $ + MaybeCaseOfOpportunityDetectionSetting + <$> fmap Just status + <*> fmap Just provideSuggestion + <*> fmap Just additionalMessage + +maybeToMaybeCaseOfOpportunityDetectionSetting + :: MaybeCaseOfOpportunityDetectionSettingOpt + -> Maybe MaybeCaseOfOpportunityDetectionSetting +maybeToMaybeCaseOfOpportunityDetectionSetting MaybeCaseOfOpportunityDetectionSetting{..} = + MaybeCaseOfOpportunityDetectionSetting + <$> fmap Identity status + <*> fmap Identity provideSuggestion + <*> fmap Identity additionalMessage + + +combineMaybeCaseOfOpportunityDetectionSetting + :: MaybeCaseOfOpportunityDetectionSettingOpt + -> MaybeCaseOfOpportunityDetectionSettingOpt + -> MaybeCaseOfOpportunityDetectionSettingOpt +combineMaybeCaseOfOpportunityDetectionSetting x y = MaybeCaseOfOpportunityDetectionSetting { + status = status x <|> status y, + -- automatically ignore default values when status was explicitly set to ignore + provideSuggestion = provideSuggestion x <|> (if status x == Just Ignore then Just False else provideSuggestion y), + additionalMessage = additionalMessage x <|> (if status x == Just Ignore then Just Nothing else additionalMessage y) + } data FSolutionConfig m = SolutionConfig { allowAdding :: m Bool, @@ -257,7 +299,7 @@ data FSolutionConfig m = SolutionConfig { configHlintRules :: m [String], configHlintSuggestions :: m [String], configLanguageExtensions :: m [String], - detectOpportunitiesToUseCaseOfWithMaybe :: m MaybeCaseOfOpportunityDetectionSetting, + detectOpportunitiesToUseCaseOfWithMaybe :: m (FMaybeCaseOfOpportunityDetectionSetting m), maxLineLength :: m (Maybe Natural), provideSampleSolution :: m Bool, messageOnCloningSampleSolution :: m (Maybe String), @@ -296,9 +338,9 @@ defaultSolutionConfig = SolutionConfig { configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { - status = Hint, + status = Just Hint, provideSuggestion = Just True, - additionalMessage = Nothing + additionalMessage = Just Nothing }, maxLineLength = Just Nothing, provideSampleSolution = Nothing, @@ -325,7 +367,7 @@ toSolutionConfigOpt SolutionConfig {..} = runIdentity $ SolutionConfig <*> fmap Just configHlintRules <*> fmap Just configHlintSuggestions <*> fmap Just configLanguageExtensions - <*> fmap Just detectOpportunitiesToUseCaseOfWithMaybe + <*> fmap (Just . toMaybeCaseOfOpportunityDetectionSettingOpt) detectOpportunitiesToUseCaseOfWithMaybe <*> fmap Just maxLineLength <*> fmap Just provideSampleSolution <*> fmap Just messageOnCloningSampleSolution @@ -350,7 +392,7 @@ toMaybeSolutionConfig SolutionConfig{..} = SolutionConfig <*> fmap Identity configHlintRules <*> fmap Identity configHlintSuggestions <*> fmap Identity configLanguageExtensions - <*> fmap Identity detectOpportunitiesToUseCaseOfWithMaybe + <*> fmap Identity (detectOpportunitiesToUseCaseOfWithMaybe >>= maybeToMaybeCaseOfOpportunityDetectionSetting) <*> fmap Identity maxLineLength <*> fmap Identity provideSampleSolution <*> fmap Identity messageOnCloningSampleSolution @@ -376,7 +418,9 @@ combineConfigs x y = SolutionConfig { configHlintSuggestions = configHlintSuggestions x <|> configHlintSuggestions y, configLanguageExtensions = configLanguageExtensions x <|> configLanguageExtensions y, detectOpportunitiesToUseCaseOfWithMaybe - = detectOpportunitiesToUseCaseOfWithMaybe x <|> detectOpportunitiesToUseCaseOfWithMaybe y, + = combineDetectOpportunitiesToUseCaseOfWithMaybe + (detectOpportunitiesToUseCaseOfWithMaybe x) + (detectOpportunitiesToUseCaseOfWithMaybe y), maxLineLength = maxLineLength x <|> maxLineLength y, provideSampleSolution = provideSampleSolution x <|> provideSampleSolution y, messageOnCloningSampleSolution = messageOnCloningSampleSolution x <|> messageOnCloningSampleSolution y, @@ -384,6 +428,11 @@ combineConfigs x y = SolutionConfig { rigorousValidation = rigorousValidation x <|> rigorousValidation y, syntaxCutoff = syntaxCutoff x <|> syntaxCutoff y } + where + combineDetectOpportunitiesToUseCaseOfWithMaybe (Just a) (Just b) + = Just $ combineMaybeCaseOfOpportunityDetectionSetting a b + combineDetectOpportunitiesToUseCaseOfWithMaybe Nothing b = b + combineDetectOpportunitiesToUseCaseOfWithMaybe a Nothing = a string :: String -> Doc string = text . pack @@ -400,13 +449,13 @@ check reject inform path i = do (config@SolutionConfig{..}, exts, (m,s), ms) <- processConfig reject inform i let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe - case status maybeDetectionConfig of + case runIdentity $ status maybeDetectionConfig of Ignore - | isJust (provideSuggestion maybeDetectionConfig) -> + | runIdentity $ provideSuggestion maybeDetectionConfig -> reject $ "Cannot set 'provideSuggestion' to true when 'status' is 'Ignore'" <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." - | isJust (additionalMessage maybeDetectionConfig) -> + | isJust (runIdentity $ additionalMessage maybeDetectionConfig) -> reject $ "Cannot set an 'additionalMessage' when 'status' is 'Ignore'" <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." @@ -626,10 +675,10 @@ getMaybeFeedback documentInfo MaybeCaseOfOpportunityDetectionSetting{..} ast = d sequence $ flip map (collectIfsWithMaybeChecks (annotate env ast)) $ \(foundIf,caseReplacement) -> documentInfo $ vcat [ string "Found:" <$$> indent 2 (text $ pack $ E.prettyPrint foundIf) - , if fromMaybe False provideSuggestion + , if runIdentity provideSuggestion then string "Perhaps:" <$$> indent 2 (text $ pack $ E.prettyPrint caseReplacement) else empty - , maybe empty (enclose linebreak linebreak . string) additionalMessage + , maybe empty (enclose linebreak linebreak . string) $ runIdentity additionalMessage ] editFeedback :: String -> String @@ -1034,7 +1083,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors -- Reject if checks on maybe values encounter a hit and were configured to reject. - when (Reject == status maybeDetectionConfig) $ do + when (Reject == runIdentity (status maybeDetectionConfig)) $ do void $ getMaybeFeedback rejectWithHint maybeDetectionConfig submissionAST , -- Reject on task template violations according to settings (modifying, adding, deleting). @@ -1053,7 +1102,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions -- Display suggestions involving checks on maybe values if configured as hints. - when (Hint == status maybeDetectionConfig) $ do + when (Hint == runIdentity (status maybeDetectionConfig)) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] where diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 86c83f8..6342b7d 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -16,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) @@ -505,9 +505,9 @@ maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] maybeCheckIO asError provideSuggestion additionalMessage code = do codeAST <- parse (fail . show) [] code let config = MaybeCaseOfOpportunityDetectionSetting { - status = if asError then Reject else Hint, - provideSuggestion = Just provideSuggestion, - additionalMessage + status = Identity $ if asError then Reject else Hint, + provideSuggestion = Identity provideSuggestion, + additionalMessage = Identity additionalMessage } getMaybeFeedback (pure . show) config codeAST From 8e14146cf9ea8d01b4a96ae09054a5e142641d3b Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:56:45 +0000 Subject: [PATCH 46/99] allow FMaybe --- .github/actions/spelling/allow.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index 8c072ee..a9e783c 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -5,6 +5,7 @@ concat elems finalise fmap +FMaybe fmidue foldl foldr From 94ce8cfc8ec580df1f4e1fc403fe18280cce5aad Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:32:12 +0000 Subject: [PATCH 47/99] rename provideSuggestion and update documentation --- src/Haskell/Template/Task.hs | 21 ++++++++++----------- test/Haskell/Template/TaskSpec.hs | 4 ++-- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 02379b6..e9cf68c 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -131,9 +131,8 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { \# `Reject`: reject the submission and show the first detection, but only if \# no errors were reported by hlint, and then at that point; \# defaults to `Hint` -\# provideSuggestion - whether to show the replacement using a case-of expression; -\# defaults to true if status is not set to `Ignore`; -\# otherwise defaults to false +\# offerReplacement - whether to offer the replacement using a case-of expression; +\# defaults to true if status is not set to `Ignore` \# additionalMessage - potential message to show; defaults to no message \# \# maxLineLength - submissions with lines longer than this value are rejected; defaults to no limit @@ -245,7 +244,7 @@ data Status = Ignore | Hint | Reject data FMaybeCaseOfOpportunityDetectionSetting m = MaybeCaseOfOpportunityDetectionSetting { status :: m Status, - provideSuggestion :: m Bool, + offerReplacement :: m Bool, additionalMessage :: m (Maybe String) } deriving (Generic) @@ -265,7 +264,7 @@ toMaybeCaseOfOpportunityDetectionSettingOpt toMaybeCaseOfOpportunityDetectionSettingOpt MaybeCaseOfOpportunityDetectionSetting{..} = runIdentity $ MaybeCaseOfOpportunityDetectionSetting <$> fmap Just status - <*> fmap Just provideSuggestion + <*> fmap Just offerReplacement <*> fmap Just additionalMessage maybeToMaybeCaseOfOpportunityDetectionSetting @@ -274,7 +273,7 @@ maybeToMaybeCaseOfOpportunityDetectionSetting maybeToMaybeCaseOfOpportunityDetectionSetting MaybeCaseOfOpportunityDetectionSetting{..} = MaybeCaseOfOpportunityDetectionSetting <$> fmap Identity status - <*> fmap Identity provideSuggestion + <*> fmap Identity offerReplacement <*> fmap Identity additionalMessage @@ -285,7 +284,7 @@ combineMaybeCaseOfOpportunityDetectionSetting combineMaybeCaseOfOpportunityDetectionSetting x y = MaybeCaseOfOpportunityDetectionSetting { status = status x <|> status y, -- automatically ignore default values when status was explicitly set to ignore - provideSuggestion = provideSuggestion x <|> (if status x == Just Ignore then Just False else provideSuggestion y), + 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) } @@ -345,7 +344,7 @@ defaultSolutionConfig = SolutionConfig { configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { status = Just Hint, - provideSuggestion = Just True, + offerReplacement = Just True, additionalMessage = Just Nothing }, maxLineLength = Just Nothing, @@ -457,9 +456,9 @@ check reject inform path i = do let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe case runIdentity $ status maybeDetectionConfig of Ignore - | runIdentity $ provideSuggestion maybeDetectionConfig -> + | runIdentity $ offerReplacement maybeDetectionConfig -> reject - $ "Cannot set 'provideSuggestion' to true when 'status' is 'Ignore'" + $ "Cannot set 'offerReplacement' to true when 'status' is 'Ignore'" <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." | isJust (runIdentity $ additionalMessage maybeDetectionConfig) -> reject @@ -681,7 +680,7 @@ getMaybeFeedback documentInfo MaybeCaseOfOpportunityDetectionSetting{..} ast = d sequence $ flip map (collectIfsWithMaybeChecks (annotate env ast)) $ \(foundIf,caseReplacement) -> documentInfo $ vcat [ string "Found:" <$$> indent 2 (text $ pack $ E.prettyPrint foundIf) - , if runIdentity provideSuggestion + , if runIdentity offerReplacement then string "Perhaps:" <$$> indent 2 (text $ pack $ E.prettyPrint caseReplacement) else empty , maybe empty (enclose linebreak linebreak . string) $ runIdentity additionalMessage diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 6342b7d..862bec5 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -502,11 +502,11 @@ hlintIO config content display selectHints = do firstLineOf [] = [] maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] -maybeCheckIO asError provideSuggestion additionalMessage code = do +maybeCheckIO asError offerReplacement additionalMessage code = do codeAST <- parse (fail . show) [] code let config = MaybeCaseOfOpportunityDetectionSetting { status = Identity $ if asError then Reject else Hint, - provideSuggestion = Identity provideSuggestion, + offerReplacement = Identity offerReplacement, additionalMessage = Identity additionalMessage } getMaybeFeedback (pure . show) config codeAST From 53acb2808b4e2d53a07f399876d6d0bae727db9b Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 09:02:28 +0000 Subject: [PATCH 48/99] make status required --- src/Haskell/Template/Task.hs | 20 ++++++++++---------- test/Haskell/Template/TaskSpec.hs | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index e9cf68c..2e12511 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -243,7 +243,7 @@ data Status = Ignore | Hint | Reject deriving (Eq, Generic, Show, FromJSON, ToJSON) data FMaybeCaseOfOpportunityDetectionSetting m = MaybeCaseOfOpportunityDetectionSetting { - status :: m Status, + status :: Status, offerReplacement :: m Bool, additionalMessage :: m (Maybe String) } deriving (Generic) @@ -263,7 +263,7 @@ toMaybeCaseOfOpportunityDetectionSettingOpt -> MaybeCaseOfOpportunityDetectionSettingOpt toMaybeCaseOfOpportunityDetectionSettingOpt MaybeCaseOfOpportunityDetectionSetting{..} = runIdentity $ MaybeCaseOfOpportunityDetectionSetting - <$> fmap Just status + <$> Identity status <*> fmap Just offerReplacement <*> fmap Just additionalMessage @@ -272,7 +272,7 @@ maybeToMaybeCaseOfOpportunityDetectionSetting -> Maybe MaybeCaseOfOpportunityDetectionSetting maybeToMaybeCaseOfOpportunityDetectionSetting MaybeCaseOfOpportunityDetectionSetting{..} = MaybeCaseOfOpportunityDetectionSetting - <$> fmap Identity status + <$> Just status <*> fmap Identity offerReplacement <*> fmap Identity additionalMessage @@ -282,10 +282,10 @@ combineMaybeCaseOfOpportunityDetectionSetting -> MaybeCaseOfOpportunityDetectionSettingOpt -> MaybeCaseOfOpportunityDetectionSettingOpt combineMaybeCaseOfOpportunityDetectionSetting x y = MaybeCaseOfOpportunityDetectionSetting { - status = status x <|> status y, + status = status x, -- 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) + offerReplacement = offerReplacement x <|> (if status x == Ignore then Just False else offerReplacement y), + additionalMessage = additionalMessage x <|> (if status x == Ignore then Just Nothing else additionalMessage y) } data FSolutionConfig m = SolutionConfig { @@ -343,7 +343,7 @@ defaultSolutionConfig = SolutionConfig { configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { - status = Just Hint, + status = Hint, offerReplacement = Just True, additionalMessage = Just Nothing }, @@ -454,7 +454,7 @@ check reject inform path i = do (config@SolutionConfig{..}, exts, (m,s), ms) <- processConfig reject inform i let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe - case runIdentity $ status maybeDetectionConfig of + case status maybeDetectionConfig of Ignore | runIdentity $ offerReplacement maybeDetectionConfig -> reject @@ -1088,7 +1088,7 @@ testPhases reject inform template submissionFile modules config exts submission 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)) $ do + when (Reject == status maybeDetectionConfig) $ do void $ getMaybeFeedback rejectWithHint maybeDetectionConfig submissionAST , -- Reject on task template violations according to settings (modifying, adding, deleting). @@ -1107,7 +1107,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions -- Display suggestions involving checks on maybe values if configured as hints. - when (Hint == runIdentity (status maybeDetectionConfig)) $ do + when (Hint == status maybeDetectionConfig) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] where diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 862bec5..8464a42 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -505,7 +505,7 @@ maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] maybeCheckIO asError offerReplacement additionalMessage code = do codeAST <- parse (fail . show) [] code let config = MaybeCaseOfOpportunityDetectionSetting { - status = Identity $ if asError then Reject else Hint, + status = if asError then Reject else Hint, offerReplacement = Identity offerReplacement, additionalMessage = Identity additionalMessage } From 1126e73880d0b32a2b1c21a6fffe464a4fd52e1e Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:21:43 +0000 Subject: [PATCH 49/99] add config spec --- haskell-template-task.cabal | 1 + test/Haskell/Template/ConfigSpec.hs | 165 ++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+) create mode 100644 test/Haskell/Template/ConfigSpec.hs diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index 1f44d4c..fdeb2e6 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -62,6 +62,7 @@ test-suite haskell-template-task-test type: exitcode-stdio-1.0 main-is: Spec.hs other-modules: + Haskell.Template.ConfigSpec Haskell.Template.MatchSpec Haskell.Template.TaskSpec Paths_haskell_template_task diff --git a/test/Haskell/Template/ConfigSpec.hs b/test/Haskell/Template/ConfigSpec.hs new file mode 100644 index 0000000..f84e55d --- /dev/null +++ b/test/Haskell/Template/ConfigSpec.hs @@ -0,0 +1,165 @@ +{-# 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 ( + FMaybeCaseOfOpportunityDetectionSetting (..), + 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 be configured by default" $ do + (mRejection, _) <- + evaluateCheck + $ flip encode Nothing + $ adjustedDefaultConfig { + detectOpportunitiesToUseCaseOfWithMaybe = detectOpportunitiesToUseCaseOfWithMaybe defaultSolutionConfig + } + + mRejection `shouldSatisfy` isRight + it "should allow to override the status while preserving other default values" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + status: Reject +|] + + let expectedConfig = MaybeCaseOfOpportunityDetectionSetting 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 -> "key \\\"status\\\" not found" `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 -> "key \\\"status\\\" not found" `isInfixOf` errorMsg + it "should prefer explicit value over default" $ do + result <- + evaluateCheck + $ encode adjustedDefaultConfig + $ Just + [SI.i| +detectOpportunitiesToUseCaseOfWithMaybe: + status: Reject + offerReplacement: false +|] + + let expectedConfig = MaybeCaseOfOpportunityDetectionSetting 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 = MaybeCaseOfOpportunityDetectionSetting 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 From 2d994d5fb42bb57c8991e73ba80ce59cc7253980 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:25:33 +0000 Subject: [PATCH 50/99] allow Utf --- .github/actions/spelling/allow.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index a9e783c..0541ccc 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -31,4 +31,5 @@ snd thd uncurry unlines +Utf yml From d35a838bf56ecf5838fb0facfc1e83c0e0d5b5c3 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:49:45 +0000 Subject: [PATCH 51/99] reject unknown fields --- src/Haskell/Template/Task.hs | 4 +++- test/Haskell/Template/ConfigSpec.hs | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 2e12511..b89cdd0 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -252,7 +252,9 @@ type MaybeCaseOfOpportunityDetectionSettingOpt = FMaybeCaseOfOpportunityDetectio deriving instance Show MaybeCaseOfOpportunityDetectionSettingOpt deriving instance ToJSON MaybeCaseOfOpportunityDetectionSettingOpt -deriving instance FromJSON MaybeCaseOfOpportunityDetectionSettingOpt + +instance FromJSON MaybeCaseOfOpportunityDetectionSettingOpt where + parseJSON = genericParseJSON defaultOptions {rejectUnknownFields = True} type MaybeCaseOfOpportunityDetectionSetting = FMaybeCaseOfOpportunityDetectionSetting Identity diff --git a/test/Haskell/Template/ConfigSpec.hs b/test/Haskell/Template/ConfigSpec.hs index f84e55d..8b856a0 100644 --- a/test/Haskell/Template/ConfigSpec.hs +++ b/test/Haskell/Template/ConfigSpec.hs @@ -163,3 +163,16 @@ detectOpportunitiesToUseCaseOfWithMaybe: 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" +|] + result `shouldSatisfy` \(mRejection, _) -> case mRejection of + Right () -> False + Left errorMsg -> "unknown fields: [\\\"aditionalMessage\\\"]" `isInfixOf` errorMsg From 66806a21eb2768badef1710f5495a1fcc21328b0 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:22:06 +0000 Subject: [PATCH 52/99] Revert "make status required" This reverts commit 53acb2808b4e2d53a07f399876d6d0bae727db9b. --- src/Haskell/Template/Task.hs | 20 ++++++++++---------- test/Haskell/Template/TaskSpec.hs | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index b89cdd0..0b61ce2 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -243,7 +243,7 @@ data Status = Ignore | Hint | Reject deriving (Eq, Generic, Show, FromJSON, ToJSON) data FMaybeCaseOfOpportunityDetectionSetting m = MaybeCaseOfOpportunityDetectionSetting { - status :: Status, + status :: m Status, offerReplacement :: m Bool, additionalMessage :: m (Maybe String) } deriving (Generic) @@ -265,7 +265,7 @@ toMaybeCaseOfOpportunityDetectionSettingOpt -> MaybeCaseOfOpportunityDetectionSettingOpt toMaybeCaseOfOpportunityDetectionSettingOpt MaybeCaseOfOpportunityDetectionSetting{..} = runIdentity $ MaybeCaseOfOpportunityDetectionSetting - <$> Identity status + <$> fmap Just status <*> fmap Just offerReplacement <*> fmap Just additionalMessage @@ -274,7 +274,7 @@ maybeToMaybeCaseOfOpportunityDetectionSetting -> Maybe MaybeCaseOfOpportunityDetectionSetting maybeToMaybeCaseOfOpportunityDetectionSetting MaybeCaseOfOpportunityDetectionSetting{..} = MaybeCaseOfOpportunityDetectionSetting - <$> Just status + <$> fmap Identity status <*> fmap Identity offerReplacement <*> fmap Identity additionalMessage @@ -284,10 +284,10 @@ combineMaybeCaseOfOpportunityDetectionSetting -> MaybeCaseOfOpportunityDetectionSettingOpt -> MaybeCaseOfOpportunityDetectionSettingOpt combineMaybeCaseOfOpportunityDetectionSetting x y = MaybeCaseOfOpportunityDetectionSetting { - status = status x, + status = status x <|> status y, -- automatically ignore default values when status was explicitly set to ignore - offerReplacement = offerReplacement x <|> (if status x == Ignore then Just False else offerReplacement y), - additionalMessage = additionalMessage x <|> (if status x == Ignore then Just Nothing else additionalMessage y) + 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 { @@ -345,7 +345,7 @@ defaultSolutionConfig = SolutionConfig { configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { - status = Hint, + status = Just Hint, offerReplacement = Just True, additionalMessage = Just Nothing }, @@ -456,7 +456,7 @@ check reject inform path i = do (config@SolutionConfig{..}, exts, (m,s), ms) <- processConfig reject inform i let maybeDetectionConfig = runIdentity detectOpportunitiesToUseCaseOfWithMaybe - case status maybeDetectionConfig of + case runIdentity $ status maybeDetectionConfig of Ignore | runIdentity $ offerReplacement maybeDetectionConfig -> reject @@ -1090,7 +1090,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors -- Reject if checks on maybe values encounter a hit and were configured to reject. - when (Reject == status maybeDetectionConfig) $ do + when (Reject == runIdentity (status maybeDetectionConfig)) $ do void $ getMaybeFeedback rejectWithHint maybeDetectionConfig submissionAST , -- Reject on task template violations according to settings (modifying, adding, deleting). @@ -1109,7 +1109,7 @@ testPhases reject inform template submissionFile modules config exts submission void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions -- Display suggestions involving checks on maybe values if configured as hints. - when (Hint == status maybeDetectionConfig) $ do + when (Hint == runIdentity (status maybeDetectionConfig)) $ do void $ getMaybeFeedback inform maybeDetectionConfig submissionAST ] where diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 8464a42..862bec5 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -505,7 +505,7 @@ maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] maybeCheckIO asError offerReplacement additionalMessage code = do codeAST <- parse (fail . show) [] code let config = MaybeCaseOfOpportunityDetectionSetting { - status = if asError then Reject else Hint, + status = Identity $ if asError then Reject else Hint, offerReplacement = Identity offerReplacement, additionalMessage = Identity additionalMessage } From e0dd66a4dded8f6937f638c1f7b367af2b37aa26 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:29:56 +0000 Subject: [PATCH 53/99] fix test cases --- test/Haskell/Template/ConfigSpec.hs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Haskell/Template/ConfigSpec.hs b/test/Haskell/Template/ConfigSpec.hs index 8b856a0..d4c2246 100644 --- a/test/Haskell/Template/ConfigSpec.hs +++ b/test/Haskell/Template/ConfigSpec.hs @@ -80,7 +80,7 @@ detectOpportunitiesToUseCaseOfWithMaybe: status: Reject |] - let expectedConfig = MaybeCaseOfOpportunityDetectionSetting Reject (Identity True) (Identity Nothing) + let expectedConfig = MaybeCaseOfOpportunityDetectionSetting (Identity Reject) (Identity True) (Identity Nothing) result `shouldSatisfy` \(mRejection, infos) -> isRight mRejection && any (isInfixOf (show expectedConfig)) infos @@ -119,7 +119,7 @@ detectOpportunitiesToUseCaseOfWithMaybe: offerReplacement: false |] - let expectedConfig = MaybeCaseOfOpportunityDetectionSetting Reject (Identity False) (Identity Nothing) + let expectedConfig = MaybeCaseOfOpportunityDetectionSetting (Identity Reject) (Identity False) (Identity Nothing) result `shouldSatisfy` \(mRejection, infos) -> isRight mRejection && any (isInfixOf (show expectedConfig)) infos @@ -133,7 +133,7 @@ detectOpportunitiesToUseCaseOfWithMaybe: status: Ignore |] - let expectedConfig = MaybeCaseOfOpportunityDetectionSetting Ignore (Identity False) (Identity Nothing) + let expectedConfig = MaybeCaseOfOpportunityDetectionSetting (Identity Ignore) (Identity False) (Identity Nothing) result `shouldSatisfy` \(mRejection, infos) -> isRight mRejection && any (isInfixOf (show expectedConfig)) infos From 36f1410d605bb25106d3b8dc6b97051e03efb3f7 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:31:15 +0000 Subject: [PATCH 54/99] don't set a default value for status (which also makes status a required field) --- src/Haskell/Template/Task.hs | 2 +- test/Haskell/Template/ConfigSpec.hs | 14 ++++++++------ test/Haskell/Template/MatchSpec.hs | 5 +++++ test/Haskell/Template/TaskSpec.hs | 5 +++++ 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 0b61ce2..3b632ca 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -345,7 +345,7 @@ defaultSolutionConfig = SolutionConfig { configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { - status = Just Hint, + status = Nothing, offerReplacement = Just True, additionalMessage = Just Nothing }, diff --git a/test/Haskell/Template/ConfigSpec.hs b/test/Haskell/Template/ConfigSpec.hs index d4c2246..426cfe6 100644 --- a/test/Haskell/Template/ConfigSpec.hs +++ b/test/Haskell/Template/ConfigSpec.hs @@ -61,16 +61,18 @@ evaluateCheck configString = withSystemTempDirectory "haskell-template-task" $ \ spec :: Spec spec = describe "Task config" $ do describe "detectOpportunitiesToUseCaseOfWithMaybe" $ do - it "should be configured by default" $ do - (mRejection, _) <- + it "should reject config where status is not specified" $ do + result <- evaluateCheck $ flip encode Nothing $ adjustedDefaultConfig { detectOpportunitiesToUseCaseOfWithMaybe = detectOpportunitiesToUseCaseOfWithMaybe defaultSolutionConfig } - mRejection `shouldSatisfy` isRight - it "should allow to override the status while preserving other default values" $ do + 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 @@ -95,7 +97,7 @@ detectOpportunitiesToUseCaseOfWithMaybe: |] result `shouldSatisfy` \(mRejection, _) -> case mRejection of Right () -> False - Left errorMsg -> "key \\\"status\\\" not found" `isInfixOf` errorMsg + Left errorMsg -> "There is a required configuration parameter missing" `isInfixOf` errorMsg it "should not allow to provide additionalMessage without setting status" $ do result <- evaluateCheck @@ -107,7 +109,7 @@ detectOpportunitiesToUseCaseOfWithMaybe: |] result `shouldSatisfy` \(mRejection, _) -> case mRejection of Right () -> False - Left errorMsg -> "key \\\"status\\\" not found" `isInfixOf` errorMsg + Left errorMsg -> "There is a required configuration parameter missing" `isInfixOf` errorMsg it "should prefer explicit value over default" $ do result <- evaluateCheck diff --git a/test/Haskell/Template/MatchSpec.hs b/test/Haskell/Template/MatchSpec.hs index b48037e..42f8524 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 $ MaybeCaseOfOpportunityDetectionSetting { + 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 862bec5..2c1ae1e 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -41,6 +41,11 @@ defaultConfig = fromJust $ toMaybeSolutionConfig configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], + detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { + status = Just Hint, + offerReplacement = Just True, + additionalMessage = Just Nothing + }, provideSampleSolution = Just True, rigorousValidation = Just True } ) From 9ddeb09190bda2b293dcc46e309ae3b793df3bcd Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:41:02 +0000 Subject: [PATCH 55/99] disable spell checking for two lines --- test/Haskell/Template/ConfigSpec.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Haskell/Template/ConfigSpec.hs b/test/Haskell/Template/ConfigSpec.hs index 426cfe6..4106ba2 100644 --- a/test/Haskell/Template/ConfigSpec.hs +++ b/test/Haskell/Template/ConfigSpec.hs @@ -173,8 +173,8 @@ detectOpportunitiesToUseCaseOfWithMaybe: [SI.i| detectOpportunitiesToUseCaseOfWithMaybe: status: Hint - aditionalMessage: "hello world" + aditionalMessage: "hello world" \# no-spell-check |] result `shouldSatisfy` \(mRejection, _) -> case mRejection of Right () -> False - Left errorMsg -> "unknown fields: [\\\"aditionalMessage\\\"]" `isInfixOf` errorMsg + Left errorMsg -> "unknown fields: [\\\"aditionalMessage\\\"]" `isInfixOf` errorMsg -- no-spell-check From 93708696a7cc2c965d89c9087142107ad0a80fae Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:50:53 +0000 Subject: [PATCH 56/99] also make "# no-spell-check" ignore line --- .github/actions/spelling/patterns.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/spelling/patterns.txt b/.github/actions/spelling/patterns.txt index 4d0dba3..a7084b7 100644 --- a/.github/actions/spelling/patterns.txt +++ b/.github/actions/spelling/patterns.txt @@ -41,3 +41,4 @@ https?://[-+0-9a-zA-Z?&=_\/%.]* # marker to ignore all code on line ^.*-- no-spell-check$ +^.*# no-spell-check$ From 8440355277f1e0ce58072072ad7a7cc0cfe340f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Mon, 9 Nov 2026 20:05:29 +0100 Subject: [PATCH 57/99] Refactor comments in Task.hs for better clarity Updated comments for clarity and consistency in Task.hs. --- src/Haskell/Template/Task.hs | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 3b632ca..08605ba 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -123,17 +123,16 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { \# 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; -\# defaults to `Hint` -\# offerReplacement - whether to offer the replacement using a case-of expression; -\# defaults to true if status is not set to `Ignore` -\# additionalMessage - potential message to show; defaults to no message +\# 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` +\# additionalMessage - potential message to show; defaults to no message \# \# 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); @@ -193,9 +192,8 @@ module SampleSolution where import Prelude {- -This module may provide a sample solution. -Including it is currently optional, but strongly encouraged, -as the sample will be validated the same way a student's submission would, +This module has to provide a sample solution. +The sample will be validated the same way a student's submission would, thus preventing a broken configuration or impossible task. -} From 63e45c025ea71329007825d00564570d9de2aff2 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:24:32 +0000 Subject: [PATCH 58/99] make defaultCode complete again --- src/Haskell/Template/Task.hs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 08605ba..047104e 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -99,6 +99,11 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], + detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { + status = Just Hint, + offerReplacement = Just True, + additionalMessage = Just Nothing + }, rigorousValidation = Just True } )) ++ [SI.i|\#\#\#\#\# parameter description: \# allowAdding - allow adding program parts; defaults to true From cb324ddfd7db2da7e8f3928dd3ad67ad35c4d1b8 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:43:16 +0000 Subject: [PATCH 59/99] make (==) and (/=) need to be default implementations --- src/Haskell/Template/Detection.hs | 5 +++-- test/Haskell/Template/TaskSpec.hs | 6 +++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index dfc17fa..0cb62da 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -62,11 +62,12 @@ exprToIfInfo expr@(If _ cond t e) = case removeParens cond of | hasName maybeMod "isNothing" vn -> transform maybeVal e t (InfixApp _ l (QVarOp _ opName) r) -> case getMaybeVal l r of Just maybeVal - | hasName Nothing "==" opName -> transform maybeVal e t - | hasName Nothing "/=" opName -> transform maybeVal t e + | 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 diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 2c1ae1e..c87d271 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -277,7 +277,11 @@ Perhaps: def2 :: Maybe Int -> Int def2 mVal = if isJust mVal then fromJust mVal else -3 - where fromJust _ = 99|] + 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 From 68663c1efbb2c66b54e46d0c7a59b32fc945c156 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:58:41 +0000 Subject: [PATCH 60/99] don't replace unrelated fromJust expressions --- src/Haskell/Template/Detection.hs | 18 ++++++++++++------ test/Haskell/Template/TaskSpec.hs | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index 0cb62da..c5f39a4 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -100,7 +100,12 @@ hasFromJust mExpr expr = notNull $ listify isFromJustApp expr hasName (Just "Data.Maybe") "fromJust" vn && fmap void (removeParens maybeVal) == fmap void mExpr isFromJustApp _ = False -asCaseExpression :: String -> Exp a -> Exp a -> Exp a -> Exp () +asCaseExpression + :: String + -> Exp (Scoped SrcSpanInfo) + -> Exp (Scoped SrcSpanInfo) + -> Exp (Scoped SrcSpanInfo) + -> Exp () asCaseExpression valueName maybeValue justCase nothingCase = Case () @@ -109,16 +114,17 @@ asCaseExpression valueName maybeValue justCase nothingCase = , Alt () (PApp () (UnQual () (Ident () "Just")) [PVar () (Ident () valueName)]) - (UnGuardedRhs () $ replaceFromJustWithValue valueName (void maybeValue) (void justCase)) + (UnGuardedRhs () $ replaceFromJustWithValue valueName maybeValue justCase) Nothing ] -replaceFromJustWithValue :: String -> Exp () -> Exp () -> Exp () -replaceFromJustWithValue valueName maybeValue = everywhere' $ mkT replace +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 () (Var () (UnQual _ (Ident () "fromJust"))) fnBody - | removeParens fnBody == maybeValue -> Var () (UnQual () (Ident () valueName)) + App l (Var _ (UnQual _ (Ident _ "fromJust"))) fnBody + | fmap void (removeParens fnBody) == fmap void maybeValue -> Var l (UnQual l (Ident l valueName)) _ -> expr removeParens :: Exp a -> Exp a diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index c87d271..9446fe4 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -318,6 +318,23 @@ Perhaps: Nothing -> -3 Just value -> 1 + value|] ] + it "replacement should not replace unrelated fromJust expressions" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Main where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = 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)|] + ] describe "grade" $ do it "is running" $ gradeIO completedDefaultCode useImport `shouldReturn` "" From 5b78ce8600aecc9f83a16df2ccbe8a667a37ce4e Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:01:50 +0000 Subject: [PATCH 61/99] directly use derived value name instead of replacing it afterwards --- src/Haskell/Template/Detection.hs | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index c5f39a4..936eca0 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -1,8 +1,8 @@ module Haskell.Template.Detection (collectIfsWithMaybeChecks) where -import Control.Monad (guard, void) +import Control.Monad (void) import Data.Data (Data) -import Data.Generics (everything, everywhere, listify, mkQ, mkT, everywhere') +import Data.Generics (everything, listify, mkQ, mkT, everywhere') import Data.List.Extra (notNull) import Data.Maybe (listToMaybe, mapMaybe, maybeToList) import Data.Set (Set) @@ -27,19 +27,13 @@ collectIfsWithMaybeChecks :: Module (Scoped SrcSpanInfo) -> [(Exp (Scoped SrcSpa collectIfsWithMaybeChecks (Module _ _ _ _ decls) = concat $ mapMaybe process decls where process d = do - let opportunities = everything (++) (mkQ [] (maybeToList . exprToIfInfo)) d - guard $ notNull opportunities - let allSymbols = Set.fromList (mapMaybe declName decls) `Set.union` allNames d freeName n | Set.member n allSymbols = freeName (n ++ "'") | otherwise = n - rename :: String -> Name () -> Name () - rename n (Ident l "_valueNamePlaceholder") = Ident l n - rename _ nExpr = nExpr - pure $ map (everywhere $ mkT (rename $ freeName "value")) opportunities + pure $ everything (++) (mkQ [] (maybeToList . exprToIfInfo (freeName "value"))) d collectIfsWithMaybeChecks _ = [] declName :: Decl a -> Maybe String @@ -55,8 +49,8 @@ declName (PatBind _ (PVar _ pn) _ _) = Just $ fromName pn fromName (Symbol _ n) = n declName _ = Nothing -exprToIfInfo :: Exp (Scoped SrcSpanInfo) -> Maybe (Exp (Scoped SrcSpanInfo), Exp ()) -exprToIfInfo expr@(If _ cond t e) = case removeParens cond of +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 @@ -80,10 +74,10 @@ exprToIfInfo expr@(If _ cond t e) = case removeParens cond of transform mValExpr j n = case removeParens mValExpr of mVal@(Var _ _) - | hasFromJust mVal j -> Just (expr, asCaseExpression "_valueNamePlaceholder" mVal j n) + | hasFromJust mVal j -> Just (expr, asCaseExpression valueName mVal j n) | otherwise -> Nothing _ -> Nothing -exprToIfInfo _ = Nothing +exprToIfInfo _ _ = Nothing allNames :: Data a => a -> Set String allNames = everything Set.union $ mkQ Set.empty extract From 5ed122bd2e0679dbcb58a0d68dfdfd21956fb87c Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:05:06 +0000 Subject: [PATCH 62/99] minimize diff? --- test/Haskell/Template/MatchSpec.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Haskell/Template/MatchSpec.hs b/test/Haskell/Template/MatchSpec.hs index 42f8524..16dab1b 100644 --- a/test/Haskell/Template/MatchSpec.hs +++ b/test/Haskell/Template/MatchSpec.hs @@ -77,10 +77,10 @@ spec = it "accepts code with guards and parameter" $ getComment withAdding modUndefinedParameter modGuardsParameter `shouldBe` Right [] - it "rejects code where parts beside undefined are changed" $ (do + it "rejects code where parts beside undefined are changed" $ do mod43AST <- parse errorP [] mod43 matchTemplate errorP withAdding 0 [] mod42 mod43 mod43AST - ) `shouldSatisfy` isLeft + `shouldSatisfy` isLeft it "marks not matching parts within functions" $ getComment withAdding mod42 mod43 `shouldBe` Right [Mismatch ["foo = 42" From 5aed49e296454ab2ab5f7e3d548275cdc6f6702e Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:15:06 +0000 Subject: [PATCH 63/99] only try to parse submission when syntaxCutoff is not CodeWidth --- src/Haskell/Template/Task.hs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 047104e..4c05e7f 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -606,7 +606,9 @@ grade withSyntax withSemantics reject inform dirname task submission = do -- and semantics phase is disabled. then pure (undefined, undefined) else writeModules (moduleName', submission) others dirname - submissionAST <- parse reject exts submission + submissionAST <- case runIdentity syntaxCutoff of + CodeWidth -> pure undefined + _ -> parse reject exts submission let (syntax, semantics) = splitAt (fromEnum syntaxCutoff) $ testPhases reject inform template submissionFile modules config exts submission submissionAST dirname From 5698cad0b488a43f32fcf7b95988d8b605670532 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Mon, 9 Nov 2026 23:04:51 +0100 Subject: [PATCH 64/99] only overwrite what really was Nothing --- src/Haskell/Template/Task.hs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 4c05e7f..b6058d5 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -99,11 +99,9 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], - detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { - status = Just Hint, - offerReplacement = Just True, - additionalMessage = Just Nothing - }, + detectOpportunitiesToUseCaseOfWithMaybe = Just $ (fromJust $ detectOpportunitiesToUseCaseOfWithMaybe defaultSolutionConfig) { + status = Just Hint + }, rigorousValidation = Just True } )) ++ [SI.i|\#\#\#\#\# parameter description: \# allowAdding - allow adding program parts; defaults to true From bc3f5ec4d2649fda862ea3d0d79b8e0582ef7768 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Mon, 9 Nov 2026 23:08:00 +0100 Subject: [PATCH 65/99] import fromJust --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index b6058d5..af047c2 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -58,7 +58,7 @@ import Data.List ) import Data.List.Extra (genericTake, nubOrd, replace, takeEnd, takeWhileEnd) -import Data.Maybe (fromMaybe, isJust) +import Data.Maybe (fromJust, fromMaybe, isJust) import Data.Text.Lazy (pack) import Data.Typeable (Typeable) import Data.Yaml From 3d100971fad57c27cee782d5562397333a942500 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Mon, 9 Nov 2026 23:14:56 +0100 Subject: [PATCH 66/99] line length --- src/Haskell/Template/Task.hs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index af047c2..f4c7675 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -99,9 +99,11 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], - detectOpportunitiesToUseCaseOfWithMaybe = Just $ (fromJust $ detectOpportunitiesToUseCaseOfWithMaybe defaultSolutionConfig) { - status = Just Hint - }, + detectOpportunitiesToUseCaseOfWithMaybe = + Just $ + (fromJust $ detectOpportunitiesToUseCaseOfWithMaybe defaultSolutionConfig) { + status = Just Hint + }, rigorousValidation = Just True } )) ++ [SI.i|\#\#\#\#\# parameter description: \# allowAdding - allow adding program parts; defaults to true From ab063384384c459370edef35cec7f31dc09e0cf0 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:53:25 +0000 Subject: [PATCH 67/99] fix condition --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 53c945c..02a7b98 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -607,7 +607,7 @@ grade withSyntax withSemantics reject inform dirname task submission = do then pure (undefined, undefined) else writeModules (moduleName', submission) others dirname submissionAST <- case runIdentity syntaxCutoff of - CodeWidth -> pure undefined + CodeWidth | runIdentity disableSemantics -> pure undefined _ -> parse reject exts submission let (syntax, semantics) = splitAt (fromEnum syntaxCutoff) From da6daca2b1556482c5131adcf1924b59ef4d6cae Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:11:25 +0000 Subject: [PATCH 68/99] add GradingSpec --- haskell-template-task.cabal | 1 + test/Haskell/Template/GradingSpec.hs | 74 ++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 test/Haskell/Template/GradingSpec.hs diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index fdeb2e6..82b8820 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -63,6 +63,7 @@ test-suite haskell-template-task-test main-is: Spec.hs other-modules: Haskell.Template.ConfigSpec + Haskell.Template.GradingSpec Haskell.Template.MatchSpec Haskell.Template.TaskSpec Paths_haskell_template_task diff --git a/test/Haskell/Template/GradingSpec.hs b/test/Haskell/Template/GradingSpec.hs new file mode 100644 index 0000000..ce1b12f --- /dev/null +++ b/test/Haskell/Template/GradingSpec.hs @@ -0,0 +1,74 @@ +{-# 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 (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 ( + FMaybeCaseOfOpportunityDetectionSetting (..), + 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 $ + MaybeCaseOfOpportunityDetectionSetting { + status = Just Ignore + , offerReplacement = Just False + , additionalMessage = Just 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) + +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 From 16d15497d46fff297ce6896129f00ff43f1a5bec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Tue, 10 Nov 2026 08:09:04 +0100 Subject: [PATCH 69/99] Update comments in Task.hs for clarity Clarified comments regarding the status options and additional message behavior in the configuration. --- src/Haskell/Template/Task.hs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 02a7b98..fe3a704 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -131,13 +131,15 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { \# 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 +\# 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` -\# additionalMessage - potential message to show; defaults to no message +\# 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); From 6770af16ef96f5e708937ed0c189c27cb9bfb101 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 07:51:22 +0000 Subject: [PATCH 70/99] add parsing test under normal conditions --- test/Haskell/Template/GradingSpec.hs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/test/Haskell/Template/GradingSpec.hs b/test/Haskell/Template/GradingSpec.hs index ce1b12f..f61642c 100644 --- a/test/Haskell/Template/GradingSpec.hs +++ b/test/Haskell/Template/GradingSpec.hs @@ -6,7 +6,7 @@ import Control.Exception (IOException, try) import Data.Aeson (ToJSON) import Data.Either.Extra (isRight, mapLeft) import Data.IORef (modifyIORef, newIORef, readIORef) -import Data.List (isPrefixOf) +import Data.List (isPrefixOf, isInfixOf) import Data.Maybe (fromMaybe) import qualified Data.String.Interpolate as SI (i) import Data.Text (unpack) @@ -72,3 +72,15 @@ 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 From 42e565ff27f00ef0e5ed2362727ba885e506c7da Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:00:13 +0000 Subject: [PATCH 71/99] rename config name and related functions --- src/Haskell/Template/Task.hs | 62 ++++++++++++++-------------- test/Haskell/Template/ConfigSpec.hs | 8 ++-- test/Haskell/Template/GradingSpec.hs | 4 +- test/Haskell/Template/MatchSpec.hs | 2 +- test/Haskell/Template/TaskSpec.hs | 4 +- 5 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index fe3a704..45ced76 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -29,8 +29,8 @@ module Haskell.Template.Task ( toMaybeSolutionConfig, unsafeTemplateSegment, getMaybeFeedback, - FMaybeCaseOfOpportunityDetectionSetting (..), - MaybeCaseOfOpportunityDetectionSettingOpt, + FCaseOfWithMaybeConfig (..), + CaseOfWithMaybeConfigOpt, Status (..), ) where @@ -247,48 +247,48 @@ data FeedbackPhase data Status = Ignore | Hint | Reject deriving (Eq, Generic, Show, FromJSON, ToJSON) -data FMaybeCaseOfOpportunityDetectionSetting m = MaybeCaseOfOpportunityDetectionSetting { +data FCaseOfWithMaybeConfig m = CaseOfWithMaybeConfig { status :: m Status, offerReplacement :: m Bool, additionalMessage :: m (Maybe String) } deriving (Generic) -type MaybeCaseOfOpportunityDetectionSettingOpt = FMaybeCaseOfOpportunityDetectionSetting Maybe +type CaseOfWithMaybeConfigOpt = FCaseOfWithMaybeConfig Maybe -deriving instance Show MaybeCaseOfOpportunityDetectionSettingOpt -deriving instance ToJSON MaybeCaseOfOpportunityDetectionSettingOpt +deriving instance Show CaseOfWithMaybeConfigOpt +deriving instance ToJSON CaseOfWithMaybeConfigOpt -instance FromJSON MaybeCaseOfOpportunityDetectionSettingOpt where +instance FromJSON CaseOfWithMaybeConfigOpt where parseJSON = genericParseJSON defaultOptions {rejectUnknownFields = True} -type MaybeCaseOfOpportunityDetectionSetting = FMaybeCaseOfOpportunityDetectionSetting Identity +type CaseOfWithMaybeConfig = FCaseOfWithMaybeConfig Identity -deriving instance Show MaybeCaseOfOpportunityDetectionSetting +deriving instance Show CaseOfWithMaybeConfig -toMaybeCaseOfOpportunityDetectionSettingOpt - :: MaybeCaseOfOpportunityDetectionSetting - -> MaybeCaseOfOpportunityDetectionSettingOpt -toMaybeCaseOfOpportunityDetectionSettingOpt MaybeCaseOfOpportunityDetectionSetting{..} = runIdentity $ - MaybeCaseOfOpportunityDetectionSetting +toCaseOfWithMaybeConfigOpt + :: CaseOfWithMaybeConfig + -> CaseOfWithMaybeConfigOpt +toCaseOfWithMaybeConfigOpt CaseOfWithMaybeConfig{..} = runIdentity $ + CaseOfWithMaybeConfig <$> fmap Just status <*> fmap Just offerReplacement <*> fmap Just additionalMessage -maybeToMaybeCaseOfOpportunityDetectionSetting - :: MaybeCaseOfOpportunityDetectionSettingOpt - -> Maybe MaybeCaseOfOpportunityDetectionSetting -maybeToMaybeCaseOfOpportunityDetectionSetting MaybeCaseOfOpportunityDetectionSetting{..} = - MaybeCaseOfOpportunityDetectionSetting +toMaybeCaseOfWithMaybeConfig + :: CaseOfWithMaybeConfigOpt + -> Maybe CaseOfWithMaybeConfig +toMaybeCaseOfWithMaybeConfig CaseOfWithMaybeConfig{..} = + CaseOfWithMaybeConfig <$> fmap Identity status <*> fmap Identity offerReplacement <*> fmap Identity additionalMessage -combineMaybeCaseOfOpportunityDetectionSetting - :: MaybeCaseOfOpportunityDetectionSettingOpt - -> MaybeCaseOfOpportunityDetectionSettingOpt - -> MaybeCaseOfOpportunityDetectionSettingOpt -combineMaybeCaseOfOpportunityDetectionSetting x y = MaybeCaseOfOpportunityDetectionSetting { +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), @@ -311,7 +311,7 @@ data FSolutionConfig m = SolutionConfig { configHlintRules :: m [String], configHlintSuggestions :: m [String], configLanguageExtensions :: m [String], - detectOpportunitiesToUseCaseOfWithMaybe :: m (FMaybeCaseOfOpportunityDetectionSetting m), + detectOpportunitiesToUseCaseOfWithMaybe :: m (FCaseOfWithMaybeConfig m), maxLineLength :: m (Maybe Natural), provideSampleSolution :: m Bool, messageOnCloningSampleSolution :: m (Maybe String), @@ -349,7 +349,7 @@ defaultSolutionConfig = SolutionConfig { configHlintRules = Just [], configHlintSuggestions = Nothing, configLanguageExtensions = Just ["NPlusKPatterns","ScopedTypeVariables"], - detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { + detectOpportunitiesToUseCaseOfWithMaybe = Just $ CaseOfWithMaybeConfig { status = Nothing, offerReplacement = Just True, additionalMessage = Just Nothing @@ -379,7 +379,7 @@ toSolutionConfigOpt SolutionConfig {..} = runIdentity $ SolutionConfig <*> fmap Just configHlintRules <*> fmap Just configHlintSuggestions <*> fmap Just configLanguageExtensions - <*> fmap (Just . toMaybeCaseOfOpportunityDetectionSettingOpt) detectOpportunitiesToUseCaseOfWithMaybe + <*> fmap (Just . toCaseOfWithMaybeConfigOpt) detectOpportunitiesToUseCaseOfWithMaybe <*> fmap Just maxLineLength <*> fmap Just provideSampleSolution <*> fmap Just messageOnCloningSampleSolution @@ -404,7 +404,7 @@ toMaybeSolutionConfig SolutionConfig{..} = SolutionConfig <*> fmap Identity configHlintRules <*> fmap Identity configHlintSuggestions <*> fmap Identity configLanguageExtensions - <*> fmap Identity (detectOpportunitiesToUseCaseOfWithMaybe >>= maybeToMaybeCaseOfOpportunityDetectionSetting) + <*> fmap Identity (detectOpportunitiesToUseCaseOfWithMaybe >>= toMaybeCaseOfWithMaybeConfig) <*> fmap Identity maxLineLength <*> fmap Identity provideSampleSolution <*> fmap Identity messageOnCloningSampleSolution @@ -442,7 +442,7 @@ combineConfigs x y = SolutionConfig { } where combineDetectOpportunitiesToUseCaseOfWithMaybe (Just a) (Just b) - = Just $ combineMaybeCaseOfOpportunityDetectionSetting a b + = Just $ combineCaseOfWithMaybeConfigs a b combineDetectOpportunitiesToUseCaseOfWithMaybe Nothing b = b combineDetectOpportunitiesToUseCaseOfWithMaybe a Nothing = a @@ -681,10 +681,10 @@ getHlintFeedback documentInfo config dir file selectHints = case hints of getMaybeFeedback :: MonadIO m => (Doc -> m a) - -> MaybeCaseOfOpportunityDetectionSetting + -> CaseOfWithMaybeConfig -> E.Module E.SrcSpanInfo -> m [a] -getMaybeFeedback documentInfo MaybeCaseOfOpportunityDetectionSetting{..} ast = do +getMaybeFeedback documentInfo CaseOfWithMaybeConfig{..} ast = do env <- liftIO loadBase sequence $ flip map (collectIfsWithMaybeChecks (annotate env ast)) $ \(foundIf,caseReplacement) -> documentInfo $ vcat diff --git a/test/Haskell/Template/ConfigSpec.hs b/test/Haskell/Template/ConfigSpec.hs index 4106ba2..1b01163 100644 --- a/test/Haskell/Template/ConfigSpec.hs +++ b/test/Haskell/Template/ConfigSpec.hs @@ -13,7 +13,7 @@ import Data.Text (unpack) import Data.Text.Encoding (decodeUtf8Lenient) import Data.Yaml.Pretty (defConfig, encodePretty, setConfCompare) import Haskell.Template.Task ( - FMaybeCaseOfOpportunityDetectionSetting (..), + FCaseOfWithMaybeConfig (..), FSolutionConfig (..), SolutionConfigOpt, Status (..), @@ -82,7 +82,7 @@ detectOpportunitiesToUseCaseOfWithMaybe: status: Reject |] - let expectedConfig = MaybeCaseOfOpportunityDetectionSetting (Identity Reject) (Identity True) (Identity Nothing) + let expectedConfig = CaseOfWithMaybeConfig (Identity Reject) (Identity True) (Identity Nothing) result `shouldSatisfy` \(mRejection, infos) -> isRight mRejection && any (isInfixOf (show expectedConfig)) infos @@ -121,7 +121,7 @@ detectOpportunitiesToUseCaseOfWithMaybe: offerReplacement: false |] - let expectedConfig = MaybeCaseOfOpportunityDetectionSetting (Identity Reject) (Identity False) (Identity Nothing) + let expectedConfig = CaseOfWithMaybeConfig (Identity Reject) (Identity False) (Identity Nothing) result `shouldSatisfy` \(mRejection, infos) -> isRight mRejection && any (isInfixOf (show expectedConfig)) infos @@ -135,7 +135,7 @@ detectOpportunitiesToUseCaseOfWithMaybe: status: Ignore |] - let expectedConfig = MaybeCaseOfOpportunityDetectionSetting (Identity Ignore) (Identity False) (Identity Nothing) + let expectedConfig = CaseOfWithMaybeConfig (Identity Ignore) (Identity False) (Identity Nothing) result `shouldSatisfy` \(mRejection, infos) -> isRight mRejection && any (isInfixOf (show expectedConfig)) infos diff --git a/test/Haskell/Template/GradingSpec.hs b/test/Haskell/Template/GradingSpec.hs index f61642c..8bb0126 100644 --- a/test/Haskell/Template/GradingSpec.hs +++ b/test/Haskell/Template/GradingSpec.hs @@ -13,7 +13,7 @@ import Data.Text (unpack) import Data.Text.Encoding (decodeUtf8Lenient) import Data.Yaml.Pretty (defConfig, encodePretty, setConfCompare) import Haskell.Template.Task ( - FMaybeCaseOfOpportunityDetectionSetting (..), + FCaseOfWithMaybeConfig (..), FSolutionConfig (..), SolutionConfigOpt, Status (..), @@ -35,7 +35,7 @@ adjustedDefaultConfig = , rigorousValidation = Just False , detectOpportunitiesToUseCaseOfWithMaybe = Just $ - MaybeCaseOfOpportunityDetectionSetting { + CaseOfWithMaybeConfig { status = Just Ignore , offerReplacement = Just False , additionalMessage = Just Nothing diff --git a/test/Haskell/Template/MatchSpec.hs b/test/Haskell/Template/MatchSpec.hs index 16dab1b..1fd3461 100644 --- a/test/Haskell/Template/MatchSpec.hs +++ b/test/Haskell/Template/MatchSpec.hs @@ -28,7 +28,7 @@ completedDefaultSolutionConfig = configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], - detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { + detectOpportunitiesToUseCaseOfWithMaybe = Just $ CaseOfWithMaybeConfig { status = Just Hint, offerReplacement = Just True, additionalMessage = Just Nothing diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 9446fe4..55bee8e 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -41,7 +41,7 @@ defaultConfig = fromJust $ toMaybeSolutionConfig configGhcWarnings = Just [], configHlintErrors = Just [], configHlintSuggestions = Just [], - detectOpportunitiesToUseCaseOfWithMaybe = Just $ MaybeCaseOfOpportunityDetectionSetting { + detectOpportunitiesToUseCaseOfWithMaybe = Just $ CaseOfWithMaybeConfig { status = Just Hint, offerReplacement = Just True, additionalMessage = Just Nothing @@ -530,7 +530,7 @@ hlintIO config content display selectHints = do maybeCheckIO :: Bool -> Bool -> Maybe String -> String -> IO [String] maybeCheckIO asError offerReplacement additionalMessage code = do codeAST <- parse (fail . show) [] code - let config = MaybeCaseOfOpportunityDetectionSetting { + let config = CaseOfWithMaybeConfig { status = Identity $ if asError then Reject else Hint, offerReplacement = Identity offerReplacement, additionalMessage = Identity additionalMessage From 2ed36d0c5cdd49a046d6900ac6452c3d911874ab Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:08:22 +0000 Subject: [PATCH 72/99] don't reveal potentially confusing error message from haskell-src-exts --- src/Haskell/Template/Task.hs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 45ced76..2d41d8a 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -885,18 +885,17 @@ parse reject' exts' m = case E.readExtensions m of { P.extensions = exts ++ exts' } in case P.parseModuleWithMode parseMode m of P.ParseOk a -> return a - P.ParseFailed loc msg -> - rejectParse reject' m loc msg + P.ParseFailed loc _ -> + rejectParse reject' m loc -rejectParse :: (Doc -> t) -> String -> E.SrcLoc -> String -> t -rejectParse reject' m loc msg = +rejectParse :: (Doc -> t) -> String -> E.SrcLoc -> t +rejectParse reject' m loc = let (lPre, _) = splitAt (E.srcLine loc) $ lines m lPre' = takeEnd 3 lPre tag = replicate (E.srcColumn loc - 1) '.' ++ "^" in reject' $ vcat ["Syntax error (your submission is no Haskell program):", - bloc $ lPre' ++ [tag], - string msg] + bloc $ lPre' ++ [tag]] rejectMatch :: Applicative m From eeae76b016bc0bc33b840ae0120ba08d36d3b3ee Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:12:28 +0000 Subject: [PATCH 73/99] document parsing behavior --- src/Haskell/Template/Task.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 2d41d8a..8dae049 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -147,6 +147,8 @@ defaultCode = BS.unpack (encode ( defaultSolutionConfig { \# CodeWidth, Compilation, GhcErrors, HlintErrors, TemplateMatch, TestSuite \# default on omission is TemplateMatch; steps after TestSuite are (in this order): \# GhcWarnings, HlintSuggestions +\# one subtlety of the Compilation phase is that there is a generic syntax error shown +\# when haskell-src-exts is unable to parse a program, the GHC error will not surface \# disableSemantics - will prevent the semantics phase (as determined by syntaxCutoff) from running; \# this means a submission will be accepted after passing the syntax phase; \# defaults to false From b818c805821541ac2a25971bac8b049e12f63ad6 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:17:54 +0000 Subject: [PATCH 74/99] update allowed words --- .github/actions/spelling/allow.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/spelling/allow.txt b/.github/actions/spelling/allow.txt index 0541ccc..21d9547 100644 --- a/.github/actions/spelling/allow.txt +++ b/.github/actions/spelling/allow.txt @@ -3,9 +3,9 @@ autotool Bifunctor concat elems +FCase finalise fmap -FMaybe fmidue foldl foldr From 3f3772092be599eed1a03085412aa0bd82cd030a Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:18:51 +0000 Subject: [PATCH 75/99] refactor handling of parse error to embed withSyntax --- haskell-template-task.cabal | 1 + package.yaml | 1 + src/Haskell/Template/Task.hs | 21 ++++++++++++++++++++- test/Haskell/Template/TaskSpec.hs | 5 ----- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index 82b8820..f24ff6e 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -41,6 +41,7 @@ library , base >=4.7 && <5 , bytestring , containers + , exceptions , extra , file-embed , filepath diff --git a/package.yaml b/package.yaml index ecb54a0..e6c269e 100644 --- a/package.yaml +++ b/package.yaml @@ -37,6 +37,7 @@ dependencies: - aeson - containers - haskell-names + - exceptions ghc-options: - -Wall diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 8dae049..538a663 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -32,6 +32,7 @@ module Haskell.Template.Task ( FCaseOfWithMaybeConfig (..), CaseOfWithMaybeConfigOpt, Status (..), + CustomException (..), ) where import qualified Data.ByteString.Char8 as BS @@ -88,6 +89,8 @@ import Text.Read (readMaybe) import Text.Regex.PCRE.Heavy (re, sub, (=~)) import Language.Haskell.Names (loadBase, annotate) import Haskell.Template.Detection (collectIfsWithMaybeChecks) +import Control.Exception (try, Exception) +import Control.Monad.Catch (throwM) encode :: ToJSON a => a -> BS.ByteString encode = encodePretty $ setConfCompare compare defConfig @@ -237,6 +240,11 @@ Also available are the following modules: with the option to allow a fixed number of tests to fail.) -}|] +newtype CustomException = CustomException Doc + deriving Show + +instance Exception CustomException + data FeedbackPhase = CodeWidth | Compilation @@ -566,6 +574,11 @@ whileOpen :: IO.Handle -> IO () whileOpen h = IO.hIsClosed h >>= flip unless (whileOpen h) +dummySyntax :: MonadIO m => m () -> m () +dummySyntax m = do + liftIO $ putStrLn "withSyntax was called" + m + {-| Generate consecutive syntax and possible semantics feedback in the context of an evaluation Monad. @@ -612,7 +625,13 @@ grade withSyntax withSemantics reject inform dirname task submission = do else writeModules (moduleName', submission) others dirname submissionAST <- case runIdentity syntaxCutoff of CodeWidth | runIdentity disableSemantics -> pure undefined - _ -> parse reject exts submission + _ -> do + result <- liftIO (try (parse (throwM . CustomException) exts submission) :: IO (Either CustomException (E.Module E.SrcSpanInfo))) + case result of + Left (CustomException errDoc) -> do + void $ withSyntax $ reject errDoc + pure undefined + Right ast -> pure ast let (syntax, semantics) = splitAt (fromEnum syntaxCutoff) $ testPhases reject inform template submissionFile modules config exts submission submissionAST dirname diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 55bee8e..8c08e64 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -28,11 +28,6 @@ import System.FilePath (()) import System.IO.Temp (withTempDirectory) import Test.Hspec -newtype CustomException = CustomException PP.Doc - deriving Show - -instance Exception CustomException - defaultConfig :: SolutionConfig defaultConfig = fromJust $ toMaybeSolutionConfig ( defaultSolutionConfig { From 613592c48f2aa85bd085efb89205e43413c04e9d Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:21:17 +0000 Subject: [PATCH 76/99] remove dummy method --- src/Haskell/Template/Task.hs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 538a663..6a980f2 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -574,11 +574,6 @@ whileOpen :: IO.Handle -> IO () whileOpen h = IO.hIsClosed h >>= flip unless (whileOpen h) -dummySyntax :: MonadIO m => m () -> m () -dummySyntax m = do - liftIO $ putStrLn "withSyntax was called" - m - {-| Generate consecutive syntax and possible semantics feedback in the context of an evaluation Monad. From 6683b5ccee34dc6c2f2fde642bada6af96334cdf Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:23:57 +0000 Subject: [PATCH 77/99] shorten line --- src/Haskell/Template/Task.hs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 6a980f2..e417a3a 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -621,7 +621,10 @@ grade withSyntax withSemantics reject inform dirname task submission = do submissionAST <- case runIdentity syntaxCutoff of CodeWidth | runIdentity disableSemantics -> pure undefined _ -> do - result <- liftIO (try (parse (throwM . CustomException) exts submission) :: IO (Either CustomException (E.Module E.SrcSpanInfo))) + result <- liftIO ( + try ( + parse (throwM . CustomException) exts submission) :: IO (Either CustomException (E.Module E.SrcSpanInfo)) + ) case result of Left (CustomException errDoc) -> do void $ withSyntax $ reject errDoc From 3ca739623d194e76723725bbbaa2d21169eee681 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:52:50 +0000 Subject: [PATCH 78/99] revert changes --- haskell-template-task.cabal | 1 - package.yaml | 1 - src/Haskell/Template/Task.hs | 19 +------------------ test/Haskell/Template/TaskSpec.hs | 5 +++++ 4 files changed, 6 insertions(+), 20 deletions(-) diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index f24ff6e..82b8820 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -41,7 +41,6 @@ library , base >=4.7 && <5 , bytestring , containers - , exceptions , extra , file-embed , filepath diff --git a/package.yaml b/package.yaml index e6c269e..ecb54a0 100644 --- a/package.yaml +++ b/package.yaml @@ -37,7 +37,6 @@ dependencies: - aeson - containers - haskell-names - - exceptions ghc-options: - -Wall diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index e417a3a..8dae049 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -32,7 +32,6 @@ module Haskell.Template.Task ( FCaseOfWithMaybeConfig (..), CaseOfWithMaybeConfigOpt, Status (..), - CustomException (..), ) where import qualified Data.ByteString.Char8 as BS @@ -89,8 +88,6 @@ import Text.Read (readMaybe) import Text.Regex.PCRE.Heavy (re, sub, (=~)) import Language.Haskell.Names (loadBase, annotate) import Haskell.Template.Detection (collectIfsWithMaybeChecks) -import Control.Exception (try, Exception) -import Control.Monad.Catch (throwM) encode :: ToJSON a => a -> BS.ByteString encode = encodePretty $ setConfCompare compare defConfig @@ -240,11 +237,6 @@ Also available are the following modules: with the option to allow a fixed number of tests to fail.) -}|] -newtype CustomException = CustomException Doc - deriving Show - -instance Exception CustomException - data FeedbackPhase = CodeWidth | Compilation @@ -620,16 +612,7 @@ grade withSyntax withSemantics reject inform dirname task submission = do else writeModules (moduleName', submission) others dirname submissionAST <- case runIdentity syntaxCutoff of CodeWidth | runIdentity disableSemantics -> pure undefined - _ -> do - result <- liftIO ( - try ( - parse (throwM . CustomException) exts submission) :: IO (Either CustomException (E.Module E.SrcSpanInfo)) - ) - case result of - Left (CustomException errDoc) -> do - void $ withSyntax $ reject errDoc - pure undefined - Right ast -> pure ast + _ -> parse reject exts submission let (syntax, semantics) = splitAt (fromEnum syntaxCutoff) $ testPhases reject inform template submissionFile modules config exts submission submissionAST dirname diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 8c08e64..55bee8e 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -28,6 +28,11 @@ import System.FilePath (()) import System.IO.Temp (withTempDirectory) import Test.Hspec +newtype CustomException = CustomException PP.Doc + deriving Show + +instance Exception CustomException + defaultConfig :: SolutionConfig defaultConfig = fromJust $ toMaybeSolutionConfig ( defaultSolutionConfig { From 711c624a934cb03d73ed49c03b7c2ea385e85312 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:55:49 +0000 Subject: [PATCH 79/99] simpler way to embed withSyntax --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 8dae049..61cbc22 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -612,7 +612,7 @@ grade withSyntax withSemantics reject inform dirname task submission = do else writeModules (moduleName', submission) others dirname submissionAST <- case runIdentity syntaxCutoff of CodeWidth | runIdentity disableSemantics -> pure undefined - _ -> parse reject exts submission + _ -> parse (fmap undefined . withSyntax . reject) exts submission let (syntax, semantics) = splitAt (fromEnum syntaxCutoff) $ testPhases reject inform template submissionFile modules config exts submission submissionAST dirname From 66428e13d36b2e488efd69ac5799b29aa58f1af1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sat, 28 Nov 2026 06:40:39 +0100 Subject: [PATCH 80/99] spacing --- src/Haskell/Template/Task.hs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 61cbc22..368f03a 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -86,8 +86,8 @@ import Text.PrettyPrint.Leijen.Text (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 (collectIfsWithMaybeChecks) +import Language.Haskell.Names (loadBase, annotate) +import Haskell.Template.Detection (collectIfsWithMaybeChecks) encode :: ToJSON a => a -> BS.ByteString encode = encodePretty $ setConfCompare compare defConfig @@ -285,7 +285,6 @@ toMaybeCaseOfWithMaybeConfig CaseOfWithMaybeConfig{..} = <*> fmap Identity offerReplacement <*> fmap Identity additionalMessage - combineCaseOfWithMaybeConfigs :: CaseOfWithMaybeConfigOpt -> CaseOfWithMaybeConfigOpt @@ -468,11 +467,11 @@ check reject inform path i = do | runIdentity $ offerReplacement maybeDetectionConfig -> reject $ "Cannot set 'offerReplacement' to true when 'status' is 'Ignore'" - <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." + <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." | isJust (runIdentity $ additionalMessage maybeDetectionConfig) -> reject $ "Cannot set an 'additionalMessage' when 'status' is 'Ignore'" - <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." + <> " at 'detectOpportunitiesToUseCaseOfWithMaybe'." _ -> pure () checkUniqueness (m : map fst ms) From eaed8d600e6bb55bcf97c5caf929ea106c839f62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sat, 28 Nov 2026 14:30:48 +0100 Subject: [PATCH 81/99] fixup after merge --- src/Haskell/Template/Task.hs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 6503ba8..1957618 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -613,9 +613,6 @@ grade withSyntax withSemantics reject inform dirname task submission = do -- and semantics phase is disabled. then pure (undefined, undefined) else writeModules (moduleName', submission) others dirname - submissionAST <- case runIdentity syntaxCutoff of - CodeWidth | runIdentity disableSemantics -> pure undefined - _ -> parse (fmap undefined . withSyntax . reject) exts submission let (syntax, semantics) = splitAt (fromEnum syntaxCutoff) $ testPhases reject inform template submissionFile modules config exts submission dirname @@ -1074,7 +1071,6 @@ testPhases -> SolutionConfig -> [E.Extension] -> String - -> E.Module E.SrcSpanInfo -> FilePath -> [StateT (E.Module E.SrcSpanInfo) m ()] testPhases reject inform template submissionFile modules config exts submission dirname = @@ -1107,8 +1103,8 @@ testPhases reject inform template submissionFile modules config exts submission lift $ void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors -- Reject if checks on maybe values encounter a hit and were configured to reject. - get >>= when (Reject == runIdentity (status maybeDetectionConfig)) . - lift . void . getMaybeFeedback rejectWithHint maybeDetectionConfig + when (Reject == runIdentity (status maybeDetectionConfig)) $ + get >>= lift . void . getMaybeFeedback rejectWithHint maybeDetectionConfig , -- Reject on task template violations according to settings (modifying, adding, deleting). get >>= lift . matchTemplate reject config 2 exts template submission @@ -1126,8 +1122,8 @@ testPhases reject inform template submissionFile modules config exts submission lift $ void $ getHlintFeedback inform config dirname submissionFile configHlintSuggestions -- Display suggestions involving checks on maybe values if configured as hints. - get >>= when (Hint == runIdentity (status maybeDetectionConfig)) . - lift . void . getMaybeFeedback inform maybeDetectionConfig + when (Hint == runIdentity (status maybeDetectionConfig)) $ + get >>= lift . void . getMaybeFeedback inform maybeDetectionConfig ] where maybeDetectionConfig = runIdentity $ detectOpportunitiesToUseCaseOfWithMaybe config From f4a2638ea024a241a62041a71de81a822768fd7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sat, 28 Nov 2026 15:39:07 +0100 Subject: [PATCH 82/99] list layout like in the rest of this function --- src/Haskell/Template/Task.hs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 1957618..9c325c4 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -1098,7 +1098,8 @@ 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 + , + do -- Reject if HLint warnings configured as errors are triggered by submission. lift $ void $ getHlintFeedback rejectWithHint config dirname submissionFile configHlintErrors From 04cf3aca441142595df037c7a6594067914d9063 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:33:49 +0000 Subject: [PATCH 83/99] don't replace shadowed fromJust call --- src/Haskell/Template/Detection.hs | 5 +++-- test/Haskell/Template/TaskSpec.hs | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index 936eca0..be25bae 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -117,8 +117,9 @@ replaceFromJustWithValue valueName maybeValue = void . everywhere' (mkT replace) where replace :: Exp (Scoped SrcSpanInfo) -> Exp (Scoped SrcSpanInfo) replace expr = case removeParens expr of - App l (Var _ (UnQual _ (Ident _ "fromJust"))) fnBody - | fmap void (removeParens fnBody) == fmap void maybeValue -> Var l (UnQual l (Ident l valueName)) + 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 diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 55bee8e..d4ea79f 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -335,6 +335,23 @@ Perhaps: 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 Main where + import Data.Maybe + + def :: Maybe Int -> Int + def mVal = 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)|] + ] describe "grade" $ do it "is running" $ gradeIO completedDefaultCode useImport `shouldReturn` "" From abd60c9c5b6ba92bc137dfbd313d1ac80cb0a3f1 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:35:52 +0000 Subject: [PATCH 84/99] fix test case names --- test/Haskell/Template/TaskSpec.hs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index d4ea79f..eb92ce5 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -86,7 +86,7 @@ spec = do hlintIO dilatedWithFixity useDilated errorP configHlintErrors `shouldReturn` [Left "Warning: Use dilated"] describe "maybe feedback" $ do - it "should suggest replacing if with case-of when applicable (isJust)" $ 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 Main where import Data.Maybe @@ -101,7 +101,7 @@ spec = do Is there maybe a better way to express this? |] ] - it "should suggest replacing if with case-of when applicable (isNothing)" $ do + it "should suggest replacing if with case-of when applicable (== Nothing)" $ do result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -110,7 +110,7 @@ Is there maybe a better way to express this? 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 + it "should suggest replacing if with case-of when applicable (/= Nothing)" $ do result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe @@ -119,7 +119,7 @@ Is there maybe a better way to express this? def mVal = if mVal /= Nothing then fromJust mVal else -3|] length result `shouldBe` 1 - it "should suggest replacing if with case-of when applicable (/= Nothing)" $ do + it "should suggest replacing if with case-of when applicable (isJust)" $ do result <- maybeCheckIO False True Nothing [SI.i| module Main where import Data.Maybe From 5dafd72ec0b34c793f3a534201d713cf5ba75823 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:38:23 +0000 Subject: [PATCH 85/99] fix test case using fromMaybe instead of fromJust --- test/Haskell/Template/TaskSpec.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index eb92ce5..ca7d220 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -290,7 +290,7 @@ Perhaps: import Data.Maybe def :: a -> (a -> Maybe Int) -> Int - def val f = if isJust (f val) then fromMaybe (f val) else -3|] + 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 From bb4c0331fc7ff16b4efde699a23645a157e21c8c Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:40:46 +0000 Subject: [PATCH 86/99] fix invalid programs in test cases --- test/Haskell/Template/TaskSpec.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index ca7d220..d1b99dc 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -247,7 +247,7 @@ Perhaps: import Data.Maybe def :: Maybe Int -> Maybe Int -> Int - def mVal1 mVal 2 = if isJust mVal1 then fromJust mVal1 + if isJust mVal2 then 2 * fromJust mVal2 else 0 else -1|] + 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: @@ -324,7 +324,7 @@ Perhaps: import Data.Maybe def :: Maybe Int -> Int - def mVal = if isJust m then fromJust m + (let m = Just 99 in fromJust m) else 0|] + def m = if isJust m then fromJust m + (let m = Just 99 in fromJust m) else 0|] result `shouldBe` [ [SI.i|Found: From 034d318a22f479f1e6672efc09b9b9c4008f1a5b Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:01:56 +0000 Subject: [PATCH 87/99] test interaction with grade --- test/Haskell/Template/GradingSpec.hs | 95 +++++++++++++++++++++++++++- 1 file changed, 93 insertions(+), 2 deletions(-) diff --git a/test/Haskell/Template/GradingSpec.hs b/test/Haskell/Template/GradingSpec.hs index 8bb0126..edaa423 100644 --- a/test/Haskell/Template/GradingSpec.hs +++ b/test/Haskell/Template/GradingSpec.hs @@ -43,11 +43,68 @@ adjustedDefaultConfig = } encode :: ToJSON a => a -> Maybe String -> String -encode doc override = encodedConfig ++ "\n" ++ fromMaybe "" override ++ "\n" ++ defaultCodeModules +encode doc override = + encodeConfig doc ++ "\n" ++ fromMaybe "" override ++ "\n" ++ defaultCodeModules where - encodedConfig = unpack $ decodeUtf8Lenient $ encodePretty (setConfCompare compare defConfig) doc 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 @@ -84,3 +141,37 @@ 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 From d4251d4fe384786c06d43ec124b977b21b6c31c8 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:01:18 +0000 Subject: [PATCH 88/99] take record fields into account --- src/Haskell/Template/Detection.hs | 17 ++++++++++++++++- test/Haskell/Template/TaskSpec.hs | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index be25bae..6b97524 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -11,6 +11,7 @@ import Language.Haskell.Exts ( Alt (..), Decl (..), Exp (..), + FieldDecl (..), Match (..), Module (..), ModuleName (..), @@ -26,9 +27,14 @@ 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 none (to the students available) module exports a 'value'-named symbol. + moduleNames = + Set.fromList (mapMaybe declName decls) + `Set.union` recordFieldNames decls + process d = do let - allSymbols = Set.fromList (mapMaybe declName decls) `Set.union` allNames d + allSymbols = moduleNames `Set.union` allNames d freeName n | Set.member n allSymbols = freeName (n ++ "'") | otherwise = n @@ -86,6 +92,15 @@ allNames = everything Set.union $ mkQ Set.empty extract 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 diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index d1b99dc..746a9ff 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -241,6 +241,22 @@ Perhaps: Just value' -> do value <- xs pure $ value' value|] ] + it "replacement should avoid record field names" $ do + result <- maybeCheckIO False True Nothing [SI.i| + module Main 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 Main where From c38a16ec5b4132304328fe70a1698621dd290f2f Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:41:32 +0000 Subject: [PATCH 89/99] make getMaybeFeedback respect default language extensions --- src/Haskell/Template/Task.hs | 10 +++++-- test/Haskell/Template/GradingSpec.hs | 43 ++++++++++++++++++++++++++++ test/Haskell/Template/TaskSpec.hs | 2 +- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 9c325c4..383c095 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -686,10 +686,13 @@ getMaybeFeedback :: MonadIO m => (Doc -> m a) -> CaseOfWithMaybeConfig + -> [E.Extension] -> E.Module E.SrcSpanInfo -> m [a] -getMaybeFeedback documentInfo CaseOfWithMaybeConfig{..} ast = do +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) @@ -698,6 +701,7 @@ getMaybeFeedback documentInfo CaseOfWithMaybeConfig{..} ast = do else empty , maybe empty (enclose linebreak linebreak . string) $ runIdentity additionalMessage ] +getMaybeFeedback _ _ _ _ = pure [] editFeedback :: String -> String editFeedback xs = case elemIndex ':' xs of @@ -1105,7 +1109,7 @@ testPhases reject inform template submissionFile modules config exts submission -- 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 + 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 @@ -1124,7 +1128,7 @@ testPhases reject inform template submissionFile modules config exts submission -- Display suggestions involving checks on maybe values if configured as hints. when (Hint == runIdentity (status maybeDetectionConfig)) $ - get >>= lift . void . getMaybeFeedback inform maybeDetectionConfig + get >>= lift . void . getMaybeFeedback inform maybeDetectionConfig exts ] where maybeDetectionConfig = runIdentity $ detectOpportunitiesToUseCaseOfWithMaybe config diff --git a/test/Haskell/Template/GradingSpec.hs b/test/Haskell/Template/GradingSpec.hs index edaa423..a8f8483 100644 --- a/test/Haskell/Template/GradingSpec.hs +++ b/test/Haskell/Template/GradingSpec.hs @@ -175,3 +175,46 @@ main :: "Found:" `isInfixOf` err && not ("later test ran" `isInfixOf` err) Right _ -> False + it "respects default language extensions" $ do + let taskConfig = encodeConfig ((maybeConfig Hint) { configLanguageExtensions = Just ["NoImplicitPrelude"] }) ++[SI.i| +--- +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/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 746a9ff..b0da274 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -568,7 +568,7 @@ maybeCheckIO asError offerReplacement additionalMessage code = do offerReplacement = Identity offerReplacement, additionalMessage = Identity additionalMessage } - getMaybeFeedback (pure . show) config codeAST + getMaybeFeedback (pure . show) config [] codeAST render :: PP.Doc -> String render = unpack . PP.displayT . PP.renderPretty 1.0 100 From 9f2ea2071ee2c9bdaf2a21879e57c5753038b940 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:58:39 +0000 Subject: [PATCH 90/99] shorten line --- test/Haskell/Template/GradingSpec.hs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/Haskell/Template/GradingSpec.hs b/test/Haskell/Template/GradingSpec.hs index a8f8483..f98f8a0 100644 --- a/test/Haskell/Template/GradingSpec.hs +++ b/test/Haskell/Template/GradingSpec.hs @@ -176,7 +176,8 @@ main :: && not ("later test ran" `isInfixOf` err) Right _ -> False it "respects default language extensions" $ do - let taskConfig = encodeConfig ((maybeConfig Hint) { configLanguageExtensions = Just ["NoImplicitPrelude"] }) ++[SI.i| + let settings = encodeConfig ((maybeConfig Hint) { configLanguageExtensions = Just ["NoImplicitPrelude"] }) + let taskConfig = [SI.i|#{settings} --- module Solution where import Data.Maybe From b094c5a52f1fa6f71a137546f7ad3e485aedc2eb Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:25:26 +0000 Subject: [PATCH 91/99] throw error on unexpected module type --- src/Haskell/Template/Task.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index 383c095..b6a6232 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -701,7 +701,7 @@ getMaybeFeedback documentInfo CaseOfWithMaybeConfig{..} exts (E.Module l mHead p else empty , maybe empty (enclose linebreak linebreak . string) $ runIdentity additionalMessage ] -getMaybeFeedback _ _ _ _ = pure [] +getMaybeFeedback _ _ _ _ = error "unexpected Module type at getMaybeFeedback" editFeedback :: String -> String editFeedback xs = case elemIndex ':' xs of From 8314392b3be8e5bdf79f0c025cb7d24b68c36c5f Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:27:11 +0000 Subject: [PATCH 92/99] add notice --- src/Haskell/Template/Detection.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index 6b97524..aea7641 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -28,6 +28,7 @@ collectIfsWithMaybeChecks :: Module (Scoped SrcSpanInfo) -> [(Exp (Scoped SrcSpa collectIfsWithMaybeChecks (Module _ _ _ _ decls) = concat $ mapMaybe process decls where -- Imports are disregarded as none (to the students available) module exports a 'value'-named symbol. + -- This also assumes that the modules provided by lecturer don't expose such a symbol. moduleNames = Set.fromList (mapMaybe declName decls) `Set.union` recordFieldNames decls From af054c6879c3a760af4f5c56bd437c8dd6644a38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sun, 29 Nov 2026 21:48:00 +0100 Subject: [PATCH 93/99] Clarify comment about module exports in Detection.hs --- src/Haskell/Template/Detection.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection.hs index aea7641..74a44c1 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection.hs @@ -27,8 +27,8 @@ 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 none (to the students available) module exports a 'value'-named symbol. - -- This also assumes that the modules provided by lecturer don't expose such a symbol. + -- 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 From 84cd1201a6ea7b7e4048addd92e572d0ebdd4963 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Sun, 29 Nov 2026 22:04:31 +0100 Subject: [PATCH 94/99] Fix typo --- test/Haskell/Template/TaskSpec.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index b0da274..8b54c44 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -357,7 +357,7 @@ Perhaps: import Data.Maybe def :: Maybe Int -> Int - def mVal = if isJust m then fromJust m + (let fromJust x = 99 in fromJust m) else 0|] + def m = if isJust m then fromJust m + (let fromJust x = 99 in fromJust m) else 0|] result `shouldBe` [ [SI.i|Found: From 0282b192ff333ddacf2ba3d6f910ce083c0624bd Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:40:27 +0000 Subject: [PATCH 95/99] move module --- haskell-template-task.cabal | 2 +- src/Haskell/Template/{Detection.hs => Detection/Maybe.hs} | 2 +- src/Haskell/Template/Task.hs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename src/Haskell/Template/{Detection.hs => Detection/Maybe.hs} (98%) diff --git a/haskell-template-task.cabal b/haskell-template-task.cabal index 74b1cd0..8d0a894 100644 --- a/haskell-template-task.cabal +++ b/haskell-template-task.cabal @@ -27,7 +27,7 @@ source-repository head library exposed-modules: - Haskell.Template.Detection + Haskell.Template.Detection.Maybe Haskell.Template.Match Haskell.Template.Task other-modules: diff --git a/src/Haskell/Template/Detection.hs b/src/Haskell/Template/Detection/Maybe.hs similarity index 98% rename from src/Haskell/Template/Detection.hs rename to src/Haskell/Template/Detection/Maybe.hs index 74a44c1..66a723e 100644 --- a/src/Haskell/Template/Detection.hs +++ b/src/Haskell/Template/Detection/Maybe.hs @@ -1,4 +1,4 @@ -module Haskell.Template.Detection (collectIfsWithMaybeChecks) where +module Haskell.Template.Detection.Maybe (collectIfsWithMaybeChecks) where import Control.Monad (void) import Data.Data (Data) diff --git a/src/Haskell/Template/Task.hs b/src/Haskell/Template/Task.hs index b6a6232..b695b6b 100644 --- a/src/Haskell/Template/Task.hs +++ b/src/Haskell/Template/Task.hs @@ -89,7 +89,7 @@ import Text.PrettyPrint.Leijen.Text import Text.Read (readMaybe) import Text.Regex.PCRE.Heavy (re, sub, (=~)) import Language.Haskell.Names (loadBase, annotate) -import Haskell.Template.Detection (collectIfsWithMaybeChecks) +import Haskell.Template.Detection.Maybe (collectIfsWithMaybeChecks) encode :: ToJSON a => a -> BS.ByteString encode = encodePretty $ setConfCompare compare defConfig From 95c0aa794b5fd9e68329d0c3bd4c415a782c421b Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:08:57 +0000 Subject: [PATCH 96/99] add test cases (for edge cases) --- test/Haskell/Template/TaskSpec.hs | 60 +++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 8b54c44..8d7c50e 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -368,6 +368,66 @@ Perhaps: 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 Main 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 "edge cases" $ do + it "it suggests replacement even though Maybe constructors are not in scope" $ do + result <- maybeCheckIO False True Nothing [SI.i| + {-\# LANGUAGE NoImplicitPrelude \#-} + module Main 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 Main 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 Main 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` "" From 7edc81c0277a679108ede24ef6a3a12dfb3f0757 Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:10:57 +0000 Subject: [PATCH 97/99] rename module in test submissions --- test/Haskell/Template/TaskSpec.hs | 40 +++++++++++++++---------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 8d7c50e..0659e6b 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -88,7 +88,7 @@ spec = do 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 Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -103,7 +103,7 @@ 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 Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -112,7 +112,7 @@ Is there maybe a better way to express this? length result `shouldBe` 1 it "should suggest replacing if with case-of when applicable (/= Nothing)" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -121,7 +121,7 @@ Is there maybe a better way to express this? length result `shouldBe` 1 it "should suggest replacing if with case-of when applicable (isJust)" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -130,7 +130,7 @@ Is there maybe a better way to express this? 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 Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -139,7 +139,7 @@ Is there maybe a better way to express this? 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 Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -148,7 +148,7 @@ Is there maybe a better way to express this? 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 Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -157,7 +157,7 @@ Is there maybe a better way to express this? 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 Main where + module Solution where import Data.Maybe def mVal = let value = -3 in if isJust mVal then fromJust mVal else value @@ -243,7 +243,7 @@ Perhaps: ] it "replacement should avoid record field names" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Data.Maybe data Record = Record { value :: Int } @@ -259,7 +259,7 @@ Perhaps: Just value' -> value'|]] it "should suggest replacement even when nested" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Data.Maybe def :: Maybe Int -> Maybe Int -> Int @@ -284,7 +284,7 @@ Perhaps: ] 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 Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -302,7 +302,7 @@ Perhaps: 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 Main where + module Solution where import Data.Maybe def :: a -> (a -> Maybe Int) -> Int @@ -311,7 +311,7 @@ Perhaps: 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 Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -320,7 +320,7 @@ Perhaps: length result `shouldBe` 0 it "replacement should not use redundant brackets" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -336,7 +336,7 @@ Perhaps: ] it "replacement should not replace unrelated fromJust expressions" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -353,7 +353,7 @@ Perhaps: ] it "replacement should not replace shadowed fromJust call" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Data.Maybe def :: Maybe Int -> Int @@ -370,7 +370,7 @@ Perhaps: ] it "doesn't get misled by qualified imports" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import qualified SomeModule as Data.Maybe def :: Maybe Int -> Int @@ -381,7 +381,7 @@ Perhaps: it "it suggests replacement even though Maybe constructors are not in scope" $ do result <- maybeCheckIO False True Nothing [SI.i| {-\# LANGUAGE NoImplicitPrelude \#-} - module Main where + module Solution where import Data.Maybe (isJust, fromJust) def m = if isJust m then fromJust m else 0|] @@ -396,7 +396,7 @@ Perhaps: ] it "replacement doesn't use qualified constructor names" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Prelude (Int) import qualified Data.Maybe as M (Maybe (..), isJust, fromJust) @@ -413,7 +413,7 @@ Perhaps: ] it "replacement doesn't take imports into account" $ do result <- maybeCheckIO False True Nothing [SI.i| - module Main where + module Solution where import Data.Maybe import Helper (value) From f35afc35456bcc04420d2ee97bbf361f6314e30d Mon Sep 17 00:00:00 2001 From: nimec01 <24428341+nimec01@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:16:12 +0000 Subject: [PATCH 98/99] format new files --- src/Haskell/Template/Detection/Maybe.hs | 6 ++--- test/Haskell/Template/GradingSpec.hs | 33 ++++++++++++++----------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/Haskell/Template/Detection/Maybe.hs b/src/Haskell/Template/Detection/Maybe.hs index 66a723e..dd10690 100644 --- a/src/Haskell/Template/Detection/Maybe.hs +++ b/src/Haskell/Template/Detection/Maybe.hs @@ -2,7 +2,7 @@ module Haskell.Template.Detection.Maybe (collectIfsWithMaybeChecks) where import Control.Monad (void) import Data.Data (Data) -import Data.Generics (everything, listify, mkQ, mkT, everywhere') +import Data.Generics (everything, everywhere', listify, mkQ, mkT) import Data.List.Extra (notNull) import Data.Maybe (listToMaybe, mapMaybe, maybeToList) import Data.Set (Set) @@ -134,8 +134,8 @@ replaceFromJustWithValue valueName maybeValue = void . everywhere' (mkT replace) 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)) + | 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 diff --git a/test/Haskell/Template/GradingSpec.hs b/test/Haskell/Template/GradingSpec.hs index f98f8a0..4fe237d 100644 --- a/test/Haskell/Template/GradingSpec.hs +++ b/test/Haskell/Template/GradingSpec.hs @@ -6,7 +6,7 @@ import Control.Exception (IOException, try) import Data.Aeson (ToJSON) import Data.Either.Extra (isRight, mapLeft) import Data.IORef (modifyIORef, newIORef, readIORef) -import Data.List (isPrefixOf, isInfixOf) +import Data.List (isInfixOf, isPrefixOf) import Data.Maybe (fromMaybe) import qualified Data.String.Interpolate as SI (i) import Data.Text (unpack) @@ -52,7 +52,9 @@ encodeConfig :: ToJSON a => a -> String encodeConfig = unpack . decodeUtf8Lenient . encodePretty (setConfCompare compare defConfig) maybeTaskConfig :: Status -> String -maybeTaskConfig maybeStatus = encodeConfig (maybeConfig maybeStatus) ++[SI.i| +maybeTaskConfig maybeStatus = + encodeConfig (maybeConfig maybeStatus) + ++ [SI.i| --- module Solution where @@ -94,7 +96,8 @@ maybeConfig maybeStatus = } maybeModule :: String -> String -maybeModule testBody = [SI.i|module Solution where +maybeModule testBody = + [SI.i|module Solution where import Prelude import Data.Maybe import Test.HUnit (Test (..), assertFailure) @@ -148,9 +151,9 @@ main :: result `shouldSatisfy` \(mResult, infos) -> isRight mResult && any - (\info -> - "Perhaps:" `isInfixOf` info - && "case mVal of" `isInfixOf` info + ( \info -> + "Perhaps:" `isInfixOf` info + && "case mVal of" `isInfixOf` info ) infos it "doesn't provide maybe suggestions when configured to Ignore" $ do @@ -160,11 +163,11 @@ main :: result `shouldSatisfy` \(mResult, infos) -> isRight mResult && not - (any - (\info -> - "Found:" `isInfixOf` info || "Perhaps:" `isInfixOf` info - ) - infos + ( 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\")]" @@ -176,8 +179,9 @@ main :: && 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} + let settings = encodeConfig ((maybeConfig Hint) {configLanguageExtensions = Just ["NoImplicitPrelude"]}) + let taskConfig = + [SI.i|#{settings} --- module Solution where import Data.Maybe @@ -206,7 +210,8 @@ import Prelude (Bool (..)) _ /= _ = False |] - let source = [SI.i|module Solution where + let source = + [SI.i|module Solution where import Data.Maybe import Test.HUnit (Test (..), assertFailure) import Helper From 0d8e21b97743400b72cb41dbb28fe49d33ef69b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Janis=20Voigtl=C3=A4nder?= Date: Mon, 30 Nov 2026 14:21:05 +0100 Subject: [PATCH 99/99] Clarify description of edge cases in TaskSpec --- test/Haskell/Template/TaskSpec.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Haskell/Template/TaskSpec.hs b/test/Haskell/Template/TaskSpec.hs index 0659e6b..3599fc7 100644 --- a/test/Haskell/Template/TaskSpec.hs +++ b/test/Haskell/Template/TaskSpec.hs @@ -377,7 +377,7 @@ Perhaps: def m = if Data.Maybe.isJust m then Data.Maybe.fromJust m else 0|] result `shouldBe` [] - describe "edge cases" $ do + 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 \#-}