diff --git a/main/Main.hs b/main/Main.hs index a3116754c..c7c29bb87 100644 --- a/main/Main.hs +++ b/main/Main.hs @@ -51,24 +51,24 @@ main = do runWithBasicEffectsIO opts $ case readFrom opts of Just path -> do let file = addExtension (dropExtension path) "nixc" - process opts (Just file) =<< liftIO (readCache path) + process opts (pure file) =<< liftIO (readCache path) Nothing -> case expression opts of - Just s -> handleResult opts Nothing (parseNixTextLoc s) + Just s -> handleResult opts mempty (parseNixTextLoc s) Nothing -> case fromFile opts of Just "-" -> mapM_ (processFile opts) . lines =<< liftIO getContents Just path -> mapM_ (processFile opts) . lines =<< liftIO (readFile path) Nothing -> case filePaths opts of - [] -> withNixContext Nothing Repl.main + [] -> withNixContext mempty Repl.main ["-"] -> - handleResult opts Nothing + handleResult opts mempty . parseNixTextLoc =<< liftIO Text.getContents paths -> mapM_ (processFile opts) paths where processFile opts path = do eres <- parseNixFileLoc path - handleResult opts (Just path) eres + handleResult opts (pure path) eres handleResult opts mpath = \case Failure err -> @@ -77,14 +77,14 @@ main = do else errorWithoutStackTrace ) $ "Parse failed: " - ++ show err + <> show err Success expr -> do when (check opts) $ do expr' <- liftIO (reduceExpr mpath expr) case HM.inferTop Env.empty [("it", stripAnnotation expr')] of - Left err -> errorWithoutStackTrace $ "Type error: " ++ PS.ppShow err - Right ty -> liftIO $ putStrLn $ "Type of expression: " ++ PS.ppShow + Left err -> errorWithoutStackTrace $ "Type error: " <> PS.ppShow err + Right ty -> liftIO $ putStrLn $ "Type of expression: " <> PS.ppShow (fromJust (Map.lookup "it" (Env.types ty))) -- liftIO $ putStrLn $ runST $ @@ -102,8 +102,8 @@ main = do if evaluate opts then do val <- Nix.nixEvalExprLoc mpath expr - withNixContext Nothing (Repl.main' $ Just val) - else withNixContext Nothing Repl.main + withNixContext mempty (Repl.main' $ pure val) + else withNixContext mempty Repl.main process opts mpath expr | evaluate opts @@ -165,9 +165,9 @@ main = do where go prefix s = do xs <- forM (sortOn fst (M.toList s)) $ \(k, nv) -> case nv of - Free v -> pure (k, Just (Free v)) + Free v -> pure (k, pure (Free v)) Pure (StdThunk (extract -> Thunk _ _ ref)) -> do - let path = prefix ++ Text.unpack k + let path = prefix <> Text.unpack k (_, descend) = filterEntry path k val <- readVar @(StandardT (StdIdT IO)) ref case val of @@ -176,14 +176,14 @@ main = do | otherwise -> pure (k, Nothing) forM_ xs $ \(k, mv) -> do - let path = prefix ++ Text.unpack k + let path = prefix <> Text.unpack k (report, descend) = filterEntry path k when report $ do liftIO $ putStrLn path when descend $ case mv of Nothing -> pure () Just v -> case v of - NVSet s' _ -> go (path ++ ".") s' + NVSet s' _ -> go (path <> ".") s' _ -> pure () where filterEntry path k = case (path, k) of @@ -204,12 +204,12 @@ main = do _ -> (True, True) forceEntry k v = - catch (Just <$> demand v pure) $ \(NixException frames) -> do + catch (pure <$> demand v pure) $ \(NixException frames) -> do liftIO . putStrLn - . ("Exception forcing " ++) - . (k ++) - . (": " ++) + . ("Exception forcing " <>) + . (k <>) + . (": " <>) . show =<< renderFrames @(StdValue (StandardT (StdIdT IO))) @(StdThunk (StandardT (StdIdT IO))) @@ -228,7 +228,7 @@ main = do -> m (NValue t f m) handleReduced path (expr', eres) = do liftIO $ do - putStrLn $ "Wrote winnowed expression tree to " ++ path + putStrLn $ "Wrote winnowed expression tree to " <> path writeFile path $ show $ prettyNix (stripAnnotation expr') case eres of Left err -> throwM err diff --git a/main/Repl.hs b/main/Repl.hs index a35946d33..7143f82e1 100644 --- a/main/Repl.hs +++ b/main/Repl.hs @@ -76,10 +76,10 @@ main' iniVal = initState iniVal >>= \s -> flip evalStateT s banner cmd options - (Just commandPrefix) - (Just "paste") + (pure commandPrefix) + (pure "paste") completion - (rcFile >> greeter) + (rcFile *> greeter) finalizer where commandPrefix = ':' @@ -119,7 +119,7 @@ main' iniVal = initState iniVal >>= \s -> flip evalStateT s -> System.Console.Repline.Options m -> String -> m () - optMatcher s [] _ = liftIO $ putStrLn $ "No such command :" ++ s + optMatcher s [] _ = liftIO $ putStrLn $ "No such command :" <> s optMatcher s ((x, m) : xs) args | s `Data.List.isPrefixOf` x = m args | otherwise = optMatcher s xs args @@ -166,7 +166,7 @@ initState mIni = do where evalText :: (MonadNix e t f m) => Text -> m (NValue t f m) evalText expr = case parseNixTextLoc expr of - Failure e -> error $ "Impossible happened: Unable to parse expression - '" ++ Data.Text.unpack expr ++ "' error was " ++ show e + Failure e -> error $ "Impossible happened: Unable to parse expression - '" <> Data.Text.unpack expr <> "' error was " <> show e Success e -> do evalExprLoc e type Repl e t f m = HaskelineT (StateT (IState t f m) m) @@ -212,14 +212,14 @@ exec update source = do -- Update the interpreter state when (update && isBinding) $ do -- Set `replIt` to last entered expression - put st { replIt = Just expr } + put st { replIt = pure expr } -- If the result value is a set, update our context with it case val of NVSet xs _ -> put st { replCtx = Data.HashMap.Lazy.union xs (replCtx st) } _ -> pure () - pure $ Just val + pure $ pure val where -- If parsing fails, turn the input into singleton attribute set -- and try again. @@ -292,7 +292,7 @@ typeof typeof args = do st <- get mVal <- case Data.HashMap.Lazy.lookup line (replCtx st) of - Just val -> pure $ Just val + Just val -> pure $ pure val Nothing -> do exec False line @@ -329,7 +329,7 @@ completion :: (MonadNix e t f m, MonadIO m) => CompleterStyle (StateT (IState t f m) m) completion = System.Console.Repline.Prefix - (completeWordWithPrev (Just '\\') separators completeFunc) + (completeWordWithPrev (pure '\\') separators completeFunc) defaultMatcher where separators :: String @@ -360,7 +360,7 @@ completeFunc reversedPrev word = do s <- get case Data.HashMap.Lazy.lookup var (replCtx s) of - Nothing -> pure [] + Nothing -> pure mempty Just binding -> do candidates <- lift $ algebraicComplete subFields binding pure $ notFinished <$> listCompletion (Data.Text.unpack . (var <>) <$> candidates) @@ -396,14 +396,14 @@ completeFunc reversedPrev word [_] -> pure $ keys m f:fs -> case Data.HashMap.Lazy.lookup f m of - Nothing -> pure [] + Nothing -> pure mempty Just e -> demand e (\e' -> (fmap . fmap) (("." <> f) <>) $ algebraicComplete fs e') in case val of NVSet xs _ -> withMap xs - _ -> pure [] + _ -> pure mempty -- HelpOption inspired by Dhall Repl -- with `Doc` instead of String for syntax and doc diff --git a/src/Nix.hs b/src/Nix.hs index bc94c8e48..f443a3342 100644 --- a/src/Nix.hs +++ b/src/Nix.hs @@ -107,7 +107,7 @@ evaluateExpression -> m a evaluateExpression mpath evaluator handler expr = do opts :: Options <- asks (view hasLens) - args <- traverse (traverse eval') $ fmap (second parseArg) (arg opts) ++ fmap + args <- traverse (traverse eval') $ fmap (second parseArg) (arg opts) <> fmap (second mkStr) (argstr opts) evaluator mpath expr >>= \f -> demand f $ \f' -> @@ -144,22 +144,22 @@ processResult h val = do _ -> errorWithoutStackTrace $ "Expected a list for selector '" - ++ show n - ++ "', but got: " - ++ show v + <> show n + <> "', but got: " + <> show v go (k : ks) v = demand v $ \case NVSet xs _ -> case M.lookup k xs of Nothing -> errorWithoutStackTrace $ "Set does not contain key '" - ++ Text.unpack k - ++ "'" + <> Text.unpack k + <> "'" Just v' -> case ks of [] -> h v' _ -> go ks v' _ -> errorWithoutStackTrace $ "Expected a set for selector '" - ++ Text.unpack k - ++ "', but got: " - ++ show v + <> Text.unpack k + <> "', but got: " + <> show v diff --git a/src/Nix/Builtins.hs b/src/Nix/Builtins.hs index 48ba12e6b..245b53ee9 100644 --- a/src/Nix/Builtins.hs +++ b/src/Nix/Builtins.hs @@ -316,7 +316,7 @@ foldNixPath foldNixPath f z = do mres <- lookupVar "__includes" dirs <- case mres of - Nothing -> pure [] + Nothing -> pure mempty Just v -> demand v $ fromValue . Deeper mPath <- getEnvVar "NIX_PATH" mDataDir <- getEnvVar "NIX_DATA_DIR" @@ -324,19 +324,19 @@ foldNixPath f z = do foldrM go z $ fmap (fromInclude . stringIgnoreContext) dirs <> case mPath of - Nothing -> [] + Nothing -> mempty Just str -> uriAwareSplit (Text.pack str) <> [ fromInclude $ Text.pack $ "nix=" <> dataDir <> "/nix/corepkgs" ] where fromInclude x | "://" `Text.isInfixOf` x = (x, PathEntryURI) | otherwise = (x, PathEntryPath) go (x, ty) rest = case Text.splitOn "=" x of - [p] -> f (Text.unpack p) Nothing ty rest - [n, p] -> f (Text.unpack p) (Just (Text.unpack n)) ty rest + [p] -> f (Text.unpack p) mempty ty rest + [n, p] -> f (Text.unpack p) (pure (Text.unpack n)) ty rest _ -> throwError $ ErrorCall $ "Unexpected entry in NIX_PATH: " <> show x nixPath :: MonadNix e t f m => m (NValue t f m) -nixPath = fmap nvList $ flip foldNixPath [] $ \p mn ty rest -> +nixPath = fmap nvList $ flip foldNixPath mempty $ \p mn ty rest -> pure $ flip nvSet mempty ( M.fromList [ case ty of @@ -512,7 +512,7 @@ versionComponentSeparators = ".-" splitVersion :: Text -> [VersionComponent] splitVersion s = case Text.uncons s of - Nothing -> [] + Nothing -> mempty Just (h, t) | h `elem` versionComponentSeparators -> splitVersion t @@ -575,7 +575,7 @@ splitDrvName s = breakAfterFirstItem :: (a -> Bool) -> [a] -> ([a], [a]) breakAfterFirstItem f = \case h : t -> let (a, b) = break f t in (h : a, b) - [] -> ([], []) + [] -> (mempty, mempty) (namePieces, versionPieces) = breakAfterFirstItem isFirstVersionPiece pieces in @@ -825,7 +825,7 @@ elem_ x = toValue <=< anyM (valueEqM x) <=< fromValue elemAt :: [a] -> Int -> Maybe a elemAt ls i = case drop i ls of [] -> Nothing - a : _ -> Just a + a : _ -> pure a elemAt_ :: MonadNix e t f m @@ -910,7 +910,7 @@ genericClosure = fromValue @(AttrSet (NValue t f m)) >=> \s -> -> [NValue t f m] -> Set (WValue t f m) -> m (Set (WValue t f m), [NValue t f m]) - go _ [] ks = pure (ks, []) + go _ [] ks = pure (ks, mempty) go op (t : ts) ks = demand t $ \v -> fromValue @(AttrSet (NValue t f m)) v >>= \s -> do k <- attrsetGet "key" s demand k $ \k' -> do @@ -1108,7 +1108,7 @@ scopedImport asetArg pathArg = fromValue @(AttrSet (NValue t f m)) asetArg >>= \ traceM $ "Current file being evaluated is: " <> show p' pure $ takeDirectory p' path clearScopes @(NValue t f m) - $ withNixContext (Just path') + $ withNixContext (pure path') $ pushScope s $ importPath @t @f @m path' @@ -1480,7 +1480,7 @@ appendContext x y = demand x $ \x' -> demand y $ \y' -> case (x', y') of allOutputs <- maybe (pure False) (demand ?? fromValue) $ M.lookup "allOutputs" attrs outputs <- case M.lookup "outputs" attrs of - Nothing -> pure [] + Nothing -> pure mempty Just os -> demand os $ \case NVList vs -> forM vs $ fmap stringIgnoreContext . fromValue diff --git a/src/Nix/Cache.hs b/src/Nix/Cache.hs index f7dde7a1c..1ca44b234 100644 --- a/src/Nix/Cache.hs +++ b/src/Nix/Cache.hs @@ -24,13 +24,13 @@ readCache path = do eres <- C.unsafeReadCompact path case eres of Left err -> error $ "Error reading cache file: " <> err - Right expr -> return $ C.getCompact expr + Right expr -> pure $ C.getCompact expr #else #ifdef MIN_VERSION_serialise eres <- S.deserialiseOrFail <$> BS.readFile path case eres of Left err -> error $ "Error reading cache file: " <> show err - Right expr -> return expr + Right expr -> pure expr #else error "readCache not implemented for this platform" #endif diff --git a/src/Nix/Cited.hs b/src/Nix/Cited.hs index 90855df83..3e94430e5 100644 --- a/src/Nix/Cited.hs +++ b/src/Nix/Cited.hs @@ -38,7 +38,7 @@ data NCited m v a = NCited deriving (Generic, Typeable, Functor, Foldable, Traversable, Show) instance Applicative (NCited m v) where - pure = NCited [] + pure = NCited mempty NCited xs f <*> NCited ys x = NCited (xs <> ys) (f x) instance Comonad (NCited m v) where diff --git a/src/Nix/Cited/Basic.hs b/src/Nix/Cited/Basic.hs index 91569d345..935b8ecd1 100644 --- a/src/Nix/Cited/Basic.hs +++ b/src/Nix/Cited/Basic.hs @@ -66,11 +66,11 @@ instance ( Has e Options (Fix (Compose (Ann s e))))) = let e' = Compose (Ann s (Nothing <$ e)) in [Provenance scope e'] - go _ = [] + go _ = mempty ps = concatMap (go . frame) frames fmap (Cited . NCited ps) . thunk $ mv - else fmap (Cited . NCited []) . thunk $ mv + else fmap (Cited . NCited mempty) . thunk $ mv thunkId (Cited (NCited _ t)) = thunkId @_ @m t diff --git a/src/Nix/Context.hs b/src/Nix/Context.hs index 5d14677e2..fec3caff0 100644 --- a/src/Nix/Context.hs +++ b/src/Nix/Context.hs @@ -32,4 +32,4 @@ instance Has (Context m t) Options where hasLens f a = (\x -> a { options = x }) <$> f (options a) newContext :: Options -> Context m t -newContext = Context emptyScopes nullSpan [] +newContext = Context emptyScopes nullSpan mempty diff --git a/src/Nix/Convert.hs b/src/Nix/Convert.hs index 7fe84cfac..9e2ec0d9e 100644 --- a/src/Nix/Convert.hs +++ b/src/Nix/Convert.hs @@ -98,8 +98,8 @@ instance ( Convertible e t f m instance Convertible e t f m => FromValue () m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVConstant' NNull -> pure $ Just () - _ -> pure Nothing + NVConstant' NNull -> pure $ pure () + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m TNull (Free v) @@ -107,7 +107,7 @@ instance Convertible e t f m instance Convertible e t f m => FromValue Bool m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVConstant' (NBool b) -> pure $ Just b + NVConstant' (NBool b) -> pure $ pure b _ -> pure Nothing fromValue v = fromValueMay v >>= \case Just b -> pure b @@ -116,7 +116,7 @@ instance Convertible e t f m instance Convertible e t f m => FromValue Int m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVConstant' (NInt b) -> pure $ Just (fromInteger b) + NVConstant' (NInt b) -> pure $ pure (fromInteger b) _ -> pure Nothing fromValue v = fromValueMay v >>= \case Just b -> pure b @@ -125,7 +125,7 @@ instance Convertible e t f m instance Convertible e t f m => FromValue Integer m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVConstant' (NInt b) -> pure $ Just b + NVConstant' (NInt b) -> pure $ pure b _ -> pure Nothing fromValue v = fromValueMay v >>= \case Just b -> pure b @@ -134,8 +134,8 @@ instance Convertible e t f m instance Convertible e t f m => FromValue Float m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVConstant' (NFloat b) -> pure $ Just b - NVConstant' (NInt i) -> pure $ Just (fromInteger i) + NVConstant' (NFloat b) -> pure $ pure b + NVConstant' (NInt i) -> pure $ pure (fromInteger i) _ -> pure Nothing fromValue v = fromValueMay v >>= \case Just b -> pure b @@ -147,17 +147,17 @@ instance ( Convertible e t f m ) => FromValue NixString m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVStr' ns -> pure $ Just ns + NVStr' ns -> pure $ pure ns NVPath' p -> - Just + pure . (\s -> makeNixStringWithSingletonContext s (StringContext s DirectPath)) . Text.pack . unStorePath <$> addPath p NVSet' s _ -> case M.lookup "outPath" s of - Nothing -> pure Nothing + Nothing -> pure mempty Just p -> fromValueMay p - _ -> pure Nothing + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m (TString NoContext) (Free v) @@ -166,7 +166,7 @@ instance Convertible e t f m => FromValue ByteString m (NValue' t f m (NValue t f m)) where fromValueMay = \case NVStr' ns -> pure $ encodeUtf8 <$> getStringNoContext ns - _ -> pure Nothing + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m (TString NoContext) (Free v) @@ -179,7 +179,7 @@ instance ( Convertible e t f m ) => FromValue Path m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVPath' p -> pure $ Just (Path p) + NVPath' p -> pure $ pure (Path p) NVStr' ns -> pure $ Path . Text.unpack <$> getStringNoContext ns NVSet' s _ -> case M.lookup "outPath" s of Nothing -> pure Nothing @@ -192,8 +192,8 @@ instance ( Convertible e t f m instance Convertible e t f m => FromValue [NValue t f m] m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVList' l -> pure $ Just l - _ -> pure Nothing + NVList' l -> pure $ pure l + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m TList (Free v) @@ -204,7 +204,7 @@ instance ( Convertible e t f m => FromValue [a] m (Deeper (NValue' t f m (NValue t f m))) where fromValueMay = \case Deeper (NVList' l) -> sequence <$> traverse fromValueMay l - _ -> pure Nothing + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m TList (Free (getDeeper v)) @@ -212,8 +212,8 @@ instance ( Convertible e t f m instance Convertible e t f m => FromValue (AttrSet (NValue t f m)) m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVSet' s _ -> pure $ Just s - _ -> pure Nothing + NVSet' s _ -> pure $ pure s + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m TSet (Free v) @@ -224,7 +224,7 @@ instance ( Convertible e t f m => FromValue (AttrSet a) m (Deeper (NValue' t f m (NValue t f m))) where fromValueMay = \case Deeper (NVSet' s _) -> sequence <$> traverse fromValueMay s - _ -> pure Nothing + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m TSet (Free (getDeeper v)) @@ -233,8 +233,8 @@ instance Convertible e t f m => FromValue (AttrSet (NValue t f m), AttrSet SourcePos) m (NValue' t f m (NValue t f m)) where fromValueMay = \case - NVSet' s p -> pure $ Just (s, p) - _ -> pure Nothing + NVSet' s p -> pure $ pure (s, p) + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m TSet (Free v) @@ -246,7 +246,7 @@ instance ( Convertible e t f m (Deeper (NValue' t f m (NValue t f m))) where fromValueMay = \case Deeper (NVSet' s p) -> fmap (, p) . sequence <$> traverse fromValueMay s - _ -> pure Nothing + _ -> pure mempty fromValue v = fromValueMay v >>= \case Just b -> pure b _ -> throwError $ Expectation @t @f @m TSet (Free (getDeeper v)) @@ -352,9 +352,9 @@ instance (Convertible e t f m, ToValue a m (NValue t f m)) instance Convertible e t f m => ToValue NixLikeContextValue m (NValue' t f m (NValue t f m)) where toValue nlcv = do - path <- if nlcvPath nlcv then Just <$> toValue True else pure Nothing + path <- if nlcvPath nlcv then pure <$> toValue True else pure Nothing allOutputs <- if nlcvAllOutputs nlcv - then Just <$> toValue True + then pure <$> toValue True else pure Nothing outputs <- do let outputs = @@ -362,7 +362,7 @@ instance Convertible e t f m ts :: [NValue t f m] <- traverse toValue outputs case ts of [] -> pure Nothing - _ -> Just <$> toValue ts + _ -> pure <$> toValue ts pure $ flip nvSet' M.empty $ M.fromList $ catMaybes [ ("path",) <$> path , ("allOutputs",) <$> allOutputs diff --git a/src/Nix/Effects.hs b/src/Nix/Effects.hs index b44d914b3..86828c842 100644 --- a/src/Nix/Effects.hs +++ b/src/Nix/Effects.hs @@ -92,7 +92,7 @@ instance MonadIntrospect IO where #if MIN_VERSION_ghc_datasize(0,2,0) recursiveSize #else -\_ -> return 0 +\_ -> pure 0 #endif #else \_ -> pure 0 @@ -269,31 +269,31 @@ class Monad m => MonadStore m where parseStoreResult :: Monad m => String -> (Either String a, [Store.Remote.Logger]) -> m (Either ErrorCall a) parseStoreResult name res = case res of - (Left msg, logs) -> return $ Left $ ErrorCall $ "Failed to execute '" <> name <> "': " <> msg <> "\n" <> show logs - (Right result, _) -> return $ Right result + (Left msg, logs) -> pure $ Left $ ErrorCall $ "Failed to execute '" <> name <> "': " <> msg <> "\n" <> show logs + (Right result, _) -> pure $ Right result instance MonadStore IO where addToStore name path recursive repair = case Store.makeStorePathName name of - Left err -> return $ Left $ ErrorCall $ "String '" <> show name <> "' is not a valid path name: " <> err + Left err -> pure $ Left $ ErrorCall $ "String '" <> show name <> "' is not a valid path name: " <> err Right pathName -> do -- TODO: redesign the filter parameter res <- Store.Remote.runStore $ Store.Remote.addToStore @'Store.SHA256 pathName path recursive (const False) repair parseStoreResult "addToStore" res >>= \case - Left err -> return $ Left err - Right storePath -> return $ Right $ StorePath $ T.unpack $ T.decodeUtf8 $ Store.storePathToRawFilePath storePath + Left err -> pure $ Left err + Right storePath -> pure $ Right $ StorePath $ T.unpack $ T.decodeUtf8 $ Store.storePathToRawFilePath storePath addTextToStore' name text references repair = do res <- Store.Remote.runStore $ Store.Remote.addTextToStore name text references repair parseStoreResult "addTextToStore" res >>= \case - Left err -> return $ Left err - Right path -> return $ Right $ StorePath $ T.unpack $ T.decodeUtf8 $ Store.storePathToRawFilePath path + Left err -> pure $ Left err + Right path -> pure $ Right $ StorePath $ T.unpack $ T.decodeUtf8 $ Store.storePathToRawFilePath path addTextToStore :: (Framed e m, MonadStore m) => StorePathName -> Text -> Store.StorePathSet -> RepairFlag -> m StorePath -addTextToStore a b c d = either throwError return =<< addTextToStore' a b c d +addTextToStore a b c d = either throwError pure =<< addTextToStore' a b c d addPath :: (Framed e m, MonadStore m) => FilePath -> m StorePath -addPath p = either throwError return =<< addToStore (T.pack $ takeFileName p) p True False +addPath p = either throwError pure =<< addToStore (T.pack $ takeFileName p) p True False toFile_ :: (Framed e m, MonadStore m) => FilePath -> String -> m StorePath toFile_ p contents = addTextToStore (T.pack p) (T.pack contents) HS.empty False diff --git a/src/Nix/Effects/Basic.hs b/src/Nix/Effects/Basic.hs index b647e9260..d8fc2369c 100644 --- a/src/Nix/Effects/Basic.hs +++ b/src/Nix/Effects/Basic.hs @@ -73,7 +73,7 @@ expandHomePath p = pure p -- parent may be a different directory from @a@. See the discussion at -- https://hackage.haskell.org/package/directory-1.3.1.5/docs/System-Directory.html#v:canonicalizePath removeDotDotIndirections :: FilePath -> FilePath -removeDotDotIndirections = intercalate "/" . go [] . splitOn "/" +removeDotDotIndirections = intercalate "/" . go mempty . splitOn "/" where go s [] = reverse s go (_ : s) (".." : rest) = go s rest @@ -105,9 +105,9 @@ findEnvPathM name = do isDir <- doesDirectoryExist absPath absFile <- if isDir then makeAbsolutePath @t @f $ absPath "default.nix" - else return absPath + else pure absPath exists <- doesFileExist absFile - pure $ if exists then Just absFile else Nothing + pure $ if exists then pure absFile else mempty findPathBy :: forall e t f m @@ -117,7 +117,7 @@ findPathBy -> FilePath -> m FilePath findPathBy finder ls name = do - mpath <- foldM go Nothing ls + mpath <- foldM go mempty ls case mpath of Nothing -> throwError @@ -134,14 +134,14 @@ findPathBy finder ls name = do demand l $ fromValue >=> \(s :: HashMap Text (NValue t f m)) -> do p <- resolvePath s demand p $ fromValue >=> \(Path path) -> case M.lookup "prefix" s of - Nothing -> tryPath path Nothing + Nothing -> tryPath path mempty Just pf -> demand pf $ fromValueMay >=> \case Just (nsPfx :: NixString) -> let pfx = stringIgnoreContext nsPfx in if not (Text.null pfx) - then tryPath path (Just (Text.unpack pfx)) - else tryPath path Nothing - _ -> tryPath path Nothing + then tryPath path (pure (Text.unpack pfx)) + else tryPath path mempty + _ -> tryPath path mempty tryPath p (Just n) | n' : ns <- splitDirectories name, n == n' = finder $ p joinPath ns @@ -222,7 +222,7 @@ findPathM = findPathBy existingPath existingPath path = do apath <- makeAbsolutePath @t @f path exists <- doesPathExist apath - pure $ if exists then Just apath else Nothing + pure $ if exists then pure apath else mempty defaultImportPath :: (MonadNix e t f m, MonadState (HashMap FilePath NExprLoc, b) m) diff --git a/src/Nix/Effects/Derivation.hs b/src/Nix/Effects/Derivation.hs index 7d7b234f6..4398140fe 100644 --- a/src/Nix/Effects/Derivation.hs +++ b/src/Nix/Effects/Derivation.hs @@ -73,7 +73,7 @@ defaultDerivation = Derivation , inputs = (Set.empty, Map.empty) , platform = undefined , builder = undefined - , args = [] + , args = mempty , env = Map.empty , mFixed = Nothing , hashMode = Flat @@ -86,17 +86,17 @@ data HashMode = Flat | Recursive makeStorePathName :: (Framed e m) => Text -> m Store.StorePathName makeStorePathName name = case Store.makeStorePathName name of Left err -> throwError $ ErrorCall $ "Invalid name '" <> show name <> "' for use in a store path: " <> err - Right spname -> return spname + Right spname -> pure spname parsePath :: (Framed e m) => Text -> m Store.StorePath parsePath p = case Store.parsePath "/nix/store" (Text.encodeUtf8 p) of Left err -> throwError $ ErrorCall $ "Cannot parse store path " <> show p <> ":\n" <> show err - Right path -> return path + Right path -> pure path writeDerivation :: (Framed e m, MonadStore m) => Derivation -> m Store.StorePath -writeDerivation (drv@Derivation {inputs, name}) = do +writeDerivation drv@Derivation{inputs, name} = do let (inputSrcs, inputDrvs) = inputs - references <- Set.fromList <$> (mapM parsePath $ Set.toList $ inputSrcs `Set.union` (Set.fromList $ Map.keys inputDrvs)) + references <- fmap Set.fromList $ mapM parsePath $ Set.toList $ Set.union inputSrcs $ Set.fromList $ Map.keys inputDrvs path <- addTextToStore (Text.append name ".drv") (unparseDrv drv) (S.fromList $ Set.toList references) False parsePath $ Text.pack $ unStorePath path @@ -108,27 +108,27 @@ hashDerivationModulo (Derivation { outputs, hashMode }) = case Map.toList outputs of - [("out", path)] -> return $ Store.hash @'Store.SHA256 $ Text.encodeUtf8 + [("out", path)] -> pure $ Store.hash @'Store.SHA256 $ Text.encodeUtf8 $ "fixed:out" <> (if hashMode == Recursive then ":r" else "") <> ":" <> (Store.algoName @hashType) - <> ":" <> (Store.encodeInBase Store.Base16 digest) + <> ":" <> Store.encodeInBase Store.Base16 digest <> ":" <> path outputsList -> throwError $ ErrorCall $ "This is weird. A fixed output drv should only have one output named 'out'. Got " <> show outputsList -hashDerivationModulo drv@(Derivation {inputs = (inputSrcs, inputDrvs)}) = do +hashDerivationModulo drv@Derivation{inputs = (inputSrcs, inputDrvs)} = do cache <- gets snd inputsModulo <- Map.fromList <$> forM (Map.toList inputDrvs) (\(path, outs) -> case MS.lookup path cache of - Just hash -> return (hash, outs) + Just hash -> pure (hash, outs) Nothing -> do drv' <- readDerivation $ Text.unpack path hash <- Store.encodeInBase Store.Base16 <$> hashDerivationModulo drv' - return (hash, outs) + pure (hash, outs) ) - return $ Store.hash @'Store.SHA256 $ Text.encodeUtf8 $ unparseDrv (drv {inputs = (inputSrcs, inputsModulo)}) + pure $ Store.hash @'Store.SHA256 $ Text.encodeUtf8 $ unparseDrv (drv {inputs = (inputSrcs, inputsModulo)}) unparseDrv :: Derivation -> Text -unparseDrv (Derivation {..}) = Text.append "Derive" $ parens +unparseDrv Derivation{..} = Text.append "Derive" $ parens [ -- outputs: [("out", "/nix/store/.....-out", "", ""), ...] list $ flip fmap (Map.toList outputs) (\(outputName, outputPath) -> let prefix = if hashMode == Recursive then "r:" else "" in @@ -169,7 +169,7 @@ readDerivation path = do content <- Text.decodeUtf8 <$> readFile path case parse derivationParser path content of Left err -> throwError $ ErrorCall $ "Failed to parse " <> show path <> ":\n" <> show err - Right drv -> return drv + Right drv -> pure drv derivationParser :: Parsec () Text Derivation derivationParser = do @@ -197,7 +197,7 @@ derivationParser = do let name = "" -- FIXME (extract from file path ?) let useJson = ["__json"] == Map.keys env - return $ Derivation {inputs = (inputSrcs, inputDrvs), ..} + pure $ Derivation {inputs = (inputSrcs, inputDrvs), ..} where s :: Parsec () Text Text s = fmap Text.pack $ string "\"" *> manyTill (escaped <|> regular) (string "\"") @@ -221,7 +221,7 @@ derivationParser = do [ht] -> (ht, Flat) _ -> error $ "Unsupported hash type for output of fixed-output derivation in .drv file: " <> show fullOutputs in case Store.mkNamedDigest hashType hash of - Right digest -> (Just digest, hashMode) + Right digest -> (pure digest, hashMode) Left err -> error $ "Unsupported hash " <> show (hashType <> ":" <> hash) <> "in .drv file: " <> err _ -> (Nothing, Flat) @@ -238,7 +238,7 @@ defaultDerivationStrict = fromValue @(AttrSet (NValue t f m)) >=> \s -> do Just (Store.SomeDigest digest) -> do let out = pathToText $ Store.makeFixedOutputPath "/nix/store" (hashMode drv == Recursive) digest drvName let env' = if useJson drv then env drv else Map.insert "out" out (env drv) - return $ drv { inputs, env = env', outputs = Map.singleton "out" out } + pure $ drv { inputs, env = env', outputs = Map.singleton "out" out } Nothing -> do hash <- hashDerivationModulo $ drv @@ -248,7 +248,7 @@ defaultDerivationStrict = fromValue @(AttrSet (NValue t f m)) >=> \s -> do else foldl' (\m k -> Map.insert k "" m) (env drv) (Map.keys $ outputs drv) } outputs' <- sequence $ Map.mapWithKey (\o _ -> makeOutputPath o hash drvName) (outputs drv) - return $ drv + pure $ drv { inputs , outputs = outputs' , env = if useJson drv then env drv else Map.union outputs' (env drv) @@ -265,7 +265,7 @@ defaultDerivationStrict = fromValue @(AttrSet (NValue t f m)) >=> \s -> do attrSet = M.map nvStr $ M.fromList $ ("drvPath", drvPathWithContext): Map.toList outputsWithContext -- TODO: Add location information for all the entries. -- here --v - return $ nvSet attrSet M.empty + pure $ nvSet attrSet M.empty where @@ -273,7 +273,7 @@ defaultDerivationStrict = fromValue @(AttrSet (NValue t f m)) >=> \s -> do makeOutputPath o h n = do name <- makeStorePathName (Store.unStorePathName n <> if o == "out" then "" else "-" <> o) - return $ pathToText $ Store.makeStorePath "/nix/store" ("output:" <> Text.encodeUtf8 o) h name + pure $ pathToText $ Store.makeStorePath "/nix/store" ("output:" <> Text.encodeUtf8 o) h name toStorePaths ctx = foldl (flip addToInputs) (Set.empty, Map.empty) ctx addToInputs (StringContext path kind) = case kind of @@ -294,30 +294,30 @@ buildDerivationWithContext drvAttrs = do drvName <- getAttr "name" $ extractNixString >=> assertDrvStoreName withFrame' Info (ErrorCall $ "While evaluating derivation " <> show drvName) $ do - useJson <- getAttrOr "__structuredAttrs" False $ return - ignoreNulls <- getAttrOr "__ignoreNulls" False $ return + useJson <- getAttrOr "__structuredAttrs" False $ pure + ignoreNulls <- getAttrOr "__ignoreNulls" False $ pure - args <- getAttrOr "args" [] $ mapM (fromValue' >=> extractNixString) + args <- getAttrOr "args" mempty $ mapM (fromValue' >=> extractNixString) builder <- getAttr "builder" $ extractNixString platform <- getAttr "system" $ extractNoCtx >=> assertNonNull - mHash <- getAttrOr "outputHash" Nothing $ extractNoCtx >=> (return . Just) + mHash <- getAttrOr "outputHash" mempty $ extractNoCtx >=> (pure . pure) hashMode <- getAttrOr "outputHashMode" Flat $ extractNoCtx >=> parseHashMode outputs <- getAttrOr "outputs" ["out"] $ mapM (fromValue' >=> extractNoCtx) mFixedOutput <- case mHash of - Nothing -> return Nothing + Nothing -> pure Nothing Just hash -> do when (outputs /= ["out"]) $ lift $ throwError $ ErrorCall $ "Multiple outputs are not supported for fixed-output derivations" hashType <- getAttr "outputHashAlgo" $ extractNoCtx - digest <- lift $ either (throwError . ErrorCall) return $ Store.mkNamedDigest hashType hash - return $ Just digest + digest <- lift $ either (throwError . ErrorCall) pure $ Store.mkNamedDigest hashType hash + pure $ pure digest -- filter out null values if needed. attrs <- if not ignoreNulls - then return drvAttrs + then pure drvAttrs else M.mapMaybe id <$> forM drvAttrs (demand' ?? (\case - NVConstant NNull -> return Nothing - value -> return $ Just value + NVConstant NNull -> pure Nothing + value -> pure $ pure value )) env <- if useJson @@ -325,12 +325,12 @@ buildDerivationWithContext drvAttrs = do jsonString :: NixString <- lift $ nvalueToJSONNixString $ flip nvSet M.empty $ deleteKeys [ "args", "__ignoreNulls", "__structuredAttrs" ] attrs rawString :: Text <- extractNixString jsonString - return $ Map.singleton "__json" rawString + pure $ Map.singleton "__json" rawString else mapM (lift . coerceToString callFunc CopyToStore CoerceAny >=> extractNixString) $ Map.fromList $ M.toList $ deleteKeys [ "args", "__ignoreNulls" ] attrs - return $ defaultDerivation { platform, builder, args, env, hashMode, useJson + pure $ defaultDerivation { platform, builder, args, env, hashMode, useJson , name = drvName , outputs = Map.fromList $ fmap (\o -> (o, "")) outputs , mFixed = mFixedOutput @@ -339,13 +339,13 @@ buildDerivationWithContext drvAttrs = do -- common functions, lifted to WithStringContextT demand' :: NValue t f m -> (NValue t f m -> WithStringContextT m a) -> WithStringContextT m a - demand' v f = join $ lift $ demand v (return . f) + demand' v f = join $ lift $ demand v (pure . f) fromValue' :: (FromValue a m (NValue' t f m (NValue t f m)), MonadNix e t f m) => NValue t f m -> WithStringContextT m a fromValue' = lift . fromValue withFrame' :: (Framed e m, Exception s) => NixLevel -> s -> WithStringContextT m a -> WithStringContextT m a - withFrame' level f = join . lift . withFrame level f . return + withFrame' level f = join . lift . withFrame level f . pure -- shortcuts to get the (forced) value of an AttrSet field @@ -356,7 +356,7 @@ buildDerivationWithContext drvAttrs = do Just v -> withFrame' Info (ErrorCall $ "While evaluating attribute '" <> show n <> "'") $ fromValue' v >>= f - getAttrOr n d f = getAttrOr' n (return d) f + getAttrOr n d f = getAttrOr' n (pure d) f getAttr n = getAttrOr' n (throwError $ ErrorCall $ "Required attribute '" <> show n <> "' not found.") @@ -370,22 +370,22 @@ buildDerivationWithContext drvAttrs = do when (Text.length name > 211) $ failWith "must be no longer than 211 characters" when (Text.any invalid name) $ failWith "contains some invalid character" when (".drv" `Text.isSuffixOf` name) $ failWith "is not allowed to end in '.drv'" - return name + pure name extractNoCtx :: MonadNix e t f m => NixString -> WithStringContextT m Text extractNoCtx ns = case getStringNoContext ns of Nothing -> lift $ throwError $ ErrorCall $ "The string " <> show ns <> " is not allowed to have a context." - Just v -> return v + Just v -> pure v assertNonNull :: MonadNix e t f m => Text -> WithStringContextT m Text assertNonNull t = do when (Text.null t) $ lift $ throwError $ ErrorCall "Value must not be empty" - return t + pure t parseHashMode :: MonadNix e t f m => Text -> WithStringContextT m HashMode parseHashMode = \case - "flat" -> return Flat - "recursive" -> return Recursive + "flat" -> pure Flat + "recursive" -> pure Recursive other -> lift $ throwError $ ErrorCall $ "Hash mode " <> show other <> " is not valid. It must be either 'flat' or 'recursive'" -- Other helpers diff --git a/src/Nix/Eval.hs b/src/Nix/Eval.hs index f445724c0..e790ce226 100644 --- a/src/Nix/Eval.hs +++ b/src/Nix/Eval.hs @@ -9,7 +9,7 @@ {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeApplications #-} -{-# OPTIONS_GHC -fno-warn-name-shadowing #-} + module Nix.Eval where @@ -132,7 +132,7 @@ eval (NBinary NApp fun arg) = do eval (NBinary op larg rarg) = larg >>= evalBinary op ?? rarg eval (NSelect aset attr alt ) = evalSelect aset attr >>= either go id - where go (s, ks) = fromMaybe (attrMissing ks (Just s)) alt + where go (s, ks) = fromMaybe (attrMissing ks (pure s)) alt eval (NHasAttr aset attr) = evalSelect aset attr >>= toValue . isRight @@ -262,24 +262,26 @@ evalBinds recursive binds = do (M.toList o') go _ (NamedVar pathExpr finalValue pos) = do - let go :: NAttrPath (m v) -> m ([Text], SourcePos, m v) - go = \case - h :| t -> evalSetterKeyName h >>= \case - Nothing -> - pure - ( [] - , nullPos - , toValue @(AttrSet v, AttrSet SourcePos) (mempty, mempty) - ) - Just k -> case t of - [] -> pure ([k], pos, finalValue) - x : xs -> do - (restOfPath, _, v) <- go (x :| xs) - pure (k : restOfPath, pos, v) - go pathExpr <&> \case + let + gogo :: NAttrPath (m v) -> m ([Text], SourcePos, m v) + gogo = \case + h :| t -> evalSetterKeyName h >>= \case + Nothing -> + pure + ( mempty + , nullPos + , toValue @(AttrSet v, AttrSet SourcePos) (mempty, mempty) + ) + Just k -> case t of + [] -> pure ([k], pos, finalValue) + x : xs -> do + (restOfPath, _, v) <- gogo (x :| xs) + pure (k : restOfPath, pos, v) + + gogo pathExpr <&> \case -- When there are no path segments, e.g. `${null} = 5;`, we don't -- bind anything - ([], _, _) -> [] + ([], _, _) -> mempty result -> [result] go scope (Inherit ms names pos) = @@ -292,8 +294,8 @@ evalBinds recursive binds = do mv <- case ms of Nothing -> withScopes scope $ lookupVar key Just s -> - s >>= fromValue @(AttrSet v, AttrSet SourcePos) >>= \(s, _) -> - clearScopes @v $ pushScope s $ lookupVar key + s >>= fromValue @(AttrSet v, AttrSet SourcePos) >>= \(attrset, _) -> + clearScopes @v $ pushScope attrset $ lookupVar key case mv of Nothing -> attrMissing (key :| []) Nothing Just v -> demand v pure @@ -352,11 +354,11 @@ evalSetterKeyName => NKeyName (m v) -> m (Maybe Text) evalSetterKeyName = \case - StaticKey k -> pure (Just k) + StaticKey k -> pure (pure k) DynamicKey k -> runAntiquoted "\n" assembleString (>>= fromValueMay) k <&> \case Just ns -> Just (stringIgnoreContext ns) - _ -> Nothing + _ -> mempty assembleString :: forall v m @@ -370,7 +372,7 @@ assembleString = \case fromParts = fmap (fmap mconcat . sequence) . traverse go go = runAntiquoted "\n" - (pure . Just . makeNixStringWithoutContext) + (pure . pure . makeNixStringWithoutContext) (>>= fromValueMay) buildArgument @@ -398,25 +400,25 @@ buildArgument params arg = do -> Maybe (AttrSet v -> m v) assemble scope isVariadic k = \case That Nothing -> - Just + pure $ const $ evalError @v $ ErrorCall $ "Missing value for parameter: " <> show k That (Just f) -> - Just $ \args -> defer $ withScopes scope $ pushScope args f + pure $ \args -> defer $ withScopes scope $ pushScope args f This _ | isVariadic -> Nothing | otherwise - -> Just + -> pure $ const $ evalError @v $ ErrorCall $ "Unexpected parameter: " <> show k - These x _ -> Just (const (pure x)) + These x _ -> pure (const (pure x)) addSourcePositions :: (MonadReader e m, Has e SrcSpan) => Transform NExprLocF (m a) diff --git a/src/Nix/Exec.hs b/src/Nix/Exec.hs index f3417347f..3329c1c9e 100644 --- a/src/Nix/Exec.hs +++ b/src/Nix/Exec.hs @@ -241,7 +241,7 @@ instance MonadNix e t f m => MonadEval (NValue t f m) m where evalWith c b = do scope <- currentScopes span <- currentPos - (\b -> addProvenance (Provenance scope (NWith_ span Nothing (Just b))) b) + (\b -> addProvenance (Provenance scope (NWith_ span Nothing (pure b))) b) <$> evalWithAttrSet c b evalIf c t f = do @@ -250,13 +250,13 @@ instance MonadNix e t f m => MonadEval (NValue t f m) m where fromValue c >>= \b -> if b then (\t -> addProvenance - (Provenance scope (NIf_ span (Just c) (Just t) Nothing)) + (Provenance scope (NIf_ span (pure c) (pure t) Nothing)) t ) <$> t else (\f -> addProvenance - (Provenance scope (NIf_ span (Just c) Nothing (Just f))) + (Provenance scope (NIf_ span (pure c) Nothing (pure f))) f ) <$> f @@ -267,7 +267,7 @@ instance MonadNix e t f m => MonadEval (NValue t f m) m where then do scope <- currentScopes (\b -> - addProvenance (Provenance scope (NAssert_ span (Just c) (Just b))) b + addProvenance (Provenance scope (NAssert_ span (pure c) (pure b))) b ) <$> body else nverr $ Assertion span c @@ -275,7 +275,7 @@ instance MonadNix e t f m => MonadEval (NValue t f m) m where evalApp f x = do scope <- currentScopes span <- currentPos - addProvenance (Provenance scope (NBinary_ span NApp (Just f) Nothing)) + addProvenance (Provenance scope (NBinary_ span NApp (pure f) Nothing)) <$> (callFunc f =<< defer x) evalAbs p k = do @@ -333,7 +333,7 @@ execUnaryOp scope span op arg = do <> " must evaluate to an atomic type: " <> show x where - unaryOp = pure . nvConstantP (Provenance scope (NUnary_ span op (Just arg))) + unaryOp = pure . nvConstantP (Provenance scope (NUnary_ span op (pure arg))) execBinaryOp :: forall e t f m @@ -365,9 +365,9 @@ execBinaryOp scope span op lval rarg = case op of where toBoolOp :: Maybe (NValue t f m) -> Bool -> m (NValue t f m) toBoolOp r b = pure $ nvConstantP - (Provenance scope (NBinary_ span op (Just lval) r)) + (Provenance scope (NBinary_ span op (pure lval) r)) (NBool b) - boolOp rval = toBoolOp (Just rval) + boolOp rval = toBoolOp (pure rval) bypass = toBoolOp Nothing @@ -430,7 +430,7 @@ execBinaryOpForced scope span op lval rval = case op of where prov :: Provenance m (NValue t f m) - prov = Provenance scope (NBinary_ span op (Just lval) (Just rval)) + prov = Provenance scope (NBinary_ span op (pure lval) (pure rval)) toBool = pure . nvConstantP prov . NBool compare :: (forall a. Ord a => a -> a -> Bool) -> m (NValue t f m) diff --git a/src/Nix/Expr/Shorthands.hs b/src/Nix/Expr/Shorthands.hs index 01b7d20aa..83ba05758 100644 --- a/src/Nix/Expr/Shorthands.hs +++ b/src/Nix/Expr/Shorthands.hs @@ -32,13 +32,13 @@ mkFloatF = NConstant . NFloat -- | Make a regular (double-quoted) string. mkStr :: Text -> NExpr mkStr = Fix . NStr . DoubleQuoted . \case - "" -> [] + "" -> mempty x -> [Plain x] -- | Make an indented string. mkIndentedStr :: Int -> Text -> NExpr mkIndentedStr w = Fix . NStr . Indented w . \case - "" -> [] + "" -> mempty x -> [Plain x] -- | Make a path. Use 'True' if the path should be read from the @@ -78,7 +78,7 @@ mkSynHoleF :: Text -> NExprF a mkSynHoleF = NSynHole mkSelector :: Text -> NAttrPath NExpr -mkSelector = (:| []) . StaticKey +mkSelector = (:| mempty) . StaticKey mkBool :: Bool -> NExpr mkBool = Fix . mkBoolF @@ -99,7 +99,7 @@ mkOper2 :: NBinaryOp -> NExpr -> NExpr -> NExpr mkOper2 op a = Fix . NBinary op a mkParamset :: [(Text, Maybe NExpr)] -> Bool -> Params NExpr -mkParamset params variadic = ParamSet params variadic Nothing +mkParamset params variadic = ParamSet params variadic mempty mkRecSet :: [Binding NExpr] -> NExpr mkRecSet = Fix . NSet NRecursive @@ -145,7 +145,7 @@ inherit = Inherit Nothing -- | An `inherit` clause with an expression to pull from. inheritFrom :: e -> [NKeyName e] -> SourcePos -> Binding e -inheritFrom expr = Inherit (Just expr) +inheritFrom expr = Inherit (pure expr) -- | Shorthand for producing a binding of a name to an expression. bindTo :: Text -> NExpr -> Binding NExpr @@ -231,5 +231,5 @@ infixl 1 @@ infixr 1 ==> (@.) :: NExpr -> Text -> NExpr -obj @. name = Fix (NSelect obj (StaticKey name :| []) Nothing) +obj @. name = Fix (NSelect obj (StaticKey name :| mempty) Nothing) infixl 2 @. diff --git a/src/Nix/Expr/Strings.hs b/src/Nix/Expr/Strings.hs index 51e5cef5b..3476afae7 100644 --- a/src/Nix/Expr/Strings.hs +++ b/src/Nix/Expr/Strings.hs @@ -15,7 +15,7 @@ import Nix.Expr -- | Merge adjacent 'Plain' values with 'mappend'. mergePlain :: [Antiquoted Text r] -> [Antiquoted Text r] -mergePlain [] = [] +mergePlain [] = mempty mergePlain (Plain a : EscapedNewline : Plain b : xs) = mergePlain (Plain (a <> "\n" <> b) : xs) mergePlain (Plain a : Plain b : xs) = mergePlain (Plain (a <> b) : xs) @@ -45,10 +45,10 @@ splitLines :: [Antiquoted Text r] -> [[Antiquoted Text r]] splitLines = uncurry (flip (:)) . go where go (Plain t : xs) = (Plain l :) <$> foldr f (go xs) ls where (l : ls) = T.split (== '\n') t - f prefix (finished, current) = ((Plain prefix : current) : finished, []) + f prefix (finished, current) = ((Plain prefix : current) : finished, mempty) go (Antiquoted a : xs) = (Antiquoted a :) <$> go xs go (EscapedNewline : xs) = (EscapedNewline :) <$> go xs - go [] = ([], []) + go [] = (mempty, mempty) -- | Join a stream of strings containing antiquotes again. This is the inverse -- of 'splitLines'. @@ -57,7 +57,7 @@ unsplitLines = intercalate [Plain "\n"] -- | Form an indented string by stripping spaces equal to the minimal indent. stripIndent :: [Antiquoted Text r] -> NString r -stripIndent [] = Indented 0 [] +stripIndent [] = Indented 0 mempty stripIndent xs = Indented minIndent . removePlainEmpty @@ -65,10 +65,10 @@ stripIndent xs = . fmap snd . dropWhileEnd cleanup . (\ys -> zip - (map + (fmap (\case [] -> Nothing - x -> Just (last x) + x -> pure (last x) ) (inits ys) ) diff --git a/src/Nix/Expr/Types.hs b/src/Nix/Expr/Types.hs index ab4ecdfa1..c6e2dc305 100644 --- a/src/Nix/Expr/Types.hs +++ b/src/Nix/Expr/Types.hs @@ -123,7 +123,7 @@ data NExprF r -- alternative if the key doesn't exist. -- -- > NSelect s (x :| []) Nothing ~ s.x - -- > NSelect s (x :| []) (Just y) ~ s.x or y + -- > NSelect s (x :| []) (pure y) ~ s.x or y | NHasAttr !r !(NAttrPath r) -- ^ Ask if a set contains a given attribute path. -- @@ -174,7 +174,7 @@ instance IsString NExpr where instance Lift (Fix NExprF) where lift = dataToExpQ $ \b -> case Reflection.typeOf b `eqTypeRep` Reflection.typeRep @Text of - Just HRefl -> Just [| pack $(liftString $ unpack b) |] + Just HRefl -> pure [| pack $(liftString $ unpack b) |] Nothing -> Nothing #if MIN_VERSION_template_haskell(2,17,0) @@ -204,7 +204,7 @@ data Binding r -- the first member of the list in the second argument. -- -- > Inherit Nothing [StaticKey "x"] SourcePos{} ~ inherit x; - -- > Inherit (Just x) [] SourcePos{} ~ inherit (x); + -- > Inherit (pure x) mempty SourcePos{} ~ inherit (x); deriving (Generic, Generic1, Typeable, Data, Ord, Eq, Functor, Foldable, Traversable, Show, NFData, Hashable) @@ -227,7 +227,7 @@ data Params r -- variadic or not. -- -- > ParamSet [("x",Nothing)] False Nothing ~ { x } - -- > ParamSet [("x",Just y)] True (Just "s") ~ s@{ x ? y, ... } + -- > ParamSet [("x",pure y)] True (pure "s") ~ s@{ x ? y, ... } deriving (Ord, Eq, Generic, Generic1, Typeable, Data, Functor, Show, Foldable, Traversable, NFData, Hashable) @@ -310,7 +310,7 @@ instance Serialise r => Serialise (NString r) -- | For the the 'IsString' instance, we use a plain doublequoted string. instance IsString (NString r) where - fromString "" = DoubleQuoted [] + fromString "" = DoubleQuoted mempty fromString string = DoubleQuoted [Plain $ pack string] -- | A 'KeyName' is something that can appear on the left side of an @@ -478,7 +478,7 @@ instance Serialise NRecordType -- | Get the name out of the parameter (there might be none). paramName :: Params r -> Maybe VarName -paramName (Param n ) = Just n +paramName (Param n ) = pure n paramName (ParamSet _ _ n) = n $(deriveEq1 ''NExprF) @@ -575,7 +575,7 @@ ekey -> SourcePos -> Lens' (Fix g) (Maybe (Fix g)) ekey keys pos f e@(Fix x) | (NSet NNonRecursive xs, ann) <- fromNExpr x = case go xs of - ((v, [] ) : _) -> fromMaybe e <$> f (Just v) + ((v, [] ) : _) -> fromMaybe e <$> f (pure v) ((v, r : rest) : _) -> ekey (r :| rest) pos f v _ -> f Nothing <&> \case diff --git a/src/Nix/Expr/Types/Annotated.hs b/src/Nix/Expr/Types/Annotated.hs index dbebeac66..cfa83b985 100644 --- a/src/Nix/Expr/Types/Annotated.hs +++ b/src/Nix/Expr/Types/Annotated.hs @@ -147,7 +147,7 @@ nSelectLoc :: NExprLoc -> Ann SrcSpan (NAttrPath NExprLoc) -> Maybe NExprLoc -> NExprLoc nSelectLoc e1@(AnnE s1 _) (Ann s2 ats) d = case d of Nothing -> AnnE (s1 <> s2) (NSelect e1 ats Nothing) - Just e2@(AnnE s3 _) -> AnnE (s1 <> s2 <> s3) (NSelect e1 ats (Just e2)) + Just e2@(AnnE s3 _) -> AnnE (s1 <> s2 <> s3) (NSelect e1 ats (pure e2)) _ -> error "nSelectLoc: unexpected" nSelectLoc _ _ _ = error "nSelectLoc: unexpected" diff --git a/src/Nix/Fresh.hs b/src/Nix/Fresh.hs index f690b34ba..02c7833a3 100644 --- a/src/Nix/Fresh.hs +++ b/src/Nix/Fresh.hs @@ -90,9 +90,9 @@ instance MonadAtomicRef (ST s) where v <- readRef r let (a, b) = f v writeRef r a - return b + pure b atomicModifyRef' r f = do v <- readRef r let (a, b) = f v writeRef r $! a - return b + pure b diff --git a/src/Nix/Fresh/Basic.hs b/src/Nix/Fresh/Basic.hs index e60aa0f34..579751bc5 100644 --- a/src/Nix/Fresh/Basic.hs +++ b/src/Nix/Fresh/Basic.hs @@ -43,10 +43,10 @@ instance (MonadEffects t f m, MonadDataContext f m) importPath path = do i <- FreshIdT ask p <- lift $ importPath @t @f @m path - return $ liftNValue (runFreshIdT i) p + pure $ liftNValue (runFreshIdT i) p pathToDefaultNix = lift . pathToDefaultNix @t @f @m derivationStrict v = do i <- FreshIdT ask p <- lift $ derivationStrict @t @f @m $ unliftNValue (runFreshIdT i) v - return $ liftNValue (runFreshIdT i) p + pure $ liftNValue (runFreshIdT i) p traceEffect = lift . traceEffect @t @f @m diff --git a/src/Nix/Lint.hs b/src/Nix/Lint.hs index 3293db960..6dc53c803 100644 --- a/src/Nix/Lint.hs +++ b/src/Nix/Lint.hs @@ -168,8 +168,8 @@ merge context = go :: [NTypeF m (Symbolic m)] -> [NTypeF m (Symbolic m)] -> m [NTypeF m (Symbolic m)] - go [] _ = pure [] - go _ [] = pure [] + go [] _ = pure mempty + go _ [] = pure mempty go (x : xs) (y : ys) = case (x, y) of (TStr , TStr ) -> (TStr :) <$> go xs ys (TPath, TPath) -> (TPath :) <$> go xs ys @@ -189,7 +189,7 @@ merge context = go ) (pure <$> l) (pure <$> r) - if M.null m then go xs ys else (TSet (Just m) :) <$> go xs ys + if M.null m then go xs ys else (TSet (pure m) :) <$> go xs ys (TClosure{}, TClosure{}) -> throwError $ ErrorCall "Cannot unify functions" (TBuiltin _ _, TBuiltin _ _) -> @@ -202,12 +202,12 @@ merge context = go mergeFunctions pl nl fl pr fr xs ys = do m <- sequenceA $ M.intersectionWith (\i j -> i >>= \i' -> j >>= \j' -> case (i', j') of - (Nothing, Nothing) -> return $ Just Nothing - (_, Nothing) -> return Nothing - (Nothing, _) -> return Nothing + (Nothing, Nothing) -> pure $ pure Nothing + (_, Nothing) -> pure Nothing + (Nothing, _) -> pure Nothing (Just i'', Just j'') -> - Just . Just <$> unify context i'' j'') - (return <$> pl) (return <$> pr) + pure . pure <$> unify context i'' j'') + (pure <$> pl) (pure <$> pr) let Just m' = sequenceA $ M.filter isJust m if M.null m' then go xs ys @@ -217,7 +217,7 @@ merge context = go <$> go xs ys -} --- | unify raises an error if the result is would be 'NMany []'. +-- | unify raises an error if the result is would be 'NMany mempty'. unify :: forall e m . MonadLint e m @@ -290,7 +290,7 @@ instance MonadLint e m => MonadEval (Symbolic m) m where f <- mkSymbolic [TPath] l <- mkSymbolic [TConstant [TInt]] c <- mkSymbolic [TConstant [TInt]] - mkSymbolic [TSet (Just (M.fromList (go f l c)))] + mkSymbolic [TSet (pure (M.fromList (go f l c)))] where go f l c = [(Text.pack "file", f), (Text.pack "line", l), (Text.pack "col", c)] @@ -372,7 +372,7 @@ lintBinaryOp op lsym rarg = do NMult -> check lsym rsym [TConstant [TInt]] NDiv -> check lsym rsym [TConstant [TInt]] - NUpdate -> check lsym rsym [TSet Nothing] + NUpdate -> check lsym rsym [TSet mempty] NConcat -> check lsym rsym [TList y] where diff --git a/src/Nix/Options.hs b/src/Nix/Options.hs index f43dea7e9..d64d36c89 100644 --- a/src/Nix/Options.hs +++ b/src/Nix/Options.hs @@ -43,30 +43,30 @@ defaultOptions current = Options { verbose = ErrorsOnly , thunks = False , values = False , showScopes = False - , reduce = Nothing + , reduce = mempty , reduceSets = False , reduceLists = False , parse = False , parseOnly = False , finder = False - , findFile = Nothing + , findFile = mempty , strict = False , evaluate = False , json = False , xml = False - , attr = Nothing - , include = [] + , attr = mempty + , include = mempty , check = False - , readFrom = Nothing + , readFrom = mempty , cache = False , repl = False , ignoreErrors = False - , expression = Nothing - , arg = [] - , argstr = [] - , fromFile = Nothing + , expression = mempty + , arg = mempty + , argstr = mempty + , fromFile = mempty , currentTime = current - , filePaths = [] + , filePaths = mempty } data Verbosity diff --git a/src/Nix/Parser.hs b/src/Nix/Parser.hs index 5997346dc..4447b9911 100644 --- a/src/Nix/Parser.hs +++ b/src/Nix/Parser.hs @@ -179,7 +179,7 @@ nixSym :: Parser NExprLoc nixSym = annotateLocation1 $ mkSymF <$> identifier nixSynHole :: Parser NExprLoc -nixSynHole = annotateLocation1 $ mkSynHoleF <$> (char '^' >> identifier) +nixSynHole = annotateLocation1 $ mkSynHoleF <$> (char '^' *> identifier) nixInt :: Parser NExprLoc nixInt = annotateLocation1 (mkIntF <$> integer "integer") @@ -253,7 +253,7 @@ nixLet = annotateLocation1 letBinders = NLet <$> nixBinders <*> (reserved "in" *> nixToplevelForm) -- Let expressions `let {..., body = ...}' are just desugared -- into `(rec {..., body = ...}).body'. - letBody = (\x -> NSelect x (StaticKey "body" :| []) Nothing) <$> aset + letBody = (\x -> NSelect x (StaticKey "body" :| mempty) Nothing) <$> aset aset = annotateLocation1 $ NSet NRecursive <$> braces nixBinders nixIf :: Parser NExprLoc @@ -357,7 +357,7 @@ argExpr = msum [atLeft, onlyname, atRight] <* symbol ":" where -- there's a valid URI parse here. onlyname = msum - [ nixUri >> unexpected (Label ('v' NE.:| "alid uri")) + [ nixUri *> unexpected (Label ('v' NE.:| "alid uri")) , Param <$> identifier ] @@ -365,7 +365,7 @@ argExpr = msum [atLeft, onlyname, atRight] <* symbol ":" where atLeft = try $ do name <- identifier <* symbol "@" (variadic, params) <- params - pure $ ParamSet params variadic (Just name) + pure $ ParamSet params variadic (pure name) -- Parameters named by an identifier on the right, or none (`{x, y} @ args`) atRight = do @@ -381,7 +381,7 @@ argExpr = msum [atLeft, onlyname, atRight] <* symbol ":" where -- Collects the parameters within curly braces. Returns the parameters and -- a boolean indicating if the parameters are variadic. getParams :: Parser ([(Text, Maybe NExprLoc)], Bool) - getParams = go [] where + getParams = go mempty where -- Attempt to parse `...`. If this succeeds, stop and return True. -- Otherwise, attempt to parse an argument, optionally with a -- default. If this fails, then return what has been accumulated @@ -393,7 +393,7 @@ argExpr = msum [atLeft, onlyname, atRight] <* symbol ":" where -- Get an argument name and an optional default. pair <- liftM2 (,) identifier (optional $ question *> nixToplevelForm) -- Either return this, or attempt to get a comma and restart. - option (acc <> [pair], False) $ comma >> go (acc <> [pair]) + option (acc <> [pair], False) $ comma *> go (acc <> [pair]) nixBinders :: Parser [Binding NExprLoc] nixBinders = (inherit <+> namedVar) `endBy` semi where @@ -440,7 +440,7 @@ parseNixTextLoc = parseFromText (whiteSpace *> nixToplevelForm <* eof) skipLineComment' :: Tokens Text -> Parser () skipLineComment' prefix = string prefix - *> void (takeWhileP (Just "character") (\x -> x /= '\n' && x /= '\r')) + *> void (takeWhileP (pure "character") (\x -> x /= '\n' && x /= '\r')) whiteSpace :: Parser () whiteSpace = do @@ -492,7 +492,7 @@ identifier = lexeme $ try $ do ident <- cons <$> satisfy (\x -> isAlpha x || x == '_') - <*> takeWhileP Nothing identLetter + <*> takeWhileP mempty identLetter guard (not (ident `HashSet.member` reservedNames)) pure ident where @@ -608,7 +608,7 @@ nixOperators selector = -- Postfix $ do -- sel <- seldot *> selector -- mor <- optional (reserved "or" *> term) - -- return $ \x -> nSelectLoc x sel mor) ] + -- pure $ \x -> nSelectLoc x sel mor) ] {- 2 -} [ ( NBinaryDef " " NApp NAssocLeft @@ -659,7 +659,7 @@ getUnaryOperator = (m Map.!) where (nixOperators (error "unused")) buildEntry i = concatMap $ \case (NUnaryDef name op, _) -> [(op, OperatorInfo i NAssocNone name)] - _ -> [] + _ -> mempty getBinaryOperator :: NBinaryOp -> OperatorInfo getBinaryOperator = (m Map.!) where @@ -668,7 +668,7 @@ getBinaryOperator = (m Map.!) where (nixOperators (error "unused")) buildEntry i = concatMap $ \case (NBinaryDef name op assoc, _) -> [(op, OperatorInfo i assoc name)] - _ -> [] + _ -> mempty getSpecialOperator :: NSpecialOp -> OperatorInfo getSpecialOperator NSelectOp = OperatorInfo 1 NAssocLeft "." @@ -678,4 +678,4 @@ getSpecialOperator o = m Map.! o where (nixOperators (error "unused")) buildEntry i = concatMap $ \case (NSpecialDef name op assoc, _) -> [(op, OperatorInfo i assoc name)] - _ -> [] + _ -> mempty diff --git a/src/Nix/Pretty.hs b/src/Nix/Pretty.hs index 2b1c28499..bb94b96fe 100644 --- a/src/Nix/Pretty.hs +++ b/src/Nix/Pretty.hs @@ -122,7 +122,7 @@ prettyString (DoubleQuoted parts) = dquotes . hcat . fmap prettyPart $ parts prettyPart EscapedNewline = "''\\n" prettyPart (Antiquoted r) = "$" <> braces (withoutParens r) escape '"' = "\\\"" - escape x = maybe [x] (('\\' :) . (: [])) $ toEscapeCode x + escape x = maybe [x] (('\\' :) . (: mempty)) $ toEscapeCode x prettyString (Indented _ parts) = group $ nest 2 $ vcat [dsquote, content, dsquote] where @@ -310,7 +310,7 @@ valueToExpr = iterNValue (\_ _ -> thk) phi phi (NVStr' ns) = mkStr ns phi (NVList' l ) = Fix $ NList l phi (NVSet' s p ) = Fix $ NSet NNonRecursive - [ NamedVar (StaticKey k :| []) v (fromMaybe nullPos (M.lookup k p)) + [ NamedVar (StaticKey k :| mempty) v (fromMaybe nullPos (M.lookup k p)) | (k, v) <- toList s ] phi (NVClosure' _ _ ) = Fix . NSym . pack $ "" diff --git a/src/Nix/Reduce.hs b/src/Nix/Reduce.hs index ed289aece..fa9d9b1e4 100644 --- a/src/Nix/Reduce.hs +++ b/src/Nix/Reduce.hs @@ -105,15 +105,15 @@ staticImport pann path = do let pos = SourcePos "Reduce.hs" (mkPos 1) (mkPos 1) span = SrcSpan pos pos - cur = NamedVar (StaticKey "__cur_file" :| []) + cur = NamedVar (StaticKey "__cur_file" :| mempty) (Fix (NLiteralPath_ pann path)) pos x' = Fix (NLet_ span [cur] x) modify (\(a, b) -> (M.insert path x' a, b)) - local (const (Just path, emptyScopes @m @NExprLoc)) $ do + local (const (pure path, emptyScopes @m @NExprLoc)) $ do x'' <- foldFix reduce x' modify (\(a, b) -> (M.insert path x'' a, b)) - return x'' + pure x'' -- gatherNames :: NExprLoc -> HashSet VarName -- gatherNames = foldFix $ \case @@ -148,10 +148,10 @@ reduce (NSym_ ann var) = lookupVar var <&> \case -- | Reduce binary and integer negation. reduce (NUnary_ uann op arg) = arg >>= \x -> case (op, x) of (NNeg, Fix (NConstant_ cann (NInt n))) -> - return $ Fix $ NConstant_ cann (NInt (negate n)) + pure $ Fix $ NConstant_ cann (NInt (negate n)) (NNot, Fix (NConstant_ cann (NBool b))) -> - return $ Fix $ NConstant_ cann (NBool (not b)) - _ -> return $ Fix $ NUnary_ uann op x + pure $ Fix $ NConstant_ cann (NBool (not b)) + _ -> pure $ Fix $ NUnary_ uann op x -- | Reduce function applications. -- @@ -163,7 +163,7 @@ reduce (NBinary_ bann NApp fun arg) = fun >>= \case f@(Fix (NSym_ _ "import")) -> arg >>= \case -- Fix (NEnvPath_ pann origPath) -> staticImport pann origPath Fix (NLiteralPath_ pann origPath) -> staticImport pann origPath - v -> return $ Fix $ NBinary_ bann NApp f v + v -> pure $ Fix $ NBinary_ bann NApp f v Fix (NAbs_ _ (Param name) body) -> do x <- arg @@ -177,7 +177,7 @@ reduce (NBinary_ bann op larg rarg) = do rval <- rarg case (op, lval, rval) of (NPlus, Fix (NConstant_ ann (NInt x)), Fix (NConstant_ _ (NInt y))) -> - return $ Fix (NConstant_ ann (NInt (x + y))) + pure $ Fix (NConstant_ ann (NInt (x + y))) _ -> pure $ Fix $ NBinary_ bann op lval rval -- | Reduce a select on a Set by substituting the set to the selected value. @@ -196,12 +196,12 @@ reduce base@(NSelect_ _ _ attrs _) sId = Fix <$> sequence base -- The selection AttrPath is composed of StaticKeys. sAttrPath (StaticKey _ : xs) = sAttrPath xs - sAttrPath [] = True + sAttrPath [] = True sAttrPath _ = False -- Find appropriate bind in set's binds. - findBind [] _ = Nothing + findBind [] _ = Nothing findBind (x : xs) attrs@(a :| _) = case x of - n@(NamedVar (a' :| _) _ _) | a' == a -> Just n + n@(NamedVar (a' :| _) _ _) | a' == a -> pure n _ -> findBind xs attrs -- Follow the attrpath recursively in sets. inspectSet (NSet_ _ NNonRecursive binds) attrs = case findBind binds attrs of @@ -238,23 +238,23 @@ reduce (NWith_ ann scope body) = reduce (NLet_ ann binds body) = do s <- fmap (M.fromList . catMaybes) $ forM binds $ \case NamedVar (StaticKey name :| []) def _pos -> def >>= \case - d@(Fix NAbs_{} ) -> pure $ Just (name, d) - d@(Fix NConstant_{}) -> pure $ Just (name, d) - d@(Fix NStr_{} ) -> pure $ Just (name, d) + d@(Fix NAbs_{} ) -> pure $ pure (name, d) + d@(Fix NConstant_{}) -> pure $ pure (name, d) + d@(Fix NStr_{} ) -> pure $ pure (name, d) _ -> pure Nothing _ -> pure Nothing body' <- pushScope s body binds' <- traverse sequence binds -- let names = gatherNames body' -- binds' <- traverse sequence binds <&> \b -> flip filter b $ \case - -- NamedVar (StaticKey name _ :| []) _ -> + -- NamedVar (StaticKey name _ :| mempty) _ -> -- name `S.member` names -- _ -> True pure $ Fix $ NLet_ ann binds' body' -- where -- go m [] = pure m -- go m (x:xs) = case x of - -- NamedVar (StaticKey name _ :| []) def -> do + -- NamedVar (StaticKey name _ :| mempty) def -> do -- v <- pushScope m def -- go (M.insert name v m) xs -- _ -> go m xs @@ -307,28 +307,28 @@ pruneTree opts = foldFixM $ \(FlaggedF (b, Compose x)) -> do where prune :: NExprF (Maybe NExprLoc) -> Maybe (NExprF NExprLoc) prune = \case - NStr str -> Just $ NStr (pruneString str) + NStr str -> pure $ NStr (pruneString str) NHasAttr (Just aset) attr -> - Just $ NHasAttr aset (NE.map pruneKeyName attr) - NAbs params (Just body) -> Just $ NAbs (pruneParams params) body + pure $ NHasAttr aset (NE.map pruneKeyName attr) + NAbs params (Just body) -> pure $ NAbs (pruneParams params) body - NList l | reduceLists opts -> Just $ NList (catMaybes l) - | otherwise -> Just $ NList (fmap (fromMaybe nNull) l) + NList l | reduceLists opts -> pure $ NList (catMaybes l) + | otherwise -> pure $ NList (fmap (fromMaybe nNull) l) NSet recur binds - | reduceSets opts -> Just $ NSet recur (mapMaybe sequence binds) - | otherwise -> Just $ NSet recur (fmap (fmap (fromMaybe nNull)) binds) + | reduceSets opts -> pure $ NSet recur (mapMaybe sequence binds) + | otherwise -> pure $ NSet recur (fmap (fmap (fromMaybe nNull)) binds) NLet binds (Just body@(Fix (Compose (Ann _ x)))) -> - Just $ case mapMaybe pruneBinding binds of + pure $ case mapMaybe pruneBinding binds of [] -> x xs -> NLet xs body NSelect (Just aset) attr alt -> - Just $ NSelect aset (NE.map pruneKeyName attr) (join alt) + pure $ NSelect aset (NE.map pruneKeyName attr) (join alt) -- These are the only short-circuiting binary operators - NBinary NAnd (Just (Fix (Compose (Ann _ larg)))) _ -> Just larg - NBinary NOr (Just (Fix (Compose (Ann _ larg)))) _ -> Just larg + NBinary NAnd (Just (Fix (Compose (Ann _ larg)))) _ -> pure larg + NBinary NOr (Just (Fix (Compose (Ann _ larg)))) _ -> pure larg -- If the function was never called, it means its argument was in a -- thunk that was forced elsewhere. @@ -338,22 +338,22 @@ pruneTree opts = foldFixM $ \(FlaggedF (b, Compose x)) -> do -- invalid is that we're trying to emit what will reproduce whatever -- error the user encountered, which means providing all aspects of -- the evaluation path they ultimately followed. - NBinary op Nothing (Just rarg) -> Just $ NBinary op nNull rarg - NBinary op (Just larg) Nothing -> Just $ NBinary op larg nNull + NBinary op Nothing (Just rarg) -> pure $ NBinary op nNull rarg + NBinary op (Just larg) Nothing -> pure $ NBinary op larg nNull -- If the scope of a with was never referenced, it's not needed - NWith Nothing (Just (Fix (Compose (Ann _ body)))) -> Just body + NWith Nothing (Just (Fix (Compose (Ann _ body)))) -> pure body NAssert Nothing _ -> error "How can an assert be used, but its condition not?" - NAssert _ (Just (Fix (Compose (Ann _ body)))) -> Just body - NAssert (Just cond) _ -> Just $ NAssert cond nNull + NAssert _ (Just (Fix (Compose (Ann _ body)))) -> pure body + NAssert (Just cond) _ -> pure $ NAssert cond nNull NIf Nothing _ _ -> error "How can an if be used, but its condition not?" - NIf _ Nothing (Just (Fix (Compose (Ann _ f)))) -> Just f - NIf _ (Just (Fix (Compose (Ann _ t)))) Nothing -> Just t + NIf _ Nothing (Just (Fix (Compose (Ann _ f)))) -> pure f + NIf _ (Just (Fix (Compose (Ann _ t)))) Nothing -> pure t x -> sequence x @@ -364,18 +364,18 @@ pruneTree opts = foldFixM $ \(FlaggedF (b, Compose x)) -> do pruneAntiquotedText :: Antiquoted Text (Maybe NExprLoc) -> Maybe (Antiquoted Text NExprLoc) - pruneAntiquotedText (Plain v) = Just (Plain v) - pruneAntiquotedText EscapedNewline = Just EscapedNewline + pruneAntiquotedText (Plain v) = pure (Plain v) + pruneAntiquotedText EscapedNewline = pure EscapedNewline pruneAntiquotedText (Antiquoted Nothing ) = Nothing - pruneAntiquotedText (Antiquoted (Just k)) = Just (Antiquoted k) + pruneAntiquotedText (Antiquoted (Just k)) = pure (Antiquoted k) pruneAntiquoted :: Antiquoted (NString (Maybe NExprLoc)) (Maybe NExprLoc) -> Maybe (Antiquoted (NString NExprLoc) NExprLoc) - pruneAntiquoted (Plain v) = Just (Plain (pruneString v)) - pruneAntiquoted EscapedNewline = Just EscapedNewline + pruneAntiquoted (Plain v) = pure (Plain (pruneString v)) + pruneAntiquoted EscapedNewline = pure EscapedNewline pruneAntiquoted (Antiquoted Nothing ) = Nothing - pruneAntiquoted (Antiquoted (Just k)) = Just (Antiquoted k) + pruneAntiquoted (Antiquoted (Just k)) = pure (Antiquoted k) pruneKeyName :: NKeyName (Maybe NExprLoc) -> NKeyName NExprLoc pruneKeyName (StaticKey n) = StaticKey n @@ -386,7 +386,7 @@ pruneTree opts = foldFixM $ \(FlaggedF (b, Compose x)) -> do pruneParams (Param n) = Param n pruneParams (ParamSet xs b n) | reduceSets opts = ParamSet - (fmap (second (maybe (Just nNull) (Just . fromMaybe nNull))) xs) + (fmap (second (maybe (pure nNull) (pure . fromMaybe nNull))) xs) b n | otherwise = ParamSet (fmap (second (fmap (fromMaybe nNull))) xs) b n @@ -394,11 +394,11 @@ pruneTree opts = foldFixM $ \(FlaggedF (b, Compose x)) -> do pruneBinding :: Binding (Maybe NExprLoc) -> Maybe (Binding NExprLoc) pruneBinding (NamedVar _ Nothing _) = Nothing pruneBinding (NamedVar xs (Just x) pos) = - Just (NamedVar (NE.map pruneKeyName xs) x pos) + pure (NamedVar (NE.map pruneKeyName xs) x pos) pruneBinding (Inherit _ [] _) = Nothing pruneBinding (Inherit (join -> Nothing) _ _) = Nothing pruneBinding (Inherit (join -> m) xs pos) = - Just (Inherit m (fmap pruneKeyName xs) pos) + pure (Inherit m (fmap pruneKeyName xs) pos) reducingEvalExpr :: (Framed e m, Has e Options, Exception r, MonadCatch m, MonadIO m) @@ -411,7 +411,7 @@ reducingEvalExpr eval mpath expr = do eres <- catch (Right <$> foldFix (addEvalFlags eval) expr') (pure . Left) opts :: Options <- asks (view hasLens) expr'' <- pruneTree opts expr' - return (fromMaybe nNull expr'', eres) + pure (fromMaybe nNull expr'', eres) where addEvalFlags k (FlaggedF (b, x)) = liftIO (writeIORef b True) *> k x instance Monad m => Scoped NExprLoc (Reducer m) where diff --git a/src/Nix/Render.hs b/src/Nix/Render.hs index e059a5e7f..c4095c1b0 100644 --- a/src/Nix/Render.hs +++ b/src/Nix/Render.hs @@ -92,14 +92,14 @@ renderLocation (SrcSpan (SourcePos file begLine begCol) (SourcePos file' endLine if exist then do txt <- sourceContext file begLine begCol endLine endCol msg - return + pure $ vsep [ "In file " <> errorContext file begLine begCol endLine endCol <> ":" , txt ] - else return msg + else pure msg renderLocation (SrcSpan beg end) msg = fail $ "Don't know how to render range from " diff --git a/src/Nix/Render/Frame.hs b/src/Nix/Render/Frame.hs index 69b49198f..71e24ccdd 100644 --- a/src/Nix/Render/Frame.hs +++ b/src/Nix/Render/Frame.hs @@ -61,7 +61,7 @@ renderFrames (x : xs) = do go f = case framePos @v @m f of Just pos -> ["While evaluating at " <> pretty (sourcePosPretty pos) <> colon] - Nothing -> [] + Nothing -> mempty framePos :: forall v (m :: * -> *) @@ -70,7 +70,7 @@ framePos -> Maybe SourcePos framePos (NixFrame _ f) | Just (e :: EvalFrame m v) <- fromException f = case e of - EvaluatingExpr _ (Fix (Compose (Ann (SrcSpan beg _) _))) -> Just beg + EvaluatingExpr _ (Fix (Compose (Ann (SrcSpan beg _) _))) -> pure beg _ -> Nothing | otherwise = Nothing @@ -107,18 +107,18 @@ renderEvalFrame level f = do case f of EvaluatingExpr scope e@(Fix (Compose (Ann ann _))) -> do let scopeInfo | showScopes opts = [pretty $ show scope] - | otherwise = [] + | otherwise = mempty fmap (\x -> scopeInfo <> [x]) $ renderLocation ann =<< renderExpr level "While evaluating" "Expression" e ForcingExpr _scope e@(Fix (Compose (Ann ann _))) | thunks opts -> - fmap (: []) + fmap (: mempty) $ renderLocation ann =<< renderExpr level "While forcing thunk from" "Forcing thunk" e Calling name ann -> - fmap (: []) + fmap (: mempty) $ renderLocation ann $ "While calling builtins." <> pretty name @@ -131,7 +131,7 @@ renderEvalFrame level f = do , pure $ pretty $ show (_synHoleInfo_scope synfo) ] - ForcingExpr _ _ -> pure [] + ForcingExpr _ _ -> pure mempty renderExpr @@ -163,7 +163,7 @@ renderValueFrame => NixLevel -> ValueFrame t f m -> m [Doc ann] -renderValueFrame level = fmap (: []) . \case +renderValueFrame level = fmap (: mempty) . \case ForcingThunk _t -> pure "ForcingThunk" -- jww (2019-03-18): NYI ConcerningValue _v -> pure "ConcerningValue" Comparison _ _ -> pure "Comparing" @@ -206,7 +206,7 @@ renderExecFrame -> m [Doc ann] renderExecFrame level = \case Assertion ann v -> - fmap (: []) + fmap (: mempty) $ renderLocation ann =<< ( (\d -> fillSep ["Assertion failed:", d]) <$> renderValue level "" "" v @@ -217,7 +217,7 @@ renderThunkLoop => NixLevel -> ThunkLoop -> m [Doc ann] -renderThunkLoop _level = pure . (: []) . \case +renderThunkLoop _level = pure . (: mempty) . \case ThunkLoop n -> pretty $ "Infinite recursion in thunk " <> n renderNormalLoop @@ -225,7 +225,7 @@ renderNormalLoop => NixLevel -> NormalLoop t f m -> m [Doc ann] -renderNormalLoop level = fmap (: []) . \case +renderNormalLoop level = fmap (: mempty) . \case NormalLoop v -> do v' <- renderValue level "" "" v pure $ "Infinite recursion during normalization forcing " <> v' diff --git a/src/Nix/Scope.hs b/src/Nix/Scope.hs index 8270372aa..d3c848a44 100644 --- a/src/Nix/Scope.hs +++ b/src/Nix/Scope.hs @@ -28,7 +28,9 @@ newScope = Scope scopeLookup :: Text -> [Scope a] -> Maybe a scopeLookup key = foldr go Nothing - where go (Scope m) rest = M.lookup key m <|> rest + where + go :: Scope a -> Maybe a -> Maybe a + go (Scope m) rest = M.lookup key m <|> rest data Scopes m a = Scopes { lexicalScopes :: [Scope a] @@ -47,7 +49,7 @@ instance Monoid (Scopes m a) where mappend = (<>) emptyScopes :: forall m a . Scopes m a -emptyScopes = Scopes [] [] +emptyScopes = Scopes mempty mempty class Scoped a m | m -> a where currentScopes :: m (Scopes m a) @@ -64,10 +66,10 @@ clearScopesReader clearScopesReader = local (set hasLens (emptyScopes @m @a)) pushScope :: Scoped a m => AttrSet a -> m r -> m r -pushScope s = pushScopes (Scopes [Scope s] []) +pushScope s = pushScopes (Scopes [Scope s] mempty) pushWeakScope :: (Functor m, Scoped a m) => m (AttrSet a) -> m r -> m r -pushWeakScope s = pushScopes (Scopes [] [Scope <$> s]) +pushWeakScope s = pushScopes (Scopes mempty [Scope <$> s]) pushScopesReader :: (MonadReader e m, Has e (Scopes m a)) => Scopes m a -> m r -> m r @@ -78,14 +80,14 @@ lookupVarReader lookupVarReader k = do mres <- asks (scopeLookup k . lexicalScopes @m . view hasLens) case mres of - Just sym -> pure $ Just sym + Just sym -> pure $ pure sym Nothing -> do ws <- asks (dynamicScopes . view hasLens) foldr (\x rest -> do mres' <- M.lookup k . getScope <$> x case mres' of - Just sym -> pure $ Just sym + Just sym -> pure $ pure sym Nothing -> rest ) (pure Nothing) diff --git a/src/Nix/String.hs b/src/Nix/String.hs index c770fddeb..aff5c4a49 100644 --- a/src/Nix/String.hs +++ b/src/Nix/String.hs @@ -82,7 +82,7 @@ instance Semigroup NixLikeContextValue where } instance Monoid NixLikeContextValue where - mempty = NixLikeContextValue False False [] + mempty = NixLikeContextValue False False mempty -- ** StringContext accumulator @@ -146,8 +146,8 @@ fromNixLikeContext = -- | Extract the string contents from a NixString that has no context getStringNoContext :: NixString -> Maybe Text -getStringNoContext (NixString s c) | null c = Just s - | otherwise = Nothing +getStringNoContext (NixString s c) | null c = pure s + | otherwise = mempty -- | Extract the string contents from a NixString even if the NixString has an associated context stringIgnoreContext :: NixString -> Text @@ -155,7 +155,7 @@ stringIgnoreContext (NixString s _) = s -- | Get the contents of a 'NixString' and write its context into the resulting set. extractNixString :: Monad m => NixString -> WithStringContextT m Text -extractNixString (NixString s c) = WithStringContextT $ tell c >> pure s +extractNixString (NixString s c) = WithStringContextT $ tell c *> pure s -- ** Setters @@ -168,12 +168,12 @@ toStringContexts (path, nlcv) = case nlcv of : toStringContexts (path, nlcv { nlcvAllOutputs = False }) NixLikeContextValue _ _ ls | not (null ls) -> fmap (StringContext path . DerivationOutput) ls - _ -> [] + _ -> mempty toNixLikeContextValue :: StringContext -> (Text, NixLikeContextValue) toNixLikeContextValue sc = (,) (scPath sc) $ case scFlavor sc of - DirectPath -> NixLikeContextValue True False [] - AllOutputs -> NixLikeContextValue False True [] + DirectPath -> NixLikeContextValue True False mempty + AllOutputs -> NixLikeContextValue False True mempty DerivationOutput t -> NixLikeContextValue False False [t] toNixLikeContext :: S.HashSet StringContext -> NixLikeContext diff --git a/src/Nix/TH.hs b/src/Nix/TH.hs index 2f175821a..5661ecec2 100644 --- a/src/Nix/TH.hs +++ b/src/Nix/TH.hs @@ -29,7 +29,7 @@ quoteExprExp s = do Failure err -> fail $ show err Success e -> pure e dataToExpQ - (const Nothing `extQ` metaExp (freeVars expr) `extQ` (Just . liftText)) + (const Nothing `extQ` metaExp (freeVars expr) `extQ` (pure . liftText)) expr where liftText :: Text.Text -> Q Exp @@ -82,8 +82,8 @@ freeVars e = case unFix e of where staticKey :: NKeyName r -> Maybe VarName - staticKey (StaticKey varname) = Just varname - staticKey (DynamicKey _ ) = Nothing + staticKey (StaticKey varname) = pure varname + staticKey (DynamicKey _ ) = mempty bindDefs :: Binding r -> Set VarName bindDefs (Inherit Nothing _ _) = Set.empty @@ -120,12 +120,12 @@ instance ToExpr Float where metaExp :: Set VarName -> NExprLoc -> Maybe ExpQ metaExp fvs (Fix (NSym_ _ x)) | x `Set.member` fvs = - Just [| toExpr $(varE (mkName (Text.unpack x))) |] + pure [| toExpr $(varE (mkName (Text.unpack x))) |] metaExp _ _ = Nothing metaPat :: Set VarName -> NExprLoc -> Maybe PatQ metaPat fvs (Fix (NSym_ _ x)) | x `Set.member` fvs = - Just (varP (mkName (Text.unpack x))) + pure (varP (mkName (Text.unpack x))) metaPat _ _ = Nothing nix :: QuasiQuoter diff --git a/src/Nix/Thunk.hs b/src/Nix/Thunk.hs index 9469bab3e..08e0c8f57 100644 --- a/src/Nix/Thunk.hs +++ b/src/Nix/Thunk.hs @@ -45,7 +45,7 @@ class MonadThunkId m => MonadThunk t m a | t -> m, t -> a where -- | Return an identifier for the thunk unless it is a pure value (i.e., -- strictly an encapsulation of some 'a' without any additional - -- structure). For pure values represented as thunks, returns Nothing. + -- structure). For pure values represented as thunks, returns mempty. thunkId :: t -> ThunkId m queryM :: t -> m r -> (a -> m r) -> m r diff --git a/src/Nix/Type/Assumption.hs b/src/Nix/Type/Assumption.hs index 982db43f5..9d92efd42 100644 --- a/src/Nix/Type/Assumption.hs +++ b/src/Nix/Type/Assumption.hs @@ -21,7 +21,7 @@ newtype Assumption = Assumption { assumptions :: [(Name, Type)] } deriving (Eq, Show) empty :: Assumption -empty = Assumption [] +empty = Assumption mempty extend :: Assumption -> (Name, Type) -> Assumption extend (Assumption a) (x, s) = Assumption ((x, s) : a) diff --git a/src/Nix/Type/Infer.hs b/src/Nix/Type/Infer.hs index ac1f53576..88a729811 100644 --- a/src/Nix/Type/Infer.hs +++ b/src/Nix/Type/Infer.hs @@ -244,7 +244,7 @@ inferType env ex = do inferState <- get let eres = (`evalState` inferState) $ runSolver $ do subst <- solve (cs <> cs') - return (subst, subst `apply` t) + pure (subst, subst `apply` t) case eres of Left errs -> throwError $ TypeInferenceErrors errs Right xs -> pure xs @@ -269,7 +269,7 @@ freshTVar :: MonadState InferState m => m TVar freshTVar = do s <- get put s { count = count s + 1 } - return $ TV (letters !! count s) + pure $ TV (letters !! count s) fresh :: MonadState InferState m => m Type fresh = TVar <$> freshTVar @@ -278,7 +278,7 @@ instantiate :: MonadState InferState m => Scheme -> m Type instantiate (Forall as t) = do as' <- mapM (const fresh) as let s = Subst $ Map.fromList $ zip as as' - return $ apply s t + pure $ apply s t generalize :: Set.Set TVar -> Type -> Scheme generalize free t = Forall as t @@ -295,12 +295,12 @@ unops u1 = \case binops :: Type -> NBinaryOp -> [Constraint] binops u1 = \case - NApp -> [] -- this is handled separately + NApp -> mempty -- this is handled separately -- Equality tells you nothing about the types, because any two types are -- allowed. - NEq -> [] - NNEq -> [] + NEq -> mempty + NNEq -> mempty NGt -> inequality NGte -> inequality @@ -379,7 +379,7 @@ instance MonadAtomicRef m => MonadAtomicRef (InferT s m) where atomicModifyRef x f = liftInfer $ do res <- snd . f <$> readRef x _ <- modifyRef x (fst . f) - return res + pure res -- newtype JThunkT s m = JThunk (NThunkF (InferT s m) (Judgment s)) @@ -414,32 +414,32 @@ instance MonadInfer m -- If we have a thunk loop, we just don't know the type. force (JThunk t) f = catch (force t f) $ \(_ :: ThunkLoop) -> - f =<< Judgment As.empty [] <$> fresh + f =<< Judgment As.empty mempty <$> fresh -- If we have a thunk loop, we just don't know the type. forceEff (JThunk t) f = catch (forceEff t f) $ \(_ :: ThunkLoop) -> - f =<< Judgment As.empty [] <$> fresh + f =<< Judgment As.empty mempty <$> fresh -} instance MonadInfer m => MonadEval (Judgment s) (InferT s m) where freeVariable var = do tv <- fresh - return $ Judgment (As.singleton var tv) [] tv + pure $ Judgment (As.singleton var tv) mempty tv synHole var = do tv <- fresh - return $ Judgment (As.singleton var tv) [] tv + pure $ Judgment (As.singleton var tv) mempty tv -- If we fail to look up an attribute, we just don't know the type. - attrMissing _ _ = Judgment As.empty [] <$> fresh + attrMissing _ _ = Judgment As.empty mempty <$> fresh evaledSym _ = pure - evalCurPos = return $ Judgment As.empty [] $ TSet False $ M.fromList + evalCurPos = pure $ Judgment As.empty mempty $ TSet False $ M.fromList [("file", typePath), ("line", typeInt), ("col", typeInt)] - evalConstant c = return $ Judgment As.empty [] (go c) + evalConstant c = pure $ Judgment As.empty mempty (go c) where go = \case NURI _ -> typeString @@ -448,18 +448,18 @@ instance MonadInfer m => MonadEval (Judgment s) (InferT s m) where NBool _ -> typeBool NNull -> typeNull - evalString = const $ return $ Judgment As.empty [] typeString - evalLiteralPath = const $ return $ Judgment As.empty [] typePath - evalEnvPath = const $ return $ Judgment As.empty [] typePath + evalString = const $ pure $ Judgment As.empty mempty typeString + evalLiteralPath = const $ pure $ Judgment As.empty mempty typePath + evalEnvPath = const $ pure $ Judgment As.empty mempty typePath evalUnary op (Judgment as1 cs1 t1) = do tv <- fresh - return $ Judgment as1 (cs1 <> unops (t1 :~> tv) op) tv + pure $ Judgment as1 (cs1 <> unops (t1 :~> tv) op) tv evalBinary op (Judgment as1 cs1 t1) e2 = do Judgment as2 cs2 t2 <- e2 tv <- fresh - return $ Judgment (as1 `As.merge` as2) + pure $ Judgment (as1 `As.merge` as2) (cs1 <> cs2 <> binops (t1 :~> t2 :~> tv) op) tv @@ -468,20 +468,20 @@ instance MonadInfer m => MonadEval (Judgment s) (InferT s m) where evalIf (Judgment as1 cs1 t1) t f = do Judgment as2 cs2 t2 <- t Judgment as3 cs3 t3 <- f - return $ Judgment + pure $ Judgment (as1 `As.merge` as2 `As.merge` as3) (cs1 <> cs2 <> cs3 <> [EqConst t1 typeBool, EqConst t2 t3]) t2 evalAssert (Judgment as1 cs1 t1) body = do Judgment as2 cs2 t2 <- body - return + pure $ Judgment (as1 `As.merge` as2) (cs1 <> cs2 <> [EqConst t1 typeBool]) t2 evalApp (Judgment as1 cs1 t1) e2 = do Judgment as2 cs2 t2 <- e2 tv <- fresh - return $ Judgment (as1 `As.merge` as2) + pure $ Judgment (as1 `As.merge` as2) (cs1 <> cs2 <> [EqConst t1 (t2 :~> tv)]) tv @@ -490,8 +490,8 @@ instance MonadInfer m => MonadEval (Judgment s) (InferT s m) where let tv = TVar a ((), Judgment as cs t) <- extendMSet a - (k (pure (Judgment (As.singleton x tv) [] tv)) (\_ b -> ((), ) <$> b)) - return $ Judgment (as `As.remove` x) + (k (pure (Judgment (As.singleton x tv) mempty tv)) (\_ b -> ((), ) <$> b)) + pure $ Judgment (as `As.remove` x) (cs <> [ EqConst t' tv | t' <- As.lookup x as ]) (tv :~> t) @@ -503,7 +503,7 @@ instance MonadInfer m => MonadEval (Judgment s) (InferT s m) where let (env, tys) = (\f -> foldl' f (As.empty, M.empty) js) $ \(as1, t1) (k, t) -> (as1 `As.merge` As.singleton k t, M.insert k t t1) - arg = pure $ Judgment env [] (TSet True tys) + arg = pure $ Judgment env mempty (TSet True tys) call = k arg $ \args b -> (args, ) <$> b names = fmap fst js @@ -511,7 +511,7 @@ instance MonadInfer m => MonadEval (Judgment s) (InferT s m) where ty <- TSet variadic <$> traverse (inferredType <$>) args - return $ Judgment + pure $ Judgment (foldl' As.remove as names) (cs <> [ EqConst t' (tys M.! x) | x <- names, t' <- As.lookup x as ]) (ty :~> t) @@ -526,16 +526,16 @@ data Judgment s = Judgment deriving Show instance Monad m => FromValue NixString (InferT s m) (Judgment s) where - fromValueMay _ = return Nothing + fromValueMay _ = pure mempty fromValue _ = error "Unused" instance MonadInfer m => FromValue (AttrSet (Judgment s), AttrSet SourcePos) (InferT s m) (Judgment s) where fromValueMay (Judgment _ _ (TSet _ xs)) = do - let sing _ = Judgment As.empty [] - pure $ Just (M.mapWithKey sing xs, M.empty) - fromValueMay _ = pure Nothing + let sing _ = Judgment As.empty mempty + pure $ pure (M.mapWithKey sing xs, M.empty) + fromValueMay _ = pure mempty fromValue = fromValueMay >=> \case Just v -> pure v Nothing -> pure (M.empty, M.empty) @@ -559,7 +559,7 @@ instance MonadInfer m => ToValue [Judgment s] (InferT s m) (Judgment s) where where go x rest = demand x $ \x' -> pure $ As.merge (assumptions x') rest instance MonadInfer m => ToValue Bool (InferT s m) (Judgment s) where - toValue _ = pure $ Judgment As.empty [] typeBool + toValue _ = pure $ Judgment As.empty mempty typeBool infer :: MonadInfer m => NExpr -> InferT s m (Judgment s) infer = foldFix Eval.eval @@ -577,7 +577,7 @@ normalizeScheme (Forall _ body) = Forall (fmap snd ord) (normtype body) fv (TVar a ) = [a] fv (a :~> b ) = fv a <> fv b - fv (TCon _ ) = [] + fv (TCon _ ) = mempty fv (TSet _ a) = concatMap fv (M.elems a) fv (TList a ) = concatMap fv a fv (TMany ts) = concatMap fv ts @@ -603,12 +603,12 @@ instance MonadTrans Solver where lift = Solver . lift . lift instance Monad m => MonadError TypeError (Solver m) where - throwError err = Solver $ lift (modify (err :)) >> mzero + throwError err = Solver $ lift (modify (err :)) *> mzero catchError _ _ = error "This is never used" runSolver :: Monad m => Solver m a -> m (Either [TypeError] [a]) runSolver (Solver s) = do - res <- runStateT (observeAllT s) [] + res <- runStateT (observeAllT s) mempty pure $ case res of (x : xs, _ ) -> Right (x : xs) (_ , es) -> Left (nub es) @@ -623,11 +623,11 @@ Subst s1 `compose` Subst s2 = Subst $ Map.map (apply (Subst s1)) s2 `Map.union` s1 unifyMany :: Monad m => [Type] -> [Type] -> Solver m Subst -unifyMany [] [] = return emptySubst +unifyMany [] [] = pure emptySubst unifyMany (t1 : ts1) (t2 : ts2) = do su1 <- unifies t1 t2 su2 <- unifyMany (apply su1 ts1) (apply su1 ts2) - return (su2 `compose` su1) + pure (su2 `compose` su1) unifyMany t1 t2 = throwError $ UnificationMismatch t1 t2 allSameType :: [Type] -> Bool @@ -636,33 +636,33 @@ allSameType [_ ] = True allSameType (x : y : ys) = x == y && allSameType (y : ys) unifies :: Monad m => Type -> Type -> Solver m Subst -unifies t1 t2 | t1 == t2 = return emptySubst +unifies t1 t2 | t1 == t2 = pure emptySubst unifies (TVar v) t = v `bind` t unifies t (TVar v) = v `bind` t unifies (TList xs) (TList ys) | allSameType xs && allSameType ys = case (xs, ys) of (x : _, y : _) -> unifies x y - _ -> return emptySubst + _ -> pure emptySubst | length xs == length ys = unifyMany xs ys -- We assume that lists of different lengths containing various types cannot -- be unified. unifies t1@(TList _ ) t2@(TList _ ) = throwError $ UnificationFail t1 t2 -unifies ( TSet True _) ( TSet True _) = return emptySubst +unifies ( TSet True _) ( TSet True _) = pure emptySubst unifies (TSet False b) (TSet True s) - | M.keys b `intersect` M.keys s == M.keys s = return emptySubst + | M.keys b `intersect` M.keys s == M.keys s = pure emptySubst unifies (TSet True s) (TSet False b) - | M.keys b `intersect` M.keys s == M.keys b = return emptySubst + | M.keys b `intersect` M.keys s == M.keys b = pure emptySubst unifies (TSet False s) (TSet False b) | null (M.keys b \\ M.keys s) = - return emptySubst + pure emptySubst unifies (t1 :~> t2) (t3 :~> t4) = unifyMany [t1, t2] [t3, t4] unifies (TMany t1s) t2 = considering t1s >>- unifies ?? t2 unifies t1 (TMany t2s) = considering t2s >>- unifies t1 unifies t1 t2 = throwError $ UnificationFail t1 t2 bind :: Monad m => TVar -> Type -> Solver m Subst -bind a t | t == TVar a = return emptySubst +bind a t | t == TVar a = pure emptySubst | occursCheck a t = throwError $ InfiniteType a t - | otherwise = return (Subst $ Map.singleton a t) + | otherwise = pure (Subst $ Map.singleton a t) occursCheck :: FreeTypeVars a => TVar -> a -> Bool occursCheck a t = a `Set.member` ftv t @@ -681,11 +681,11 @@ considering :: [a] -> Solver m a considering xs = Solver $ LogicT $ \c n -> foldr c n xs solve :: MonadState InferState m => [Constraint] -> Solver m Subst -solve [] = return emptySubst +solve [] = pure emptySubst solve cs = solve' (nextSolvable cs) where solve' (EqConst t1 t2, cs) = unifies t1 t2 - >>- \su1 -> solve (apply su1 cs) >>- \su2 -> return (su2 `compose` su1) + >>- \su1 -> solve (apply su1 cs) >>- \su2 -> pure (su2 `compose` su1) solve' (ImpInstConst t1 ms t2, cs) = solve (ExpInstConst t1 (generalize ms t2) : cs) diff --git a/src/Nix/Type/Type.hs b/src/Nix/Type/Type.hs index 246fa6710..0b2ef1a0f 100644 --- a/src/Nix/Type/Type.hs +++ b/src/Nix/Type/Type.hs @@ -26,7 +26,7 @@ typeSet :: Type typeSet = TSet True M.empty typeList :: Type -typeList = TList [] +typeList = TList mempty infixr 1 :~> diff --git a/src/Nix/Utils.hs b/src/Nix/Utils.hs index 01b16586b..45d7f3c48 100644 --- a/src/Nix/Utils.hs +++ b/src/Nix/Utils.hs @@ -48,7 +48,7 @@ traceM :: Monad m => String -> m () traceM = const (pure ()) #endif -$(makeLensesBy (\n -> Just ("_" <> n)) ''Fix) +$(makeLensesBy (\n -> pure ("_" <> n)) ''Fix) type DList a = Endo [a] diff --git a/src/Nix/Value/Equal.hs b/src/Nix/Value/Equal.hs index 6a54c1feb..85abe98cf 100644 --- a/src/Nix/Value/Equal.hs +++ b/src/Nix/Value/Equal.hs @@ -156,11 +156,11 @@ valueEqM (Free (NValue (extract -> x))) (Free (NValue (extract -> y))) = valueFEqM (compareAttrSetsM f valueEqM) valueEqM x y where f (Pure t) = force t $ \case - NVStr s -> pure $ Just s - _ -> pure Nothing + NVStr s -> pure $ pure s + _ -> pure mempty f (Free v) = case v of - NVStr' s -> pure $ Just s - _ -> pure Nothing + NVStr' s -> pure $ pure s + _ -> pure mempty thunkEqM :: (MonadThunk t m (NValue t f m), Comonad f) => t -> t -> m Bool thunkEqM lt rt = force lt $ \lv -> force rt $ \rv -> diff --git a/src/Nix/XML.hs b/src/Nix/XML.hs index 7ab4ae660..ba7af1d82 100644 --- a/src/Nix/XML.hs +++ b/src/Nix/XML.hs @@ -25,7 +25,7 @@ toXML = runWithStringContext . fmap pp . iterNValue (\_ _ -> cyc) phi . (<> "\n") . Text.pack . ppElement - . (\e -> Element (unqual "expr") [] [Elem e] Nothing) + . (\e -> Element (unqual "expr") mempty [Elem e] Nothing) phi :: NValue' t f m (WithStringContext Element) -> WithStringContext Element phi = \case @@ -34,17 +34,17 @@ toXML = runWithStringContext . fmap pp . iterNValue (\_ _ -> cyc) phi NInt n -> pure $ mkElem "int" "value" (show n) NFloat f -> pure $ mkElem "float" "value" (show f) NBool b -> pure $ mkElem "bool" "value" (if b then "true" else "false") - NNull -> pure $ Element (unqual "null") [] [] Nothing + NNull -> pure $ Element (unqual "null") mempty mempty Nothing NVStr' str -> mkElem "string" "value" . Text.unpack <$> extractNixString str NVList' l -> sequence l - >>= \els -> pure $ Element (unqual "list") [] (Elem <$> els) Nothing + >>= \els -> pure $ Element (unqual "list") mempty (Elem <$> els) Nothing NVSet' s _ -> sequence s >>= \kvs -> pure $ Element (unqual "attrs") - [] - (map + mempty + (fmap (\(k, v) -> Elem (Element (unqual "attr") [Attr (unqual "name") (Text.unpack k)] @@ -57,13 +57,13 @@ toXML = runWithStringContext . fmap pp . iterNValue (\_ _ -> cyc) phi Nothing NVClosure' p _ -> - pure $ Element (unqual "function") [] (paramsXML p) Nothing + pure $ Element (unqual "function") mempty (paramsXML p) Nothing NVPath' fp -> pure $ mkElem "path" "value" fp NVBuiltin' name _ -> pure $ mkElem "function" "name" name _ -> error "Pattern synonyms mask coverage" mkElem :: String -> String -> String -> Element -mkElem n a v = Element (unqual n) [Attr (unqual a) v] [] Nothing +mkElem n a v = Element (unqual n) [Attr (unqual a) v] mempty Nothing paramsXML :: Params r -> [Content] paramsXML (Param name) = [Elem $ mkElem "varpat" "name" (Text.unpack name)] @@ -71,7 +71,7 @@ paramsXML (ParamSet s b mname) = [Elem $ Element (unqual "attrspat") (battr <> nattr) (paramSetXML s) Nothing] where battr = [ Attr (unqual "ellipsis") "1" | b ] - nattr = maybe [] ((: []) . Attr (unqual "name") . Text.unpack) mname + nattr = maybe mempty ((: mempty) . Attr (unqual "name") . Text.unpack) mname paramSetXML :: ParamSet r -> [Content] paramSetXML = fmap (\(k, _) -> Elem $ mkElem "attr" "name" (Text.unpack k)) diff --git a/tests/EvalTests.hs b/tests/EvalTests.hs index 4a4a32ba6..e9075b72d 100644 --- a/tests/EvalTests.hs +++ b/tests/EvalTests.hs @@ -455,8 +455,8 @@ constantEqual expected actual = do let opts = defaultOptions time -- putStrLn =<< lint (stripAnnotation a) (eq, expectedNF, actualNF) <- runWithBasicEffectsIO opts $ do - expectedNF <- normalForm =<< nixEvalExprLoc Nothing expected - actualNF <- normalForm =<< nixEvalExprLoc Nothing actual + expectedNF <- normalForm =<< nixEvalExprLoc mempty expected + actualNF <- normalForm =<< nixEvalExprLoc mempty actual eq <- valueEqM expectedNF actualNF pure (eq, expectedNF, actualNF) let message = @@ -485,7 +485,7 @@ assertNixEvalThrows a = do let opts = defaultOptions time errored <- catch (False <$ runWithBasicEffectsIO opts - (normalForm =<< nixEvalExprLoc Nothing a')) + (normalForm =<< nixEvalExprLoc mempty a')) (\(_ :: NixException) -> pure True) unless errored $ assertFailure "Did not catch nix exception" diff --git a/tests/Main.hs b/tests/Main.hs index b0fcb75cd..01575fded 100644 --- a/tests/Main.hs +++ b/tests/Main.hs @@ -42,7 +42,7 @@ ensureLangTestsPresent = do errorWithoutStackTrace $ unlines [ "Directory data/nix does not have any files." , "Did you forget to run" - ++ " \"git submodule update --init --recursive\"?" ] + <> " \"git submodule update --init --recursive\"?" ] ensureNixpkgsCanParse :: Assertion ensureNixpkgsCanParse = @@ -58,16 +58,16 @@ ensureNixpkgsCanParse = NVStr ns <- do time <- getCurrentTime runWithBasicEffectsIO (defaultOptions time) $ - Nix.nixEvalExprLoc Nothing expr + Nix.nixEvalExprLoc mempty expr let dir = stringIgnoreContext ns exists <- fileExist (unpack dir) unless exists $ errorWithoutStackTrace $ - "Directory " ++ show dir ++ " does not exist" + "Directory " <> show dir <> " does not exist" files <- globDir1 (compile "**/*.nix") (unpack dir) when (null files) $ errorWithoutStackTrace $ - "Directory " ++ show dir ++ " does not have any files" + "Directory " <> show dir <> " does not have any files" forM_ files $ \file -> do unless ("azure-cli/default.nix" `isSuffixOf` file || "os-specific/linux/udisks/2-default.nix" `isSuffixOf` file) $ do @@ -75,7 +75,7 @@ ensureNixpkgsCanParse = -- parser is fully executed. _ <- consider file (parseNixFileLoc file) $ Exc.evaluate . force pure () - v -> error $ "Unexpected parse from default.nix: " ++ show v + v -> error $ "Unexpected parse from default.nix: " <> show v where getExpr k m = let Just (Just r) = lookup k m in r getString k m = @@ -83,7 +83,7 @@ ensureNixpkgsCanParse = consider path action k = action >>= \case Failure err -> errorWithoutStackTrace $ - "Parsing " ++ path ++ " failed: " ++ show err + "Parsing " <> path <> " failed: " <> show err Success expr -> k expr main :: IO () @@ -95,18 +95,18 @@ main = do prettyTestsEnv <- lookupEnv "PRETTY_TESTS" pwd <- getCurrentDirectory - setEnv "NIX_REMOTE" (pwd ++ "/real-store") - setEnv "NIX_DATA_DIR" (pwd ++ "/data") + setEnv "NIX_REMOTE" (pwd <> "/real-store") + setEnv "NIX_DATA_DIR" (pwd <> "/data") defaultMain $ testGroup "hnix" $ [ ParserTests.tests , EvalTests.tests , PrettyTests.tests - , ReduceExprTests.tests] ++ + , ReduceExprTests.tests] <> [ PrettyParseTests.tests - (fromIntegral (read (fromMaybe "0" prettyTestsEnv) :: Int)) ] ++ - [ evalComparisonTests ] ++ + (fromIntegral (read (fromMaybe "0" prettyTestsEnv) :: Int)) ] <> + [ evalComparisonTests ] <> [ testCase "Nix language tests present" ensureLangTestsPresent - , nixLanguageTests ] ++ + , nixLanguageTests ] <> [ testCase "Nixpkgs parses without errors" ensureNixpkgsCanParse | isJust nixpkgsTestsEnv ] diff --git a/tests/NixLanguageTests.hs b/tests/NixLanguageTests.hs index c479eeb99..952fcab74 100644 --- a/tests/NixLanguageTests.hs +++ b/tests/NixLanguageTests.hs @@ -60,7 +60,7 @@ From (git://nix)/tests/lang.sh we see that -} groupBy :: Ord k => (v -> k) -> [v] -> Map k [v] -groupBy key = Map.fromListWith (++) . fmap (key &&& pure) +groupBy key = Map.fromListWith (<>) . fmap (key &&& pure) -- | New tests, which have never yet passed. Once any of these is passing, -- please remove it from this list. Do not add tests to this list if they have @@ -101,13 +101,13 @@ genTests = do ["parse", "fail"] -> assertParseFail opts $ the files ["eval" , "okay"] -> assertEval opts files ["eval" , "fail"] -> assertEvalFail $ the files - _ -> error $ "Unexpected: " ++ show kind + _ -> error $ "Unexpected: " <> show kind assertParse :: Options -> FilePath -> Assertion assertParse _opts file = parseNixFileLoc file >>= \case Success _expr -> pure () -- pure $! runST $ void $ lint opts expr Failure err -> - assertFailure $ "Failed to parse " ++ file ++ ":\n" ++ show err + assertFailure $ "Failed to parse " <> file <> ":\n" <> show err assertParseFail :: Options -> FilePath -> Assertion assertParseFail opts file = do @@ -118,25 +118,25 @@ assertParseFail opts file = do _ <- pure $! runST $ void $ lint opts expr assertFailure $ "Unexpected success parsing `" - ++ file - ++ ":\nParsed value: " - ++ show expr + <> file + <> ":\nParsed value: " + <> show expr Failure _ -> pure () ) $ \(_ :: SomeException) -> pure () assertLangOk :: Options -> FilePath -> Assertion assertLangOk opts file = do - actual <- printNix <$> hnixEvalFile opts (file ++ ".nix") - expected <- Text.readFile $ file ++ ".exp" - assertEqual "" expected $ Text.pack (actual ++ "\n") + actual <- printNix <$> hnixEvalFile opts (file <> ".nix") + expected <- Text.readFile $ file <> ".exp" + assertEqual "" expected $ Text.pack (actual <> "\n") assertLangOkXml :: Options -> FilePath -> Assertion assertLangOkXml opts file = do actual <- stringIgnoreContext . toXML <$> hnixEvalFile opts - (file ++ ".nix") - expected <- Text.readFile $ file ++ ".exp.xml" + (file <> ".nix") + expected <- Text.readFile $ file <> ".exp.xml" assertEqual "" expected actual assertEval :: Options -> [FilePath] -> Assertion @@ -144,14 +144,14 @@ assertEval _opts files = do time <- liftIO getCurrentTime let opts = defaultOptions time case delete ".nix" $ sort $ fmap takeExtensions files of - [] -> () <$ hnixEvalFile opts (name ++ ".nix") + [] -> () <$ hnixEvalFile opts (name <> ".nix") [".exp" ] -> assertLangOk opts name [".exp.xml" ] -> assertLangOkXml opts name [".exp.disabled"] -> pure () [".exp-disabled"] -> pure () [".exp", ".flags"] -> do liftIO $ setEnv "NIX_PATH" "lang/dir4:lang/dir5" - flags <- Text.readFile (name ++ ".flags") + flags <- Text.readFile (name <> ".flags") let flags' | Text.last flags == '\n' = Text.init flags | otherwise = flags case @@ -163,20 +163,20 @@ assertEval _opts files = do Opts.Failure err -> errorWithoutStackTrace $ "Error parsing flags from " - ++ name - ++ ".flags: " - ++ show err + <> name + <> ".flags: " + <> show err Opts.Success opts' -> assertLangOk opts' name Opts.CompletionInvoked _ -> error "unused" - _ -> assertFailure $ "Unknown test type " ++ show files + _ -> assertFailure $ "Unknown test type " <> show files where name = - "data/nix/tests/lang/" ++ the (fmap (takeFileName . dropExtensions) files) + "data/nix/tests/lang/" <> the (fmap (takeFileName . dropExtensions) files) - fixup ("--arg" : x : y : rest) = "--arg" : (x ++ "=" ++ y) : fixup rest - fixup ("--argstr" : x : y : rest) = "--argstr" : (x ++ "=" ++ y) : fixup rest + fixup ("--arg" : x : y : rest) = "--arg" : (x <> "=" <> y) : fixup rest + fixup ("--argstr" : x : y : rest) = "--argstr" : (x <> "=" <> y) : fixup rest fixup (x : rest) = x : fixup rest - fixup [] = [] + fixup [] = mempty assertEvalFail :: FilePath -> Assertion assertEvalFail file = catch ?? (\(_ :: SomeException) -> pure ()) $ do @@ -185,6 +185,6 @@ assertEvalFail file = catch ?? (\(_ :: SomeException) -> pure ()) $ do evalResult `seq` assertFailure $ file - ++ " should not evaluate.\nThe evaluation result was `" - ++ evalResult - ++ "`." + <> " should not evaluate.\nThe evaluation result was `" + <> evalResult + <> "`." diff --git a/tests/ParserTests.hs b/tests/ParserTests.hs index 1ac883c8a..03e1d73d6 100644 --- a/tests/ParserTests.hs +++ b/tests/ParserTests.hs @@ -83,12 +83,12 @@ case_set_inherit = do [ NamedVar (mkSelector "e") (mkInt 3) nullPos , Inherit Nothing (StaticKey <$> ["a", "b"]) nullPos ] - assertParseText "{ inherit; }" $ Fix $ NSet NNonRecursive [ Inherit Nothing [] nullPos ] + assertParseText "{ inherit; }" $ Fix $ NSet NNonRecursive [ Inherit Nothing mempty nullPos ] case_set_scoped_inherit = assertParseText "{ inherit (a) b c; e = 4; inherit(a)b c; }" $ Fix $ NSet NNonRecursive - [ Inherit (Just (mkSym "a")) (StaticKey <$> ["b", "c"]) nullPos + [ Inherit (pure (mkSym "a")) (StaticKey <$> ["b", "c"]) nullPos , NamedVar (mkSelector "e") (mkInt 4) nullPos - , Inherit (Just (mkSym "a")) (StaticKey <$> ["b", "c"]) nullPos + , Inherit (pure (mkSym "a")) (StaticKey <$> ["b", "c"]) nullPos ] case_set_rec = assertParseText "rec { a = 3; b = a; }" $ Fix $ NSet NRecursive @@ -98,13 +98,13 @@ case_set_rec = assertParseText "rec { a = 3; b = a; }" $ Fix $ NSet NRecursive case_set_complex_keynames = do assertParseText "{ \"\" = null; }" $ Fix $ NSet NNonRecursive - [ NamedVar (DynamicKey (Plain (DoubleQuoted [])) :| []) mkNull nullPos ] + [ NamedVar (DynamicKey (Plain (DoubleQuoted mempty)) :| mempty) mkNull nullPos ] assertParseText "{ a.b = 3; a.c = 4; }" $ Fix $ NSet NNonRecursive [ NamedVar (StaticKey "a" :| [StaticKey "b"]) (mkInt 3) nullPos , NamedVar (StaticKey "a" :| [StaticKey "c"]) (mkInt 4) nullPos ] assertParseText "{ ${let a = \"b\"; in a} = 4; }" $ Fix $ NSet NNonRecursive - [ NamedVar (DynamicKey (Antiquoted letExpr) :| []) (mkInt 4) nullPos ] + [ NamedVar (DynamicKey (Antiquoted letExpr) :| mempty) (mkInt 4) nullPos ] assertParseText "{ \"a${let a = \"b\"; in a}c\".e = 4; }" $ Fix $ NSet NNonRecursive [ NamedVar (DynamicKey (Plain str) :| [StaticKey "e"]) (mkInt 4) nullPos ] where @@ -112,7 +112,7 @@ case_set_complex_keynames = do str = DoubleQuoted [Plain "a", Antiquoted letExpr, Plain "c"] case_set_inherit_direct = assertParseText "{ inherit ({a = 3;}); }" $ Fix $ NSet NNonRecursive - [ Inherit (Just $ Fix $ NSet NNonRecursive [NamedVar (mkSelector "a") (mkInt 3) nullPos]) [] nullPos + [ Inherit (pure $ Fix $ NSet NNonRecursive [NamedVar (mkSelector "a") (mkInt 3) nullPos]) mempty nullPos ] case_inherit_selector = do @@ -130,8 +130,8 @@ case_mixed_list = do [ Fix (NSelect (Fix (NSet NNonRecursive [NamedVar (mkSelector "a") (mkInt 3) nullPos])) (mkSelector "a") Nothing) , Fix (NIf (mkBool True) mkNull (mkBool False)) - , mkNull, mkBool False, mkInt 4, Fix (NList []) - , Fix (NSelect (mkSym "c") (mkSelector "d") (Just mkNull)) + , mkNull, mkBool False, mkInt 4, Fix (NList mempty) + , Fix (NSelect (mkSym "c") (mkSelector "d") (pure mkNull)) ] assertParseFail "[if true then null else null]" assertParseFail "[a ? b]" @@ -144,31 +144,31 @@ case_lambda_or_uri = do assertParseText "a :b" $ Fix $ NAbs (Param "a") (mkSym "b") assertParseText "a c:def" $ Fix $ NBinary NApp (mkSym "a") (mkStr "c:def") assertParseText "c:def: c" $ Fix $ NBinary NApp (mkStr "c:def:") (mkSym "c") - assertParseText "a:{}" $ Fix $ NAbs (Param "a") $ Fix $ NSet NNonRecursive [] + assertParseText "a:{}" $ Fix $ NAbs (Param "a") $ Fix $ NSet NNonRecursive mempty assertParseText "a:[a]" $ Fix $ NAbs (Param "a") $ Fix $ NList [mkSym "a"] assertParseFail "def:" case_lambda_pattern = do assertParseText "{b, c ? 1}: b" $ - Fix $ NAbs (fixed args Nothing) (mkSym "b") + Fix $ NAbs (fixed args mempty) (mkSym "b") assertParseText "{ b ? x: x }: b" $ - Fix $ NAbs (fixed args2 Nothing) (mkSym "b") + Fix $ NAbs (fixed args2 mempty) (mkSym "b") assertParseText "a@{b,c ? 1}: b" $ - Fix $ NAbs (fixed args (Just "a")) (mkSym "b") + Fix $ NAbs (fixed args (pure "a")) (mkSym "b") assertParseText "{b,c?1}@a: c" $ - Fix $ NAbs (fixed args (Just "a")) (mkSym "c") + Fix $ NAbs (fixed args (pure "a")) (mkSym "c") assertParseText "{b,c?1,...}@a: c" $ - Fix $ NAbs (variadic vargs (Just "a")) (mkSym "c") + Fix $ NAbs (variadic vargs (pure "a")) (mkSym "c") assertParseText "{...}: 1" $ - Fix $ NAbs (variadic mempty Nothing) (mkInt 1) + Fix $ NAbs (variadic mempty mempty) (mkInt 1) assertParseFail "a@b: a" assertParseFail "{a}@{b}: a" where fixed args = ParamSet args False variadic args = ParamSet args True - args = [("b", Nothing), ("c", Just $ mkInt 1)] - vargs = [("b", Nothing), ("c", Just $ mkInt 1)] - args2 = [("b", Just lam)] + args = [("b", Nothing), ("c", pure $ mkInt 1)] + vargs = [("b", Nothing), ("c", pure $ mkInt 1)] + args2 = [("b", pure lam)] lam = Fix $ NAbs (Param "x") (mkSym "x") case_lambda_app_int = assertParseText "(a: a) 3" $ Fix (NBinary NApp lam int) where @@ -196,7 +196,7 @@ case_nested_let = do case_let_scoped_inherit = do assertParseText "let a = null; inherit (b) c; in c" $ Fix $ NLet [ NamedVar (mkSelector "a") mkNull nullPos - , Inherit (Just $ mkSym "b") [StaticKey "c"] nullPos ] + , Inherit (pure $ mkSym "b") [StaticKey "c"] nullPos ] (mkSym "c") assertParseFail "let inherit (b) c in c" @@ -255,24 +255,24 @@ case_select = do Nothing assertParseText "a.e . d or null" $ Fix $ NSelect (mkSym "a") (StaticKey "e" :| [StaticKey "d"]) - (Just mkNull) - assertParseText "{}.\"\"or null" $ Fix $ NSelect (Fix (NSet NNonRecursive [])) - (DynamicKey (Plain (DoubleQuoted [])) :| []) (Just mkNull) + (pure mkNull) + assertParseText "{}.\"\"or null" $ Fix $ NSelect (Fix (NSet NNonRecursive mempty)) + (DynamicKey (Plain (DoubleQuoted mempty)) :| mempty) (pure mkNull) assertParseText "{ a = [1]; }.a or [2] ++ [3]" $ Fix $ NBinary NConcat (Fix (NSelect - (Fix (NSet NNonRecursive [NamedVar (StaticKey "a" :| []) + (Fix (NSet NNonRecursive [NamedVar (StaticKey "a" :| mempty) (Fix (NList [Fix (NConstant (NInt 1))])) nullPos])) - (StaticKey "a" :| []) - (Just (Fix (NList [Fix (NConstant (NInt 2))]))))) + (StaticKey "a" :| mempty) + (pure (Fix (NList [Fix (NConstant (NInt 2))]))))) (Fix (NList [Fix (NConstant (NInt 3))])) case_select_path = do assertParseText "f ./." $ Fix $ NBinary NApp (mkSym "f") (mkPath False "./.") assertParseText "f.b ../a" $ Fix $ NBinary NApp select (mkPath False "../a") - assertParseText "{}./def" $ Fix $ NBinary NApp (Fix (NSet NNonRecursive [])) (mkPath False "./def") + assertParseText "{}./def" $ Fix $ NBinary NApp (Fix (NSet NNonRecursive mempty)) (mkPath False "./def") assertParseText "{}.\"\"./def" $ Fix $ NBinary NApp - (Fix $ NSelect (Fix (NSet NNonRecursive [])) (DynamicKey (Plain (DoubleQuoted [])) :| []) Nothing) + (Fix $ NSelect (Fix (NSet NNonRecursive mempty)) (DynamicKey (Plain (DoubleQuoted mempty)) :| mempty) Nothing) (mkPath False "./def") where select = Fix $ NSelect (mkSym "f") (mkSelector "b") Nothing @@ -282,7 +282,7 @@ case_select_keyword = do case_fun_app = do assertParseText "f a b" $ Fix $ NBinary NApp (Fix $ NBinary NApp (mkSym "f") (mkSym "a")) (mkSym "b") assertParseText "f a.x or null" $ Fix $ NBinary NApp (mkSym "f") $ Fix $ - NSelect (mkSym "a") (mkSelector "x") (Just mkNull) + NSelect (mkSym "a") (mkSelector "x") (pure mkNull) assertParseFail "f if true then null else null" case_indented_string = do @@ -367,27 +367,27 @@ tests = $testGroupGenerator assertParseText :: Text -> NExpr -> Assertion assertParseText str expected = case parseNixText str of Success actual -> - assertEqual ("When parsing " ++ unpack str) + assertEqual ("When parsing " <> unpack str) (stripPositionInfo expected) (stripPositionInfo actual) Failure err -> - assertFailure $ "Unexpected error parsing `" ++ unpack str ++ "':\n" ++ show err + assertFailure $ "Unexpected error parsing `" <> unpack str <> "':\n" <> show err assertParseFile :: FilePath -> NExpr -> Assertion assertParseFile file expected = do - res <- parseNixFile $ "data/" ++ file + res <- parseNixFile $ "data/" <> file case res of - Success actual -> assertEqual ("Parsing data file " ++ file) + Success actual -> assertEqual ("Parsing data file " <> file) (stripPositionInfo expected) (stripPositionInfo actual) Failure err -> assertFailure $ "Unexpected error parsing data file `" - ++ file ++ "':\n" ++ show err + <> file <> "':\n" <> show err assertParseFail :: Text -> Assertion assertParseFail str = case parseNixText str of Failure _ -> pure () Success r -> assertFailure $ "Unexpected success parsing `" - ++ unpack str ++ ":\nParsed value: " ++ show r + <> unpack str <> ":\nParsed value: " <> show r -- assertRoundTrip :: Text -> Assertion -- assertRoundTrip src = assertParsePrint src src diff --git a/tests/PrettyParseTests.hs b/tests/PrettyParseTests.hs index 3426bfe04..5707802b4 100644 --- a/tests/PrettyParseTests.hs +++ b/tests/PrettyParseTests.hs @@ -78,7 +78,7 @@ genParams = Gen.choice , ParamSet <$> Gen.list (Range.linear 0 10) ((,) <$> asciiText <*> Gen.maybe genExpr) <*> Gen.bool - <*> Gen.choice [pure Nothing, Just <$> asciiText] + <*> Gen.choice [pure mempty, pure <$> asciiText] ] genAtom :: Gen NAtom @@ -118,7 +118,7 @@ genExpr = Gen.sized $ \(Size n) -> Fix <$> if n < 2 genList = NList <$> fairList genExpr genSet = NSet NNonRecursive <$> fairList genBinding genRecSet = NSet NRecursive <$> fairList genBinding - genLiteralPath = NLiteralPath . ("./" ++) <$> asciiString + genLiteralPath = NLiteralPath . ("./" <>) <$> asciiString genEnvPath = NEnvPath <$> asciiString genUnary = NUnary <$> Gen.enumBounded <*> genExpr genBinary = NBinary <$> Gen.enumBounded <*> genExpr <*> genExpr @@ -177,7 +177,7 @@ normalize = foldFix $ \case normAntiquotedText (Plain "''\n") = EscapedNewline normAntiquotedText r = r - normParams (ParamSet binds var (Just "")) = ParamSet binds var Nothing + normParams (ParamSet binds var (Just "")) = ParamSet binds var mempty normParams r = r -- | Test that parse . pretty == id up to attribute position information. @@ -220,7 +220,7 @@ prop_prettyparse p = do normalise = unlines . fmap (reverse . dropWhile isSpace . reverse) . lines ldiff :: String -> String -> [Diff [String]] - ldiff s1 s2 = getDiff (fmap (: []) (lines s1)) (fmap (: []) (lines s2)) + ldiff s1 s2 = getDiff (fmap (: mempty) (lines s1)) (fmap (: mempty) (lines s2)) tests :: TestLimit -> TestTree tests n = testProperty "Pretty/Parse Property" $ withTests n $ property $ do diff --git a/tests/PrettyTests.hs b/tests/PrettyTests.hs index 9e7540639..f69db5673 100644 --- a/tests/PrettyTests.hs +++ b/tests/PrettyTests.hs @@ -21,7 +21,7 @@ case_string_antiquotation = do case_function_params :: Assertion case_function_params = - assertPretty (mkFunction (mkParamset [] True) (mkInt 3)) "{ ... }:\n 3" + assertPretty (mkFunction (mkParamset mempty True) (mkInt 3)) "{ ... }:\n 3" case_paths :: Assertion case_paths = do @@ -35,4 +35,4 @@ tests = $testGroupGenerator --------------------------------------------------------------------------------- assertPretty :: NExpr -> String -> Assertion assertPretty e s = - assertEqual ("When pretty-printing " ++ show e) s . show $ prettyNix e + assertEqual ("When pretty-printing " <> show e) s . show $ prettyNix e diff --git a/tests/ReduceExprTests.hs b/tests/ReduceExprTests.hs index 29fb1cf6a..c3490252f 100644 --- a/tests/ReduceExprTests.hs +++ b/tests/ReduceExprTests.hs @@ -32,13 +32,13 @@ assertSucc (Failure d) = assertFailure $ show d cmpReduceResult :: Result NExprLoc -> NExpr -> Assertion cmpReduceResult r e = do r <- assertSucc r - r <- stripAnnotation <$> reduceExpr Nothing r + r <- stripAnnotation <$> reduceExpr mempty r r @?= e shouldntReduce :: Result NExprLoc -> Assertion shouldntReduce r = do r <- assertSucc r - rReduced <- reduceExpr Nothing r + rReduced <- reduceExpr mempty r r @?= rReduced selectBasic :: Result NExprLoc diff --git a/tests/TestCommon.hs b/tests/TestCommon.hs index f0042f18b..17d2db24a 100644 --- a/tests/TestCommon.hs +++ b/tests/TestCommon.hs @@ -27,11 +27,11 @@ hnixEvalFile opts file = do parseResult <- parseNixFileLoc file case parseResult of Failure err -> - error $ "Parsing failed for file `" ++ file ++ "`.\n" ++ show err + error $ "Parsing failed for file `" <> file <> "`.\n" <> show err Success expr -> do setEnv "TEST_VAR" "foo" runWithBasicEffects opts - $ catch (evaluateExpression (Just file) nixEvalExprLoc normalForm expr) + $ catch (evaluateExpression (pure file) nixEvalExprLoc normalForm expr) $ \case NixException frames -> errorWithoutStackTrace @@ -45,11 +45,11 @@ hnixEvalText opts src = case parseNixText src of Failure err -> error $ "Parsing failed for expression `" - ++ unpack src - ++ "`.\n" - ++ show err + <> unpack src + <> "`.\n" + <> show err Success expr -> - runWithBasicEffects opts $ normalForm =<< nixEvalExpr Nothing expr + runWithBasicEffects opts $ normalForm =<< nixEvalExpr mempty expr nixEvalString :: String -> IO String nixEvalString expr = do @@ -66,14 +66,14 @@ nixEvalFile fp = readProcess "nix-instantiate" ["--eval", "--strict", fp] "" assertEvalFileMatchesNix :: FilePath -> Assertion assertEvalFileMatchesNix fp = do time <- liftIO getCurrentTime - hnixVal <- (++ "\n") . printNix <$> hnixEvalFile (defaultOptions time) fp + hnixVal <- (<> "\n") . printNix <$> hnixEvalFile (defaultOptions time) fp nixVal <- nixEvalFile fp assertEqual fp nixVal hnixVal assertEvalMatchesNix :: Text -> Assertion assertEvalMatchesNix expr = do time <- liftIO getCurrentTime - hnixVal <- (++ "\n") . printNix <$> hnixEvalText (defaultOptions time) expr + hnixVal <- (<> "\n") . printNix <$> hnixEvalText (defaultOptions time) expr nixVal <- nixEvalString expr' assertEqual expr' nixVal hnixVal where expr' = unpack expr