diff --git a/src/Assembly/HeapAllocates.hs b/src/Assembly/HeapAllocates.hs index cbff8cd..8e0cd55 100644 --- a/src/Assembly/HeapAllocates.hs +++ b/src/Assembly/HeapAllocates.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE BlockArguments #-} {-# LANGUAGE ScopedTypeVariables #-} module Assembly.HeapAllocates where @@ -17,7 +18,7 @@ type HeapAllocates = MaybeT M () run :: HeapAllocates -> M Bool run ha = do result <- runMaybeT ha - pure $ case result of + pure case result of Nothing -> True Just () -> False diff --git a/src/AssemblyToLLVM.hs b/src/AssemblyToLLVM.hs index 48a5f57..5d50999 100644 --- a/src/AssemblyToLLVM.hs +++ b/src/AssemblyToLLVM.hs @@ -150,7 +150,7 @@ freshName (Assembly.NameSuggestion nameSuggestion) = do s { usedNames = HashMap.insert bsName (i + 1) usedNames } - pure $ Name $ if i == 0 then bsName else bsName <> "$" <> ShortByteString.toShort (toUtf8 (show i :: Text)) + pure $ Name if i == 0 then bsName else bsName <> "$" <> ShortByteString.toShort (toUtf8 (show i :: Text)) activateLocal :: Assembly.Type -> Assembly.Local -> Assembler Name activateLocal type_ local@(Assembly.Local _ nameSuggestion) = do @@ -203,8 +203,8 @@ assembleModule definitions = do assembleDefinition :: Name.Lifted -> Assembly.Definition -> ([(Name, Builder)], HashMap Name Builder) assembleDefinition name@(Name.Lifted _ liftedNameNumber) definition = - second (.usedGlobals) - $ flip + second (.usedGlobals) $ + flip runState AssemblerState { locals = mempty @@ -214,77 +214,77 @@ assembleDefinition name@(Name.Lifted _ liftedNameNumber) definition = , basicBlocks = mempty , basicBlockName = panic "AssemblyToLLVM: not in a basic block" } - $ case definition of - Assembly.KnownConstantDefinition type_ (Literal.Integer value) isConstant -> do - let type' = llvmType type_ - pure - [ - ( name' - , globalName name' - <> " = unnamed_addr " - <> linkage - <> (if isConstant then "constant " else "global ") - <> type' - <> " " - <> Builder.integerDec value - ) - ] - Assembly.ConstantDefinition type_ functionReturnType parameters basicBlock -> do - let type' = llvmType type_ - initName = assembleName $ ClosureConvertedToAssembly.initDefinitionName name - parameters' <- mapM (uncurry activateLocal) parameters - assembleBasicBlockReturningResult functionReturnType basicBlock - basicBlocks <- gets (.basicBlocks) - pure - [ - ( name' - , globalName name' <> " = unnamed_addr " <> linkage <> "global " <> type' <> " undef" - ) - , - ( initName - , "define private fastcc " - <> llvmReturnType functionReturnType - <> " " - <> globalName initName - <> parens [typedOperand TypedOperand {type_ = pointer, operand = Local p} | p <- parameters'] - <> " align " - <> Builder.intDec alignment - <> " {" - <> basicBlocks - <> "\n}" - ) - ] - Assembly.FunctionDefinition returnType parameters basicBlock -> do - parameters' <- mapM (uncurry activateLocal) parameters - assembleBasicBlockReturningResult returnType basicBlock - basicBlocks <- gets (.basicBlocks) - pure - [ - ( name' - , "define " - <> linkage - <> "fastcc " - <> llvmReturnType returnType - <> " " - <> globalName (assembleName name) - <> parens - [ separate - " " - ( concat - [ [llvmType type_] - , parameterAttributes type_ - , [localName parameter] - ] - ) - | ((type_, _), parameter) <- zip parameters parameters' - ] - <> " align " - <> Builder.intDec alignment - <> " {" - <> basicBlocks - <> "\n}" - ) - ] + case definition of + Assembly.KnownConstantDefinition type_ (Literal.Integer value) isConstant -> do + let type' = llvmType type_ + pure + [ + ( name' + , globalName name' + <> " = unnamed_addr " + <> linkage + <> (if isConstant then "constant " else "global ") + <> type' + <> " " + <> Builder.integerDec value + ) + ] + Assembly.ConstantDefinition type_ functionReturnType parameters basicBlock -> do + let type' = llvmType type_ + initName = assembleName $ ClosureConvertedToAssembly.initDefinitionName name + parameters' <- mapM (uncurry activateLocal) parameters + assembleBasicBlockReturningResult functionReturnType basicBlock + basicBlocks <- gets (.basicBlocks) + pure + [ + ( name' + , globalName name' <> " = unnamed_addr " <> linkage <> "global " <> type' <> " undef" + ) + , + ( initName + , "define private fastcc " + <> llvmReturnType functionReturnType + <> " " + <> globalName initName + <> parens [typedOperand TypedOperand {type_ = pointer, operand = Local p} | p <- parameters'] + <> " align " + <> Builder.intDec alignment + <> " {" + <> basicBlocks + <> "\n}" + ) + ] + Assembly.FunctionDefinition returnType parameters basicBlock -> do + parameters' <- mapM (uncurry activateLocal) parameters + assembleBasicBlockReturningResult returnType basicBlock + basicBlocks <- gets (.basicBlocks) + pure + [ + ( name' + , "define " + <> linkage + <> "fastcc " + <> llvmReturnType returnType + <> " " + <> globalName (assembleName name) + <> parens + [ separate + " " + ( concat + [ [llvmType type_] + , parameterAttributes type_ + , [localName parameter] + ] + ) + | ((type_, _), parameter) <- zip parameters parameters' + ] + <> " align " + <> Builder.intDec alignment + <> " {" + <> basicBlocks + <> "\n}" + ) + ] where name' = assembleName name linkage = diff --git a/src/ClosureConversion.hs b/src/ClosureConversion.hs index 8048d3f..ed8a598 100644 --- a/src/ClosureConversion.hs +++ b/src/ClosureConversion.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE BlockArguments #-} {-# LANGUAGE FlexibleContexts #-} module ClosureConversion where @@ -101,20 +102,19 @@ convertGlobal global args = do applyArgs args $ pure $ ClosureConverted.Global global functionCase tele = - pure $ - case (Telescope.length tele, length args) of - (arity, numArgs) - | arity == numArgs -> - ClosureConverted.Apply global args - | arity < numArgs -> do - let (preArgs, postArgs) = - splitAt arity args + pure case (Telescope.length tele, length args) of + (arity, numArgs) + | arity == numArgs -> + ClosureConverted.Apply global args + | arity < numArgs -> do + let (preArgs, postArgs) = + splitAt arity args - ClosureConverted.ApplyClosure - (ClosureConverted.Apply global preArgs) - postArgs - | otherwise -> - ClosureConverted.Closure global args + ClosureConverted.ApplyClosure + (ClosureConverted.Apply global preArgs) + postArgs + | otherwise -> + ClosureConverted.Closure global args case definition of LambdaLifted.TypeDeclaration type_ -> diff --git a/src/ClosureConverted/Evaluation.hs b/src/ClosureConverted/Evaluation.hs index 6865094..823d2fb 100644 --- a/src/ClosureConverted/Evaluation.hs +++ b/src/ClosureConverted/Evaluation.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE BlockArguments #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} @@ -31,15 +32,14 @@ evaluate env term = let var = Environment.lookupIndexVar index env - pure $ - case Environment.lookupVarValue var env of - Nothing -> - Domain.var var - Just value - | Index.Succ index > Environment.glueableBefore env -> - Domain.Glued (Domain.Var var) mempty value - | otherwise -> - value + pure case Environment.lookupVarValue var env of + Nothing -> + Domain.var var + Just value + | Index.Succ index > Environment.glueableBefore env -> + Domain.Glued (Domain.Var var) mempty value + | otherwise -> + value Syntax.Global name -> do maybeDefinition <- fetchVisibleDefinition name case maybeDefinition of @@ -143,7 +143,7 @@ apply env fun args = appliedValue <- apply env value args pure $ Domain.Glued hd (spine <> (Domain.App <$> fromList args)) appliedValue Domain.Lazy lazyValue -> do - lazyValue' <- lazy $ do + lazyValue' <- lazy do value' <- force lazyValue apply env value' args pure $ Domain.Lazy lazyValue' @@ -202,7 +202,7 @@ case_ scrutinee branches@(Domain.Branches env branches' defaultBranch) = casedValue <- case_ value branches pure $ Domain.Glued hd (spine Tsil.:> Domain.Case branches) casedValue (Domain.Lazy lazyValue, _) -> do - lazyValue' <- lazy $ do + lazyValue' <- lazy do value <- force lazyValue case_ value branches pure $ Domain.Lazy lazyValue' @@ -217,7 +217,7 @@ evaluateClosure (Domain.Closure env body) argument = do fetchVisibleDefinition :: Name.Lifted -> M (Maybe Syntax.Definition) fetchVisibleDefinition name = do result <- try $ fetch $ Query.ClosureConverted name - pure $ case result of + pure case result of Right def -> Just def Left (Cyclic (_ :: Some Query)) -> Nothing diff --git a/src/ClosureConverted/Representation.hs b/src/ClosureConverted/Representation.hs index ef560d9..8689d3d 100644 --- a/src/ClosureConverted/Representation.hs +++ b/src/ClosureConverted/Representation.hs @@ -1,5 +1,4 @@ {-# LANGUAGE BlockArguments #-} -{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} @@ -161,7 +160,7 @@ unboxedDataRepresentation dataTypeName env (Syntax.ConstructorDefinitions constr constructorFieldRepresentation env type' mempty | (_, type_) <- OrderedHashMap.toList constructors ] - pure $ case maybeTags of + pure case maybeTags of Nothing -> fieldRepresentation Just _ -> constructorTagRepresentation <> fieldRepresentation where @@ -210,7 +209,7 @@ compileData env dataTypeName (Syntax.ConstructorDefinitions constructors) = do (\a b -> Syntax.Apply (Name.Lifted Builtin.MaxRepresentationName 0) [a, b]) (Syntax.Global $ Name.Lifted Builtin.EmptyRepresentationName 0) compiledConstructorFields - pure $ case maybeTags of + pure case maybeTags of Nothing -> maxFieldSize Just _ -> Syntax.Apply @@ -301,7 +300,7 @@ compileBranches branches = pure $ LiteralBranches literalBranches Syntax.ConstructorBranches typeName constructorBranches -> do (boxity, maybeTags) <- fetch $ Query.ConstructorRepresentations typeName - pure $ case (maybeTags, OrderedHashMap.toList constructorBranches) of + pure case (maybeTags, OrderedHashMap.toList constructorBranches) of (Nothing, [(_, constructorBranch)]) -> UntaggedConstructorBranch boxity constructorBranch (Nothing, _) -> panic "ClosureConverted.Representation.compileBranches: Untagged constructor branch length mismatch" (Just tags, constructorBranchesList) -> @@ -312,7 +311,7 @@ compileBranches branches = constructorRepresentations :: Name.Qualified -> Task Query (Boxity, Maybe (HashMap Name.Constructor Int)) constructorRepresentations name = do (definition, _) <- fetch $ Query.ElaboratedDefinition name - pure $ case definition of + pure case definition of Core.Syntax.DataDefinition boxity tele -> ( boxity , Telescope.under tele \(Core.Syntax.ConstructorDefinitions constructors) -> diff --git a/src/ClosureConvertedToAssembly.hs b/src/ClosureConvertedToAssembly.hs index 8e3ad6d..5b1b477 100644 --- a/src/ClosureConvertedToAssembly.hs +++ b/src/ClosureConvertedToAssembly.hs @@ -106,7 +106,7 @@ emptyEnvironment = extend :: Environment v -> Syntax.Type v -> Operand -> Builder (Environment (Succ v)) extend env type_ location = Builder $ - lift $ do + lift do type' <- Evaluation.evaluate (Context.toEnvironment env.context) type_ (context', var) <- Context.extend env.context type' pure @@ -176,7 +176,7 @@ getFreeShadowStackSlot = do shadowStackInit :: Assembly.Operand -> Builder (Bool, [Assembly.Instruction]) shadowStackInit shadowStackParameterOperand = - subBuilder $ do + subBuilder do slotCount <- gets (.shadowStackSlotCount) case slotCount of 0 -> @@ -203,10 +203,10 @@ indexOperand index env = do globalConstantOperand :: Name.Lifted -> Builder Operand globalConstantOperand name = do signature <- fetch $ Query.ClosureConvertedSignature name - pure $ case signature of + pure case signature of Representation.ConstantSignature representation -> Indirect $ - Assembly.GlobalConstant name $ case representation of + Assembly.GlobalConstant name case representation of Representation.Empty -> Assembly.WordPointer Representation.Direct Representation.Doesn'tContainHeapPointers -> Assembly.Word Representation.Direct Representation.MightContainHeapPointers -> Assembly.WordPointer @@ -263,7 +263,7 @@ extractHeapPointerConstructorTag nameSuggestion location = do typeOf :: Environment v -> Syntax.Term v -> Builder (Operand, Representation) typeOf env term = do (type_, typeRepresentation) <- Builder $ - lift $ do + lift do value <- Evaluation.evaluate (Context.toEnvironment env.context) term typeValue <- TypeOf.typeOf env.context value typeRepresentation <- ClosureConverted.Representation.typeRepresentation (Context.toEnvironment env.context) typeValue @@ -286,7 +286,7 @@ switch returnType scrutinee branches defaultBranch = do initialNextShadowStackSlot <- gets (.nextShadowStackSlot) initialHeapPointer <- gets (.heapPointer) initialHeapLimit <- gets (.heapLimit) - let wrapBranch branch = subBuilder $ do + let wrapBranch branch = subBuilder do modify \s -> s { nextShadowStackSlot = initialNextShadowStackSlot @@ -535,7 +535,7 @@ initDefinitionName (Name.Lifted (Name.Qualified moduleName (Name.Name name)) m) generateModuleInits :: [Name.Module] -> M Assembly.Definition generateModuleInits moduleNames = - runBuilder $ do + runBuilder do Assembly.LocalOperand heapPointerParameter <- gets (.heapPointer) Assembly.LocalOperand heapLimitParameter <- gets (.heapLimit) globalPointer <- freshLocal "globals" @@ -556,7 +556,7 @@ generateModuleInit -> [(Name.Lifted, Assembly.Definition)] -> M [(Name.Lifted, Assembly.Definition)] generateModuleInit moduleName definitions = - runBuilder $ do + runBuilder do Assembly.LocalOperand heapPointerParameter <- gets (.heapPointer) Assembly.LocalOperand heapLimitParameter <- gets (.heapLimit) globalBasePointer <- freshLocal "globals_base" @@ -609,7 +609,7 @@ generateModuleInit moduleName definitions = initImport globalBasePointer globalPointer import_ = callInitFunction "globals" - (moduleInitName $ import_.module_) + (moduleInitName import_.module_) [(Assembly.WordPointer, globalBasePointer), (Assembly.WordPointer, globalPointer)] initDefinition globalBasePointer globalPointer (name, definition) = @@ -638,7 +638,8 @@ withFunctionDefinitionParameters m = do Assembly.Return type_ -> Assembly.Return $ Assembly.Struct [type_, Assembly.WordPointer, Assembly.WordPointer] ) ((Assembly.WordPointer, heapPointerParameter) : (Assembly.WordPointer, heapLimitParameter) : parameters) - ( Assembly.BasicBlock instructions $ + ( Assembly.BasicBlock + instructions case returnOperand of Assembly.Void -> Assembly.Return $ Assembly.StructOperand [heapPointer, heapLimit] Assembly.Return operand -> Assembly.Return $ Assembly.StructOperand [operand, heapPointer, heapLimit] @@ -648,7 +649,7 @@ generateDefinition :: Name.Lifted -> Syntax.Definition -> M (Maybe Assembly.Defi generateDefinition name@(Name.Lifted qualifiedName _) definition = do signature <- fetch $ Query.ClosureConvertedSignature name let env = emptyEnvironment - runBuilder $ do + runBuilder do case (definition, signature) of (Syntax.TypeDeclaration _, _) -> pure Nothing @@ -783,19 +784,19 @@ generateFunction env returnRepresentation tele parameterRepresentations params = (Telescope.Empty term, []) -> case returnRepresentation of Representation.Empty -> - makeFunctionDefinition Assembly.Void (toList params) $ do + makeFunctionDefinition Assembly.Void (toList params) do (_, deallocateTerm) <- generateTypedTerm env term (Direct emptyTypeOperand) returnRepresentation sequence_ deallocateTerm pure Assembly.Void Representation.Direct _ -> - makeFunctionDefinition (Assembly.Return Assembly.Word) (toList params) $ do + makeFunctionDefinition (Assembly.Return Assembly.Word) (toList params) do (result, deallocateTerm) <- generateTypedTerm env term (Direct directTypeOperand) returnRepresentation directResult <- forceDirect result sequence_ deallocateTerm pure $ Assembly.Return directResult Representation.Indirect _ -> do returnLocation <- freshLocal "return_location" - makeFunctionDefinition Assembly.Void ((Assembly.WordPointer, returnLocation) : toList params) $ do + makeFunctionDefinition Assembly.Void ((Assembly.WordPointer, returnLocation) : toList params) do (type_, _representation) <- typeOf env term storeTerm env term (Assembly.LocalOperand returnLocation) type_ pure Assembly.Void @@ -845,7 +846,8 @@ makeFunctionDefinition returnType parameters m = do : (Assembly.WordPointer, heapLimitParameter) : parameters ) - ( Assembly.BasicBlock (shadowStackInitInstructions <> toList instructions) $ + ( Assembly.BasicBlock + (shadowStackInitInstructions <> toList instructions) case returnOperand of Assembly.Void -> Assembly.Return $ Assembly.StructOperand [heapPointer, heapLimit] Assembly.Return operand -> Assembly.Return $ Assembly.StructOperand [operand, heapPointer, heapLimit] @@ -877,7 +879,7 @@ generateTypedTerm env term type_ representation = do storeTerm env term termLocation type_ pure ( Indirect termLocation - , Just $ do + , Just do unregisterShadowStackSlot restoreStack stack ) @@ -965,7 +967,7 @@ storeTerm env term returnLocation returnType = location <- constructLocation (argType, _argRepresentation) <- typeOf env arg storeTerm env arg location argType - pure $ do + pure do argTypeSize <- sizeOfType argType addPointer "constructor_argument_offset" location argTypeSize foldM_ go (pure returnLocation) tagArgs @@ -1157,7 +1159,7 @@ storeBoxedBranch env constructorBasePointerBuilder constructorFieldOffsetBuilder stack <- saveStack stackConstructorField <- stackAllocate (Assembly.NameSuggestion $ name <> "_stack") typeSize typeRepresentation <- Builder $ - lift $ do + lift do typeValue <- Evaluation.evaluate (Context.toEnvironment env.context) type_ ClosureConverted.Representation.typeRepresentation (Context.toEnvironment env.context) typeValue unregisterShadowStackSlot <- case Representation.containsHeapPointers typeRepresentation of diff --git a/src/Command/Check.hs b/src/Command/Check.hs index d9434e1..aeec01c 100644 --- a/src/Command/Check.hs +++ b/src/Command/Check.hs @@ -25,7 +25,10 @@ check argumentFiles printElaborated = do startTime <- getCurrentTime (sourceDirectories, filePaths) <- Project.filesFromArguments argumentFiles ((), errs) <- - Driver.runTask sourceDirectories filePaths Error.Hydrated.pretty $ + Driver.runTask + sourceDirectories + filePaths + Error.Hydrated.pretty if printElaborated then withAsync (void Driver.checkAll) \checkedAll -> do inputFiles <- fetch Query.InputFiles @@ -40,7 +43,7 @@ check argumentFiles printElaborated = do type_ <- fetch $ Query.ElaboratedType name liftIO $ putDoc $ Pretty.prettyDefinition emptyPrettyEnv name (Syntax.TypeDeclaration type_) <> line (definition, _) <- fetch $ Query.ElaboratedDefinition name - liftIO $ do + liftIO do case definition of Syntax.TypeDeclaration {} -> pure () _ -> putDoc $ Pretty.prettyDefinition emptyPrettyEnv name definition <> line diff --git a/src/Command/Run.hs b/src/Command/Run.hs index 722a911..c6ec2c8 100644 --- a/src/Command/Run.hs +++ b/src/Command/Run.hs @@ -8,4 +8,4 @@ import System.Process run :: Command.Compile.Options -> IO () run = - Command.Compile.withCompiledExecutable \exe -> callProcess exe [] + Command.Compile.withCompiledExecutable (`callProcess` []) diff --git a/src/Command/Watch.hs b/src/Command/Watch.hs index ff070be..6afaa78 100644 --- a/src/Command/Watch.hs +++ b/src/Command/Watch.hs @@ -32,9 +32,9 @@ watch argumentFiles = do } void $ tryPutMVar signalChangeVar () - (`finally` stopListening) $ do + (`finally` stopListening) do driverState <- Driver.initialState - forever $ do + forever do projectFiles <- waitForChanges signalChangeVar fileStateVar driverState checkAndPrintErrors driverState projectFiles diff --git a/src/Compiler.hs b/src/Compiler.hs index c2571a8..76f71e1 100644 --- a/src/Compiler.hs +++ b/src/Compiler.hs @@ -47,7 +47,7 @@ compile assemblyDir saveAssembly outputExecutableFile maybeOptimisationLevel = d -- TODO configurable clang path let optimisationArgs = maybe [] (\o -> ["-O" <> o]) maybeOptimisationLevel - liftIO $ + liftIO if saveAssembly then do let linkedProgramName = diff --git a/src/Core/Binding.hs b/src/Core/Binding.hs index 2b65fba..87e27ef 100644 --- a/src/Core/Binding.hs +++ b/src/Core/Binding.hs @@ -1,6 +1,5 @@ {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE TupleSections #-} module Core.Binding where diff --git a/src/Core/Domain/Pattern.hs b/src/Core/Domain/Pattern.hs index eacdfc8..b5608b1 100644 --- a/src/Core/Domain/Pattern.hs +++ b/src/Core/Domain/Pattern.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module Core.Domain.Pattern where diff --git a/src/Core/Evaluation.hs b/src/Core/Evaluation.hs index e7c4b31..e36ee98 100644 --- a/src/Core/Evaluation.hs +++ b/src/Core/Evaluation.hs @@ -56,15 +56,14 @@ evaluate env term = let var = Environment.lookupIndexVar index env - pure $ - case Environment.lookupVarValue var env of - Nothing -> - Domain.var var - Just value - | Index.Succ index > Environment.glueableBefore env -> - Domain.Glued (Domain.Var var) mempty value - | otherwise -> - value + pure case Environment.lookupVarValue var env of + Nothing -> + Domain.var var + Just value + | Index.Succ index > Environment.glueableBefore env -> + Domain.Glued (Domain.Var var) mempty value + | otherwise -> + value Syntax.Global name -> do result <- try $ fetch $ Query.ElaboratedDefinition name case result of @@ -212,7 +211,7 @@ apply fun plicity arg = appliedValue <- apply value plicity arg pure $ Domain.Glued hd (spine Domain.:> Domain.App plicity arg) appliedValue Domain.Lazy lazyValue -> do - lazyValue' <- lazy $ do + lazyValue' <- lazy do value' <- force lazyValue apply value' plicity arg pure $ Domain.Lazy lazyValue' @@ -234,7 +233,7 @@ case_ scrutinee branches@(Domain.Branches env branches' defaultBranch) = casedValue <- case_ value branches pure $ Domain.Glued hd (spine Domain.:> Domain.Case branches) casedValue (Domain.Lazy lazyValue, _) -> do - lazyValue' <- lazy $ do + lazyValue' <- lazy do value' <- force lazyValue case_ value' branches pure $ Domain.Lazy lazyValue' diff --git a/src/Core/Pretty.hs b/src/Core/Pretty.hs index 0603b07..f674595 100644 --- a/src/Core/Pretty.hs +++ b/src/Core/Pretty.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE BlockArguments #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} @@ -121,14 +122,15 @@ prettyTerm prec env term = prettyParen (prec > funPrec) $ prettyPiTerm env Explicit term " ->" Syntax.Pi binding type_ plicity scope -> - prettyParen (prec > funPrec) $ + prettyParen + (prec > funPrec) let (env', name) = extendBinding env binding in Plicity.prettyAnnotation plicity <> lparen <> pretty name <+> ":" <+> prettyTerm 0 env type_ - <> rparen + <> rparen <+> "->" <+> prettyTerm funPrec env' scope Syntax.Fun domain plicity target -> @@ -145,26 +147,27 @@ prettyTerm prec env term = "case" <+> prettyTerm 0 env scrutinee <+> "of" - <> line - <> indent - 2 - ( vcat $ - case branches of - Syntax.ConstructorBranches constructorTypeName constructorBranches -> - [ prettyConstr env (Name.QualifiedConstructor constructorTypeName constr) <+> prettyBranch env tele - | (constr, (_, tele)) <- OrderedHashMap.toList constructorBranches - ] - Syntax.LiteralBranches literalBranches -> - [ pretty lit <+> "->" <+> prettyTerm 0 env body - | (lit, (_, body)) <- OrderedHashMap.toList literalBranches - ] - <> [ "_" - <+> "->" - <> line - <> indent 2 (prettyTerm casePrec env branch) - | Just branch <- [defaultBranch] - ] - ) + <> line + <> indent + 2 + ( vcat $ + ( case branches of + Syntax.ConstructorBranches constructorTypeName constructorBranches -> + [ prettyConstr env (Name.QualifiedConstructor constructorTypeName constr) <+> prettyBranch env tele + | (constr, (_, tele)) <- OrderedHashMap.toList constructorBranches + ] + Syntax.LiteralBranches literalBranches -> + [ pretty lit <+> "->" <+> prettyTerm 0 env body + | (lit, (_, body)) <- OrderedHashMap.toList literalBranches + ] + ) + <> [ "_" + <+> "->" + <> line + <> indent 2 (prettyTerm casePrec env branch) + | Just branch <- [defaultBranch] + ] + ) Syntax.Spanned _ term' -> prettyTerm prec env term' @@ -220,8 +223,8 @@ prettyLamTerm env term = <> pretty name <+> ":" <+> prettyTerm 0 env type_ - <> rparen - <> prettyLamTerm env' scope + <> rparen + <> prettyLamTerm env' scope Syntax.Spanned _ term' -> prettyLamTerm env term' t -> @@ -237,8 +240,8 @@ prettyPiTerm env plicity term separator = <> pretty name <+> ":" <+> prettyTerm 0 env type_ - <> rparen - <> prettyPiTerm env' plicity scope separator + <> rparen + <> prettyPiTerm env' plicity scope separator Syntax.Spanned _ term' -> prettyPiTerm env plicity term' separator t -> @@ -252,14 +255,14 @@ prettyLets env lets = in pretty name <+> ":" <+> prettyTerm letPrec env type_ - <> line - <> prettyLets env' lets' + <> line + <> prettyLets env' lets' Syntax.Let _ index term lets' -> prettyTerm letPrec env (Syntax.Var index) <+> "=" <+> prettyTerm letPrec env term - <> line - <> prettyLets env lets' + <> line + <> prettyLets env lets' Syntax.In term -> "in" <> line @@ -280,7 +283,7 @@ prettyBranch env tele = <> pretty name <+> ":" <+> prettyTerm 0 env type_ - <> ")" + <> ")" <+> prettyBranch env' tele' ------------------------------------------------------------------------------- @@ -320,7 +323,7 @@ prettyConstructorDefinitions env tele = <> pretty name <+> ":" <+> prettyTerm 0 env type_ - <> ")" + <> ")" <+> prettyConstructorDefinitions env' tele' prettyConstructorDefinitionsImplicit @@ -337,9 +340,9 @@ prettyConstructorDefinitionsImplicit env tele = <> pretty name <+> ":" <+> prettyTerm 0 env type_ - <> rparen - <> prettyConstructorDefinitionsImplicit env' tele' - Telescope.Extend _ _ _ _ -> + <> rparen + <> prettyConstructorDefinitionsImplicit env' tele' + Telescope.Extend {} -> "." <+> prettyConstructorDefinitions env tele ------------------------------------------------------------------------------- diff --git a/src/Core/Syntax.hs b/src/Core/Syntax.hs index dedaf84..732d928 100644 --- a/src/Core/Syntax.hs +++ b/src/Core/Syntax.hs @@ -107,7 +107,7 @@ varView term = funs :: (Foldable f) => f (Term v) -> Plicity -> Term v -> Term v funs args plicity res = - foldr (\a b -> Fun a plicity b) res args + foldr (`Fun` plicity) res args succ :: Term v -> Term (Succ v) succ = diff --git a/src/Driver.hs b/src/Driver.hs index e030fa1..6ca23b1 100644 --- a/src/Driver.hs +++ b/src/Driver.hs @@ -83,8 +83,8 @@ runTask sourceDirectories files prettyError task = do Rules.rules sourceDirectories files \file -> Right <$> readFile file `catch` \(_ :: IOException) -> pure mempty - Rock.runTask rules $ do - -- Rock.runMemoisedTask startedVar rules $ do + Rock.runTask rules do + -- Rock.runMemoisedTask startedVar rules do result <- task errorsMap <- readIORef errorsVar let errors = @@ -133,55 +133,54 @@ runIncrementalTask -> Task Query a -> IO (a, [err]) runIncrementalTask state changedFiles sourceDirectories files prettyError prune task = - handleEx $ do - do - reverseDependencies <- readIORef state.reverseDependenciesVar - started <- readIORef state.startedVar - hashes <- readIORef state.hashesVar + handleEx do + reverseDependencies <- readIORef state.reverseDependenciesVar + started <- readIORef state.startedVar + hashes <- readIORef state.hashesVar - case DHashMap.lookup Query.InputFiles started of - Just (Done inputFiles) -> do - -- TODO find a nicer way to do this - builtinFile <- Paths.getDataFileName "builtin/Builtin.vix" - if inputFiles /= HashSet.insert builtinFile (HashSet.fromMap $ void files) - then do - atomicWriteIORef state.reverseDependenciesVar mempty - atomicWriteIORef state.startedVar mempty - atomicWriteIORef state.hashesVar mempty - else do - changedFiles' <- flip filterM (toList changedFiles) \file -> - pure $ case (HashMap.lookup file files, DHashMap.lookup (Query.FileRope file) started, DHashMap.lookup (Query.FileText file) started) of - (Just (Left rope), Just (Done rope'), _) -> rope /= rope' - (Just (Left rope), _, Just (Done text')) -> Rope.toText rope /= text' - (Just (Right text), _, Just (Done text')) -> text /= text' - (Just (Right text), Just (Done rope'), _) -> text /= Rope.toText rope' - _ -> True - let (keysToInvalidate, reverseDependencies') = - foldl' - ( \(keysToInvalidate_, reverseDependencies_) file -> - first (<> keysToInvalidate_) $ reachableReverseDependencies (Query.FileText file) reverseDependencies_ - ) - (mempty, reverseDependencies) - changedFiles' - let started' = - DHashMap.difference started keysToInvalidate + case DHashMap.lookup Query.InputFiles started of + Just (Done inputFiles) -> do + -- TODO find a nicer way to do this + builtinFile <- Paths.getDataFileName "builtin/Builtin.vix" + if inputFiles /= HashSet.insert builtinFile (HashSet.fromMap $ void files) + then do + atomicWriteIORef state.reverseDependenciesVar mempty + atomicWriteIORef state.startedVar mempty + atomicWriteIORef state.hashesVar mempty + else do + changedFiles' <- flip filterM (toList changedFiles) \file -> + pure case (HashMap.lookup file files, DHashMap.lookup (Query.FileRope file) started, DHashMap.lookup (Query.FileText file) started) of + (Just (Left rope), Just (Done rope'), _) -> rope /= rope' + (Just (Left rope), _, Just (Done text')) -> Rope.toText rope /= text' + (Just (Right text), _, Just (Done text')) -> text /= text' + (Just (Right text), Just (Done rope'), _) -> text /= Rope.toText rope' + _ -> True + let (keysToInvalidate, reverseDependencies') = + foldl' + ( \(keysToInvalidate_, reverseDependencies_) file -> + first (<> keysToInvalidate_) $ reachableReverseDependencies (Query.FileText file) reverseDependencies_ + ) + (mempty, reverseDependencies) + changedFiles' + let started' = + DHashMap.difference started keysToInvalidate - hashes' = - DHashMap.difference hashes keysToInvalidate - -- Text.hPutStrLn stderr $ "keysToInvalidate " <> show (DHashMap.size keysToInvalidate) - -- Text.hPutStrLn stderr $ "Started " <> show (DHashMap.size started) <> " -> " <> show (DHashMap.size started') - -- Text.hPutStrLn stderr $ "Hashes " <> show (DHashMap.size hashes) <> " -> " <> show (DHashMap.size hashes') - -- Text.hPutStrLn stderr $ "ReverseDependencies " <> show (Map.size reverseDependencies) <> " -> " <> show (Map.size reverseDependencies') + hashes' = + DHashMap.difference hashes keysToInvalidate + -- Text.hPutStrLn stderr $ "keysToInvalidate " <> show (DHashMap.size keysToInvalidate) + -- Text.hPutStrLn stderr $ "Started " <> show (DHashMap.size started) <> " -> " <> show (DHashMap.size started') + -- Text.hPutStrLn stderr $ "Hashes " <> show (DHashMap.size hashes) <> " -> " <> show (DHashMap.size hashes') + -- Text.hPutStrLn stderr $ "ReverseDependencies " <> show (Map.size reverseDependencies) <> " -> " <> show (Map.size reverseDependencies') - atomicWriteIORef state.startedVar started' - atomicWriteIORef state.hashesVar hashes' - atomicWriteIORef state.reverseDependenciesVar reverseDependencies' + atomicWriteIORef state.startedVar started' + atomicWriteIORef state.hashesVar hashes' + atomicWriteIORef state.reverseDependenciesVar reverseDependencies' - -- printVar <- newMVar 0 - _ -> do - atomicWriteIORef state.reverseDependenciesVar mempty - atomicWriteIORef state.startedVar mempty - atomicWriteIORef state.hashesVar mempty + -- printVar <- newMVar 0 + _ -> do + atomicWriteIORef state.reverseDependenciesVar mempty + atomicWriteIORef state.startedVar mempty + atomicWriteIORef state.hashesVar mempty threadDepsVar <- newIORef mempty let readSourceFile_ file @@ -231,15 +230,15 @@ runIncrementalTask state changedFiles sourceDirectories files prettyError prune $ Rules.rules sourceDirectories (HashSet.fromMap $ void files) readSourceFile_ -- result <- Rock.runMemoisedTask (_startedVar state) rules task result <- Rock.runTask rules task - started <- readIORef state.startedVar + started' <- readIORef state.startedVar errorsMap <- case prune of Don'tPrune -> readIORef state.errorsVar Prune -> do atomicModifyIORef' state.tracesVar $ - (,()) . DHashMap.intersectionWithKey (\_ _ t -> t) started + (,()) . DHashMap.intersectionWithKey (\_ _ t -> t) started' atomicModifyIORef' state.errorsVar \errors -> do - let errors' = DHashMap.intersectionWithKey (\_ _ e -> e) started errors + let errors' = DHashMap.intersectionWithKey (\_ _ e -> e) started' errors (errors', errors') let errors = do (_ :=> Const errs) <- DHashMap.toList errorsMap diff --git a/src/Elaboration.hs b/src/Elaboration.hs index 62c2bed..f321720 100644 --- a/src/Elaboration.hs +++ b/src/Elaboration.hs @@ -498,7 +498,7 @@ elaborateWith context spannedTerm@(Surface.Term span term) mode canPostpone = do -- Approximate polymorphic variable inference Domain.Neutral (Domain.Meta _) _ -> do success <- Context.try_ context $ Unification.unify context Flexibility.Rigid type' expectedType - term' <- readback context $ if success then value else Builtin.Unknown expectedType + term' <- readback context if success then value else Builtin.Unknown expectedType pure $ Checked $ Syntax.Spanned span term' _ -> checkUnderBinder @@ -981,7 +981,7 @@ resolveConstructor constructorCandidates dataCandidates getExpectedTypeName_ = pure $ Right $ ResolvedData data_ _ -> do maybeExpectedTypeName <- getExpectedTypeName_ - pure $ case maybeExpectedTypeName of + pure case maybeExpectedTypeName of Nothing -> Right $ Ambiguous constructorCandidates dataCandidates Just (Left blockingMeta) -> diff --git a/src/Elaboration/Equation.hs b/src/Elaboration/Equation.hs index d11859c..6614cad 100644 --- a/src/Elaboration/Equation.hs +++ b/src/Elaboration/Equation.hs @@ -1,6 +1,5 @@ {-# LANGUAGE BlockArguments #-} {-# LANGUAGE DeriveAnyClass #-} -{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NoFieldSelectors #-} diff --git a/src/Elaboration/Matching.hs b/src/Elaboration/Matching.hs index 1c51215..d91efd7 100644 --- a/src/Elaboration/Matching.hs +++ b/src/Elaboration/Matching.hs @@ -155,8 +155,8 @@ resolvePattern context unspannedPattern type_ canPostpone = do pure Wildcard Surface.LitPattern lit -> pure $ Lit lit - Surface.Anno pattern annoType -> - pure $ Anno pattern annoType + Surface.Anno pat annoType -> + pure $ Anno pat annoType Surface.Forced term -> pure $ Forced term @@ -269,7 +269,7 @@ check context config canPostpone = do case clauses of [] -> do exhaustive <- anyM (uninhabitedScrutinee context . snd) config.scrutinees - unless exhaustive $ do + unless exhaustive do scrutinees <- forM config.scrutinees \(plicity, scrutinee) -> do patterns <- uncoveredScrutineePatterns context scrutinee pure $ (,) plicity <$> (Context.toPrettyablePattern context <$> patterns) @@ -446,7 +446,7 @@ simplifyMatch context canPostpone match@(Match value forcedValue plicity pat typ case (forcedValue', unspannedPattern) of (Domain.Con constr args, Con _ constr' pats) | constr == constr' -> do - matches' <- lift $ do + matches' <- lift do constrType <- fetch $ Query.ConstructorType constr (patsType, patSpine) <- instantiateConstructorType @@ -603,7 +603,7 @@ expandAnnotations context matches = Nothing -> case match of Match value forcedValue plicity (Pattern span (Anno pat annoType)) type_ -> do - lift $ do + lift do annoType' <- Elaboration.check context annoType Builtin.Type annoType'' <- Elaboration.evaluate context annoType' let context' = @@ -709,7 +709,7 @@ splitConstructor outerContext config scrutineeValue scrutineeHead scrutineeSpine OrderedHashMap.fromListWith (<>) . concat <$> mapWhileM - (fmap $ \xs -> if null xs then Nothing else Just xs) + (fmap \xs -> if null xs then Nothing else Just xs) (findConstructorMatches context scrutineeHead scrutineeSpine . (.matches) <$> config.clauses) branches <- forM (OrderedHashMap.toList matchedConstructors) \(qualifiedConstr@(Name.QualifiedConstructor _ constr), patterns) -> do @@ -836,7 +836,7 @@ splitLiteral context config scrutineeValue scrutineeHead scrutineeSpine span lit matchedLiterals <- OrderedHashMap.fromListWith (<>) . concat <$> mapWhileM - (fmap $ \xs -> if null xs then Nothing else Just xs) + (fmap \xs -> if null xs then Nothing else Just xs) (findLiteralMatches context scrutineeHead scrutineeSpine . (.matches) <$> config.clauses) f <- Unification.tryUnify (Context.spanned span context) (Elaboration.inferLiteral lit) outerType @@ -960,7 +960,7 @@ uninhabitedType context fuel covered type_ = do case type' of Builtin.Equals _ value1 value2 -> do result <- try $ Equation.equate context Flexibility.Rigid value1 value2 - pure $ case result of + pure case result of Left Equation.Nope -> True Left Equation.Dunno -> diff --git a/src/Elaboration/Meta.hs b/src/Elaboration/Meta.hs index bee0502..e7e4dcb 100644 --- a/src/Elaboration/Meta.hs +++ b/src/Elaboration/Meta.hs @@ -224,7 +224,7 @@ solutionMetas metaIndex state = do | EnumSet.null metas.unsolved -> pure (Just metas, state) | otherwise -> - flip runStateT state $ do + flip runStateT state do indirects <- forM (EnumSet.toList metas.unsolved) \i -> (,) i <$> StateT (solutionMetas i) diff --git a/src/Elaboration/MetaInlining.hs b/src/Elaboration/MetaInlining.hs index 762240c..44ce70b 100644 --- a/src/Elaboration/MetaInlining.hs +++ b/src/Elaboration/MetaInlining.hs @@ -545,7 +545,7 @@ inlineArguments value@(Value innerValue _) type_@(Value innerType _) args subst case (innerValue, innerType) of (Lam name var argType plicity1 body, Pi name' var' domain plicity2 target) | plicity1 == plicity2 -> - sharing (value, type_) $ do + sharing (value, type_) do argType' <- substitute subst argType domain' <- substitute subst domain (body', target') <- inlineArguments body target args' subst @@ -563,69 +563,66 @@ substitute subst | otherwise = go where - go value@(Value innerValue occs) = - sharing value $ - case innerValue of - Var var -> - case EnumMap.lookup var subst of - Nothing -> - pure value - Just value' -> do - modified - pure value' - Global _ -> + go value@(Value innerValue occs) = sharing value case innerValue of + Var var -> + case EnumMap.lookup var subst of + Nothing -> pure value - Con _ -> - pure value - Lit _ -> - pure value - Meta index args -> - makeMeta index <$> mapM go args - PostponedCheck index value' -> - makePostponedCheck index <$> go value' - LetsValue lets -> - makeLets <$> goLets (Lets lets occs) - Pi name var domain plicity target -> - makePi name var <$> go domain <*> pure plicity <*> go target - Fun domain plicity target -> - makeFun <$> go domain <*> pure plicity <*> go target - Lam name var type_ plicity body -> - makeLam name var <$> go type_ <*> pure plicity <*> go body - App function plicity argument -> - makeApp <$> go function <*> pure plicity <*> go argument - Case scrutinee branches defaultBranch -> - makeCase - <$> go scrutinee - <*> ( case branches of - ConstructorBranches constructorTypeName constructorBranches -> - ConstructorBranches constructorTypeName - <$> OrderedHashMap.forMUnordered - constructorBranches - ( \(span, (bindings, body)) -> do - bindings' <- forM bindings \(name, var, type_, plicity) -> - (name,var,,plicity) <$> go type_ - - body' <- go body - pure (span, (bindings', body')) - ) - LiteralBranches literalBranches -> - LiteralBranches - <$> OrderedHashMap.mapMUnordered (mapM go) literalBranches - ) - <*> mapM go defaultBranch - Spanned span value' -> - makeSpanned span <$> go (Value value' occs) + Just value' -> do + modified + pure value' + Global _ -> + pure value + Con _ -> + pure value + Lit _ -> + pure value + Meta index args -> + makeMeta index <$> mapM go args + PostponedCheck index value' -> + makePostponedCheck index <$> go value' + LetsValue lets -> + makeLets <$> goLets (Lets lets occs) + Pi name var domain plicity target -> + makePi name var <$> go domain <*> pure plicity <*> go target + Fun domain plicity target -> + makeFun <$> go domain <*> pure plicity <*> go target + Lam name var type_ plicity body -> + makeLam name var <$> go type_ <*> pure plicity <*> go body + App function plicity argument -> + makeApp <$> go function <*> pure plicity <*> go argument + Case scrutinee branches defaultBranch -> + makeCase + <$> go scrutinee + <*> ( case branches of + ConstructorBranches constructorTypeName constructorBranches -> + ConstructorBranches constructorTypeName + <$> OrderedHashMap.forMUnordered + constructorBranches + ( \(span, (bindings, body)) -> do + bindings' <- forM bindings \(name, var, type_, plicity) -> + (name,var,,plicity) <$> go type_ + + body' <- go body + pure (span, (bindings', body')) + ) + LiteralBranches literalBranches -> + LiteralBranches + <$> OrderedHashMap.mapMUnordered (mapM go) literalBranches + ) + <*> mapM go defaultBranch + Spanned span value' -> + makeSpanned span <$> go (Value value' occs) goLets :: Lets -> Shared Lets goLets lets@(Lets innerLets occs) = - sharing lets $ - case innerLets of - LetType name var type_ lets' -> - makeLetType name var <$> go type_ <*> goLets lets' - Let name var value lets' -> - makeLet name var <$> go value <*> goLets lets' - In value -> - makeIn <$> go (Value value occs) + sharing lets case innerLets of + LetType name var type_ lets' -> + makeLetType name var <$> go type_ <*> goLets lets' + Let name var value lets' -> + makeLet name var <$> go value <*> goLets lets' + In value -> + makeIn <$> go (Value value occs) data Shared a = Shared !Bool a deriving (Eq, Ord, Show, Functor, Foldable, Traversable) @@ -649,10 +646,7 @@ modified = sharing :: a -> Shared a -> Shared a sharing a (Shared modified_ a') = - Shared modified_ $ - if modified_ - then a' - else a + Shared modified_ if modified_ then a' else a unShared :: Shared a -> a unShared (Shared _ a) = @@ -681,7 +675,7 @@ inlineIndex index targetScope solution@(solutionVar, occurrenceCount, duplicable <$> filter (isNothing . fst) (zip (duplicableArgs <> repeat Nothing) (toList args)) - pure $ foldl' (\v1 v2 -> makeApp v1 Explicit v2) solutionValue remainingArgs + pure $ foldl' (`makeApp` Explicit) solutionValue remainingArgs _ | EnumSet.null targetScope && occurrenceCount > 1 -> if index `EnumMap.member` occurrencesMap value @@ -728,8 +722,8 @@ inlineIndex index targetScope solution@(solutionVar, occurrenceCount, duplicable scrutinee' <- recurse scrutinee branches' <- case branches of ConstructorBranches constructorTypeName constructorBranches -> - fmap (ConstructorBranches constructorTypeName) $ - OrderedHashMap.forMUnordered constructorBranches \(span, (bindings, body)) -> do + ConstructorBranches constructorTypeName + <$> OrderedHashMap.forMUnordered constructorBranches \(span, (bindings, body)) -> do let go targetScope' bindings' = case bindings' of [] -> do @@ -751,20 +745,19 @@ inlineIndex index targetScope solution@(solutionVar, occurrenceCount, duplicable inlineLetsIndex :: Meta.Index -> EnumSet Var -> (Var, Int, [Maybe DuplicableValue], Value, Value) -> Lets -> Shared Lets inlineLetsIndex index targetScope solution lets@(Lets innerLets occs) = - sharing lets $ - case innerLets of - LetType name var type_ lets' -> - makeLetType name var <$> recurseValue type_ <*> recurseScope var lets' - Let name var value lets' -> - makeLet name var <$> recurseValue value <*> recurseLets lets' - In value -> - makeIn <$> recurseValue (Value value occs) + sharing lets case innerLets of + LetType name var type_ lets' -> + makeLetType name var <$> recurseValue type_ <*> recurseScope var lets' + Let name var value lets' -> + makeLet name var <$> recurseValue value <*> recurseLets lets' + In value -> + makeIn <$> recurseValue (Value value occs) where - recurseLets lets' = - inlineLetsIndex index targetScope solution lets' + recurseLets = + inlineLetsIndex index targetScope solution - recurseScope var lets' = - inlineLetsIndex index (EnumSet.delete var targetScope) solution lets' + recurseScope var = + inlineLetsIndex index (EnumSet.delete var targetScope) solution - recurseValue value = - inlineIndex index targetScope solution value + recurseValue = + inlineIndex index targetScope solution diff --git a/src/Elaboration/Unification.hs b/src/Elaboration/Unification.hs index ae6b952..18eed32 100644 --- a/src/Elaboration/Unification.hs +++ b/src/Elaboration/Unification.hs @@ -62,7 +62,7 @@ tryUnify context value1 value2 = do tryUnifyD :: Context v -> Domain.Value -> Domain.Value -> M (Domain.Value -> Domain.Value) tryUnifyD context value1 value2 = do success <- Context.try_ context $ unify context Flexibility.Rigid value1 value2 - pure $ + pure if success then identity else const $ Builtin.Unknown value2 @@ -225,11 +225,11 @@ unify context flexibility unforcedValue1 unforcedValue2 = catchAndAdd $ go unfor (Domain.Neutral head1 spine1@(Domain.Spine args1 ((branches1, _) Seq.:<| _)), Domain.Neutral head2 spine2) | head1 == head2 -> unifySpines context Flexibility.Flexible spine1 spine2 `catch` \(_ :: Error.Elaboration) -> - withBranches context head1 args1 branches1 $ \context' -> unify context' flexibility value1' value2 + withBranches context head1 args1 branches1 \context' -> unify context' flexibility value1' value2 (Domain.Neutral head (Domain.Spine args ((branches, _) Seq.:<| _)), _) -> - withBranches context head args branches $ \context' -> unify context' flexibility value1' value2 + withBranches context head args branches \context' -> unify context' flexibility value1' value2 (_, Domain.Neutral head (Domain.Spine args ((branches, _) Seq.:<| _))) -> - withBranches context head args branches $ \context' -> unify context' flexibility value1 value2' + withBranches context head args branches \context' -> unify context' flexibility value1 value2' -- Failure terms mean that there has been an earlier error that's already -- been reported, so let's not trigger more errors from them. (Domain.Neutral (Domain.Global Builtin.UnknownName) _, _) -> @@ -541,19 +541,20 @@ potentiallyMatchingBranches outerContext resultValue (Domain.Branches outerEnv b then Just Nothing else Nothing - branches' <- fmap catMaybes $ + branches' <- fmap + catMaybes case branches of Syntax.ConstructorBranches constructorTypeName constructorBranches -> forM (OrderedHashMap.toList constructorBranches) \(constr, (_, tele)) -> do isMatch <- branchMatches outerContext resultValue' outerEnv tele - pure $ + pure if isMatch then Just $ Just $ Left $ Name.QualifiedConstructor constructorTypeName constr else Nothing Syntax.LiteralBranches literalBranches -> forM (OrderedHashMap.toList literalBranches) \(int, (_, branch)) -> do isMatch <- branchMatches outerContext resultValue' outerEnv $ Telescope.Empty branch - pure $ + pure if isMatch then Just $ Just $ Right int else Nothing diff --git a/src/Elaboration/ZonkPostponedChecks.hs b/src/Elaboration/ZonkPostponedChecks.hs index 010577f..3b0c7ab 100644 --- a/src/Elaboration/ZonkPostponedChecks.hs +++ b/src/Elaboration/ZonkPostponedChecks.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE OverloadedStrings #-} - module Elaboration.ZonkPostponedChecks where import qualified Core.Syntax as Syntax diff --git a/src/Error/Hydrated.hs b/src/Error/Hydrated.hs index a23414a..b5bc548 100644 --- a/src/Error/Hydrated.hs +++ b/src/Error/Hydrated.hs @@ -1,5 +1,4 @@ {-# LANGUAGE BlockArguments #-} -{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedRecordDot #-} @@ -189,7 +188,7 @@ headingAndBody error = <+> "applies or not, because the unification of a constructor type's indices failed to produce a definite result." ) Error.PlicityMismatch fieldOrArg plicityMismatch -> - pure $ case plicityMismatch of + pure case plicityMismatch of Error.Mismatch expected_ actual -> ( "Plicity mismatch" , "Expected an" @@ -245,12 +244,12 @@ pretty h = do <> Doc.pretty h.lineColumn <> ":" <+> heading - <> line - <> line - <> body - <> line - <> line - <> spannedLine + <> line + <> line + <> body + <> line + <> line + <> spannedLine where spannedLine = let UTF16.LineColumns @@ -293,7 +292,7 @@ fromError err = do pure (fromMaybe "" maybeModuleFile, Right span) Error.ImportNotFound module_ import_ -> do maybeModuleFile <- fetch $ Query.ModuleFile module_ - pure (fromMaybe "" maybeModuleFile, Right $ import_.span) + pure (fromMaybe "" maybeModuleFile, Right import_.span) Error.MultipleFilesWithModuleName _ _ file2 -> pure (file2, Right $ Span.Absolute 0 0) Error.ModuleFileNameMismatch _ _ span file -> diff --git a/src/FileSystem.hs b/src/FileSystem.hs index 9147e21..d072b1b 100644 --- a/src/FileSystem.hs +++ b/src/FileSystem.hs @@ -71,7 +71,7 @@ instance Monad Watcher where modifyMVar_ stopListening2Var \stopListening2 -> do stopListening2 runWatcher (f value1) manager onChange - pure $ do + pure do stopListening1 modifyMVar_ stopListening2Var \stopListening2 -> do stopListening2 @@ -147,8 +147,8 @@ watcherFromArguments files = projectFile' <- Directory.canonicalizePath projectFile pure $ projectWatcher projectFile' _ -> - fmap mconcat $ - forM files \file -> do + mconcat + <$> forM files \file -> do file' <- Directory.canonicalizePath file isDir <- Directory.doesDirectoryExist file' case () of @@ -241,8 +241,8 @@ directoryWatcher predicate directory = Watcher \manager onChange -> do listDirectoryRecursive :: (FilePath -> Bool) -> FilePath -> IO (HashMap FilePath Text) listDirectoryRecursive predicate directory = do files <- Directory.listDirectory directory - fmap mconcat $ - forM files \file -> do + mconcat + <$> forM files \file -> do path <- Directory.canonicalizePath $ directory FilePath. file isDir <- Directory.doesDirectoryExist path if isDir diff --git a/src/LambdaLifting.hs b/src/LambdaLifting.hs index bf16d8d..4ef107b 100644 --- a/src/LambdaLifting.hs +++ b/src/LambdaLifting.hs @@ -200,7 +200,7 @@ evaluate baseName env term args = Syntax.Var index -> do let var = Environment.lookupIndexVar index env - applyArgs $ + applyArgs case Environment.lookupVarValue var env of Just (Just value, _) -> pure value diff --git a/src/LanguageServer.hs b/src/LanguageServer.hs index d8b160b..e57b87a 100644 --- a/src/LanguageServer.hs +++ b/src/LanguageServer.hs @@ -205,17 +205,16 @@ handle logger = Hover.hover (uriToFilePath uri) (positionFromPosition position) let response = - foreach maybeAnnotation $ - \(span, doc) -> - LSP.Hover - { _contents = - LSP.InL - LSP.MarkupContent - { _kind = LSP.MarkupKind_PlainText - , _value = show doc - } - , _range = Just $ spanToRange span - } + foreach maybeAnnotation \(span, doc) -> + LSP.Hover + { _contents = + LSP.InL + LSP.MarkupContent + { _kind = LSP.MarkupKind_PlainText + , _value = show doc + } + , _range = Just $ spanToRange span + } respond $ Right $ LSP.maybeToNull response , LSP.requestHandler LSP.SMethod_TextDocumentDefinition \message respond -> do @@ -247,12 +246,11 @@ handle logger = maybeContext = message ^. LSP.params . LSP.context (completions, _) <- - runTask Driver.Don'tPrune $ - case maybeContext of - Just (LSP.CompletionContext LSP.CompletionTriggerKind_TriggerCharacter (Just "?")) -> - Completion.questionMark (uriToFilePath uri) (positionFromPosition position) - _ -> - Completion.complete (uriToFilePath uri) (positionFromPosition position) + runTask Driver.Don'tPrune case maybeContext of + Just (LSP.CompletionContext LSP.CompletionTriggerKind_TriggerCharacter (Just "?")) -> + Completion.questionMark (uriToFilePath uri) (positionFromPosition position) + _ -> + Completion.complete (uriToFilePath uri) (positionFromPosition position) logger <& ("handle CompletionResponse: " <> show completions) `WithSeverity` Info diff --git a/src/LanguageServer/CodeLens.hs b/src/LanguageServer/CodeLens.hs index eb9a867..ebbfbab 100644 --- a/src/LanguageServer/CodeLens.hs +++ b/src/LanguageServer/CodeLens.hs @@ -1,5 +1,4 @@ {-# LANGUAGE BlockArguments #-} -{-# LANGUAGE OverloadedStrings #-} module LanguageServer.CodeLens where @@ -22,36 +21,34 @@ import qualified Surface.Syntax as Surface import qualified UTF16 codeLens :: FilePath -> Task Query [(UTF16.LineColumns, Doc ann)] -codeLens filePath = - runM $ do - (moduleName, _, defs) <- fetch $ Query.ParsedFile filePath +codeLens filePath = runM do + (moduleName, _, defs) <- fetch $ Query.ParsedFile filePath - toLineColumns <- LineColumns.fromAbsolute moduleName - let previousDefs = - Nothing : fmap Just defs - fmap concat $ - forM (zip previousDefs defs) \(previousDef, (pos, (name@(Name nameText), def))) -> do - let qualifiedName = - Name.Qualified moduleName name + toLineColumns <- LineColumns.fromAbsolute moduleName + let previousDefs = Nothing : fmap Just defs + concat + <$> forM (zip previousDefs defs) \(previousDef, (pos, (name@(Name nameText), def))) -> do + let qualifiedName = + Name.Qualified moduleName name - go = do - context <- Context.empty Scope.Definition qualifiedName - type_ <- fetch $ Query.ElaboratedType qualifiedName - prettyType <- Error.prettyPrettyableTerm 0 =<< Context.toPrettyableTerm context type_ - pure - [ - ( toLineColumns $ Span.Absolute pos $ pos + Position.Absolute (Text.lengthWord8 nameText) - , prettyType - ) - ] + go = do + context <- Context.empty Scope.Definition qualifiedName + type_ <- fetch $ Query.ElaboratedType qualifiedName + prettyType <- Error.prettyPrettyableTerm 0 =<< Context.toPrettyableTerm context type_ + pure + [ + ( toLineColumns $ Span.Absolute pos $ pos + Position.Absolute (Text.lengthWord8 nameText) + , prettyType + ) + ] - case (previousDef, def) of - (Just (_, (previousName, Surface.TypeDeclaration {})), _) - | previousName == name -> - pure [] - (_, Surface.TypeDeclaration {}) -> - pure [] - (_, Surface.ConstantDefinition {}) -> - go - (_, Surface.DataDefinition {}) -> - go + case (previousDef, def) of + (Just (_, (previousName, Surface.TypeDeclaration {})), _) + | previousName == name -> + pure [] + (_, Surface.TypeDeclaration {}) -> + pure [] + (_, Surface.ConstantDefinition {}) -> + go + (_, Surface.DataDefinition {}) -> + go diff --git a/src/LanguageServer/Completion.hs b/src/LanguageServer/Completion.hs index c18d08d..85b2c82 100644 --- a/src/LanguageServer/Completion.hs +++ b/src/LanguageServer/Completion.hs @@ -90,8 +90,8 @@ questionMark filePath (UTF16.LineColumn line column) = metasBefore <- readIORef context.metas lift $ - fmap concat $ - forM names \(name, value, kind) -> do + concat + <$> forM names \(name, value, kind) -> do writeIORef context.metas metasBefore type_ <- TypeOf.typeOf context value (maxArgs, _) <- Elaboration.insertMetas context Elaboration.UntilTheEnd type_ @@ -102,12 +102,12 @@ questionMark filePath (UTF16.LineColumn line column) = writeIORef context.metas metasBefore' appliedValue <- lift $ foldM (\fun (plicity, arg) -> Evaluation.apply fun plicity arg) value args appliedType <- lift $ TypeOf.typeOf context appliedValue - MaybeT $ do + MaybeT do isSubtype <- Elaboration.isSubtype context appliedType typeUnderCursor - pure $ if isSubtype then Just () else Nothing + pure if isSubtype then Just () else Nothing pure args - pure $ case maybeArgs of + pure case maybeArgs of Nothing -> -- typeUnderCursor' <- Elaboration.readback context typeUnderCursor -- type' <- Elaboration.readback context type_ @@ -117,8 +117,7 @@ questionMark filePath (UTF16.LineColumn line column) = -- Text.hPutStrLn stderr $ "nothing toc " <> show prettyTypeUnderCursor [] Just args -> do - let explicitArgs = - filter ((== Explicit) . fst) args + let explicitArgs = filter ((== Explicit) . fst) args pure LSP.CompletionItem { _label = name @@ -213,11 +212,12 @@ getUsableNames itemContext context varPositions = do Scope.Constructors constrs datas -> do let go = pure $ - case toList datas of - [data_] -> - [(name, Domain.global data_, LSP.CompletionItemKind_Enum)] - _ -> - [] + ( case toList datas of + [data_] -> + [(name, Domain.global data_, LSP.CompletionItemKind_Enum)] + _ -> + [] + ) <> [ (name, Domain.con con, LSP.CompletionItemKind_EnumMember) | con <- toList constrs ] diff --git a/src/LanguageServer/CursorAction.hs b/src/LanguageServer/CursorAction.hs index 6f706b2..94cc529 100644 --- a/src/LanguageServer/CursorAction.hs +++ b/src/LanguageServer/CursorAction.hs @@ -4,7 +4,6 @@ {-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE NoFieldSelectors #-} module LanguageServer.CursorAction where @@ -76,12 +75,12 @@ cursorAction -> Task Query (Maybe a) cursorAction filePath (UTF16.LineColumn line column) k = runM $ - runMaybeT $ do + runMaybeT do (moduleName, moduleHeader, _) <- fetch $ Query.ParsedFile filePath spans <- fetch $ Query.ModuleSpanMap moduleName contents <- fetch $ Query.FileRope filePath let pos = - Position.Absolute $ + Position.Absolute case Rope.splitAtPosition (Rope.Position (fromIntegral line) (fromIntegral $ UTF16.toInt column)) contents of Nothing -> 0 Just (rope, _) -> fromIntegral $ Rope.utf8Length rope diff --git a/src/LanguageServer/DocumentHighlights.hs b/src/LanguageServer/DocumentHighlights.hs index b529485..638560c 100644 --- a/src/LanguageServer/DocumentHighlights.hs +++ b/src/LanguageServer/DocumentHighlights.hs @@ -25,7 +25,7 @@ highlights filePath (UTF16.LineColumn line column) = do spans <- fetch $ Query.ModuleSpanMap moduleName contents <- fetch $ Query.FileRope filePath let pos = - Position.Absolute $ + Position.Absolute case Rope.splitAtPosition (Rope.Position (fromIntegral line) (fromIntegral $ UTF16.toInt column)) contents of Nothing -> 0 Just (rope, _) -> fromIntegral $ Rope.utf8Length rope @@ -33,16 +33,16 @@ highlights filePath (UTF16.LineColumn line column) = do toLineColumns <- LineColumns.fromAbsolute moduleName let itemSpans item = - fmap concat $ - forM (HashMap.toList spans) \((definitionKind, name), Span.Absolute defPos _) -> do + concat + <$> forM (HashMap.toList spans) \((definitionKind, name), Span.Absolute defPos _) -> do occurrenceIntervals <- fetch $ Query.Occurrences definitionKind $ Name.Qualified moduleName name pure $ toLineColumns . Span.absoluteFrom defPos <$> Intervals.itemSpans item occurrenceIntervals - fmap concat $ - forM (HashMap.toList spans) \((definitionKind, name), span@(Span.Absolute defPos _)) -> + concat + <$> forM (HashMap.toList spans) \((definitionKind, name), span@(Span.Absolute defPos _)) -> if span `Span.contains` pos then do occurrenceIntervals <- @@ -55,8 +55,8 @@ highlights filePath (UTF16.LineColumn line column) = do items = Intervals.intersect relativePos occurrenceIntervals - fmap concat $ - forM items \item -> + concat + <$> forM items \item -> case item of Intervals.Var var -> pure $ toLineColumns . Span.absoluteFrom defPos <$> Intervals.varSpans var relativePos occurrenceIntervals diff --git a/src/LanguageServer/GoToDefinition.hs b/src/LanguageServer/GoToDefinition.hs index db77772..4ba8071 100644 --- a/src/LanguageServer/GoToDefinition.hs +++ b/src/LanguageServer/GoToDefinition.hs @@ -28,7 +28,7 @@ goToDefinition filePath (UTF16.LineColumn line column) = do spans <- fetch $ Query.ModuleSpanMap moduleName rope <- fetch $ Query.FileRope filePath let pos = - Position.Absolute $ + Position.Absolute case Rope.splitAtPosition (Rope.Position (fromIntegral line) (fromIntegral $ UTF16.toInt column)) rope of Nothing -> 0 Just (rope', _) -> fromIntegral $ Rope.utf8Length rope' diff --git a/src/LanguageServer/References.hs b/src/LanguageServer/References.hs index b3be53d..ff2fb96 100644 --- a/src/LanguageServer/References.hs +++ b/src/LanguageServer/References.hs @@ -31,15 +31,15 @@ references filePath (UTF16.LineColumn line column) = do moduleName == definingModule || any ((==) definingModule . (.module_)) header.imports inputFiles <- fetch Query.InputFiles - fmap concat $ - forM (HashSet.toList inputFiles) \inputFile -> do + concat + <$> forM (HashSet.toList inputFiles) \inputFile -> do (moduleName, header, _) <- fetch $ Query.ParsedFile inputFile if mightUseDefiningModule moduleName header then do spans <- fetch $ Query.ModuleSpanMap moduleName toLineColumns <- LineColumns.fromAbsolute moduleName - fmap concat $ - forM (HashMap.toList spans) \((definitionKind, name), Span.Absolute defPos _) -> do + concat + <$> forM (HashMap.toList spans) \((definitionKind, name), Span.Absolute defPos _) -> do occurrenceIntervals <- fetch $ Query.Occurrences definitionKind $ @@ -49,14 +49,14 @@ references filePath (UTF16.LineColumn line column) = do contents <- fetch $ Query.FileRope filePath let pos = - Position.Absolute $ + Position.Absolute case Rope.splitAtPosition (Rope.Position (fromIntegral line) (fromIntegral $ UTF16.toInt column)) contents of Nothing -> 0 Just (rope, _) -> fromIntegral $ Rope.utf8Length rope toLineColumns <- LineColumns.fromAbsolute originalModuleName spans <- fetch $ Query.ModuleSpanMap originalModuleName - fmap concat $ - forM (HashMap.toList spans) \((definitionKind, name), span@(Span.Absolute defPos _)) -> + concat + <$> forM (HashMap.toList spans) \((definitionKind, name), span@(Span.Absolute defPos _)) -> if span `Span.contains` pos then do occurrenceIntervals <- diff --git a/src/Lexer.hs b/src/Lexer.hs index 9f205db..d934258 100644 --- a/src/Lexer.hs +++ b/src/Lexer.hs @@ -1,4 +1,5 @@ {-# LANGUAGE BangPatterns #-} +{-# LANGUAGE BlockArguments #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} @@ -290,7 +291,9 @@ identifierToken -> TokenList -> TokenList identifierToken !input !startPosition !startLineColumn !position = - Token startLineColumn (Span.Absolute startPosition position) $ + Token + startLineColumn + (Span.Absolute startPosition position) case index input startPosition of [UTF8.unit1|_|] | len == 1 -> Underscore [UTF8.unit1|l|] | "let" <- str -> Let @@ -336,7 +339,9 @@ operatorToken -> TokenList -> TokenList operatorToken !input !startPosition !startLineColumn !position = - Token startLineColumn (Span.Absolute startPosition position) $ + Token + startLineColumn + (Span.Absolute startPosition position) case index input startPosition of [UTF8.unit1|=|] | len == 1 -> Equals [UTF8.unit1|.|] | len == 1 -> Dot @@ -380,8 +385,7 @@ number !startPosition !startLineColumn state@State {..} !shouldNegate !acc where token = Token startLineColumn (Span.Absolute startPosition position) $ - Number $ - if shouldNegate then negate acc else acc + Number if shouldNegate then negate acc else acc ------------------------------------------------------------------------------- diff --git a/src/Monad.hs b/src/Monad.hs index dca7d1a..ce4decb 100644 --- a/src/Monad.hs +++ b/src/Monad.hs @@ -1,6 +1,5 @@ {-# LANGUAGE BlockArguments #-} {-# LANGUAGE FlexibleContexts #-} -{-# LANGUAGE OverloadedStrings #-} module Monad where @@ -26,6 +25,8 @@ force :: Lazy a -> M a force (Lazy a) = liftIO $ evaluate a +{-# ANN module "HLint: ignore Use newtype instead of data" #-} + {-# NOINLINE lazy #-} lazy :: M a -> M (Lazy a) lazy m = diff --git a/src/Name.hs b/src/Name.hs index 2df0ffe..6a13976 100644 --- a/src/Name.hs +++ b/src/Name.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} diff --git a/src/Occurrences.hs b/src/Occurrences.hs index a1c4772..ec6a69f 100644 --- a/src/Occurrences.hs +++ b/src/Occurrences.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE BlockArguments #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} @@ -85,12 +86,11 @@ definitionConstructorSpans -> m [(Span.Relative, Name.QualifiedConstructor)] definitionConstructorSpans definitionKind qualifiedName@(Name.Qualified moduleName name) = do maybeParsedDefinition <- fetch $ Query.ParsedDefinition moduleName $ Mapped.Query (definitionKind, name) - pure $ - case maybeParsedDefinition of - Nothing -> - [] - Just parsedDefinition -> - second (Name.QualifiedConstructor qualifiedName) <$> Surface.constructorSpans parsedDefinition + pure case maybeParsedDefinition of + Nothing -> + [] + Just parsedDefinition -> + second (Name.QualifiedConstructor qualifiedName) <$> Surface.constructorSpans parsedDefinition termOccurrences :: Domain.Environment v diff --git a/src/Orphans.hs b/src/Orphans.hs index db7a67b..55c52bc 100644 --- a/src/Orphans.hs +++ b/src/Orphans.hs @@ -1,7 +1,6 @@ {-# LANGUAGE BlockArguments #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE TypeApplications #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -Wno-orphans #-} diff --git a/src/Position.hs b/src/Position.hs index c28dd00..4fb6065 100644 --- a/src/Position.hs +++ b/src/Position.hs @@ -2,7 +2,6 @@ {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -{-# LANGUAGE OverloadedStrings #-} module Position where diff --git a/src/Postponement.hs b/src/Postponement.hs index 45bad94..3d9d47b 100644 --- a/src/Postponement.hs +++ b/src/Postponement.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DeriveAnyClass #-} -{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} diff --git a/src/Project.hs b/src/Project.hs index 71f9992..aff044c 100644 --- a/src/Project.hs +++ b/src/Project.hs @@ -30,8 +30,8 @@ filesFromArguments files = do workingDirectory <- Directory.getCurrentDirectory filesFromProjectInDirectory workingDirectory _ -> - fmap mconcat $ - forM files' \file -> do + mconcat + <$> forM files' \file -> do isDir <- Directory.doesDirectoryExist file isFile <- Directory.doesFileExist file case () of @@ -98,8 +98,8 @@ listProject file project = do listDirectoryRecursive :: (FilePath -> Bool) -> FilePath -> IO (HashSet FilePath) listDirectoryRecursive p dir = do files <- Directory.listDirectory dir - fmap mconcat $ - forM files \file -> do + mconcat + <$> forM files \file -> do let path = dir FilePath. file isDir <- Directory.doesDirectoryExist path if isDir diff --git a/src/Query/Mapped.hs b/src/Query/Mapped.hs index 32fad6a..9ac206d 100644 --- a/src/Query/Mapped.hs +++ b/src/Query/Mapped.hs @@ -5,8 +5,6 @@ {-# LANGUAGE QuantifiedConstraints #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StandaloneDeriving #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} module Query.Mapped where diff --git a/src/Rules.hs b/src/Rules.hs index 0db4a13..2ff6454 100644 --- a/src/Rules.hs +++ b/src/Rules.hs @@ -71,7 +71,7 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = case query of SourceDirectories -> input $ - pure $ + pure case (HashSet.toList sourceDirectories, HashSet.toList files) of -- A little hack to allow opening single source files without a project file ([], [file]) -> @@ -79,28 +79,28 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = (sourceDirectoriesList, _) -> sourceDirectoriesList InputFiles -> - input $ do + input do builtinFile <- liftIO $ Paths.getDataFileName "builtin/Builtin.vix" pure $ HashSet.insert builtinFile files FileText filePath -> input $ - liftIO $ do + liftIO do result <- readFile_ filePath - pure $ case result of + pure case result of Left rope -> Rope.toText rope Right text -> text FileRope filePath -> input $ - liftIO $ do + liftIO do result <- readFile_ filePath - pure $ case result of + pure case result of Left rope -> rope Right text -> Rope.fromText text ModuleFile Builtin.Module -> noError $ Just <$> liftIO (Paths.getDataFileName "builtin/Builtin.vix") ModuleFile moduleName@(Name.Module moduleNameText) -> - nonInput $ do + nonInput do files_ <- fetch InputFiles sourceDirectories_ <- fetch SourceDirectories let candidates = @@ -111,7 +111,7 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = , candidate `HashSet.member` files_ ] - pure $ + pure case candidates of [] -> (Nothing, mempty) @@ -124,7 +124,7 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = , [Error.MultipleFilesWithModuleName moduleName filePath1 filePath2] ) ParsedFile filePath -> - nonInput $ do + nonInput do text <- fetch $ FileText filePath fileModuleName <- moduleNameFromFilePath case Parser.parseTokens Parser.module_ $ Lexer.lexText text of @@ -146,7 +146,7 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = : header.imports } - pure $ + pure case maybeModuleName of Nothing -> ((fileModuleName, headerImportingBuiltins, definitions), errors) @@ -176,33 +176,34 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = ] pure $ - Name.Module $ + Name.Module case candidates of [] -> toS filePath firstCandidate : _ -> firstCandidate ModuleDefinitions module_ -> - noError $ do + noError do maybeFile <- fetch $ ModuleFile module_ - fmap (OrderedHashSet.fromList . fold) $ - forM maybeFile \file -> do + OrderedHashSet.fromList . fold + <$> forM maybeFile \file -> do (_, _, defs) <- fetch $ ParsedFile file pure $ fst . snd <$> defs ModuleHeader module_ -> - nonInput $ do + nonInput do maybeFilePath <- fetch $ Query.ModuleFile module_ - fmap fold $ - forM maybeFilePath \filePath -> do + fold + <$> forM maybeFilePath \filePath -> do (_, header, _) <- fetch $ ParsedFile filePath - errors <- fmap concat $ - forM header.imports \import_ -> do - maybeModuleFile <- fetch $ Query.ModuleFile import_.module_ - pure [Error.ImportNotFound module_ import_ | isNothing maybeModuleFile] + errors <- + concat + <$> forM header.imports \import_ -> do + maybeModuleFile <- fetch $ Query.ModuleFile import_.module_ + pure [Error.ImportNotFound module_ import_ | isNothing maybeModuleFile] pure (header, errors) ImportedNames module_ subQuery -> noError $ - Mapped.rule (ImportedNames module_) subQuery $ do + Mapped.rule (ImportedNames module_) subQuery do header <- fetch $ ModuleHeader module_ scopes <- forM header.imports \import_ -> do importedHeader <- fetch $ ModuleHeader import_.module_ @@ -213,16 +214,16 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = pure $ foldl' (HashMap.unionWith (<>)) mempty scopes NameAliases module_ -> - noError $ do + noError do importedNames <- fetch $ ImportedNames module_ Mapped.Map (localScope, _) <- fetch $ ModuleScope module_ pure $ Scope.aliases $ HashMap.unionWith (<>) localScope importedNames ParsedDefinition module_ subQuery -> noError $ - Mapped.rule (ParsedDefinition module_) subQuery $ do + Mapped.rule (ParsedDefinition module_) subQuery do maybeFilePath <- fetch $ Query.ModuleFile module_ - fmap fold $ - forM maybeFilePath \filePath -> do + fold + <$> forM maybeFilePath \filePath -> do (_, _, defs) <- fetch $ ParsedFile filePath pure $ HashMap.fromListWith @@ -231,14 +232,14 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = | (_, (name, def)) <- defs ] ModulePositionMap module_ -> - noError $ do + noError do spans <- fetch $ ModuleSpanMap module_ pure $ (\(Span.Absolute start _) -> start) <$> spans ModuleSpanMap module_ -> - noError $ do + noError do maybeFilePath <- fetch $ Query.ModuleFile module_ - fmap fold $ - forM maybeFilePath \filePath -> do + fold + <$> forM maybeFilePath \filePath -> do text <- fetch $ FileText filePath (_, _, defs) <- fetch $ ParsedFile filePath let go = \case @@ -251,19 +252,19 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = pure $ HashMap.fromListWith (\_new old -> old) $ go defs ModuleScope module_ -> - nonInput $ do + nonInput do maybeFilePath <- fetch $ Query.ModuleFile module_ - fmap fold $ - forM maybeFilePath \filePath -> do + fold + <$> forM maybeFilePath \filePath -> do (_, _, defs) <- fetch $ ParsedFile filePath pure $ Resolution.moduleScopes module_ defs ResolvedName module_ surfaceName -> - noError $ do + noError do (privateScope, _) <- fetch $ ModuleScope module_ importedScopeEntry <- fetchImportedName module_ surfaceName pure $ importedScopeEntry <> HashMap.lookup surfaceName privateScope ElaboratingDefinition definitionKind qualifiedName@(Name.Qualified module_ name) -> - nonInput $ do + nonInput do mdef <- fetch $ ParsedDefinition module_ $ Mapped.Query (definitionKind, name) case mdef of Nothing -> @@ -278,7 +279,10 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = forM mtype \_ -> fetch $ ElaboratedType qualifiedName - runElaboratorWithDefault Nothing definitionKind qualifiedName $ + runElaboratorWithDefault + Nothing + definitionKind + qualifiedName case mtype of Nothing -> first Just <$> Elaboration.inferTopLevelDefinition definitionKind qualifiedName def @@ -290,7 +294,7 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = nonInput $ pure (Syntax.Global Builtin.TypeName, mempty) ElaboratedType qualifiedName -> - nonInput $ do + nonInput do mtypeDecl <- fetch $ ElaboratingDefinition Scope.Type qualifiedName case mtypeDecl of Nothing -> do @@ -303,14 +307,14 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = (typeDecl', errs) <- runElaboratorWithDefault (Syntax.TypeDeclaration $ Builtin.unknown Builtin.type_, Builtin.unknown Builtin.type_) Scope.Type qualifiedName $ Elaboration.checkDefinitionMetaSolutions Scope.Type qualifiedName typeDecl type_ metaVars - pure $ + pure case typeDecl' of (Syntax.TypeDeclaration result, _) -> (result, errs) _ -> panic "ElaboratedType: Not a type declaration" ElaboratedDefinition qualifiedName -> - nonInput $ do + nonInput do maybeDef <- fetch $ ElaboratingDefinition Scope.Definition qualifiedName case maybeDef of Nothing -> do @@ -322,12 +326,12 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = Elaboration.checkDefinitionMetaSolutions Scope.Definition qualifiedName def type_ metaVars Dependencies qualifiedName subQuery -> noError $ - Mapped.rule (Dependencies qualifiedName) subQuery $ do + Mapped.rule (Dependencies qualifiedName) subQuery do (def, type_) <- fetch $ ElaboratedDefinition qualifiedName pure $ HashSet.toMap $ Syntax.definitionDependencies def <> Syntax.dependencies type_ TransitiveDependencies qualifiedName subQuery -> noError $ - Mapped.rule (TransitiveDependencies qualifiedName) subQuery $ do + Mapped.rule (TransitiveDependencies qualifiedName) subQuery do let go [] done = pure done go (dep : todo) done | dep `HashSet.member` done = go todo done @@ -340,7 +344,7 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = (HashMap.keys deps) (HashSet.singleton qualifiedName) ConstructorType (Name.QualifiedConstructor dataTypeName constr) -> - noError $ do + noError do (def, _) <- fetch $ ElaboratedDefinition dataTypeName let fail = Builtin.unknown $ Builtin.unknown Builtin.type_ @@ -363,7 +367,7 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = _ -> pure $ Telescope.Empty fail DefinitionPosition definitionKind (Name.Qualified module_ name) -> - noError $ do + noError do positions <- fetch $ ModulePositionMap module_ maybeFilePath <- fetch $ Query.ModuleFile module_ pure @@ -379,13 +383,13 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = definitionKind name LambdaLifted qualifiedName -> - noError $ do + noError do (definition, _) <- fetch $ ElaboratedDefinition qualifiedName runM $ LambdaLifting.liftDefinition qualifiedName definition LambdaLiftedDefinition (Name.Lifted qualifiedName index) -> - noError $ do + noError do (def, liftedDefs) <- fetch $ LambdaLifted qualifiedName - pure $ + pure case index of 0 -> def _ -> @@ -395,24 +399,24 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = index liftedDefs LambdaLiftedModuleDefinitions module_ -> - noError $ do + noError do names <- fetch $ ModuleDefinitions module_ - fmap (OrderedHashSet.fromList . concat) $ - forM (toList names) \name -> do + OrderedHashSet.fromList . concat + <$> forM (toList names) \name -> do let qualifiedName = Name.Qualified module_ name (_, extras) <- fetch $ LambdaLifted qualifiedName pure $ Name.Lifted qualifiedName <$> 0 : EnumMap.keys extras ClosureConverted name -> - noError $ do + noError do definition <- fetch $ LambdaLiftedDefinition name ClosureConversion.convertDefinition definition ClosureConvertedType name -> - noError $ do + noError do definition <- fetch $ ClosureConverted name runM $ ClosureConverted.typeOfDefinition ClosureConverted.Context.empty definition ClosureConvertedConstructorType (Name.QualifiedConstructor dataTypeName constr) -> - noError $ do + noError do definition <- fetch $ ClosureConverted $ Name.Lifted dataTypeName 0 case definition of ClosureConverted.Syntax.DataDefinition _ (ClosureConverted.Syntax.ConstructorDefinitions constrs) -> @@ -441,43 +445,44 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = _ -> panic "ClosureConvertedConstructorType: none-datatype" ClosureConvertedSignature name -> - noError $ do + noError do definition <- fetch $ ClosureConverted name runM $ ClosureConverted.Representation.signature definition ConstructorRepresentations dataTypeName -> noError $ ClosureConverted.Representation.constructorRepresentations dataTypeName ConstructorRepresentation (Name.QualifiedConstructor dataTypeName constr) -> - noError $ do + noError do (boxity, maybeTags) <- fetch $ ConstructorRepresentations dataTypeName pure (boxity, (HashMap.! constr) <$> maybeTags) Assembly name -> - noError $ do + noError do definition <- fetch $ ClosureConverted name runM $ ClosureConvertedToAssembly.generateDefinition name definition HeapAllocates name -> - noError $ do + noError do maybeAssembly <- fetch $ Assembly name case maybeAssembly of Nothing -> pure False Just assembly -> runM $ Assembly.HeapAllocates.run $ Assembly.definitionHeapAllocates assembly AssemblyModule module_ -> - noError $ do + noError do names <- fetch $ LambdaLiftedModuleDefinitions module_ - assemblyDefinitions <- fmap concat $ - forM (toList names) \name -> do - maybeAssembly <- fetch $ Assembly name - pure $ toList $ (name,) <$> maybeAssembly + assemblyDefinitions <- + concat + <$> forM (toList names) \name -> do + maybeAssembly <- fetch $ Assembly name + pure $ toList $ (name,) <$> maybeAssembly moduleInitDefs <- runM $ ClosureConvertedToAssembly.generateModuleInit module_ assemblyDefinitions pure $ moduleInitDefs <> assemblyDefinitions LLVMModule module_ -> - noError $ do + noError do assemblyDefinitions <- fetch $ AssemblyModule module_ pure $ AssemblyToLLVM.assembleModule assemblyDefinitions LLVMModuleInitModule -> - noError $ do + noError do inputFiles <- fetch Query.InputFiles moduleNames <- forM (toList inputFiles) \filePath -> do (moduleName, _, _) <- fetch $ Query.ParsedFile filePath @@ -504,7 +509,7 @@ rules sourceDirectories files readFile_ (Writer (Writer query)) = -> Task Query (a, [Error]) runElaboratorWithDefault default_ definitionKind defName m = do eitherResult <- try $ runM m - pure $ + pure case eitherResult of Left err -> ( default_ diff --git a/src/Span.hs b/src/Span.hs index 88206b7..54a747c 100644 --- a/src/Span.hs +++ b/src/Span.hs @@ -1,6 +1,5 @@ {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE OverloadedStrings #-} module Span where diff --git a/tests/Main.hs b/tests/Main.hs index ebaa19a..adcbc06 100644 --- a/tests/Main.hs +++ b/tests/Main.hs @@ -66,7 +66,7 @@ checkFiles sourceDirectories files = do let prettyError err = do p <- Error.Hydrated.pretty err pure (err, p) - (moduleSources, errs) <- Driver.runTask (HashSet.fromList sourceDirectories) (HashSet.fromList files) prettyError $ do + (moduleSources, errs) <- Driver.runTask (HashSet.fromList sourceDirectories) (HashSet.fromList files) prettyError do Driver.checkAll forM files \filePath -> do moduleSource <- fetch $ Query.FileText filePath @@ -87,7 +87,7 @@ compileFiles optimisationLevel sourceDirectories files = do pure (err, p) Command.Compile.withOutputFile Nothing \outputExecutableFile -> Command.Compile.withAssemblyDirectory Nothing \assemblyDir -> do - (moduleSources, errs) <- Driver.runTask (HashSet.fromList sourceDirectories) (HashSet.fromList files) prettyError $ do + (moduleSources, errs) <- Driver.runTask (HashSet.fromList sourceDirectories) (HashSet.fromList files) prettyError do Driver.checkAll Compiler.compile assemblyDir False outputExecutableFile optimisationLevel forM files \filePath -> do @@ -103,7 +103,7 @@ compileFiles optimisationLevel sourceDirectories files = do filter ((filePath ==) . (.filePath) . fst) errs verifyErrors filePath moduleErrs expectedErrors let expectedOutput = expectedOutputFromSource moduleSource - unless (null expectedOutput) $ do + unless (null expectedOutput) do verifyExecutableOutput filePath (toS executableOutput) $ Text.unlines expectedOutput verifyErrors :: FilePath -> [(Error.Hydrated, Doc ann)] -> HashMap Int [ExpectedError] -> IO () @@ -278,8 +278,8 @@ expectedOutputFromSource sourceText = listDirectoryRecursive :: (FilePath -> Bool) -> FilePath -> IO [FilePath] listDirectoryRecursive p dir = do files <- listDirectory dir - fmap concat $ - forM files \file -> do + concat + <$> forM files \file -> do let path = dir file isDir <- doesDirectoryExist path if isDir @@ -297,9 +297,10 @@ listDirectoriesWithFilesMatching p dir = do then do recursiveFiles <- listDirectoryRecursive p dir pure [(dir, recursiveFiles)] - else fmap concat $ - forM paths \path -> do - isDir <- doesDirectoryExist path - if isDir - then listDirectoriesWithFilesMatching p path - else pure [] + else + concat + <$> forM paths \path -> do + isDir <- doesDirectoryExist path + if isDir + then listDirectoriesWithFilesMatching p path + else pure []