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 Image
YoshikuniJujo/markdown2svg
tests/testImage.hs
Haskell
bsd-3-clause
13
module Opaleye.Internal.Order where import qualified Opaleye.Column as C import qualified Opaleye.Internal.Tag as T import qualified Opaleye.Internal.PrimQuery as PQ import qualified Database.HaskellDB.PrimQuery as HPQ import qualified Data.Functor.Contravariant as C import qualified Data.Profunctor as P import qualified Data.Monoid as M -- FIXME: make capitilisation of Specs consistent with UnpackSpec data SingleOrderSpec a = SingleOrderSpec HPQ.OrderOp (a -> HPQ.PrimExpr) instance C.Contravariant SingleOrderSpec where contramap f (SingleOrderSpec op g) = SingleOrderSpec op (P.lmap f g) newtype OrderSpec a = OrderSpec [SingleOrderSpec a] instance C.Contravariant OrderSpec where contramap f (OrderSpec xs) = OrderSpec (fmap (C.contramap f) xs) instance M.Monoid (OrderSpec a) where mempty = OrderSpec M.mempty OrderSpec o `mappend` OrderSpec o' = OrderSpec (o `M.mappend` o') orderSpec :: HPQ.OrderOp -> (a -> C.Column b) -> OrderSpec a orderSpec op f = C.contramap f (OrderSpec [SingleOrderSpec op C.unColumn]) orderByU :: OrderSpec a -> (a, PQ.PrimQuery, T.Tag) -> (a, PQ.PrimQuery, T.Tag) orderByU os (columns, primQ, t) = (columns, primQ', t) where primQ' = PQ.Order orderExprs primQ OrderSpec sos = os orderExprs = map (\(SingleOrderSpec op f) -> HPQ.OrderExpr op (f columns)) sos limit' :: Int -> (a, PQ.PrimQuery, T.Tag) -> (a, PQ.PrimQuery, T.Tag) limit' n (x, q, t) = (x, PQ.Limit (PQ.LimitOp n) q, t) offset' :: Int -> (a, PQ.PrimQuery, T.Tag) -> (a, PQ.PrimQuery, T.Tag) offset' n (x, q, t) = (x, PQ.Limit (PQ.OffsetOp n) q, t)
k0001/haskell-opaleye
Opaleye/Internal/Order.hs
Haskell
bsd-3-clause
1,611
module Test6 where import qualified Data.HashMap.Strict as H import qualified Data.Text as T import qualified Data.Text.IO as T import Data.List import Debug.Trace import System.IO isAlpha ch = ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') wrds :: T.Text -> [ T.Text ] wrds bs = let (_, r1) = T.span (not . isAlpha) bs (w, r2) = T.span isAlpha r1 in if T.null w then [] else T.toLower w : wrds r2 readDict = do let add h w = let c = H.lookupDefault (0 :: Int) w h in H.insert w (c+1) h loop h fh = do b <- hIsEOF fh if b then return h else do cs <- T.hGetLine fh let h' = foldl' add h (wrds cs) loop h' fh h <- withFile "big.txt" ReadMode (loop H.empty) let member = \k -> H.member k h frequency = \k -> H.lookupDefault 0 k h return (member, frequency, T.pack)
erantapaa/test-spelling
src/Test6.hs
Haskell
bsd-3-clause
942
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} module Development.Shake.Install.RequestResponse where import Development.Shake as Shake import Control.Applicative import Data.Data import Data.Binary import Control.DeepSeq import Data.Hashable data Request a = Request deriving (Show) deriving instance Typeable Request instance NFData (Request a) where rnf _ = () instance Eq (Request a) where _ == _ = True instance Hashable (Request a) where hashWithSalt _ _ = 1 instance Binary (Request a) where get = return Request put _ = return () data Response a = Response{unResponse :: a} deriving instance Show a => Show (Response a) deriving instance Read a => Read (Response a) deriving instance Eq a => Eq (Response a) deriving instance Ord a => Ord (Response a) deriving instance Typeable1 Response instance Hashable a => Hashable (Response a) where hashWithSalt s (Response x) = hashWithSalt s x instance Binary a => Binary (Response a) where get = fmap Response get put (Response x) = put x instance NFData a => NFData (Response a) where rnf (Response x) = rnf x `seq` () instance (Show a, Binary a, NFData a, Typeable a, Hashable a, Eq a) => Rule (Request a) (Response a) where storedValue _ = return Nothing requestOf :: forall a b . Rule (Request a) (Response a) => (a -> b) -- ^ record field selector -> Action b requestOf fun = fun . unResponse <$> apply1 (Request :: Request a)
alphaHeavy/shake-install
Development/Shake/Install/RequestResponse.hs
Haskell
bsd-3-clause
1,597
{-# LANGUAGE Arrows #-} import Hatter import Hatter.Types import Hatter.Wires import Control.Wire as Wire hiding (id) import Control.Arrow import Control.Applicative import FRP.Netwire hiding (id) import Prelude hiding ((.), null, filter) import Data.Map as Map hiding (foldl) import Linear hiding (trace) import Debug.Trace initialGameState :: GameState String initialGameState = createInitialState (Map.fromList [(oid squareObject,squareObject)]) "" objectName :: String objectName = assetDirPath ++ "square.png" squareObject :: GameObject squareObject = GameObject "square1" (V2 2 2) Hatter.Types.None (Image $ Hatter.Types.Sprite objectName 100 100) myGameWire :: (Real t, HasTime t s) => Wire s e IO (GameState String) (Map String GameObject) myGameWire = proc state -> do let object = head $ Map.elems $ gameObjects state newposition <- positionWire identityCorrectionFunction (V2 0 0) (velocityWire identityCorrectionFunction $ V2 0 0) (constantAcceleration $ V2 0.1 0.03) -< state let newobject = GameObject {oid=oid object, position=newposition, boundingBox=boundingBox object, gameGraphic=gameGraphic object} returnA -< (Map.fromList [(oid newobject, newobject)]) --TODO: Provide function to form new game object with updated position myEventCheckers :: Map String (GameState String -> ()) myEventCheckers = Map.fromList [] assetDirPath :: String assetDirPath = "/Users/apple/Documents/Academics/sem9/FP/Hatter/examples/assets/" canvas :: Canvas canvas = Canvas 1000 1000 "Square" main = run myGameDefinition canvas initialGameState myGameDefinition = GameDefinition { gameWire=myGameWire , eventCheckers=myEventCheckers , frameRate=20 , externalState="" , assetDir=assetDirPath }
shivanshuag/Hatter
examples/square_using_wires.hs
Haskell
bsd-3-clause
1,899
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} module Main where ------------------------------------------------------------------------------ import Control.Exception (SomeException, try) import qualified Data.Text as T import Site import Snap.Core import Snap.Http.Server import Snap.Snaplet import Snap.Snaplet.Config import System.IO #ifdef DEVELOPMENT import Snap.Loader.Dynamic #else import Snap.Loader.Static #endif ------------------------------------------------------------------------------ -- | This is the entry point for this web server application. It supports -- easily switching between interpreting source and running statically compiled -- code. -- -- In either mode, the generated program should be run from the root of the -- project tree. When it is run, it locates its templates, static content, and -- source files in development mode, relative to the current working directory. -- -- When compiled with the development flag, only changes to the libraries, your -- cabal file, or this file should require a recompile to be picked up. -- Everything else is interpreted at runtime. There are a few consequences of -- this. -- -- First, this is much slower. Running the interpreter takes a significant -- chunk of time (a couple tenths of a second on the author's machine, at this -- time), regardless of the simplicity of the loaded code. In order to -- recompile and re-load server state as infrequently as possible, the source -- directories are watched for updates, as are any extra directories specified -- below. -- -- Second, the generated server binary is MUCH larger, since it links in the -- GHC API (via the hint library). -- -- Third, and the reason you would ever want to actually compile with -- development mode, is that it enables a faster development cycle. You can -- simply edit a file, save your changes, and hit reload to see your changes -- reflected immediately. -- -- When this is compiled without the development flag, all the actions are -- statically compiled in. This results in faster execution, a smaller binary -- size, and having to recompile the server for any code change. -- main :: IO () main = do -- Depending on the version of loadSnapTH in scope, this either enables -- dynamic reloading, or compiles it without. The last argument to -- loadSnapTH is a list of additional directories to watch for changes to -- trigger reloads in development mode. It doesn't need to include source -- directories, those are picked up automatically by the splice. (conf, site, cleanup) <- $(loadSnapTH [| getConf |] 'getActions ["snaplets/heist/templates"]) _ <- try $ httpServe conf site :: IO (Either SomeException ()) cleanup ------------------------------------------------------------------------------ -- | This action loads the config used by this application. The loaded config -- is returned as the first element of the tuple produced by the loadSnapTH -- Splice. The type is not solidly fixed, though it must be an IO action that -- produces the same type as 'getActions' takes. It also must be an instance of -- Typeable. If the type of this is changed, a full recompile will be needed to -- pick up the change, even in development mode. -- -- This action is only run once, regardless of whether development or -- production mode is in use. getConf :: IO (Config Snap AppConfig) getConf = commandLineAppConfig defaultConfig ------------------------------------------------------------------------------ -- | This function generates the the site handler and cleanup action from the -- configuration. In production mode, this action is only run once. In -- development mode, this action is run whenever the application is reloaded. -- -- Development mode also makes sure that the cleanup actions are run -- appropriately before shutdown. The cleanup action returned from loadSnapTH -- should still be used after the server has stopped handling requests, as the -- cleanup actions are only automatically run when a reload is triggered. -- -- This sample doesn't actually use the config passed in, but more -- sophisticated code might. getActions :: Config Snap AppConfig -> IO (Snap (), IO ()) getActions conf = do (msgs, site, cleanup) <- runSnaplet (appEnvironment =<< getOther conf) app hPutStrLn stderr $ T.unpack msgs return (site, cleanup)
HaskellCNOrg/snaplet-oauth
example/src/Main.hs
Haskell
bsd-3-clause
4,565
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} module MongoDbConnector where import Control.Monad (when) import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Data.Text (pack, unpack) import Data.Time.Clock (UTCTime, getCurrentTime) import Data.Time.Format (defaultTimeLocale, formatTime) import Database.MongoDB import System.Environment (getArgs, getProgName, lookupEnv) import System.Log.Logger connectToDatabase :: Action IO a -> IO a connectToDatabase act = do pipe <- connect (host "127.0.0.1") access pipe master "GluonDatabase" act drainCursor :: Cursor -> Action IO [Document] drainCursor cur = drainCursor' cur [] where drainCursor' cur res = do batch <- nextBatch cur if null batch then return res else drainCursor' cur (res ++ batch)
Coggroach/Gluon
src/MongoDbConnector.hs
Haskell
bsd-3-clause
1,299
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} -- | <http://www.libtorrent.org/reference-Core.html#peer-info peer_info> structure for "Libtorrent" module Network.Libtorrent.PeerInfo (PeerFlags(..) , PeerSourceFlags(..) , ConnectionType(..) , BwState(..) , PeerInfo(..) , getClient , setClient , getPeerInfoPieces , setPeerInfoPieces , getPeerInfoTotalDownload , setPeerInfoTotalDownload , getPeerInfoTotalUpload , setPeerInfoTotalUpload , getLastRequest , setLastRequest , getLastActive , setLastActive , getDownloadQueueTime , setDownloadQueueTime , getPeerInfoFlags , setPeerInfoFlags , getPeerInfoSource , setPeerInfoSource , getUpSpeed , setUpSpeed , getDownSpeed , setDownSpeed , getPayloadUpSpeed , setPayloadUpSpeed , getPayloadDownSpeed , setPayloadDownSpeed , getPid , setPid , getQueueBytes , setQueueBytes , getPeerInfoRequestTimeout , setPeerInfoRequestTimeout , getSendBufferSize , setSendBufferSize , getUsedSendBuffer , setUsedSendBuffer , getReceiveBufferSize , setReceiveBufferSize , getUsedReceiveBuffer , setUsedReceiveBuffer , getNumHashfails , setNumHashfails , getDownloadQueueLength , setDownloadQueueLength , getTimedOutRequests , setTimedOutRequests , getBusyRequests , setBusyRequests , getRequestsInBuffer , setRequestsInBuffer , getTargetDlQueueLength , setTargetDlQueueLength , getUploadQueueLength , setUploadQueueLength , getFailcount , setFailcount , getDownloadingPieceIndex , setDownloadingPieceIndex , getDownloadingBlockIndex , setDownloadingBlockIndex , getDownloadingProgress , setDownloadingProgress , getDownloadingTotal , setDownloadingTotal , getConnectionType , setConnectionType , getRemoteDlRate , setRemoteDlRate , getPendingDiskBytes , setPendingDiskBytes , getSendQuota , setSendQuota , getReceiveQuota , setReceiveQuota , getRtt , setRtt , getPeerInfoNumPieces , setPeerInfoNumPieces , getDownloadRatePeak , setDownloadRatePeak , getUploadRatePeak , setUploadRatePeak , getPeerInfoProgressPpm , setPeerInfoProgressPpm , getEstimatedReciprocationRate , setEstimatedReciprocationRate , getIp , getLocalEndpoint , getReadState , setReadState , getWriteState , setWriteState ) where import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Array.BitArray (BitArray) import Data.Int (Int64) import Data.Text (Text) import qualified Data.Text.Foreign as TF import Data.Word (Word64) import Foreign.C.Types (CInt) import Foreign.ForeignPtr (ForeignPtr, withForeignPtr) import qualified Language.C.Inline as C import qualified Language.C.Inline.Cpp as C import qualified Language.C.Inline.Unsafe as CU import Network.Libtorrent.Bitfield import Network.Libtorrent.Inline import Network.Libtorrent.Internal import Network.Libtorrent.Sha1Hash import Network.Libtorrent.String import Network.Libtorrent.Types C.context libtorrentCtx C.include "<libtorrent/peer_info.hpp>" C.include "<libtorrent/torrent_handle.hpp>" C.include "torrent_handle.hpp" C.using "namespace libtorrent" C.using "namespace std" data PeerFlags = Interesting | Choked | RemoteInterested | RemoteChoked | SupportsExtensions | LocalConnection | Handshake | Connecting | Queued | OnParole | Seed | OptimisticUnchoke | Snubbed | UploadOnly | EndgameMode | Holepunched | I2pSocket | UtpSocket | SslSocket | Rc4Encrypted | PlaintextEncrypted deriving (Show, Enum, Bounded, Eq, Ord) data PeerSourceFlags = Tracker | Dht | Pex | Lsd | ResumeData | Incoming deriving (Show, Enum, Bounded, Eq, Ord) data ConnectionType = StandardBittorrent | WebSeed | HttpSeed deriving (Show, Enum, Bounded, Eq, Ord) data BwState = BwIdle | BwLimit | BwNetwork | BwDisk deriving (Show, Enum, Bounded, Eq, Ord) newtype PeerInfo = PeerInfo { unPeerInfo :: ForeignPtr (CType PeerInfo)} instance Show PeerInfo where show _ = "PeerInfo" instance Inlinable PeerInfo where type (CType PeerInfo) = C'PeerInfo instance FromPtr PeerInfo where fromPtr = objFromPtr PeerInfo $ \ptr -> [CU.exp| void { delete $(peer_info * ptr); } |] instance WithPtr PeerInfo where withPtr (PeerInfo fptr) = withForeignPtr fptr getClient :: MonadIO m => PeerInfo -> m Text getClient ho = liftIO . withPtr ho $ \hoPtr -> do res <- fromPtr [CU.exp| string * { new std::string($(peer_info * hoPtr)->client) } |] stdStringToText res setClient :: MonadIO m => PeerInfo -> Text -> m () setClient ho val = do liftIO . TF.withCStringLen val $ \(cstr, len) -> do let clen = fromIntegral len liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->client = std::string($(const char * cstr), $(size_t clen))} |] getPeerInfoPieces :: MonadIO m => PeerInfo -> m (BitArray Int) getPeerInfoPieces ho = liftIO . withPtr ho $ \hoPtr -> do bf <- fromPtr [CU.exp| bitfield * { new bitfield($(peer_info * hoPtr)->pieces) } |] bitfieldToBitArray bf setPeerInfoPieces :: MonadIO m => PeerInfo -> (BitArray Int) -> m () setPeerInfoPieces ho ba = liftIO $ do bf <- bitArrayToBitfield ba withPtr bf $ \bfPtr -> withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->pieces = bitfield(*$(bitfield * bfPtr))} |] getPeerInfoTotalDownload :: MonadIO m => PeerInfo -> m Int64 getPeerInfoTotalDownload ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int64_t { $(peer_info * hoPtr)->total_download } |] setPeerInfoTotalDownload :: MonadIO m => PeerInfo -> Int64 -> m () setPeerInfoTotalDownload ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->total_download = $(int64_t val)} |] getPeerInfoTotalUpload :: MonadIO m => PeerInfo -> m Int64 getPeerInfoTotalUpload ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int64_t { $(peer_info * hoPtr)->total_upload } |] setPeerInfoTotalUpload :: MonadIO m => PeerInfo -> Int64 -> m () setPeerInfoTotalUpload ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->total_upload = $(int64_t val)} |] getLastRequest :: MonadIO m => PeerInfo -> m Word64 getLastRequest ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| uint64_t { $(peer_info * hoPtr)->last_request.diff } |] setLastRequest :: MonadIO m => PeerInfo -> Word64 -> m () setLastRequest ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->last_request = time_duration($(uint64_t val))} |] getLastActive :: MonadIO m => PeerInfo -> m Word64 getLastActive ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| uint64_t { $(peer_info * hoPtr)->last_active.diff } |] setLastActive :: MonadIO m => PeerInfo -> Word64 -> m () setLastActive ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->last_active = time_duration($(uint64_t val))} |] getDownloadQueueTime :: MonadIO m => PeerInfo -> m Word64 getDownloadQueueTime ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| uint64_t { $(peer_info * hoPtr)->download_queue_time.diff } |] setDownloadQueueTime :: MonadIO m => PeerInfo -> Word64 -> m () setDownloadQueueTime ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->download_queue_time = time_duration($(uint64_t val))} |] getPeerInfoFlags :: MonadIO m => PeerInfo -> m (BitFlags PeerFlags) getPeerInfoFlags ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| int32_t{ $(peer_info * hoPtr)->flags } |] setPeerInfoFlags :: MonadIO m => PeerInfo -> BitFlags PeerFlags -> m () setPeerInfoFlags ho flags = do let val = fromIntegral $ fromEnum flags liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->flags = $(int32_t val)} |] getPeerInfoSource :: MonadIO m => PeerInfo -> m (BitFlags PeerSourceFlags) getPeerInfoSource ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| int32_t { $(peer_info * hoPtr)->source } |] setPeerInfoSource :: MonadIO m => PeerInfo -> BitFlags PeerSourceFlags -> m () setPeerInfoSource ho flags = do let val = fromIntegral $ fromEnum flags liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->source = $(int32_t val)} |] getUpSpeed :: MonadIO m => PeerInfo -> m CInt getUpSpeed ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->up_speed } |] setUpSpeed :: MonadIO m => PeerInfo -> CInt -> m () setUpSpeed ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->up_speed = $(int val)} |] getDownSpeed :: MonadIO m => PeerInfo -> m CInt getDownSpeed ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->down_speed } |] setDownSpeed :: MonadIO m => PeerInfo -> CInt -> m () setDownSpeed ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->down_speed = $(int val)} |] getPayloadUpSpeed :: MonadIO m => PeerInfo -> m CInt getPayloadUpSpeed ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->payload_up_speed } |] setPayloadUpSpeed :: MonadIO m => PeerInfo -> CInt -> m () setPayloadUpSpeed ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->payload_up_speed = $(int val)} |] getPayloadDownSpeed :: MonadIO m => PeerInfo -> m CInt getPayloadDownSpeed ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->payload_down_speed } |] setPayloadDownSpeed :: MonadIO m => PeerInfo -> CInt -> m () setPayloadDownSpeed ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->payload_down_speed = $(int val)} |] getPid :: MonadIO m => PeerInfo -> m Sha1Hash getPid ho = liftIO . withPtr ho $ \hoPtr -> do fromPtr [CU.exp| sha1_hash * { new sha1_hash($(peer_info * hoPtr)->pid) } |] setPid :: MonadIO m => PeerInfo -> Sha1Hash -> m () setPid ho val = liftIO . withPtr ho $ \hoPtr -> withPtr val $ \valPtr -> [CU.exp| void { $(peer_info * hoPtr)->pid = sha1_hash(*$(sha1_hash * valPtr)) } |] getQueueBytes :: MonadIO m => PeerInfo -> m CInt getQueueBytes ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->queue_bytes } |] setQueueBytes :: MonadIO m => PeerInfo -> CInt -> m () setQueueBytes ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->queue_bytes = $(int val)} |] getPeerInfoRequestTimeout :: MonadIO m => PeerInfo -> m CInt getPeerInfoRequestTimeout ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->request_timeout } |] setPeerInfoRequestTimeout :: MonadIO m => PeerInfo -> CInt -> m () setPeerInfoRequestTimeout ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->request_timeout = $(int val)} |] getSendBufferSize :: MonadIO m => PeerInfo -> m CInt getSendBufferSize ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->send_buffer_size } |] setSendBufferSize :: MonadIO m => PeerInfo -> CInt -> m () setSendBufferSize ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->send_buffer_size = $(int val)} |] getUsedSendBuffer :: MonadIO m => PeerInfo -> m CInt getUsedSendBuffer ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->used_send_buffer } |] setUsedSendBuffer :: MonadIO m => PeerInfo -> CInt -> m () setUsedSendBuffer ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->used_send_buffer = $(int val)} |] getReceiveBufferSize :: MonadIO m => PeerInfo -> m CInt getReceiveBufferSize ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->receive_buffer_size } |] setReceiveBufferSize :: MonadIO m => PeerInfo -> CInt -> m () setReceiveBufferSize ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->receive_buffer_size = $(int val)} |] getUsedReceiveBuffer :: MonadIO m => PeerInfo -> m CInt getUsedReceiveBuffer ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->used_receive_buffer } |] setUsedReceiveBuffer :: MonadIO m => PeerInfo -> CInt -> m () setUsedReceiveBuffer ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->used_receive_buffer = $(int val)} |] getNumHashfails :: MonadIO m => PeerInfo -> m CInt getNumHashfails ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->num_hashfails } |] setNumHashfails :: MonadIO m => PeerInfo -> CInt -> m () setNumHashfails ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->num_hashfails = $(int val)} |] getDownloadQueueLength :: MonadIO m => PeerInfo -> m CInt getDownloadQueueLength ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->download_queue_length } |] setDownloadQueueLength :: MonadIO m => PeerInfo -> CInt -> m () setDownloadQueueLength ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->download_queue_length = $(int val)} |] getTimedOutRequests :: MonadIO m => PeerInfo -> m CInt getTimedOutRequests ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->timed_out_requests } |] setTimedOutRequests :: MonadIO m => PeerInfo -> CInt -> m () setTimedOutRequests ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->timed_out_requests = $(int val)} |] getBusyRequests :: MonadIO m => PeerInfo -> m CInt getBusyRequests ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->busy_requests } |] setBusyRequests :: MonadIO m => PeerInfo -> CInt -> m () setBusyRequests ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->busy_requests = $(int val)} |] getRequestsInBuffer :: MonadIO m => PeerInfo -> m CInt getRequestsInBuffer ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->requests_in_buffer } |] setRequestsInBuffer :: MonadIO m => PeerInfo -> CInt -> m () setRequestsInBuffer ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->requests_in_buffer = $(int val)} |] getTargetDlQueueLength :: MonadIO m => PeerInfo -> m CInt getTargetDlQueueLength ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->target_dl_queue_length } |] setTargetDlQueueLength :: MonadIO m => PeerInfo -> CInt -> m () setTargetDlQueueLength ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->target_dl_queue_length = $(int val)} |] getUploadQueueLength :: MonadIO m => PeerInfo -> m CInt getUploadQueueLength ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->upload_queue_length } |] setUploadQueueLength :: MonadIO m => PeerInfo -> CInt -> m () setUploadQueueLength ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->upload_queue_length = $(int val)} |] getFailcount :: MonadIO m => PeerInfo -> m CInt getFailcount ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->failcount } |] setFailcount :: MonadIO m => PeerInfo -> CInt -> m () setFailcount ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->failcount = $(int val)} |] getDownloadingPieceIndex :: MonadIO m => PeerInfo -> m CInt getDownloadingPieceIndex ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->downloading_piece_index } |] setDownloadingPieceIndex :: MonadIO m => PeerInfo -> CInt -> m () setDownloadingPieceIndex ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->downloading_piece_index = $(int val)} |] getDownloadingBlockIndex :: MonadIO m => PeerInfo -> m CInt getDownloadingBlockIndex ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->downloading_block_index } |] setDownloadingBlockIndex :: MonadIO m => PeerInfo -> CInt -> m () setDownloadingBlockIndex ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->downloading_block_index = $(int val)} |] getDownloadingProgress :: MonadIO m => PeerInfo -> m CInt getDownloadingProgress ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->downloading_progress } |] setDownloadingProgress :: MonadIO m => PeerInfo -> CInt -> m () setDownloadingProgress ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->downloading_progress = $(int val)} |] getDownloadingTotal :: MonadIO m => PeerInfo -> m CInt getDownloadingTotal ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->downloading_total } |] setDownloadingTotal :: MonadIO m => PeerInfo -> CInt -> m () setDownloadingTotal ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->downloading_total = $(int val)} |] getConnectionType :: MonadIO m => PeerInfo -> m ConnectionType getConnectionType ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| int { $(peer_info * hoPtr)->connection_type } |] setConnectionType :: MonadIO m => PeerInfo -> ConnectionType -> m () setConnectionType ho flag = do let val = fromIntegral $ fromEnum flag liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->connection_type = $(int val)} |] getRemoteDlRate :: MonadIO m => PeerInfo -> m CInt getRemoteDlRate ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->remote_dl_rate } |] setRemoteDlRate :: MonadIO m => PeerInfo -> CInt -> m () setRemoteDlRate ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->remote_dl_rate = $(int val)} |] getPendingDiskBytes :: MonadIO m => PeerInfo -> m CInt getPendingDiskBytes ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->pending_disk_bytes } |] setPendingDiskBytes :: MonadIO m => PeerInfo -> CInt -> m () setPendingDiskBytes ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->pending_disk_bytes = $(int val)} |] -- getPendingDiskReadBytes :: MonadIO m => PeerInfo -> m CInt -- getPendingDiskReadBytes ho = -- liftIO . withPtr ho $ \hoPtr -> -- [CU.exp| int { $(peer_info * hoPtr)->pending_disk_read_bytes } |] -- setPendingDiskReadBytes :: MonadIO m => PeerInfo -> CInt -> m () -- setPendingDiskReadBytes ho val = -- liftIO . withPtr ho $ \hoPtr -> -- [CU.exp| void { $(peer_info * hoPtr)->pending_disk_read_bytes = $(int val)} |] getSendQuota :: MonadIO m => PeerInfo -> m CInt getSendQuota ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->send_quota } |] setSendQuota :: MonadIO m => PeerInfo -> CInt -> m () setSendQuota ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->send_quota = $(int val)} |] getReceiveQuota :: MonadIO m => PeerInfo -> m CInt getReceiveQuota ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->receive_quota } |] setReceiveQuota :: MonadIO m => PeerInfo -> CInt -> m () setReceiveQuota ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->receive_quota = $(int val)} |] getRtt :: MonadIO m => PeerInfo -> m CInt getRtt ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->rtt } |] setRtt :: MonadIO m => PeerInfo -> CInt -> m () setRtt ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->rtt = $(int val)} |] getPeerInfoNumPieces :: MonadIO m => PeerInfo -> m CInt getPeerInfoNumPieces ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->num_pieces } |] setPeerInfoNumPieces :: MonadIO m => PeerInfo -> CInt -> m () setPeerInfoNumPieces ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->num_pieces = $(int val)} |] getDownloadRatePeak :: MonadIO m => PeerInfo -> m CInt getDownloadRatePeak ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->download_rate_peak } |] setDownloadRatePeak :: MonadIO m => PeerInfo -> CInt -> m () setDownloadRatePeak ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->download_rate_peak = $(int val)} |] getUploadRatePeak :: MonadIO m => PeerInfo -> m CInt getUploadRatePeak ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->upload_rate_peak } |] setUploadRatePeak :: MonadIO m => PeerInfo -> CInt -> m () setUploadRatePeak ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->upload_rate_peak = $(int val)} |] getPeerInfoProgressPpm :: MonadIO m => PeerInfo -> m CInt getPeerInfoProgressPpm ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->progress_ppm } |] setPeerInfoProgressPpm :: MonadIO m => PeerInfo -> CInt -> m () setPeerInfoProgressPpm ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->progress_ppm = $(int val)} |] getEstimatedReciprocationRate :: MonadIO m => PeerInfo -> m CInt getEstimatedReciprocationRate ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(peer_info * hoPtr)->estimated_reciprocation_rate } |] setEstimatedReciprocationRate :: MonadIO m => PeerInfo -> CInt -> m () setEstimatedReciprocationRate ho val = liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->estimated_reciprocation_rate = $(int val)} |] getIp :: MonadIO m => PeerInfo -> m (Text, C.CShort) getIp ho = liftIO . withPtr ho $ \hoPtr -> do addr <- fromPtr [CU.block| string * { tcp::endpoint ep = $(peer_info * hoPtr)->ip; return new std::string(ep.address().to_string()); } |] port <- [CU.block| short { tcp::endpoint ep = $(peer_info * hoPtr)->ip; return ep.port(); } |] ( , port) <$> stdStringToText addr getLocalEndpoint :: MonadIO m => PeerInfo -> m (Text, C.CShort) getLocalEndpoint ho = liftIO . withPtr ho $ \hoPtr -> do addr <- fromPtr [CU.block| string * { tcp::endpoint ep = $(peer_info * hoPtr)->local_endpoint; return new std::string(ep.address().to_string()); } |] port <- [CU.block| short { tcp::endpoint ep = $(peer_info * hoPtr)->local_endpoint; return ep.port(); } |] ( , port) <$> stdStringToText addr getReadState :: MonadIO m => PeerInfo -> m (BitFlags BwState) getReadState ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| char { $(peer_info * hoPtr)->read_state } |] setReadState :: MonadIO m => PeerInfo -> BitFlags BwState -> m () setReadState ho flags = do let val = fromIntegral $ fromEnum flags liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->read_state = $(char val)} |] getWriteState :: MonadIO m => PeerInfo -> m (BitFlags BwState) getWriteState ho = liftIO . withPtr ho $ \hoPtr -> toEnum . fromIntegral <$> [CU.exp| char { $(peer_info * hoPtr)->write_state } |] setWriteState :: MonadIO m => PeerInfo -> BitFlags BwState -> m () setWriteState ho flags = do let val = fromIntegral $ fromEnum flags liftIO . withPtr ho $ \hoPtr -> [CU.exp| void { $(peer_info * hoPtr)->write_state = $(char val)} |]
eryx67/haskell-libtorrent
src/Network/Libtorrent/PeerInfo.hs
Haskell
bsd-3-clause
26,211
{-# LANGUAGE UndecidableInstances, FlexibleInstances, FlexibleContexts, TypeFamilies, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.Signal.Multichannel -- Copyright : (c) Alexander Vivian Hugh McPhail 2010, 2014, 2015, 2016 -- License : BSD3 -- -- Maintainer : haskell.vivian.mcphail <at> gmail <dot> com -- Stability : provisional -- Portability : uses Concurrency -- -- Signal processing functions, multichannel datatype -- -- link with '-threaded' and run with +RTS -Nn, where n is the number of CPUs -- ----------------------------------------------------------------------------- -- IncoherentInstances, module Numeric.Signal.Multichannel ( Multichannel,readMultichannel,writeMultichannel, createMultichannel, sampling_rate,precision,channels,samples, detrended,filtered, getChannel,getChannels, toMatrix, mapConcurrently, detrend,filter, slice, histograms, entropy_delta_phase,mi_phase ) where ----------------------------------------------------------------------------- import qualified Numeric.Signal as S --import Complex import qualified Data.Array.IArray as I import Data.Ix --import Data.Word import Control.Concurrent --import Control.Concurrent.MVar import System.IO.Unsafe(unsafePerformIO) --import qualified Data.List as L import Data.Binary import Data.Maybe import Foreign.Storable import Numeric.LinearAlgebra hiding(range) import qualified Data.Vector.Generic as GV --import qualified Numeric.GSL.Fourier as F import qualified Numeric.GSL.Histogram as H import qualified Numeric.GSL.Histogram2D as H2 import qualified Numeric.Statistics.Information as SI import Prelude hiding(filter) import Control.Monad(replicateM) {- ------------------------------------------------------------------- instance (Binary a, Storable a) => Binary (Vector a) where put v = do let d = GV.length v put d mapM_ (\i -> put $ v @> i) [0..(d-1)] get = do d <- get xs <- replicateM d get return $ fromList xs ------------------------------------------------------------------- -} ----------------------------------------------------------------------------- -- | data type with multiple channels data Multichannel a = MC { _sampling_rate :: Int -- ^ sampling rate , _precision :: Int -- ^ bits of precision , _channels :: Int -- ^ number of channels , _length :: Int -- ^ length in samples , _detrended :: Bool -- ^ was the data detrended? , _filtered :: Maybe (Int,Int) -- ^ if filtered the passband , _data :: I.Array Int (Vector a) -- ^ data } ----------------------------------------------------------------------------- instance Binary (Multichannel Double) where put (MC s p c l de f d) = do put s put p put c put l put de put f put $! fmap convert d where convert v = let (mi,ma) = (minElement v,maxElement v) v' = GV.map (\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v in (mi,ma,v' :: Vector Word64) get = do s <- get p <- get c <- get l <- get de <- get f <- get (d :: I.Array Int (Double,Double,Vector Word64)) <- get return $! (MC s p c l de f (seq d (fmap convert) d)) where convert (mi,ma,v) = GV.map (\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word64)) * (ma - mi) + mi) v instance Binary (Multichannel Float) where put (MC s p c l de f d) = do put s put p put c put l put de put f put $! fmap convert d where convert v = let (mi,ma) = (minElement v,maxElement v) v' = GV.map (\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v in (mi,ma,v' :: Vector Word64) get = do s <- get p <- get c <- get l <- get de <- get f <- get (d :: I.Array Int (Float,Float,Vector Word32)) <- get return $! (MC s p c l de f (seq d (fmap convert) d)) where convert (mi,ma,v) = GV.map (\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word32)) * (ma - mi) + mi) v instance Binary (Multichannel (Complex Double)) where put (MC s p c l de f d) = do put s put p put c put l put de put f put $! fmap ((\(r,j) -> (convert r, convert j)) . fromComplex) d where convert v = let (mi,ma) = (minElement v,maxElement v) v' = GV.map (\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word64))) v in (mi,ma,v' :: Vector Word64) get = do s <- get p <- get c <- get l <- get de <- get f <- get (d :: I.Array Int ((Double,Double,Vector Word64),(Double,Double,Vector Word64))) <- get return $! (MC s p c l de f (seq d (fmap (\(r,j) -> toComplex (convert r,convert j)) d))) where convert (mi,ma,v) = GV.map (\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word64)) * (ma - mi) + mi) v instance Binary (Multichannel (Complex Float)) where put (MC s p c l de f d) = do put s put p put c put l put de put f put $! fmap ((\(r,j) -> (convert r, convert j)) . fromComplex) d where convert v = let (mi,ma) = (minElement v,maxElement v) v' = GV.map (\x -> round $ (x - mi)/(ma - mi) * (fromIntegral (maxBound :: Word32))) v in (mi,ma,v' :: Vector Word32) get = do s <- get p <- get c <- get l <- get de <- get f <- get (d :: I.Array Int ((Float,Float,Vector Word32),(Float,Float,Vector Word32))) <- get return $! (MC s p c l de f (seq d (fmap (\(r,j) -> toComplex (convert r,convert j)) d))) where convert (mi,ma,v) = GV.map (\x -> ((fromIntegral x)) / (fromIntegral (maxBound :: Word32)) * (ma - mi) + mi) v ----------------------------------------------------------------------------- readMultichannel :: (Binary (Multichannel a)) => FilePath -> IO (Multichannel a) readMultichannel = decodeFile writeMultichannel :: (Binary (Multichannel a)) => FilePath -> Multichannel a -> IO () writeMultichannel = encodeFile ----------------------------------------------------------------------------- -- | create a multichannel data type createMultichannel :: Storable a => Int -- ^ sampling rate -> Int -- ^ bits of precision -> [Vector a] -- ^ data -> Multichannel a -- ^ datatype createMultichannel s p d = let c = length d in MC s p c (GV.length $ head d) False Nothing (I.listArray (1,c) d) -- | the sampling rate sampling_rate :: Multichannel a -> Int sampling_rate = _sampling_rate -- | the bits of precision precision :: Multichannel a -> Int precision = _precision -- | the number of channels channels :: Multichannel a -> Int channels = _channels -- | the length, in samples samples :: Multichannel a -> Int samples = _length -- | extract one channel getChannel :: Int -> Multichannel a -> Vector a getChannel c d = (_data d) I.! c -- | extract all channels getChannels :: Multichannel a -> I.Array Int (Vector a) getChannels d = _data d -- | convert the data to a matrix with channels as rows toMatrix :: Element a => Multichannel a -> Matrix a toMatrix = fromRows . I.elems . _data -- | was the data detrended? detrended :: Multichannel a -> Bool detrended = _detrended -- | was the data filtered? filtered :: Multichannel a -> Maybe (Int,Int) filtered = _filtered ----------------------------------------------------------------------------- -- | map a function executed concurrently mapArrayConcurrently :: Ix i => (a -> b) -- ^ function to map -> I.Array i a -- ^ input -> (I.Array i b) -- ^ output mapArrayConcurrently f d = unsafePerformIO $ do let b = I.bounds d results <- replicateM (rangeSize b) newEmptyMVar mapM_ (forkIO . applyFunction f) $ zip results (I.assocs d) vectors <- mapM takeMVar results return $ I.array b vectors where applyFunction f' (m,(j,e)) = putMVar m (j,f' e) {- -- | map a function executed concurrently mapListConcurrently :: (a -> b) -- ^ function to map -> [a] -- ^ input -> [b] -- ^ output mapListConcurrently f d = unsafePerformIO $ do results <- replicateM (length d) newEmptyMVar mapM_ (forkIO . applyFunction f) zip results d mapM takeMVar results where applyFunction f' (m,e) = putMVar m (f' e) -} -- | map a function executed concurrently mapConcurrently :: Storable b => (Vector a -> Vector b) -- ^ the function to be mapped -> Multichannel a -- ^ input data -> Multichannel b -- ^ output data mapConcurrently f (MC sr p c _ de fi d) = let d' = mapArrayConcurrently f d in MC sr p c (GV.length $ d' I.! 1) de fi d' -- | map a function mapMC :: Storable b => (Vector a -> Vector b) -- ^ the function to be mapped -> Multichannel a -- ^ input data -> Multichannel b -- ^ output data mapMC f (MC sr p c _ de fi d) = let d' = fmap f d in MC sr p c (GV.length $ d' I.! 1) de fi d' ----------------------------------------------------------------------------- -- | detrend the data with a specified window size detrend :: Int -> Multichannel Double -> Multichannel Double detrend w m = let m' = mapConcurrently (S.detrend w) m in m' { _detrended = True } -- | filter the data with the given passband filter :: (S.Filterable a, Double ~ DoubleOf a) => (Int,Int) -> Multichannel a -> Multichannel a filter pb m = let m' = mapConcurrently (S.broadband_filter (_sampling_rate m) pb) m in m' { _filtered = Just pb } ----------------------------------------------------------------------------- -- | extract a slice of the data slice :: Storable a => Int -- ^ starting sample number -> Int -- ^ length -> Multichannel a -> Multichannel a slice j w m = let m' = mapConcurrently (subVector j w) m in m' { _length = w } ----------------------------------------------------------------------------- -- | calculate histograms histograms :: (S.Filterable a, Double ~ DoubleOf a) => I.Array Int (Vector a) -> Int -> (Double,Double) -> Int -> Int -> (Double,Double) -> (Double,Double) -- ^ bins and ranges -> (I.Array Int H.Histogram,I.Array (Int,Int) H2.Histogram2D) histograms d' b (l,u) bx by (lx,ux) (ly,uy) = let d = fmap double d' (bl,bu) = I.bounds d br = ((bl,bl),(bu,bu)) histarray = mapArrayConcurrently (H.fromLimits b (l,u)) d pairs = I.array br $ map (\(m,n) -> ((m,n),(d I.! m,d I.! n))) (range br) hist2array = mapArrayConcurrently (\(x,y) -> (H2.addVector (H2.emptyLimits bx by (lx,ux) (ly,uy)) x y)) pairs in (histarray,hist2array) ----------------------------------------------------------------------------- -- | calculate the entropy of the phase difference between pairs of channels (fills upper half of matrix) entropy_delta_phase :: (S.Filterable a, Double ~ DoubleOf a) => Multichannel a -- ^ input data -> Matrix Double entropy_delta_phase m = let d = _data m c = _channels m b = ((1,1),(c,c)) r = I.range b diff = I.listArray b (map (\j@(x,y) -> (j,if x <= y then Just (double $ (d I.! y)-(d I.! x)) else Nothing)) r) :: I.Array (Int,Int) ((Int,Int),Maybe (Vector Double)) h = mapArrayConcurrently (maybe Nothing (\di -> Just $ H.fromLimits 128 ((-2)*pi,2*pi) di)) (fmap snd diff) ent = mapArrayConcurrently (\(j,difvec) -> case difvec of Nothing -> 0 :: Double Just da -> SI.entropy (fromJust (h I.! j)) da) diff in fromArray2D ent ----------------------------------------------------------------------------- -- | calculate the mutual information of the phase between pairs of channels (fills upper half of matrix) mi_phase :: (S.Filterable a, Double ~ DoubleOf a) => Multichannel a -- ^ input data -> Matrix Double mi_phase m = let d = _data m (histarray,hist2array) = histograms d 128 (-pi,pi) 128 128 (-pi,pi) (-pi,pi) indhist = I.listArray (I.bounds hist2array) (I.assocs hist2array) mi = mapArrayConcurrently (doMI histarray (fmap double d)) indhist in fromArray2D mi where doMI histarray d ((x,y),h2) | x <= y = SI.mutual_information h2 (histarray I.! x) (histarray I.! y) (d I.! x,d I.! y) | otherwise = 0 -----------------------------------------------------------------------------
amcphail/hsignal
lib/Numeric/Signal/Multichannel.hs
Haskell
bsd-3-clause
15,032
-- Implements a simple language embedded in the reactive resumption -- monad, ReactT. First useful application example of resumptions. {-# OPTIONS -fglasgow-exts -fno-monomorphism-restriction #-} import InterpreterLib.Algebras import InterpreterLib.Functors import InterpreterLib.Terms.ArithTerm import InterpreterLib.Terms.IfTerm import InterpreterLib.Terms.LambdaTerm import InterpreterLib.Terms.VarTerm import InterpreterLib.Terms.ImperativeTerm import Data.Ratio import Monad import Control.Monad.Reader import Control.Monad.State import Monad.Resumption -- Basic value type including numbers, booleans and functions data Value = ValNum Int | ValBool Bool | ValLambda (ValueMonad -> ValueMonad) | ValRef Int | ValNull instance Show Value where show (ValNum x) = show x show (ValBool x) = show x show (ValLambda x) = show x show (ValRef x) = "<Reference " ++ (show x) ++ ">" show ValNull = "null" instance Eq Value where (==) (ValNum x) (ValNum y) = x == y (==) (ValBool x) (ValBool y) = x == y (==) (ValLambda x) (ValLambda y) = x == y (==) (ValRef x) (ValRef y) = x == y (==) ValNull ValNull = True -- Variable environment. String used to reference Value associated with -- variable of that name. type Gamma = [(String,Value)] -- Reference environment. Integer used to reference Value associated with -- location of that number type Env = [Value] -- Variable utility functions addSubst v g = v:g findSubstValue s g = case (lookup s g) of (Just x) -> x Nothing -> error "Variable not in scope" -- Reference utility functions addRef t st = t:st deref (ValRef x) refs = refs!!x replace x v vs = (take x vs) ++ (v:(drop (x+1) vs)) -- Value type nesting monads data SignalVal = Cont | Ack instance Signal SignalVal where cont = Cont ack = Ack type ValueMonad = (ReactT SignalVal SignalVal (StateT Env (Reader Gamma))) Value instance Show (ValueMonad -> ValueMonad) where show f = "<Function Value>" instance Eq (ValueMonad -> ValueMonad) where (==) _ _ = error "Cannot compare function values." -- Define numeric properties over value so we can use +,-,*,/ and friends -- rather than define a call helper functions everywhere. This is a big -- enough pain that helpers might be preferable. instance Num Value where (+) (ValNum x) (ValNum y) = ValNum (x+y) (+) (ValBool x) (ValBool y) = ValBool (x || y) (-) (ValNum x) (ValNum y) = ValNum (x-y) (*) (ValNum x) (ValNum y) = ValNum (x*y) (*) (ValBool x) (ValBool y) = ValBool (x && y) negate (ValNum x) = ValNum (-x) negate (ValBool x) = ValBool (not x) abs (ValNum x) = ValNum (abs x) signum (ValNum x) = ValNum (signum x) fromInteger = ValNum . fromInteger instance Enum Value where succ (ValNum x) = ValNum (x+1) pred (ValNum x) = ValNum (x-1) toEnum = ValNum fromEnum (ValNum x) = x instance Integral Value where (div) (ValNum x) (ValNum y) = ValNum (div x y) quotRem (ValNum x) (ValNum y) = case (quotRem x y) of (x,y) -> (ValNum x, ValNum y) toInteger (ValNum x) = toInteger x instance Real Value where toRational (ValNum x) = (toInteger x) % (toInteger 1) instance Ord Value where (<) (ValNum x) (ValNum y) = x < y (>=) (ValNum x) (ValNum y) = x >= y (>) (ValNum x) (ValNum y) = x > y (<=) (ValNum x) (ValNum y) = x <= y max (ValNum x) (ValNum y) = ValNum (max x y) min (ValNum x) (ValNum y) = ValNum (min x y) -- Now define the interpreter. First, define the functions for the -- semantices of various operations. phiArith (Add x1 x2) = liftM2 (+) x1 x2 phiArith (Sub x1 x2) = liftM2 (-) x1 x2 phiArith (Mult x1 x2) = liftM2 (*) x1 x2 phiArith (Div x1 x2) = liftM2 (div) x1 x2 phiArith (NumEq x1 x2) = liftM2 (\v1 -> \v2 -> if (v1==v2) then 1 else 0) x1 x2 phiArith (Num x1) = return (ValNum x1) phiIf (IfTerm x1 x2 x3) = do { (ValBool x1') <- x1 ; liftM id (if x1' then x2 else x3) } phiIf TrueTerm = return $ ValBool True phiIf FalseTerm = return $ ValBool False -- Need to undo the value addition. phiLambda (Lam s _ t) = do { g <- ask ; return $ ValLambda (\v -> do { v' <- v ; local (const ((s,v'):g)) t }) } phiLambda (App t1 t2) = do { (ValLambda f) <- t1 ; (f t2) } phiVar :: (VarTerm ValueMonad) -> ValueMonad phiVar (VarTerm s) = do { v <- asks (lookup s) ; case v of (Just x) -> return x Nothing -> error "Variable not found" } -- The dummy term definition helps Haskell figure out what type VarTerm -- is defined over. It is never used. phiVar (DummyTerm x) = return (ValBool True) phiImp (NewRef t) = do { st <- get ; t' <- t ; put (addRef t' st) ; return $ (ValRef (length st)) } phiImp (DeRef t) = do { t' <- t ; st <- get ; return $ deref t' st } phiImp (Assign t1 t2) = do { t1' <- t1 ; t2' <- t2 ; case t1' of (ValRef r) -> do { env <- get ; put (replace r t2' env) ; return ValNull } _ -> error "Cannot assign to non-reference value" } phiImp (SeqTerm t1 t2) = do { t1' <- t1 ; t2' <- t2 ; return $ t2' } -- Build the term type and the term language. type TermType = ArithTerm :$: IfTerm :$: LambdaTerm () :$: VarTerm :$: ImperativeTerm type TermLang = Fix TermType -- Build the explicit algebra. termAlgebra = (mkAlgebra phiArith) @+@ (mkAlgebra phiIf) @+@ (mkAlgebra phiLambda) @+@ (mkAlgebra phiVar) @+@ (mkAlgebra phiImp) -- Write a basic handler and scheduler function and type class. -- scheduler selects the monad to be resumed. handler resumes it and -- generates the new set of resumptions. class (MonadReact m req rsp) => Simulator m req rsp a where scheduler :: [(m req rsp a)] -> (m req rsp a) handler :: [(m req rsp a)] -> (m req resp a) -> [(m req rsp a)] instance Simulator (ReactT SignalVal SignalVal) where scheduler [] = error "No monad to resume." scheduler [rm:rms] = rm handler (D v) = return v handler (P q r) = [(r 1)] -- Here are several test terms and an evaluation function to play with. To -- evaluate a term, use the following: -- runReader (runStateT (runXXX (eval termX)) []) [] -- |(eval termX)| returns the monad resulting from evaluating |termX|. -- |runStateT| then evaluates that monad with the empty environment []|. -- |runReader| then evaluates the previous monad with the empty gamma. -- |In the past, we have encapsulated the environment in some kind of -- |constructed type. Here, we are just using a list. -- Shorthand eval function eval = (cata termAlgebra) -- Shorthans for (S (Right x)) and (S (Right y)) sright = S . Right sleft = S . Left -- Some simple arithmetic terms term1 = (inn (sleft (Num 1))) one = term1 two = (inn (sleft (Num 2))) three = (inn (sleft (Num 3))) term2 = (inn (sleft (Add term1 term1))) term3 = (inn (sleft (Mult term2 term2))) term4 = (inn (sleft (Sub term2 term1))) -- Shorthands for true and false values termTrue = (inn (sright (sleft TrueTerm))) termFalse = (inn (sright (sleft FalseTerm))) -- if term that returns true case term5 = (inn (sright (sleft (IfTerm termTrue term4 term3)))) -- if term that returns false case term6 = (inn (sright (sleft (IfTerm termFalse term4 term3)))) -- Constant function that always returns term6 term7 = (inn (sright (sright (sleft (Lam "x" () term6))))) -- Constant function applied to 1 term8 = (inn (sright (sright (sleft (App term7 term1))))) -- Variable x term9 = (inn (sright (sright (sright (sleft (VarTerm "x")))))) -- Identity function term10 = (inn (sright (sright (sleft (Lam "x" () term9))))) -- Identity function applied to 1 term11 = (inn (sright (sright (sleft (App term10 term1))))) -- NewRef and return term12 = (inn (sright (sright (sright (sright (NewRef term1)))))) -- Access allocated location term13 = (inn (sright (sright (sright (sright (DeRef term12)))))) -- Replace allocated location term14 = (inn (sright (sright (sright (sright (Assign term12 term1)))))) -- -- Lambda accessing memory -- Create a reference to value 1 term15a = (inn (sright (sright (sright (sright (NewRef one)))))) -- Dereference a reference to value 1 term15b = (inn (sright (sright (sright (sright (DeRef term9)))))) -- Create a lambda dereferencing a reference to value 1 term15 = (inn (sright (sright (sleft (Lam "x" () term15b))))) -- Applying memory access lambda to location term16 = (inn (sright (sright (sleft (App term15 term12))))) -- -- Sequencing two terms -- Assign 2 to the variable "x" term17a = (inn (sright (sright (sright (sright (Assign term9 two)))))) -- Sequence assinging 2 to "x" and dereferncing "x" term17b = (inn (sright (sright (sright (sright (SeqTerm term17a term15b)))))) -- Put the sequence in a lambda with "x" as the variable name term17c = (inn (sright (sright (sleft (Lam "x" () term17b))))) -- Evaluate the lambda on a reference to the value 1. Should return 2 term17 = (inn (sright (sright (sleft (App term17c term15a)))))
palexand/interpreters
AbstractInterp/Sample5.hs
Haskell
bsd-3-clause
9,519
module StringCompressorKata.Day6 (compress) where import Data.Char (intToDigit) compress :: Maybe String -> Maybe String compress Nothing = Nothing compress (Just "") = Just "" compress (Just (c:str)) = Just $ compress' 1 c str where compress' :: Int -> Char -> String -> String compress' counter prev "" = intToDigit counter : prev : "" compress' counter prev (current:str) = case theSameChar of True -> compress' (counter + 1) prev str False -> intToDigit counter : prev : compress' 1 current str where theSameChar = current == prev
Alex-Diez/haskell-tdd-kata
old-katas/src/StringCompressorKata/Day6.hs
Haskell
bsd-3-clause
674
module Language.Haskell.TH.SCCs (binding_group, binding_groups, scc, sccs, Dependencies(..), type_dependencies, td_recur, td_descend, Named(..), printQ ) where import Language.Haskell.TH.Syntax import qualified Data.Set as Set; import Data.Set (Set) import qualified Data.Map as Map import qualified Data.Traversable as Traversable import Control.Monad (liftM, liftM2, (<=<)) import Data.Graph (stronglyConnComp, SCC(..)) -- | Helpful for debugging generated code printQ :: Show a => Maybe String -> Q a -> Q [Dec] printQ s m = do x <- m runIO (maybe (return ()) putStr s >> print x) >> return [] -- | Computes the SCC that includes the declaration of the given name; @Left@ -- is a singly acyclic declaration, @Right@ is a mutually recursive group -- (possibly of size one: singly recursion). scc :: Name -> Q (Either Name (Set Name)) scc n = (head . filter (either (==n) (Set.member n))) `liftM` sccs [n] -- | Computes all SCCs for the given names (including those it dominates) sccs :: [Name] -> Q [Either Name (Set Name)] sccs ns = do let withK f k = (,) k `liftM` f k chaotic f = loop <=< analyze where analyze = Traversable.mapM f . Map.fromList . map (\ x -> (x, x)) . Set.toList loop m | Set.null fringe = return m | otherwise = Map.union m `liftM` analyze fringe >>= loop where fringe = Set.unions (Map.elems m) `Set.difference` Map.keysSet m names <- chaotic (fmap type_dependencies . reify) (Set.fromList ns) let listify (AcyclicSCC v) = Left v listify (CyclicSCC vs) = Right (Set.fromList vs) return (map listify (stronglyConnComp [(n, n, Set.toList deps) | (n, deps) <- Map.assocs names])) -- | Wrapper for 'scc' that forgets the distinction between a single acyclic -- SCC and a singly recursive SCC binding_group :: Name -> Q (Set Name) binding_group = liftM binding_group' . scc -- | Wrapper for 'sccs' that forgets the distinction between a single acyclic -- SCC and a singly recursive SCC binding_groups :: [Name] -> Q [Set Name] binding_groups ns = (filter relevant . map binding_group') `liftM` sccs ns where relevant bg = not (Set.null (Set.intersection (Set.fromList ns) bg)) binding_group' = either Set.singleton id -- | This is semantically murky: it's just the name of anything that -- \"naturally\" /defines/ a name; error if it doesn't. class Named t where name_of :: t -> Name instance Named Info where name_of i = case i of ClassI d _ -> name_of d ClassOpI n _ _ _ -> n TyConI d -> name_of d PrimTyConI n _ _ -> n DataConI n _ _ _ -> n VarI n _ _ _ -> n TyVarI n _ -> n instance Named Dec where name_of d = case d of FunD n _ -> n ValD p _ _ -> name_of p DataD _ n _ _ _ -> n NewtypeD _ n _ _ _ -> n TySynD n _ _ -> n ClassD _ n _ _ _ -> n FamilyD _ n _ _ -> n o -> error $ show o ++ " is not a named declaration." instance Named Con where name_of c = case c of NormalC n _ -> n RecC n _ -> n InfixC _ n _ -> n ForallC _ _ c -> name_of c instance Named Pat where name_of p = case p of VarP n -> n AsP n _ -> n SigP p _ -> name_of p o -> error $ "The pattern `" ++ show o ++ "' does not define exactly one name." -- | Calculate the type declarations upon which this construct syntactically -- depends. The first argument tracks the bindings traversed; use 'td_descend' -- to maintain it. class Dependencies t where type_dependencies' :: [Name] -> t -> Set Name type_dependencies :: Dependencies t => t -> Set Name type_dependencies = type_dependencies' [] -- | Just a bit shorter than 'type_dependencies'' td_recur :: Dependencies t => [Name] -> t -> Set Name td_recur ns = type_dependencies' ns -- | Shorter than 'type_dependencies'' and also adds the name of the seconda -- argument to the tracked bindings td_descend :: (Named a, Dependencies t) => [Name] -> a -> t -> Set Name td_descend ns x = type_dependencies' (ns ++ [name_of x]) instance Dependencies Info where type_dependencies' ns i = case i of TyConI d -> td_descend ns i d PrimTyConI n _ _ -> Set.empty _ -> error $ "This version of th-sccs only calculates mutually " ++ "recursive groups for types; " ++ show (name_of i) ++ " is not a type." instance Dependencies Dec where type_dependencies' ns d = case d of DataD _ _ _ cons _ -> Set.unions (map w cons) NewtypeD _ _ _ c _ -> w c TySynD _ _ ty -> w ty FamilyD {} -> error $ "This version of th-sccs cannot calculate mutually recursive " ++ "groups for types involving type families; " ++ show (last ns) ++ " uses " ++ show (name_of d) ++ "." o -> error $ "Unexpected declaration: " ++ show o ++ "." where w x = td_descend ns d x instance Dependencies Con where type_dependencies' ns c = case c of NormalC _ sts -> w $ map snd sts RecC _ vsts -> w $ map (\ (n, _, t) -> RecordField n t) vsts InfixC stL _ stR -> w $ map snd [stL, stR] ForallC _ _ c -> type_dependencies' ns c where w xs = Set.unions (map (td_descend ns c) xs) data RecordField = RecordField Name Type instance Named RecordField where name_of (RecordField n _) = n instance Dependencies RecordField where type_dependencies' ns rf@(RecordField _ ty) = td_descend ns rf ty instance Dependencies Type where type_dependencies' ns t = case t of ForallT _ _ t -> w t ConT n -> Set.singleton n AppT tfn targ -> Set.union (w tfn) (w targ) SigT t _ -> w t _ -> Set.empty where w x = td_recur ns x
nfrisby/th-sccs
Language/Haskell/TH/SCCs.hs
Haskell
bsd-3-clause
5,645
module Paths_Todo ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) 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 [0,1,0,0] [] bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/bin" libdir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/lib/x86_64-linux-ghc-7.10.3/Todo-0.1.0.0-IpKjDdVbKs8326hsSNRKrL" datadir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/share/x86_64-linux-ghc-7.10.3/Todo-0.1.0.0" libexecdir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/libexec" sysconfdir = "/home/frank/CODE/Todo/.stack-work/install/x86_64-linux/lts-6.14/7.10.3/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "Todo_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "Todo_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "Todo_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "Todo_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "Todo_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
frankhucek/Todo
.stack-work/dist/x86_64-linux/Cabal-1.22.5.0/build/autogen/Paths_Todo.hs
Haskell
bsd-3-clause
1,566
module PPTest.Grammars.Lexical (specs) where import PP import PP.Grammars.Lexical import Test.Hspec specs = describe "PPTest.Grammars.Lexical" $ do it "should parse a regular expression (any)" $ case parseAst "." :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "." it "should parse a regular expression (value)" $ case parseAst "a" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "a" it "should parse a regular expression (class interval)" $ case parseAst "[a-z]" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "[a-z]" it "should parse a regular expression (class)" $ case parseAst "[a-z0-9.-]" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "[a-z0-9.-]" it "should parse a regular expression (group)" $ case parseAst "(a)" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "(a)" it "should parse a regular expression (option)" $ case parseAst "a?" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "a?" it "should parse a regular expression (many1)" $ case parseAst "a+" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "a+" it "should parse a regular expression (many0)" $ case parseAst "a*" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "a*" it "should parse a regular expression (choice)" $ case parseAst "abc" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "abc" it "should parse a regular expression (regexpr)" $ case parseAst "ab|cd" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "ab|cd" it "should parse a complex regular expression" $ case parseAst "(a*b)?|[a-z]+(a|[b-d])?|(a|(b|c))de|.|" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "(a*b)?|[a-z]+(a|[b-d])?|(a|(b|c))de|.|" it "should parse all meta symbols into class" $ case parseAst "[[][|][*][+][?][(][(][]][.]" :: To RegExpr of Left e -> show e `shouldBe` "not an error" Right o -> stringify o `shouldBe` "[[][|][*][+][?][(][(][]][.]"
chlablak/platinum-parsing
test/PPTest/Grammars/Lexical.hs
Haskell
bsd-3-clause
2,584
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Main ( main ) where ------------------------------------------------------------------------------- import Control.Monad.IO.Class (liftIO) import Data.Aeson (FromJSON (..), defaultOptions, genericParseJSON, genericToJSON, object, (.=)) import Data.List.NonEmpty (NonEmpty (..)) import Data.Text (Text) import Data.Time.Calendar (Day (..)) import Data.Time.Clock (UTCTime (..), secondsToDiffTime) import qualified Data.Vector as V import Database.V5.Bloodhound import GHC.Generics (Generic) import Network.HTTP.Client (defaultManagerSettings) ------------------------------------------------------------------------------- data TweetMapping = TweetMapping deriving (Eq, Show) instance ToJSON TweetMapping where toJSON TweetMapping = object [ "properties" .= object ["location" .= object ["type" .= ("geo_point" :: Text)]] ] ------------------------------------------------------------------------------- data Tweet = Tweet { user :: Text , postDate :: UTCTime , message :: Text , age :: Int , location :: LatLon } deriving (Eq, Generic, Show) ------------------------------------------------------------------------------- exampleTweet :: Tweet exampleTweet = Tweet { user = "bitemyapp" , postDate = UTCTime (ModifiedJulianDay 55000) (secondsToDiffTime 10) , message = "Use haskell!" , age = 10000 , location = loc } where loc = LatLon {lat = 40.12, lon = -71.3} instance ToJSON Tweet where toJSON = genericToJSON defaultOptions instance FromJSON Tweet where parseJSON = genericParseJSON defaultOptions main :: IO () main = runBH' $ do -- set up index _ <- createIndex indexSettings testIndex True <- indexExists testIndex _ <- putMapping testIndex testMapping TweetMapping -- create a tweet resp <- indexDocument testIndex testMapping defaultIndexDocumentSettings exampleTweet (DocId "1") liftIO (print resp) -- Response {responseStatus = Status {statusCode = 201, statusMessage = "Created"}, responseVersion = HTTP/1.1, responseHeaders = [("Content-Type","application/json; charset=UTF-8"),("Content-Length","74")], responseBody = "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"1\",\"_version\":1,\"created\":true}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose} -- bulk load let stream = V.fromList [BulkIndex testIndex testMapping (DocId "2") (toJSON exampleTweet)] _ <- bulk stream -- Bulk loads require an index refresh before new data is loaded. _ <- refreshIndex testIndex -- set up some aliases let aliasName = IndexName "twitter-alias" let iAlias = IndexAlias testIndex (IndexAliasName aliasName) let aliasRouting = Nothing let aliasFiltering = Nothing let aliasCreate = IndexAliasCreate aliasRouting aliasFiltering _ <- updateIndexAliases (AddAlias iAlias aliasCreate :| []) True <- indexExists aliasName -- create a template so that if we just write into an index named tweet-2017-01-02, for instance, the index will be automatically created with the given mapping. This is a great idea for any ongoing indices because it makes them much easier to manage and rotate. let idxTpl = IndexTemplate (TemplatePattern "tweet-*") (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping] let templateName = TemplateName "tweet-tpl" _ <- putTemplate idxTpl templateName True <- templateExists templateName -- do a search let boost = Nothing let query = TermQuery (Term "user" "bitemyapp") boost let search = mkSearch (Just query) boost _ <- searchByType testIndex testMapping search -- clean up _ <- deleteTemplate templateName _ <- deleteIndex testIndex False <- indexExists testIndex return () where testServer = Server "http://localhost:9200" runBH' = withBH defaultManagerSettings testServer testIndex = IndexName "twitter" testMapping = MappingName "tweet" indexSettings = IndexSettings (ShardCount 1) (ReplicaCount 0)
bermanjosh/bloodhound
examples/Tweet.hs
Haskell
bsd-3-clause
4,281
module Bot.Util where import Paths_5chbot import qualified Data.Version as V eitherToMaybe :: Either a b -> Maybe b eitherToMaybe (Left _) = Nothing eitherToMaybe (Right a) = Just a showVersion :: String showVersion = "5chbot ver. " ++ V.showVersion version
hithroc/5chbot
src/Bot/Util.hs
Haskell
bsd-3-clause
262
module Scurry.Console ( consoleThread ) where import Control.Concurrent.STM.TChan import Control.Monad (forever) import Data.List import System.IO import System.Exit import qualified GHC.Conc as GC import Scurry.Console.Parser import Scurry.Comm.Message import Scurry.Comm.Util import Scurry.Types.Network import Scurry.Types.Console import Scurry.Types.Threads import Scurry.State import Scurry.Peer -- Console command interpreter consoleThread :: StateRef -> SockWriterChan -> IO () consoleThread sr chan = do (ScurryState {scurryPeers = peers, scurryMyRecord = rec}) <- getState sr mapM_ (\(PeerRecord { peerEndPoint = ep }) -> GC.atomically $ writeTChan chan (DestSingle ep,SJoin rec)) peers forever $ do ln <- getLine case parseConsole ln of (Left err) -> badCmd err (Right ln') -> goodCmd ln' where goodCmd cmd = case cmd of CmdShutdown -> exitWith ExitSuccess CmdListPeers -> getState sr >>= print {- TODO: Find a way to do this... -} {- (CmdNewPeer ha pn) -> addPeer sr (Nothing, (EndPoint ha pn)) -} CmdNewPeer _ _ -> putStrLn "CmdNewPeer disabled for now..." (CmdRemovePeer ha pn) -> delPeer sr (EndPoint ha pn) badCmd err = putStrLn $ "Bad Command: " ++ show err
dmagyar/scurry
src/Scurry/Console.hs
Haskell
bsd-3-clause
1,459
{- | Utilities for dealing with the location of parsed entities in their source files. -} {-# LANGUAGE OverloadedStrings #-} module Base.Location ( Location(..) , Position(..) ) where import Data.Monoid import Data.Text.Prettyprint.Doc (Pretty (..)) -- | Position within a text file. data Position = Position { line :: Int, column :: Int } deriving (Eq, Show) instance Ord Position where Position l1 c1 <= Position l2 c2 = l1 < l2 || (l1 == l2 && c1 <= c2) instance Pretty Position where pretty (Position l1 c1) = pretty l1 <> ":" <> pretty c1 data Location = Location { sourceFile :: FilePath , position :: Position } deriving (Show, Eq, Ord) instance Pretty Location where pretty (Location path pos) = pretty path <> ":" <> pretty pos
Verites/verigraph
src/library/Base/Location.hs
Haskell
apache-2.0
789
<?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="zh-CN"> <title>Bug Tracker</title> <maps> <homeID>top</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>
veggiespam/zap-extensions
addOns/bugtracker/src/main/javahelp/org/zaproxy/zap/extension/bugtracker/resources/help_zh_CN/helpset_zh_CN.hs
Haskell
apache-2.0
957
<?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="pt-BR"> <title>Getting started Guide</title> <maps> <homeID>top</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>Localizar</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>
brunoqc/zap-extensions
src/org/zaproxy/zap/extension/gettingStarted/resources/help_pt_BR/helpset_pt_BR.hs
Haskell
apache-2.0
970
{-| Module : Servant.Server.Auth.Token.SingleUse Description : Specific functions to work with single usage codes. Copyright : (c) Anton Gushcha, 2016 License : MIT Maintainer : ncrashed@gmail.com Stability : experimental Portability : Portable -} module Servant.Server.Auth.Token.SingleUse( makeSingleUseExpire , registerSingleUseCode , invalidateSingleUseCode , validateSingleUseCode , generateSingleUsedCodes ) where import Control.Monad import Control.Monad.IO.Class import Data.Aeson.WithField import Data.Time import Servant.API.Auth.Token import Servant.Server.Auth.Token.Common import Servant.Server.Auth.Token.Model -- | Calculate expire date for single usage code makeSingleUseExpire :: MonadIO m => NominalDiffTime -- ^ Duration of code -> m UTCTime -- ^ Time when the code expires makeSingleUseExpire dt = do t <- liftIO getCurrentTime return $ dt `addUTCTime` t -- | Register single use code in DB registerSingleUseCode :: HasStorage m => UserImplId -- ^ Id of user -> SingleUseCode -- ^ Single usage code -> Maybe UTCTime -- ^ Time when the code expires, 'Nothing' is never expiring code -> m () registerSingleUseCode uid code expire = void $ insertSingleUseCode $ UserSingleUseCode code uid expire Nothing -- | Marks single use code that it cannot be used again invalidateSingleUseCode :: HasStorage m => UserSingleUseCodeId -- ^ Id of code -> m () invalidateSingleUseCode i = do t <- liftIO getCurrentTime setSingleUseCodeUsed i $ Just t -- | Check single use code and return 'True' on success. -- -- On success invalidates single use code. validateSingleUseCode :: HasStorage m => UserImplId -- ^ Id of user -> SingleUseCode -- ^ Single usage code -> m Bool validateSingleUseCode uid code = do t <- liftIO getCurrentTime mcode <- getUnusedCode code uid t whenJust mcode $ invalidateSingleUseCode . (\(WithField i _) -> i) return $ maybe False (const True) mcode -- | Generates a set single use codes that doesn't expire. -- -- Note: previous codes without expiration are invalidated. generateSingleUsedCodes :: HasStorage m => UserImplId -- ^ Id of user -> IO SingleUseCode -- ^ Generator of codes -> Word -- Count of codes -> m [SingleUseCode] generateSingleUsedCodes uid gen n = do t <- liftIO getCurrentTime invalidatePermamentCodes uid t replicateM (fromIntegral n) $ do code <- liftIO gen _ <- insertSingleUseCode $ UserSingleUseCode code uid Nothing Nothing return code
VyacheslavHashov/servant-auth-token
src/Servant/Server/Auth/Token/SingleUse.hs
Haskell
bsd-3-clause
2,483
{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds #-} module Tests.Compile.Readme where import Data.Metrology.Poly hiding (LCSU) data LengthDim = LengthDim -- each dimension is a datatype that acts as its own proxy instance Dimension LengthDim data TimeDim = TimeDim instance Dimension TimeDim type VelocityDim = LengthDim :/ TimeDim data Meter = Meter instance Unit Meter where -- declare Meter as a Unit type BaseUnit Meter = Canonical -- Meters are "canonical" type DimOfUnit Meter = LengthDim -- Meters measure Lengths instance Show Meter where -- Show instances are optional but useful show _ = "m" -- do *not* examine the argument! data Foot = Foot instance Unit Foot where type BaseUnit Foot = Meter -- Foot is defined in terms of Meter conversionRatio _ = 0.3048 -- do *not* examine the argument! -- We don't need to specify the `DimOfUnit`; -- it's implied by the `BaseUnit`. instance Show Foot where show _ = "ft" data Second = Second instance Unit Second where type BaseUnit Second = Canonical type DimOfUnit Second = TimeDim instance Show Second where show _ = "s" type LCSU = MkLCSU '[(LengthDim, Meter), (TimeDim, Second)] type Length = MkQu_DLN LengthDim LCSU Double -- Length stores lengths in our defined LCSU, using `Double` as the numerical type type Length' = MkQu_ULN Foot LCSU Double -- same as Length. Note the `U` in `MkQu_ULN`, allowing it to take a unit type Time = MkQu_DLN TimeDim LCSU Double extend :: Length -> Length -- a function over lengths extend x = redim $ x |+| (1 % Meter) inMeters :: Length -> Double -- extract the # of meters inMeters = (# Meter) -- more on this later conversion :: Length -- mixing units conversion = (4 % Meter) |+| (10 % Foot) vel :: Length %/ Time -- The `%*` and `%/` operators allow -- you to combine types vel = (3 % Meter) |/| (2 % Second) data Kilo = Kilo instance UnitPrefix Kilo where multiplier _ = 1000 kilo :: unit -> Kilo :@ unit kilo = (Kilo :@) longWayAway :: Length longWayAway = 150 % kilo Meter longWayAwayInMeters :: Double longWayAwayInMeters = longWayAway # Meter -- 150000.0 type MetersPerSecond = Meter :/ Second type Velocity1 = MkQu_ULN MetersPerSecond LCSU Double speed :: Velocity1 speed = 20 % (Meter :/ Second) type Velocity2 = Length %/ Time -- same type as Velocity1 type MetersSquared = Meter :^ Two type Area1 = MkQu_ULN MetersSquared LCSU Double type Area2 = Length %^ Two -- same type as Area1 roomSize :: Area1 roomSize = 100 % (Meter :^ sTwo) roomSize' :: Area1 roomSize' = 100 % (Meter :* Meter) type Velocity3 = (MkQu_ULN Number LCSU Double) %/ Time %* Length addVels :: Velocity1 -> Velocity1 -> Velocity3 addVels v1 v2 = redim $ (v1 |+| v2) type instance DefaultUnitOfDim LengthDim = Meter type instance DefaultUnitOfDim TimeDim = Second -- type Length = MkQu_D LengthDim
goldfirere/units
units-test/Tests/Compile/Readme.hs
Haskell
bsd-3-clause
3,352
-- | Basic data flow analysis over the Haste AST. module Haste.AST.FlowAnalysis ( Strict (..), VarInfo (..), InfoMap, ArgMap, mkVarInfo, nullInfo, mergeVarInfos, findVarInfos ) where import Haste.AST.Syntax import Control.Monad.State import Data.List (foldl', sort, group) import qualified Data.Set as S import qualified Data.Map as M data Strict = Strict | Unknown deriving (Eq, Show) data VarInfo = VarInfo { -- | Is this var always strict? varStrict :: Strict, -- | Does this var always have the same, statically known, arity? -- @Nothing@, if var is not a function. varArity :: Maybe Int, -- | What are the sources of this var? I.e. for each occurrence where the -- var is the LHS of an assignment or substitution (including function -- call), add the RHS to this list. varAlias :: [Var] } deriving (Eq, Show) mkVarInfo :: Strict -> Maybe Int -> VarInfo mkVarInfo s ar = VarInfo s ar [] type InfoMap = M.Map Var VarInfo type ArgMap = M.Map Var [Var] nullInfo :: VarInfo nullInfo = VarInfo Unknown Nothing [] -- | Merge two var infos. The aliases of the infos are simply concatenated -- and filtered for duplicates. For concrete information, if the two infos -- disagree on any field, that field becomes unknown. mergeVarInfos :: VarInfo -> VarInfo -> VarInfo mergeVarInfos a b = VarInfo strict' arity' (varAlias a `merge` varAlias b) where strict' | varStrict a == varStrict b = varStrict a | otherwise = Unknown arity' | varArity a == varArity b = varArity a | otherwise = Nothing merge as bs = map head . group . sort $ as ++ bs -- | Merge the infos of a var with that of all of its aliases. resolveVarInfo :: InfoMap -> Var -> Maybe VarInfo resolveVarInfo m var = go (S.singleton var) var where go seen v = do nfo <- M.lookup v m let xs' = filter (not . (`S.member` seen)) (varAlias nfo) seen' = foldl' (flip S.insert) seen xs' nfos <- mapM (go seen') xs' case foldl' mergeVarInfos (nfo {varAlias = xs'}) nfos of VarInfo Unknown Nothing _ -> Nothing nfo' -> return nfo' type EvalM = State InfoMap -- | Figure out as much statically known information as possible about all -- vars in a program. The returned map will be collapsed so that recursive -- lookups are not necessary, and the 'varAlias' field of each info will -- be empty. -- -- TODO: track return values, tail call status findVarInfos :: ArgMap -> Stm -> InfoMap findVarInfos argmap = mergeAll . snd . flip runState M.empty . goS where mergeAll m = M.foldWithKey resolve m m resolve v _ m = case resolveVarInfo m v of Just nfo -> M.insert v (nfo {varAlias = []}) m _ -> m goS Stop = return () goS Cont = return () goS (Forever s) = goS s goS (Case c d as next) = do goE c goS d mapM_ (\(e, s) -> goE e >> goS s) as goS next goS (Assign (NewVar _ v) rhs next) = handleAssign v rhs >> goS next goS (Assign (LhsExp _ (Var v)) rhs next) = handleAssign v rhs >> goS next goS (Assign (LhsExp _ lhs) rhs next) = goE lhs >> goE rhs >> goS next goS (Return ex) = goE ex goS (ThunkRet ex) = goE ex goS (Tailcall ex) = goE ex handleAssign v (Var v') = v `dependsOn` v' handleAssign v (Eval (Var v')) = v `dependsOn` v' handleAssign v (Fun args body) = do v `hasInfo` mkVarInfo Strict (Just $ length args) goS body handleAssign v (Lit _) = v `hasInfo` mkVarInfo Strict Nothing handleAssign v (JSLit _) = v `hasInfo` mkVarInfo Strict Nothing handleAssign v rhs = v `hasInfo` nullInfo >> goE rhs -- If a function is ever stored anywhere except as a pure alias, we must -- immediately stop assuming things about it, since we now have no idea -- where it may be called. If it is not stored, we know that all calls to -- it will be direct, so it is safe to assume things about its arguments -- based on our static analysis. -- To be safe - but overly conservative - we set the -- info of any arguments of each function aliased by a var that occurs -- outside a permitted context (function call or synonymous assignment) -- to nullInfo. goE (Var v) = setArgsOf v nullInfo (S.singleton v) goE (Lit _) = return () goE (JSLit _) = return () goE (Not ex) = goE ex goE (BinOp _ a b) = goE a >> goE b goE (Fun _ body) = goS body goE (Call _ _ (Var f) xs) = handleCall f xs goE (Call _ _ (Fun as b) xs) = handleArgs as xs >> goS b goE (Call _ _ f xs) = mapM_ goE (f:xs) goE (Index x ix) = goE x >> goE ix goE (Arr xs) = mapM_ goE xs goE (Member x _) = goE x goE (Obj xs) = mapM_ goE (map snd xs) goE (AssignEx (Var v) rhs) = handleAssign v rhs goE (AssignEx lhs rhs) = goE lhs >> goE rhs goE (IfEx c l r) = mapM_ goE [c, l, r] goE (Eval ex) = goE ex goE (Thunk _ body) = goS body handleArgs as xs = sequence_ (zipWith handleAssign as xs) handleCall f argexs = case M.lookup f argmap of Just argvars -> handleArgs argvars argexs _ -> return () -- Finds the functions (if any) aliased by v and sets the varinfo of their -- arguments to @nfo@. setArgsOf v nfo seen = do case M.lookup v argmap of Just args -> mapM_ (`hasInfo` nullInfo) args _ -> do nfos <- get case M.lookup v nfos of Nothing -> return () Just nfo' -> do let aliases = filter (not . (`S.member` seen)) (varAlias nfo') seen' = foldl' (flip S.insert) seen aliases mapM_ (\v' -> setArgsOf v' nfo seen') aliases hasInfo :: Var -> VarInfo -> EvalM () hasInfo v nfo = do nfos <- get put $ M.alter upd v nfos where upd (Just nfo') = Just $ mergeVarInfos nfo nfo' upd _ = Just nfo dependsOn :: Var -> Var -> EvalM () dependsOn v v' = do nfos <- get put $ M.alter upd v nfos where upd (Just nfo) = Just $ nfo {varAlias = v' : varAlias nfo} upd _ = Just $ nullInfo {varAlias = [v']}
kranich/haste-compiler
src/Haste/AST/FlowAnalysis.hs
Haskell
bsd-3-clause
6,515
{-# LANGUAGE BangPatterns, DeriveFunctor, RecordWildCards #-} module Network.Wreq.Cache.Store ( Store , empty , insert , delete , lookup , fromList , toList ) where import Data.Hashable (Hashable) import Data.Int (Int64) import Data.List (foldl') import Prelude hiding (lookup, map) import qualified Data.HashPSQ as HashPSQ type Epoch = Int64 data Store k v = Store { capacity :: {-# UNPACK #-} !Int , size :: {-# UNPACK #-} !Int , epoch :: {-# UNPACK #-} !Epoch , psq :: !(HashPSQ.HashPSQ k Epoch v) } instance (Show k, Show v, Ord k, Hashable k) => Show (Store k v) where show st = "fromList " ++ show (toList st) empty :: Ord k => Int -> Store k v empty cap | cap <= 0 = error "empty: invalid capacity" | otherwise = Store cap 0 0 HashPSQ.empty {-# INLINABLE empty #-} insert :: (Ord k, Hashable k) => k -> v -> Store k v -> Store k v insert k v st@Store{..} = case HashPSQ.insertView k epoch v psq of (Just (_, _), psq0) -> st {epoch = epoch + 1, psq = psq0} (Nothing, psq0) | size < capacity -> st {size = size + 1, epoch = epoch + 1, psq = psq0} | otherwise -> st {epoch = epoch + 1, psq = HashPSQ.deleteMin psq0} {-# INLINABLE insert #-} lookup :: (Ord k, Hashable k) => k -> Store k v -> Maybe (v, Store k v) lookup k st@Store{..} = case HashPSQ.alter tick k psq of (Nothing, _) -> Nothing (Just v, psq0) -> Just (v, st { epoch = epoch + 1, psq = psq0 }) where tick Nothing = (Nothing, Nothing) tick (Just (_, v)) = (Just v, Just (epoch, v)) {-# INLINABLE lookup #-} delete :: (Ord k, Hashable k) => k -> Store k v -> Store k v delete k st@Store{..} = case HashPSQ.deleteView k psq of Nothing -> st Just (_, _, psq0) -> st {size = size - 1, psq = psq0} {-# INLINABLE delete #-} fromList :: (Ord k, Hashable k) => Int -> [(k, v)] -> Store k v fromList = foldl' (flip (uncurry insert)) . empty {-# INLINABLE fromList #-} toList :: (Ord k, Hashable k) => Store k v -> [(k, v)] toList Store{..} = [(k,v) | (k, _, v) <- HashPSQ.toList psq] {-# INLINABLE toList #-}
bitemyapp/wreq
Network/Wreq/Cache/Store.hs
Haskell
bsd-3-clause
2,108
<?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="bs-BA"> <title>Directory List v2.3 LC</title> <maps> <homeID>directorylistv2_3_lc</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>
kingthorin/zap-extensions
addOns/directorylistv2_3_lc/src/main/javahelp/help_bs_BA/helpset_bs_BA.hs
Haskell
apache-2.0
984
module A4 where data T a = C1 a over :: (T b) -> b over (C1 x) = x under :: (T a) -> a under (C1 x) = x
SAdams601/HaRe
old/testing/addCon/A4.hs
Haskell
bsd-3-clause
109
{-| Module describing an NIC. The NIC data type only holds data about a NIC, but does not provide any logic. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Nic ( Nic(..) , Mode(..) , List , create ) where import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Types as T -- * Type declarations data Mode = Bridged | Routed | OpenVSwitch deriving (Show, Eq) -- | The NIC type. -- -- It holds the data for a NIC as it is provided via the IAllocator protocol -- for an instance creation request. All data in those request is optional, -- that's why all fields are Maybe's. -- -- TODO: Another name might be more appropriate for this type, as for example -- RequestedNic. But this type is used as a field in the Instance type, which -- is not named RequestedInstance, so such a name would be weird. PartialNic -- already exists in Objects, but doesn't fit the bill here, as it contains -- a required field (mac). Objects and the types therein are subject to being -- reworked, so until then this type is left as is. data Nic = Nic { mac :: Maybe String -- ^ MAC address of the NIC , ip :: Maybe String -- ^ IP address of the NIC , mode :: Maybe Mode -- ^ the mode the NIC operates in , link :: Maybe String -- ^ the link of the NIC , bridge :: Maybe String -- ^ the bridge this NIC is connected to if -- the mode is Bridged , network :: Maybe T.NetworkID -- ^ network UUID if this NIC is connected -- to a network } deriving (Show, Eq) -- | A simple name for an instance map. type List = Container.Container Nic -- * Initialization -- | Create a NIC. -- create :: Maybe String -> Maybe String -> Maybe Mode -> Maybe String -> Maybe String -> Maybe T.NetworkID -> Nic create mac_init ip_init mode_init link_init bridge_init network_init = Nic { mac = mac_init , ip = ip_init , mode = mode_init , link = link_init , bridge = bridge_init , network = network_init }
apyrgio/snf-ganeti
src/Ganeti/HTools/Nic.hs
Haskell
bsd-2-clause
3,420
{-# LANGUAGE BangPatterns, OverloadedStrings #-} import Control.DeepSeq import Control.Exception import Control.Monad import Data.Aeson import Data.Aeson.Parser import Data.Attoparsec import Data.Time.Clock import System.Environment (getArgs) import System.IO import qualified Data.ByteString as B main = do (cnt:args) <- getArgs let count = read cnt :: Int forM_ args $ \arg -> bracket (openFile arg ReadMode) hClose $ \h -> do putStrLn $ arg ++ ":" start <- getCurrentTime let loop !n | n >= count = return () | otherwise = do let go = do s <- B.hGet h 16384 if B.null s then loop (n+1) else go go loop 0 end <- getCurrentTime putStrLn $ " " ++ show (diffUTCTime end start)
jprider63/aeson-ios-0.8.0.2
benchmarks/ReadFile.hs
Haskell
bsd-3-clause
821
{-# LANGUAGE BangPatterns, Rank2Types, OverloadedStrings, RecordWildCards, MagicHash, UnboxedTuples #-} module Data.Attoparsec.Internal.Fhthagn ( inlinePerformIO ) where import GHC.Base (realWorld#) import GHC.IO (IO(IO)) -- | Just like unsafePerformIO, but we inline it. Big performance gains as -- it exposes lots of things to further inlining. /Very unsafe/. In -- particular, you should do no memory allocation inside an -- 'inlinePerformIO' block. On Hugs this is just @unsafePerformIO@. inlinePerformIO :: IO a -> a inlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r {-# INLINE inlinePerformIO #-}
DavidAlphaFox/ghc
utils/haddock/haddock-library/vendor/attoparsec-0.12.1.1/Data/Attoparsec/Internal/Fhthagn.hs
Haskell
bsd-3-clause
636
module Main where import System.IO import DynFlags import GHC import Exception import Module import FastString import MonadUtils import Outputable import Bag (filterBag,isEmptyBag) import System.Directory (removeFile) import System.Environment( getArgs ) import PrelNames main :: IO() main = do [libdir] <- getArgs ok <- runGhc (Just libdir) $ do dflags <- getSessionDynFlags setSessionDynFlags dflags liftIO (setUnsafeGlobalDynFlags dflags) setContext [ IIDecl (simpleImportDecl pRELUDE_NAME) , IIDecl (simpleImportDecl (mkModuleNameFS (fsLit "System.IO")))] runDecls "data X = Y ()" execStmt "print True" execOptions gtry $ execStmt "print (Y ())" execOptions :: GhcMonad m => m (Either SomeException ExecResult) runDecls "data X = Y () deriving Show" _ <- dynCompileExpr "'x'" execStmt "print (Y ())" execOptions execStmt "System.IO.hFlush System.IO.stdout" execOptions print "done"
urbanslug/ghc
testsuite/tests/ghc-api/T8628.hs
Haskell
bsd-3-clause
1,039
{-# LANGUAGE OverloadedStrings #-} module Jamo where import Prelude hiding (readFile, putStrLn, lookup, writeFile) import Data.List (intersect, (\\)) import Data.Map (fromList, lookup) import Data.Attoparsec.Text (takeWhile1, takeTill, inClass, char, parseOnly, choice, many', endOfInput) import Data.Text (Text, cons, unpack, pack, singleton, intercalate, intersperse) import Data.Text.IO (readFile, writeFile) import qualified Data.Text as T import Data.Monoid ((<>)) import Debug.Trace (trace) cho = "ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ" jong = "ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ" jung = "ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ" jaeum = intersect cho jong unique_cho = cho \\ jaeum unique_jong = jong \\ jaeum declBody :: Char -> Bool -> String -> Text declBody c indent = intercalate "\n" . map (\x -> pack ((if indent then " " else "") ++ x:" = " ++ c:x:"")) datas = fromList [ ("data-cho", intercalate "|" $ map (cons 'C' . singleton) cho) , ("data-jung", intercalate "|" $ map (cons 'M' . singleton) jung) , ("data-jong", intercalate "|" $ map (cons 'J' . singleton) ('_':jong)) , ("jaeum-comma-sep", intersperse ',' $ pack jaeum) , ("unique-cho-comma-sep", intersperse ',' $ pack unique_cho) , ("unique-jong-comma-sep", intersperse ',' $ pack unique_jong) , ("jung-comma-sep", intersperse ',' $ pack jung) , ("jaeum-cho", declBody 'C' True jaeum) , ("jaeum-jong", declBody 'J' True jaeum) , ("unique-cho", declBody 'C' False unique_cho) , ("unique-jong", declBody 'J' False unique_jong) , ("jung", declBody 'M' False jung) , ("data-deriving", "deriving (Enum, Eq, Ord, Show)") ] holeParser = do "{-!" a <- takeWhile1 (inClass "a-z-") let b = T.last a == '-' k = if b then T.init a else a if b then "}" else "-}" case lookup k datas of Just z -> return z Nothing -> error $ "Cannot find " ++ unpack k takeallParser = takeWhile1 (/='{') consumebraceParser = do char '{' a <- takeTill (=='{') return a main :: IO () main = do a <- readFile "template/Jamo.template.hs" case parseOnly (many' $ choice [holeParser, consumebraceParser, takeallParser]) a of Left err -> error err Right xs -> writeFile "src/Jamo.hs" $ T.concat xs
xnuk/another-aheui-interpreter
template/Jamo.hs
Haskell
mit
2,569
----------------------------------------------------------------------------- -- -- Module : Network.Google -- Copyright : (c) 2012-13 Brian W Bush -- License : MIT -- -- Maintainer : Brian W Bush <b.w.bush@acm.org> -- Stability : Stable -- Portability : Portable -- -- | Helper functions for accessing Google APIs. -- ----------------------------------------------------------------------------- {-# LANGUAGE FlexibleInstances #-} module Network.Google ( -- * Types AccessToken , toAccessToken , ProjectId -- * Functions , appendBody , appendHeaders , appendQuery , doManagedRequest , doRequest , makeHeaderName , makeProjectRequest , makeRequest , makeRequestValue ) where import Control.Exception (finally) import Control.Monad.Trans.Resource (ResourceT, runResourceT) import Data.List (intercalate) import Data.Maybe (fromJust) import Data.ByteString as BS (ByteString) import Data.ByteString.Char8 as BS8 (ByteString, append, pack) import Data.ByteString.Lazy.Char8 as LBS8 (ByteString) import Data.ByteString.Lazy.UTF8 (toString) import Data.CaseInsensitive as CI (CI(..), mk) import Network.HTTP.Base (urlEncode) import Network.HTTP.Conduit (Manager, Request(..), RequestBody(..), Response(..), closeManager, def, httpLbs, newManager, responseBody) import Text.JSON (JSValue, Result(Ok), decode) import Text.XML.Light (Element, parseXMLDoc) -- | OAuth 2.0 access token. type AccessToken = BS.ByteString -- | Convert a string to an access token. toAccessToken :: String -- ^ The string. -> AccessToken -- ^ The OAuth 2.0 access token. toAccessToken = BS8.pack -- | Google API project ID, see <https://code.google.com/apis/console>. type ProjectId = String -- | Construct a Google API request. makeRequest :: AccessToken -- ^ The OAuth 2.0 access token. -> (String, String) -- ^ The Google API name and version. -> String -- ^ The HTTP method. -> (String, String) -- ^ The host and path for the request. -> Request m -- ^ The HTTP request. makeRequest accessToken (apiName, apiVersion) method (host, path) = -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. def { method = BS8.pack method , secure = True , host = BS8.pack host , port = 443 , path = BS8.pack path , requestHeaders = [ (makeHeaderName apiName, BS8.pack apiVersion) , (makeHeaderName "Authorization", BS8.append (BS8.pack "OAuth ") accessToken) ] } -- | Construct a project-related Google API request. makeProjectRequest :: ProjectId -- ^ The project ID. -> AccessToken -- ^ The OAuth 2.0 access token. -> (String, String) -- ^ The Google API name and version. -> String -- ^ The HTTP method. -> (String, String) -- ^ The host and path for the request. -> Request m -- ^ The HTTP request. makeProjectRequest projectId accessToken api method hostPath = appendHeaders [ ("x-goog-project-id", projectId) ] (makeRequest accessToken api method hostPath) -- | Class for Google API request. class DoRequest a where -- | Perform a request. doRequest :: Request (ResourceT IO) -- ^ The request. -> IO a -- ^ The action returning the result of performing the request. doRequest request = do {-- -- TODO: The following seems cleaner, but has type/instance problems: (_, manager) <- allocate (newManager def) closeManager doManagedRequest manager request --} manager <- newManager def finally (doManagedRequest manager request) (closeManager manager) doManagedRequest :: Manager -- ^ The conduit HTTP manager. -> Request (ResourceT IO) -- ^ The request. -> IO a -- ^ The action returning the result of performing the request. instance DoRequest LBS8.ByteString where doManagedRequest manager request = do response <- runResourceT (httpLbs request manager) return $ responseBody response instance DoRequest String where doManagedRequest manager request = do result <- doManagedRequest manager request return $ toString result instance DoRequest [(String, String)] where doManagedRequest manager request = do response <- runResourceT (httpLbs request manager) return $ read . show $ responseHeaders response instance DoRequest () where doManagedRequest manager request = do doManagedRequest manager request :: IO LBS8.ByteString return () instance DoRequest Element where doManagedRequest manager request = do result <- doManagedRequest manager request :: IO String return $ fromJust $ parseXMLDoc result instance DoRequest JSValue where doManagedRequest manager request = do result <- doManagedRequest manager request :: IO String let Ok result' = decode result return result' -- | Prepare a string for inclusion in a request. makeRequestValue :: String -- ^ The string. -> BS8.ByteString -- ^ The prepared string. -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. makeRequestValue = BS8.pack -- | Prepare a name\/key for a header. makeHeaderName :: String -- ^ The name. -> CI.CI BS8.ByteString -- ^ The prepared name. -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. makeHeaderName = CI.mk . BS8.pack -- | Prepare a value for a header. makeHeaderValue :: String -- ^ The value. -> BS8.ByteString -- ^ The prepared value. -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. makeHeaderValue = BS8.pack -- | Append headers to a request. appendHeaders :: [(String, String)] -- ^ The (name\/key, value) pairs for the headers. -> Request m -- ^ The request. -> Request m -- ^ The request with the additional headers. appendHeaders headers request = let headerize :: (String, String) -> (CI.CI BS8.ByteString, BS8.ByteString) headerize (n, v) = (makeHeaderName n, makeHeaderValue v) in request { requestHeaders = requestHeaders request ++ map headerize headers } -- | Append a body to a request. appendBody :: LBS8.ByteString -- ^ The data for the body. -> Request m -- ^ The request. -> Request m -- ^ The request with the body appended. appendBody bytes request = request { requestBody = RequestBodyLBS bytes } -- | Append a query to a request. appendQuery :: [(String, String)] -- ^ The query keys and values. -> Request m -- ^ The request. -> Request m -- ^ The request with the query appended. appendQuery query request = let makeParameter :: (String, String) -> String makeParameter (k, v) = k ++ "=" ++ urlEncode v query' :: String query' = intercalate "&" $ map makeParameter query in request { -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. queryString = BS8.pack $ '?' : query' }
rrnewton/hgdata_trash
src/Network/Google.hs
Haskell
mit
7,085
module TeX.Alias ( Alias(AliasIfTrue, AliasIfFalse) , AliasMap(), emptyAliasMap, aliasLens ) where import qualified Data.Map as M import TeX.StateUtils import TeX.Token data Alias = AliasIfTrue | AliasIfFalse deriving (Eq, Show) newtype AliasMap = AliasMap (M.Map Token Alias) deriving (Show) emptyAliasMap :: AliasMap emptyAliasMap = AliasMap M.empty aliasLens :: Functor f => Token -> (Maybe Alias -> f (Maybe Alias)) -> AliasMap -> f AliasMap aliasLens = makeMapLens (\(AliasMap x) -> x) AliasMap
xymostech/tex-parser
src/TeX/Alias.hs
Haskell
mit
510
------------------------------------------------------------------------------ -- | Defines the 'Charset' accept header with an 'Accept' instance for use in -- encoding negotiation. module Network.HTTP.Media.Charset ( Charset ) where import Network.HTTP.Media.Charset.Internal
zmthy/http-media
src/Network/HTTP/Media/Charset.hs
Haskell
mit
292
module Sprinkler where import Control.Monad (when) import Control.Monad.Bayes.Class hard :: MonadBayes m => m Bool hard = do rain <- bernoulli 0.3 sprinkler <- bernoulli $ if rain then 0.1 else 0.4 wet <- bernoulli $ case (rain,sprinkler) of (True,True) -> 0.98 (True,False) -> 0.8 (False,True) -> 0.9 (False,False) -> 0.0 condition (wet == False) return rain soft :: MonadBayes m => m Bool soft = do rain <- bernoulli 0.3 when rain (factor 0.2) sprinkler <- bernoulli $ if rain then 0.1 else 0.4 when sprinkler (factor 0.1) return rain
ocramz/monad-bayes
models/Sprinkler.hs
Haskell
mit
699
module CLI ( Options(..) , Command(..) , SolveOptions(..) , GenerateOptions(..) , parseOpts ) where import Options.Applicative data Options = Options { cmd :: Command , useAscii :: Bool } data Command = Solve SolveOptions | Generate GenerateOptions data SolveOptions = SolveOptions { puzzleFile :: String , allSolutions :: Bool } data GenerateOptions = GenerateOptions { hideSolution :: Bool } parseOpts :: IO Options parseOpts = customExecParser (prefs showHelpOnError) optParser where optParser = info (helper <*> parseOptions) $ fullDesc <> progDesc "Solve and generate sudoku puzzles" parseOptions = Options <$> parseCommand <*> parseUseAscii parseCommand = subparser $ command "solve" (Solve <$> parseSolveOptionInfo) <> command "generate" (Generate <$> parseGenerateOptionInfo) parseUseAscii = flag False True $ long "ascii" <> help "Render the board in ascii instead of unicode" parseSolveOptionInfo = info (helper <*> parseSolveOptions) $ progDesc "Solve a sudoku puzzle in PUZZLE_FILE" parseSolveOptions = SolveOptions <$> parsePuzzleFile <*> parseAllSolutions parseGenerateOptionInfo = info (helper <*> parseGenerateOptions) $ progDesc "Generate a random sudoku puzzle" parseGenerateOptions = GenerateOptions <$> parseHideSolution parsePuzzleFile = argument str $ metavar "PUZZLE_FILE" parseAllSolutions = flag False True $ long "all" <> short 'a' <> help "Find all solutions instead of stopping at one" parseHideSolution = flag False True $ long "hideSolution" <> help "Only show the puzzle, not its solution"
patrickherrmann/sudoku
src/CLI.hs
Haskell
mit
1,764
{-# LANGUAGE OverloadedStrings #-} module GhostLang.LinkerTests ( -- Pre link semantic tests. checkEmptyModule , checkOneNonMainModule , checkMainModuleWithoutPatterns , checkOtherModuleWithPatterns , checkDuplicateMainModules , checkSingleCorrectMainModule , checkTwoCorrectModules -- Proc map tests. , findUndefinedProc , findDefinedProc , findDoubleDefinedProc -- Procedure resolving tests. , resolveLocalProc , resolveImportedProc , resolveProcInProc , resolveInLoopProc , resolveInConcProc , resolveUnimportedProc , resolveAmbiguousProc , resolveConflictingArityProc ) where import Data.List (sortBy) import GhostLang.Compiler.Linker ( ProcDef , semanticChecks , resolve , buildProcMap , findProcDefs ) import GhostLang.Interpreter (IntrinsicSet) import GhostLang.Types ( ModuleSegment , Value (..) , GhostModule (..) , ImportDecl (..) , ModuleDecl (..) , Pattern (..) , Procedure (..) , Operation (..) ) import Test.HUnit import Text.Parsec.Pos (initialPos) -- | Test that the semantic checker is rejecting an empty -- module list. checkEmptyModule :: Assertion checkEmptyModule = do let mods = [] :: [GhostModule IntrinsicSet] case semanticChecks mods of Right _ -> assertBool "Shall not accept empty list" False Left _ -> return () -- | Test that the semanic checker is rejecting a single module which -- name not is main. checkOneNonMainModule :: Assertion checkOneNonMainModule = do let mods = [GhostModule (moduleDecl ["Other"]) [] [emptyPattern] []] case semanticChecks mods of Right _ -> assertBool "Shall not accept single non main module" False Left _ -> return () -- | Test that the semantic checker is rejecting a main module without -- any patterns. checkMainModuleWithoutPatterns :: Assertion checkMainModuleWithoutPatterns = do let mods = [GhostModule (moduleDecl ["Main"]) [] [] []] case semanticChecks mods of Right _ -> assertBool "Shall not accept main module without patterns" False Left _ -> return () -- | Test that the semantic checker is rejecting an other module -- having patterns. checkOtherModuleWithPatterns :: Assertion checkOtherModuleWithPatterns = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [emptyPattern] [] , GhostModule (moduleDecl ["Other"]) [] [emptyPattern] [] ] case semanticChecks mods of Right _ -> assertBool "Shall not accept other module with patterns" False Left _ -> return () -- | Test that the semantic checker is rejecting duplicate main modules. checkDuplicateMainModules :: Assertion checkDuplicateMainModules = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [emptyPattern] [] , GhostModule (moduleDecl ["Main"]) [] [emptyPattern] [] ] case semanticChecks mods of Right _ -> assertBool "Shall reject duplicate main modules" False Left _ -> return () -- | Test that the semantic checker is accepting a single main module -- with one pattern. checkSingleCorrectMainModule :: Assertion checkSingleCorrectMainModule = do let mods = [GhostModule (moduleDecl ["Main"]) [] [emptyPattern] []] case semanticChecks mods of Right mods' -> mods @=? mods' _ -> assertBool "Shall accept" False -- | Test that the semantic checker is accepting is accepting two -- modules, one main module with a pattern and one other module -- without patterns. checkTwoCorrectModules :: Assertion checkTwoCorrectModules = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [emptyPattern] [] , GhostModule (moduleDecl ["Other"]) [] [] [] ] case semanticChecks mods of Right mods' -> mods @=? mods' _ -> assertBool "Shall accept" False -- | Try to find an undefined procedure. findUndefinedProc :: Assertion findUndefinedProc = do let mods = [] :: [GhostModule IntrinsicSet] procMap = buildProcMap mods [] @=? findProcDefs "foo" procMap -- | Try to find a procedure defined once. findDefinedProc :: Assertion findDefinedProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [] [ emptyProcedure ] ] procMap = buildProcMap mods [("Main", emptyProcedure)] @=? findProcDefs "foo" procMap -- | Find a procedure name defined in two modules. findDoubleDefinedProc :: Assertion findDoubleDefinedProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [] [ emptyProcedure ] , GhostModule (moduleDecl ["Other"]) [] [] [ emptyProcedure ] ] procMap = buildProcMap mods lhs = sortBy procSort [ ("Main", emptyProcedure) , ("Other", emptyProcedure) ] rhs = sortBy procSort $ findProcDefs "foo" procMap lhs @=? rhs -- | Resolve a module with a reference to a local procedure. resolveLocalProc :: Assertion resolveLocalProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [] ] ] [ emptyProcedure ] ] -- The expected result with the unresolved reference resolved. res = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Call emptyProcedure [] ] ] [ emptyProcedure ] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Resolve a module with a reference to an imported procedure. resolveImportedProc :: Assertion resolveImportedProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [ ImportDecl ["Other", "Module"] ] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [] ] ] [] , GhostModule (moduleDecl ["Other", "Module"]) [] [] [ emptyProcedure ] ] -- The expected result. res = [ GhostModule (moduleDecl ["Main"]) [ ImportDecl ["Other", "Module"] ] [ Pattern (initialPos "") "bar" 1 [ Call emptyProcedure [] ] ] [] , GhostModule (moduleDecl ["Other", "Module"]) [] [] [ emptyProcedure ] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Resolve a procedure called from within a procedure. resolveProcInProc :: Assertion resolveProcInProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "caller" [] ] ] [ Procedure "caller" [] [ Unresolved (initialPos "") "foo" [] ] , emptyProcedure ] ] -- The resolved caller proc. caller = Procedure "caller" [] [ Call emptyProcedure [] ] -- The expected result. res = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Call caller [] ] ] [ caller, emptyProcedure ] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Resolve a module with a procedure reference inside a loop. resolveInLoopProc :: Assertion resolveInLoopProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Loop (Literal 1) [ Unresolved (initialPos "") "foo" [] ] ] ] [ emptyProcedure ] ] -- The expected result. res = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Loop (Literal 1) [ Call emptyProcedure [] ] ] ] [ emptyProcedure] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Resolve a module with a procedure reference inside a concurrent section. resolveInConcProc :: Assertion resolveInConcProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Concurrently [ Unresolved (initialPos "") "foo" [] ] ] ] [ emptyProcedure ] ] -- The expect result. res = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Concurrently [ Call emptyProcedure [] ] ] ] [ emptyProcedure] ] case resolve mods of Right mods' -> res @=? mods' Left _ -> assertBool "Shall accept" False -- | Try to resolve a module with an unresolvable (unimported) -- procedure. resolveUnimportedProc :: Assertion resolveUnimportedProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [] ] ] [] , GhostModule (moduleDecl ["Other", "Module"]) [] [] [ emptyProcedure ] ] case resolve mods of Right _ -> assertBool "Shall not accept unresolvable proc" False Left _ -> return () -- | Try to resolve an ambiguous procedure. resolveAmbiguousProc :: Assertion resolveAmbiguousProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [ ImportDecl ["Other", "Module"] , ImportDecl ["Other", "Module2"] ] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [] ] ] [] , GhostModule (moduleDecl ["Other", "Module"]) [] [] [ emptyProcedure ] , GhostModule (moduleDecl ["Other", "Module2"]) [] [] [ emptyProcedure ] ] case resolve mods of Right _ -> assertBool "Shall not accept ambiguous definitions" False Left _ -> return () -- | Try to resolve a procedure with different arity at definition and -- use. resolveConflictingArityProc :: Assertion resolveConflictingArityProc = do let mods = [ GhostModule (moduleDecl ["Main"]) [] [ Pattern (initialPos "") "bar" 1 [ Unresolved (initialPos "") "foo" [Literal 1] ] ] [emptyProcedure] ] case resolve mods of Right _ -> assertBool "Shall not accept conflicting arity" False Left _ -> return () moduleDecl :: [ModuleSegment] -> ModuleDecl moduleDecl = ModuleDecl (initialPos "") emptyPattern :: Pattern IntrinsicSet emptyPattern = Pattern (initialPos "") "" 0 [] emptyProcedure :: Procedure IntrinsicSet emptyProcedure = Procedure "foo" [] [] procSort :: ProcDef a -> ProcDef a -> Ordering procSort x y = fst x `compare` fst y
kosmoskatten/ghost-lang
ghost-lang/test/GhostLang/LinkerTests.hs
Haskell
mit
12,556
{-# LANGUAGE ForeignFunctionInterface #-} -- | -- Module : Crypto.Hash.BLAKE -- Copyright : (c) Austin Seipp 2013 -- License : MIT -- -- Maintainer : aseipp@pobox.com -- Stability : experimental -- Portability : portable -- -- BLAKE-256 and BLAKE-512 hashes. The underlying implementation uses -- the @ref@ code of @blake256@ and @blake512@ from SUPERCOP, and -- should be relatively fast. -- -- For more information visit <https://131002.net/blake/>. -- module Crypto.Hash.BLAKE ( blake256 -- :: ByteString -> ByteString , blake512 -- :: ByteString -> ByteString ) where import Data.Word import Foreign.C.Types import Foreign.Ptr import System.IO.Unsafe (unsafePerformIO) import Data.ByteString (ByteString) import Data.ByteString.Internal (create) import Data.ByteString.Unsafe (unsafeUseAsCStringLen) -- | Compute a 256-bit (32 byte) digest of an input string. blake256 :: ByteString -> ByteString blake256 xs = -- SHA256 has 32 bytes of output unsafePerformIO . create 32 $ \out -> unsafeUseAsCStringLen xs $ \(cstr,clen) -> c_blake256 out cstr (fromIntegral clen) >> return () {-# INLINE blake256 #-} -- | Compute a 512-bit (64 byte) digest of an input string. blake512 :: ByteString -> ByteString blake512 xs = -- The default primitive of SHA512 has 64 bytes of output. unsafePerformIO . create 64 $ \out -> unsafeUseAsCStringLen xs $ \(cstr,clen) -> c_blake512 out cstr (fromIntegral clen) >> return () {-# INLINE blake512 #-} -- -- FFI hash binding -- foreign import ccall unsafe "blake256" c_blake256 ::Ptr Word8 -> Ptr CChar -> CULLong -> IO CInt foreign import ccall unsafe "blake512" c_blake512 ::Ptr Word8 -> Ptr CChar -> CULLong -> IO CInt
thoughtpolice/hs-blake
src/Crypto/Hash/BLAKE.hs
Haskell
mit
1,817
module Main where main :: IO () main = do input <- getLine print input -- getWrappingPaperSurfaceArea :: type Len = Integer data Box = Box Len Len Len data Side = Side Len Len getSides :: Box -> [Side] getSides (Box l w h) = [ Side l w , Side w h , Side l h ] class Shape a where area :: (Num b) => a -> b instance Shape Box where area b = 2 * sum (area <$> getSides b) instance Shape Side where area (Side x y) = fromIntegral (x * y) instance Read Box where readPrec = readNumber convertInt readListPrec = readListPrecDefault readList = readListDefault
spicydonuts/adventofcode-2015
2/Main.hs
Haskell
mit
634
module Coins.A265415Spec (main, spec) where import Test.Hspec import Coins.A265415 (a265415) main :: IO () main = hspec spec spec :: Spec spec = describe "A265415" $ it "correctly computes the first 10 elements" $ take 10 (map a265415 [1..]) `shouldBe` expectedValue where expectedValue = [1,10,21,31,37,101,119,157,197,273]
peterokagey/haskellOEIS
test/Coins/A265415Spec.hs
Haskell
apache-2.0
339
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE TemplateHaskell #-} module Worker where import Control.Concurrent (threadDelay) import Control.Applicative import Control.Monad import Control.Monad.Trans.Except import Control.Distributed.Process import Control.Distributed.Process.Closure import Control.Distributed.Process.Serializable (Serializable) import Text.Printf import GHC.Generics (Generic) import Types ---------------------------------------------------------------- -- Dot product ---------------------------------------------------------------- -- | Worker for dot product dotProductWorker :: (MasterProtocol, BoundedProtocol Double) -> Process () dotProductWorker (master,upstream) = workerLoop master $ \(i::Int,j::Int) -> do me <- getSelfPid logMsg master $ printf "[%s]: Fold received work %s" (show me) (show (i,j)) liftIO $ threadDelay (1000*1000) sendBoundedStream upstream (1 :: Double) workerLoop :: (Serializable a) => MasterProtocol -> (a -> Process ()) -> Process () workerLoop master action = loop where loop = do idle master msg <- expect case msg of Nothing -> return () Just a -> action a >> loop ---------------------------------------------------------------- -- Fold ---------------------------------------------------------------- -- | Worker for summing partial results foldWorker :: (MasterProtocol,ResultProtocol Double) -> Process () foldWorker (master,result) = loop Nothing 0 0 where loop :: Maybe Int -> Int -> Double -> Process () loop (Just tot) !n !x | n >= tot = sendResult result x loop tot n x = do msg <- receiveWait [ match $ return . Val . (\(BoundedV x) -> x) , match $ return . Total . (\(Count x) -> x) ] me <- getSelfPid logMsg master $ printf "[%s] fold received: %s" (show me) (show msg) case msg of Val y -> loop tot (n+1) (x+y) Total k | n >= k -> sendResult result x | otherwise -> loop (Just k) n x data FoldTypes = Val Double | Total Int deriving Show remotable [ 'dotProductWorker , 'foldWorker ]
SKA-ScienceDataProcessor/RC
MS1/distributed-dot-product/Worker.hs
Haskell
apache-2.0
2,242
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-} {-# LANGUAGE NoMonomorphismRestriction #-} module Handler.Root where import Model.Accessor import Foundation import Control.Applicative import Data.Text (Text, pack, unpack) import Text.Blaze import qualified Data.Text as T -- This is a handler function for the GET request method on the HomeR -- resource pattern. All of your resource patterns are defined in -- config/routes -- -- The majority of the code you will write in Yesod lives in these handler -- functions. You can spread them across multiple files if you are so -- inclined, or create a single monolithic file. getHomeR :: Handler RepHtml getHomeR = getPageR "home" -- read getPageR :: Text -> Handler RepHtml getPageR pageName = do page <- runDB $ getPage pageName case page of Nothing -> do redirect RedirectTemporary $ EditR pageName Just (id,page) -> do render <- getUrlRender let body = page `toWidgetWith` render sidebarLayout [whamlet|^{toolbar pageName}^{body}|] -- create & update data YikiPageEdit = YikiPageEdit { peBody :: Textarea } toPageEdit :: YikiPage -> YikiPageEdit toPageEdit yp = YikiPageEdit $ Textarea $ yikiPageBody yp yikiPageEditForm :: Maybe YikiPageEdit -> Html -> Form Yiki Yiki (FormResult YikiPageEdit, Widget) yikiPageEditForm ype = renderDivs $ YikiPageEdit <$> areq textareaField "" (peBody <$> ype) getEditR :: Text -> Handler RepHtml getEditR pageName = do -- result :: Maybe (YikiPageId, YikiPage) result <- runDB $ getPage pageName let edit = case result of Nothing -> YikiPageEdit $ Textarea "" Just (_,page) -> toPageEdit page ((_, widget), enctype) <- generateFormPost $ yikiPageEditForm $ Just edit sidebarLayout [whamlet| <h1>#{unpack pageName} <form method=post action=@{EditR pageName} enctype=#{enctype}> ^{widget} <input type=submit> <a href=@{PageR pageName}>cancel <p> |] postEditR :: Text -> Handler RepHtml postEditR pageName = do ((result, widget), enctype) <- runFormPost $ yikiPageEditForm Nothing case result of FormSuccess ype -> do let body = T.filter (`notElem` "\r") $ unTextarea $ peBody ype runDB $ createOrUpdatePageBody pageName body redirect RedirectTemporary $ PageR pageName _ -> sidebarLayout [whamlet| <p>Invalid input, let's try again. <form method=post action=@{EditR pageName} enctype=#{enctype}> ^{widget} <input type=submit> |] -- delete postDeleteR :: Text -> Handler RepHtml postDeleteR = undefined -- display all articles getIndexR :: Handler RepHtml getIndexR = do pages <- runDB $ getAllPages sidebarLayout [whamlet| <h1>Index <h2> All articles $if null pages No Articles $else <ul> $forall page <- pages <li><a href=@{PageR $ yikiPageName page}>#{yikiPageName page}</a> #{show $ yikiPageCreated page} |] ------------------------------------------------------------ -- Helpers ------------------------------------------------------------ toolbar name = [whamlet| <div .toolbar> <a href=@{EditR name}>edit</a> <a href=@{IndexR}>index</a> |] yikiPageNameField = checkBool validateYikiPageName errorMessage textField where errorMessage :: Text errorMessage = pack $ "Unacceptable page name!" ++ " Available page name must be composed of" ++ " only alphabet and digit." toWidgetWith :: YikiPage -> (YikiRoute -> Text) -> Widget page `toWidgetWith` routeRender = either failure success rendered where body = yikiPageBody page name = yikiPageName page rendered :: Either String String rendered = markdownToHtml routeRender $ unpack body success :: String -> Widget success html = [whamlet|<p>#{preEscapedString html}|] failure :: String -> Widget failure err = [whamlet|<p>#{err}</p><pre>#{body}</pre>|] ------------------------------------------------------------ -- Design ------------------------------------------------------------ sidebarLayout :: Widget -> Handler RepHtml sidebarLayout content = do yikiSidebar <- runDB $ getPage "sidebar" urlRender <- getUrlRender let sidebar = toSidebarWith (snd <$> yikiSidebar) urlRender titleId <- newIdent mainId <- newIdent sidebarId <- newIdent contentId <- newIdent defaultLayout' $ do addCassius [cassius| html height: 100%; body height: 100%; background-color: #EBE1AD; margin: 0; color: #423B0B; header background-color: #666149; color: #FFF; ##{titleId} width: 900px; height: 80px; position: relative; margin: 0 auto; padding-top: 25px; color: #fff; ##{mainId} width: 900px; position: relative; margin: 0 auto; ##{sidebarId} width: 240px; float: right; padding-bottom: 40px; ##{contentId} width: 500px; float: left; text-shadow: 0 1px 0 #fff; padding-bottom: 40px; footer width: 900px; position: relative; margin: 0 auto; clear: both; padding: 30px 0; footer p font-size: 11px; line-height: 18px; text-shadow: 0 1px 0 #fff; h1, h2, h3 color: #221F66; textarea resize: none; font-size: medium; width: 125%; height: 500px; border: 3px solid #cccccc; padding: 5px; font-family: Tahoma, sans-serif; background-position: bottom right; background-repeat: no-repeat; |] addWidget [whamlet| <header> <h1 ##{titleId}>Yiki: a simple wiki <div ##{mainId}> <div ##{contentId}> ^{content} <div ##{sidebarId}> ^{sidebar} |] toSidebarWith :: Maybe YikiPage -> (YikiRoute -> Text) -> Widget page `toSidebarWith` routeRender = maybe redirectWidget (`toWidgetWith` routeRender) page where redirectWidget = [whamlet| hoge |] defaultLayout' :: Widget -> Handler RepHtml defaultLayout' w = do p <- widgetToPageContent w mmsg <- getMessage hamletToRepHtml [hamlet| !!! <html> <head> <title>#{pageTitle p} ^{pageHead p} <body> $maybe msg <- mmsg <p .message>#{msg} ^{pageBody p} <footer> <p> powerd by <a href=http://www.github.com/masaedw/Yiki/>Yiki</a><br/> powerd by <a href=http://www.yesodweb.com/>yesod</a> |]
masaedw/Yiki
Handler/Root.hs
Haskell
bsd-2-clause
6,292
module P011 where import Arrays run :: IO () run = print . maximum . map product $ groups where groups = concatMap (($ grid) . ($ 4)) [verticalWindow, horizontalWindow, forwardDiagWindow, backwardDiagWindow] grid :: [[Integer]] grid = [[08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08] ,[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00] ,[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65] ,[52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91] ,[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80] ,[24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50] ,[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70] ,[67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21] ,[24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72] ,[21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95] ,[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92] ,[16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57] ,[86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58] ,[19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40] ,[04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66] ,[88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69] ,[04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36] ,[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16] ,[20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54] ,[01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]]
tyehle/euler-haskell
src/P011.hs
Haskell
bsd-3-clause
2,018
module GameData.Animation where import qualified Data.List as L import Gamgine.Math.Vect as V data Animation = Animation { currentPosition :: V.Vect, currentVelocity :: V.Vect, velocity :: Double, path :: [V.Vect], bidirectional :: Bool, movingToPathIdx :: Int, finished :: Bool } deriving Show newAnimation :: Double -> [V.Vect] -> Bool -> Animation newAnimation velocity path@(currPos : nextPos : _) bidirectional = Animation currPos currVelo velocity path bidirectional 1 False where currVelo = (V.normalize $ nextPos - currPos) * V.v3 velocity velocity velocity basePosition :: Animation -> V.Vect basePosition = L.head . path setBasePosition :: Animation -> V.Vect -> Animation setBasePosition ani newBase = let (basePt : otherPts) = path ani diffPath = L.map ((-) basePt) otherPts otherPts' = L.map (newBase `plus`) diffPath in newAnimation (velocity ani) (newBase : otherPts') (bidirectional ani) where plus = (+) update :: Animation -> Animation update ani@Animation {finished = True} = ani update ani@Animation {currentPosition = currPos, currentVelocity = currVelo, velocity = velo, path = path, movingToPathIdx = idx} = let nextPos | idx >= L.length path = currPos | otherwise = path !! idx currPos' = currPos + currVelo nextPosReached = V.len (currPos' - nextPos) < 0.1 in if nextPosReached then incrementIdx ani {currentPosition = nextPos} else ani {currentPosition = currPos'} where incrementIdx ani@Animation {currentPosition = currPos, movingToPathIdx = idx, path = path, bidirectional = bidir} = let nextIdx = idx + 1 atEnd = nextIdx >= L.length path in if atEnd then if bidir then newAnimation velo (L.reverse path) bidir else ani {finished = True} else ani {movingToPathIdx = nextIdx, currentVelocity = (V.normalize $ (path !! nextIdx) - currPos) * V.v3 velo velo velo}
dan-t/layers
src/GameData/Animation.hs
Haskell
bsd-3-clause
2,114
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift Compiler (0.9.2) -- -- -- -- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING -- ----------------------------------------------------------------- module AuroraSchedulerManager_Client(createJob,scheduleCronJob,descheduleCronJob,startCronJob,restartShards,killTasks,addInstances,acquireLock,releaseLock,replaceCronTemplate,startJobUpdate,pauseJobUpdate,resumeJobUpdate,abortJobUpdate,pulseJobUpdate) where import ReadOnlyScheduler_Client import qualified Data.IORef as R import Prelude (($), (.), (>>=), (==), (++)) import qualified Prelude as P import qualified Control.Exception as X import qualified Control.Monad as M ( liftM, ap, when ) import Data.Functor ( (<$>) ) import qualified Data.ByteString.Lazy as LBS import qualified Data.Hashable as H import qualified Data.Int as I import qualified Data.Maybe as M (catMaybes) import qualified Data.Text.Lazy.Encoding as E ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as LT import qualified Data.Typeable as TY ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import qualified Test.QuickCheck.Arbitrary as QC ( Arbitrary(..) ) import qualified Test.QuickCheck as QC ( elements ) import qualified Thrift as T import qualified Thrift.Types as T import qualified Thrift.Arbitraries as T import Api_Types import AuroraSchedulerManager seqid = R.newIORef 0 createJob (ip,op) arg_description arg_lock arg_session = do send_createJob op arg_description arg_lock arg_session recv_createJob ip send_createJob op arg_description arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("createJob", T.M_CALL, seqn) write_CreateJob_args op (CreateJob_args{createJob_args_description=arg_description,createJob_args_lock=arg_lock,createJob_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_createJob ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_CreateJob_result ip T.readMessageEnd ip P.return $ createJob_result_success res scheduleCronJob (ip,op) arg_description arg_lock arg_session = do send_scheduleCronJob op arg_description arg_lock arg_session recv_scheduleCronJob ip send_scheduleCronJob op arg_description arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("scheduleCronJob", T.M_CALL, seqn) write_ScheduleCronJob_args op (ScheduleCronJob_args{scheduleCronJob_args_description=arg_description,scheduleCronJob_args_lock=arg_lock,scheduleCronJob_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_scheduleCronJob ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_ScheduleCronJob_result ip T.readMessageEnd ip P.return $ scheduleCronJob_result_success res descheduleCronJob (ip,op) arg_job arg_lock arg_session = do send_descheduleCronJob op arg_job arg_lock arg_session recv_descheduleCronJob ip send_descheduleCronJob op arg_job arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("descheduleCronJob", T.M_CALL, seqn) write_DescheduleCronJob_args op (DescheduleCronJob_args{descheduleCronJob_args_job=arg_job,descheduleCronJob_args_lock=arg_lock,descheduleCronJob_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_descheduleCronJob ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_DescheduleCronJob_result ip T.readMessageEnd ip P.return $ descheduleCronJob_result_success res startCronJob (ip,op) arg_job arg_session = do send_startCronJob op arg_job arg_session recv_startCronJob ip send_startCronJob op arg_job arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("startCronJob", T.M_CALL, seqn) write_StartCronJob_args op (StartCronJob_args{startCronJob_args_job=arg_job,startCronJob_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_startCronJob ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_StartCronJob_result ip T.readMessageEnd ip P.return $ startCronJob_result_success res restartShards (ip,op) arg_job arg_shardIds arg_lock arg_session = do send_restartShards op arg_job arg_shardIds arg_lock arg_session recv_restartShards ip send_restartShards op arg_job arg_shardIds arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("restartShards", T.M_CALL, seqn) write_RestartShards_args op (RestartShards_args{restartShards_args_job=arg_job,restartShards_args_shardIds=arg_shardIds,restartShards_args_lock=arg_lock,restartShards_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_restartShards ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_RestartShards_result ip T.readMessageEnd ip P.return $ restartShards_result_success res killTasks (ip,op) arg_query arg_lock arg_session = do send_killTasks op arg_query arg_lock arg_session recv_killTasks ip send_killTasks op arg_query arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("killTasks", T.M_CALL, seqn) write_KillTasks_args op (KillTasks_args{killTasks_args_query=arg_query,killTasks_args_lock=arg_lock,killTasks_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_killTasks ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_KillTasks_result ip T.readMessageEnd ip P.return $ killTasks_result_success res addInstances (ip,op) arg_config arg_lock arg_session = do send_addInstances op arg_config arg_lock arg_session recv_addInstances ip send_addInstances op arg_config arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("addInstances", T.M_CALL, seqn) write_AddInstances_args op (AddInstances_args{addInstances_args_config=arg_config,addInstances_args_lock=arg_lock,addInstances_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_addInstances ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_AddInstances_result ip T.readMessageEnd ip P.return $ addInstances_result_success res acquireLock (ip,op) arg_lockKey arg_session = do send_acquireLock op arg_lockKey arg_session recv_acquireLock ip send_acquireLock op arg_lockKey arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("acquireLock", T.M_CALL, seqn) write_AcquireLock_args op (AcquireLock_args{acquireLock_args_lockKey=arg_lockKey,acquireLock_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_acquireLock ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_AcquireLock_result ip T.readMessageEnd ip P.return $ acquireLock_result_success res releaseLock (ip,op) arg_lock arg_validation arg_session = do send_releaseLock op arg_lock arg_validation arg_session recv_releaseLock ip send_releaseLock op arg_lock arg_validation arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("releaseLock", T.M_CALL, seqn) write_ReleaseLock_args op (ReleaseLock_args{releaseLock_args_lock=arg_lock,releaseLock_args_validation=arg_validation,releaseLock_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_releaseLock ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_ReleaseLock_result ip T.readMessageEnd ip P.return $ releaseLock_result_success res replaceCronTemplate (ip,op) arg_config arg_lock arg_session = do send_replaceCronTemplate op arg_config arg_lock arg_session recv_replaceCronTemplate ip send_replaceCronTemplate op arg_config arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("replaceCronTemplate", T.M_CALL, seqn) write_ReplaceCronTemplate_args op (ReplaceCronTemplate_args{replaceCronTemplate_args_config=arg_config,replaceCronTemplate_args_lock=arg_lock,replaceCronTemplate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_replaceCronTemplate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_ReplaceCronTemplate_result ip T.readMessageEnd ip P.return $ replaceCronTemplate_result_success res startJobUpdate (ip,op) arg_request arg_session = do send_startJobUpdate op arg_request arg_session recv_startJobUpdate ip send_startJobUpdate op arg_request arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("startJobUpdate", T.M_CALL, seqn) write_StartJobUpdate_args op (StartJobUpdate_args{startJobUpdate_args_request=arg_request,startJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_startJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_StartJobUpdate_result ip T.readMessageEnd ip P.return $ startJobUpdate_result_success res pauseJobUpdate (ip,op) arg_jobKey arg_session = do send_pauseJobUpdate op arg_jobKey arg_session recv_pauseJobUpdate ip send_pauseJobUpdate op arg_jobKey arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("pauseJobUpdate", T.M_CALL, seqn) write_PauseJobUpdate_args op (PauseJobUpdate_args{pauseJobUpdate_args_jobKey=arg_jobKey,pauseJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_pauseJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_PauseJobUpdate_result ip T.readMessageEnd ip P.return $ pauseJobUpdate_result_success res resumeJobUpdate (ip,op) arg_jobKey arg_session = do send_resumeJobUpdate op arg_jobKey arg_session recv_resumeJobUpdate ip send_resumeJobUpdate op arg_jobKey arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("resumeJobUpdate", T.M_CALL, seqn) write_ResumeJobUpdate_args op (ResumeJobUpdate_args{resumeJobUpdate_args_jobKey=arg_jobKey,resumeJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_resumeJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_ResumeJobUpdate_result ip T.readMessageEnd ip P.return $ resumeJobUpdate_result_success res abortJobUpdate (ip,op) arg_jobKey arg_session = do send_abortJobUpdate op arg_jobKey arg_session recv_abortJobUpdate ip send_abortJobUpdate op arg_jobKey arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("abortJobUpdate", T.M_CALL, seqn) write_AbortJobUpdate_args op (AbortJobUpdate_args{abortJobUpdate_args_jobKey=arg_jobKey,abortJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_abortJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_AbortJobUpdate_result ip T.readMessageEnd ip P.return $ abortJobUpdate_result_success res pulseJobUpdate (ip,op) arg_updateId arg_session = do send_pulseJobUpdate op arg_updateId arg_session recv_pulseJobUpdate ip send_pulseJobUpdate op arg_updateId arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("pulseJobUpdate", T.M_CALL, seqn) write_PulseJobUpdate_args op (PulseJobUpdate_args{pulseJobUpdate_args_updateId=arg_updateId,pulseJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_pulseJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_PulseJobUpdate_result ip T.readMessageEnd ip P.return $ pulseJobUpdate_result_success res
futufeld/eclogues
eclogues-impl/gen-hs/AuroraSchedulerManager_Client.hs
Haskell
bsd-3-clause
13,610
module Main where import Lib main :: IO () main = tokenizerMain
NogikuchiKBYS/hsit-sandbox
app/Tokenizer.hs
Haskell
bsd-3-clause
67
{-# LANGUAGE TypeOperators, ScopedTypeVariables #-} -- | -- Module : Data.Array.Accelerate.Prelude -- Copyright : [2010..2011] Manuel M T Chakravarty, Gabriele Keller, Ben Lever -- [2009..2012] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Standard functions that are not part of the core set (directly represented in the AST), but are -- instead implemented in terms of the core set. -- module Data.Array.Accelerate.Prelude ( -- * Zipping zipWith3, zipWith4, zip, zip3, zip4, -- * Unzipping unzip, unzip3, unzip4, -- * Reductions foldAll, fold1All, -- ** Specialised folds all, any, and, or, sum, product, minimum, maximum, -- * Scans prescanl, postscanl, prescanr, postscanr, -- ** Segmented scans scanlSeg, scanl'Seg, scanl1Seg, prescanlSeg, postscanlSeg, scanrSeg, scanr'Seg, scanr1Seg, prescanrSeg, postscanrSeg, -- * Shape manipulation flatten, -- * Enumeration and filling fill, enumFromN, enumFromStepN, -- * Working with predicates -- ** Filtering filter, -- ** Scatter / Gather scatter, scatterIf, gather, gatherIf, -- * Permutations reverse, transpose, -- * Extracting sub-vectors init, tail, take, drop, slit ) where -- avoid clashes with Prelude functions -- import Data.Bits import Data.Bool import Prelude ((.), ($), (+), (-), (*), const, subtract, id) import qualified Prelude as P -- friends import Data.Array.Accelerate.Array.Sugar hiding ((!), ignore, shape, size) import Data.Array.Accelerate.Language import Data.Array.Accelerate.Smart import Data.Array.Accelerate.Type -- Map-like composites -- ------------------- -- | Zip three arrays with the given function -- zipWith3 :: (Shape sh, Elt a, Elt b, Elt c, Elt d) => (Exp a -> Exp b -> Exp c -> Exp d) -> Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh c) -> Acc (Array sh d) zipWith3 f as bs cs = map (\x -> let (a,b,c) = unlift x in f a b c) $ zip3 as bs cs -- | Zip four arrays with the given function -- zipWith4 :: (Shape sh, Elt a, Elt b, Elt c, Elt d, Elt e) => (Exp a -> Exp b -> Exp c -> Exp d -> Exp e) -> Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh c) -> Acc (Array sh d) -> Acc (Array sh e) zipWith4 f as bs cs ds = map (\x -> let (a,b,c,d) = unlift x in f a b c d) $ zip4 as bs cs ds -- | Combine the elements of two arrays pairwise. The shape of the result is -- the intersection of the two argument shapes. -- zip :: (Shape sh, Elt a, Elt b) => Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh (a, b)) zip = zipWith (curry lift) -- | Take three arrays and return an array of triples, analogous to zip. -- zip3 :: forall sh. forall a. forall b. forall c. (Shape sh, Elt a, Elt b, Elt c) => Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh c) -> Acc (Array sh (a, b, c)) zip3 as bs cs = zipWith (\a bc -> let (b, c) = unlift bc :: (Exp b, Exp c) in lift (a, b, c)) as $ zip bs cs -- | Take four arrays and return an array of quadruples, analogous to zip. -- zip4 :: forall sh. forall a. forall b. forall c. forall d. (Shape sh, Elt a, Elt b, Elt c, Elt d) => Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh c) -> Acc (Array sh d) -> Acc (Array sh (a, b, c, d)) zip4 as bs cs ds = zipWith (\a bcd -> let (b, c, d) = unlift bcd :: (Exp b, Exp c, Exp d) in lift (a, b, c, d)) as $ zip3 bs cs ds -- | The converse of 'zip', but the shape of the two results is identical to the -- shape of the argument. -- unzip :: (Shape sh, Elt a, Elt b) => Acc (Array sh (a, b)) -> (Acc (Array sh a), Acc (Array sh b)) unzip arr = (map fst arr, map snd arr) -- | Take an array of triples and return three arrays, analogous to unzip. -- unzip3 :: (Shape sh, Elt a, Elt b, Elt c) => Acc (Array sh (a, b, c)) -> (Acc (Array sh a), Acc (Array sh b), Acc (Array sh c)) unzip3 xs = (map get1 xs, map get2 xs, map get3 xs) where get1 :: forall a b c. (Elt a, Elt b, Elt c) => Exp (a,b,c) -> Exp a get1 x = let (a, _ :: Exp b, _ :: Exp c) = unlift x in a get2 :: forall a b c. (Elt a, Elt b, Elt c) => Exp (a,b,c) -> Exp b get2 x = let (_ :: Exp a, b, _ :: Exp c) = unlift x in b get3 :: forall a b c. (Elt a, Elt b, Elt c) => Exp (a,b,c) -> Exp c get3 x = let (_ :: Exp a, _ :: Exp b, c) = unlift x in c -- | Take an array of quadruples and return four arrays, analogous to unzip. -- unzip4 :: (Shape sh, Elt a, Elt b, Elt c, Elt d) => Acc (Array sh (a, b, c, d)) -> (Acc (Array sh a), Acc (Array sh b), Acc (Array sh c), Acc (Array sh d)) unzip4 xs = (map get1 xs, map get2 xs, map get3 xs, map get4 xs) where get1 :: forall a b c d. (Elt a, Elt b, Elt c, Elt d) => Exp (a,b,c,d) -> Exp a get1 x = let (a, _ :: Exp b, _ :: Exp c, _ :: Exp d) = unlift x in a get2 :: forall a b c d. (Elt a, Elt b, Elt c, Elt d) => Exp (a,b,c,d) -> Exp b get2 x = let (_ :: Exp a, b, _ :: Exp c, _ :: Exp d) = unlift x in b get3 :: forall a b c d. (Elt a, Elt b, Elt c, Elt d) => Exp (a,b,c,d) -> Exp c get3 x = let (_ :: Exp a, _ :: Exp b, c, _ :: Exp d) = unlift x in c get4 :: forall a b c d. (Elt a, Elt b, Elt c, Elt d) => Exp (a,b,c,d) -> Exp d get4 x = let (_ :: Exp a, _ :: Exp b, _ :: Exp c, d) = unlift x in d -- Reductions -- ---------- -- | Reduction of an array of arbitrary rank to a single scalar value. -- foldAll :: (Shape sh, Elt a) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Array sh a) -> Acc (Scalar a) foldAll f e arr = fold f e (flatten arr) -- | Variant of 'foldAll' that requires the reduced array to be non-empty and -- doesn't need an default value. -- fold1All :: (Shape sh, Elt a) => (Exp a -> Exp a -> Exp a) -> Acc (Array sh a) -> Acc (Scalar a) fold1All f arr = fold1 f (flatten arr) -- Specialised reductions -- ---------------------- -- -- Leave the results of these as scalar arrays to make it clear that these are -- array computations, and thus can not be nested. -- | Check if all elements satisfy a predicate -- all :: (Shape sh, Elt e) => (Exp e -> Exp Bool) -> Acc (Array sh e) -> Acc (Scalar Bool) all f = and . map f -- | Check if any element satisfies the predicate -- any :: (Shape sh, Elt e) => (Exp e -> Exp Bool) -> Acc (Array sh e) -> Acc (Scalar Bool) any f = or . map f -- | Check if all elements are 'True' -- and :: Shape sh => Acc (Array sh Bool) -> Acc (Scalar Bool) and = foldAll (&&*) (constant True) -- | Check if any element is 'True' -- or :: Shape sh => Acc (Array sh Bool) -> Acc (Scalar Bool) or = foldAll (||*) (constant False) -- | Compute the sum of elements -- sum :: (Shape sh, Elt e, IsNum e) => Acc (Array sh e) -> Acc (Scalar e) sum = foldAll (+) 0 -- | Compute the product of the elements -- product :: (Shape sh, Elt e, IsNum e) => Acc (Array sh e) -> Acc (Scalar e) product = foldAll (*) 1 -- | Yield the minimum element of an array. The array must not be empty. -- minimum :: (Shape sh, Elt e, IsScalar e) => Acc (Array sh e) -> Acc (Scalar e) minimum = fold1All min -- | Yield the maximum element of an array. The array must not be empty. -- maximum :: (Shape sh, Elt e, IsScalar e) => Acc (Array sh e) -> Acc (Scalar e) maximum = fold1All max -- Composite scans -- --------------- -- |Left-to-right prescan (aka exclusive scan). As for 'scan', the first argument must be an -- /associative/ function. Denotationally, we have -- -- > prescanl f e = Prelude.fst . scanl' f e -- prescanl :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) prescanl f e = P.fst . scanl' f e -- |Left-to-right postscan, a variant of 'scanl1' with an initial value. Denotationally, we have -- -- > postscanl f e = map (e `f`) . scanl1 f -- postscanl :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) postscanl f e = map (e `f`) . scanl1 f -- |Right-to-left prescan (aka exclusive scan). As for 'scan', the first argument must be an -- /associative/ function. Denotationally, we have -- -- > prescanr f e = Prelude.fst . scanr' f e -- prescanr :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) prescanr f e = P.fst . scanr' f e -- |Right-to-left postscan, a variant of 'scanr1' with an initial value. Denotationally, we have -- -- > postscanr f e = map (e `f`) . scanr1 f -- postscanr :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) postscanr f e = map (`f` e) . scanr1 f -- Segmented scans -- --------------- -- |Segmented version of 'scanl' -- scanlSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) scanlSeg f z vec seg = scanl1Seg f vec' seg' where -- Segmented exclusive scan is implemented by first injecting the seed -- element at the head of each segment, and then performing a segmented -- inclusive scan. -- -- This is done by creating a creating a vector entirely of the seed -- element, and overlaying the input data in all places other than at the -- start of a segment. -- seg' = map (+1) seg vec' = permute const (fill (index1 $ size vec + size seg) z) (\ix -> index1' $ unindex1' ix + inc ! ix) vec -- Each element in the segments must be shifted to the right one additional -- place for each successive segment, to make room for the seed element. -- Here, we make use of the fact that the vector returned by 'mkHeadFlags' -- contains non-unit entries, which indicate zero length segments. -- flags = mkHeadFlags seg inc = scanl1 (+) flags -- |Segmented version of 'scanl'' -- -- The first element of the resulting tuple is a vector of scanned values. The -- second element is a vector of segment scan totals and has the same size as -- the segment vector. -- scanl'Seg :: forall a i. (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a, Vector a) scanl'Seg f z vec seg = result where -- Returned the result combined, so that the sub-calculations are shared -- should the user require both results. -- result = lift (body, sums) -- Segmented scan' is implemented by deconstructing a segmented exclusive -- scan, to separate the final value and scan body. -- -- TLM: Segmented scans, and this version in particular, expend a lot of -- effort scanning flag arrays. On inspection it appears that several -- of these operations are duplicated, but this will not be picked up -- by sharing _observation_. Perhaps a global CSE-style pass would be -- beneficial. -- vec' = scanlSeg f z vec seg -- Extract the final reduction value for each segment, which is at the last -- index of each segment. -- seg' = map (+1) seg tails = zipWith (+) seg . P.fst $ scanl' (+) 0 seg' sums = backpermute (shape seg) (\ix -> index1' $ tails ! ix) vec' -- Slice out the body of each segment. -- -- Build a head-flags representation based on the original segment -- descriptor. This contains the target length of each of the body segments, -- which is one fewer element than the actual bodies stored in vec'. Thus, -- the flags align with the last element of each body section, and when -- scanned, this element will be incremented over. -- offset = scanl1 (+) seg inc = scanl1 (+) $ permute (+) (fill (index1 $ size vec + 1) 0) (\ix -> index1' $ offset ! ix) (fill (shape seg) (1 :: Exp i)) body = backpermute (shape vec) (\ix -> index1' $ unindex1' ix + inc ! ix) vec' -- |Segmented version of 'scanl1'. -- scanl1Seg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) scanl1Seg f vec seg = P.snd . unzip . scanl1 (segmented f) $ zip (mkHeadFlags seg) vec -- |Segmented version of 'prescanl'. -- prescanlSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) prescanlSeg f e vec seg = P.fst . unatup2 $ scanl'Seg f e vec seg -- |Segmented version of 'postscanl'. -- postscanlSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) postscanlSeg f e vec seg = map (f e) $ scanl1Seg f vec seg -- |Segmented version of 'scanr'. -- scanrSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) scanrSeg f z vec seg = scanr1Seg f vec' seg' where -- Using technique described for 'scanlSeg', where we intersperse the array -- with the seed element at the start of each segment, and then perform an -- inclusive segmented scan. -- inc = scanl1 (+) (mkHeadFlags seg) seg' = map (+1) seg vec' = permute const (fill (index1 $ size vec + size seg) z) (\ix -> index1' $ unindex1' ix + inc ! ix - 1) vec -- | Segmented version of 'scanr''. -- scanr'Seg :: forall a i. (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a, Vector a) scanr'Seg f z vec seg = result where -- Using technique described for scanl'Seg -- result = lift (body, sums) vec' = scanrSeg f z vec seg -- reduction values seg' = map (+1) seg heads = P.fst $ scanl' (+) 0 seg' sums = backpermute (shape seg) (\ix -> index1' $ heads ! ix) vec' -- body segments inc = scanl1 (+) $ mkHeadFlags seg body = backpermute (shape vec) (\ix -> index1' $ unindex1' ix + inc ! ix) vec' -- |Segmented version of 'scanr1'. -- scanr1Seg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) scanr1Seg f vec seg = P.snd . unzip . scanr1 (segmented f) $ zip (mkTailFlags seg) vec -- |Segmented version of 'prescanr'. -- prescanrSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) prescanrSeg f e vec seg = P.fst . unatup2 $ scanr'Seg f e vec seg -- |Segmented version of 'postscanr'. -- postscanrSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) postscanrSeg f e vec seg = map (f e) $ scanr1Seg f vec seg -- Segmented scan helpers -- ---------------------- -- |Compute head flags vector from segment vector for left-scans. -- -- The vector will be full of zeros in the body of a segment, and non-zero -- otherwise. The "flag" value, if greater than one, indicates that several -- empty segments are represented by this single flag entry. This is additional -- data is used by exclusive segmented scan. -- mkHeadFlags :: (Elt i, IsIntegral i) => Acc (Segments i) -> Acc (Segments i) mkHeadFlags seg = init $ permute (+) zeros (\ix -> index1' (offset ! ix)) ones where (offset, len) = scanl' (+) 0 seg zeros = fill (index1' $ the len + 1) 0 ones = fill (index1 $ size offset) 1 -- |Compute tail flags vector from segment vector for right-scans. That is, the -- flag is placed at the last place in each segment. -- mkTailFlags :: (Elt i, IsIntegral i) => Acc (Segments i) -> Acc (Segments i) mkTailFlags seg = init $ permute (+) zeros (\ix -> index1' (the len - 1 - offset ! ix)) ones where (offset, len) = scanr' (+) 0 seg zeros = fill (index1' $ the len + 1) 0 ones = fill (index1 $ size offset) 1 -- |Construct a segmented version of a function from a non-segmented version. -- The segmented apply operates on a head-flag value tuple, and follows the -- procedure of Sengupta et. al. -- segmented :: (Elt e, Elt i, IsIntegral i) => (Exp e -> Exp e -> Exp e) -> Exp (i, e) -> Exp (i, e) -> Exp (i, e) segmented f a b = let (aF, aV) = unlift a (bF, bV) = unlift b in lift (aF .|. bF, bF /=* 0 ? (bV, f aV bV)) -- |Index construction and destruction generalised to integral types. -- -- We generalise the segment descriptor to integral types because some -- architectures, such as GPUs, have poor performance for 64-bit types. So, -- there is a tension between performance and requiring 64-bit indices for some -- applications, and we would not like to restrict ourselves to either one. -- -- As we don't yet support non-Int dimensions in shapes, we will need to convert -- back to concrete Int. However, don't put these generalised forms into the -- base library, because it results in too many ambiguity errors. -- index1' :: (Elt i, IsIntegral i) => Exp i -> Exp DIM1 index1' i = lift (Z :. fromIntegral i) unindex1' :: (Elt i, IsIntegral i) => Exp DIM1 -> Exp i unindex1' ix = let Z :. i = unlift ix in fromIntegral i -- Reshaping of arrays -- ------------------- -- | Flattens a given array of arbitrary dimension. -- flatten :: (Shape ix, Elt a) => Acc (Array ix a) -> Acc (Vector a) flatten a = reshape (index1 $ size a) a -- Enumeration and filling -- ----------------------- -- | Create an array where all elements are the same value. -- fill :: (Shape sh, Elt e) => Exp sh -> Exp e -> Acc (Array sh e) fill sh c = generate sh (const c) -- | Create an array of the given shape containing the values x, x+1, etc (in -- row-major order). -- enumFromN :: (Shape sh, Elt e, IsNum e) => Exp sh -> Exp e -> Acc (Array sh e) enumFromN sh x = enumFromStepN sh x 1 -- | Create an array of the given shape containing the values @x@, @x+y@, -- @x+y+y@ etc. (in row-major order). -- enumFromStepN :: (Shape sh, Elt e, IsNum e) => Exp sh -> Exp e -- ^ x: start -> Exp e -- ^ y: step -> Acc (Array sh e) enumFromStepN sh x y = reshape sh $ generate (index1 $ shapeSize sh) (\ix -> (fromIntegral (unindex1 ix :: Exp Int) * y) + x) -- Filtering -- --------- -- | Drop elements that do not satisfy the predicate -- filter :: Elt a => (Exp a -> Exp Bool) -> Acc (Vector a) -> Acc (Vector a) filter p arr = let flags = map (boolToInt . p) arr (targetIdx, len) = scanl' (+) 0 flags arr' = backpermute (index1 $ the len) id arr in permute const arr' (\ix -> flags!ix ==* 0 ? (ignore, index1 $ targetIdx!ix)) arr -- FIXME: This is abusing 'permute' in that the first two arguments are -- only justified because we know the permutation function will -- write to each location in the target exactly once. -- Instead, we should have a primitive that directly encodes the -- compaction pattern of the permutation function. {-# RULES "ACC filter/filter" forall f g arr. filter f (filter g arr) = filter (\x -> g x &&* f x) arr #-} -- Gather operations -- ----------------- -- | Copy elements from source array to destination array according to a map. This -- is a backpermute operation where a 'map' vector encodes the ouput to input -- index mapping. -- -- For example: -- -- > input = [1, 9, 6, 4, 4, 2, 0, 1, 2] -- > map = [1, 3, 7, 2, 5, 3] -- > -- > output = [9, 4, 1, 6, 2, 4] -- gather :: (Elt e) => Acc (Vector Int) -- ^map -> Acc (Vector e) -- ^input -> Acc (Vector e) -- ^output gather mapV inputV = backpermute (shape mapV) bpF inputV where bpF ix = lift (Z :. (mapV ! ix)) -- | Conditionally copy elements from source array to destination array according -- to a map. This is a backpermute opereation where a 'map' vector encdes the -- output to input index mapping. In addition, there is a 'mask' vector, and an -- associated predication function, that specifies whether an element will be -- copied. If not copied, the output array assumes the default vector's value. -- -- For example: -- -- > default = [6, 6, 6, 6, 6, 6] -- > map = [1, 3, 7, 2, 5, 3] -- > mask = [3, 4, 9, 2, 7, 5] -- > pred = (> 4) -- > input = [1, 9, 6, 4, 4, 2, 0, 1, 2] -- > -- > output = [6, 6, 1, 6, 2, 4] -- gatherIf :: (Elt e, Elt e') => Acc (Vector Int) -- ^map -> Acc (Vector e) -- ^mask -> (Exp e -> Exp Bool) -- ^predicate -> Acc (Vector e') -- ^default -> Acc (Vector e') -- ^input -> Acc (Vector e') -- ^output gatherIf mapV maskV pred defaultV inputV = zipWith zwF predV gatheredV where zwF p g = p ? (unlift g) gatheredV = zip (gather mapV inputV) defaultV predV = map pred maskV -- Scatter operations -- ------------------ -- | Copy elements from source array to destination array according to a map. This -- is a forward-permute operation where a 'map' vector encodes an input to output -- index mapping. Output elements for indices that are not mapped assume the -- default vector's value. -- -- For example: -- -- > default = [0, 0, 0, 0, 0, 0, 0, 0, 0] -- > map = [1, 3, 7, 2, 5, 8] -- > input = [1, 9, 6, 4, 4, 2, 5] -- > -- > output = [0, 1, 4, 9, 0, 4, 0, 6, 2] -- -- Note if the same index appears in the map more than once, the result is -- undefined. The map vector cannot be larger than the input vector. -- scatter :: (Elt e) => Acc (Vector Int) -- ^map -> Acc (Vector e) -- ^default -> Acc (Vector e) -- ^input -> Acc (Vector e) -- ^output scatter mapV defaultV inputV = permute (const) defaultV pF inputV where pF ix = lift (Z :. (mapV ! ix)) -- | Conditionally copy elements from source array to destination array according -- to a map. This is a forward-permute operation where a 'map' vector encodes an -- input to output index mapping. In addition, there is a 'mask' vector, and an -- associated predicate function, that specifies whether an elements will be -- copied. If not copied, the output array assumes the default vector's value. -- -- For example: -- -- > default = [0, 0, 0, 0, 0, 0, 0, 0, 0] -- > map = [1, 3, 7, 2, 5, 8] -- > mask = [3, 4, 9, 2, 7, 5] -- > pred = (> 4) -- > input = [1, 9, 6, 4, 4, 2] -- > -- > output = [0, 0, 0, 0, 0, 4, 0, 6, 2] -- -- Note if the same index appears in the map more than once, the result is -- undefined. The map and input vector must be of the same length. -- scatterIf :: (Elt e, Elt e') => Acc (Vector Int) -- ^map -> Acc (Vector e) -- ^mask -> (Exp e -> Exp Bool) -- ^predicate -> Acc (Vector e') -- ^default -> Acc (Vector e') -- ^input -> Acc (Vector e') -- ^output scatterIf mapV maskV pred defaultV inputV = permute const defaultV pF inputV where pF ix = (pred (maskV ! ix)) ? (lift (Z :. (mapV ! ix)), ignore) -- Permutations -- ------------ -- | Reverse the elements of a vector. -- reverse :: Elt e => Acc (Vector e) -> Acc (Vector e) reverse xs = let len = unindex1 (shape xs) pf i = len - i - 1 in backpermute (shape xs) (ilift1 pf) xs -- | Transpose the rows and columns of a matrix. -- transpose :: Elt e => Acc (Array DIM2 e) -> Acc (Array DIM2 e) transpose mat = let swap = lift1 $ \(Z:.x:.y) -> Z:.y:.x :: Z:.Exp Int:.Exp Int in backpermute (swap $ shape mat) swap mat -- Extracting sub-vectors -- ---------------------- -- | Yield the first @n@ elements of the input vector. The vector must contain -- no more than @n@ elements. -- take :: Elt e => Exp Int -> Acc (Vector e) -> Acc (Vector e) take n = backpermute (index1 n) id -- | Yield all but the first @n@ elements of the input vector. The vector must -- contain no more than @n@ elements. -- drop :: Elt e => Exp Int -> Acc (Vector e) -> Acc (Vector e) drop n arr = let n' = unit n in backpermute (ilift1 (subtract n) (shape arr)) (ilift1 (+ the n')) arr -- | Yield all but the last element of the input vector. The vector must not be -- empty. -- init :: Elt e => Acc (Vector e) -> Acc (Vector e) init arr = take ((unindex1 $ shape arr) - 1) arr -- | Yield all but the first element of the input vector. The vector must not be -- empty. -- tail :: Elt e => Acc (Vector e) -> Acc (Vector e) tail arr = backpermute (ilift1 (subtract 1) (shape arr)) (ilift1 (+1)) arr -- | Yield a slit (slice) from the vector. The vector must contain at least -- @i + n@ elements. Denotationally, we have: -- -- > slit i n = take n . drop i -- slit :: Elt e => Exp Int -> Exp Int -> Acc (Vector e) -> Acc (Vector e) slit i n = let i' = unit i in backpermute (index1 n) (ilift1 (+ the i'))
robeverest/accelerate
Data/Array/Accelerate/Prelude.hs
Haskell
bsd-3-clause
26,223
module Onedrive.Session (Session, newSessionWithToken, newSessionWithRenewableToken, getAccessToken, tryRenewToken) where import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (TVar, newTVar, readTVar, writeTVar) import Data.Text (Text) data Session = SessionWithToken Text | SessionWithRenewableToken (TVar Text) (IO Text) newSessionWithToken :: Text -> IO Session newSessionWithToken accessToken = return $ SessionWithToken accessToken newSessionWithRenewableToken :: Text -> IO Text -> IO Session newSessionWithRenewableToken accessToken renewAccessToken = do tokenStore <- atomically $ newTVar accessToken return $ SessionWithRenewableToken tokenStore renewAccessToken getAccessToken :: Session -> IO Text getAccessToken (SessionWithToken accessToken) = return accessToken getAccessToken (SessionWithRenewableToken accessToken _) = atomically $ readTVar accessToken tryRenewToken :: Session -> IO (Maybe Text) tryRenewToken (SessionWithToken _) = return Nothing tryRenewToken (SessionWithRenewableToken accessToken renewAccessToken) = do newAccessToken <- renewAccessToken atomically $ writeTVar accessToken newAccessToken return $ Just newAccessToken
asvyazin/hs-onedrive
src/Onedrive/Session.hs
Haskell
bsd-3-clause
1,214
-- Enter your code here. Read input from STDIN. Print output to STDOUT is_function :: [(Int, Int)] -> Bool is_function pairs = no_dups (map fst pairs) no_dups :: Eq a => [a] -> Bool no_dups [] = True no_dups (x:xs) = (not (x `elem` xs)) && (no_dups xs) swap f = \y -> \x -> f x y for = swap map list2pair :: [a] -> (a, a) list2pair [] = undefined list2pair (x : xs) = (x, head xs) main :: IO [()] main = do num_tests <- readLn sequence $ take num_tests $ repeat $ do num_pairs <- readLn pairs <- sequence $ take num_pairs $ repeat $ (list2pair . map read . words) `fmap` getLine if is_function pairs then (putStrLn "YES") else (putStrLn "NO")
capn-freako/Haskell_Misc
HackerRank/function_test.hs
Haskell
bsd-3-clause
715
{-# LANGUAGE OverloadedStrings #-} module Seeds (users) where import Data.Time import UserService.Types user1 = User "burt" "bobby" email theirAddress "218-222-5555" theirDob where email = "derp@gmail.com" theirDob = fromGregorian 2012 1 1 theirAddress = Address "Sttreet" "LA" "CA" "#1" "90210" user2 = User "basdf" "sdfawef" email theirAddress "218-222-5555" theirDob where email = "sdafasdf@gmail.com" theirDob = fromGregorian 2000 1 1 theirAddress = Address "St ave goo" "Pelican Rapids" "MN" "#1" "56572" users = [user1, user2]
tippenein/user_clone
src/Seeds.hs
Haskell
bsd-3-clause
565
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, CApiFFI #-} ----------------------------------------------------------------------------- -- | -- Module : System.IO -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : stable -- Portability : portable -- -- The standard IO library. -- ----------------------------------------------------------------------------- module System.IO ( -- * The IO monad IO, fixIO, -- * Files and handles FilePath, Handle, -- abstract, instance of: Eq, Show. -- | GHC note: a 'Handle' will be automatically closed when the garbage -- collector detects that it has become unreferenced by the program. -- However, relying on this behaviour is not generally recommended: -- the garbage collector is unpredictable. If possible, use -- an explicit 'hClose' to close 'Handle's when they are no longer -- required. GHC does not currently attempt to free up file -- descriptors when they have run out, it is your responsibility to -- ensure that this doesn't happen. -- ** Standard handles -- | Three handles are allocated during program initialisation, -- and are initially open. stdin, stdout, stderr, -- * Opening and closing files -- ** Opening files withFile, openFile, IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode), -- ** Closing files hClose, -- ** Special cases -- | These functions are also exported by the "Prelude". readFile, writeFile, appendFile, -- ** File locking -- $locking -- * Operations on handles -- ** Determining and changing the size of a file hFileSize, hSetFileSize, -- ** Detecting the end of input hIsEOF, isEOF, -- ** Buffering operations BufferMode(NoBuffering,LineBuffering,BlockBuffering), hSetBuffering, hGetBuffering, hFlush, -- ** Repositioning handles hGetPosn, hSetPosn, HandlePosn, -- abstract, instance of: Eq, Show. hSeek, SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd), hTell, -- ** Handle properties hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable, -- ** Terminal operations (not portable: GHC only) hIsTerminalDevice, hSetEcho, hGetEcho, -- ** Showing handle state (not portable: GHC only) hShow, -- * Text input and output -- ** Text input hWaitForInput, hReady, hGetChar, hGetLine, hLookAhead, hGetContents, -- ** Text output hPutChar, hPutStr, hPutStrLn, hPrint, -- ** Special cases for standard input and output -- | These functions are also exported by the "Prelude". interact, putChar, putStr, putStrLn, print, getChar, getLine, getContents, readIO, readLn, -- * Binary input and output withBinaryFile, openBinaryFile, hSetBinaryMode, hPutBuf, hGetBuf, hGetBufSome, hPutBufNonBlocking, hGetBufNonBlocking, -- * Temporary files openTempFile, openBinaryTempFile, openTempFileWithDefaultPermissions, openBinaryTempFileWithDefaultPermissions, -- * Unicode encoding\/decoding -- | A text-mode 'Handle' has an associated 'TextEncoding', which -- is used to decode bytes into Unicode characters when reading, -- and encode Unicode characters into bytes when writing. -- -- The default 'TextEncoding' is the same as the default encoding -- on your system, which is also available as 'localeEncoding'. -- (GHC note: on Windows, we currently do not support double-byte -- encodings; if the console\'s code page is unsupported, then -- 'localeEncoding' will be 'latin1'.) -- -- Encoding and decoding errors are always detected and reported, -- except during lazy I/O ('hGetContents', 'getContents', and -- 'readFile'), where a decoding error merely results in -- termination of the character stream, as with other I/O errors. hSetEncoding, hGetEncoding, -- ** Unicode encodings TextEncoding, latin1, utf8, utf8_bom, utf16, utf16le, utf16be, utf32, utf32le, utf32be, localeEncoding, char8, mkTextEncoding, -- * Newline conversion -- | In Haskell, a newline is always represented by the character -- @\'\\n\'@. However, in files and external character streams, a -- newline may be represented by another character sequence, such -- as @\'\\r\\n\'@. -- -- A text-mode 'Handle' has an associated 'NewlineMode' that -- specifies how to translate newline characters. The -- 'NewlineMode' specifies the input and output translation -- separately, so that for instance you can translate @\'\\r\\n\'@ -- to @\'\\n\'@ on input, but leave newlines as @\'\\n\'@ on output. -- -- The default 'NewlineMode' for a 'Handle' is -- 'nativeNewlineMode', which does no translation on Unix systems, -- but translates @\'\\r\\n\'@ to @\'\\n\'@ and back on Windows. -- -- Binary-mode 'Handle's do no newline translation at all. -- hSetNewlineMode, Newline(..), nativeNewline, NewlineMode(..), noNewlineTranslation, universalNewlineMode, nativeNewlineMode, ) where import Control.Exception.Base import Data.Bits import Data.Maybe import Foreign.C.Error #if defined(mingw32_HOST_OS) import Foreign.C.String import Foreign.Ptr import Foreign.Marshal.Alloc import Foreign.Storable #endif import Foreign.C.Types import System.Posix.Internals import System.Posix.Types import GHC.Base import GHC.List #if !defined(mingw32_HOST_OS) import GHC.IORef #endif import GHC.Num import GHC.IO hiding ( bracket, onException ) import GHC.IO.IOMode import GHC.IO.Handle.FD import qualified GHC.IO.FD as FD import GHC.IO.Handle import GHC.IO.Handle.Text ( hGetBufSome, hPutStrLn ) import GHC.IO.Exception ( userError ) import GHC.IO.Encoding import Text.Read import GHC.Show import GHC.MVar -- ----------------------------------------------------------------------------- -- Standard IO -- | Write a character to the standard output device -- (same as 'hPutChar' 'stdout'). putChar :: Char -> IO () putChar c = hPutChar stdout c -- | Write a string to the standard output device -- (same as 'hPutStr' 'stdout'). putStr :: String -> IO () putStr s = hPutStr stdout s -- | The same as 'putStr', but adds a newline character. putStrLn :: String -> IO () putStrLn s = hPutStrLn stdout s -- | The 'print' function outputs a value of any printable type to the -- standard output device. -- Printable types are those that are instances of class 'Show'; 'print' -- converts values to strings for output using the 'show' operation and -- adds a newline. -- -- For example, a program to print the first 20 integers and their -- powers of 2 could be written as: -- -- > main = print ([(n, 2^n) | n <- [0..19]]) print :: Show a => a -> IO () print x = putStrLn (show x) -- | Read a character from the standard input device -- (same as 'hGetChar' 'stdin'). getChar :: IO Char getChar = hGetChar stdin -- | Read a line from the standard input device -- (same as 'hGetLine' 'stdin'). getLine :: IO String getLine = hGetLine stdin -- | The 'getContents' operation returns all user input as a single string, -- which is read lazily as it is needed -- (same as 'hGetContents' 'stdin'). getContents :: IO String getContents = hGetContents stdin -- | The 'interact' function takes a function of type @String->String@ -- as its argument. The entire input from the standard input device is -- passed to this function as its argument, and the resulting string is -- output on the standard output device. interact :: (String -> String) -> IO () interact f = do s <- getContents putStr (f s) -- | The 'readFile' function reads a file and -- returns the contents of the file as a string. -- The file is read lazily, on demand, as with 'getContents'. readFile :: FilePath -> IO String readFile name = openFile name ReadMode >>= hGetContents -- | The computation 'writeFile' @file str@ function writes the string @str@, -- to the file @file@. writeFile :: FilePath -> String -> IO () writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt) -- | The computation 'appendFile' @file str@ function appends the string @str@, -- to the file @file@. -- -- Note that 'writeFile' and 'appendFile' write a literal string -- to a file. To write a value of any printable type, as with 'print', -- use the 'show' function to convert the value to a string first. -- -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]]) appendFile :: FilePath -> String -> IO () appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt) -- | The 'readLn' function combines 'getLine' and 'readIO'. readLn :: Read a => IO a readLn = do l <- getLine r <- readIO l return r -- | The 'readIO' function is similar to 'read' except that it signals -- parse failure to the 'IO' monad instead of terminating the program. readIO :: Read a => String -> IO a readIO s = case (do { (x,t) <- reads s ; ("","") <- lex t ; return x }) of [x] -> return x [] -> ioError (userError "Prelude.readIO: no parse") _ -> ioError (userError "Prelude.readIO: ambiguous parse") -- | The Unicode encoding of the current locale -- -- This is the initial locale encoding: if it has been subsequently changed by -- 'GHC.IO.Encoding.setLocaleEncoding' this value will not reflect that change. localeEncoding :: TextEncoding localeEncoding = initLocaleEncoding -- | Computation 'hReady' @hdl@ indicates whether at least one item is -- available for input from handle @hdl@. -- -- This operation may fail with: -- -- * 'System.IO.Error.isEOFError' if the end of file has been reached. hReady :: Handle -> IO Bool hReady h = hWaitForInput h 0 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@ -- given by the 'shows' function to the file or channel managed by @hdl@ -- and appends a newline. -- -- This operation may fail with: -- -- * 'System.IO.Error.isFullError' if the device is full; or -- -- * 'System.IO.Error.isPermissionError' if another system resource limit -- would be exceeded. hPrint :: Show a => Handle -> a -> IO () hPrint hdl = hPutStrLn hdl . show -- | @'withFile' name mode act@ opens a file using 'openFile' and passes -- the resulting handle to the computation @act@. The handle will be -- closed on exit from 'withFile', whether by normal termination or by -- raising an exception. If closing the handle raises an exception, then -- this exception will be raised by 'withFile' rather than any exception -- raised by @act@. withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r withFile name mode = bracket (openFile name mode) hClose -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile' -- and passes the resulting handle to the computation @act@. The handle -- will be closed on exit from 'withBinaryFile', whether by normal -- termination or by raising an exception. withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r withBinaryFile name mode = bracket (openBinaryFile name mode) hClose -- --------------------------------------------------------------------------- -- fixIO -- | The implementation of 'Control.Monad.Fix.mfix' for 'IO'. If the function -- passed to 'fixIO' inspects its argument, the resulting action will throw -- 'FixIOException'. fixIO :: (a -> IO a) -> IO a fixIO k = do m <- newEmptyMVar ans <- unsafeDupableInterleaveIO (readMVar m `catch` \BlockedIndefinitelyOnMVar -> throwIO FixIOException) result <- k ans putMVar m result return result -- NOTE: we do our own explicit black holing here, because GHC's lazy -- blackholing isn't enough. In an infinite loop, GHC may run the IO -- computation a few times before it notices the loop, which is wrong. -- -- NOTE2: the explicit black-holing with an IORef ran into trouble -- with multiple threads (see #5421), so now we use an MVar. We used -- to use takeMVar with unsafeInterleaveIO. This, however, uses noDuplicate#, -- which is not particularly cheap. Better to use readMVar, which can be -- performed in multiple threads safely, and to use unsafeDupableInterleaveIO -- to avoid the noDuplicate cost. -- -- What we'd ideally want is probably an IVar, but we don't quite have those. -- STM TVars look like an option at first, but I don't think they are: -- we'd need to be able to write to the variable in an IO context, which can -- only be done using 'atomically', and 'atomically' is not allowed within -- unsafePerformIO. We can't know if someone will try to use the result -- of fixIO with unsafePerformIO! -- -- See also System.IO.Unsafe.unsafeFixIO. -- -- | The function creates a temporary file in ReadWrite mode. -- The created file isn\'t deleted automatically, so you need to delete it manually. -- -- The file is created with permissions such that only the current -- user can read\/write it. -- -- With some exceptions (see below), the file will be created securely -- in the sense that an attacker should not be able to cause -- openTempFile to overwrite another file on the filesystem using your -- credentials, by putting symbolic links (on Unix) in the place where -- the temporary file is to be created. On Unix the @O_CREAT@ and -- @O_EXCL@ flags are used to prevent this attack, but note that -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you -- rely on this behaviour it is best to use local filesystems only. -- openTempFile :: FilePath -- ^ Directory in which to create the file -> String -- ^ File name template. If the template is \"foo.ext\" then -- the created file will be \"fooXXX.ext\" where XXX is some -- random number. Note that this should not contain any path -- separator characters. -> IO (FilePath, Handle) openTempFile tmp_dir template = openTempFile' "openTempFile" tmp_dir template False 0o600 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments. openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) openBinaryTempFile tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True 0o600 -- | Like 'openTempFile', but uses the default file permissions openTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) openTempFileWithDefaultPermissions tmp_dir template = openTempFile' "openTempFileWithDefaultPermissions" tmp_dir template False 0o666 -- | Like 'openBinaryTempFile', but uses the default file permissions openBinaryTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) openBinaryTempFileWithDefaultPermissions tmp_dir template = openTempFile' "openBinaryTempFileWithDefaultPermissions" tmp_dir template True 0o666 openTempFile' :: String -> FilePath -> String -> Bool -> CMode -> IO (FilePath, Handle) openTempFile' loc tmp_dir template binary mode | pathSeparator template = failIO $ "openTempFile': Template string must not contain path separator characters: "++template | otherwise = findTempName where -- We split off the last extension, so we can use .foo.ext files -- for temporary files (hidden on Unix OSes). Unfortunately we're -- below filepath in the hierarchy here. (prefix, suffix) = case break (== '.') $ reverse template of -- First case: template contains no '.'s. Just re-reverse it. (rev_suffix, "") -> (reverse rev_suffix, "") -- Second case: template contains at least one '.'. Strip the -- dot from the prefix and prepend it to the suffix (if we don't -- do this, the unique number will get added after the '.' and -- thus be part of the extension, which is wrong.) (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix) -- Otherwise, something is wrong, because (break (== '.')) should -- always return a pair with either the empty string or a string -- beginning with '.' as the second component. _ -> errorWithoutStackTrace "bug in System.IO.openTempFile" #if defined(mingw32_HOST_OS) findTempName = do let label = if null prefix then "ghc" else prefix withCWString tmp_dir $ \c_tmp_dir -> withCWString label $ \c_template -> withCWString suffix $ \c_suffix -> -- NOTE: revisit this when new I/O manager in place and use a UUID -- based one when we are no longer MAX_PATH bound. allocaBytes (sizeOf (undefined :: CWchar) * 260) $ \c_str -> do res <- c_getTempFileNameErrorNo c_tmp_dir c_template c_suffix 0 c_str if not res then do errno <- getErrno ioError (errnoToIOError loc errno Nothing (Just tmp_dir)) else do filename <- peekCWString c_str handleResults filename handleResults filename = do let oflags1 = rw_flags .|. o_EXCL binary_flags | binary = o_BINARY | otherwise = 0 oflags = oflags1 .|. binary_flags fd <- withFilePath filename $ \ f -> c_open f oflags mode case fd < 0 of True -> do errno <- getErrno ioError (errnoToIOError loc errno Nothing (Just tmp_dir)) False -> do (fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-} False{-is_socket-} True{-is_nonblock-} enc <- getLocaleEncoding h <- mkHandleFromFD fD fd_type filename ReadWriteMode False{-set non-block-} (Just enc) return (filename, h) foreign import ccall "getTempFileNameErrorNo" c_getTempFileNameErrorNo :: CWString -> CWString -> CWString -> CUInt -> Ptr CWchar -> IO Bool pathSeparator :: String -> Bool pathSeparator template = any (\x-> x == '/' || x == '\\') template output_flags = std_flags #else /* else mingw32_HOST_OS */ findTempName = do rs <- rand_string let filename = prefix ++ rs ++ suffix filepath = tmp_dir `combine` filename r <- openNewFile filepath binary mode case r of FileExists -> findTempName OpenNewError errno -> ioError (errnoToIOError loc errno Nothing (Just tmp_dir)) NewFileCreated fd -> do (fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-} False{-is_socket-} True{-is_nonblock-} enc <- getLocaleEncoding h <- mkHandleFromFD fD fd_type filepath ReadWriteMode False{-set non-block-} (Just enc) return (filepath, h) where -- XXX bits copied from System.FilePath, since that's not available here combine a b | null b = a | null a = b | pathSeparator [last a] = a ++ b | otherwise = a ++ [pathSeparatorChar] ++ b tempCounter :: IORef Int tempCounter = unsafePerformIO $ newIORef 0 {-# NOINLINE tempCounter #-} -- build large digit-alike number rand_string :: IO String rand_string = do r1 <- c_getpid (r2, _) <- atomicModifyIORef'_ tempCounter (+1) return $ show r1 ++ "-" ++ show r2 data OpenNewFileResult = NewFileCreated CInt | FileExists | OpenNewError Errno openNewFile :: FilePath -> Bool -> CMode -> IO OpenNewFileResult openNewFile filepath binary mode = do let oflags1 = rw_flags .|. o_EXCL binary_flags | binary = o_BINARY | otherwise = 0 oflags = oflags1 .|. binary_flags fd <- withFilePath filepath $ \ f -> c_open f oflags mode if fd < 0 then do errno <- getErrno case errno of _ | errno == eEXIST -> return FileExists _ -> return (OpenNewError errno) else return (NewFileCreated fd) -- XXX Should use filepath library pathSeparatorChar :: Char pathSeparatorChar = '/' pathSeparator :: String -> Bool pathSeparator template = pathSeparatorChar `elem` template output_flags = std_flags .|. o_CREAT #endif /* mingw32_HOST_OS */ -- XXX Copied from GHC.Handle std_flags, output_flags, rw_flags :: CInt std_flags = o_NONBLOCK .|. o_NOCTTY rw_flags = output_flags .|. o_RDWR -- $locking -- Implementations should enforce as far as possible, at least locally to the -- Haskell process, multiple-reader single-writer locking on files. -- That is, /there may either be many handles on the same file which manage input, or just one handle on the file which manages output/. If any -- open or semi-closed handle is managing a file for output, no new -- handle can be allocated for that file. If any open or semi-closed -- handle is managing a file for input, new handles can only be allocated -- if they do not manage output. Whether two files are the same is -- implementation-dependent, but they should normally be the same if they -- have the same absolute path name and neither has been renamed, for -- example. -- -- /Warning/: the 'readFile' operation holds a semi-closed handle on -- the file until the entire contents of the file have been consumed. -- It follows that an attempt to write to a file (using 'writeFile', for -- example) that was earlier opened by 'readFile' will usually result in -- failure with 'System.IO.Error.isAlreadyInUseError'.
sdiehl/ghc
libraries/base/System/IO.hs
Haskell
bsd-3-clause
22,275
-- A little benchmark adapted from attoparsec module Main where import Control.Monad -- import qualified Data.ByteString.Lazy as L import System.Environment import Data.IterIO import Data.IterIO.Parse iterio :: IO () iterio = do args <- getArgs forM_ args $ \arg -> do result <- enumFile' arg |$ p print (length result) where fast = many (while1I isLetter <|> while1I isDigit) isDigit c = c >= eord '0' && c <= eord '9' isLetter c = (c >= eord 'a' && c <= eord 'z') || (c >= eord 'A' && c <= eord 'Z') p = fast main :: IO () main = iterio
scslab/iterIO
tests/bench.hs
Haskell
bsd-3-clause
595
----------------------------------------------------------------------------- -- TIMain: Type Inference Algorithm -- -- Part of `Typing Haskell in Haskell', version of November 23, 2000 -- Copyright (c) Mark P Jones and the Oregon Graduate Institute -- of Science and Technology, 1999-2000 -- -- This program is distributed as Free Software under the terms -- in the file "License" that is included in the distribution -- of this software, copies of which may be obtained from: -- http://www.cse.ogi.edu/~mpj/thih/ -- ----------------------------------------------------------------------------- module Thih.TI.TIMain where import Data.List( (\\), intersect, union, partition ) import Thih.TI.Id import Thih.TI.Kind import Thih.TI.Type import Thih.TI.Subst import Thih.TI.Pred import Thih.TI.Scheme import Thih.TI.Assump import Thih.TI.TIMonad import Thih.TI.Infer import Thih.TI.Lit import Thih.TI.Pat import Thih.Static.Prelude ----------------------------------------------------------------------------- data Expr = Var Id | Lit Literal | Const Assump | Ap Expr Expr | Let BindGroup Expr | Lam Alt | If Expr Expr Expr | Case Expr [(Pat,Expr)] ----------------------------------------------------------------------------- -- The following helper functions are used to construct sample programs; if we -- change the representation of Expr above, then we need only change the -- definitions of the following combinators to match, and do not need to -- rewrite all the test code. ap = foldl1 Ap evar v = (Var v) elit l = (Lit l) econst c = (Const c) elet e f = foldr Let f (map toBg e) toBg :: [(Id, Maybe Scheme, [Alt])] -> BindGroup toBg g = ([(v, t, alts) | (v, Just t, alts) <- g ], filter (not . null) [[(v,alts) | (v,Nothing,alts) <- g]]) pNil = PCon nilCfun [] pCons x y = PCon consCfun [x,y] eNil = econst nilCfun eCons x y = ap [ econst consCfun, x, y ] {- ecase = Case elambda = Lam eif = If -} ecase d as = elet [[ ("_case", Nothing, [([p],e) | (p,e) <- as]) ]] (ap [evar "_case", d]) eif c t f = ecase c [(PCon trueCfun [], t),(PCon falseCfun [], f)] elambda alt = elet [[ ("_lambda", Nothing, [alt]) ]] (evar "_lambda") eguarded l = foldr (\(c,t) e -> eif c t e) efail l efail = Const ("FAIL" :>: Forall [Star] ([] :=> TGen 0)) esign e t = elet [[ ("_val", Just t, [([],e)]) ]] (evar "_val") eCompFrom p e c = ap [ econst mbindMfun, e, elambda ([p],c) ] eCompGuard e c = eif e c eNil eCompLet bgs c = elet bgs c eListRet e = eCons e eNil ----------------------------------------------------------------------------- tiExpr :: Infer Expr Type tiExpr ce as (Var i) = do sc <- find i as (ps :=> t) <- freshInst sc return (ps, t) tiExpr ce as (Const (i:>:sc)) = do (ps :=> t) <- freshInst sc return (ps, t) tiExpr ce as (Lit l) = do (ps,t) <- tiLit l return (ps, t) tiExpr ce as (Ap e f) = do (ps,te) <- tiExpr ce as e (qs,tf) <- tiExpr ce as f t <- newTVar Star unify (tf `fn` t) te return (ps++qs, t) tiExpr ce as (Let bg e) = do (ps, as') <- tiBindGroup ce as bg (qs, t) <- tiExpr ce (as' ++ as) e return (ps ++ qs, t) tiExpr ce as (Lam alt) = tiAlt ce as alt tiExpr ce as (If e e1 e2) = do (ps,t) <- tiExpr ce as e unify t tBool (ps1,t1) <- tiExpr ce as e1 (ps2,t2) <- tiExpr ce as e2 unify t1 t2 return (ps++ps1++ps2, t1) tiExpr ce as (Case e branches) = do (ps, t) <- tiExpr ce as e v <- newTVar Star let tiBr (pat, f) = do (ps, as',t') <- tiPat pat unify t t' (qs, t'') <- tiExpr ce (as'++as) f unify v t'' return (ps++qs) pss <- mapM tiBr branches return (ps++concat pss, v) ----------------------------------------------------------------------------- type Alt = ([Pat], Expr) tiAlt :: Infer Alt Type tiAlt ce as (pats, e) = do (ps, as', ts) <- tiPats pats (qs,t) <- tiExpr ce (as'++as) e return (ps++qs, foldr fn t ts) tiAlts :: ClassEnv -> [Assump] -> [Alt] -> Type -> TI [Pred] tiAlts ce as alts t = do psts <- mapM (tiAlt ce as) alts mapM (unify t) (map snd psts) return (concat (map fst psts)) ----------------------------------------------------------------------------- split :: Monad m => ClassEnv -> [Tyvar] -> [Tyvar] -> [Pred] -> m ([Pred], [Pred]) split ce fs gs ps = do ps' <- reduce ce ps let (ds, rs) = partition (all (`elem` fs) . tv) ps' rs' <- defaultedPreds ce (fs++gs) rs return (ds, rs \\ rs') type Ambiguity = (Tyvar, [Pred]) ambiguities :: ClassEnv -> [Tyvar] -> [Pred] -> [Ambiguity] ambiguities ce vs ps = [ (v, filter (elem v . tv) ps) | v <- tv ps \\ vs ] numClasses :: [Id] numClasses = ["Num", "Integral", "Floating", "Fractional", "Real", "RealFloat", "RealFrac"] stdClasses :: [Id] stdClasses = ["Eq", "Ord", "Show", "Read", "Bounded", "Enum", "Ix", "Functor", "Monad", "MonadPlus"] ++ numClasses candidates :: ClassEnv -> Ambiguity -> [Type] candidates ce (v, qs) = [ t' | let is = [ i | IsIn i t <- qs ] ts = [ t | IsIn i t <- qs ], all ((TVar v)==) ts, any (`elem` numClasses) is, all (`elem` stdClasses) is, t' <- defaults ce, all (entail ce []) [ IsIn i t' | i <- is ] ] withDefaults :: Monad m => ([Ambiguity] -> [Type] -> a) -> ClassEnv -> [Tyvar] -> [Pred] -> m a withDefaults f ce vs ps | any null tss = fail "cannot resolve ambiguity" | otherwise = return (f vps (map head tss)) where vps = ambiguities ce vs ps tss = map (candidates ce) vps defaultedPreds :: Monad m => ClassEnv -> [Tyvar] -> [Pred] -> m [Pred] defaultedPreds = withDefaults (\vps ts -> concat (map snd vps)) defaultSubst :: Monad m => ClassEnv -> [Tyvar] -> [Pred] -> m Subst defaultSubst = withDefaults (\vps ts -> zip (map fst vps) ts) ----------------------------------------------------------------------------- type Expl = (Id, Scheme, [Alt]) tiExpl :: ClassEnv -> [Assump] -> Expl -> TI [Pred] tiExpl ce as (i, sc, alts) = do (qs :=> t) <- freshInst sc ps <- tiAlts ce as alts t s <- getSubst let qs' = apply s qs t' = apply s t fs = tv (apply s as) gs = tv t' \\ fs sc' = quantify gs (qs':=>t') ps' = filter (not . entail ce qs') (apply s ps) (ds,rs) <- split ce fs gs ps' if sc /= sc' then fail "signature too general" else if not (null rs) then fail "context too weak" else return ds ----------------------------------------------------------------------------- type Impl = (Id, [Alt]) restricted :: [Impl] -> Bool restricted bs = any simple bs where simple (i,alts) = any (null . fst) alts tiImpls :: Infer [Impl] [Assump] tiImpls ce as bs = do ts <- mapM (\_ -> newTVar Star) bs let is = map fst bs scs = map toScheme ts as' = zipWith (:>:) is scs ++ as altss = map snd bs pss <- sequence (zipWith (tiAlts ce as') altss ts) s <- getSubst let ps' = apply s (concat pss) ts' = apply s ts fs = tv (apply s as) vss = map tv ts' gs = foldr1 union vss \\ fs (ds,rs) <- split ce fs (foldr1 intersect vss) ps' if restricted bs then let gs' = gs \\ tv rs scs' = map (quantify gs' . ([]:=>)) ts' in return (ds++rs, zipWith (:>:) is scs') else let scs' = map (quantify gs . (rs:=>)) ts' in return (ds, zipWith (:>:) is scs') ----------------------------------------------------------------------------- type BindGroup = ([Expl], [[Impl]]) tiBindGroup :: Infer BindGroup [Assump] tiBindGroup ce as (es,iss) = do let as' = [ v:>:sc | (v,sc,alts) <- es ] (ps, as'') <- tiSeq tiImpls ce (as'++as) iss qss <- mapM (tiExpl ce (as''++as'++as)) es return (ps++concat qss, as''++as') tiSeq :: Infer bg [Assump] -> Infer [bg] [Assump] tiSeq ti ce as [] = return ([],[]) tiSeq ti ce as (bs:bss) = do (ps,as') <- ti ce as bs (qs,as'') <- tiSeq ti ce (as'++as) bss return (ps++qs, as''++as') -----------------------------------------------------------------------------
yu-i9/thih
src/Thih/TI/TIMain.hs
Haskell
bsd-3-clause
9,988
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Diff2Html where import Data.Foldable import Data.Monoid import qualified Data.Text as T import qualified Data.Algorithm.Patience as P import Lucid import Chunk import Diff import Utils (breakWith) chunksToTable :: [Chunk] -> Html () chunksToTable chunks = table_ [class_ "diff"]$ foldMap chunkToRows chunks chunkToRows :: Chunk -> Html () chunkToRows (Chunk files pos body) = do tr_ [class_ "header"] $ mapM_ (td_ . span_ [class_ "filename"] . toHtml . fileName) files tr_ $ mapM_ showTd pos mapM_ chunkBodyToRows body where showTd :: Show a => a -> Html () showTd = cell [] . show chunkBodyToRows :: ChunkBody -> Html () chunkBodyToRows (CContext lines) = mapM_ go lines where go :: T.Text -> Html () go l = tr_ [class_ "diff"] $ cell [] l <> cell [] l chunkBodyToRows (CDiff (Diff dels adds)) = mapM_ row' (fillIn dels adds) where row, row' :: (T.Text, T.Text) -> Html () row' (del, add) = tr_ [class_ "diff"] $ fold (td_ <$> Diff delAttrs addAttrs <*> diffLines del add) row (del, add) = tr_ [class_ "diff"] $ do cell delAttrs del cell addAttrs add addAttrs = [class_ "add"] delAttrs = [class_ "del"] fillIn :: [T.Text] -> [T.Text] -> [(T.Text, T.Text)] fillIn [] [] = [] fillIn (x:xs) (y:ys) = (x, y) : fillIn xs ys fillIn (x:xs) [] = (x, T.empty) : fillIn xs [] fillIn [] (y:ys) = (T.empty, y) : fillIn [] ys cell :: ToHtml a => [Attribute] -> a -> Html () cell attrs d = td_ attrs $ pre_ (toHtml d) data Pair a b = Pair !a !b diffLines :: T.Text -> T.Text -> Diff (Html ()) diffLines a b = foldl' go (Diff mempty mempty) $ groupItems $ P.diff (T.unpack a) (T.unpack b) where go :: Diff (Html ()) -> P.Item String -> Diff (Html ()) go (Diff l r) (P.Both l' r') = Diff (l <> span_ [] (toHtml l')) (r <> span_ [] (toHtml r')) go (Diff l r) (P.Old l') = Diff (l <> span_ new (toHtml l')) r go (Diff l r) (P.New r') = Diff l (r <> span_ new (toHtml r')) new = [class_ "change"] groupItems :: [P.Item a] -> [P.Item [a]] groupItems [] = [] groupItems (P.Old a : rest) = P.Old (a:xs) : groupItems rest' where (xs, rest') = breakWith go rest go (P.Old x) = Just x go _ = Nothing groupItems (P.New a : rest) = P.New (a:xs) : groupItems rest' where (xs, rest') = breakWith go rest go (P.New x) = Just x go _ = Nothing groupItems (P.Both l r : rest) = P.Both (l:ls) (r:rs) : groupItems rest' where (ls, rs) = unzip xs (xs, rest') = breakWith go rest go (P.Both a b) = Just (a, b) go _ = Nothing
bgamari/diff-utils
src/Diff2Html.hs
Haskell
bsd-3-clause
2,790
module GalFld.GalFld ( module X , factorP , extendFFBy ) where import GalFld.Core as X import GalFld.Algorithmen as X -- |Nimmt einen Grad `d` und ein Element `e` eines Endlichen Körpers und bildet -- über den Endlichen Körper, dass das Element enthält eine Erweiterun von Grad -- `d`. -- Das übergebene Element muss "genug" Information enthalten. extendFFBy :: (Show a, Num a, Fractional a, FiniteField a) => Int -> a -> FFElem a extendFFBy d e = FFElem (pTupUnsave [(0,onefy)]) $ findIrred $ getAllMonicPs (elems e) [d] where onefy | e == 1 = e | otherwise = e / e -- |Nimmt ein Polynom f und faktorisiert dieses komplett mittels SFF und -- Berlekamp factorP :: (Show a, Num a, Fractional a, FiniteField a) => Polynom a -> [(Int,Polynom a)] factorP = aggFact . appBerlekamp . appSff . obviousFactor
maximilianhuber/softwareProjekt
src/GalFld/GalFld.hs
Haskell
bsd-3-clause
838
-- | -- Module : $Header$ -- Copyright : (c) 2013-2014 Galois, Inc. -- License : BSD3 -- Maintainer : cryptol@galois.com -- Stability : provisional -- Portability : portable {-# LANGUAGE Safe #-} {-# LANGUAGE PatternGuards #-} module Cryptol.Eval ( moduleEnv , EvalEnv() , emptyEnv , evalExpr , EvalError(..) , WithBase(..) ) where import Cryptol.Eval.Error import Cryptol.Eval.Env import Cryptol.Eval.Type import Cryptol.Eval.Value import Cryptol.TypeCheck.AST import Cryptol.Utils.Panic (panic) import Cryptol.Utils.PP import Cryptol.Prims.Eval import Data.List (transpose) import Data.Monoid (Monoid(..),mconcat) import qualified Data.Map as Map -- Expression Evaluation ------------------------------------------------------- moduleEnv :: Module -> EvalEnv -> EvalEnv moduleEnv m env = evalDecls (mDecls m) (evalNewtypes (mNewtypes m) env) evalExpr :: EvalEnv -> Expr -> Value evalExpr env expr = case expr of ECon con -> evalECon con EList es ty -> evalList env es (evalType env ty) ETuple es -> VTuple (length es) (map eval es) ERec fields -> VRecord [ (f,eval e) | (f,e) <- fields ] ESel e sel -> evalSel env e sel EIf c t f | fromVBit (eval c) -> eval t | otherwise -> eval f EComp l h gs -> evalComp env (evalType env l) h gs EVar n -> case lookupVar n env of Just val -> val Nothing -> panic "[Eval] evalExpr" ["var `" ++ show (pp n) ++ "` is not defined" , pretty (WithBase defaultPPOpts env) ] ETAbs tv b -> VPoly $ \ty -> evalExpr (bindType (tpVar tv) ty env) b ETApp e ty -> case eval e of VPoly f -> f (evalType env ty) val -> panic "[Eval] evalExpr" ["expected a polymorphic value" , show (ppV val), show e, show ty ] EApp f x -> case eval f of VFun f' -> f' (eval x) it -> panic "[Eval] evalExpr" ["not a function", show (ppV it) ] EAbs n _ty b -> VFun (\ val -> evalExpr (bindVar n val env) b ) -- XXX these will likely change once there is an evidence value EProofAbs _ e -> evalExpr env e EProofApp e -> evalExpr env e ECast e _ty -> evalExpr env e EWhere e ds -> evalExpr (evalDecls ds env) e where eval = evalExpr env ppV = ppValue defaultPPOpts -- Newtypes -------------------------------------------------------------------- evalNewtypes :: Map.Map QName Newtype -> EvalEnv -> EvalEnv evalNewtypes nts env = Map.foldl (flip evalNewtype) env nts -- | Introduce the constructor function for a newtype. evalNewtype :: Newtype -> EvalEnv -> EvalEnv evalNewtype nt = bindVar (ntName nt) (foldr tabs con (ntParams nt)) where tabs _tp body = tlam (\ _ -> body) con = VFun id -- Declarations ---------------------------------------------------------------- evalDecls :: [DeclGroup] -> EvalEnv -> EvalEnv evalDecls dgs env = foldl (flip evalDeclGroup) env dgs evalDeclGroup :: DeclGroup -> EvalEnv -> EvalEnv evalDeclGroup dg env = env' where -- the final environment is passed in for each declaration, to permit -- recursive values. env' = case dg of Recursive ds -> foldr (evalDecl env') env ds NonRecursive d -> evalDecl env d env evalDecl :: ReadEnv -> Decl -> EvalEnv -> EvalEnv evalDecl renv d = bindVar (dName d) (evalExpr renv (dDefinition d)) -- Selectors ------------------------------------------------------------------- evalSel :: ReadEnv -> Expr -> Selector -> Value evalSel env e sel = case sel of TupleSel n _ -> tupleSel n val RecordSel n _ -> recordSel n val ListSel ix _ -> fromSeq val !! ix where val = evalExpr env e tupleSel n v = case v of VTuple _ vs -> vs !! (n - 1) VSeq False vs -> VSeq False [ tupleSel n v1 | v1 <- vs ] VStream vs -> VStream [ tupleSel n v1 | v1 <- vs ] VFun f -> VFun (\x -> tupleSel n (f x)) _ -> evalPanic "Cryptol.Eval.evalSel" [ "Unexpected value in tuple selection" , show (ppValue defaultPPOpts v) ] recordSel n v = case v of VRecord {} -> lookupRecord n v VSeq False vs -> VSeq False [ recordSel n v1 | v1 <- vs ] VStream vs -> VStream [recordSel n v1 | v1 <- vs ] VFun f -> VFun (\x -> recordSel n (f x)) _ -> evalPanic "Cryptol.Eval.evalSel" [ "Unexpected value in record selection" , show (ppValue defaultPPOpts v) ] -- List Comprehensions --------------------------------------------------------- -- | Evaluate a comprehension. evalComp :: ReadEnv -> TValue -> Expr -> [[Match]] -> Value evalComp env seqty body ms | Just (len,el) <- isTSeq seqty = toSeq len el [ evalExpr e body | e <- envs ] | otherwise = evalPanic "Cryptol.Eval" [ "evalComp given a non sequence" , show seqty ] -- XXX we could potentially print this as a number if the type was available. where -- generate a new environment for each iteration of each parallel branch benvs = map (branchEnvs env) ms -- take parallel slices of each environment. when the length of the list -- drops below the number of branches, one branch has terminated. allBranches es = length es == length ms slices = takeWhile allBranches (transpose benvs) -- join environments to produce environments at each step through the process. envs = map mconcat slices -- | Turn a list of matches into the final environments for each iteration of -- the branch. branchEnvs :: ReadEnv -> [Match] -> [EvalEnv] branchEnvs env matches = case matches of m:ms -> do env' <- evalMatch env m branchEnvs env' ms [] -> return env -- | Turn a match into the list of environments it represents. evalMatch :: EvalEnv -> Match -> [EvalEnv] evalMatch env m = case m of -- many envs From n _ty expr -> do e <- fromSeq (evalExpr env expr) return (bindVar n e env) -- XXX we don't currently evaluate these as though they could be recursive, as -- they are typechecked that way; the read environment to evalDecl is the same -- as the environment to bind a new name in. Let d -> [evalDecl env d env] -- Lists ----------------------------------------------------------------------- -- | Evaluate a list literal, optionally packing them into a word. evalList :: EvalEnv -> [Expr] -> TValue -> Value evalList env es ty = toPackedSeq w ty (map (evalExpr env) es) where w = TValue $ tNum $ length es
dylanmc/cryptol
src/Cryptol/Eval.hs
Haskell
bsd-3-clause
6,625
module Reporting.Annotation where import Prelude hiding (map) import qualified Reporting.Region as R import qualified Data.String as String -- ANNOTATION data Located a = A R.Region a deriving (Eq) instance (Show a) => Show (Located a) where showsPrec p (A r a) = showParen (p > 10) $ showString $ String.unwords [ "at" , show (R.line $ R.start r) , show (R.column $ R.start r) , show (R.line $ R.end r) , show (R.column $ R.end r) , showsPrec 99 a "" ] -- CREATE at :: R.Position -> R.Position -> a -> Located a at start end value = A (R.Region start end) value merge :: Located a -> Located b -> value -> Located value merge (A region1 _) (A region2 _) value = A (R.merge region1 region2) value sameAs :: Located a -> b -> Located b sameAs (A annotation _) value = A annotation value -- MANIPULATE map :: (a -> b) -> Located a -> Located b map f (A annotation value) = A annotation (f value) drop :: Located a -> a drop (A _ value) = value class Strippable a where stripRegion :: a -> a instance Strippable (Located a) where stripRegion (A _ value) = A (R.Region (R.Position 0 0) (R.Position 0 0)) value
rgrempel/frelm.org
vendor/elm-format/parser/src/Reporting/Annotation.hs
Haskell
mit
1,260
{-# LANGUAGE StandaloneDeriving #-} module TreeDB( DirList, dlEmpty, dlByExt, dlByExts, dlAdd, dlAddByExt, TreeDB, tdbEmpty, tdbByDir, tdbAdd, tdbAddDir, tdbBuild, tdbMerge, tdbByDirExt, tdbByDirExts ) where import qualified Data.ByteString.Char8 as C import Data.List import Data.Trie(Trie) import qualified Data.Trie as T import Data.Typeable import System.FilePath -- -- The files in a directory, partitioned by extension. -- type DirList = [(String, [String])] dlEmpty :: DirList dlEmpty = [] -- Linear search for files by extension, in a single directory. dlByExt :: String -> DirList -> [String] dlByExt _ [] = [] dlByExt ext ((ext', names) : dirlist) | ext' == ext = [n <.> ext' | n <- names] | otherwise = dlByExt ext dirlist -- Search for multiple extensions at once. 'exts' must be sorted, with no -- duplicates. dlByExts :: [String] -> DirList -> [String] dlByExts _ [] = [] dlByExts [] _ = [] dlByExts (ext:exts) ((ext', names):dirlist) = case compare ext ext' of -- 'ext' isn't in the list. LT -> dlByExts exts ((ext', names):dirlist) -- 'ext' is right here. EQ -> [n <.> ext' | n <- names] ++ dlByExts exts dirlist -- 'ext' may be in the remainder. Nothing else can match here. GT -> dlByExts (ext:exts) dirlist -- Insert a file, given its extension. Again linear. dlAdd :: FilePath -> DirList -> DirList dlAdd file dirList = dlAddByExt (takeExtension file) (dropExtension file) dirList -- Keeps the list sorted by extension dlAddByExt :: String -> String -> DirList -> DirList dlAddByExt ext name [] = [(ext, [name])] dlAddByExt ext name ((ext', names):dirlist) = case compare ext ext' of LT -> (ext, [name]):(ext', names):dirlist EQ -> (ext', name:names):dirlist GT -> (ext', names):(dlAddByExt ext name dirlist) -- -- A map from directory to contents, excluding subdirectories. -- type TreeDB = Trie DirList deriving instance Typeable Trie tdbEmpty :: TreeDB tdbEmpty = T.empty -- Get directory contents by directory path tdbByDir :: FilePath -> TreeDB -> Maybe DirList tdbByDir path treeDB = T.lookup (C.pack path) treeDB -- Add a file tdbAdd :: FilePath -> TreeDB -> TreeDB tdbAdd path treeDB | T.member dirS treeDB = T.adjust (\dirList -> dlAdd file dirList) dirS treeDB | otherwise = T.insert dirS (dlAdd file dlEmpty) treeDB where dir = takeDirectory path file = takeFileName path dirS = C.pack dir -- Add a directory, complete with (relative) contents tdbAddDir :: FilePath -> [FilePath] -> TreeDB -> TreeDB tdbAddDir dir files treeDB | T.member dirS treeDB = T.adjust (\dirList -> foldr dlAdd dirList files) dirS treeDB | otherwise = T.insert dirS (foldr dlAdd dlEmpty files) treeDB where dirS = C.pack dir tdbBuild :: [FilePath] -> TreeDB tdbBuild files = foldr tdbAdd tdbEmpty files tdbMerge :: TreeDB -> TreeDB -> TreeDB tdbMerge = T.unionL -- -- Combined queries -- -- Find files by directory and extension tdbByDirExt :: FilePath -> String -> TreeDB -> Maybe [FilePath] tdbByDirExt path ext treeDB = do dirList <- tdbByDir path treeDB let filenames = dlByExt ext dirList return [ path </> file | file <- filenames ] -- Look for multiple extensions. 'exts' need not be sorted. tdbByDirExts :: FilePath -> [String] -> TreeDB -> Maybe [FilePath] tdbByDirExts path exts treeDB = do dirList <- tdbByDir path treeDB let filenames = dlByExts (sort exts) dirList return [ path </> file | file <- filenames ]
kishoredbn/barrelfish
hake/TreeDB.hs
Haskell
mit
3,589
-- | This module provide a totally partial and incomplete maping -- of Exif values. Used for Tiff parsing and reused for Exif extraction. module Codec.Picture.Metadata.Exif ( ExifTag( .. ) , ExifData( .. ) , tagOfWord16 , word16OfTag ) where import Control.DeepSeq( NFData( .. ) ) import Data.Int( Int32 ) import Data.Word( Word16, Word32 ) import qualified Data.Vector as V import qualified Data.ByteString as B -- | Tag values used for exif fields. Completly incomplete data ExifTag = TagPhotometricInterpretation | TagCompression -- ^ Short type | TagImageWidth -- ^ Short or long type | TagImageLength -- ^ Short or long type | TagXResolution -- ^ Rational type | TagYResolution -- ^ Rational type | TagResolutionUnit -- ^ Short type | TagRowPerStrip -- ^ Short or long type | TagStripByteCounts -- ^ Short or long | TagStripOffsets -- ^ Short or long | TagBitsPerSample -- ^ Short | TagColorMap -- ^ Short | TagTileWidth | TagTileLength | TagTileOffset | TagTileByteCount | TagSamplesPerPixel -- ^ Short | TagArtist | TagDocumentName | TagSoftware | TagPlanarConfiguration -- ^ Short | TagOrientation | TagSampleFormat -- ^ Short | TagInkSet | TagSubfileType | TagFillOrder | TagYCbCrCoeff | TagYCbCrSubsampling | TagYCbCrPositioning | TagReferenceBlackWhite | TagXPosition | TagYPosition | TagExtraSample | TagImageDescription | TagPredictor | TagCopyright | TagMake | TagModel | TagDateTime | TagGPSInfo | TagJpegProc | TagJPEGInterchangeFormat | TagJPEGInterchangeFormatLength | TagJPEGRestartInterval | TagJPEGLosslessPredictors | TagJPEGPointTransforms | TagJPEGQTables | TagJPEGDCTables | TagJPEGACTables | TagExifOffset | TagUnknown !Word16 deriving (Eq, Ord, Show) -- | Convert a value to it's corresponding Exif tag. -- Will often be written as 'TagUnknown' tagOfWord16 :: Word16 -> ExifTag tagOfWord16 v = case v of 255 -> TagSubfileType 256 -> TagImageWidth 257 -> TagImageLength 258 -> TagBitsPerSample 259 -> TagCompression 262 -> TagPhotometricInterpretation 266 -> TagFillOrder 269 -> TagDocumentName 270 -> TagImageDescription 271 -> TagMake 272 -> TagModel 273 -> TagStripOffsets 274 -> TagOrientation 277 -> TagSamplesPerPixel 278 -> TagRowPerStrip 279 -> TagStripByteCounts 282 -> TagXResolution 283 -> TagYResolution 284 -> TagPlanarConfiguration 286 -> TagXPosition 287 -> TagYPosition 296 -> TagResolutionUnit 305 -> TagSoftware 306 -> TagDateTime 315 -> TagArtist 317 -> TagPredictor 320 -> TagColorMap 322 -> TagTileWidth 323 -> TagTileLength 324 -> TagTileOffset 325 -> TagTileByteCount 332 -> TagInkSet 338 -> TagExtraSample 339 -> TagSampleFormat 529 -> TagYCbCrCoeff 512 -> TagJpegProc 513 -> TagJPEGInterchangeFormat 514 -> TagJPEGInterchangeFormatLength 515 -> TagJPEGRestartInterval 517 -> TagJPEGLosslessPredictors 518 -> TagJPEGPointTransforms 519 -> TagJPEGQTables 520 -> TagJPEGDCTables 521 -> TagJPEGACTables 530 -> TagYCbCrSubsampling 531 -> TagYCbCrPositioning 532 -> TagReferenceBlackWhite 33432 -> TagCopyright 34665 -> TagExifOffset 34853 -> TagGPSInfo vv -> TagUnknown vv -- | Convert a tag to it's corresponding value. word16OfTag :: ExifTag -> Word16 word16OfTag t = case t of TagSubfileType -> 255 TagImageWidth -> 256 TagImageLength -> 257 TagBitsPerSample -> 258 TagCompression -> 259 TagPhotometricInterpretation -> 262 TagFillOrder -> 266 TagDocumentName -> 269 TagImageDescription -> 270 TagMake -> 271 TagModel -> 272 TagStripOffsets -> 273 TagOrientation -> 274 TagSamplesPerPixel -> 277 TagRowPerStrip -> 278 TagStripByteCounts -> 279 TagXResolution -> 282 TagYResolution -> 283 TagPlanarConfiguration -> 284 TagXPosition -> 286 TagYPosition -> 287 TagResolutionUnit -> 296 TagSoftware -> 305 TagDateTime -> 306 TagArtist -> 315 TagPredictor -> 317 TagColorMap -> 320 TagTileWidth -> 322 TagTileLength -> 323 TagTileOffset -> 324 TagTileByteCount -> 325 TagInkSet -> 332 TagExtraSample -> 338 TagSampleFormat -> 339 TagYCbCrCoeff -> 529 TagJpegProc -> 512 TagJPEGInterchangeFormat -> 513 TagJPEGInterchangeFormatLength -> 514 TagJPEGRestartInterval -> 515 TagJPEGLosslessPredictors -> 517 TagJPEGPointTransforms -> 518 TagJPEGQTables -> 519 TagJPEGDCTables -> 520 TagJPEGACTables -> 521 TagYCbCrSubsampling -> 530 TagYCbCrPositioning -> 531 TagReferenceBlackWhite -> 532 TagCopyright -> 33432 TagExifOffset -> 34665 TagGPSInfo -> 34853 (TagUnknown v) -> v -- | Possible data held by an Exif tag data ExifData = ExifNone | ExifLong !Word32 | ExifShort !Word16 | ExifString !B.ByteString | ExifUndefined !B.ByteString | ExifShorts !(V.Vector Word16) | ExifLongs !(V.Vector Word32) | ExifRational !Word32 !Word32 | ExifSignedRational !Int32 !Int32 | ExifIFD ![(ExifTag, ExifData)] deriving Show instance NFData ExifTag where rnf a = a `seq` () instance NFData ExifData where rnf (ExifIFD ifds) = rnf ifds `seq` () rnf (ExifLongs l) = rnf l `seq` () rnf (ExifShorts l) = rnf l `seq` () rnf a = a `seq` ()
clinty/Juicy.Pixels
src/Codec/Picture/Metadata/Exif.hs
Haskell
bsd-3-clause
5,379
module CmmMachOp ( MachOp(..) , pprMachOp, isCommutableMachOp, isAssociativeMachOp , isComparisonMachOp, machOpResultType , machOpArgReps, maybeInvertComparison -- MachOp builders , mo_wordAdd, mo_wordSub, mo_wordEq, mo_wordNe,mo_wordMul, mo_wordSQuot , mo_wordSRem, mo_wordSNeg, mo_wordUQuot, mo_wordURem , mo_wordSGe, mo_wordSLe, mo_wordSGt, mo_wordSLt, mo_wordUGe , mo_wordULe, mo_wordUGt, mo_wordULt , mo_wordAnd, mo_wordOr, mo_wordXor, mo_wordNot, mo_wordShl, mo_wordSShr, mo_wordUShr , mo_u_8To32, mo_s_8To32, mo_u_16To32, mo_s_16To32 , mo_u_8ToWord, mo_s_8ToWord, mo_u_16ToWord, mo_s_16ToWord, mo_u_32ToWord, mo_s_32ToWord , mo_32To8, mo_32To16, mo_WordTo8, mo_WordTo16, mo_WordTo32 -- CallishMachOp , CallishMachOp(..) , pprCallishMachOp ) where #include "HsVersions.h" import CmmType import Outputable ----------------------------------------------------------------------------- -- MachOp ----------------------------------------------------------------------------- {- | Machine-level primops; ones which we can reasonably delegate to the native code generators to handle. Most operations are parameterised by the 'Width' that they operate on. Some operations have separate signed and unsigned versions, and float and integer versions. -} data MachOp -- Integer operations (insensitive to signed/unsigned) = MO_Add Width | MO_Sub Width | MO_Eq Width | MO_Ne Width | MO_Mul Width -- low word of multiply -- Signed multiply/divide | MO_S_MulMayOflo Width -- nonzero if signed multiply overflows | MO_S_Quot Width -- signed / (same semantics as IntQuotOp) | MO_S_Rem Width -- signed % (same semantics as IntRemOp) | MO_S_Neg Width -- unary - -- Unsigned multiply/divide | MO_U_MulMayOflo Width -- nonzero if unsigned multiply overflows | MO_U_Quot Width -- unsigned / (same semantics as WordQuotOp) | MO_U_Rem Width -- unsigned % (same semantics as WordRemOp) -- Signed comparisons | MO_S_Ge Width | MO_S_Le Width | MO_S_Gt Width | MO_S_Lt Width -- Unsigned comparisons | MO_U_Ge Width | MO_U_Le Width | MO_U_Gt Width | MO_U_Lt Width -- Floating point arithmetic | MO_F_Add Width | MO_F_Sub Width | MO_F_Neg Width -- unary - | MO_F_Mul Width | MO_F_Quot Width -- Floating point comparison | MO_F_Eq Width | MO_F_Ne Width | MO_F_Ge Width | MO_F_Le Width | MO_F_Gt Width | MO_F_Lt Width -- Bitwise operations. Not all of these may be supported -- at all sizes, and only integral Widths are valid. | MO_And Width | MO_Or Width | MO_Xor Width | MO_Not Width | MO_Shl Width | MO_U_Shr Width -- unsigned shift right | MO_S_Shr Width -- signed shift right -- Conversions. Some of these will be NOPs. -- Floating-point conversions use the signed variant. | MO_SF_Conv Width Width -- Signed int -> Float | MO_FS_Conv Width Width -- Float -> Signed int | MO_SS_Conv Width Width -- Signed int -> Signed int | MO_UU_Conv Width Width -- unsigned int -> unsigned int | MO_FF_Conv Width Width -- Float -> Float deriving (Eq, Show) pprMachOp :: MachOp -> SDoc pprMachOp mo = text (show mo) -- ----------------------------------------------------------------------------- -- Some common MachReps -- A 'wordRep' is a machine word on the target architecture -- Specifically, it is the size of an Int#, Word#, Addr# -- and the unit of allocation on the stack and the heap -- Any pointer is also guaranteed to be a wordRep. mo_wordAdd, mo_wordSub, mo_wordEq, mo_wordNe,mo_wordMul, mo_wordSQuot , mo_wordSRem, mo_wordSNeg, mo_wordUQuot, mo_wordURem , mo_wordSGe, mo_wordSLe, mo_wordSGt, mo_wordSLt, mo_wordUGe , mo_wordULe, mo_wordUGt, mo_wordULt , mo_wordAnd, mo_wordOr, mo_wordXor, mo_wordNot, mo_wordShl, mo_wordSShr, mo_wordUShr , mo_u_8To32, mo_s_8To32, mo_u_16To32, mo_s_16To32 , mo_u_8ToWord, mo_s_8ToWord, mo_u_16ToWord, mo_s_16ToWord, mo_u_32ToWord, mo_s_32ToWord , mo_32To8, mo_32To16, mo_WordTo8, mo_WordTo16, mo_WordTo32 :: MachOp mo_wordAdd = MO_Add wordWidth mo_wordSub = MO_Sub wordWidth mo_wordEq = MO_Eq wordWidth mo_wordNe = MO_Ne wordWidth mo_wordMul = MO_Mul wordWidth mo_wordSQuot = MO_S_Quot wordWidth mo_wordSRem = MO_S_Rem wordWidth mo_wordSNeg = MO_S_Neg wordWidth mo_wordUQuot = MO_U_Quot wordWidth mo_wordURem = MO_U_Rem wordWidth mo_wordSGe = MO_S_Ge wordWidth mo_wordSLe = MO_S_Le wordWidth mo_wordSGt = MO_S_Gt wordWidth mo_wordSLt = MO_S_Lt wordWidth mo_wordUGe = MO_U_Ge wordWidth mo_wordULe = MO_U_Le wordWidth mo_wordUGt = MO_U_Gt wordWidth mo_wordULt = MO_U_Lt wordWidth mo_wordAnd = MO_And wordWidth mo_wordOr = MO_Or wordWidth mo_wordXor = MO_Xor wordWidth mo_wordNot = MO_Not wordWidth mo_wordShl = MO_Shl wordWidth mo_wordSShr = MO_S_Shr wordWidth mo_wordUShr = MO_U_Shr wordWidth mo_u_8To32 = MO_UU_Conv W8 W32 mo_s_8To32 = MO_SS_Conv W8 W32 mo_u_16To32 = MO_UU_Conv W16 W32 mo_s_16To32 = MO_SS_Conv W16 W32 mo_u_8ToWord = MO_UU_Conv W8 wordWidth mo_s_8ToWord = MO_SS_Conv W8 wordWidth mo_u_16ToWord = MO_UU_Conv W16 wordWidth mo_s_16ToWord = MO_SS_Conv W16 wordWidth mo_s_32ToWord = MO_SS_Conv W32 wordWidth mo_u_32ToWord = MO_UU_Conv W32 wordWidth mo_WordTo8 = MO_UU_Conv wordWidth W8 mo_WordTo16 = MO_UU_Conv wordWidth W16 mo_WordTo32 = MO_UU_Conv wordWidth W32 mo_32To8 = MO_UU_Conv W32 W8 mo_32To16 = MO_UU_Conv W32 W16 -- ---------------------------------------------------------------------------- -- isCommutableMachOp {- | Returns 'True' if the MachOp has commutable arguments. This is used in the platform-independent Cmm optimisations. If in doubt, return 'False'. This generates worse code on the native routes, but is otherwise harmless. -} isCommutableMachOp :: MachOp -> Bool isCommutableMachOp mop = case mop of MO_Add _ -> True MO_Eq _ -> True MO_Ne _ -> True MO_Mul _ -> True MO_S_MulMayOflo _ -> True MO_U_MulMayOflo _ -> True MO_And _ -> True MO_Or _ -> True MO_Xor _ -> True _other -> False -- ---------------------------------------------------------------------------- -- isAssociativeMachOp {- | Returns 'True' if the MachOp is associative (i.e. @(x+y)+z == x+(y+z)@) This is used in the platform-independent Cmm optimisations. If in doubt, return 'False'. This generates worse code on the native routes, but is otherwise harmless. -} isAssociativeMachOp :: MachOp -> Bool isAssociativeMachOp mop = case mop of MO_Add {} -> True -- NB: does not include MO_Mul {} -> True -- floatint point! MO_And {} -> True MO_Or {} -> True MO_Xor {} -> True _other -> False -- ---------------------------------------------------------------------------- -- isComparisonMachOp {- | Returns 'True' if the MachOp is a comparison. If in doubt, return False. This generates worse code on the native routes, but is otherwise harmless. -} isComparisonMachOp :: MachOp -> Bool isComparisonMachOp mop = case mop of MO_Eq _ -> True MO_Ne _ -> True MO_S_Ge _ -> True MO_S_Le _ -> True MO_S_Gt _ -> True MO_S_Lt _ -> True MO_U_Ge _ -> True MO_U_Le _ -> True MO_U_Gt _ -> True MO_U_Lt _ -> True MO_F_Eq {} -> True MO_F_Ne {} -> True MO_F_Ge {} -> True MO_F_Le {} -> True MO_F_Gt {} -> True MO_F_Lt {} -> True _other -> False -- ----------------------------------------------------------------------------- -- Inverting conditions -- Sometimes it's useful to be able to invert the sense of a -- condition. Not all conditional tests are invertible: in -- particular, floating point conditionals cannot be inverted, because -- there exist floating-point values which return False for both senses -- of a condition (eg. !(NaN > NaN) && !(NaN /<= NaN)). maybeInvertComparison :: MachOp -> Maybe MachOp maybeInvertComparison op = case op of -- None of these Just cases include floating point MO_Eq r -> Just (MO_Ne r) MO_Ne r -> Just (MO_Eq r) MO_U_Lt r -> Just (MO_U_Ge r) MO_U_Gt r -> Just (MO_U_Le r) MO_U_Le r -> Just (MO_U_Gt r) MO_U_Ge r -> Just (MO_U_Lt r) MO_S_Lt r -> Just (MO_S_Ge r) MO_S_Gt r -> Just (MO_S_Le r) MO_S_Le r -> Just (MO_S_Gt r) MO_S_Ge r -> Just (MO_S_Lt r) MO_F_Eq r -> Just (MO_F_Ne r) MO_F_Ne r -> Just (MO_F_Eq r) MO_F_Ge r -> Just (MO_F_Le r) MO_F_Le r -> Just (MO_F_Ge r) MO_F_Gt r -> Just (MO_F_Lt r) MO_F_Lt r -> Just (MO_F_Gt r) _other -> Nothing -- ---------------------------------------------------------------------------- -- machOpResultType {- | Returns the MachRep of the result of a MachOp. -} machOpResultType :: MachOp -> [CmmType] -> CmmType machOpResultType mop tys = case mop of MO_Add {} -> ty1 -- Preserve GC-ptr-hood MO_Sub {} -> ty1 -- of first arg MO_Mul r -> cmmBits r MO_S_MulMayOflo r -> cmmBits r MO_S_Quot r -> cmmBits r MO_S_Rem r -> cmmBits r MO_S_Neg r -> cmmBits r MO_U_MulMayOflo r -> cmmBits r MO_U_Quot r -> cmmBits r MO_U_Rem r -> cmmBits r MO_Eq {} -> comparisonResultRep MO_Ne {} -> comparisonResultRep MO_S_Ge {} -> comparisonResultRep MO_S_Le {} -> comparisonResultRep MO_S_Gt {} -> comparisonResultRep MO_S_Lt {} -> comparisonResultRep MO_U_Ge {} -> comparisonResultRep MO_U_Le {} -> comparisonResultRep MO_U_Gt {} -> comparisonResultRep MO_U_Lt {} -> comparisonResultRep MO_F_Add r -> cmmFloat r MO_F_Sub r -> cmmFloat r MO_F_Mul r -> cmmFloat r MO_F_Quot r -> cmmFloat r MO_F_Neg r -> cmmFloat r MO_F_Eq {} -> comparisonResultRep MO_F_Ne {} -> comparisonResultRep MO_F_Ge {} -> comparisonResultRep MO_F_Le {} -> comparisonResultRep MO_F_Gt {} -> comparisonResultRep MO_F_Lt {} -> comparisonResultRep MO_And {} -> ty1 -- Used for pointer masking MO_Or {} -> ty1 MO_Xor {} -> ty1 MO_Not r -> cmmBits r MO_Shl r -> cmmBits r MO_U_Shr r -> cmmBits r MO_S_Shr r -> cmmBits r MO_SS_Conv _ to -> cmmBits to MO_UU_Conv _ to -> cmmBits to MO_FS_Conv _ to -> cmmBits to MO_SF_Conv _ to -> cmmFloat to MO_FF_Conv _ to -> cmmFloat to where (ty1:_) = tys comparisonResultRep :: CmmType comparisonResultRep = bWord -- is it? -- ----------------------------------------------------------------------------- -- machOpArgReps -- | This function is used for debugging only: we can check whether an -- application of a MachOp is "type-correct" by checking that the MachReps of -- its arguments are the same as the MachOp expects. This is used when -- linting a CmmExpr. machOpArgReps :: MachOp -> [Width] machOpArgReps op = case op of MO_Add r -> [r,r] MO_Sub r -> [r,r] MO_Eq r -> [r,r] MO_Ne r -> [r,r] MO_Mul r -> [r,r] MO_S_MulMayOflo r -> [r,r] MO_S_Quot r -> [r,r] MO_S_Rem r -> [r,r] MO_S_Neg r -> [r] MO_U_MulMayOflo r -> [r,r] MO_U_Quot r -> [r,r] MO_U_Rem r -> [r,r] MO_S_Ge r -> [r,r] MO_S_Le r -> [r,r] MO_S_Gt r -> [r,r] MO_S_Lt r -> [r,r] MO_U_Ge r -> [r,r] MO_U_Le r -> [r,r] MO_U_Gt r -> [r,r] MO_U_Lt r -> [r,r] MO_F_Add r -> [r,r] MO_F_Sub r -> [r,r] MO_F_Mul r -> [r,r] MO_F_Quot r -> [r,r] MO_F_Neg r -> [r] MO_F_Eq r -> [r,r] MO_F_Ne r -> [r,r] MO_F_Ge r -> [r,r] MO_F_Le r -> [r,r] MO_F_Gt r -> [r,r] MO_F_Lt r -> [r,r] MO_And r -> [r,r] MO_Or r -> [r,r] MO_Xor r -> [r,r] MO_Not r -> [r] MO_Shl r -> [r,wordWidth] MO_U_Shr r -> [r,wordWidth] MO_S_Shr r -> [r,wordWidth] MO_SS_Conv from _ -> [from] MO_UU_Conv from _ -> [from] MO_SF_Conv from _ -> [from] MO_FS_Conv from _ -> [from] MO_FF_Conv from _ -> [from] ----------------------------------------------------------------------------- -- CallishMachOp ----------------------------------------------------------------------------- -- CallishMachOps tend to be implemented by foreign calls in some backends, -- so we separate them out. In Cmm, these can only occur in a -- statement position, in contrast to an ordinary MachOp which can occur -- anywhere in an expression. data CallishMachOp = MO_F64_Pwr | MO_F64_Sin | MO_F64_Cos | MO_F64_Tan | MO_F64_Sinh | MO_F64_Cosh | MO_F64_Tanh | MO_F64_Asin | MO_F64_Acos | MO_F64_Atan | MO_F64_Log | MO_F64_Exp | MO_F64_Sqrt | MO_F32_Pwr | MO_F32_Sin | MO_F32_Cos | MO_F32_Tan | MO_F32_Sinh | MO_F32_Cosh | MO_F32_Tanh | MO_F32_Asin | MO_F32_Acos | MO_F32_Atan | MO_F32_Log | MO_F32_Exp | MO_F32_Sqrt | MO_WriteBarrier | MO_Touch -- Keep variables live (when using interior pointers) -- Note that these three MachOps all take 1 extra parameter than the -- standard C lib versions. The extra (last) parameter contains -- alignment of the pointers. Used for optimisation in backends. | MO_Memcpy | MO_Memset | MO_Memmove | MO_PopCnt Width deriving (Eq, Show) pprCallishMachOp :: CallishMachOp -> SDoc pprCallishMachOp mo = text (show mo)
mcmaniac/ghc
compiler/cmm/CmmMachOp.hs
Haskell
bsd-3-clause
14,455
{-# LANGUAGE OverloadedStrings #-} -- | -- Module: Trace.Hpc.Coveralls -- Copyright: (c) 2014-2015 Guillaume Nargeot -- License: BSD3 -- Maintainer: Guillaume Nargeot <guillaume+hackage@nargeot.com> -- Stability: experimental -- -- Functions for converting and sending hpc output to coveralls.io. module Trace.Hpc.Coveralls ( generateCoverallsFromTix ) where import Control.Applicative import Data.Aeson import Data.Aeson.Types () import qualified Data.ByteString.Lazy.Char8 as LBS import Data.Digest.Pure.MD5 import Data.Function import Data.List import qualified Data.Map.Strict as M import System.Exit (exitFailure) import Trace.Hpc.Coveralls.Config import Trace.Hpc.Coveralls.GitInfo (GitInfo) import Trace.Hpc.Coveralls.Lix import Trace.Hpc.Coveralls.Paths import Trace.Hpc.Coveralls.Types import Trace.Hpc.Coveralls.Util import Trace.Hpc.Mix import Trace.Hpc.Tix import Trace.Hpc.Util type ModuleCoverageData = ( String, -- file source code Mix, -- module index data [Integer]) -- tixs recorded by hpc type TestSuiteCoverageData = M.Map FilePath ModuleCoverageData -- single file coverage data in the format defined by coveralls.io type SimpleCoverage = [CoverageValue] -- Is there a way to restrict this to only Number and Null? type CoverageValue = Value type LixConverter = Lix -> SimpleCoverage strictConverter :: LixConverter strictConverter = map $ \lix -> case lix of Full -> Number 1 Partial -> Number 0 None -> Number 0 Irrelevant -> Null looseConverter :: LixConverter looseConverter = map $ \lix -> case lix of Full -> Number 2 Partial -> Number 1 None -> Number 0 Irrelevant -> Null toSimpleCoverage :: LixConverter -> Int -> [CoverageEntry] -> SimpleCoverage toSimpleCoverage convert lineCount = convert . toLix lineCount getExprSource :: [String] -> MixEntry -> [String] getExprSource source (hpcPos, _) = subSubSeq startCol endCol subLines where subLines = subSeq startLine endLine source startLine = startLine' - 1 startCol = startCol' - 1 (startLine', startCol', endLine, endCol) = fromHpcPos hpcPos groupMixEntryTixs :: [(MixEntry, Integer, [String])] -> [CoverageEntry] groupMixEntryTixs = map mergeOnLst3 . groupBy ((==) `on` fst . fst3) where mergeOnLst3 xxs@(x : _) = (map fst3 xxs, map snd3 xxs, trd3 x) mergeOnLst3 [] = error "mergeOnLst3 appliedTo empty list" coverageToJson :: LixConverter -> FilePath -> ModuleCoverageData -> Value coverageToJson converter filePath (source, mix, tixs) = object [ "name" .= filePath, "source_digest" .= (show . md5 . LBS.pack) source, "coverage" .= coverage] where coverage = toSimpleCoverage converter lineCount mixEntriesTixs lineCount = length $ lines source mixEntriesTixs = groupMixEntryTixs mixEntryTixs mixEntryTixs = zip3 mixEntries tixs (map getExprSource' mixEntries) Mix _ _ _ _ mixEntries = mix getExprSource' = getExprSource $ lines source toCoverallsJson :: String -> String -> Maybe String -> GitInfo -> LixConverter -> TestSuiteCoverageData -> Value toCoverallsJson serviceName jobId repoTokenM gitInfo converter testSuiteCoverageData = object $ if serviceName == "travis-ci" then withRepoToken else withGitInfo where base = [ "service_job_id" .= jobId, "service_name" .= serviceName, "source_files" .= toJsonCoverageList testSuiteCoverageData] toJsonCoverageList = map (uncurry $ coverageToJson converter) . M.toList withRepoToken = mcons (("repo_token" .=) <$> repoTokenM) base withGitInfo = ("git" .= gitInfo) : withRepoToken mergeModuleCoverageData :: ModuleCoverageData -> ModuleCoverageData -> ModuleCoverageData mergeModuleCoverageData (source, mix, tixs1) (_, _, tixs2) = (source, mix, zipWith (+) tixs1 tixs2) mergeCoverageData :: [TestSuiteCoverageData] -> TestSuiteCoverageData mergeCoverageData = foldr1 (M.unionWith mergeModuleCoverageData) readMix' :: Maybe String -> String -> String -> TixModule -> IO Mix readMix' mPkgNameVer hpcDir name tix = readMix dirs (Right tix) where dirs = nub $ (\x -> getMixPath x hpcDir name tix) <$> [Nothing, mPkgNameVer] -- | Create a list of coverage data from the tix input readCoverageData :: Maybe String -- ^ Package name-version -> String -- ^ hpc data directory -> [String] -- ^ excluded source folders -> String -- ^ test suite name -> IO TestSuiteCoverageData -- ^ coverage data list readCoverageData mPkgNameVer hpcDir excludeDirPatterns testSuiteName = do let tixPath = getTixPath hpcDir testSuiteName mTix <- readTix tixPath case mTix of Nothing -> putStrLn ("Couldn't find the file " ++ tixPath) >> dumpDirectoryTree hpcDir >> ioFailure Just (Tix tixs) -> do mixs <- mapM (readMix' mPkgNameVer hpcDir testSuiteName) tixs let files = map filePath mixs sources <- mapM readFile files let coverageDataList = zip4 files sources mixs (map tixModuleTixs tixs) let filteredCoverageDataList = filter sourceDirFilter coverageDataList return $ M.fromList $ map toFirstAndRest filteredCoverageDataList where filePath (Mix fp _ _ _ _) = fp sourceDirFilter = not . matchAny excludeDirPatterns . fst4 -- | Generate coveralls json formatted code coverage from hpc coverage data generateCoverallsFromTix :: String -- ^ CI name -> String -- ^ CI Job ID -> GitInfo -- ^ Git repo information -> Config -- ^ hpc-coveralls configuration -> Maybe String -- ^ Package name-version -> IO Value -- ^ code coverage result in json format generateCoverallsFromTix serviceName jobId gitInfo config mPkgNameVer = do mHpcDir <- firstExistingDirectory hpcDirs case mHpcDir of Nothing -> putStrLn "Couldn't find the hpc data directory" >> dumpDirectory distDir >> ioFailure Just hpcDir -> do testSuitesCoverages <- mapM (readCoverageData mPkgNameVer hpcDir excludedDirPatterns) testSuiteNames let coverageData = mergeCoverageData testSuitesCoverages return $ toCoverallsJson serviceName jobId repoTokenM gitInfo converter coverageData where excludedDirPatterns = excludedDirs config testSuiteNames = testSuites config repoTokenM = repoToken config converter = case coverageMode config of StrictlyFullLines -> strictConverter AllowPartialLines -> looseConverter ioFailure :: IO a ioFailure = putStrLn ("You can get support at " ++ gitterUrl) >> exitFailure where gitterUrl = "https://gitter.im/guillaume-nargeot/hpc-coveralls" :: String
jdnavarro/hpc-coveralls
src/Trace/Hpc/Coveralls.hs
Haskell
bsd-3-clause
7,216
main = putStrLn "hello" foo x = y + 3 y = 7
ankhers/haskell-ide-engine
test/testdata/HaReDemote.hs
Haskell
bsd-3-clause
47
{-# LANGUAGE TypeFamilies, EmptyDataDecls, GADTs #-} module T4484 where import Data.Kind (Type) type family F f :: Type data Id c = Id type instance F (Id c) = c data C :: Type -> Type where C :: f -> C (W (F f)) data W :: Type -> Type fails :: C a -> C a fails (C _) = -- We know (W (F f) ~ a) C Id -- We need (a ~ W (F (Id beta))) -- ie (a ~ W beta) -- Use the equality; we need -- (W (F f) ~ W beta) -- ie (F f ~ beta) -- Solve with beta := f works :: C (W a) -> C (W a) works (C _) = -- We know (W (F f) ~ W a) C Id -- We need (W a ~ W (F (Id beta))) -- ie (W a ~ W beta) -- Solve with beta := a
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/T4484.hs
Haskell
bsd-3-clause
714
-- | Comment on the first declaration main = return ()
sdiehl/ghc
testsuite/tests/haddock/should_compile_flag_haddock/T17561.hs
Haskell
bsd-3-clause
55
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module T5886a where import Language.Haskell.TH class C α where type AT α ∷ ★ bang ∷ DecsQ bang = return [InstanceD Nothing [] (AppT (ConT ''C) (ConT ''Int)) [TySynInstD ''AT (TySynEqn [ConT ''Int] (ConT ''Int))]]
olsner/ghc
testsuite/tests/th/T5886a.hs
Haskell
bsd-3-clause
337
{-# LANGUAGE OverloadedStrings #-} import Data.Time.LocalTime import Data.Time.Clock import Data.Maybe import Control.Monad import System.Environment import qualified Data.Configurator as CFG import Data.Configurator.Types import Format import System.Console.Terminfo.PrettyPrint import Data.Time.Calendar import Data.Time.Clock import System.Console.GetOpt import Text.Read getHomoList :: Config -> Name -> IO (Maybe [String]) getHomoList cfg str = do r <- CFG.lookup cfg str case r of (Just (List v)) -> return $ helper v _ -> return $ Nothing where helper values = let vs = map convert values :: [Maybe String] homo = foldr (\x y -> y && isJust x) True vs in if homo then Just $ map fromJust vs else Nothing addDaysTime :: Integer -> UTCTime -> UTCTime addDaysTime i (UTCTime day t) = let dday = addDays i day in UTCTime dday t -- can't we do this better, also missing colors str2color :: String -> TermDoc -> TermDoc str2color str | str == "white" = white | str == "red" = red | str == "magenta" = magenta getColors :: Config -> Name -> IO (Coloring, Coloring, Coloring, Coloring) getColors cfg name = do s <- CFG.lookup cfg name case s of Nothing -> return (white, red, magenta, white) (Just (a,b,c,d)) -> return (str2color a, str2color b, str2color c, str2color d) getConfig :: [Worth FilePath] -> IO XmlTvPP getConfig paths = do cfg <- CFG.load paths url <- liftM (fromMaybe "") $ CFG.lookup cfg "url" chans <- liftM (fromMaybe []) $ getHomoList cfg "channels" minWidth <- liftM (fromMaybe 20) $ CFG.lookup cfg "min-width" colors <- getColors cfg "colors" yester <- liftM (fromMaybe False) $ CFG.lookup cfg "show-trailing" sort <- liftM (fromMaybe True) $ CFG.lookup cfg "sort-channels" showAired <- liftM (fromMaybe True) $ CFG.lookup cfg "show-aired" width <- getCols tz <- getCurrentTimeZone current <- getCurrentTime return $ XmlTvPP url chans tz current width minWidth colors yester sort showAired True readpos :: String -> Int readpos str = let i = read str in if i >= 0 then i else error "negative number" parseChannels :: String -> [String] parseChannels str = case readMaybe str of (Just c) -> c Nothing -> [str] options :: [OptDescr (XmlTvPP -> XmlTvPP)] options = [ Option ['t'] ["time"] (ReqArg (\d cfg -> cfg { currentTime = addDaysTime (read d) (currentTime cfg) , today = (read d) == 0}) "relative day") "relative day, -1,2,+1" , Option ['c'] ["channel"] (ReqArg (\c cfg -> cfg { channels = parseChannels c}) "channels") "channels you want to display" , Option ['w'] ["width"] (ReqArg (\w cfg -> cfg { minWidth = readpos w }) "width") "Min width of channel" , Option ['u'] ["url"] (ReqArg (\u cfg -> cfg { url = u }) "xmltv url") "url to the xmltv" ] parseArgs :: XmlTvPP -> [String] -> IO (XmlTvPP, [String]) parseArgs cfg args = case getOpt Permute options args of (o,n,[]) -> return (foldl (flip id) cfg o, n) (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) where header = "Usage: tv [OPTION...]" main :: IO () main = do args <- getArgs cfg <- getConfig ["$(HOME)/.config/tv/tv.cfg"] (parsed, _) <- parseArgs cfg args showTvDay parsed
dagle/hs-xmltv
src/Tv.hs
Haskell
mit
3,493
module Data.Vector.Generic.Lifted ( unsafeFreeze , read , write , new , freeze , replicate , mapM , thaw , forM ) where import Prelude hiding (mapM, read, replicate) import Control.Monad.Trans (MonadTrans, lift) import Data.Vector.Generic (Mutable, Vector) import qualified Data.Vector.Generic as V import Data.Vector.Generic.Mutable (MVector) import qualified Data.Vector.Generic.Mutable as MV import Control.Monad.Primitive (PrimMonad, PrimState) unsafeFreeze :: (Vector v a, PrimMonad m, MonadTrans t) => Mutable v (PrimState m) a -> t m (v a) unsafeFreeze = lift . V.unsafeFreeze {-# INLINE unsafeFreeze #-} read :: (MVector v a, PrimMonad m, MonadTrans t) => v (PrimState m) a -> Int -> t m a read v i = lift (MV.read v i) {-# INLINE read #-} write :: (MVector v a, PrimMonad m, MonadTrans t) => v (PrimState m) a -> Int -> a -> t m () write v i a = lift (MV.write v i a) {-# INLINE write #-} new :: (MVector v a, PrimMonad m, MonadTrans t) => Int -> t m (v (PrimState m) a) new = lift . MV.new {-# INLINE new #-} freeze :: (Vector v a, PrimMonad m, MonadTrans t) => Mutable v (PrimState m) a -> t m (v a) freeze = lift . V.freeze {-# INLINE freeze #-} replicate :: (MVector v a, PrimMonad m, MonadTrans t) => Int -> a -> t m (v (PrimState m) a) replicate i a = lift (MV.replicate i a) mapM :: (Vector v a, Vector v b, Monad m, MonadTrans t) => (a -> m b) -> v a -> t m (v b) mapM f v = lift $ V.mapM f v {-# INLINE mapM #-} thaw :: (Vector v a, PrimMonad m, MonadTrans t) => v a -> t m (Mutable v (PrimState m) a) thaw = lift . V.thaw {-# INLINE thaw #-} forM :: (Vector v a, Vector v b, Monad m, MonadTrans t) => v a -> (a -> m b) -> t m (v b) forM = flip mapM {-# INLINE forM #-}
NicolasT/reedsolomon
src/Data/Vector/Generic/Lifted.hs
Haskell
mit
1,742
-- | -- Module: Math.NumberTheory.ArithmeticFunctions.NFreedom -- Copyright: (c) 2018 Alexandre Rodrigues Baldé -- Licence: MIT -- Maintainer: Alexandre Rodrigues Baldé <alexandrer_b@outlook.com> -- -- N-free number generation. -- {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} module Math.NumberTheory.ArithmeticFunctions.NFreedom ( nFrees , nFreesBlock , sieveBlockNFree ) where import Control.Monad (forM_) import Control.Monad.ST (runST) import Data.Bits (Bits) import Data.List (scanl') import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as MU import Math.NumberTheory.Roots import Math.NumberTheory.Primes import Math.NumberTheory.Utils.FromIntegral -- | Evaluate the `Math.NumberTheory.ArithmeticFunctions.isNFree` function over a block. -- Value at @0@, if zero falls into block, is undefined. -- -- This function should __**not**__ be used with a negative lower bound. -- If it is, the result is undefined. -- Furthermore, do not: -- -- * use a block length greater than @maxBound :: Int@. -- * use a power that is either of @0, 1@. -- -- None of these preconditions are checked, and if any occurs, the result is -- undefined, __if__ the function terminates. -- -- >>> sieveBlockNFree 2 1 10 -- [True,True,True,False,True,True,True,False,False,True] sieveBlockNFree :: forall a. (Integral a, Enum (Prime a), Bits a, UniqueFactorisation a) => Word -- ^ Power whose @n@-freedom will be checked. -> a -- ^ Lower index of the block. -> Word -- ^ Length of the block. -> U.Vector Bool -- ^ Vector of flags, where @True@ at index @i@ means the @i@-th element of -- the block is @n@-free. sieveBlockNFree _ _ 0 = U.empty sieveBlockNFree n lowIndex len' = runST $ do as <- MU.replicate (wordToInt len') True forM_ ps $ \p -> do let pPow :: a pPow = p ^ n offset :: a offset = negate lowIndex `mod` pPow -- The second argument in @Data.Vector.Unboxed.Mutable.write@ is an -- @Int@, so to avoid segmentation faults or out-of-bounds errors, -- the enumeration's higher bound must always be less than -- @maxBound :: Int@. -- As mentioned above, this is not checked when using this function -- by itself, but is carefully managed when this function is called -- by @nFrees@, see the comments in it. indices :: [a] indices = [offset, offset + pPow .. len - 1] forM_ indices $ \ix -> MU.write as (fromIntegral ix) False U.freeze as where len :: a len = fromIntegral len' highIndex :: a highIndex = lowIndex + len - 1 ps :: [a] ps = if highIndex < 4 then [] else map unPrime [nextPrime 2 .. precPrime (integerSquareRoot highIndex)] -- | For a given nonnegative integer power @n@, generate all @n@-free -- numbers in ascending order, starting at @1@. -- -- When @n@ is @0@ or @1@, the resulting list is @[1]@. nFrees :: forall a. (Integral a, Bits a, UniqueFactorisation a, Enum (Prime a)) => Word -- ^ Power @n@ to be used to generate @n@-free numbers. -> [a] -- ^ Generated infinite list of @n@-free numbers. nFrees 0 = [1] nFrees 1 = [1] nFrees n = concatMap (uncurry (nFreesBlock n)) $ zip bounds strides where -- The 56th element of @iterate (2 *) 256@ is @2^64 :: Word == 0@, so to -- avoid overflow only the first 55 elements of this list are used. -- After those, since @maxBound :: Int@ is the largest a vector can be, -- this value is just repeated. This means after a few dozen iterations, -- the sieve will stop increasing in size. strides :: [Word] strides = take 55 (iterate (2 *) 256) ++ repeat (intToWord (maxBound :: Int)) -- Infinite list of lower bounds at which @sieveBlockNFree@ will be -- applied. This has type @Integral a => a@ instead of @Word@ because -- unlike the sizes of the sieve that eventually stop increasing (see -- above comment), the lower bound at which @sieveBlockNFree@ is called does not. bounds :: [a] bounds = scanl' (+) 1 $ map fromIntegral strides -- | Generate @n@-free numbers in a block starting at a certain value. -- The length of the list is determined by the value passed in as the third -- argument. It will be lesser than or equal to this value. -- -- This function should not be used with a negative lower bound. If it is, -- the result is undefined. -- -- The block length cannot exceed @maxBound :: Int@, this precondition is not -- checked. -- -- As with @nFrees@, passing @n = 0, 1@ results in an empty list. nFreesBlock :: forall a . (Integral a, Bits a, UniqueFactorisation a, Enum (Prime a)) => Word -- ^ Power @n@ to be used to generate @n@-free numbers. -> a -- ^ Starting number in the block. -> Word -- ^ Maximum length of the block to be generated. -> [a] -- ^ Generated list of @n@-free numbers. nFreesBlock 0 lo _ = help lo nFreesBlock 1 lo _ = help lo nFreesBlock n lowIndex len = let -- When indexing the array of flags @bs@, the index has to be an -- @Int@. As such, it's necessary to cast @strd@ twice. -- * Once, immediately below, to create the range of values whose -- @n@-freedom will be tested. Since @nFrees@ has return type -- @[a]@, this cannot be avoided as @strides@ has type @[Word]@. len' :: Int len' = wordToInt len -- * Twice, immediately below, to create the range of indices with -- which to query @bs@. len'' :: a len'' = fromIntegral len bs = sieveBlockNFree n lowIndex len in map snd . filter ((bs U.!) . fst) . zip [0 .. len' - 1] $ [lowIndex .. lowIndex + len''] {-# INLINE nFreesBlock #-} help :: Integral a => a -> [a] help 1 = [1] help _ = [] {-# INLINE help #-}
Bodigrim/arithmoi
Math/NumberTheory/ArithmeticFunctions/NFreedom.hs
Haskell
mit
5,954
{-# LANGUAGE OverloadedStrings #-} module Database.Selda.SQL.Print.Config (PPConfig (..), defPPConfig) where import Data.Text (Text) import qualified Data.Text as T import Database.Selda.SqlType import Database.Selda.Table -- | Backend-specific configuration for the SQL pretty-printer. data PPConfig = PPConfig { -- | The SQL type name of the given type. -- -- This function should be used everywhere a type is needed to be printed but in primary -- keys position. This is due to the fact that some backends might have a special -- representation of primary keys (using sequences are such). If you have such a need, -- please use the 'ppTypePK' record instead. ppType :: SqlTypeRep -> Text -- | Hook that allows you to modify 'ppType' output. , ppTypeHook :: SqlTypeRep -> [ColAttr] -> (SqlTypeRep -> Text) -> Text -- | The SQL type name of the given type for primary keys uses. , ppTypePK :: SqlTypeRep -> Text -- | Parameter placeholder for the @n@th parameter. , ppPlaceholder :: Int -> Text -- | List of column attributes. , ppColAttrs :: [ColAttr] -> Text -- | Hook that allows you to modify 'ppColAttrs' output. , ppColAttrsHook :: SqlTypeRep -> [ColAttr] -> ([ColAttr] -> Text) -> Text -- | The value used for the next value for an auto-incrementing column. -- For instance, @DEFAULT@ for PostgreSQL, and @NULL@ for SQLite. , ppAutoIncInsert :: Text -- | Insert queries may have at most this many parameters; if an insertion -- has more parameters than this, it will be chunked. -- -- Note that only insertions of multiple rows are chunked. If your table -- has more than this many columns, you should really rethink -- your database design. , ppMaxInsertParams :: Maybe Int -- | @CREATE INDEX@ suffix to indicate that the index should use the given -- index method. , ppIndexMethodHook :: IndexMethod -> Text } -- | Default settings for pretty-printing. -- Geared towards SQLite. -- -- The default definition of 'ppTypePK' is 'defType, so that you don’t have to do anything -- special if you don’t use special types for primary keys. defPPConfig :: PPConfig defPPConfig = PPConfig { ppType = defType , ppTypeHook = \ty _ _ -> defType ty , ppTypePK = defType , ppPlaceholder = T.cons '$' . T.pack . show , ppColAttrs = T.unwords . map defColAttr , ppColAttrsHook = \_ ats _ -> T.unwords $ map defColAttr ats , ppAutoIncInsert = "NULL" , ppMaxInsertParams = Nothing , ppIndexMethodHook = const "" } -- | Default compilation for SQL types. -- By default, anything we don't know is just a blob. defType :: SqlTypeRep -> Text defType TText = "TEXT" defType TRowID = "INTEGER" defType TInt32 = "INT" defType TInt64 = "BIGINT" defType TFloat = "DOUBLE PRECISION" defType TBool = "BOOLEAN" defType TDateTime = "DATETIME" defType TDate = "DATE" defType TTime = "TIME" defType TBlob = "BLOB" defType TUUID = "BLOB" defType TJSON = "BLOB" -- | Default compilation for a column attribute. defColAttr :: ColAttr -> Text defColAttr Primary = "" defColAttr (AutoPrimary Strong) = "PRIMARY KEY AUTOINCREMENT" defColAttr (AutoPrimary Weak) = "PRIMARY KEY" defColAttr Required = "NOT NULL" defColAttr Optional = "NULL" defColAttr Unique = "UNIQUE" defColAttr (Indexed _) = ""
valderman/selda
selda/src/Database/Selda/SQL/Print/Config.hs
Haskell
mit
3,457
module Main where import Control.Monad import Data.IORef import Data.Tuple.HT import FRP.Yampa import Graphics import Graphics.Rendering.OpenGL import Graphics.UI.GLUT import System.Exit import Types import Simulation -- Entry point. main :: IO () main = do newInput <- newIORef NoEvent oldTime <- newIORef (0 :: Int) rh <- reactInit (initGL >> return NoEvent) (\_ _ b -> b >> return False) simulate -- We allow control over the position of the ball, though the rate of spin is -- determined as a constant. keyboardMouseCallback $= Just (keyMouse newInput) displayCallback $= return () idleCallback $= Just (idle newInput oldTime rh) mainLoop where keyMouse _keyEv (Char '\27') Down _ _ = exitSuccess keyMouse keyEv (Char ' ') Down _ _ = writeIORef keyEv $ Event () keyMouse _keyEv _ _ _ _ = return () -- Update angle of the ball when idle. -- angle the angle should idle :: IORef (Event ()) -> IORef Int -> ReactHandle (Event ()) (IO ()) -> IO () idle newInput oldTime rh = do newInput' <- readIORef newInput if isEvent newInput' then print "Spacebar pressed!" else return () newTime' <- get elapsedTime oldTime' <- readIORef oldTime let dt = let dt' = (fromIntegral $ newTime' - oldTime')/100 in if dt' < 0.8 then dt' else 0.8 -- clamping of time react rh (dt,Just newInput') writeIORef newInput NoEvent writeIORef oldTime newTime' return ()
fatuhoku/haskell-yampa-bouncing-ball
src/Main.hs
Haskell
mit
1,480
import System.Random main = do gen <- getStdGen putStr $ take 20 (randomRs ('a', 'z') gen)
UoBCS/haskell-diary
monads/random/random_string.hs
Haskell
mit
102
module Feature.User.PG where import ClassyPrelude import Feature.User.Types import Feature.Auth.Types import Platform.PG import Database.PostgreSQL.Simple -- * UserRepo findUserByAuth :: PG r m => Auth -> m (Maybe (UserId, User)) findUserByAuth (Auth email pass) = do results <- withConn $ \conn -> query conn qry (email, pass) case results of [(uId, name, bio, image)] -> return $ Just (uId, User email "tempToken" name bio image) _ -> return Nothing where qry = "select id, cast (name as text), bio, image \ \from users where email = ? AND pass = crypt(?, pass) \ \limit 1" findUserById :: PG r m => UserId -> m (Maybe User) findUserById uId = do results <- withConn $ \conn -> query conn qry (Only uId) case results of [(name, email, bio, image)] -> return $ Just $ User email "tempToken" name bio image _ -> return Nothing where qry = "select cast (name as text), cast (email as text), bio, image \ \from users where id = ? limit 1" addUser :: (PG r m) => Register -> Text -> m (Either UserError ()) addUser (Register name email pass) defaultImgUrl = do result <- withConn $ try . action return $ bimap (translateSqlUserError email name) (const ()) result where action conn = execute conn qry (name, email, pass, defaultImgUrl) qry = "insert into users (name, email, pass, bio, image) \ \values (?, ?, crypt(?, gen_salt('bf')), '', ?)" updateUserById :: (PG r m) => UserId -> UpdateUser -> m (Either UserError ()) updateUserById uId (UpdateUser email uname pass img bio) = do result <- withConn $ try . action return $ bimap (translateSqlUserError (fromMaybe "" email) (fromMaybe "" uname)) (const ()) result where action conn = execute conn qry (email, uname, pass, img, bio, uId) qry = "update users set \ \email = coalesce(?, email), \ \name = coalesce(?, name), \ \pass = coalesce(crypt(?, gen_salt('bf')), pass), \ \image = coalesce(?, image), \ \bio = coalesce(?, bio) \ \where id = ?" translateSqlUserError :: Email -> Username -> SqlError -> UserError translateSqlUserError email username sqlError | isUniqueConstraintsViolation sqlError "users_email_key" = UserErrorEmailTaken email | isUniqueConstraintsViolation sqlError "users_name_key" = UserErrorNameTaken username | otherwise = error $ "Unknown SQL error: " <> show sqlError isUniqueConstraintsViolation :: SqlError -> ByteString -> Bool isUniqueConstraintsViolation SqlError{sqlState = state, sqlErrorMsg = msg} constraintName = state == "23505" && constraintName `isInfixOf` msg -- * ProfileRepo findProfile :: PG r m => Maybe UserId -> Username -> m (Maybe Profile) findProfile mayUserId username = do results <- withConn $ \conn -> query conn qry (mayUserId, username) return $ case results of [a] -> Just a _ -> Nothing where qry = "select cast (name as text), bio, image, exists(select 1 from followings where user_id = id and followed_by = ?) as following \ \from users where name = ? limit 1" followUserByUsername :: (PG r m) => UserId -> Username -> m (Either UserError ()) followUserByUsername uId username = do result <- withConn $ \conn -> try $ execute conn qry (uId, username) return $ case result of Left SqlError{sqlState="23503"} -> Left $ UserErrorNotFound username Left err -> error $ "Unhandled PG error: " <> show err Right _ -> Right () where qry = "insert into followings (followed_by, user_id) \ \(select ?, id from users where name = ? limit 1) on conflict do nothing" unfollowUserByUsername :: PG r m => UserId -> Username -> m () unfollowUserByUsername uId username = void . withConn $ \conn -> execute conn qry (uId, username) where qry = "delete from followings where \ \followed_by = ? and user_id in (select id from users where name = ? limit 1)"
eckyputrady/haskell-scotty-realworld-example-app
src/Feature/User/PG.hs
Haskell
mit
3,969
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import qualified Control.Foldl as Fold import Data.List (genericLength) import Data.Maybe (catMaybes) import Data.Text (unpack) import System.Exit (exitFailure, exitSuccess) import Text.Regex (matchRegex, mkRegex) import Turtle (inprocWithErr, fold) average :: (Fractional a, Real b) => [b] -> a average xs = realToFrac (sum xs) / genericLength xs expected :: Fractional a => a expected = 90 main :: IO () main = do text <- fold (fmap (\(Left o) -> o) (inprocWithErr "stack" ["haddock"] "")) Fold.list let output = map unpack text avg = average $ match output putStrLn $ "\nAverage documentation coverage: " ++ show avg if avg >= expected then exitSuccess else exitFailure match :: [String] -> [Int] match = fmap read . concat . catMaybes . fmap (matchRegex p) where p = mkRegex "^ *([0-9]*)% "
tylerjl/adventofcode
test/Haddock.hs
Haskell
mit
1,020
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} {-# LANGUAGE UnicodeSyntax #-} -- From: Herbert P. Sander. A logic of functional programs with an -- application to concurrency. PhD thesis, Chalmers University of -- Technology and University of Gothenburg, Department of Computer -- Sciences, 1992. pp. 12-13. module Berry where import Data.Peano ( PeanoNat(S,Z) ) loop ∷ a loop = loop -- Warning: Pattern match(es) are non-exhaustive -- In an equation for `f': -- Patterns not matched: -- Z (S (S _)) _ -- Z Z Z -- Z Z (S (S _)) -- (S (S _)) (S _) _ -- ... f ∷ PeanoNat → PeanoNat → PeanoNat → PeanoNat f Z (S Z) _ = S Z f (S Z) _ Z = S (S Z) f _ Z (S Z) = S (S (S Z)) -- Tests: -- f Z (S Z) loop = 1 -- f (S Z) loop Z = 2 -- f loop Z (S Z) = *** Non-terminating ***
asr/fotc
notes/Berry/Berry.hs
Haskell
mit
905
{-# LANGUAGE BangPatterns , FlexibleContexts , TypeFamilies , MultiParamTypeClasses , FunctionalDependencies , TypeSynonymInstances , FlexibleInstances #-} module RobotVision.ImageRep.Utility ( fromChannels , toChannels , getNotBoundaryPoints , getImagePoints , onBoundary ) where import Data.Array.Repa import qualified Data.Array.Repa.Repr.Unboxed as U import Data.Array.Repa.Repr.ForeignPtr as F import Data.Word import Prelude as P import Data.Convertible test = id toChannels :: (Source r e) => Array r DIM3 e -> (Array D DIM2 e, Array D DIM2 e, Array D DIM2 e) toChannels img = (r,g,b) where r = fromFunction (Z :. height :. width) rf g = fromFunction (Z :. height :. width) gf b = fromFunction (Z :. height :. width) bf (Z :. height :. width :. _) = extent img rf (Z :. y :. x) = img ! (Z :. y :. x :. 0) gf (Z :. y :. x) = img ! (Z :. y :. x :. 1) bf (Z :. y :. x) = img ! (Z :. y :. x :. 2) {-# INLINE toChannels #-} fromChannels :: (Source r e) => (Array r DIM2 e, Array r DIM2 e, Array r DIM2 e) -> Array D DIM3 e fromChannels (r,g,b) = let (Z :. width :. height) = extent r in fromFunction (Z :. width :. height :. 3) f where f (Z :. y :. x :. z) = case z of 0 -> r ! (Z :. y :. x) 1 -> g ! (Z :. y :. x) 2 -> b ! (Z :. y :. x) {-# INLINE fromChannels #-} getImagePoints :: (Source r e) => Array r DIM2 e -> [DIM2] getImagePoints img = let (Z :. y :. x) = extent img in P.map tupleToPoint $ permuteList [0 .. (y-1)] [0 .. (x-1)] tupleList :: [a] -> b -> [(a,b)] tupleList [] _ = [] tupleList (x:xs) y = (x,y) : (tupleList xs y) permuteList :: [a] -> [b] -> [(a,b)] permuteList _ [] = [] permuteList xs (y:ys) = tupleList xs y P.++ permuteList xs ys tupleToPoint :: (Int, Int) -> DIM2 tupleToPoint (x,y) = Z :. x :. y getNotBoundaryPoints :: (Source r e) => Array r DIM2 e -> [DIM2] getNotBoundaryPoints img = notBoundaryPoints img $ getImagePoints img notBoundaryPoints :: (Source r e) => Array r DIM2 e -> [DIM2] -> [DIM2] notBoundaryPoints img pts = let (Z :. w :. h) = extent img in filter (not . (onBoundary w h)) pts onTop :: Int -> DIM2 -> Bool onTop height (Z :. y :. _) = y == (height - 1) onBot :: DIM2 -> Bool onBot (Z :. y :. _) = y == 0 onLeft :: DIM2 -> Bool onLeft (Z :. _ :. x) = x == 0 onRight :: Int -> DIM2 -> Bool onRight width (Z :. _ :. x) = x == (width - 1) onBoundary :: Int -> Int -> DIM2 -> Bool onBoundary height width pt = (onTop height pt) || (onBot pt) || (onLeft pt) || (onRight width pt)
eklinkhammer/haskell-vision
RobotVision/ImageRep/Utility.hs
Haskell
mit
2,685
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Models where import Data.Aeson import Data.Text import Data.Time (UTCTime) import Database.Persist.Sql import Database.Persist.TH import Elm import GHC.Generics -- DB Models share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Account firstName Text lastName Text email Text UniqueEmail email deriving Show Generic Gig date UTCTime venue Text -- venueId VenueId deriving Show Generic -- Venue json -- name Text -- locationId LocationId -- deriving Show -- Location json -- -- Consider adding for Maps or something. -- -- Maybe needs it's own model like Location -- street Text -- city Text -- state Text -- zip Integer -- deriving Show |] instance ElmType Account instance ToJSON Account instance FromJSON Account instance ElmType Gig instance ToJSON Gig instance FromJSON Gig
erlandsona/caldwell-api
library/Models.hs
Haskell
mit
1,186
module HelperSequences.A112798 (a112798, a112798_row) where import HelperSequences.A027746 (a027746_row) import Data.Maybe (fromJust) import Data.List (elemIndex) import HelperSequences.A000040 (a000040_list) a112798 :: Int -> Int a112798 n = a112798_tabl !! (n - 2) a112798_tabl :: [Int] a112798_tabl = concatMap a112798_row [1..] a112798_row :: Integer -> [Int] a112798_row 1 = [] a112798_row n = map f $ a027746_row n where f p = (1+) $ fromJust $ elemIndex p a000040_list
peterokagey/haskellOEIS
src/HelperSequences/A112798.hs
Haskell
apache-2.0
482
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} -- | Data types for the K3 effect system module Language.K3.Analysis.SEffects.Core where import Control.DeepSeq import GHC.Generics (Generic) import Data.Binary import Data.Serialize import Data.List import Data.Tree import Data.Typeable import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Utils.Pretty import Data.Text ( Text ) import qualified Data.Text as T import qualified Language.K3.Utils.PrettyText as PT import Language.K3.Analysis.Provenance.Core type FPtr = Int data FMatVar = FMatVar {fmvn :: !Identifier, fmvloc :: !UID, fmvptr :: !FPtr} deriving (Eq, Ord, Read, Show, Typeable, Generic) data Effect = FFVar !Identifier | FBVar !FMatVar | FRead !(K3 Provenance) | FWrite !(K3 Provenance) | FIO | FData !(Maybe [Identifier]) -- An effect container, to support structural matching for lambda effects. | FScope ![FMatVar] -- Materialization point for the given FMatVars. This has four children: -- initialization execution effects (i.e., pre-body effects), body execution effects -- post-body execution effects, and result effect structure. | FLambda !Identifier -- Lambda effects have three effect children: closure construction effects, -- deferred execution effects and deferred effect structure. | FApply !(Maybe FMatVar) -- Application effect nodes have either two, three or five children: -- i. 5-child variant: -- lambda effect structure, arg effect structure, -- initializer execution effects, result execution effects, -- and a result effect structure. -- ii. 2-child variant: -- lambda effect structure, and arg effect structure. -- iii. 1-child variant: result effect structure -- -- Note after simplification, we introduce a 3-child variant as a -- simplified form of the 5-child version: -- iv. initializer execution effects, result execution effects, -- and a result effect structure. | FSet -- Set of effects, all of which are possible. | FSeq | FLoop -- A repetitive effect. Can only happen in a foreign function | FNone -- Null effect deriving (Eq, Ord, Read, Show, Typeable, Generic) data instance Annotation Effect = FDeclared !(K3 Effect) deriving (Eq, Ord, Read, Show, Generic) {- SEffect instances -} instance NFData FMatVar instance NFData Effect instance NFData (Annotation Effect) instance Binary FMatVar instance Binary Effect instance Binary (Annotation Effect) instance Serialize FMatVar instance Serialize Effect instance Serialize (Annotation Effect) {- Annotation extractors -} isFDeclared :: Annotation Effect -> Bool isFDeclared (FDeclared _) = True instance Pretty (K3 Effect) where prettyLines (Node (FRead p :@: as) _) = let (aStr, chAStr) = drawFAnnotations as in ["FRead " ++ aStr] %+ prettyLines p ++ shift "`- " " " chAStr prettyLines (Node (FWrite p :@: as) _) = let (aStr, chAStr) = drawFAnnotations as in ["FWrite " ++ aStr] %+ prettyLines p ++ shift "`- " " " chAStr prettyLines (Node (tg :@: as) ch) = let (aStr, chAStr) = drawFAnnotations as in [show tg ++ aStr] ++ (let (p,l) = if null ch then ("`- ", " ") else ("+- ", "| ") in shift p l chAStr) ++ drawSubTrees ch drawFAnnotations :: [Annotation Effect] -> (String, [String]) drawFAnnotations as = let (fdeclAnns, anns) = partition isFDeclared as prettyEffAnns = concatMap drawFDeclAnnotation fdeclAnns in (drawAnnotations anns, prettyEffAnns) where drawFDeclAnnotation (FDeclared f) = ["FDeclared "] %+ prettyLines f instance PT.Pretty (K3 Effect) where prettyLines (Node (FRead p :@: as) _) = let (aTxt, chATxt) = drawFAnnotationsT as in [T.append (T.pack "FRead ") aTxt] PT.%+ PT.prettyLines p ++ (PT.shift (T.pack "`- ") (T.pack " ") chATxt) prettyLines (Node (FWrite p :@: as) _) = let (aTxt, chATxt) = drawFAnnotationsT as in [T.append (T.pack "FWrite ") aTxt] PT.%+ PT.prettyLines p ++ (PT.shift (T.pack "`- ") (T.pack " ") chATxt) prettyLines (Node (tg :@: as) ch) = let (aTxt, chATxt) = drawFAnnotationsT as in [T.append (T.pack $ show tg) aTxt] ++ (let (p,l) = if null ch then (T.pack "`- ", T.pack " ") else (T.pack "+- ", T.pack "| ") in PT.shift p l chATxt) ++ PT.drawSubTrees ch drawFAnnotationsT :: [Annotation Effect] -> (Text, [Text]) drawFAnnotationsT as = let (fdeclAnns, anns) = partition isFDeclared as prettyEffAnns = concatMap drawFDeclAnnotation fdeclAnns in (PT.drawAnnotations anns, prettyEffAnns) where drawFDeclAnnotation (FDeclared f) = [T.pack "FDeclared "] PT.%+ PT.prettyLines f
DaMSL/K3
src/Language/K3/Analysis/SEffects/Core.hs
Haskell
apache-2.0
5,420
-- parse nested parens into a tree structure -- Exercise 1 from chapter 8 of Basics of Haskell -- https://www.schoolofhaskell.com/school/starting-with-haskell/basics-of-haskell/8_Parser data Token = TokLParen | TokRParen | TokEnd deriving (Show, Eq) lookAhead :: String -> Token lookAhead [] = TokEnd lookAhead (c:cs)| c == '(' = TokLParen | c == ')' = TokRParen | otherwise = error $ "Bad input: " ++ (c:cs) accept :: String -> String accept [] = error "Nothing to accept" accept (c:cs) = cs data Tree = Node Tree Tree | Leaf deriving Show root, expr, par :: String -> (Tree, String) root = par expr s = let (p, s') = par s (p', s'') = par s' in (Node p p', s'') par s = case lookAhead s of TokLParen -> case lookAhead (accept s) of TokRParen -> (Leaf, accept (accept s)) _ -> let (e, s') = expr (accept s) in if lookAhead s' == TokRParen then (e, accept s') else error $ "Missing closing paren in: " ++ show s' _ -> error $ "Bad expression: " ++ show s parse str = let (tree, str') = root str in if null str' then tree else error $ "Unconsumed string " ++ str' main = print $ parse "(()(()(()())))"
cbare/Etudes
haskell/parse_parens.hs
Haskell
apache-2.0
1,526
import Control.Parallel.Strategies power5 x = x * x * x * x * x digitSumPower5 n = sum $ map power5 $ map (\x -> read [x] :: Int) $ show n isSameAsDigitSumPower5 n = (n == digitSumPower5 n) main = do let base = [2..10000000] let filtered = filter isSameAsDigitSumPower5 base let cs = filtered `using` parList rdeepseq print $ sum $ cs
ulikoehler/ProjectEuler
Euler30.hs
Haskell
apache-2.0
355
{-# LANGUAGE TemplateHaskell #-} module DBusTests.TH where import DBus.Generation import DBusTests.Generation generateClient defaultGenerationParams testIntrospectionInterface generateSignalsFromInterface defaultGenerationParams testIntrospectionInterface
rblaze/haskell-dbus
tests/DBusTests/TH.hs
Haskell
apache-2.0
259
-- | Specific configuration for Joey Hess's sites. Probably not useful to -- others except as an example. {-# LANGUAGE FlexibleContexts, TypeFamilies #-} module Propellor.Property.SiteSpecific.JoeySites where import Propellor.Base import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.File as File import qualified Propellor.Property.ConfFile as ConfFile import qualified Propellor.Property.Gpg as Gpg import qualified Propellor.Property.Ssh as Ssh import qualified Propellor.Property.Git as Git import qualified Propellor.Property.Cron as Cron import qualified Propellor.Property.Service as Service import qualified Propellor.Property.User as User import qualified Propellor.Property.Obnam as Obnam import qualified Propellor.Property.Apache as Apache import qualified Propellor.Property.Postfix as Postfix import qualified Propellor.Property.Systemd as Systemd import qualified Propellor.Property.Fail2Ban as Fail2Ban import qualified Propellor.Property.LetsEncrypt as LetsEncrypt import Utility.FileMode import Data.List import System.Posix.Files import Data.String.Utils scrollBox :: Property (HasInfo + DebianLike) scrollBox = propertyList "scroll server" $ props & User.accountFor (User "scroll") & Git.cloned (User "scroll") "git://git.kitenet.net/scroll" (d </> "scroll") Nothing & Apt.installed ["ghc", "make", "cabal-install", "libghc-vector-dev", "libghc-bytestring-dev", "libghc-mtl-dev", "libghc-ncurses-dev", "libghc-random-dev", "libghc-monad-loops-dev", "libghc-text-dev", "libghc-ifelse-dev", "libghc-case-insensitive-dev", "libghc-data-default-dev", "libghc-optparse-applicative-dev"] & userScriptProperty (User "scroll") [ "cd " ++ d </> "scroll" , "git pull" , "cabal configure" , "make" ] `assume` MadeChange & s `File.hasContent` [ "#!/bin/sh" , "set -e" , "echo Preparing to run scroll!" , "cd " ++ d , "mkdir -p tmp" , "TMPDIR= t=$(tempfile -d tmp)" , "export t" , "rm -f \"$t\"" , "mkdir \"$t\"" , "cd \"$t\"" , "echo" , "echo Note that games on this server are time-limited to 2 hours" , "echo 'Need more time? Run scroll locally instead!'" , "echo" , "echo Press Enter to start the game." , "read me" , "SHELL=/bin/sh script --timing=timing -c " ++ g ] `onChange` (s `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) & g `File.hasContent` [ "#!/bin/sh" , "if ! timeout --kill-after 1m --foreground 2h ../../scroll/scroll; then" , "echo Scroll seems to have ended unexpectedly. Possibly a bug.." , "else" , "echo Thanks for playing scroll! https://joeyh.name/code/scroll/" , "fi" , "echo Your game was recorded, as ID:$(basename \"$t\")" , "echo if you would like to talk about how it went, email scroll@joeyh.name" , "read line" ] `onChange` (g `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) -- prevent port forwarding etc by not letting scroll log in via ssh & Ssh.sshdConfig `File.containsLine` ("DenyUsers scroll") `onChange` Ssh.restarted & User.shellSetTo (User "scroll") s & User.hasPassword (User "scroll") -- telnetd attracted password crackers, so disabled & Apt.removed ["telnetd"] & Apt.installed ["shellinabox"] & File.hasContent "/etc/default/shellinabox" [ "# Deployed by propellor" , "SHELLINABOX_DAEMON_START=1" , "SHELLINABOX_PORT=4242" , "SHELLINABOX_ARGS=\"--disable-ssl --no-beep --service=:scroll:scroll:" ++ d ++ ":" ++ s ++ "\"" ] `onChange` Service.restarted "shellinabox" & Service.running "shellinabox" where d = "/home/scroll" s = d </> "login.sh" g = d </> "game.sh" oldUseNetServer :: [Host] -> Property (HasInfo + DebianLike) oldUseNetServer hosts = propertyList "olduse.net server" $ props & Apt.installed ["leafnode"] & oldUseNetInstalled "oldusenet-server" & oldUseNetBackup & spoolsymlink & "/etc/news/leafnode/config" `File.hasContent` [ "# olduse.net configuration (deployed by propellor)" , "expire = 1000000" -- no expiry via texpire , "server = " -- no upstream server , "debugmode = 1" , "allowSTRANGERS = 42" -- lets anyone connect , "nopost = 1" -- no new posting (just gather them) ] & "/etc/hosts.deny" `File.lacksLine` "leafnode: ALL" & Apt.serviceInstalledRunning "openbsd-inetd" & File.notPresent "/etc/cron.daily/leafnode" & File.notPresent "/etc/cron.d/leafnode" & Cron.niceJob "oldusenet-expire" (Cron.Times "11 1 * * *") (User "news") newsspool expirecommand & Cron.niceJob "oldusenet-uucp" (Cron.Times "*/5 * * * *") (User "news") "/" uucpcommand & Apache.siteEnabled "nntp.olduse.net" nntpcfg where newsspool = "/var/spool/news" datadir = "/var/spool/oldusenet" expirecommand = intercalate ";" [ "find \\( -path ./out.going -or -path ./interesting.groups -or -path './*/.overview' \\) -prune -or -type f -ctime +60 -print | xargs --no-run-if-empty rm" , "find -type d -empty | xargs --no-run-if-empty rmdir" ] uucpcommand = "/usr/bin/uucp " ++ datadir nntpcfg = apachecfg "nntp.olduse.net" [ " DocumentRoot " ++ datadir ++ "/" , " <Directory " ++ datadir ++ "/>" , " Options Indexes FollowSymlinks" , " AllowOverride None" , Apache.allowAll , " </Directory>" ] spoolsymlink :: Property UnixLike spoolsymlink = check (not . isSymbolicLink <$> getSymbolicLinkStatus newsspool) (property "olduse.net spool in place" $ makeChange $ do removeDirectoryRecursive newsspool createSymbolicLink (datadir </> "news") newsspool ) oldUseNetBackup :: Property (HasInfo + DebianLike) oldUseNetBackup = Obnam.backup datadir (Cron.Times "33 4 * * *") [ "--repository=sftp://2318@usw-s002.rsync.net/~/olduse.net" , "--client-name=spool" , "--ssh-key=" ++ keyfile , Obnam.keepParam [Obnam.KeepDays 30] ] Obnam.OnlyClient `requires` Ssh.userKeyAt (Just keyfile) (User "root") (Context "olduse.net") (SshRsa, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD0F6L76SChMCIGmeyGhlFMUTgZ3BoTbATiOSs0A7KXQoI1LTE5ZtDzzUkrQRJVpJ640pfMR7cQZyBm8tv+kYIPp0238GrX43c1vgm0L78agDnBU7r2iNMyWIwhssK8O3ZAhp8Q4KCz1r8hP2nIiD0y1D1VWW8h4KWOS7I1XCEAjOTvFvEjTh6a9MyHrcIkv7teUUzTBRjNrsyijCFRk1+pEET54RueoOmEjQcWd/sK1tYRiMZjegRLBOus2wUWsUOvznJ2iniLONUTGAWRnEV+O7hLN6CD44osJ+wkZk8bPAumTS0zcSLckX1jpdHJicmAyeniWSd4FCqm1YE6/xDD") `requires` Ssh.knownHost hosts "usw-s002.rsync.net" (User "root") keyfile = "/root/.ssh/olduse.net.key" oldUseNetShellBox :: Property DebianLike oldUseNetShellBox = propertyList "olduse.net shellbox" $ props & oldUseNetInstalled "oldusenet" & Service.running "shellinabox" oldUseNetInstalled :: Apt.Package -> Property DebianLike oldUseNetInstalled pkg = check (not <$> Apt.isInstalled pkg) $ propertyList ("olduse.net " ++ pkg) $ props & Apt.installed (words "build-essential devscripts debhelper git libncursesw5-dev libpcre3-dev pkg-config bison libicu-dev libidn11-dev libcanlock2-dev libuu-dev ghc libghc-strptime-dev libghc-hamlet-dev libghc-ifelse-dev libghc-hxt-dev libghc-utf8-string-dev libghc-missingh-dev libghc-sha-dev") `describe` "olduse.net build deps" & scriptProperty [ "rm -rf /root/tmp/oldusenet" -- idenpotency , "git clone git://olduse.net/ /root/tmp/oldusenet/source" , "cd /root/tmp/oldusenet/source/" , "dpkg-buildpackage -us -uc" , "dpkg -i ../" ++ pkg ++ "_*.deb || true" , "apt-get -fy install" -- dependencies , "rm -rf /root/tmp/oldusenet" ] `assume` MadeChange `describe` "olduse.net built" kgbServer :: Property (HasInfo + Debian) kgbServer = propertyList desc $ props & installed & File.hasPrivContent "/etc/kgb-bot/kgb.conf" anyContext `onChange` Service.restarted "kgb-bot" where desc = "kgb.kitenet.net setup" installed :: Property Debian installed = withOS desc $ \w o -> case o of (Just (System (Debian _ Unstable) _)) -> ensureProperty w $ propertyList desc $ props & Apt.serviceInstalledRunning "kgb-bot" & "/etc/default/kgb-bot" `File.containsLine` "BOT_ENABLED=1" `describe` "kgb bot enabled" `onChange` Service.running "kgb-bot" _ -> error "kgb server needs Debian unstable (for kgb-bot 1.31+)" mumbleServer :: [Host] -> Property (HasInfo + DebianLike) mumbleServer hosts = combineProperties hn $ props & Apt.serviceInstalledRunning "mumble-server" & Obnam.backup "/var/lib/mumble-server" (Cron.Times "55 5 * * *") [ "--repository=sftp://2318@usw-s002.rsync.net/~/" ++ hn ++ ".obnam" , "--ssh-key=" ++ sshkey , "--client-name=mumble" , Obnam.keepParam [Obnam.KeepDays 30] ] Obnam.OnlyClient `requires` Ssh.userKeyAt (Just sshkey) (User "root") (Context hn) (SshRsa, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDSXXSM3mM8SNu+qel9R/LkDIkjpV3bfpUtRtYv2PTNqicHP+DdoThrr0ColFCtLH+k2vQJvR2n8uMzHn53Dq2IO3TtD27+7rJSsJwAZ8oftNzuTir8IjAwX5g6JYJs+L0Ny4RB0ausd+An0k/CPMRl79zKxpZd2MBMDNXt8hyqu0vS0v1ohq5VBEVhBBvRvmNQvWOCj7PdrKQXpUBHruZOeVVEdUUXZkVc1H0t7LVfJnE+nGKyWbw2jM+7r3Rn5Semc4R1DxsfaF8lKkZyE88/5uZQ/ddomv8ptz6YZ5b+Bg6wfooWPC3RWAALjxnHaC2yN1VONAvHmT0uNn1o6v0b") `requires` Ssh.knownHost hosts "usw-s002.rsync.net" (User "root") & cmdProperty "chown" ["-R", "mumble-server:mumble-server", "/var/lib/mumble-server"] `assume` NoChange where hn = "mumble.debian.net" sshkey = "/root/.ssh/mumble.debian.net.key" -- git.kitenet.net and git.joeyh.name gitServer :: [Host] -> Property (HasInfo + DebianLike) gitServer hosts = propertyList "git.kitenet.net setup" $ props & Obnam.backupEncrypted "/srv/git" (Cron.Times "33 3 * * *") [ "--repository=sftp://2318@usw-s002.rsync.net/~/git.kitenet.net" , "--ssh-key=" ++ sshkey , "--client-name=wren" -- historical , Obnam.keepParam [Obnam.KeepDays 30] ] Obnam.OnlyClient (Gpg.GpgKeyId "1B169BE1") `requires` Ssh.userKeyAt (Just sshkey) (User "root") (Context "git.kitenet.net") (SshRsa, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD0F6L76SChMCIGmeyGhlFMUTgZ3BoTbATiOSs0A7KXQoI1LTE5ZtDzzUkrQRJVpJ640pfMR7cQZyBm8tv+kYIPp0238GrX43c1vgm0L78agDnBU7r2iNMyWIwhssK8O3ZAhp8Q4KCz1r8hP2nIiD0y1D1VWW8h4KWOS7I1XCEAjOTvFvEjTh6a9MyHrcIkv7teUUzTBRjNrsyijCFRk1+pEET54RueoOmEjQcWd/sK1tYRiMZjegRLBOus2wUWsUOvznJ2iniLONUTGAWRnEV+O7hLN6CD44osJ+wkZk8bPAumTS0zcSLckX1jpdHJicmAyeniWSd4FCqm1YE6/xDD") `requires` Ssh.knownHost hosts "usw-s002.rsync.net" (User "root") `requires` Ssh.authorizedKeys (User "family") (Context "git.kitenet.net") `requires` User.accountFor (User "family") & Apt.installed ["git", "rsync", "cgit"] & Apt.installed ["git-annex"] & Apt.installed ["kgb-client"] & File.hasPrivContentExposed "/etc/kgb-bot/kgb-client.conf" anyContext `requires` File.dirExists "/etc/kgb-bot/" & Git.daemonRunning "/srv/git" & "/etc/cgitrc" `File.hasContent` [ "clone-url=https://git.joeyh.name/git/$CGIT_REPO_URL git://git.joeyh.name/$CGIT_REPO_URL" , "css=/cgit-css/cgit.css" , "logo=/cgit-css/cgit.png" , "enable-http-clone=1" , "root-title=Joey's git repositories" , "root-desc=" , "enable-index-owner=0" , "snapshots=tar.gz" , "enable-git-config=1" , "scan-path=/srv/git" ] `describe` "cgit configured" -- I keep the website used for git.kitenet.net/git.joeyh.name checked into git.. & Git.cloned (User "root") "/srv/git/joey/git.kitenet.net.git" "/srv/web/git.kitenet.net" Nothing -- Don't need global apache configuration for cgit. ! Apache.confEnabled "cgit" & website "git.kitenet.net" & website "git.joeyh.name" & Apache.modEnabled "cgi" where sshkey = "/root/.ssh/git.kitenet.net.key" website hn = Apache.httpsVirtualHost' hn "/srv/web/git.kitenet.net/" letos [ Apache.iconDir , " <Directory /srv/web/git.kitenet.net/>" , " Options Indexes ExecCGI FollowSymlinks" , " AllowOverride None" , " AddHandler cgi-script .cgi" , " DirectoryIndex index.cgi" , Apache.allowAll , " </Directory>" , "" , " ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/" , " <Directory /usr/lib/cgi-bin>" , " SetHandler cgi-script" , " Options ExecCGI" , " </Directory>" ] type AnnexUUID = String -- | A website, with files coming from a git-annex repository. annexWebSite :: Git.RepoUrl -> HostName -> AnnexUUID -> [(String, Git.RepoUrl)] -> Property (HasInfo + DebianLike) annexWebSite origin hn uuid remotes = propertyList (hn ++" website using git-annex") $ props & Git.cloned (User "joey") origin dir Nothing `onChange` setup & alias hn & postupdatehook `File.hasContent` [ "#!/bin/sh" , "exec git update-server-info" ] `onChange` (postupdatehook `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) & setupapache where dir = "/srv/web/" ++ hn postupdatehook = dir </> ".git/hooks/post-update" setup = userScriptProperty (User "joey") setupscript `assume` MadeChange setupscript = [ "cd " ++ shellEscape dir , "git annex reinit " ++ shellEscape uuid ] ++ map addremote remotes ++ [ "git annex get" , "git update-server-info" ] addremote (name, url) = "git remote add " ++ shellEscape name ++ " " ++ shellEscape url setupapache = Apache.httpsVirtualHost' hn dir letos [ " ServerAlias www."++hn , Apache.iconDir , " <Directory "++dir++">" , " Options Indexes FollowSymLinks ExecCGI" , " AllowOverride None" , " AddHandler cgi-script .cgi" , " DirectoryIndex index.html index.cgi" , Apache.allowAll , " </Directory>" ] letos :: LetsEncrypt.AgreeTOS letos = LetsEncrypt.AgreeTOS (Just "id@joeyh.name") apacheSite :: HostName -> Apache.ConfigFile -> RevertableProperty DebianLike DebianLike apacheSite hn middle = Apache.siteEnabled hn $ apachecfg hn middle apachecfg :: HostName -> Apache.ConfigFile -> Apache.ConfigFile apachecfg hn middle = [ "<VirtualHost *:" ++ val port ++ ">" , " ServerAdmin grue@joeyh.name" , " ServerName "++hn++":" ++ val port ] ++ middle ++ [ "" , " ErrorLog /var/log/apache2/error.log" , " LogLevel warn" , " CustomLog /var/log/apache2/access.log combined" , " ServerSignature On" , " " , Apache.iconDir , "</VirtualHost>" ] where port = Port 80 gitAnnexDistributor :: Property (HasInfo + DebianLike) gitAnnexDistributor = combineProperties "git-annex distributor, including rsync server and signer" $ props & Apt.installed ["rsync"] & File.hasPrivContent "/etc/rsyncd.conf" (Context "git-annex distributor") `onChange` Service.restarted "rsync" & File.hasPrivContent "/etc/rsyncd.secrets" (Context "git-annex distributor") `onChange` Service.restarted "rsync" & "/etc/default/rsync" `File.containsLine` "RSYNC_ENABLE=true" `onChange` Service.running "rsync" & Systemd.enabled "rsync" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild/x86_64-apple-yosemite" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild/windows" -- git-annex distribution signing key & Gpg.keyImported (Gpg.GpgKeyId "89C809CB") (User "joey") where endpoint d = combineProperties ("endpoint " ++ d) $ props & File.dirExists d & File.ownerGroup d (User "joey") (Group "joey") downloads :: [Host] -> Property (HasInfo + DebianLike) downloads hosts = annexWebSite "/srv/git/downloads.git" "downloads.kitenet.net" "840760dc-08f0-11e2-8c61-576b7e66acfd" [("eubackup", "ssh://eubackup.kitenet.net/~/lib/downloads/")] `requires` Ssh.knownHost hosts "eubackup.kitenet.net" (User "joey") tmp :: Property (HasInfo + DebianLike) tmp = propertyList "tmp.joeyh.name" $ props & annexWebSite "/srv/git/joey/tmp.git" "tmp.joeyh.name" "26fd6e38-1226-11e2-a75f-ff007033bdba" [] & pumpRss -- Work around for expired ssl cert. -- (Obsolete; need to revert this.) pumpRss :: Property DebianLike pumpRss = Cron.job "pump rss" (Cron.Times "15 * * * *") (User "joey") "/srv/web/tmp.joeyh.name/" "wget https://pump2rss.com/feed/joeyh@identi.ca.atom -O pump.atom.new --no-check-certificate 2>/dev/null; sed 's/ & / /g' pump.atom.new > pump.atom" ircBouncer :: Property (HasInfo + DebianLike) ircBouncer = propertyList "IRC bouncer" $ props & Apt.installed ["znc"] & User.accountFor (User "znc") & File.dirExists (takeDirectory conf) & File.hasPrivContent conf anyContext & File.ownerGroup conf (User "znc") (Group "znc") & Cron.job "znconboot" (Cron.Times "@reboot") (User "znc") "~" "znc" -- ensure running if it was not already & userScriptProperty (User "znc") ["znc || true"] `assume` NoChange `describe` "znc running" where conf = "/home/znc/.znc/configs/znc.conf" kiteShellBox :: Property DebianLike kiteShellBox = propertyList "kitenet.net shellinabox" $ props & Apt.installed ["openssl", "shellinabox", "openssh-client"] & File.hasContent "/etc/default/shellinabox" [ "# Deployed by propellor" , "SHELLINABOX_DAEMON_START=1" , "SHELLINABOX_PORT=443" , "SHELLINABOX_ARGS=\"--no-beep --service=/:SSH:kitenet.net\"" ] `onChange` Service.restarted "shellinabox" & Service.running "shellinabox" githubBackup :: Property (HasInfo + DebianLike) githubBackup = propertyList "github-backup box" $ props & Apt.installed ["github-backup", "moreutils"] & githubKeys & Cron.niceJob "github-backup run" (Cron.Times "30 4 * * *") (User "joey") "/home/joey/lib/backup" backupcmd where backupcmd = intercalate "&&" $ [ "mkdir -p github" , "cd github" , ". $HOME/.github-keys" , "github-backup joeyh" ] githubKeys :: Property (HasInfo + UnixLike) githubKeys = let f = "/home/joey/.github-keys" in File.hasPrivContent f anyContext `onChange` File.ownerGroup f (User "joey") (Group "joey") rsyncNetBackup :: [Host] -> Property DebianLike rsyncNetBackup hosts = Cron.niceJob "rsync.net copied in daily" (Cron.Times "30 5 * * *") (User "joey") "/home/joey/lib/backup" "mkdir -p rsync.net && rsync --delete -az 2318@usw-s002.rsync.net: rsync.net" `requires` Ssh.knownHost hosts "usw-s002.rsync.net" (User "joey") backupsBackedupFrom :: [Host] -> HostName -> FilePath -> Property DebianLike backupsBackedupFrom hosts srchost destdir = Cron.niceJob desc (Cron.Times "@reboot") (User "joey") "/" cmd `requires` Ssh.knownHost hosts srchost (User "joey") where desc = "backups copied from " ++ srchost ++ " on boot" cmd = "sleep 30m && rsync -az --bwlimit=300K --partial --delete " ++ srchost ++ ":lib/backup/ " ++ destdir </> srchost obnamRepos :: [String] -> Property UnixLike obnamRepos rs = propertyList ("obnam repos for " ++ unwords rs) $ toProps (mkbase : map mkrepo rs) where mkbase = mkdir "/home/joey/lib/backup" `requires` mkdir "/home/joey/lib" mkrepo r = mkdir ("/home/joey/lib/backup/" ++ r ++ ".obnam") mkdir d = File.dirExists d `before` File.ownerGroup d (User "joey") (Group "joey") podcatcher :: Property DebianLike podcatcher = Cron.niceJob "podcatcher run hourly" (Cron.Times "55 * * * *") (User "joey") "/home/joey/lib/sound/podcasts" "xargs git-annex importfeed -c annex.genmetadata=true < feeds; mr --quiet update" `requires` Apt.installed ["git-annex", "myrepos"] kiteMailServer :: Property (HasInfo + DebianLike) kiteMailServer = propertyList "kitenet.net mail server" $ props & Postfix.installed & Apt.installed ["postfix-pcre"] & Apt.serviceInstalledRunning "postgrey" & Apt.serviceInstalledRunning "spamassassin" & "/etc/default/spamassassin" `File.containsLines` [ "# Propellor deployed" , "ENABLED=1" , "OPTIONS=\"--create-prefs --max-children 5 --helper-home-dir\"" , "CRON=1" , "NICE=\"--nicelevel 15\"" ] `onChange` Service.restarted "spamassassin" `describe` "spamd enabled" `requires` Apt.serviceInstalledRunning "cron" & Apt.serviceInstalledRunning "spamass-milter" -- Add -m to prevent modifying messages Subject or body. & "/etc/default/spamass-milter" `File.containsLine` "OPTIONS=\"-m -u spamass-milter -i 127.0.0.1\"" `onChange` Service.restarted "spamass-milter" `describe` "spamass-milter configured" & Apt.serviceInstalledRunning "amavisd-milter" & "/etc/default/amavisd-milter" `File.containsLines` [ "# Propellor deployed" , "MILTERSOCKET=/var/spool/postfix/amavis/amavis.sock" , "MILTERSOCKETOWNER=\"postfix:postfix\"" , "MILTERSOCKETMODE=\"0660\"" ] `onChange` Service.restarted "amavisd-milter" `describe` "amavisd-milter configured for postfix" & Apt.serviceInstalledRunning "clamav-freshclam" -- Workaround https://bugs.debian.org/569150 & Cron.niceJob "amavis-expire" Cron.Daily (User "root") "/" "find /var/lib/amavis/virusmails/ -type f -ctime +7 -delete" & dkimInstalled & Postfix.saslAuthdInstalled & Fail2Ban.installed & Fail2Ban.jailEnabled "postfix-sasl" & "/etc/default/saslauthd" `File.containsLine` "MECHANISMS=sasldb" & Postfix.saslPasswdSet "kitenet.net" (User "errol") & Postfix.saslPasswdSet "kitenet.net" (User "joey") & Apt.installed ["maildrop"] & "/etc/maildroprc" `File.hasContent` [ "# Global maildrop filter file (deployed with propellor)" , "DEFAULT=\"$HOME/Maildir\"" , "MAILBOX=\"$DEFAULT/.\"" , "# Filter spam to a spam folder, unless .keepspam exists" , "if (/^X-Spam-Status: Yes/)" , "{" , " `test -e \"$HOME/.keepspam\"`" , " if ( $RETURNCODE != 0 )" , " to ${MAILBOX}spam" , "}" ] `describe` "maildrop configured" & "/etc/aliases" `File.hasPrivContentExposed` ctx `onChange` Postfix.newaliases & hasPostfixCert ctx & "/etc/postfix/mydomain" `File.containsLines` [ "/.*\\.kitenet\\.net/\tOK" , "/ikiwiki\\.info/\tOK" , "/joeyh\\.name/\tOK" ] `onChange` Postfix.reloaded `describe` "postfix mydomain file configured" & "/etc/postfix/obscure_client_relay.pcre" `File.hasContent` -- Remove received lines for mails relayed from trusted -- clients. These can be a privacy violation, or trigger -- spam filters. [ "/^Received: from ([^.]+)\\.kitenet\\.net.*using TLS.*by kitenet\\.net \\(([^)]+)\\) with (E?SMTPS?A?) id ([A-F[:digit:]]+)(.*)/ IGNORE" -- Munge local Received line for postfix running on a -- trusted client that relays through. These can trigger -- spam filters. , "/^Received: by ([^.]+)\\.kitenet\\.net.*/ REPLACE X-Question: 42" ] `onChange` Postfix.reloaded `describe` "postfix obscure_client_relay file configured" & Postfix.mappedFile "/etc/postfix/virtual" (flip File.containsLines [ "# *@joeyh.name to joey" , "@joeyh.name\tjoey" ] ) `describe` "postfix virtual file configured" `onChange` Postfix.reloaded & Postfix.mappedFile "/etc/postfix/relay_clientcerts" (flip File.hasPrivContentExposed ctx) & Postfix.mainCfFile `File.containsLines` [ "myhostname = kitenet.net" , "mydomain = $myhostname" , "append_dot_mydomain = no" , "myorigin = kitenet.net" , "mydestination = $myhostname, localhost.$mydomain, $mydomain, kite.$mydomain., localhost, regexp:$config_directory/mydomain" , "mailbox_command = maildrop" , "virtual_alias_maps = hash:/etc/postfix/virtual" , "# Allow clients with trusted certs to relay mail through." , "relay_clientcerts = hash:/etc/postfix/relay_clientcerts" , "smtpd_relay_restrictions = permit_mynetworks,permit_tls_clientcerts,permit_sasl_authenticated,reject_unauth_destination" , "# Filter out client relay lines from headers." , "header_checks = pcre:$config_directory/obscure_client_relay.pcre" , "# Password auth for relaying" , "smtpd_sasl_auth_enable = yes" , "smtpd_sasl_security_options = noanonymous" , "smtpd_sasl_local_domain = kitenet.net" , "# Enable postgrey." , "smtpd_recipient_restrictions = permit_tls_clientcerts,permit_sasl_authenticated,,permit_mynetworks,reject_unauth_destination,check_policy_service inet:127.0.0.1:10023" , "# Enable spamass-milter, amavis-milter (opendkim is not enabled because it causes mails forwarded from eg gmail to be rejected)" , "smtpd_milters = unix:/spamass/spamass.sock unix:amavis/amavis.sock" , "# opendkim is used for outgoing mail" , "non_smtpd_milters = inet:localhost:8891" , "milter_connect_macros = j {daemon_name} v {if_name} _" , "# If a milter is broken, fall back to just accepting mail." , "milter_default_action = accept" , "# TLS setup -- server" , "smtpd_tls_CAfile = /etc/ssl/certs/joeyca.pem" , "smtpd_tls_cert_file = /etc/ssl/certs/postfix.pem" , "smtpd_tls_key_file = /etc/ssl/private/postfix.pem" , "smtpd_tls_loglevel = 1" , "smtpd_tls_received_header = yes" , "smtpd_use_tls = yes" , "smtpd_tls_ask_ccert = yes" , "smtpd_tls_session_cache_database = sdbm:/etc/postfix/smtpd_scache" , "# TLS setup -- client" , "smtp_tls_CAfile = /etc/ssl/certs/joeyca.pem" , "smtp_tls_cert_file = /etc/ssl/certs/postfix.pem" , "smtp_tls_key_file = /etc/ssl/private/postfix.pem" , "smtp_tls_loglevel = 1" , "smtp_use_tls = yes" , "smtp_tls_session_cache_database = sdbm:/etc/postfix/smtp_scache" ] `onChange` Postfix.dedupMainCf `onChange` Postfix.reloaded `describe` "postfix configured" & Apt.serviceInstalledRunning "dovecot-imapd" & Apt.serviceInstalledRunning "dovecot-pop3d" & "/etc/dovecot/conf.d/10-mail.conf" `File.containsLine` "mail_location = maildir:~/Maildir" `onChange` Service.reloaded "dovecot" `describe` "dovecot mail.conf" & "/etc/dovecot/conf.d/10-auth.conf" `File.containsLine` "!include auth-passwdfile.conf.ext" `onChange` Service.restarted "dovecot" `describe` "dovecot auth.conf" & File.hasPrivContent dovecotusers ctx `onChange` (dovecotusers `File.mode` combineModes [ownerReadMode, groupReadMode]) & File.ownerGroup dovecotusers (User "root") (Group "dovecot") & Apt.installed ["mutt", "bsd-mailx", "alpine"] & pinescript `File.hasContent` [ "#!/bin/sh" , "# deployed with propellor" , "set -e" , "pass=$HOME/.pine-password" , "if [ ! -e $pass ]; then" , "\ttouch $pass" , "fi" , "chmod 600 $pass" , "exec alpine -passfile $pass \"$@\"" ] `onChange` (pinescript `File.mode` combineModes (readModes ++ executeModes)) `describe` "pine wrapper script" & "/etc/pine.conf" `File.hasContent` [ "# deployed with propellor" , "inbox-path={localhost/novalidate-cert/NoRsh}inbox" ] `describe` "pine configured to use local imap server" & Apt.serviceInstalledRunning "mailman" -- Override the default http url. (Only affects new lists.) & "/etc/mailman/mm_cfg.py" `File.containsLine` "DEFAULT_URL_PATTERN = 'https://%s/cgi-bin/mailman/'" & Postfix.service ssmtp & Apt.installed ["fetchmail"] where ctx = Context "kitenet.net" pinescript = "/usr/local/bin/pine" dovecotusers = "/etc/dovecot/users" ssmtp = Postfix.Service (Postfix.InetService Nothing "ssmtp") "smtpd" Postfix.defServiceOpts -- Configures postfix to have the dkim milter, and no other milters. dkimMilter :: Property (HasInfo + DebianLike) dkimMilter = Postfix.mainCfFile `File.containsLines` [ "smtpd_milters = inet:localhost:8891" , "non_smtpd_milters = inet:localhost:8891" , "milter_default_action = accept" ] `describe` "postfix dkim milter" `onChange` Postfix.dedupMainCf `onChange` Postfix.reloaded `requires` dkimInstalled -- This does not configure postfix to use the dkim milter, -- nor does it set up domainkey DNS. dkimInstalled :: Property (HasInfo + DebianLike) dkimInstalled = go `onChange` Service.restarted "opendkim" where go = propertyList "opendkim installed" $ props & Apt.serviceInstalledRunning "opendkim" & File.dirExists "/etc/mail" & File.hasPrivContent "/etc/mail/dkim.key" (Context "kitenet.net") & File.ownerGroup "/etc/mail/dkim.key" (User "opendkim") (Group "opendkim") & "/etc/default/opendkim" `File.containsLine` "SOCKET=\"inet:8891@localhost\"" & "/etc/opendkim.conf" `File.containsLines` [ "KeyFile /etc/mail/dkim.key" , "SubDomains yes" , "Domain *" , "Selector mail" ] -- This is the dkim public key, corresponding with /etc/mail/dkim.key -- This value can be included in a domain's additional records to make -- it use this domainkey. domainKey :: (BindDomain, Record) domainKey = (RelDomain "mail._domainkey", TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCc+/rfzNdt5DseBBmfB3C6sVM7FgVvf4h1FeCfyfwPpVcmPdW6M2I+NtJsbRkNbEICxiP6QY2UM0uoo9TmPqLgiCCG2vtuiG6XMsS0Y/gGwqKM7ntg/7vT1Go9vcquOFFuLa5PnzpVf8hB9+PMFdS4NPTvWL2c5xxshl/RJzICnQIDAQAB") hasJoeyCAChain :: Property (HasInfo + UnixLike) hasJoeyCAChain = "/etc/ssl/certs/joeyca.pem" `File.hasPrivContentExposed` Context "joeyca.pem" hasPostfixCert :: Context -> Property (HasInfo + UnixLike) hasPostfixCert ctx = combineProperties "postfix tls cert installed" $ props & "/etc/ssl/certs/postfix.pem" `File.hasPrivContentExposed` ctx & "/etc/ssl/private/postfix.pem" `File.hasPrivContent` ctx -- Legacy static web sites and redirections from kitenet.net to newer -- sites. legacyWebSites :: Property (HasInfo + DebianLike) legacyWebSites = propertyList "legacy web sites" $ props & Apt.serviceInstalledRunning "apache2" & Apache.modEnabled "rewrite" & Apache.modEnabled "cgi" & Apache.modEnabled "speling" & userDirHtml & Apache.httpsVirtualHost' "kitenet.net" "/var/www" letos kitenetcfg & alias "anna.kitenet.net" & apacheSite "anna.kitenet.net" [ "DocumentRoot /home/anna/html" , "<Directory /home/anna/html/>" , " Options Indexes ExecCGI" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "sows-ear.kitenet.net" & alias "www.sows-ear.kitenet.net" & apacheSite "sows-ear.kitenet.net" [ "ServerAlias www.sows-ear.kitenet.net" , "DocumentRoot /srv/web/sows-ear.kitenet.net" , "<Directory /srv/web/sows-ear.kitenet.net>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "RewriteEngine On" , "RewriteRule .* http://www.sowsearpoetry.org/ [L]" ] & alias "wortroot.kitenet.net" & alias "www.wortroot.kitenet.net" & apacheSite "wortroot.kitenet.net" [ "ServerAlias www.wortroot.kitenet.net" , "DocumentRoot /srv/web/wortroot.kitenet.net" , "<Directory /srv/web/wortroot.kitenet.net>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "creeksidepress.com" & apacheSite "creeksidepress.com" [ "ServerAlias www.creeksidepress.com" , "DocumentRoot /srv/web/www.creeksidepress.com" , "<Directory /srv/web/www.creeksidepress.com>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "joey.kitenet.net" & apacheSite "joey.kitenet.net" [ "DocumentRoot /var/www" , "<Directory /var/www/>" , " Options Indexes ExecCGI" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "RewriteEngine On" , "# Old ikiwiki filenames for joey's wiki." , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ http://joeyh.name/$1/ [l]" , "rewritecond $1 !.*/index$" , "rewriterule (.+).rss$ http://joeyh.name/$1/index.rss [l]" , "# Redirect all to joeyh.name." , "rewriterule (.*) http://joeyh.name$1 [r]" ] where kitenetcfg = -- /var/www is empty [ "DocumentRoot /var/www" , "<Directory /var/www>" , " Options Indexes FollowSymLinks MultiViews ExecCGI Includes" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/" -- for mailman cgi scripts , "<Directory /usr/lib/cgi-bin>" , " AllowOverride None" , " Options ExecCGI" , Apache.allowAll , "</Directory>" , "Alias /pipermail/ /var/lib/mailman/archives/public/" , "<Directory /var/lib/mailman/archives/public/>" , " Options Indexes MultiViews FollowSymlinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "Alias /images/ /usr/share/images/" , "<Directory /usr/share/images/>" , " Options Indexes MultiViews" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "RewriteEngine On" , "# Force hostname to kitenet.net" , "RewriteCond %{HTTP_HOST} !^kitenet\\.net [NC]" , "RewriteCond %{HTTP_HOST} !^$" , "RewriteRule ^/(.*) http://kitenet\\.net/$1 [L,R]" , "# Moved pages" , "RewriteRule /programs/debhelper http://joeyh.name/code/debhelper/ [L]" , "RewriteRule /programs/satutils http://joeyh.name/code/satutils/ [L]" , "RewriteRule /programs/filters http://joeyh.name/code/filters/ [L]" , "RewriteRule /programs/ticker http://joeyh.name/code/ticker/ [L]" , "RewriteRule /programs/pdmenu http://joeyh.name/code/pdmenu/ [L]" , "RewriteRule /programs/sleepd http://joeyh.name/code/sleepd/ [L]" , "RewriteRule /programs/Lingua::EN::Words2Nums http://joeyh.name/code/Words2Nums/ [L]" , "RewriteRule /programs/wmbattery http://joeyh.name/code/wmbattery/ [L]" , "RewriteRule /programs/dpkg-repack http://joeyh.name/code/dpkg-repack/ [L]" , "RewriteRule /programs/debconf http://joeyh.name/code/debconf/ [L]" , "RewriteRule /programs/perlmoo http://joeyh.name/code/perlmoo/ [L]" , "RewriteRule /programs/alien http://joeyh.name/code/alien/ [L]" , "RewriteRule /~joey/blog/entry/(.+)-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9].html http://joeyh.name/blog/entry/$1/ [L]" , "RewriteRule /~anna/.* http://waldeneffect\\.org/ [R]" , "RewriteRule /~anna/.* http://waldeneffect\\.org/ [R]" , "RewriteRule /~anna http://waldeneffect\\.org/ [R]" , "RewriteRule /simpleid/ http://openid.kitenet.net:8081/simpleid/" , "# Even the kite home page is not here any more!" , "RewriteRule ^/$ http://www.kitenet.net/ [R]" , "RewriteRule ^/index.html http://www.kitenet.net/ [R]" , "RewriteRule ^/joey http://www.kitenet.net/joey/ [R]" , "RewriteRule ^/joey/index.html http://www.kitenet.net/joey/ [R]" , "RewriteRule ^/wifi http://www.kitenet.net/wifi/ [R]" , "RewriteRule ^/wifi/index.html http://www.kitenet.net/wifi/ [R]" , "# Old ikiwiki filenames for kitenet.net wiki." , "rewritecond $1 !^/~" , "rewritecond $1 !^/doc/" , "rewritecond $1 !^/pipermail/" , "rewritecond $1 !^/cgi-bin/" , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ $1/ [r]" , "# Old ikiwiki filenames for joey's wiki." , "rewritecond $1 ^/~joey/" , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ http://kitenet.net/$1/ [L,R]" , "# ~joey to joeyh.name" , "rewriterule /~joey/(.*) http://joeyh.name/$1 [L]" , "# Old familywiki location." , "rewriterule /~family/(.*).html http://family.kitenet.net/$1 [L]" , "rewriterule /~family/(.*).rss http://family.kitenet.net/$1/index.rss [L]" , "rewriterule /~family(.*) http://family.kitenet.net$1 [L]" , "rewriterule /~kyle/bywayofscience(.*) http://bywayofscience.branchable.com$1 [L]" , "rewriterule /~kyle/family/wiki/(.*).html http://macleawiki.branchable.com/$1 [L]" , "rewriterule /~kyle/family/wiki/(.*).rss http://macleawiki.branchable.com/$1/index.rss [L]" , "rewriterule /~kyle/family/wiki(.*) http://macleawiki.branchable.com$1 [L]" ] userDirHtml :: Property DebianLike userDirHtml = File.fileProperty "apache userdir is html" (map munge) conf `onChange` Apache.reloaded `requires` Apache.modEnabled "userdir" where munge = replace "public_html" "html" conf = "/etc/apache2/mods-available/userdir.conf" -- Alarm clock: see -- <http://joeyh.name/blog/entry/a_programmable_alarm_clock_using_systemd/> -- -- oncalendar example value: "*-*-* 7:30" alarmClock :: String -> User -> String -> Property Linux alarmClock oncalendar (User user) command = combineProperties "goodmorning timer installed" $ props & "/etc/systemd/system/goodmorning.timer" `File.hasContent` [ "[Unit]" , "Description=good morning" , "" , "[Timer]" , "Unit=goodmorning.service" , "OnCalendar=" ++ oncalendar , "WakeSystem=true" , "Persistent=false" , "" , "[Install]" , "WantedBy=multi-user.target" ] `onChange` (Systemd.daemonReloaded `before` Systemd.restarted "goodmorning.timer") & "/etc/systemd/system/goodmorning.service" `File.hasContent` [ "[Unit]" , "Description=good morning" , "RefuseManualStart=true" , "RefuseManualStop=true" , "ConditionACPower=true" , "StopWhenUnneeded=yes" , "" , "[Service]" , "Type=oneshot" , "ExecStart=/bin/systemd-inhibit --what=handle-lid-switch --why=goodmorning /bin/su " ++ user ++ " -c \"" ++ command ++ "\"" ] `onChange` Systemd.daemonReloaded & Systemd.enabled "goodmorning.timer" & Systemd.started "goodmorning.timer" & "/etc/systemd/logind.conf" `ConfFile.containsIniSetting` ("Login", "LidSwitchIgnoreInhibited", "no")
ArchiveTeam/glowing-computing-machine
src/Propellor/Property/SiteSpecific/JoeySites.hs
Haskell
bsd-2-clause
36,052
module BookCalendar where import Data.Time import Data.Time.Calendar.WeekDate currentWordCount :: Integer currentWordCount = 14700 wordsPerDay :: Integer wordsPerDay = 333 isWeekend :: Day -> Bool isWeekend d = let (_,_,dow) = toWeekDate d in dow > 5 addToDay :: UTCTime -> Integer -> Day addToDay today days = addDays days . utctDay $ today printDay :: FormatTime t => t -> String printDay d = formatTime defaultTimeLocale " %a - %b %e %Y" d futureCounts :: [Integer] futureCounts = map (\n -> currentWordCount + (n * wordsPerDay)) [1..] buildDate :: UTCTime -> Integer -> String buildDate today daysFuture = let dayNumber = addToDay today daysFuture in printDay dayNumber dailyCounts :: t -> UTCTime -> [String] dailyCounts goal today = let days = filter (\n -> not $ isWeekend $ addToDay today n) [1..35] dayStrings = map (buildDate today) days in map (\(n, d) -> (show n) ++ d) $ zip futureCounts dayStrings main :: IO [()] main = do today <- getCurrentTime sequence $ map (putStrLn . show) $ dailyCounts wordsPerDay today
steveshogren/haskell-katas
src/BookCalendar.hs
Haskell
bsd-3-clause
1,058
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 The @TyCon@ datatype -} {-# LANGUAGE CPP, FlexibleInstances #-} module TyCon( -- * Main TyCon data types TyCon, AlgTyConRhs(..), visibleDataCons, AlgTyConFlav(..), isNoParent, FamTyConFlav(..), Role(..), Injectivity(..), RuntimeRepInfo(..), -- * TyConBinder TyConBinder, TyConBndrVis(..), mkNamedTyConBinder, mkNamedTyConBinders, mkAnonTyConBinder, mkAnonTyConBinders, tyConBinderArgFlag, isNamedTyConBinder, isVisibleTyConBinder, isInvisibleTyConBinder, -- ** Field labels tyConFieldLabels, tyConFieldLabelEnv, -- ** Constructing TyCons mkAlgTyCon, mkClassTyCon, mkFunTyCon, mkPrimTyCon, mkKindTyCon, mkLiftedPrimTyCon, mkTupleTyCon, mkSynonymTyCon, mkFamilyTyCon, mkPromotedDataCon, mkTcTyCon, -- ** Predicates on TyCons isAlgTyCon, isVanillaAlgTyCon, isClassTyCon, isFamInstTyCon, isFunTyCon, isPrimTyCon, isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon, isTypeSynonymTyCon, mightBeUnsaturatedTyCon, isPromotedDataCon, isPromotedDataCon_maybe, isKindTyCon, isLiftedTypeKindTyConName, isDataTyCon, isProductTyCon, isDataProductTyCon_maybe, isEnumerationTyCon, isNewTyCon, isAbstractTyCon, isFamilyTyCon, isOpenFamilyTyCon, isTypeFamilyTyCon, isDataFamilyTyCon, isOpenTypeFamilyTyCon, isClosedSynFamilyTyConWithAxiom_maybe, familyTyConInjectivityInfo, isBuiltInSynFamTyCon_maybe, isUnliftedTyCon, isGadtSyntaxTyCon, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs, isTyConAssoc, tyConAssoc_maybe, isImplicitTyCon, isTyConWithSrcDataCons, isTcTyCon, -- ** Extracting information out of TyCons tyConName, tyConKind, tyConUnique, tyConTyVars, tyConCType, tyConCType_maybe, tyConDataCons, tyConDataCons_maybe, tyConSingleDataCon_maybe, tyConSingleDataCon, tyConSingleAlgDataCon_maybe, tyConFamilySize, tyConStupidTheta, tyConArity, tyConRoles, tyConFlavour, tyConTuple_maybe, tyConClass_maybe, tyConATs, tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe, tyConFamilyResVar_maybe, synTyConDefn_maybe, synTyConRhs_maybe, famTyConFlav_maybe, famTcResVar, algTyConRhs, newTyConRhs, newTyConEtadArity, newTyConEtadRhs, unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe, newTyConDataCon_maybe, algTcFields, tyConRuntimeRepInfo, tyConBinders, tyConResKind, tcTyConScopedTyVars, -- ** Manipulating TyCons expandSynTyCon_maybe, makeTyConAbstract, newTyConCo, newTyConCo_maybe, pprPromotionQuote, mkTyConKind, -- * Runtime type representation TyConRepName, tyConRepName_maybe, mkPrelTyConRepName, tyConRepModOcc, -- * Primitive representations of Types PrimRep(..), PrimElemRep(..), isVoidRep, isGcPtrRep, primRepSizeW, primElemRepSizeB, primRepIsFloat, -- * Recursion breaking RecTcChecker, initRecTc, checkRecTc ) where #include "HsVersions.h" import {-# SOURCE #-} TyCoRep ( Kind, Type, PredType, pprType ) import {-# SOURCE #-} TysWiredIn ( runtimeRepTyCon, constraintKind , vecCountTyCon, vecElemTyCon, liftedTypeKind , mkFunKind, mkForAllKind ) import {-# SOURCE #-} DataCon ( DataCon, dataConExTyVars, dataConFieldLabels ) import Binary import Var import Class import BasicTypes import DynFlags import ForeignCall import Name import NameEnv import CoAxiom import PrelNames import Maybes import Outputable import FastStringEnv import FieldLabel import Constants import Util import Unique( tyConRepNameUnique, dataConRepNameUnique ) import UniqSet import Module import qualified Data.Data as Data {- ----------------------------------------------- Notes about type families ----------------------------------------------- Note [Type synonym families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Type synonym families, also known as "type functions", map directly onto the type functions in FC: type family F a :: * type instance F Int = Bool ..etc... * Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon * From the user's point of view (F Int) and Bool are simply equivalent types. * A Haskell 98 type synonym is a degenerate form of a type synonym family. * Type functions can't appear in the LHS of a type function: type instance F (F Int) = ... -- BAD! * Translation of type family decl: type family F a :: * translates to a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon type family G a :: * where G Int = Bool G Bool = Char G a = () translates to a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the appropriate CoAxiom representing the equations We also support injective type families -- see Note [Injective type families] Note [Data type families] ~~~~~~~~~~~~~~~~~~~~~~~~~ See also Note [Wrappers for data instance tycons] in MkId.hs * Data type families are declared thus data family T a :: * data instance T Int = T1 | T2 Bool Here T is the "family TyCon". * Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon * The user does not see any "equivalent types" as he did with type synonym families. He just sees constructors with types T1 :: T Int T2 :: Bool -> T Int * Here's the FC version of the above declarations: data T a data R:TInt = T1 | T2 Bool axiom ax_ti : T Int ~R R:TInt Note that this is a *representational* coercion The R:TInt is the "representation TyCons". It has an AlgTyConFlav of DataFamInstTyCon T [Int] ax_ti * The axiom ax_ti may be eta-reduced; see Note [Eta reduction for data family axioms] in TcInstDcls * The data constructor T2 has a wrapper (which is what the source-level "T2" invokes): $WT2 :: Bool -> T Int $WT2 b = T2 b `cast` sym ax_ti * A data instance can declare a fully-fledged GADT: data instance T (a,b) where X1 :: T (Int,Bool) X2 :: a -> b -> T (a,b) Here's the FC version of the above declaration: data R:TPair a where X1 :: R:TPair Int Bool X2 :: a -> b -> R:TPair a b axiom ax_pr :: T (a,b) ~R R:TPair a b $WX1 :: forall a b. a -> b -> T (a,b) $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b) The R:TPair are the "representation TyCons". We have a bit of work to do, to unpick the result types of the data instance declaration for T (a,b), to get the result type in the representation; e.g. T (a,b) --> R:TPair a b The representation TyCon R:TList, has an AlgTyConFlav of DataFamInstTyCon T [(a,b)] ax_pr * Notice that T is NOT translated to a FC type function; it just becomes a "data type" with no constructors, which can be coerced inot into R:TInt, R:TPair by the axioms. These axioms axioms come into play when (and *only* when) you - use a data constructor - do pattern matching Rather like newtype, in fact As a result - T behaves just like a data type so far as decomposition is concerned - (T Int) is not implicitly converted to R:TInt during type inference. Indeed the latter type is unknown to the programmer. - There *is* an instance for (T Int) in the type-family instance environment, but it is only used for overlap checking - It's fine to have T in the LHS of a type function: type instance F (T a) = [a] It was this last point that confused me! The big thing is that you should not think of a data family T as a *type function* at all, not even an injective one! We can't allow even injective type functions on the LHS of a type function: type family injective G a :: * type instance F (G Int) = Bool is no good, even if G is injective, because consider type instance G Int = Bool type instance F Bool = Char So a data type family is not an injective type function. It's just a data type with some axioms that connect it to other data types. * The tyConTyVars of the representation tycon are the tyvars that the user wrote in the patterns. This is important in TcDeriv, where we bring these tyvars into scope before type-checking the deriving clause. This fact is arranged for in TcInstDecls.tcDataFamInstDecl. Note [Associated families and their parent class] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *Associated* families are just like *non-associated* families, except that they have a famTcParent field of (Just cls), which identifies the parent class. However there is an important sharing relationship between * the tyConTyVars of the parent Class * the tyConTyvars of the associated TyCon class C a b where data T p a type F a q b Here the 'a' and 'b' are shared with the 'Class'; that is, they have the same Unique. This is important. In an instance declaration we expect * all the shared variables to be instantiated the same way * the non-shared variables of the associated type should not be instantiated at all instance C [x] (Tree y) where data T p [x] = T1 x | T2 p type F [x] q (Tree y) = (x,y,q) Note [TyCon Role signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Every tycon has a role signature, assigning a role to each of the tyConTyVars (or of equal length to the tyConArity, if there are no tyConTyVars). An example demonstrates these best: say we have a tycon T, with parameters a at nominal, b at representational, and c at phantom. Then, to prove representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have nominal equality between a1 and a2, representational equality between b1 and b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This might happen, say, with the following declaration: data T a b c where MkT :: b -> T Int b c Data and class tycons have their roles inferred (see inferRoles in TcTyDecls), as do vanilla synonym tycons. Family tycons have all parameters at role N, though it is conceivable that we could relax this restriction. (->)'s and tuples' parameters are at role R. Each primitive tycon declares its roles; it's worth noting that (~#)'s parameters are at role N. Promoted data constructors' type arguments are at role R. All kind arguments are at role N. Note [Unboxed tuple RuntimeRep vars] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The contents of an unboxed tuple may have any representation. Accordingly, the kind of the unboxed tuple constructor is runtime-representation polymorphic. For example, (#,#) :: forall (q :: RuntimeRep) (r :: RuntimeRep). TYPE q -> TYPE r -> # These extra tyvars (v and w) cause some delicate processing around tuples, where we used to be able to assume that the tycon arity and the datacon arity were the same. Note [Injective type families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We allow injectivity annotations for type families (both open and closed): type family F (a :: k) (b :: k) = r | r -> a type family G a b = res | res -> a b where ... Injectivity information is stored in the `famTcInj` field of `FamilyTyCon`. `famTcInj` maybe stores a list of Bools, where each entry corresponds to a single element of `tyConTyVars` (both lists should have identical length). If no injectivity annotation was provided `famTcInj` is Nothing. From this follows an invariant that if `famTcInj` is a Just then at least one element in the list must be True. See also: * [Injectivity annotation] in HsDecls * [Renaming injectivity annotation] in RnSource * [Verifying injectivity annotation] in FamInstEnv * [Type inference for type families with injectivity] in TcInteract ************************************************************************ * * TyConBinder * * ************************************************************************ -} type TyConBinder = TyVarBndr TyVar TyConBndrVis data TyConBndrVis = NamedTCB ArgFlag | AnonTCB mkAnonTyConBinder :: TyVar -> TyConBinder mkAnonTyConBinder tv = TvBndr tv AnonTCB mkAnonTyConBinders :: [TyVar] -> [TyConBinder] mkAnonTyConBinders tvs = map mkAnonTyConBinder tvs mkNamedTyConBinder :: ArgFlag -> TyVar -> TyConBinder -- The odd argument order supports currying mkNamedTyConBinder vis tv = TvBndr tv (NamedTCB vis) mkNamedTyConBinders :: ArgFlag -> [TyVar] -> [TyConBinder] -- The odd argument order supports currying mkNamedTyConBinders vis tvs = map (mkNamedTyConBinder vis) tvs tyConBinderArgFlag :: TyConBinder -> ArgFlag tyConBinderArgFlag (TvBndr _ (NamedTCB vis)) = vis tyConBinderArgFlag (TvBndr _ AnonTCB) = Required isNamedTyConBinder :: TyConBinder -> Bool isNamedTyConBinder (TvBndr _ (NamedTCB {})) = True isNamedTyConBinder _ = False isVisibleTyConBinder :: TyVarBndr tv TyConBndrVis -> Bool -- Works for IfaceTyConBinder too isVisibleTyConBinder (TvBndr _ (NamedTCB vis)) = isVisibleArgFlag vis isVisibleTyConBinder (TvBndr _ AnonTCB) = True isInvisibleTyConBinder :: TyVarBndr tv TyConBndrVis -> Bool -- Works for IfaceTyConBinder too isInvisibleTyConBinder tcb = not (isVisibleTyConBinder tcb) mkTyConKind :: [TyConBinder] -> Kind -> Kind mkTyConKind bndrs res_kind = foldr mk res_kind bndrs where mk :: TyConBinder -> Kind -> Kind mk (TvBndr tv AnonTCB) k = mkFunKind (tyVarKind tv) k mk (TvBndr tv (NamedTCB vis)) k = mkForAllKind tv vis k {- Note [The binders/kind/arity fields of a TyCon] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All TyCons have this group of fields tyConBinders :: [TyConBinder] tyConResKind :: Kind tyConTyVars :: [TyVra] -- Cached = binderVars tyConBinders tyConKind :: Kind -- Cached = mkTyConKind tyConBinders tyConResKind tyConArity :: Arity -- Cached = length tyConBinders They fit together like so: * tyConBinders gives the telescope of type variables on the LHS of the type declaration. For example: type App a (b :: k) = a b tyConBinders = [ TvBndr (k::*) (NamedTCB Inferred) , TvBndr (a:k->*) AnonTCB , TvBndr (b:k) AnonTCB ] Note that that are three binders here, including the kind variable k. See Note [TyBinders and ArgFlags] in TyCoRep for what the visibility flag means. * Each TyConBinder tyConBinders has a TyVar, and that TyVar may scope over some other part of the TyCon's definition. Eg type T a = a->a we have tyConBinders = [ TvBndr (a:*) AnonTCB ] synTcRhs = a->a So the 'a' scopes over the synTcRhs * From the tyConBinders and tyConResKind we can get the tyConKind E.g for our App example: App :: forall k. (k->*) -> k -> * We get a 'forall' in the kind for each NamedTCB, and an arrow for each AnonTCB tyConKind is the full kind of the TyCon, not just the result kind * tyConArity is the arguments this TyCon must be applied to, to be considered saturated. Here we mean "applied to in the actual Type", not surface syntax; i.e. including implicit kind variables. So it's just (length tyConBinders) -} instance Outputable tv => Outputable (TyVarBndr tv TyConBndrVis) where ppr (TvBndr v AnonTCB) = ppr v ppr (TvBndr v (NamedTCB Required)) = ppr v ppr (TvBndr v (NamedTCB Specified)) = char '@' <> ppr v ppr (TvBndr v (NamedTCB Inferred)) = braces (ppr v) instance Binary TyConBndrVis where put_ bh AnonTCB = putByte bh 0 put_ bh (NamedTCB vis) = do { putByte bh 1; put_ bh vis } get bh = do { h <- getByte bh ; case h of 0 -> return AnonTCB _ -> do { vis <- get bh; return (NamedTCB vis) } } {- ********************************************************************* * * The TyCon type * * ************************************************************************ -} -- | TyCons represent type constructors. Type constructors are introduced by -- things such as: -- -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of -- kind @*@ -- -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor -- -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor -- of kind @* -> *@ -- -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor -- of kind @*@ -- -- This data type also encodes a number of primitive, built in type constructors -- such as those for function and tuple types. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data TyCon = -- | The function type constructor, @(->)@ FunTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity tcRepName :: TyConRepName } -- | Algebraic data types, from -- - @data@ declararations -- - @newtype@ declarations -- - data instance declarations -- - type instance declarations -- - the TyCon generated by a class declaration -- - boxed tuples -- - unboxed tuples -- - constraint tuples -- All these constructors are lifted and boxed except unboxed tuples -- which should have an 'UnboxedAlgTyCon' parent. -- Data/newtype/type /families/ are handled by 'FamilyTyCon'. -- See 'AlgTyConRhs' for more information. | AlgTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConTyVars :: [TyVar], -- ^ TyVar binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity -- The tyConTyVars scope over: -- -- 1. The 'algTcStupidTheta' -- 2. The cached types in algTyConRhs.NewTyCon -- 3. The family instance types if present -- -- Note that it does /not/ scope over the data -- constructors. tcRoles :: [Role], -- ^ The role for each type variable -- This list has length = tyConArity -- See also Note [TyCon Role signatures] tyConCType :: Maybe CType,-- ^ The C type that should be used -- for this type when using the FFI -- and CAPI algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT -- syntax? If so, that doesn't mean it's a -- true GADT; only that the "where" form -- was used. This field is used only to -- guide pretty-printing algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data -- type (always empty for GADTs). A -- \"stupid theta\" is the context to -- the left of an algebraic type -- declaration, e.g. @Eq a@ in the -- declaration @data Eq a => T a ...@. algTcRhs :: AlgTyConRhs, -- ^ Contains information about the -- data constructors of the algebraic type algTcFields :: FieldLabelEnv, -- ^ Maps a label to information -- about the field algTcParent :: AlgTyConFlav -- ^ Gives the class or family declaration -- 'TyCon' for derived 'TyCon's representing -- class or family instances, respectively. } -- | Represents type synonyms | SynonymTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConTyVars :: [TyVar], -- ^ TyVar binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity -- tyConTyVars scope over: synTcRhs tcRoles :: [Role], -- ^ The role for each type variable -- This list has length = tyConArity -- See also Note [TyCon Role signatures] synTcRhs :: Type -- ^ Contains information about the expansion -- of the synonym } -- | Represents families (both type and data) -- Argument roles are all Nominal | FamilyTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConTyVars :: [TyVar], -- ^ TyVar binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity -- tyConTyVars connect an associated family TyCon -- with its parent class; see TcValidity.checkConsistentFamInst famTcResVar :: Maybe Name, -- ^ Name of result type variable, used -- for pretty-printing with --show-iface -- and for reifying TyCon in Template -- Haskell famTcFlav :: FamTyConFlav, -- ^ Type family flavour: open, closed, -- abstract, built-in. See comments for -- FamTyConFlav famTcParent :: Maybe Class, -- ^ For *associated* type/data families -- The class in whose declaration the family is declared -- See Note [Associated families and their parent class] famTcInj :: Injectivity -- ^ is this a type family injective in -- its type variables? Nothing if no -- injectivity annotation was given } -- | Primitive types; cannot be defined in Haskell. This includes -- the usual suspects (such as @Int#@) as well as foreign-imported -- types and kinds (@*@, @#@, and @?@) | PrimTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity tcRoles :: [Role], -- ^ The role for each type variable -- This list has length = tyConArity -- See also Note [TyCon Role signatures] isUnlifted :: Bool, -- ^ Most primitive tycons are unlifted (may -- not contain bottom) but other are lifted, -- e.g. @RealWorld@ -- Only relevant if tyConKind = * primRepName :: Maybe TyConRepName -- Only relevant for kind TyCons -- i.e, *, #, ? } -- | Represents promoted data constructor. | PromotedDataCon { -- See Note [Promoted data constructors] tyConUnique :: Unique, -- ^ Same Unique as the data constructor tyConName :: Name, -- ^ Same Name as the data constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity tcRoles :: [Role], -- ^ Roles: N for kind vars, R for type vars dataCon :: DataCon, -- ^ Corresponding data constructor tcRepName :: TyConRepName, promDcRepInfo :: RuntimeRepInfo -- ^ See comments with 'RuntimeRepInfo' } -- | These exist only during a recursive type/class type-checking knot. | TcTyCon { tyConUnique :: Unique, tyConName :: Name, tyConUnsat :: Bool, -- ^ can this tycon be unsaturated? -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConTyVars :: [TyVar], -- ^ TyVar binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity tcTyConScopedTyVars :: [TyVar] -- ^ Scoped tyvars over the -- tycon's body. See Note [TcTyCon] } -- | Represents right-hand-sides of 'TyCon's for algebraic types data AlgTyConRhs -- | Says that we know nothing about this data type, except that -- it's represented by a pointer. Used when we export a data type -- abstractly into an .hi file. = AbstractTyCon Bool -- True <=> It's definitely a distinct data type, -- equal only to itself; ie not a newtype -- False <=> Not sure -- | Information about those 'TyCon's derived from a @data@ -- declaration. This includes data types with no constructors at -- all. | DataTyCon { data_cons :: [DataCon], -- ^ The data type constructors; can be empty if the -- user declares the type to have no constructors -- -- INVARIANT: Kept in order of increasing 'DataCon' -- tag (see the tag assignment in DataCon.mkDataCon) is_enum :: Bool -- ^ Cached value: is this an enumeration type? -- See Note [Enumeration types] } | TupleTyCon { -- A boxed, unboxed, or constraint tuple data_con :: DataCon, -- NB: it can be an *unboxed* tuple tup_sort :: TupleSort -- ^ Is this a boxed, unboxed or constraint -- tuple? } -- | Information about those 'TyCon's derived from a @newtype@ declaration | NewTyCon { data_con :: DataCon, -- ^ The unique constructor for the @newtype@. -- It has no existentials nt_rhs :: Type, -- ^ Cached value: the argument type of the -- constructor, which is just the representation -- type of the 'TyCon' (remember that @newtype@s -- do not exist at runtime so need a different -- representation type). -- -- The free 'TyVar's of this type are the -- 'tyConTyVars' from the corresponding 'TyCon' nt_etad_rhs :: ([TyVar], Type), -- ^ Same as the 'nt_rhs', but this time eta-reduced. -- Hence the list of 'TyVar's in this field may be -- shorter than the declared arity of the 'TyCon'. -- See Note [Newtype eta] nt_co :: CoAxiom Unbranched -- The axiom coercion that creates the @newtype@ -- from the representation 'Type'. -- See Note [Newtype coercions] -- Invariant: arity = #tvs in nt_etad_rhs; -- See Note [Newtype eta] -- Watch out! If any newtypes become transparent -- again check Trac #1072. } -- | Some promoted datacons signify extra info relevant to GHC. For example, -- the @IntRep@ constructor of @RuntimeRep@ corresponds to the 'IntRep' -- constructor of 'PrimRep'. This data structure allows us to store this -- information right in the 'TyCon'. The other approach would be to look -- up things like @RuntimeRep@'s @PrimRep@ by known-key every time. data RuntimeRepInfo = NoRRI -- ^ an ordinary promoted data con | RuntimeRep ([Type] -> PrimRep) -- ^ A constructor of @RuntimeRep@. The argument to the function should -- be the list of arguments to the promoted datacon. | VecCount Int -- ^ A constructor of @VecCount@ | VecElem PrimElemRep -- ^ A constructor of @VecElem@ -- | Extract those 'DataCon's that we are able to learn about. Note -- that visibility in this sense does not correspond to visibility in -- the context of any particular user program! visibleDataCons :: AlgTyConRhs -> [DataCon] visibleDataCons (AbstractTyCon {}) = [] visibleDataCons (DataTyCon{ data_cons = cs }) = cs visibleDataCons (NewTyCon{ data_con = c }) = [c] visibleDataCons (TupleTyCon{ data_con = c }) = [c] -- ^ Both type classes as well as family instances imply implicit -- type constructors. These implicit type constructors refer to their parent -- structure (ie, the class or family from which they derive) using a type of -- the following form. data AlgTyConFlav = -- | An ordinary type constructor has no parent. VanillaAlgTyCon TyConRepName -- | An unboxed type constructor. Note that this carries no TyConRepName -- as it is not representable. | UnboxedAlgTyCon -- | Type constructors representing a class dictionary. -- See Note [ATyCon for classes] in TyCoRep | ClassTyCon Class -- INVARIANT: the classTyCon of this Class is the -- current tycon TyConRepName -- | Type constructors representing an *instance* of a *data* family. -- Parameters: -- -- 1) The type family in question -- -- 2) Instance types; free variables are the 'tyConTyVars' -- of the current 'TyCon' (not the family one). INVARIANT: -- the number of types matches the arity of the family 'TyCon' -- -- 3) A 'CoTyCon' identifying the representation -- type with the type instance family | DataFamInstTyCon -- See Note [Data type families] (CoAxiom Unbranched) -- The coercion axiom. -- A *Representational* coercion, -- of kind T ty1 ty2 ~R R:T a b c -- where T is the family TyCon, -- and R:T is the representation TyCon (ie this one) -- and a,b,c are the tyConTyVars of this TyCon -- -- BUT may be eta-reduced; see TcInstDcls -- Note [Eta reduction for data family axioms] -- Cached fields of the CoAxiom, but adjusted to -- use the tyConTyVars of this TyCon TyCon -- The family TyCon [Type] -- Argument types (mentions the tyConTyVars of this TyCon) -- Match in length the tyConTyVars of the family TyCon -- E.g. data intance T [a] = ... -- gives a representation tycon: -- data R:TList a = ... -- axiom co a :: T [a] ~ R:TList a -- with R:TList's algTcParent = DataFamInstTyCon T [a] co instance Outputable AlgTyConFlav where ppr (VanillaAlgTyCon {}) = text "Vanilla ADT" ppr (UnboxedAlgTyCon {}) = text "Unboxed ADT" ppr (ClassTyCon cls _) = text "Class parent" <+> ppr cls ppr (DataFamInstTyCon _ tc tys) = text "Family parent (family instance)" <+> ppr tc <+> sep (map pprType tys) -- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class -- name, if any okParent :: Name -> AlgTyConFlav -> Bool okParent _ (VanillaAlgTyCon {}) = True okParent _ (UnboxedAlgTyCon) = True okParent tc_name (ClassTyCon cls _) = tc_name == tyConName (classTyCon cls) okParent _ (DataFamInstTyCon _ fam_tc tys) = tyConArity fam_tc == length tys isNoParent :: AlgTyConFlav -> Bool isNoParent (VanillaAlgTyCon {}) = True isNoParent _ = False -------------------- data Injectivity = NotInjective | Injective [Bool] -- 1-1 with tyConTyVars (incl kind vars) deriving( Eq ) -- | Information pertaining to the expansion of a type synonym (@type@) data FamTyConFlav = -- | Represents an open type family without a fixed right hand -- side. Additional instances can appear at any time. -- -- These are introduced by either a top level declaration: -- -- > data family T a :: * -- -- Or an associated data type declaration, within a class declaration: -- -- > class C a b where -- > data T b :: * DataFamilyTyCon TyConRepName -- | An open type synonym family e.g. @type family F x y :: * -> *@ | OpenSynFamilyTyCon -- | A closed type synonym family e.g. -- @type family F x where { F Int = Bool }@ | ClosedSynFamilyTyCon (Maybe (CoAxiom Branched)) -- See Note [Closed type families] -- | A closed type synonym family declared in an hs-boot file with -- type family F a where .. | AbstractClosedSynFamilyTyCon -- | Built-in type family used by the TypeNats solver | BuiltInSynFamTyCon BuiltInSynFamily {- Note [Closed type families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * In an open type family you can add new instances later. This is the usual case. * In a closed type family you can only put equations where the family is defined. A non-empty closed type family has a single axiom with multiple branches, stored in the 'ClosedSynFamilyTyCon' constructor. A closed type family with no equations does not have an axiom, because there is nothing for the axiom to prove! Note [Promoted data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All data constructors can be promoted to become a type constructor, via the PromotedDataCon alternative in TyCon. * The TyCon promoted from a DataCon has the *same* Name and Unique as the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78, say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78) * Small note: We promote the *user* type of the DataCon. Eg data T = MkT {-# UNPACK #-} !(Bool, Bool) The promoted kind is MkT :: (Bool,Bool) -> T *not* MkT :: Bool -> Bool -> T Note [Enumeration types] ~~~~~~~~~~~~~~~~~~~~~~~~ We define datatypes with no constructors to *not* be enumerations; this fixes trac #2578, Otherwise we end up generating an empty table for <mod>_<type>_closure_tbl which is used by tagToEnum# to map Int# to constructors in an enumeration. The empty table apparently upset the linker. Moreover, all the data constructor must be enumerations, meaning they have type (forall abc. T a b c). GADTs are not enumerations. For example consider data T a where T1 :: T Int T2 :: T Bool T3 :: T a What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them. See Trac #4528. Note [Newtype coercions] ~~~~~~~~~~~~~~~~~~~~~~~~ The NewTyCon field nt_co is a CoAxiom which is used for coercing from the representation type of the newtype, to the newtype itself. For example, newtype T a = MkT (a -> a) the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t. In the case that the right hand side is a type application ending with the same type variables as the left hand side, we "eta-contract" the coercion. So if we had newtype S a = MkT [a] then we would generate the arity 0 axiom CoS : S ~ []. The primary reason we do this is to make newtype deriving cleaner. In the paper we'd write axiom CoT : (forall t. T t) ~ (forall t. [t]) and then when we used CoT at a particular type, s, we'd say CoT @ s which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s]) Note [Newtype eta] ~~~~~~~~~~~~~~~~~~ Consider newtype Parser a = MkParser (IO a) deriving Monad Are these two types equal (to Core)? Monad Parser Monad IO which we need to make the derived instance for Monad Parser. Well, yes. But to see that easily we eta-reduce the RHS type of Parser, in this case to ([], Froogle), so that even unsaturated applications of Parser will work right. This eta reduction is done when the type constructor is built, and cached in NewTyCon. Here's an example that I think showed up in practice Source code: newtype T a = MkT [a] newtype Foo m = MkFoo (forall a. m a -> Int) w1 :: Foo [] w1 = ... w2 :: Foo T w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x) After desugaring, and discarding the data constructors for the newtypes, we get: w2 = w1 `cast` Foo CoT so the coercion tycon CoT must have kind: T ~ [] and arity: 0 Note [TcTyCon] ~~~~~~~~~~~~~~ When checking a type/class declaration (in module TcTyClsDecls), we come upon knowledge of the eventual tycon in bits and pieces. First, we use getInitialKinds to look over the user-provided kind signature of a tycon (including, for example, the number of parameters written to the tycon) to get an initial shape of the tycon's kind. Then, using these initial kinds, we kind-check the body of the tycon (class methods, data constructors, etc.), filling in the metavariables in the tycon's initial kind. We then generalize to get the tycon's final, fixed kind. Finally, once this has happened for all tycons in a mutually recursive group, we can desugar the lot. For convenience, we store partially-known tycons in TcTyCons, which might store meta-variables. These TcTyCons are stored in the local environment in TcTyClsDecls, until the real full TyCons can be created during desugaring. A desugared program should never have a TcTyCon. A challenging piece in all of this is that we end up taking three separate passes over every declaration: one in getInitialKind (this pass look only at the head, not the body), one in kcTyClDecls (to kind-check the body), and a final one in tcTyClDecls (to desugar). In the latter two passes, we need to connect the user-written type variables in an LHsQTyVars with the variables in the tycon's inferred kind. Because the tycon might not have a CUSK, this matching up is, in general, quite hard to do. (Look through the git history between Dec 2015 and Apr 2016 for TcHsType.splitTelescopeTvs!) Instead of trying, we just store the list of type variables to bring into scope in the later passes when we create a TcTyCon in getInitialKinds. Much easier this way! These tyvars are brought into scope in kcTyClTyVars and tcTyClTyVars, both in TcHsType. It is important that the scoped type variables not be zonked, as some scoped type variables come into existence as SigTvs. If we zonk, the Unique will change and the user-written occurrences won't match up with what we expect. In a TcTyCon, everything is zonked (except the scoped vars) after the kind-checking pass. ************************************************************************ * * TyConRepName * * ********************************************************************* -} type TyConRepName = Name -- The Name of the top-level declaration -- $tcMaybe :: Data.Typeable.Internal.TyCon -- $tcMaybe = TyCon { tyConName = "Maybe", ... } tyConRepName_maybe :: TyCon -> Maybe TyConRepName tyConRepName_maybe (FunTyCon { tcRepName = rep_nm }) = Just rep_nm tyConRepName_maybe (PrimTyCon { primRepName = mb_rep_nm }) = mb_rep_nm tyConRepName_maybe (AlgTyCon { algTcParent = parent }) | VanillaAlgTyCon rep_nm <- parent = Just rep_nm | ClassTyCon _ rep_nm <- parent = Just rep_nm tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm }) = Just rep_nm tyConRepName_maybe (PromotedDataCon { tcRepName = rep_nm }) = Just rep_nm tyConRepName_maybe _ = Nothing -- | Make a 'Name' for the 'Typeable' representation of the given wired-in type mkPrelTyConRepName :: Name -> TyConRepName -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable. mkPrelTyConRepName tc_name -- Prelude tc_name is always External, -- so nameModule will work = mkExternalName rep_uniq rep_mod rep_occ (nameSrcSpan tc_name) where name_occ = nameOccName tc_name name_mod = nameModule tc_name name_uniq = nameUnique tc_name rep_uniq | isTcOcc name_occ = tyConRepNameUnique name_uniq | otherwise = dataConRepNameUnique name_uniq (rep_mod, rep_occ) = tyConRepModOcc name_mod name_occ -- | The name (and defining module) for the Typeable representation (TyCon) of a -- type constructor. -- -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable. tyConRepModOcc :: Module -> OccName -> (Module, OccName) tyConRepModOcc tc_module tc_occ = (rep_module, mkTyConRepOcc tc_occ) where rep_module | tc_module == gHC_PRIM = gHC_TYPES | otherwise = tc_module {- ********************************************************************* * * PrimRep * * ************************************************************************ Note [rep swamp] GHC has a rich selection of types that represent "primitive types" of one kind or another. Each of them makes a different set of distinctions, and mostly the differences are for good reasons, although it's probably true that we could merge some of these. Roughly in order of "includes more information": - A Width (cmm/CmmType) is simply a binary value with the specified number of bits. It may represent a signed or unsigned integer, a floating-point value, or an address. data Width = W8 | W16 | W32 | W64 | W80 | W128 - Size, which is used in the native code generator, is Width + floating point information. data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80 it is necessary because e.g. the instruction to move a 64-bit float on x86 (movsd) is different from the instruction to move a 64-bit integer (movq), so the mov instruction is parameterised by Size. - CmmType wraps Width with more information: GC ptr, float, or other value. data CmmType = CmmType CmmCat Width data CmmCat -- "Category" (not exported) = GcPtrCat -- GC pointer | BitsCat -- Non-pointer | FloatCat -- Float It is important to have GcPtr information in Cmm, since we generate info tables containing pointerhood for the GC from this. As for why we have float (and not signed/unsigned) here, see Note [Signed vs unsigned]. - ArgRep makes only the distinctions necessary for the call and return conventions of the STG machine. It is essentially CmmType + void. - PrimRep makes a few more distinctions than ArgRep: it divides non-GC-pointers into signed/unsigned and addresses, information that is necessary for passing these values to foreign functions. There's another tension here: whether the type encodes its size in bytes, or whether its size depends on the machine word size. Width and CmmType have the size built-in, whereas ArgRep and PrimRep do not. This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags. On the other hand, CmmType includes some "nonsense" values, such as CmmType GcPtrCat W32 on a 64-bit machine. -} -- | A 'PrimRep' is an abstraction of a type. It contains information that -- the code generator needs in order to pass arguments, return results, -- and store values of this type. data PrimRep = VoidRep | PtrRep | IntRep -- ^ Signed, word-sized value | WordRep -- ^ Unsigned, word-sized value | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only) | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only) | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep') | FloatRep | DoubleRep | VecRep Int PrimElemRep -- ^ A vector deriving( Eq, Show ) data PrimElemRep = Int8ElemRep | Int16ElemRep | Int32ElemRep | Int64ElemRep | Word8ElemRep | Word16ElemRep | Word32ElemRep | Word64ElemRep | FloatElemRep | DoubleElemRep deriving( Eq, Show ) instance Outputable PrimRep where ppr r = text (show r) instance Outputable PrimElemRep where ppr r = text (show r) isVoidRep :: PrimRep -> Bool isVoidRep VoidRep = True isVoidRep _other = False isGcPtrRep :: PrimRep -> Bool isGcPtrRep PtrRep = True isGcPtrRep _ = False -- | Find the size of a 'PrimRep', in words primRepSizeW :: DynFlags -> PrimRep -> Int primRepSizeW _ IntRep = 1 primRepSizeW _ WordRep = 1 primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags primRepSizeW _ FloatRep = 1 -- NB. might not take a full word primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags primRepSizeW _ AddrRep = 1 primRepSizeW _ PtrRep = 1 primRepSizeW _ VoidRep = 0 primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags primElemRepSizeB :: PrimElemRep -> Int primElemRepSizeB Int8ElemRep = 1 primElemRepSizeB Int16ElemRep = 2 primElemRepSizeB Int32ElemRep = 4 primElemRepSizeB Int64ElemRep = 8 primElemRepSizeB Word8ElemRep = 1 primElemRepSizeB Word16ElemRep = 2 primElemRepSizeB Word32ElemRep = 4 primElemRepSizeB Word64ElemRep = 8 primElemRepSizeB FloatElemRep = 4 primElemRepSizeB DoubleElemRep = 8 -- | Return if Rep stands for floating type, -- returns Nothing for vector types. primRepIsFloat :: PrimRep -> Maybe Bool primRepIsFloat FloatRep = Just True primRepIsFloat DoubleRep = Just True primRepIsFloat (VecRep _ _) = Nothing primRepIsFloat _ = Just False {- ************************************************************************ * * Field labels * * ************************************************************************ -} -- | The labels for the fields of this particular 'TyCon' tyConFieldLabels :: TyCon -> [FieldLabel] tyConFieldLabels tc = dFsEnvElts $ tyConFieldLabelEnv tc -- | The labels for the fields of this particular 'TyCon' tyConFieldLabelEnv :: TyCon -> FieldLabelEnv tyConFieldLabelEnv tc | isAlgTyCon tc = algTcFields tc | otherwise = emptyDFsEnv -- | Make a map from strings to FieldLabels from all the data -- constructors of this algebraic tycon fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv fieldsOfAlgTcRhs rhs = mkDFsEnv [ (flLabel fl, fl) | fl <- dataConsFields (visibleDataCons rhs) ] where -- Duplicates in this list will be removed by 'mkFsEnv' dataConsFields dcs = concatMap dataConFieldLabels dcs {- ************************************************************************ * * \subsection{TyCon Construction} * * ************************************************************************ Note: the TyCon constructors all take a Kind as one argument, even though they could, in principle, work out their Kind from their other arguments. But to do so they need functions from Types, and that makes a nasty module mutual-recursion. And they aren't called from many places. So we compromise, and move their Kind calculation to the call site. -} -- | Given the name of the function type constructor and it's kind, create the -- corresponding 'TyCon'. It is reccomended to use 'TyCoRep.funTyCon' if you want -- this functionality mkFunTyCon :: Name -> [TyConBinder] -> Name -> TyCon mkFunTyCon name binders rep_nm = FunTyCon { tyConUnique = nameUnique name, tyConName = name, tyConBinders = binders, tyConResKind = liftedTypeKind, tyConKind = mkTyConKind binders liftedTypeKind, tyConArity = 2, tcRepName = rep_nm } -- | This is the making of an algebraic 'TyCon'. Notably, you have to -- pass in the generic (in the -XGenerics sense) information about the -- type constructor - you can get hold of it easily (see Generics -- module) mkAlgTyCon :: Name -> [TyConBinder] -- ^ Binders of the 'TyCon' -> Kind -- ^ Result kind -> [Role] -- ^ The roles for each TyVar -> Maybe CType -- ^ The C type this type corresponds to -- when using the CAPI FFI -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta' -> AlgTyConRhs -- ^ Information about data constructors -> AlgTyConFlav -- ^ What flavour is it? -- (e.g. vanilla, type family) -> Bool -- ^ Was the 'TyCon' declared with GADT syntax? -> TyCon mkAlgTyCon name binders res_kind roles cType stupid rhs parent gadt_syn = AlgTyCon { tyConName = name, tyConUnique = nameUnique name, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, tyConArity = length binders, tyConTyVars = binderVars binders, tcRoles = roles, tyConCType = cType, algTcStupidTheta = stupid, algTcRhs = rhs, algTcFields = fieldsOfAlgTcRhs rhs, algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent, algTcGadtSyntax = gadt_syn } -- | Simpler specialization of 'mkAlgTyCon' for classes mkClassTyCon :: Name -> [TyConBinder] -> [Role] -> AlgTyConRhs -> Class -> Name -> TyCon mkClassTyCon name binders roles rhs clas tc_rep_name = mkAlgTyCon name binders constraintKind roles Nothing [] rhs (ClassTyCon clas tc_rep_name) False mkTupleTyCon :: Name -> [TyConBinder] -> Kind -- ^ Result kind of the 'TyCon' -> Arity -- ^ Arity of the tuple -> DataCon -> TupleSort -- ^ Whether the tuple is boxed or unboxed -> AlgTyConFlav -> TyCon mkTupleTyCon name binders res_kind arity con sort parent = AlgTyCon { tyConName = name, tyConUnique = nameUnique name, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, tyConArity = arity, tyConTyVars = binderVars binders, tcRoles = replicate arity Representational, tyConCType = Nothing, algTcStupidTheta = [], algTcRhs = TupleTyCon { data_con = con, tup_sort = sort }, algTcFields = emptyDFsEnv, algTcParent = parent, algTcGadtSyntax = False } -- | Makes a tycon suitable for use during type-checking. -- The only real need for this is for printing error messages during -- a recursive type/class type-checking knot. It has a kind because -- TcErrors sometimes calls typeKind. -- See also Note [Kind checking recursive type and class declarations] -- in TcTyClsDecls. mkTcTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind only -> Bool -- ^ Can this be unsaturated? -> [TyVar] -- ^ Scoped type variables, see Note [TcTyCon] -> TyCon mkTcTyCon name binders res_kind unsat scoped_tvs = TcTyCon { tyConUnique = getUnique name , tyConName = name , tyConTyVars = binderVars binders , tyConBinders = binders , tyConResKind = res_kind , tyConKind = mkTyConKind binders res_kind , tyConUnsat = unsat , tyConArity = length binders , tcTyConScopedTyVars = scoped_tvs } -- | Create an unlifted primitive 'TyCon', such as @Int#@ mkPrimTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> TyCon mkPrimTyCon name binders res_kind roles = mkPrimTyCon' name binders res_kind roles True (Just $ mkPrelTyConRepName name) -- | Kind constructors mkKindTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> Name -> TyCon mkKindTyCon name binders res_kind roles rep_nm = tc where tc = mkPrimTyCon' name binders res_kind roles False (Just rep_nm) -- | Create a lifted primitive 'TyCon' such as @RealWorld@ mkLiftedPrimTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> TyCon mkLiftedPrimTyCon name binders res_kind roles = mkPrimTyCon' name binders res_kind roles False (Just rep_nm) where rep_nm = mkPrelTyConRepName name mkPrimTyCon' :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> Bool -> Maybe TyConRepName -> TyCon mkPrimTyCon' name binders res_kind roles is_unlifted rep_nm = PrimTyCon { tyConName = name, tyConUnique = nameUnique name, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, tyConArity = length roles, tcRoles = roles, isUnlifted = is_unlifted, primRepName = rep_nm } -- | Create a type synonym 'TyCon' mkSynonymTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> Type -> TyCon mkSynonymTyCon name binders res_kind roles rhs = SynonymTyCon { tyConName = name, tyConUnique = nameUnique name, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, tyConArity = length binders, tyConTyVars = binderVars binders, tcRoles = roles, synTcRhs = rhs } -- | Create a type family 'TyCon' mkFamilyTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> Maybe Name -> FamTyConFlav -> Maybe Class -> Injectivity -> TyCon mkFamilyTyCon name binders res_kind resVar flav parent inj = FamilyTyCon { tyConUnique = nameUnique name , tyConName = name , tyConBinders = binders , tyConResKind = res_kind , tyConKind = mkTyConKind binders res_kind , tyConArity = length binders , tyConTyVars = binderVars binders , famTcResVar = resVar , famTcFlav = flav , famTcParent = parent , famTcInj = inj } -- | Create a promoted data constructor 'TyCon' -- Somewhat dodgily, we give it the same Name -- as the data constructor itself; when we pretty-print -- the TyCon we add a quote; see the Outputable TyCon instance mkPromotedDataCon :: DataCon -> Name -> TyConRepName -> [TyConBinder] -> Kind -> [Role] -> RuntimeRepInfo -> TyCon mkPromotedDataCon con name rep_name binders res_kind roles rep_info = PromotedDataCon { tyConUnique = nameUnique name, tyConName = name, tyConArity = length roles, tcRoles = roles, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, dataCon = con, tcRepName = rep_name, promDcRepInfo = rep_info } isFunTyCon :: TyCon -> Bool isFunTyCon (FunTyCon {}) = True isFunTyCon _ = False -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors) isAbstractTyCon :: TyCon -> Bool isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True isAbstractTyCon _ = False -- | Make an fake, abstract 'TyCon' from an existing one. -- Used when recovering from errors makeTyConAbstract :: TyCon -> TyCon makeTyConAbstract tc = mkTcTyCon (tyConName tc) (tyConBinders tc) (tyConResKind tc) (mightBeUnsaturatedTyCon tc) [{- no scoped vars -}] -- | Does this 'TyCon' represent something that cannot be defined in Haskell? isPrimTyCon :: TyCon -> Bool isPrimTyCon (PrimTyCon {}) = True isPrimTyCon _ = False -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can -- only be true for primitive and unboxed-tuple 'TyCon's isUnliftedTyCon :: TyCon -> Bool isUnliftedTyCon (PrimTyCon {isUnlifted = is_unlifted}) = is_unlifted isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } ) | TupleTyCon { tup_sort = sort } <- rhs = not (isBoxed (tupleSortBoxity sort)) isUnliftedTyCon _ = False -- | Returns @True@ if the supplied 'TyCon' resulted from either a -- @data@ or @newtype@ declaration isAlgTyCon :: TyCon -> Bool isAlgTyCon (AlgTyCon {}) = True isAlgTyCon _ = False -- | Returns @True@ for vanilla AlgTyCons -- that is, those created -- with a @data@ or @newtype@ declaration. isVanillaAlgTyCon :: TyCon -> Bool isVanillaAlgTyCon (AlgTyCon { algTcParent = VanillaAlgTyCon _ }) = True isVanillaAlgTyCon _ = False isDataTyCon :: TyCon -> Bool -- ^ Returns @True@ for data types that are /definitely/ represented by -- heap-allocated constructors. These are scrutinised by Core-level -- @case@ expressions, and they get info tables allocated for them. -- -- Generally, the function will be true for all @data@ types and false -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is -- not guaranteed to return @True@ in all cases that it could. -- -- NB: for a data type family, only the /instance/ 'TyCon's -- get an info table. The family declaration 'TyCon' does not isDataTyCon (AlgTyCon {algTcRhs = rhs}) = case rhs of TupleTyCon { tup_sort = sort } -> isBoxed (tupleSortBoxity sort) DataTyCon {} -> True NewTyCon {} -> False AbstractTyCon {} -> False -- We don't know, so return False isDataTyCon _ = False -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds -- (where X is the role passed in): -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2) -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X) -- See also Note [Decomposing equality] in TcCanonical isInjectiveTyCon :: TyCon -> Role -> Bool isInjectiveTyCon _ Phantom = False isInjectiveTyCon (FunTyCon {}) _ = True isInjectiveTyCon (AlgTyCon {}) Nominal = True isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational = isGenInjAlgRhs rhs isInjectiveTyCon (SynonymTyCon {}) _ = False isInjectiveTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True isInjectiveTyCon (FamilyTyCon { famTcInj = Injective inj }) _ = and inj isInjectiveTyCon (FamilyTyCon {}) _ = False isInjectiveTyCon (PrimTyCon {}) _ = True isInjectiveTyCon (PromotedDataCon {}) _ = True isInjectiveTyCon tc@(TcTyCon {}) _ = pprPanic "isInjectiveTyCon sees a TcTyCon" (ppr tc) -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds -- (where X is the role passed in): -- If (T tys ~X t), then (t's head ~X T). -- See also Note [Decomposing equality] in TcCanonical isGenerativeTyCon :: TyCon -> Role -> Bool isGenerativeTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True isGenerativeTyCon (FamilyTyCon {}) _ = False -- in all other cases, injectivity implies generativitiy isGenerativeTyCon tc r = isInjectiveTyCon tc r -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective -- with respect to representational equality? isGenInjAlgRhs :: AlgTyConRhs -> Bool isGenInjAlgRhs (TupleTyCon {}) = True isGenInjAlgRhs (DataTyCon {}) = True isGenInjAlgRhs (AbstractTyCon distinct) = distinct isGenInjAlgRhs (NewTyCon {}) = False -- | Is this 'TyCon' that for a @newtype@ isNewTyCon :: TyCon -> Bool isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True isNewTyCon _ = False -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands -- into, and (possibly) a coercion from the representation type to the @newtype@. -- Returns @Nothing@ if this is not possible. unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched) unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, algTcRhs = NewTyCon { nt_co = co, nt_rhs = rhs }}) = Just (tvs, rhs, co) unwrapNewTyCon_maybe _ = Nothing unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched) unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co, nt_etad_rhs = (tvs,rhs) }}) = Just (tvs, rhs, co) unwrapNewTyConEtad_maybe _ = Nothing isProductTyCon :: TyCon -> Bool -- True of datatypes or newtypes that have -- one, non-existential, data constructor -- See Note [Product types] isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of TupleTyCon {} -> True DataTyCon{ data_cons = [data_con] } -> null (dataConExTyVars data_con) NewTyCon {} -> True _ -> False isProductTyCon _ = False isDataProductTyCon_maybe :: TyCon -> Maybe DataCon -- True of datatypes (not newtypes) with -- one, vanilla, data constructor -- See Note [Product types] isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [con] } | null (dataConExTyVars con) -- non-existential -> Just con TupleTyCon { data_con = con } -> Just con _ -> Nothing isDataProductTyCon_maybe _ = Nothing {- Note [Product types] ~~~~~~~~~~~~~~~~~~~~~~~ A product type is * A data type (not a newtype) * With one, boxed data constructor * That binds no existential type variables The main point is that product types are amenable to unboxing for * Strict function calls; we can transform f (D a b) = e to fw a b = e via the worker/wrapper transformation. (Question: couldn't this work for existentials too?) * CPR for function results; we can transform f x y = let ... in D a b to fw x y = let ... in (# a, b #) Note that the data constructor /can/ have evidence arguments: equality constraints, type classes etc. So it can be GADT. These evidence arguments are simply value arguments, and should not get in the way. -} -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)? isTypeSynonymTyCon :: TyCon -> Bool isTypeSynonymTyCon (SynonymTyCon {}) = True isTypeSynonymTyCon _ = False -- As for newtypes, it is in some contexts important to distinguish between -- closed synonyms and synonym families, as synonym families have no unique -- right hand side to which a synonym family application can expand. -- -- | True iff we can decompose (T a b c) into ((T a b) c) -- I.e. is it injective and generative w.r.t nominal equality? -- That is, if (T a b) ~N d e f, is it always the case that -- (T ~N d), (a ~N e) and (b ~N f)? -- Specifically NOT true of synonyms (open and otherwise) -- -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98 -- type synonym, because you should probably have expanded it first -- But regardless, it's not decomposable mightBeUnsaturatedTyCon :: TyCon -> Bool mightBeUnsaturatedTyCon (SynonymTyCon {}) = False mightBeUnsaturatedTyCon (FamilyTyCon { famTcFlav = flav}) = isDataFamFlav flav mightBeUnsaturatedTyCon (TcTyCon { tyConUnsat = unsat }) = unsat mightBeUnsaturatedTyCon _other = True -- | Is this an algebraic 'TyCon' declared with the GADT syntax? isGadtSyntaxTyCon :: TyCon -> Bool isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res isGadtSyntaxTyCon _ = False -- | Is this an algebraic 'TyCon' which is just an enumeration of values? isEnumerationTyCon :: TyCon -> Bool -- See Note [Enumeration types] in TyCon isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs }) = case rhs of DataTyCon { is_enum = res } -> res TupleTyCon {} -> arity == 0 _ -> False isEnumerationTyCon _ = False -- | Is this a 'TyCon', synonym or otherwise, that defines a family? isFamilyTyCon :: TyCon -> Bool isFamilyTyCon (FamilyTyCon {}) = True isFamilyTyCon _ = False -- | Is this a 'TyCon', synonym or otherwise, that defines a family with -- instances? isOpenFamilyTyCon :: TyCon -> Bool isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav }) | OpenSynFamilyTyCon <- flav = True | DataFamilyTyCon {} <- flav = True isOpenFamilyTyCon _ = False -- | Is this a synonym 'TyCon' that can have may have further instances appear? isTypeFamilyTyCon :: TyCon -> Bool isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav) isTypeFamilyTyCon _ = False -- | Is this a synonym 'TyCon' that can have may have further instances appear? isDataFamilyTyCon :: TyCon -> Bool isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav isDataFamilyTyCon _ = False -- | Is this an open type family TyCon? isOpenTypeFamilyTyCon :: TyCon -> Bool isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True isOpenTypeFamilyTyCon _ = False -- | Is this a non-empty closed type family? Returns 'Nothing' for -- abstract or empty closed families. isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched) isClosedSynFamilyTyConWithAxiom_maybe (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing -- | Try to read the injectivity information from a FamilyTyCon. -- For every other TyCon this function panics. familyTyConInjectivityInfo :: TyCon -> Injectivity familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo" isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily isBuiltInSynFamTyCon_maybe (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops isBuiltInSynFamTyCon_maybe _ = Nothing isDataFamFlav :: FamTyConFlav -> Bool isDataFamFlav (DataFamilyTyCon {}) = True -- Data family isDataFamFlav _ = False -- Type synonym family -- | Are we able to extract information 'TyVar' to class argument list -- mapping from a given 'TyCon'? isTyConAssoc :: TyCon -> Bool isTyConAssoc tc = isJust (tyConAssoc_maybe tc) tyConAssoc_maybe :: TyCon -> Maybe Class tyConAssoc_maybe (FamilyTyCon { famTcParent = mb_cls }) = mb_cls tyConAssoc_maybe _ = Nothing -- The unit tycon didn't used to be classed as a tuple tycon -- but I thought that was silly so I've undone it -- If it can't be for some reason, it should be a AlgTyCon isTupleTyCon :: TyCon -> Bool -- ^ Does this 'TyCon' represent a tuple? -- -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they -- get spat into the interface file as tuple tycons, so I don't think -- it matters. isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True isTupleTyCon _ = False tyConTuple_maybe :: TyCon -> Maybe TupleSort tyConTuple_maybe (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort} <- rhs = Just sort tyConTuple_maybe _ = Nothing -- | Is this the 'TyCon' for an unboxed tuple? isUnboxedTupleTyCon :: TyCon -> Bool isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort } <- rhs = not (isBoxed (tupleSortBoxity sort)) isUnboxedTupleTyCon _ = False -- | Is this the 'TyCon' for a boxed tuple? isBoxedTupleTyCon :: TyCon -> Bool isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort } <- rhs = isBoxed (tupleSortBoxity sort) isBoxedTupleTyCon _ = False -- | Is this a PromotedDataCon? isPromotedDataCon :: TyCon -> Bool isPromotedDataCon (PromotedDataCon {}) = True isPromotedDataCon _ = False -- | Retrieves the promoted DataCon if this is a PromotedDataCon; isPromotedDataCon_maybe :: TyCon -> Maybe DataCon isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc isPromotedDataCon_maybe _ = Nothing -- | Is this tycon really meant for use at the kind level? That is, -- should it be permitted without -XDataKinds? isKindTyCon :: TyCon -> Bool isKindTyCon tc = getUnique tc `elementOfUniqSet` kindTyConKeys -- | These TyCons should be allowed at the kind level, even without -- -XDataKinds. kindTyConKeys :: UniqSet Unique kindTyConKeys = unionManyUniqSets ( mkUniqSet [ liftedTypeKindTyConKey, starKindTyConKey, unicodeStarKindTyConKey , constraintKindTyConKey, tYPETyConKey ] : map (mkUniqSet . tycon_with_datacons) [ runtimeRepTyCon , vecCountTyCon, vecElemTyCon ] ) where tycon_with_datacons tc = getUnique tc : map getUnique (tyConDataCons tc) isLiftedTypeKindTyConName :: Name -> Bool isLiftedTypeKindTyConName = (`hasKey` liftedTypeKindTyConKey) <||> (`hasKey` starKindTyConKey) <||> (`hasKey` unicodeStarKindTyConKey) -- | Identifies implicit tycons that, in particular, do not go into interface -- files (because they are implicitly reconstructed when the interface is -- read). -- -- Note that: -- -- * Associated families are implicit, as they are re-constructed from -- the class declaration in which they reside, and -- -- * Family instances are /not/ implicit as they represent the instance body -- (similar to a @dfun@ does that for a class instance). -- -- * Tuples are implicit iff they have a wired-in name -- (namely: boxed and unboxed tupeles are wired-in and implicit, -- but constraint tuples are not) isImplicitTyCon :: TyCon -> Bool isImplicitTyCon (FunTyCon {}) = True isImplicitTyCon (PrimTyCon {}) = True isImplicitTyCon (PromotedDataCon {}) = True isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name }) | TupleTyCon {} <- rhs = isWiredInName name | otherwise = False isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent isImplicitTyCon (SynonymTyCon {}) = False isImplicitTyCon tc@(TcTyCon {}) = pprPanic "isImplicitTyCon sees a TcTyCon" (ppr tc) tyConCType_maybe :: TyCon -> Maybe CType tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc tyConCType_maybe _ = Nothing -- | Is this a TcTyCon? (That is, one only used during type-checking?) isTcTyCon :: TyCon -> Bool isTcTyCon (TcTyCon {}) = True isTcTyCon _ = False {- ----------------------------------------------- -- Expand type-constructor applications ----------------------------------------------- -} expandSynTyCon_maybe :: TyCon -> [tyco] -- ^ Arguments to 'TyCon' -> Maybe ([(TyVar,tyco)], Type, [tyco]) -- ^ Returns a 'TyVar' substitution, the body -- type of the synonym (not yet substituted) -- and any arguments remaining from the -- application -- ^ Expand a type synonym application, if any expandSynTyCon_maybe tc tys | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs, tyConArity = arity } <- tc = case arity `compare` length tys of LT -> Just (tvs `zip` tys, rhs, drop arity tys) EQ -> Just (tvs `zip` tys, rhs, []) GT -> Nothing | otherwise = Nothing ---------------- -- | Check if the tycon actually refers to a proper `data` or `newtype` -- with user defined constructors rather than one from a class or other -- construction. isTyConWithSrcDataCons :: TyCon -> Bool isTyConWithSrcDataCons (AlgTyCon { algTcRhs = rhs, algTcParent = parent }) = case rhs of DataTyCon {} -> isSrcParent NewTyCon {} -> isSrcParent TupleTyCon {} -> isSrcParent _ -> False where isSrcParent = isNoParent parent isTyConWithSrcDataCons _ = False -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no -- constructors could be found tyConDataCons :: TyCon -> [DataCon] -- It's convenient for tyConDataCons to return the -- empty list for type synonyms etc tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` [] -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon' -- is the sort that can have any constructors (note: this does not include -- abstract algebraic types) tyConDataCons_maybe :: TyCon -> Maybe [DataCon] tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs}) = case rhs of DataTyCon { data_cons = cons } -> Just cons NewTyCon { data_con = con } -> Just [con] TupleTyCon { data_con = con } -> Just [con] _ -> Nothing tyConDataCons_maybe _ = Nothing -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ -- type with one alternative, a tuple type or a @newtype@ then that constructor -- is returned. If the 'TyCon' has more than one constructor, or represents a -- primitive or function type constructor then @Nothing@ is returned. In any -- other case, the function panics tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [c] } -> Just c TupleTyCon { data_con = c } -> Just c NewTyCon { data_con = c } -> Just c _ -> Nothing tyConSingleDataCon_maybe _ = Nothing tyConSingleDataCon :: TyCon -> DataCon tyConSingleDataCon tc = case tyConSingleDataCon_maybe tc of Just c -> c Nothing -> pprPanic "tyConDataCon" (ppr tc) tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon -- Returns (Just con) for single-constructor -- *algebraic* data types *not* newtypes tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [c] } -> Just c TupleTyCon { data_con = c } -> Just c _ -> Nothing tyConSingleAlgDataCon_maybe _ = Nothing -- | Determine the number of value constructors a 'TyCon' has. Panics if the -- 'TyCon' is not algebraic or a tuple tyConFamilySize :: TyCon -> Int tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = cons } -> length cons NewTyCon {} -> 1 TupleTyCon {} -> 1 _ -> pprPanic "tyConFamilySize 1" (ppr tc) tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc) -- | Extract an 'AlgTyConRhs' with information about data constructors from an -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon' algTyConRhs :: TyCon -> AlgTyConRhs algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs algTyConRhs other = pprPanic "algTyConRhs" (ppr other) -- | Extract type variable naming the result of injective type family tyConFamilyResVar_maybe :: TyCon -> Maybe Name tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res tyConFamilyResVar_maybe _ = Nothing -- | Get the list of roles for the type parameters of a TyCon tyConRoles :: TyCon -> [Role] -- See also Note [TyCon Role signatures] tyConRoles tc = case tc of { FunTyCon {} -> const_role Representational ; AlgTyCon { tcRoles = roles } -> roles ; SynonymTyCon { tcRoles = roles } -> roles ; FamilyTyCon {} -> const_role Nominal ; PrimTyCon { tcRoles = roles } -> roles ; PromotedDataCon { tcRoles = roles } -> roles ; TcTyCon {} -> pprPanic "tyConRoles sees a TcTyCon" (ppr tc) } where const_role r = replicate (tyConArity tc) r -- | Extract the bound type variables and type expansion of a type synonym -- 'TyCon'. Panics if the 'TyCon' is not a synonym newTyConRhs :: TyCon -> ([TyVar], Type) newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs) newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon) -- | The number of type parameters that need to be passed to a newtype to -- resolve it. May be less than in the definition if it can be eta-contracted. newTyConEtadArity :: TyCon -> Int newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = length (fst tvs_rhs) newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon) -- | Extract the bound type variables and type expansion of an eta-contracted -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym newTyConEtadRhs :: TyCon -> ([TyVar], Type) newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon) -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to -- construct something with the @newtype@s type from its representation type -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns -- @Nothing@ newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched) newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co newTyConCo_maybe _ = Nothing newTyConCo :: TyCon -> CoAxiom Unbranched newTyConCo tc = case newTyConCo_maybe tc of Just co -> co Nothing -> pprPanic "newTyConCo" (ppr tc) newTyConDataCon_maybe :: TyCon -> Maybe DataCon newTyConDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }}) = Just con newTyConDataCon_maybe _ = Nothing -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration -- @data Eq a => T a ...@ tyConStupidTheta :: TyCon -> [PredType] tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon) -- | Extract the 'TyVar's bound by a vanilla type synonym -- and the corresponding (unsubstituted) right hand side. synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type) synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty}) = Just (tyvars, ty) synTyConDefn_maybe _ = Nothing -- | Extract the information pertaining to the right hand side of a type synonym -- (@type@) declaration. synTyConRhs_maybe :: TyCon -> Maybe Type synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs synTyConRhs_maybe _ = Nothing -- | Extract the flavour of a type family (with all the extra information that -- it carries) famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav famTyConFlav_maybe _ = Nothing -- | Is this 'TyCon' that for a class instance? isClassTyCon :: TyCon -> Bool isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True isClassTyCon _ = False -- | If this 'TyCon' is that for a class instance, return the class it is for. -- Otherwise returns @Nothing@ tyConClass_maybe :: TyCon -> Maybe Class tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas tyConClass_maybe _ = Nothing -- | Return the associated types of the 'TyCon', if any tyConATs :: TyCon -> [TyCon] tyConATs (AlgTyCon {algTcParent = ClassTyCon clas _}) = classATs clas tyConATs _ = [] ---------------------------------------------------------------------------- -- | Is this 'TyCon' that for a data family instance? isFamInstTyCon :: TyCon -> Bool isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} }) = True isFamInstTyCon _ = False tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched) tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts }) = Just (f, ts, ax) tyConFamInstSig_maybe _ = Nothing -- | If this 'TyCon' is that of a data family instance, return the family in question -- and the instance types. Otherwise, return @Nothing@ tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type]) tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts }) = Just (f, ts) tyConFamInst_maybe _ = Nothing -- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which -- represents a coercion identifying the representation type with the type -- instance family. Otherwise, return @Nothing@ tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched) tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ }) = Just ax tyConFamilyCoercion_maybe _ = Nothing -- | Extract any 'RuntimeRepInfo' from this TyCon tyConRuntimeRepInfo :: TyCon -> RuntimeRepInfo tyConRuntimeRepInfo (PromotedDataCon { promDcRepInfo = rri }) = rri tyConRuntimeRepInfo _ = NoRRI -- could panic in that second case. But Douglas Adams told me not to. {- ************************************************************************ * * \subsection[TyCon-instances]{Instance declarations for @TyCon@} * * ************************************************************************ @TyCon@s are compared by comparing their @Unique@s. -} instance Eq TyCon where a == b = getUnique a == getUnique b a /= b = getUnique a /= getUnique b instance Uniquable TyCon where getUnique tc = tyConUnique tc instance Outputable TyCon where -- At the moment a promoted TyCon has the same Name as its -- corresponding TyCon, so we add the quote to distinguish it here ppr tc = pprPromotionQuote tc <> ppr (tyConName tc) tyConFlavour :: TyCon -> String tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs }) | ClassTyCon _ _ <- parent = "class" | otherwise = case rhs of TupleTyCon { tup_sort = sort } | isBoxed (tupleSortBoxity sort) -> "tuple" | otherwise -> "unboxed tuple" DataTyCon {} -> "data type" NewTyCon {} -> "newtype" AbstractTyCon {} -> "abstract type" tyConFlavour (FamilyTyCon { famTcFlav = flav }) | isDataFamFlav flav = "data family" | otherwise = "type family" tyConFlavour (SynonymTyCon {}) = "type synonym" tyConFlavour (FunTyCon {}) = "built-in type" tyConFlavour (PrimTyCon {}) = "built-in type" tyConFlavour (PromotedDataCon {}) = "promoted data constructor" tyConFlavour tc@(TcTyCon {}) = pprPanic "tyConFlavour sees a TcTyCon" (ppr tc) pprPromotionQuote :: TyCon -> SDoc -- Promoted data constructors already have a tick in their OccName pprPromotionQuote tc = case tc of PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types _ -> empty instance NamedThing TyCon where getName = tyConName instance Data.Data TyCon where -- don't traverse? toConstr _ = abstractConstr "TyCon" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "TyCon" instance Binary Injectivity where put_ bh NotInjective = putByte bh 0 put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs get bh = do { h <- getByte bh ; case h of 0 -> return NotInjective _ -> do { xs <- get bh ; return (Injective xs) } } {- ************************************************************************ * * Walking over recursive TyCons * * ************************************************************************ Note [Expanding newtypes and products] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When expanding a type to expose a data-type constructor, we need to be careful about newtypes, lest we fall into an infinite loop. Here are the key examples: newtype Id x = MkId x newtype Fix f = MkFix (f (Fix f)) newtype T = MkT (T -> T) Type Expansion -------------------------- T T -> T Fix Maybe Maybe (Fix Maybe) Id (Id Int) Int Fix Id NO NO NO Notice that * We can expand T, even though it's recursive. * We can expand Id (Id Int), even though the Id shows up twice at the outer level, because Id is non-recursive So, when expanding, we keep track of when we've seen a recursive newtype at outermost level; and bale out if we see it again. We sometimes want to do the same for product types, so that the strictness analyser doesn't unbox infinitely deeply. More precisely, we keep a *count* of how many times we've seen it. This is to account for data instance T (a,b) = MkT (T a) (T b) Then (Trac #10482) if we have a type like T (Int,(Int,(Int,(Int,Int)))) we can still unbox deeply enough during strictness analysis. We have to treat T as potentially recursive, but it's still good to be able to unwrap multiple layers. The function that manages all this is checkRecTc. -} data RecTcChecker = RC !Int (NameEnv Int) -- The upper bound, and the number of times -- we have encountered each TyCon initRecTc :: RecTcChecker -- Intialise with a fixed max bound of 100 -- We should probably have a flag for this initRecTc = RC 100 emptyNameEnv checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker -- Nothing => Recursion detected -- Just rec_tcs => Keep going checkRecTc (RC bound rec_nts) tc = case lookupNameEnv rec_nts tc_name of Just n | n >= bound -> Nothing | otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1))) Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1)) where tc_name = tyConName tc
vTurbine/ghc
compiler/types/TyCon.hs
Haskell
bsd-3-clause
89,529
{-# LANGUAGE TypeOperators #-} module Main where import Control.Applicative ((<*>)) import Data.OI hiding (openFile) import System.IO (IOMode (..), Handle) import qualified System.IO as IO import Prelude hiding (readFile, writeFile) main :: IO () main = runInteraction pmain pmain :: (([String],Either ((Handle, String), [(Handle, String)]) [(Handle, String)]), (Handle, ())) :-> () pmain = args |/| ((choiceOI (lines . readFile "files2" |/| zipWithOI readFile) . zipWithOI readFile) <*> null) |/| writeFile "output2.txt" . concatMap textproc textproc :: String -> String textproc = id readFile :: FilePath -> (Handle, String) :-> String readFile f = openFile f ReadMode |/| hGetContents writeFile :: FilePath -> String -> (Handle, ()) :-> () writeFile f cs = openFile f WriteMode |/| flip hPutStr cs openFile :: FilePath -> IOMode -> Handle :-> Handle openFile = (iooi .) . IO.openFile hGetContents :: Handle -> String :-> String hGetContents = iooi . IO.hGetContents hPutStr :: Handle -> String -> () :-> () hPutStr = (iooi .) . IO.hPutStr
nobsun/oi
sample/cats2.hs
Haskell
bsd-3-clause
1,078
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans -fno-warn-incomplete-patterns -fno-warn-deprecations -fno-warn-unused-binds #-} --FIXME module UnitTests.Distribution.Version (versionTests) where import Distribution.Version import Distribution.Text import Text.PrettyPrint as Disp (text, render, parens, hcat ,punctuate, int, char, (<>), (<+>)) import Test.Tasty import Test.Tasty.QuickCheck import qualified Test.Laws as Laws #if !MIN_VERSION_QuickCheck(2,9,0) import Test.QuickCheck.Utils #endif import Control.Monad (liftM, liftM2) import Data.Maybe (isJust, fromJust) import Data.List (sort, sortBy, nub) import Data.Ord (comparing) versionTests :: [TestTree] versionTests = zipWith (\n p -> testProperty ("Range Property " ++ show n) p) [1::Int ..] -- properties to validate the test framework [ property prop_nonNull , property prop_gen_intervals1 , property prop_gen_intervals2 --, property prop_equivalentVersionRange --FIXME: runs out of test cases , property prop_intermediateVersion -- the basic syntactic version range functions , property prop_anyVersion , property prop_noVersion , property prop_thisVersion , property prop_notThisVersion , property prop_laterVersion , property prop_orLaterVersion , property prop_earlierVersion , property prop_orEarlierVersion , property prop_unionVersionRanges , property prop_intersectVersionRanges , property prop_differenceVersionRanges , property prop_invertVersionRange , property prop_withinVersion , property prop_foldVersionRange , property prop_foldVersionRange' -- the semantic query functions --, property prop_isAnyVersion1 --FIXME: runs out of test cases --, property prop_isAnyVersion2 --FIXME: runs out of test cases --, property prop_isNoVersion --FIXME: runs out of test cases --, property prop_isSpecificVersion1 --FIXME: runs out of test cases --, property prop_isSpecificVersion2 --FIXME: runs out of test cases , property prop_simplifyVersionRange1 , property prop_simplifyVersionRange1' --, property prop_simplifyVersionRange2 --FIXME: runs out of test cases --, property prop_simplifyVersionRange2' --FIXME: runs out of test cases --, property prop_simplifyVersionRange2'' --FIXME: actually wrong -- converting between version ranges and version intervals , property prop_to_intervals --, property prop_to_intervals_canonical --FIXME: runs out of test cases --, property prop_to_intervals_canonical' --FIXME: runs out of test cases , property prop_from_intervals , property prop_to_from_intervals , property prop_from_to_intervals , property prop_from_to_intervals' -- union and intersection of version intervals , property prop_unionVersionIntervals , property prop_unionVersionIntervals_idempotent , property prop_unionVersionIntervals_commutative , property prop_unionVersionIntervals_associative , property prop_intersectVersionIntervals , property prop_intersectVersionIntervals_idempotent , property prop_intersectVersionIntervals_commutative , property prop_intersectVersionIntervals_associative , property prop_union_intersect_distributive , property prop_intersect_union_distributive -- inversion of version intervals , property prop_invertVersionIntervals , property prop_invertVersionIntervalsTwice ] -- parseTests :: [TestTree] -- parseTests = -- zipWith (\n p -> testProperty ("Parse Property " ++ show n) p) [1::Int ..] -- -- parsing and pretty printing -- [ -- property prop_parse_disp1 --FIXME: actually wrong -- -- These are also wrong, see -- -- https://github.com/haskell/cabal/issues/3037#issuecomment-177671011 -- -- property prop_parse_disp2 -- -- , property prop_parse_disp3 -- -- , property prop_parse_disp4 -- -- , property prop_parse_disp5 -- ] #if !MIN_VERSION_QuickCheck(2,9,0) instance Arbitrary Version where arbitrary = do branch <- smallListOf1 $ frequency [(3, return 0) ,(3, return 1) ,(2, return 2) ,(1, return 3)] return (Version branch []) -- deliberate [] where smallListOf1 = adjustSize (\n -> min 5 (n `div` 3)) . listOf1 shrink (Version branch []) = [ Version branch' [] | branch' <- shrink branch, not (null branch') ] shrink (Version branch _tags) = [ Version branch [] ] #endif instance Arbitrary VersionRange where arbitrary = sized verRangeExp where verRangeExp n = frequency $ [ (2, return anyVersion) , (1, liftM thisVersion arbitrary) , (1, liftM laterVersion arbitrary) , (1, liftM orLaterVersion arbitrary) , (1, liftM orLaterVersion' arbitrary) , (1, liftM earlierVersion arbitrary) , (1, liftM orEarlierVersion arbitrary) , (1, liftM orEarlierVersion' arbitrary) , (1, liftM withinVersion arbitrary) , (2, liftM VersionRangeParens arbitrary) ] ++ if n == 0 then [] else [ (2, liftM2 unionVersionRanges verRangeExp2 verRangeExp2) , (2, liftM2 intersectVersionRanges verRangeExp2 verRangeExp2) ] where verRangeExp2 = verRangeExp (n `div` 2) orLaterVersion' v = unionVersionRanges (LaterVersion v) (ThisVersion v) orEarlierVersion' v = unionVersionRanges (EarlierVersion v) (ThisVersion v) --------------------------- -- VersionRange properties -- prop_nonNull :: Version -> Bool prop_nonNull = not . null . versionBranch prop_anyVersion :: Version -> Bool prop_anyVersion v' = withinRange v' anyVersion == True prop_noVersion :: Version -> Bool prop_noVersion v' = withinRange v' noVersion == False prop_thisVersion :: Version -> Version -> Bool prop_thisVersion v v' = withinRange v' (thisVersion v) == (v' == v) prop_notThisVersion :: Version -> Version -> Bool prop_notThisVersion v v' = withinRange v' (notThisVersion v) == (v' /= v) prop_laterVersion :: Version -> Version -> Bool prop_laterVersion v v' = withinRange v' (laterVersion v) == (v' > v) prop_orLaterVersion :: Version -> Version -> Bool prop_orLaterVersion v v' = withinRange v' (orLaterVersion v) == (v' >= v) prop_earlierVersion :: Version -> Version -> Bool prop_earlierVersion v v' = withinRange v' (earlierVersion v) == (v' < v) prop_orEarlierVersion :: Version -> Version -> Bool prop_orEarlierVersion v v' = withinRange v' (orEarlierVersion v) == (v' <= v) prop_unionVersionRanges :: VersionRange -> VersionRange -> Version -> Bool prop_unionVersionRanges vr1 vr2 v' = withinRange v' (unionVersionRanges vr1 vr2) == (withinRange v' vr1 || withinRange v' vr2) prop_intersectVersionRanges :: VersionRange -> VersionRange -> Version -> Bool prop_intersectVersionRanges vr1 vr2 v' = withinRange v' (intersectVersionRanges vr1 vr2) == (withinRange v' vr1 && withinRange v' vr2) prop_differenceVersionRanges :: VersionRange -> VersionRange -> Version -> Bool prop_differenceVersionRanges vr1 vr2 v' = withinRange v' (differenceVersionRanges vr1 vr2) == (withinRange v' vr1 && not (withinRange v' vr2)) prop_invertVersionRange :: VersionRange -> Version -> Bool prop_invertVersionRange vr v' = withinRange v' (invertVersionRange vr) == not (withinRange v' vr) prop_withinVersion :: Version -> Version -> Bool prop_withinVersion v v' = withinRange v' (withinVersion v) == (v' >= v && v' < upper v) where upper (Version lower t) = Version (init lower ++ [last lower + 1]) t prop_foldVersionRange :: VersionRange -> Bool prop_foldVersionRange range = expandWildcard range == foldVersionRange anyVersion thisVersion laterVersion earlierVersion unionVersionRanges intersectVersionRanges range where expandWildcard (WildcardVersion v) = intersectVersionRanges (orLaterVersion v) (earlierVersion (upper v)) where upper (Version lower t) = Version (init lower ++ [last lower + 1]) t expandWildcard (UnionVersionRanges v1 v2) = UnionVersionRanges (expandWildcard v1) (expandWildcard v2) expandWildcard (IntersectVersionRanges v1 v2) = IntersectVersionRanges (expandWildcard v1) (expandWildcard v2) expandWildcard (VersionRangeParens v) = expandWildcard v expandWildcard v = v prop_foldVersionRange' :: VersionRange -> Bool prop_foldVersionRange' range = canonicalise range == foldVersionRange' anyVersion thisVersion laterVersion earlierVersion orLaterVersion orEarlierVersion (\v _ -> withinVersion v) (\v _ -> majorBoundVersion v) unionVersionRanges intersectVersionRanges id range where canonicalise (UnionVersionRanges (LaterVersion v) (ThisVersion v')) | v == v' = UnionVersionRanges (ThisVersion v') (LaterVersion v) canonicalise (UnionVersionRanges (EarlierVersion v) (ThisVersion v')) | v == v' = UnionVersionRanges (ThisVersion v') (EarlierVersion v) canonicalise (UnionVersionRanges v1 v2) = UnionVersionRanges (canonicalise v1) (canonicalise v2) canonicalise (IntersectVersionRanges v1 v2) = IntersectVersionRanges (canonicalise v1) (canonicalise v2) canonicalise (VersionRangeParens v) = canonicalise v canonicalise v = v prop_isAnyVersion1 :: VersionRange -> Version -> Property prop_isAnyVersion1 range version = isAnyVersion range ==> withinRange version range prop_isAnyVersion2 :: VersionRange -> Property prop_isAnyVersion2 range = isAnyVersion range ==> foldVersionRange True (\_ -> False) (\_ -> False) (\_ -> False) (\_ _ -> False) (\_ _ -> False) (simplifyVersionRange range) prop_isNoVersion :: VersionRange -> Version -> Property prop_isNoVersion range version = isNoVersion range ==> not (withinRange version range) prop_isSpecificVersion1 :: VersionRange -> NonEmptyList Version -> Property prop_isSpecificVersion1 range (NonEmpty versions) = isJust version && not (null versions') ==> allEqual (fromJust version : versions') where version = isSpecificVersion range versions' = filter (`withinRange` range) versions allEqual xs = and (zipWith (==) xs (tail xs)) prop_isSpecificVersion2 :: VersionRange -> Property prop_isSpecificVersion2 range = isJust version ==> foldVersionRange Nothing Just (\_ -> Nothing) (\_ -> Nothing) (\_ _ -> Nothing) (\_ _ -> Nothing) (simplifyVersionRange range) == version where version = isSpecificVersion range -- | 'simplifyVersionRange' is a semantic identity on 'VersionRange'. -- prop_simplifyVersionRange1 :: VersionRange -> Version -> Bool prop_simplifyVersionRange1 range version = withinRange version range == withinRange version (simplifyVersionRange range) prop_simplifyVersionRange1' :: VersionRange -> Bool prop_simplifyVersionRange1' range = range `equivalentVersionRange` (simplifyVersionRange range) -- | 'simplifyVersionRange' produces a canonical form for ranges with -- equivalent semantics. -- prop_simplifyVersionRange2 :: VersionRange -> VersionRange -> Version -> Property prop_simplifyVersionRange2 r r' v = r /= r' && simplifyVersionRange r == simplifyVersionRange r' ==> withinRange v r == withinRange v r' prop_simplifyVersionRange2' :: VersionRange -> VersionRange -> Property prop_simplifyVersionRange2' r r' = r /= r' && simplifyVersionRange r == simplifyVersionRange r' ==> r `equivalentVersionRange` r' --FIXME: see equivalentVersionRange for details prop_simplifyVersionRange2'' :: VersionRange -> VersionRange -> Property prop_simplifyVersionRange2'' r r' = r /= r' && r `equivalentVersionRange` r' ==> simplifyVersionRange r == simplifyVersionRange r' || isNoVersion r || isNoVersion r' -------------------- -- VersionIntervals -- -- | Generating VersionIntervals -- -- This is a tad tricky as VersionIntervals is an abstract type, so we first -- make a local type for generating the internal representation. Then we check -- that this lets us construct valid 'VersionIntervals'. -- newtype VersionIntervals' = VersionIntervals' [VersionInterval] deriving (Eq, Show) instance Arbitrary VersionIntervals' where arbitrary = do ubound <- arbitrary bounds <- arbitrary let intervals = mergeTouching . map fixEmpty . replaceUpper ubound . pairs . sortBy (comparing fst) $ bounds return (VersionIntervals' intervals) where pairs ((l, lb):(u, ub):bs) = (LowerBound l lb, UpperBound u ub) : pairs bs pairs _ = [] replaceUpper NoUpperBound [(l,_)] = [(l, NoUpperBound)] replaceUpper NoUpperBound (i:is) = i : replaceUpper NoUpperBound is replaceUpper _ is = is -- merge adjacent intervals that touch mergeTouching (i1@(l,u):i2@(l',u'):is) | doesNotTouch u l' = i1 : mergeTouching (i2:is) | otherwise = mergeTouching ((l,u'):is) mergeTouching is = is doesNotTouch :: UpperBound -> LowerBound -> Bool doesNotTouch NoUpperBound _ = False doesNotTouch (UpperBound u ub) (LowerBound l lb) = u < l || (u == l && ub == ExclusiveBound && lb == ExclusiveBound) fixEmpty (LowerBound l _, UpperBound u _) | l == u = (LowerBound l InclusiveBound, UpperBound u InclusiveBound) fixEmpty i = i shrink (VersionIntervals' intervals) = [ VersionIntervals' intervals' | intervals' <- shrink intervals ] instance Arbitrary Bound where arbitrary = elements [ExclusiveBound, InclusiveBound] instance Arbitrary LowerBound where arbitrary = liftM2 LowerBound arbitrary arbitrary instance Arbitrary UpperBound where arbitrary = oneof [return NoUpperBound ,liftM2 UpperBound arbitrary arbitrary] -- | Check that our VersionIntervals' arbitrary instance generates intervals -- that satisfies the invariant. -- prop_gen_intervals1 :: VersionIntervals' -> Bool prop_gen_intervals1 (VersionIntervals' intervals) = isJust (mkVersionIntervals intervals) instance Arbitrary VersionIntervals where arbitrary = do VersionIntervals' intervals <- arbitrary case mkVersionIntervals intervals of Just xs -> return xs -- | Check that constructing our intervals type and converting it to a -- 'VersionRange' and then into the true intervals type gives us back -- the exact same sequence of intervals. This tells us that our arbitrary -- instance for 'VersionIntervals'' is ok. -- prop_gen_intervals2 :: VersionIntervals' -> Bool prop_gen_intervals2 (VersionIntervals' intervals') = asVersionIntervals (fromVersionIntervals intervals) == intervals' where Just intervals = mkVersionIntervals intervals' -- | Check that 'VersionIntervals' models 'VersionRange' via -- 'toVersionIntervals'. -- prop_to_intervals :: VersionRange -> Version -> Bool prop_to_intervals range version = withinRange version range == withinIntervals version intervals where intervals = toVersionIntervals range -- | Check that semantic equality on 'VersionRange's is the same as converting -- to 'VersionIntervals' and doing syntactic equality. -- prop_to_intervals_canonical :: VersionRange -> VersionRange -> Property prop_to_intervals_canonical r r' = r /= r' && r `equivalentVersionRange` r' ==> toVersionIntervals r == toVersionIntervals r' prop_to_intervals_canonical' :: VersionRange -> VersionRange -> Property prop_to_intervals_canonical' r r' = r /= r' && toVersionIntervals r == toVersionIntervals r' ==> r `equivalentVersionRange` r' -- | Check that 'VersionIntervals' models 'VersionRange' via -- 'fromVersionIntervals'. -- prop_from_intervals :: VersionIntervals -> Version -> Bool prop_from_intervals intervals version = withinRange version range == withinIntervals version intervals where range = fromVersionIntervals intervals -- | @'toVersionIntervals' . 'fromVersionIntervals'@ is an exact identity on -- 'VersionIntervals'. -- prop_to_from_intervals :: VersionIntervals -> Bool prop_to_from_intervals intervals = toVersionIntervals (fromVersionIntervals intervals) == intervals -- | @'fromVersionIntervals' . 'toVersionIntervals'@ is a semantic identity on -- 'VersionRange', though not necessarily a syntactic identity. -- prop_from_to_intervals :: VersionRange -> Bool prop_from_to_intervals range = range' `equivalentVersionRange` range where range' = fromVersionIntervals (toVersionIntervals range) -- | Equivalent of 'prop_from_to_intervals' -- prop_from_to_intervals' :: VersionRange -> Version -> Bool prop_from_to_intervals' range version = withinRange version range' == withinRange version range where range' = fromVersionIntervals (toVersionIntervals range) -- | The semantics of 'unionVersionIntervals' is (||). -- prop_unionVersionIntervals :: VersionIntervals -> VersionIntervals -> Version -> Bool prop_unionVersionIntervals is1 is2 v = withinIntervals v (unionVersionIntervals is1 is2) == (withinIntervals v is1 || withinIntervals v is2) -- | 'unionVersionIntervals' is idempotent -- prop_unionVersionIntervals_idempotent :: VersionIntervals -> Bool prop_unionVersionIntervals_idempotent = Laws.idempotent_binary unionVersionIntervals -- | 'unionVersionIntervals' is commutative -- prop_unionVersionIntervals_commutative :: VersionIntervals -> VersionIntervals -> Bool prop_unionVersionIntervals_commutative = Laws.commutative unionVersionIntervals -- | 'unionVersionIntervals' is associative -- prop_unionVersionIntervals_associative :: VersionIntervals -> VersionIntervals -> VersionIntervals -> Bool prop_unionVersionIntervals_associative = Laws.associative unionVersionIntervals -- | The semantics of 'intersectVersionIntervals' is (&&). -- prop_intersectVersionIntervals :: VersionIntervals -> VersionIntervals -> Version -> Bool prop_intersectVersionIntervals is1 is2 v = withinIntervals v (intersectVersionIntervals is1 is2) == (withinIntervals v is1 && withinIntervals v is2) -- | 'intersectVersionIntervals' is idempotent -- prop_intersectVersionIntervals_idempotent :: VersionIntervals -> Bool prop_intersectVersionIntervals_idempotent = Laws.idempotent_binary intersectVersionIntervals -- | 'intersectVersionIntervals' is commutative -- prop_intersectVersionIntervals_commutative :: VersionIntervals -> VersionIntervals -> Bool prop_intersectVersionIntervals_commutative = Laws.commutative intersectVersionIntervals -- | 'intersectVersionIntervals' is associative -- prop_intersectVersionIntervals_associative :: VersionIntervals -> VersionIntervals -> VersionIntervals -> Bool prop_intersectVersionIntervals_associative = Laws.associative intersectVersionIntervals -- | 'unionVersionIntervals' distributes over 'intersectVersionIntervals' -- prop_union_intersect_distributive :: Property prop_union_intersect_distributive = Laws.distributive_left unionVersionIntervals intersectVersionIntervals .&. Laws.distributive_right unionVersionIntervals intersectVersionIntervals -- | 'intersectVersionIntervals' distributes over 'unionVersionIntervals' -- prop_intersect_union_distributive :: Property prop_intersect_union_distributive = Laws.distributive_left intersectVersionIntervals unionVersionIntervals .&. Laws.distributive_right intersectVersionIntervals unionVersionIntervals -- | The semantics of 'invertVersionIntervals' is 'not'. -- prop_invertVersionIntervals :: VersionIntervals -> Version -> Bool prop_invertVersionIntervals vi v = withinIntervals v (invertVersionIntervals vi) == not (withinIntervals v vi) -- | Double application of 'invertVersionIntervals' is the identity function prop_invertVersionIntervalsTwice :: VersionIntervals -> Bool prop_invertVersionIntervalsTwice vi = invertVersionIntervals (invertVersionIntervals vi) == vi -------------------------------- -- equivalentVersionRange helper prop_equivalentVersionRange :: VersionRange -> VersionRange -> Version -> Property prop_equivalentVersionRange range range' version = equivalentVersionRange range range' && range /= range' ==> withinRange version range == withinRange version range' --FIXME: this is wrong. consider version ranges "<=1" and "<1.0" -- this algorithm cannot distinguish them because there is no version -- that is included by one that is excluded by the other. -- Alternatively we must reconsider the semantics of '<' and '<=' -- in version ranges / version intervals. Perhaps the canonical -- representation should use just < v and interpret "<= v" as "< v.0". equivalentVersionRange :: VersionRange -> VersionRange -> Bool equivalentVersionRange vr1 vr2 = let allVersionsUsed = nub (sort (versionsUsed vr1 ++ versionsUsed vr2)) minPoint = Version [0] [] maxPoint | null allVersionsUsed = minPoint | otherwise = case maximum allVersionsUsed of Version vs _ -> Version (vs ++ [1]) [] probeVersions = minPoint : maxPoint : intermediateVersions allVersionsUsed in all (\v -> withinRange v vr1 == withinRange v vr2) probeVersions where versionsUsed = foldVersionRange [] (\x->[x]) (\x->[x]) (\x->[x]) (++) (++) intermediateVersions (v1:v2:vs) = v1 : intermediateVersion v1 v2 : intermediateVersions (v2:vs) intermediateVersions vs = vs intermediateVersion :: Version -> Version -> Version intermediateVersion v1 v2 | v1 >= v2 = error "intermediateVersion: v1 >= v2" intermediateVersion (Version v1 _) (Version v2 _) = Version (intermediateList v1 v2) [] where intermediateList :: [Int] -> [Int] -> [Int] intermediateList [] (_:_) = [0] intermediateList (x:xs) (y:ys) | x < y = x : xs ++ [0] | otherwise = x : intermediateList xs ys prop_intermediateVersion :: Version -> Version -> Property prop_intermediateVersion v1 v2 = (v1 /= v2) && not (adjacentVersions v1 v2) ==> if v1 < v2 then let v = intermediateVersion v1 v2 in (v1 < v && v < v2) else let v = intermediateVersion v2 v1 in v1 > v && v > v2 adjacentVersions :: Version -> Version -> Bool adjacentVersions (Version v1 _) (Version v2 _) = v1 ++ [0] == v2 || v2 ++ [0] == v1 -------------------------------- -- Parsing and pretty printing -- prop_parse_disp1 :: VersionRange -> Bool prop_parse_disp1 vr = fmap stripParens (simpleParse (display vr)) == Just (canonicalise vr) where canonicalise = swizzle . swap swizzle (UnionVersionRanges (UnionVersionRanges v1 v2) v3) | not (isOrLaterVersion v1 v2) && not (isOrEarlierVersion v1 v2) = swizzle (UnionVersionRanges v1 (UnionVersionRanges v2 v3)) swizzle (IntersectVersionRanges (IntersectVersionRanges v1 v2) v3) = swizzle (IntersectVersionRanges v1 (IntersectVersionRanges v2 v3)) swizzle (UnionVersionRanges v1 v2) = UnionVersionRanges (swizzle v1) (swizzle v2) swizzle (IntersectVersionRanges v1 v2) = IntersectVersionRanges (swizzle v1) (swizzle v2) swizzle (VersionRangeParens v) = swizzle v swizzle v = v isOrLaterVersion (ThisVersion v) (LaterVersion v') = v == v' isOrLaterVersion _ _ = False isOrEarlierVersion (ThisVersion v) (EarlierVersion v') = v == v' isOrEarlierVersion _ _ = False swap = foldVersionRange' anyVersion thisVersion laterVersion earlierVersion orLaterVersion orEarlierVersion (\v _ -> withinVersion v) (\v _ -> MajorBoundVersion v) unionVersionRanges intersectVersionRanges id stripParens :: VersionRange -> VersionRange stripParens (VersionRangeParens v) = stripParens v stripParens (UnionVersionRanges v1 v2) = UnionVersionRanges (stripParens v1) (stripParens v2) stripParens (IntersectVersionRanges v1 v2) = IntersectVersionRanges (stripParens v1) (stripParens v2) stripParens v = v prop_parse_disp2 :: VersionRange -> Property prop_parse_disp2 vr = let b = fmap (display :: VersionRange -> String) (simpleParse (display vr)) a = Just (display vr) in counterexample ("Expected: " ++ show a) $ counterexample ("But got: " ++ show b) $ b == a prop_parse_disp3 :: VersionRange -> Property prop_parse_disp3 vr = let a = Just (display vr) b = fmap displayRaw (simpleParse (display vr)) in counterexample ("Expected: " ++ show a) $ counterexample ("But got: " ++ show b) $ b == a prop_parse_disp4 :: VersionRange -> Property prop_parse_disp4 vr = let a = Just vr b = (simpleParse (display vr)) in counterexample ("Expected: " ++ show a) $ counterexample ("But got: " ++ show b) $ b == a prop_parse_disp5 :: VersionRange -> Property prop_parse_disp5 vr = let a = Just vr b = simpleParse (displayRaw vr) in counterexample ("Expected: " ++ show a) $ counterexample ("But got: " ++ show b) $ b == a displayRaw :: VersionRange -> String displayRaw = Disp.render . foldVersionRange' -- precedence: -- All the same as the usual pretty printer, except for the parens ( Disp.text "-any") (\v -> Disp.text "==" <> disp v) (\v -> Disp.char '>' <> disp v) (\v -> Disp.char '<' <> disp v) (\v -> Disp.text ">=" <> disp v) (\v -> Disp.text "<=" <> disp v) (\v _ -> Disp.text "==" <> dispWild v) (\v _ -> Disp.text "^>=" <> disp v) (\r1 r2 -> r1 <+> Disp.text "||" <+> r2) (\r1 r2 -> r1 <+> Disp.text "&&" <+> r2) (\r -> Disp.parens r) -- parens where dispWild (Version b _) = Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int b)) <> Disp.text ".*"
sopvop/cabal
Cabal/tests/UnitTests/Distribution/Version.hs
Haskell
bsd-3-clause
26,798
{-# LANGUAGE QuasiQuotes #-} -- | Simple C runtime representation. module Futhark.CodeGen.Backends.SimpleRepresentation ( sameRepresentation , tupleField , tupleFieldExp , funName , defaultMemBlockType , builtInFunctionDefs , intTypeToCType , floatTypeToCType , primTypeToCType -- * Primitive value operations , cIntOps , cFloat32Ops , cFloat64Ops , cFloatConvOps -- * Specific builtin functions , c_log32, c_sqrt32, c_exp32, c_sin32, c_cos32, c_atan2_32, c_isnan32, c_isinf32 , c_log64, c_sqrt64, c_exp64, c_sin64, c_cos64, c_atan2_64, c_isnan64, c_isinf64 ) where import qualified Language.C.Syntax as C import qualified Language.C.Quote.C as C import Futhark.CodeGen.ImpCode import Futhark.Util.Pretty (pretty) intTypeToCType :: IntType -> C.Type intTypeToCType Int8 = [C.cty|typename int8_t|] intTypeToCType Int16 = [C.cty|typename int16_t|] intTypeToCType Int32 = [C.cty|typename int32_t|] intTypeToCType Int64 = [C.cty|typename int64_t|] uintTypeToCType :: IntType -> C.Type uintTypeToCType Int8 = [C.cty|typename uint8_t|] uintTypeToCType Int16 = [C.cty|typename uint16_t|] uintTypeToCType Int32 = [C.cty|typename uint32_t|] uintTypeToCType Int64 = [C.cty|typename uint64_t|] floatTypeToCType :: FloatType -> C.Type floatTypeToCType Float32 = [C.cty|float|] floatTypeToCType Float64 = [C.cty|double|] primTypeToCType :: PrimType -> C.Type primTypeToCType (IntType t) = intTypeToCType t primTypeToCType (FloatType t) = floatTypeToCType t primTypeToCType Bool = [C.cty|char|] primTypeToCType Cert = [C.cty|char|] -- | True if both types map to the same runtime representation. This -- is the case if they are identical modulo uniqueness. sameRepresentation :: [Type] -> [Type] -> Bool sameRepresentation ets1 ets2 | length ets1 == length ets2 = and $ zipWith sameRepresentation' ets1 ets2 | otherwise = False sameRepresentation' :: Type -> Type -> Bool sameRepresentation' (Scalar t1) (Scalar t2) = t1 == t2 sameRepresentation' (Mem _ space1) (Mem _ space2) = space1 == space2 sameRepresentation' _ _ = False -- | @tupleField i@ is the name of field number @i@ in a tuple. tupleField :: Int -> String tupleField i = "elem_" ++ show i -- | @tupleFieldExp e i@ is the expression for accesing field @i@ of -- tuple @e@. If @e@ is an lvalue, so will the resulting expression -- be. tupleFieldExp :: C.Exp -> Int -> C.Exp tupleFieldExp e i = [C.cexp|$exp:e.$id:(tupleField i)|] -- | @funName f@ is the name of the C function corresponding to -- the Futhark function @f@. funName :: Name -> String funName = ("futhark_"++) . nameToString funName' :: String -> String funName' = funName . nameFromString -- | The type of memory blocks in the default memory space. defaultMemBlockType :: C.Type defaultMemBlockType = [C.cty|unsigned char*|] cIntOps :: [C.Definition] cIntOps = concatMap (`map` [minBound..maxBound]) ops where ops = [mkAdd, mkSub, mkMul, mkUDiv, mkUMod, mkSDiv, mkSMod, mkSQuot, mkSRem, mkShl, mkLShr, mkAShr, mkAnd, mkOr, mkXor, mkUlt, mkUle, mkSlt, mkSle, mkPow ] ++ map mkSExt [minBound..maxBound] ++ map mkZExt [minBound..maxBound] taggedI s Int8 = s ++ "8" taggedI s Int16 = s ++ "16" taggedI s Int32 = s ++ "32" taggedI s Int64 = s ++ "64" mkAdd = simpleIntOp "add" [C.cexp|x + y|] mkSub = simpleIntOp "sub" [C.cexp|x - y|] mkMul = simpleIntOp "mul" [C.cexp|x * y|] mkUDiv = simpleUintOp "udiv" [C.cexp|x / y|] mkUMod = simpleUintOp "umod" [C.cexp|x % y|] mkSDiv t = let ct = intTypeToCType t in [C.cedecl|static inline $ty:ct $id:(taggedI "sdiv" t)($ty:ct x, $ty:ct y) { $ty:ct q = x / y; $ty:ct r = x % y; return q - (((r != 0) && ((r < 0) != (y < 0))) ? 1 : 0); }|] mkSMod t = let ct = intTypeToCType t in [C.cedecl|static inline $ty:ct $id:(taggedI "smod" t)($ty:ct x, $ty:ct y) { $ty:ct r = x % y; return r + ((r == 0 || (x > 0 && y > 0) || (x < 0 && y < 0)) ? 0 : y); }|] mkSQuot = simpleIntOp "squot" [C.cexp|x / y|] mkSRem = simpleIntOp "srem" [C.cexp|x % y|] mkShl = simpleUintOp "shl" [C.cexp|x << y|] mkLShr = simpleUintOp "lshr" [C.cexp|x >> y|] mkAShr = simpleIntOp "ashr" [C.cexp|x >> y|] mkAnd = simpleUintOp "and" [C.cexp|x & y|] mkOr = simpleUintOp "or" [C.cexp|x | y|] mkXor = simpleUintOp "xor" [C.cexp|x ^ y|] mkUlt = uintCmpOp "ult" [C.cexp|x < y|] mkUle = uintCmpOp "ule" [C.cexp|x <= y|] mkSlt = intCmpOp "slt" [C.cexp|x < y|] mkSle = intCmpOp "sle" [C.cexp|x <= y|] mkPow t = let ct = intTypeToCType t in [C.cedecl|static inline $ty:ct $id:(taggedI "pow" t)($ty:ct x, $ty:ct y) { $ty:ct res = 1, rem = y; while (rem != 0) { if (rem & 1) { res *= x; } rem >>= 1; x *= x; } return res; }|] mkSExt from_t to_t = [C.cedecl|static inline $ty:to_ct $id:name($ty:from_ct x) { return x;} |] where name = "sext_"++pretty from_t++"_"++pretty to_t from_ct = intTypeToCType from_t to_ct = intTypeToCType to_t mkZExt from_t to_t = [C.cedecl|static inline $ty:to_ct $id:name($ty:from_ct x) { return x;} |] where name = "zext_"++pretty from_t++"_"++pretty to_t from_ct = uintTypeToCType from_t to_ct = uintTypeToCType to_t simpleUintOp s e t = [C.cedecl|static inline $ty:ct $id:(taggedI s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = uintTypeToCType t simpleIntOp s e t = [C.cedecl|static inline $ty:ct $id:(taggedI s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = intTypeToCType t intCmpOp s e t = [C.cedecl|static inline char $id:(taggedI s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = intTypeToCType t uintCmpOp s e t = [C.cedecl|static inline char $id:(taggedI s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = uintTypeToCType t cFloat32Ops :: [C.Definition] cFloat64Ops :: [C.Definition] cFloatConvOps :: [C.Definition] (cFloat32Ops, cFloat64Ops, cFloatConvOps) = ( map ($Float32) mkOps , map ($Float64) mkOps , [ mkFPConvFF "fpconv" from to | from <- [minBound..maxBound], to <- [minBound..maxBound] ]) where taggedF s Float32 = s ++ "32" taggedF s Float64 = s ++ "64" convOp s from to = s ++ "_" ++ pretty from ++ "_" ++ pretty to mkOps = [mkFDiv, mkFAdd, mkFSub, mkFMul, mkPow, mkCmpLt, mkCmpLe] ++ map (mkFPConvIF "sitofp") [minBound..maxBound] ++ map (mkFPConvUF "uitofp") [minBound..maxBound] ++ map (flip $ mkFPConvFI "fptosi") [minBound..maxBound] ++ map (flip $ mkFPConvFU "fptoui") [minBound..maxBound] mkFDiv = simpleFloatOp "fdiv" [C.cexp|x / y|] mkFAdd = simpleFloatOp "fadd" [C.cexp|x + y|] mkFSub = simpleFloatOp "fsub" [C.cexp|x - y|] mkFMul = simpleFloatOp "fmul" [C.cexp|x * y|] mkCmpLt = floatCmpOp "cmplt" [C.cexp|x < y|] mkCmpLe = floatCmpOp "cmple" [C.cexp|x <= y|] mkPow Float32 = [C.cedecl|static inline float fpow32(float x, float y) { return pow(x, y); }|] mkPow Float64 = [C.cedecl|static inline double fpow64(double x, double y) { return pow(x, y); }|] mkFPConv from_f to_f s from_t to_t = [C.cedecl|static inline $ty:to_ct $id:(convOp s from_t to_t)($ty:from_ct x) { return x;} |] where from_ct = from_f from_t to_ct = to_f to_t mkFPConvFF = mkFPConv floatTypeToCType floatTypeToCType mkFPConvFI = mkFPConv floatTypeToCType intTypeToCType mkFPConvIF = mkFPConv intTypeToCType floatTypeToCType mkFPConvFU = mkFPConv floatTypeToCType uintTypeToCType mkFPConvUF = mkFPConv uintTypeToCType floatTypeToCType simpleFloatOp s e t = [C.cedecl|static inline $ty:ct $id:(taggedF s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = floatTypeToCType t floatCmpOp s e t = [C.cedecl|static inline char $id:(taggedF s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = floatTypeToCType t c_log32 :: C.Func c_log32 = [C.cfun| static inline float $id:(funName' "log32")(float x) { return log(x); } |] c_sqrt32 :: C.Func c_sqrt32 = [C.cfun| static inline float $id:(funName' "sqrt32")(float x) { return sqrt(x); } |] c_exp32 ::C.Func c_exp32 = [C.cfun| static inline float $id:(funName' "exp32")(float x) { return exp(x); } |] c_cos32 ::C.Func c_cos32 = [C.cfun| static inline float $id:(funName' "cos32")(float x) { return cos(x); } |] c_sin32 ::C.Func c_sin32 = [C.cfun| static inline float $id:(funName' "sin32")(float x) { return sin(x); } |] c_atan2_32 ::C.Func c_atan2_32 = [C.cfun| static inline double $id:(funName' "atan2_32")(double x, double y) { return atan2(x,y); } |] c_isnan32 ::C.Func c_isnan32 = [C.cfun| static inline char $id:(funName' "isnan32")(float x) { return isnan(x); } |] c_isinf32 ::C.Func c_isinf32 = [C.cfun| static inline char $id:(funName' "isinf32")(float x) { return isinf(x); } |] c_log64 :: C.Func c_log64 = [C.cfun| static inline double $id:(funName' "log64")(double x) { return log(x); } |] c_sqrt64 :: C.Func c_sqrt64 = [C.cfun| static inline double $id:(funName' "sqrt64")(double x) { return sqrt(x); } |] c_exp64 ::C.Func c_exp64 = [C.cfun| static inline double $id:(funName' "exp64")(double x) { return exp(x); } |] c_cos64 ::C.Func c_cos64 = [C.cfun| static inline double $id:(funName' "cos64")(double x) { return cos(x); } |] c_sin64 ::C.Func c_sin64 = [C.cfun| static inline double $id:(funName' "sin64")(double x) { return sin(x); } |] c_atan2_64 ::C.Func c_atan2_64 = [C.cfun| static inline double $id:(funName' "atan2_64")(double x, double y) { return atan2(x,y); } |] c_isnan64 ::C.Func c_isnan64 = [C.cfun| static inline char $id:(funName' "isnan64")(double x) { return isnan(x); } |] c_isinf64 ::C.Func c_isinf64 = [C.cfun| static inline char $id:(funName' "isinf64")(double x) { return isinf(x); } |] -- | C definitions of the Futhark "standard library". builtInFunctionDefs :: [C.Func] builtInFunctionDefs = [c_log32, c_sqrt32, c_exp32, c_cos32, c_sin32, c_atan2_32, c_isnan32, c_isinf32, c_log64, c_sqrt64, c_exp64, c_cos64, c_sin64, c_atan2_64, c_isnan64, c_isinf64]
CulpaBS/wbBach
src/Futhark/CodeGen/Backends/SimpleRepresentation.hs
Haskell
bsd-3-clause
11,377
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Geometry where import GHC.Generics import Data.Aeson data Point = Point1D {xp :: Double} | Point2D {xp :: Double, yp :: Double} | Point3D {xp :: Double, yp :: Double, zp :: Double} deriving (Eq, Ord, Show, Generic) instance ToJSON Point instance FromJSON Point data Node = Node { nodeNumber :: Int , nodePoint :: Point} deriving (Eq, Ord, Show, Generic) instance ToJSON Node instance FromJSON Node -- | The `x` coordinate of the `Node`. xn :: Node -> Double xn (Node _ p) = xp p -- | The `y` coordinate of the given `Node`. An exception is thrown in the case of a dimension mismatch. yn :: Node -> Double yn (Node _ p) = yp p -- | The `z` coordinate of the given `Node`. An exception is thrown in the case of a dimension mismatch. zn :: Node -> Double zn (Node _ p) = zp p
adrienhaxaire/funfem
Geometry.hs
Haskell
bsd-3-clause
925
import Test.Framework (defaultMain) import qualified Database.Sqroll.Pure.Tests import qualified Database.Sqroll.Sqlite3.Tests import qualified Database.Sqroll.Table.Naming.Tests import qualified Database.Sqroll.TH.Tests import qualified Database.Sqroll.Json.Tests import qualified Database.Sqroll.Tests import qualified Database.Sqroll.Flexible.Tests main :: IO () main = defaultMain [ Database.Sqroll.Pure.Tests.tests , Database.Sqroll.Sqlite3.Tests.tests , Database.Sqroll.Table.Naming.Tests.tests , Database.Sqroll.TH.Tests.tests , Database.Sqroll.Tests.tests , Database.Sqroll.Flexible.Tests.tests , Database.Sqroll.Json.Tests.tests ]
pacak/sqroll
tests/TestSuite.hs
Haskell
bsd-3-clause
674
{-# LANGUAGE OverloadedStrings #-} -- | RequestTests runs as a standalone executable so that developers can change -- TestConfig to whatever settings they want. module Main where import Blaze.ByteString.Builder import Control.Applicative import Control.Monad import Control.Monad.IO.Class import qualified Data.ByteString.Lazy.Char8 as BSL8 import Data.Char import Data.Either.Utils import Data.Map import Data.Maybe import Data.OpenSRS import Data.OpenSRS.Types import Data.Time import Data.Tuple.Sequence import Data.UUID import Data.UUID.V5 import System.Environment import System.Locale (defaultTimeLocale) import Test.Hspec import Test.Hspec.Expectations import Text.XmlHtml import TestConfig -- To run a full suite, you must define the following environment variables: -- * SRS Configuration -- * SRS_HOST -- * SRS_USER -- * SRS_KEY -- * SRS_IP -- * Domain availability tests -- * SRSTEST_DOMAINLOOKUP_FREE -- * SRSTEST_DOMAINLOOKUP_TAKEN -- * SRSTEST_DOMAINGET_OURS -- * SRSTEST_DOMAINGET_NOTOURS -- * Domain registration and renewal tests -- * SRSTEST_DOMAINREGISTER_NAME -- * SRSTEST_DOMAINREGISTER_NAME2 -- * SRSTEST_DOMAINRENEW_NAME -- * SRSTEST_DOMAINRENEW_AFFID -- * SRSTEST_DOMAINRENEW_EXPYEAR -- * Cookie tests -- * SRSTEST_COOKIE_DOMAINGET_DOMAIN -- * SRSTEST_COOKIE_DOMAINGET_USER -- * SRSTEST_COOKIE_DOMAINGET_PASS -- * Domain password tests -- * SRSTEST_DOMAINPASSWORD_SEND -- * Domain update tests -- * SRSTEST_DOMAINMODIFY_WHOISPRIV_DOMAIN -- * SRSTEST_DOMAINMODIFY_WHOISPRIV_ENABLE (True || False) makeDomain :: String -> IO Domain makeDomain dname = do t <- getCurrentTime let t' = addUTCTime ((86400 * 365) :: NominalDiffTime) t return $ Domain dname True testContacts (Just t) True (Just t) (Just "5534") True (Just t') testNameservers suite :: Spec suite = do describe "Domain List" . it "can list domains with expiry in a given period" $ let run cfg = do t <- getCurrentTime let sd = addUTCTime ((-86400 * 365 * 20) :: NominalDiffTime) t let ed = addUTCTime ((86400 * 365 * 20) :: NominalDiffTime) t res <- doRequest $ ListDomainsByExpiry cfg sd ed 0 5000 case res of Right (DomainListResult (DomainList count items _)) -> length items `shouldBe` count Left e -> error e _ -> error "This should never happen." in withSRSConfig run describe "Domain Lookup/Get" $ do it "looks up a valid free domain" $ let run cfg d = do res <- doRequest $ LookupDomain cfg d res `shouldBe` (Right . DomainAvailabilityResult $ Available d) in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINLOOKUP_FREE") run it "looks up a valid taken domain" $ let run cfg d = do res <- doRequest $ LookupDomain cfg d res `shouldBe` (Right . DomainAvailabilityResult $ Unavailable d) in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINLOOKUP_TAKEN") run it "gets a valid existing domain" $ let run cfg d = do res <- doRequest $ GetDomain cfg d case res of Right (DomainResult dr) -> domainName dr `shouldBe` d Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINGET_OURS") run it "gets a valid existing domain that we don't own" $ withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINGET_NOTOURS") (\cfg d -> do res <- doRequest $ GetDomain cfg d fromLeft res `shouldContain` "415: Authentication Error.") describe "Domain Registration" . it "registers a domain" $ let run cfg d = do domain <- makeDomain d res <- doRequest $ RegisterDomain cfg domain True Nothing Nothing False False False True 2 un pwd NewRegistration Nothing case res of Right DomainRegistrationResult{} -> pass Left e -> error e _ -> error "This should never happen." un = fromJust $ makeUsername "webmaster" pwd = fromJust $ makePassword "aTestingPassWord123" in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINREGISTER_NAME") run describe "Domain Registration/Renewal" $ do it "registers and renews a new domain" $ let run cfg d = do domain <- makeDomain d let changeContact = False let comments = Nothing let encoding = Nothing let lock = False let park = False let whois = False let handleNow = True let regPeriod = 1 let username = fromJust $ makeUsername "webmaster" let password = fromJust $ makePassword "testPassword123" let regType = NewRegistration let tldData = Nothing -- Stage 1: Register domain let req = RegisterDomain cfg domain changeContact comments encoding lock park whois handleNow regPeriod username password regType tldData res <- doRequest req case res of Right DomainRegistrationResult{} -> do -- Stage 2: Get domain let req = GetDomain cfg (domainName domain) res <- doRequest req case res of Right (DomainResult d2) -> do -- Stage 3: Renew domain let expyear = read . formatTime defaultTimeLocale "%Y" . fromJust $ domainExpireDate d2 let req = RenewDomain cfg (domainName d2) (domainAutoRenew d2) (fromJust $ domainAffiliateID d2) expyear True 1 res <- doRequest req case res of Right (DomainRenewalResult drr) -> do print drr pass Left e -> error e _ -> error "This should never happen." Left e -> error e _ -> error "This should never happen." Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINREGISTER_NAME2") run it "renews a domain" $ let run cfg (d,a,y) = do res <- doRequest $ RenewDomain cfg d False a y True 1 case res of Right (DomainRenewalResult dr) -> do print dr pass Left e -> error e _ -> error "This should never happen." getSettings = do d <- lookupEnv "SRSTEST_DOMAINRENEW_NAME" a <- lookupEnv "SRSTEST_DOMAINRENEW_AFFID" y <- lookupEnv "SRSTEST_DOMAINRENEW_EXPYEAR" return $ sequenceT (d, a, fmap toInt y) toInt x = read x :: Int in withSRSConfigArgs getSettings run describe "Passwords" $ do it "can change to a valid password" $ let run cfg d = do let un = fromJust $ makeUsername "webmaster" let pwd = fromJust $ makePassword validPassword unPassword pwd `shouldBe` validPassword res <- doRequest $ ChangeDomainOwnership cfg d un pwd case res of Right (GenericSuccess _) -> pass Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINPASSWORD_SEND") run it "cannot use an invalid password" $ do let pwd = makePassword invalidPassword pwd `shouldBe` Nothing it "can send passwords to a domain contact" $ let run cfg d = do res <- doRequest $ SendDomainPassword cfg d "owner" False case res of Right (GenericSuccess _) -> pass Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINPASSWORD_SEND") run describe "Cookies" $ do it "can get a cookie for a valid domain logon" $ let run cfg (d,u,p) = do res <- doRequest $ SetCookie cfg d u p case res of Right (CookieResult _) -> pass Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs getCookieSettings run it "gets a domain using a cookie" $ let run cfg (d,u,p) = do res <- doRequest $ SetCookie cfg d u p case res of Right (CookieResult jar) -> do res2 <- doRequest (GetDomainWithCookie cfg d $ cookieStr jar) case res2 of Right (DomainResult d') -> domainName d' `shouldBe` d Left e -> error e _ -> error "This should never happen." Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs getCookieSettings run describe "Domain Updates" . it "can set whois privacy" $ let run cfg (d,s) = do let s' = if s then "enable" else "disable" let req = ModifyDomain cfg d False (fromList [("data", "whois_privacy_state"), ("state", s')]) Nothing res <- doRequest req if s then res `shouldBe` (Right $ GenericSuccess "Whois Privacy successfully enabled") else res `shouldBe` (Right $ GenericSuccess "Whois Privacy successfully disabled") getSettings = do d <- liftIO $ lookupEnv "SRSTEST_DOMAINMODIFY_WHOISPRIV_DOMAIN" e <- liftIO $ lookupEnv "SRSTEST_DOMAINMODIFY_WHOISPRIV_ENABLE" return $ sequenceT (d, (== "True") <$> e) in withSRSConfigArgs getSettings run -- | Get configuration getSRSConfig :: IO (Maybe SRSConfig) getSRSConfig = do host <- lookupEnv "SRS_HOST" user <- lookupEnv "SRS_USER" key <- lookupEnv "SRS_KEY" ip <- lookupEnv "SRS_IP" return $ case sequenceT (host,user,key,ip) of Just (h,u,k,i) -> Just (SRSConfig h u k i False) _ -> Nothing -- | Wrap an expectation in a check for config. -- If we don't have config, we pass (defer) the expectation. withSRSConfig :: (SRSConfig -> Expectation) -> Expectation withSRSConfig fn = do cfg <- liftIO getSRSConfig case cfg of Just c -> fn c _ -> do liftIO $ putStrLn "WARNING: No OpenSRS configuration in use." pass -- | Wrap an expectation in a check for config and arguments. -- If we don't have config or arguments, we pass (defer) the expectation. withSRSConfigArgs :: IO (Maybe a) -> (SRSConfig -> a -> Expectation) -> Expectation withSRSConfigArgs getArgs fn = do cfg <- liftIO getSRSConfig args <- liftIO getArgs case sequenceT (cfg, args) of Just (c, a) -> fn c a _ -> do liftIO $ putStrLn "WARNING: Cannot get OpenSRS configuration and/or test arguments." pass getCookieSettings :: IO (Maybe (String, SRSUsername, Password)) getCookieSettings = do d <- liftIO $ lookupEnv "SRSTEST_COOKIE_DOMAINGET_DOMAIN" u <- liftIO $ lookupEnv "SRSTEST_COOKIE_DOMAINGET_USER" p <- liftIO $ lookupEnv "SRSTEST_COOKIE_DOMAINGET_PASS" return $ sequenceT (d, join $ fmap makeUsername u, join $ fmap makePassword p) -- | Explicitly pass a test. pass :: Expectation pass = return () main :: IO () main = do res <- hspec suite return ()
anchor/haskell-opensrs
tests/RequestTests.hs
Haskell
bsd-3-clause
13,098
{-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module ChartSpec where import Test.Hspec import Graphics.HSD3.Chart import Graphics.HSD3.Theme import Utils spec :: Spec spec = describe "Chart" $ do describe "Bar Graph, with records" $ do sample "a simple graph, with a record" [Bar 1.0 "red", Bar 0.2 "green", Bar 0.3 "blue"] (ThemeChart def coloredBarGraph) sample "a more complicated record graph, with a record" (zipWith Bar (map ((+ 10) . (*10) . sin . (/5)) (take 15 [0..])) (concat $ repeat ["red", "red", "red", "green", "green", "green", "blue", "blue", "blue"])) (ThemeChart def coloredBarGraph) describe "Bar Graphs" $ do sample "a simple graph" [1.0, 0.2, 0.3] (ThemeChart def barGraph) sample "a large, but still simple bar graph" (take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8]) (ThemeChart def barGraph) sample "a bar graph with arbitrary data size" (map ((+ 10) . (*10) . sin . (/5)) (take 75 [0..])) (ThemeChart def barGraph) describe "Stacked Bar Graphs" $ do sample "a trivial stacked bar graph" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a simple stacked bar graph" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a normal stacked bar graph" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a complex stacked bar graph" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a complex stacked bar graph with different number of elements" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 40 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 20 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 2 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 14 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a stacked bar graph with arbitrary data size" (replicate 10 (map ((+ 10) . (*10) . sin . (/5)) (take 75 [0..]))) (ThemeChart def stackedBarGraph) describe "Grid layouts" $ do sample "a trivial grid layout" (replicate 5 [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ]) (ThemeChart def gridBarGraph) sample "a non symmetrical grid layout" (fmap (uncurry take) . zip [5, 4, 4, 2, 5] . replicate 5 $ [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 40 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 30 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 10 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ]) (ThemeChart def gridBarGraph) sample "a grid bar graph with arbitrary data size" (replicate 6 (replicate 6 (map ((+ 10) . (*10) . sin . (/5)) (take 75 [0..])))) (ThemeChart def gridBarGraph)
Soostone/hs-d3
test/suite/ChartSpec.hs
Haskell
bsd-3-clause
5,451
module PrefStringUtil where import Data.List import Data.List.Split import Data.Char (isSpace) import Data.Maybe -- | This is a quick and dirty "Trim whitespace from both sides" function", that is taken straight outta -- <http://stackoverflow.com/questions/6270324/in-haskell-how-do-you-trim-whitespace-from-the-beginning-and-end-of-a-string Stack Overflow>. trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace -- | This takes a string of form "Value1 delim Value2 delim ... Valuen", with a character representing -- a delimiter. It returns the sequence [Value1, Value2, ... Valuen]. All whitespace is trimmed -- from all the values. stripandtrim :: String -> Char -> [String] stripandtrim stringval charval = [trim x | x <- splitOn [charval] stringval] -- | This method takes a string, and attempts to parse it into a number. convertstringtoint :: String -> Maybe Int convertstringtoint stringval | null conversion = Nothing | otherwise = Just (fst (head conversion)) where conversion = reads stringval -- | This method takes a string of the form "a, b, c, ..." where a, b, c -- and so on are integer; it attempts to create a sequence of integers -- from them. convertstringtoseq :: String -> Maybe [Int] convertstringtoseq stringval | null result = Nothing | elem Nothing result = Nothing | otherwise = Just [fromJust d | d <- result] where result = [convertstringtoint c | c <- stripandtrim stringval ','] -- This is for test code. This is a constant for a selection of space characters spacerange = " \t\n\r\f\v\160" -- | This is used for the existence of whitespace in a string. This is used for testing. iswhitespacewithin :: String -> Bool iswhitespacewithin stringval | isNothing (find isSpace stringval) = False | otherwise = True
peterkmurphy/preference
src/PrefStringUtil.hs
Haskell
bsd-3-clause
1,809
{-| Module : Database.Relational.Update Description : Definition of UPDATE and friends. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} module Database.Relational.Update ( UPDATE(..) ) where data UPDATE table projection rows = UPDATE table projection rows
avieth/Relational
Database/Relational/Update.hs
Haskell
bsd-3-clause
423
module Language.TNT.Token ( Token (..) ) where import Prelude hiding (Bool (..)) data Token = Name String | Operator String | Number Double | String String | Char Char | Import | As | Var | Fun | If | Else | For | In | While | Return | Throw | Null | True | False | Or | And | LT | LE | GT | GE | Plus | Minus | Multiply | Div | Mod | Not | Period | Comma | OpenParen | CloseParen | OpenBrace | CloseBrace | OpenBracket | CloseBracket | Equal | PlusEqual | Colon | Semi | EOF deriving (Eq, Show)
sonyandy/tnt
Language/TNT/Token.hs
Haskell
bsd-3-clause
984
{-# OPTIONS_GHC -fno-warn-orphans #-} {-| Module : Game.GoreAndAsh.Resources.Module Description : Monad transformer and instance for core module Copyright : (c) Anton Gushcha, 2016 License : BSD3 Maintainer : ncrashed@gmail.com Stability : experimental Portability : POSIX -} module Game.GoreAndAsh.Resources.Module( ResourcesT(..) ) where import Control.Monad.Catch import Control.Monad.Fix import Control.Monad.State.Strict import Game.GoreAndAsh import Game.GoreAndAsh.Resources.State -- | Monad transformer of the core module. -- -- [@s@] - State of next core module in modules chain; -- -- [@m@] - Next monad in modules monad stack; -- -- [@a@] - Type of result value; -- -- How to embed module: -- -- @ -- type AppStack = ModuleStack [ResourcesT, ... other modules ... ] IO -- -- newtype AppMonad a = AppMonad (AppStack a) -- deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadThrow, MonadCatch, MonadResources) -- @ -- -- The module is pure within first phase (see 'ModuleStack' docs), therefore 'Identity' can be used as end monad. newtype ResourcesT s m a = ResourcesT { runResourcesT :: StateT (ResourcesState s) m a } deriving (Functor, Applicative, Monad, MonadState (ResourcesState s), MonadFix, MonadTrans, MonadIO, MonadThrow, MonadCatch, MonadMask) instance GameModule m s => GameModule (ResourcesT s m) (ResourcesState s) where type ModuleState (ResourcesT s m) = ResourcesState s runModule (ResourcesT m) s = do ((a, s'), nextState) <- runModule (runStateT m s) (resourcesNextState s) return (a, s' { resourcesNextState = nextState }) newModuleState = emptyResourcesState <$> newModuleState withModule _ = id cleanupModule _ = return ()
Teaspot-Studio/gore-and-ash-resources
src/Game/GoreAndAsh/Resources/Module.hs
Haskell
bsd-3-clause
1,734
{-# LANGUAGE CPP #-} {-# LANGUAGE ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- This module rexposes wrapped parsers from the GHC API. Along with -- returning the parse result, the corresponding annotations are also -- returned such that it is then easy to modify the annotations and print -- the result. -- ---------------------------------------------------------------------------- module Language.Haskell.GHC.ExactPrint.Parsers ( -- * Utility Parser , withDynFlags , CppOptions(..) , defaultCppOptions -- * Module Parsers , parseModule , parseModuleFromString , parseModuleWithOptions , parseModuleWithCpp -- * Basic Parsers , parseExpr , parseImport , parseType , parseDecl , parsePattern , parseStmt , parseWith -- * Internal , parseModuleApiAnnsWithCpp ) where import Language.Haskell.GHC.ExactPrint.Annotate import Language.Haskell.GHC.ExactPrint.Delta import Language.Haskell.GHC.ExactPrint.Preprocess import Language.Haskell.GHC.ExactPrint.Types import Control.Monad.RWS import GHC.Paths (libdir) import qualified ApiAnnotation as GHC import qualified DynFlags as GHC import qualified FastString as GHC import qualified GHC as GHC hiding (parseModule) import qualified HeaderInfo as GHC import qualified Lexer as GHC import qualified MonadUtils as GHC import qualified Outputable as GHC import qualified Parser as GHC import qualified SrcLoc as GHC import qualified StringBuffer as GHC #if __GLASGOW_HASKELL__ <= 710 import qualified OrdList as OL #else import qualified GHC.LanguageExtensions as LangExt #endif import qualified Data.Map as Map -- --------------------------------------------------------------------- -- | Wrapper function which returns Annotations along with the parsed -- element. parseWith :: Annotate w => GHC.DynFlags -> FilePath -> GHC.P (GHC.Located w) -> String -> Either (GHC.SrcSpan, String) (Anns, GHC.Located w) parseWith dflags fileName parser s = case runParser parser dflags fileName s of GHC.PFailed ss m -> Left (ss, GHC.showSDoc dflags m) GHC.POk (mkApiAnns -> apianns) pmod -> Right (as, pmod) where as = relativiseApiAnns pmod apianns -- --------------------------------------------------------------------- runParser :: GHC.P a -> GHC.DynFlags -> FilePath -> String -> GHC.ParseResult a runParser parser flags filename str = GHC.unP parser parseState where location = GHC.mkRealSrcLoc (GHC.mkFastString filename) 1 1 buffer = GHC.stringToStringBuffer str parseState = GHC.mkPState flags buffer location -- --------------------------------------------------------------------- -- | Provides a safe way to consume a properly initialised set of -- 'DynFlags'. -- -- @ -- myParser fname expr = withDynFlags (\\d -> parseExpr d fname expr) -- @ withDynFlags :: (GHC.DynFlags -> a) -> IO a withDynFlags action = GHC.defaultErrorHandler GHC.defaultFatalMessager GHC.defaultFlushOut $ GHC.runGhc (Just libdir) $ do dflags <- GHC.getSessionDynFlags void $ GHC.setSessionDynFlags dflags return (action dflags) -- --------------------------------------------------------------------- parseFile :: GHC.DynFlags -> FilePath -> String -> GHC.ParseResult (GHC.Located (GHC.HsModule GHC.RdrName)) parseFile = runParser GHC.parseModule -- --------------------------------------------------------------------- type Parser a = GHC.DynFlags -> FilePath -> String -> Either (GHC.SrcSpan, String) (Anns, a) parseExpr :: Parser (GHC.LHsExpr GHC.RdrName) parseExpr df fp = parseWith df fp GHC.parseExpression parseImport :: Parser (GHC.LImportDecl GHC.RdrName) parseImport df fp = parseWith df fp GHC.parseImport parseType :: Parser (GHC.LHsType GHC.RdrName) parseType df fp = parseWith df fp GHC.parseType -- safe, see D1007 parseDecl :: Parser (GHC.LHsDecl GHC.RdrName) #if __GLASGOW_HASKELL__ <= 710 parseDecl df fp = parseWith df fp (head . OL.fromOL <$> GHC.parseDeclaration) #else parseDecl df fp = parseWith df fp GHC.parseDeclaration #endif parseStmt :: Parser (GHC.ExprLStmt GHC.RdrName) parseStmt df fp = parseWith df fp GHC.parseStatement parsePattern :: Parser (GHC.LPat GHC.RdrName) parsePattern df fp = parseWith df fp GHC.parsePattern -- --------------------------------------------------------------------- -- -- | This entry point will also work out which language extensions are -- required and perform CPP processing if necessary. -- -- @ -- parseModule = parseModuleWithCpp defaultCppOptions -- @ -- -- Note: 'GHC.ParsedSource' is a synonym for 'GHC.Located' ('GHC.HsModule' 'GHC.RdrName') parseModule :: FilePath -> IO (Either (GHC.SrcSpan, String) (Anns, GHC.ParsedSource)) parseModule = parseModuleWithCpp defaultCppOptions normalLayout -- | This entry point will work out which language extensions are -- required but will _not_ perform CPP processing. -- In contrast to `parseModoule` the input source is read from the provided -- string; the `FilePath` parameter solely exists to provide a name -- in source location annotations. parseModuleFromString :: FilePath -> String -> IO (Either (GHC.SrcSpan, String) (Anns, GHC.ParsedSource)) parseModuleFromString fp s = do GHC.defaultErrorHandler GHC.defaultFatalMessager GHC.defaultFlushOut $ GHC.runGhc (Just libdir) $ do dflags <- initDynFlagsPure fp s return $ parseWith dflags fp GHC.parseModule s parseModuleWithOptions :: DeltaOptions -> FilePath -> IO (Either (GHC.SrcSpan, String) (Anns, GHC.ParsedSource)) parseModuleWithOptions opts fp = parseModuleWithCpp defaultCppOptions opts fp -- | Parse a module with specific instructions for the C pre-processor. parseModuleWithCpp :: CppOptions -> DeltaOptions -> FilePath -> IO (Either (GHC.SrcSpan, String) (Anns, GHC.ParsedSource)) parseModuleWithCpp cpp opts fp = do res <- parseModuleApiAnnsWithCpp cpp fp return (either Left mkAnns res) where mkAnns (apianns, cs, _, m) = Right (relativiseApiAnnsWithOptions opts cs m apianns, m) -- | Low level function which is used in the internal tests. -- It is advised to use 'parseModule' or 'parseModuleWithCpp' instead of -- this function. parseModuleApiAnnsWithCpp :: CppOptions -> FilePath -> IO (Either (GHC.SrcSpan, String) (GHC.ApiAnns, [Comment], GHC.DynFlags, GHC.ParsedSource)) parseModuleApiAnnsWithCpp cppOptions file = GHC.defaultErrorHandler GHC.defaultFatalMessager GHC.defaultFlushOut $ GHC.runGhc (Just libdir) $ do dflags <- initDynFlags file #if __GLASGOW_HASKELL__ <= 710 let useCpp = GHC.xopt GHC.Opt_Cpp dflags #else let useCpp = GHC.xopt LangExt.Cpp dflags #endif (fileContents, injectedComments, dflags') <- if useCpp then do (contents,dflags1) <- getPreprocessedSrcDirect cppOptions file cppComments <- getCppTokensAsComments cppOptions file return (contents,cppComments,dflags1) else do txt <- GHC.liftIO $ readFileGhc file let (contents1,lp) = stripLinePragmas txt return (contents1,lp,dflags) return $ case parseFile dflags' file fileContents of GHC.PFailed ss m -> Left $ (ss, (GHC.showSDoc dflags m)) GHC.POk (mkApiAnns -> apianns) pmod -> Right $ (apianns, injectedComments, dflags', pmod) -- --------------------------------------------------------------------- initDynFlags :: GHC.GhcMonad m => FilePath -> m GHC.DynFlags initDynFlags file = do dflags0 <- GHC.getSessionDynFlags src_opts <- GHC.liftIO $ GHC.getOptionsFromFile dflags0 file (dflags1, _, _) <- GHC.parseDynamicFilePragma dflags0 src_opts -- Turn this on last to avoid T10942 let dflags2 = dflags1 `GHC.gopt_set` GHC.Opt_KeepRawTokenStream void $ GHC.setSessionDynFlags dflags2 return dflags2 -- | Requires GhcMonad constraint because there is -- no pure variant of `parseDynamicFilePragma`. Yet, in constrast to -- `initDynFlags`, it does not (try to) read the file at filepath, but -- solely depends on the module source in the input string. initDynFlagsPure :: GHC.GhcMonad m => FilePath -> String -> m GHC.DynFlags initDynFlagsPure fp s = do -- I was told we could get away with using the unsafeGlobalDynFlags. -- as long as `parseDynamicFilePragma` is impure there seems to be -- no reason to use it. dflags0 <- GHC.getSessionDynFlags let pragmaInfo = GHC.getOptions dflags0 (GHC.stringToStringBuffer $ s) fp (dflags1, _, _) <- GHC.parseDynamicFilePragma dflags0 pragmaInfo -- Turn this on last to avoid T10942 let dflags2 = dflags1 `GHC.gopt_set` GHC.Opt_KeepRawTokenStream void $ GHC.setSessionDynFlags dflags2 return dflags2 -- --------------------------------------------------------------------- mkApiAnns :: GHC.PState -> GHC.ApiAnns mkApiAnns pstate = ( Map.fromListWith (++) . GHC.annotations $ pstate , Map.fromList ((GHC.noSrcSpan, GHC.comment_q pstate) : (GHC.annotations_comments pstate)))
mpickering/ghc-exactprint
src/Language/Haskell/GHC/ExactPrint/Parsers.hs
Haskell
bsd-3-clause
9,633
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-| Module : Network.Linode License : BSD3 Stability : experimental This package contains some helpers to create and configure <https://www.linode.com/ Linode> instances. They all require an API key, which can be created on the Linode website. Usage example. We want to create one Linode instance in Atlanta with 1GB of RAM: > import Network.Linode > import Data.List (find) > import qualified System.Process as P > import Data.Foldable (traverse_) > import Data.Monoid ((<>)) > > main :: IO() > main = do > apiKey <- fmap (head . words) (readFile "apiKey") > sshPublicKey <- readFile "id_rsa.pub" > let options = defaultLinodeCreationOptions { > datacenterChoice = "atlanta", > planChoice = "Linode 1024", > sshKey = Just sshPublicKey > } > c <- createLinode apiKey True options > case c of > Left err -> print err > Right linode -> do > traverse_ (\a -> waitForSSH a >> setup a) (publicAddress linode) > print linode > > setup address = P.callCommand $ "scp yourfile root@" <> ip address <> ":/root" You should see something like this: > Creating empty linode (Linode 1024 at atlanta) > Creating disk (24448 MB) > .............. > Creating swap (128 MB) > ........ > Creating config > Booting > ...................................... > Booted linode 1481198 And get something like that: > Linode { > linodeId = LinodeId {unLinodeId = 1481198}, > linodeConfigId = ConfigId {unConfigId = 2251152}, > linodeDatacenterName = "atlanta", > linodePassword = "We4kP4ssw0rd", > linodeAddresses = [Address {ip = "45.79.194.121", rdnsName = "li1293-121.members.linode.com"}]} -} module Network.Linode ( -- * Most common operations createLinode , createCluster , defaultLinodeCreationOptions , waitForSSH , deleteInstance , deleteCluster -- * Lower level API calls , getAccountInfo , getDatacenters , getDistributions , getInstances , getKernels , getPlans , getIpList , createConfig , createDiskFromDistribution , createDisklessLinode , createSwapDisk , createDisk , boot , jobList -- * Helpers , waitUntilCompletion , select , publicAddress -- * Examples , exampleCreateOneLinode , exampleCreateTwoLinodes , module Network.Linode.Types ) where import Control.Concurrent (threadDelay) import qualified Control.Concurrent.Async as A import Control.Error hiding (err) import Control.Lens import Control.Monad (when) import Control.Monad.IO.Class (liftIO) import qualified Control.Retry as R import Data.Foldable (traverse_) import Data.List (find, sortBy) import Data.Monoid ((<>)) import Data.Ord (comparing) import qualified Data.Text as T import qualified Network.Wreq as W import Prelude hiding (log) import qualified System.Process as P import Network.Linode.Internal import Network.Linode.Types {-| Create a Linode instance and boot it. -} createLinode :: ApiKey -> Bool -> LinodeCreationOptions -> IO (Either LinodeError Linode) createLinode apiKey log options = do i <- runExceptT create case i of Left e -> return $ Left e Right (linId, selected) -> do r <- runExceptT $ configure linId selected case r of Left e -> deleteInstance apiKey linId >> return (Left e) Right l -> return $ Right l where create :: ExceptT LinodeError IO (LinodeId, (Datacenter, Distribution, Plan, Kernel)) = do (datacenter, distribution, plan, kernel) <- select apiKey options printLog $ "Creating empty linode (" <> T.unpack (planName plan) <> " at " <> T.unpack (datacenterName datacenter) <> ")" CreatedLinode linId <- createDisklessLinode apiKey (datacenterId datacenter) (planId plan) (paymentChoice options) return (linId, (datacenter, distribution, plan, kernel)) configure linId (datacenter, distribution, plan, kernel) = do let swapSize = swapAmount options let rootDiskSize = (1024 * disk plan) - swapSize let wait = liftIO (waitUntilCompletion apiKey linId log) (CreatedDisk diskId _) <- createDiskFromDistribution apiKey linId (distributionId distribution) (diskLabel options) rootDiskSize (password options) (sshKey options) printLog ("Creating disk (" ++ show rootDiskSize ++ " MB)") >> wait (CreatedDisk swapId _) <- createSwapDisk apiKey linId "swap" swapSize printLog ("Creating swap (" ++ show swapSize ++ " MB)") >> wait (CreatedConfig configId) <- maybeOr (CreatedConfig <$> config options) (createConfig apiKey linId (kernelId kernel) "profile" [diskId, swapId]) printLog "Creating config" (BootedInstance _) <- boot apiKey linId configId printLog "Booting" >> wait addresses <- getIpList apiKey linId printLog $ "Booted linode " ++ show (unLinodeId linId) return $ Linode linId configId (datacenterName datacenter) (password options) addresses printLog l = when log (liftIO $ putStrLn l) {-| Create a Linode cluster. -} createCluster :: ApiKey -> LinodeCreationOptions -> Int -> Bool -> IO (Either [LinodeError] [Linode]) createCluster apiKey options number log = do let optionsList = take number $ map (\(o,i) -> o {diskLabel = diskLabel o <> "-" <> show i}) (zip (repeat options) ([0..] :: [Int])) r <- partitionEithers <$> A.mapConcurrently (createLinode apiKey log) optionsList case r of ([], linodes) -> return (Right linodes) (errors, linodes) -> do _ <- deleteCluster apiKey (map linodeId linodes) return (Left errors) {-| Default options to create an instance. Please customize the security options. -} defaultLinodeCreationOptions :: LinodeCreationOptions defaultLinodeCreationOptions = LinodeCreationOptions { datacenterChoice = "london", planChoice = "Linode 1024", kernelSelect = find (("Latest 64 bit" `T.isPrefixOf`) . kernelName), -- Most recent 64 bits kernel distributionSelect = lastMay . sortBy (comparing distributionName) . filter ((T.pack "Debian" `T.isPrefixOf`) . distributionName), -- Most recent Debian paymentChoice = OneMonth, swapAmount = 128, password = "We4kP4ssw0rd", sshKey = Nothing, diskLabel = "mainDisk", config = Nothing } -- TODO: only works in linux and macos {-| Wait until an ssh connexion is possible, then add the Linode's ip in known_hosts. A newly created Linode is unreachable during a few seconds. -} waitForSSH :: Address -> IO () waitForSSH address = R.recoverAll retryPolicy command where retryPolicy = R.constantDelay oneSecond <> R.limitRetries 100 oneSecond = 1000 * 1000 command _ = P.callCommand $ "ssh -q -o StrictHostKeyChecking=no root@" <> ip address <> " exit" {-| Delete a Linode instance. -} deleteInstance :: ApiKey -> LinodeId -> IO (Either LinodeError DeletedLinode) deleteInstance apiKey (LinodeId i) = runExceptT $ getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.delete"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "skipChecks" .~ ["true"] {-| Delete a list of Linode instances. -} deleteCluster :: ApiKey -> [LinodeId] -> IO ([LinodeError],[DeletedLinode]) deleteCluster apiKey linodes = partitionEithers <$> mapM (deleteInstance apiKey) linodes {-| Read your global account information: network usage, billing state and billing method. -} getAccountInfo :: ApiKey -> ExceptT LinodeError IO AccountInfo getAccountInfo = simpleGetter "account.info" {-| Read all Linode datacenters: dallas, fremont, atlanta, newark, london, tokyo, singapore, frankfurt -} getDatacenters :: ApiKey -> ExceptT LinodeError IO [Datacenter] getDatacenters = simpleGetter "avail.datacenters" {-| Read all available Linux distributions. For example, Debian 8.1 has id 140. -} getDistributions :: ApiKey -> ExceptT LinodeError IO [Distribution] getDistributions = simpleGetter "avail.distributions" {-| Read detailed information about all your instances. -} getInstances :: ApiKey -> ExceptT LinodeError IO [Instance] getInstances = simpleGetter "linode.list" {-| Read all available Linux kernels. -} getKernels :: ApiKey -> ExceptT LinodeError IO [Kernel] getKernels = simpleGetter "avail.kernels" {-| Read all plans offered by Linode. A plan specifies the available CPU, RAM, network usage and pricing of an instance. The smallest plan is Linode 1024. -} getPlans :: ApiKey -> ExceptT LinodeError IO [Plan] getPlans = simpleGetter "avail.linodeplans" {-| Read all IP addresses of an instance. -} getIpList :: ApiKey -> LinodeId -> ExceptT LinodeError IO [Address] getIpList apiKey (LinodeId i) = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.ip.list"] & W.param "LinodeID" .~ [T.pack $ show i] {-| Create a Linode Config (a bag of instance options). -} createConfig :: ApiKey -> LinodeId -> KernelId -> String -> [DiskId] -> ExceptT LinodeError IO CreatedConfig createConfig apiKey (LinodeId i) (KernelId k) label disksIds = do let disksList = T.intercalate "," $ take 9 $ map (T.pack . show . unDisk) disksIds ++ repeat "" let opts = W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.config.create"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "KernelID" .~ [T.pack $ show k] & W.param "Label" .~ [T.pack label] & W.param "DiskList" .~ [disksList] & W.param "helper_distro" .~ ["true"] & W.param "helper_network" .~ ["true"] getWith opts {-| Create a disk from a supported Linux distribution. Size in MB. -} createDiskFromDistribution :: ApiKey -> LinodeId -> DistributionId -> String -> Int -> String -> Maybe String -> ExceptT LinodeError IO CreatedDisk createDiskFromDistribution apiKey (LinodeId i) (DistributionId d) label size pass sshPublicKey = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.disk.createfromdistribution"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "DistributionID" .~ [T.pack $ show d] & W.param "Label" .~ [T.pack label] & W.param "Size" .~ [T.pack $ show size] & W.param "rootPass" .~ [T.pack pass] & case T.pack <$> sshPublicKey of Nothing -> id Just k -> W.param "rootSSHKey" .~ [k] {-| Create a Linode instance with no disk and no configuration. You probably want createLinode instead. -} createDisklessLinode :: ApiKey -> DatacenterId -> PlanId -> PaymentTerm -> ExceptT LinodeError IO CreatedLinode createDisklessLinode apiKey (DatacenterId d) (PlanId p) paymentTerm = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.create"] & W.param "DatacenterID" .~ [T.pack $ show d] & W.param "PlanID" .~ [T.pack $ show p] & W.param "PaymentTerm" .~ [T.pack $ show (paymentTermToInt paymentTerm)] {-| Create a swap partition. -} createSwapDisk :: ApiKey -> LinodeId -> String -> Int -> ExceptT LinodeError IO CreatedDisk createSwapDisk apiKey linId label = createDisk apiKey linId label Swap {-| Create a partition. -} createDisk :: ApiKey -> LinodeId -> String -> DiskType -> Int -> ExceptT LinodeError IO CreatedDisk createDisk apiKey (LinodeId i) label diskType size = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.disk.create"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "Label" .~ [T.pack label] & W.param "Type" .~ [T.pack (diskTypeToString diskType)] & W.param "size" .~ [T.pack $ show size] {-| Boot a Linode instance. -} boot :: ApiKey-> LinodeId -> ConfigId -> ExceptT LinodeError IO BootedInstance boot apiKey (LinodeId i) (ConfigId c) = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.boot"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "ConfigID" .~ [T.pack $ show c] {-| List of pending jobs for this Linode instance. -} jobList :: ApiKey -> LinodeId -> ExceptT LinodeError IO [WaitingJob] jobList apiKey (LinodeId i) = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.job.list"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "pendingOnly" .~ ["true"] {-| Wait until all operations on one instance are done. -} waitUntilCompletion :: ApiKey -> LinodeId -> Bool -> IO() waitUntilCompletion apiKey linId log = do waitingJobs <- runExceptT $ jobList apiKey linId case all waitingJobSuccess <$> waitingJobs of Left e -> putStrLn $ "Error during wait:" ++ show e Right True -> when log (putStrLn "") Right False -> do when log (putStr ".") threadDelay (100*1000) waitUntilCompletion apiKey linId log {-| Select a Datacenter, a Plan, a Linux distribution and kernel from all Linode offering. -} select :: ApiKey -> LinodeCreationOptions -> ExceptT LinodeError IO (Datacenter, Distribution, Plan, Kernel) select apiKey options = (,,,) <$> fetchAndSelect (runExceptT $ getDatacenters apiKey) (find ((== T.pack (datacenterChoice options)) . datacenterName)) "datacenter" <*> fetchAndSelect (runExceptT $ getDistributions apiKey) (distributionSelect options) "distribution" <*> fetchAndSelect (runExceptT $ getPlans apiKey) (find ((== T.pack (planChoice options)) . planName)) "plan" <*> fetchAndSelect (runExceptT $ getKernels apiKey) (kernelSelect options) "kernel" {-| Pick one public address of the Linode Instance -} publicAddress :: Linode -> Maybe Address publicAddress = headMay . sortBy (comparing ip) . filter isPublic . linodeAddresses {-| Example of Linode creation. It expects the apiKey and id_rsa.pub files in the current directory. -} exampleCreateOneLinode :: IO (Maybe Linode) exampleCreateOneLinode = do apiKey <- fmap (head . words) (readFile "apiKey") sshPublicKey <- readFile "id_rsa.pub" let options = defaultLinodeCreationOptions { datacenterChoice = "atlanta", planChoice = "Linode 1024", sshKey = Just sshPublicKey } c <- createLinode apiKey True options case c of Left err -> do print err return Nothing Right linode -> do traverse_ (\a -> waitForSSH a >> setup a) (publicAddress linode) return (Just linode) where setup address = P.callCommand $ "scp TODO root@" <> ip address <> ":/root" {-| Example of Linodes creation. It expects the apiKey and id_rsa.pub files in the current directory. -} exampleCreateTwoLinodes :: IO (Maybe [Linode]) exampleCreateTwoLinodes = do sshPublicKey <- readFile "id_rsa.pub" apiKey <- fmap (head . words) (readFile "apiKey") let options = defaultLinodeCreationOptions { datacenterChoice = "atlanta", planChoice = "Linode 1024", sshKey = Just sshPublicKey } c <- createCluster apiKey options 2 True case c of Left errors -> do print ("error(s) in cluster creation" ++ show errors) return Nothing Right linodes -> do mapM_ (traverse_ (\a -> waitForSSH a >> setup a) . publicAddress) linodes return (Just linodes) where setup address = P.callCommand $ "scp TODO root@" <> ip address <> ":/root"
Helkafen/haskell-linode
src/Network/Linode.hs
Haskell
bsd-3-clause
15,875
-- | Special retrieval queries to build 'ClockTable's using 'HeadingFilter's. -- -- 'ClockTable' is not a type saved directly in the database, it's a combination -- type used for presenting org-mode data. -- Should work similarly to -- <http://orgmode.org/manual/The-clock-table.html The clock table in emacs>. -- -- = Usage -- -- To retrieve a 'ClockTable' you only need to use the 'getTable' function and -- understand how 'HeadingFilter' (see docs for type for usage) works. -- -- For example if you want to retrieve a 'ClockTable' with from all 'Heading's -- that have clocks in all 'Document's: -- -- > import Data.Default -- > import qualified Database.OrgMode.Query.ClockTable as ClockTable -- > -- > ctable <- ClockTable.getTable def -- -- If you want to retrieve a 'ClockTable' with all 'Heading's from a specific -- document you use: -- -- > ctable <- ClockTable.getTable def { headingFilterDocumentIds = [yourDocId] } module Database.OrgMode.Export.ClockTable where import Control.Monad (unless) import Data.Int (Int64) import Database.Esqueleto import qualified Data.HashMap.Strict as HM import Data.HashMap.Strict (HashMap) import Database.OrgMode.Internal.Import import Database.OrgMode.Internal.Types import Database.OrgMode.Types ------------------------------------------------------------------------------- -- * Retrieval {-| Retrives a clocktable using the given 'HeadingFilter' for all items. See the docs of 'HeadingFilter' for more information about how the filter works. NB: Does not check that the given date range is valid. -} getTable :: (MonadIO m) => HeadingFilter -> ReaderT SqlBackend m ClockTable getTable hedFilter = do rows <- getRows hedFilter return $ ClockTable rows hedFilter {-| Retrieves all 'ClockRow's from the database using the given 'HeadingFilter' for all items. -} getRows :: (MonadIO m) => HeadingFilter -> ReaderT SqlBackend m [ClockRow] getRows hedFilter = shortsToRows `liftM` getShorts hedFilter {-| Retrieves a list of 'HeadingShort' using the given 'HeadingFilter'. The list of 'HeadingShort's have the right hierarchy, and is not just a flat list. The hierarchy is built using the 'mkShortsHierarchy' function. NB: 'Heading's without clocks are ignored. -} getShorts :: (MonadIO m) => HeadingFilter -> ReaderT SqlBackend m [HeadingShort] getShorts hedFilter = (mkShortsHierarchy . map unWrap) `liftM` select q where (HeadingFilter startM endM docIds) = hedFilter q = from $ \(doc, heading, clock) -> do let docId = doc ^. DocumentId hedId = heading ^. HeadingId hedDurM = sum_ (clock ^. ClockDuration) where_ $ heading ^. HeadingDocument ==. docId where_ $ clock ^. ClockHeading ==. hedId whenJust startM $ \startT -> where_ (clock ^. ClockStart >=. val startT) whenJust endM $ \endT -> where_ (clock ^. ClockEnd <=. just (val endT)) unless (null docIds) $ where_ (in_ docId (valList docIds)) groupBy hedId return $ (heading, docId, hedDurM) unWrap :: (Entity Heading, Value (Key Document), Value (Maybe Int)) -> HeadingShort unWrap ((Entity headingId Heading{..}), docId, hedDurM) = let docKey = fromSqlKey (unValue docId) hedKey = fromSqlKey headingId hedParKey = fromSqlKey <$> headingParent dur = maybe 0 id (unValue hedDurM) in HeadingShort docKey hedKey hedParKey headingTitle dur [] ------------------------------------------------------------------------------- -- * Helpers {-| Helper for running a Monadic function on the given value when it is 'Just'. Instead of writing: > case valM of > Just val -> myFunc val > Nothing -> return () You can write: > whenJust valM myFunc And get the same result with less code. -} whenJust :: (Monad m) => Maybe a -- ^ Value to use -> (a -> m ()) -- ^ Function to apply on pure value -> m () whenJust (Just v) f = f v whenJust Nothing _ = return () {-| Takes a flat list of 'HeadingShort's and creates a 'HeadingShort' hierarchy. NB: This function is really naive and inefficient. It probably has time complexity of O(n^∞) and you need a quantum computer to run it. -} mkShortsHierarchy :: [HeadingShort] -> [HeadingShort] mkShortsHierarchy inp = map findChildren $ filter isRoot inp where isRoot :: HeadingShort -> Bool isRoot HeadingShort{..} = case headingShortParId of Nothing -> True _ -> False isChild :: Int64 -> HeadingShort -> Bool isChild currParent HeadingShort{..} = maybe False (currParent ==) headingShortParId findChildren curr@HeadingShort{..} = let subs = map findChildren $ filter (isChild headingShortId) inp in curr{ headingShortSubs = subs } {-| Creates a list of 'ClockRow's from a list of 'HeadingShort'. 'ClockRow's are matched and created from each 'HeadingShort's document ID. NB: This function needs to be run _after_ the 'HeadingShort' hierarchy is created. It should not be run on a flat list. -} shortsToRows :: [HeadingShort] -> [ClockRow] shortsToRows = go emptyMap where emptyMap :: HashMap Int64 [HeadingShort] emptyMap = HM.empty go m [] = map (\(k, v) -> ClockRow k 0 v) (HM.toList m) go m (h:hs) = let newM = HM.insertWith (++) (headingShortDocId h) [h] m in go newM hs
rzetterberg/orgmode-sql
lib/Database/OrgMode/Export/ClockTable.hs
Haskell
bsd-3-clause
5,556
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} {-# LANGUAGE DeriveGeneric #-} #endif {-# LANGUAGE DeriveDataTypeable #-} #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708 {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} #endif ----------------------------------------------------------------------------- -- | -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : portable -- -- Operations on affine spaces. ----------------------------------------------------------------------------- module Linear.Affine where import Control.Applicative import Control.DeepSeq import Control.Monad (liftM) import Control.Lens import Data.Binary as Binary import Data.Bytes.Serial import Data.Complex (Complex) import Data.Data import Data.Distributive import Data.Foldable as Foldable import Data.Functor.Bind import Data.Functor.Classes import Data.Functor.Rep as Rep import Data.HashMap.Lazy (HashMap) import Data.Hashable import Data.IntMap (IntMap) import Data.Ix import Data.Map (Map) import Data.Serialize as Cereal import Data.Vector (Vector) import Foreign.Storable #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 import GHC.Generics (Generic) #endif #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706 import GHC.Generics (Generic1) #endif import Linear.Epsilon import Linear.Metric import Linear.Plucker import Linear.Quaternion import Linear.V import Linear.V0 import Linear.V1 import Linear.V2 import Linear.V3 import Linear.V4 import Linear.Vector #ifdef HLINT {-# ANN module "HLint: ignore Unused LANGUAGE pragma" #-} #endif -- | An affine space is roughly a vector space in which we have -- forgotten or at least pretend to have forgotten the origin. -- -- > a .+^ (b .-. a) = b@ -- > (a .+^ u) .+^ v = a .+^ (u ^+^ v)@ -- > (a .-. b) ^+^ v = (a .+^ v) .-. q@ class Additive (Diff p) => Affine p where type Diff p :: * -> * infixl 6 .-. -- | Get the difference between two points as a vector offset. (.-.) :: Num a => p a -> p a -> Diff p a infixl 6 .+^ -- | Add a vector offset to a point. (.+^) :: Num a => p a -> Diff p a -> p a infixl 6 .-^ -- | Subtract a vector offset from a point. (.-^) :: Num a => p a -> Diff p a -> p a p .-^ v = p .+^ negated v {-# INLINE (.-^) #-} -- | Compute the quadrance of the difference (the square of the distance) qdA :: (Affine p, Foldable (Diff p), Num a) => p a -> p a -> a qdA a b = Foldable.sum (fmap (join (*)) (a .-. b)) {-# INLINE qdA #-} -- | Distance between two points in an affine space distanceA :: (Floating a, Foldable (Diff p), Affine p) => p a -> p a -> a distanceA a b = sqrt (qdA a b) {-# INLINE distanceA #-} #define ADDITIVEC(CTX,T) instance CTX => Affine T where type Diff T = T ; \ (.-.) = (^-^) ; {-# INLINE (.-.) #-} ; (.+^) = (^+^) ; {-# INLINE (.+^) #-} ; \ (.-^) = (^-^) ; {-# INLINE (.-^) #-} #define ADDITIVE(T) ADDITIVEC((), T) ADDITIVE([]) ADDITIVE(Complex) ADDITIVE(ZipList) ADDITIVE(Maybe) ADDITIVE(IntMap) ADDITIVE(Identity) ADDITIVE(Vector) ADDITIVE(V0) ADDITIVE(V1) ADDITIVE(V2) ADDITIVE(V3) ADDITIVE(V4) ADDITIVE(Plucker) ADDITIVE(Quaternion) ADDITIVE(((->) b)) ADDITIVEC(Ord k, (Map k)) ADDITIVEC((Eq k, Hashable k), (HashMap k)) ADDITIVEC(Dim n, (V n)) -- | A handy wrapper to help distinguish points from vectors at the -- type level newtype Point f a = P (f a) deriving ( Eq, Ord, Show, Read, Monad, Functor, Applicative, Foldable , Eq1, Ord1, Show1, Read1 , Traversable, Apply, Additive, Metric , Fractional , Num, Ix, Storable, Epsilon , Hashable #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 , Generic #endif #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706 , Generic1 #endif #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 708 , Typeable, Data #endif ) instance NFData (f a) => NFData (Point f a) where rnf (P x) = rnf x instance Serial1 f => Serial1 (Point f) where serializeWith f (P p) = serializeWith f p deserializeWith m = P `liftM` deserializeWith m instance Serial (f a) => Serial (Point f a) where serialize (P p) = serialize p deserialize = P `liftM` deserialize instance Binary (f a) => Binary (Point f a) where put (P p) = Binary.put p get = P `liftM` Binary.get instance Serialize (f a) => Serialize (Point f a) where put (P p) = Cereal.put p get = P `liftM` Cereal.get #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708 instance forall f. Typeable1 f => Typeable1 (Point f) where typeOf1 _ = mkTyConApp (mkTyCon3 "linear" "Linear.Affine" "Point") [] `mkAppTy` typeOf1 (undefined :: f a) deriving instance (Data (f a), Typeable1 f, Typeable a) => Data (Point f a) #endif lensP :: Lens' (Point g a) (g a) lensP afb (P a) = P <$> afb a {-# INLINE lensP #-} _Point :: Iso' (Point f a) (f a) _Point = iso (\(P a) -> a) P {-# INLINE _Point #-} instance (t ~ Point g b) => Rewrapped (Point f a) t instance Wrapped (Point f a) where type Unwrapped (Point f a) = f a _Wrapped' = _Point {-# INLINE _Wrapped' #-} instance Bind f => Bind (Point f) where join (P m) = P $ join $ fmap (\(P m')->m') m instance Distributive f => Distributive (Point f) where distribute = P . collect (\(P p) -> p) instance Representable f => Representable (Point f) where type Rep (Point f) = Rep f tabulate f = P (tabulate f) {-# INLINE tabulate #-} index (P xs) = Rep.index xs {-# INLINE index #-} type instance Index (Point f a) = Index (f a) type instance IxValue (Point f a) = IxValue (f a) instance Ixed (f a) => Ixed (Point f a) where ix l = lensP . ix l {-# INLINE ix #-} instance Traversable f => Each (Point f a) (Point f b) a b where each = traverse {-# INLINE each #-} instance R1 f => R1 (Point f) where _x = lensP . _x {-# INLINE _x #-} instance R2 f => R2 (Point f) where _y = lensP . _y {-# INLINE _y #-} _xy = lensP . _xy {-# INLINE _xy #-} instance R3 f => R3 (Point f) where _z = lensP . _z {-# INLINE _z #-} _xyz = lensP . _xyz {-# INLINE _xyz #-} instance R4 f => R4 (Point f) where _w = lensP . _w {-# INLINE _w #-} _xyzw = lensP . _xyzw {-# INLINE _xyzw #-} instance Additive f => Affine (Point f) where type Diff (Point f) = f P x .-. P y = x ^-^ y {-# INLINE (.-.) #-} P x .+^ v = P (x ^+^ v) {-# INLINE (.+^) #-} P x .-^ v = P (x ^-^ v) {-# INLINE (.-^) #-} -- | Vector spaces have origins. origin :: (Additive f, Num a) => Point f a origin = P zero -- | An isomorphism between points and vectors, given a reference -- point. relative :: (Additive f, Num a) => Point f a -> Iso' (Point f a) (f a) relative p0 = iso (.-. p0) (p0 .+^) {-# INLINE relative #-}
phaazon/linear
src/Linear/Affine.hs
Haskell
bsd-3-clause
7,173
module Physics.Falling.Collision.Detection.GJK ( distanceToOrigin , distance , algorithmGJK , closestPoints , initialSimplexResult , SimplexResult ) where import Physics.Falling.Math.Error import Physics.Falling.Math.Transform hiding(distance) import Physics.Falling.Math.AnnotatedVector import Physics.Falling.Shape.ImplicitShape import Physics.Falling.Shape.CSO import Physics.Falling.Collision.Detection.Simplex hiding(dimension) import qualified Physics.Falling.Collision.Detection.Simplex as S (dimension) type SimplexResult v = Either (v, [ Double ], Simplex v, Simplex v) -- need more iterations (v, [ Double ], Simplex v) -- success {-# INLINABLE initialSimplexResult #-} initialSimplexResult :: (Dimension v, Vector v, DotProd v) => v -> SimplexResult v initialSimplexResult initialPoint = let initSimplex = addPoint initialPoint emptySimplex in Left (initialPoint, [1.0], initSimplex, initSimplex) {-# INLINABLE distance #-} distance :: (Dimension v , ImplicitShape g1 v , ImplicitShape g2 v , UnitVector v n , Eq v , Fractional v) => g1 -> g2 -> Double distance g1 g2 = distanceToOrigin cso (neg notZeroDirection) where cso = mkCSO g1 g2 -- initialDirection = -- translation t1 &- translation t2 notZeroDirection = 1.0 -- if lensqr initialDirection /= 0.0 then initialDirection -- else 1.0 {-# INLINABLE closestPoints #-} closestPoints :: (Dimension v , ImplicitShape g1 v , ImplicitShape g2 v , UnitVector v n , Eq v , Fractional v) => g1 -> g2 -> Maybe (v, v) closestPoints g1 g2 = case algorithmGJK cso $ initialSimplexResult initialPoint of Nothing -> Nothing Just (_, b, s) -> Just $ _pointsFromAnnotatedSimplex b s where cso = mkAnnotatedCSO g1 g2 -- initialDirection = 1.0 -- translation t1 &- translation t2 notZeroDirection = 1.0 -- if lensqr initialDirection /= 0.0 then initialDirection -- else 1.0 initialPoint = supportPoint cso (AnnotatedVector notZeroDirection undefined) {-# INLINABLE distanceToOrigin #-} distanceToOrigin :: (Dimension v, ImplicitShape g v, Eq v, DotProd v, Fractional v) => g -> v -> Double distanceToOrigin s initialDirection = case algorithmGJK s $ initialSimplexResult initialPoint of Nothing -> 0.0 Just (projection, _, _) -> len projection where initialPoint = supportPoint s initialDirection {-# INLINABLE algorithmGJK #-} algorithmGJK :: (Dimension v, ImplicitShape g v, Eq v, DotProd v) => g -> SimplexResult v -> Maybe (v, [ Double ], Simplex v) algorithmGJK s (Left (projection, barCoords, lastSimplex, newSimplex)) | (sDim == dimension || lensqr projection <= epsTol * maxLen newSimplex) = Nothing | otherwise = algorithmGJK s $ _stepGJK s lastSimplex newSimplex projection barCoords where sDim = S.dimension newSimplex dimension = dim projection algorithmGJK _ (Right (projection, barCoords, simplex)) = Just (projection, barCoords, simplex) {-# INLINABLE _stepGJK #-} _stepGJK :: (ImplicitShape g v, Eq v, DotProd v) => g -> Simplex v -> Simplex v -> v -> [ Double ] -> SimplexResult v _stepGJK s lastSimplex newSimplex v barCoords = if contains csoPoint lastSimplex || sqlenv - v &. csoPoint <= sqEpsRel * sqlenv || lensqr proj > sqlenv then -- we test for inconsistancies: if the new lower bound -- is greater than the old one something went wrong. -- This should actually nether happen and might be an -- implementation bug… Right $ (v, barCoords, newSimplex) -- terminate the algorithm: distance has acceptable precision else Left (proj, projCoords, newSimplex', projSimplex) where sqlenv = lensqr v csoPoint = supportPoint s $ neg v newSimplex' = addPoint csoPoint newSimplex (proj, projCoords, projSimplex) = projectOrigin newSimplex' {-# INLINABLE _pointsFromAnnotatedSimplex #-} _pointsFromAnnotatedSimplex :: (Vector v, DotProd v) => [ Double ] -> Simplex (AnnotatedVector v (v, v)) -> (v, v) _pointsFromAnnotatedSimplex coords simplex = let (pa, pb) = foldr1 (\(a, b) (a', b') -> (a &+ a', b &+ b')) $ zipWith (\coord (a, b) -> (coord *& a, coord *& b)) coords $ map annotation $ points simplex in (pa, neg pb) {-# INLINABLE _pointFromBarycentricCoordinates #-} _pointFromBarycentricCoordinates :: Vector v => [ Double ] -> [ v ] -> v _pointFromBarycentricCoordinates coords pts = foldr1 (&+) $ zipWith (\coord pt -> pt &* coord) coords pts
sebcrozet/falling
Physics/Falling/Collision/Detection/GJK.hs
Haskell
bsd-3-clause
5,672