code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
import System.Exit mul [x, y] = xInt * yInt where xInt = read x :: Integer yInt = read y :: Integer mainLoop 0 = exitWith ExitSuccess mainLoop x = do values <- getLine print $ mul (words values) mainLoop (x - 1) main = do loops <- getLine mainLoop (read loops :: Integer)
ranisalt/spoj
mul.hs
Haskell
mit
288
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-} module Main where import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as BS import Data.Map.Strict(Map) import qualified Data.Map.Strict as M import Data.Maybe(fromJust) import Data.Tree(Tree(..), flatten, unfoldTree) import Diagrams.Backend.SVG.CmdLine(defaultMain) import Diagrams.Prelude import GHC.Generics import Control.Applicative import Data.Attoparsec.Char8 -- import Data.Attoparsec.Text -- import qualified Data.HashMap.Strict as HM -- import Data.Scientific (toRealFloat) -- import Data.Text (Text) -- import qualified Data.Text as T -- import qualified Data.Vector as V main = defaultMain $ pad 1.1 $ renderTree buildTree renderTree = mconcat . flatten . fmap drawBranch buildTree = unfoldTree (growTree fs) seed seed = (origin, unitY) drawBranch (p, v) = position [(p, fromOffsets [v])] growTree fs n = if stop n then branchTip n else branches fs n branchTip n = (n, []) branches fs n = (n, zipWith ($) fs (repeat n)) fs = buildXfm symMap rule -- The rule has been transformed from "b r [ < B ] [ > B ]" --rule = [["b", "r", "<"], ["b", "r", ">"]] rule = getRule userRule getRule = elimVars stringToGrammarDef . distribute . parseRule userRule = "b r [ < B ] [ > B ]" symbols = (map toSymbolMap . filter isTerminal) grammar isTerminal (Follow _) = True isTerminal (Scale _ _) = True isTerminal (Turn _ _) = True isTerminal _ = False toSymbolMap (Follow s) = (s, followBranch) toSymbolMap (Scale s r) = (s, scaleBranch r) toSymbolMap (Turn s t) = (s, rotateBranch t) toSymbolMap t = error $ "Bad terminal in toSymbolMap:" ++ show t type SeedVal = ((Double, Double), (Double, Double)) type RuleVal = (String, String) type Grammar = [GrammarDef] data GrammarDef = Var String | Turn String Double | Scale String Double | Follow String | Seed String SeedVal | Rule String RuleVal deriving (Show, Generic) instance FromJSON GrammarDef instance ToJSON GrammarDef -- What I would like: -- jsonInputWanted = -- "[\ -- \{\"b\": {\"follow\":null}},\ -- \{\"r\": {\"scale\": 0.6}},\ -- \{\"<\": {\"turn\": 0.45}},\ -- \{\">\": {\"turn\": -0.45}},\ -- \{\"B\": {\"var\": null}},\ -- \{\"s\": {\"seed\": {\"p\": {\"x\":0, \"y\":0}, \"v\":{\"x\":0, \"y\":1}}}},\ -- \{\"R1\": {\"rule\": {\"B\": \"b r [ < B ] [ > B ]\"}}}\ -- \]" -- What I have to use with generically derived instance jsonInput = "[\ \{\"contents\":\"b\",\"tag\":\"Follow\"},\ \{\"contents\":\"B\",\"tag\":\"Var\"},\ \{\"contents\":[\"r\",0.6],\"tag\":\"Scale\"},\ \{\"contents\":[\"\\u003c\",0.14285714285714],\"tag\":\"Turn\"},\ \{\"contents\":[\"\\u003e\",-0.14285714285714],\"tag\":\"Turn\"},\ \{\"contents\":[\"s\",[[0,0],[0,1]]],\"tag\":\"Seed\"},\ \{\"contents\":[\"R1\",[\"B\" ,\"b r [ < B ] [ > B ]\"]],\"tag\":\"Rule\"}\ \]" parseGrammar j = case decode (BS.pack j) of (Just g) -> g Nothing -> error $ "Bad grammar in JSON: " ++ j grammar = parseGrammar jsonInput toGrammarMap g@(Var s) = (s, g) toGrammarMap g@(Follow s) = (s, g) toGrammarMap g@(Scale s _) = (s, g) toGrammarMap g@(Turn s _) = (s, g) toGrammarMap g@(Seed s _) = (s, g) toGrammarMap g@(Rule s _) = (s, g) stringToGrammarDef = initMap (map toGrammarMap grammar) -- Assumes string has been converted to a list of lists of -- terminal symbols corresponding to transformations. buildXfm :: Map String ((P2, R2) -> (P2, R2)) -> [[String]] -> [(P2, R2) -> (P2, R2)] buildXfm _ [] = [] buildXfm m (xs:xss) = (buildXfm' m id xs) : buildXfm m xss buildXfm' _ f [] = f buildXfm' m f (x:xs) = buildXfm' m (g . f) xs where g = fromJust (M.lookup x m) --parseRule :: Text -> Tree [String] parseRule r = case parseOnly tree r of Left e -> error $ "Could not parse rule: " ++ show r ++ " (" ++ e ++ ")" Right t -> t tree :: Parser (Tree [String]) tree = (do ts <- many1 subTree return $ Node [] ts) <|> (do xs <- flatList ts <- many1 subTree return $ Node xs ts) <|> (do xs <- flatList return $ Node xs []) -- One level of recursion only subTree :: Parser (Tree [String]) subTree = do skipSpace char '[' xs <- flatList skipSpace char ']' return $ Node xs [] flatList :: Parser [String] flatList = many1 idToken idToken :: Parser String idToken = skipSpace >> many1 (satisfy (notInClass "[] \t\n")) -- One level of recursion. distribute (Node p []) = [p] distribute (Node p ts) = map (p ++) (map rootLabel ts) elimVars m = map (filter (not . isVar m)) isVar m s = case M.lookup s m of Just (Var _) -> True otherwise -> False symMap = initMap symbols initMap = foldr updateMap M.empty updateMap (k,f) = M.insert k f stop (_, v) = magnitude v < 0.05 followBranch (p, v) = (p .+^ v, v) scaleBranch s (p, v) = (p, v ^* s) rotateBranch t (p, v) = (p, rotateBy t v)
bobgru/tree-derivations
src/LSystem5.hs
Haskell
mit
5,140
import Test.Hspec import StringCalculator import Control.Exception (evaluate) main :: IO () main = hspec $ do describe "StringCalculator" $ do it "should return 0 for an empty string" $ do calculate "" `shouldBe` 0 it "should return 1 for a string '1'" $ do calculate "1" `shouldBe` 1 it "should return 2 for a string '2'" $ do calculate "2" `shouldBe` 2 it "should return 3 for a string '1,2'" $ do calculate "1,2" `shouldBe` 3 it "should return 6 for a string '1\n2,3'" $ do calculate "1\n2,3" `shouldBe` 6 it "should return 3 for a string of '//;\n1;2'" $ do calculate "//;\n1;2" `shouldBe` 3 it "should throw an exception if a negative number is given" $ do evaluate (calculate "1,-2") `shouldThrow` errorCall "negatives not allowed"
theUniC/string-calculator.hs
tests/Spec.hs
Haskell
mit
890
module Main where import qualified Network as Net import System.IO (Handle, hClose) import System.Environment (getArgs) import Data.ByteString (ByteString) import Control.Monad (forever, unless) import Control.Concurrent.STM (STM, atomically) import Control.Concurrent (ThreadId, forkIO, threadDelay) import Control.Exception (SomeException, catch, finally) import Network.Neks.Disk (saveTo, loadFrom) import Network.Neks.NetPack (netRead, netWrite) import Network.Neks.Message (parseRequests, formatResponses) import Network.Neks.DataStore (DataStore, createStore, insert, get, delete) import Network.Neks.Actions (Request(Set, Get, Delete, Atomic), Reply(Found, NotFound)) type Store = DataStore ByteString ByteString main = do args <- getArgs case args of [] -> serveWithPersistence ["--no-persistence"] -> serveWithoutPersistence ["--help"] -> putStrLn instructions -- To be explicit _ -> putStrLn instructions serveWithPersistence = do loaded <- loadFrom "store.kvs" globalStore <- case loaded of Just store -> return store Nothing -> atomically createStore let periodically action = forever (threadDelay (30*10^6) >> action) forkIO $ periodically (saveTo "store.kvs" globalStore) putStrLn "Serving on port 9999 \nSaving DB to store.kvs" serve globalStore (Net.PortNumber 9999) serveWithoutPersistence = do globalStore <- atomically createStore putStrLn "Serving on port 9999\nNot persisting to disk" serve globalStore (Net.PortNumber 9999) serve :: Store -> Net.PortID -> IO () serve store port = Net.withSocketsDo $ do sock <- Net.listenOn port forever (wait sock store) wait :: Net.Socket -> Store -> IO ThreadId wait sock store = do (client, _, _) <- Net.accept sock forkIO (run client) where run client = (handle client store `finally` hClose client) `catch` exceptionHandler exceptionHandler :: SomeException -> IO () exceptionHandler exception = return () -- Optional exception reporting handle :: Handle -> Store -> IO () handle client store = do result <- processRequests client store case result of Right success -> handle client store Left failure -> return () -- Optional soft error reporting processRequests :: Handle -> Store -> IO (Either String ()) processRequests client store = do requestData <- netRead client case requestData >>= parseRequests of Left err -> return (Left err) Right requests -> do results <- mapM (atomically . processWith store) requests netWrite client . formatResponses . concat $ results return (Right ()) processWith :: Store -> Request -> STM [Reply] processWith store (Set k v) = do insert k v store return [] processWith store (Get k) = do result <- get k store return $ case result of Nothing -> [NotFound] Just v -> [Found v] processWith store (Delete k) = do delete k store return [] processWith store (Atomic requests) = do results <- mapM (processWith store) requests return (concat results) instructions = "Usage: NeksServer <opt-args>\n" ++ "<opt-args> can be empty or can be \"--no-persistence\" to disable storing keys and values on disk"
wyager/Neks
Network/Neks/NeksServer.hs
Haskell
mit
3,546
-------------------------------------------------------------------------- -- Copyright (c) 2007-2010, ETH Zurich. -- All rights reserved. -- -- This file is distributed under the terms in the attached LICENSE file. -- If you do not find this file, copies can be found by writing to: -- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. -- -- Default architecture-specific definitions for Barrelfish -- -------------------------------------------------------------------------- module ArchDefaults where import Data.List import HakeTypes import Path import qualified Config commonFlags = [ Str s | s <- [ "-fno-builtin", "-nostdinc", "-U__linux__", "-Ulinux", "-Wall", "-Wshadow", "-Wmissing-declarations", "-Wmissing-field-initializers", "-Wredundant-decls", "-Werror", "-imacros" ] ] ++ [ NoDep SrcTree "src" "/include/deputy/nodeputy.h" ] commonCFlags = [ Str s | s <- [ "-std=c99", "-U__STRICT_ANSI__", -- for newlib headers "-Wstrict-prototypes", "-Wold-style-definition", "-Wmissing-prototypes" ] ] ++ [ ContStr Config.use_fp "-fno-omit-frame-pointer" ""] commonCxxFlags = [ Str s | s <- [ "-nostdinc++", "-std=c++0x", "-fno-exceptions", "-I" ] ] ++ [ NoDep SrcTree "src" "/include/cxx" ] ++ [ ContStr Config.use_fp "-fno-omit-frame-pointer" ""] cFlags = [ Str s | s <- [ "-Wno-packed-bitfield-compat" ] ] ++ commonCFlags cxxFlags = [ Str s | s <- [ "-Wno-packed-bitfield-compat" ] ] ++ commonCxxFlags cDefines options = [ Str ("-D"++s) | s <- [ "BARRELFISH" ]] ++ Config.defines ++ Config.arch_defines options cStdIncs arch archFamily = [ NoDep SrcTree "src" "/include", NoDep SrcTree "src" ("/include/arch" ./. archFamily), NoDep SrcTree "src" Config.libcInc, NoDep SrcTree "src" "/include/c", NoDep SrcTree "src" ("/include/target" ./. archFamily), NoDep SrcTree "src" Config.lwipxxxInc, -- XXX NoDep SrcTree "src" Config.lwipInc, NoDep InstallTree arch "/include", NoDep InstallTree arch "/include/dev", NoDep SrcTree "src" ".", NoDep BuildTree arch "." ] ldFlags arch = [ Str Config.cOptFlags, In InstallTree arch "/lib/crt0.o", In InstallTree arch "/lib/crtbegin.o", Str "-fno-builtin", Str "-nostdlib" ] ldCxxFlags arch = [ Str Config.cOptFlags, In InstallTree arch "/lib/crt0.o", In InstallTree arch "/lib/crtbegin.o", Str "-fno-builtin", Str "-nostdlib" ] -- Libraries that are linked to all applications. stdLibs arch = [ In InstallTree arch "/lib/libbarrelfish.a", In InstallTree arch "/lib/libterm_client.a", In InstallTree arch "/lib/liboctopus_parser.a", -- XXX: For NS client in libbarrelfish In InstallTree arch "/errors/errno.o", In InstallTree arch ("/lib/lib" ++ Config.libc ++ ".a"), --In InstallTree arch "/lib/libposixcompat.a", --In InstallTree arch "/lib/libvfs.a", --In InstallTree arch "/lib/libnfs.a", --In InstallTree arch "/lib/liblwip.a", --In InstallTree arch "/lib/libbarrelfish.a", --In InstallTree arch "/lib/libcontmng.a", --In InstallTree arch "/lib/libprocon.a", In InstallTree arch "/lib/crtend.o" , In InstallTree arch "/lib/libcollections.a" ] stdCxxLibs arch = [ In InstallTree arch "/lib/libcxx.a", Str "./libsupc++.a" ] ++ stdLibs arch options arch archFamily = Options { optArch = arch, optArchFamily = archFamily, optFlags = cFlags, optCxxFlags = cxxFlags, optDefines = [ Str "-DBARRELFISH" ] ++ Config.defines, optIncludes = cStdIncs arch archFamily, optDependencies = [ PreDep InstallTree arch "/include/errors/errno.h", PreDep InstallTree arch "/include/barrelfish_kpi/capbits.h", PreDep InstallTree arch "/include/asmoffsets.h", PreDep InstallTree arch "/include/trace_definitions/trace_defs.h" ], optLdFlags = ldFlags arch, optLdCxxFlags = ldCxxFlags arch, optLibs = stdLibs arch, optCxxLibs = stdCxxLibs arch, optInterconnectDrivers = ["lmp", "ump", "multihop"], optFlounderBackends = ["lmp", "ump", "multihop"], extraFlags = [], extraDefines = [], extraIncludes = [], extraDependencies = [], extraLdFlags = [], optSuffix = [] } ------------------------------------------------------------------------ -- -- Now, commands to actually do something -- ------------------------------------------------------------------------ -- -- C compiler -- cCompiler arch compiler opts phase src obj = let incls = (optIncludes opts) ++ (extraIncludes opts) flags = (optFlags opts) ++ (optDefines opts) ++ [ Str f | f <- extraFlags opts ] ++ [ Str f | f <- extraDefines opts ] deps = (optDependencies opts) ++ (extraDependencies opts) in [ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ] ++ concat [ [ NStr "-I", i ] | i <- incls ] ++ [ Str "-o", Out arch obj, Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src ] ++ deps -- -- the C preprocessor, like C compiler but with -E -- cPreprocessor arch compiler opts phase src obj = let incls = (optIncludes opts) ++ (extraIncludes opts) flags = (optFlags opts) ++ (optDefines opts) ++ [ Str f | f <- extraFlags opts ] ++ [ Str f | f <- extraDefines opts ] deps = (optDependencies opts) ++ (extraDependencies opts) cOptFlags = unwords ((words Config.cOptFlags) \\ ["-g"]) in [ Str compiler ] ++ flags ++ [ Str cOptFlags ] ++ concat [ [ NStr "-I", i ] | i <- incls ] ++ [ Str "-o", Out arch obj, Str "-E", In (if phase == "src" then SrcTree else BuildTree) phase src ] ++ deps -- -- C++ compiler -- cxxCompiler arch cxxcompiler opts phase src obj = let incls = (optIncludes opts) ++ (extraIncludes opts) flags = (optCxxFlags opts) ++ (optDefines opts) ++ [ Str f | f <- extraFlags opts ] ++ [ Str f | f <- extraDefines opts ] deps = (optDependencies opts) ++ (extraDependencies opts) in [ Str cxxcompiler ] ++ flags ++ [ Str Config.cOptFlags ] ++ concat [ [ NStr "-I", i ] | i <- incls ] ++ [ Str "-o", Out arch obj, Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src ] ++ deps -- -- Create C file dependencies -- makeDepend arch compiler opts phase src obj depfile = let incls = (optIncludes opts) ++ (extraIncludes opts) flags = (optFlags opts) ++ (optDefines opts) ++ [ Str f | f <- extraFlags opts ] ++ [ Str f | f <- extraDefines opts ] in [ Str ('@':compiler) ] ++ flags ++ concat [ [ NStr "-I", i ] | i <- incls ] ++ (optDependencies opts) ++ (extraDependencies opts) ++ [ Str "-M -MF", Out arch depfile, Str "-MQ", NoDep BuildTree arch obj, Str "-MQ", NoDep BuildTree arch depfile, Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src ] -- -- Create C++ file dependencies -- makeCxxDepend arch cxxcompiler opts phase src obj depfile = let incls = (optIncludes opts) ++ (extraIncludes opts) flags = (optCxxFlags opts) ++ (optDefines opts) ++ [ Str f | f <- extraFlags opts ] ++ [ Str f | f <- extraDefines opts ] in [ Str ('@':cxxcompiler) ] ++ flags ++ concat [ [ NStr "-I", i ] | i <- incls ] ++ (optDependencies opts) ++ (extraDependencies opts) ++ [ Str "-M -MF", Out arch depfile, Str "-MQ", NoDep BuildTree arch obj, Str "-MQ", NoDep BuildTree arch depfile, Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src ] -- -- Compile a C program to assembler -- cToAssembler :: String -> String -> Options -> String -> String -> String -> String -> [ RuleToken ] cToAssembler arch compiler opts phase src afile objdepfile = let incls = (optIncludes opts) ++ (extraIncludes opts) flags = (optFlags opts) ++ (optDefines opts) ++ [ Str f | f <- extraFlags opts ] ++ [ Str f | f <- extraDefines opts ] deps = [ Dep BuildTree arch objdepfile ] ++ (optDependencies opts) ++ (extraDependencies opts) in [ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ] ++ concat [ [ NStr "-I", i ] | i <- incls ] ++ [ Str "-o ", Out arch afile, Str "-S ", In (if phase == "src" then SrcTree else BuildTree) phase src ] ++ deps -- -- Assemble an assembly language file -- assembler :: String -> String -> Options -> String -> String -> [ RuleToken ] assembler arch compiler opts src obj = let incls = (optIncludes opts) ++ (extraIncludes opts) flags = (optFlags opts) ++ (optDefines opts) ++ [ Str f | f <- extraFlags opts ] ++ [ Str f | f <- extraDefines opts ] deps = (optDependencies opts) ++ (extraDependencies opts) in [ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ] ++ concat [ [ NStr "-I", i ] | i <- incls ] ++ [ Str "-o ", Out arch obj, Str "-c ", In SrcTree "src" src ] ++ deps -- -- Create a library from a set of object files -- archive :: String -> Options -> [String] -> [String] -> String -> String -> [ RuleToken ] archive arch opts objs libs name libname = [ Str "rm -f ", Out arch libname ] ++ [ NL, Str "ar cr ", Out arch libname ] ++ [ In BuildTree arch o | o <- objs ] ++ if libs == [] then [] else ( [ NL, Str ("rm -fr tmp-" ++ arch ++ name ++ "; mkdir tmp-" ++ arch ++ name) ] ++ [ NL, Str ("cd tmp-" ++ arch ++ name ++ "; for i in ") ] ++ [ In BuildTree arch a | a <- libs ] ++ [ Str "; do ar x ../$$i; done" ] ++ [ NL, Str "ar q ", Out arch libname, Str (" tmp-" ++ arch ++ name ++ "/*.o") ] ++ [ NL, Str ("rm -fr tmp-" ++ arch ++ name) ] ) ++ [ NL, Str "ranlib ", Out arch libname ] -- -- Link an executable -- linker :: String -> String -> Options -> [String] -> [String] -> String -> [RuleToken] linker arch compiler opts objs libs bin = [ Str compiler ] ++ (optLdFlags opts) ++ (extraLdFlags opts) ++ [ Str "-o", Out arch bin ] ++ [ In BuildTree arch o | o <- objs ] ++ [ In BuildTree arch l | l <- libs ] ++ (optLibs opts) -- -- Link an executable -- cxxlinker :: String -> String -> Options -> [String] -> [String] -> String -> [RuleToken] cxxlinker arch cxxcompiler opts objs libs bin = [ Str cxxcompiler ] ++ (optLdCxxFlags opts) ++ (extraLdFlags opts) ++ [ Str "-o", Out arch bin ] ++ [ In BuildTree arch o | o <- objs ] ++ [ In BuildTree arch l | l <- libs ] ++ (optCxxLibs opts)
UWNetworksLab/arrakis
hake/ArchDefaults.hs
Haskell
mit
11,931
{-# LANGUAGE QuasiQuotes, ScopedTypeVariables #-} module Handler.EntryPics where import Import import Utils.Database import qualified Hasql as H import qualified Data.Text as T getEntryPicsR :: Int -> Handler Html getEntryPicsR entryId = do dbres <- liftIO $ do conn <- getDbConn H.session conn $ H.tx Nothing $ do (images :: [(Int,T.Text)]) <- H.listEx $ [H.stmt| SELECT id , ext FROM images WHERE entry_id = ? AND img_type = 'entry' ORDER BY id ASC |] entryId return images case dbres of Left err -> error $ show err Right images -> defaultLayout $ do setTitle $ "Entry Images | Brandreth Guestbook" $(widgetFile "entrypics")
dgonyeo/brandskell
Handler/EntryPics.hs
Haskell
mit
860
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Numeric.Natural.Compat" -- from a globally unique namespace. module Numeric.Natural.Compat.Repl ( module Numeric.Natural.Compat ) where import "this" Numeric.Natural.Compat
haskell-compat/base-compat
base-compat/src/Numeric/Natural/Compat/Repl.hs
Haskell
mit
292
{-# LANGUAGE BangPatterns #-} {- | - Module : Memo - Description : Infinite memorization tree structure - Copyright : (c) Maciej Bendkowski - - Maintainer : maciej.bendkowski@gmail.com - Stability : experimental -} module Memo ( Tree(..), idx, nats, toList ) where -- | An infinite binary tree data structure -- with additional functor capabilities data Tree a = Tree (Tree a) a (Tree a) instance Functor Tree where fmap f (Tree l x r) = Tree (fmap f l) (f x) (fmap f r) -- | Tree indexer idx :: Tree a -> Int -> a idx (Tree _ x _) 0 = x idx (Tree l _ r) k = case (k-1) `divMod` 2 of (k', 0) -> idx l k' (k', _) -> idx r k' -- | Natural numbers represented in an -- infinite binary tree nats :: Tree Int nats = f 0 1 where f :: Int -> Int -> Tree Int f !k !s = Tree (f l s') k (f r s') where l = k + s r = l + s s' = s * 2 -- | Tree to list converter toList :: Tree a -> [a] toList ts = map (idx ts) [0..]
maciej-bendkowski/blaz
src/Memo.hs
Haskell
mit
1,080
module YesNo ( YesNo ) where import Tree import TrafficLight class YesNo a where yesno :: a -> Bool instance YesNo Int where yesno 0 = False yesno _ = True instance YesNo [ a ] where yesno [] = False yesno _ = True instance YesNo Bool where yesno = id -- Function 'id' means identity, get argument and return the same thing. instance YesNo (Maybe a) where yesno (Just _) = True yesno Nothing = False instance YesNo (Tree a) where yesno EmptyTree = False yesno _ = True instance YesNo TrafficLight where yesno Red = False yesno _ = True yesnoIf :: (YesNo y) => y -> a -> a -> a yesnoIf yesnoVal yesResult noResult = if yesno yesnoVal then yesResult else noResult
afronski/playground-fp
books/learn-you-a-haskell-for-great-good/making-our-own-types-and-typeclasses/YesNo.hs
Haskell
mit
713
{-# OPTIONS_GHC -O0 #-} {-# LANGUAGE CPP, DeriveGeneric, DeriveDataTypeable, LambdaCase, MagicHash, StandaloneDeriving #-} #ifndef __GHCJS__ {-# LANGUAGE PackageImports #-} #endif {- | Communication between the compiler (GHCJS) and runtime (on node.js) for Template Haskell -} module GHCJS.Prim.TH.Types ( Message(..) , THResultType(..) ) where import Prelude import Data.Binary import Data.ByteString (ByteString) import Data.Data import GHC.Generics import GHCi.TH.Binary () #if defined(__GHCJS__) || !defined(MIN_VERSION_template_haskell_ghcjs) import qualified Language.Haskell.TH as TH import qualified Language.Haskell.TH.Syntax as TH #else import qualified "template-haskell-ghcjs" Language.Haskell.TH as TH import qualified "template-haskell-ghcjs" Language.Haskell.TH.Syntax as TH #endif data THResultType = THExp | THPat | THType | THDec | THAnnWrapper deriving (Enum, Show, Data, Generic) data Message -- | compiler to node requests = RunTH THResultType ByteString (Maybe TH.Loc) | FinishTH Bool -- ^ also stop runner (False to just clean up at end of module) -- | node to compiler responses | RunTH' ByteString -- ^ serialized result | FinishTH' Int -- ^ memory consumption -- | node to compiler requests | NewName String | Report Bool String | LookupName Bool String | Reify TH.Name | ReifyInstances TH.Name [TH.Type] | ReifyRoles TH.Name | ReifyAnnotations TH.AnnLookup | ReifyModule TH.Module | ReifyFixity TH.Name | ReifyConStrictness TH.Name | AddForeignFilePath TH.ForeignSrcLang String | AddDependentFile FilePath | AddTempFile String | AddTopDecls [TH.Dec] | AddCorePlugin String | IsExtEnabled TH.Extension | ExtsEnabled -- | compiler to node responses | NewName' TH.Name | Report' | LookupName' (Maybe TH.Name) | Reify' TH.Info | ReifyInstances' [TH.Dec] | ReifyRoles' [TH.Role] | ReifyAnnotations' [ByteString] | ReifyModule' TH.ModuleInfo | ReifyFixity' (Maybe TH.Fixity) | ReifyConStrictness' [TH.DecidedStrictness] | AddForeignFilePath' | AddDependentFile' | AddTempFile' FilePath | AddTopDecls' | AddCorePlugin' | IsExtEnabled' Bool | ExtsEnabled' [TH.Extension] | QFail' | QCompilerException' Int String -- ^ exception id and result of showing the exception -- | error recovery | StartRecover | EndRecover Bool -- ^ true for recovery action taken | StartRecover' | EndRecover' -- | exit with error status | QFail String -- ^ monadic fail called | QUserException String -- ^ exception in user code | QCompilerException Int -- ^ exception originated on compiler side deriving (Generic) -- deriving instance Generic TH.ForeignSrcLang instance Binary TH.Extension instance Binary TH.ForeignSrcLang instance Binary THResultType instance Binary Message
ghcjs/ghcjs
lib/ghcjs-th/GHCJS/Prim/TH/Types.hs
Haskell
mit
3,274
import AdventOfCode (readInputFile) import Control.Monad (foldM) import Data.Char (isDigit) import Text.Read (readMaybe) data JsonNest = Object Bool | Array deriving (Show) -- Left are for possible but malformed input strings, like } or ]. -- error are for invalid states that no input string, well-formed or malformed, should ever cause. sums :: String -> Either String (Int, Int) sums s = foldM parse empty s >>= expectOneSum where expectOneSum r = case objSum r of [a] -> Right (total r, a) [] -> error ("should always have 1+ objSums: " ++ show r) _ -> Left ("too many sums (unclosed object): " ++ show r) data ParseState = ParseState { objSum :: [Int] , total :: !Int , nest :: [JsonNest] , inString :: Bool , numBuf :: String , redStart :: Int , redGood :: Int , idx :: Int } deriving Show empty :: ParseState empty = ParseState { objSum = [0] , total = 0 , nest = [] , inString = False , numBuf = "" , redStart = 0 , redGood = 0 , idx = 0 } pushNest :: JsonNest -> ParseState -> ParseState pushNest state ps = ps { nest = state : nest ps } parseNum :: ParseState -> Either String ParseState parseNum ps@ParseState { numBuf = "" } = Right ps parseNum ps@ParseState { objSum = [] } = error ("should always have 1+ objSums: " ++ show ps) parseNum ps@ParseState { total = t, objSum = o:os, numBuf = bf } = case readMaybe (reverse bf) of Just i -> Right (ps { total = t + i, objSum = (o + i):os, numBuf = "" }) Nothing -> Left ("not a number: " ++ bf) closeObj :: ParseState -> Either String ParseState closeObj ps@ParseState { objSum = a:b:os, nest = Object red:ns } = Right (ps { objSum = (b + if red then 0 else a):os, nest = ns }) closeObj ps@ParseState { nest = Object _:_ } = error ("should always have 2+ objSums when closing obj: " ++ show ps) closeObj ps = Left ("invalid close obj: " ++ show ps) closeArray :: ParseState -> Either String ParseState closeArray ps@ParseState { nest = Array:ns } = Right (ps { nest = ns }) closeArray ps = Left ("invalid close array: " ++ show ps) parse :: ParseState -> Char -> Either String ParseState parse ps c = fmap (\p -> p { idx = idx p + 1 }) (parseC c ps) incRedGood :: ParseState -> Either a ParseState incRedGood ps = Right (ps { redGood = redGood ps + 1 }) parseC :: Char -> ParseState -> Either String ParseState -- in string parseC c ps@ParseState { inString = True } = case (c, ps) of ('r', _) | redStart ps + 1 == idx ps -> incRedGood ps ('e', _) | redStart ps + 2 == idx ps -> incRedGood ps ('d', _) | redStart ps + 3 == idx ps -> incRedGood ps -- "red" ('"', ParseState { nest = Object _:ns, redGood = 3 }) | redStart ps + 4 == idx ps -> -- assumes that there is never a key "red" Right (ps { nest = Object True:ns, inString = False }) -- any other close quote ('"', _) -> Right (ps { inString = False }) _ -> Right ps -- not in string parseC '{' ps = Right (pushNest (Object False) ps { objSum = 0:objSum ps }) parseC '}' ps = parseNum ps >>= closeObj parseC '[' ps = Right (pushNest Array ps) parseC ']' ps = parseNum ps >>= closeArray parseC ',' ps = parseNum ps parseC '"' ps = Right (ps { inString = True, redGood = 0, redStart = idx ps }) parseC c ps | c == '-' || isDigit c = Right (ps { numBuf = c:numBuf ps }) parseC ':' ps = Right ps parseC '\n' ps = Right ps parseC c _ = Left ("invalid char: " ++ [c]) main :: IO () main = do s <- readInputFile case sums s of Right (a, b) -> print a >> print b Left err -> putStrLn err
petertseng/adventofcode-hs
bin/12_json_numbers.hs
Haskell
apache-2.0
3,487
{- Copyright 2015 Tristan Aubrey-Jones Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} import Compiler.Front.Common import Compiler.Front.Indices (IdxMonad) import Compiler.Planner.SolExec import Compiler.Planner.SearchCache import Compiler.Planner.Searches import Data.List (isSuffixOf, intercalate) import qualified Data.Map.Strict as Data.Map import qualified Data.IntMap.Strict as IM import System.Directory import Control.Monad.State.Strict (lift) import Data.Functor.Identity (runIdentity) import Data.Maybe (isJust, isNothing) import System.IO import System.Exit (exitFailure) import Data.Time.Clock import System.Environment (getArgs) putStrE = hPutStr stderr search :: String -> SCacheM String search dir = do -- load cache loadCache dir -- do exaustive search tryAllSearches -- display result return "" main2 :: IdxMonad IO () main2 = do -- get dir from command line args args <- lift $ getArgs let subDir = (if (length args < 1) then "search7" else head args) -- init dir lift $ putStrE $ "PerformanceFeedback code gen from solution source: " ++ subDir ++ "\n" let relDir = "/Compiler/Tests/PfFb/" ++ subDir curDir <- lift $ getCurrentDirectory let dir = curDir ++ relDir -- load context ctx <- loadContext dir -- run with cache msg <- lift $ runWithCache (setSolCtx ctx >> search dir) -- display message lift $ putStr $ msg return () main :: IO () main = do evalIdxStateT 0 main2 return ()
flocc-net/flocc
v0.1/Compiler/Tests/PfFb/Run2.hs
Haskell
apache-2.0
1,951
data Position t = Position t deriving (Show) stagger (Position d) = Position (d + 2) crawl (Position d) = Position (d + 1) rtn x = x x >>== f = f x
fbartnitzek/notes
7_languages/Haskell/drunken-monad.hs
Haskell
apache-2.0
149
module Routes.Header where import Text.Blaze.Html -- local import Session import Html.Header buildHeaderHtml :: ServerT Html buildHeaderHtml = do return $ headerHtml
mcmaniac/blog.nils.cc
src/Routes/Header.hs
Haskell
apache-2.0
173
{-# LANGUAGE DeriveGeneric #-} module Model.JsonTypes.Turn ( Turn(..) , jsonTurn ) where import Data.Aeson (ToJSON) import Database.Persist.Sql (Entity(..)) import Data.Time.Clock (UTCTime) import GHC.Generics (Generic) import qualified Model.SqlTypes as SqlT import Query.Util (integerKey) data Turn = Turn { userId :: Integer , startDate :: UTCTime } deriving (Show, Generic) instance ToJSON Turn jsonTurn :: Entity SqlT.Turn -> Turn jsonTurn (Entity _turnId turn) = Turn { userId = integerKey . SqlT.turnUserId $ turn , startDate = SqlT.turnStartDate turn }
flatrapp/core
app/Model/JsonTypes/Turn.hs
Haskell
apache-2.0
717
s :: [Int] s = map (2^) [0..] bin :: Int -> [Int] bin 0 = [] bin x = (x `mod` 2):(bin $ x `div` 2) tak [] = [] tak ((0,s):xs) = tak xs tak ((1,s):xs) = s:(tak xs) ans x = tak $ zip (bin x) s main = do c <- getContents let i = map read $ lines c :: [Int] o = map ans i mapM_ putStrLn $ map unwords $ map (map show) o
a143753/AOJ
0031.hs
Haskell
apache-2.0
334
-- Copyright 2020 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- An alternate version of chain3 that depends on Chain2Conflict. module Chain3Alternate (chain3) where import qualified Chain2Conflict as X chain3 o = appendFile o "3"
google/hrepl
hrepl/tests/Chain3Alternate.hs
Haskell
apache-2.0
760
{-# LANGUAGE OverloadedStrings #-} -- This is needed so that we can have constraints in type synonyms. {-# LANGUAGE RankNTypes #-} module Main where import Network.Wreq import Control.Lens import Data.Aeson.Lens (_String, _Array, key) main :: IO() main = do r <- get "https://api.github.com/users/prt2121/repos" putStrLn $ show $ r ^.. responseBody . _Array . traverse . key "git_url" . _String -- putStrLn $ show $ r ^? responseBody . _Array . traverse . key "git_url" . _String -- ^? -- Perform a safe head of a Fold or Traversal or retrieve Just the result from a Getter or Lens. -- ^.. -- (^..) :: s -> Getting (Endo [a]) s a -> [a] -- A convenient infix (flipped) version of toListOf -- toListOf :: Getting (Endo [a]) s a -> s -> [a] Source -- -- Extract a list of the targets of a Fold. See also (^..). -- -- toList ≡ toListOf folded -- (^..) ≡ flip toListOf -- Traversals are Lenses which focus on multiple targets simultaneously -- Operators that begin with ^ are kinds of views. -- https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens-starter-tutorial
prt2121/haskell-practice
httpee/src/Main.hs
Haskell
apache-2.0
1,117
{-# LANGUAGE TupleSections #-} module Evolution where import System.Random import Control.Monad import Control.Arrow import Data.List import Data.Ord --import Data.MList type Probability = Double type FitnessValue = Double type Quantile = Double type FitnessFunction a = a -> FitnessValue type ReproducingFunction a = [a] -> [a] type ReproductivePressureFunction = Quantile -> Probability type Population a = [a] boolChance :: Double -> IO Bool boolChance p = liftM (p <) (randomRIO (0.0,100.0)) assignQuantile :: [a] -> [(a, Quantile)] assignQuantile xs = zipWith divByLen xs ([0..]::[Integer]) where len = fromIntegral $ length xs divByLen e i = (e, fromIntegral i / len) deleteAt :: Int -> [a] -> [a] deleteAt i xs = take (i-1) xs ++ drop (i+1) xs shuffle :: [a] -> IO [a] shuffle [] = return [] shuffle xs = do ind <- randomRIO (0, length xs - 1) rest <- shuffle (deleteAt ind xs) return $! (xs !! ind) : rest chop :: Int -> [a] -> [[a]] chop _ [] = [] chop n xs = take n xs : chop n (drop n xs) evolution :: FitnessFunction a -> ReproducingFunction a -> ReproductivePressureFunction -> Population a -> IO (Population a) evolution fitness reproduce pressure pop = let doesReproduce = second (boolChance . pressure) fitnessSorted = assignQuantile $ sortBy (comparing fitness) pop chosenPop = liftM (map fst) $ filterM snd $ map doesReproduce fitnessSorted chosenPairs = liftM (chop 2) $ shuffle =<< chosenPop newGen = liftM (concatMap reproduce) chosenPairs --futureGens = newGen >>= evolution fitness reproduce pressure in --newGen :# futureGens newGen
jtapolczai/Scratchpad
src/Evolution.hs
Haskell
apache-2.0
1,717
module Data.IORef ( IORef, newIORef, readIORef, writeIORef, modifyIORef, modifyIORef', atomicModifyIORef, atomicModifyIORef', atomicWriteIORef ) where import System.Mock.IO.Internal
3of8/mockio
New_IORef.hs
Haskell
bsd-2-clause
190
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QCursor.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:16 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QCursor ( QqCursor(..) ,QqCursor_nf(..) ,bitmap ,qCursorPos, qqCursorPos ,QqCursorSetPos(..), qqCursorSetPos ,qCursor_delete ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqCursor x1 where qCursor :: x1 -> IO (QCursor ()) instance QqCursor (()) where qCursor () = withQCursorResult $ qtc_QCursor foreign import ccall "qtc_QCursor" qtc_QCursor :: IO (Ptr (TQCursor ())) instance QqCursor ((QPixmap t1)) where qCursor (x1) = withQCursorResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor1 cobj_x1 foreign import ccall "qtc_QCursor1" qtc_QCursor1 :: Ptr (TQPixmap t1) -> IO (Ptr (TQCursor ())) instance QqCursor ((QCursor t1)) where qCursor (x1) = withQCursorResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor2 cobj_x1 foreign import ccall "qtc_QCursor2" qtc_QCursor2 :: Ptr (TQCursor t1) -> IO (Ptr (TQCursor ())) instance QqCursor ((CursorShape)) where qCursor (x1) = withQCursorResult $ qtc_QCursor3 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QCursor3" qtc_QCursor3 :: CLong -> IO (Ptr (TQCursor ())) instance QqCursor ((QBitmap t1, QBitmap t2)) where qCursor (x1, x2) = withQCursorResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCursor4 cobj_x1 cobj_x2 foreign import ccall "qtc_QCursor4" qtc_QCursor4 :: Ptr (TQBitmap t1) -> Ptr (TQBitmap t2) -> IO (Ptr (TQCursor ())) instance QqCursor ((QPixmap t1, Int)) where qCursor (x1, x2) = withQCursorResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor5 cobj_x1 (toCInt x2) foreign import ccall "qtc_QCursor5" qtc_QCursor5 :: Ptr (TQPixmap t1) -> CInt -> IO (Ptr (TQCursor ())) instance QqCursor ((QBitmap t1, QBitmap t2, Int)) where qCursor (x1, x2, x3) = withQCursorResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCursor6 cobj_x1 cobj_x2 (toCInt x3) foreign import ccall "qtc_QCursor6" qtc_QCursor6 :: Ptr (TQBitmap t1) -> Ptr (TQBitmap t2) -> CInt -> IO (Ptr (TQCursor ())) instance QqCursor ((QPixmap t1, Int, Int)) where qCursor (x1, x2, x3) = withQCursorResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor7 cobj_x1 (toCInt x2) (toCInt x3) foreign import ccall "qtc_QCursor7" qtc_QCursor7 :: Ptr (TQPixmap t1) -> CInt -> CInt -> IO (Ptr (TQCursor ())) instance QqCursor ((QBitmap t1, QBitmap t2, Int, Int)) where qCursor (x1, x2, x3, x4) = withQCursorResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCursor8 cobj_x1 cobj_x2 (toCInt x3) (toCInt x4) foreign import ccall "qtc_QCursor8" qtc_QCursor8 :: Ptr (TQBitmap t1) -> Ptr (TQBitmap t2) -> CInt -> CInt -> IO (Ptr (TQCursor ())) class QqCursor_nf x1 where qCursor_nf :: x1 -> IO (QCursor ()) instance QqCursor_nf (()) where qCursor_nf () = withObjectRefResult $ qtc_QCursor instance QqCursor_nf ((QPixmap t1)) where qCursor_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor1 cobj_x1 instance QqCursor_nf ((QCursor t1)) where qCursor_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor2 cobj_x1 instance QqCursor_nf ((CursorShape)) where qCursor_nf (x1) = withObjectRefResult $ qtc_QCursor3 (toCLong $ qEnum_toInt x1) instance QqCursor_nf ((QBitmap t1, QBitmap t2)) where qCursor_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCursor4 cobj_x1 cobj_x2 instance QqCursor_nf ((QPixmap t1, Int)) where qCursor_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor5 cobj_x1 (toCInt x2) instance QqCursor_nf ((QBitmap t1, QBitmap t2, Int)) where qCursor_nf (x1, x2, x3) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCursor6 cobj_x1 cobj_x2 (toCInt x3) instance QqCursor_nf ((QPixmap t1, Int, Int)) where qCursor_nf (x1, x2, x3) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor7 cobj_x1 (toCInt x2) (toCInt x3) instance QqCursor_nf ((QBitmap t1, QBitmap t2, Int, Int)) where qCursor_nf (x1, x2, x3, x4) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QCursor8 cobj_x1 cobj_x2 (toCInt x3) (toCInt x4) bitmap :: QCursor a -> (()) -> IO (QBitmap ()) bitmap x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_bitmap cobj_x0 foreign import ccall "qtc_QCursor_bitmap" qtc_QCursor_bitmap :: Ptr (TQCursor a) -> IO (Ptr (TQBitmap ())) instance QhotSpot (QCursor a) (()) where hotSpot x0 () = withPointResult $ \cpoint_ret_x cpoint_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_hotSpot_qth cobj_x0 cpoint_ret_x cpoint_ret_y foreign import ccall "qtc_QCursor_hotSpot_qth" qtc_QCursor_hotSpot_qth :: Ptr (TQCursor a) -> Ptr CInt -> Ptr CInt -> IO () instance QqhotSpot (QCursor a) (()) where qhotSpot x0 () = withQPointResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_hotSpot cobj_x0 foreign import ccall "qtc_QCursor_hotSpot" qtc_QCursor_hotSpot :: Ptr (TQCursor a) -> IO (Ptr (TQPoint ())) instance Qmask (QCursor a) (()) (IO (QBitmap ())) where mask x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_mask cobj_x0 foreign import ccall "qtc_QCursor_mask" qtc_QCursor_mask :: Ptr (TQCursor a) -> IO (Ptr (TQBitmap ())) instance Qmask_nf (QCursor a) (()) (IO (QBitmap ())) where mask_nf x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_mask cobj_x0 instance Qpixmap (QCursor ()) (()) where pixmap x0 () = withQPixmapResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_pixmap cobj_x0 foreign import ccall "qtc_QCursor_pixmap" qtc_QCursor_pixmap :: Ptr (TQCursor a) -> IO (Ptr (TQPixmap ())) instance Qpixmap (QCursorSc a) (()) where pixmap x0 () = withQPixmapResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_pixmap cobj_x0 instance Qpixmap_nf (QCursor ()) (()) where pixmap_nf x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_pixmap cobj_x0 instance Qpixmap_nf (QCursorSc a) (()) where pixmap_nf x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_pixmap cobj_x0 qCursorPos :: (()) -> IO (Point) qCursorPos () = withPointResult $ \cpoint_ret_x cpoint_ret_y -> qtc_QCursor_pos_qth cpoint_ret_x cpoint_ret_y foreign import ccall "qtc_QCursor_pos_qth" qtc_QCursor_pos_qth :: Ptr CInt -> Ptr CInt -> IO () qqCursorPos :: (()) -> IO (QPoint ()) qqCursorPos () = withQPointResult $ qtc_QCursor_pos foreign import ccall "qtc_QCursor_pos" qtc_QCursor_pos :: IO (Ptr (TQPoint ())) class QqCursorSetPos x1 where qCursorSetPos :: x1 -> IO () instance QqCursorSetPos ((Int, Int)) where qCursorSetPos (x1, x2) = qtc_QCursor_setPos1 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QCursor_setPos1" qtc_QCursor_setPos1 :: CInt -> CInt -> IO () instance QqCursorSetPos ((Point)) where qCursorSetPos (x1) = withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QCursor_setPos_qth cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QCursor_setPos_qth" qtc_QCursor_setPos_qth :: CInt -> CInt -> IO () qqCursorSetPos :: ((QPoint t1)) -> IO () qqCursorSetPos (x1) = withObjectPtr x1 $ \cobj_x1 -> qtc_QCursor_setPos cobj_x1 foreign import ccall "qtc_QCursor_setPos" qtc_QCursor_setPos :: Ptr (TQPoint t1) -> IO () instance QsetShape (QCursor a) ((CursorShape)) where setShape x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_setShape cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QCursor_setShape" qtc_QCursor_setShape :: Ptr (TQCursor a) -> CLong -> IO () instance Qshape (QCursor a) (()) (IO (CursorShape)) where shape x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_shape cobj_x0 foreign import ccall "qtc_QCursor_shape" qtc_QCursor_shape :: Ptr (TQCursor a) -> IO CLong qCursor_delete :: QCursor a -> IO () qCursor_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QCursor_delete cobj_x0 foreign import ccall "qtc_QCursor_delete" qtc_QCursor_delete :: Ptr (TQCursor a) -> IO ()
keera-studios/hsQt
Qtc/Gui/QCursor.hs
Haskell
bsd-2-clause
8,833
{-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} -- | An example of how to do LDAP logins with ldap-client. -- -- First, the assumptions this example makes. It defaults to LDAP over TLS, -- so if you only have a plaintext server, please replace `Secure` with `Plain`. -- It also assumes the accounts you may want to log in as all have -- `objectClass` "Person". -- -- To run the example you have to provide a bunch of environment variables: -- -- - `HOST` is the LDAP host to connect to (without "ldap://", "ldaps://", etc). -- - `POST` is the port LDAP server listens on. -- - `MANAGER_DN` is the DN of the account the first bind is made with. -- - `MANAGER_PASSWORD` is its password. -- - `BASE_OBJECT` is the search root module Main (main) where import Control.Exception (bracket_) -- base import Control.Monad (when) -- base import Data.Function (fix) -- base import Data.Text (Text) -- text import qualified Data.Text.Encoding as Text -- text import qualified Data.Text.IO as Text -- text import Env -- envparse import Ldap.Client as Ldap -- ldap-client import qualified Ldap.Client.Bind as Ldap -- ldap-client import System.Exit (die) -- base import qualified System.IO as IO -- base data Conf = Conf { host :: String , port :: PortNumber , dn :: Dn , password :: Password , base :: Dn } deriving (Show, Eq) getConf :: IO Conf getConf = Env.parse (header "LDAP login example") $ Conf <$> var str "HOST" (help "LDAP hostname") <*> var (fmap fromIntegral . auto) "PORT" (help "LDAP port") <*> var (fmap Ldap.Dn . str) "MANAGER_DN" (help "Manager login DN") <*> var (fmap Ldap.Password . str) "MANAGER_PASSWORD" (help "Manager password") <*> var (fmap Ldap.Dn . str) "BASE_OBJECT" (help "Search root") main :: IO () main = do conf <- getConf res <- login conf case res of Left e -> die (show e) Right _ -> return () login :: Conf -> IO (Either LdapError ()) login conf = Ldap.with (Ldap.Secure (host conf)) (port conf) $ \l -> do Ldap.bind l (dn conf) (password conf) fix $ \loop -> do uid <- prompt "Username: " us <- Ldap.search l (base conf) (typesOnly True) (And [ Attr "objectClass" := "Person" , Attr "uid" := Text.encodeUtf8 uid ]) [] case us of SearchEntry udn _ : _ -> fix $ \loop' -> do pwd <- bracket_ hideOutput showOutput (do pwd <- prompt ("Password for ‘" <> uid <> "’: ") Text.putStr "\n" return pwd) res <- Ldap.bindEither l udn (Password (Text.encodeUtf8 pwd)) case res of Left _ -> do again <- question "Invalid password. Try again? [y/n] " when again loop' Right _ -> Text.putStrLn "OK" [] -> do again <- question "Invalid username. Try again? [y/n] " when again loop prompt :: Text -> IO Text prompt msg = do Text.putStr msg; IO.hFlush IO.stdout; Text.getLine question :: Text -> IO Bool question msg = fix $ \loop -> do res <- prompt msg case res of "y" -> return True "n" -> return False _ -> do Text.putStrLn "Please, answer either ‘y’ or ‘n’."; loop hideOutput, showOutput :: IO () hideOutput = IO.hSetEcho IO.stdout False showOutput = IO.hSetEcho IO.stdout True
VictorDenisov/ldap-client
example/login.hs
Haskell
bsd-2-clause
3,786
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} module Math.Budget.Lens.FixedIntervalL where import Math.Budget.FixedPeriod class FixedIntervalL cat target | target -> cat where fixedIntervalL :: cat target FixedPeriod
tonymorris/hbudget
src/Math/Budget/Lens/FixedIntervalL.hs
Haskell
bsd-3-clause
239
{-# LANGUAGE FlexibleContexts #-} -- for parsec 3 import SICP.LispParser import SICP.DB import Text.Parsec hiding (space) import Data.MultiSet (MultiSet) import qualified Data.MultiSet as MultiSet import Control.Monad import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck as QC dbTests :: DB -> TestTree dbTests db = testGroup "DB" -- assertions [ testCase "case 1" $ (runQuery "?x" "(начальник ?x (Битобор Бен))") @?= parseMultiSet "(Хакер Лиза П) (Фект Пабло Э) (Поправич Дайко)" , testCase "case 2" $ (runQuery "?x" "(должность ?x (бухгалтерия . ?y))") @?= parseMultiSet "(Крэтчит Роберт) (Скрудж Эбин)" , testCase "case 3" $ (runQuery "?x" "(адрес ?x (Сламервилл . ?y))") @?= parseMultiSet "(Фиден Кон) (Дум Хьюго) (Битобор Бен)" , testCase "case AND" $ (runQuery "(?x ?y)" "(and (начальник ?x (Битобор Бен)) (адрес ?x ?y))") @?= parseMultiSet "((Поправич Дайко) (Бостон (Бэй Стейт Роуд) 22))\ \((Фект Пабло Э) (Кембридж (Эймс Стрит) 3))\ \((Хакер Лиза П) (Кембридж (Массачусетс Авеню) 78))" , testCase "case NOT" $ (runQuery "(?person ?his-boss ?z2)" "(and \ \(начальник ?person ?his-boss) \ \(not (должность ?his-boss (компьютеры . ?z1))) \ \(должность ?his-boss ?z2))") @?= parseMultiSet "((Фиден Кон) (Уорбак Оливер) (администрация большая шишка))\ \((Крэтчит Роберт) (Скрудж Эбин) (бухгалтерия главный бухгалтер))\ \((Скрудж Эбин) (Уорбак Оливер) (администрация большая шишка))\ \((Битобор Бен) (Уорбак Оливер) (администрация большая шишка))" -- rules , testCase "rule 1" $ (runQuery "?x" "(живет-около ?x (Битобор Бен))") @?= parseMultiSet "(Фиден Кон) (Дум Хьюго)" , testCase "rule 2 can-replace" $ (runQuery "?x" "(can-replace ?x (Фект Пабло Э))") @?= parseMultiSet "(Битобор Бен) (Хакер Лиза П)" , testCase "rule 3 independent" $ (runQuery "?x" "(independent ?x)") @?= parseMultiSet "(Скрудж Эбин) (Уорбак Оливер) (Битобор Бен)" , testCase "rule 4 " $ (runQuery "(?time ?who)" "(совещание ?who (пятница ?time))") @?= parseMultiSet "(13 администрация)" , testCase "rule 5" $ (runQuery "?day-and-time" "(время-совещания (Хакер Лиза П) ?day-and-time)") @?= parseMultiSet "(среда 16) (среда 15)" , testCase "rule 6" $ (runQuery "?time" "(время-совещания (Хакер Лиза П) (среда ?time))") @?= parseMultiSet "16 15" , testCase "rule 7" $ (runQuery "(?p1 ?p2)" "(живет-около ?p1 ?p2)") @?= parseMultiSet "((Фиден Кон) (Дум Хьюго))\ \((Фиден Кон) (Битобор Бен))\ \((Дум Хьюго) (Фиден Кон))\ \((Дум Хьюго) (Битобор Бен))\ \((Хакер Лиза П) (Фект Пабло Э))\ \((Фект Пабло Э) (Хакер Лиза П))\ \((Битобор Бен) (Фиден Кон))\ \((Битобор Бен) (Дум Хьюго))" , testCase "rule 8 append-to-form" $ (runQuery "?z" "(append-to-form (a b) (c d) ?z)") @?= parseMultiSet "(a b c d)" , testCase "rule 9 append-to-form" $ (runQuery "?y" "(append-to-form (a b) ?y (a b c d))") @?= parseMultiSet "(c d)" , testCase "rule 10 append-to-form" $ (runQuery "(?x ?y)" "(append-to-form ?x ?y (a b c d))") @?= parseMultiSet "((a b c d) ())\ \(() (a b c d))\ \((a) (b c d))\ \((a b) (c d))\ \((a b c) (d))" , testCase "rule 11 last-pair" $ (runQuery "?x" "(last-pair (3) ?x)") @?= parseMultiSet "3" , testCase "rule 12 last-pair" $ (runQuery "?x" "(last-pair (1 2 3) ?x)") @?= parseMultiSet "3" , testCase "rule 13 last-pair" $ (runQuery "?x" "(last-pair (2 ?x) (3))") @?= parseMultiSet "(3)" , testCase "rule 14 next-to" $ (runQuery "(?x ?y)" "(?x next-to ?y in (1 (2 3) 4))") @?= parseMultiSet "((2 3) 4) (1 (2 3))" , testCase "rule 15 next-to" $ (runQuery "?x" "(?x next-to 1 in (2 1 3 1))") @?= parseMultiSet "2 3" , testCase "rule 16" $ (runQuery "?x" "(подчиняется (Битобор Бен) ?x)") @?= parseMultiSet "(Уорбак Оливер)" , testCase "rule 17" $ (runQuery "?x" "(подчиняется1 (Битобор Бен) ?x)") @?= parseMultiSet "(Уорбак Оливер)" , testCase "rule 18 reverse" $ (runQuery "?x" "(reverse () ?x)") @?= parseMultiSet "()" , testCase "rule 19 reverse" $ (runQuery "?x" "(reverse ?x ())") @?= parseMultiSet "()" , testCase "rule 20 reverse" $ (runQuery "?x" "(reverse (a) ?x)") @?= parseMultiSet "(a)" , testCase "rule 21 reverse" $ (runQuery "?x" "(reverse ?x (a))") @?= parseMultiSet "(a)" , testCase "rule 22 reverse" $ (runQuery "?x" "(reverse (a b c d) ?x)") @?= parseMultiSet "(d c b a)" , testCase "rule 23 reverse" $ (runQuery "?x" "(reverse ?x (a b c d))") @?= parseMultiSet "(d c b a)" , testCase "rule 24 reverse" $ (runQuery "?x" "(reverse (a b c d e) ?x)") @?= parseMultiSet "(e d c b a)" , testCase "rule 25 reverse" $ (runQuery "?x" "(reverse ?x (a b c d e))") @?= parseMultiSet "(e d c b a)" -- lisp-value {- , test $ runQuery "(?name ?y ?x)" "(and (зарплата (Битобор Бен) ?x)\ \(зарплата ?name ?y) (lisp-value < ?y ?x))" >>= (@?= "caseLV1" (parseMultiSet "((Фиден Кон) 25000 60000)\ \((Крэтчит Роберт) 18000 60000)\ \((Дум Хьюго) 30000 60000)\ \((Поправич Дайко) 25000 60000)\ \((Фект Пабло Э) 35000 60000)\ \((Хакер Лиза П) 40000 60000)") , test $ runQuery "(?x ?sx ?sy)" "(and\ \(can-replace ?x ?y)\ \(зарплата ?x ?sx)\ \(зарплата ?y ?sy)\ \(lisp-value > ?sy ?sx))" >>= (@?= "caseLV2" (parseMultiSet "((Фиден Кон) 25000 150000) ((Фект Пабло Э) 35000 40000)") -} ] where runQuery :: String -> String -> MultiSet Value runQuery o q = foldl (flip MultiSet.insert) MultiSet.empty $ evaluate db (parseExpr q) (parseExpr o) parseExpr s = case parse (space >> expr <* eof) "" s of Left e -> error $ show e Right x -> x parseMultiSet :: String -> MultiSet Value parseMultiSet s = case parse (space >> many expr <* eof) "" s of Left e -> error $ show e Right x -> MultiSet.fromList x propValue' :: Value -> Bool propValue' x = either (const False) (== x) $ parse expr "" $ show $ toDoc x propValue :: TestTree propValue = QC.testProperty "LispParser QuickCheck" propValue' main :: IO () main = do edb <- fmap compileDB `liftM` parseFile "data.txt" case edb of Left e -> print e Right db -> defaultMain $ testGroup "Tests" [ SICP.LispParser.tests, propValue, SICP.DB.tests db, dbTests db ]
feumilieu/sicp-haskell
test/test.hs
Haskell
bsd-3-clause
7,633
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module SIGyM.Store.Generation ( Generation , GenEnv (..) , GenState (..) , GenError (..) , Registry , mkEnvironment , runGen , evalGen , getTime , findStore , findContext , noMsg , strMsg , throwError , catchError , liftIO ) where import Control.Monad.Reader hiding (liftIO) import Control.Monad.State hiding (liftIO) import Control.Monad.Error hiding (liftIO) import Data.Time.Clock (UTCTime, getCurrentTime) import SIGyM.Store.Registry import SIGyM.Store.Types mkEnvironment :: Maybe UTCTime -> Maybe Registry -> IO (GenEnv) mkEnvironment t r = do defaultTime <- getCurrentTime return GenEnv { currentTime = maybe defaultTime id t , registry = maybe emptyRegistry id r } runGen :: GenEnv -> GenState -> Generation a -> IO (Either GenError a, GenState) runGen e s (Generation g) = runStateT (runErrorT (runReaderT g e)) s evalGen :: GenEnv -> GenState -> Generation a -> IO (Either GenError a) evalGen e s g = runGen e s g >>= return . fst liftIO :: IO a -> Generation a liftIO = Generation . lift . lift . lift getTime :: Generation UTCTime getTime = asks currentTime findStore :: StoreID -> Generation Store findStore k = do mv <- asks (lookupStore k . registry) maybe (throwError$ RegistryLookupError$ "No such store: "++show k) return mv findContext :: ContextID -> Generation Context findContext k = do mv <- asks (lookupContext k . registry) maybe (throwError$ RegistryLookupError$ "No such context: "++show k) return mv
meteogrid/sigym-core
src/SIGyM/Store/Generation.hs
Haskell
bsd-3-clause
1,612
{-# LANGUAGE FlexibleContexts #-} module Text.Parsec.Char.Extras where import Control.Applicative ((*>), (<*)) import Data.Char (isSpace) import Text.Parsec (ParsecT, Stream, between, char, letter, many, sepBy1, satisfy, spaces) csv :: Stream s m Char => ParsecT s u m a -> ParsecT s u m [a] csv = (`sepBy1` comma) comma :: Stream s m Char => ParsecT s u m Char comma = char ',' notSpace :: Stream s m Char => ParsecT s u m Char notSpace = satisfy (not . isSpace) notSpaces :: Stream s m Char => ParsecT s u m String notSpaces = many notSpace word :: Stream s m Char => ParsecT s u m String word = many letter token :: Stream s m Char => ParsecT s u m a -> ParsecT s u m a token = between spaces spaces
mitchellwrosen/Sloch
src/lang-gen/Text/Parsec/Char/Extras.hs
Haskell
bsd-3-clause
711
module Main where import Control.Exception (bracket) import Data.ByteString (hGetSome) import Data.Serialize (decode) import Data.Vector (Vector) import qualified Data.Vector as Vector import Minecraft.Anvil (AnvilHeader(..), ChunkLocation(..), getAnvilHeader, readChunkData, decompressChunkData, showAnvilHeader) import System.IO (Handle, openFile, hClose, IOMode(ReadMode)) import System.Environment (getArgs) main :: IO () main = do [fp] <- getArgs bracket (openFile fp ReadMode) hClose $ \h -> do bs <- hGetSome h 8192 -- ^ header size is a fixed 8KiB case decode bs of (Left err) -> putStrLn err (Right ah) -> do putStrLn (showAnvilHeader ah) -- bs <- hGetSome h 1024 -- print bs dumpChunks h ah dumpChunk :: Handle -> ChunkLocation -> IO () dumpChunk h chunkLocation = do ecd <- readChunkData h chunkLocation case ecd of (Left e) -> putStrLn e (Right cd) -> print (decompressChunkData cd) dumpChunks :: Handle -> AnvilHeader -> IO () dumpChunks h ah = do mapM_ (dumpChunk h) (locations ah)
stepcut/minecraft-data
utils/DumpAnvil.hs
Haskell
bsd-3-clause
1,117
module D5Lib where import Text.Megaparsec (ParseError, Dec, endBy) import Text.Megaparsec.String (Parser) import Text.Megaparsec.Char as C import Text.Megaparsec.Lexer as L import Data.List (splitAt) type ParseResult = Either (ParseError Char Dec) Jmps type Jmps = [Int] data State = State { pos :: Int , jmps :: Jmps } deriving (Show, Eq) parser :: Parser Jmps parser = (L.signed C.space pInt) `endBy` eol where pInt = fromIntegral <$> L.integer start :: Jmps -> State start js = State { pos = 0, jmps = js } -- returns Nothing if pos is outside list step :: (Int -> Int) -> State -> Maybe State step _ State { pos = p } | p < 0 = Nothing step _ State { pos = p, jmps = js } | p >= length js = Nothing step jmpIncr State { pos = p, jmps = js } = Just $ State { pos = p', jmps = js' } where (h, (curJmp : t)) = splitAt p js js' = h ++ ((jmpIncr curJmp) : t) p' = p + curJmp stepP1 = step (+ 1) stepP2 = step f where f x = if x >= 3 then x - 1 else x + 1 -- starting from a given state, run until a terminal state run :: (State -> Maybe State) -> State -> [State] run stepper s0 = s0 : rest where rest = case stepper s0 of Nothing -> [] Just s -> run stepper s -- starting from a given state, run until a terminal state -- don't track intermediate states, just count the number of steps taken run' :: (State -> Maybe State) -> State -> Int run' stepper s0 = 1 + rest where rest = case stepper s0 of Nothing -> 0 Just s -> run' stepper s
wfleming/advent-of-code-2016
2017/D5/src/D5Lib.hs
Haskell
bsd-3-clause
1,538
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Temperature.EN.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Test.Tasty.HUnit import Duckling.Dimensions.Types import Duckling.Temperature.EN.Corpus import Duckling.Testing.Asserts import Duckling.Testing.Types (testContext, testOptions) import Duckling.Types (Range(..)) tests :: TestTree tests = testGroup "EN Tests" [ makeCorpusTest [Seal Temperature] corpus , rangeTests ] rangeTests :: TestTree rangeTests = testCase "Range Test" $ mapM_ (analyzedRangeTest testContext testOptions . withTargets [Seal Temperature]) xs where xs = [ ("between 40 and 30 degrees", Range 15 25 ) , ("30 degrees degrees", Range 0 10 ) ]
facebookincubator/duckling
tests/Duckling/Temperature/EN/Tests.hs
Haskell
bsd-3-clause
928
-- | Display mode is for drawing a static picture. module Graphics.Gloss.Interface.Pure.Display ( module Graphics.Gloss.Data.Display , module Graphics.Gloss.Data.Picture , module Graphics.Gloss.Data.Color , display) where import Graphics.Gloss.Data.Display import Graphics.Gloss.Data.Picture import Graphics.Gloss.Data.Color import Graphics.Gloss.Internals.Interface.Display import Graphics.Gloss.Internals.Interface.Backend -- | Open a new window and display the given picture. -- -- Use the following commands once the window is open: -- -- * Quit - esc-key. -- * Move Viewport - left-click drag, arrow keys. -- * Rotate Viewport - right-click drag, control-left-click drag, or home\/end-keys. -- * Zoom Viewport - mouse wheel, or page up\/down-keys. -- display :: Display -- ^ Display mode. -> Color -- ^ Background color. -> Picture -- ^ The picture to draw. -> IO () display = displayWithBackend defaultBackendState
ardumont/snake
deps/gloss/Graphics/Gloss/Interface/Pure/Display.hs
Haskell
bsd-3-clause
1,032
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Eleco.Slave.Backend.Repa where import Data.Vector.Unboxed ( Vector , imap , fromList ) import qualified Data.Vector.Unboxed as V import Data.Vector.Binary import Data.Array.Repa ( Array , DIM1 , U , Z(..) , (:.)(..) , fromUnboxed , fromListUnboxed , toUnboxed , computeP ) import qualified Data.Array.Repa as R import Data.Array.Repa.Algorithms.Matrix import Control.Distributed.Process (Process) import Control.Distributed.Process.Node (initRemoteTable) import Control.Distributed.Process.Closure (remotable) import Control.Distributed.Process.Backend.SimpleLocalnet ( initializeBackend , startSlave ) import Eleco.Core.Entity import Eleco.Slave import Eleco.Slave.State import Eleco.Slave.Backend type Vec2D = (Double, Double) {-# INLINE vecAdd #-} vecAdd :: Vec2D -> Vec2D -> Vec2D vecAdd (!x1, !y1) (!x2, !y2) = (x1 + x2, y1 + y2) {-# INLINE vecSub #-} vecSub :: Vec2D -> Vec2D -> Vec2D vecSub (!x1, !y1) (!x2, !y2) = (x1 - x2, y1 - y2) {-# INLINE vecDis #-} vecDis :: Vec2D -> Vec2D -> Double vecDis (!x1, !y1) (!x2, !y2) = let dx = x1 - x2 dy = y1 - y2 in dx * dx + dy * dy {-# INLINE vecMul #-} vecMul :: Vec2D -> Double -> Vec2D vecMul (!vx, !vy) !x = (vx * x, vy * x) {-# INLINE vecDiv #-} vecDiv :: Vec2D -> Double -> Vec2D vecDiv (!vx, !vy) !x = (vx / x, vy / x) {-# INLINE vecLen2 #-} vecLen2 :: Vec2D -> Double vecLen2 (!vx, !vy) = vx * vx + vy * vy {-# INLINE vecLen #-} vecLen :: Vec2D -> Double vecLen = sqrt . vecLen2 {-# INLINE vecNorm #-} vecNorm :: Vec2D -> Vec2D vecNorm vec = let len = vecLen vec in if len /= 0 then vecDiv vec len else vec data RepaBackend = RepaBackend { positions :: !(Array U DIM1 RawEntity) , velocities :: !(Array U DIM1 Vec2D) , masses :: !(Vector Double) , gravity :: {-# UNPACK #-} !Double } instance Backend (Vector RawEntity) RepaBackend where type CrossNodeData RepaBackend = (Vector RawEntity, Vector Double) updateBackend simState@SimulationState{..} = do datas <- expectCrossNodeDatas simState newvs <- computeP $ R.zipWith (calNewVel datas) positions velocities newps <- computeP $ R.zipWith calNewPos positions newvs return b { positions = newps , velocities = newvs } where b@RepaBackend{..} = simBackend vecPositions = toUnboxed positions interactions = [gravityInteraction] indeces = [0..entityCount-1] gravityInteraction !ent1 !m1 !ent2 !m2 !dir_vec !dis = let !co = gravity * m1 * m2 / (dis * dis) in dir_vec `vecMul` co calNewVel !datas !ent1 (!vx, !vy) = let ents = map (V.unsafeIndex vecPositions) $ filter (/=eid) indeces tvel = foldl (go masses) (0, 0) ents in foldl (\acc (cnEnts, cnMasses) -> V.foldl' (go cnMasses) acc cnEnts) tvel datas where !e1pos = position ent1 !eid = localId ent1 !e1m = V.unsafeIndex masses eid go e2masses acc ent2 = let !e2pos = position ent2 !e2m = V.unsafeIndex e2masses $ localId ent2 !vec = e1pos `vecSub` e2pos !dir_vec = vecNorm vec !dis = vecLen vec in foldl (\v f -> f ent1 e1m ent2 e2m dir_vec dis `vecAdd` v) acc interactions calNewPos (!px, !py, !i) (!vx, !vy) = (px + vx, py + vy, i) backendInfo = const BackendInfo { backendName = "Repa" , backendVersion = (0, 0, 0, 1) , backendBehaviours = ["Gravity"] } entitySeq = toUnboxed . positions fullCrossNodeData RepaBackend{..} = (toUnboxed positions, masses) regionalCrossNodeData RepaBackend{..} indeces = ( fromList $ fmap (V.unsafeIndex poss) indeces , fromList $ fmap (V.unsafeIndex masses) indeces ) where poss = toUnboxed positions repaSlaveSimulator :: Process () repaSlaveSimulator = slaveSimulatorProcess emptyBackend where emptyBackend = RepaBackend { positions = fromListUnboxed (Z :. 0 :: DIM1) [] , velocities = fromListUnboxed (Z :. 0 :: DIM1) [] , masses = fromList [] , gravity = 1.0 } remotable ['repaSlaveSimulator]
cikusa/Eleco
Eleco/Slave/Backend/Repa.hs
Haskell
bsd-3-clause
4,224
module Arimaa ( module Types , module Parser ) where import Types import Parser
Saulzar/arimaa
src/Arimaa.hs
Haskell
bsd-3-clause
91
----------------------------------------------------------------------------- -- | -- Module : XMonad.Util.Timer -- Description : A module for setting up timers. -- Copyright : (c) Andrea Rossato and David Roundy 2007 -- License : BSD-style (see xmonad/LICENSE) -- -- Maintainer : andrea.rossato@unibz.it -- Stability : unstable -- Portability : unportable -- -- A module for setting up timers ----------------------------------------------------------------------------- module XMonad.Util.Timer ( -- * Usage -- $usage startTimer , handleTimer , TimerId ) where import XMonad import Control.Concurrent import Data.Unique -- $usage -- This module can be used to setup a timer to handle deferred events. -- See 'XMonad.Layout.ShowWName' for an usage example. type TimerId = Int -- | Start a timer, which will send a ClientMessageEvent after some -- time (in seconds). startTimer :: Rational -> X TimerId startTimer s = io $ do u <- hashUnique <$> newUnique xfork $ do d <- openDisplay "" rw <- rootWindow d $ defaultScreen d threadDelay (fromEnum $ s * 1000000) a <- internAtom d "XMONAD_TIMER" False allocaXEvent $ \e -> do setEventType e clientMessage setClientMessageEvent e rw a 32 (fromIntegral u) 0 sendEvent d rw False structureNotifyMask e sync d False return u -- | Given a 'TimerId' and an 'Event', run an action when the 'Event' -- has been sent by the timer specified by the 'TimerId' handleTimer :: TimerId -> Event -> X (Maybe a) -> X (Maybe a) handleTimer ti ClientMessageEvent{ev_message_type = mt, ev_data = dt} action = do d <- asks display a <- io $ internAtom d "XMONAD_TIMER" False if mt == a && dt /= [] && fromIntegral (head dt) == ti then action else return Nothing handleTimer _ _ _ = return Nothing
xmonad/xmonad-contrib
XMonad/Util/Timer.hs
Haskell
bsd-3-clause
1,857
module Language.Haskell.GhcMod.Lang where import DynFlags (supportedLanguagesAndExtensions) import Language.Haskell.GhcMod.Types import Language.Haskell.GhcMod.Convert -- | Listing language extensions. listLanguages :: Options -> IO String listLanguages opt = return $ convert opt supportedLanguagesAndExtensions
darthdeus/ghc-mod-ng
Language/Haskell/GhcMod/Lang.hs
Haskell
bsd-3-clause
316
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.PixelBufferObject -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/pixel_buffer_object.txt ARB_pixel_buffer_object> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.PixelBufferObject ( -- * Enums gl_PIXEL_PACK_BUFFER_ARB, gl_PIXEL_PACK_BUFFER_BINDING_ARB, gl_PIXEL_UNPACK_BUFFER_ARB, gl_PIXEL_UNPACK_BUFFER_BINDING_ARB ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/PixelBufferObject.hs
Haskell
bsd-3-clause
779
{-# LANGUAGE CPP #-} -- | This module provides remote monitoring of a running process over -- HTTP. It can be used to run an HTTP server that provides both a -- web-based user interface and a machine-readable API (e.g. JSON.) -- The former can be used by a human to get an overview of what the -- program is doing and the latter can be used by automated monitoring -- tools. -- -- Typical usage is to start the monitoring server at program startup -- -- > main = do -- > forkServer "localhost" 8000 -- > ... -- -- and then periodically check the stats using a web browser or a -- command line tool (e.g. curl) -- -- > $ curl -H "Accept: application/json" http://localhost:8000/ module System.Remote.Monitoring ( -- * Required configuration -- $configuration -- * REST API -- $api -- * The monitoring server Server , serverThreadId , forkServer -- * User-defined counters, gauges, and labels -- $userdefined , getCounter , getGauge , getLabel ) where import Control.Concurrent (ThreadId, forkIO) import qualified Data.ByteString as S import qualified Data.HashMap.Strict as M import Data.IORef (newIORef) import Prelude hiding (read) import System.Remote.Common #if USE_WAI import System.Remote.Wai #else import System.Remote.Snap #endif -- $configuration -- -- To use this module you must first enable GC statistics collection -- in the run-time system. To enable GC statistics collection, either -- run your program with -- -- > +RTS -T -- -- or compile it with -- -- > -with-rtsopts=-T -- -- The runtime overhead of @-T@ is very small so it's safe to always -- leave it enabled. -- $api -- To use the machine-readable REST API, send an HTTP GET request to -- the host and port passed to 'forkServer'. The following resources -- (i.e. URLs) are available: -- -- [\/] JSON object containing all counters and gauges. Counters and -- gauges are stored as nested objects under the @counters@ and -- @gauges@ attributes, respectively. Content types: \"text\/html\" -- (default), \"application\/json\" -- -- [\/combined] Flattened JSON object containing all counters, gauges, -- and labels. Content types: \"application\/json\" -- -- [\/counters] JSON object containing all counters. Content types: -- \"application\/json\" -- -- [\/counters/\<counter name\>] Value of a single counter, as a -- string. The name should be UTF-8 encoded. Content types: -- \"text\/plain\" -- -- [\/gauges] JSON object containing all gauges. Content types: -- \"application\/json\" -- -- [\/gauges/\<gauge name\>] Value of a single gauge, as a string. -- The name should be UTF-8 encoded. Content types: \"text\/plain\" -- -- [\/labels] JSON object containing all labels. Content types: -- \"application\/json\" -- -- [\/labels/\<label name\>] Value of a single label, as a string. -- The name should be UTF-8 encoded. Content types: \"text\/plain\" -- -- Counters, gauges and labels are stored as attributes of the -- returned JSON objects, one attribute per counter, gauge or label. -- In addition to user-defined counters, gauges, and labels, the below -- built-in counters and gauges are also returned. Furthermore, the -- top-level JSON object of any resource contains the -- @server_timestamp_millis@ attribute, which indicates the server -- time, in milliseconds, when the sample was taken. -- -- Built-in counters: -- -- [@bytes_allocated@] Total number of bytes allocated -- -- [@num_gcs@] Number of garbage collections performed -- -- [@num_bytes_usage_samples@] Number of byte usage samples taken -- -- [@cumulative_bytes_used@] Sum of all byte usage samples, can be -- used with @numByteUsageSamples@ to calculate averages with -- arbitrary weighting (if you are sampling this record multiple -- times). -- -- [@bytes_copied@] Number of bytes copied during GC -- -- [@mutator_cpu_seconds@] CPU time spent running mutator threads. -- This does not include any profiling overhead or initialization. -- -- [@mutator_wall_seconds@] Wall clock time spent running mutator -- threads. This does not include initialization. -- -- [@gc_cpu_seconds@] CPU time spent running GC -- -- [@gc_wall_seconds@] Wall clock time spent running GC -- -- [@cpu_seconds@] Total CPU time elapsed since program start -- -- [@wall_seconds@] Total wall clock time elapsed since start -- -- Built-in gauges: -- -- [@max_bytes_used@] Maximum number of live bytes seen so far -- -- [@current_bytes_used@] Current number of live bytes -- -- [@current_bytes_slop@] Current number of bytes lost to slop -- -- [@max_bytes_slop@] Maximum number of bytes lost to slop at any one time so far -- -- [@peak_megabytes_allocated@] Maximum number of megabytes allocated -- #if MIN_VERSION_base(4,6,0) -- [@par_tot_bytes_copied@] Number of bytes copied during GC, minus -- space held by mutable lists held by the capabilities. Can be used -- with 'parMaxBytesCopied' to determine how well parallel GC utilized -- all cores. -- -- [@par_avg_bytes_copied@] Deprecated alias for -- @par_tot_bytes_copied@. #else -- [@par_avg_bytes_copied@] Number of bytes copied during GC, minus -- space held by mutable lists held by the capabilities. Can be used -- with 'parMaxBytesCopied' to determine how well parallel GC utilized -- all cores. #endif -- -- [@par_max_bytes_copied@] Sum of number of bytes copied each GC by -- the most active GC thread each GC. The ratio of #if MIN_VERSION_base(4,6,0) -- 'parTotBytesCopied' divided by 'parMaxBytesCopied' approaches 1 for #else -- 'parAvgBytesCopied' divided by 'parMaxBytesCopied' approaches 1 for #endif -- a maximally sequential run and approaches the number of threads -- (set by the RTS flag @-N@) for a maximally parallel run. ------------------------------------------------------------------------ -- * The monitoring server -- | The thread ID of the server. You can kill the server by killing -- this thread (i.e. by throwing it an asynchronous exception.) serverThreadId :: Server -> ThreadId serverThreadId = threadId -- | Start an HTTP server in a new thread. The server replies to GET -- requests to the given host and port. The host argument can be -- either a numeric network address (dotted quad for IPv4, -- colon-separated hex for IPv6) or a hostname (e.g. \"localhost\".) -- The client can control the Content-Type used in responses by -- setting the Accept header. At the moment three content types are -- available: \"application\/json\", \"text\/html\", and -- \"text\/plain\". forkServer :: S.ByteString -- ^ Host to listen on (e.g. \"localhost\") -> Int -- ^ Port to listen on (e.g. 8000) -> IO Server forkServer host port = do counters <- newIORef M.empty gauges <- newIORef M.empty labels <- newIORef M.empty tid <- forkIO $ startServer counters gauges labels host port return $! Server tid counters gauges labels
fpco/ekg
System/Remote/Monitoring.hs
Haskell
bsd-3-clause
6,893
{-| Module : PP.Grammars.Ebnf Description : Defines a AST and parser for the EBNF language Copyright : (c) 2017 Patrick Champion License : see LICENSE file Maintainer : chlablak@gmail.com Stability : provisional Portability : portable AST for the EBNF language. Based on the grammar given in the ISO/IEC 14977:1996, page 10, part 8.2. Comments are valid in EBNF, but are not present in this AST. -} module PP.Grammars.Ebnf ( -- * AST Syntax(..) -- ** Inner ASTs , SyntaxRule(..) , DefinitionsList(..) , SingleDefinition(..) , Term(..) , Exception(..) , Factor(..) , Primary(..) , MetaIdentifier(..) ) where import Control.Applicative ((<$>), (<*>)) import qualified Data.List as L import Data.Maybe import Data.Text (pack, strip, unpack) import PP.Grammar import PP.Grammars.LexicalHelper (LexicalRule, lexicalString) import qualified PP.Rule as R import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Language (emptyDef) import qualified Text.ParserCombinators.Parsec.Token as Token -- |Start rule newtype Syntax = Syntax [SyntaxRule] deriving (Show, Eq) -- |Syntax rule data SyntaxRule -- |Defines the sequence of symbols represented by a MetaIdentifier = SyntaxRule MetaIdentifier DefinitionsList -- |Defines a lexical definition inside the EBNF grammar | LexicalInner LexicalRule deriving (Show, Eq) -- |Separates alternative SingleDefinition newtype DefinitionsList = DefinitionsList [SingleDefinition] deriving (Show, Eq) -- |Separates successive Term newtype SingleDefinition = SingleDefinition [Term] deriving (Show, Eq) -- |Represents any sequence of symbols that is defined by the Factor -- but not defined by the Exception data Term = Term Factor (Maybe Exception) deriving (Show, Eq) -- |A Factor may be used as an Exception if it could be replaced by a -- Factor containing no MetaIdentifier newtype Exception = Exception Factor deriving (Show, Eq) -- |The Integer specifies the number of repetitions of the Primay data Factor = Factor (Maybe Integer) Primary deriving (Show, Eq) -- |Primary data Primary -- |Encloses symbols which are optional = OptionalSequence DefinitionsList -- |Encloses symbols which may be repeated any number of times | RepeatedSequence DefinitionsList -- |Allows any DefinitionsList to be a Primary | GroupedSequence DefinitionsList -- |A Primary can be a MetaIdentifier | PrimaryMetaIdentifier MetaIdentifier -- |Represents the characters between the quote symbols '...' or "..." | TerminalString String -- |Empty Primary | Empty deriving (Show, Eq) -- |A MetaIdentifier is the name of a syntactic element of the langage being defined newtype MetaIdentifier = MetaIdentifier String deriving (Show, Eq) -- |Lexer definitions for EBNF lexer = Token.makeTokenParser def where def = emptyDef { Token.commentStart = "(*" , Token.commentEnd = "*)" , Token.commentLine = "" , Token.nestedComments = False , Token.identStart = letter , Token.identLetter = alphaNum <|> oneOf "_- " , Token.reservedNames = [] , Token.reservedOpNames = ["=", ";", "|", ",", "-", "*"] , Token.caseSensitive = True } identifier = Token.identifier lexer reservedOp = Token.reservedOp lexer stringLiteral = Token.stringLiteral lexer natural = Token.natural lexer whiteSpace = Token.whiteSpace lexer parens = Token.parens lexer braces = Token.braces lexer angles = Token.angles lexer brackets = Token.brackets lexer -- |Syntax parser syntax :: Parser Syntax syntax = whiteSpace *> (Syntax <$> many1 syntaxRule) <?> "syntax" -- |SyntaxRule parser syntaxRule :: Parser SyntaxRule syntaxRule = try (SyntaxRule <$> (metaIdentifier <* reservedOp "=") <*> (definitionsList <* reservedOp ";")) <|> LexicalInner <$> parser <?> "syntax rule" -- |DefinitionsList parser definitionsList :: Parser DefinitionsList definitionsList = DefinitionsList <$> sepBy1 singleDefinition (reservedOp "|") <?> "definitions list" -- |SingleDefinition parser singleDefinition :: Parser SingleDefinition singleDefinition = SingleDefinition <$> sepBy1 term (reservedOp ",") <?> "single definition" -- |Term parser term :: Parser Term term = Term <$> factor <*> optionMaybe (reservedOp "-" *> exception) <?> "term" -- |Exception parser exception :: Parser Exception exception = Exception <$> factor <?> "exception" -- |Factor parser factor :: Parser Factor factor = Factor <$> optionMaybe (natural <* reservedOp "*") <*> primary <?> "factor" -- |Primary parser primary :: Parser Primary primary = option Empty ( OptionalSequence <$> brackets definitionsList <|> RepeatedSequence <$> braces definitionsList <|> GroupedSequence <$> parens definitionsList <|> PrimaryMetaIdentifier <$> metaIdentifier <|> TerminalString <$> stringLiteral ) -- end of option <?> "primary" -- |MetaIdentifier parser metaIdentifier :: Parser MetaIdentifier metaIdentifier = trimMetaIdentifier <$> (angles identifier <|> identifier) <?> "meta identifier" where trimMetaIdentifier = MetaIdentifier . unpack . strip . pack -- |Lexify an EBNF syntax tree lexifySyntax :: Syntax -> Syntax lexifySyntax s = replaceTerm tok $ addLexicalInner tok s where tok = generateTokens $ findTerm s findTerm (Syntax srs) = L.concatMap findTerm' srs findTerm' (SyntaxRule _ dl) = findTerm'' dl findTerm' (LexicalInner _) = [] findTerm'' (DefinitionsList sds) = L.concatMap findTerm''' sds findTerm''' (SingleDefinition ts) = L.concatMap findTerm'''' ts findTerm'''' (Term f _) = findTerm''''' f findTerm''''' (Factor _ p) = findTerm'''''' p findTerm'''''' (OptionalSequence dl) = findTerm'' dl findTerm'''''' (RepeatedSequence dl) = findTerm'' dl findTerm'''''' (GroupedSequence dl) = findTerm'' dl findTerm'''''' (PrimaryMetaIdentifier mi) = [] findTerm'''''' (TerminalString term) = [term] findTerm'''''' Empty = [] generateTokens = map (\t -> (t, "__token_" ++ t)) . L.nub addLexicalInner [] s = s addLexicalInner ((n, t):ts) (Syntax srs) = addLexicalInner ts $ Syntax $ LexicalInner (lexicalString t n) : srs replaceTerm [] s = s replaceTerm (t:ts) (Syntax srs) = replaceTerm ts $ Syntax $ L.map (replaceTerm' t) srs replaceTerm' t (SyntaxRule r dl) = SyntaxRule r $ replaceTerm'' t dl replaceTerm' _ li@(LexicalInner _) = li replaceTerm'' t (DefinitionsList sds) = DefinitionsList $ L.map (replaceTerm''' t) sds replaceTerm''' t (SingleDefinition ts) = SingleDefinition $ L.map (replaceTerm'''' t) ts replaceTerm'''' t (Term f e) = Term (replaceTerm''''' t f) e replaceTerm''''' t (Factor f p) = Factor f $ replaceTerm'''''' t p replaceTerm'''''' t (OptionalSequence dl) = OptionalSequence $ replaceTerm'' t dl replaceTerm'''''' t (RepeatedSequence dl) = RepeatedSequence $ replaceTerm'' t dl replaceTerm'''''' t (GroupedSequence dl) = GroupedSequence $ replaceTerm'' t dl replaceTerm'''''' (n, t) ts@(TerminalString s) = if n == s then PrimaryMetaIdentifier (MetaIdentifier t) else ts replaceTerm'''''' _ p = p -- * InputGrammar instances for EBNF AST instance InputGrammar Syntax where parser = syntax stringify (Syntax []) = "" stringify (Syntax [sr]) = stringify sr stringify (Syntax (sr:r)) = stringify sr ++ "\n" ++ stringify (Syntax r) rules (Syntax srs) = R.uniformize $ L.concatMap rules srs lexify = lexifySyntax instance InputGrammar SyntaxRule where parser = syntaxRule stringify (SyntaxRule mi dl) = stringify mi ++ "=" ++ stringify dl ++ ";" stringify (LexicalInner lr) = stringify lr rules (SyntaxRule (MetaIdentifier mi) dl) = [R.Rule mi [r, R.Empty] | r <- rules dl] rules (LexicalInner lr) = rules lr instance InputGrammar DefinitionsList where parser = definitionsList stringify (DefinitionsList []) = "" stringify (DefinitionsList [sd]) = stringify sd stringify (DefinitionsList (sd:r)) = stringify sd ++ "|" ++ stringify (DefinitionsList r) rules (DefinitionsList sds) = L.concatMap rules sds instance InputGrammar SingleDefinition where parser = singleDefinition stringify (SingleDefinition []) = "" stringify (SingleDefinition [t]) = stringify t stringify (SingleDefinition (t:r)) = stringify t ++ "," ++ stringify (SingleDefinition r) rules (SingleDefinition [t]) = rules t rules (SingleDefinition (t:ts)) = [R.Concat [r,n] | r <- rules t, n <- rules (SingleDefinition ts)] instance InputGrammar Term where parser = term stringify (Term f Nothing) = stringify f stringify (Term f (Just e)) = stringify f ++ "-" ++ stringify e rules (Term f Nothing) = rules f rules _ = error "no translation for exception" -- ... yet instance InputGrammar Exception where parser = exception stringify (Exception f) = stringify f rules _ = undefined -- should not be called, look at the Term instance instance InputGrammar Factor where parser = factor stringify (Factor Nothing p) = stringify p stringify (Factor (Just i) p) = show i ++ "*" ++ stringify p rules (Factor Nothing p) = rules p rules (Factor (Just i) p) = [R.Concat . concat $ replicate (fromIntegral i) (rules p)] instance InputGrammar Primary where parser = primary stringify (OptionalSequence dl) = "[" ++ stringify dl ++ "]" stringify (RepeatedSequence dl) = "{" ++ stringify dl ++ "}" stringify (GroupedSequence dl) = "(" ++ stringify dl ++ ")" stringify (PrimaryMetaIdentifier mi) = stringify mi stringify (TerminalString s) = show s stringify Empty = "" rules a@(OptionalSequence dl) = let x = stringify a in R.NonTerm x : R.Rule x [R.Empty] : [R.Rule x [r, R.Empty] | r <- rules dl] rules a@(RepeatedSequence dl) = let x = stringify a in R.NonTerm x : R.Rule x [R.Empty] : [R.Rule x [r, R.NonTerm x, R.Empty] | r <- rules dl] rules a@(GroupedSequence dl) = let x = stringify a in R.NonTerm x : [R.Rule x [r, R.Empty] | r <- rules dl] rules (PrimaryMetaIdentifier mi) = rules mi rules (TerminalString s) = [R.Concat $ L.map R.Term s] rules Empty = [R.Empty] instance InputGrammar MetaIdentifier where parser = metaIdentifier stringify (MetaIdentifier s) = "<" ++ s ++ ">" rules (MetaIdentifier s) = [R.NonTerm s]
chlablak/platinum-parsing
src/PP/Grammars/Ebnf.hs
Haskell
bsd-3-clause
10,858
module Cases.DeclDependencyTest where import Language.Haskell.Exts hiding (name) import Test.HUnit import Cases.BaseDir import Utils.DependencyAnalysis import Utils.Nameable testdecldependency1 = testdecldependency test1 testdecldependency :: (String, String) -> Assertion testdecldependency (f,s) = do r <- parseFileWithExts exts f let r' = parseResult decls undefined r ns = show $ map (map name) (dependencyAnalysis TypeAnalysis r') assertEqual "Type Dependency Result:" s ns test1 = (baseDir ++ "/mptc/test/Data/TestCase1DeclDependence.hs", "[[a],[b],[h,g,f],[c,d]]") decls (Module _ _ _ _ _ _ ds) = ds -- pattern matching function over parser results parseResult :: (a -> b) -> (SrcLoc -> String -> b) -> ParseResult a -> b parseResult f g (ParseOk m) = f m parseResult f g (ParseFailed l s) = g l s -- always enabled extensions exts :: [Extension] exts = map EnableExtension [MultiParamTypeClasses, RankNTypes, FlexibleContexts]
rodrigogribeiro/mptc
test/Cases/DeclDependencyTest.hs
Haskell
bsd-3-clause
1,013
module Agon.Data.Types where data UUIDs = UUIDs [String] data CouchUpdateResult = CouchUpdateResult { curRev :: String } deriving Show data CouchList e = CouchList { clItems :: [CouchListItem e] } deriving Show data CouchListItem e = CouchListItem { cliItem :: e } deriving Show
Feeniks/Agon
app/Agon/Data/Types.hs
Haskell
bsd-3-clause
296
{-# LANGUAGE StandaloneDeriving, DeriveFunctor, OverloadedStrings #-} module Web.Rest ( Request(..), Method(..),Location,Accept,ContentType,Body, Response(..), ResponseCode, RestT,Rest,rest, runRestT,Hostname,Port,RestError(..)) where import Web.Rest.Internal ( Request(..), Method(..),Location,Accept,ContentType,Body, Response(..), ResponseCode, RestT,Rest,rest) import Web.Rest.HTTP ( runRestT,Hostname,Port,RestError(..))
phischu/haskell-rest
src/Web/Rest.hs
Haskell
bsd-3-clause
476
{-# LANGUAGE DataKinds, DeriveDataTypeable, FlexibleContexts #-} {-# LANGUAGE FlexibleInstances, FunctionalDependencies, MagicHash #-} {-# LANGUAGE MultiParamTypeClasses, PolyKinds, QuasiQuotes, RankNTypes #-} {-# LANGUAGE ScopedTypeVariables, StandaloneDeriving, TemplateHaskell #-} {-# LANGUAGE TypeFamilies, TypeOperators #-} module Messaging.Core ((:>)(..), cast, Object(..), withTypeableSymbol, Selector(..), send, (#), (#.), (===), unsafeDownCast) where import Data.Typeable.Internal (Proxy (..), Typeable (..), mkTyCon3, mkTyConApp) import Foreign.ForeignPtr (ForeignPtr) import GHC.Base (Proxy#) import GHC.TypeLits (Symbol) import GHC.TypeLits (symbolVal) import GHC.TypeLits (KnownSymbol) import Unsafe.Coerce (unsafeCoerce) newtype Object (a :: k) = Object (ForeignPtr ()) deriving (Typeable, Show, Eq) -- | @a ':>' b@ indicates that @a@ is a super-class of @b@. class (a :: k) :> (b :: k2) newtype Typing sym a = Typing (Typeable (sym :: Symbol) => a) unsafeDownCast :: (a :> b) => Object a -> Object b unsafeDownCast (Object a) = Object a withTypeableSymbol :: forall sym a proxy. KnownSymbol sym => proxy sym -> (Typeable sym => a) -> a withTypeableSymbol _ f = unsafeCoerce (Typing f :: Typing sym a) inst where inst pxy = let _ = pxy :: Proxy# sym in mkTyConApp (mkTyCon3 "base" "GHC.TypeLits" ('"': symbolVal (Proxy :: Proxy sym) ++ "\"")) [] instance (a :> b, c :> d) => (b -> c) :> (a -> d) instance a :> a instance (a :> b) => [a] :> [b] class Selector cls msg | msg -> cls where data Message (msg :: k') :: * type Returns msg :: * send' :: Object cls -> Message msg -> Returns msg cast :: (a :> b) => Object b -> Object a cast (Object ptr) = Object ptr send :: (a :> b, Selector a msg) => Object b -> Message msg -> Returns msg send = send' . cast infixl 4 # (#) :: (a :> b, Selector a msg) => Object b -> Message msg -> Returns msg (#) = send infixl 4 #. (#.) :: (a :> b, Selector a msg, Returns msg ~ IO c) => IO (Object b) -> Message msg -> IO c recv #. sel = recv >>= flip send sel infix 4 === (===) :: Object t -> Object t1 -> Bool Object fptr === Object fptr' = fptr == fptr'
konn/reactive-objc
Messaging/Core.hs
Haskell
bsd-3-clause
2,309
{-# LANGUAGE OverloadedStrings #-} module OAuthHandlers ( routes ) where ------------------------------------------------------------------------------ import Control.Applicative import Control.Monad import Control.Monad.Trans import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Maybe import qualified Data.Text as T import qualified Data.Text.Encoding as T import Snap.Core import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Auth.Backends.JsonFile import Snap.Snaplet.Heist import Snap.Snaplet.OAuth import Text.Templating.Heist import qualified Snap.Snaplet.OAuth.Github as GH import qualified Snap.Snaplet.OAuth.Google as G import qualified Snap.Snaplet.OAuth.Weibo as W import Application import Splices ---------------------------------------------------------------------- -- Weibo ---------------------------------------------------------------------- -- | Logs out and redirects the user to the site index. weiboOauthCallbackH :: AppHandler () weiboOauthCallbackH = W.weiboUserH >>= success where success Nothing = writeBS "No user info found" success (Just usr) = do with auth $ createOAuthUser weibo $ W.wUidStr usr --writeText $ T.pack $ show usr toHome usr ---------------------------------------------------------------------- -- Google ---------------------------------------------------------------------- googleOauthCallbackH :: AppHandler () googleOauthCallbackH = G.googleUserH >>= googleUserId googleUserId :: Maybe G.GoogleUser -> AppHandler () googleUserId Nothing = redirect "/" googleUserId (Just user) = with auth (createOAuthUser google (G.gid user)) >> toHome user ---------------------------------------------------------------------- -- Github ---------------------------------------------------------------------- githubOauthCallbackH :: AppHandler () githubOauthCallbackH = GH.githubUserH >>= githubUser githubUser :: Maybe GH.GithubUser -> AppHandler () githubUser Nothing = redirect "/" githubUser (Just user) = with auth (createOAuthUser github uid) >> toHome user where uid = intToText $ GH.gid user intToText = T.pack . show ---------------------------------------------------------------------- -- Create User per oAuth response ---------------------------------------------------------------------- -- | Create new user for Weibo User to local -- createOAuthUser :: OAuthKey -> T.Text -- ^ oauth user id -> Handler App (AuthManager App) () createOAuthUser key name = do let name' = textToBS name passwd = ClearText name' role = Role (BS.pack $ show key) exists <- usernameExists name unless exists (void (createUser name name')) res <- loginByUsername name' passwd False case res of Left l -> liftIO $ print l Right r -> do res2 <- saveUser (r {userRoles = [ role ]}) return () --either (liftIO . print) (const $ return ()) res2 ---------------------------------------------------------------------- -- Routes ---------------------------------------------------------------------- -- | The application's routes. routes :: [(ByteString, AppHandler ())] routes = [ ("/oauthCallback", weiboOauthCallbackH) , ("/googleCallback", googleOauthCallbackH) , ("/githubCallback", githubOauthCallbackH) ] -- | NOTE: when use such way to show callback result, -- the url does not change, which can not be invoke twice. -- This is quite awkful thing and only for testing purpose. -- toHome a = heistLocal (bindRawResponseSplices a) $ render "index" ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
HaskellCNOrg/snaplet-oauth
example/src/OAuthHandlers.hs
Haskell
bsd-3-clause
4,350
module Math.Matrix where import Math.Vector import Data.List ( intercalate ) import Data.Maybe ( fromJust, fromMaybe ) import qualified Data.List as L type Matrix a = [Vector a] -- Projection Matrices orthoMatrix :: (Num t, Fractional t) => t -> t -> t -> t -> t -> t -> Matrix t orthoMatrix left right top bottom near far = [ [ 2/(right-left), 0, 0, -(right+left)/(right-left) ] , [ 0, 2/(top-bottom), 0, -(top+bottom)/(top-bottom) ] , [ 0, 0, -2/(far-near), -(far+near)/(far-near) ] , [ 0, 0, 0, 1] ] -- Affine Transformation Matrices scaleMatrix3d :: Num t => t -> t -> t -> Matrix t scaleMatrix3d x y z = [ [x, 0, 0, 0] , [0, y, 0, 0] , [0, 0, z, 0] , [0, 0, 0, 1] ] rotationMatrix3d :: Floating t => t -> t -> t -> Matrix t rotationMatrix3d x y z = [ [cy*cz, -cx*sz+sx*sy*sz, sx*sz+cx*sy*cz, 0] , [cy*sz, cx*cz+sx*sy*sz, -sx*cz+cx*sy*sz, 0] , [ -sy, sx*cy, cx*cy, 0] , [ 0, 0, 0, 1] ] where [cx, cy, cz] = map cos [x, y, z] [sx, sy, sz] = map sin [x, y, z] translationMatrix3d :: Num t => t -> t -> t -> Matrix t translationMatrix3d x y z = [ [1, 0, 0, x] , [0, 1, 0, y] , [0, 0, 1, z] , [0, 0, 0, 1] ] -- Basic Matrix Math fromVector :: Int -> Int -> [a] -> Maybe [[a]] fromVector r c v = if length v `mod` r*c == 0 then Just $ groupByRowsOf c v else Nothing -- | The identity of an NxN matrix. identityN :: (Num a) => Int -> Matrix a identityN n = groupByRowsOf n $ modList n where modList l = [ if x `mod` (l+1) == 0 then 1 else 0 | x <- [0..(l*l)-1] ] -- | The identity of the given matrix. identity :: (Num a) => Matrix a -> Matrix a identity m = groupByRowsOf rows modList where modList = [ if x `mod` (cols+1) == 0 then 1 else 0 | x <- [0..len-1] ] len = sum $ map length m rows = numRows m cols = numColumns m -- | The number of columns in the matrix. numColumns :: Matrix a -> Int numColumns = length -- | The number of rows in the matrix. numRows :: Matrix a -> Int numRows [] = 0 numRows (r:_) = length r -- | A list of the columns. toColumns :: Matrix a -> [[a]] toColumns = transpose -- | A list of the rows. toRows :: Matrix a -> [[a]] toRows = id -- | The minor for an element of `a` at the given row and column. minorAt :: Floating a => [Vector a] -> Int -> Int -> a minorAt m x y = let del = deleteColRow m x y in determinant del -- | The Matrix created by deleting column x and row y of the given matrix. deleteColRow :: Matrix a -> Int -> Int -> Matrix a deleteColRow m x y = let nRws = numRows m nCls = numColumns m rNdxs = [ row + x | row <- [0,nCls..nCls*(nCls-1)] ] cNdxs = [ nRws*y + col | col <- [0..nRws-1] ] ndxs = rNdxs ++ cNdxs (_, vec) = foldl filtNdx (0,[]) $ concat m filtNdx (i, acc) el = if i `elem` ndxs then (i+1, acc) else (i+1, acc++[el]) in groupByRowsOf (nRws-1) vec -- | The transpose of the matrix. transpose :: Matrix a -> Matrix a transpose = L.transpose -- | Computes the inverse of the matrix. inverse :: (Num a, Eq a, Fractional a, Floating a) => Matrix a -> Maybe (Matrix a) inverse m = let det = determinant m one_det = 1/ det cofacts = cofactors m adjoint = transpose cofacts inv = (map . map) (*one_det) adjoint in if det /= 0 then Just inv else Nothing -- | The matrix of cofactors of the given matrix. cofactors :: (Num a, Floating a) => Matrix a -> Matrix a cofactors m = fromJust $ fromVector (numRows m) (numColumns m) [ cofactorAt m x y | y <- [0..numRows m -1], x <- [0..numColumns m -1] ] -- | Computes the multiplication of two matrices. multiply :: (Num a, Show a) => Matrix a -> Matrix a -> Matrix a multiply m1 m2 = let element row col = sum $ zipWith (*) row col rows = toRows m1 cols = toColumns m2 nRows = numRows m1 nCols = numColumns m2 vec = take (nRows*nCols) [ element r c | r <- rows, c <- cols ] mM = fromVector nRows nCols vec err = error $ intercalate "\n" [ "Could not multiply matrices:" , "m1:" , show m1 , "m2:" , show m2 , "from vector:" , show vec ] in fromMaybe err mM -- | The cofactor for an element of `a` at the given row and column. cofactorAt :: (Num a, Floating a) => Matrix a -> Int -> Int -> a cofactorAt m x y = let pow = fromIntegral $ x + y + 2 -- I think zero indexed. in (-1)**pow * minorAt m x y -- | Computes the determinant of the matrix. determinant :: (Num a, Floating a) => Matrix a -> a determinant [[a]] = a determinant m = let rowCofactors = [ cofactorAt m x 0 | x <- [0..numColumns m -1] ] row = head $ toRows m in sum $ zipWith (*) rowCofactors row -- Helpers groupByRowsOf :: Int -> [a] -> [[a]] groupByRowsOf _ [] = [] groupByRowsOf cols xs = take cols xs : groupByRowsOf cols (drop cols xs)
schell/blocks
src/Math/Matrix.hs
Haskell
bsd-3-clause
6,213
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module VirtualDom.Prim where import Control.Applicative import Control.Lens import Control.Monad.State import Data.String (IsString(fromString)) import GHCJS.DOM.Event import GHCJS.Foreign import GHCJS.Types import System.IO.Unsafe import qualified Data.Immutable as Immutable import qualified GHCJS.DOM.HTMLElement as DOM -- | An opaque data-type representing a foreign @VNode@ object. data VNode -- | A HTML node - either an element with attributes, or a piece of text. newtype Node = Node (JSRef VNode) foreign import javascript safe "new virtualdom.VText($1)" ffiNewVText :: JSString -> JSRef VNode -- | Construct a 'HTML' text node. text :: ToJSString t => t -> Node text = Node . ffiNewVText . toJSString foreign import javascript safe "new virtualdom.VNode($1)" ffiNewVNode :: JSString -> JSRef VNode -- | Construct a new 'HTML' element consisting of a given element, with no -- child content or attributes. emptyElement :: JSString -> Node emptyElement = Node . ffiNewVNode -- | Strings are considered HTML nodes by converting them to text nodes. instance IsString Node where fromString = text -- | Witness that a 'HTML' node is pointing to a VNode. newtype HTMLElement = HTMLElement (JSRef VNode) foreign import javascript safe "$r = $1.type" ffiGetVNodeType :: JSRef VNode -> JSString -- A zero-or-one traversal into a 'HTML' fragment to determine if it is an -- element or not. _HTMLElement :: Traversal' Node HTMLElement _HTMLElement f (Node vNode) | fromJSString (ffiGetVNodeType vNode) == ("VirtualNode" :: String) = fmap (\(HTMLElement vNode') -> Node vNode') (f (HTMLElement vNode)) | otherwise = pure (Node vNode) foreign import javascript safe "Immutable.Map($1.properties)" ffiVNodeGetProperties :: JSRef VNode -> Immutable.Map foreign import javascript safe "new virtualdom.VNode($1.tagName, $2.toJS(), $1.children, $1.key, $1.namespace)" ffiVNodeSetProperties :: JSRef VNode -> Immutable.Map -> JSRef VNode properties :: Lens' HTMLElement Immutable.Map properties f (HTMLElement vNode) = fmap (HTMLElement . ffiVNodeSetProperties vNode) (f (ffiVNodeGetProperties vNode)) foreign import javascript safe "Immutable.Map($1.properties.attributes)" ffiVNodeGetAttributes :: JSRef VNode -> Immutable.Map foreign import javascript safe "new virtualdom.VNode($1.tagName, Immutable.Map($1.properties).set('attributes', $2).toJS(), $1.children, $1.key)" ffiVNodeSetAttributes :: JSRef VNode -> Immutable.Map -> JSRef VNode attributes :: Lens' HTMLElement Immutable.Map attributes f (HTMLElement vNode) = fmap (HTMLElement . ffiVNodeSetAttributes vNode) (f (ffiVNodeGetAttributes vNode)) foreign import javascript safe "$1.children" ffiGetVNodeChildren :: JSRef VNode -> JSArray (JSRef VNode) foreign import javascript safe "new virtualdom.VNode($1.tagName, $1.properties, $2, $1.key, $1.namespace)" ffiSetVNodeChildren :: JSRef VNode -> JSArray (JSRef VNode) -> JSRef VNode children :: Lens' HTMLElement (JSArray (JSRef VNode)) children f (HTMLElement vNode) = fmap (HTMLElement . ffiSetVNodeChildren vNode) (f (ffiGetVNodeChildren vNode)) foreign import javascript safe "$1.key" ffiGetVNodeKey :: JSRef VNode -> JSString foreign import javascript safe "new virtualdom.VNode($1.tagName, $1.properties, $1.children, $2, $1.namespace)" ffiSetVNodeKey :: JSRef VNode -> JSString -> JSRef VNode key :: Lens' HTMLElement JSString key f (HTMLElement vNode) = fmap (HTMLElement . ffiSetVNodeKey vNode) (f (ffiGetVNodeKey vNode)) foreign import javascript safe "$1.namespace" ffiGetVNodeNamespace :: JSRef VNode -> JSString foreign import javascript safe "new virtualdom.VNode($1.tagName, $1.properties, $1.children, $1.children, $2)" ffiSetVNodeNamespace :: JSRef VNode -> JSString -> JSRef VNode namespace :: Lens' HTMLElement JSString namespace f (HTMLElement vNode) = fmap (HTMLElement . ffiSetVNodeKey vNode) (f (ffiGetVNodeKey vNode)) foreign import javascript safe "new virtualdom.VNode($1.tagName, Immutable.Map($1.properties).set('ev-' + $2, evHook($3)).toJS(), $1.children, $1.key, $1.namespace)" ffiSetVNodeEvent :: JSRef VNode -> JSString -> JSFun (JSRef Event -> IO ()) -> JSRef VNode on :: MonadState HTMLElement m => JSString -> (JSRef Event -> IO ()) -> m () on ev f = modify (\(HTMLElement vnode) -> HTMLElement (ffiSetVNodeEvent vnode ev (unsafePerformIO (syncCallback1 AlwaysRetain True f)))) foreign import javascript safe "new virtualdom.VNode($1.tagName, Immutable.Map($1.properties).set('hook-' + $2, Object.create({ hook: $3 })).toJS(), $1.children, $1.key, $1.namespace)" ffiRegisterVNodeHook :: JSRef VNode -> JSString -> JSFun (JSRef DOM.HTMLElement -> JSString -> IO ()) -> JSRef VNode registerHook :: MonadState HTMLElement m => JSString -> (JSRef DOM.HTMLElement -> JSString -> IO ()) -> m () registerHook hookName f = modify (\(HTMLElement vnode) -> HTMLElement (ffiRegisterVNodeHook vnode hookName (unsafePerformIO (syncCallback2 AlwaysRetain True f))))
ocharles/virtual-dom
src/VirtualDom/Prim.hs
Haskell
bsd-3-clause
5,318
module Twitch.Run where import Prelude hiding (FilePath, log) import Twitch.Internal ( Dep, runDep ) import Twitch.InternalRule ( Config(dirs, logger), InternalRule, toInternalRule, setupRules ) import Twitch.Rule ( RuleIssue ) import Data.Either ( partitionEithers ) import System.FilePath ( FilePath ) import System.FSNotify ( WatchManager ) import System.Directory ( getCurrentDirectory ) import Twitch.Path ( findAllDirs ) import Data.Default ( Default(def) ) -- This the main interface for running a Dep run :: Dep -> IO WatchManager run dep = do currentDir <- getCurrentDirectory dirs' <- findAllDirs currentDir runWithConfig currentDir (def { logger = print, dirs = dirs' }) dep runWithConfig :: FilePath -> Config -> Dep -> IO WatchManager runWithConfig root config dep = do let (_issues, rules) = depToRules root dep -- TODO handle the issues somehow -- Log and perhaps error setupRules config rules depToRulesWithCurrentDir :: Dep -> IO ([RuleIssue], [InternalRule]) depToRulesWithCurrentDir dep = do currentDir <- getCurrentDirectory return $ depToRules currentDir dep depToRules :: FilePath -> Dep -> ([RuleIssue], [InternalRule]) depToRules currentDir = partitionEithers . map (toInternalRule currentDir) . runDep
jfischoff/twitch
src/Twitch/Run.hs
Haskell
mit
1,264
{-# LANGUAGE TemplateHaskell #-} module Chapter2.Section2.LabInteractive where import Prelude {- Ex 1: Which of the following implementations defines a function putStr' :: String -> IO () that takes a String as its parameter and writes it to the standard output? Note: The helper function putChar :: Char -> IO () takes a character as its parameter and writes it to the standard output. -} putStr' :: String -> IO () -- WRONG --putStr' [] = return "" --putStr' (x : xs) = putChar x >> putStr' xs -- RIGHT putStr' [] = return () putStr' (x : xs) = putChar x >> putStr' xs -- WRONG --putStr' [] = return () --putStr' (x : xs) = putChar x >>= putStr' xs -- WRONG --putStr' [] = return () --putStr' (x : xs) = putStr' xs >>= putChar x {- Ex 2: Choose all possible implementations for a function putStrLn' :: String -> IO () that takes a String parameter and writes it to the standard output, followed by a newline character. Assume "fast and loose" reasoning where there are no bottoms involved, and all functions are total, and all values are finite. -} putStrLn' :: String -> IO () -- RIGHT putStrLn' [] = putChar '\n' putStrLn' xs = putStr' xs >> putStrLn' "" -- RIGHT --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >> putChar '\n' -- RIGHT --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >>= \ x -> putChar '\n' -- WRONG --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >> \ x -> putChar '\n' -- RIGHT -- NOTE: "" instead of '' has been used!!! --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >> putStr' "\n" -- WRONG --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >> putStrLn' "\n" -- WRONG --putStrLn' [] = return "" --putStrLn' xs = putStrLn' xs >> putStr' "\n" -- WRONG --putStrLn' [] = putChar "\n" --putStrLn' xs = putStr' xs >> putChar '\n' {- Ex 3: Which of the following implementation defines a function getLine' :: IO String that reads a line, up to the first \n character, from the standard input? Note: The helper function getChar :: IO Char reads a single character from the standard input. Test #1: Type: getLine' Wait for prompt on new line to appear Type: ab c\nabc It should only return: "abc" -} -- WRONG - returns "abc\\nabc" for INPUT abc\nabc -- WRONG - returns "ab" for INPUT ab c\nabc {- getLine' :: IO String getLine' = get "" get :: String -> IO String get xs = do x <- getChar case x of ' ' -> return xs '\n' -> return xs _ -> get (xs ++ [x]) -} -- WRONG - returns "cban\\cba" {- getLine' :: IO String getLine' = get "" get :: String -> IO String get xs = do x <- getChar case x of '\n' -> return xs _ -> get (x : xs) -} -- - returns "abc\\nabc" -- RIGHT - returns "ab c\\nabc" for INPUT ab c\nabc getLine' :: IO String getLine' = get [] get :: String -> IO String get xs = do x <- getChar case x of '\n' -> return xs _ -> get (xs ++ [x]) -- WRONG - returns "\nabc\\nabc" {- getLine' :: IO String getLine' = get [] get :: String -> IO String get xs = do x <- getChar case x of '\n' -> return (x : xs) _ -> get (xs ++ [x]) -} {- Ex 4: Which of the following implementations defines a function interact' :: (String -> String) -> IO () that takes as its argument a function of type String -> String, and reads a line from the standard input, and passes it to this function, and then prints the resulting output followed by a newline on the standard output? Note: Quick tip: the ' is there because sequence_ is a built-in function. You can use that to see what the behaviour should be. Prelude> :t interact interact :: (String -> String) -> IO () -} -- NO IDEA {- interact' :: (String -> String) -> IO () interact' f = do input <- getLine' putStrLn' (f input) -} {- Ex. 5: Choose all possible implementations of the function sequence_' :: Monad m => [m a] -> m () that takes a finite, non-partial, list of non-bottom, monadic values, and evaluates them in sequence, from left to right, ignoring all (intermediate) results? Hint: Make sure you type in all these definitions in GHCi and play around with a variety of possible input. Test with: sequence_' [(>4), (<10), odd] 7 sequence_' [putChar 'a', putChar 'b', putChar 'c', putChar 'd'] -} sequence_' :: Monad m => [m a] -> m () -- WRONG {- sequence_' [] = return [] sequence_' (m : ms) = m >> \ _ -> sequence_' ms -} {- Test output: <interactive>:2:14: Warning: Defaulting the following constraint(s) to type ‘Integer’ (Ord a0) arising from a use of ‘>’ at <interactive>:2:14 (Num a0) arising from the literal ‘4’ at <interactive>:2:15 (Integral a0) arising from a use of ‘odd’ at <interactive>:2:26-28 In the expression: (> 4) In the first argument of ‘sequence_'’, namely ‘[(> 4), (< 10), odd]’ In the expression: sequence_' [(> 4), (< 10), odd] 7 () -} -- MAYBE {- Check Type Signature Prelude> let sequence_' [] = return () Prelude> let sequence_' (m : ms) = (foldl (>>) m ms) >> return () Prelude> :t sequence_' sequence_' :: Monad m => [m a] -> m () -} sequence_' [] = return () sequence_' (m : ms) = (foldl (>>) m ms) >> return () -- WRONG {- Check Type Signature: Prelude> let sequence_' ms = foldl (>>) (return ()) ms Prelude> :t sequence_' sequence_' :: Monad m => [m ()] -> m () -} {- sequence_' ms = foldl (>>) (return ()) ms -} {- Test output: <interactive>:9:14: Warning: Defaulting the following constraint(s) to type ‘Integer’ (Ord a0) arising from a use of ‘>’ at <interactive>:9:14 (Num a0) arising from the literal ‘4’ at <interactive>:9:16 (Integral a0) arising from a use of ‘odd’ at <interactive>:9:28-30 In the expression: (> 4) In the first argument of ‘sequence_'’, namely ‘[(> 4), (< 10), odd]’ In the expression: sequence_' [(> 4), (< 10), odd] 7 () -} -- WRONG !! MAYBE {- Check Type: Prelude> letsequence_' (m : ms) = m >> sequence_' ms Prelude> let sequence_' (m : ms) = m >> sequence_' ms Prelude> :t sequence_' sequence_' :: Monad m => [m a] -> m b -} {- sequence_' [] = return () sequence_' (m : ms) = m >> sequence_' ms -} {- Test output: <interactive>:19:14: Warning: Defaulting the following constraint(s) to type ‘Integer’ (Ord a0) arising from a use of ‘>’ at <interactive>:19:14 (Num a0) arising from the literal ‘4’ at <interactive>:19:16 (Integral a0) arising from a use of ‘odd’ at <interactive>:19:28-30 In the expression: (> 4) In the first argument of ‘sequence_'’, namely ‘[(> 4), (< 10), odd]’ In the expression: sequence_' [(> 4), (< 10), odd] 7 () -} -- WRONG !! MAYBE {- Check Type: Prelude> let sequence_' [] = return () Prelude> let sequence_' (m : ms) = m >>= \ _ -> sequence_' ms Prelude> :t sequence_' sequence_' :: Monad m => [m a] -> m b -} {- sequence_' [] = return () sequence_' (m : ms) = m >>= \ _ -> sequence_' ms -} {- Test output: Couldn't match type ‘m ()’ with ‘()’ Expected type: m a -> m () -> m () Actual type: m a -> (a -> m ()) -> m () -} -- WRONG {- sequence_' ms = foldr (>>=) (return ()) ms -} {- Test output: <interactive>:29:14: Warning: Defaulting the following constraint(s) to type ‘Integer’ (Ord a0) arising from a use of ‘>’ at <interactive>:29:14 (Num a0) arising from the literal ‘4’ at <interactive>:29:16 (Integral a0) arising from a use of ‘odd’ at <interactive>:29:28-30 In the expression: (> 4) In the first argument of ‘sequence_'’, namely ‘[(> 4), (< 10), odd]’ In the expression: sequence_' [(> 4), (< 10), odd] 7 () -} -- MAYBE {- Check Type: Prelude> let sequence_' ms = foldr (>>) (return ()) ms Prelude> :t sequence_' sequence_' :: Monad m => [m a] -> m () -} {- sequence_' ms = foldr (>>) (return ()) ms -} -- WRONG -- Couldn't match expected type ‘()’ with actual type ‘[t0]’ --sequence_' ms = foldr (>>=) (return []) ms {- Ex. 6: Choose all possible implementations of the function sequence' :: Monad m => [m a] -> m [a] that takes a finite, non-partial, list of non-bottom, monadic values, and evaluates them in sequence, from left to right, collecting all (intermediate) results into a list? Hint: Make sure you type in all these definitions in GHCi and play around with a variety of possible input. Test with: sequence' [(>4), (<10), odd] 7 -} sequence' :: Monad m => [m a] -> m [a] {- RIGHT -} sequence' [] = return [] sequence' (m : ms) = m >>= \ a -> do as <- sequence' ms return (a : as) {- WRONG sequence' ms = foldr func (return ()) ms where func :: (Monad m) => m a -> m [a] -> m [a] func m acc = do x <- m xs <- acc return (x : xs) -} {- WRONG sequence' ms = foldr func (return []) ms where func :: (Monad m) => m a -> m [a] -> m [a] func m acc = m : acc -} {- WRONG sequence' [] = return [] sequence' (m : ms) = return (a : as) where a <- m as <- sequence' ms -} {- RIGHT sequence' ms = foldr func (return []) ms where func :: (Monad m) => m a -> m [a] -> m [a] func m acc = do x <- m xs <- acc return (x : xs) -} {- WRONG sequence' [] = return [] sequence' (m : ms) = m >> \ a -> do as <- sequence' ms return (a : as) -} {- WRONG sequence' [] = return [] sequence' (m : ms) = m >>= \a -> as <- sequence' ms return (a : as) -} {- RIGHT sequence' [] = return [] sequence' (m : ms) = do a <- m as <- sequence' ms return (a : as) -} {- Ex. 7: Choose all possible implementations of a function mapM' :: Monad m => (a -> m b) -> [a] -> m [b] which takes a non-bottom function of type a -> m b, and a finite, non-partial list of non-bottom elements of type a and (similarly to map) applies the function to every element of the list, but produces the resulting list wrapped inside a monadic action? Note: mapM' must preserve the order of the elements of the input list. Hint: Make sure you try each of these options in GHCi and play around with a variety of inputs to experiment with the behaviour. It's easiest to use the IO Monad for the function passed into mapM' Test with: mapM' reverse ["ab","3","12"] Expect: ["b32","b31","a32","a31"] Also test with: mapM' (putChar) ['a', 'b', 'c'] Gives: abc[(),(),()] Also test with: mapM' (\x -> putChar x >> return x) ['a', 'b', 'c'] Gives: abc"abc" -} mapM' :: Monad m => (a -> m b) -> [a] -> m [b] {- RIGHT -} mapM' f as = sequence' (map f as) {- RIGHT mapM' f [] = return [] mapM' f (a : as) = f a >>= \ b -> mapM' f as >>= \ bs -> return (b : bs) -} {- WRONG mapM' f as = sequence_' (map f as) -} {- WRONG mapM' f [] = return [] mapM' f (a : as) = f a >> \ b -> mapM' f as >> \ bs -> return (b : bs) -} {- WRONG mapM' f [] = return [] mapM' f (a : as) = do f a -> b mapM' f as -> bs return (b : bs) -} {- RIGHT mapM' f [] = return [] mapM' f (a : as) = do b <- f a bs <- mapM' f as return (b : bs) -} {- RIGHT mapM' f [] = return [] mapM' f (a : as) = f a >>= \ b -> do bs <- mapM' f as return (b : bs) -} {- WRONG mapM' f [] = return [] mapM' f (a : as ) = f a >>= \ b -> do bs <- mapM' f as return (bs ++ [b]) -} {- Ex. 8: Which of the following definitions implements the function filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a], that takes a "predicate" of type Monad m => a -> m Bool and uses this to filter a finite, non-partial list of non-bottom elements of type a. Note: filterM' must preserve the order of the elements of the input list, as far as they appear in the result. Test with: filterM' True [False,True,False] filterM (const [True, False]) Expect: . -} -- NO IDEA!!! --filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a] {- filterM' _ [] = return [] filterM' p (x : xs) = do flag <- p x ys <- filterM' p xs return (x : ys) -} {- filterM' _ [] = return [] filterM' p (x : xs) = do flag <- p x ys <- filterM' p xs if flag then return (x : ys) else return ys -} {- WRONG filterM' _ [] = return [] filterM' p (x : xs) = do ys <- filterM' p xs if p x then return (x : ys) else return ys -} {- filterM' _ [] = return [] filterM' p (x : xs) = do flag <- p x ys <- filterM' p xs if flag then return ys else return (x : ys) -} {- Ex. 9 Implement the function foldLeftM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a that takes an accumulation function a -> b -> m a, and a seed of type a and left folds a finite, non-partial list of non-bottom elements of type b into a single result of type m a Hint: The recursive structure of foldLeftM looks as follows: foldLeftM f a [] = ... a ... foldLeftM f a (x:xs) = foldLeftM f (... f ... a ... (>>=) ...) xs Remember the definition of foldl: foldl f a [] = ... a ... foldl f a (x:xs) = foldl f (... f ... a ...) xs What is the result of evaluating the expression: haskellhaskell lleksahhaskell haskellhaskellhaskell haskelllleksahhaskell -} {- Proposed approach: Apply the function with the default accumulator and the leftmost element of the list and bind its return (to get rid of the monadic) then proceed to apply the function recursively, passing the same f, but instead of the default accumulator pass it b and the remainder of the list. Noting to 'return a' for the base case -} --foldLeftM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a --foldLeftM (\a b -> putChar b >> return (b : a ++ [b])) [] "haskell" >>= \r -> putStrLn r {- Ex. 10 Implement the function foldRightM :: Monad m => (a -> b -> m b) -> b -> [a] -> m b which is like to foldLeftM from the previous exercise, except that it folds a finite, non-partial list of non-bottom elements of type a into a single monadic value of type m b. Hint: look up the definition of foldr. What is the result of evaluating the expression: ]9,7,5,3,1[[1,3,5,7,9] [9,7,5,3,1][1,3,5,7,9] [1,3,5,7,9][9,7,5,3,1] [1,3,5,7,9][1,3,5,7,9] Note: A simple test like the following won't reveal the flaw in the code foldLeftM (\a b -> Just (a + b)) 0 [1..10] Proper test in GHCi foldRightM' (\a b -> putChar a >> return (a : b)) [] (show [1,3..10]) >>= \r -> putStrLn r Returns: ]9,7,5,3,1[[1,3,5,7,9] -} foldRightM' :: Monad m => (a -> b -> m b) -> b -> [a] -> m b -- carefully compare with the implementation of foldr -- foldRightM' |operator| |init_value| |list| -- Note: the code must be associating to the right and implementing the right fold correctly foldRightM' f d [] = return d foldRightM' f d (x:xs) = (\z -> f x z) <<= foldRightM' f d xs where (<<=) = flip (>>=) -- {- Ex. 11 Choose all possible implementations that define a function liftM :: Monad m => (a -> b) -> m a -> m b that takes a function of type a -> b and "maps" it over a non-bottom monadic value of type m a to produce a value of type m b? -} liftM :: Monad m => (a -> b) -> m a -> m b -- liftM (+1) [1,2] ===> [2,3] -- liftM (+1) [] ===> [] -- RIGHT liftM f m = do x <- m return (f x) -- WRONG --liftM f m = m >>= \ a -> f a -- RIGHT --liftM f m = m >>= \ a -> return (f a) -- WRONG --liftM f m = return (f m) {- WRONG - doesn't map correctly liftM (+1) [1,2] ===> [2,2,3,3] -} --liftM f m = m >>= \ a -> m >>= \ b -> return (f a) {- WRONG - doesn't map correctly liftM (+1) [1,2] ===> [2,3,2,3] -} --liftM f m = m >>= \ a -> m >>= \ b -> return (f b) --WRONG --liftM f m = mapM f [m] --WRONG --liftM f m = m >> \ a -> return (f a)
ltfschoen/HelloHaskell
src/Chapter2/Section2/LabInteractive.hs
Haskell
mit
17,861
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 @Uniques@ are used to distinguish entities in the compiler (@Ids@, @Classes@, etc.) from each other. Thus, @Uniques@ are the basic comparison key in the compiler. If there is any single operation that needs to be fast, it is @Unique@ comparison. Unsurprisingly, there is quite a bit of huff-and-puff directed to that end. Some of the other hair in this code is to be able to use a ``splittable @UniqueSupply@'' if requested/possible (not standard Haskell). -} {-# LANGUAGE CPP, BangPatterns, MagicHash #-} module Unique ( -- * Main data types Unique, Uniquable(..), -- ** Constructors, desctructors and operations on 'Unique's hasKey, cmpByUnique, pprUnique, mkUniqueGrimily, -- Used in UniqSupply only! getKey, -- Used in Var, UniqFM, Name only! mkUnique, unpkUnique, -- Used in BinIface only incrUnique, -- Used for renumbering deriveUnique, -- Ditto newTagUnique, -- Used in CgCase initTyVarUnique, -- ** Making built-in uniques -- now all the built-in Uniques (and functions to make them) -- [the Oh-So-Wonderful Haskell module system wins again...] mkAlphaTyVarUnique, mkPrimOpIdUnique, mkTupleTyConUnique, mkTupleDataConUnique, mkCTupleTyConUnique, mkPreludeMiscIdUnique, mkPreludeDataConUnique, mkPreludeTyConUnique, mkPreludeClassUnique, mkPArrDataConUnique, mkCoVarUnique, mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique, mkRegSingleUnique, mkRegPairUnique, mkRegClassUnique, mkRegSubUnique, mkCostCentreUnique, tyConRepNameUnique, dataConWorkerUnique, dataConRepNameUnique, mkBuiltinUnique, mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH ) where #include "HsVersions.h" import BasicTypes import FastString import Outputable import Util -- just for implementing a fast [0,61) -> Char function import GHC.Exts (indexCharOffAddr#, Char(..), Int(..)) import Data.Char ( chr, ord ) import Data.Bits {- ************************************************************************ * * \subsection[Unique-type]{@Unique@ type and operations} * * ************************************************************************ The @Chars@ are ``tag letters'' that identify the @UniqueSupply@. Fast comparison is everything on @Uniques@: -} --why not newtype Int? -- | The type of unique identifiers that are used in many places in GHC -- for fast ordering and equality tests. You should generate these with -- the functions from the 'UniqSupply' module data Unique = MkUnique {-# UNPACK #-} !Int {- Now come the functions which construct uniques from their pieces, and vice versa. The stuff about unique *supplies* is handled further down this module. -} unpkUnique :: Unique -> (Char, Int) -- The reverse mkUniqueGrimily :: Int -> Unique -- A trap-door for UniqSupply getKey :: Unique -> Int -- for Var incrUnique :: Unique -> Unique stepUnique :: Unique -> Int -> Unique deriveUnique :: Unique -> Int -> Unique newTagUnique :: Unique -> Char -> Unique mkUniqueGrimily = MkUnique {-# INLINE getKey #-} getKey (MkUnique x) = x incrUnique (MkUnique i) = MkUnique (i + 1) stepUnique (MkUnique i) n = MkUnique (i + n) -- deriveUnique uses an 'X' tag so that it won't clash with -- any of the uniques produced any other way -- SPJ says: this looks terribly smelly to me! deriveUnique (MkUnique i) delta = mkUnique 'X' (i + delta) -- newTagUnique changes the "domain" of a unique to a different char newTagUnique u c = mkUnique c i where (_,i) = unpkUnique u -- pop the Char in the top 8 bits of the Unique(Supply) -- No 64-bit bugs here, as long as we have at least 32 bits. --JSM -- and as long as the Char fits in 8 bits, which we assume anyway! mkUnique :: Char -> Int -> Unique -- Builds a unique from pieces -- NOT EXPORTED, so that we can see all the Chars that -- are used in this one module mkUnique c i = MkUnique (tag .|. bits) where tag = ord c `shiftL` 24 bits = i .&. 16777215 {-``0x00ffffff''-} unpkUnique (MkUnique u) = let -- as long as the Char may have its eighth bit set, we -- really do need the logical right-shift here! tag = chr (u `shiftR` 24) i = u .&. 16777215 {-``0x00ffffff''-} in (tag, i) {- ************************************************************************ * * \subsection[Uniquable-class]{The @Uniquable@ class} * * ************************************************************************ -} -- | Class of things that we can obtain a 'Unique' from class Uniquable a where getUnique :: a -> Unique hasKey :: Uniquable a => a -> Unique -> Bool x `hasKey` k = getUnique x == k instance Uniquable FastString where getUnique fs = mkUniqueGrimily (uniqueOfFS fs) instance Uniquable Int where getUnique i = mkUniqueGrimily i cmpByUnique :: Uniquable a => a -> a -> Ordering cmpByUnique x y = (getUnique x) `cmpUnique` (getUnique y) {- ************************************************************************ * * \subsection[Unique-instances]{Instance declarations for @Unique@} * * ************************************************************************ And the whole point (besides uniqueness) is fast equality. We don't use `deriving' because we want {\em precise} control of ordering (equality on @Uniques@ is v common). -} -- Note [Unique Determinism] -- ~~~~~~~~~~~~~~~~~~~~~~~~~ -- The order of allocated @Uniques@ is not stable across rebuilds. -- The main reason for that is that typechecking interface files pulls -- @Uniques@ from @UniqSupply@ and the interface file for the module being -- currently compiled can, but doesn't have to exist. -- -- It gets more complicated if you take into account that the interface -- files are loaded lazily and that building multiple files at once has to -- work for any subset of interface files present. When you add parallelism -- this makes @Uniques@ hopelessly random. -- -- As such, to get deterministic builds, the order of the allocated -- @Uniques@ should not affect the final result. -- see also wiki/DeterministicBuilds eqUnique, ltUnique, leUnique :: Unique -> Unique -> Bool eqUnique (MkUnique u1) (MkUnique u2) = u1 == u2 ltUnique (MkUnique u1) (MkUnique u2) = u1 < u2 leUnique (MkUnique u1) (MkUnique u2) = u1 <= u2 cmpUnique :: Unique -> Unique -> Ordering cmpUnique (MkUnique u1) (MkUnique u2) = if u1 == u2 then EQ else if u1 < u2 then LT else GT instance Eq Unique where a == b = eqUnique a b a /= b = not (eqUnique a b) instance Ord Unique where a < b = ltUnique a b a <= b = leUnique a b a > b = not (leUnique a b) a >= b = not (ltUnique a b) compare a b = cmpUnique a b ----------------- instance Uniquable Unique where getUnique u = u -- We do sometimes make strings with @Uniques@ in them: showUnique :: Unique -> String showUnique uniq = case unpkUnique uniq of (tag, u) -> finish_show tag u (iToBase62 u) finish_show :: Char -> Int -> String -> String finish_show 't' u _pp_u | u < 26 = -- Special case to make v common tyvars, t1, t2, ... -- come out as a, b, ... (shorter, easier to read) [chr (ord 'a' + u)] finish_show tag _ pp_u = tag : pp_u pprUnique :: Unique -> SDoc pprUnique u = text (showUnique u) instance Outputable Unique where ppr = pprUnique instance Show Unique where show uniq = showUnique uniq {- ************************************************************************ * * \subsection[Utils-base62]{Base-62 numbers} * * ************************************************************************ A character-stingy way to read/write numbers (notably Uniques). The ``62-its'' are \tr{[0-9a-zA-Z]}. We don't handle negative Ints. Code stolen from Lennart. -} iToBase62 :: Int -> String iToBase62 n_ = ASSERT(n_ >= 0) go n_ "" where go n cs | n < 62 = let !c = chooseChar62 n in c : cs | otherwise = go q (c : cs) where (q, r) = quotRem n 62 !c = chooseChar62 r chooseChar62 :: Int -> Char {-# INLINE chooseChar62 #-} chooseChar62 (I# n) = C# (indexCharOffAddr# chars62 n) chars62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"# {- ************************************************************************ * * \subsection[Uniques-prelude]{@Uniques@ for wired-in Prelude things} * * ************************************************************************ Allocation of unique supply characters: v,t,u : for renumbering value-, type- and usage- vars. B: builtin C-E: pseudo uniques (used in native-code generator) X: uniques derived by deriveUnique _: unifiable tyvars (above) 0-9: prelude things below (no numbers left any more..) :: (prelude) parallel array data constructors other a-z: lower case chars for unique supplies. Used so far: d desugarer f AbsC flattener g SimplStg n Native codegen r Hsc name cache s simplifier -} mkAlphaTyVarUnique :: Int -> Unique mkPreludeClassUnique :: Int -> Unique mkPreludeTyConUnique :: Int -> Unique mkTupleTyConUnique :: Boxity -> Arity -> Unique mkCTupleTyConUnique :: Arity -> Unique mkPreludeDataConUnique :: Arity -> Unique mkTupleDataConUnique :: Boxity -> Arity -> Unique mkPrimOpIdUnique :: Int -> Unique mkPreludeMiscIdUnique :: Int -> Unique mkPArrDataConUnique :: Int -> Unique mkCoVarUnique :: Int -> Unique mkAlphaTyVarUnique i = mkUnique '1' i mkCoVarUnique i = mkUnique 'g' i mkPreludeClassUnique i = mkUnique '2' i -------------------------------------------------- -- Wired-in type constructor keys occupy *two* slots: -- * u: the TyCon itself -- * u+1: the TyConRepName of the TyCon mkPreludeTyConUnique i = mkUnique '3' (2*i) mkTupleTyConUnique Boxed a = mkUnique '4' (2*a) mkTupleTyConUnique Unboxed a = mkUnique '5' (2*a) mkCTupleTyConUnique a = mkUnique 'k' (2*a) tyConRepNameUnique :: Unique -> Unique tyConRepNameUnique u = incrUnique u -- Data constructor keys occupy *two* slots. The first is used for the -- data constructor itself and its wrapper function (the function that -- evaluates arguments as necessary and calls the worker). The second is -- used for the worker function (the function that builds the constructor -- representation). -------------------------------------------------- -- Wired-in data constructor keys occupy *three* slots: -- * u: the DataCon itself -- * u+1: its worker Id -- * u+2: the TyConRepName of the promoted TyCon -- Prelude data constructors are too simple to need wrappers. mkPreludeDataConUnique i = mkUnique '6' (3*i) -- Must be alphabetic mkTupleDataConUnique Boxed a = mkUnique '7' (3*a) -- ditto (*may* be used in C labels) mkTupleDataConUnique Unboxed a = mkUnique '8' (3*a) dataConRepNameUnique, dataConWorkerUnique :: Unique -> Unique dataConWorkerUnique u = incrUnique u dataConRepNameUnique u = stepUnique u 2 -------------------------------------------------- mkPrimOpIdUnique op = mkUnique '9' op mkPreludeMiscIdUnique i = mkUnique '0' i -- No numbers left anymore, so I pick something different for the character tag mkPArrDataConUnique a = mkUnique ':' (2*a) -- The "tyvar uniques" print specially nicely: a, b, c, etc. -- See pprUnique for details initTyVarUnique :: Unique initTyVarUnique = mkUnique 't' 0 mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH, mkBuiltinUnique :: Int -> Unique mkBuiltinUnique i = mkUnique 'B' i mkPseudoUniqueD i = mkUnique 'D' i -- used in NCG for getUnique on RealRegs mkPseudoUniqueE i = mkUnique 'E' i -- used in NCG spiller to create spill VirtualRegs mkPseudoUniqueH i = mkUnique 'H' i -- used in NCG spiller to create spill VirtualRegs mkRegSingleUnique, mkRegPairUnique, mkRegSubUnique, mkRegClassUnique :: Int -> Unique mkRegSingleUnique = mkUnique 'R' mkRegSubUnique = mkUnique 'S' mkRegPairUnique = mkUnique 'P' mkRegClassUnique = mkUnique 'L' mkCostCentreUnique :: Int -> Unique mkCostCentreUnique = mkUnique 'C' mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique :: FastString -> Unique -- See Note [The Unique of an OccName] in OccName mkVarOccUnique fs = mkUnique 'i' (uniqueOfFS fs) mkDataOccUnique fs = mkUnique 'd' (uniqueOfFS fs) mkTvOccUnique fs = mkUnique 'v' (uniqueOfFS fs) mkTcOccUnique fs = mkUnique 'c' (uniqueOfFS fs)
nushio3/ghc
compiler/basicTypes/Unique.hs
Haskell
bsd-3-clause
13,652
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Setup -- Copyright : Isaac Jones 2003-2004 -- Duncan Coutts 2007 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This is a big module, but not very complicated. The code is very regular -- and repetitive. It defines the command line interface for all the Cabal -- commands. For each command (like @configure@, @build@ etc) it defines a type -- that holds all the flags, the default set of flags and a 'CommandUI' that -- maps command line flags to and from the corresponding flags type. -- -- All the flags types are instances of 'Monoid', see -- <http://www.haskell.org/pipermail/cabal-devel/2007-December/001509.html> -- for an explanation. -- -- The types defined here get used in the front end and especially in -- @cabal-install@ which has to do quite a bit of manipulating sets of command -- line flags. -- -- This is actually relatively nice, it works quite well. The main change it -- needs is to unify it with the code for managing sets of fields that can be -- read and written from files. This would allow us to save configure flags in -- config files. module Distribution.Simple.Setup ( GlobalFlags(..), emptyGlobalFlags, defaultGlobalFlags, globalCommand, ConfigFlags(..), emptyConfigFlags, defaultConfigFlags, configureCommand, configAbsolutePaths, readPackageDbList, showPackageDbList, CopyFlags(..), emptyCopyFlags, defaultCopyFlags, copyCommand, InstallFlags(..), emptyInstallFlags, defaultInstallFlags, installCommand, HaddockFlags(..), emptyHaddockFlags, defaultHaddockFlags, haddockCommand, HscolourFlags(..), emptyHscolourFlags, defaultHscolourFlags, hscolourCommand, BuildFlags(..), emptyBuildFlags, defaultBuildFlags, buildCommand, buildVerbose, ReplFlags(..), defaultReplFlags, replCommand, CleanFlags(..), emptyCleanFlags, defaultCleanFlags, cleanCommand, RegisterFlags(..), emptyRegisterFlags, defaultRegisterFlags, registerCommand, unregisterCommand, SDistFlags(..), emptySDistFlags, defaultSDistFlags, sdistCommand, TestFlags(..), emptyTestFlags, defaultTestFlags, testCommand, TestShowDetails(..), BenchmarkFlags(..), emptyBenchmarkFlags, defaultBenchmarkFlags, benchmarkCommand, CopyDest(..), configureArgs, configureOptions, configureCCompiler, configureLinker, buildOptions, haddockOptions, installDirsOptions, programConfigurationOptions, programConfigurationPaths', splitArgs, defaultDistPref, optionDistPref, Flag(..), toFlag, fromFlag, fromFlagOrDefault, flagToMaybe, flagToList, boolOpt, boolOpt', trueArg, falseArg, optionVerbosity, optionNumJobs ) where import Distribution.Compiler () import Distribution.ReadE import Distribution.Text ( Text(..), display ) import qualified Distribution.Compat.ReadP as Parse import qualified Text.PrettyPrint as Disp import Distribution.ModuleName import Distribution.Package ( Dependency(..) , PackageName , ComponentId(..) ) import Distribution.PackageDescription ( FlagName(..), FlagAssignment ) import Distribution.Simple.Command hiding (boolOpt, boolOpt') import qualified Distribution.Simple.Command as Command import Distribution.Simple.Compiler ( CompilerFlavor(..), defaultCompilerFlavor, PackageDB(..) , DebugInfoLevel(..), flagToDebugInfoLevel , OptimisationLevel(..), flagToOptimisationLevel , ProfDetailLevel(..), flagToProfDetailLevel, showProfDetailLevel , absolutePackageDBPath ) import Distribution.Simple.Utils ( wrapText, wrapLine, lowercase, intercalate ) import Distribution.Simple.Program (Program(..), ProgramConfiguration, requireProgram, programInvocation, progInvokePath, progInvokeArgs, knownPrograms, addKnownProgram, emptyProgramConfiguration, haddockProgram, ghcProgram, gccProgram, ldProgram) import Distribution.Simple.InstallDirs ( InstallDirs(..), CopyDest(..), PathTemplate, toPathTemplate, fromPathTemplate ) import Distribution.Verbosity import Distribution.Utils.NubList import Control.Monad (liftM) import Distribution.Compat.Binary (Binary) import Distribution.Compat.Semigroup as Semi import Data.List ( sort ) import Data.Char ( isSpace, isAlpha ) import GHC.Generics (Generic) -- FIXME Not sure where this should live defaultDistPref :: FilePath defaultDistPref = "dist" -- ------------------------------------------------------------ -- * Flag type -- ------------------------------------------------------------ -- | All flags are monoids, they come in two flavours: -- -- 1. list flags eg -- -- > --ghc-option=foo --ghc-option=bar -- -- gives us all the values ["foo", "bar"] -- -- 2. singular value flags, eg: -- -- > --enable-foo --disable-foo -- -- gives us Just False -- So this Flag type is for the latter singular kind of flag. -- Its monoid instance gives us the behaviour where it starts out as -- 'NoFlag' and later flags override earlier ones. -- data Flag a = Flag a | NoFlag deriving (Eq, Generic, Show, Read) instance Binary a => Binary (Flag a) instance Functor Flag where fmap f (Flag x) = Flag (f x) fmap _ NoFlag = NoFlag instance Monoid (Flag a) where mempty = NoFlag mappend = (Semi.<>) instance Semigroup (Flag a) where _ <> f@(Flag _) = f f <> NoFlag = f instance Bounded a => Bounded (Flag a) where minBound = toFlag minBound maxBound = toFlag maxBound instance Enum a => Enum (Flag a) where fromEnum = fromEnum . fromFlag toEnum = toFlag . toEnum enumFrom (Flag a) = map toFlag . enumFrom $ a enumFrom _ = [] enumFromThen (Flag a) (Flag b) = toFlag `map` enumFromThen a b enumFromThen _ _ = [] enumFromTo (Flag a) (Flag b) = toFlag `map` enumFromTo a b enumFromTo _ _ = [] enumFromThenTo (Flag a) (Flag b) (Flag c) = toFlag `map` enumFromThenTo a b c enumFromThenTo _ _ _ = [] toFlag :: a -> Flag a toFlag = Flag fromFlag :: Flag a -> a fromFlag (Flag x) = x fromFlag NoFlag = error "fromFlag NoFlag. Use fromFlagOrDefault" fromFlagOrDefault :: a -> Flag a -> a fromFlagOrDefault _ (Flag x) = x fromFlagOrDefault def NoFlag = def flagToMaybe :: Flag a -> Maybe a flagToMaybe (Flag x) = Just x flagToMaybe NoFlag = Nothing flagToList :: Flag a -> [a] flagToList (Flag x) = [x] flagToList NoFlag = [] allFlags :: [Flag Bool] -> Flag Bool allFlags flags = if all (\f -> fromFlagOrDefault False f) flags then Flag True else NoFlag -- ------------------------------------------------------------ -- * Global flags -- ------------------------------------------------------------ -- In fact since individual flags types are monoids and these are just sets of -- flags then they are also monoids pointwise. This turns out to be really -- useful. The mempty is the set of empty flags and mappend allows us to -- override specific flags. For example we can start with default flags and -- override with the ones we get from a file or the command line, or both. -- | Flags that apply at the top level, not to any sub-command. data GlobalFlags = GlobalFlags { globalVersion :: Flag Bool, globalNumericVersion :: Flag Bool } defaultGlobalFlags :: GlobalFlags defaultGlobalFlags = GlobalFlags { globalVersion = Flag False, globalNumericVersion = Flag False } globalCommand :: [Command action] -> CommandUI GlobalFlags globalCommand commands = CommandUI { commandName = "" , commandSynopsis = "" , commandUsage = \pname -> "This Setup program uses the Haskell Cabal Infrastructure.\n" ++ "See http://www.haskell.org/cabal/ for more information.\n" ++ "\n" ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n" , commandDescription = Just $ \pname -> let commands' = commands ++ [commandAddAction helpCommandUI undefined] cmdDescs = getNormalCommandDescriptions commands' maxlen = maximum $ [length name | (name, _) <- cmdDescs] align str = str ++ replicate (maxlen - length str) ' ' in "Commands:\n" ++ unlines [ " " ++ align name ++ " " ++ description | (name, description) <- cmdDescs ] ++ "\n" ++ "For more information about a command use\n" ++ " " ++ pname ++ " COMMAND --help\n\n" ++ "Typical steps for installing Cabal packages:\n" ++ concat [ " " ++ pname ++ " " ++ x ++ "\n" | x <- ["configure", "build", "install"]] , commandNotes = Nothing , commandDefaultFlags = defaultGlobalFlags , commandOptions = \_ -> [option ['V'] ["version"] "Print version information" globalVersion (\v flags -> flags { globalVersion = v }) trueArg ,option [] ["numeric-version"] "Print just the version number" globalNumericVersion (\v flags -> flags { globalNumericVersion = v }) trueArg ] } emptyGlobalFlags :: GlobalFlags emptyGlobalFlags = mempty instance Monoid GlobalFlags where mempty = GlobalFlags { globalVersion = mempty, globalNumericVersion = mempty } mappend = (Semi.<>) instance Semigroup GlobalFlags where a <> b = GlobalFlags { globalVersion = combine globalVersion, globalNumericVersion = combine globalNumericVersion } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Config flags -- ------------------------------------------------------------ -- | Flags to @configure@ command. -- -- IMPORTANT: every time a new flag is added, 'D.C.Setup.filterConfigureFlags' -- should be updated. data ConfigFlags = ConfigFlags { --FIXME: the configPrograms is only here to pass info through to configure -- because the type of configure is constrained by the UserHooks. -- when we change UserHooks next we should pass the initial -- ProgramConfiguration directly and not via ConfigFlags configPrograms :: ProgramConfiguration, -- ^All programs that cabal may -- run configProgramPaths :: [(String, FilePath)], -- ^user specified programs paths configProgramArgs :: [(String, [String])], -- ^user specified programs args configProgramPathExtra :: NubList FilePath, -- ^Extend the $PATH configHcFlavor :: Flag CompilerFlavor, -- ^The \"flavor\" of the -- compiler, such as GHC or -- JHC. configHcPath :: Flag FilePath, -- ^given compiler location configHcPkg :: Flag FilePath, -- ^given hc-pkg location configVanillaLib :: Flag Bool, -- ^Enable vanilla library configProfLib :: Flag Bool, -- ^Enable profiling in the library configSharedLib :: Flag Bool, -- ^Build shared library configDynExe :: Flag Bool, -- ^Enable dynamic linking of the -- executables. configProfExe :: Flag Bool, -- ^Enable profiling in the -- executables. configProf :: Flag Bool, -- ^Enable profiling in the library -- and executables. configProfDetail :: Flag ProfDetailLevel, -- ^Profiling detail level -- in the library and executables. configProfLibDetail :: Flag ProfDetailLevel, -- ^Profiling detail level -- in the library configConfigureArgs :: [String], -- ^Extra arguments to @configure@ configOptimization :: Flag OptimisationLevel, -- ^Enable optimization. configProgPrefix :: Flag PathTemplate, -- ^Installed executable prefix. configProgSuffix :: Flag PathTemplate, -- ^Installed executable suffix. configInstallDirs :: InstallDirs (Flag PathTemplate), -- ^Installation -- paths configScratchDir :: Flag FilePath, configExtraLibDirs :: [FilePath], -- ^ path to search for extra libraries configExtraIncludeDirs :: [FilePath], -- ^ path to search for header files configIPID :: Flag String, -- ^ explicit IPID to be used configDistPref :: Flag FilePath, -- ^"dist" prefix configVerbosity :: Flag Verbosity, -- ^verbosity level configUserInstall :: Flag Bool, -- ^The --user\/--global flag configPackageDBs :: [Maybe PackageDB], -- ^Which package DBs to use configGHCiLib :: Flag Bool, -- ^Enable compiling library for GHCi configSplitObjs :: Flag Bool, -- ^Enable -split-objs with GHC configStripExes :: Flag Bool, -- ^Enable executable stripping configStripLibs :: Flag Bool, -- ^Enable library stripping configConstraints :: [Dependency], -- ^Additional constraints for -- dependencies. configDependencies :: [(PackageName, ComponentId)], configInstantiateWith :: [(ModuleName, (ComponentId, ModuleName))], -- ^The packages depended on. configConfigurationsFlags :: FlagAssignment, configTests :: Flag Bool, -- ^Enable test suite compilation configBenchmarks :: Flag Bool, -- ^Enable benchmark compilation configCoverage :: Flag Bool, -- ^Enable program coverage configLibCoverage :: Flag Bool, -- ^Enable program coverage (deprecated) configExactConfiguration :: Flag Bool, -- ^All direct dependencies and flags are provided on the command line by -- the user via the '--dependency' and '--flags' options. configFlagError :: Flag String, -- ^Halt and show an error message indicating an error in flag assignment configRelocatable :: Flag Bool, -- ^ Enable relocatable package built configDebugInfo :: Flag DebugInfoLevel -- ^ Emit debug info. } deriving (Generic, Read, Show) instance Binary ConfigFlags configAbsolutePaths :: ConfigFlags -> IO ConfigFlags configAbsolutePaths f = (\v -> f { configPackageDBs = v }) `liftM` mapM (maybe (return Nothing) (liftM Just . absolutePackageDBPath)) (configPackageDBs f) defaultConfigFlags :: ProgramConfiguration -> ConfigFlags defaultConfigFlags progConf = emptyConfigFlags { configPrograms = progConf, configHcFlavor = maybe NoFlag Flag defaultCompilerFlavor, configVanillaLib = Flag True, configProfLib = NoFlag, configSharedLib = NoFlag, configDynExe = Flag False, configProfExe = NoFlag, configProf = NoFlag, configProfDetail = NoFlag, configProfLibDetail= NoFlag, configOptimization = Flag NormalOptimisation, configProgPrefix = Flag (toPathTemplate ""), configProgSuffix = Flag (toPathTemplate ""), configDistPref = NoFlag, configVerbosity = Flag normal, configUserInstall = Flag False, --TODO: reverse this #if defined(mingw32_HOST_OS) -- See #1589. configGHCiLib = Flag True, #else configGHCiLib = NoFlag, #endif configSplitObjs = Flag False, -- takes longer, so turn off by default configStripExes = Flag True, configStripLibs = Flag True, configTests = Flag False, configBenchmarks = Flag False, configCoverage = Flag False, configLibCoverage = NoFlag, configExactConfiguration = Flag False, configFlagError = NoFlag, configRelocatable = Flag False, configDebugInfo = Flag NoDebugInfo } configureCommand :: ProgramConfiguration -> CommandUI ConfigFlags configureCommand progConf = CommandUI { commandName = "configure" , commandSynopsis = "Prepare to build the package." , commandDescription = Just $ \_ -> wrapText $ "Configure how the package is built by setting " ++ "package (and other) flags.\n" ++ "\n" ++ "The configuration affects several other commands, " ++ "including build, test, bench, run, repl.\n" , commandNotes = Just $ \_pname -> programFlagsDescription progConf , commandUsage = \pname -> "Usage: " ++ pname ++ " configure [FLAGS]\n" , commandDefaultFlags = defaultConfigFlags progConf , commandOptions = \showOrParseArgs -> configureOptions showOrParseArgs ++ programConfigurationPaths progConf showOrParseArgs configProgramPaths (\v fs -> fs { configProgramPaths = v }) ++ programConfigurationOption progConf showOrParseArgs configProgramArgs (\v fs -> fs { configProgramArgs = v }) ++ programConfigurationOptions progConf showOrParseArgs configProgramArgs (\v fs -> fs { configProgramArgs = v }) } configureOptions :: ShowOrParseArgs -> [OptionField ConfigFlags] configureOptions showOrParseArgs = [optionVerbosity configVerbosity (\v flags -> flags { configVerbosity = v }) ,optionDistPref configDistPref (\d flags -> flags { configDistPref = d }) showOrParseArgs ,option [] ["compiler"] "compiler" configHcFlavor (\v flags -> flags { configHcFlavor = v }) (choiceOpt [ (Flag GHC, ("g", ["ghc"]), "compile with GHC") , (Flag GHCJS, ([] , ["ghcjs"]), "compile with GHCJS") , (Flag JHC, ([] , ["jhc"]), "compile with JHC") , (Flag LHC, ([] , ["lhc"]), "compile with LHC") , (Flag UHC, ([] , ["uhc"]), "compile with UHC") -- "haskell-suite" compiler id string will be replaced -- by a more specific one during the configure stage , (Flag (HaskellSuite "haskell-suite"), ([] , ["haskell-suite"]), "compile with a haskell-suite compiler")]) ,option "w" ["with-compiler"] "give the path to a particular compiler" configHcPath (\v flags -> flags { configHcPath = v }) (reqArgFlag "PATH") ,option "" ["with-hc-pkg"] "give the path to the package tool" configHcPkg (\v flags -> flags { configHcPkg = v }) (reqArgFlag "PATH") ] ++ map liftInstallDirs installDirsOptions ++ [option "" ["program-prefix"] "prefix to be applied to installed executables" configProgPrefix (\v flags -> flags { configProgPrefix = v }) (reqPathTemplateArgFlag "PREFIX") ,option "" ["program-suffix"] "suffix to be applied to installed executables" configProgSuffix (\v flags -> flags { configProgSuffix = v } ) (reqPathTemplateArgFlag "SUFFIX") ,option "" ["library-vanilla"] "Vanilla libraries" configVanillaLib (\v flags -> flags { configVanillaLib = v }) (boolOpt [] []) ,option "p" ["library-profiling"] "Library profiling" configProfLib (\v flags -> flags { configProfLib = v }) (boolOpt "p" []) ,option "" ["shared"] "Shared library" configSharedLib (\v flags -> flags { configSharedLib = v }) (boolOpt [] []) ,option "" ["executable-dynamic"] "Executable dynamic linking" configDynExe (\v flags -> flags { configDynExe = v }) (boolOpt [] []) ,option "" ["profiling"] "Executable and library profiling" configProf (\v flags -> flags { configProf = v }) (boolOpt [] []) ,option "" ["executable-profiling"] "Executable profiling (DEPRECATED)" configProfExe (\v flags -> flags { configProfExe = v }) (boolOpt [] []) ,option "" ["profiling-detail"] ("Profiling detail level for executable and library (default, " ++ "none, exported-functions, toplevel-functions, all-functions).") configProfDetail (\v flags -> flags { configProfDetail = v }) (reqArg' "level" (Flag . flagToProfDetailLevel) showProfDetailLevelFlag) ,option "" ["library-profiling-detail"] "Profiling detail level for libraries only." configProfLibDetail (\v flags -> flags { configProfLibDetail = v }) (reqArg' "level" (Flag . flagToProfDetailLevel) showProfDetailLevelFlag) ,multiOption "optimization" configOptimization (\v flags -> flags { configOptimization = v }) [optArg' "n" (Flag . flagToOptimisationLevel) (\f -> case f of Flag NoOptimisation -> [] Flag NormalOptimisation -> [Nothing] Flag MaximumOptimisation -> [Just "2"] _ -> []) "O" ["enable-optimization","enable-optimisation"] "Build with optimization (n is 0--2, default is 1)", noArg (Flag NoOptimisation) [] ["disable-optimization","disable-optimisation"] "Build without optimization" ] ,multiOption "debug-info" configDebugInfo (\v flags -> flags { configDebugInfo = v }) [optArg' "n" (Flag . flagToDebugInfoLevel) (\f -> case f of Flag NoDebugInfo -> [] Flag MinimalDebugInfo -> [Just "1"] Flag NormalDebugInfo -> [Nothing] Flag MaximalDebugInfo -> [Just "3"] _ -> []) "" ["enable-debug-info"] "Emit debug info (n is 0--3, default is 0)", noArg (Flag NoDebugInfo) [] ["disable-debug-info"] "Don't emit debug info" ] ,option "" ["library-for-ghci"] "compile library for use with GHCi" configGHCiLib (\v flags -> flags { configGHCiLib = v }) (boolOpt [] []) ,option "" ["split-objs"] "split library into smaller objects to reduce binary sizes (GHC 6.6+)" configSplitObjs (\v flags -> flags { configSplitObjs = v }) (boolOpt [] []) ,option "" ["executable-stripping"] "strip executables upon installation to reduce binary sizes" configStripExes (\v flags -> flags { configStripExes = v }) (boolOpt [] []) ,option "" ["library-stripping"] "strip libraries upon installation to reduce binary sizes" configStripLibs (\v flags -> flags { configStripLibs = v }) (boolOpt [] []) ,option "" ["configure-option"] "Extra option for configure" configConfigureArgs (\v flags -> flags { configConfigureArgs = v }) (reqArg' "OPT" (\x -> [x]) id) ,option "" ["user-install"] "doing a per-user installation" configUserInstall (\v flags -> flags { configUserInstall = v }) (boolOpt' ([],["user"]) ([], ["global"])) ,option "" ["package-db"] ( "Append the given package database to the list of package" ++ " databases used (to satisfy dependencies and register into)." ++ " May be a specific file, 'global' or 'user'. The initial list" ++ " is ['global'], ['global', 'user'], or ['global', $sandbox]," ++ " depending on context. Use 'clear' to reset the list to empty." ++ " See the user guide for details.") configPackageDBs (\v flags -> flags { configPackageDBs = v }) (reqArg' "DB" readPackageDbList showPackageDbList) ,option "f" ["flags"] "Force values for the given flags in Cabal conditionals in the .cabal file. E.g., --flags=\"debug -usebytestrings\" forces the flag \"debug\" to true and \"usebytestrings\" to false." configConfigurationsFlags (\v flags -> flags { configConfigurationsFlags = v }) (reqArg' "FLAGS" readFlagList showFlagList) ,option "" ["extra-include-dirs"] "A list of directories to search for header files" configExtraIncludeDirs (\v flags -> flags {configExtraIncludeDirs = v}) (reqArg' "PATH" (\x -> [x]) id) ,option "" ["ipid"] "Installed package ID to compile this package as" configIPID (\v flags -> flags {configIPID = v}) (reqArgFlag "IPID") ,option "" ["extra-lib-dirs"] "A list of directories to search for external libraries" configExtraLibDirs (\v flags -> flags {configExtraLibDirs = v}) (reqArg' "PATH" (\x -> [x]) id) ,option "" ["extra-prog-path"] "A list of directories to search for required programs (in addition to the normal search locations)" configProgramPathExtra (\v flags -> flags {configProgramPathExtra = v}) (reqArg' "PATH" (\x -> toNubList [x]) fromNubList) ,option "" ["constraint"] "A list of additional constraints on the dependencies." configConstraints (\v flags -> flags { configConstraints = v}) (reqArg "DEPENDENCY" (readP_to_E (const "dependency expected") ((\x -> [x]) `fmap` parse)) (map (\x -> display x))) ,option "" ["dependency"] "A list of exact dependencies. E.g., --dependency=\"void=void-0.5.8-177d5cdf20962d0581fe2e4932a6c309\"" configDependencies (\v flags -> flags { configDependencies = v}) (reqArg "NAME=ID" (readP_to_E (const "dependency expected") ((\x -> [x]) `fmap` parseDependency)) (map (\x -> display (fst x) ++ "=" ++ display (snd x)))) ,option "" ["instantiate-with"] "A mapping of signature names to concrete module instantiations. E.g., --instantiate-with=\"Map=Data.Map.Strict@containers-0.5.5.1-inplace\"" configInstantiateWith (\v flags -> flags { configInstantiateWith = v }) (reqArg "NAME=PKG:MOD" (readP_to_E (const "signature mapping expected") ((\x -> [x]) `fmap` parseHoleMapEntry)) (map (\(n,(p,m)) -> display n ++ "=" ++ display m ++ "@" ++ display p))) ,option "" ["tests"] "dependency checking and compilation for test suites listed in the package description file." configTests (\v flags -> flags { configTests = v }) (boolOpt [] []) ,option "" ["coverage"] "build package with Haskell Program Coverage. (GHC only)" configCoverage (\v flags -> flags { configCoverage = v }) (boolOpt [] []) ,option "" ["library-coverage"] "build package with Haskell Program Coverage. (GHC only) (DEPRECATED)" configLibCoverage (\v flags -> flags { configLibCoverage = v }) (boolOpt [] []) ,option "" ["exact-configuration"] "All direct dependencies and flags are provided on the command line." configExactConfiguration (\v flags -> flags { configExactConfiguration = v }) trueArg ,option "" ["benchmarks"] "dependency checking and compilation for benchmarks listed in the package description file." configBenchmarks (\v flags -> flags { configBenchmarks = v }) (boolOpt [] []) ,option "" ["relocatable"] "building a package that is relocatable. (GHC only)" configRelocatable (\v flags -> flags { configRelocatable = v}) (boolOpt [] []) ] where readFlagList :: String -> FlagAssignment readFlagList = map tagWithValue . words where tagWithValue ('-':fname) = (FlagName (lowercase fname), False) tagWithValue fname = (FlagName (lowercase fname), True) showFlagList :: FlagAssignment -> [String] showFlagList fs = [ if not set then '-':fname else fname | (FlagName fname, set) <- fs] liftInstallDirs = liftOption configInstallDirs (\v flags -> flags { configInstallDirs = v }) reqPathTemplateArgFlag title _sf _lf d get set = reqArgFlag title _sf _lf d (fmap fromPathTemplate . get) (set . fmap toPathTemplate) readPackageDbList :: String -> [Maybe PackageDB] readPackageDbList "clear" = [Nothing] readPackageDbList "global" = [Just GlobalPackageDB] readPackageDbList "user" = [Just UserPackageDB] readPackageDbList other = [Just (SpecificPackageDB other)] showPackageDbList :: [Maybe PackageDB] -> [String] showPackageDbList = map showPackageDb where showPackageDb Nothing = "clear" showPackageDb (Just GlobalPackageDB) = "global" showPackageDb (Just UserPackageDB) = "user" showPackageDb (Just (SpecificPackageDB db)) = db showProfDetailLevelFlag :: Flag ProfDetailLevel -> [String] showProfDetailLevelFlag NoFlag = [] showProfDetailLevelFlag (Flag dl) = [showProfDetailLevel dl] parseDependency :: Parse.ReadP r (PackageName, ComponentId) parseDependency = do x <- parse _ <- Parse.char '=' y <- parse return (x, y) parseHoleMapEntry :: Parse.ReadP r (ModuleName, (ComponentId, ModuleName)) parseHoleMapEntry = do x <- parse _ <- Parse.char '=' y <- parse _ <- Parse.char '@' z <- parse return (x, (z, y)) installDirsOptions :: [OptionField (InstallDirs (Flag PathTemplate))] installDirsOptions = [ option "" ["prefix"] "bake this prefix in preparation of installation" prefix (\v flags -> flags { prefix = v }) installDirArg , option "" ["bindir"] "installation directory for executables" bindir (\v flags -> flags { bindir = v }) installDirArg , option "" ["libdir"] "installation directory for libraries" libdir (\v flags -> flags { libdir = v }) installDirArg , option "" ["libsubdir"] "subdirectory of libdir in which libs are installed" libsubdir (\v flags -> flags { libsubdir = v }) installDirArg , option "" ["libexecdir"] "installation directory for program executables" libexecdir (\v flags -> flags { libexecdir = v }) installDirArg , option "" ["datadir"] "installation directory for read-only data" datadir (\v flags -> flags { datadir = v }) installDirArg , option "" ["datasubdir"] "subdirectory of datadir in which data files are installed" datasubdir (\v flags -> flags { datasubdir = v }) installDirArg , option "" ["docdir"] "installation directory for documentation" docdir (\v flags -> flags { docdir = v }) installDirArg , option "" ["htmldir"] "installation directory for HTML documentation" htmldir (\v flags -> flags { htmldir = v }) installDirArg , option "" ["haddockdir"] "installation directory for haddock interfaces" haddockdir (\v flags -> flags { haddockdir = v }) installDirArg , option "" ["sysconfdir"] "installation directory for configuration files" sysconfdir (\v flags -> flags { sysconfdir = v }) installDirArg ] where installDirArg _sf _lf d get set = reqArgFlag "DIR" _sf _lf d (fmap fromPathTemplate . get) (set . fmap toPathTemplate) emptyConfigFlags :: ConfigFlags emptyConfigFlags = mempty instance Monoid ConfigFlags where mempty = ConfigFlags { configPrograms = error "FIXME: remove configPrograms", configProgramPaths = mempty, configProgramArgs = mempty, configProgramPathExtra = mempty, configHcFlavor = mempty, configHcPath = mempty, configHcPkg = mempty, configVanillaLib = mempty, configProfLib = mempty, configSharedLib = mempty, configDynExe = mempty, configProfExe = mempty, configProf = mempty, configProfDetail = mempty, configProfLibDetail = mempty, configConfigureArgs = mempty, configOptimization = mempty, configProgPrefix = mempty, configProgSuffix = mempty, configInstallDirs = mempty, configScratchDir = mempty, configDistPref = mempty, configVerbosity = mempty, configUserInstall = mempty, configPackageDBs = mempty, configGHCiLib = mempty, configSplitObjs = mempty, configStripExes = mempty, configStripLibs = mempty, configExtraLibDirs = mempty, configConstraints = mempty, configDependencies = mempty, configInstantiateWith = mempty, configExtraIncludeDirs = mempty, configIPID = mempty, configConfigurationsFlags = mempty, configTests = mempty, configCoverage = mempty, configLibCoverage = mempty, configExactConfiguration = mempty, configBenchmarks = mempty, configFlagError = mempty, configRelocatable = mempty, configDebugInfo = mempty } mappend = (Semi.<>) instance Semigroup ConfigFlags where a <> b = ConfigFlags { configPrograms = configPrograms b, configProgramPaths = combine configProgramPaths, configProgramArgs = combine configProgramArgs, configProgramPathExtra = combine configProgramPathExtra, configHcFlavor = combine configHcFlavor, configHcPath = combine configHcPath, configHcPkg = combine configHcPkg, configVanillaLib = combine configVanillaLib, configProfLib = combine configProfLib, configSharedLib = combine configSharedLib, configDynExe = combine configDynExe, configProfExe = combine configProfExe, configProf = combine configProf, configProfDetail = combine configProfDetail, configProfLibDetail = combine configProfLibDetail, configConfigureArgs = combine configConfigureArgs, configOptimization = combine configOptimization, configProgPrefix = combine configProgPrefix, configProgSuffix = combine configProgSuffix, configInstallDirs = combine configInstallDirs, configScratchDir = combine configScratchDir, configDistPref = combine configDistPref, configVerbosity = combine configVerbosity, configUserInstall = combine configUserInstall, configPackageDBs = combine configPackageDBs, configGHCiLib = combine configGHCiLib, configSplitObjs = combine configSplitObjs, configStripExes = combine configStripExes, configStripLibs = combine configStripLibs, configExtraLibDirs = combine configExtraLibDirs, configConstraints = combine configConstraints, configDependencies = combine configDependencies, configInstantiateWith = combine configInstantiateWith, configExtraIncludeDirs = combine configExtraIncludeDirs, configIPID = combine configIPID, configConfigurationsFlags = combine configConfigurationsFlags, configTests = combine configTests, configCoverage = combine configCoverage, configLibCoverage = combine configLibCoverage, configExactConfiguration = combine configExactConfiguration, configBenchmarks = combine configBenchmarks, configFlagError = combine configFlagError, configRelocatable = combine configRelocatable, configDebugInfo = combine configDebugInfo } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Copy flags -- ------------------------------------------------------------ -- | Flags to @copy@: (destdir, copy-prefix (backwards compat), verbosity) data CopyFlags = CopyFlags { copyDest :: Flag CopyDest, copyDistPref :: Flag FilePath, copyVerbosity :: Flag Verbosity } deriving Show defaultCopyFlags :: CopyFlags defaultCopyFlags = CopyFlags { copyDest = Flag NoCopyDest, copyDistPref = NoFlag, copyVerbosity = Flag normal } copyCommand :: CommandUI CopyFlags copyCommand = CommandUI { commandName = "copy" , commandSynopsis = "Copy the files into the install locations." , commandDescription = Just $ \_ -> wrapText $ "Does not call register, and allows a prefix at install time. " ++ "Without the --destdir flag, configure determines location.\n" , commandNotes = Nothing , commandUsage = \pname -> "Usage: " ++ pname ++ " copy [FLAGS]\n" , commandDefaultFlags = defaultCopyFlags , commandOptions = \showOrParseArgs -> [optionVerbosity copyVerbosity (\v flags -> flags { copyVerbosity = v }) ,optionDistPref copyDistPref (\d flags -> flags { copyDistPref = d }) showOrParseArgs ,option "" ["destdir"] "directory to copy files to, prepended to installation directories" copyDest (\v flags -> flags { copyDest = v }) (reqArg "DIR" (succeedReadE (Flag . CopyTo)) (\f -> case f of Flag (CopyTo p) -> [p]; _ -> [])) ] } emptyCopyFlags :: CopyFlags emptyCopyFlags = mempty instance Monoid CopyFlags where mempty = CopyFlags { copyDest = mempty, copyDistPref = mempty, copyVerbosity = mempty } mappend = (Semi.<>) instance Semigroup CopyFlags where a <> b = CopyFlags { copyDest = combine copyDest, copyDistPref = combine copyDistPref, copyVerbosity = combine copyVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Install flags -- ------------------------------------------------------------ -- | Flags to @install@: (package db, verbosity) data InstallFlags = InstallFlags { installPackageDB :: Flag PackageDB, installDistPref :: Flag FilePath, installUseWrapper :: Flag Bool, installInPlace :: Flag Bool, installVerbosity :: Flag Verbosity } deriving Show defaultInstallFlags :: InstallFlags defaultInstallFlags = InstallFlags { installPackageDB = NoFlag, installDistPref = NoFlag, installUseWrapper = Flag False, installInPlace = Flag False, installVerbosity = Flag normal } installCommand :: CommandUI InstallFlags installCommand = CommandUI { commandName = "install" , commandSynopsis = "Copy the files into the install locations. Run register." , commandDescription = Just $ \_ -> wrapText $ "Unlike the copy command, install calls the register command." ++ "If you want to install into a location that is not what was" ++ "specified in the configure step, use the copy command.\n" , commandNotes = Nothing , commandUsage = \pname -> "Usage: " ++ pname ++ " install [FLAGS]\n" , commandDefaultFlags = defaultInstallFlags , commandOptions = \showOrParseArgs -> [optionVerbosity installVerbosity (\v flags -> flags { installVerbosity = v }) ,optionDistPref installDistPref (\d flags -> flags { installDistPref = d }) showOrParseArgs ,option "" ["inplace"] "install the package in the install subdirectory of the dist prefix, so it can be used without being installed" installInPlace (\v flags -> flags { installInPlace = v }) trueArg ,option "" ["shell-wrappers"] "using shell script wrappers around executables" installUseWrapper (\v flags -> flags { installUseWrapper = v }) (boolOpt [] []) ,option "" ["package-db"] "" installPackageDB (\v flags -> flags { installPackageDB = v }) (choiceOpt [ (Flag UserPackageDB, ([],["user"]), "upon configuration register this package in the user's local package database") , (Flag GlobalPackageDB, ([],["global"]), "(default) upon configuration register this package in the system-wide package database")]) ] } emptyInstallFlags :: InstallFlags emptyInstallFlags = mempty instance Monoid InstallFlags where mempty = InstallFlags{ installPackageDB = mempty, installDistPref = mempty, installUseWrapper = mempty, installInPlace = mempty, installVerbosity = mempty } mappend = (Semi.<>) instance Semigroup InstallFlags where a <> b = InstallFlags{ installPackageDB = combine installPackageDB, installDistPref = combine installDistPref, installUseWrapper = combine installUseWrapper, installInPlace = combine installInPlace, installVerbosity = combine installVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * SDist flags -- ------------------------------------------------------------ -- | Flags to @sdist@: (snapshot, verbosity) data SDistFlags = SDistFlags { sDistSnapshot :: Flag Bool, sDistDirectory :: Flag FilePath, sDistDistPref :: Flag FilePath, sDistListSources :: Flag FilePath, sDistVerbosity :: Flag Verbosity } deriving Show defaultSDistFlags :: SDistFlags defaultSDistFlags = SDistFlags { sDistSnapshot = Flag False, sDistDirectory = mempty, sDistDistPref = NoFlag, sDistListSources = mempty, sDistVerbosity = Flag normal } sdistCommand :: CommandUI SDistFlags sdistCommand = CommandUI { commandName = "sdist" , commandSynopsis = "Generate a source distribution file (.tar.gz)." , commandDescription = Nothing , commandNotes = Nothing , commandUsage = \pname -> "Usage: " ++ pname ++ " sdist [FLAGS]\n" , commandDefaultFlags = defaultSDistFlags , commandOptions = \showOrParseArgs -> [optionVerbosity sDistVerbosity (\v flags -> flags { sDistVerbosity = v }) ,optionDistPref sDistDistPref (\d flags -> flags { sDistDistPref = d }) showOrParseArgs ,option "" ["list-sources"] "Just write a list of the package's sources to a file" sDistListSources (\v flags -> flags { sDistListSources = v }) (reqArgFlag "FILE") ,option "" ["snapshot"] "Produce a snapshot source distribution" sDistSnapshot (\v flags -> flags { sDistSnapshot = v }) trueArg ,option "" ["output-directory"] ("Generate a source distribution in the given directory, " ++ "without creating a tarball") sDistDirectory (\v flags -> flags { sDistDirectory = v }) (reqArgFlag "DIR") ] } emptySDistFlags :: SDistFlags emptySDistFlags = mempty instance Monoid SDistFlags where mempty = SDistFlags { sDistSnapshot = mempty, sDistDirectory = mempty, sDistDistPref = mempty, sDistListSources = mempty, sDistVerbosity = mempty } mappend = (Semi.<>) instance Semigroup SDistFlags where a <> b = SDistFlags { sDistSnapshot = combine sDistSnapshot, sDistDirectory = combine sDistDirectory, sDistDistPref = combine sDistDistPref, sDistListSources = combine sDistListSources, sDistVerbosity = combine sDistVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Register flags -- ------------------------------------------------------------ -- | Flags to @register@ and @unregister@: (user package, gen-script, -- in-place, verbosity) data RegisterFlags = RegisterFlags { regPackageDB :: Flag PackageDB, regGenScript :: Flag Bool, regGenPkgConf :: Flag (Maybe FilePath), regInPlace :: Flag Bool, regDistPref :: Flag FilePath, regPrintId :: Flag Bool, regVerbosity :: Flag Verbosity } deriving Show defaultRegisterFlags :: RegisterFlags defaultRegisterFlags = RegisterFlags { regPackageDB = NoFlag, regGenScript = Flag False, regGenPkgConf = NoFlag, regInPlace = Flag False, regDistPref = NoFlag, regPrintId = Flag False, regVerbosity = Flag normal } registerCommand :: CommandUI RegisterFlags registerCommand = CommandUI { commandName = "register" , commandSynopsis = "Register this package with the compiler." , commandDescription = Nothing , commandNotes = Nothing , commandUsage = \pname -> "Usage: " ++ pname ++ " register [FLAGS]\n" , commandDefaultFlags = defaultRegisterFlags , commandOptions = \showOrParseArgs -> [optionVerbosity regVerbosity (\v flags -> flags { regVerbosity = v }) ,optionDistPref regDistPref (\d flags -> flags { regDistPref = d }) showOrParseArgs ,option "" ["packageDB"] "" regPackageDB (\v flags -> flags { regPackageDB = v }) (choiceOpt [ (Flag UserPackageDB, ([],["user"]), "upon registration, register this package in the user's local package database") , (Flag GlobalPackageDB, ([],["global"]), "(default)upon registration, register this package in the system-wide package database")]) ,option "" ["inplace"] "register the package in the build location, so it can be used without being installed" regInPlace (\v flags -> flags { regInPlace = v }) trueArg ,option "" ["gen-script"] "instead of registering, generate a script to register later" regGenScript (\v flags -> flags { regGenScript = v }) trueArg ,option "" ["gen-pkg-config"] "instead of registering, generate a package registration file" regGenPkgConf (\v flags -> flags { regGenPkgConf = v }) (optArg' "PKG" Flag flagToList) ,option "" ["print-ipid"] "print the installed package ID calculated for this package" regPrintId (\v flags -> flags { regPrintId = v }) trueArg ] } unregisterCommand :: CommandUI RegisterFlags unregisterCommand = CommandUI { commandName = "unregister" , commandSynopsis = "Unregister this package with the compiler." , commandDescription = Nothing , commandNotes = Nothing , commandUsage = \pname -> "Usage: " ++ pname ++ " unregister [FLAGS]\n" , commandDefaultFlags = defaultRegisterFlags , commandOptions = \showOrParseArgs -> [optionVerbosity regVerbosity (\v flags -> flags { regVerbosity = v }) ,optionDistPref regDistPref (\d flags -> flags { regDistPref = d }) showOrParseArgs ,option "" ["user"] "" regPackageDB (\v flags -> flags { regPackageDB = v }) (choiceOpt [ (Flag UserPackageDB, ([],["user"]), "unregister this package in the user's local package database") , (Flag GlobalPackageDB, ([],["global"]), "(default) unregister this package in the system-wide package database")]) ,option "" ["gen-script"] "Instead of performing the unregister command, generate a script to unregister later" regGenScript (\v flags -> flags { regGenScript = v }) trueArg ] } emptyRegisterFlags :: RegisterFlags emptyRegisterFlags = mempty instance Monoid RegisterFlags where mempty = RegisterFlags { regPackageDB = mempty, regGenScript = mempty, regGenPkgConf = mempty, regInPlace = mempty, regPrintId = mempty, regDistPref = mempty, regVerbosity = mempty } mappend = (Semi.<>) instance Semigroup RegisterFlags where a <> b = RegisterFlags { regPackageDB = combine regPackageDB, regGenScript = combine regGenScript, regGenPkgConf = combine regGenPkgConf, regInPlace = combine regInPlace, regPrintId = combine regPrintId, regDistPref = combine regDistPref, regVerbosity = combine regVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * HsColour flags -- ------------------------------------------------------------ data HscolourFlags = HscolourFlags { hscolourCSS :: Flag FilePath, hscolourExecutables :: Flag Bool, hscolourTestSuites :: Flag Bool, hscolourBenchmarks :: Flag Bool, hscolourDistPref :: Flag FilePath, hscolourVerbosity :: Flag Verbosity } deriving Show emptyHscolourFlags :: HscolourFlags emptyHscolourFlags = mempty defaultHscolourFlags :: HscolourFlags defaultHscolourFlags = HscolourFlags { hscolourCSS = NoFlag, hscolourExecutables = Flag False, hscolourTestSuites = Flag False, hscolourBenchmarks = Flag False, hscolourDistPref = NoFlag, hscolourVerbosity = Flag normal } instance Monoid HscolourFlags where mempty = HscolourFlags { hscolourCSS = mempty, hscolourExecutables = mempty, hscolourTestSuites = mempty, hscolourBenchmarks = mempty, hscolourDistPref = mempty, hscolourVerbosity = mempty } mappend = (Semi.<>) instance Semigroup HscolourFlags where a <> b = HscolourFlags { hscolourCSS = combine hscolourCSS, hscolourExecutables = combine hscolourExecutables, hscolourTestSuites = combine hscolourTestSuites, hscolourBenchmarks = combine hscolourBenchmarks, hscolourDistPref = combine hscolourDistPref, hscolourVerbosity = combine hscolourVerbosity } where combine field = field a `mappend` field b hscolourCommand :: CommandUI HscolourFlags hscolourCommand = CommandUI { commandName = "hscolour" , commandSynopsis = "Generate HsColour colourised code, in HTML format." , commandDescription = Just (\_ -> "Requires the hscolour program.\n") , commandNotes = Nothing , commandUsage = \pname -> "Usage: " ++ pname ++ " hscolour [FLAGS]\n" , commandDefaultFlags = defaultHscolourFlags , commandOptions = \showOrParseArgs -> [optionVerbosity hscolourVerbosity (\v flags -> flags { hscolourVerbosity = v }) ,optionDistPref hscolourDistPref (\d flags -> flags { hscolourDistPref = d }) showOrParseArgs ,option "" ["executables"] "Run hscolour for Executables targets" hscolourExecutables (\v flags -> flags { hscolourExecutables = v }) trueArg ,option "" ["tests"] "Run hscolour for Test Suite targets" hscolourTestSuites (\v flags -> flags { hscolourTestSuites = v }) trueArg ,option "" ["benchmarks"] "Run hscolour for Benchmark targets" hscolourBenchmarks (\v flags -> flags { hscolourBenchmarks = v }) trueArg ,option "" ["all"] "Run hscolour for all targets" (\f -> allFlags [ hscolourExecutables f , hscolourTestSuites f , hscolourBenchmarks f]) (\v flags -> flags { hscolourExecutables = v , hscolourTestSuites = v , hscolourBenchmarks = v }) trueArg ,option "" ["css"] "Use a cascading style sheet" hscolourCSS (\v flags -> flags { hscolourCSS = v }) (reqArgFlag "PATH") ] } -- ------------------------------------------------------------ -- * Haddock flags -- ------------------------------------------------------------ data HaddockFlags = HaddockFlags { haddockProgramPaths :: [(String, FilePath)], haddockProgramArgs :: [(String, [String])], haddockHoogle :: Flag Bool, haddockHtml :: Flag Bool, haddockHtmlLocation :: Flag String, haddockForHackage :: Flag Bool, haddockExecutables :: Flag Bool, haddockTestSuites :: Flag Bool, haddockBenchmarks :: Flag Bool, haddockInternal :: Flag Bool, haddockCss :: Flag FilePath, haddockHscolour :: Flag Bool, haddockHscolourCss :: Flag FilePath, haddockContents :: Flag PathTemplate, haddockDistPref :: Flag FilePath, haddockKeepTempFiles:: Flag Bool, haddockVerbosity :: Flag Verbosity } deriving Show defaultHaddockFlags :: HaddockFlags defaultHaddockFlags = HaddockFlags { haddockProgramPaths = mempty, haddockProgramArgs = [], haddockHoogle = Flag False, haddockHtml = Flag False, haddockHtmlLocation = NoFlag, haddockForHackage = Flag False, haddockExecutables = Flag False, haddockTestSuites = Flag False, haddockBenchmarks = Flag False, haddockInternal = Flag False, haddockCss = NoFlag, haddockHscolour = Flag False, haddockHscolourCss = NoFlag, haddockContents = NoFlag, haddockDistPref = NoFlag, haddockKeepTempFiles= Flag False, haddockVerbosity = Flag normal } haddockCommand :: CommandUI HaddockFlags haddockCommand = CommandUI { commandName = "haddock" , commandSynopsis = "Generate Haddock HTML documentation." , commandDescription = Just $ \_ -> "Requires the program haddock, version 2.x.\n" , commandNotes = Nothing , commandUsage = \pname -> "Usage: " ++ pname ++ " haddock [FLAGS]\n" , commandDefaultFlags = defaultHaddockFlags , commandOptions = \showOrParseArgs -> haddockOptions showOrParseArgs ++ programConfigurationPaths progConf ParseArgs haddockProgramPaths (\v flags -> flags { haddockProgramPaths = v}) ++ programConfigurationOption progConf showOrParseArgs haddockProgramArgs (\v fs -> fs { haddockProgramArgs = v }) ++ programConfigurationOptions progConf ParseArgs haddockProgramArgs (\v flags -> flags { haddockProgramArgs = v}) } where progConf = addKnownProgram haddockProgram $ addKnownProgram ghcProgram $ emptyProgramConfiguration haddockOptions :: ShowOrParseArgs -> [OptionField HaddockFlags] haddockOptions showOrParseArgs = [optionVerbosity haddockVerbosity (\v flags -> flags { haddockVerbosity = v }) ,optionDistPref haddockDistPref (\d flags -> flags { haddockDistPref = d }) showOrParseArgs ,option "" ["keep-temp-files"] "Keep temporary files" haddockKeepTempFiles (\b flags -> flags { haddockKeepTempFiles = b }) trueArg ,option "" ["hoogle"] "Generate a hoogle database" haddockHoogle (\v flags -> flags { haddockHoogle = v }) trueArg ,option "" ["html"] "Generate HTML documentation (the default)" haddockHtml (\v flags -> flags { haddockHtml = v }) trueArg ,option "" ["html-location"] "Location of HTML documentation for pre-requisite packages" haddockHtmlLocation (\v flags -> flags { haddockHtmlLocation = v }) (reqArgFlag "URL") ,option "" ["for-hackage"] "Collection of flags to generate documentation suitable for upload to hackage" haddockForHackage (\v flags -> flags { haddockForHackage = v }) trueArg ,option "" ["executables"] "Run haddock for Executables targets" haddockExecutables (\v flags -> flags { haddockExecutables = v }) trueArg ,option "" ["tests"] "Run haddock for Test Suite targets" haddockTestSuites (\v flags -> flags { haddockTestSuites = v }) trueArg ,option "" ["benchmarks"] "Run haddock for Benchmark targets" haddockBenchmarks (\v flags -> flags { haddockBenchmarks = v }) trueArg ,option "" ["all"] "Run haddock for all targets" (\f -> allFlags [ haddockExecutables f , haddockTestSuites f , haddockBenchmarks f]) (\v flags -> flags { haddockExecutables = v , haddockTestSuites = v , haddockBenchmarks = v }) trueArg ,option "" ["internal"] "Run haddock for internal modules and include all symbols" haddockInternal (\v flags -> flags { haddockInternal = v }) trueArg ,option "" ["css"] "Use PATH as the haddock stylesheet" haddockCss (\v flags -> flags { haddockCss = v }) (reqArgFlag "PATH") ,option "" ["hyperlink-source","hyperlink-sources"] "Hyperlink the documentation to the source code (using HsColour)" haddockHscolour (\v flags -> flags { haddockHscolour = v }) trueArg ,option "" ["hscolour-css"] "Use PATH as the HsColour stylesheet" haddockHscolourCss (\v flags -> flags { haddockHscolourCss = v }) (reqArgFlag "PATH") ,option "" ["contents-location"] "Bake URL in as the location for the contents page" haddockContents (\v flags -> flags { haddockContents = v }) (reqArg' "URL" (toFlag . toPathTemplate) (flagToList . fmap fromPathTemplate)) ] emptyHaddockFlags :: HaddockFlags emptyHaddockFlags = mempty instance Monoid HaddockFlags where mempty = HaddockFlags { haddockProgramPaths = mempty, haddockProgramArgs = mempty, haddockHoogle = mempty, haddockHtml = mempty, haddockHtmlLocation = mempty, haddockForHackage = mempty, haddockExecutables = mempty, haddockTestSuites = mempty, haddockBenchmarks = mempty, haddockInternal = mempty, haddockCss = mempty, haddockHscolour = mempty, haddockHscolourCss = mempty, haddockContents = mempty, haddockDistPref = mempty, haddockKeepTempFiles= mempty, haddockVerbosity = mempty } mappend = (Semi.<>) instance Semigroup HaddockFlags where a <> b = HaddockFlags { haddockProgramPaths = combine haddockProgramPaths, haddockProgramArgs = combine haddockProgramArgs, haddockHoogle = combine haddockHoogle, haddockHtml = combine haddockHtml, haddockHtmlLocation = combine haddockHtmlLocation, haddockForHackage = combine haddockForHackage, haddockExecutables = combine haddockExecutables, haddockTestSuites = combine haddockTestSuites, haddockBenchmarks = combine haddockBenchmarks, haddockInternal = combine haddockInternal, haddockCss = combine haddockCss, haddockHscolour = combine haddockHscolour, haddockHscolourCss = combine haddockHscolourCss, haddockContents = combine haddockContents, haddockDistPref = combine haddockDistPref, haddockKeepTempFiles= combine haddockKeepTempFiles, haddockVerbosity = combine haddockVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Clean flags -- ------------------------------------------------------------ data CleanFlags = CleanFlags { cleanSaveConf :: Flag Bool, cleanDistPref :: Flag FilePath, cleanVerbosity :: Flag Verbosity } deriving Show defaultCleanFlags :: CleanFlags defaultCleanFlags = CleanFlags { cleanSaveConf = Flag False, cleanDistPref = NoFlag, cleanVerbosity = Flag normal } cleanCommand :: CommandUI CleanFlags cleanCommand = CommandUI { commandName = "clean" , commandSynopsis = "Clean up after a build." , commandDescription = Just $ \_ -> "Removes .hi, .o, preprocessed sources, etc.\n" , commandNotes = Nothing , commandUsage = \pname -> "Usage: " ++ pname ++ " clean [FLAGS]\n" , commandDefaultFlags = defaultCleanFlags , commandOptions = \showOrParseArgs -> [optionVerbosity cleanVerbosity (\v flags -> flags { cleanVerbosity = v }) ,optionDistPref cleanDistPref (\d flags -> flags { cleanDistPref = d }) showOrParseArgs ,option "s" ["save-configure"] "Do not remove the configuration file (dist/setup-config) during cleaning. Saves need to reconfigure." cleanSaveConf (\v flags -> flags { cleanSaveConf = v }) trueArg ] } emptyCleanFlags :: CleanFlags emptyCleanFlags = mempty instance Monoid CleanFlags where mempty = CleanFlags { cleanSaveConf = mempty, cleanDistPref = mempty, cleanVerbosity = mempty } mappend = (Semi.<>) instance Semigroup CleanFlags where a <> b = CleanFlags { cleanSaveConf = combine cleanSaveConf, cleanDistPref = combine cleanDistPref, cleanVerbosity = combine cleanVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Build flags -- ------------------------------------------------------------ data BuildFlags = BuildFlags { buildProgramPaths :: [(String, FilePath)], buildProgramArgs :: [(String, [String])], buildDistPref :: Flag FilePath, buildVerbosity :: Flag Verbosity, buildNumJobs :: Flag (Maybe Int), -- TODO: this one should not be here, it's just that the silly -- UserHooks stop us from passing extra info in other ways buildArgs :: [String] } deriving Show {-# DEPRECATED buildVerbose "Use buildVerbosity instead" #-} buildVerbose :: BuildFlags -> Verbosity buildVerbose = fromFlagOrDefault normal . buildVerbosity defaultBuildFlags :: BuildFlags defaultBuildFlags = BuildFlags { buildProgramPaths = mempty, buildProgramArgs = [], buildDistPref = mempty, buildVerbosity = Flag normal, buildNumJobs = mempty, buildArgs = [] } buildCommand :: ProgramConfiguration -> CommandUI BuildFlags buildCommand progConf = CommandUI { commandName = "build" , commandSynopsis = "Compile all/specific components." , commandDescription = Just $ \_ -> wrapText $ "Components encompass executables, tests, and benchmarks.\n" ++ "\n" ++ "Affected by configuration options, see `configure`.\n" , commandNotes = Just $ \pname -> "Examples:\n" ++ " " ++ pname ++ " build " ++ " All the components in the package\n" ++ " " ++ pname ++ " build foo " ++ " A component (i.e. lib, exe, test suite)\n\n" ++ programFlagsDescription progConf --TODO: re-enable once we have support for module/file targets -- ++ " " ++ pname ++ " build Foo.Bar " -- ++ " A module\n" -- ++ " " ++ pname ++ " build Foo/Bar.hs" -- ++ " A file\n\n" -- ++ "If a target is ambiguous it can be qualified with the component " -- ++ "name, e.g.\n" -- ++ " " ++ pname ++ " build foo:Foo.Bar\n" -- ++ " " ++ pname ++ " build testsuite1:Foo/Bar.hs\n" , commandUsage = usageAlternatives "build" $ [ "[FLAGS]" , "COMPONENTS [FLAGS]" ] , commandDefaultFlags = defaultBuildFlags , commandOptions = \showOrParseArgs -> [ optionVerbosity buildVerbosity (\v flags -> flags { buildVerbosity = v }) , optionDistPref buildDistPref (\d flags -> flags { buildDistPref = d }) showOrParseArgs ] ++ buildOptions progConf showOrParseArgs } buildOptions :: ProgramConfiguration -> ShowOrParseArgs -> [OptionField BuildFlags] buildOptions progConf showOrParseArgs = [ optionNumJobs buildNumJobs (\v flags -> flags { buildNumJobs = v }) ] ++ programConfigurationPaths progConf showOrParseArgs buildProgramPaths (\v flags -> flags { buildProgramPaths = v}) ++ programConfigurationOption progConf showOrParseArgs buildProgramArgs (\v fs -> fs { buildProgramArgs = v }) ++ programConfigurationOptions progConf showOrParseArgs buildProgramArgs (\v flags -> flags { buildProgramArgs = v}) emptyBuildFlags :: BuildFlags emptyBuildFlags = mempty instance Monoid BuildFlags where mempty = BuildFlags { buildProgramPaths = mempty, buildProgramArgs = mempty, buildVerbosity = mempty, buildDistPref = mempty, buildNumJobs = mempty, buildArgs = mempty } mappend = (Semi.<>) instance Semigroup BuildFlags where a <> b = BuildFlags { buildProgramPaths = combine buildProgramPaths, buildProgramArgs = combine buildProgramArgs, buildVerbosity = combine buildVerbosity, buildDistPref = combine buildDistPref, buildNumJobs = combine buildNumJobs, buildArgs = combine buildArgs } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * REPL Flags -- ------------------------------------------------------------ data ReplFlags = ReplFlags { replProgramPaths :: [(String, FilePath)], replProgramArgs :: [(String, [String])], replDistPref :: Flag FilePath, replVerbosity :: Flag Verbosity, replReload :: Flag Bool } deriving Show defaultReplFlags :: ReplFlags defaultReplFlags = ReplFlags { replProgramPaths = mempty, replProgramArgs = [], replDistPref = NoFlag, replVerbosity = Flag normal, replReload = Flag False } instance Monoid ReplFlags where mempty = ReplFlags { replProgramPaths = mempty, replProgramArgs = mempty, replVerbosity = mempty, replDistPref = mempty, replReload = mempty } mappend = (Semi.<>) instance Semigroup ReplFlags where a <> b = ReplFlags { replProgramPaths = combine replProgramPaths, replProgramArgs = combine replProgramArgs, replVerbosity = combine replVerbosity, replDistPref = combine replDistPref, replReload = combine replReload } where combine field = field a `mappend` field b replCommand :: ProgramConfiguration -> CommandUI ReplFlags replCommand progConf = CommandUI { commandName = "repl" , commandSynopsis = "Open an interpreter session for the given component." , commandDescription = Just $ \pname -> wrapText $ "If the current directory contains no package, ignores COMPONENT " ++ "parameters and opens an interactive interpreter session; if a " ++ "sandbox is present, its package database will be used.\n" ++ "\n" ++ "Otherwise, (re)configures with the given or default flags, and " ++ "loads the interpreter with the relevant modules. For executables, " ++ "tests and benchmarks, loads the main module (and its " ++ "dependencies); for libraries all exposed/other modules.\n" ++ "\n" ++ "The default component is the library itself, or the executable " ++ "if that is the only component.\n" ++ "\n" ++ "Support for loading specific modules is planned but not " ++ "implemented yet. For certain scenarios, `" ++ pname ++ " exec -- ghci :l Foo` may be used instead. Note that `exec` will " ++ "not (re)configure and you will have to specify the location of " ++ "other modules, if required.\n" , commandNotes = Just $ \pname -> "Examples:\n" ++ " " ++ pname ++ " repl " ++ " The first component in the package\n" ++ " " ++ pname ++ " repl foo " ++ " A named component (i.e. lib, exe, test suite)\n" ++ " " ++ pname ++ " repl --ghc-options=\"-lstdc++\"" ++ " Specifying flags for interpreter\n" --TODO: re-enable once we have support for module/file targets -- ++ " " ++ pname ++ " repl Foo.Bar " -- ++ " A module\n" -- ++ " " ++ pname ++ " repl Foo/Bar.hs" -- ++ " A file\n\n" -- ++ "If a target is ambiguous it can be qualified with the component " -- ++ "name, e.g.\n" -- ++ " " ++ pname ++ " repl foo:Foo.Bar\n" -- ++ " " ++ pname ++ " repl testsuite1:Foo/Bar.hs\n" , commandUsage = \pname -> "Usage: " ++ pname ++ " repl [COMPONENT] [FLAGS]\n" , commandDefaultFlags = defaultReplFlags , commandOptions = \showOrParseArgs -> optionVerbosity replVerbosity (\v flags -> flags { replVerbosity = v }) : optionDistPref replDistPref (\d flags -> flags { replDistPref = d }) showOrParseArgs : programConfigurationPaths progConf showOrParseArgs replProgramPaths (\v flags -> flags { replProgramPaths = v}) ++ programConfigurationOption progConf showOrParseArgs replProgramArgs (\v flags -> flags { replProgramArgs = v}) ++ programConfigurationOptions progConf showOrParseArgs replProgramArgs (\v flags -> flags { replProgramArgs = v}) ++ case showOrParseArgs of ParseArgs -> [ option "" ["reload"] "Used from within an interpreter to update files." replReload (\v flags -> flags { replReload = v }) trueArg ] _ -> [] } -- ------------------------------------------------------------ -- * Test flags -- ------------------------------------------------------------ data TestShowDetails = Never | Failures | Always | Streaming | Direct deriving (Eq, Ord, Enum, Bounded, Show) knownTestShowDetails :: [TestShowDetails] knownTestShowDetails = [minBound..maxBound] instance Text TestShowDetails where disp = Disp.text . lowercase . show parse = maybe Parse.pfail return . classify =<< ident where ident = Parse.munch1 (\c -> isAlpha c || c == '_' || c == '-') classify str = lookup (lowercase str) enumMap enumMap :: [(String, TestShowDetails)] enumMap = [ (display x, x) | x <- knownTestShowDetails ] --TODO: do we need this instance? instance Monoid TestShowDetails where mempty = Never mappend = (Semi.<>) instance Semigroup TestShowDetails where a <> b = if a < b then b else a data TestFlags = TestFlags { testDistPref :: Flag FilePath, testVerbosity :: Flag Verbosity, testHumanLog :: Flag PathTemplate, testMachineLog :: Flag PathTemplate, testShowDetails :: Flag TestShowDetails, testKeepTix :: Flag Bool, -- TODO: think about if/how options are passed to test exes testOptions :: [PathTemplate] } defaultTestFlags :: TestFlags defaultTestFlags = TestFlags { testDistPref = NoFlag, testVerbosity = Flag normal, testHumanLog = toFlag $ toPathTemplate $ "$pkgid-$test-suite.log", testMachineLog = toFlag $ toPathTemplate $ "$pkgid.log", testShowDetails = toFlag Failures, testKeepTix = toFlag False, testOptions = [] } testCommand :: CommandUI TestFlags testCommand = CommandUI { commandName = "test" , commandSynopsis = "Run all/specific tests in the test suite." , commandDescription = Just $ \pname -> wrapText $ "If necessary (re)configures with `--enable-tests` flag and builds" ++ " the test suite.\n" ++ "\n" ++ "Remember that the tests' dependencies must be installed if there" ++ " are additional ones; e.g. with `" ++ pname ++ " install --only-dependencies --enable-tests`.\n" ++ "\n" ++ "By defining UserHooks in a custom Setup.hs, the package can" ++ " define actions to be executed before and after running tests.\n" , commandNotes = Nothing , commandUsage = usageAlternatives "test" [ "[FLAGS]" , "TESTCOMPONENTS [FLAGS]" ] , commandDefaultFlags = defaultTestFlags , commandOptions = \showOrParseArgs -> [ optionVerbosity testVerbosity (\v flags -> flags { testVerbosity = v }) , optionDistPref testDistPref (\d flags -> flags { testDistPref = d }) showOrParseArgs , option [] ["log"] ("Log all test suite results to file (name template can use " ++ "$pkgid, $compiler, $os, $arch, $test-suite, $result)") testHumanLog (\v flags -> flags { testHumanLog = v }) (reqArg' "TEMPLATE" (toFlag . toPathTemplate) (flagToList . fmap fromPathTemplate)) , option [] ["machine-log"] ("Produce a machine-readable log file (name template can use " ++ "$pkgid, $compiler, $os, $arch, $result)") testMachineLog (\v flags -> flags { testMachineLog = v }) (reqArg' "TEMPLATE" (toFlag . toPathTemplate) (flagToList . fmap fromPathTemplate)) , option [] ["show-details"] ("'always': always show results of individual test cases. " ++ "'never': never show results of individual test cases. " ++ "'failures': show results of failing test cases. " ++ "'streaming': show results of test cases in real time." ++ "'direct': send results of test cases in real time; no log file.") testShowDetails (\v flags -> flags { testShowDetails = v }) (reqArg "FILTER" (readP_to_E (\_ -> "--show-details flag expects one of " ++ intercalate ", " (map display knownTestShowDetails)) (fmap toFlag parse)) (flagToList . fmap display)) , option [] ["keep-tix-files"] "keep .tix files for HPC between test runs" testKeepTix (\v flags -> flags { testKeepTix = v}) trueArg , option [] ["test-options"] ("give extra options to test executables " ++ "(name templates can use $pkgid, $compiler, " ++ "$os, $arch, $test-suite)") testOptions (\v flags -> flags { testOptions = v }) (reqArg' "TEMPLATES" (map toPathTemplate . splitArgs) (const [])) , option [] ["test-option"] ("give extra option to test executables " ++ "(no need to quote options containing spaces, " ++ "name template can use $pkgid, $compiler, " ++ "$os, $arch, $test-suite)") testOptions (\v flags -> flags { testOptions = v }) (reqArg' "TEMPLATE" (\x -> [toPathTemplate x]) (map fromPathTemplate)) ] } emptyTestFlags :: TestFlags emptyTestFlags = mempty instance Monoid TestFlags where mempty = TestFlags { testDistPref = mempty, testVerbosity = mempty, testHumanLog = mempty, testMachineLog = mempty, testShowDetails = mempty, testKeepTix = mempty, testOptions = mempty } mappend = (Semi.<>) instance Semigroup TestFlags where a <> b = TestFlags { testDistPref = combine testDistPref, testVerbosity = combine testVerbosity, testHumanLog = combine testHumanLog, testMachineLog = combine testMachineLog, testShowDetails = combine testShowDetails, testKeepTix = combine testKeepTix, testOptions = combine testOptions } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Benchmark flags -- ------------------------------------------------------------ data BenchmarkFlags = BenchmarkFlags { benchmarkDistPref :: Flag FilePath, benchmarkVerbosity :: Flag Verbosity, benchmarkOptions :: [PathTemplate] } defaultBenchmarkFlags :: BenchmarkFlags defaultBenchmarkFlags = BenchmarkFlags { benchmarkDistPref = NoFlag, benchmarkVerbosity = Flag normal, benchmarkOptions = [] } benchmarkCommand :: CommandUI BenchmarkFlags benchmarkCommand = CommandUI { commandName = "bench" , commandSynopsis = "Run all/specific benchmarks." , commandDescription = Just $ \pname -> wrapText $ "If necessary (re)configures with `--enable-benchmarks` flag and" ++ " builds the benchmarks.\n" ++ "\n" ++ "Remember that the benchmarks' dependencies must be installed if" ++ " there are additional ones; e.g. with `" ++ pname ++ " install --only-dependencies --enable-benchmarks`.\n" ++ "\n" ++ "By defining UserHooks in a custom Setup.hs, the package can" ++ " define actions to be executed before and after running" ++ " benchmarks.\n" , commandNotes = Nothing , commandUsage = usageAlternatives "bench" [ "[FLAGS]" , "BENCHCOMPONENTS [FLAGS]" ] , commandDefaultFlags = defaultBenchmarkFlags , commandOptions = \showOrParseArgs -> [ optionVerbosity benchmarkVerbosity (\v flags -> flags { benchmarkVerbosity = v }) , optionDistPref benchmarkDistPref (\d flags -> flags { benchmarkDistPref = d }) showOrParseArgs , option [] ["benchmark-options"] ("give extra options to benchmark executables " ++ "(name templates can use $pkgid, $compiler, " ++ "$os, $arch, $benchmark)") benchmarkOptions (\v flags -> flags { benchmarkOptions = v }) (reqArg' "TEMPLATES" (map toPathTemplate . splitArgs) (const [])) , option [] ["benchmark-option"] ("give extra option to benchmark executables " ++ "(no need to quote options containing spaces, " ++ "name template can use $pkgid, $compiler, " ++ "$os, $arch, $benchmark)") benchmarkOptions (\v flags -> flags { benchmarkOptions = v }) (reqArg' "TEMPLATE" (\x -> [toPathTemplate x]) (map fromPathTemplate)) ] } emptyBenchmarkFlags :: BenchmarkFlags emptyBenchmarkFlags = mempty instance Monoid BenchmarkFlags where mempty = BenchmarkFlags { benchmarkDistPref = mempty, benchmarkVerbosity = mempty, benchmarkOptions = mempty } mappend = (Semi.<>) instance Semigroup BenchmarkFlags where a <> b = BenchmarkFlags { benchmarkDistPref = combine benchmarkDistPref, benchmarkVerbosity = combine benchmarkVerbosity, benchmarkOptions = combine benchmarkOptions } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Shared options utils -- ------------------------------------------------------------ programFlagsDescription :: ProgramConfiguration -> String programFlagsDescription progConf = "The flags --with-PROG and --PROG-option(s) can be used with" ++ " the following programs:" ++ (concatMap (\line -> "\n " ++ unwords line) . wrapLine 77 . sort) [ programName prog | (prog, _) <- knownPrograms progConf ] ++ "\n" -- | For each known program @PROG@ in 'progConf', produce a @with-PROG@ -- 'OptionField'. programConfigurationPaths :: ProgramConfiguration -> ShowOrParseArgs -> (flags -> [(String, FilePath)]) -> ([(String, FilePath)] -> (flags -> flags)) -> [OptionField flags] programConfigurationPaths progConf showOrParseArgs get set = programConfigurationPaths' ("with-" ++) progConf showOrParseArgs get set -- | Like 'programConfigurationPaths', but allows to customise the option name. programConfigurationPaths' :: (String -> String) -> ProgramConfiguration -> ShowOrParseArgs -> (flags -> [(String, FilePath)]) -> ([(String, FilePath)] -> (flags -> flags)) -> [OptionField flags] programConfigurationPaths' mkName progConf showOrParseArgs get set = case showOrParseArgs of -- we don't want a verbose help text list so we just show a generic one: ShowArgs -> [withProgramPath "PROG"] ParseArgs -> map (withProgramPath . programName . fst) (knownPrograms progConf) where withProgramPath prog = option "" [mkName prog] ("give the path to " ++ prog) get set (reqArg' "PATH" (\path -> [(prog, path)]) (\progPaths -> [ path | (prog', path) <- progPaths, prog==prog' ])) -- | For each known program @PROG@ in 'progConf', produce a @PROG-option@ -- 'OptionField'. programConfigurationOption :: ProgramConfiguration -> ShowOrParseArgs -> (flags -> [(String, [String])]) -> ([(String, [String])] -> (flags -> flags)) -> [OptionField flags] programConfigurationOption progConf showOrParseArgs get set = case showOrParseArgs of -- we don't want a verbose help text list so we just show a generic one: ShowArgs -> [programOption "PROG"] ParseArgs -> map (programOption . programName . fst) (knownPrograms progConf) where programOption prog = option "" [prog ++ "-option"] ("give an extra option to " ++ prog ++ " (no need to quote options containing spaces)") get set (reqArg' "OPT" (\arg -> [(prog, [arg])]) (\progArgs -> concat [ args | (prog', args) <- progArgs, prog==prog' ])) -- | For each known program @PROG@ in 'progConf', produce a @PROG-options@ -- 'OptionField'. programConfigurationOptions :: ProgramConfiguration -> ShowOrParseArgs -> (flags -> [(String, [String])]) -> ([(String, [String])] -> (flags -> flags)) -> [OptionField flags] programConfigurationOptions progConf showOrParseArgs get set = case showOrParseArgs of -- we don't want a verbose help text list so we just show a generic one: ShowArgs -> [programOptions "PROG"] ParseArgs -> map (programOptions . programName . fst) (knownPrograms progConf) where programOptions prog = option "" [prog ++ "-options"] ("give extra options to " ++ prog) get set (reqArg' "OPTS" (\args -> [(prog, splitArgs args)]) (const [])) -- ------------------------------------------------------------ -- * GetOpt Utils -- ------------------------------------------------------------ boolOpt :: SFlags -> SFlags -> MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a boolOpt = Command.boolOpt flagToMaybe Flag boolOpt' :: OptFlags -> OptFlags -> MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a boolOpt' = Command.boolOpt' flagToMaybe Flag trueArg, falseArg :: MkOptDescr (a -> Flag Bool) (Flag Bool -> a -> a) a trueArg sfT lfT = boolOpt' (sfT, lfT) ([], []) sfT lfT falseArg sfF lfF = boolOpt' ([], []) (sfF, lfF) sfF lfF reqArgFlag :: ArgPlaceHolder -> SFlags -> LFlags -> Description -> (b -> Flag String) -> (Flag String -> b -> b) -> OptDescr b reqArgFlag ad = reqArg ad (succeedReadE Flag) flagToList optionDistPref :: (flags -> Flag FilePath) -> (Flag FilePath -> flags -> flags) -> ShowOrParseArgs -> OptionField flags optionDistPref get set = \showOrParseArgs -> option "" (distPrefFlagName showOrParseArgs) ( "The directory where Cabal puts generated build files " ++ "(default " ++ defaultDistPref ++ ")") get set (reqArgFlag "DIR") where distPrefFlagName ShowArgs = ["builddir"] distPrefFlagName ParseArgs = ["builddir", "distdir", "distpref"] optionVerbosity :: (flags -> Flag Verbosity) -> (Flag Verbosity -> flags -> flags) -> OptionField flags optionVerbosity get set = option "v" ["verbose"] "Control verbosity (n is 0--3, default verbosity level is 1)" get set (optArg "n" (fmap Flag flagToVerbosity) (Flag verbose) -- default Value if no n is given (fmap (Just . showForCabal) . flagToList)) optionNumJobs :: (flags -> Flag (Maybe Int)) -> (Flag (Maybe Int) -> flags -> flags) -> OptionField flags optionNumJobs get set = option "j" ["jobs"] "Run NUM jobs simultaneously (or '$ncpus' if no NUM is given)." get set (optArg "NUM" (fmap Flag numJobsParser) (Flag Nothing) (map (Just . maybe "$ncpus" show) . flagToList)) where numJobsParser :: ReadE (Maybe Int) numJobsParser = ReadE $ \s -> case s of "$ncpus" -> Right Nothing _ -> case reads s of [(n, "")] | n < 1 -> Left "The number of jobs should be 1 or more." | n > 64 -> Left "You probably don't want that many jobs." | otherwise -> Right (Just n) _ -> Left "The jobs value should be a number or '$ncpus'" -- ------------------------------------------------------------ -- * Other Utils -- ------------------------------------------------------------ -- | Arguments to pass to a @configure@ script, e.g. generated by -- @autoconf@. configureArgs :: Bool -> ConfigFlags -> [String] configureArgs bcHack flags = hc_flag ++ optFlag "with-hc-pkg" configHcPkg ++ optFlag' "prefix" prefix ++ optFlag' "bindir" bindir ++ optFlag' "libdir" libdir ++ optFlag' "libexecdir" libexecdir ++ optFlag' "datadir" datadir ++ optFlag' "sysconfdir" sysconfdir ++ configConfigureArgs flags where hc_flag = case (configHcFlavor flags, configHcPath flags) of (_, Flag hc_path) -> [hc_flag_name ++ hc_path] (Flag hc, NoFlag) -> [hc_flag_name ++ display hc] (NoFlag,NoFlag) -> [] hc_flag_name --TODO kill off thic bc hack when defaultUserHooks is removed. | bcHack = "--with-hc=" | otherwise = "--with-compiler=" optFlag name config_field = case config_field flags of Flag p -> ["--" ++ name ++ "=" ++ p] NoFlag -> [] optFlag' name config_field = optFlag name (fmap fromPathTemplate . config_field . configInstallDirs) configureCCompiler :: Verbosity -> ProgramConfiguration -> IO (FilePath, [String]) configureCCompiler verbosity lbi = configureProg verbosity lbi gccProgram configureLinker :: Verbosity -> ProgramConfiguration -> IO (FilePath, [String]) configureLinker verbosity lbi = configureProg verbosity lbi ldProgram configureProg :: Verbosity -> ProgramConfiguration -> Program -> IO (FilePath, [String]) configureProg verbosity programConfig prog = do (p, _) <- requireProgram verbosity prog programConfig let pInv = programInvocation p [] return (progInvokePath pInv, progInvokeArgs pInv) -- | Helper function to split a string into a list of arguments. -- It's supposed to handle quoted things sensibly, eg: -- -- > splitArgs "--foo=\"C:\Program Files\Bar\" --baz" -- > = ["--foo=C:\Program Files\Bar", "--baz"] -- splitArgs :: String -> [String] splitArgs = space [] where space :: String -> String -> [String] space w [] = word w [] space w ( c :s) | isSpace c = word w (space [] s) space w ('"':s) = string w s space w s = nonstring w s string :: String -> String -> [String] string w [] = word w [] string w ('"':s) = space w s string w ( c :s) = string (c:w) s nonstring :: String -> String -> [String] nonstring w [] = word w [] nonstring w ('"':s) = string w s nonstring w ( c :s) = space (c:w) s word [] s = s word w s = reverse w : s -- The test cases kinda have to be rewritten from the ground up... :/ --hunitTests :: [Test] --hunitTests = -- let m = [("ghc", GHC), ("nhc98", NHC), ("hugs", Hugs)] -- (flags, commands', unkFlags, ers) -- = getOpt Permute options ["configure", "foobar", "--prefix=/foo", "--ghc", "--nhc98", "--hugs", "--with-compiler=/comp", "--unknown1", "--unknown2", "--install-prefix=/foo", "--user", "--global"] -- in [TestLabel "very basic option parsing" $ TestList [ -- "getOpt flags" ~: "failed" ~: -- [Prefix "/foo", GhcFlag, NhcFlag, HugsFlag, -- WithCompiler "/comp", InstPrefix "/foo", UserFlag, GlobalFlag] -- ~=? flags, -- "getOpt commands" ~: "failed" ~: ["configure", "foobar"] ~=? commands', -- "getOpt unknown opts" ~: "failed" ~: -- ["--unknown1", "--unknown2"] ~=? unkFlags, -- "getOpt errors" ~: "failed" ~: [] ~=? ers], -- -- TestLabel "test location of various compilers" $ TestList -- ["configure parsing for prefix and compiler flag" ~: "failed" ~: -- (Right (ConfigCmd (Just comp, Nothing, Just "/usr/local"), [])) -- ~=? (parseArgs ["--prefix=/usr/local", "--"++name, "configure"]) -- | (name, comp) <- m], -- -- TestLabel "find the package tool" $ TestList -- ["configure parsing for prefix comp flag, withcompiler" ~: "failed" ~: -- (Right (ConfigCmd (Just comp, Just "/foo/comp", Just "/usr/local"), [])) -- ~=? (parseArgs ["--prefix=/usr/local", "--"++name, -- "--with-compiler=/foo/comp", "configure"]) -- | (name, comp) <- m], -- -- TestLabel "simpler commands" $ TestList -- [flag ~: "failed" ~: (Right (flagCmd, [])) ~=? (parseArgs [flag]) -- | (flag, flagCmd) <- [("build", BuildCmd), -- ("install", InstallCmd Nothing False), -- ("sdist", SDistCmd), -- ("register", RegisterCmd False)] -- ] -- ] {- Testing ideas: * IO to look for hugs and hugs-pkg (which hugs, etc) * quickCheck to test permutations of arguments * what other options can we over-ride with a command-line flag? -}
randen/cabal
Cabal/Distribution/Simple/Setup.hs
Haskell
bsd-3-clause
89,397
{- (c) The University of Glasgow, 2000-2006 \section{Fast booleans} -} {-# LANGUAGE CPP, MagicHash #-} module Eta.Utils.FastBool ( --fastBool could be called bBox; isFastTrue, bUnbox; but they're not FastBool, fastBool, isFastTrue, fastOr, fastAnd ) where -- Import the beggars import GHC.Exts #ifdef DEBUG import Eta.Utils.Panic #endif type FastBool = Int# fastBool True = 1# fastBool False = 0# #ifdef DEBUG --then waste time deciding whether to panic. FastBool should normally --be at least as fast as Bool, one would hope... isFastTrue 1# = True isFastTrue 0# = False isFastTrue _ = panic "FastTypes: isFastTrue" -- note that fastOr and fastAnd are strict in both arguments -- since they are unboxed fastOr 1# _ = 1# fastOr 0# x = x fastOr _ _ = panicFastInt "FastTypes: fastOr" fastAnd 0# _ = 0# fastAnd 1# x = x fastAnd _ _ = panicFastInt "FastTypes: fastAnd" --these "panicFastInt"s (formerly known as "panic#") rely on --FastInt = FastBool ( = Int# presumably), --haha, true enough when __GLASGOW_HASKELL__. Why can't we have functions --that return _|_ be kind-polymorphic ( ?? to be precise ) ? #else /* ! DEBUG */ --Isn't comparison to zero sometimes faster on CPUs than comparison to 1? -- (since using Int# as _synonym_ fails to guarantee that it will -- only take on values of 0 and 1) isFastTrue 0# = False isFastTrue _ = True -- note that fastOr and fastAnd are strict in both arguments -- since they are unboxed -- Also, to avoid incomplete-pattern warning -- (and avoid wasting time with redundant runtime checks), -- we don't pattern-match on both 0# and 1# . fastOr 0# x = x fastOr _ _ = 1# fastAnd 0# _ = 0# fastAnd _ x = x #endif /* ! DEBUG */ fastBool :: Bool -> FastBool isFastTrue :: FastBool -> Bool fastOr :: FastBool -> FastBool -> FastBool fastAnd :: FastBool -> FastBool -> FastBool
rahulmutt/ghcvm
compiler/Eta/Utils/FastBool.hs
Haskell
bsd-3-clause
1,846
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Bits -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- This module defines bitwise operations for signed and unsigned -- integers. Instances of the class 'Bits' for the 'Int' and -- 'Integer' types are available from this module, and instances for -- explicitly sized integral types are available from the -- "Data.Int" and "Data.Word" modules. -- ----------------------------------------------------------------------------- module Data.Bits ( Bits( (.&.), (.|.), xor, complement, shift, rotate, zeroBits, bit, setBit, clearBit, complementBit, testBit, bitSizeMaybe, bitSize, isSigned, shiftL, shiftR, unsafeShiftL, unsafeShiftR, rotateL, rotateR, popCount ), FiniteBits( finiteBitSize, countLeadingZeros, countTrailingZeros ), bitDefault, testBitDefault, popCountDefault, toIntegralSized ) where -- Defines the @Bits@ class containing bit-based operations. -- See library document for details on the semantics of the -- individual operations. #define WORD_SIZE_IN_BITS 32 import Data.Maybe import GHC.Enum import GHC.Num import GHC.Base import GHC.Real infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR` infixl 7 .&. infixl 6 `xor` infixl 5 .|. {-# DEPRECATED bitSize "Use 'bitSizeMaybe' or 'finiteBitSize' instead" #-} -- deprecated in 7.8 -- | The 'Bits' class defines bitwise operations over integral types. -- -- * Bits are numbered from 0 with bit 0 being the least -- significant bit. class Eq a => Bits a where {-# MINIMAL (.&.), (.|.), xor, complement, (shift | (shiftL, shiftR)), (rotate | (rotateL, rotateR)), bitSize, bitSizeMaybe, isSigned, testBit, bit, popCount #-} -- | Bitwise \"and\" (.&.) :: a -> a -> a -- | Bitwise \"or\" (.|.) :: a -> a -> a -- | Bitwise \"xor\" xor :: a -> a -> a {-| Reverse all the bits in the argument -} complement :: a -> a {-| @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive, or right by @-i@ bits otherwise. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. An instance can define either this unified 'shift' or 'shiftL' and 'shiftR', depending on which is more convenient for the type in question. -} shift :: a -> Int -> a x `shift` i | i<0 = x `shiftR` (-i) | i>0 = x `shiftL` i | otherwise = x {-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive, or right by @-i@ bits otherwise. For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'. An instance can define either this unified 'rotate' or 'rotateL' and 'rotateR', depending on which is more convenient for the type in question. -} rotate :: a -> Int -> a x `rotate` i | i<0 = x `rotateR` (-i) | i>0 = x `rotateL` i | otherwise = x {- -- Rotation can be implemented in terms of two shifts, but care is -- needed for negative values. This suggested implementation assumes -- 2's-complement arithmetic. It is commented out because it would -- require an extra context (Ord a) on the signature of 'rotate'. x `rotate` i | i<0 && isSigned x && x<0 = let left = i+bitSize x in ((x `shift` i) .&. complement ((-1) `shift` left)) .|. (x `shift` left) | i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x)) | i==0 = x | i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x)) -} -- | 'zeroBits' is the value with all bits unset. -- -- The following laws ought to hold (for all valid bit indices @/n/@): -- -- * @'clearBit' 'zeroBits' /n/ == 'zeroBits'@ -- * @'setBit' 'zeroBits' /n/ == 'bit' /n/@ -- * @'testBit' 'zeroBits' /n/ == False@ -- * @'popCount' 'zeroBits' == 0@ -- -- This method uses @'clearBit' ('bit' 0) 0@ as its default -- implementation (which ought to be equivalent to 'zeroBits' for -- types which possess a 0th bit). -- -- @since 4.7.0.0 zeroBits :: a zeroBits = clearBit (bit 0) 0 -- | @bit /i/@ is a value with the @/i/@th bit set and all other bits clear. -- -- Can be implemented using `bitDefault' if @a@ is also an -- instance of 'Num'. -- -- See also 'zeroBits'. bit :: Int -> a -- | @x \`setBit\` i@ is the same as @x .|. bit i@ setBit :: a -> Int -> a -- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@ clearBit :: a -> Int -> a -- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@ complementBit :: a -> Int -> a -- | Return 'True' if the @n@th bit of the argument is 1 -- -- Can be implemented using `testBitDefault' if @a@ is also an -- instance of 'Num'. testBit :: a -> Int -> Bool {-| Return the number of bits in the type of the argument. The actual value of the argument is ignored. Returns Nothing for types that do not have a fixed bitsize, like 'Integer'. @since 4.7.0.0 -} bitSizeMaybe :: a -> Maybe Int {-| Return the number of bits in the type of the argument. The actual value of the argument is ignored. The function 'bitSize' is undefined for types that do not have a fixed bitsize, like 'Integer'. -} bitSize :: a -> Int {-| Return 'True' if the argument is a signed type. The actual value of the argument is ignored -} isSigned :: a -> Bool {-# INLINE setBit #-} {-# INLINE clearBit #-} {-# INLINE complementBit #-} x `setBit` i = x .|. bit i x `clearBit` i = x .&. complement (bit i) x `complementBit` i = x `xor` bit i {-| Shift the argument left by the specified number of bits (which must be non-negative). An instance can define either this and 'shiftR' or the unified 'shift', depending on which is more convenient for the type in question. -} shiftL :: a -> Int -> a {-# INLINE shiftL #-} x `shiftL` i = x `shift` i {-| Shift the argument left by the specified number of bits. The result is undefined for negative shift amounts and shift amounts greater or equal to the 'bitSize'. Defaults to 'shiftL' unless defined explicitly by an instance. @since 4.5.0.0 -} unsafeShiftL :: a -> Int -> a {-# INLINE unsafeShiftL #-} x `unsafeShiftL` i = x `shiftL` i {-| Shift the first argument right by the specified number of bits. The result is undefined for negative shift amounts and shift amounts greater or equal to the 'bitSize'. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. An instance can define either this and 'shiftL' or the unified 'shift', depending on which is more convenient for the type in question. -} shiftR :: a -> Int -> a {-# INLINE shiftR #-} x `shiftR` i = x `shift` (-i) {-| Shift the first argument right by the specified number of bits, which must be non-negative an smaller than the number of bits in the type. Right shifts perform sign extension on signed number types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 otherwise. Defaults to 'shiftR' unless defined explicitly by an instance. @since 4.5.0.0 -} unsafeShiftR :: a -> Int -> a {-# INLINE unsafeShiftR #-} x `unsafeShiftR` i = x `shiftR` i {-| Rotate the argument left by the specified number of bits (which must be non-negative). An instance can define either this and 'rotateR' or the unified 'rotate', depending on which is more convenient for the type in question. -} rotateL :: a -> Int -> a {-# INLINE rotateL #-} x `rotateL` i = x `rotate` i {-| Rotate the argument right by the specified number of bits (which must be non-negative). An instance can define either this and 'rotateL' or the unified 'rotate', depending on which is more convenient for the type in question. -} rotateR :: a -> Int -> a {-# INLINE rotateR #-} x `rotateR` i = x `rotate` (-i) {-| Return the number of set bits in the argument. This number is known as the population count or the Hamming weight. Can be implemented using `popCountDefault' if @a@ is also an instance of 'Num'. @since 4.5.0.0 -} popCount :: a -> Int -- |The 'FiniteBits' class denotes types with a finite, fixed number of bits. -- -- @since 4.7.0.0 class Bits b => FiniteBits b where -- | Return the number of bits in the type of the argument. -- The actual value of the argument is ignored. Moreover, 'finiteBitSize' -- is total, in contrast to the deprecated 'bitSize' function it replaces. -- -- @ -- 'finiteBitSize' = 'bitSize' -- 'bitSizeMaybe' = 'Just' . 'finiteBitSize' -- @ -- -- @since 4.7.0.0 finiteBitSize :: b -> Int -- | Count number of zero bits preceding the most significant set bit. -- -- @ -- 'countLeadingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a) -- @ -- -- 'countLeadingZeros' can be used to compute log base 2 via -- -- @ -- logBase2 x = 'finiteBitSize' x - 1 - 'countLeadingZeros' x -- @ -- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive -- integral types are implemented using CPU specific machine -- instructions. -- -- @since 4.8.0.0 countLeadingZeros :: b -> Int countLeadingZeros x = (w-1) - go (w-1) where go i | i < 0 = i -- no bit set | testBit x i = i | otherwise = go (i-1) w = finiteBitSize x -- | Count number of zero bits following the least significant set bit. -- -- @ -- 'countTrailingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a) -- 'countTrailingZeros' . 'negate' = 'countTrailingZeros' -- @ -- -- The related -- <http://en.wikipedia.org/wiki/Find_first_set find-first-set operation> -- can be expressed in terms of 'countTrailingZeros' as follows -- -- @ -- findFirstSet x = 1 + 'countTrailingZeros' x -- @ -- -- Note: The default implementation for this method is intentionally -- naive. However, the instances provided for the primitive -- integral types are implemented using CPU specific machine -- instructions. -- -- @since 4.8.0.0 countTrailingZeros :: b -> Int countTrailingZeros x = go 0 where go i | i >= w = i | testBit x i = i | otherwise = go (i+1) w = finiteBitSize x -- The defaults below are written with lambdas so that e.g. -- bit = bitDefault -- is fully applied, so inlining will happen -- | Default implementation for 'bit'. -- -- Note that: @bitDefault i = 1 `shiftL` i@ -- -- @since 4.6.0.0 bitDefault :: (Bits a, Num a) => Int -> a bitDefault = \i -> 1 `shiftL` i {-# INLINE bitDefault #-} -- | Default implementation for 'testBit'. -- -- Note that: @testBitDefault x i = (x .&. bit i) /= 0@ -- -- @since 4.6.0.0 testBitDefault :: (Bits a, Num a) => a -> Int -> Bool testBitDefault = \x i -> (x .&. bit i) /= 0 {-# INLINE testBitDefault #-} -- | Default implementation for 'popCount'. -- -- This implementation is intentionally naive. Instances are expected to provide -- an optimized implementation for their size. -- -- @since 4.6.0.0 popCountDefault :: (Bits a, Num a) => a -> Int popCountDefault = go 0 where go !c 0 = c go c w = go (c+1) (w .&. (w - 1)) -- clear the least significant {-# INLINABLE popCountDefault #-} -- Interpret 'Bool' as 1-bit bit-field; @since 4.7.0.0 instance Bits Bool where (.&.) = (&&) (.|.) = (||) xor = (/=) complement = not shift x 0 = x shift _ _ = False rotate x _ = x bit 0 = True bit _ = False testBit x 0 = x testBit _ _ = False bitSizeMaybe _ = Just 1 bitSize _ = 1 isSigned _ = False popCount False = 0 popCount True = 1 instance FiniteBits Bool where finiteBitSize _ = 1 countTrailingZeros x = if x then 0 else 1 countLeadingZeros x = if x then 0 else 1 instance Bits Int where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} zeroBits = 0 bit = bitDefault testBit = testBitDefault (I# x#) .&. (I# y#) = I# (x# `andI#` y#) (I# x#) .|. (I# y#) = I# (x# `orI#` y#) (I# x#) `xor` (I# y#) = I# (x# `xorI#` y#) complement (I# x#) = I# (notI# x#) (I# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = I# (x# `iShiftL#` i#) | otherwise = I# (x# `iShiftRA#` negateInt# i#) (I# x#) `shiftL` (I# i#) = I# (x# `iShiftL#` i#) (I# x#) `unsafeShiftL` (I# i#) = I# (x# `uncheckedIShiftL#` i#) (I# x#) `shiftR` (I# i#) = I# (x# `iShiftRA#` i#) (I# x#) `unsafeShiftR` (I# i#) = I# (x# `uncheckedIShiftRA#` i#) {-# INLINE rotate #-} -- See Note [Constant folding for rotate] (I# x#) `rotate` (I# i#) = I# ((x# `uncheckedIShiftL#` i'#) `orI#` (x# `uncheckedIShiftRL#` (wsib -# i'#))) where !i'# = i# `andI#` (wsib -# 1#) !wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -} bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i popCount (I# x#) = I# (word2Int# (popCnt# (int2Word# x#))) isSigned _ = True instance FiniteBits Int where finiteBitSize _ = WORD_SIZE_IN_BITS countLeadingZeros (I# x#) = I# (word2Int# (clz# (int2Word# x#))) countTrailingZeros (I# x#) = I# (word2Int# (ctz# (int2Word# x#))) instance Bits Word where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W# x#) .&. (W# y#) = W# (x# `and#` y#) (W# x#) .|. (W# y#) = W# (x# `or#` y#) (W# x#) `xor` (W# y#) = W# (x# `xor#` y#) complement (W# x#) = W# (x# `xor#` mb#) where !(W# mb#) = maxBound (W# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W# (x# `shiftL#` i#) | otherwise = W# (x# `shiftRL#` negateInt# i#) (W# x#) `shiftL` (I# i#) = W# (x# `shiftL#` i#) (W# x#) `unsafeShiftL` (I# i#) = W# (x# `uncheckedShiftL#` i#) (W# x#) `shiftR` (I# i#) = W# (x# `shiftRL#` i#) (W# x#) `unsafeShiftR` (I# i#) = W# (x# `uncheckedShiftRL#` i#) (W# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W# x# | otherwise = W# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (wsib -# i'#))) where !i'# = i# `andI#` (wsib -# 1#) !wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -} bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = False popCount (W# x#) = I# (word2Int# (popCnt# x#)) bit = bitDefault testBit = testBitDefault instance FiniteBits Word where finiteBitSize _ = WORD_SIZE_IN_BITS countLeadingZeros (W# x#) = I# (word2Int# (clz# x#)) countTrailingZeros (W# x#) = I# (word2Int# (ctz# x#)) instance Bits Integer where (.&.) = andInteger (.|.) = orInteger xor = xorInteger complement = complementInteger shift x i@(I# i#) | i >= 0 = shiftLInteger x i# | otherwise = shiftRInteger x (negateInt# i#) shiftL x i@(I# i#) | i < 0 = error "Bits.shiftL(Integer): negative shift" | otherwise = shiftLInteger x i# shiftR x i@(I# i#) | i < 0 = error "Bits.shiftR(Integer): negative shift" | otherwise = shiftRInteger x i# testBit x (I# i) = testBitInteger x i zeroBits = 0 bit = bitDefault popCount = popCountDefault rotate x i = shift x i -- since an Integer never wraps around bitSizeMaybe _ = Nothing bitSize _ = error "Data.Bits.bitSize(Integer)" isSigned _ = True ----------------------------------------------------------------------------- -- | Attempt to convert an 'Integral' type @a@ to an 'Integral' type @b@ using -- the size of the types as measured by 'Bits' methods. -- -- A simpler version of this function is: -- -- > toIntegral :: (Integral a, Integral b) => a -> Maybe b -- > toIntegral x -- > | toInteger x == y = Just (fromInteger y) -- > | otherwise = Nothing -- > where -- > y = toInteger x -- -- This version requires going through 'Integer', which can be inefficient. -- However, @toIntegralSized@ is optimized to allow GHC to statically determine -- the relative type sizes (as measured by 'bitSizeMaybe' and 'isSigned') and -- avoid going through 'Integer' for many types. (The implementation uses -- 'fromIntegral', which is itself optimized with rules for @base@ types but may -- go through 'Integer' for some type pairs.) -- -- @since 4.8.0.0 toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b toIntegralSized x -- See Note [toIntegralSized optimization] | maybe True (<= x) yMinBound , maybe True (x <=) yMaxBound = Just y | otherwise = Nothing where y = fromIntegral x xWidth = bitSizeMaybe x yWidth = bitSizeMaybe y yMinBound | isBitSubType x y = Nothing | isSigned x, not (isSigned y) = Just 0 | isSigned x, isSigned y , Just yW <- yWidth = Just (negate $ bit (yW-1)) -- Assumes sub-type | otherwise = Nothing yMaxBound | isBitSubType x y = Nothing | isSigned x, not (isSigned y) , Just xW <- xWidth, Just yW <- yWidth , xW <= yW+1 = Nothing -- Max bound beyond a's domain | Just yW <- yWidth = if isSigned y then Just (bit (yW-1)-1) else Just (bit yW-1) | otherwise = Nothing {-# INLINEABLE toIntegralSized #-} -- | 'True' if the size of @a@ is @<=@ the size of @b@, where size is measured -- by 'bitSizeMaybe' and 'isSigned'. isBitSubType :: (Bits a, Bits b) => a -> b -> Bool isBitSubType x y -- Reflexive | xWidth == yWidth, xSigned == ySigned = True -- Every integer is a subset of 'Integer' | ySigned, Nothing == yWidth = True | not xSigned, not ySigned, Nothing == yWidth = True -- Sub-type relations between fixed-with types | xSigned == ySigned, Just xW <- xWidth, Just yW <- yWidth = xW <= yW | not xSigned, ySigned, Just xW <- xWidth, Just yW <- yWidth = xW < yW | otherwise = False where xWidth = bitSizeMaybe x xSigned = isSigned x yWidth = bitSizeMaybe y ySigned = isSigned y {-# INLINE isBitSubType #-} {- Note [Constant folding for rotate] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The INLINE on the Int instance of rotate enables it to be constant folded. For example: sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int) goes to: Main.$wfold = \ (ww_sO7 :: Int#) (ww1_sOb :: Int#) -> case ww1_sOb of wild_XM { __DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1); 10000000 -> ww_sO7 whereas before it was left as a call to $wrotate. All other Bits instances seem to inline well enough on their own to enable constant folding; for example 'shift': sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int) goes to: Main.$wfold = \ (ww_sOb :: Int#) (ww1_sOf :: Int#) -> case ww1_sOf of wild_XM { __DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1); 10000000 -> ww_sOb } -} -- Note [toIntegralSized optimization] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- The code in 'toIntegralSized' relies on GHC optimizing away statically -- decidable branches. -- -- If both integral types are statically known, GHC will be able optimize the -- code significantly (for @-O1@ and better). -- -- For instance (as of GHC 7.8.1) the following definitions: -- -- > w16_to_i32 = toIntegralSized :: Word16 -> Maybe Int32 -- > -- > i16_to_w16 = toIntegralSized :: Int16 -> Maybe Word16 -- -- are translated into the following (simplified) /GHC Core/ language: -- -- > w16_to_i32 = \x -> Just (case x of _ { W16# x# -> I32# (word2Int# x#) }) -- > -- > i16_to_w16 = \x -> case eta of _ -- > { I16# b1 -> case tagToEnum# (<=# 0 b1) of _ -- > { False -> Nothing -- > ; True -> Just (W16# (narrow16Word# (int2Word# b1))) -- > } -- > }
alexander-at-github/eta
libraries/base/Data/Bits.hs
Haskell
bsd-3-clause
21,596
{-# LANGUAGE CPP #-} module ETA.Rename.RnSplice ( rnTopSpliceDecls, rnSpliceType, rnSpliceExpr, rnSplicePat, rnSpliceDecl, rnBracket, checkThLocalName ) where import ETA.BasicTypes.Name import ETA.BasicTypes.NameSet import ETA.HsSyn.HsSyn import ETA.BasicTypes.RdrName import ETA.TypeCheck.TcRnMonad import ETA.Types.Kind #ifdef GHCI import ETA.Main.ErrUtils ( dumpIfSet_dyn_printer ) import Control.Monad ( unless, when ) import ETA.Main.DynFlags import ETA.DeSugar.DsMeta ( decsQTyConName, expQTyConName, patQTyConName, typeQTyConName ) import ETA.Iface.LoadIface ( loadInterfaceForName ) import ETA.BasicTypes.Module import ETA.Rename.RnEnv import ETA.Rename.RnPat ( rnPat ) import ETA.Rename.RnSource ( rnSrcDecls, findSplice ) import ETA.Rename.RnTypes ( rnLHsType ) import ETA.BasicTypes.SrcLoc import ETA.TypeCheck.TcEnv ( checkWellStaged, tcMetaTy ) import ETA.Utils.Outputable import ETA.BasicTypes.BasicTypes ( TopLevelFlag, isTopLevel ) import ETA.Utils.FastString import ETA.Main.Hooks import {-# SOURCE #-} ETA.Rename.RnExpr ( rnLExpr ) import {-# SOURCE #-} ETA.TypeCheck.TcExpr ( tcMonoExpr ) import {-# SOURCE #-} ETA.TypeCheck.TcSplice ( runMetaD, runMetaE, runMetaP, runMetaT, tcTopSpliceExpr ) #endif #ifndef GHCI rnBracket :: HsExpr RdrName -> HsBracket RdrName -> RnM (HsExpr Name, FreeVars) rnBracket e _ = failTH e "Template Haskell bracket" rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars) rnTopSpliceDecls e = failTH e "Template Haskell top splice" rnSpliceType :: HsSplice RdrName -> PostTc Name Kind -> RnM (HsType Name, FreeVars) rnSpliceType e _ = failTH e "Template Haskell type splice" rnSpliceExpr :: Bool -> HsSplice RdrName -> RnM (HsExpr Name, FreeVars) rnSpliceExpr _ e = failTH e "Template Haskell splice" rnSplicePat :: HsSplice RdrName -> RnM (Either (Pat RdrName) (Pat Name), FreeVars) rnSplicePat e = failTH e "Template Haskell pattern splice" rnSpliceDecl :: SpliceDecl RdrName -> RnM (SpliceDecl Name, FreeVars) rnSpliceDecl e = failTH e "Template Haskell declaration splice" #else {- ********************************************************* * * Splices * * ********************************************************* Note [Free variables of typed splices] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider renaming this: f = ... h = ...$(thing "f")... where the splice is a *typed* splice. The splice can expand into literally anything, so when we do dependency analysis we must assume that it might mention 'f'. So we simply treat all locally-defined names as mentioned by any splice. This is terribly brutal, but I don't see what else to do. For example, it'll mean that every locally-defined thing will appear to be used, so no unused-binding warnings. But if we miss the dependency, then we might typecheck 'h' before 'f', and that will crash the type checker because 'f' isn't in scope. Currently, I'm not treating a splice as also mentioning every import, which is a bit inconsistent -- but there are a lot of them. We might thereby get some bogus unused-import warnings, but we won't crash the type checker. Not very satisfactory really. Note [Renamer errors] ~~~~~~~~~~~~~~~~~~~~~ It's important to wrap renamer calls in checkNoErrs, because the renamer does not fail for out of scope variables etc. Instead it returns a bogus term/type, so that it can report more than one error. We don't want the type checker to see these bogus unbound variables. -} rnSpliceGen :: Bool -- Typed splice? -> (HsSplice Name -> RnM (a, FreeVars)) -- Outside brackets, run splice -> (HsSplice Name -> (PendingRnSplice, a)) -- Inside brackets, make it pending -> HsSplice RdrName -> RnM (a, FreeVars) rnSpliceGen is_typed_splice run_splice pend_splice splice@(HsSplice _ expr) = addErrCtxt (spliceCtxt (HsSpliceE is_typed_splice splice)) $ setSrcSpan (getLoc expr) $ do { stage <- getStage ; case stage of Brack pop_stage RnPendingTyped -> do { checkTc is_typed_splice illegalUntypedSplice ; (splice', fvs) <- setStage pop_stage $ rnSplice splice ; let (_pending_splice, result) = pend_splice splice' ; return (result, fvs) } Brack pop_stage (RnPendingUntyped ps_var) -> do { checkTc (not is_typed_splice) illegalTypedSplice ; (splice', fvs) <- setStage pop_stage $ rnSplice splice ; let (pending_splice, result) = pend_splice splice' ; ps <- readMutVar ps_var ; writeMutVar ps_var (pending_splice : ps) ; return (result, fvs) } _ -> do { (splice', fvs1) <- setStage (Splice is_typed_splice) $ rnSplice splice ; (result, fvs2) <- run_splice splice' ; return (result, fvs1 `plusFV` fvs2) } } --------------------- rnSplice :: HsSplice RdrName -> RnM (HsSplice Name, FreeVars) -- Not exported...used for all rnSplice (HsSplice splice_name expr) = do { checkTH expr "Template Haskell splice" ; loc <- getSrcSpanM ; n' <- newLocalBndrRn (L loc splice_name) ; (expr', fvs) <- rnLExpr expr ; return (HsSplice n' expr', fvs) } --------------------- rnSpliceExpr :: Bool -> HsSplice RdrName -> RnM (HsExpr Name, FreeVars) rnSpliceExpr is_typed splice = rnSpliceGen is_typed run_expr_splice pend_expr_splice splice where pend_expr_splice :: HsSplice Name -> (PendingRnSplice, HsExpr Name) pend_expr_splice rn_splice@(HsSplice n e) = (PendingRnExpSplice (PendSplice n e), HsSpliceE is_typed rn_splice) run_expr_splice :: HsSplice Name -> RnM (HsExpr Name, FreeVars) run_expr_splice rn_splice@(HsSplice _ expr') | is_typed -- Run it later, in the type checker = do { -- Ugh! See Note [Splices] above lcl_rdr <- getLocalRdrEnv ; gbl_rdr <- getGlobalRdrEnv ; let gbl_names = mkNameSet [gre_name gre | gre <- globalRdrEnvElts gbl_rdr , isLocalGRE gre] lcl_names = mkNameSet (localRdrEnvElts lcl_rdr) ; return (HsSpliceE is_typed rn_splice, lcl_names `plusFV` gbl_names) } | otherwise -- Run it here = do { expr <- getHooked runRnSpliceHook return >>= ($ expr') -- The splice must have type ExpQ ; meta_exp_ty <- tcMetaTy expQTyConName -- Typecheck the expression ; zonked_q_expr <- tcTopSpliceExpr False $ tcMonoExpr expr meta_exp_ty -- Run the expression ; expr2 <- runMetaE zonked_q_expr ; showSplice "expression" expr (ppr expr2) ; (lexpr3, fvs) <- checkNoErrs $ rnLExpr expr2 ; return (unLoc lexpr3, fvs) } ---------------------- rnSpliceType :: HsSplice RdrName -> PostTc Name Kind -> RnM (HsType Name, FreeVars) rnSpliceType splice k = rnSpliceGen False run_type_splice pend_type_splice splice where pend_type_splice rn_splice@(HsSplice n e) = (PendingRnTypeSplice (PendSplice n e), HsSpliceTy rn_splice k) run_type_splice (HsSplice _ expr') = do { expr <- getHooked runRnSpliceHook return >>= ($ expr') ; meta_exp_ty <- tcMetaTy typeQTyConName -- Typecheck the expression ; zonked_q_expr <- tcTopSpliceExpr False $ tcMonoExpr expr meta_exp_ty -- Run the expression ; hs_ty2 <- runMetaT zonked_q_expr ; showSplice "type" expr (ppr hs_ty2) ; (hs_ty3, fvs) <- do { let doc = SpliceTypeCtx hs_ty2 ; checkNoErrs $ rnLHsType doc hs_ty2 -- checkNoErrs: see Note [Renamer errors] } ; return (unLoc hs_ty3, fvs) } {- Note [rnSplicePat] ~~~~~~~~~~~~~~~~~~ Renaming a pattern splice is a bit tricky, because we need the variables bound in the pattern to be in scope in the RHS of the pattern. This scope management is effectively done by using continuation-passing style in RnPat, through the CpsRn monad. We don't wish to be in that monad here (it would create import cycles and generally conflict with renaming other splices), so we really want to return a (Pat RdrName) -- the result of running the splice -- which can then be further renamed in RnPat, in the CpsRn monad. The problem is that if we're renaming a splice within a bracket, we *don't* want to run the splice now. We really do just want to rename it to an HsSplice Name. Of course, then we can't know what variables are bound within the splice, so pattern splices within brackets aren't all that useful. In any case, when we're done in rnSplicePat, we'll either have a Pat RdrName (the result of running a top-level splice) or a Pat Name (the renamed nested splice). Thus, the awkward return type of rnSplicePat. -} -- | Rename a splice pattern. See Note [rnSplicePat] rnSplicePat :: HsSplice RdrName -> RnM ( Either (Pat RdrName) (Pat Name) , FreeVars) rnSplicePat splice = rnSpliceGen False run_pat_splice pend_pat_splice splice where pend_pat_splice rn_splice@(HsSplice n e) = (PendingRnPatSplice (PendSplice n e), Right $ SplicePat rn_splice) run_pat_splice (HsSplice _ expr') = do { expr <- getHooked runRnSpliceHook return >>= ($ expr') ; meta_exp_ty <- tcMetaTy patQTyConName -- Typecheck the expression ; zonked_q_expr <- tcTopSpliceExpr False $ tcMonoExpr expr meta_exp_ty -- Run the expression ; pat <- runMetaP zonked_q_expr ; showSplice "pattern" expr (ppr pat) ; return (Left $ unLoc pat, emptyFVs) } ---------------------- rnSpliceDecl :: SpliceDecl RdrName -> RnM (SpliceDecl Name, FreeVars) rnSpliceDecl (SpliceDecl (L loc splice) flg) = rnSpliceGen False run_decl_splice pend_decl_splice splice where pend_decl_splice rn_splice@(HsSplice n e) = (PendingRnDeclSplice (PendSplice n e), SpliceDecl(L loc rn_splice) flg) run_decl_splice rn_splice = pprPanic "rnSpliceDecl" (ppr rn_splice) rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars) -- Declaration splice at the very top level of the module rnTopSpliceDecls (HsSplice _ expr'') = do { (expr, fvs) <- setStage (Splice False) $ rnLExpr expr'' ; expr' <- getHooked runRnSpliceHook return >>= ($ expr) ; list_q <- tcMetaTy decsQTyConName -- Q [Dec] ; zonked_q_expr <- tcTopSpliceExpr False (tcMonoExpr expr' list_q) -- Run the expression ; decls <- runMetaD zonked_q_expr ; traceSplice $ SpliceInfo True "declarations" (Just (getLoc expr)) (Just $ ppr expr') (vcat (map ppr decls)) ; return (decls,fvs) } {- ************************************************************************ * * Template Haskell brackets * * ************************************************************************ -} rnBracket :: HsExpr RdrName -> HsBracket RdrName -> RnM (HsExpr Name, FreeVars) rnBracket e br_body = addErrCtxt (quotationCtxtDoc br_body) $ do { -- Check that Template Haskell is enabled and available thEnabled <- xoptM Opt_TemplateHaskell ; unless thEnabled $ failWith ( vcat [ ptext (sLit "Syntax error on") <+> ppr e , ptext (sLit "Perhaps you intended to use TemplateHaskell") ] ) ; checkTH e "Template Haskell bracket" -- Check for nested brackets ; cur_stage <- getStage ; case cur_stage of { Splice True -> checkTc (isTypedBracket br_body) illegalUntypedBracket ; Splice False -> checkTc (not (isTypedBracket br_body)) illegalTypedBracket ; Comp -> return () ; Brack {} -> failWithTc illegalBracket } -- Brackets are desugared to code that mentions the TH package ; recordThUse ; case isTypedBracket br_body of True -> do { (body', fvs_e) <- setStage (Brack cur_stage RnPendingTyped) $ rn_bracket cur_stage br_body ; return (HsBracket body', fvs_e) } False -> do { ps_var <- newMutVar [] ; (body', fvs_e) <- setStage (Brack cur_stage (RnPendingUntyped ps_var)) $ rn_bracket cur_stage br_body ; pendings <- readMutVar ps_var ; return (HsRnBracketOut body' pendings, fvs_e) } } rn_bracket :: ThStage -> HsBracket RdrName -> RnM (HsBracket Name, FreeVars) rn_bracket outer_stage br@(VarBr flg rdr_name) = do { name <- lookupOccRn rdr_name ; this_mod <- getModule ; case flg of { -- Type variables can be quoted in TH. See #5721. False -> return () ; True | nameIsLocalOrFrom this_mod name -> do { mb_bind_lvl <- lookupLocalOccThLvl_maybe name ; case mb_bind_lvl of { Nothing -> return () -- Can happen for data constructors, -- but nothing needs to be done for them ; Just (top_lvl, bind_lvl) -- See Note [Quoting names] | isTopLevel top_lvl -> when (isExternalName name) (keepAlive name) | otherwise -> do { traceRn (text "rn_bracket VarBr" <+> ppr name <+> ppr bind_lvl <+> ppr outer_stage) ; checkTc (thLevel outer_stage + 1 == bind_lvl) (quotedNameStageErr br) } } } ; True | otherwise -> -- Imported thing discardResult (loadInterfaceForName msg name) -- Reason for loadInterface: deprecation checking -- assumes that the home interface is loaded, and -- this is the only way that is going to happen } ; return (VarBr flg name, unitFV name) } where msg = ptext (sLit "Need interface for Template Haskell quoted Name") rn_bracket _ (ExpBr e) = do { (e', fvs) <- rnLExpr e ; return (ExpBr e', fvs) } rn_bracket _ (PatBr p) = rnPat ThPatQuote p $ \ p' -> return (PatBr p', emptyFVs) rn_bracket _ (TypBr t) = do { (t', fvs) <- rnLHsType TypBrCtx t ; return (TypBr t', fvs) } rn_bracket _ (DecBrL decls) = do { group <- groupDecls decls ; gbl_env <- getGblEnv ; let new_gbl_env = gbl_env { tcg_dus = emptyDUs } -- The emptyDUs is so that we just collect uses for this -- group alone in the call to rnSrcDecls below ; (tcg_env, group') <- setGblEnv new_gbl_env $ rnSrcDecls [] group -- The empty list is for extra dependencies coming from .hs-boot files -- See Note [Extra dependencies from .hs-boot files] in RnSource -- Discard the tcg_env; it contains only extra info about fixity ; traceRn (text "rn_bracket dec" <+> (ppr (tcg_dus tcg_env) $$ ppr (duUses (tcg_dus tcg_env)))) ; return (DecBrG group', duUses (tcg_dus tcg_env)) } where groupDecls :: [LHsDecl RdrName] -> RnM (HsGroup RdrName) groupDecls decls = do { (group, mb_splice) <- findSplice decls ; case mb_splice of { Nothing -> return group ; Just (splice, rest) -> do { group' <- groupDecls rest ; let group'' = appendGroups group group' ; return group'' { hs_splcds = noLoc splice : hs_splcds group' } } }} rn_bracket _ (DecBrG _) = panic "rn_bracket: unexpected DecBrG" rn_bracket _ (TExpBr e) = do { (e', fvs) <- rnLExpr e ; return (TExpBr e', fvs) } spliceCtxt :: HsExpr RdrName -> SDoc spliceCtxt expr= hang (ptext (sLit "In the splice:")) 2 (ppr expr) showSplice :: String -> LHsExpr Name -> SDoc -> TcM () -- Note that 'before' is *renamed* but not *typechecked* -- Reason (a) less typechecking crap -- (b) data constructors after type checking have been -- changed to their *wrappers*, and that makes them -- print always fully qualified showSplice what before after = traceSplice $ SpliceInfo False what Nothing (Just $ ppr before) after -- | The splice data to be logged -- -- duplicates code in TcSplice.lhs data SpliceInfo = SpliceInfo { spliceIsDeclaration :: Bool , spliceDescription :: String , spliceLocation :: Maybe SrcSpan , spliceSource :: Maybe SDoc , spliceGenerated :: SDoc } -- | outputs splice information for 2 flags which have different output formats: -- `-ddump-splices` and `-dth-dec-file` -- -- This duplicates code in TcSplice.lhs traceSplice :: SpliceInfo -> TcM () traceSplice sd = do loc <- case sd of SpliceInfo { spliceLocation = Nothing } -> getSrcSpanM SpliceInfo { spliceLocation = Just loc } -> return loc traceOptTcRn Opt_D_dump_splices (spliceDebugDoc loc sd) when (spliceIsDeclaration sd) $ do dflags <- getDynFlags liftIO $ dumpIfSet_dyn_printer alwaysQualify dflags Opt_D_th_dec_file (spliceCodeDoc loc sd) where -- `-ddump-splices` spliceDebugDoc :: SrcSpan -> SpliceInfo -> SDoc spliceDebugDoc loc sd = let code = case spliceSource sd of Nothing -> ending Just b -> nest 2 b : ending ending = [ text "======>", nest 2 (spliceGenerated sd) ] in (vcat [ ppr loc <> colon <+> text "Splicing" <+> text (spliceDescription sd) , nest 2 (sep code) ]) -- `-dth-dec-file` spliceCodeDoc :: SrcSpan -> SpliceInfo -> SDoc spliceCodeDoc loc sd = (vcat [ text "--" <+> ppr loc <> colon <+> text "Splicing" <+> text (spliceDescription sd) , sep [spliceGenerated sd] ]) illegalBracket :: SDoc illegalBracket = ptext (sLit "Template Haskell brackets cannot be nested (without intervening splices)") illegalTypedBracket :: SDoc illegalTypedBracket = ptext (sLit "Typed brackets may only appear in typed slices.") illegalUntypedBracket :: SDoc illegalUntypedBracket = ptext (sLit "Untyped brackets may only appear in untyped slices.") illegalTypedSplice :: SDoc illegalTypedSplice = ptext (sLit "Typed splices may not appear in untyped brackets") illegalUntypedSplice :: SDoc illegalUntypedSplice = ptext (sLit "Untyped splices may not appear in typed brackets") quotedNameStageErr :: HsBracket RdrName -> SDoc quotedNameStageErr br = sep [ ptext (sLit "Stage error: the non-top-level quoted name") <+> ppr br , ptext (sLit "must be used at the same stage at which is is bound")] quotationCtxtDoc :: HsBracket RdrName -> SDoc quotationCtxtDoc br_body = hang (ptext (sLit "In the Template Haskell quotation")) 2 (ppr br_body) -- spliceResultDoc :: OutputableBndr id => LHsExpr id -> SDoc -- spliceResultDoc expr -- = vcat [ hang (ptext (sLit "In the splice:")) -- 2 (char '$' <> pprParendExpr expr) -- , ptext (sLit "To see what the splice expanded to, use -ddump-splices") ] #endif checkThLocalName :: Name -> RnM () #ifndef GHCI /* GHCI and TH is off */ -------------------------------------- -- Check for cross-stage lifting checkThLocalName _name = return () #else /* GHCI and TH is on */ checkThLocalName name = do { traceRn (text "checkThLocalName" <+> ppr name) ; mb_local_use <- getStageAndBindLevel name ; case mb_local_use of { Nothing -> return () ; -- Not a locally-bound thing Just (top_lvl, bind_lvl, use_stage) -> do { let use_lvl = thLevel use_stage ; checkWellStaged (quotes (ppr name)) bind_lvl use_lvl ; traceRn (text "checkThLocalName" <+> ppr name <+> ppr bind_lvl <+> ppr use_stage <+> ppr use_lvl) ; when (use_lvl > bind_lvl) $ checkCrossStageLifting top_lvl name use_stage } } } -------------------------------------- checkCrossStageLifting :: TopLevelFlag -> Name -> ThStage -> TcM () -- We are inside brackets, and (use_lvl > bind_lvl) -- Now we must check whether there's a cross-stage lift to do -- Examples \x -> [| x |] -- [| map |] checkCrossStageLifting top_lvl name (Brack _ (RnPendingUntyped ps_var)) | isTopLevel top_lvl -- Top-level identifiers in this module, -- (which have External Names) -- are just like the imported case: -- no need for the 'lifting' treatment -- E.g. this is fine: -- f x = x -- g y = [| f 3 |] = when (isExternalName name) (keepAlive name) -- See Note [Keeping things alive for Template Haskell] | otherwise = -- Nested identifiers, such as 'x' in -- E.g. \x -> [| h x |] -- We must behave as if the reference to x was -- h $(lift x) -- We use 'x' itself as the splice proxy, used by -- the desugarer to stitch it all back together. -- If 'x' occurs many times we may get many identical -- bindings of the same splice proxy, but that doesn't -- matter, although it's a mite untidy. do { traceRn (text "checkCrossStageLifting" <+> ppr name) ; -- Update the pending splices ; ps <- readMutVar ps_var ; writeMutVar ps_var (PendingRnCrossStageSplice name : ps) } checkCrossStageLifting _ _ _ = return () #endif /* GHCI */ {- Note [Keeping things alive for Template Haskell] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f x = x+1 g y = [| f 3 |] Here 'f' is referred to from inside the bracket, which turns into data and mentions only f's *name*, not 'f' itself. So we need some other way to keep 'f' alive, lest it get dropped as dead code. That's what keepAlive does. It puts it in the keep-alive set, which subsequently ensures that 'f' stays as a top level binding. This must be done by the renamer, not the type checker (as of old), because the type checker doesn't typecheck the body of untyped brackets (Trac #8540). A thing can have a bind_lvl of outerLevel, but have an internal name: foo = [d| op = 3 bop = op + 1 |] Here the bind_lvl of 'op' is (bogusly) outerLevel, even though it is bound inside a bracket. That is because we don't even even record binding levels for top-level things; the binding levels are in the LocalRdrEnv. So the occurrence of 'op' in the rhs of 'bop' looks a bit like a cross-stage thing, but it isn't really. And in fact we never need to do anything here for top-level bound things, so all is fine, if a bit hacky. For these chaps (which have Internal Names) we don't want to put them in the keep-alive set. Note [Quoting names] ~~~~~~~~~~~~~~~~~~~~ A quoted name 'n is a bit like a quoted expression [| n |], except that we have no cross-stage lifting (c.f. TcExpr.thBrackId). So, after incrementing the use-level to account for the brackets, the cases are: bind > use Error bind = use+1 OK bind < use Imported things OK Top-level things OK Non-top-level Error where 'use' is the binding level of the 'n quote. (So inside the implied bracket the level would be use+1.) Examples: f 'map -- OK; also for top-level defns of this module \x. f 'x -- Not ok (bind = 1, use = 1) -- (whereas \x. f [| x |] might have been ok, by -- cross-stage lifting \y. [| \x. $(f 'y) |] -- Not ok (bind =1, use = 1) [| \x. $(f 'x) |] -- OK (bind = 2, use = 1) -}
alexander-at-github/eta
compiler/ETA/Rename/RnSplice.hs
Haskell
bsd-3-clause
24,906
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Дополнение Selenium</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Содержание</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/selenium/src/main/javahelp/org/zaproxy/zap/extension/selenium/resources/help_ru_RU/helpset_ru_RU.hs
Haskell
apache-2.0
1,006
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ar-SA"> <title>Retest Add-On</title> <maps> <homeID>retest</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/retest/src/main/javahelp/org/zaproxy/addon/retest/resources/help_ar_SA/helpset_ar_SA.hs
Haskell
apache-2.0
961
module T16804a where import Data.Monoid data Test = A | B deriving (Show) instance Monoid Test where mempty = A -- empty for linenumbers in T16804 to be correct -- empty for linenumbers in T16804 to be correct testFunction :: Test -> Test -> Bool testFunction A B = True testFunction B A = True testFunction _ _ = False testFunction2 :: Bool -> Test testFunction2 True = A testFunction2 False = B niceValue :: Int niceValue = getSum (Sum 1 <> Sum 2 <> mempty) niceValue2 :: Test niceValue2 = A <> A <> A <> B <> A <> mempty instance Semigroup Test where A <> val = val B <> _ = B
sdiehl/ghc
testsuite/tests/ghci/scripts/T16804a.hs
Haskell
bsd-3-clause
597
{- $Id: AFRPTestsRPSwitch.hs,v 1.2 2003/11/10 21:28:58 antony Exp $ ****************************************************************************** * A F R P * * * * Module: AFRPTestsRPSwitch * * Purpose: Test cases for rpSwitchB and drpSwitchB * * Authors: Antony Courtney and Henrik Nilsson * * * * Copyright (c) Yale University, 2003 * * * ****************************************************************************** -} module AFRPTestsRPSwitch ( rpswitch_tr, rpswitch_trs, rpswitch_st0, rpswitch_st0r ) where import Data.Maybe (fromJust) import Data.List (findIndex) import FRP.Yampa import FRP.Yampa.Internals (Event(NoEvent, Event)) import AFRPTestsCommon ------------------------------------------------------------------------------ -- Test cases for rpSwitchB and drpSwitchB ------------------------------------------------------------------------------ rpswitch_inp1 = (fromJust (head delta_inp), zip (repeat 1.0) (tail delta_inp)) where delta_inp = [Just (1.0, NoEvent), Nothing, Nothing, Just (2.0, Event (integral:)), Just (3.0, NoEvent), Nothing, Just (4.0, NoEvent), Nothing, Nothing, Just (5.0, Event ((integral >>> arr (+100.0)):)), Just (6.0, NoEvent), Nothing, Just (7.0, NoEvent), Nothing, Nothing, Just (8.0, Event tail), Just (9.0, NoEvent), Nothing] ++ repeat Nothing -- This input contains exaples of "continuos switching", i.e. the same -- switching event ocurring during a a few contiguous time steps. -- It also starts with an immediate switch. rpswitch_inp2 = (fromJust (head delta_inp), zip (repeat 1.0) (tail delta_inp)) where delta_inp = [Just (1.0, Event (integral:)), Just (1.0, NoEvent), Nothing, Just (2.0, Event ((integral >>> arr(+100.0)):)), Nothing, Nothing, Just (3.0, Event ((integral >>> arr(+200.0)):)), Nothing, Nothing, Just (4.0, NoEvent), Nothing, Nothing, Just (5.0, Event ((arr (*3)):)), Just (5.0, NoEvent), Nothing, Just (6.0, Event tail), Just (7.0, Event ((arr (*7)):)), Just (8.0, Event (take 2)), Just (9.0, NoEvent), Nothing] ++ repeat Nothing rpswitch_t0 :: [[Double]] rpswitch_t0 = take 20 $ embed (rpSwitchB []) rpswitch_inp1 rpswitch_t0r = [[], -- 0 s [], -- 1 s [], -- 2 s [0.0], -- 3 s [2.0], -- 4 s [5.0], -- 5 s [8.0], -- 6 s [12.0], -- 7 s [16.0], -- 8 s [100.0, 20.0], -- 9 s [105.0, 25.0], -- 10 s [111.0, 31.0], -- 11 s [117.0, 37.0], -- 12 s [124.0, 44.0], -- 13 s [131.0, 51.0], -- 14 s [58.0], -- 15 s [66.0], -- 16 s [75.0], -- 17 s [84.0], -- 18 s [93.0]] -- 19 s rpswitch_t1 :: [[Double]] rpswitch_t1 = take 20 $ embed (drpSwitchB []) rpswitch_inp1 rpswitch_t1r = [[], -- 0 s [], -- 1 s [], -- 2 s [], -- 3 s [2.0], -- 4 s [5.0], -- 5 s [8.0], -- 6 s [12.0], -- 7 s [16.0], -- 8 s [20.0] , -- 9 s [105.0, 25.0], -- 10 s [111.0, 31.0], -- 11 s [117.0, 37.0], -- 12 s [124.0, 44.0], -- 13 s [131.0, 51.0], -- 14 s [138.0, 58.0], -- 15 s [66.0], -- 16 s [75.0], -- 17 s [84.0], -- 18 s [93.0]] -- 19 s rpswitch_t2 :: [[Double]] rpswitch_t2 = take 20 $ embed (rpSwitchB []) rpswitch_inp2 rpswitch_t2r = [[0.0], -- 0 s [1.0], -- 1 s [2.0], -- 2 s [100.0, 3.0], -- 3 s [100.0, 102.0, 5.0], -- 4 s [100.0, 102.0, 104.0, 7.0], -- 5 s [200.0, 102.0, 104.0, 106.0, 9.0], -- 6 s [200.0, 203.0, 105.0, 107.0, 109.0, 12.0], -- 7 s [200.0, 203.0, 206.0, 108.0, 110.0, 112.0, 15.0], -- 8 s [203.0, 206.0, 209.0, 111.0, 113.0, 115.0, 18.0], -- 9 s [207.0, 210.0, 213.0, 115.0, 117.0, 119.0, 22.0], -- 10 s [211.0, 214.0, 217.0, 119.0, 121.0, 123.0, 26.0], -- 11 s [15.0, 215.0, 218.0, 221.0, 123.0, 125.0, 127.0, 30.0], -- 12 s [15.0, 220.0, 223.0, 226.0, 128.0, 130.0, 132.0, 35.0], -- 13 s [15.0, 225.0, 228.0, 231.0, 133.0, 135.0, 137.0, 40.0], -- 14 s [230.0, 233.0, 236.0, 138.0, 140.0, 142.0, 45.0], -- 15 s [49.0, 236.0, 239.0, 242.0, 144.0, 146.0, 148.0, 51.0], -- 16 s [56.0, 243.0], -- 17 s [63.0, 251.0], -- 18 s [63.0, 260.0]] -- 19 s rpswitch_t3 :: [[Double]] rpswitch_t3 = take 20 $ embed (drpSwitchB []) rpswitch_inp2 rpswitch_t3r = [[], -- 0 s [1.0], -- 1 s [2.0], -- 2 s [3.0], -- 3 s [102.0, 5.0], -- 4 s [102.0, 104.0, 7.0], -- 5 s [102.0, 104.0, 106.0, 9.0], -- 6 s [203.0, 105.0, 107.0, 109.0, 12.0], -- 7 s [203.0, 206.0, 108.0, 110.0, 112.0, 15.0], -- 8 s [203.0, 206.0, 209.0, 111.0, 113.0, 115.0, 18.0], -- 9 s [207.0, 210.0, 213.0, 115.0, 117.0, 119.0, 22.0], -- 10 s [211.0, 214.0, 217.0, 119.0, 121.0, 123.0, 26.0], -- 11 s [215.0, 218.0, 221.0, 123.0, 125.0, 127.0, 30.0], -- 12 s [15.0, 220.0, 223.0, 226.0, 128.0, 130.0, 132.0, 35.0], -- 13 s [15.0, 225.0, 228.0, 231.0, 133.0, 135.0, 137.0, 40.0], -- 14 s [18.0, 230.0, 233.0, 236.0, 138.0, 140.0, 142.0, 45.0], -- 15 s [236.0, 239.0, 242.0, 144.0, 146.0, 148.0, 51.0], -- 16 s [56.0, 243.0, 246.0, 249.0, 151.0, 153.0, 155.0, 58.0], -- 17 s [63.0, 251.0], -- 18 s [63.0, 260.0]] -- 19 s -- Starts three "ramps" with different phase. As soon as one exceeds a -- threshold, it's restarted, while the others are left alone. The observaton -- of the output is done via a loop, thus the use of a delayed switch is -- essential. rpswitch_ramp :: Double -> SF a Double rpswitch_ramp phase = constant 2.0 >>> integral >>> arr (+phase) -- We assume that only one signal function will reach the limit at a time. rpswitch_limit :: Double -> SF [Double] (Event ([SF a Double]->[SF a Double])) rpswitch_limit x = arr (findIndex (>=x)) >>> edgeJust >>> arr (fmap restart) where restart n = \sfs -> take n sfs ++ [rpswitch_ramp 0.0] ++ drop (n+1) sfs rpswitch_t4 :: [[Double]] rpswitch_t4 = take 30 $ embed (loop sf) (deltaEncode 0.1 (repeat ())) where sf :: SF (a, [Double]) ([Double],[Double]) sf = (second (rpswitch_limit 2.99) >>> drpSwitchB [rpswitch_ramp 0.0, rpswitch_ramp 1.0, rpswitch_ramp 2.0]) >>> arr dup rpswitch_t4r = [[0.0, 1.0, 2.0], [0.2, 1.2, 2.2], [0.4, 1.4, 2.4], [0.6, 1.6, 2.6], [0.8, 1.8, 2.8], [1.0, 2.0, 3.0], [1.2, 2.2, 0.2], [1.4, 2.4, 0.4], [1.6, 2.6, 0.6], [1.8, 2.8, 0.8], [2.0, 3.0, 1.0], [2.2, 0.2, 1.2], [2.4, 0.4, 1.4], [2.6, 0.6, 1.6], [2.8, 0.8, 1.8], [3.0, 1.0, 2.0], [0.2, 1.2, 2.2], [0.4, 1.4, 2.4], [0.6, 1.6, 2.6], [0.8, 1.8, 2.8], [1.0, 2.0, 3.0], [1.2, 2.2, 0.2], [1.4, 2.4, 0.4], [1.6, 2.6, 0.6], [1.8, 2.8, 0.8], [2.0, 3.0, 1.0], [2.2, 0.2, 1.2], [2.4, 0.4, 1.4], [2.6, 0.6, 1.6], [2.8, 0.8, 1.8]] rpswitch_trs = [ rpswitch_t0 ~= rpswitch_t0r, rpswitch_t1 ~= rpswitch_t1r, rpswitch_t2 ~= rpswitch_t2r, rpswitch_t3 ~= rpswitch_t3r, rpswitch_t4 ~= rpswitch_t4r ] rpswitch_tr = and rpswitch_trs rpswitch_st0 = testSFSpaceLeak 1000000 (loop sf) where sf :: SF (a, [Double]) ([Double],[Double]) sf = (second (rpswitch_limit 2.99) >>> drpSwitchB [rpswitch_ramp 0.0, rpswitch_ramp 1.0, rpswitch_ramp 2.0]) >>> arr dup rpswitch_st0r = [1.5,2.5,0.5]
ony/Yampa-core
tests/AFRPTestsRPSwitch.hs
Haskell
bsd-3-clause
8,137
-- (c) 2000-2005 by Martin Erwig [see file COPYRIGHT] module Data.Graph.Inductive.Query.SP( spTree,spLength,sp, dijkstra ) where import qualified Data.Graph.Inductive.Internal.Heap as H import Data.Graph.Inductive.Graph import Data.Graph.Inductive.Internal.RootPath expand :: Real b => b -> LPath b -> Context a b -> [H.Heap b (LPath b)] expand d (LP p) (_,_,_,s) = map (\(l,v)->H.unit (l+d) (LP ((v,l+d):p))) s -- | Implementation of Dijkstra's shortest path algorithm dijkstra :: (Graph gr, Real b) => H.Heap b (LPath b) -> gr a b -> LRTree b dijkstra h g | H.isEmpty h || isEmpty g = [] dijkstra h g = case match v g of (Just c,g') -> p:dijkstra (H.mergeAll (h':expand d p c)) g' (Nothing,g') -> dijkstra h' g' where (_,p@(LP ((v,d):_)),h') = H.splitMin h spTree :: (Graph gr, Real b) => Node -> gr a b -> LRTree b spTree v = dijkstra (H.unit 0 (LP [(v,0)])) spLength :: (Graph gr, Real b) => Node -> Node -> gr a b -> b spLength s t = getDistance t . spTree s sp :: (Graph gr, Real b) => Node -> Node -> gr a b -> Path sp s t = getLPathNodes t . spTree s
FranklinChen/hugs98-plus-Sep2006
packages/fgl/Data/Graph/Inductive/Query/SP.hs
Haskell
bsd-3-clause
1,114
import Test.Cabal.Prelude main = cabalTest $ do cabal "new-test" []
themoritz/cabal
cabal-testsuite/PackageTests/TestSuiteTests/ExeV10/cabal.test.hs
Haskell
bsd-3-clause
73
----------------------------------------------------------------------------- -- | -- Module : XMonad.Doc.Developing -- Copyright : (C) 2007 Andrea Rossato -- License : BSD3 -- -- Maintainer : andrea.rossato@unibz.it -- Stability : unstable -- Portability : portable -- -- This module gives a brief overview of the xmonad internals. It is -- intended for advanced users who are curious about the xmonad source -- code and want an brief overview. This document may also be helpful -- for the beginner\/intermediate Haskell programmer who is motivated -- to write an xmonad extension as a way to deepen her understanding -- of this powerful functional language; however, there is not space -- here to go into much detail. For a more comprehensive document -- covering some of the same material in more depth, see the guided -- tour of the xmonad source on the xmonad wiki: -- <http://haskell.org/haskellwiki/Xmonad/Guided_tour_of_the_xmonad_source>. -- -- If you write an extension module and think it may be useful for -- others, consider releasing it. Coding guidelines and licensing -- policies are covered at the end of this document, and must be -- followed if you want your code to be included in the official -- repositories. For a basic tutorial on the nuts and bolts of -- developing a new extension for xmonad, see the tutorial on the -- wiki: -- <http://haskell.org/haskellwiki/Xmonad/xmonad_development_tutorial>. -- ----------------------------------------------------------------------------- module XMonad.Doc.Developing ( -- * Writing new extensions -- $writing -- * Libraries for writing window managers -- $xmonad-libs -- * xmonad internals -- $internals -- ** The @main@ entry point -- $main -- ** The X monad and the internal state -- $internalState -- ** Event handling and messages -- $events -- ** The 'LayoutClass' -- $layoutClass -- * Coding style -- $style -- * Licensing policy -- $license ) where -------------------------------------------------------------------------------- -- -- Writing Extensions -- -------------------------------------------------------------------------------- {- $writing -} {- $xmonad-libs Starting with version 0.5, xmonad and xmonad-contrib are packaged and distributed as libraries, instead of components which must be compiled by the user into a binary (as they were prior to version 0.5). This way of distributing xmonad has many advantages, since it allows packaging by GNU\/Linux distributions while still allowing the user to customize the window manager to fit her needs. Basically, xmonad and the xmonad-contrib libraries let users write their own window manager in just a few lines of code. While @~\/.xmonad\/xmonad.hs@ at first seems to be simply a configuration file, it is actually a complete Haskell program which uses the xmonad and xmonad-contrib libraries to create a custom window manager. This makes it possible not only to edit the default xmonad configuration, as we have seen in the "XMonad.Doc.Extending" document, but to use the Haskell programming language to extend the window manager you are writing in any way you see fit. -} {- $internals -} {- $main #The_main_entry_point# xmonad installs a binary, @xmonad@, which must be executed by the Xsession starting script. This binary, whose code can be read in @Main.hs@ of the xmonad source tree, will use 'XMonad.Core.recompile' to run @ghc@ in order to build a binary from @~\/.xmonad\/xmonad.hs@. If this compilation process fails, for any reason, a default @main@ entry point will be used, which calls the 'XMonad.Main.xmonad' function with a default configuration. Thus, the real @main@ entry point, the one that even the users' custom window manager application in @~\/.xmonad\/xmonad.hs@ must call, is the 'XMonad.Main.xmonad' function. This function takes a configuration as its only argument, whose type ('XMonad.Core.XConfig') is defined in "XMonad.Core". 'XMonad.Main.xmonad' takes care of opening the connection with the X server, initializing the state (or deserializing it when restarted) and the configuration, and calling the event handler ('XMonad.Main.handle') that goes into an infinite loop (using 'Prelude.forever') waiting for events and acting accordingly. -} {- $internalState The event loop which calls 'XMonad.Main.handle' to react to events is run within the 'XMonad.Core.X' monad, which is a 'Control.Monad.State.StateT' transformer over 'IO', encapsulated within a 'Control.Monad.Reader.ReaderT' transformer. The 'Control.Monad.State.StateT' transformer encapsulates the (read\/writable) state of the window manager (of type 'XMonad.Core.XState'), whereas the 'Control.Monad.Reader.ReaderT' transformer encapsulates the (read-only) configuration (of type 'XMonad.Core.XConf'). Thanks to GHC's newtype deriving feature, the instance of the 'Control.Monad.State.MonadState' class parametrized over 'XMonad.Core.XState' and the instance of the 'Control.Monad.Reader.MonadReader' class parametrized over 'XMonad.Core.XConf' are automatically derived for the 'XMonad.Core.X' monad. This way we can use 'Control.Monad.State.get', 'Control.Monad.State.gets' and 'Control.Monad.State.modify' for the 'XMonad.Core.XState', and 'Control.Monad.Reader.ask' and 'Control.Monad.Reader.asks' for reading the 'XMonad.Core.XConf'. 'XMonad.Core.XState' is where all the sensitive information about window management is stored. The most important field of the 'XMonad.Core.XState' is the 'XMonad.Core.windowset', whose type ('XMonad.Core.WindowSet') is a synonym for a 'XMonad.StackSet.StackSet' parametrized over a 'XMonad.Core.WorkspaceID' (a 'String'), a layout type wrapped inside the 'XMonad.Layout.Layout' existential data type, the 'Graphics.X11.Types.Window' type, the 'XMonad.Core.ScreenID' and the 'XMonad.Core.ScreenDetail's. What a 'XMonad.StackSet.StackSet' is and how it can be manipulated with pure functions is described in the Haddock documentation of the "XMonad.StackSet" module. The 'XMonad.StackSet.StackSet' ('XMonad.Core.WindowSet') has four fields: * 'XMonad.StackSet.current', for the current, focused workspace. This is a 'XMonad.StackSet.Screen', which is composed of a 'XMonad.StackSet.Workspace' together with the screen information (for Xinerama support). * 'XMonad.StackSet.visible', a list of 'XMonad.StackSet.Screen's for the other visible (with Xinerama) workspaces. For non-Xinerama setups, this list is always empty. * 'XMonad.StackSet.hidden', the list of non-visible 'XMonad.StackSet.Workspace's. * 'XMonad.StackSet.floating', a map from floating 'Graphics.X11.Types.Window's to 'XMonad.StackSet.RationalRect's specifying their geometry. The 'XMonad.StackSet.Workspace' type is made of a 'XMonad.StackSet.tag', a 'XMonad.StackSet.layout' and a (possibly empty) 'XMonad.StackSet.stack' of windows. "XMonad.StackSet" (which should usually be imported qualified, to avoid name clashes with Prelude functions such as 'Prelude.delete' and 'Prelude.filter') provides many pure functions to manipulate the 'XMonad.StackSet.StackSet'. These functions are most commonly used as an argument to 'XMonad.Operations.windows', which takes a pure function to manipulate the 'XMonad.Core.WindowSet' and does all the needed operations to refresh the screen and save the modified 'XMonad.Core.XState'. During each 'XMonad.Operations.windows' call, the 'XMonad.StackSet.layout' field of the 'XMonad.StackSet.current' and 'XMonad.StackSet.visible' 'XMonad.StackSet.Workspace's are used to physically arrange the 'XMonad.StackSet.stack' of windows on each workspace. The possibility of manipulating the 'XMonad.StackSet.StackSet' ('XMonad.Core.WindowSet') with pure functions makes it possible to test all the properties of those functions with QuickCheck, providing greater reliability of the core code. Every change to the "XMonad.StackSet" module must be accompanied by appropriate QuickCheck properties before being applied. -} {- $events Event handling is the core activity of xmonad. Events generated by the X server are most important, but there may also be events generated by layouts or the user. "XMonad.Core" defines a class that generalizes the concept of events, 'XMonad.Core.Message', constrained to types with a 'Data.Typeable.Typeable' instance definition (which can be automatically derived by GHC). 'XMonad.Core.Message's are wrapped within an existential type 'XMonad.Core.SomeMessage'. The 'Data.Typeable.Typeable' constraint allows for the definition of a 'XMonad.Core.fromMessage' function that can unwrap the message with 'Data.Typeable.cast'. X Events are instances of this class, along with any messages used by xmonad itself or by extension modules. Using the 'Data.Typeable.Typeable' class for any kind of 'XMonad.Core.Message's and events allows us to define polymorphic functions for processing messages or unhandled events. This is precisely what happens with X events: xmonad passes them to 'XMonad.Main.handle'. If the main event handling function doesn't have anything to do with the event, the event is sent to all visible layouts by 'XMonad.Operations.broadcastMessage'. This messaging system allows the user to create new message types, simply declare an instance of the 'Data.Typeable.Typeable' and use 'XMonad.Operations.sendMessage' to send commands to layouts. And, finally, layouts may handle X events and other messages within the same function... miracles of polymorphism. -} {- $layoutClass #The_LayoutClass# to do -} {- $style These are the coding guidelines for contributing to xmonad and the xmonad contributed extensions. * Comment every top level function (particularly exported funtions), and provide a type signature. * Use Haddock syntax in the comments (see below). * Follow the coding style of the other modules. * Code should be compilable with "ghc-options: -Wall -Werror" set in the xmonad-contrib.cabal file. There should be no warnings. * Code should be free of any warnings or errors from the Hlint tool; use your best judgement on some warnings like eta-reduction or bracket removal, though. * Partial functions should be avoided: the window manager should not crash, so never call 'error' or 'undefined'. * Tabs are /illegal/. Use 4 spaces for indenting. * Any pure function added to the core must have QuickCheck properties precisely defining its behaviour. Tests for everything else are encouraged. For examples of Haddock documentation syntax, have a look at other extensions. Important points are: * Every exported function (or even better, every function) should have a Haddock comment explaining what it does, and providing examples. * Literal chunks of code can be written in comments using \"birdtrack\" notation (a greater-than symbol at the beginning of each line). Be sure to leave a blank line before and after each birdtrack-quoted section. * Link to functions by surrounding the names in single quotes, modules in double quotes. * Literal quote marks and slashes should be escaped with a backslash. To generate and view the Haddock documentation for your extension, run > runhaskell Setup haddock and then point your browser to @\/path\/to\/XMonadContrib\/dist\/doc\/html\/xmonad-contrib\/index.html@. For more information, see the Haddock documentation: <http://www.haskell.org/haddock/doc/html/index.html>. For more information on the nuts and bolts of how to develop your own extension, see the tutorial on the wiki: <http://haskell.org/haskellwiki/Xmonad/xmonad_development_tutorial>. -} {- $license New modules should identify the author, and be submitted under the same license as xmonad (BSD3 license or freer). -}
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Doc/Developing.hs
Haskell
bsd-2-clause
11,768
{-| Code for setting up the RIO environment. -} module Urbit.King.App ( KingEnv , runKingEnvStderr , runKingEnvStderrRaw , runKingEnvLogFile , runKingEnvNoLog , kingEnvKillSignal , killKingActionL , onKillKingSigL , HostEnv , runHostEnv , PierEnv , runPierEnv , killPierActionL , onKillPierSigL , HasStderrLogFunc(..) , HasKingId(..) , HasProcId(..) , HasKingEnv(..) , HasMultiEyreApi(..) , HasHostEnv(..) , HasPierEnv(..) , module Urbit.King.Config ) where import Urbit.King.Config import Urbit.Prelude import RIO (logGeneric) import System.Directory ( createDirectoryIfMissing , getXdgDirectory , XdgDirectory(XdgCache) ) import System.Posix.Internals (c_getpid) import System.Posix.Types (CPid(..)) import System.Random (randomIO) import Urbit.King.App.Class (HasStderrLogFunc(..)) import Urbit.Vere.Eyre.Multi (MultiEyreApi) import Urbit.Vere.Ports (PortControlApi, HasPortControlApi(..)) -- KingEnv --------------------------------------------------------------------- class HasKingId a where kingIdL :: Lens' a Word16 class HasProcId a where procIdL :: Lens' a Int32 class (HasLogFunc a, HasStderrLogFunc a, HasKingId a, HasProcId a) => HasKingEnv a where kingEnvL :: Lens' a KingEnv data KingEnv = KingEnv { _kingEnvLogFunc :: !LogFunc , _kingEnvStderrLogFunc :: !LogFunc , _kingEnvKingId :: !Word16 , _kingEnvProcId :: !Int32 , _kingEnvKillSignal :: !(TMVar ()) } makeLenses ''KingEnv instance HasKingEnv KingEnv where kingEnvL = id instance HasLogFunc KingEnv where logFuncL = kingEnvLogFunc instance HasStderrLogFunc KingEnv where stderrLogFuncL = kingEnvStderrLogFunc instance HasProcId KingEnv where procIdL = kingEnvProcId instance HasKingId KingEnv where kingIdL = kingEnvKingId -- Running KingEnvs ------------------------------------------------------------ runKingEnvStderr :: Bool -> LogLevel -> RIO KingEnv a -> IO a runKingEnvStderr verb lvl inner = do logOptions <- logOptionsHandle stderr verb <&> setLogUseTime True <&> setLogUseLoc False <&> setLogMinLevel lvl withLogFunc logOptions $ \logFunc -> runKingEnv logFunc logFunc inner runKingEnvStderrRaw :: Bool -> LogLevel -> RIO KingEnv a -> IO a runKingEnvStderrRaw verb lvl inner = do logOptions <- logOptionsHandle stderr verb <&> setLogUseTime True <&> setLogUseLoc False <&> setLogMinLevel lvl withLogFunc logOptions $ \logFunc -> let lf = wrapCarriage logFunc in runKingEnv lf lf inner -- XX loses callstack wrapCarriage :: LogFunc -> LogFunc wrapCarriage lf = mkLogFunc $ \_ ls ll bldr -> runRIO lf $ logGeneric ls ll (bldr <> "\r") runKingEnvLogFile :: Bool -> LogLevel -> Maybe FilePath -> RIO KingEnv a -> IO a runKingEnvLogFile verb lvl fileM inner = do logFile <- case fileM of Just f -> pure f Nothing -> defaultLogFile withLogFileHandle logFile $ \h -> do logOptions <- logOptionsHandle h verb <&> setLogUseTime True <&> setLogUseLoc False <&> setLogMinLevel lvl stderrLogOptions <- logOptionsHandle stderr verb <&> setLogUseTime False <&> setLogUseLoc False <&> setLogMinLevel lvl withLogFunc stderrLogOptions $ \stderrLogFunc -> withLogFunc logOptions $ \logFunc -> runKingEnv logFunc stderrLogFunc inner withLogFileHandle :: FilePath -> (Handle -> IO a) -> IO a withLogFileHandle f act = withFile f AppendMode $ \handle -> do hSetBuffering handle LineBuffering act handle defaultLogFile :: IO FilePath defaultLogFile = do logDir <- getXdgDirectory XdgCache "urbit" createDirectoryIfMissing True logDir logId :: Word32 <- randomIO pure (logDir </> "king-" <> show logId <> ".log") runKingEnvNoLog :: RIO KingEnv a -> IO a runKingEnvNoLog act = runKingEnv mempty mempty act runKingEnv :: LogFunc -> LogFunc -> RIO KingEnv a -> IO a runKingEnv logFunc stderr action = do kid <- randomIO CPid pid <- c_getpid kil <- newEmptyTMVarIO runRIO (KingEnv logFunc stderr kid pid kil) action -- KingEnv Utils --------------------------------------------------------------- onKillKingSigL :: HasKingEnv e => Getter e (STM ()) onKillKingSigL = kingEnvL . kingEnvKillSignal . to readTMVar killKingActionL :: HasKingEnv e => Getter e (STM ()) killKingActionL = kingEnvL . kingEnvKillSignal . to (\kil -> void (tryPutTMVar kil ())) -- HostEnv ------------------------------------------------------------------ -- The host environment is everything in King, eyre configuration shared -- across ships, and nat punching data. class HasMultiEyreApi a where multiEyreApiL :: Lens' a MultiEyreApi class (HasKingEnv a, HasMultiEyreApi a, HasPortControlApi a) => HasHostEnv a where hostEnvL :: Lens' a HostEnv data HostEnv = HostEnv { _hostEnvKingEnv :: !KingEnv , _hostEnvMultiEyreApi :: !MultiEyreApi , _hostEnvPortControlApi :: !PortControlApi } makeLenses ''HostEnv instance HasKingEnv HostEnv where kingEnvL = hostEnvKingEnv instance HasLogFunc HostEnv where logFuncL = kingEnvL . logFuncL instance HasStderrLogFunc HostEnv where stderrLogFuncL = kingEnvL . stderrLogFuncL instance HasProcId HostEnv where procIdL = kingEnvL . procIdL instance HasKingId HostEnv where kingIdL = kingEnvL . kingEnvKingId instance HasMultiEyreApi HostEnv where multiEyreApiL = hostEnvMultiEyreApi instance HasPortControlApi HostEnv where portControlApiL = hostEnvPortControlApi -- Running Running Envs -------------------------------------------------------- runHostEnv :: MultiEyreApi -> PortControlApi -> RIO HostEnv a -> RIO KingEnv a runHostEnv multi ports action = do king <- ask let hostEnv = HostEnv { _hostEnvKingEnv = king , _hostEnvMultiEyreApi = multi , _hostEnvPortControlApi = ports } io (runRIO hostEnv action) -- PierEnv --------------------------------------------------------------------- class (HasKingEnv a, HasHostEnv a, HasPierConfig a, HasNetworkConfig a) => HasPierEnv a where pierEnvL :: Lens' a PierEnv data PierEnv = PierEnv { _pierEnvHostEnv :: !HostEnv , _pierEnvPierConfig :: !PierConfig , _pierEnvNetworkConfig :: !NetworkConfig , _pierEnvKillSignal :: !(TMVar ()) } makeLenses ''PierEnv instance HasKingEnv PierEnv where kingEnvL = pierEnvHostEnv . kingEnvL instance HasHostEnv PierEnv where hostEnvL = pierEnvHostEnv instance HasMultiEyreApi PierEnv where multiEyreApiL = pierEnvHostEnv . multiEyreApiL instance HasPortControlApi PierEnv where portControlApiL = pierEnvHostEnv . portControlApiL instance HasPierEnv PierEnv where pierEnvL = id instance HasKingId PierEnv where kingIdL = kingEnvL . kingEnvKingId instance HasStderrLogFunc PierEnv where stderrLogFuncL = kingEnvL . stderrLogFuncL instance HasLogFunc PierEnv where logFuncL = kingEnvL . logFuncL instance HasPierPath PierEnv where pierPathL = pierEnvPierConfig . pierPathL instance HasDryRun PierEnv where dryRunL = pierEnvPierConfig . dryRunL instance HasPierConfig PierEnv where pierConfigL = pierEnvPierConfig instance HasNetworkConfig PierEnv where networkConfigL = pierEnvNetworkConfig instance HasProcId PierEnv where procIdL = kingEnvL . kingEnvProcId -- PierEnv Utils --------------------------------------------------------------- onKillPierSigL :: HasPierEnv e => Getter e (STM ()) onKillPierSigL = pierEnvL . pierEnvKillSignal . to readTMVar killPierActionL :: HasPierEnv e => Getter e (STM ()) killPierActionL = pierEnvL . pierEnvKillSignal . to (\kil -> void (tryPutTMVar kil ())) -- Running Pier Envs ----------------------------------------------------------- runPierEnv :: PierConfig -> NetworkConfig -> TMVar () -> RIO PierEnv a -> RIO HostEnv a runPierEnv pierConfig networkConfig vKill action = do host <- ask let pierEnv = PierEnv { _pierEnvHostEnv = host , _pierEnvPierConfig = pierConfig , _pierEnvNetworkConfig = networkConfig , _pierEnvKillSignal = vKill } io (runRIO pierEnv action)
urbit/urbit
pkg/hs/urbit-king/lib/Urbit/King/App.hs
Haskell
mit
8,381
{-| Module : Test.Problem Description : The Test node for the Problem module Copyright : (c) Andrew Burnett 2014-2015 Maintainer : andyburnett88@gmail.com Stability : experimental Portability : Unknown Contains the node for the tests of the Problem module and its children -} module Test.Problem ( tests ) where import qualified Test.Problem.Instances as Instances import qualified Test.Problem.Internal as Internal import qualified Test.Problem.ProblemExpr as ProblemExpr import qualified Test.Problem.Source as Source import TestUtils name :: String name = "Problem" tests :: TestTree tests = testGroup name [ Internal.tests , ProblemExpr.tests, Source.tests , Instances.tests ]
aburnett88/HSat
tests-src/Test/Problem.hs
Haskell
mit
748
{-# LANGUAGE CPP #-} module GHCJS.DOM.DedicatedWorkerGlobalScope ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.DedicatedWorkerGlobalScope #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.DedicatedWorkerGlobalScope #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/DedicatedWorkerGlobalScope.hs
Haskell
mit
391
import Test.Hspec import qualified Jenkins.TypesSpec as TypesSpec main :: IO () main = hspec TypesSpec.test
afiore/jenkins-tty.hs
test/Suite.hs
Haskell
mit
109
{-# LANGUAGE BangPatterns #-} module LMisc (zipp, zipp4, tokens, tokens', in2out, rDoubleS , findWithRemainder ,differentiateBy,findWithAdjs , takeFirst, mtone3, subs, subsN, choose, force ,ascending,nppP , allPieces, nPieces, adjustMatrix , myMin , nPieces2,nPiecesPOpt, trendLine , predict, nPiecesP , butLastElm,maintainBy,myTake,maintainBy',sumBy,similarBy , fillZeroes,fillZeroes_aux, takeFirstM, oSubs , zipp3, myMin',zipMaybe,allPositiveSlopes , findIndexesPresent, maintainByLen , findCuts,mkIntervals,getOppFuns,printElm,printElmChr,predsFromLP , manyInvNS,findGrps , lastN, mapSnd ) where --- some miscellaneous list operations import qualified Control.Parallel.Strategies as St ---(parList, rseq) import IO import Data.List (transpose, delete,findIndex,foldl',nub,maximumBy,minimumBy,find) import Data.Ord (comparing) import Data.Maybe (listToMaybe) import Control.Parallel (par, pseq) import Numeric.LinearAlgebra (fromList, toList, join, Vector, foldVector,takesV,dim,(@>),mapVector ) import Numeric.GSL.Statistics (mean,stddev) ---------------------------------------------------------------------------------------------------- --- create pairs of consecutive members of a lists ---------------------------------------------------------------------------------------------------- zipp :: [a] ->[(a,a)] zipp (x:y:xs) = (x,y):zipp (y:xs) zipp _ = [] -- unZipp :: [(a,a)] -> [a] unZipp [(a,b)] = [a,b] unZipp ((a,_) : xs) = a : unZipp xs unZipp _ = [] -- zipp3 :: [a] -> [(a,a,a)] zipp3 (a:b:c:xs) = (a,b,c): zipp3 (b:c:xs) zipp3 _ = [] -- zipp4 :: [a] -> [(a,a,a,a)] zipp4 (a:b:c:d:xs) = (a,b,c,d): zipp4 (c:d:xs) zipp4 _ = [] ------------------------------------------------------------ -- -- zipMaybe :: [a] ->[b] ->[(Maybe a, Maybe b)] zipMaybe [] [] = [] zipMaybe (a:as) [] = (Just a, Nothing) : zipMaybe as [] zipMaybe [] (b:bs) = (Nothing, Just b) : zipMaybe [] bs zipMaybe (a:as) (b:bs) = (Just a, Just b) : zipMaybe as bs ------------------------------------------------------------ --mapSnd mapSnd :: ([a],b) -> [(a,b)] mapSnd (xs,y) = St.parMap St.rseq (\a -> (a,y)) xs -- find the number of unique elements in a list num_unique [] = 0 num_unique (a:xs)| null ass = num_unique rest | otherwise = 1 + num_unique rest where (ass, rest) = span (==a) xs ---- LastN : the dual of take n lastN :: Int -> [a] -> [a] lastN n xs = drop (m-n) xs where m = length xs -- myTake - a strict version of take myTake _ [] = [] myTake 0 _ = [] myTake n (x:xs) = ys `seq` (x:ys) where ys = myTake (n-1) xs --- summing using a function sumBy :: Num a => (b -> a) -> [b] -> a sumBy f = foldl' (\b a -> b + f a) 0 --- force a list down to the last term force :: [a] -> () force xs = go xs `pseq` () where go (_:xs) = go xs go [] = 1 --- finds an element of a list and returns the element along with -- the remainder of the list findWithRemainder :: (a -> Bool) -> [a] -> (Maybe a, [a]) findWithRemainder f [] = (Nothing, []) findWithRemainder f (x:xs) | f x = (Just x , xs) | otherwise = case findWithRemainder f xs of (mf, ys) -> (mf , x : ys) --- finds an element of a list and returns the element along -- with other elemens adjacent to it findWithAdjs :: (a -> Bool) -> [a] -> ([a] , Maybe a, [a]) findWithAdjs f [] = ([] , Nothing, []) findWithAdjs f (x:xs) | f x = ([] , Just x , xs) | otherwise = case findWithAdjs f xs of (fs, mf, ys) -> (x: fs , mf , ys) -- differentiateBy f xs ys: returns all elements in ys where -- that are similar, after an application of f, to xs (in the first argument) --- along with the remaining elemets of ys (in the second argument) differentiateBy :: Eq a => (a -> a) -> [a] -> [a] -> ([a],[a]) differentiateBy f [] ys = ([],ys) differentiateBy f _ [] = ([],[]) differentiateBy f (x:xs) ys = case findWithRemainder ((== x) . f) ys of (Nothing , zs) -> differentiateBy f xs zs (Just k, zs) -> (k : ps , qs) where (ps, qs) = differentiateBy f xs zs --- --- findIndexesPresent f xs ys: finds the indexes of elements xs --- where f i is in ys findIndexesPresent :: Eq a => (b -> a) -> [b] -> [a] -> [Int] findIndexesPresent f [] _ = [] findIndexesPresent f _ [] = [] findIndexesPresent f (x:xs) ys = case findIndex (== f x) ys of Nothing -> findIndexesPresent f xs ys Just k -> k : findIndexesPresent f xs ys --} --- repeatedly preforms differentiateBy over a list of elements differentiateList :: Eq a => (a -> a) -> [[a]] -> [a] -> [[a]] differentiateList f [] _ = [] differentiateList f (xs:xss) ys | null zs = differentiateList f xss rest | otherwise = zs : differentiateList f xss rest where (zs, rest) = differentiateBy f xs ys ---------------------------------------------------------------------------------------------------- -- monotone decreasing lists ---------------------------------------------------------------------------------------------------- mtone3 :: Ord a => [a] -> [a] mtone3 (w:x:y:z:zs) | w >= x && x >= y && y >= z = y: mtone3 (z:zs) | otherwise = mtone3 (z:zs) mtone3 _ = [] -- ----------- minimum function that does not crash ------------------- myMin :: (Ord a) => [a] -> Maybe a myMin [] = Nothing myMin xs = Just (minimum xs) -- need to write this function myMin' :: (Ord a) => [(a,b)] -> (a,b) myMin' [] = error "minimum empty list" myMin' ((a,b):xs) = foldl mF (a,b) xs where mF (x,y) (p,q) = if x < p then (x,y) else (p,q) ---------------------------------------------------------------------------------------------------- -- | returns a list with the penultimate element removed along with the element -- | that was removed. Only works for list of lenght greater than 2. butLastElm :: [a] -> Maybe ([a],a) butLastElm [x,y,z] = Just ([x,z],y) butLastElm (x:xs) = case butLastElm xs of Nothing -> Nothing Just (ys,k) -> Just (x:ys, k) butLastElm _ = Nothing -- choose all sublists subs :: [a] -> [[a]] subs [] = [[]] subs (x:xs) = ys ++ map (x:) ys where ys = subs xs --- subsN _ [] = [[]] subsN n (x:xs) = [ks | ks <- map (x:) ys ++ ys , length ks == n] where ys = subsN n xs --- choose all possible sublists of xs with length less or equal to xs choose xs n = [ x | x <- subs xs , length x == n] -- nSegs :: [a] -> > [[a]] nSegs _ [] = [] nSegs 0 xs = [xs] nSegs n xs@(_:ys) | n >= length xs = [xs] | otherwise = take n xs : nSegs n ys -- determine whether two lists have the same element sameElements :: Eq a => [a] -> [a] -> Bool sameElements [] [] = True sameElements (x:xs) ys = sameElements xs (delete x ys) sameElements _ _ = False ---------------------------------------------------------------------------------------------------- -- COMPUTING THE ADJUSTED MATRIX ---------------------------------------------------------------------------------------------------- -- ordered sub lists. The ordering is subject to the aprori arrangement of the list oSubs :: [a] -> [[a]] oSubs [] = [] oSubs xs@(_:xs') = [take i xs | i <- [1..length xs]] ++ oSubs xs' -- return all possible pieces, ignoring pieces that treat individual points -- as a line segment. I may have to add the possibility to treat at least the -- final point as a piece when annalysing segments allPieces :: Eq a => [a] -> [[[a]]] allPieces xs = [ ys | let n = length xs, i <- [1.. n], ys <- allOperms_aux i n xs] where allOperms_aux _ _ [] = [] allOperms_aux n m xs | n == 1 = [[xs]] | n == 2 = [[ys,zs] | i <- [1 .. length xs], let (ys,zs) = splitAt i xs, not (null ys), length zs > 1, length ys > 1] -- ] | otherwise = [(ns:ps) | i <- [1.. m], let (ns, ms) = splitAt i xs, let mm = length ms, length ns > 1, ps <- allOperms_aux (n-1) mm ms] -- | nPieces : all possible adjacent elements from n cuts of the list, excluding empty subslists nPieces :: Eq a => Int -> [a] -> [[[a]]] nPieces n xs | n == 0 = [[xs]] | otherwise = [(ns:ps) | i <- [1.. (length xs - 1)], let (ns, ms) = splitAt i xs, not $ null ns, ps <- nPieces (n-1) ms, all (not . null) ps] --- -- | nPieces : all possible adjacent elements from n cuts of the list, excluding empty subslists nPiecesF :: (Eq a, Ord b) => ([a] -> b) -> Int -> [a] -> [[[a]]] nPiecesF f n xs | n == 0 = [[xs]] | otherwise = [ (ns:ps) | i <- [2.. 5], let (ns, ms) = splitAt i xs, not $ null ns, ps <- (nPiecesF f (n-1) ms)] -- all (not . null) ps] {-# INLINE nppP #-} ---- towards a more efficient version of the npieces function ---- to be continued nppP :: Int -> Int -> [a] -> [([[a]],[Int])] nppP 0 lim xs = [([xs],[])] nppP 1 lim xs = nppP' lim (length xs - lim + 1) xs -- nppP m lim xs = [(ns : ps, i : ks) | i <- [lim .. (length xs - lim)] , let (ns, ms) = splitAt i xs -- now recursively build-up the tail with sublists longer than lim , (ps,ks) <- nppP (m-1) lim ms , all ( < 10) (i : ks) ] {-# INLINE nppP' #-} nppP' :: Int -> Int -> [a] -> [([[a]],[Int])] nppP' _ _ [] = [] nppP' st en xs | st >= en = [] | null back = [([front], [st])] -- ] : nppP' (st + 1) en xs | otherwise = ([front,back], [st,length back]) : nppP' (st + 1) en xs where !ln = length front (front,back) = splitAt st xs ---------------------------------------------------------------------------------------------------- -- | nPieces: all possible adjacent adjacent elements from n cuts of the list built from -- | least lim elements, keeping track of the occurrence of cuts {-# INLINE nPiecesP #-} nPiecesP :: Int -> -- ^ The number of splits for the lsit Int -> -- ^ The minimum length of the shortest piece Maybe Int -> -- ^ The maximum length of the longest piece (bar the first bit) [a] -> -- ^ The list to split up [([[a]],[Int])] nPiecesP m lim mLn xs | null xs = [] | m == 0 = [([xs],[])] -- | length xs <= m = [([xs],[])] | otherwise = [(ns:ps, i : ks) | i <- [lim .. (length xs - lim)] -- get the first element, making sure it is longer than lim , let (ns, ms) = splitAt i xs -- length ns >= lim, -- now recursively build-up the tail with sublists longer than lim , (ps,ks) <- nPP (m-1) lim mLn ms , let pss = ns:ps , maybe (all ((>= lim) . length) pss) (\n -> maxLn n pss) mLn ] where nPP mn lm mlN ys = let npp = nPiecesP mn lm mlN ys in npp `pseq` npp maxLn mx = all (\xs -> let lm = length xs in (lm >= lim ) && (lm <= mx)) ---------------------------------------------------------------------------------------------------- {-# INLINE nPiecesPF #-} nPiecesPF :: (Ord a , Num a) => Int -> -- ^ The number of splits for the lsit Int -> -- ^ The minimum length of the shortest piece (a -> a) -> Maybe Int -> -- ^ The maximum length of the longest piece (bar the first bit) [a] -> -- ^ The list to split up [([[a]],[Int])] nPiecesPF m lim f mLn xs -- = maintainBy' (sumBy (sumBy f) . fst) (Just 6) . nPiecesP m lim mLn | null xs = [] | m == 0 = [([xs],[])] -- | length xs <= m = [([xs],[])] | otherwise = [(pss, i : ks) | i <- [lim .. (length xs - lim)] -- get the first element, making sure it is longer than lim , let (ns, ms) = splitAt i xs -- length ns >= lim, -- now recursively build-up the tail with sublists longer than lim , (ps,ks) <- take 2 $ nPP (m-1) lim mLn ms , let pss = (ns:ps) , maybe (all ((>= lim) . length) pss) (\n -> maxLn n pss) mLn ] where nPP mn lm mlN ys = let npp = nPiecesPF mn lm f mlN ys in npp `pseq` npp maxLn mx = all (\xs -> let lm = length xs in (lm >= lim ) && (lm <= mx)) ----------------------------------------------------------------------------------------------------} nPiecesPOpt :: Int -> -- ^ The minimum length of the shortest piece -- Int -> -- ^ The maximum length of the longest piece [a] -> -- ^ The list to split up [([[a]],[Int])] nPiecesPOpt lim xs = [(ns:ps, i : ks) | i <- [lim .. (length xs - lim)], -- get the first element, making sure it is longer than lim let (ns, ms) = splitAt i xs , length ns >= lim, -- now build-up the tail with sublists longer than lim (ps,ks) <- splits lim lim (length xs - lim) ms, all ((>= lim) . length) ps] where splits :: Int -> Int -> Int -> [a] -> [([[a]], [Int])] splits _ _ _ [] = [] splits mn m n xs | length xs <= n + m = [ ([front,back],[m])] | m >= n = splits mn mn n xs | otherwise = case splits mn (m+1) n back of [] -> [([front],[m]) ] ((ps,zs) :rest) -> (front : ps, m : zs) : rest where (front, back) = splitAt m xs --- maintain elements of a list that are valid by maintainBy' :: (Eq a , Ord b ) => (a -> b) -> Maybe Int -> [a] -> [a] maintainBy' f mb = maybe (($!) (maintainBy f)) (\n -> myTake n . maintainBy f) mb maintainBy :: (Eq a , Ord b ) => (a -> b) -> [a] -> [a] maintainBy _ [] = [] maintainBy f (x:xs) = maintainBy_aux f x [] xs where maintainBy_aux :: (Eq a , Ord b) => (a -> b) -> a -> [a] -> [a] -> [a] maintainBy_aux _ _ acc [] = acc maintainBy_aux f a acc (y:ys) | f a < f y = maintainBy_aux f a (a <:> acc) ys | otherwise = maintainBy_aux f y (y <:> acc) ys where (<:>) :: Eq c => c -> [c] -> [c] (<:>) x [] = [x] (<:>) x ys@(y:_) | x == y = ys | otherwise = x : ys --- filter out "poor values" inroder to preserve a list of length n maintainByLen :: (Eq a , Ord b) => Int -> (a -> b) -> [a] -> [a] maintainByLen n f xs | n < length xs = maintainBy' f (Just n) xs -- xs | otherwise = xs -- maintainBy' f (Just n) xs ---------------------------------------------------------------------------------------------------- -- return the first elements of a list when ther are all similiar by a given predicate similarBy :: (a -> a -> Bool) -> [a] -> Maybe a -- similarBy p [a] = Just a similarBy p [a,b] | p a b = Just a | otherwise = Nothing similarBy p (a:b:c:xs) | p a b && p b c = Just a | otherwise = similarBy p (b:c:xs) similarBy p _ = Nothing ---------------------------------------------------------------------------------------------------- -- nPieces2: Gets all possible combinations of adjacent n pieces, without single -- pieces at the end. Suitable for MML2DS nPieces2 :: Eq a => Int -> Int -> Int -> [a] -> [[[a]]] nPieces2 n m len xs | n == 0 = [[xs]] | n == 1 = [[ys,zs] | i <- [3 .. len], let (ys,zs) = splitAt i xs, -- not (null zs), length zs > 1, length zs <= m, length ys <= m] | otherwise = [(ns:ps) | i <- [3.. len], let (ns, ms) = splitAt i xs, length ms > 1, length ns <= m, -- length ms <= m, ps <- nPieces2 (n-1) m (len - i) ms] --- filling zeroes to align the pieces ------------------------------------------------------------- fillZeroes_aux :: Num a => Int -> Int -> Int -> [[a]] -> [[a]] fillZeroes_aux _ _ _ [] = [] fillZeroes_aux n m i (xs:xss) | null xss && m == 0 = [zeros (n - lxs) ++ xs] | i == 1 = inKtor : appZros : fillZeroes_aux n ml (i+1) xss | otherwise = inKtor : zerosXz : fillZeroes_aux n ml (i+1) xss where lxs = length xs ml = m + lxs zeros k = [0 | _ <- [1..k]] nmxs = n - ml appZros = (xs ++ zeros (n - lxs)) zerosXz = (zeros m ++ xs ++ zeros nmxs) inKtor = (zeros m ++ [1 | _ <- xs] ++ zeros nmxs) fillZeroes :: Num a => [[a]] -> [[a]] fillZeroes xs = fillZeroes_aux (length xs) 0 1 xs -- Finally, adjusting the matrix. This is achieved by removing the -- last indicator vector and adding it to the first indicator vector. -- This operation is only performed for lists of length greater than 2. adjustMatrix :: Num a => [[a]] -> [[a]] adjustMatrix xss = case butLastElm xss of Nothing -> xss Just ((ys:yss), zs) -> (sub ys zs) : yss where sub ps qs = zipWith (-) ps qs --- END OF ADJUSTED MATRIX DEFINITIONS --------------------------------------------------------------------------------------------------- findCuts :: Ord a => [a] -> [[a]] findCuts xs | null xs = [] | null asenBlock = [xs] | otherwise = front : findCuts rest where asenBlock = [(ps,qs) | (ps,qs) <- firstNs 1 xs, ascDes ps ] (front, rest) = last asenBlock -- ascDes xs = ascending xs || desending xs -- firstNs :: Int -> [a] -> [([a],[a])] firstNs n xs | n > length xs = [] | otherwise = (ys, zs) : firstNs (n+1) xs where (ys, zs) = splitAt n xs ---- remove increasing cuts remIncrCuts :: Bool -> [[Double]] -> [[Double]] remIncrCuts positive xs | not positive = xs | 1 >= length xs = xs | otherwise = (unZipp . map remIncrCuts_aux . zipp) xs where remIncrCuts_aux :: ([Double],[Double]) -> ([Double],[Double]) remIncrCuts_aux (xs,ys) | any null [xs,ys] = (xs,ys) | last xs < head ys = case (find (/= 0) (reverse xs)) of Nothing -> (xs, ys) Just k -> (xs , (mkAscending . map (minusUntil k)) ys) | otherwise = (xs, ys) --- remove increasing cuts minusUntil :: Double -> Double -> Double minusUntil n m -- | n == 0 = minusUntil (n + 0.5) m | m <= n = m | otherwise = minusUntil n (m - (n + 0.0001)) -- make a set of points ascending mkAscending :: [Double] -> [Double] mkAscending (a : b : xs) | a <= b = a : mkAscending ( b : xs) | otherwise = b : (b + 0.12) : mkAscending (map (+ b) xs) mkAscending xs = xs -- says if the elements of a list are in ascending ascending_aux ((a,b,c,d):xs) | a <= b && b <= c && c <= d = ascending_aux xs | otherwise = False ascending_aux _ = True -- monotone True --ascending4 = ascending_aux . zipp4 --desending4 = not . ascending4 -- all (uncurry (>)) . zipp ascending :: Ord a => [a ] -> Bool ascending = all (uncurry (<=)) . zipp -- monotone True -- desending :: Ord a => [a ] -> Bool desending = all (uncurry (>)) . zipp --desending' = all (uncurry (>=)) . zipp ------------------------------------------------------------------------------------ -- FUNCTIONS FOR GRAPHING ------------------------------------------------------------------------------------ -- mkIntervals : takes a lsit of known predictions and a list of the -- frequency of cuts and produces a lsits of predictions relating to -- each cut, along with the length of the list mkIntervals :: [a] -> [Int] -> [([a],Int)] mkIntervals [] _ = [] mkIntervals predts [] = [(predts, length predts)] mkIntervals predts (n:ns) = (front,length front): mkIntervals rest ns where (front,rest) = splitAt n predts --------------- -- just like mkIntervals but considers a minimum number of points mkIntervals1 :: [a] -> [Int] -> [[a]] mkIntervals1 [] _ = [] mkIntervals1 predts [] = [predts] mkIntervals1 predts (n:ns) = front : mkIntervals1 rest ns -- | length rest < 4 = front : [rest] -- | otherwise = where (front,rest) = splitAt n predts -- calculates that function defined over the entire range trendLine :: [Double] -> [Int] -> Double -> Double trendLine ys = getFun . mkIntervals ys where getFun xs = getFun' xs 1 f = fromIntegral getFun' [(xs,_)] k x = fun xs k x getFun' ((xs,n):rest) k x | x <= k - 0.9999999 + f n = fun xs k x | otherwise = getFun' rest (k + f n) x predict :: [Double] -> [Int] -> Double -> Double predict xs ns = predict_aux xs ns 1 where predict_aux xs [] k = fun xs k predict_aux xs (n:ns) k = let (_,rest) = splitAt n xs in predict_aux rest ns (k + f n) f = fromIntegral -- computing a linear frunction defined over a monotone list of points fun xs k x = m * x + c where m = (last xs - head xs) / (fromIntegral (length xs) - 1) c = head xs - m * k ---- list of length k with inverted predictions getOppFuns :: Double -> [Double] -> [Vector Double] getOppFuns k xs | null xs = [] | otherwise = zipWith mFl mfs (replicate (floor k) [1 .. fLen xs]) where mFl f = fromList . map f hs = head xs ms = mean (fromList xs) fLen = fromIntegral . length m = (last xs - hs) / (fLen xs - 0.5) mf n x = (fst n) * x + (snd n - fst n) mfs = map mf $ zip (map (m/) [-1 * k .. -1]) mkSlp mkSlp | m >= 0 = [ms ,ms + (1/k) .. ] | otherwise = [ms , ms - (1/k) .. ] --- given a list of predictions, check that all of it is ascending. --- if all are not, calculate the inversion of the descending slopes and --- combine them up to form a larger list manyInvNS :: Bool -> [Double] -> [[Double]] manyInvNS positive = take 1 . map toList. combWithInv positive . remIncrCuts positive . findCuts where combWithInv :: Bool -> [[Double]] -> [Vector Double] combWithInv pos [] = [] combWithInv pos (x:xs) | pos && ascending x = case combWithInv pos xs of [] -> [fromList x] xss -> [vAdd (fromList x) k | k <- xss] | (not pos) && desending x = case combWithInv pos xs of [] -> [fromList x] xss -> [vAdd (fromList x) k | k <- xss] | otherwise = case combWithInv pos xs of [] -> vss yss -> concatMap (\a -> map (flip vAdd a) vss) yss where vAdd v1 v2 = join [v1,v2] vss = getOppFuns 20 x ----------------------------------- ---returning the gradient of each new slope, which determins how steep the inversions are getOppFuns1 :: Double -> [Double] -> [(Double ,Vector Double)] getOppFuns1 k xs | null xs = [] | otherwise = [ (fst (yss !! i) , vs) | (yss,i) <- zip mprs [0,1 .. length xs - 1] , let vs = fromList $ map snd yss , let vsum = foldVector (+) 0 vs , vsum /= 0 ] where mprs :: [[(Double,Double) ]] mprs = zipWith map mfs (replicate (floor k) [1 .. fLen]) --- hs1 = head xs hs = if hs == 0 then 0.0000001 else hs1 ms = mean (fromList xs) fLen = (fromIntegral . length) xs mm = (last xs - hs) / (fLen - 0.5) mf (m,c) x = (m, m * x + c) -- mfs :: [Double -> (Double , Double)] mfs = map mf $ zip (map (mm/) [-(2 * k) .. -1]) intercept intercept | mm <= 0 = iterate ((+) (1/k)) ms | otherwise = iterate ((-) (1/k)) ms -- given a list of predictions, returns a lists where the portions of the predictions -- with negative slopes are inverted (in the sense that the least possible positive slope is -- drawn where slope is not zero) manyInvNS1 :: Bool -> [Double] -> [(Double ,[Double])] manyInvNS1 pos = map (\(a,b) -> (a,toList b)) . combWithInv pos . remIncrCuts pos . findCuts where -- combWithInv :: Bool -> [[Double]] -> [(Double , Vector Double)] combWithInv pos [] = [] combWithInv pos (x:xs) | (pos && ascending x) || ((not pos) && desending x) = case combWithInv pos xs of [] -> [ (1, fromList x)] xss -> [ (i , vAdd (fromList x) k) | (i,k) <- xss] | otherwise = case combWithInv pos xs of [] -> vss yss -> concatMap (\(j,a) -> [(j,flip vAdd a k) | (_,k) <- vss]) yss where vAdd v1 v2 = join [v1,v2] len = length x ln = if len < 20 then 15 else 20 vss_aux = getOppFuns1 (fromIntegral ln) x vss = maybe [(0,fromList x)] (:[]) (listToMaybe vss_aux) ----------------------------------------------------------------------------------------------- {-- allPositiveSlopes : takes a list of known predictions, paired with a list frequency of cuts in the predictions, and decides whether all slopes among the predictions are >= 0. The function returns True if all slopes are at least 0 and False otherwise. --} allPositiveSlopes :: [Double] -> [Int] -> Bool allPositiveSlopes predts cuts = all id slopes where slopes = [ascending points | (points, _) <- mkIntervals predts cuts] gradient xs | null xs = 0 | otherwise = m xs m xs = (last xs - head xs) / (fromIntegral (length xs) - 1) --------------------------------------------------------------------------------------------------- --- takes a list of functions, a list of split positions and a --- list of the input (i.e x) values for the functions piecewiseFun :: [(Double -> Double)] -> [Int] -> [Double] -> Double -> Double piecewiseFun xs@(f:_) [] _ k = f k piecewiseFun (f:fs) (n:ns) ys k | k < x = f k | otherwise = piecewiseFun fs ns rest k where x = (ys !! n-1) (_,!rest) = splitAt n ys --- predictions from linear parameters predsFromLP :: [Double] -> [Int] -> Double -> Double predsFromLP [c,m] [] x = c + m* x predsFromLP (c:m:xs) (y:ys) x | x <= (fromIntegral y) = c + m * x | otherwise = predsFromLP xs ys x predsFromLP _ _ x = x -- factorize then common----} -- appFunAfterFactoring :: Eq a => (a -> b) -> [[a]] -> [[b]] appFunAfterFactoring f xs = concat [appF f zs | zs <- factorHead xs] where appF :: (a -> b) -> Either (a,[[a]]) [a] -> [[b]] appF f eth = case eth of Left !ps -> multiplyThrough f ps Right !qs -> [map f qs] -- multiplyThrough :: (a -> b) -> (a, [[a]]) -> [[b]] multiplyThrough f (x, xs) = fx `seq` map ((fx:) . map f) xs where fx = f x -- factorHead :: Eq a => [[a]] -> [Either (a,[[a]]) [a]] factorHead [] = [] factorHead ((x:xs):ys) | null ys = [(Right (x:xs))] | null front = (Right (x:xs)) : factorHead back | otherwise = (Left (x,xs: map tail front)) : factorHead back where (front,back) = span ((== x) . head) ys -------------------------------------------------------------------------------------------------- findGrps :: ( Eq a) => Double -> Int -> (a -> a -> Double) -> [a] -> [[Int]] findGrps tol lim f xs -- move sg and replace it with an integer reppresenting the maximum ot group | tol <= 0.2 = groups: [ js | let lss = preCombine1 False groups, js <- [groups,lss]] | length groups < lim = [ ks | ks <- recomnFix groups] | otherwise = findGrps (tol - 0.05) lim f xs where groups = findGrps_aux 1 f tol xs -- possCuts -- groups elements together to possiblt form a group possCuts m n xs | n > (length xs - m) = [] | otherwise = (front, length front) : possCuts m (n+1) xs where front = take n xs --- add preCombine1 :: Bool -> [Int] -> [Int] preCombine1 bb (x:y:z:xs) -- | null xs = | all1 [y,z] = preCombine1 bb (x : 2 : xs) | x == 1 = preCombine1 bb ((1 + y) : z : xs) | y == 1 = preCombine1 bb ((x + 1) : z : xs) | all1 [y,z] && x == 1 = preCombine1 bb (3 : xs) | all1 [x,y] = preCombine1 bb (2 : z : xs) | otherwise = x : preCombine1 bb (y : z : xs) where all1 :: [Int] -> Bool all1 xs = all (== 1) xs preCombine1 _ xs = xs --- findGrps_aux :: ( Eq a) => Int -> (a -> a -> Double) -> Double -> [a] -> [Int] findGrps_aux _ _ _ [] = [] findGrps_aux _ _ _ [a] = [1] findGrps_aux mn f trh ks@(x:xs) = mxx : findGrps_aux mn f trh (drop mxx ks) where mxx = maybe mn (\_ -> maximum mkGrps) (listToMaybe mkGrps) mkGrps = [ n | (ys,n) <- possCuts mn mn ks , let rss = map (f x) ys , all (>= trh) rss ] --- recombinining with fixed groups recomnFix :: [Int] -> [[Int]] recomnFix cls | lcls <= 25 = combinations 0 2 cls | lcls <= 32 = combinations 7 (lim `div` 15) cls | otherwise = combinations 8 (lim `div` 10) cls where lcls = length cls combinations m k xs = [kss | i <- [m .. 19], (ks,_) <- nPiecesP i k Nothing xs , kss <- [map sum ks]] ---------------------------------------------------------------- -- returns the first elements that satisfies a given predicate takeFirst :: (a -> Bool) -> [a] -> [a] takeFirst f = myTake 1 . filter f -- alternative takeFirst returning maybe a takeFirstM :: (a -> Bool) -> [a] -> Maybe a takeFirstM f = listToMaybe . takeFirst f ----------------------------------------------------------------------- -- change the suffix of an inout file in2out :: String -> String in2out ".dat" = ".nrm" in2out (x:xs) = x : in2out xs in2out xs = xs -- tokens tokens :: String -> Char -> [String] tokens [] a = [] tokens (x:xs) a | x == a = tokens xs a | otherwise = let (front, back) = span ( /= a) xs in (x:front) : tokens back a -- make tokens of a list of a given number of elements tokeNn :: Int -> [a] -> [[a]] tokeNn _ [] = [] tokeNn n xs = y : tokeNn n ys where (y , ys) = splitAt n xs -- puts a character between every element of a list of strings rToks :: [String] -> Char -> String rToks (x:xs) a = x ++ foldr (\bs as -> (flip (:) bs a) ++ as) "" xs rToks [] _ = [] --- rDoubleS: takes a lists of numbers as strings and returns then as list of Double rDoubleS :: [String] -> [Double] rDoubleS = map rDouble rDouble :: String -> Double rDouble = read -- does the opposite to rDoubles showDoubles :: [Double] -> [String] showDoubles = map show tokens' = flip tokens -- i want the files in the .nrm file to be standardised ------------------------------------------------------------------------------------------------ printElmChr :: Show a => Char -> [a] -> String printElmChr chr = foldl' prt [] where prt b a | null b = show a | otherwise = b ++ (chr : show a) printElm :: Show a => [a] -> String printElm = printElmChr ',' --------------------------------------------------------------------- printStrings :: [String] -> Handle -> IO () printStrings [] _ = return () printStrings (x:xs) handle = do hPutStrLn handle x printStrings xs handle -- removes the brackets from a string remSqBrcs xs = filter (\a -> a /= ']' && a /= '[') xs
rawlep/EQS
sourceCode/LMisc.hs
Haskell
mit
34,881
module GameTypes.ServerGame where import Net.Communication (open, accept, receive, send) import Net.Protocol (Message(..)) import Players.RemotePlayer (RemotePlayer(..)) import Players.LocalPlayer (LocalPlayer(..)) import Network.Socket (sClose) import System.IO import TicTacToe (Token(..)) -- closes the client handle and the server socket cleanUp :: (LocalPlayer, RemotePlayer) -> IO () cleanUp (LocalPlayer _ _ hdl Nothing, _) = hClose hdl cleanUp (LocalPlayer _ _ hdl (Just sock), _) = do hClose hdl sClose sock -- initiates communication between a server and a -- client by opening a server socket, and accepting -- a connection. Then, hellos are exchanged. create :: IO (LocalPlayer, RemotePlayer) create = do putStrLn "What is your name?" xPlayer <- getLine putStrLn "Waiting for player..." sock <- open 2345 accept sock >>= onJoined xPlayer sock where onJoined ln sock (hdl, _, _) = do (Hello name) <- receive hdl Hello ln `send` hdl let lp = LocalPlayer ln X hdl (Just sock) let rm = RemotePlayer name O hdl return (lp, rm)
davidarnarsson/tictactoe
GameTypes/ServerGame.hs
Haskell
mit
1,187
module Util.PrettyPrint ( PrettyPrint(..) , Util.PrettyPrint.print , Out , pprName , nil , str , num , append , newline , indent , Util.PrettyPrint.concat , interleave ) where -- Data type for Output data Out = Str String | Newline | Indent Out | Nil | Append Out Out -- helpers nil :: Out nil = Nil str :: String -> Out str = Str num :: (Num n, Show n) => n -> Out num n = str (show n) append :: Out -> Out -> Out append = Append newline :: Out newline = Newline indent :: Out -> Out indent = Indent concat :: [Out] -> Out concat = foldr append Nil interleave :: Out -> [Out] -> Out interleave _ [] = Nil interleave _ [o] = o interleave sep (o : os) = (o `append` sep) `append` interleave sep os -- Class for PrettyPrinting with Out class PrettyPrint a where pprint :: a -> Out -- Printing Out instance Show Out where show out = flatten 0 [(out, 0)] -- Idempotent instance PrettyPrint Out where pprint a = a print :: PrettyPrint a => a -> String print = show . pprint flatten :: Int -> [(Out, Int)] -> String flatten _ [] = "" flatten _ ((Newline, indent) : out) = '\n' : spaces indent ++ flatten indent out flatten col ((Str s, _) : out) = s ++ flatten col out flatten col ((Indent o, _) : out) = flatten col ((o, col + 1) : out) flatten col ((Nil, _) : out) = flatten col out flatten col ((Append o1 o2, indent) : out) = flatten col ((o1, indent) : (o2, indent) : out) spaces :: Int -> String spaces n = replicate (n * indent_size) ' ' indent_size :: Int indent_size = 2 -- should be (re)moved pprName :: String -> String pprName = reverse . takeWhile (/= '.') . reverse
tadeuzagallo/verve-lang
src/Util/PrettyPrint.hs
Haskell
mit
1,635
----------------------------------------------------------------------------- -- -- Module : TypeNum.TypeFunctions -- Copyright : -- License : MIT -- -- Maintainer : - -- Stability : -- Portability : -- -- | -- {-# LANGUAGE PolyKinds, ConstraintKinds #-} module TypeNum.TypeFunctions ( -- * Types equality TypesEq(..) , type (==) , type (=~=), type (/~=) -- * Types ordering , TypesOrd(..) -- , Cmp , type (<), type (>), type (<=), type (>=) , Min, Max -- * Pairs deconstruction , Fst, Snd, ZipPairs -- * Maybe , FromMaybe -- * Arrow-like tuple operations , First, Second -- * Different tuple operations , Firsts, Seconds -- * Containers , TContainerElem(..) -- Contains, All, Any, Prepend, Append, Rm , type (++), ContainsEach , TContainers(..) -- , Concat, SameSize , TContainerSameSize(..) -- , Zip -- -- * Folds -- , Fold, FoldWhile -- * Functions , (:$:) , Curry, Uncurry -- * Some :$: functions , EqFunc, EqualFunc, CmpFunc , ContainsFunc ) where import Data.Type.Bool import Data.Type.Equality ----------------------------------------------------------------------------- infix 4 ~=~, =~=, /~= infix 4 <, <=, >, >= ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- class TypesEq (x :: a) (y :: b) where -- | Types equality, permitting types of different kinds. type (~=~) (x :: a) (y :: b) :: Bool type (=~=) a b = (a ~=~ b) ~ True type (/~=) a b = (a ~=~ b) ~ False ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- class (TypesEq x y) => TypesOrd (x :: a) (y :: b) where -- | Types ordering. type Cmp (x :: a) (y :: b) :: Ordering type family (x :: a) < (y :: b) where a < b = Cmp a b == LT type family (x :: a) > (y :: b) where a > b = Cmp a b == GT type family (x :: a) <= (y :: b) where a <= b = a ~=~ b || a < b type family (x :: a) >= (y :: b) where a >= b = a ~=~ b || a > b type Max (x :: a) (y :: b) = If (x >= y) x y type Min (x :: a) (y :: b) = If (x <= y) x y ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- instance TypesEq (a :: Ordering) (b :: Ordering) where type a ~=~ b = a == b ----------------------------------------------------------------------------- instance TypesEq (a :: (x,y)) (b :: (x,y)) where type a ~=~ b = (Fst a == Fst b) && (Snd a == Snd b) instance TypesOrd (a :: (x,y)) (b :: (x,y)) where type Cmp a b = Cmp2 a b ----------------------------------------------------------------------------- instance TypesEq (a :: [x]) (b :: [x]) where type a ~=~ b = All EqFunc (Zip a b) -- Lexicographical order. instance TypesOrd (h1 ': t1 :: [x]) (h2 ': t2 :: [x]) where type Cmp (h1 ': t1) (h2 ': t2) = CmpTypesOrd (Cmp h1 h2) t1 t2 type family CmpTypesOrd (o :: Ordering) (a :: [x]) (b :: [x]) :: Ordering where CmpTypesOrd EQ (h1 ': t1) (h2 ': t2) = CmpTypesOrd (Cmp h1 h2) t1 t2 CmpTypesOrd EQ '[] '[] = EQ CmpTypesOrd EQ '[] l2 = LT CmpTypesOrd EQ l1 '[] = GT CmpTypesOrd o l1 l2 = o ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- type family Fst (p :: (a, b)) :: a where Fst '(a, b) = a type family Snd (p :: (a, b)) :: b where Snd '(a, b) = b ----------------------------------------------------------------------------- type family Cmp2 (a :: (x,y)) (b :: (x,y)) :: Ordering where Cmp2 '(x1, y1) '(x2, y2) = If (x1 == x2) (Cmp y1 y2) (Cmp x1 x2) ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Apply a type-level function. Extendable. type family (:$:) (f :: a -> b -> *) (x :: a) :: b ----------------------------------------------------------------------------- type family Curry (f :: (a,b) -> c -> *) (x :: a) (y :: b) :: c where Curry f x y = f :$: '(x, y) type family Uncurry (f :: a -> (b -> c -> *) -> *) (p :: (a,b)) :: c where Uncurry f '(x,y) = (f :$: x) :$: y ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Arrow-like tuple operations type family First (p :: (a,b)) f :: (c,b) where First '(a,b) f = '(f :$: a, b) type family Second (p :: (a,b)) f :: (a,c) where Second '(a,b) f = '(a, f :$: b) ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- type family ZipPairs (p1 :: (a,a)) (p2 :: (b,b)) :: ((a,b), (a,b)) where ZipPairs '(a1, a2) '(b1, b2) = '( '(a1,b1), '(a2,b2)) type family Firsts (p :: ((a,b), (a,b))) f :: ((c,b), (c,b)) where Firsts '( '(a1,b1), '(a2,b2)) f = ZipPairs (f :$: '(a1, a2)) '(b1,b2) type family Seconds (p :: ((a,b), (a,b))) f :: ((a,c), (a,c)) where Seconds '( '(a1,b1), '(a2,b2)) f = ZipPairs '(a1,a2) (f :$: '(b1, b2)) ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- data EqFunc (arg :: (a,b)) (res :: Bool) type instance EqFunc :$: '(x,y) = x ~=~ y data EqualFunc (val :: a) (arg :: b) (res :: Bool) type instance EqualFunc x :$: y = x ~=~ y data CmpFunc (c :: (a,b)) (o :: Ordering) type instance CmpFunc :$: '(x,y) = Cmp x y ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- class TContainerElem (t :: k) (x :: e) where type Contains x t :: Bool type All (cond :: e -> Bool -> *) t :: Bool type Any (cond :: e -> Bool -> *) t :: Bool type Prepend x t :: k type Append t x :: k type Rm x t :: k class TContainers (t1 :: k) (t2 :: k) where type Concat t1 t2 :: k type SameSize t1 t2 :: Bool -- class (SameSize t1 t2 ~ True) => -- TContainerSameSize (t1 :: k) (t2 :: k) where -- type Zip t1 t2 :: k class (SameSize t1 t2 ~ True) => TContainerSameSize (t1 :: k) (t2 :: k) (res :: k') where type Zip t1 t2 :: k' data ContainsFunc (t :: k) (x :: e) (res :: Bool) type instance ContainsFunc t :$: x = Contains x t type ContainsEach (t :: k) (xs :: k) = All (ContainsFunc t) xs type xs ++ ys = Concat xs ys ----------------------------------------------------------------------------- class FoldableT (t :: k) (x :: e) (x0 :: r) where type Fold (f :: (r, e) -> r -> *) x0 t :: r type FoldWhile (cond :: e -> Bool -> *) (f :: (r, e) -> r -> *) x0 t :: r ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- instance TContainerElem ('[] :: [a]) (x :: a) where type Contains x '[] = False type All cond '[] = True type Any cond '[] = False type Prepend x '[] = '[x] type Append '[] x = '[x] type Rm x '[] = '[] instance TContainerElem ((h ': t) :: [a]) (x :: a) where type Contains x (h ': t) = h == x || Contains x t type All cond (h ': t) = (cond :$: h) && All cond t type Any cond (h ': t) = (cond :$: h) || Any cond t type Prepend x (h ': t) = x ': h ': t type Append (h ': t) x = h ': Append t x type Rm x (h ': t) = If (h == x) (Rm x t) (h ': Rm x t) ----------------------------------------------------------------------------- instance TContainers ('[] :: [a]) ('[] :: [a]) where type Concat '[] '[] = '[] type SameSize '[] '[] = True instance TContainers ('[] :: [a]) ((h ': t) :: [a]) where type Concat '[] (h ': t) = (h ': t) type SameSize '[] (h ': t) = False instance TContainers ((h ': t) :: [a]) ('[] :: [a]) where type Concat (h ': t) '[] = (h ': t) type SameSize (h ': t) '[] = False instance TContainers ((h1 ': t1) :: [a]) ((h2 ': t2) :: [a]) where type Concat (h1 ': t1) (h2 ': t2) = h1 ': Concat t1 (h2 ': t2) type SameSize (h1 ': t1) (h2 ': t2) = SameSize t1 t2 ----------------------------------------------------------------------------- instance TContainerSameSize ('[] :: [a]) ('[] :: [a]) ('[] :: [(a,a)]) where type Zip '[] '[] = '[] instance (SameSize t1 t2 ~ True) => TContainerSameSize ((h1 ': t1) :: [a]) ((h2 ': t2) :: [a]) (res :: [(a,a)]) where type Zip (h1 ': t1) (h2 ': t2) = '(h1, h2) ': Zip t1 t2 ----------------------------------------------------------------------------- instance FoldableT ('[] :: [a]) (x :: a) x0 where type Fold f x0 '[] = x0 type FoldWhile cond f x0 '[] = x0 instance FoldableT ((h ': t) :: [a]) (x :: a) x0 where type Fold f x0 (x ': xs) = Fold f (f :$: '(x0, x)) xs type FoldWhile cond f x0 (x ': xs) = If (cond :$: x) (FoldWhile cond f (f :$: '(x0, x)) xs) x0 ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- type family FromMaybe (mb :: Maybe b) f (x0 :: a) :: a where FromMaybe (Just x) f x0 = f :$: x FromMaybe Nothing f x0 = x0 ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Tests data A = A' data B = B' data C = C' data ACFunc a c type instance ACFunc :$: A' = C' type X = First '(A', B') ACFunc data ACFunc2 a c type instance ACFunc2 :$: '(A', A') = '(C', C') type Y = Firsts '( '(A',B'), '(A',B')) ACFunc2
fehu/TypeNumerics
src/TypeNum/TypeFunctions.hs
Haskell
mit
9,940
import Data.List (maximumBy) import MyLib (fact,numOfDgt) main = print $ answer 1000 answer n = sndmax (cycs n) -- sndmax [(2,0),(0,5),(3,1)]==(0,5) -- sndmax [(2,0),(0,2),(3,3)]==(3,3) sndmax :: Ord a => [(b,a)] -> (b,a) sndmax = maximumBy (\(x,y) (z,w)->compare y w) -- cycs 3 == [] cycs :: Integral a => a -> [(a,a)] cycs n = zip [1..n] [cyc i | i<-[1..n]] -- trim 6==3, trim 70=7 trim :: Integral a => a -> a trim n = (product.drop25.fact) n -- drop25 [2,2,3,3,5,5,5,7] == [3,3,7] drop25 :: Integral a => [a] -> [a] drop25 [] = [] drop25 (x:xs) = if x==2 || x==5 then drop25 xs else x:drop25 xs -- cyc 10 == 0, cyc 3 == 1, cyc 7 == 6 cyc :: Integral a => a->a cyc n | trim n == 1 = 0 | otherwise = helper 1 where helper i | isCyc n i = i | otherwise = helper (i+1) -- isCyc 3 1 == True, isCyc 7 6 == True isCyc :: Integral a => a -> a -> Bool isCyc n d= f==g where f = sub (trim n) (d+offset) g = sub (trim n) (d*2+offset) `mod` (10^d) offset = numOfDgt (trim n) - 1 -- sub 6 2 == 16, sub 6 5 == 16666 sub :: Integral a => a -> a -> a sub n i = numer `div` demin where numer = 10^(fromIntegral i) demin = fromIntegral n
yuto-matsum/contest-util-hs
src/Euler/026.hs
Haskell
mit
1,181
module GHCJS.DOM.RTCIceCandidateEvent ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/RTCIceCandidateEvent.hs
Haskell
mit
50
---------------------------------------------------------------------------- ---- | ---- Module: ETL ---- Description: Transform scrabble scores from [(score: [letter])] map to ---- [(letter:score)] map ---- Copyright: (c) 2015 Alex Dzyoba <alex@dzyoba.com> ---- License: MIT ---------------------------------------------------------------------------- module ETL (transform) where import qualified Data.Map as M import qualified Data.Text as T type OldScores = M.Map Int [String] type NewScores = M.Map String Int -- | Transform old scores to the new one ---- We iterate over key-value pairs and fold them into empty map of new scores transform :: OldScores -> NewScores transform old = M.foldWithKey transformEntry M.empty old -- | Transform single entry of old scores ---- This iterates over letters and fold them into newScores transformEntry :: Int -> [String] -> NewScores -> NewScores transformEntry score letters newScores = foldr (updateWithScore score) newScores letters -- | Insert single letter with score into map of new scores. ---- Letter is converted to lowercase updateWithScore :: Int -> String -> NewScores -> NewScores updateWithScore score letter newScores = M.insert (toLower letter) score newScores -- | Little helper to convert string to lowercase with help of Data.Text toLower :: String -> String toLower = T.unpack . T.toLower . T.pack
dzeban/haskell-exercism
etl/ETL.hs
Haskell
mit
1,388
import Data.ByteString.Char8 (pack) import Crypto.Hash main = do let input = "vkjiggvb" result = compute input print result type Coord = (Int, Int) type Dir = Char type State = (Coord, [Dir], String) bounds :: Int bounds = 3 start :: Coord start = (0,0) initState :: String -> State initState input = (start, [], input) compute :: String -> Int compute input = length $ search [initState input] [] isGoal :: State -> Bool isGoal (coord, _, _) = coord == (bounds, bounds) nextStates :: State -> [State] nextStates s@(coord, dirs, input) = up ++ down ++ left ++ right where h = take 4 $ getHash (input ++ dirs) up = if open (h !! 0) then moveState 'U' s else [] down = if open (h !! 1) then moveState 'D' s else [] left = if open (h !! 2) then moveState 'L' s else [] right = if open (h !! 3) then moveState 'R' s else [] open :: Char -> Bool open c = c `elem` "bcdef" moveState :: Char -> State -> [State] moveState 'U' ((x, y), dirs, input) | y == 0 = [] | otherwise = [((x, y - 1), dirs ++ ['U'], input)] moveState 'D' ((x, y), dirs, input) | y == bounds = [] | otherwise = [((x, y + 1), dirs ++ ['D'], input)] moveState 'L' ((x, y), dirs, input) | x == 0 = [] | otherwise = [((x - 1, y), dirs ++ ['L'], input)] moveState 'R' ((x, y), dirs, input) | x == bounds = [] | otherwise = [((x + 1, y), dirs ++ ['R'], input)] -- Breadth-first search search :: [State] -> [Dir] -> [Dir] search [] dirs = dirs search (current : rest) dirs | isGoal current = let (_, path, _) = current in search rest path | otherwise = search (rest ++ (nextStates current)) dirs getHash :: String -> String getHash input = show (hash $ pack input :: Digest MD5)
aBhallo/AoC2016
Day 17/day17part2.hs
Haskell
mit
1,805
module Solidran.Lexf.DetailSpec (spec) where import Test.Hspec import Solidran.Lexf.Detail spec :: Spec spec = do describe "Solidran.Lexf.Detail" $ do describe "getAlphabetStrings" $ do it "should return an empty list on empty alphabet" $ do getAlphabetStrings 2 [] `shouldBe` [] it "should return a single string on 0-length strings" $ do getAlphabetStrings 0 "AB" `shouldBe` [""] it "should work for 1-length strings" $ do getAlphabetStrings 1 "TAGC" `shouldBe` ["T", "A", "G", "C"] it "should work for 1-symbol alphabets" $ do getAlphabetStrings 3 "A" `shouldBe` ["AAA"] it "should work on the given example" $ do getAlphabetStrings 2 "TAGC" `shouldBe` [ "TT", "TA", "TG", "TC" , "AT", "AA", "AG", "AC" , "GT", "GA", "GG", "GC" , "CT", "CA", "CG", "CC" ]
Jefffrey/Solidran
test/Solidran/Lexf/DetailSpec.hs
Haskell
mit
1,105
import State (Token(..), State(..), TransitionFunction(..), Transition(..), TransitionMap) import qualified NDFSM (NDFSM(..)) import NDFSM (NDFSM, NDState, exploreTransitions, flatten, tabulate, acceptsState, eps) import qualified FSM (FSM(..)) import FSM (FSM, mapTransitions, mapToFunc, accepts) import qualified Data.Set as Set (fromList, singleton, empty) import Data.Bimap (elems, keys, (!)) import PrettyPrinter (ndfsm_to_fsm_string) import Control.Applicative ((<$>)) import ExampleNDFSMs (abba_ndfsm) -- Transforms an NDFSM into an FSM ndfsm_to_fsm :: NDFSM -> FSM ndfsm_to_fsm ndfsm = FSM.FSM {FSM.states = Set.fromList $ elems correspondence, FSM.state0 = correspondence ! (eps ndfsm $ NDFSM.state0 ndfsm), FSM.accepting = Set.fromList $ [correspondence ! ndstate | ndstate <- keys correspondence, ndfsm `acceptsState` ndstate], FSM.transitionFunction = mapToFunc transitionMap, FSM.alphabet = NDFSM.alphabet ndfsm } where nd_transitions = exploreTransitions ndfsm d_transitions = flatten nd_transitions -- Bimap correspondence between ND states and D states correspondence = tabulate nd_transitions transitionMap = mapTransitions d_transitions my_ndfsm = abba_ndfsm my_fsm = ndfsm_to_fsm my_ndfsm strings = ["abab", "babb", "abb", "babba", "abbaabba", "abbabbbb"] main = do putStrLn "generated FSM:" putStrLn $ ndfsm_to_fsm_string my_ndfsm putStrLn $ "matching " ++ show strings let matches = (my_fsm `accepts`) <$> map Token <$> strings putStrLn $ "matches: " ++ show matches
wyager/NDFSMtoFSM
StateMachine.hs
Haskell
mit
1,601
{-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MagicHash #-} module Main (main) where import Test.HUnit hiding (Test) import Test.QuickCheck hiding ((.&.)) import Test.Framework ( Test, defaultMain ) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.Framework.Providers.HUnit import Data.Word.N import Data.Word.N.Util import Data.Bits import Data.Binary.Get import Data.Binary.Put import qualified Data.ByteString.Lazy as LZ import GHC.TypeLits import Data.Word -- Most of these properties come from the package 'largeword' (on hackage). -- This is because that package and this one expose pretty much the same api. encode' :: (8 :|: n) => W n -> LZ.ByteString encode' = disassembleR (runPut . putWord8 . (fromIntegral :: W 8 -> Word8)) decode' :: (8 :|: n) => LZ.ByteString -> W n decode' = runGet (assembleR (fmap (fromIntegral :: Word8 -> W 8) getWord8)) instance (8 :|: n) => Arbitrary (W n) where arbitrary = assembleL $ fmap (fromIntegral :: (Word8 -> W 8)) arbitrary pShiftRightShiftLeft :: W 128 -> Bool pShiftRightShiftLeft x = shiftR (shiftL x 1) 1 == x .&. (fromInteger ((2^127) - 1)) u1 :: Assertion u1 = shiftR (18446744073709551616 :: W 128) 64 @?= 1 pQuotRem :: W 256 -> Bool pQuotRem x = rx == fromInteger ry where (_qx, rx) = quotRem x 16 (_qy, ry) = quotRem ((fromIntegral x) :: Integer) 16 encodeDecode :: (8 :|: n) => W n -> Bool encodeDecode word = decode' encoded == word where encoded = encode' word {-# NOINLINE encoded #-} correctEncoding :: Assertion correctEncoding = (decode' . LZ.pack) [0,0,0,0,0,0,0,0,50,89,125,125,237,119,73,240 ,217,12,178,101,235,8,44,221,50,122,244,125,115,181,239,78] @?= (1234567891234567891234567812345678123456781234567812345678 :: W 256) pRotateLeftRight :: W 256 -> Bool pRotateLeftRight x = rotate (rotate x 8) (-8) == x pRepeatedShift :: Int -> Property pRepeatedShift n = (n >= 0) && (n <= 1024) ==> (((iterate (`shift` 8) (1::W 192))!!n) == shift (1::W 192) (n*8)) pRepeatedShift' :: Int -> Property pRepeatedShift' n = (n >= 0) && (n <= 1024) ==> (((iterate (`shift` 8) a)!!n) == shift a (n*8)) where a :: W 192 a = 0x0123456789ABCDEFFEDCBA98765432100011223344556677 pRepeatedShift160 :: Int -> Property pRepeatedShift160 n = (n >= 0) && (n <= 1024) ==> (((iterate (`shift` 8) (1::W 160))!!n) == shift (1::W 160) (n*8)) u2 :: Assertion u2 = (2 :: W (256 + 128)) ^ 254 @?= (fromInteger (2 :: Integer) ^ 254) u3 :: Assertion u3 = rotate (rotate ((2^255) :: W 256) (1)) (-1) @?= ((2^255) :: W 256) u4 :: Assertion u4 = shift (0x0123456789ABCDEFFEDCBA98765432100011223344556677 :: W 192) 80 @?= (0xBA9876543210001122334455667700000000000000000000 :: W 192) u5 :: Assertion u5 = shift (0x112233445566778899AABBCC :: W 96) 40 @?= (0x66778899AABBCC0000000000 :: W 96) u6 :: Assertion u6 = rotate ((2^95) :: W 96) (1) @?= 1 tests :: [Test] tests = [ testProperty "largeword shift left then right" pShiftRightShiftLeft , testProperty "largeword quotRem by 16" pQuotRem , testProperty "largeword rotate left then right" pRotateLeftRight , testProperty "largeword repeated shift vs single shift" pRepeatedShift , testProperty "largeword repeated shift vs single shift" pRepeatedShift' , testProperty "largeword repeated shift vs single shift" pRepeatedShift160 , testCase "largeword shift 2^64 by 2^64" u1 , testCase "largeword exponentiation 2^254" u2 , testCase "largeword rotation by 1" u3 , testCase "largeword shift by 80" u4 , testCase "largeword shift by 40" u5 , testCase "largeword rotate by 1" u6 , testCase "big-endian encoding" correctEncoding , testProperty "Word96 encode/decode loop" (encodeDecode::W 96 -> Bool) , testProperty "Word128 encode/decode loop" (encodeDecode::W 128 -> Bool) , testProperty "Word160 encode/decode loop" (encodeDecode::W 160 -> Bool) , testProperty "Word192 encode/decode loop" (encodeDecode::W 192 -> Bool) , testProperty "Word224 encode/decode loop" (encodeDecode::W 224 -> Bool) , testProperty "Word256 encode/decode loop" (encodeDecode::W 256 -> Bool) ] main :: IO () main = defaultMain tests
nickspinale/bigword
tests/Properties.hs
Haskell
mit
5,100
{-| Module : DataAssociation.Abstract Description : Rules mining abstractions. License : MIT Stability : development Rules mining abstractions. -} module DataAssociation.Abstract ( LargeItemsetsExtractor(..) , AssociationRulesGenerator(..) ) where import DataAssociation.Definitions import Data.Map (Map) -- | An abstraction for extracting __Large__ 'Itemset's. class (Itemset set it) => LargeItemsetsExtractor set it where findLargeItemsets :: MinSupport -- ^ minimal support to consider an itemset __large__ -> [set it] -- ^ input 'Itemset's -> Map (set it) Float -- ^ __large__ itemsets with the corresponding support -- | An abstraction for generating the association rules from the __large__ 'Itemset's. class (Itemset set it) => AssociationRulesGenerator set it where generateAssociationRules :: MinConfidence -- ^ minimal confidence for accepting a rule -> [set it] -- ^ original full list of 'Itemset's -> Map (set it) Float -- ^ __large__ 'Itemset's with the corresponding support -> [AssocRule set it] -- ^ association rules
fehu/min-dat--a-priori
core/src/DataAssociation/Abstract.hs
Haskell
mit
1,277
{-# OPTIONS_GHC -Wall #-} -- {-# LANGUAGE DatatypeContexts #-} module ApplicativeFunctors where -- import Prelude hiding (Maybe) -- import Data.Maybe hiding (Maybe) import Control.Applicative type Name = String data Employee = Employee { name :: Name , phone :: String } deriving (Show) -- data Maybe a = Nothing -- | Just a -- instance Applicative Maybe where -- pure = Just -- Nothing <*> _ = Nothing -- _ <*> Nothing = Nothing -- Just f <*> Just x = Just (f x) mName, mName' :: Maybe Name mName = Nothing mName' = Just "Brent" mPhone, mPhone' :: Maybe String mPhone = Nothing mPhone' = Just "555-1234" ex01, ex02, ex03, ex04 :: Maybe Employee ex01 = Employee <$> mName <*> mPhone ex02 = Employee <$> mName <*> mPhone' ex03 = Employee <$> mName' <*> mPhone ex04 = Employee <$> mName' <*> mPhone'
harrisi/on-being-better
list-expansion/Haskell/Learning/ApplicativeFunctors.hs
Haskell
cc0-1.0
873
-- http://www.codewars.com/kata/52b757663a95b11b3d00062d module WeIrDStRiNgCaSe where import Data.Char import Data.List.Split toWeirdCase :: String -> String toWeirdCase = unwords . map weirdise . words where weirdise = concatMap f . chunksOf 2 f (x:xs) = toUpper x : map toLower xs
Bodigrim/katas
src/haskell/6-WeIrD-StRiNg-CaSe.hs
Haskell
bsd-2-clause
288
-- | Command line options. module Options ( -- * Options type Options(..) -- * Options parsing , options ) where import Control.Applicative import Options.Applicative -- | Data type for command options. data Options = Options { inputFile :: FilePath -- ^ File to be compiled. , outputFile :: Maybe FilePath -- ^ Where to put the resulting C++ code. , addRuntime :: Bool -- ^ Whether to add the C++ runtime -- directly. , includeDir :: Maybe FilePath -- ^ Location of the C++ runtime. , useGuards :: Bool -- ^ Whether to use @#include@ guards. } deriving (Eq, Show) -- | The actual command line parser. All options are aggregated into -- a single value of type 'Options'. options :: ParserInfo Options options = info (helper <*> opts) ( fullDesc <> progDesc "Compile source code in INPUT into C++ template metaprogram." ) where opts = Options <$> argument str ( metavar "INPUT" <> help "Location of the source code" ) <*> (optional . strOption) ( long "output" <> short 'o' <> metavar "OUTPUT" <> help "Location of the compiled code" ) <*> switch ( long "addruntime" <> short 'a' <> help "Whether to directly include the runtime" ) <*> (optional . strOption) ( long "includedir" <> short 'i' <> metavar "DIR" <> help "Location of the C++ \"runtime\"" ) <*> (fmap not . switch) ( long "noguards" <> short 'n' <> help "Do not add #include guards" )
vituscze/norri
src/Options.hs
Haskell
bsd-3-clause
1,784
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} module Control.CP.FD.OvertonFD.Sugar ( ) where import Data.Set(Set) import qualified Data.Set as Set import Control.CP.Debug import Control.Mixin.Mixin import Control.CP.Solver import Control.CP.FD.FD import Control.CP.FD.SimpleFD import Data.Expr.Data import Data.Expr.Sugar -- import Control.CP.FD.Expr.Util import Control.CP.FD.Model import Control.CP.FD.Graph import Control.CP.FD.OvertonFD.OvertonFD newVars :: Term s t => Int -> s [t] newVars 0 = return [] newVars n = do l <- newVars $ n-1 n <- newvar return $ n:l instance FDSolver OvertonFD where type FDIntTerm OvertonFD = FDVar type FDBoolTerm OvertonFD = FDVar type FDIntSpec OvertonFD = FDVar type FDBoolSpec OvertonFD = FDVar type FDColSpec OvertonFD = [FDVar] type FDIntSpecType OvertonFD = () type FDBoolSpecType OvertonFD = () type FDColSpecType OvertonFD = () fdIntSpec_const (Const i) = ((),do v <- newvar add $ OHasValue v $ fromInteger i return v) fdIntSpec_term i = ((),return i) fdBoolSpec_const (BoolConst i) = ((),do v <- newvar add $ OHasValue v $ if i then 1 else 0 return v) fdBoolSpec_term i = ((),return i) fdColSpec_list l = ((),return l) fdColSpec_size (Const s) = ((),newVars $ fromInteger s) fdColSpec_const l = ((),error "constant collections not yet supported by overton interface") fdColInspect = return fdSpecify = specify <@> simple_fdSpecify fdProcess = process <@> simple_fdProcess fdEqualInt v1 v2 = addFD $ OSame v1 v2 fdEqualBool v1 v2 = addFD $ OSame v1 v2 fdEqualCol v1 v2 = do if length v1 /= length v2 then setFailed else sequence_ $ zipWith (\a b -> addFD $ OSame a b) v1 v2 fdIntVarSpec = return . Just fdBoolVarSpec = return . Just fdSplitIntDomain b = do d <- fd_domain b return $ (map (b `OHasValue`) d, True) fdSplitBoolDomain b = do d <- fd_domain b return $ (map (b `OHasValue`) $ filter (\x -> x==0 || x==1) d, True) -- processBinary :: (EGVarId,EGVarId,EGVarId) -> (FDVar -> FDVar -> FDVar -> OConstraint) -> FDInstance OvertonFD () processBinary (v1,v2,va) f = addFD $ f (getDefIntSpec v1) (getDefIntSpec v2) (getDefIntSpec va) -- processUnary :: (EGVarId,EGVarId) -> (FDVar -> FDVar -> OConstraint) -> FDInstance OvertonFD () processUnary (v1,va) f = addFD $ f (getDefIntSpec v1) (getDefIntSpec va) specify :: Mixin (SpecFn OvertonFD) specify s t edge = case (debug ("overton-specify("++(show edge)++")") edge) of EGEdge { egeCons = EGChannel, egeLinks = EGTypeData { intData=[i], boolData=[b] } } -> ([(1000,b,True,do s <- getIntSpec i case s of Just ss -> return $ SpecResSpec ((),return (ss,Nothing)) _ -> return SpecResNone )],[(1000,i,True,do s <- getBoolSpec b case s of Just ss -> return $ SpecResSpec ((),return (ss,Nothing)) _ -> return SpecResNone )],[]) _ -> s edge -- process :: Mixin (EGEdge -> FDInstance OvertonFD ()) process s t con info = case (con,info) of (EGIntValue c, ([],[a],[])) -> case c of Const v -> addFD $ OHasValue (getDefIntSpec a) (fromInteger v) _ -> error "Overton solver does not support parametrized values" (EGPlus, ([],[a,b,c],[])) -> processBinary (b,c,a) OAdd (EGMinus, ([],[a,b,c],[])) -> processBinary (a,c,b) OAdd (EGMult, ([],[a,b,c],[])) -> processBinary (b,c,a) OMult (EGAbs, ([],[a,b],[])) -> processUnary (b,a) OAbs (EGDiff, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ ODiff (getDefIntSpec a) (getDefIntSpec b) (EGLess True, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OLess (getDefIntSpec a) (getDefIntSpec b) (EGLess False, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OLessEq (getDefIntSpec a) (getDefIntSpec b) (EGEqual, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OSame (getDefIntSpec a) (getDefIntSpec b) _ -> s con info
neothemachine/monadiccp
src/Control/CP/FD/OvertonFD/Sugar.hs
Haskell
bsd-3-clause
4,046
module Tests.WebTest (tests) where import Test.HUnit import qualified Data.DataHandler import qualified Service.ServiceHandler import qualified Configuration.Util import qualified Service.Users import qualified Web.WebHandler import qualified Web.WebHelper import Control.Monad.Trans.Resource import Data.ByteString.Lazy.UTF8 import Blaze.ByteString.Builder import Data.Conduit import Network.Wai tests = TestList [ TestLabel "web to service to database test" $ TestCase $ do Just configuration <- Configuration.Util.readConfiguration "Configuration.yaml" configurationTVar <- Data.DataHandler.setupDataMonad configuration serviceConfiguration <- Service.ServiceHandler.setupServiceMonad configuration configurationTVar webConfiguration <- Web.WebHandler.setupHandlerMonad configuration serviceConfiguration let handler = do Web.WebHandler.renderView $ Web.WebHelper.toBuilder ["One","Two"] ResponseBuilder _ _ returnValue <- runResourceT $ Web.WebHandler.handleMonadWithConfiguration webConfiguration handler assertEqual "Return value" (toLazyByteString returnValue) (fromString "OneTwo") ]
stevechy/HaskellCakeStore
Tests/WebTest.hs
Haskell
bsd-3-clause
1,143
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This provides an abstraction which deals with configuring and running -- programs. A 'Program' is a static notion of a known program. A -- 'ConfiguredProgram' is a 'Program' that has been found on the current -- machine and is ready to be run (possibly with some user-supplied default -- args). Configuring a program involves finding its location and if necessary -- finding its version. There is also a 'ProgramConfiguration' type which holds -- configured and not-yet configured programs. It is the parameter to lots of -- actions elsewhere in Cabal that need to look up and run programs. If we had -- a Cabal monad, the 'ProgramConfiguration' would probably be a reader or -- state component of it. -- -- The module also defines all the known built-in 'Program's and the -- 'defaultProgramConfiguration' which contains them all. -- -- One nice thing about using it is that any program that is -- registered with Cabal will get some \"configure\" and \".cabal\" -- helpers like --with-foo-args --foo-path= and extra-foo-args. -- -- There's also good default behavior for trying to find \"foo\" in -- PATH, being able to override its location, etc. -- -- There's also a hook for adding programs in a Setup.lhs script. See -- hookedPrograms in 'Distribution.Simple.UserHooks'. This gives a -- hook user the ability to get the above flags and such so that they -- don't have to write all the PATH logic inside Setup.lhs. module Distribution.Simple.Program ( -- * Program and functions for constructing them Program(..) , simpleProgram , findProgramLocation , findProgramVersion -- * Configured program and related functions , ConfiguredProgram(..) , programPath , ProgArg , ProgramLocation(..) , runProgram , getProgramOutput -- * Program invocations , ProgramInvocation(..) , emptyProgramInvocation , simpleProgramInvocation , programInvocation , runProgramInvocation , getProgramInvocationOutput -- * The collection of unconfigured and configured progams , builtinPrograms -- * The collection of configured programs we can run , ProgramConfiguration , emptyProgramConfiguration , defaultProgramConfiguration , restoreProgramConfiguration , addKnownProgram , addKnownPrograms , lookupKnownProgram , knownPrograms , userSpecifyPath , userSpecifyPaths , userMaybeSpecifyPath , userSpecifyArgs , userSpecifyArgss , userSpecifiedArgs , lookupProgram , updateProgram , configureProgram , configureAllKnownPrograms , reconfigurePrograms , requireProgram , requireProgramVersion , runDbProgram , getDbProgramOutput -- * Programs that Cabal knows about , ghcProgram , ghcPkgProgram , gccProgram , ranlibProgram , arProgram , stripProgram , happyProgram , alexProgram , hsc2hsProgram , c2hsProgram , cpphsProgram , hscolourProgram , haddockProgram , greencardProgram , ldProgram , tarProgram , touchProgram , ibtoolProgram , cppProgram , pkgConfigProgram , hpcProgram -- * deprecated , rawSystemProgram , rawSystemProgramStdout , rawSystemProgramConf , rawSystemProgramStdoutConf , findProgramOnPath ) where import Distribution.Simple.Program.Types import Distribution.Simple.Program.Run import Distribution.Simple.Program.Db import Distribution.Simple.Program.Builtin import Distribution.Simple.Utils ( die, findProgramLocation, findProgramVersion ) import Distribution.Verbosity ( Verbosity ) -- | Runs the given configured program. -- runProgram :: Verbosity -- ^Verbosity -> ConfiguredProgram -- ^The program to run -> [ProgArg] -- ^Any /extra/ arguments to add -> IO () runProgram verbosity prog args = runProgramInvocation verbosity (programInvocation prog args) -- | Runs the given configured program and gets the output. -- getProgramOutput :: Verbosity -- ^Verbosity -> ConfiguredProgram -- ^The program to run -> [ProgArg] -- ^Any /extra/ arguments to add -> IO String getProgramOutput verbosity prog args = getProgramInvocationOutput verbosity (programInvocation prog args) -- | Looks up the given program in the program database and runs it. -- runDbProgram :: Verbosity -- ^verbosity -> Program -- ^The program to run -> ProgramDb -- ^look up the program here -> [ProgArg] -- ^Any /extra/ arguments to add -> IO () runDbProgram verbosity prog programDb args = case lookupProgram prog programDb of Nothing -> die notFound Just configuredProg -> runProgram verbosity configuredProg args where notFound = "The program " ++ programName prog ++ " is required but it could not be found" -- | Looks up the given program in the program database and runs it. -- getDbProgramOutput :: Verbosity -- ^verbosity -> Program -- ^The program to run -> ProgramDb -- ^look up the program here -> [ProgArg] -- ^Any /extra/ arguments to add -> IO String getDbProgramOutput verbosity prog programDb args = case lookupProgram prog programDb of Nothing -> die notFound Just configuredProg -> getProgramOutput verbosity configuredProg args where notFound = "The program " ++ programName prog ++ " is required but it could not be found" --------------------- -- Deprecated aliases -- rawSystemProgram :: Verbosity -> ConfiguredProgram -> [ProgArg] -> IO () rawSystemProgram = runProgram rawSystemProgramStdout :: Verbosity -> ConfiguredProgram -> [ProgArg] -> IO String rawSystemProgramStdout = getProgramOutput rawSystemProgramConf :: Verbosity -> Program -> ProgramConfiguration -> [ProgArg] -> IO () rawSystemProgramConf = runDbProgram rawSystemProgramStdoutConf :: Verbosity -> Program -> ProgramConfiguration -> [ProgArg] -> IO String rawSystemProgramStdoutConf = getDbProgramOutput type ProgramConfiguration = ProgramDb emptyProgramConfiguration, defaultProgramConfiguration :: ProgramConfiguration emptyProgramConfiguration = emptyProgramDb defaultProgramConfiguration = defaultProgramDb restoreProgramConfiguration :: [Program] -> ProgramConfiguration -> ProgramConfiguration restoreProgramConfiguration = restoreProgramDb {-# DEPRECATED findProgramOnPath "use findProgramLocation instead" #-} findProgramOnPath :: String -> Verbosity -> IO (Maybe FilePath) findProgramOnPath = flip findProgramLocation
IreneKnapp/Faction
libfaction/Distribution/Simple/Program.hs
Haskell
bsd-3-clause
7,075
module PolyGraph.ReadOnly.DiGraph.Properties where import PolyGraph.ReadOnly (GMorphism(..), isValidGraphDataSet) import PolyGraph.ReadOnly.DiGraph (DiGraph, DiEdgeSemantics(..)) import PolyGraph.Common (OPair(..), PairLike(toPair)) import qualified Data.Maybe as M import qualified Data.Foldable as F isValidDiGraph :: forall g v e t . DiGraph g v e t => g -> Bool isValidDiGraph = isValidGraphDataSet (toPair . resolveDiEdge) -- | to be valid eTrans and resolveEdge needs to commute with the vTrans ignoring the pair order isValidMorphism :: forall v0 e0 v1 e1 . (Eq v0, Eq v1, DiEdgeSemantics e0 v0, DiEdgeSemantics e1 v1) => [e0] -> GMorphism v0 e0 v1 e1 -> Bool isValidMorphism es m = M.isNothing $ F.find (isValidMorphismSingleEdge m) es -- | NOTE UOPair == is diffrent from OPair == -- forcing different implementation for EdgeSemantics and DiEdgeSemantics isValidMorphismSingleEdge :: forall v0 e0 v1 e1 . (Eq v0, Eq v1, DiEdgeSemantics e0 v0, DiEdgeSemantics e1 v1) => GMorphism v0 e0 v1 e1 -> e0 -> Bool isValidMorphismSingleEdge m e0 = let OPair(v0a, v0b) = resolveDiEdge e0 e1 = eTrans m e0 in OPair(vTrans m v0a, vTrans m v0b) == resolveDiEdge e1
rpeszek/GraphPlay
src/PolyGraph/ReadOnly/DiGraph/Properties.hs
Haskell
bsd-3-clause
1,308
module WorkerClient where import Control.Monad import qualified Data.Aeson as A import Data.ByteString.Lazy.Char8 import Codec.Picture import qualified Network.WebSockets as WS import qualified Model as Model import Job import Message -- import WebSocketServer import Options.Applicative -------------------------------------------------------------------- -- Entry point for CBaaS worker nodes runWorker :: (Model.FromVal a, Model.ToVal b) => (a -> IO b) -> IO () runWorker f = WS.runClient "localhost" 9160 "/worker?name=test&function=size" $ \conn -> forever $ do msg <- WS.receive conn let t = case msg of WS.DataMessage (WS.Text x) -> Just x WS.DataMessage (WS.Binary y) -> Just y _ -> Nothing case A.decode =<< t of Just (JobRequested (i, j)) -> do print "Good decode of job request" -- print (Model.fromVal $ _jArg j) print "About to send to worker" r <- f (Model.fromVal $ _jArg j) print "Result: " print (Model.toVal r) WS.sendTextData conn (A.encode $ WorkerFinished (i, (JobResult (Model.toVal r) i))) Just x -> print $ "Good decode for unexpected message: " ++ show x Nothing -> print $ fmap (("Bad decode of " ++) . unpack ) t -- x -> print $ "Got non-text message: " ++ show x
CBMM/CBaaS
cbaas-server/src/WorkerClient.hs
Haskell
bsd-3-clause
1,443
{-# language TemplateHaskell #-} module Phil.Core.Kinds.KindError where import Control.Lens import Data.Text (unpack) import Text.PrettyPrint.ANSI.Leijen hiding ((<$>)) import Phil.Core.AST.Identifier import Phil.Core.Kinds.Kind import Phil.ErrorMsg import Phil.Typecheck.Unification data KindError = KVarNotDefined Ident | KCtorNotDefined Ctor | KUnificationError (UnificationError Kind) deriving (Eq, Show) makeClassyPrisms ''KindError -- kindErrorMsg :: AsKindError e => e -> Maybe Doc -- kindErrorMsg = previews _KindError (errorMsg "Kind error" . msgBody) kindErrorMsg = errorMsg "Kind error" . msgBody where msgBody (KVarNotDefined name) = hsep $ text <$> [ "Variable" , unpack $ getIdent name , "not in scope" ] msgBody (KCtorNotDefined name) = hsep $ text <$> [ "Type constructor" , unpack $ getCtor name , "not in scope" ] msgBody (KUnificationError (CannotUnify k k')) = vcat [ hsep [text "Cannot unify", renderKind k] , text "with" , hsep [renderKind k'] ] msgBody (KUnificationError (Occurs var k)) = hsep [ text "Cannot constuct infinite kind" , squotes $ hsep [text . unpack $ getIdent var, text "=", renderKind k] ]
LightAndLight/hindley-milner
src/Phil/Core/Kinds/KindError.hs
Haskell
bsd-3-clause
1,340
{-# LANGUAGE RankNTypes, NoMonomorphismRestriction, BangPatterns, DeriveDataTypeable, GADTs, ScopedTypeVariables, ExistentialQuantification, StandaloneDeriving #-} {-# OPTIONS -Wall #-} module Language.Hakaru.Metropolis where import System.Random (RandomGen, StdGen, randomR, getStdGen) import Data.Dynamic import Data.Maybe import qualified Data.Map.Strict as M import Language.Hakaru.Types {- Shortcomings of this implementation * uses parent-conditional sampling for proposal distribution * re-evaluates entire program at every sample * lacks way to block sample groups of variables -} type DistVal = Dynamic -- and what does XRP stand for? data XRP where XRP :: Typeable e => (Density e, Dist e) -> XRP unXRP :: Typeable a => XRP -> Maybe (Density a, Dist a) unXRP (XRP (e,f)) = cast (e,f) type Visited = Bool type Observed = Bool type LL = LogLikelihood type Subloc = Int type Name = [Subloc] data DBEntry = DBEntry { xrp :: XRP, llhd :: LL, vis :: Visited, observed :: Observed } type Database = M.Map Name DBEntry data SamplerState g where S :: { ldb :: Database, -- ldb = local database -- (total likelihood, total likelihood of XRPs newly introduced) llh2 :: {-# UNPACK #-} !(LL, LL), cnds :: [Cond], -- conditions left to process seed :: g } -> SamplerState g type Sampler a = forall g. (RandomGen g) => SamplerState g -> (a, SamplerState g) sreturn :: a -> Sampler a sreturn x s = (x, s) sbind :: Sampler a -> (a -> Sampler b) -> Sampler b sbind s k = \ st -> let (v, s') = s st in k v s' smap :: (a -> b) -> Sampler a -> Sampler b smap f s = sbind s (\a -> sreturn (f a)) newtype Measure a = Measure {unMeasure :: Name -> Sampler a } deriving (Typeable) return_ :: a -> Measure a return_ x = Measure $ \ _ -> sreturn x updateXRP :: Typeable a => Name -> Cond -> Dist a -> Sampler a updateXRP n obs dist' s@(S {ldb = db, seed = g}) = case M.lookup n db of Just (DBEntry xd lb _ ob) -> let Just (xb, dist) = unXRP xd (x,_) = case obs of Just yd -> let Just y = fromDynamic yd in (y, logDensity dist y) Nothing -> (xb, lb) l' = logDensity dist' x d1 = M.insert n (DBEntry (XRP (x,dist)) l' True ob) db in (fromDensity x, s {ldb = d1, llh2 = updateLogLikelihood l' 0 s, seed = g}) Nothing -> let (xnew2, l, g2) = case obs of Just xdnew -> let Just xnew = fromDynamic xdnew in (xnew, logDensity dist' xnew, g) Nothing -> let (xnew, g1) = distSample dist' g in (xnew, logDensity dist' xnew, g1) d1 = M.insert n (DBEntry (XRP (xnew2, dist')) l True (isJust obs)) db in (fromDensity xnew2, s {ldb = d1, llh2 = updateLogLikelihood l l s, seed = g2}) updateLogLikelihood :: RandomGen g => LL -> LL -> SamplerState g -> (LL, LL) updateLogLikelihood llTotal llFresh s = let (l,lf) = llh2 s in (llTotal+l, llFresh+lf) factor :: LL -> Measure () factor l = Measure $ \ _ -> \ s -> let (llTotal, llFresh) = llh2 s in ((), s {llh2 = (llTotal + l, llFresh)}) condition :: Eq b => Measure (a, b) -> b -> Measure a condition (Measure m) b' = Measure $ \ n -> let comp a b s | a /= b = s {llh2 = (log 0, 0)} comp _ _ s = s in sbind (m n) (\ (a, b) s -> (a, comp b b' s)) bind :: Measure a -> (a -> Measure b) -> Measure b bind (Measure m) cont = Measure $ \ n -> sbind (m (0:n)) (\ a -> unMeasure (cont a) (1:n)) conditioned :: Typeable a => Dist a -> Measure a conditioned dist = Measure $ \ n -> \s@(S {cnds = cond:conds }) -> updateXRP n cond dist s{cnds = conds} unconditioned :: Typeable a => Dist a -> Measure a unconditioned dist = Measure $ \ n -> updateXRP n Nothing dist instance Monad Measure where return = return_ (>>=) = bind run :: Measure a -> [Cond] -> IO (a, Database, LL) run (Measure prog) cds = do g <- getStdGen let (v, S d ll [] _) = (prog [0]) (S M.empty (0,0) cds g) return (v, d, fst ll) traceUpdate :: RandomGen g => Measure a -> Database -> [Cond] -> g -> (a, Database, LL, LL, LL, g) traceUpdate (Measure prog) d cds g = do -- let d1 = M.map (\ (x, l, _, ob) -> (x, l, False, ob)) d let d1 = M.map (\ s -> s { vis = False }) d let (v, S d2 (llTotal, llFresh) [] g1) = (prog [0]) (S d1 (0,0) cds g) let (d3, stale_d) = M.partition vis d2 let llStale = M.foldl' (\ llStale' s -> llStale' + llhd s) 0 stale_d (v, d3, llTotal, llFresh, llStale, g1) initialStep :: Measure a -> [Cond] -> IO (a, Database, LL, LL, LL, StdGen) initialStep prog cds = do g <- getStdGen return $ traceUpdate prog M.empty cds g -- TODO: Make a way of passing user-provided proposal distributions resample :: RandomGen g => Name -> Database -> Observed -> XRP -> g -> (Database, LL, LL, LL, g) resample name db ob (XRP (x, dist)) g = let (x', g1) = distSample dist g fwd = logDensity dist x' rvs = logDensity dist x l' = fwd newEntry = DBEntry (XRP (x', dist)) l' True ob db' = M.insert name newEntry db in (db', l', fwd, rvs, g1) transition :: (Typeable a, RandomGen g) => Measure a -> [Cond] -> a -> Database -> LL -> g -> [a] transition prog cds v db ll g = let dbSize = M.size db -- choose an unconditioned choice (_, uncondDb) = M.partition observed db (choice, g1) = randomR (0, (M.size uncondDb) -1) g (name, (DBEntry xd _ _ ob)) = M.elemAt choice uncondDb (db', _, fwd, rvs, g2) = resample name db ob xd g1 (v', db2, llTotal, llFresh, llStale, g3) = traceUpdate prog db' cds g2 a = llTotal - ll + rvs - fwd + log (fromIntegral dbSize) - log (fromIntegral $ M.size db2) + llStale - llFresh (u, g4) = randomR (0 :: Double, 1) g3 in if (log u < a) then v' : (transition prog cds v' db2 llTotal g4) else v : (transition prog cds v db ll g4) mcmc :: Typeable a => Measure a -> [Cond] -> IO [a] mcmc prog cds = do (v, d, llTotal, _, _, g) <- initialStep prog cds return $ transition prog cds v d llTotal g sample :: Typeable a => Measure a -> [Cond] -> IO [(a, Double)] sample prog cds = do (v, d, llTotal, _, _, g) <- initialStep prog cds return $ map (\ x -> (x,1)) (transition prog cds v d llTotal g)
zaxtax/hakaru-old
Language/Hakaru/Metropolis.hs
Haskell
bsd-3-clause
6,619
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE FlexibleContexts #-} module NetworkSim.LinkLayer ( -- * MAC module NetworkSim.LinkLayer.MAC -- * Link-layer exception , LinkException (..) -- * Ethernet Frame , Frame (..) , Payload () , OutFrame , Destination (..) , destinationAddr , InFrame -- * Hardware Port , Port () , portCount , newPort , PortInfo (..) -- * Network Interface Controller (NIC) , NIC () , newNIC , address , portInfo , connectNICs , disconnectPort , sendOnNIC , receiveOnNIC , setPromiscuity , PortConnectHook , setPortConnectHook -- * Logging , module NetworkSim.LinkLayer.Logging -- * Utilities , atomically' ) where import NetworkSim.LinkLayer.MAC import NetworkSim.LinkLayer.Logging import qualified Data.ByteString.Lazy as LB import Control.Concurrent.STM import Data.Typeable import Control.Monad.Catch import Data.Vector (Vector) import qualified Data.Vector as V import Control.Monad import Data.Maybe import qualified Data.Text as T import Data.Monoid import Control.Monad.IO.Class import Control.Monad.Trans.Control import Control.Concurrent.Lifted (fork) import Data.Word data LinkException = PortDisconnected MAC PortNum | PortAlreadyConnected MAC PortNum | NoFreePort MAC | ConnectToSelf MAC deriving (Show, Typeable) instance Exception LinkException type Payload = LB.ByteString -- | A simplified representation of an Ethernet frame, assuming a -- perfect physical layer. data Frame a = Frame { destination :: !a , source :: {-# UNPACK #-} !MAC , payload :: !Payload } deriving (Show) -- | An outbound Ethernet frame. type OutFrame = Frame MAC data Destination = Broadcast | Unicast MAC deriving (Eq, Show) -- | Retrieve underlying MAC address of a 'Destination'. destinationAddr :: Destination -> MAC destinationAddr Broadcast = broadcastAddr destinationAddr (Unicast addr) = addr -- | An Ethernet frame with parsed destination field. type InFrame = Frame Destination data Port = Port { mate :: !(TVar (Maybe Port)) , buffer' :: !(TQueue OutFrame) } newPort :: STM Port newPort = Port <$> newTVar Nothing <*> newTQueue data PortInfo = PortInfo { isConnected :: !Bool } deriving (Show) getPortInfo :: Port -> STM PortInfo getPortInfo = fmap (PortInfo . isJust) . readTVar . mate -- | First arg: the local NIC being connected. Second arg: the local port being connected. Third arg: the address of the remote NIC. type PortConnectHook = NIC -> PortNum -> MAC -> STM () -- | Network interface controller (NIC). data NIC = NIC { mac :: {-# UNPACK #-} !MAC , ports :: {-# UNPACK #-} !(Vector Port) , promiscuity :: !(TVar Bool) , buffer :: !(TQueue (PortNum, InFrame)) -- ^ Buffer of messages filtered by ports. , portConnectHook :: !(TVar PortConnectHook) -- ^ Hook guaranteed to be executed atomically after successful 'connectNICs' action. } instance Eq NIC where nic == nic' = mac nic == mac nic' deviceName = "NIC" newNIC :: (MonadIO m, MonadBaseControl IO m, MonadLogger m) => Word16 -- ^ Number of ports. Pre: >= 1. -> Bool -- ^ Initial promiscuity setting. -> m NIC newNIC n promis = do mac <- liftIO freshMAC nic <- atomically' $ NIC mac <$> V.replicateM (fromIntegral n) newPort <*> newTVar promis <*> newTQueue <*> newTVar defaultHook V.imapM_ (\(fromIntegral -> i) p -> void . fork $ portAction nic i p) $ ports nic return nic where portAction nic i p = forever $ do frame <- atomically' $ readTQueue (buffer' p) let dest = destination frame if | dest == broadcastAddr -> atomically' $ writeTQueue (buffer nic) (i, frame { destination = Broadcast }) | dest == mac nic -> atomically' $ writeTQueue (buffer nic) (i, frame { destination = Unicast dest }) | otherwise -> do written <- atomically' $ do isPromiscuous <- readTVar (promiscuity nic) when isPromiscuous $ writeTQueue (buffer nic) (i, frame { destination = Unicast dest }) return isPromiscuous when (not written) $ recordWithPort deviceName (mac nic) i $ "Dropping frame destined for " <> (T.pack . show) dest defaultHook _ _ _ = return () -- | Connect two NICs, using the first free port available for -- each. Returns these ports. connectNICs :: (MonadIO m, MonadThrow m, MonadLogger m) => NIC -> NIC -> m (PortNum, PortNum) connectNICs nic nic' = do if nic == nic' then throwM $ ConnectToSelf (mac nic) else do ports@(portNum, portNum') <- atomically' $ do (fromIntegral -> portNum, p) <- firstFreePort nic (fromIntegral -> portNum', p') <- firstFreePort nic' checkDisconnected nic portNum p checkDisconnected nic' portNum' p' writeTVar (mate p) (Just p') writeTVar (mate p') (Just p) readTVar (portConnectHook nic) >>= \f -> f nic portNum (address nic') readTVar (portConnectHook nic') >>= \f -> f nic' portNum' (address nic) return (portNum, portNum') announce . T.pack $ "Connected " <> show (mac nic) <> "(" <> show portNum <> ") and " <> show (mac nic') <> "(" <> show portNum' <> ")" return ports where firstFreePort nic = do free <- V.filterM hasFreePort . V.indexed $ ports nic if V.length free > 0 then return $ V.head free else throwM $ NoFreePort (mac nic) where hasFreePort (_, port) = isNothing <$> readTVar (mate port) checkDisconnected :: NIC -> PortNum -> Port -> STM () checkDisconnected nic n p = do q <- readTVar (mate p) when (isJust q) $ throwM $ PortAlreadyConnected (mac nic) n -- | Will throw a 'PortDisconnected' exception if the port requested port -- is already disconnected. disconnectPort :: (MonadIO m, MonadLogger m) => NIC -> PortNum -> m () disconnectPort nic n = case ports nic V.!? (fromIntegral n) of Nothing -> -- TODO: alert user to index out of bounds error? return () Just p -> do atomically' $ do mate' <- readTVar (mate p) case mate' of Nothing -> throwM $ PortDisconnected (mac nic) n Just q -> do -- __NOTE__: We do not check if the mate is already -- disconnected. writeTVar (mate q) Nothing writeTVar (mate p) Nothing recordWithPort deviceName (mac nic) n $ "Disconnected port" -- | Will throw a 'PortDisconnected' exception if you try to send on a -- disconnected port. sendOnNIC :: OutFrame -- ^ The source MAC here is allowed to differ from the NIC's MAC. -> NIC -> PortNum -> STM () sendOnNIC frame nic n = case ports nic V.!? (fromIntegral n) of Nothing -> -- TODO: alert user to index out of bounds error? return () Just p -> do mate' <- readTVar (mate p) case mate' of Nothing -> throwM $ PortDisconnected (mac nic) n Just q -> writeTQueue (buffer' q) frame -- | Wait on all ports of a NIC for the next incoming frame. This is a -- blocking method. Behaviour is affected by the NIC's promiscuity -- setting (see 'setPromiscuity'). receiveOnNIC :: NIC -> STM (PortNum, InFrame) receiveOnNIC = readTQueue . buffer -- | Toggle promiscuous mode for a 'NIC'. When promiscuous, a NIC will -- not drop the frames destined for another NIC. This is a useful -- operating mode for, e.g. switches. setPromiscuity :: (MonadIO m, MonadLogger m) => NIC -> Bool -> m () setPromiscuity nic b = do old <- atomically' $ swapTVar (promiscuity nic) b when (old /= b) $ if b then record deviceName (mac nic) $ "Enabling promiscuity mode" else record deviceName (mac nic) $ "Disabling promiscuity mode" -- | Set a hook guaranteed to be run atomically after successful -- execution of 'connectNICs'. setPortConnectHook :: PortConnectHook -> NIC -> STM () setPortConnectHook h nic = writeTVar (portConnectHook nic) h address :: NIC -> MAC address = mac portInfo :: NIC -> STM (Vector PortInfo) portInfo = V.mapM getPortInfo . ports -- | @ atomically' = liftIO . atomically @ atomically' :: MonadIO m => STM a -> m a atomically' = liftIO . atomically portCount :: NIC -> Word16 portCount = fromIntegral . V.length . ports
prophet-on-that/network-sim
src/NetworkSim/LinkLayer.hs
Haskell
bsd-3-clause
8,672
{-# LANGUAGE OverloadedStrings , BangPatterns , ScopedTypeVariables #-} module RunTests where import Control.Exception import Data.Conduit import Data.List (foldl') import Data.Monoid ((<>)) import Data.Conduit.HDBI import Database.HDBI import Database.HDBI.SQlite import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck import Test.QuickCheck.Assertions import qualified Data.Conduit.List as L import qualified Data.Conduit.Util as U import qualified Test.QuickCheck.Monadic as M createTables :: SQliteConnection -> IO () createTables c = do runRaw c "create table values1(val1 integer, val2 integer)" runRaw c "create table values2(val1 integer, val2 integer)" runRaw c "create table values3(val1 integer, val2 integer)" allTests :: SQliteConnection -> Test allTests c = testGroup "All tests" [ testProperty "Insert + fold" $ insertFold c , testProperty "Insert + copy" $ insertCopy c , testProperty "Insert + copy + sum" $ insertCopySum c , testProperty "Insert trans fluahAt" $ insertTransFlushAt c , testProperty "Insert trans flushBy" $ insertTransFlushBy c ] sumPairs :: (Num a, Num b) => (a, b) -> (a, b) -> (a, b) sumPairs (!a, !b) (!x, !y) = (a+x, b+y) insertTransFlushAt :: SQliteConnection -> Positive Int -> [(Integer, Integer)] -> Property insertTransFlushAt c count vals = M.monadicIO $ do (Just res, tr) <- M.run $ do runRaw c "delete from values1" runResourceT $ L.sourceList vals $= (flushAt $ getPositive count) $$ insertAllTrans c "insert into values1 (val1, val2) values (?,?)" r <- runFetchOne c "select count(*) from values1" () tr <- inTransaction c return (r, tr) _ <- M.stop $ res ?== (length vals) M.stop $ tr ?== False insertTransFlushBy :: SQliteConnection -> NonEmptyList Integer -> Property insertTransFlushBy con vals = M.monadicIO $ do (tr, r) <- M.run $ do runRaw con "delete from values1" runResourceT $ L.sourceList nvals $= flushBy signFlush $= L.map (fmap one) -- flush is the functor $$ insertAllTrans con "insert into values1 (val1) values (?)" tr <- inTransaction con Just r <- runFetchOne con "select sum(val1) from values1" () return (tr, r) _ <- M.stop $ tr ?== False M.stop $ r ?== (sum nvals) where nvals = getNonEmpty vals signFlush a b = (signum a) == (signum b) insertFold :: SQliteConnection -> [(Integer, Integer)] -> Property insertFold c vals = M.monadicIO $ do res <- M.run $ withTransaction c $ do runRaw c "delete from values1" runMany c "insert into values1(val1, val2) values (?,?)" vals runResourceT $ selectAll c "select val1, val2 from values1" () $$ L.fold sumPairs (0 :: Integer, 0 :: Integer) M.stop $ res ?== (foldl' sumPairs (0, 0) vals) insertCopy :: SQliteConnection -> [(Integer, Integer)] -> Property insertCopy c vals = M.monadicIO $ do res <- M.run $ withTransaction c $ do runRaw c "delete from values1" runRaw c "delete from values2" runResourceT $ L.sourceList vals $$ insertAll c "insert into values1(val1, val2) values (?,?)" runResourceT $ selectAll c "select val1, val2 from values1" () $= asThisType (undefined :: (Int, Int)) $$ insertAllCount c "insert into values2(val1, val2) values (?,?)" M.stop $ res == (length vals) insertCopySum :: SQliteConnection -> [(Integer, Integer)] -> Property insertCopySum c vals = M.monadicIO $ do res <- M.run $ withTransaction c $ do mapM_ (runRaw c . ("delete from " <>)) ["values1", "values2", "values3"] runResourceT $ L.sourceList vals $$ insertAll c "insert into values1(val1, val2) values (?,?)" runResourceT $ selectAll c "select val1, val2 from values1" () $= asSqlVals $$ insertAll c "insert into values2(val1, val2) values (?,?)" runResourceT $ (U.zip (selectAll c "select val1, val2 from values1" ()) (selectAll c "select val1, val2 from values2" ())) $= L.map (\(a, b :: (Integer, Integer)) -> sumPairs a b) $$ insertAll c "insert into values3(val1, val2) values (?,?)" runResourceT $ selectAll c "select val1, val2 from values3" () $$ L.fold sumPairs (0 :: Integer, 0 :: Integer) let (a, b) = foldl' sumPairs (0, 0) vals M.stop $ (a*2, b*2) ==? res main :: IO () main = bracket (connectSqlite3 ":memory:") disconnect $ \c -> do createTables c defaultMain [allTests c]
s9gf4ult/hdbi-conduit
testsrc/runtests.hs
Haskell
bsd-3-clause
4,603
{-# LANGUAGE DeriveGeneric #-} module Real.Types (module Real.Types, Version(..)) where import GHC.Generics newtype InstalledPackageId = InstalledPackageId String deriving (Eq, Ord, Generic) newtype PackageName = PackageName String deriving (Eq, Ord, Generic) data Version = Version [Int] [String] deriving (Eq, Ord, Generic) data PackageId = PackageId { pkgName :: PackageName, -- ^The name of this package, eg. foo pkgVersion :: Version -- ^the version of this package, eg 1.2 } deriving (Eq, Ord, Generic) newtype ModuleName = ModuleName [String] deriving (Eq, Ord, Generic) data License = GPL (Maybe Version) | AGPL (Maybe Version) | LGPL (Maybe Version) | BSD3 | BSD4 | MIT | Apache (Maybe Version) | PublicDomain | AllRightsReserved | OtherLicense | UnknownLicense String deriving (Eq, Generic) {- data InstalledPackageInfo = InstalledPackageInfo { -- these parts are exactly the same as PackageDescription installedPackageId :: InstalledPackageId, sourcePackageId :: PackageId, license :: License, copyright :: String, maintainer :: String, author :: String, stability :: String, homepage :: String, pkgUrl :: String, synopsis :: String, description :: String, category :: String, -- these parts are required by an installed package only: exposed :: Bool, exposedModules :: [ModuleName], hiddenModules :: [ModuleName], trusted :: Bool, importDirs :: [FilePath], -- contain sources in case of Hugs libraryDirs :: [FilePath], hsLibraries :: [String], extraLibraries :: [String], extraGHCiLibraries:: [String], -- overrides extraLibraries for GHCi includeDirs :: [FilePath], includes :: [String], depends :: [InstalledPackageId], hugsOptions :: [String], ccOptions :: [String], ldOptions :: [String], frameworkDirs :: [FilePath], frameworks :: [String], haddockInterfaces :: [FilePath], haddockHTMLs :: [FilePath] } deriving (Eq, Generic) -} data VersionRange = AnyVersion | ThisVersion Version -- = version | LaterVersion Version -- > version (NB. not >=) | EarlierVersion Version -- < version | WildcardVersion Version -- == ver.* (same as >= ver && < ver+1) | UnionVersionRanges VersionRange VersionRange | IntersectVersionRanges VersionRange VersionRange | VersionRangeParens VersionRange -- just '(exp)' parentheses syntax deriving (Eq, Generic) data Dependency = Dependency PackageName VersionRange deriving (Eq, Generic) data CompilerFlavor = GHC | NHC | YHC | Hugs | HBC | Helium | JHC | LHC | UHC | HaskellSuite String -- string is the id of the actual compiler | OtherCompiler String deriving (Eq, Ord, Generic) data SourceRepo = SourceRepo { repoKind :: RepoKind, repoType :: Maybe RepoType, repoLocation :: Maybe String, repoModule :: Maybe String, repoBranch :: Maybe String, repoTag :: Maybe String, repoSubdir :: Maybe FilePath } deriving (Eq, Generic) data RepoKind = RepoHead | RepoThis | RepoKindUnknown String deriving (Eq, Ord, Generic) data RepoType = Darcs | Git | SVN | CVS | Mercurial | GnuArch | Bazaar | Monotone | OtherRepoType String deriving (Eq, Ord, Generic) data BuildType = Simple | Configure | Make | Custom | UnknownBuildType String deriving (Eq, Generic) data Library = Library { exposedModules :: [ModuleName], libExposed :: Bool, -- ^ Is the lib to be exposed by default? libBuildInfo :: BuildInfo } deriving (Eq, Generic) data Executable = Executable { exeName :: String, modulePath :: FilePath, buildInfo :: BuildInfo } deriving (Eq, Generic) data TestSuite = TestSuite { testName :: String, testInterface :: TestSuiteInterface, testBuildInfo :: BuildInfo, testEnabled :: Bool } deriving (Eq, Generic) data TestType = TestTypeExe Version | TestTypeLib Version | TestTypeUnknown String Version deriving (Eq, Generic) data TestSuiteInterface = TestSuiteExeV10 Version FilePath | TestSuiteLibV09 Version ModuleName | TestSuiteUnsupported TestType deriving (Eq, Generic) data Benchmark = Benchmark { benchmarkName :: String, benchmarkInterface :: BenchmarkInterface, benchmarkBuildInfo :: BuildInfo, benchmarkEnabled :: Bool } deriving (Eq, Generic) data BenchmarkType = BenchmarkTypeExe Version | BenchmarkTypeUnknown String Version deriving (Eq, Generic) data BenchmarkInterface = BenchmarkExeV10 Version FilePath | BenchmarkUnsupported BenchmarkType deriving (Eq, Generic) data Language = Haskell98 | Haskell2010 | UnknownLanguage String deriving (Eq, Generic) data Extension = EnableExtension KnownExtension | DisableExtension KnownExtension | UnknownExtension String deriving (Eq, Generic) data KnownExtension = OverlappingInstances | UndecidableInstances | IncoherentInstances | DoRec | RecursiveDo | ParallelListComp | MultiParamTypeClasses | MonomorphismRestriction | FunctionalDependencies | Rank2Types | RankNTypes | PolymorphicComponents | ExistentialQuantification | ScopedTypeVariables | PatternSignatures | ImplicitParams | FlexibleContexts | FlexibleInstances | EmptyDataDecls | CPP | KindSignatures | BangPatterns | TypeSynonymInstances | TemplateHaskell | ForeignFunctionInterface | Arrows | Generics | ImplicitPrelude | NamedFieldPuns | PatternGuards | GeneralizedNewtypeDeriving | ExtensibleRecords | RestrictedTypeSynonyms | HereDocuments | MagicHash | TypeFamilies | StandaloneDeriving | UnicodeSyntax | UnliftedFFITypes | InterruptibleFFI | CApiFFI | LiberalTypeSynonyms | TypeOperators | RecordWildCards | RecordPuns | DisambiguateRecordFields | TraditionalRecordSyntax | OverloadedStrings | GADTs | GADTSyntax | MonoPatBinds | RelaxedPolyRec | ExtendedDefaultRules | UnboxedTuples | DeriveDataTypeable | DeriveGeneric | DefaultSignatures | InstanceSigs | ConstrainedClassMethods | PackageImports | ImpredicativeTypes | NewQualifiedOperators | PostfixOperators | QuasiQuotes | TransformListComp | MonadComprehensions | ViewPatterns | XmlSyntax | RegularPatterns | TupleSections | GHCForeignImportPrim | NPlusKPatterns | DoAndIfThenElse | MultiWayIf | LambdaCase | RebindableSyntax | ExplicitForAll | DatatypeContexts | MonoLocalBinds | DeriveFunctor | DeriveTraversable | DeriveFoldable | NondecreasingIndentation | SafeImports | Safe | Trustworthy | Unsafe | ConstraintKinds | PolyKinds | DataKinds | ParallelArrays | RoleAnnotations | OverloadedLists | EmptyCase | AutoDeriveTypeable | NegativeLiterals | NumDecimals | NullaryTypeClasses | ExplicitNamespaces | AllowAmbiguousTypes deriving (Eq, Enum, Bounded, Generic) data BuildInfo = BuildInfo { buildable :: Bool, -- ^ component is buildable here buildTools :: [Dependency], -- ^ tools needed to build this bit cppOptions :: [String], -- ^ options for pre-processing Haskell code ccOptions :: [String], -- ^ options for C compiler ldOptions :: [String], -- ^ options for linker pkgconfigDepends :: [Dependency], -- ^ pkg-config packages that are used frameworks :: [String], -- ^support frameworks for Mac OS X cSources :: [FilePath], hsSourceDirs :: [FilePath], -- ^ where to look for the haskell module Real.hierarchy otherModules :: [ModuleName], -- ^ non-exposed or non-main modules defaultLanguage :: Maybe Language,-- ^ language used when not explicitly specified otherLanguages :: [Language], -- ^ other languages used within the package defaultExtensions :: [Extension], -- ^ language extensions used by all modules otherExtensions :: [Extension], -- ^ other language extensions used within the package oldExtensions :: [Extension], -- ^ the old extensions field, treated same as 'defaultExtensions' extraLibs :: [String], -- ^ what libraries to link with when compiling a program that uses your package extraLibDirs :: [String], includeDirs :: [FilePath], -- ^directories to find .h files includes :: [FilePath], -- ^ The .h files to be found in includeDirs installIncludes :: [FilePath], -- ^ .h files to install with the package options :: [(CompilerFlavor,[String])], ghcProfOptions :: [String], ghcSharedOptions :: [String], customFieldsBI :: [(String,String)], -- ^Custom fields starting -- with x-, stored in a -- simple assoc-list. targetBuildDepends :: [Dependency] -- ^ Dependencies specific to a library or executable target } deriving (Eq, Generic) data PackageDescription = PackageDescription { -- the following are required by all packages: package :: PackageId, license :: License, licenseFile :: FilePath, copyright :: String, maintainer :: String, author :: String, stability :: String, testedWith :: [(CompilerFlavor,VersionRange)], homepage :: String, pkgUrl :: String, bugReports :: String, sourceRepos :: [SourceRepo], synopsis :: String, -- ^A one-line summary of this package description :: String, -- ^A more verbose description of this package category :: String, customFieldsPD :: [(String,String)], -- ^Custom fields starting -- with x-, stored in a -- simple assoc-list. buildDepends :: [Dependency], -- | The version of the Cabal spec that this package description uses. -- For historical reasons this is specified with a version range but -- only ranges of the form @>= v@ make sense. We are in the process of -- transitioning to specifying just a single version, not a range. specVersionRaw :: Either Version VersionRange, buildType :: Maybe BuildType, -- components library :: Maybe Library, executables :: [Executable], testSuites :: [TestSuite], benchmarks :: [Benchmark], dataFiles :: [FilePath], dataDir :: FilePath, extraSrcFiles :: [FilePath], extraTmpFiles :: [FilePath], extraDocFiles :: [FilePath] } deriving (Eq, Generic) data GenericPackageDescription = GenericPackageDescription { packageDescription :: PackageDescription, genPackageFlags :: [Flag], condLibrary :: Maybe (CondTree ConfVar [Dependency] Library), condExecutables :: [(String, CondTree ConfVar [Dependency] Executable)], condTestSuites :: [(String, CondTree ConfVar [Dependency] TestSuite)], condBenchmarks :: [(String, CondTree ConfVar [Dependency] Benchmark)] } deriving (Eq, Generic) data OS = Linux | Windows | OSX -- tier 1 desktop OSs | FreeBSD | OpenBSD | NetBSD -- other free unix OSs | Solaris | AIX | HPUX | IRIX -- ageing Unix OSs | HaLVM -- bare metal / VMs / hypervisors | IOS -- iOS | OtherOS String deriving (Eq, Ord, Generic) data Arch = I386 | X86_64 | PPC | PPC64 | Sparc | Arm | Mips | SH | IA64 | S390 | Alpha | Hppa | Rs6000 | M68k | Vax | OtherArch String deriving (Eq, Ord, Generic) data Flag = MkFlag { flagName :: FlagName , flagDescription :: String , flagDefault :: Bool , flagManual :: Bool } deriving (Eq, Generic) newtype FlagName = FlagName String deriving (Eq, Ord, Generic) type FlagAssignment = [(FlagName, Bool)] data ConfVar = OS OS | Arch Arch | Flag FlagName | Impl CompilerFlavor VersionRange deriving (Eq, Generic) data Condition c = Var c | Lit Bool | CNot (Condition c) | COr (Condition c) (Condition c) | CAnd (Condition c) (Condition c) deriving (Eq, Generic) data CondTree v c a = CondNode { condTreeData :: a , condTreeConstraints :: c , condTreeComponents :: [( Condition v , CondTree v c a , Maybe (CondTree v c a))] } deriving (Eq, Generic)
thoughtpolice/binary-serialise-cbor
bench/Real/Types.hs
Haskell
bsd-3-clause
13,470
module Paths_CipherSolver ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,1,0,0], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/home/abhi/.cabal/bin" libdir = "/home/abhi/.cabal/lib/CipherSolver-0.1.0.0/ghc-7.6.3" datadir = "/home/abhi/.cabal/share/CipherSolver-0.1.0.0" libexecdir = "/home/abhi/.cabal/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "CipherSolver_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "CipherSolver_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "CipherSolver_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "CipherSolver_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
abhinav-mehta/CipherSolver
dist/build/autogen/Paths_CipherSolver.hs
Haskell
bsd-3-clause
1,174
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, Rank2Types #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.LinearAlgebra.Matrix.STBase -- Copyright : Copyright (c) 2010, Patrick Perry <patperry@gmail.com> -- License : BSD3 -- Maintainer : Patrick Perry <patperry@gmail.com> -- Stability : asinerimental -- module Numeric.LinearAlgebra.Matrix.STBase where import Control.Monad( forM_, when ) import Control.Monad.ST( ST, RealWorld, runST, unsafeInterleaveST, unsafeIOToST ) import Data.Maybe( fromMaybe ) import Data.Typeable( Typeable ) import Foreign( Ptr, advancePtr, peek, peekElemOff, pokeElemOff, mallocForeignPtrArray ) import Text.Printf( printf ) import Unsafe.Coerce( unsafeCoerce ) import Numeric.LinearAlgebra.Types import qualified Foreign.BLAS as BLAS import Numeric.LinearAlgebra.Matrix.Base hiding ( unsafeWith, unsafeToForeignPtr, unsafeFromForeignPtr, ) import qualified Numeric.LinearAlgebra.Matrix.Base as M import Numeric.LinearAlgebra.Vector( STVector, RVector ) import qualified Numeric.LinearAlgebra.Vector as V -- | Mutable dense matrices in the 'ST' monad. newtype STMatrix s e = STMatrix { unSTMatrix :: Matrix e } deriving (Typeable) -- | Mutable dense matrices in the 'IO' monad. type IOMatrix = STMatrix RealWorld -- | A safe way to create and work with a mutable matrix before returning -- an immutable matrix for later perusal. This function avoids copying -- the matrix before returning it - it uses 'unsafeFreeze' internally, -- but this wrapper is a safe interface to that function. create :: (Storable e) => (forall s . ST s (STMatrix s e)) -> Matrix e create mx = runST $ mx >>= unsafeFreeze {-# INLINE create #-} -- | Converts a mutable matrix to an immutable one by taking a complete -- copy of it. freeze :: (RMatrix m, Storable e) => m e -> ST s (Matrix e) freeze a = do a' <- newCopy a unsafeFreeze a' {-# INLINE freeze #-} -- | Read-only matrices class RMatrix m where -- | Get the dimensions of the matrix (number of rows and columns). getDim :: (Storable e) => m e -> ST s (Int,Int) -- | Same as 'withCol' but does not range-check index. unsafeWithCol :: (Storable e) => m e -> Int -> (forall v. RVector v => v e -> ST s a) -> ST s a -- | Perform an action with a list of views of the matrix columns. withCols :: (Storable e) => m e -> (forall v . RVector v => [v e] -> ST s a) -> ST s a -- | Same as 'withSlice' but does not range-check index. unsafeWithSlice :: (Storable e) => (Int,Int) -> (Int,Int) -> m e -> (forall m'. RMatrix m' => m' e -> ST s a) -> ST s a -- | Possibly view a matrix as a vector and perform an action on the -- view. This only succeeds if the matrix is stored contiguously in -- memory, i.e. if the matrix contains a single column or the \"lda\" -- of the matrix is equal to the number of rows. maybeWithVector :: (Storable e) => m e -> (forall v . RVector v => v e -> ST s a) -> Maybe (ST s a) -- | Converts a read-only matrix into an immutable matrix. This simply -- casts the matrix from one type to the other without copying. -- Note that because the matrix is possibly not copied, any subsequent -- modifications made to the read-only version of the matrix may be shared -- with the immutable version. It is safe to use, therefore, if the -- read-only version is never modified after the freeze operation. unsafeFreeze :: (Storable e) => m e -> ST s (Matrix e) -- | Unsafe cast from a read-only matrix to a mutable matrix. unsafeThaw :: (Storable e) => m e -> ST s (STMatrix s e) -- | Execute an 'IO' action with a pointer to the first element in the -- matrix and the leading dimension (lda). unsafeWith :: (Storable e) => m e -> (Ptr e -> Int -> IO a) -> IO a instance RMatrix Matrix where getDim = return . dim {-# INLINE getDim #-} unsafeWithCol a j f = f (unsafeCol a j) {-# INLINE unsafeWithCol #-} withCols a f = f (cols a) {-# INLINE withCols #-} unsafeWithSlice ij mn a f = f (unsafeSlice ij mn a) {-# INLINE unsafeWithSlice #-} maybeWithVector a f | isContig a = Just $ f (toVector a) | otherwise = Nothing {-# INLINE maybeWithVector #-} unsafeWith = M.unsafeWith {-# INLINE unsafeWith #-} unsafeFreeze = return {-# INLINE unsafeFreeze #-} unsafeThaw = return . STMatrix {-# INLINE unsafeThaw #-} instance RMatrix (STMatrix s) where getDim = return . dim . unSTMatrix {-# INLINE getDim #-} unsafeWithCol = unsafeWithCol . unSTMatrix {-# INLINE unsafeWithCol #-} withCols = withCols . unSTMatrix {-# INLINE withCols #-} unsafeWithSlice ij mn = unsafeWithSlice ij mn . unSTMatrix {-# INLINE unsafeWithSlice #-} maybeWithVector = maybeWithVector . unSTMatrix {-# INLINE maybeWithVector #-} unsafeWith = unsafeWith . unSTMatrix {-# INLINE unsafeWith #-} unsafeFreeze = return . unSTMatrix {-# INLINE unsafeFreeze #-} unsafeThaw v = return $ cast v where cast :: STMatrix s e -> STMatrix s' e cast = unsafeCoerce {-# INLINE unsafeThaw #-} -- | Perform an action with a view of a mutable matrix column -- (no index checking). unsafeWithColM :: (Storable e) => STMatrix s e -> Int -> (STVector s e -> ST s a) -> ST s a unsafeWithColM a j f = unsafeWithCol a j $ \c -> do mc <- V.unsafeThaw c f mc {-# INLINE unsafeWithColM #-} -- | Perform an action with a list of views of the mutable matrix columns. See -- also 'withCols'. withColsM :: (Storable e) => STMatrix s e -> ([STVector s e] -> ST s a) -> ST s a withColsM a f = withCols a $ \cs -> do mcs <- thawVecs cs f mcs where thawVecs [] = return [] thawVecs (c:cs) = unsafeInterleaveST $ do mc <- V.unsafeThaw c mcs <- thawVecs cs return $ mc:mcs {-# INLINE withColsM #-} -- | Possibly view a matrix as a vector and perform an action on the -- view. This succeeds when the matrix is stored contiguously in memory, -- i.e. if the matrix contains a single column or the \"lda\" of the matrix -- is equal to the number of rows. See also 'maybeWithVector'. maybeWithVectorM :: (Storable e) => STMatrix s e -> (STVector s e -> ST s a) -> Maybe (ST s a) maybeWithVectorM a f = maybeWithVector a $ \v -> do mv <- V.unsafeThaw v f mv {-# INLINE maybeWithVectorM #-} -- | View a vector as a matrix of the given shape and pass it to -- the specified function. withFromVector :: (RVector v, Storable e) => (Int,Int) -> v e -> (forall m . RMatrix m => m e -> ST s a) -> ST s a withFromVector mn@(m,n) v f = do nv <- V.getDim v when (nv /= m*n) $ error $ printf ("withFromVector (%d,%d) <vector with dim %d>:" ++ " dimension mismatch") m n nv iv <- V.unsafeFreeze v f $ fromVector mn iv {-# INLINE withFromVector #-} -- | View a mutable vector as a mutable matrix of the given shape and pass it -- to the specified function. withFromVectorM :: (Storable e) => (Int,Int) -> STVector s e -> (STMatrix s e -> ST s a) -> ST s a withFromVectorM mn@(m,n) v f = do nv <- V.getDim v when (nv /= m*n) $ error $ printf ("withFromVectorM (%d,%d) <vector with dim %d>:" ++ " dimension mismatch") m n nv withFromVector mn v $ \a -> do ma <- unsafeThaw a f ma {-# INLINE withFromVectorM #-} -- | View a vector as a matrix with one column and pass it to -- the specified function. withFromCol :: (RVector v, Storable e) => v e -> (forall m . RMatrix m => m e -> ST s a) -> ST s a withFromCol v f = do m <- V.getDim v withFromVector (m,1) v f {-# INLINE withFromCol #-} -- | View a mutable vector as a mutable matrix with one column and pass it to -- the specified function. withFromColM :: (Storable e) => STVector s e -> (STMatrix s e -> ST s a) -> ST s a withFromColM v f = do m <- V.getDim v withFromVectorM (m, 1) v f {-# INLINE withFromColM #-} -- | View a vector as a matrix with one row and pass it to -- the specified function. withFromRow :: (RVector v, Storable e) => v e -> (forall m . RMatrix m => m e -> ST s a) -> ST s a withFromRow v f = do n <- V.getDim v withFromVector (1,n) v f {-# INLINE withFromRow #-} -- | View a mutable vector as a mutable matrix with one row and pass it to -- the specified function. withFromRowM :: (Storable e) => STVector s e -> (STMatrix s e -> ST s a) -> ST s a withFromRowM v f = do n <- V.getDim v withFromVectorM (1,n) v f {-# INLINE withFromRowM #-} -- | Perform an action with a view of a matrix column. withCol :: (RMatrix m, Storable e) => m e -> Int -> (forall v . RVector v => v e -> ST s a) -> ST s a withCol a j f = do (m,n) <- getDim a when (j < 0 || j >= n) $ error $ printf ("withCol <matrix with dim (%d,%d)> %d:" ++ " index out of range") m n j unsafeWithCol a j f {-# INLINE withCol #-} -- | Like 'withCol', but perform the action with a mutable view. withColM :: (Storable e) => STMatrix s e -> Int -> (STVector s e -> ST s a) -> ST s a withColM a j f = do (m,n) <- getDim a when (j < 0 || j >= n) $ error $ printf ("withColM <matrix with dim (%d,%d)> %d:" ++ " index out of range") m n j unsafeWithColM a j f {-# INLINE withColM #-} -- | Create a new matrix of given shape, but do not initialize the elements. new_ :: (Storable e) => (Int,Int) -> ST s (STMatrix s e) new_ (m,n) | m < 0 || n < 0 = error $ printf "new_ (%d,%d): invalid dimensions" m n | otherwise = unsafeIOToST $ do f <- mallocForeignPtrArray (m*n) return $ STMatrix $ M.unsafeFromForeignPtr f 0 (m,n) (max 1 m) -- | Create a matrix with every element initialized to the same value. new :: (Storable e) => (Int,Int) -> e -> ST s (STMatrix s e) new (m,n) e = do a <- new_ (m,n) setElems a $ replicate (m*n) e return a -- | Creates a new matrix by copying another one. newCopy :: (RMatrix m, Storable e) => m e -> ST s (STMatrix s e) newCopy a = do mn <- getDim a b <- new_ mn unsafeCopyTo b a return b -- | @copyTo dst src@ replaces the values in @dst@ with those in -- source. The operands must be the same shape. copyTo :: (RMatrix m, Storable e) => STMatrix s e -> m e -> ST s () copyTo = checkOp2 "copyTo" unsafeCopyTo {-# INLINE copyTo #-} -- | Same as 'copyTo' but does not range-check indices. unsafeCopyTo :: (RMatrix m, Storable e) => STMatrix s e -> m e -> ST s () unsafeCopyTo = vectorOp2 V.unsafeCopyTo {-# INLINE unsafeCopyTo #-} -- | Get the indices of the elements in the matrix, in column-major order. getIndices :: (RMatrix m, Storable e) => m e -> ST s [(Int,Int)] getIndices a = do (m,n) <- getDim a return $ [ (i,j) | j <- [ 0..n-1 ], i <- [ 0..m-1 ] ] -- | Lazily get the elements of the matrix, in column-major order. getElems :: (RMatrix m, Storable e) => m e -> ST s [e] getElems a = case maybeWithVector a V.getElems of Just es -> es Nothing -> withCols a $ \xs -> concat `fmap` mapM V.getElems xs -- | Get the elements of the matrix, in column-major order. getElems' :: (RMatrix m, Storable e) => m e -> ST s [e] getElems' a = case maybeWithVector a V.getElems' of Just es -> es Nothing -> withCols a $ \xs -> concat `fmap` mapM V.getElems' xs -- | Lazily get the association list of the matrix, in column-major order. getAssocs :: (RMatrix m, Storable e) => m e -> ST s [((Int,Int),e)] getAssocs a = do is <- getIndices a es <- getElems a return $ zip is es -- | Get the association list of the matrix, in column-major order. getAssocs' :: (RMatrix m, Storable e) => m e -> ST s [((Int,Int),e)] getAssocs' a = do is <- getIndices a es <- getElems' a return $ zip is es -- | Set all of the values of the matrix from the elements in the list, -- in column-major order. setElems :: (Storable e) => STMatrix s e -> [e] -> ST s () setElems a es = case maybeWithVectorM a (`V.setElems` es) of Just st -> st Nothing -> do (m,n) <- getDim a go m n 0 es where go _ n j [] | j == n = return () go m n j [] | j < n = error $ printf ("setElems <matrix with dim (%d,%d>" ++ "<list with length %d>: not enough elements)") m n (j*m) go m n j es' = let (es1', es2') = splitAt m es' in do withColM a j (`V.setElems` es1') go m n (j+1) es2' -- | Set the given values in the matrix. If an index is repeated twice, -- the value is implementation-defined. setAssocs :: (Storable e) => STMatrix s e -> [((Int,Int),e)] -> ST s () setAssocs a ies = sequence_ [ write a i e | (i,e) <- ies ] -- | Same as 'setAssocs' but does not range-check indices. unsafeSetAssocs :: (Storable e) => STMatrix s e -> [((Int,Int),e)] -> ST s () unsafeSetAssocs a ies = sequence_ [ unsafeWrite a i e | (i,e) <- ies ] -- | Set the specified row of the matrix to the given vector. setRow :: (RVector v, Storable e) => STMatrix s e -> Int -> v e -> ST s () setRow a i x = do (m,n) <- getDim a nx <- V.getDim x when (i < 0 || i >= m) $ error $ printf ("setRow <matrix with dim (%d,%d)> %d:" ++ " index out of range") m n i when (nx /= n) $ error $ printf ("setRow <matrix with dim (%d,%d)> _" ++ " <vector with dim %d>:" ++ " dimension mismatch") m n nx unsafeSetRow a i x {-# INLINE setRow #-} -- | Same as 'setRow' but does not range-check index or check -- vector dimension. unsafeSetRow :: (RVector v, Storable e) => STMatrix s e -> Int -> v e -> ST s () unsafeSetRow a i x = do jes <- V.getAssocs x sequence_ [ unsafeWrite a (i,j) e | (j,e) <- jes ] {-# INLINE unsafeSetRow #-} -- | Exchange corresponding elements in the given rows. swapRows :: (BLAS1 e) => STMatrix s e -> Int -> Int -> ST s () swapRows a i1 i2 = do (m,n) <- getDim a when (i1 < 0 || i1 >= m || i2 < 0 || i2 >= m) $ error $ printf ("swapRows <matrix with dim (%d,%d)> %d %d" ++ ": index out of range") m n i1 i2 unsafeSwapRows a i1 i2 -- | Same as 'swapRows' but does not range-check indices. unsafeSwapRows :: (BLAS1 e) => STMatrix s e -> Int -> Int -> ST s () unsafeSwapRows a i1 i2 = when (i1 /= i2) $ do (_,n) <- getDim a unsafeIOToST $ unsafeWith a $ \pa lda -> let px = pa `advancePtr` i1 py = pa `advancePtr` i2 incx = lda incy = lda in BLAS.swap n px incx py incy -- | Exchange corresponding elements in the given columns. swapCols :: (BLAS1 e) => STMatrix s e -> Int -> Int -> ST s () swapCols a j1 j2 = do (m,n) <- getDim a when (j1 < 0 || j1 >= n || j2 < 0 || j2 >= n) $ error $ printf ("swapCols <matrix with dim (%d,%d)> %d %d" ++ ": index out of range") m n j1 j2 unsafeSwapCols a j1 j2 -- | Same as 'swapCols' but does not range-check indices. unsafeSwapCols :: (BLAS1 e) => STMatrix s e -> Int -> Int -> ST s () unsafeSwapCols a j1 j2 = when (j1 /= j2) $ do (m,_) <- getDim a unsafeIOToST $ unsafeWith a $ \pa lda -> let px = pa `advancePtr` (j1*lda) py = pa `advancePtr` (j2*lda) incx = 1 incy = 1 in BLAS.swap m px incx py incy -- | Copy the specified row of the matrix to the vector. rowTo :: (RMatrix m, Storable e) => STVector s e -> m e -> Int -> ST s () rowTo x a i = do (m,n) <- getDim a nx <- V.getDim x when (i < 0 || i >= m) $ error $ printf ("rowTo" ++ " _" ++ " <matrix with dim (%d,%d)>" ++ " %d:" ++ ": index out of range" ) m n i when (nx /= n) $ error $ printf ("rowTo" ++ " <vector with dim %d>" ++ " <matrix with dim (%d,%d)>" ++ " _" ++ ": dimension mismatch") nx m n unsafeRowTo x a i {-# INLINE rowTo #-} -- | Same as 'rowTo' but does not range-check index or check dimension. unsafeRowTo :: (RMatrix m, Storable e) => STVector s e -> m e -> Int ->ST s () unsafeRowTo x a i = do (_,n) <- getDim a forM_ [ 0..n-1 ] $ \j -> do e <- unsafeRead a (i,j) V.unsafeWrite x j e {-# INLINE unsafeRowTo #-} -- | Set the diagonal of the matrix to the given vector. setDiag :: (RVector v, Storable e) => STMatrix s e -> v e -> ST s () setDiag a x = do (m,n) <- getDim a nx <- V.getDim x let mn = min m n when (nx /= mn) $ error $ printf ("setRow <matrix with dim (%d,%d)>" ++ " <vector with dim %d>:" ++ " dimension mismatch") m n nx unsafeSetDiag a x {-# INLINE setDiag #-} -- | Same as 'setDiag' but does not range-check index or check dimension. unsafeSetDiag :: (RVector v, Storable e) => STMatrix s e -> v e -> ST s () unsafeSetDiag a x = do ies <- V.getAssocs x sequence_ [ unsafeWrite a (i,i) e | (i,e) <- ies ] {-# INLINE unsafeSetDiag #-} -- | Copy the diagonal of the matrix to the vector. diagTo :: (RMatrix m, Storable e) => STVector s e -> m e -> ST s () diagTo x a = do nx <- V.getDim x (m,n) <- getDim a let mn = min m n when (nx /= mn) $ error $ printf ("diagTo" ++ " <vector with dim %d>" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") nx m n unsafeDiagTo x a {-# INLINE diagTo #-} -- | Same as 'diagTo' but does not range-check index or check dimensions. unsafeDiagTo :: (RMatrix m, Storable e) => STVector s e -> m e -> ST s () unsafeDiagTo x a = do (m,n) <- getDim a let mn = min m n forM_ [ 0..mn-1 ] $ \i -> do e <- unsafeRead a (i,i) V.unsafeWrite x i e {-# INLINE unsafeDiagTo #-} -- | Get the element stored at the given index. read :: (RMatrix m, Storable e) => m e -> (Int,Int) -> ST s e read a (i,j) = do (m,n) <- getDim a when (i < 0 || i >= m || j < 0 || j >= n) $ error $ printf ("read <matrix with dim (%d,%d)> (%d,%d):" ++ " index out of range") m n i j unsafeRead a (i,j) {-# INLINE read #-} -- | Same as 'read' but does not range-check index. unsafeRead :: (RMatrix m, Storable e) => m e -> (Int,Int) -> ST s e unsafeRead a (i,j) = unsafeIOToST $ unsafeWith a $ \p lda -> peekElemOff p (i + j * lda) {-# INLINE unsafeRead #-} -- | Set the element stored at the given index. write :: (Storable e) => STMatrix s e -> (Int,Int) -> e -> ST s () write a (i,j) e = do (m,n) <- getDim a when (i < 0 || i >= m || j < 0 || j >= n) $ error $ printf ("write <matrix with dim (%d,%d)> (%d,%d):" ++ " index out of range") m n i j unsafeWrite a (i,j) e {-# INLINE write #-} -- | Same as 'write' but does not range-check index. unsafeWrite :: (Storable e) => STMatrix s e -> (Int,Int) -> e -> ST s () unsafeWrite a (i,j) e = unsafeIOToST $ unsafeWith a $ \p lda -> pokeElemOff p (i + j * lda) e {-# INLINE unsafeWrite #-} -- | Modify the element stored at the given index. modify :: (Storable e) => STMatrix s e -> (Int,Int) -> (e -> e) -> ST s () modify a (i,j) f = do (m,n) <- getDim a when (i < 0 || i >= m || j < 0 || j >= n) $ error $ printf ("modify <matrix with dim (%d,%d)> (%d,%d):" ++ " index out of range") m n i j unsafeModify a (i,j) f {-# INLINE modify #-} -- | Same as 'modify' but does not range-check index. unsafeModify :: (Storable e) => STMatrix s e -> (Int,Int) -> (e -> e) -> ST s () unsafeModify a (i,j) f = unsafeIOToST $ unsafeWith a $ \p lda -> let o = i + j * lda in do e <- peekElemOff p o pokeElemOff p o $ f e {-# INLINE unsafeModify #-} -- | @mapTo dst f src@ replaces @dst@ elementwise with @f(src)@. mapTo :: (RMatrix m, Storable e, Storable f) => STMatrix s f -> (e -> f) -> m e -> ST s () mapTo dst f src = (checkOp2 "mapTo _" $ \z x -> unsafeMapTo z f x) dst src {-# INLINE mapTo #-} -- | Same as 'mapTo' but does not check dimensions. unsafeMapTo :: (RMatrix m, Storable e, Storable f) => STMatrix s f -> (e -> f) -> m e -> ST s () unsafeMapTo dst f src = fromMaybe colwise $ maybeWithVectorM dst $ \vdst -> fromMaybe colwise $ maybeWithVector src $ \vsrc -> V.unsafeMapTo vdst f vsrc where colwise = withColsM dst $ \zs -> withCols src $ \xs -> sequence_ [ V.unsafeMapTo z f x | (z,x) <- zip zs xs ] -- | @zipWithTo dst f x y@ replaces @dst@ elementwise with @f(x, y)@. zipWithTo :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f) => STMatrix s f -> (e1 -> e2 -> f) -> m1 e1 -> m2 e2 -> ST s () zipWithTo dst f x y = (checkOp3 "zipWithTo _" $ \dst1 x1 y1 -> unsafeZipWithTo dst1 f x1 y1) dst x y {-# INLINE zipWithTo #-} -- | Same as 'zipWithTo' but does not check dimensions. unsafeZipWithTo :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f) => STMatrix s f -> (e1 -> e2 -> f) -> m1 e1 -> m2 e2 -> ST s () unsafeZipWithTo dst f x y = fromMaybe colwise $ maybeWithVectorM dst $ \vdst -> fromMaybe colwise $ maybeWithVector x $ \vx -> fromMaybe colwise $ maybeWithVector y $ \vy -> V.unsafeZipWithTo vdst f vx vy where colwise = withColsM dst $ \vdsts -> withCols x $ \vxs -> withCols y $ \vys -> sequence_ [ V.unsafeZipWithTo vdst f vx vy | (vdst,vx,vy) <- zip3 vdsts vxs vys ] -- | Set every element in the matrix to a default value. For -- standard numeric types (including 'Double', 'Complex Double', and 'Int'), -- the default value is '0'. clear :: (Storable e) => STMatrix s e -> ST s () clear a = fromMaybe colwise $ maybeWithVectorM a V.clear where colwise = withColsM a $ mapM_ V.clear -- | @withSlice (i,j) (m,n) a@ performs an action with a view of the -- submatrix of @a@ starting at index @(i,j)@ and having dimension @(m,n)@. withSlice :: (RMatrix m, Storable e) => (Int,Int) -> (Int,Int) -> m e -> (forall m'. RMatrix m' => m' e -> ST s a) -> ST s a withSlice ij mn a f = do ia <- unsafeFreeze a f $ slice ij mn ia -- | Like 'withSlice', but perform the action with a mutable view. withSliceM :: (Storable e) => (Int,Int) -> (Int,Int) -> STMatrix s e -> (STMatrix s e -> ST s a) -> ST s a withSliceM ij mn a f = withSlice ij mn a $ \a' -> do ma <- unsafeThaw a' f ma -- | Perform an action with a view gotten from taking the given number of -- rows from the start of the matrix. withTakeRows :: (RMatrix m, Storable e) => Int -> m e -> (forall m'. RMatrix m' => m' e -> ST s a) -> ST s a withTakeRows i a f = do ia <- unsafeFreeze a f $ takeRows i ia -- | Like 'withTakeRows', but perform the action with a mutable view. withTakeRowsM :: (Storable e) => Int -> STMatrix s e -> (STMatrix s e -> ST s a) -> ST s a withTakeRowsM i a f = withTakeRows i a $ \a' -> do ma <- unsafeThaw a' f ma -- | Perform an action with a view gotten from dropping the given number of -- rows from the start of the matrix. withDropRows :: (RMatrix m, Storable e) => Int -> m e -> (forall m'. RMatrix m' => m' e -> ST s a) -> ST s a withDropRows n a f = do ia <- unsafeFreeze a f $ dropRows n ia -- | Like 'withDropRows', but perform the action with a mutable view. withDropRowsM :: (Storable e) => Int -> STMatrix s e -> (STMatrix s e -> ST s a) -> ST s a withDropRowsM i a f = withDropRows i a $ \a' -> do ma <- unsafeThaw a' f ma -- | Perform an action with views from splitting the matrix rows at the given -- index. withSplitRowsAt :: (RMatrix m, Storable e) => Int -> m e -> (forall m1 m2. (RMatrix m1, RMatrix m2) => m1 e -> m2 e -> ST s a) -> ST s a withSplitRowsAt i a f = do ia <- unsafeFreeze a uncurry f $ splitRowsAt i ia -- | Like 'withSplitRowsAt', but perform the action with a mutable view. withSplitRowsAtM :: (Storable e) => Int -> STMatrix s e -> (STMatrix s e -> STMatrix s e -> ST s a) -> ST s a withSplitRowsAtM i a f = withSplitRowsAt i a $ \a1' a2' -> do ma1 <- unsafeThaw a1' ma2 <- unsafeThaw a2' f ma1 ma2 -- | Perform an action with a view gotten from taking the given number of -- columns from the start of the matrix. withTakeCols :: (RMatrix m, Storable e) => Int -> m e -> (forall m'. RMatrix m' => m' e -> ST s a) -> ST s a withTakeCols i a f = do ia <- unsafeFreeze a f $ takeCols i ia -- | Like 'withTakeCols', but perform the action with a mutable view. withTakeColsM :: (Storable e) => Int -> STMatrix s e -> (STMatrix s e -> ST s a) -> ST s a withTakeColsM i a f = withTakeCols i a $ \a' -> do ma <- unsafeThaw a' f ma -- | Perform an action with a view gotten from dropping the given number of -- columns from the start of the matrix. withDropCols :: (RMatrix m, Storable e) => Int -> m e -> (forall m'. RMatrix m' => m' e -> ST s a) -> ST s a withDropCols n a f = do ia <- unsafeFreeze a f $ dropCols n ia -- | Like 'withDropCols', but perform the action with a mutable view. withDropColsM :: (Storable e) => Int -> STMatrix s e -> (STMatrix s e -> ST s a) -> ST s a withDropColsM i a f = withDropCols i a $ \a' -> do ma <- unsafeThaw a' f ma -- | Perform an action with views from splitting the matrix columns at the given -- index. withSplitColsAt :: (RMatrix m, Storable e) => Int -> m e -> (forall m1 m2. (RMatrix m1, RMatrix m2) => m1 e -> m2 e -> ST s a) -> ST s a withSplitColsAt i a f = do ia <- unsafeFreeze a uncurry f $ splitColsAt i ia -- | Like 'withSplitColsAt', but perform the action with mutable views. withSplitColsAtM :: (Storable e) => Int -> STMatrix s e -> (STMatrix s e -> STMatrix s e -> ST s a) -> ST s a withSplitColsAtM i a f = withSplitColsAt i a $ \a1' a2' -> do ma1 <- unsafeThaw a1' ma2 <- unsafeThaw a2' f ma1 ma2 -- | Add a vector to the diagonal of a matrix. shiftDiagM_ :: (RVector v, BLAS1 e) => v e -> STMatrix s e -> ST s () shiftDiagM_ s a = do (m,n) <- getDim a ns <- V.getDim s let mn = min m n when (ns /= mn) $ error $ printf ("shiftDiagM_" ++ " <vector with dim %d>" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") ns m n shiftDiagWithScaleM_ 1 s a -- | Add a scaled vector to the diagonal of a matrix. shiftDiagWithScaleM_ :: (RVector v, BLAS1 e) => e -> v e -> STMatrix s e -> ST s () shiftDiagWithScaleM_ e s a = do (m,n) <- getDim a ns <- V.getDim s let mn = min m n when (ns /= mn) $ error $ printf ("shiftDiagWithScaleM_" ++ " _" ++ " <vector with dim %d>" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") ns m n unsafeIOToST $ V.unsafeWith s $ \ps -> unsafeWith a $ \pa lda -> BLAS.axpy mn e ps 1 pa (lda+1) -- | Add two matrices. addTo :: (RMatrix m1, RMatrix m2, VNum e) => STMatrix s e -> m1 e -> m2 e -> ST s () addTo = checkOp3 "addTo" $ vectorOp3 V.addTo -- | Subtract two matrices. subTo :: (RMatrix m1, RMatrix m2, VNum e) => STMatrix s e -> m1 e -> m2 e -> ST s () subTo = checkOp3 "subTo" $ vectorOp3 V.subTo -- | Conjugate the entries of a matrix. conjugateTo :: (RMatrix m, VNum e) => STMatrix s e -> m e -> ST s () conjugateTo = checkOp2 "conjugateTo" $ vectorOp2 V.conjugateTo -- | Negate the entries of a matrix. negateTo :: (RMatrix m, VNum e) => STMatrix s e -> m e -> ST s () negateTo = checkOp2 "negateTo" $ vectorOp2 V.negateTo -- | Scale the entries of a matrix by the given value. scaleM_ :: (BLAS1 e) => e -> STMatrix s e -> ST s () scaleM_ e = vectorOp (V.scaleM_ e) -- | @addWithScaleM_ alpha x y@ sets @y := alpha * x + y@. addWithScaleM_ :: (RMatrix m, BLAS1 e) => e -> m e -> STMatrix s e -> ST s () addWithScaleM_ e = checkOp2 "addWithScaleM_" $ unsafeAddWithScaleM_ e unsafeAddWithScaleM_ :: (RMatrix m, BLAS1 e) => e -> m e -> STMatrix s e -> ST s () unsafeAddWithScaleM_ alpha x y = fromMaybe colwise $ maybeWithVector x $ \vx -> fromMaybe colwise $ maybeWithVectorM y $ \vy -> V.unsafeAddWithScaleM_ alpha vx vy where colwise = withCols x $ \vxs -> withColsM y $ \vys -> sequence_ [ V.unsafeAddWithScaleM_ alpha vx vy | (vx,vy) <- zip vxs vys ] -- | Scale the rows of a matrix; @scaleRowsM_ s a@ sets -- @a := diag(s) * a@. scaleRowsM_ :: (RVector v, BLAS1 e) => v e -> STMatrix s e -> ST s () scaleRowsM_ s a = do (m,n) <- getDim a ns <- V.getDim s when (ns /= m) $ error $ printf ("scaleRowsM_" ++ " <vector with dim %d>" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") ns m n unsafeIOToST $ V.unsafeWith s $ \ps -> unsafeWith a $ \pa lda -> go m n lda pa ps 0 where go m n lda pa ps i | i == m = return () | otherwise = do e <- peek ps BLAS.scal n e pa lda go m n lda (pa `advancePtr` 1) (ps `advancePtr` 1) (i+1) -- | Scale the columns of a matrix; @scaleColBysM_ s a@ sets -- @a := a * diag(s)@. scaleColsM_ :: (RVector v, BLAS1 e) => v e -> STMatrix s e -> ST s () scaleColsM_ s a = do (m,n) <- getDim a ns <- V.getDim s when (ns /= n) $ error $ printf ("scaleColsM_" ++ " <vector with dim %d>" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") ns m n es <- V.getElems s withColsM a $ \xs -> sequence_ [ V.scaleM_ e x | (e,x) <- zip es xs ] -- | @rank1UpdateM_ alpha x y a@ sets @a := alpha * x * y^H + a@. rank1UpdateM_ :: (RVector v1, RVector v2, BLAS2 e) => e -> v1 e -> v2 e -> STMatrix s e -> ST s () rank1UpdateM_ alpha x y a = do (m,n) <- getDim a nx <- V.getDim x ny <- V.getDim y when (nx /= m || ny /= n) $ error $ printf ("rank1UpdateTo" ++ " _" ++ " <vector with dim %d>" ++ " <vector with dim %d>" ++ ": dimension mismatch" ++ "<matrix with dim (%d,%d)>" ) nx ny m n unsafeIOToST $ V.unsafeWith x $ \px -> V.unsafeWith y $ \py -> unsafeWith a $ \pa lda -> BLAS.gerc m n alpha px 1 py 1 pa lda -- | @transTo dst a@ sets @dst := trans(a)@. transTo :: (RMatrix m, BLAS1 e) => STMatrix s e -> m e -> ST s () transTo a' a = do (ma,na) <- getDim a (ma',na') <- getDim a' let (m,n) = (ma,na) when ((ma,na) /= (na',ma')) $ error $ printf ( "transTo" ++ " <matrix with dim (%d,%d)>" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch" ) ma' na' ma na unsafeIOToST $ unsafeWith a' $ \pa' lda' -> unsafeWith a $ \pa lda -> let go j px py | j == n = return () | otherwise = do BLAS.copy m px 1 py lda' go (j+1) (px `advancePtr` lda) (py `advancePtr` 1) in go 0 pa pa' -- | @conjTransTo dst a@ sets @dst := conjugate(trans(a))@. conjTransTo :: (RMatrix m, BLAS1 e) => STMatrix s e -> m e -> ST s () conjTransTo a' a = do transTo a' a conjugateTo a' a' -- | @mulVectorTo dst transa a x@ -- sets @dst := op(a) * x@, where @op(a)@ is determined by @transa@. mulVectorTo :: (RMatrix m, RVector v, BLAS2 e) => STVector s e -> Trans -> m e -> v e -> ST s () mulVectorTo dst = mulVectorWithScaleTo dst 1 -- | @mulVectorWithScaleTo dst alpha transa a x@ -- sets @dst := alpha * op(a) * x@, where @op(a)@ is determined by @transa@. mulVectorWithScaleTo :: (RMatrix m, RVector v, BLAS2 e) => STVector s e -> e -> Trans -> m e -> v e -> ST s () mulVectorWithScaleTo dst alpha t a x = addMulVectorWithScalesM_ alpha t a x 0 dst -- | @addMulVectorWithScalesM_ alpha transa a x beta y@ -- sets @y := alpha * op(a) * x + beta * y@, where @op(a)@ is -- determined by @transa@. addMulVectorWithScalesM_ :: (RMatrix m, RVector v, BLAS2 e) => e -> Trans -> m e -> v e -> e -> STVector s e -> ST s () addMulVectorWithScalesM_ alpha transa a x beta y = do (ma,na) <- getDim a nx <- V.getDim x ny <- V.getDim y let (m,n) = (ny,nx) when ((not . and) [ case transa of NoTrans -> (ma,na) == (m,n) _ -> (ma,na) == (n,m) , nx == n , ny == m ]) $ error $ printf ("addMulVectorWithScalesTo" ++ " _" ++ " %s" ++ " <matrix with dim (%d,%d)>" ++ " <vector with dim %d>" ++ " _" ++ " <vector with dim %d>" ++ ": dimension mismatch") (show transa) ma na nx ny unsafeIOToST $ unsafeWith a $ \pa lda -> V.unsafeWith x $ \px -> V.unsafeWith y $ \py -> if n == 0 then BLAS.scal m beta py 1 else BLAS.gemv transa ma na alpha pa lda px 1 beta py 1 -- | @mulMatrixTo dst transa a transb b@ -- sets @dst := op(a) * op(b)@, where @op(a)@ and @op(b)@ are determined -- by @transa@ and @transb@. mulMatrixTo :: (RMatrix m1, RMatrix m2, BLAS3 e) => STMatrix s e -> Trans -> m1 e -> Trans -> m2 e -> ST s () mulMatrixTo dst = mulMatrixWithScaleTo dst 1 -- | @mulMatrixWithScaleTo alpha transa a transb b c@ -- sets @c := alpha * op(a) * op(b)@, where @op(a)@ and @op(b)@ are determined -- by @transa@ and @transb@. mulMatrixWithScaleTo :: (RMatrix m1, RMatrix m2, BLAS3 e) => STMatrix s e -> e -> Trans -> m1 e -> Trans -> m2 e -> ST s () mulMatrixWithScaleTo dst alpha ta a tb b = addMulMatrixWithScalesM_ alpha ta a tb b 0 dst -- | @addMulMatrixWithScalesM_ alpha transa a transb b beta c@ -- sets @c := alpha * op(a) * op(b) + beta * c@, where @op(a)@ and -- @op(b)@ are determined by @transa@ and @transb@. addMulMatrixWithScalesM_ :: (RMatrix m1, RMatrix m2, BLAS3 e) => e -> Trans -> m1 e -> Trans -> m2 e -> e -> STMatrix s e -> ST s () addMulMatrixWithScalesM_ alpha transa a transb b beta c = do (ma,na) <- getDim a (mb,nb) <- getDim b (mc,nc) <- getDim c let (m,n) = (mc,nc) k = case transa of NoTrans -> na _ -> ma when ((not . and) [ case transa of NoTrans -> (ma,na) == (m,k) _ -> (ma,na) == (k,m) , case transb of NoTrans -> (mb,nb) == (k,n) _ -> (mb,nb) == (n,k) , (mc, nc) == (m,n) ]) $ error $ printf ("addMulMatrixWithScalesM_" ++ " _" ++ " %s <matrix with dim (%d,%d)>" ++ " %s <matrix with dim (%d,%d)>" ++ " _" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") (show transa) ma na (show transb) mb nb mc nc unsafeIOToST $ unsafeWith a $ \pa lda -> unsafeWith b $ \pb ldb -> unsafeWith c $ \pc ldc -> BLAS.gemm transa transb m n k alpha pa lda pb ldb beta pc ldc checkOp2 :: (RMatrix x, RMatrix y, Storable e, Storable f) => String -> (x e -> y f -> ST s a) -> x e -> y f -> ST s a checkOp2 str f x y = do (m1,n1) <- getDim x (m2,n2) <- getDim y when ((m1,n1) /= (m2,n2)) $ error $ printf ("%s <matrix with dim (%d,%d)> <matrix with dim (%d,%d)>:" ++ " dimension mismatch") str m1 n1 m2 n2 f x y {-# INLINE checkOp2 #-} checkOp3 :: (RMatrix x, RMatrix y, RMatrix z, Storable e, Storable f, Storable g) => String -> (x e -> y f -> z g -> ST s a) -> x e -> y f -> z g -> ST s a checkOp3 str f x y z = do (m1,n1) <- getDim x (m2,n2) <- getDim y (m3,n3) <- getDim z when((m1,n1) /= (m2,n2) || (m1,n1) /= (m3,n3)) $ error $ printf ("%s <matrix with dim (%d,%d)> <matrix with dim (%d,%d)>:" ++ " <matrix with dim (%d,%d)> dimension mismatch") str m1 n1 m2 n2 m3 n3 f x y z {-# INLINE checkOp3 #-} vectorOp :: (Storable e) => (STVector s e -> ST s ()) -> STMatrix s e -> ST s () vectorOp f x = fromMaybe colwise $ maybeWithVectorM x $ \vx -> f vx where colwise = withColsM x $ \vxs -> sequence_ [ f vx | vx <- vxs ] vectorOp2 :: (RMatrix m, Storable e, Storable f) => (forall v . RVector v => STVector s f -> v e -> ST s ()) -> STMatrix s f -> m e -> ST s () vectorOp2 f dst x = fromMaybe colwise $ maybeWithVectorM dst $ \vdst -> fromMaybe colwise $ maybeWithVector x $ \vx -> f vdst vx where colwise = withColsM dst $ \vdsts -> withCols x $ \vxs -> sequence_ [ f vdst vx | (vdst,vx) <- zip vdsts vxs ] {-# INLINE vectorOp2 #-} vectorOp3 :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f) => (forall v1 v2 . (RVector v1, RVector v2) => STVector s f -> v1 e1 -> v2 e2 -> ST s ()) -> STMatrix s f -> m1 e1 -> m2 e2 -> ST s () vectorOp3 f dst x y = fromMaybe colwise $ maybeWithVectorM dst $ \vdst -> fromMaybe colwise $ maybeWithVector x $ \vx -> fromMaybe colwise $ maybeWithVector y $ \vy -> f vdst vx vy where colwise = withColsM dst $ \vdsts -> withCols x $ \vxs -> withCols y $ \vys -> sequence_ [ f vdst vx vy | (vdst,vx,vy) <- zip3 vdsts vxs vys ] {-# INLINE vectorOp3 #-}
patperry/hs-linear-algebra
lib/Numeric/LinearAlgebra/Matrix/STBase.hs
Haskell
bsd-3-clause
41,765
module Parse.IParser where import Parse.Primitives (Parser) import Reporting.Error.Syntax (ParsecError) type IParser a = Parser ParsecError a
avh4/elm-format
elm-format-lib/src/Parse/IParser.hs
Haskell
bsd-3-clause
145
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RecordWildCards #-} module Node.T1w (T1w(..) ,rules) where import Node.Types import Node.Util (getPath, outdir, showKey) import Shake.BuildNode import Util (alignAndCenter) data T1w = T1w {t1type :: T1wType ,caseid :: CaseId} deriving (Show,Generic,Typeable,Eq,Hashable,Binary,NFData,Read) instance BuildNode T1w where path n@(T1w{..}) = case t1type of T1wGiven -> getPath "t1" caseid _ -> outdir </> caseid </> showKey n <.> "nrrd" build out@(T1w{..}) = case t1type of T1wGiven -> Nothing T1wXc -> Just $ do let t1 = T1w T1wGiven caseid need t1 alignAndCenter (path t1) (path out) rules = rule (buildNode :: T1w -> Maybe (Action [Double]))
reckbo/ppl
pipeline-lib/Node/T1w.hs
Haskell
bsd-3-clause
939
-- | Tests for automatic deriving of ann method from Annotated type class. module Language.Java.Paragon.SyntaxSpec (main, spec) where import Test.Hspec import Language.Java.Paragon.Annotation import Language.Java.Paragon.Syntax -- | To be able to run this module from GHCi. main :: IO () main = hspec spec -- | Main specification function. spec :: Spec spec = do describe "ann" $ do it "returns annotation for leaf node" $ ann (Null emptyAnnotation) `shouldBe` emptyAnnotation it "returns annotation for internal node (1 level)" $ ann (Lit (Int emptyAnnotation 2)) `shouldBe` emptyAnnotation it "returns annotation for internal node (2 levels)" $ do let wrongAnnotation = emptyAnnotation { annIsNull = False } ann (RefType (ClassRefType (ClassType emptyAnnotation (Name wrongAnnotation (Id wrongAnnotation "Object") TypeName Nothing) []))) `shouldBe` emptyAnnotation
bvdelft/paragon
test/Language/Java/Paragon/SyntaxSpec.hs
Haskell
bsd-3-clause
919
{-# LANGUAGE QuasiQuotes, TypeFamilies, PackageImports #-} import Control.Arrow import "monads-tf" Control.Monad.State import "monads-tf" Control.Monad.Error import Data.Maybe import Data.Char import System.Environment import Text.Papillon type List = [List1] data List1 = Item String List deriving Show main :: IO () main = do fn : _ <- getArgs cnt <- readFile fn print $ parseList cnt parseList :: String -> Maybe List parseList src = case flip runState (0, [-1]) $ runErrorT $ list $ parse src of (Right (r, _), _) -> Just r _ -> Nothing checkState :: String -> Maybe (Int, [Int]) checkState src = case flip runState (0, [-1]) $ runErrorT $ list $ parse src of (_, s) -> Just s reset :: State (Int, [Int]) Bool reset = modify (first $ const 0) >> return True cntSpace :: State (Int, [Int]) () cntSpace = modify $ first (+ 1) deeper :: State (Int, [Int]) Bool deeper = do (n, n0 : ns) <- get if n > n0 then put (n, n : n0 : ns) >> return True else return False same :: State (Int, [Int]) Bool same = do (n, n0 : _) <- get return $ n == n0 shallow :: State (Int, [Int]) Bool shallow = do (n, n0 : ns) <- get if n < n0 then put (n, ns) >> return True else return False [papillon| monad: State (Int, [Int]) list :: List = _:countSpace _:dmmy[deeper] l:list1 ls:list1'* _:shllw { return $ l : ls } list1' :: List1 = _:countSpace _:dmmy[same] l:list1 { return l } list1 :: List1 = '*' ' ' l:line '\n' ls:list? { return $ Item l $ fromMaybe [] ls } line :: String = l:<isLower>+ { return l } countSpace :: () = _:dmmy[reset] _:(' ' { cntSpace })* shllw :: () = _:dmmy[shallow] / !_ dmmy :: () = |]
YoshikuniJujo/markdown2svg
tests/testParser.hs
Haskell
bsd-3-clause
1,644
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TemplateHaskell #-} module DataLayer ( KeyValue (..) , insert , find ) where import Control.Monad.Reader import Control.Monad.State import Data.Acid import Data.SafeCopy import Data.Typeable import qualified Data.Map as Map import qualified Data.Text.Lazy as T type Key = T.Text type Url = T.Text data KeyValue = KeyValue !(Map.Map Key Url) deriving (Typeable, Show) $(deriveSafeCopy 0 'base ''KeyValue) insertKey :: Key -> Url -> Update KeyValue () insertKey key value = do KeyValue m <- get put (KeyValue (Map.insert key value m)) lookupKey :: Key -> Query KeyValue (Maybe Url) lookupKey key = do KeyValue m <- ask return (Map.lookup key m) $(makeAcidic ''KeyValue ['insertKey, 'lookupKey]) insert :: AcidState KeyValue -> Key -> Url -> IO () insert acid key value = update acid (InsertKey key value) find :: AcidState KeyValue -> Key -> IO (Maybe T.Text) find acid key = query acid (LookupKey key)
wavelets/9m
src/DataLayer.hs
Haskell
bsd-3-clause
1,050
module Ribbon where import Rumpus -- Devin Chalmers remix start :: Start start = do parentID <- ask addActiveKnob "Total Speed" (Linear -5 5) 1 setClockSpeed rotSpeedKnob <- addKnob "Rot Speed" (Linear 0 5) 1 yScaleKnob <- addKnob "YScale" (Linear 0 10) 1 zScaleKnob <- addKnob "ZScale" (Linear 0.1 10) 1 forM_ [0..100] $ \i -> spawnChild $ do myShape ==> Sphere myTransformType ==> AbsolutePose myUpdate ==> do now <- getEntityClockTime parentID rotSpeed <- readKnob rotSpeedKnob yScale <- readKnob yScaleKnob zScale <- readKnob zScaleKnob let n = now + (i * 0.5) y = yScale * tan n/2 x = sin n * 5 setPositionRotationSize (V3 x y (-10)) (axisAngle (V3 1 0 1) (n*rotSpeed)) (V3 9 0.1 (sin n * zScale)) setColor (colorHSL (n*0.1) 0.8 0.6)
lukexi/rumpus
pristine/Ribbon/RibbonRemix.hs
Haskell
bsd-3-clause
989
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} module Karamaan.Opaleye.TableColspec where import Karamaan.Opaleye.Wire (Wire(Wire)) import Karamaan.Opaleye.QueryColspec (QueryColspec(QueryColspec), runWriterOfQueryColspec, runPackMapOfQueryColspec, MWriter(Writer), PackMap(PackMap)) import Control.Applicative (Applicative, pure, (<*>)) import Data.Profunctor.Product.Default (Default, def) import Data.Profunctor (Profunctor, dimap, lmap, rmap) import Data.Profunctor.Product (ProductProfunctor, empty, (***!), defaultEmpty, defaultProfunctorProduct) -- TODO: this happens to have the same implementation as QueryColspec, but I -- don't want to suggest that one derives from the other. Perhaps make this -- clearer by introducing another type from which they both inherit their -- implementation. newtype TableColspecP a b = TableColspecP (QueryColspec a b) -- TODO: we don't actually need TableColspec anymore. It's just a partially -- applied TableColspecP. We should unpick its usage from makeTable replacing -- it with TableColspecP, and then delete its definition. newtype TableColspec b = TableColspec (TableColspecP () b) tableColspecOfTableColspecP :: TableColspecP a b -> a -> TableColspec b tableColspecOfTableColspecP q a = TableColspec (lmap (const a) q) instance Functor (TableColspecP a) where fmap f (TableColspecP c) = TableColspecP (fmap f c) instance Applicative (TableColspecP a) where pure = TableColspecP . pure TableColspecP f <*> TableColspecP x = TableColspecP (f <*> x) instance Functor TableColspec where fmap f (TableColspec c) = TableColspec (rmap f c) instance Applicative TableColspec where pure = TableColspec . pure TableColspec f <*> TableColspec x = TableColspec (f <*> x) instance Profunctor TableColspecP where dimap f g (TableColspecP q) = TableColspecP (dimap f g q) instance ProductProfunctor TableColspecP where empty = defaultEmpty (***!) = defaultProfunctorProduct instance Default TableColspecP (Wire a) (Wire a) where def = TableColspecP def runWriterOfColspec :: TableColspec a -> [String] runWriterOfColspec (TableColspec (TableColspecP c)) = runWriterOfQueryColspec c () runPackMapOfColspec :: TableColspec a -> (String -> String) -> a runPackMapOfColspec (TableColspec (TableColspecP c)) f = runPackMapOfQueryColspec c f () -- TODO: this implementation is verbose colspec :: [String] -> ((String -> String) -> a) -> TableColspec a colspec w p = TableColspec (TableColspecP (QueryColspec (Writer (const w)) (PackMap (\f () -> p f)))) col :: String -> TableColspec (Wire a) col s = colspec [s] (\f -> Wire (f s)) newtype WireMaker a b = WireMaker (a -> b) runWireMaker :: WireMaker a b -> a -> b runWireMaker (WireMaker f) = f wireCol :: WireMaker String (Wire a) wireCol = WireMaker Wire instance Functor (WireMaker a) where fmap f (WireMaker g) = WireMaker (fmap f g) instance Applicative (WireMaker a) where pure = WireMaker . pure WireMaker f <*> WireMaker x = WireMaker (f <*> x) instance Profunctor WireMaker where dimap f g (WireMaker q) = WireMaker (dimap f g q) instance ProductProfunctor WireMaker where empty = defaultEmpty (***!) = defaultProfunctorProduct instance Default WireMaker String (Wire a) where def = WireMaker Wire
dbp/karamaan-opaleye
Karamaan/Opaleye/TableColspec.hs
Haskell
bsd-3-clause
3,476
module Math.Simplicial.NeighborhoodGraph where import qualified Data.Vector.Unboxed as UV import qualified Data.Vector as BV import qualified Math.VectorSpaces.Metric as Met import qualified Math.Simplicial.LandmarkSelection as LS import qualified Math.Misc.Matrix as Mat import qualified Math.VectorSpaces.DistanceMatrix as DMat import Math.Simplicial.PreScale import Math.Cloud.Cloud import Data.List import Misc.Misc data NeighborhoodGraph = C Int -- Number of nodes. Double -- Maximum scale. DMat.RealDistanceMatrix -- Edge weights. DMat.BooleanDistanceMatrix -- Edge table. exact :: (Met.Metric a) => Cloud a -> PreScale -> NeighborhoodGraph exact _ (ConditionFactor _) = error "Exact neighborhood graphs only available with absolute maximum scale." exact c (Absolute scale) = C n scale ws es where c' = BV.fromList c n = BV.length c' ws = DMat.generate n (\ (i,j) -> Met.distance (c' BV.! i) (c' BV.! j)) es = DMat.map (<= scale) ws -- | Follows de Silva, Carlsson: Topological estimation using witness complexes. lazyWitness :: (Met.Metric a) => LS.LandmarkSelection a -> Int -> PreScale -> NeighborhoodGraph lazyWitness ls nu preScale = C nl scale weights edges where scale = case preScale of Absolute s -> s ConditionFactor c -> c * (UV.maximum (UV.generate nw (Mat.rowMinimum d))) witnesses = LS.witnesses ls landmarks = LS.landmarks ls d = LS.witnessToLandmarkDistances ls m = if nu <= 0 then UV.replicate nw 0.0 else UV.generate nw (\i -> smallest' nu (UV.toList (d `Mat.row` i))) nl = LS.numLandmarks ls nw = LS.numWitnesses ls weights = DMat.generate nl weight edges = DMat.map (<= scale) weights weight :: (Int, Int) -> Double weight (i, j) = UV.minimum (UV.generate nw (witnessWeight (i,j))) witnessWeight :: (Int, Int) -> Int -> Double witnessWeight (i, j) k = max 0 (dMax - m UV.! k) where dMax = max (d Mat.! (k,i)) (d Mat.! (k,j)) weight :: NeighborhoodGraph -> Int -> Int -> Double weight (C _ _ ws _) i j = ws DMat.? (i, j) edge :: NeighborhoodGraph -> Int -> Int -> Bool edge (C _ _ _ es) i j = es DMat.? (i, j) weight' :: NeighborhoodGraph -> (Int, Int) -> Double weight' g = uncurry (weight g) numVertices :: NeighborhoodGraph -> Int numVertices (C n _ _ _) = n vertices :: NeighborhoodGraph -> [Int] vertices g = [0..(numVertices g - 1)] edges :: NeighborhoodGraph -> [(Int, Int)] edges g = go (vertices g) where go [] = [] go (i:is) = zip (repeat i) (filter (edge g i) is) ++ go is scale :: NeighborhoodGraph -> Double scale (C _ s _ _) = s
michiexile/hplex
pershom/src/Math/Simplicial/NeighborhoodGraph.hs
Haskell
bsd-3-clause
2,787
{-# LANGUAGE CPP, GADTs #-} ----------------------------------------------------------------------------- -- -- Pretty-printing of Cmm as C, suitable for feeding gcc -- -- (c) The University of Glasgow 2004-2006 -- -- Print Cmm as real C, for -fvia-C -- -- See wiki:Commentary/Compiler/Backends/PprC -- -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded" -- relative to the old AbstractC, and many oddities/decorations have -- disappeared from the data type. -- -- This code generator is only supported in unregisterised mode. -- ----------------------------------------------------------------------------- module PprC ( writeCs, pprStringInCStyle ) where #include "HsVersions.h" -- Cmm stuff import BlockId import CLabel import ForeignCall import Cmm hiding (pprBBlock) import PprCmm () import Hoopl import CmmUtils import CmmSwitch -- Utils import CPrim import DynFlags import FastString import Outputable import Platform import UniqSet import Unique import Util -- The rest import Control.Monad.ST import Data.Bits import Data.Char import Data.List import Data.Map (Map) import Data.Word import System.IO import qualified Data.Map as Map import Control.Monad (liftM, ap) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative (Applicative(..)) #endif import qualified Data.Array.Unsafe as U ( castSTUArray ) import Data.Array.ST -- -------------------------------------------------------------------------- -- Top level pprCs :: DynFlags -> [RawCmmGroup] -> SDoc pprCs dflags cmms = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms) where split_marker | gopt Opt_SplitObjs dflags = text "__STG_SPLIT_MARKER" | otherwise = empty writeCs :: DynFlags -> Handle -> [RawCmmGroup] -> IO () writeCs dflags handle cmms = printForC dflags handle (pprCs dflags cmms) -- -------------------------------------------------------------------------- -- Now do some real work -- -- for fun, we could call cmmToCmm over the tops... -- pprC :: RawCmmGroup -> SDoc pprC tops = vcat $ intersperse blankLine $ map pprTop tops -- -- top level procs -- pprTop :: RawCmmDecl -> SDoc pprTop (CmmProc infos clbl _ graph) = (case mapLookup (g_entry graph) infos of Nothing -> empty Just (Statics info_clbl info_dat) -> pprDataExterns info_dat $$ pprWordArray info_clbl info_dat) $$ (vcat [ blankLine, extern_decls, (if (externallyVisibleCLabel clbl) then mkFN_ else mkIF_) (ppr clbl) <+> lbrace, nest 8 temp_decls, vcat (map pprBBlock blocks), rbrace ] ) where blocks = toBlockListEntryFirst graph (temp_decls, extern_decls) = pprTempAndExternDecls blocks -- Chunks of static data. -- We only handle (a) arrays of word-sized things and (b) strings. pprTop (CmmData _section (Statics lbl [CmmString str])) = hcat [ pprLocalness lbl, text "char ", ppr lbl, text "[] = ", pprStringInCStyle str, semi ] pprTop (CmmData _section (Statics lbl [CmmUninitialised size])) = hcat [ pprLocalness lbl, text "char ", ppr lbl, brackets (int size), semi ] pprTop (CmmData _section (Statics lbl lits)) = pprDataExterns lits $$ pprWordArray lbl lits -- -------------------------------------------------------------------------- -- BasicBlocks are self-contained entities: they always end in a jump. -- -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn -- as many jumps as possible into fall throughs. -- pprBBlock :: CmmBlock -> SDoc pprBBlock block = nest 4 (pprBlockId (entryLabel block) <> colon) $$ nest 8 (vcat (map pprStmt (blockToList nodes)) $$ pprStmt last) where (_, nodes, last) = blockSplit block -- -------------------------------------------------------------------------- -- Info tables. Just arrays of words. -- See codeGen/ClosureInfo, and nativeGen/PprMach pprWordArray :: CLabel -> [CmmStatic] -> SDoc pprWordArray lbl ds = sdocWithDynFlags $ \dflags -> hcat [ pprLocalness lbl, text "StgWord" , space, ppr lbl, text "[]" -- See Note [StgWord alignment] , pprAlignment (wordWidth dflags) , text "= {" ] $$ nest 8 (commafy (pprStatics dflags ds)) $$ text "};" pprAlignment :: Width -> SDoc pprAlignment words = text "__attribute__((aligned(" <> int (widthInBytes words) <> text ")))" -- Note [StgWord alignment] -- C codegen builds static closures as StgWord C arrays (pprWordArray). -- Their real C type is 'StgClosure'. Macros like UNTAG_CLOSURE assume -- pointers to 'StgClosure' are aligned at pointer size boundary: -- 4 byte boundary on 32 systems -- and 8 bytes on 64-bit systems -- see TAG_MASK and TAG_BITS definition and usage. -- -- It's a reasonable assumption also known as natural alignment. -- Although some architectures have different alignment rules. -- One of known exceptions is m68k (Trac #11395, comment:16) where: -- __alignof__(StgWord) == 2, sizeof(StgWord) == 4 -- -- Thus we explicitly increase alignment by using -- __attribute__((aligned(4))) -- declaration. -- -- has to be static, if it isn't globally visible -- pprLocalness :: CLabel -> SDoc pprLocalness lbl | not $ externallyVisibleCLabel lbl = text "static " | otherwise = empty -- -------------------------------------------------------------------------- -- Statements. -- pprStmt :: CmmNode e x -> SDoc pprStmt stmt = sdocWithDynFlags $ \dflags -> case stmt of CmmEntry{} -> empty CmmComment _ -> empty -- (hang (text "/*") 3 (ftext s)) $$ ptext (sLit "*/") -- XXX if the string contains "*/", we need to fix it -- XXX we probably want to emit these comments when -- some debugging option is on. They can get quite -- large. CmmTick _ -> empty CmmUnwind{} -> empty CmmAssign dest src -> pprAssign dflags dest src CmmStore dest src | typeWidth rep == W64 && wordWidth dflags /= W64 -> (if isFloatType rep then text "ASSIGN_DBL" else ptext (sLit ("ASSIGN_Word64"))) <> parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi | otherwise -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ] where rep = cmmExprType dflags src CmmUnsafeForeignCall target@(ForeignTarget fn conv) results args -> fnCall where (res_hints, arg_hints) = foreignTargetHints target hresults = zip results res_hints hargs = zip args arg_hints ForeignConvention cconv _ _ ret = conv cast_fn = parens (cCast (pprCFunType (char '*') cconv hresults hargs) fn) -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes fnCall = case fn of CmmLit (CmmLabel lbl) | StdCallConv <- cconv -> pprCall (ppr lbl) cconv hresults hargs -- stdcall functions must be declared with -- a function type, otherwise the C compiler -- doesn't add the @n suffix to the label. We -- can't add the @n suffix ourselves, because -- it isn't valid C. | CmmNeverReturns <- ret -> pprCall cast_fn cconv hresults hargs <> semi | not (isMathFun lbl) -> pprForeignCall (ppr lbl) cconv hresults hargs _ -> pprCall cast_fn cconv hresults hargs <> semi -- for a dynamic call, no declaration is necessary. CmmUnsafeForeignCall (PrimTarget MO_Touch) _results _args -> empty CmmUnsafeForeignCall (PrimTarget (MO_Prefetch_Data _)) _results _args -> empty CmmUnsafeForeignCall target@(PrimTarget op) results args -> fn_call where cconv = CCallConv fn = pprCallishMachOp_for_C op (res_hints, arg_hints) = foreignTargetHints target hresults = zip results res_hints hargs = zip args arg_hints fn_call -- The mem primops carry an extra alignment arg. -- We could maybe emit an alignment directive using this info. -- We also need to cast mem primops to prevent conflicts with GCC -- builtins (see bug #5967). | Just _align <- machOpMemcpyishAlign op = (text ";EFF_(" <> fn <> char ')' <> semi) $$ pprForeignCall fn cconv hresults hargs | otherwise = pprCall fn cconv hresults hargs CmmBranch ident -> pprBranch ident CmmCondBranch expr yes no _ -> pprCondBranch expr yes no CmmCall { cml_target = expr } -> mkJMP_ (pprExpr expr) <> semi CmmSwitch arg ids -> sdocWithDynFlags $ \dflags -> pprSwitch dflags arg ids _other -> pprPanic "PprC.pprStmt" (ppr stmt) type Hinted a = (a, ForeignHint) pprForeignCall :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual] -> SDoc pprForeignCall fn cconv results args = fn_call where fn_call = braces ( pprCFunType (char '*' <> text "ghcFunPtr") cconv results args <> semi $$ text "ghcFunPtr" <+> equals <+> cast_fn <> semi $$ pprCall (text "ghcFunPtr") cconv results args <> semi ) cast_fn = parens (parens (pprCFunType (char '*') cconv results args) <> fn) pprCFunType :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual] -> SDoc pprCFunType ppr_fn cconv ress args = sdocWithDynFlags $ \dflags -> let res_type [] = text "void" res_type [(one, hint)] = machRepHintCType (localRegType one) hint res_type _ = panic "pprCFunType: only void or 1 return value supported" arg_type (expr, hint) = machRepHintCType (cmmExprType dflags expr) hint in res_type ress <+> parens (ccallConvAttribute cconv <> ppr_fn) <> parens (commafy (map arg_type args)) -- --------------------------------------------------------------------- -- unconditional branches pprBranch :: BlockId -> SDoc pprBranch ident = text "goto" <+> pprBlockId ident <> semi -- --------------------------------------------------------------------- -- conditional branches to local labels pprCondBranch :: CmmExpr -> BlockId -> BlockId -> SDoc pprCondBranch expr yes no = hsep [ text "if" , parens(pprExpr expr) , text "goto", pprBlockId yes <> semi, text "else goto", pprBlockId no <> semi ] -- --------------------------------------------------------------------- -- a local table branch -- -- we find the fall-through cases -- pprSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> SDoc pprSwitch dflags e ids = (hang (text "switch" <+> parens ( pprExpr e ) <+> lbrace) 4 (vcat ( map caseify pairs ) $$ def)) $$ rbrace where (pairs, mbdef) = switchTargetsFallThrough ids -- fall through case caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix where do_fallthrough ix = hsep [ text "case" , pprHexVal ix (wordWidth dflags) <> colon , text "/* fall through */" ] final_branch ix = hsep [ text "case" , pprHexVal ix (wordWidth dflags) <> colon , text "goto" , (pprBlockId ident) <> semi ] caseify (_ , _ ) = panic "pprSwitch: switch with no cases!" def | Just l <- mbdef = text "default: goto" <+> pprBlockId l <> semi | otherwise = empty -- --------------------------------------------------------------------- -- Expressions. -- -- C Types: the invariant is that the C expression generated by -- -- pprExpr e -- -- has a type in C which is also given by -- -- machRepCType (cmmExprType e) -- -- (similar invariants apply to the rest of the pretty printer). pprExpr :: CmmExpr -> SDoc pprExpr e = case e of CmmLit lit -> pprLit lit CmmLoad e ty -> sdocWithDynFlags $ \dflags -> pprLoad dflags e ty CmmReg reg -> pprCastReg reg CmmRegOff reg 0 -> pprCastReg reg CmmRegOff reg i | i < 0 && negate_ok -> pprRegOff (char '-') (-i) | otherwise -> pprRegOff (char '+') i where pprRegOff op i' = pprCastReg reg <> op <> int i' negate_ok = negate (fromIntegral i :: Integer) < fromIntegral (maxBound::Int) -- overflow is undefined; see #7620 CmmMachOp mop args -> pprMachOpApp mop args CmmStackSlot _ _ -> panic "pprExpr: CmmStackSlot not supported!" pprLoad :: DynFlags -> CmmExpr -> CmmType -> SDoc pprLoad dflags e ty | width == W64, wordWidth dflags /= W64 = (if isFloatType ty then text "PK_DBL" else text "PK_Word64") <> parens (mkP_ <> pprExpr1 e) | otherwise = case e of CmmReg r | isPtrReg r && width == wordWidth dflags && not (isFloatType ty) -> char '*' <> pprAsPtrReg r CmmRegOff r 0 | isPtrReg r && width == wordWidth dflags && not (isFloatType ty) -> char '*' <> pprAsPtrReg r CmmRegOff r off | isPtrReg r && width == wordWidth dflags , off `rem` wORD_SIZE dflags == 0 && not (isFloatType ty) -- ToDo: check that the offset is a word multiple? -- (For tagging to work, I had to avoid unaligned loads. --ARY) -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift dflags)) _other -> cLoad e ty where width = typeWidth ty pprExpr1 :: CmmExpr -> SDoc pprExpr1 (CmmLit lit) = pprLit1 lit pprExpr1 e@(CmmReg _reg) = pprExpr e pprExpr1 other = parens (pprExpr other) -- -------------------------------------------------------------------------- -- MachOp applications pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc pprMachOpApp op args | isMulMayOfloOp op = text "mulIntMayOflo" <> parens (commafy (map pprExpr args)) where isMulMayOfloOp (MO_U_MulMayOflo _) = True isMulMayOfloOp (MO_S_MulMayOflo _) = True isMulMayOfloOp _ = False pprMachOpApp mop args | Just ty <- machOpNeedsCast mop = ty <> parens (pprMachOpApp' mop args) | otherwise = pprMachOpApp' mop args -- Comparisons in C have type 'int', but we want type W_ (this is what -- resultRepOfMachOp says). The other C operations inherit their type -- from their operands, so no casting is required. machOpNeedsCast :: MachOp -> Maybe SDoc machOpNeedsCast mop | isComparisonMachOp mop = Just mkW_ | otherwise = Nothing pprMachOpApp' :: MachOp -> [CmmExpr] -> SDoc pprMachOpApp' mop args = case args of -- dyadic [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y -- unary [x] -> pprMachOp_for_C mop <> parens (pprArg x) _ -> panic "PprC.pprMachOp : machop with wrong number of args" where -- Cast needed for signed integer ops pprArg e | signedOp mop = sdocWithDynFlags $ \dflags -> cCast (machRep_S_CType (typeWidth (cmmExprType dflags e))) e | needsFCasts mop = sdocWithDynFlags $ \dflags -> cCast (machRep_F_CType (typeWidth (cmmExprType dflags e))) e | otherwise = pprExpr1 e needsFCasts (MO_F_Eq _) = False needsFCasts (MO_F_Ne _) = False needsFCasts (MO_F_Neg _) = True needsFCasts (MO_F_Quot _) = True needsFCasts mop = floatComparison mop -- -------------------------------------------------------------------------- -- Literals pprLit :: CmmLit -> SDoc pprLit lit = case lit of CmmInt i rep -> pprHexVal i rep CmmFloat f w -> parens (machRep_F_CType w) <> str where d = fromRational f :: Double str | isInfinite d && d < 0 = text "-INFINITY" | isInfinite d = text "INFINITY" | isNaN d = text "NAN" | otherwise = text (show d) -- these constants come from <math.h> -- see #1861 CmmVec {} -> panic "PprC printing vector literal" CmmBlock bid -> mkW_ <> pprCLabelAddr (infoTblLbl bid) CmmHighStackMark -> panic "PprC printing high stack mark" CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i CmmLabelDiffOff clbl1 _ i -- WARNING: -- * the lit must occur in the info table clbl2 -- * clbl1 must be an SRT, a slow entry point or a large bitmap -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i where pprCLabelAddr lbl = char '&' <> ppr lbl pprLit1 :: CmmLit -> SDoc pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit) pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit) pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit) pprLit1 other = pprLit other -- --------------------------------------------------------------------------- -- Static data pprStatics :: DynFlags -> [CmmStatic] -> [SDoc] pprStatics _ [] = [] pprStatics dflags (CmmStaticLit (CmmFloat f W32) : rest) -- floats are padded to a word by padLitToWord, see #1852 | wORD_SIZE dflags == 8, CmmStaticLit (CmmInt 0 W32) : rest' <- rest = pprLit1 (floatToWord dflags f) : pprStatics dflags rest' | wORD_SIZE dflags == 4 = pprLit1 (floatToWord dflags f) : pprStatics dflags rest | otherwise = pprPanic "pprStatics: float" (vcat (map ppr' rest)) where ppr' (CmmStaticLit l) = sdocWithDynFlags $ \dflags -> ppr (cmmLitType dflags l) ppr' _other = text "bad static!" pprStatics dflags (CmmStaticLit (CmmFloat f W64) : rest) = map pprLit1 (doubleToWords dflags f) ++ pprStatics dflags rest pprStatics dflags (CmmStaticLit (CmmInt i W64) : rest) | wordWidth dflags == W32 = if wORDS_BIGENDIAN dflags then pprStatics dflags (CmmStaticLit (CmmInt q W32) : CmmStaticLit (CmmInt r W32) : rest) else pprStatics dflags (CmmStaticLit (CmmInt r W32) : CmmStaticLit (CmmInt q W32) : rest) where r = i .&. 0xffffffff q = i `shiftR` 32 pprStatics dflags (CmmStaticLit (CmmInt _ w) : _) | w /= wordWidth dflags = panic "pprStatics: cannot emit a non-word-sized static literal" pprStatics dflags (CmmStaticLit lit : rest) = pprLit1 lit : pprStatics dflags rest pprStatics _ (other : _) = pprPanic "pprWord" (pprStatic other) pprStatic :: CmmStatic -> SDoc pprStatic s = case s of CmmStaticLit lit -> nest 4 (pprLit lit) CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i)) -- these should be inlined, like the old .hc CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s')) -- --------------------------------------------------------------------------- -- Block Ids pprBlockId :: BlockId -> SDoc pprBlockId b = char '_' <> ppr (getUnique b) -- -------------------------------------------------------------------------- -- Print a MachOp in a way suitable for emitting via C. -- pprMachOp_for_C :: MachOp -> SDoc pprMachOp_for_C mop = case mop of -- Integer operations MO_Add _ -> char '+' MO_Sub _ -> char '-' MO_Eq _ -> text "==" MO_Ne _ -> text "!=" MO_Mul _ -> char '*' MO_S_Quot _ -> char '/' MO_S_Rem _ -> char '%' MO_S_Neg _ -> char '-' MO_U_Quot _ -> char '/' MO_U_Rem _ -> char '%' -- & Floating-point operations MO_F_Add _ -> char '+' MO_F_Sub _ -> char '-' MO_F_Neg _ -> char '-' MO_F_Mul _ -> char '*' MO_F_Quot _ -> char '/' -- Signed comparisons MO_S_Ge _ -> text ">=" MO_S_Le _ -> text "<=" MO_S_Gt _ -> char '>' MO_S_Lt _ -> char '<' -- & Unsigned comparisons MO_U_Ge _ -> text ">=" MO_U_Le _ -> text "<=" MO_U_Gt _ -> char '>' MO_U_Lt _ -> char '<' -- & Floating-point comparisons MO_F_Eq _ -> text "==" MO_F_Ne _ -> text "!=" MO_F_Ge _ -> text ">=" MO_F_Le _ -> text "<=" MO_F_Gt _ -> char '>' MO_F_Lt _ -> char '<' -- Bitwise operations. Not all of these may be supported at all -- sizes, and only integral MachReps are valid. MO_And _ -> char '&' MO_Or _ -> char '|' MO_Xor _ -> char '^' MO_Not _ -> char '~' MO_Shl _ -> text "<<" MO_U_Shr _ -> text ">>" -- unsigned shift right MO_S_Shr _ -> text ">>" -- signed shift right -- Conversions. Some of these will be NOPs, but never those that convert -- between ints and floats. -- Floating-point conversions use the signed variant. -- We won't know to generate (void*) casts here, but maybe from -- context elsewhere -- noop casts MO_UU_Conv from to | from == to -> empty MO_UU_Conv _from to -> parens (machRep_U_CType to) MO_SS_Conv from to | from == to -> empty MO_SS_Conv _from to -> parens (machRep_S_CType to) MO_FF_Conv from to | from == to -> empty MO_FF_Conv _from to -> parens (machRep_F_CType to) MO_SF_Conv _from to -> parens (machRep_F_CType to) MO_FS_Conv _from to -> parens (machRep_S_CType to) MO_S_MulMayOflo _ -> pprTrace "offending mop:" (text "MO_S_MulMayOflo") (panic $ "PprC.pprMachOp_for_C: MO_S_MulMayOflo" ++ " should have been handled earlier!") MO_U_MulMayOflo _ -> pprTrace "offending mop:" (text "MO_U_MulMayOflo") (panic $ "PprC.pprMachOp_for_C: MO_U_MulMayOflo" ++ " should have been handled earlier!") MO_V_Insert {} -> pprTrace "offending mop:" (text "MO_V_Insert") (panic $ "PprC.pprMachOp_for_C: MO_V_Insert" ++ " should have been handled earlier!") MO_V_Extract {} -> pprTrace "offending mop:" (text "MO_V_Extract") (panic $ "PprC.pprMachOp_for_C: MO_V_Extract" ++ " should have been handled earlier!") MO_V_Add {} -> pprTrace "offending mop:" (text "MO_V_Add") (panic $ "PprC.pprMachOp_for_C: MO_V_Add" ++ " should have been handled earlier!") MO_V_Sub {} -> pprTrace "offending mop:" (text "MO_V_Sub") (panic $ "PprC.pprMachOp_for_C: MO_V_Sub" ++ " should have been handled earlier!") MO_V_Mul {} -> pprTrace "offending mop:" (text "MO_V_Mul") (panic $ "PprC.pprMachOp_for_C: MO_V_Mul" ++ " should have been handled earlier!") MO_VS_Quot {} -> pprTrace "offending mop:" (text "MO_VS_Quot") (panic $ "PprC.pprMachOp_for_C: MO_VS_Quot" ++ " should have been handled earlier!") MO_VS_Rem {} -> pprTrace "offending mop:" (text "MO_VS_Rem") (panic $ "PprC.pprMachOp_for_C: MO_VS_Rem" ++ " should have been handled earlier!") MO_VS_Neg {} -> pprTrace "offending mop:" (text "MO_VS_Neg") (panic $ "PprC.pprMachOp_for_C: MO_VS_Neg" ++ " should have been handled earlier!") MO_VU_Quot {} -> pprTrace "offending mop:" (text "MO_VU_Quot") (panic $ "PprC.pprMachOp_for_C: MO_VU_Quot" ++ " should have been handled earlier!") MO_VU_Rem {} -> pprTrace "offending mop:" (text "MO_VU_Rem") (panic $ "PprC.pprMachOp_for_C: MO_VU_Rem" ++ " should have been handled earlier!") MO_VF_Insert {} -> pprTrace "offending mop:" (text "MO_VF_Insert") (panic $ "PprC.pprMachOp_for_C: MO_VF_Insert" ++ " should have been handled earlier!") MO_VF_Extract {} -> pprTrace "offending mop:" (text "MO_VF_Extract") (panic $ "PprC.pprMachOp_for_C: MO_VF_Extract" ++ " should have been handled earlier!") MO_VF_Add {} -> pprTrace "offending mop:" (text "MO_VF_Add") (panic $ "PprC.pprMachOp_for_C: MO_VF_Add" ++ " should have been handled earlier!") MO_VF_Sub {} -> pprTrace "offending mop:" (text "MO_VF_Sub") (panic $ "PprC.pprMachOp_for_C: MO_VF_Sub" ++ " should have been handled earlier!") MO_VF_Neg {} -> pprTrace "offending mop:" (text "MO_VF_Neg") (panic $ "PprC.pprMachOp_for_C: MO_VF_Neg" ++ " should have been handled earlier!") MO_VF_Mul {} -> pprTrace "offending mop:" (text "MO_VF_Mul") (panic $ "PprC.pprMachOp_for_C: MO_VF_Mul" ++ " should have been handled earlier!") MO_VF_Quot {} -> pprTrace "offending mop:" (text "MO_VF_Quot") (panic $ "PprC.pprMachOp_for_C: MO_VF_Quot" ++ " should have been handled earlier!") signedOp :: MachOp -> Bool -- Argument type(s) are signed ints signedOp (MO_S_Quot _) = True signedOp (MO_S_Rem _) = True signedOp (MO_S_Neg _) = True signedOp (MO_S_Ge _) = True signedOp (MO_S_Le _) = True signedOp (MO_S_Gt _) = True signedOp (MO_S_Lt _) = True signedOp (MO_S_Shr _) = True signedOp (MO_SS_Conv _ _) = True signedOp (MO_SF_Conv _ _) = True signedOp _ = False floatComparison :: MachOp -> Bool -- comparison between float args floatComparison (MO_F_Eq _) = True floatComparison (MO_F_Ne _) = True floatComparison (MO_F_Ge _) = True floatComparison (MO_F_Le _) = True floatComparison (MO_F_Gt _) = True floatComparison (MO_F_Lt _) = True floatComparison _ = False -- --------------------------------------------------------------------- -- tend to be implemented by foreign calls pprCallishMachOp_for_C :: CallishMachOp -> SDoc pprCallishMachOp_for_C mop = case mop of MO_F64_Pwr -> text "pow" MO_F64_Sin -> text "sin" MO_F64_Cos -> text "cos" MO_F64_Tan -> text "tan" MO_F64_Sinh -> text "sinh" MO_F64_Cosh -> text "cosh" MO_F64_Tanh -> text "tanh" MO_F64_Asin -> text "asin" MO_F64_Acos -> text "acos" MO_F64_Atan -> text "atan" MO_F64_Log -> text "log" MO_F64_Exp -> text "exp" MO_F64_Sqrt -> text "sqrt" MO_F32_Pwr -> text "powf" MO_F32_Sin -> text "sinf" MO_F32_Cos -> text "cosf" MO_F32_Tan -> text "tanf" MO_F32_Sinh -> text "sinhf" MO_F32_Cosh -> text "coshf" MO_F32_Tanh -> text "tanhf" MO_F32_Asin -> text "asinf" MO_F32_Acos -> text "acosf" MO_F32_Atan -> text "atanf" MO_F32_Log -> text "logf" MO_F32_Exp -> text "expf" MO_F32_Sqrt -> text "sqrtf" MO_WriteBarrier -> text "write_barrier" MO_Memcpy _ -> text "memcpy" MO_Memset _ -> text "memset" MO_Memmove _ -> text "memmove" (MO_BSwap w) -> ptext (sLit $ bSwapLabel w) (MO_PopCnt w) -> ptext (sLit $ popCntLabel w) (MO_Clz w) -> ptext (sLit $ clzLabel w) (MO_Ctz w) -> ptext (sLit $ ctzLabel w) (MO_AtomicRMW w amop) -> ptext (sLit $ atomicRMWLabel w amop) (MO_Cmpxchg w) -> ptext (sLit $ cmpxchgLabel w) (MO_AtomicRead w) -> ptext (sLit $ atomicReadLabel w) (MO_AtomicWrite w) -> ptext (sLit $ atomicWriteLabel w) (MO_UF_Conv w) -> ptext (sLit $ word2FloatLabel w) MO_S_QuotRem {} -> unsupported MO_U_QuotRem {} -> unsupported MO_U_QuotRem2 {} -> unsupported MO_Add2 {} -> unsupported MO_SubWordC {} -> unsupported MO_AddIntC {} -> unsupported MO_SubIntC {} -> unsupported MO_U_Mul2 {} -> unsupported MO_Touch -> unsupported (MO_Prefetch_Data _ ) -> unsupported --- we could support prefetch via "__builtin_prefetch" --- Not adding it for now where unsupported = panic ("pprCallishMachOp_for_C: " ++ show mop ++ " not supported!") -- --------------------------------------------------------------------- -- Useful #defines -- mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc mkJMP_ i = text "JMP_" <> parens i mkFN_ i = text "FN_" <> parens i -- externally visible function mkIF_ i = text "IF_" <> parens i -- locally visible -- from includes/Stg.h -- mkC_,mkW_,mkP_ :: SDoc mkC_ = text "(C_)" -- StgChar mkW_ = text "(W_)" -- StgWord mkP_ = text "(P_)" -- StgWord* -- --------------------------------------------------------------------- -- -- Assignments -- -- Generating assignments is what we're all about, here -- pprAssign :: DynFlags -> CmmReg -> CmmExpr -> SDoc -- dest is a reg, rhs is a reg pprAssign _ r1 (CmmReg r2) | isPtrReg r1 && isPtrReg r2 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ] -- dest is a reg, rhs is a CmmRegOff pprAssign dflags r1 (CmmRegOff r2 off) | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE dflags == 0) = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ] where off1 = off `shiftR` wordShift dflags (op,off') | off >= 0 = (char '+', off1) | otherwise = (char '-', -off1) -- dest is a reg, rhs is anything. -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting -- the lvalue elicits a warning from new GCC versions (3.4+). pprAssign _ r1 r2 | isFixedPtrReg r1 = mkAssign (mkP_ <> pprExpr1 r2) | Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 r2) | otherwise = mkAssign (pprExpr r2) where mkAssign x = if r1 == CmmGlobal BaseReg then text "ASSIGN_BaseReg" <> parens x <> semi else pprReg r1 <> text " = " <> x <> semi -- --------------------------------------------------------------------- -- Registers pprCastReg :: CmmReg -> SDoc pprCastReg reg | isStrangeTypeReg reg = mkW_ <> pprReg reg | otherwise = pprReg reg -- True if (pprReg reg) will give an expression with type StgPtr. We -- need to take care with pointer arithmetic on registers with type -- StgPtr. isFixedPtrReg :: CmmReg -> Bool isFixedPtrReg (CmmLocal _) = False isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r -- True if (pprAsPtrReg reg) will give an expression with type StgPtr -- JD: THIS IS HORRIBLE AND SHOULD BE RENAMED, AT THE VERY LEAST. -- THE GARBAGE WITH THE VNonGcPtr HELPS MATCH THE OLD CODE GENERATOR'S OUTPUT; -- I'M NOT SURE IF IT SHOULD REALLY STAY THAT WAY. isPtrReg :: CmmReg -> Bool isPtrReg (CmmLocal _) = False isPtrReg (CmmGlobal (VanillaReg _ VGcPtr)) = True -- if we print via pprAsPtrReg isPtrReg (CmmGlobal (VanillaReg _ VNonGcPtr)) = False -- if we print via pprAsPtrReg isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg -- True if this global reg has type StgPtr isFixedPtrGlobalReg :: GlobalReg -> Bool isFixedPtrGlobalReg Sp = True isFixedPtrGlobalReg Hp = True isFixedPtrGlobalReg HpLim = True isFixedPtrGlobalReg SpLim = True isFixedPtrGlobalReg _ = False -- True if in C this register doesn't have the type given by -- (machRepCType (cmmRegType reg)), so it has to be cast. isStrangeTypeReg :: CmmReg -> Bool isStrangeTypeReg (CmmLocal _) = False isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g isStrangeTypeGlobal :: GlobalReg -> Bool isStrangeTypeGlobal CCCS = True isStrangeTypeGlobal CurrentTSO = True isStrangeTypeGlobal CurrentNursery = True isStrangeTypeGlobal BaseReg = True isStrangeTypeGlobal r = isFixedPtrGlobalReg r strangeRegType :: CmmReg -> Maybe SDoc strangeRegType (CmmGlobal CCCS) = Just (text "struct CostCentreStack_ *") strangeRegType (CmmGlobal CurrentTSO) = Just (text "struct StgTSO_ *") strangeRegType (CmmGlobal CurrentNursery) = Just (text "struct bdescr_ *") strangeRegType (CmmGlobal BaseReg) = Just (text "struct StgRegTable_ *") strangeRegType _ = Nothing -- pprReg just prints the register name. -- pprReg :: CmmReg -> SDoc pprReg r = case r of CmmLocal local -> pprLocalReg local CmmGlobal global -> pprGlobalReg global pprAsPtrReg :: CmmReg -> SDoc pprAsPtrReg (CmmGlobal (VanillaReg n gcp)) = WARN( gcp /= VGcPtr, ppr n ) char 'R' <> int n <> text ".p" pprAsPtrReg other_reg = pprReg other_reg pprGlobalReg :: GlobalReg -> SDoc pprGlobalReg gr = case gr of VanillaReg n _ -> char 'R' <> int n <> text ".w" -- pprGlobalReg prints a VanillaReg as a .w regardless -- Example: R1.w = R1.w & (-0x8UL); -- JMP_(*R1.p); FloatReg n -> char 'F' <> int n DoubleReg n -> char 'D' <> int n LongReg n -> char 'L' <> int n Sp -> text "Sp" SpLim -> text "SpLim" Hp -> text "Hp" HpLim -> text "HpLim" CCCS -> text "CCCS" CurrentTSO -> text "CurrentTSO" CurrentNursery -> text "CurrentNursery" HpAlloc -> text "HpAlloc" BaseReg -> text "BaseReg" EagerBlackholeInfo -> text "stg_EAGER_BLACKHOLE_info" GCEnter1 -> text "stg_gc_enter_1" GCFun -> text "stg_gc_fun" other -> panic $ "pprGlobalReg: Unsupported register: " ++ show other pprLocalReg :: LocalReg -> SDoc pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq -- ----------------------------------------------------------------------------- -- Foreign Calls pprCall :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual] -> SDoc pprCall ppr_fn cconv results args | not (is_cishCC cconv) = panic $ "pprCall: unknown calling convention" | otherwise = ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi where ppr_assign [] rhs = rhs ppr_assign [(one,hint)] rhs = pprLocalReg one <> text " = " <> pprUnHint hint (localRegType one) <> rhs ppr_assign _other _rhs = panic "pprCall: multiple results" pprArg (expr, AddrHint) = cCast (text "void *") expr -- see comment by machRepHintCType below pprArg (expr, SignedHint) = sdocWithDynFlags $ \dflags -> cCast (machRep_S_CType $ typeWidth $ cmmExprType dflags expr) expr pprArg (expr, _other) = pprExpr expr pprUnHint AddrHint rep = parens (machRepCType rep) pprUnHint SignedHint rep = parens (machRepCType rep) pprUnHint _ _ = empty -- Currently we only have these two calling conventions, but this might -- change in the future... is_cishCC :: CCallConv -> Bool is_cishCC CCallConv = True is_cishCC CApiConv = True is_cishCC StdCallConv = True is_cishCC PrimCallConv = False is_cishCC JavaScriptCallConv = False -- --------------------------------------------------------------------- -- Find and print local and external declarations for a list of -- Cmm statements. -- pprTempAndExternDecls :: [CmmBlock] -> (SDoc{-temps-}, SDoc{-externs-}) pprTempAndExternDecls stmts = (vcat (map pprTempDecl (uniqSetToList temps)), vcat (map (pprExternDecl False{-ToDo-}) (Map.keys lbls))) where (temps, lbls) = runTE (mapM_ te_BB stmts) pprDataExterns :: [CmmStatic] -> SDoc pprDataExterns statics = vcat (map (pprExternDecl False{-ToDo-}) (Map.keys lbls)) where (_, lbls) = runTE (mapM_ te_Static statics) pprTempDecl :: LocalReg -> SDoc pprTempDecl l@(LocalReg _ rep) = hcat [ machRepCType rep, space, pprLocalReg l, semi ] pprExternDecl :: Bool -> CLabel -> SDoc pprExternDecl _in_srt lbl -- do not print anything for "known external" things | not (needsCDecl lbl) = empty | Just sz <- foreignLabelStdcallInfo lbl = stdcall_decl sz | otherwise = hcat [ visibility, label_type lbl, lparen, ppr lbl, text ");" ] where label_type lbl | isForeignLabel lbl && isCFunctionLabel lbl = text "FF_" | isCFunctionLabel lbl = text "F_" | otherwise = text "I_" visibility | externallyVisibleCLabel lbl = char 'E' | otherwise = char 'I' -- If the label we want to refer to is a stdcall function (on Windows) then -- we must generate an appropriate prototype for it, so that the C compiler will -- add the @n suffix to the label (#2276) stdcall_decl sz = sdocWithDynFlags $ \dflags -> text "extern __attribute__((stdcall)) void " <> ppr lbl <> parens (commafy (replicate (sz `quot` wORD_SIZE dflags) (machRep_U_CType (wordWidth dflags)))) <> semi type TEState = (UniqSet LocalReg, Map CLabel ()) newtype TE a = TE { unTE :: TEState -> (a, TEState) } instance Functor TE where fmap = liftM instance Applicative TE where pure a = TE $ \s -> (a, s) (<*>) = ap instance Monad TE where TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s' return = pure te_lbl :: CLabel -> TE () te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, Map.insert lbl () lbls)) te_temp :: LocalReg -> TE () te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls)) runTE :: TE () -> TEState runTE (TE m) = snd (m (emptyUniqSet, Map.empty)) te_Static :: CmmStatic -> TE () te_Static (CmmStaticLit lit) = te_Lit lit te_Static _ = return () te_BB :: CmmBlock -> TE () te_BB block = mapM_ te_Stmt (blockToList mid) >> te_Stmt last where (_, mid, last) = blockSplit block te_Lit :: CmmLit -> TE () te_Lit (CmmLabel l) = te_lbl l te_Lit (CmmLabelOff l _) = te_lbl l te_Lit (CmmLabelDiffOff l1 _ _) = te_lbl l1 te_Lit _ = return () te_Stmt :: CmmNode e x -> TE () te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r te_Stmt (CmmUnsafeForeignCall target rs es) = do te_Target target mapM_ te_temp rs mapM_ te_Expr es te_Stmt (CmmCondBranch e _ _ _) = te_Expr e te_Stmt (CmmSwitch e _) = te_Expr e te_Stmt (CmmCall { cml_target = e }) = te_Expr e te_Stmt _ = return () te_Target :: ForeignTarget -> TE () te_Target (ForeignTarget e _) = te_Expr e te_Target (PrimTarget{}) = return () te_Expr :: CmmExpr -> TE () te_Expr (CmmLit lit) = te_Lit lit te_Expr (CmmLoad e _) = te_Expr e te_Expr (CmmReg r) = te_Reg r te_Expr (CmmMachOp _ es) = mapM_ te_Expr es te_Expr (CmmRegOff r _) = te_Reg r te_Expr (CmmStackSlot _ _) = panic "te_Expr: CmmStackSlot not supported!" te_Reg :: CmmReg -> TE () te_Reg (CmmLocal l) = te_temp l te_Reg _ = return () -- --------------------------------------------------------------------- -- C types for MachReps cCast :: SDoc -> CmmExpr -> SDoc cCast ty expr = parens ty <> pprExpr1 expr cLoad :: CmmExpr -> CmmType -> SDoc cLoad expr rep = sdocWithPlatform $ \platform -> if bewareLoadStoreAlignment (platformArch platform) then let decl = machRepCType rep <+> text "x" <> semi struct = text "struct" <+> braces (decl) packed_attr = text "__attribute__((packed))" cast = parens (struct <+> packed_attr <> char '*') in parens (cast <+> pprExpr1 expr) <> text "->x" else char '*' <> parens (cCast (machRepPtrCType rep) expr) where -- On these platforms, unaligned loads are known to cause problems bewareLoadStoreAlignment ArchAlpha = True bewareLoadStoreAlignment ArchMipseb = True bewareLoadStoreAlignment ArchMipsel = True bewareLoadStoreAlignment (ArchARM {}) = True bewareLoadStoreAlignment ArchARM64 = True -- Pessimistically assume that they will also cause problems -- on unknown arches bewareLoadStoreAlignment ArchUnknown = True bewareLoadStoreAlignment _ = False isCmmWordType :: DynFlags -> CmmType -> Bool -- True of GcPtrReg/NonGcReg of native word size isCmmWordType dflags ty = not (isFloatType ty) && typeWidth ty == wordWidth dflags -- This is for finding the types of foreign call arguments. For a pointer -- argument, we always cast the argument to (void *), to avoid warnings from -- the C compiler. machRepHintCType :: CmmType -> ForeignHint -> SDoc machRepHintCType _ AddrHint = text "void *" machRepHintCType rep SignedHint = machRep_S_CType (typeWidth rep) machRepHintCType rep _other = machRepCType rep machRepPtrCType :: CmmType -> SDoc machRepPtrCType r = sdocWithDynFlags $ \dflags -> if isCmmWordType dflags r then text "P_" else machRepCType r <> char '*' machRepCType :: CmmType -> SDoc machRepCType ty | isFloatType ty = machRep_F_CType w | otherwise = machRep_U_CType w where w = typeWidth ty machRep_F_CType :: Width -> SDoc machRep_F_CType W32 = text "StgFloat" -- ToDo: correct? machRep_F_CType W64 = text "StgDouble" machRep_F_CType _ = panic "machRep_F_CType" machRep_U_CType :: Width -> SDoc machRep_U_CType w = sdocWithDynFlags $ \dflags -> case w of _ | w == wordWidth dflags -> text "W_" W8 -> text "StgWord8" W16 -> text "StgWord16" W32 -> text "StgWord32" W64 -> text "StgWord64" _ -> panic "machRep_U_CType" machRep_S_CType :: Width -> SDoc machRep_S_CType w = sdocWithDynFlags $ \dflags -> case w of _ | w == wordWidth dflags -> text "I_" W8 -> text "StgInt8" W16 -> text "StgInt16" W32 -> text "StgInt32" W64 -> text "StgInt64" _ -> panic "machRep_S_CType" -- --------------------------------------------------------------------- -- print strings as valid C strings pprStringInCStyle :: [Word8] -> SDoc pprStringInCStyle s = doubleQuotes (text (concatMap charToC s)) -- --------------------------------------------------------------------------- -- Initialising static objects with floating-point numbers. We can't -- just emit the floating point number, because C will cast it to an int -- by rounding it. We want the actual bit-representation of the float. -- -- Consider a concrete C example: -- double d = 2.5e-10; -- float f = 2.5e-10f; -- -- int * i2 = &d; printf ("i2: %08X %08X\n", i2[0], i2[1]); -- long long * l = &d; printf (" l: %016llX\n", l[0]); -- int * i = &f; printf (" i: %08X\n", i[0]); -- Result on 64-bit LE (x86_64): -- i2: E826D695 3DF12E0B -- l: 3DF12E0BE826D695 -- i: 2F89705F -- Result on 32-bit BE (m68k): -- i2: 3DF12E0B E826D695 -- l: 3DF12E0BE826D695 -- i: 2F89705F -- -- The trick here is to notice that binary representation does not -- change much: only Word32 values get swapped on LE hosts / targets. -- This is a hack to turn the floating point numbers into ints that we -- can safely initialise to static locations. castFloatToWord32Array :: STUArray s Int Float -> ST s (STUArray s Int Word32) castFloatToWord32Array = U.castSTUArray castDoubleToWord64Array :: STUArray s Int Double -> ST s (STUArray s Int Word64) castDoubleToWord64Array = U.castSTUArray floatToWord :: DynFlags -> Rational -> CmmLit floatToWord dflags r = runST (do arr <- newArray_ ((0::Int),0) writeArray arr 0 (fromRational r) arr' <- castFloatToWord32Array arr w32 <- readArray arr' 0 return (CmmInt (toInteger w32 `shiftL` wo) (wordWidth dflags)) ) where wo | wordWidth dflags == W64 , wORDS_BIGENDIAN dflags = 32 | otherwise = 0 doubleToWords :: DynFlags -> Rational -> [CmmLit] doubleToWords dflags r = runST (do arr <- newArray_ ((0::Int),1) writeArray arr 0 (fromRational r) arr' <- castDoubleToWord64Array arr w64 <- readArray arr' 0 return (pprWord64 w64) ) where targetWidth = wordWidth dflags targetBE = wORDS_BIGENDIAN dflags pprWord64 w64 | targetWidth == W64 = [ CmmInt (toInteger w64) targetWidth ] | targetWidth == W32 = [ CmmInt (toInteger targetW1) targetWidth , CmmInt (toInteger targetW2) targetWidth ] | otherwise = panic "doubleToWords.pprWord64" where (targetW1, targetW2) | targetBE = (wHi, wLo) | otherwise = (wLo, wHi) wHi = w64 `shiftR` 32 wLo = w64 .&. 0xFFFFffff -- --------------------------------------------------------------------------- -- Utils wordShift :: DynFlags -> Int wordShift dflags = widthInLog (wordWidth dflags) commafy :: [SDoc] -> SDoc commafy xs = hsep $ punctuate comma xs -- Print in C hex format: 0x13fa pprHexVal :: Integer -> Width -> SDoc pprHexVal w rep | w < 0 = parens (char '-' <> text "0x" <> intToDoc (-w) <> repsuffix rep) | otherwise = text "0x" <> intToDoc w <> repsuffix rep where -- type suffix for literals: -- Integer literals are unsigned in Cmm/C. We explicitly cast to -- signed values for doing signed operations, but at all other -- times values are unsigned. This also helps eliminate occasional -- warnings about integer overflow from gcc. repsuffix W64 = sdocWithDynFlags $ \dflags -> if cINT_SIZE dflags == 8 then char 'U' else if cLONG_SIZE dflags == 8 then text "UL" else if cLONG_LONG_SIZE dflags == 8 then text "ULL" else panic "pprHexVal: Can't find a 64-bit type" repsuffix _ = char 'U' intToDoc :: Integer -> SDoc intToDoc i = case truncInt i of 0 -> char '0' v -> go v -- We need to truncate value as Cmm backend does not drop -- redundant bits to ease handling of negative values. -- Thus the following Cmm code on 64-bit arch, like amd64: -- CInt v; -- v = {something}; -- if (v == %lobits32(-1)) { ... -- leads to the following C code: -- StgWord64 v = (StgWord32)({something}); -- if (v == 0xFFFFffffFFFFffffU) { ... -- Such code is incorrect as it promotes both operands to StgWord64 -- and the whole condition is always false. truncInt :: Integer -> Integer truncInt i = case rep of W8 -> i `rem` (2^(8 :: Int)) W16 -> i `rem` (2^(16 :: Int)) W32 -> i `rem` (2^(32 :: Int)) W64 -> i `rem` (2^(64 :: Int)) _ -> panic ("pprHexVal/truncInt: C backend can't encode " ++ show rep ++ " literals") go 0 = empty go w' = go q <> dig where (q,r) = w' `quotRem` 16 dig | r < 10 = char (chr (fromInteger r + ord '0')) | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
GaloisInc/halvm-ghc
compiler/cmm/PprC.hs
Haskell
bsd-3-clause
48,991
{-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE ImplicitParams #-} {-# Language OverloadedStrings #-} {-# OPTIONS_GHC -Wall -fno-warn-unused-top-binds #-} import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as BS8 import Data.Char (isSpace) import Data.List (dropWhileEnd, isPrefixOf) import Data.Maybe (catMaybes) import System.Directory (listDirectory, doesDirectoryExist, doesFileExist, removeFile) import System.Exit (ExitCode(..)) import System.FilePath ((<.>), (</>), takeBaseName, takeExtension, replaceExtension, takeFileName, takeDirectory) import System.IO (IOMode(..), Handle, withFile, hClose, hGetContents, hGetLine, openFile) import System.IO.Temp (withSystemTempFile) import System.Environment (setEnv) import qualified System.Process as Proc import Test.Tasty (defaultMain, testGroup, TestTree) import Test.Tasty.HUnit (Assertion, testCaseSteps, assertBool, assertFailure) import Test.Tasty.Golden (findByExtension) import Test.Tasty.Golden.Advanced (goldenTest) import Test.Tasty.ExpectedFailure (expectFailBecause) import qualified Mir.Language as Mir import qualified Mir.Compositional as Mir import qualified Mir.Cryptol as Mir import qualified Crux as Crux import qualified Crux.Config.Common as Crux import qualified Data.AIG.Interface as AIG import qualified Config import qualified Config.Schema as Config type OracleTest = FilePath -> String -> (String -> IO ()) -> Assertion -- Don't show any debug output when testing (SAWInterface) debugLevel :: Int debugLevel = 0 -- | Check whether an input file is expected to fail based on a comment in the first line. expectedFail :: FilePath -> IO (Maybe String) expectedFail fn = withFile fn ReadMode $ \h -> do firstLine <- hGetLine h return $ if failMarker `isPrefixOf` firstLine then Just (drop (length failMarker) firstLine) else Nothing where failMarker = "// FAIL: " -- TODO: remove this - copy-pasted from Crux/Options.hs for compatibility with -- old mainline crucible defaultCruxOptions :: Crux.CruxOptions defaultCruxOptions = case res of Left x -> error $ "failed to compute default crux options: " ++ show x Right x -> x where ss = Crux.cfgFile Crux.cruxOptions res = Config.loadValue (Config.sectionsSpec "crux" ss) (Config.Sections () []) data RunCruxMode = RcmConcrete | RcmSymbolic | RcmCoverage deriving (Show, Eq) runCrux :: FilePath -> Handle -> RunCruxMode -> IO () runCrux rustFile outHandle mode = Mir.withMirLogging $ do -- goalTimeout is bumped from 60 to 180 because scalar.rs symbolic -- verification runs close to the timeout, causing flaky results -- (especially in CI). let quiet = True let outOpts = (Crux.outputOptions defaultCruxOptions) { Crux.simVerbose = 0 , Crux.quietMode = quiet } let options = (defaultCruxOptions { Crux.outputOptions = outOpts, Crux.inputFiles = [rustFile], Crux.globalTimeout = Just 180, Crux.goalTimeout = Just 180, Crux.solver = "z3", Crux.checkPathSat = (mode == RcmCoverage), Crux.outDir = case mode of RcmCoverage -> getOutputDir rustFile _ -> "", Crux.branchCoverage = (mode == RcmCoverage) } , Mir.defaultMirOptions { Mir.printResultOnly = (mode == RcmConcrete), Mir.defaultRlibsDir = "../deps/crucible/crux-mir/rlibs" }) let ?outputConfig = Crux.mkOutputConfig (outHandle, False) (outHandle, False) Mir.mirLoggingToSayWhat (Just $ Crux.outputOptions $ fst options) setEnv "CRYPTOLPATH" "." _exitCode <- Mir.runTestsWithExtraOverrides overrides options return () where overrides :: Mir.BindExtraOverridesFn overrides = Mir.compositionalOverrides `Mir.orOverride` Mir.cryptolOverrides getOutputDir :: FilePath -> FilePath getOutputDir rustFile = takeDirectory rustFile </> "out" cruxOracleTest :: FilePath -> String -> (String -> IO ()) -> Assertion cruxOracleTest dir name step = do step "Compiling and running oracle program" oracleOut <- compileAndRun dir name >>= \case Nothing -> assertFailure "failed to compile and run" Just out -> return out let orOut = dropWhileEnd isSpace oracleOut step ("Oracle output: " ++ orOut) let rustFile = dir </> name <.> "rs" cruxOut <- withSystemTempFile name $ \tempName h -> do runCrux rustFile h RcmConcrete hClose h h' <- openFile tempName ReadMode out <- hGetContents h' length out `seq` hClose h' return $ dropWhileEnd isSpace out step ("Crux output: " ++ cruxOut ++ "\n") assertBool "crux doesn't match oracle" (orOut == cruxOut) symbTest :: FilePath -> IO TestTree symbTest dir = do exists <- doesDirectoryExist dir rustFiles <- if exists then findByExtension [".rs"] dir else return [] return $ testGroup "Output testing" [ doGoldenTest (takeBaseName rustFile) goodFile outFile $ withFile outFile WriteMode $ \h -> runCrux rustFile h RcmSymbolic | rustFile <- rustFiles -- Skip hidden files, such as editor swap files , not $ "." `isPrefixOf` takeFileName rustFile , let goodFile = replaceExtension rustFile ".good" , let outFile = replaceExtension rustFile ".out" ] coverageTests :: FilePath -> IO TestTree coverageTests dir = do exists <- doesDirectoryExist dir rustFiles <- if exists then findByExtension [".rs"] dir else return [] return $ testGroup "Output testing" [ doGoldenTest rustFile goodFile outFile (doTest rustFile outFile) | rustFile <- rustFiles -- Skip hidden files, such as editor swap files , not $ "." `isPrefixOf` takeFileName rustFile , let goodFile = replaceExtension rustFile ".good" , let outFile = replaceExtension rustFile ".out" ] where doTest rustFile outFile = do let logFile = replaceExtension rustFile ".crux.log" withFile logFile WriteMode $ \h -> runCrux rustFile h RcmCoverage let reportDir = getOutputDir rustFile </> takeBaseName rustFile reportFiles <- findByExtension [".js"] reportDir out <- Proc.readProcess "cargo" (["run", "--manifest-path", "report-coverage/Cargo.toml", "--quiet", "--", "--no-color"] ++ reportFiles) "" writeFile outFile out doGoldenTest :: FilePath -> FilePath -> FilePath -> IO () -> TestTree doGoldenTest rustFile goodFile outFile act = goldenTest (takeBaseName rustFile) (BS.readFile goodFile) (act >> BS.readFile outFile) (\good out -> return $ if good == out then Nothing else Just $ "files " ++ goodFile ++ " and " ++ outFile ++ " differ; " ++ goodFile ++ " contains:\n" ++ BS8.toString out) (\out -> BS.writeFile goodFile out) main :: IO () main = defaultMain =<< suite suite :: IO TestTree suite = do let ?debug = 0 :: Int let ?assertFalseOnError = True let ?printCrucible = False trees <- sequence [ testGroup "crux concrete" <$> sequence [ testDir cruxOracleTest "test/conc_eval/" ] , testGroup "crux symbolic" <$> sequence [ symbTest "test/symb_eval" ] , testGroup "crux coverage" <$> sequence [ coverageTests "test/coverage" ] ] return $ testGroup "crux-mir" trees -- For newSAWCoreBackend proxy :: AIG.Proxy AIG.BasicLit AIG.BasicGraph proxy = AIG.basicProxy -- | Compile using 'rustc' and run executable compileAndRun :: FilePath -> String -> IO (Maybe String) compileAndRun dir name = do (ec, _, err) <- Proc.readProcessWithExitCode "rustc" [dir </> name <.> "rs", "--cfg", "with_main" , "--extern", "byteorder=rlibs_native/libbyteorder.rlib" , "--extern", "bytes=rlibs_native/libbytes.rlib"] "" case ec of ExitFailure _ -> do putStrLn $ "rustc compilation failed for " ++ name putStrLn "error output:" putStrLn err return Nothing ExitSuccess -> do let execFile = "." </> name (ec', out, _) <- Proc.readProcessWithExitCode execFile [] "" doesFileExist execFile >>= \case True -> removeFile execFile False -> return () case ec' of ExitFailure _ -> do putStrLn $ "non-zero exit code for test executable " ++ name return Nothing ExitSuccess -> return $ Just out testDir :: OracleTest -> FilePath -> IO TestTree testDir oracleTest dir = do let gen f | "." `isPrefixOf` takeBaseName f = return Nothing gen f | takeExtension f == ".rs" = do shouldFail <- expectedFail (dir </> f) case shouldFail of Nothing -> return (Just (testCaseSteps name (oracleTest dir name))) Just why -> return (Just (expectFailBecause why (testCaseSteps name (oracleTest dir name)))) where name = takeBaseName f gen f = doesDirectoryExist (dir </> f) >>= \case False -> return Nothing True -> Just <$> testDir oracleTest (dir </> f) exists <- doesDirectoryExist dir fs <- if exists then listDirectory dir else return [] tcs <- mapM gen fs return (testGroup (takeBaseName dir) (catMaybes tcs))
GaloisInc/saw-script
crux-mir-comp/test/Test.hs
Haskell
bsd-3-clause
9,682
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Lib ( mainFunc, module ClassyPrelude, module Haskakafka ) where import Common import Config import Fortune import Kansha import Threading import Control.Lens import Data.Aeson import Data.Aeson.Lens import GHC.IO.Handle hiding (hGetLine) import System.Command import System.IO (hReady) import ClassyPrelude import Haskakafka startRink :: Text -> IO (Maybe (Handle, Handle)) startRink rinkPath = do let rinkCmd = rinkPath ++ " -" (hInM, hOutM, _, _) <- createProcess (shell $ unpack rinkCmd) { std_out = CreatePipe, std_in = CreatePipe } return $ do hIn <- hInM hOut <- hOutM return (hIn, hOut) readHandleUntilNotReady :: Handle -> IO Text readHandleUntilNotReady hIn = let readOutput handle results = do handleReady <- hReady handle case handleReady of False -> return (unlines results) True -> do line <- hGetLine handle readOutput handle (mappend results [line]) in readOutput hIn [] runRinkCmd :: (Handle, Handle) -> Text -> IO Text runRinkCmd (hIn, hOut) cmdStr = do let newCmdStr = ((replaceSeqStrictText "&gt;" ">") . (replaceSeqStrictText "&lt;" "<")) cmdStr hPutStrLn hIn newCmdStr hFlush hIn --readHandleUntilNotReady hOut hGetLine hOut rinkCmdLooper :: (Handle, Handle) -> TChan SlackMessage -> TChan Text -> IO () rinkCmdLooper (hIn, hOut) cmdQueue outQueue = do cmd <- atomically $ readTChan cmdQueue let rawInput = message cmd case (tailMay $ words rawInput) of Nothing -> rinkCmdLooper (hIn, hOut) cmdQueue outQueue Just others -> do output <- runRinkCmd (hIn, hOut) (unwords others) let outputStripped = stripSuffix "\n" output case outputStripped of Nothing -> atomically $ writeTChan outQueue $ slackPayloadWithChannel (channel cmd) output Just stripped -> atomically $ writeTChan outQueue $ slackPayloadWithChannel (channel cmd) stripped rinkCmdLooper (hIn, hOut) cmdQueue outQueue consumer :: TChan Text -> Kafka -> KafkaTopic -> IO () consumer queue kafka topic = do messageE <- consumeMessage topic 0 10000 case messageE of Left (KafkaResponseError _) -> return () Left err -> do putStrLn $ "Kafka error: " ++ tshow err Right msg -> do let writeQueue = writeTChan queue atomically $ (writeQueue . asText . decodeUtf8 . asByteString . messagePayload) msg consumer queue kafka topic producer :: TChan Text -> Kafka -> KafkaTopic -> IO () producer queue kafka topic = do msg <- atomically $ readTChan queue putStrLn $ "producer: " ++ msg produceMessage topic KafkaUnassignedPartition (KafkaProduceMessage $ encodeUtf8 msg) producer queue kafka topic echoEmitter :: SlackMessage -> IO Text echoEmitter msg = do return $ slackPayloadWithChannel (channel msg) "Hollo!" papikaEmitter :: SlackMessage -> IO Text papikaEmitter msg = return $ slackPayloadWithChannel (channel msg) "Cocona!" kafkaProducerThread :: Text -> Text -> TChan Text -> IO () kafkaProducerThread brokerString topicName producerQueue = do withKafkaProducer [] [] (unpack brokerString) (unpack topicName) (producer producerQueue) return () kafkaConsumerThread :: Text -> Text -> TChan Text -> IO () kafkaConsumerThread brokerString topicName consumerQueue = do withKafkaConsumer [] [("offset.store.method", "file")] (unpack brokerString) (unpack topicName) 0 (KafkaOffsetStored) (consumer consumerQueue) return () emitterThread :: (TChan SlackMessage -> TChan Text -> STM ()) -> TChan SlackMessage -> TChan Text -> IO () emitterThread emitter inQueue outQueue = do atomically $ emitter inQueue outQueue emitterThread emitter inQueue outQueue rinkThread :: Text -> TChan SlackMessage -> TChan Text -> IO () rinkThread rinkPath inputQueue outputQueue = do handlesM <- startRink rinkPath case handlesM of Nothing -> do putStrLn "Error opening up rink" return () Just (hIn, hOut) -> do hSetBinaryMode hIn False hSetBinaryMode hOut False rinkCmdLooper (hIn, hOut) inputQueue outputQueue mainFunc :: FilePath -> IO () mainFunc configPath = do botConfigE <- getBotConfig configPath case botConfigE of Left err -> do hPutStrLn stderr $ asText "Could not parse config, using defaults" hPutStrLn stderr $ tshow err Right _ -> return () putStrLn "Starting Kokona" consumerQueue <- newTChanIO producerQueue <- newTChanIO let (brokerString, consumerTopicString, producerTopicString, rinkPathStr) = case botConfigE of Left _ -> ("localhost:9092", "consumer", "producer", "rink") Right cfg -> ( (brokerAddr cfg), (consumerTopic cfg), (producerTopic cfg), (rinkPath cfg) ) let holloAcceptor = startMessageAcceptor "!hollo" let calcAcceptor = startMessageAcceptor "!calc" let dhggsAcceptor = startMessageAcceptor "dhggs" let fortuneAcceptor = startMessageAcceptor "!fortune" let papikaAcceptor = textInMessageAcceptor "papika" let cmdThreadWithQueue = botCommandThread consumerQueue producerQueue cmdThreadWithQueue holloAcceptor (loopProcessor echoEmitter) cmdThreadWithQueue calcAcceptor (rinkThread rinkPathStr) cmdThreadWithQueue dhggsAcceptor (loopProcessor kanshaEmitter) cmdThreadWithQueue fortuneAcceptor (loopProcessor fortuneEmitter) -- cmdThreadWithQueue papikaAcceptor (loopProcessor papikaEmitter) producerTId <- fork (kafkaProducerThread brokerString producerTopicString producerQueue) kafkaConsumerThread brokerString consumerTopicString consumerQueue putStrLn $ tshow producerTId
Koshroy/kokona
src/Lib.hs
Haskell
bsd-3-clause
5,671