code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE BangPatterns, OverloadedStrings #-} module Main where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Data.Aeson import Data.Configurator import Data.Int import Data.Text (Text) import Data.Pool import Database.MySQL.Simple import Database.MySQL.Simple.Result import Database.MySQL.Simple.QueryResults import Prelude hiding (lookup) import Snap.Core import Snap.Http.Server import System.Random import qualified Data.HashMap as HM import qualified Data.ByteString.Char8 as B data RandQuery = RQ !Int !Int instance ToJSON RandQuery where toJSON (RQ i n) = object ["id" .= i, "randomNumber" .= n] instance QueryResults RandQuery where convertResults [fa, fb] [va, vb] = RQ a b where !a = convert fa va !b = convert fb vb convertResults fs vs = convertError fs vs 2 main :: IO () main = do db <- load [Required "cfg/db.cfg"] foos <- mapM (lookup db) ["host", "uname", "pword", "dbase", "dport"] let foos' = sequence foos maybe (putStrLn "No foo") dbSetup foos' dbSetup :: [String] -> IO () dbSetup sets = do pool <- createPool (connect $ getConnInfo sets) close 1 10 50 httpServe config $ site pool config :: Config Snap a config = setAccessLog ConfigNoLog . setErrorLog ConfigNoLog . setPort 8000 $ defaultConfig getConnInfo :: [String] -> ConnectInfo getConnInfo [host, user, pwd, db, port] = defaultConnectInfo { connectHost = host , connectUser = user , connectPassword = pwd , connectDatabase = db , connectPort = read port } getConnInfo _ = defaultConnectInfo site :: Pool Connection -> Snap () site pool = route [ ("json", jsonHandler) , ("db", dbHandler pool) , ("plaintext", writeBS "Hello, World!") ] jsonHandler :: Snap () jsonHandler = do modifyResponse (setContentType "application/json") writeLBS $ encode ( Object $ HM.singleton "message" (String "Hello, World!") ) dbHandler :: Pool Connection -> Snap () dbHandler pool = do modifyResponse (setContentType "application/json") qs <- getQueryParam "queries" runAll pool $ maybe 1 fst (qs >>= B.readInt) runAll :: Pool Connection -> Int -> Snap () runAll pool 1 = do !rs <- take 1 . randomRs (1, 10000) <$> liftIO newStdGen qry <- liftIO $ withResource pool (forM rs . runOne) writeLBS $ encode $ head qry runAll pool i = do !rs <- take i . randomRs (1, 10000) <$> liftIO newStdGen qry <- liftIO $ withResource pool (forM rs . runOne) writeLBS $ encode qry runOne :: Connection -> Int -> IO RandQuery runOne conn = fmap head . query conn "SELECT * FROM World where id=?" . Only
Ocramius/FrameworkBenchmarks
snap/bench/src/Main.hs
bsd-3-clause
2,839
0
13
739
928
475
453
79
1
module Example.InitFunction () where
smurphy8/refactor-patternmatch-with-lens
src/Example/InitFunction.hs
bsd-3-clause
38
0
3
5
9
6
3
1
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Meadowstalk.Model where import Data.ByteString (ByteString) import Data.Int import Data.Text (Text) import Data.Time (UTCTime) import Database.Persist.TH import Database.Persist.Quasi import Meadowstalk.Model.Types ------------------------------------------------------------------------------- share [mkPersist sqlSettings, mkMigrate "migrateModel"] $(persistFileWith lowerCaseSettings "config/model")
HalfWayMan/meadowstalk
src/Meadowstalk/Model.hs
bsd-3-clause
685
0
8
124
95
57
38
16
0
{-| Module: Data.Astro.Time.GregorianCalendar Description: Gregorian Calendar Copyright: Alexander Ignatyev, 2016 Gregorian Calendar was introduced by Pope Gregory XIII. He abolished the days 1582-10-05 to 1582-10-14 inclusive to bring back civil and tropical years back to line. -} module Data.Astro.Time.GregorianCalendar ( isLeapYear , dayNumber , easterDayInYear , gregorianDateAdjustment ) where import Data.Time.Calendar (Day(..), fromGregorian, toGregorian) -- Date after 15 October 1582 belongs to Gregorian Calendar -- Before this date - to Julian Calendar isGregorianDate :: Integer -> Int -> Int -> Bool isGregorianDate y m d = y > gyear || (y == gyear && m > gmonth) || (y == gyear && m == gmonth && d >= gday) where gyear = 1582 gmonth = 10 gday = 15 gregorianDateAdjustment :: Integer -> Int ->Int -> Int gregorianDateAdjustment year month day = if isGregorianDate year month day then let y = if month < 3 then year - 1 else year y' = fromIntegral y a = truncate (y' / 100) in 2 - a + truncate(fromIntegral a/4) else 0 -- | Check Gregorian calendar leap year isLeapYear :: Integer -> Bool isLeapYear year = year `mod` 4 == 0 && (year `mod` 100 /= 0 || year `mod` 400 == 0) -- | Day Number in a year dayNumber :: Day -> Int dayNumber date = (daysBeforeMonth year month) + day where (year, month, day) = toGregorian date -- | Get Easter date -- function uses absolutely crazy Butcher's algorithm easterDayInYear :: Int -> Day easterDayInYear year = let a = year `mod` 19 b = year `div` 100 c = year `mod` 100 d = b `div` 4 e = b `mod` 4 f = (b+8) `div` 25 g = (b-f+1) `div` 3 h = (19*a+b-d-g+15) `mod` 30 i = c `div` 4 k = c `mod` 4 l = (32+2*e+2*i-h-k) `mod` 7 m = (a+11*h+22*l) `div` 451 n' = (h+l-7*m+114) n = n' `div` 31 p = n' `mod` 31 in fromGregorian (fromIntegral year) n (p+1) daysBeforeMonth :: Integer -> Int -> Int daysBeforeMonth year month = let a = if isLeapYear year then 62 else 63 month' = (fromIntegral month) :: Double in if month > 2 then truncate $ ((month' + 1.0) * 30.6) - a else truncate $ (month' - 1.0)*a*0.5
Alexander-Ignatyev/astro
src/Data/Astro/Time/GregorianCalendar.hs
bsd-3-clause
2,256
0
16
585
788
443
345
55
3
{-# OPTIONS_GHC -F -pgmF hspec-discover -optF --module-name=Spec #-}
rimmington/haskell-continuous
test/Spec.hs
cc0-1.0
68
0
2
7
3
2
1
1
0
<?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="fr-FR"> <title>Sequence Scanner | ZAP Extension</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/sequence/src/main/javahelp/org/zaproxy/zap/extension/sequence/resources/help_fr_FR/helpset_fr_FR.hs
apache-2.0
978
80
66
160
415
210
205
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} -------------------------------------------------------------------------------- -- | -- Module : Data.Comp.Multi.Derive.Ordering -- Copyright : (c) 2011 Patrick Bahr, Tom Hvitved -- License : BSD3 -- Maintainer : Tom Hvitved <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC Extensions) -- -- Automatically derive instances of @OrdHF@. -- -------------------------------------------------------------------------------- module Data.Comp.Multi.Derive.Ordering ( OrdHF(..), makeOrdHF ) where import Data.Comp.Derive.Utils import Data.Comp.Multi.Ordering import Data.List import Data.Maybe import Language.Haskell.TH hiding (Cxt) compList :: [Ordering] -> Ordering compList = fromMaybe EQ . find (/= EQ) {-| Derive an instance of 'OrdHF' for a type constructor of any parametric kind taking at least three arguments. -} makeOrdHF :: Name -> Q [Dec] makeOrdHF fname = do TyConI (DataD _ name args constrs _) <- abstractNewtypeQ $ reify fname let args' = init args -- covariant argument let coArg :: Name = tyVarBndrName $ last args' let argNames = map (VarT . tyVarBndrName) (init args') let complType = foldl AppT (ConT name) argNames let classType = AppT (ConT ''OrdHF) complType constrs' :: [(Name,[Type])] <- mapM normalConExp constrs compareHFDecl <- funD 'compareHF (compareHFClauses coArg constrs') return [InstanceD [] classType [compareHFDecl]] where compareHFClauses :: Name -> [(Name,[Type])] -> [ClauseQ] compareHFClauses _ [] = [] compareHFClauses coArg constrs = let constrs' = constrs `zip` [1..] constPairs = [(x,y)| x<-constrs', y <- constrs'] in map (genClause coArg) constPairs genClause coArg ((c,n),(d,m)) | n == m = genEqClause coArg c | n < m = genLtClause c d | otherwise = genGtClause c d genEqClause :: Name -> (Name,[Type]) -> ClauseQ genEqClause coArg (constr, args) = do varXs <- newNames (length args) "x" varYs <- newNames (length args) "y" let patX = ConP constr $ map VarP varXs let patY = ConP constr $ map VarP varYs body <- eqDBody coArg (zip3 varXs varYs args) return $ Clause [patX, patY] (NormalB body) [] eqDBody :: Name -> [(Name, Name, Type)] -> ExpQ eqDBody coArg x = [|compList $(listE $ map (eqDB coArg) x)|] eqDB :: Name -> (Name, Name, Type) -> ExpQ eqDB coArg (x, y, tp) | not (containsType tp (VarT coArg)) = [| compare $(varE x) $(varE y) |] | otherwise = [| kcompare $(varE x) $(varE y) |] genLtClause (c, _) (d, _) = clause [recP c [], recP d []] (normalB [| LT |]) [] genGtClause (c, _) (d, _) = clause [recP c [], recP d []] (normalB [| GT |]) []
spacekitteh/compdata
src/Data/Comp/Multi/Derive/Ordering.hs
bsd-3-clause
3,145
0
14
915
926
494
432
56
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} module Network.HTTP.Download.Verified ( verifiedDownload , recoveringHttp , DownloadRequest(..) , drRetryPolicyDefault , HashCheck(..) , CheckHexDigest(..) , LengthCheck , VerifiedDownloadException(..) ) where import qualified Data.List as List import qualified Data.ByteString as ByteString import qualified Data.ByteString.Base64 as B64 import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Control.Applicative import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger (logDebug, MonadLogger) import Control.Retry (recovering,limitRetries,RetryPolicy,constantDelay) import "cryptohash" Crypto.Hash import Crypto.Hash.Conduit (sinkHash) import Data.Byteable (toBytes) import Data.ByteString (ByteString) import Data.ByteString.Char8 (readInteger) import Data.Conduit import Data.Conduit.Binary (sourceHandle, sinkHandle) import Data.Foldable (traverse_,for_) import Data.Monoid import Data.String import Data.Text.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Data.Typeable (Typeable) import GHC.IO.Exception (IOException(..),IOErrorType(..)) import Network.HTTP.Client (getUri, path) import Network.HTTP.Simple (Request, HttpException, httpSink, getResponseHeaders) import Network.HTTP.Types.Header (hContentLength, hContentMD5) import Path import Prelude -- Fix AMP warning import System.Directory import System.FilePath ((<.>)) import System.IO -- | A request together with some checks to perform. data DownloadRequest = DownloadRequest { drRequest :: Request , drHashChecks :: [HashCheck] , drLengthCheck :: Maybe LengthCheck , drRetryPolicy :: RetryPolicy } -- | Default to retrying thrice with a short constant delay. drRetryPolicyDefault :: RetryPolicy drRetryPolicyDefault = limitRetries 3 <> constantDelay onehundredMilliseconds where onehundredMilliseconds = 100000 data HashCheck = forall a. (Show a, HashAlgorithm a) => HashCheck { hashCheckAlgorithm :: a , hashCheckHexDigest :: CheckHexDigest } deriving instance Show HashCheck data CheckHexDigest = CheckHexDigestString String | CheckHexDigestByteString ByteString | CheckHexDigestHeader ByteString deriving Show instance IsString CheckHexDigest where fromString = CheckHexDigestString type LengthCheck = Int -- | An exception regarding verification of a download. data VerifiedDownloadException = WrongContentLength Request Int -- expected ByteString -- actual (as listed in the header) | WrongStreamLength Request Int -- expected Int -- actual | WrongDigest Request String -- algorithm CheckHexDigest -- expected String -- actual (shown) deriving (Typeable) instance Show VerifiedDownloadException where show (WrongContentLength req expected actual) = "Download expectation failure: ContentLength header\n" ++ "Expected: " ++ show expected ++ "\n" ++ "Actual: " ++ displayByteString actual ++ "\n" ++ "For: " ++ show (getUri req) show (WrongStreamLength req expected actual) = "Download expectation failure: download size\n" ++ "Expected: " ++ show expected ++ "\n" ++ "Actual: " ++ show actual ++ "\n" ++ "For: " ++ show (getUri req) show (WrongDigest req algo expected actual) = "Download expectation failure: content hash (" ++ algo ++ ")\n" ++ "Expected: " ++ displayCheckHexDigest expected ++ "\n" ++ "Actual: " ++ show actual ++ "\n" ++ "For: " ++ show (getUri req) instance Exception VerifiedDownloadException -- This exception is always caught and never thrown outside of this module. data VerifyFileException = WrongFileSize Int -- expected Integer -- actual (as listed by hFileSize) deriving (Show, Typeable) instance Exception VerifyFileException -- Show a ByteString that is known to be UTF8 encoded. displayByteString :: ByteString -> String displayByteString = Text.unpack . Text.strip . Text.decodeUtf8 -- Show a CheckHexDigest in human-readable format. displayCheckHexDigest :: CheckHexDigest -> String displayCheckHexDigest (CheckHexDigestString s) = s ++ " (String)" displayCheckHexDigest (CheckHexDigestByteString s) = displayByteString s ++ " (ByteString)" displayCheckHexDigest (CheckHexDigestHeader h) = show (B64.decodeLenient h) ++ " (Header. unencoded: " ++ show h ++ ")" -- | Make sure that the hash digest for a finite stream of bytes -- is as expected. -- -- Throws WrongDigest (VerifiedDownloadException) sinkCheckHash :: MonadThrow m => Request -> HashCheck -> Consumer ByteString m () sinkCheckHash req HashCheck{..} = do digest <- sinkHashUsing hashCheckAlgorithm let actualDigestString = show digest let actualDigestHexByteString = digestToHexByteString digest let actualDigestBytes = toBytes digest let passedCheck = case hashCheckHexDigest of CheckHexDigestString s -> s == actualDigestString CheckHexDigestByteString b -> b == actualDigestHexByteString CheckHexDigestHeader b -> B64.decodeLenient b == actualDigestHexByteString || B64.decodeLenient b == actualDigestBytes -- A hack to allow hackage tarballs to download. -- They should really base64-encode their md5 header as per rfc2616#sec14.15. -- https://github.com/commercialhaskell/stack/issues/240 || b == actualDigestHexByteString unless passedCheck $ throwM $ WrongDigest req (show hashCheckAlgorithm) hashCheckHexDigest actualDigestString assertLengthSink :: MonadThrow m => Request -> LengthCheck -> ZipSink ByteString m () assertLengthSink req expectedStreamLength = ZipSink $ do Sum actualStreamLength <- CL.foldMap (Sum . ByteString.length) when (actualStreamLength /= expectedStreamLength) $ throwM $ WrongStreamLength req expectedStreamLength actualStreamLength -- | A more explicitly type-guided sinkHash. sinkHashUsing :: (Monad m, HashAlgorithm a) => a -> Consumer ByteString m (Digest a) sinkHashUsing _ = sinkHash -- | Turns a list of hash checks into a ZipSink that checks all of them. hashChecksToZipSink :: MonadThrow m => Request -> [HashCheck] -> ZipSink ByteString m () hashChecksToZipSink req = traverse_ (ZipSink . sinkCheckHash req) -- 'Control.Retry.recovering' customized for HTTP failures recoveringHttp :: (MonadMask m, MonadIO m) => RetryPolicy -> m a -> m a recoveringHttp retryPolicy = #if MIN_VERSION_retry(0,7,0) recovering retryPolicy handlers . const #else recovering retryPolicy handlers #endif where handlers = [const $ Handler alwaysRetryHttp,const $ Handler retrySomeIO] alwaysRetryHttp :: Monad m => HttpException -> m Bool alwaysRetryHttp _ = return True retrySomeIO :: Monad m => IOException -> m Bool retrySomeIO e = return $ case ioe_type e of -- hGetBuf: resource vanished (Connection reset by peer) ResourceVanished -> True -- conservatively exclude all others _ -> False -- | Copied and extended version of Network.HTTP.Download.download. -- -- Has the following additional features: -- * Verifies that response content-length header (if present) -- matches expected length -- * Limits the download to (close to) the expected # of bytes -- * Verifies that the expected # bytes were downloaded (not too few) -- * Verifies md5 if response includes content-md5 header -- * Verifies the expected hashes -- -- Throws VerifiedDownloadException. -- Throws IOExceptions related to file system operations. -- Throws HttpException. verifiedDownload :: (MonadIO m, MonadLogger m) => DownloadRequest -> Path Abs File -- ^ destination -> (Maybe Integer -> Sink ByteString IO ()) -- ^ custom hook to observe progress -> m Bool -- ^ Whether a download was performed verifiedDownload DownloadRequest{..} destpath progressSink = do let req = drRequest whenM' (liftIO getShouldDownload) $ do $logDebug $ "Downloading " <> decodeUtf8With lenientDecode (path req) liftIO $ do createDirectoryIfMissing True dir recoveringHttp drRetryPolicy $ withBinaryFile fptmp WriteMode $ \h -> httpSink req (go h) renameFile fptmp fp where whenM' mp m = do p <- mp if p then m >> return True else return False fp = toFilePath destpath fptmp = fp <.> "tmp" dir = toFilePath $ parent destpath getShouldDownload = do fileExists <- doesFileExist fp if fileExists -- only download if file does not match expectations then not <$> fileMatchesExpectations -- or if it doesn't exist yet else return True -- precondition: file exists -- TODO: add logging fileMatchesExpectations = ((checkExpectations >> return True) `catch` \(_ :: VerifyFileException) -> return False) `catch` \(_ :: VerifiedDownloadException) -> return False checkExpectations = bracket (openFile fp ReadMode) hClose $ \h -> do for_ drLengthCheck $ checkFileSizeExpectations h sourceHandle h $$ getZipSink (hashChecksToZipSink drRequest drHashChecks) -- doesn't move the handle checkFileSizeExpectations h expectedFileSize = do fileSizeInteger <- hFileSize h when (fileSizeInteger > toInteger (maxBound :: Int)) $ throwM $ WrongFileSize expectedFileSize fileSizeInteger let fileSize = fromInteger fileSizeInteger when (fileSize /= expectedFileSize) $ throwM $ WrongFileSize expectedFileSize fileSizeInteger checkContentLengthHeader headers expectedContentLength = case List.lookup hContentLength headers of Just lengthBS -> do let lengthStr = displayByteString lengthBS when (lengthStr /= show expectedContentLength) $ throwM $ WrongContentLength drRequest expectedContentLength lengthBS _ -> return () go h res = do let headers = getResponseHeaders res mcontentLength = do hLength <- List.lookup hContentLength headers (i,_) <- readInteger hLength return i for_ drLengthCheck $ checkContentLengthHeader headers let hashChecks = (case List.lookup hContentMD5 headers of Just md5BS -> [ HashCheck { hashCheckAlgorithm = MD5 , hashCheckHexDigest = CheckHexDigestHeader md5BS } ] Nothing -> [] ) ++ drHashChecks maybe id (\len -> (CB.isolate len =$=)) drLengthCheck $ getZipSink ( hashChecksToZipSink drRequest hashChecks *> maybe (pure ()) (assertLengthSink drRequest) drLengthCheck *> ZipSink (sinkHandle h) *> ZipSink (progressSink mcontentLength))
AndreasPK/stack
src/Network/HTTP/Download/Verified.hs
bsd-3-clause
12,138
0
20
3,231
2,377
1,262
1,115
-1
-1
{-# LANGUAGE OverloadedStrings , QuasiQuotes , PackageImports #-} -- This module defines the main function to handle the messages that comes from users (web or device users). module Handlers ( handleMessage , parsMessage , setMessageValue ) where import Database.Persist.Postgresql import Data.Aeson.Types import Data.Aeson import Data.Conduit.Pool import Data.Default import Data.IORef import Data.Monoid ((<>)) import Data.Text (Text,pack,unpack,empty) import Data.Text.Encoding import qualified Data.HashMap.Strict as HM import qualified "unordered-containers" Data.HashSet as HS import qualified Data.Map as M import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as BS import Control.Applicative import Control.Monad (mzero,when) import Control.Monad.Logger import Control.Monad.Trans.Resource (runResourceT) import Network.PushNotify.Gcm import Network.PushNotify.Mpns import Network.PushNotify.General import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TChan (TChan, writeTChan) import Blaze.ByteString.Builder.Char.Utf8 (fromText) import Connect4 import DataBase import Extra runDBAct p a = runResourceT . runNoLoggingT $ runSqlPool a p setMessageValue :: MsgFromPlayer -> Value setMessageValue m = let message = case m of Cancel -> [(pack "Cancel" .= pack "")] Movement mov -> [(pack "Movement" .= (pack $ show mov) )] NewGame usr -> [(pack "NewGame" .= usr)] Winner usr -> [(pack "Winner" .= usr)] in (Object $ HM.fromList message) getPushNotif :: Value -> PushNotification getPushNotif (Object o) = def {gcmNotif = Just $ def { data_object = Just o } } getPushNotif _ = def parsMsg :: Value -> Parser MsgFromPlayer parsMsg (Object v) = setMsg <$> v .:? "Cancel" <*> v .:? "Movement" <*> v .:? "NewGame" parsMsg _ = mzero parsMessage :: Value -> Maybe MsgFromPlayer parsMessage = parseMaybe parsMsg setMsg :: Maybe Text -> Maybe Text -> Maybe Text -> MsgFromPlayer setMsg (Just _) _ _ = Cancel setMsg _ (Just a) _ = Movement ((read $ unpack a) :: Int) setMsg _ _ (Just a) = NewGame a handleMessage :: Pool Connection -> WebUsers -> PushManager -> Identifier -> Text -> MsgFromPlayer -> IO () handleMessage pool webUsers man id1 user1 msg = do case msg of Cancel -> do--Cancel mId2 <- getOpponentId user1 case mId2 of Just (id2,_) -> sendMessage Cancel id2 _ -> return () deleteGame user1 Movement mov -> do--New Movement mId2 <- getOpponentId user1 game <- getGame user1 case (mId2,game) of (Nothing,_) -> sendMessage Cancel id1 (_,Nothing) -> sendMessage Cancel id1 (Just (id2,user2),Just g) -> do if gamesTurn (entityVal g) /= user1 then return () else do sendMessage (Movement mov) id2 let newBoard = if gamesUser1 (entityVal g) == user1 then newMovement mov 1 (gamesMatrix(entityVal g)) else newMovement mov (-1) (gamesMatrix(entityVal g)) case checkWinner newBoard of Nothing -> runDBAct pool $ update (entityKey (g)) [GamesMatrix =. newBoard, GamesTurn =. user2] Just x -> do let msg = if x == 1 then Winner $ gamesUser1 (entityVal g) else Winner $ gamesUser2 (entityVal g) sendMessage msg id1 sendMessage msg id2 deleteGame user1 return () NewGame user2 -> do--New Game res1 <- getIdentifier user2 res2 <- isPlaying user2 case (res1,res2) of (Just id2,False) -> do sendMessage (NewGame user1) id2 runDBAct pool $ insert $ Games user1 user2 user2 emptyBoard return () (_,_) -> sendMessage Cancel id1 _ -> return () where sendMessage msg id = case id of Web chan -> do putStrLn $ "Sending on channel: " ++ show msg atomically $ writeTChan chan msg Dev d -> do putStrLn $ "Sending on PushServer: " ++ show msg res <- sendPush man (getPushNotif $ setMessageValue msg) (HS.singleton d) if HM.null (failed res) then return () else fail "Problem Communicating with Push Servers" putStrLn $ "PushResult: " ++ show res deleteGame usr = do runDBAct pool $ deleteBy $ UniqueUser1 usr runDBAct pool $ deleteBy $ UniqueUser2 usr getGame usr = do game1 <- runDBAct pool $ getBy $ UniqueUser1 usr case game1 of Just _ -> return game1 _ -> runDBAct pool $ getBy $ UniqueUser2 usr getIdentifier usr = do res1 <- runDBAct pool $ getBy $ UniqueUser usr res2 <- return $ HM.lookup usr webUsers case (res1,res2) of (Just a,_) -> return $ Just $ Dev (devicesIdentifier (entityVal a)) (_,Just (chan,_)) -> return $ Just $ Web chan _ -> return Nothing getOpponentId usr = do game1 <- runDBAct pool $ getBy $ UniqueUser1 usr game2 <- runDBAct pool $ getBy $ UniqueUser2 usr case (game1,game2) of (Just g , _) -> do let opp = gamesUser2 (entityVal g) res <- getIdentifier opp return $ res >>= \id -> Just (id,opp) (_ , Just g) -> do let opp = gamesUser1 (entityVal g) res <- getIdentifier opp return $ res >>= \id -> Just (id,opp) _ -> return Nothing isPlaying usr = do game1 <- runDBAct pool $ getBy $ UniqueUser1 usr game2 <- runDBAct pool $ getBy $ UniqueUser2 usr case (game1,game2) of (Nothing,Nothing) -> return False _ -> return True
MarcosPividori/GSoC-Communicating-with-mobile-devices
test/Connect4/Yesod-App/Handlers.hs
mit
7,678
0
33
3,570
1,934
970
964
143
20
{- | Module : $Header$ Description : after parsing XML message a list of XMLcommands is produced, containing commands that need to be executed Copyright : uni-bremen and DFKI License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable PGIP.XMLstate contains the description of the XMLstate and a function that produces such a state -} module PGIP.XMLstate where import Common.Utils (getEnvDef, trim) import Common.ToXml import Driver.Options import Text.XML.Light import Data.List (find, intercalate) import Data.Time.Clock.POSIX (getPOSIXTime) import System.IO (Handle, hPutStrLn, hFlush) {- Converts any line text that does not stand for a comment into a theoryitem element -} genProofStep :: String -> Element genProofStep str = let iname = case trim str of "" -> "whitespace" -- empty line generates a whitespace element '#' : _ -> "comment" -- comments start with # _ -> "theoryitem" -- convert line into a theoryitem element in unode iname $ mkText $ str ++ "\n" -- | adds xml structure to unstructured code addPGIPMarkup :: String -> Element addPGIPMarkup str = case lines str of [] -> error "addPgipMarkUp.empty" hd : tl -> unode "parseresult" $ add_attr (mkAttr "thyname" "whatever") (unode "opentheory" $ mkText hd) : map genProofStep tl ++ [unode "closetheory" ()] {- - other types of mark ups : - opengoal / closegoal - openblock / closeblock - -} -- generates a pgipelem element that contains the input text genPgipElem :: String -> Element genPgipElem = unode "pgipelem" . mkText {- generates a normalresponse element that has a pgml element containing the output text -} genNormalResponse :: Node t => String -> t -> Element genNormalResponse areaValue = unode "normalresponse" . add_attr (mkAttr "area" areaValue) . unode "pgml" -- same as above, just for an error instead of normal output genErrorResponse :: Bool -> String -> Element genErrorResponse fatality = add_attrs [ mkAttr "fatality" "fatal" | fatality] . unode "errorresponse" . unode "pgmltext" . mkText {- | It inserts a given string into the XML packet as normal output -} addPGIPAnswer :: String -> String -> CmdlPgipState -> CmdlPgipState addPGIPAnswer msgtxt errmsg st = if useXML st then let resp = if null msgtxt then st else addPGIPElement st $ genNormalResponse "message" $ mkText msgtxt in if null errmsg then resp else addPGIPElement resp $ genErrorResponse False errmsg else addToMsg errmsg $ addToMsg msgtxt st {- | It inserts a given string into the XML packet as error output -} addPGIPError :: String -> CmdlPgipState -> CmdlPgipState addPGIPError str st = case str of "" -> st _ | useXML st -> addPGIPElement st $ genErrorResponse True str _ -> addToMsg str st -- extracts the xml package in XML.Light format (namely the Content type) addPGIPAttributes :: CmdlPgipState -> Element -> Element addPGIPAttributes pgipData e = (add_attrs ((case refSeqNb pgipData of Nothing -> [] Just v -> [mkAttr "refseq" v]) ++ [ mkAttr "tag" $ name pgipData , mkAttr "class" "pg" , mkAttr "id" $ pgipId pgipData , mkAttr "seq" $ show $ seqNb pgipData ]) $ unode "pgip" ()) { elContent = [Elem e]} {- adds one element to the end of the content of the xml packet that represents the current output of the interface to the broker -} addPGIPElement :: CmdlPgipState -> Element -> CmdlPgipState addPGIPElement pgData el = pgData { xmlElements = addPGIPAttributes pgData el : xmlElements pgData , seqNb = seqNb pgData + 1 } {- adds a ready element at the end of the xml packet that represents the current output of the interface to the broker -} addPGIPReady :: CmdlPgipState -> CmdlPgipState addPGIPReady pgData = addPGIPElement pgData $ unode "ready" () -- | State that keeps track of the comunication between Hets and the Broker data CmdlPgipState = CmdlPgipState { pgipId :: String , name :: String , seqNb :: Int , refSeqNb :: Maybe String , msgs :: [String] , xmlElements :: [Element] , hout :: Handle , hin :: Handle , stop :: Bool , resendMsgIfTimeout :: Bool , useXML :: Bool , maxWaitTime :: Int } -- | Generates an empty CmdlPgipState genCMDLPgipState :: Bool -> Handle -> Handle -> Int -> IO CmdlPgipState genCMDLPgipState swXML h_in h_out timeOut = do pgId <- genPgipID return CmdlPgipState { pgipId = pgId , name = "Hets" , seqNb = 1 , refSeqNb = Nothing , msgs = [] , xmlElements = [] , hin = h_in , hout = h_out , stop = False , resendMsgIfTimeout = True , useXML = swXML , maxWaitTime = timeOut } -- | Generates the id of the session between Hets and the Broker genPgipID :: IO String genPgipID = do t1 <- getEnvDef "HOSTNAME" "" t2 <- getEnvDef "USER" "" t3 <- getPOSIXTime return $ t1 ++ "/" ++ t2 ++ "/" ++ show t3 -- | Concatenates the input string to the message stored in the state addToMsg :: String -> CmdlPgipState -> CmdlPgipState addToMsg str pgD = if null str then pgD else pgD { msgs = str : msgs pgD } -- | Resets the content of the message stored in the state resetPGIPData :: CmdlPgipState -> CmdlPgipState resetPGIPData pgD = pgD { msgs = [] , xmlElements = [] } {- the PGIP protocol defines the pgip element as containing a single subelement. -} convertPGIPDataToString :: CmdlPgipState -> String convertPGIPDataToString = intercalate "\n" . reverse . map showElement . xmlElements isRemote :: HetcatsOpts -> Bool isRemote opts = connectP opts /= -1 || listen opts /= -1 sendPGIPData :: HetcatsOpts -> CmdlPgipState -> IO CmdlPgipState sendPGIPData opts pgData = do let xmlMsg = convertPGIPDataToString pgData pgData' = addToMsg xmlMsg pgData sendMSGData opts pgData' sendMSGData :: HetcatsOpts -> CmdlPgipState -> IO CmdlPgipState sendMSGData opts pgData = do let msg = intercalate "\n" $ reverse $ msgs pgData if isRemote opts then hPutStrLn (hout pgData) msg else putIfVerbose opts 1 msg hFlush $ hout pgData return pgData -- | List of all possible commands inside an XML packet data CmdlXMLcommands = XmlExecute String | XmlExit | XmlProverInit | XmlAskpgip | XmlStartQuiet | XmlStopQuiet | XmlOpenGoal String | XmlCloseGoal String | XmlGiveUpGoal String | XmlUnknown String | XmlParseScript String | XmlUndo | XmlRedo | XmlForget String | XmlOpenTheory String | XmlCloseTheory String | XmlCloseFile String | XmlLoadFile String deriving (Eq, Show) -- extracts the seq attribute value to be used as reference number elsewhere getRefseqNb :: String -> Maybe String getRefseqNb input = let xmlTree = parseXML input elRef = find (\ x -> case x of Elem dt -> qName (elName dt) == "pgip" _ -> False) xmlTree in case elRef of Nothing -> Nothing Just el -> case el of Elem dt -> case find (\ x -> qName (attrKey x) == "seq") $ elAttribs dt of Nothing -> Nothing Just elatr -> Just $ attrVal elatr _ -> Nothing {- | parses the xml message creating a list of commands that it needs to execute -} parseXMLTree :: [Content] -> [CmdlXMLcommands] -> [CmdlXMLcommands] parseXMLTree xmltree acc = case xmltree of Elem info : ls -> case parseXMLElement info of Just c -> parseXMLTree ls (c : acc) Nothing -> parseXMLTree (elContent info ++ ls) acc _ : ls -> parseXMLTree ls acc [] -> acc parseXMLElement :: Element -> Maybe CmdlXMLcommands parseXMLElement info = let cnt = strContent info in case qName $ elName info of "proverinit" -> Just XmlProverInit "proverexit" -> Just XmlExit "startquiet" -> Just XmlStartQuiet "stopquiet" -> Just XmlStopQuiet "opengoal" -> Just $ XmlOpenGoal cnt "proofstep" -> Just $ XmlExecute cnt "closegoal" -> Just $ XmlCloseGoal cnt "giveupgoal" -> Just $ XmlGiveUpGoal cnt "spurioscmd" -> Just $ XmlExecute cnt "dostep" -> Just $ XmlExecute cnt "editobj" -> Just $ XmlExecute cnt "undostep" -> Just XmlUndo "redostep" -> Just XmlRedo "forget" -> Just $ XmlForget cnt "opentheory" -> Just $ XmlOpenTheory cnt "theoryitem" -> Just $ XmlExecute cnt "closetheory" -> Just $ XmlCloseTheory cnt "closefile" -> Just $ XmlCloseFile cnt "loadfile" -> Just $ XmlLoadFile cnt "askpgip" -> Just XmlAskpgip "parsescript" -> Just $ XmlParseScript cnt "pgip" -> Nothing s -> Just $ XmlUnknown s {- | Given a packet (a normal string or a xml formated string), the function converts it into a list of commands -} parseMsg :: CmdlPgipState -> String -> [CmdlXMLcommands] parseMsg st input = if useXML st then parseXMLTree (parseXML input) [] else concatMap (\ x -> [ XmlExecute x | not $ null $ trim x ]) $ lines input
keithodulaigh/Hets
PGIP/XMLstate.hs
gpl-2.0
9,135
0
21
2,234
2,207
1,127
1,080
195
23
{-# LANGUAGE CPP , DataKinds , PolyKinds , GADTs , TypeOperators , TypeFamilies , ExistentialQuantification #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- 2016.05.24 -- | -- Module : Language.Hakaru.Syntax.DatumABT -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC-only -- -- Stuff that depends on both "Language.Hakaru.Syntax.ABT" and -- "Language.Hakaru.Syntax.Datum"; factored out to avoid the cyclic -- dependency issues. ---------------------------------------------------------------- module Language.Hakaru.Syntax.DatumABT ( fromGBranch , toGBranch ) where import Language.Hakaru.Syntax.ABT import Language.Hakaru.Syntax.Datum ---------------------------------------------------------------- ---------------------------------------------------------------- fromGBranch :: (ABT syn abt) => GBranch a (abt '[] b) -> Branch a abt b fromGBranch (GBranch pat vars e) = Branch pat (binds_ vars e) toGBranch :: (ABT syn abt) => Branch a abt b -> GBranch a (abt '[] b) toGBranch (Branch pat body) = uncurry (GBranch pat) (caseBinds body) ---------------------------------------------------------------- ----------------------------------------------------------- fin.
zaxtax/hakaru
haskell/Language/Hakaru/Syntax/DatumABT.hs
bsd-3-clause
1,538
0
11
344
202
116
86
25
1
{-# LANGUAGE CPP, MagicHash #-} -- | Dynamically lookup up values from modules and loading them. module ETA.Main.DynamicLoading ( #ifdef GHCI -- * Loading plugins loadPlugins, -- * Force loading information forceLoadModuleInterfaces, forceLoadNameModuleInterface, forceLoadTyCon, -- * Finding names lookupRdrNameInModuleForPlugins, -- * Loading values getValueSafely, getHValueSafely, lessUnsafeCoerce #endif ) where #ifdef GHCI import ETA.Interactive.Linker ( linkModule, getHValue ) import ETA.BasicTypes.SrcLoc ( noSrcSpan ) import ETA.Main.Finder ( findImportedModule, cannotFindModule ) import ETA.TypeCheck.TcRnMonad ( initTcInteractive, initIfaceTcRn ) import ETA.Iface.LoadIface ( loadPluginInterface ) import ETA.BasicTypes.RdrName ( RdrName, Provenance(..), ImportSpec(..), ImpDeclSpec(..) , ImpItemSpec(..), mkGlobalRdrEnv, lookupGRE_RdrName , gre_name, mkRdrQual ) import ETA.BasicTypes.OccName ( mkVarOcc ) import ETA.Rename.RnNames ( gresFromAvails ) import ETA.Main.DynFlags import ETA.Main.Plugins ( Plugin, CommandLineOption ) import ETA.Prelude.PrelNames ( pluginTyConName ) import ETA.Main.HscTypes import ETA.BasicTypes.BasicTypes ( HValue ) import ETA.Types.TypeRep ( mkTyConTy, pprTyThingCategory ) import ETA.Types.Type ( Type, eqType ) import ETA.Types.TyCon ( TyCon ) import ETA.BasicTypes.Name ( Name, nameModule_maybe ) import ETA.BasicTypes.Id ( idType ) import ETA.BasicTypes.Module ( Module, ModuleName ) import ETA.Utils.Panic import ETA.Utils.FastString import ETA.Main.ErrUtils import ETA.Utils.Outputable import ETA.Utils.Exception import ETA.Main.Hooks import Data.Maybe ( mapMaybe ) import GHC.Exts ( unsafeCoerce# ) loadPlugins :: HscEnv -> IO [(ModuleName, Plugin, [CommandLineOption])] loadPlugins hsc_env = do { plugins <- mapM (loadPlugin hsc_env) to_load ; return $ map attachOptions $ to_load `zip` plugins } where dflags = hsc_dflags hsc_env to_load = pluginModNames dflags attachOptions (mod_nm, plug) = (mod_nm, plug, options) where options = [ option | (opt_mod_nm, option) <- pluginModNameOpts dflags , opt_mod_nm == mod_nm ] loadPlugin :: HscEnv -> ModuleName -> IO Plugin loadPlugin hsc_env mod_name = do { let plugin_rdr_name = mkRdrQual mod_name (mkVarOcc "plugin") dflags = hsc_dflags hsc_env ; mb_name <- lookupRdrNameInModuleForPlugins hsc_env mod_name plugin_rdr_name ; case mb_name of { Nothing -> throwGhcExceptionIO (CmdLineError $ showSDoc dflags $ hsep [ ptext (sLit "The module"), ppr mod_name , ptext (sLit "did not export the plugin name") , ppr plugin_rdr_name ]) ; Just name -> do { plugin_tycon <- forceLoadTyCon hsc_env pluginTyConName ; mb_plugin <- getValueSafely hsc_env name (mkTyConTy plugin_tycon) ; case mb_plugin of Nothing -> throwGhcExceptionIO (CmdLineError $ showSDoc dflags $ hsep [ ptext (sLit "The value"), ppr name , ptext (sLit "did not have the type") , ppr pluginTyConName, ptext (sLit "as required")]) Just plugin -> return plugin } } } -- | Force the interfaces for the given modules to be loaded. The 'SDoc' parameter is used -- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded. forceLoadModuleInterfaces :: HscEnv -> SDoc -> [Module] -> IO () forceLoadModuleInterfaces hsc_env doc modules = (initTcInteractive hsc_env $ initIfaceTcRn $ mapM_ (loadPluginInterface doc) modules) >> return () -- | Force the interface for the module containing the name to be loaded. The 'SDoc' parameter is used -- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded. forceLoadNameModuleInterface :: HscEnv -> SDoc -> Name -> IO () forceLoadNameModuleInterface hsc_env reason name = do let name_modules = mapMaybe nameModule_maybe [name] forceLoadModuleInterfaces hsc_env reason name_modules -- | Load the 'TyCon' associated with the given name, come hell or high water. Fails if: -- -- * The interface could not be loaded -- * The name is not that of a 'TyCon' -- * The name did not exist in the loaded module forceLoadTyCon :: HscEnv -> Name -> IO TyCon forceLoadTyCon hsc_env con_name = do forceLoadNameModuleInterface hsc_env (ptext (sLit "contains a name used in an invocation of loadTyConTy")) con_name mb_con_thing <- lookupTypeHscEnv hsc_env con_name case mb_con_thing of Nothing -> throwCmdLineErrorS dflags $ missingTyThingError con_name Just (ATyCon tycon) -> return tycon Just con_thing -> throwCmdLineErrorS dflags $ wrongTyThingError con_name con_thing where dflags = hsc_dflags hsc_env -- | Loads the value corresponding to a 'Name' if that value has the given 'Type'. This only provides limited safety -- in that it is up to the user to ensure that that type corresponds to the type you try to use the return value at! -- -- If the value found was not of the correct type, returns @Nothing@. Any other condition results in an exception: -- -- * If we could not load the names module -- * If the thing being loaded is not a value -- * If the Name does not exist in the module -- * If the link failed getValueSafely :: HscEnv -> Name -> Type -> IO (Maybe a) getValueSafely hsc_env val_name expected_type = do mb_hval <- lookupHook getValueSafelyHook getHValueSafely dflags hsc_env val_name expected_type case mb_hval of Nothing -> return Nothing Just hval -> do value <- lessUnsafeCoerce dflags "getValueSafely" hval return (Just value) where dflags = hsc_dflags hsc_env getHValueSafely :: HscEnv -> Name -> Type -> IO (Maybe HValue) getHValueSafely hsc_env val_name expected_type = do forceLoadNameModuleInterface hsc_env (ptext (sLit "contains a name used in an invocation of getHValueSafely")) val_name -- Now look up the names for the value and type constructor in the type environment mb_val_thing <- lookupTypeHscEnv hsc_env val_name case mb_val_thing of Nothing -> throwCmdLineErrorS dflags $ missingTyThingError val_name Just (AnId id) -> do -- Check the value type in the interface against the type recovered from the type constructor -- before finally casting the value to the type we assume corresponds to that constructor if expected_type `eqType` idType id then do -- Link in the module that contains the value, if it has such a module case nameModule_maybe val_name of Just mod -> do linkModule hsc_env mod return () Nothing -> return () -- Find the value that we just linked in and cast it given that we have proved it's type hval <- getHValue hsc_env val_name return (Just hval) else return Nothing Just val_thing -> throwCmdLineErrorS dflags $ wrongTyThingError val_name val_thing where dflags = hsc_dflags hsc_env -- | Coerce a value as usual, but: -- -- 1) Evaluate it immediately to get a segfault early if the coercion was wrong -- -- 2) Wrap it in some debug messages at verbosity 3 or higher so we can see what happened -- if it /does/ segfault lessUnsafeCoerce :: DynFlags -> String -> a -> IO b lessUnsafeCoerce dflags context what = do debugTraceMsg dflags 3 $ (ptext $ sLit "Coercing a value in") <+> (text context) <> (ptext $ sLit "...") output <- evaluate (unsafeCoerce# what) debugTraceMsg dflags 3 $ ptext $ sLit "Successfully evaluated coercion" return output -- | Finds the 'Name' corresponding to the given 'RdrName' in the -- context of the 'ModuleName'. Returns @Nothing@ if no such 'Name' -- could be found. Any other condition results in an exception: -- -- * If the module could not be found -- * If we could not determine the imports of the module -- -- Can only be used for looking up names while loading plugins (and is -- *not* suitable for use within plugins). The interface file is -- loaded very partially: just enough that it can be used, without its -- rules and instances affecting (and being linked from!) the module -- being compiled. This was introduced by 57d6798. -- -- See Note [Care with plugin imports] in LoadIface. lookupRdrNameInModuleForPlugins :: HscEnv -> ModuleName -> RdrName -> IO (Maybe Name) lookupRdrNameInModuleForPlugins hsc_env mod_name rdr_name = do -- First find the package the module resides in by searching exposed packages and home modules found_module <- findImportedModule hsc_env mod_name Nothing case found_module of Found _ mod -> do -- Find the exports of the module (_, mb_iface) <- initTcInteractive hsc_env $ initIfaceTcRn $ loadPluginInterface doc mod case mb_iface of Just iface -> do -- Try and find the required name in the exports let decl_spec = ImpDeclSpec { is_mod = mod_name, is_as = mod_name , is_qual = False, is_dloc = noSrcSpan } provenance = Imported [ImpSpec decl_spec ImpAll] env = mkGlobalRdrEnv (gresFromAvails provenance (mi_exports iface)) case lookupGRE_RdrName rdr_name env of [gre] -> return (Just (gre_name gre)) [] -> return Nothing _ -> panic "lookupRdrNameInModule" Nothing -> throwCmdLineErrorS dflags $ hsep [ptext (sLit "Could not determine the exports of the module"), ppr mod_name] err -> throwCmdLineErrorS dflags $ cannotFindModule dflags mod_name err where dflags = hsc_dflags hsc_env doc = ptext (sLit "contains a name used in an invocation of lookupRdrNameInModule") wrongTyThingError :: Name -> TyThing -> SDoc wrongTyThingError name got_thing = hsep [ptext (sLit "The name"), ppr name, ptext (sLit "is not that of a value but rather a"), pprTyThingCategory got_thing] missingTyThingError :: Name -> SDoc missingTyThingError name = hsep [ptext (sLit "The name"), ppr name, ptext (sLit "is not in the type environment: are you sure it exists?")] throwCmdLineErrorS :: DynFlags -> SDoc -> IO a throwCmdLineErrorS dflags = throwCmdLineError . showSDoc dflags throwCmdLineError :: String -> IO a throwCmdLineError = throwGhcExceptionIO . CmdLineError #endif
alexander-at-github/eta
compiler/ETA/Main/DynamicLoading.hs
bsd-3-clause
11,076
0
26
2,946
2,065
1,085
980
2
0
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , MagicHash , UnboxedTuples , ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} -- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN -- and Control.Concurrent.SampleVar imports. ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (concurrency) -- -- A common interface to a collection of useful concurrency -- abstractions. -- ----------------------------------------------------------------------------- module Control.Concurrent ( -- * Concurrent Haskell -- $conc_intro -- * Basic concurrency operations ThreadId, myThreadId, forkIO, forkFinally, forkIOWithUnmask, killThread, throwTo, -- ** Threads with affinity forkOn, forkOnWithUnmask, getNumCapabilities, setNumCapabilities, threadCapability, -- * Scheduling -- $conc_scheduling yield, -- ** Blocking -- $blocking -- ** Waiting threadDelay, threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM, -- * Communication abstractions module Control.Concurrent.MVar, module Control.Concurrent.Chan, module Control.Concurrent.QSem, module Control.Concurrent.QSemN, -- * Bound Threads -- $boundthreads rtsSupportsBoundThreads, forkOS, isCurrentThreadBound, runInBoundThread, runInUnboundThread, -- * Weak references to ThreadIds mkWeakThreadId, -- * GHC's implementation of concurrency -- |This section describes features specific to GHC's -- implementation of Concurrent Haskell. -- ** Haskell threads and Operating System threads -- $osthreads -- ** Terminating the program -- $termination -- ** Pre-emption -- $preemption -- ** Deadlock -- $deadlock ) where import Prelude import Control.Exception.Base as Exception import GHC.Exception import GHC.Conc hiding (threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM) import qualified GHC.Conc import GHC.IO ( IO(..), unsafeInterleaveIO, unsafeUnmask ) import GHC.IORef ( newIORef, readIORef, writeIORef ) import GHC.Base import System.Posix.Types ( Fd ) import Foreign.StablePtr import Foreign.C.Types import Control.Monad #ifdef mingw32_HOST_OS import Foreign.C import System.IO import Data.Maybe (Maybe(..)) #endif import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent.QSem import Control.Concurrent.QSemN {- $conc_intro The concurrency extension for Haskell is described in the paper /Concurrent Haskell/ <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>. Concurrency is \"lightweight\", which means that both thread creation and context switching overheads are extremely low. Scheduling of Haskell threads is done internally in the Haskell runtime system, and doesn't make use of any operating system-supplied thread packages. However, if you want to interact with a foreign library that expects your program to use the operating system-supplied thread package, you can do so by using 'forkOS' instead of 'forkIO'. Haskell threads can communicate via 'MVar's, a kind of synchronised mutable variable (see "Control.Concurrent.MVar"). Several common concurrency abstractions can be built from 'MVar's, and these are provided by the "Control.Concurrent" library. In GHC, threads may also communicate via exceptions. -} {- $conc_scheduling Scheduling may be either pre-emptive or co-operative, depending on the implementation of Concurrent Haskell (see below for information related to specific compilers). In a co-operative system, context switches only occur when you use one of the primitives defined in this module. This means that programs such as: > main = forkIO (write 'a') >> write 'b' > where write c = putChar c >> write c will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@, instead of some random interleaving of @a@s and @b@s. In practice, cooperative multitasking is sufficient for writing simple graphical user interfaces. -} {- $blocking Different Haskell implementations have different characteristics with regard to which operations block /all/ threads. Using GHC without the @-threaded@ option, all foreign calls will block all other Haskell threads in the system, although I\/O operations will not. With the @-threaded@ option, only foreign calls with the @unsafe@ attribute will block all other threads. -} -- | fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- -- > forkFinally action and_then = -- > mask $ \restore -> -- > forkIO $ try (restore action) >>= and_then -- -- This function is useful for informing the parent when a child -- terminates, for example. -- -- /Since: 4.6.0.0/ forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then -- --------------------------------------------------------------------------- -- Bound Threads {- $boundthreads #boundthreads# Support for multiple operating system threads and bound threads as described below is currently only available in the GHC runtime system if you use the /-threaded/ option when linking. Other Haskell systems do not currently support multiple operating system threads. A bound thread is a haskell thread that is /bound/ to an operating system thread. While the bound thread is still scheduled by the Haskell run-time system, the operating system thread takes care of all the foreign calls made by the bound thread. To a foreign library, the bound thread will look exactly like an ordinary operating system thread created using OS functions like @pthread_create@ or @CreateThread@. Bound threads can be created using the 'forkOS' function below. All foreign exported functions are run in a bound thread (bound to the OS thread that called the function). Also, the @main@ action of every Haskell program is run in a bound thread. Why do we need this? Because if a foreign library is called from a thread created using 'forkIO', it won't have access to any /thread-local state/ - state variables that have specific values for each OS thread (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some libraries (OpenGL, for example) will not work from a thread created using 'forkIO'. They work fine in threads created using 'forkOS' or when called from @main@ or from a @foreign export@. In terms of performance, 'forkOS' (aka bound) threads are much more expensive than 'forkIO' (aka unbound) threads, because a 'forkOS' thread is tied to a particular OS thread, whereas a 'forkIO' thread can be run by any OS thread. Context-switching between a 'forkOS' thread and a 'forkIO' thread is many times more expensive than between two 'forkIO' threads. Note in particular that the main program thread (the thread running @Main.main@) is always a bound thread, so for good concurrency performance you should ensure that the main thread is not doing repeated communication with other threads in the system. Typically this means forking subthreads to do the work using 'forkIO', and waiting for the results in the main thread. -} -- | 'True' if bound threads are supported. -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound' -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will -- fail. foreign import ccall rtsSupportsBoundThreads :: Bool {- | Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the first argument, and returns the 'ThreadId' of the newly created thread. However, 'forkOS' creates a /bound/ thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads"). Using 'forkOS' instead of 'forkIO' makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use 'forkOS' instead of 'forkIO' to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the @-threaded@ option when linking your program, and to make sure the foreign import is not marked @unsafe@. -} forkOS :: IO () -> IO ThreadId foreign export ccall forkOS_entry :: StablePtr (IO ()) -> IO () foreign import ccall "forkOS_entry" forkOS_entry_reimported :: StablePtr (IO ()) -> IO () forkOS_entry :: StablePtr (IO ()) -> IO () forkOS_entry stableAction = do action <- deRefStablePtr stableAction action foreign import ccall forkOS_createThread :: StablePtr (IO ()) -> IO CInt failNonThreaded :: IO a failNonThreaded = fail $ "RTS doesn't support multiple OS threads " ++"(use ghc -threaded when linking)" forkOS action0 | rtsSupportsBoundThreads = do mv <- newEmptyMVar b <- Exception.getMaskingState let -- async exceptions are masked in the child if they are masked -- in the parent, as for forkIO (see #1048). forkOS_createThread -- creates a thread with exceptions masked by default. action1 = case b of Unmasked -> unsafeUnmask action0 MaskedInterruptible -> action0 MaskedUninterruptible -> uninterruptibleMask_ action0 action_plus = Exception.catch action1 childHandler entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus) err <- forkOS_createThread entry when (err /= 0) $ fail "Cannot create OS thread." tid <- takeMVar mv freeStablePtr entry return tid | otherwise = failNonThreaded -- | Returns 'True' if the calling thread is /bound/, that is, if it is -- safe to use foreign libraries that rely on thread-local state from the -- calling thread. isCurrentThreadBound :: IO Bool isCurrentThreadBound = IO $ \ s# -> case isCurrentThreadBound# s# of (# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #) {- | Run the 'IO' computation passed as the first argument. If the calling thread is not /bound/, a bound thread is created temporarily. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. You can wrap a series of foreign function calls that rely on thread-local state with @runInBoundThread@ so that you can use them without knowing whether the current thread is /bound/. -} runInBoundThread :: IO a -> IO a runInBoundThread action | rtsSupportsBoundThreads = do bound <- isCurrentThreadBound if bound then action else do ref <- newIORef undefined let action_plus = Exception.try action >>= writeIORef ref bracket (newStablePtr action_plus) freeStablePtr (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>= unsafeResult | otherwise = failNonThreaded {- | Run the 'IO' computation passed as the first argument. If the calling thread is /bound/, an unbound thread is created temporarily using 'forkIO'. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. Use this function /only/ in the rare case that you have actually observed a performance loss due to the use of bound threads. A program that doesn't need it's main thread to be bound and makes /heavy/ use of concurrency (e.g. a web server), might want to wrap it's @main@ action in @runInUnboundThread@. Note that exceptions which are thrown to the current thread are thrown in turn to the thread that is executing the given computation. This ensures there's always a way of killing the forked thread. -} runInUnboundThread :: IO a -> IO a runInUnboundThread action = do bound <- isCurrentThreadBound if bound then do mv <- newEmptyMVar mask $ \restore -> do tid <- forkIO $ Exception.try (restore action) >>= putMVar mv let wait = takeMVar mv `Exception.catch` \(e :: SomeException) -> Exception.throwTo tid e >> wait wait >>= unsafeResult else action unsafeResult :: Either SomeException a -> IO a unsafeResult = either Exception.throwIO return -- --------------------------------------------------------------------------- -- threadWaitRead/threadWaitWrite -- | Block the current thread until data is available to read on the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitRead', use -- 'GHC.Conc.closeFdWith'. threadWaitRead :: Fd -> IO () threadWaitRead fd #ifdef mingw32_HOST_OS -- we have no IO manager implementing threadWaitRead on Windows. -- fdReady does the right thing, but we have to call it in a -- separate thread, otherwise threadWaitRead won't be interruptible, -- and this only works with -threaded. | threaded = withThread (waitFd fd 0) | otherwise = case fd of 0 -> do _ <- hWaitForInput stdin (-1) return () -- hWaitForInput does work properly, but we can only -- do this for stdin since we know its FD. _ -> error "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput" #else = GHC.Conc.threadWaitRead fd #endif -- | Block the current thread until data can be written to the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitWrite', use -- 'GHC.Conc.closeFdWith'. threadWaitWrite :: Fd -> IO () threadWaitWrite fd #ifdef mingw32_HOST_OS | threaded = withThread (waitFd fd 1) | otherwise = error "threadWaitWrite requires -threaded on Windows" #else = GHC.Conc.threadWaitWrite fd #endif -- | Returns an STM action that can be used to wait for data -- to read from a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- /Since: 4.7.0.0/ threadWaitReadSTM :: Fd -> IO (STM (), IO ()) threadWaitReadSTM fd #ifdef mingw32_HOST_OS | threaded = do v <- newTVarIO Nothing mask_ $ void $ forkIO $ do result <- try (waitFd fd 0) atomically (writeTVar v $ Just result) let waitAction = do result <- readTVar v case result of Nothing -> retry Just (Right ()) -> return () Just (Left e) -> throwSTM (e :: IOException) let killAction = return () return (waitAction, killAction) | otherwise = error "threadWaitReadSTM requires -threaded on Windows" #else = GHC.Conc.threadWaitReadSTM fd #endif -- | Returns an STM action that can be used to wait until data -- can be written to a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- /Since: 4.7.0.0/ threadWaitWriteSTM :: Fd -> IO (STM (), IO ()) threadWaitWriteSTM fd #ifdef mingw32_HOST_OS | threaded = do v <- newTVarIO Nothing mask_ $ void $ forkIO $ do result <- try (waitFd fd 1) atomically (writeTVar v $ Just result) let waitAction = do result <- readTVar v case result of Nothing -> retry Just (Right ()) -> return () Just (Left e) -> throwSTM (e :: IOException) let killAction = return () return (waitAction, killAction) | otherwise = error "threadWaitWriteSTM requires -threaded on Windows" #else = GHC.Conc.threadWaitWriteSTM fd #endif #ifdef mingw32_HOST_OS foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool withThread :: IO a -> IO a withThread io = do m <- newEmptyMVar _ <- mask_ $ forkIO $ try io >>= putMVar m x <- takeMVar m case x of Right a -> return a Left e -> throwIO (e :: IOException) waitFd :: Fd -> CInt -> IO () waitFd fd write = do throwErrnoIfMinus1_ "fdReady" $ fdReady (fromIntegral fd) write iNFINITE 0 iNFINITE :: CInt iNFINITE = 0xFFFFFFFF -- urgh foreign import ccall safe "fdReady" fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt #endif -- --------------------------------------------------------------------------- -- More docs {- $osthreads #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and are managed entirely by the GHC runtime. Typically Haskell threads are an order of magnitude or two more efficient (in terms of both time and space) than operating system threads. The downside of having lightweight threads is that only one can run at a time, so if one thread blocks in a foreign call, for example, the other threads cannot continue. The GHC runtime works around this by making use of full OS threads where necessary. When the program is built with the @-threaded@ option (to link against the multithreaded version of the runtime), a thread making a @safe@ foreign call will not block the other threads in the system; another OS thread will take over running Haskell threads until the original call returns. The runtime maintains a pool of these /worker/ threads so that multiple Haskell threads can be involved in external calls simultaneously. The "System.IO" library manages multiplexing in its own way. On Windows systems it uses @safe@ foreign calls to ensure that threads doing I\/O operations don't block the whole runtime, whereas on Unix systems all the currently blocked I\/O requests are managed by a single thread (the /IO manager thread/) using a mechanism such as @epoll@ or @kqueue@, depending on what is provided by the host operating system. The runtime will run a Haskell thread using any of the available worker OS threads. If you need control over which particular OS thread is used to run a given Haskell thread, perhaps because you need to call a foreign library that uses OS-thread-local state, then you need bound threads (see "Control.Concurrent#boundthreads"). If you don't use the @-threaded@ option, then the runtime does not make use of multiple OS threads. Foreign calls will block all other running Haskell threads until the call returns. The "System.IO" library still does multiplexing, so there can be multiple threads doing I\/O, and this is handled internally by the runtime using @select@. -} {- $termination In a standalone GHC program, only the main thread is required to terminate in order for the process to terminate. Thus all other forked threads will simply terminate at the same time as the main thread (the terminology for this kind of behaviour is \"daemonic threads\"). If you want the program to wait for child threads to finish before exiting, you need to program this yourself. A simple mechanism is to have each child thread write to an 'MVar' when it completes, and have the main thread wait on all the 'MVar's before exiting: > myForkIO :: IO () -> IO (MVar ()) > myForkIO io = do > mvar <- newEmptyMVar > forkFinally io (\_ -> putMVar mvar ()) > return mvar Note that we use 'forkFinally' to make sure that the 'MVar' is written to even if the thread dies or is killed for some reason. A better method is to keep a global list of all child threads which we should wait for at the end of the program: > children :: MVar [MVar ()] > children = unsafePerformIO (newMVar []) > > waitForChildren :: IO () > waitForChildren = do > cs <- takeMVar children > case cs of > [] -> return () > m:ms -> do > putMVar children ms > takeMVar m > waitForChildren > > forkChild :: IO () -> IO ThreadId > forkChild io = do > mvar <- newEmptyMVar > childs <- takeMVar children > putMVar children (mvar:childs) > forkFinally io (\_ -> putMVar mvar ()) > > main = > later waitForChildren $ > ... The main thread principle also applies to calls to Haskell from outside, using @foreign export@. When the @foreign export@ed function is invoked, it starts a new main thread, and it returns when this main thread terminates. If the call causes new threads to be forked, they may remain in the system after the @foreign export@ed function has returned. -} {- $preemption GHC implements pre-emptive multitasking: the execution of threads are interleaved in a random fashion. More specifically, a thread may be pre-empted whenever it allocates some memory, which unfortunately means that tight loops which do no allocation tend to lock out other threads (this only seems to happen with pathological benchmark-style code, however). The rescheduling timer runs on a 20ms granularity by default, but this may be altered using the @-i\<n\>@ RTS option. After a rescheduling \"tick\" the running thread is pre-empted as soon as possible. One final note: the @aaaa@ @bbbb@ example may not work too well on GHC (see Scheduling, above), due to the locking on a 'System.IO.Handle'. Only one thread may hold the lock on a 'System.IO.Handle' at any one time, so if a reschedule happens while a thread is holding the lock, the other thread won't be able to run. The upshot is that the switch from @aaaa@ to @bbbbb@ happens infrequently. It can be improved by lowering the reschedule tick period. We also have a patch that causes a reschedule whenever a thread waiting on a lock is woken up, but haven't found it to be useful for anything other than this example :-) -} {- $deadlock GHC attempts to detect when threads are deadlocked using the garbage collector. A thread that is not reachable (cannot be found by following pointers from live objects) must be deadlocked, and in this case the thread is sent an exception. The exception is either 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', 'NonTermination', or 'Deadlock', depending on the way in which the thread is deadlocked. Note that this feature is intended for debugging, and should not be relied on for the correct operation of your program. There is no guarantee that the garbage collector will be accurate enough to detect your deadlock, and no guarantee that the garbage collector will run in a timely enough manner. Basically, the same caveats as for finalizers apply to deadlock detection. There is a subtle interaction between deadlock detection and finalizers (as created by 'Foreign.Concurrent.newForeignPtr' or the functions in "System.Mem.Weak"): if a thread is blocked waiting for a finalizer to run, then the thread will be considered deadlocked and sent an exception. So preferably don't do this, but if you have no alternative then it is possible to prevent the thread from being considered deadlocked by making a 'StablePtr' pointing to it. Don't forget to release the 'StablePtr' later with 'freeStablePtr'. -}
jwiegley/ghc-release
libraries/base/Control/Concurrent.hs
gpl-3.0
24,699
0
21
6,017
1,962
1,040
922
133
3
<?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="sk-SK"> <title>Advanced SQLInjection Scanner</title> <maps> <homeID>sqliplugin</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/sqliplugin/src/main/javahelp/help_sk_SK/helpset_sk_SK.hs
apache-2.0
981
77
66
157
409
207
202
-1
-1
<?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="it-IT"> <title>Access Control Testing | ZAP Extension</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>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/accessControl/src/main/javahelp/org/zaproxy/zap/extension/accessControl/resources/help_it_IT/helpset_it_IT.hs
apache-2.0
776
63
53
120
337
170
167
-1
-1
{-# LANGUAGE GADTs, KindSignatures, PatternSynonyms #-} module ShouldCompile where import Data.Kind (Type) data X :: (Type -> Type) -> Type -> Type where Y :: f a -> X f (Maybe a) pattern C :: a -> X Maybe (Maybe a) pattern C x = Y (Just x)
sdiehl/ghc
testsuite/tests/patsyn/should_compile/T8968-1.hs
bsd-3-clause
247
0
9
54
102
54
48
-1
-1
{-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE RankNTypes #-} module T12918b where class Foo1 a where -- These ones should be rejected bar1 :: a -> b default bar1 :: b -> a bar1 = undefined bar2 :: a -> b default bar2 :: x bar2 = undefined bar3 :: a -> b default bar3 :: a -> Int bar3 = undefined bar4 :: a -> Int default bar4 :: a -> b bar4 = undefined -- These ones are OK baz1 :: forall b c. a -> b -> c default baz1 :: forall b c. a -> b -> c baz1 = undefined baz2 :: forall b c. a -> b -> c default baz2 :: forall c b. a -> b -> c baz2 = undefined baz3 :: a -> b -> c default baz3 :: a -> x -> y baz3 = undefined
ezyang/ghc
testsuite/tests/typecheck/should_fail/T12918b.hs
bsd-3-clause
728
0
10
255
236
135
101
25
0
{-# LANGUAGE FlexibleContexts #-} module FailDueToGivenOverlapping where class C a where class D a where dop :: a -> () instance C a => D [a] -- should succeed since we can't learn anything more for 'a' foo :: (C a, D [Int]) => a -> () foo x = dop [x] class E a where eop :: a -> () instance E [a] where eop = undefined -- should fail since we can never be sure that we learnt -- everything about the free unification variable. bar :: E [Int] => () -> () bar _ = eop [undefined]
ezyang/ghc
testsuite/tests/typecheck/should_fail/FailDueToGivenOverlapping.hs
bsd-3-clause
492
0
8
113
170
90
80
-1
-1
module Level1 where (..--) = undefined :: () (..-+) = undefined :: () (..++) = undefined :: ()
olsner/ghc
testsuite/tests/ghci/prog017/Level1.hs
bsd-3-clause
96
0
5
19
40
27
13
4
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.StablePtr -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- This module is part of the Foreign Function Interface (FFI) and will usually -- be imported via the module "Foreign". -- ----------------------------------------------------------------------------- module Foreign.StablePtr ( -- * Stable references to Haskell values StablePtr -- abstract , newStablePtr , deRefStablePtr , freeStablePtr , castStablePtrToPtr , castPtrToStablePtr , -- ** The C-side interface -- $cinterface ) where import GHC.Stable -- $cinterface -- -- The following definition is available to C programs inter-operating with -- Haskell code when including the header @HsFFI.h@. -- -- > typedef void *HsStablePtr; /* C representation of a StablePtr */ -- -- Note that no assumptions may be made about the values representing stable -- pointers. In fact, they need not even be valid memory addresses. The only -- guarantee provided is that if they are passed back to Haskell land, the -- function 'deRefStablePtr' will be able to reconstruct the -- Haskell value referred to by the stable pointer.
tolysz/prepare-ghcjs
spec-lts8/base/Foreign/StablePtr.hs
bsd-3-clause
1,520
0
4
323
64
53
11
11
0
module Song where import Data.List (intercalate) import Data.Char (toUpper, toLower) song n = if n == 0 then "" else song (n-1) ++ "\n" ++ verse n verse n = line1 n ++ line2 n ++ line3 n ++ line4 n numToString :: Int -> String numToString 1 = "one" numToString 2 = "two" numToString 3 = "three" numToString 4 = "four" numToString 5 = "five" numToString 6 = "six" numToString 7 = "seven" numToString 8 = "eight" numToString 9 = "nine" numToString 10 = "ten" men :: Int -> String men n | n > 1 = "men" | otherwise = "man" menCount :: Int -> String menCount n = numToString n ++ " " ++ men n cap :: String -> String cap [] = [] cap (x:xs) = toUpper x : xs range :: Int -> [Int] range n = take n $ iterate pred n line1 n = (cap . numToString) n ++ " " ++ men n ++ " went to mow\n" line2 _ = "Went to mow a meadow\n" line3 n = let allMen = map menCount $ range n menString = intercalate ", " allMen in (cap menString) ++ " and his dog\n" line4 = line2
dirkz/Thinking_Functionally_With_Haskell
1/Song.hs
isc
988
0
10
244
426
213
213
37
2
{-# Language ScopedTypeVariables, OverloadedStrings #-} module Unison.UnisonFile where import qualified Data.Foldable as Foldable import Data.Bifunctor (second) import Data.Map (Map) import qualified Data.Map as Map import Unison.Reference (Reference) import Unison.DataDeclaration (DataDeclaration, DataDeclaration') import Unison.DataDeclaration (EffectDeclaration, EffectDeclaration'(..)) import Unison.DataDeclaration (hashDecls, toDataDecl, withEffectDecl) import qualified Unison.DataDeclaration as DD import qualified Data.Text as Text import qualified Unison.Type as Type import Unison.Term (Term,AnnotatedTerm) import qualified Unison.Term as Term import Unison.Type (AnnotatedType) import qualified Data.Set as Set import Unison.Var (Var) import qualified Unison.Var as Var data UnisonFile v = UnisonFile { dataDeclarations :: Map v (Reference, DataDeclaration v), effectDeclarations :: Map v (Reference, EffectDeclaration v), term :: Term v } deriving (Show) type CtorLookup = Map String (Reference, Int) bindBuiltins :: Var v => [(v, Term v)] -> [(v, Reference)] -> [(v, Reference)] -> UnisonFile v -> UnisonFile v bindBuiltins dataAndEffectCtors termBuiltins typeBuiltins (UnisonFile d e t) = UnisonFile (second (DD.bindBuiltins typeBuiltins) <$> d) (second (withEffectDecl (DD.bindBuiltins typeBuiltins)) <$> e) (Term.bindBuiltins dataAndEffectCtors termBuiltins typeBuiltins t) data Env v a = Env -- Data declaration name to hash and its fully resolved form { datas :: Map v (Reference, DataDeclaration' v a) -- Effect declaration name to hash and its fully resolved form , effects :: Map v (Reference, EffectDeclaration' v a) -- Substitutes away any free variables bound by `datas` or `effects` -- (for instance, free type variables or free term variables that -- reference constructors of `datas` or `effects`) , resolveTerm :: AnnotatedTerm v a -> AnnotatedTerm v a -- Substitutes away any free variables bound by `datas` or `effects` , resolveType :: AnnotatedType v a -> AnnotatedType v a -- `String` to `(Reference, ConstructorId)` , constructorLookup :: CtorLookup } -- This function computes hashes for data and effect declarations, and -- also returns a function for resolving strings to (Reference, ConstructorId) -- for parsing of pattern matching environmentFor :: forall v . Var v => [(v, Reference)] -> [(v, Reference)] -> Map v (DataDeclaration v) -> Map v (EffectDeclaration v) -> Env v () environmentFor termBuiltins typeBuiltins0 dataDecls0 effectDecls0 = let -- ignore builtin types that will be shadowed by user-defined data/effects typeBuiltins = [ (v, t) | (v, t) <- typeBuiltins0, Map.notMember v dataDecls0 && Map.notMember v effectDecls0] dataDecls = DD.bindBuiltins typeBuiltins <$> dataDecls0 effectDecls = withEffectDecl (DD.bindBuiltins typeBuiltins) <$> effectDecls0 hashDecls' = hashDecls (Map.union dataDecls (toDataDecl <$> effectDecls)) allDecls = Map.fromList [ (v, (r,de)) | (v,r,de) <- hashDecls' ] dataDecls' = Map.difference allDecls effectDecls effectDecls' = second EffectDeclaration <$> Map.difference allDecls dataDecls typeEnv :: [(v, Reference)] typeEnv = Map.toList (fst <$> dataDecls') ++ Map.toList (fst <$> effectDecls') dataDecls'' = second (DD.bindBuiltins typeEnv) <$> dataDecls' effectDecls'' = second (DD.withEffectDecl (DD.bindBuiltins typeEnv)) <$> effectDecls' dataRefs = Set.fromList $ (fst <$> Foldable.toList dataDecls'') termFor :: Reference -> Int -> AnnotatedTerm v () termFor r cid = if Set.member r dataRefs then Term.constructor() r cid else Term.request() r cid -- Map `Optional.None` to `Term.constructor() ...` or `Term.request() ...` dataAndEffectCtors = [ (Var.named (Text.pack s), termFor r cid) | (s, (r,cid)) <- Map.toList ctorLookup ] typesByName = Map.toList $ (fst <$> dataDecls'') `Map.union` (fst <$> effectDecls'') ctorLookup = Map.fromList (constructors' =<< hashDecls') in Env dataDecls'' effectDecls'' (Term.bindBuiltins dataAndEffectCtors termBuiltins typesByName) (Type.bindBuiltins typesByName) ctorLookup constructors' :: Var v => (v, Reference, DataDeclaration v) -> [(String, (Reference, Int))] constructors' (typeSymbol, r, dd) = let qualCtorName ((ctor,_), i) = (Text.unpack $ mconcat [Var.qualifiedName typeSymbol, ".", Var.qualifiedName ctor], (r, i)) in qualCtorName <$> DD.constructors dd `zip` [0..]
paulp/unison
parser-typechecker/src/Unison/UnisonFile.hs
mit
4,770
0
15
1,025
1,276
710
566
81
2
-- Copyright 2015-2016 Yury Gribov -- -- Use of this source code is governed by MIT license that can be -- found in the LICENSE.txt file. import qualified System.Environment import qualified System.Random import qualified System.Exit import qualified Data.Maybe import qualified Board import qualified Support usage :: IO () usage = do progname <- System.Environment.getProgName putStrLn $ "Usage: runghc " ++ progname ++ " size numel [seed]" parse_args :: System.Random.StdGen -> [String] -> Either String (Int, Int, System.Random.StdGen) parse_args rdef args = let parse_args' :: [String] -> Either String (Int, Int, Maybe System.Random.StdGen) parse_args' [size, numel] = Right (read size, read numel, Nothing) parse_args' [size, numel, seed] = let r = System.Random.mkStdGen $ read seed in Right (read size, read numel, Just r) parse_args' _ = Left "unexpected number of arguments" res = parse_args' args in case res of Left msg -> Left msg Right (sz, n, r) -> if sz * sz < n then Left "number of elements is too big" else Right (sz, n, Data.Maybe.fromMaybe rdef r) main :: IO () main = do rdef <- System.Random.getStdGen args <- System.Environment.getArgs let parsed_args = parse_args rdef args case parsed_args of Left msg -> Support.report_error msg Right (size, numel, r) -> case Board.genrand size numel r of Left msg -> Support.report_error ("failed to generate board: " ++ msg) Right (b, _) -> putStr $ Board.pretty_print b
yugr/sudoku
src/GenRand.hs
mit
1,583
0
15
374
490
257
233
39
5
module Pitch.Network.Proxy (runProxy) where import Pitch.Network import Pitch.Players import Pitch.Players.Network import Pitch.Game import Pitch.Card import Control.Concurrent import Control.Monad import Data.Aeson import Network.HTTP import Network.URI import Network.HTTP.Base import System.Environment import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.Text as T getURI :: IO URI getURI = do putStrLn "What server are you connecting to?" server <- getLine case parseURI server of Just uri -> return uri Nothing -> do putStrLn "Invalid server" getURI mkPostRequest :: URI -> String -> Request String mkPostRequest uri body = Request { rqURI = uri , rqMethod = POST , rqHeaders = [ mkHeader HdrContentType "application/x-www-form-urlencoded" , mkHeader HdrContentLength (show (length body)) ] , rqBody = body } postJSON :: ToJSON a => URI -> a -> IO () postJSON uri obj = let responseJSON = L.unpack $ encode obj pRequest = mkPostRequest uri responseJSON in do response <- simpleHTTP pRequest body <- getResponseBody response let parsed = decode (L.pack body) :: Maybe (Status, GameState, [Card]) case parsed of Just (Failure m, _, _) -> putStrLn $ "Server says: " ++ m _ -> return () runProxy :: Player -> IO () runProxy p = do uri <- getURI authResponse <- simpleHTTP . getRequest $ show uri key <- getResponseBody authResponse let uri' = uri{uriPath = '/' : urlEncode (init key)} forever $ do response <- simpleHTTP (getRequest (show uri')) body <- getResponseBody response let parsed = decode (L.pack body) :: Maybe NetStatus case parsed of Nothing -> return () Just (NetStatus messages (pgs, action, pid)) -> do forM_ messages putStrLn case action of Wait -> return () BidAction -> do (amount, msuit) <- (mkBid p) pid pgs postJSON uri' (amount, msuit) PlayAction -> do card <- (mkPlay p) pid pgs postJSON uri' card threadDelay 500000
benweitzman/Pitch
src/Pitch/Network/Proxy.hs
mit
2,978
11
13
1,406
674
354
320
56
4
main = putStrLn "Hello, Haskell"
JordanRobinson/seven_languages
Haskell/SevenLang/src/Main.hs
mit
33
1
4
5
12
4
8
1
1
{-# LANGUAGE OverloadedStrings #-} module CommandParser where import Data.Attoparsec.ByteString.Char8 import Data.Attoparsec.Combinator import qualified Data.Text.Lazy as L import Data.Text.Encoding import Control.Applicative data Command = Retrieve | Delete | New deriving Show parseCommand :: Parser Command parseCommand = choice [ Retrieve <$ string "Retrieve" , Delete <$ string "Delete" , New <$ string "New" ] parseCommandAndArgument :: Parser (Command, Int) parseCommandAndArgument = do command <- parseCommand char ' ' argument <- parseArgument return (command, argument) parseArgument :: Parser Int parseArgument = decimal parse :: L.Text -> Either String (Command, Int) parse s = parseOnly parseCommandAndArgument ((encodeUtf8 . L.toStrict) s)
svdberg/thrift-haskell
CommandParser.hs
mit
827
0
10
170
214
118
96
23
1
module Server.Packet ( -- * Pipes PacketParseException (..) , decoder , encoder -- * Handshake , InboundPacketHandshake (..) , getInPacketHandshake , OutboundPacketHandshake (..) , putOutPacketHandshake -- * Login , InboundPacketLogin (..) , getInPacketLogin , OutboundPacketLogin (..) , putOutPacketLogin -- * Session , InboundPacketSession (..) , getInPacketSession , OutboundPacketSession (..) , putOutPacketSession ) where import Control.Applicative import Control.Exception import qualified Control.Monad.State.Strict as S import Data.Word import Data.Typeable import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.Binary.Put import Data.Binary.Get import Pipes import Pipes.Binary decoder :: Monad m => Get a -> Producer ByteString m r -> Producer a m r decoder getter = decoder_ where decoder_ p0 = do x <- lift (next p0) case x of Left r -> return r Right (bs, p1) -> do (ea, p2) <- lift $ S.runStateT (decodeGet getter) (yield bs >> p1) case ea of Left e -> throw (PacketParseException e) Right a -> yield a >> decoder_ p2 encoder :: Monad m => (a -> Put) -> Producer a m r -> Producer ByteString m r encoder putter p = for p (encodePut . putter) getByteStringWithLen :: Get ByteString getByteStringWithLen = getWord32be >>= getByteString . fromIntegral putByteStringWithLen :: ByteString -> Put putByteStringWithLen bs = putWord32be (fromIntegral $ BS.length bs) >> putByteString bs data PacketParseException = PacketParseException DecodingError deriving (Show, Typeable) instance Exception PacketParseException data InboundPacketHandshake = InboundPacketHandshake Word32 getInPacketHandshake :: Get InboundPacketHandshake getInPacketHandshake = InboundPacketHandshake <$> get data OutboundPacketHandshake = OutboundPacketHandshake Word32 putOutPacketHandshake :: OutboundPacketHandshake -> Put putOutPacketHandshake (OutboundPacketHandshake magic) = put magic data InboundPacketLogin = InboundPacketLogin ByteString ByteString getInPacketLogin :: Get InboundPacketLogin getInPacketLogin = InboundPacketLogin <$> getByteStringWithLen <*> getByteStringWithLen data OutboundPacketLogin = OutboundLoginSuccess | OutboundLoginFailure putOutPacketLogin :: OutboundPacketLogin -> Put putOutPacketLogin p = case p of OutboundLoginSuccess -> putWord8 0 OutboundLoginFailure -> putWord8 1 data InboundPacketSession = InboundPacketJoin ByteString | InboundPacketMessage ByteString ByteString | InboundPacketDisconnect ByteString getInPacketSession :: Get InboundPacketSession getInPacketSession = do op <- getWord8 case op of 0 -> InboundPacketJoin <$> getByteStringWithLen 1 -> InboundPacketMessage <$> getByteStringWithLen <*> getByteStringWithLen data OutboundPacketSession = OutboundPacketSend ByteString | OutboundPacketQuit ByteString putOutPacketSession :: OutboundPacketSession -> Put putOutPacketSession p = case p of (OutboundPacketSend msg) -> putWord8 0 >> putByteStringWithLen msg (OutboundPacketQuit msg) -> putWord8 1 >> putByteStringWithLen msg
kvanberendonck/pipes-server-template
src/Server/Packet.hs
mit
3,418
1
21
788
797
418
379
87
3
{-# LANGUAGE BangPatterns, FlexibleContexts #-} {-# OPTIONS_GHC -fno-full-laziness -funbox-strict-fields #-} module LRUBoundedMap ( Map , empty , toList , null , size , member , notMember , insert , update , delete , lookup , lookupNoLRU , popOldest , popNewest , compactTicks , valid ) where import Prelude hiding (lookup, null) import qualified Data.Hashable as H import Data.Hashable (Hashable) import Data.Bits import Data.Maybe import Data.Word import Data.List hiding (lookup, delete, null, insert) import Control.Monad import Control.Monad.Writer import Control.DeepSeq (NFData(rnf)) -- Associative array implemented on top of a Hashed Trie. Basically a prefix tree over -- the bits of key hashes. Additional least / most recently used bounds for subtrees are -- stored so the data structure can have an upper bound on the number of elements and -- remove the least recently used one overflow. The other bound allows to retrieve the -- item which was inserted / touched last. Unlike a Data.HashMap our size operation is -- O(1), we also need to rebuild the map every 2^32 changes (see compactTicks) type Tick = Word32 data Map k v = Map { mLimit :: !Int , mTick :: !Tick -- We use a 'tick', which we keep incrementing, to keep -- track of how old elements are relative to each other , mSize :: !Int -- Cached to make size O(1) instead of O(n) , mTrie :: !(Trie k v) } instance (NFData k, NFData v) => NFData (Map k v) where rnf (Map l t s h) = rnf l `seq` rnf t `seq` rnf s `seq` rnf h type Hash = Int {-# INLINE hash #-} hash :: H.Hashable a => a -> Hash hash = fromIntegral . H.hash data Leaf k v = L !k !v !Tick instance (NFData k, NFData v) => NFData (Leaf k v) where rnf (L k v _) = rnf k `seq` rnf v data Trie k v = Empty -- Storing the tick interval for both branches instead of an aggregate -- makes for slightly faster code at the expense of some storage -- -- Oldest A Newest A Oldest B Newest B A B | Node !Tick !Tick !Tick !Tick !(Trie k v) !(Trie k v) | Leaf !Hash !(Leaf k v) | Collision !Hash ![Leaf k v] {-# INLINE minMaxFromTrie #-} minMaxFromTrie :: Trie k v -> (Tick, Tick) minMaxFromTrie Empty = (maxBound, minBound) minMaxFromTrie (Node olda newa oldb newb _ _) = (min olda oldb, max newa newb) minMaxFromTrie (Leaf _ (L _ _ tick)) = (tick, tick) minMaxFromTrie (Collision _ ch) = ( minimum . map (\(L _ _ tick) -> tick) $ ch , maximum . map (\(L _ _ tick) -> tick) $ ch ) instance (NFData k, NFData v) => NFData (Trie k v) where rnf Empty = () rnf (Leaf _ l) = rnf l rnf (Node _ _ _ _ a b) = rnf a `seq` rnf b rnf (Collision _ ch) = rnf ch empty :: Int -> Map k v empty limit | limit < 1 = error "limit for LRUBoundedMap needs to be >= 1" | limit > fromIntegral maxTick = error $ "limit for LRUBoundedMap needs to be <= " ++ show maxTick | otherwise = Map { mLimit = limit , mTick = minBound , mSize = 0 , mTrie = Empty } where -- Probably doesn't make much sense to go higher than this maxTick = (maxBound :: Tick) `div` 2 {-# INLINE isA #-} {-# INLINE isB #-} isA, isB :: Hash -> Int -> Bool isA h s = h .&. (1 `unsafeShiftL` s) == 0 isB h s = not $ isA h s -- Are two hashes colliding at the given depth? {-# INLINE subkeyCollision #-} subkeyCollision :: Hash -> Hash -> Int -> Bool subkeyCollision a b s = (a `xor` b) .&. (1 `unsafeShiftL` s) == 0 -- As we keep incrementing the global tick, we eventually run into the situation where it -- overflows (2^32). We could switch to a 64 bit tick, but GHC's emulation for 64 bit -- operations on 32 bit architectures is very slow. One way around this would be to abuse -- a Double as a 53 bit integer like this: -- -- -- newtype Tick53 = Tick53 { tickDouble :: Double } -- deriving (Eq, Ord) -- -- nextTick :: Tick53 -> Tick53 -- nextTick (Tick53 t) = Tick53 (t + 1) -- -- instance NFData Tick53 where -- rnf _ = () -- -- instance Bounded Tick53 where -- maxBound = Tick53 9007199254740992 -- minBound = Tick53 0 -- -- -- This is reasonably fast on 32 bit GHC, but still causes a lot of overhead for storing -- 64 bit values all over the tree. The solution chosen here is to use a 32 bit (or less) -- tick and simply compact all the ticks in the map when we overflow. This happens very -- rarely, so it's a clear win for time and space complexity -- compactTicks :: (Eq k, Hashable k) => Map k v -> Map k v compactTicks m = go m . empty $ mLimit m where go msrc mdst = let (msrc', mkv) = popOldest msrc in case mkv of Just (k, v) -> go msrc' . fst $ insert k v mdst Nothing -> mdst {-# INLINE compactIfAtTickLimit #-} compactIfAtTickLimit :: (Eq k, Hashable k) => Map k v -> Map k v compactIfAtTickLimit m = if mTick m == maxBound then compactTicks m else m {-# INLINE popOldestIfAtSizeLimit #-} popOldestIfAtSizeLimit :: (Eq k, Hashable k) => Map k v -> (Map k v, Maybe (k, v)) popOldestIfAtSizeLimit m = if mSize m > mLimit m then popOldest m else (m, Nothing) -- Insert a new element into the map, return the new map and the truncated -- element (if over the limit) {-# INLINEABLE insert #-} insert :: (Eq k, Hashable k) => k -> v -> Map k v -> (Map k v, Maybe (k, v)) insert kIns vIns m = let go h k v s (Node mina maxa minb maxb a b) = let !(!(!tA, !(!mintA, !maxtA), !insA), !(!tB, !(!mintB, !maxtB), !insB)) = -- Traverse into child with matching subkey if isA h s then (go h k v (s + 1) a , (b, (minb, maxb), False)) else ((a, (mina, maxa), False), go h k v (s + 1) b ) !mint = min mintA mintB !maxt = max maxtA maxtB in ( Node mintA maxtA mintB maxtB tA tB , (mint, maxt) , insA || insB ) go h k v _ Empty = (Leaf h $ L k v tick, (tick, tick), True) go h k v s t@(Leaf lh li@(L lk _ lt)) = let !mint = min tick lt !maxt = max tick lt in if h == lh then if k == lk then (Leaf h $ L k v tick, (tick, tick), False) -- Update value else -- We have a hash collision, change to a collision node and insert (Collision h [L k v tick, li], (mint, maxt), True) else -- Expand leaf into interior node let !(!(!a', !mina, !maxa), !(!b', !minb, !maxb)) | subkeyCollision h lh s = -- Subkey collision, add one level (if isA h s then flip (,) (Empty, maxBound, minBound) else (,) (Empty, maxBound, minBound)) . (\(x, (minx, maxx), True) -> (x, minx, maxx)) $ go h k v (s + 1) t | otherwise = let t' = Leaf h (L k v tick) in ( if isA h s then (t', tick, tick) else (t , lt , lt ) , if isB lh s then (t , lt , lt ) else (t', tick, tick) ) in ( Node mina maxa minb maxb a' b' , (mint, maxt) , True ) go h k v s t@(Collision colh ch) = if h == colh then let trav [] = [L k v tick] -- Append new leaf trav (l@(L lk _ _):xs) = if lk == k then L k v tick : xs -- Update value else l : trav xs t' = Collision h $ trav ch in (t', minMaxFromTrie t', length ch /= length (trav ch)) else -- Expand collision into interior node let (mint, maxt) = minMaxFromTrie t in go h k v s $ if isA colh s then Node mint maxt maxBound minBound t Empty else Node maxBound minBound mint maxt Empty t !(trie', _, !didInsert) = go (hash kIns) kIns vIns 0 $ mTrie m !tick = mTick m !inserted = m { mTrie = trie' , mSize = mSize m + if didInsert then 1 else 0 , mTick = tick + 1 } in popOldestIfAtSizeLimit . compactIfAtTickLimit $ inserted -- TODO: This function is just a wrapper around insert, could write optimized version {-# INLINEABLE update #-} update :: (Eq k, Hashable k) => k -> v -> Map k v -> Map k v update k v m | member k m = case insert k v m of (m', Nothing) -> m' _ -> error $ "LRUBoundedMap.update: insert" ++ " truncated during update" | otherwise = m {-# INLINEABLE size #-} size :: Map k v -> (Int, Int) size m = (mSize m, mLimit m) -- O(n) size-by-traversal sizeTraverse :: Map k v -> Int sizeTraverse m = go $ mTrie m where go Empty = 0 go (Leaf _ _) = 1 go (Node _ _ _ _ a b) = go a + go b go (Collision _ ch) = length ch {-# INLINEABLE null #-} null :: Map k v -> Bool null m = case mTrie m of Empty -> True; _ -> False {-# INLINEABLE member #-} member :: (Eq k, Hashable k) => k -> Map k v -> Bool member k m = isJust $ lookupNoLRU k m {-# INLINEABLE notMember #-} notMember :: (Eq k, Hashable k) => k -> Map k v -> Bool notMember k m = not $ member k m {-# INLINEABLE toList #-} toList :: Map k v -> [(k, v)] toList m = go [] $ mTrie m where go l Empty = l go l (Leaf _ (L k v _)) = (k, v) : l go l (Node _ _ _ _ a b) = go (go l a) b go l (Collision _ ch) = foldr (\(L k v _) l' -> (k, v) : l') l ch -- Lookup element, also update LRU {-# INLINEABLE lookup #-} lookup :: (Eq k, Hashable k) => k -> Map k v -> (Map k v, Maybe v) lookup k' m = if isNothing mvalue -- Only increment tick if we found something then (m, Nothing) else (compactIfAtTickLimit $ m { mTick = mTick m + 1, mTrie = trie' }, mvalue) where go :: Eq k => Hash -> k -> Tick -> Int -> Trie k v -> (Maybe v, Trie k v) go h k tick s t@(Node mina maxa minb maxb a b) = -- Traverse into child with matching subkey let !(!ins, t') = go h k tick (s + 1) (if isA h s then a else b) in if isNothing ins -- Don't rebuild node if we don't need to update the LRU then (Nothing, t) else let !(!mint', !maxt') = minMaxFromTrie t' in if isA h s then (ins, Node mint' maxt' minb maxb t' b ) else (ins, Node mina maxa mint' maxt' a t') go !_ !_ _ !_ Empty = (Nothing, Empty) go h k tick _ t@(Leaf lh (L lk lv _)) | lh /= h = (Nothing, t) | lk /= k = (Nothing, t) | otherwise = (Just lv, Leaf lh (L lk lv tick)) go h k tick _ t@(Collision colh ch) | colh == h = -- Search child list for matching key, rebuild with updated tick foldl' (\(r, Collision _ ch') l@(L lk lv _) -> if lk == k then (Just lv, Collision colh $ L lk lv tick : ch') else (r , Collision colh $ l : ch') ) (Nothing, Collision colh []) ch | otherwise = (Nothing, t) !(!mvalue, !trie') = go (hash k') k' (mTick m) 0 $ mTrie m {-# INLINEABLE lookupNoLRU #-} lookupNoLRU :: (Eq k, Hashable k) => k -> Map k v -> Maybe v lookupNoLRU k' m = go (hash k') k' 0 $ mTrie m where go h k s (Node _ _ _ _ a b) = go h k (s + 1) (if isA h s then a else b) go !_ !_ !_ Empty = Nothing go h k _ (Leaf lh (L lk lv _)) | lh /= h = Nothing | lk /= k = Nothing | otherwise = Just lv go h k _ (Collision colh ch) | colh == h = (\(L _ lv _) -> lv) <$> find (\(L lk _ _) -> lk == k) ch | otherwise = Nothing {-# INLINEABLE delete #-} delete :: (Eq k, Hashable k) => k -> Map k v -> (Map k v, Maybe v) delete k' m = let go h k s t@(Node _ _ _ _ a b) = let !(ch, del') = if isA h s then (\(!t', !dchild) -> ((t', b ), dchild)) $ go h k (s + 1) a else (\(!t', !dchild) -> ((a , t'), dchild)) $ go h k (s + 1) b in if isNothing del' then (t, Nothing) else ( case ch of -- We removed the last element, delete node (Empty, Empty) -> Empty -- If our last child is a leaf / collision replace the node by it (Empty, t' ) | isLeafOrCollision t' -> t' (t' , Empty) | isLeafOrCollision t' -> t' -- Update node with new subtree !(!a', !b') -> -- TODO: Don't recompute min/max for static branch let (minA, maxA) = minMaxFromTrie a' (minB, maxB) = minMaxFromTrie b' in Node minA maxA minB maxB a' b' , del' ) go !_ !_ !_ Empty = (Empty, Nothing) go h k _ t@(Leaf lh (L lk lv _)) | lh /= h = (t, Nothing) | lk /= k = (t, Nothing) | otherwise = (Empty, Just lv) go h k _ t@(Collision colh ch) | colh == h = let (delch', ch') = partition (\(L lk _ _) -> lk == k) ch in if length ch' == 1 then -- Deleted last remaining collision, it's a leaf node now (Leaf h $ head ch', Just $ (\((L _ lv _) : []) -> lv) delch') else (Collision h ch', (\(L _ lv _) -> lv) <$> listToMaybe delch') | otherwise = (t, Nothing) !(m', del) = go (hash k') k' 0 $ mTrie m isLeafOrCollision (Leaf _ _) = True isLeafOrCollision (Collision _ _) = True isLeafOrCollision _ = False in if isNothing del then (m, Nothing) else ( m { mTrie = m' , mSize = mSize m - 1 } , del ) popNewest, popOldest :: (Eq k, Hashable k) => Map k v -> (Map k v, Maybe (k, v)) popNewest = popInternal False popOldest = popInternal True -- Delete and return most / least recently used item -- -- TODO: We first find the item and then delete it by key, could do this with a -- single traversal instead popInternal :: (Eq k, Hashable k) => Bool -> Map k v -> (Map k v, Maybe (k, v)) popInternal popOld m = case go $ mTrie m of Just k -> let !(!m', !(Just v)) = delete k m in (m', Just (k, v)) Nothing -> (m, Nothing) where go Empty = Nothing go (Leaf _ (L lk _ _)) = Just lk go (Node mina maxa minb maxb a b) = go $ if popOld then if mina < minb then a else b else if maxa > maxb then a else b go (Collision _ ch) = Just . (\(L lk _ _) -> lk) . ( if popOld then minimumBy else maximumBy ) (\(L _ _ a) (L _ _ b) -> compare a b) $ ch -- Run a series of consistency checks on the structure inside of the map, return a list of -- errors if any issues where encountered valid :: (Eq k, Hashable k, Eq v) => Map k v -> Maybe String valid m = let w = execWriter $ do when (mLimit m < 1) $ tell "Invalid limit (< 1)\n" when (fst (size m) /= sizeTraverse m) $ tell "Mismatch beween cached and actual size\n" when (fst (size m) > mLimit m) $ tell "Size over the limit\n" allTicks <- let trav s minParent maxParent ticks t = case t of Leaf h (L lk lv lt) -> (: ticks) <$> checkKey h lk lv lt minParent maxParent Collision h ch -> do -- tell "Found collision\n" when (length ch < 2) $ tell "Hash collision node with <2 children\n" foldM (\xs (L lk lv lt) -> (: xs) <$> checkKey h lk lv lt minParent maxParent ) ticks ch Node minA maxA minB maxB a b -> do let mint = min minA minB maxt = max maxA maxB when (s + 1 > finiteBitSize (undefined :: Word)) $ tell "Subkey shift too large during traversal\n" when (mint < minParent || maxt > maxParent) $ tell "Node min/max tick outside of parent interval\n" let used = foldr (\x@(t', _, _) u -> case t' of Empty -> u; _ -> x : u ) [] $ [(a, minA, maxA), (b, minB, maxB)] when (length used == 0) $ tell "Node with only empty children\n" when (length used == 1) $ case (\((x, _, _) : _) -> x) used of Leaf _ _ -> tell "Node with single Leaf child\n" Collision _ _ -> tell "Node with single Collision child\n" _ -> return () foldM (\xs (c, mint', maxt') -> trav (s + 1) mint' maxt' xs c ) ticks used Empty -> return ticks checkKey h k v tick minParent maxParent = do when (hash k /= h) $ tell "Hash / key mismatch\n" when (tick >= mTick m) $ tell "Tick of leaf matches / exceeds current tick\n" when (tick < minParent || tick > maxParent) $ tell "Leaf min/max tick outside of parent interval\n" case snd $ lookup k m of Nothing -> tell "Can't lookup key found during traversal\n" Just v' -> when (v /= v') . tell $ "Lookup of key found during traversal yields " ++ "different value\n" let (m', v') = delete k m when (fst (size m') /= (fst $ size m) - 1) $ tell "Deleting key did not reduce size\n" when (fromMaybe v v' /= v) $ tell "Delete returned wrong value\n" return tick in trav 0 minBound maxBound [] $ mTrie m when (length allTicks /= mSize m) $ tell "Collection of all tick values used resulted in different size that mSize\n" unless (not . any (\x -> length x /= 1) . group . sort $ allTicks) $ tell "Duplicate tick value found\n" let keysL = map fst $ toList m allDeleted = foldl' (\r k -> fst $ delete k r) m keysL when (length keysL /= fst (size m)) $ tell "Length of toList does not match size\n" unless (null allDeleted) $ tell "Deleting all elements does not result in an empty map\n" unless (fst (size allDeleted) == 0) $ tell "Deleting all elements does not result in a zero size map\n" let compacted = compactTicks m when (snd (popOldest m) /= snd (popOldest compacted) || snd (popNewest m) /= snd (popNewest compacted)) $ tell "Tick compaction changes LRU\n" when (toList m /= toList compacted) $ tell "Tick compaction changes map\n" when (fromIntegral (mTick compacted) /= fst (size compacted)) $ tell "Tick compaction did not reduce tick range to minimum\n" in case w of [] -> Nothing xs -> Just xs
blitzcode/jacky
src/LRUBoundedMap.hs
mit
22,902
8
23
10,607
6,529
3,396
3,133
386
15
module Nilsson where import Control.DeepSeq type Capacity = Int type Length = Int type Weight = Int type Value = Int type Path = [Int] -- ********************* MCSP Main Functions ****************************** -- ~~~~~~~~~~ Lazy, non path tracking nch :: [(Capacity, Length)] -> [(Capacity, Length)] -> [(Capacity, Length)] nch [] cls2 = cls2 nch cls1 [] = cls1 nch clcls1@((c1, l1) : cls1) clcls2@((c2, l2) : cls2) | c1 == c2 = (c1, min l1 l2) : chAux (min l1 l2) cls1 cls2 | c1 > c2 = (c1, l1 ) : chAux l1 cls1 clcls2 | otherwise = (c2, l2) : chAux l2 clcls1 cls2 where chAux _ [] [] = [] chAux l [] ((c2, l2) : cls2) = chAux' l c2 l2 [] cls2 chAux l ((c1, l1) : cls1) [] = chAux' l c1 l1 cls1 [] chAux l clcls1@((c1, l1) : cls1) clcls2@((c2, l2) : cls2) | c1 == c2 = chAux' l c1 (min l1 l2) cls1 cls2 | c1 > c2 = chAux' l c1 l1 cls1 clcls2 | otherwise = chAux' l c2 l2 clcls1 cls2 chAux' l c' l' cls1 cls2 | l > l' = (c', l') : chAux l' cls1 cls2 | otherwise = chAux l cls1 cls2 njn :: [(Capacity, Length)] -> [(Capacity, Length)] -> [(Capacity, Length)] njn [] _ = [] njn _ [] = [] njn ((c1, l1) : cls1) ((c2, l2) : cls2) | c1 <= c2 = jnAux c1 l1 l2 cls1 cls2 | otherwise = jnAux c2 l2 l1 cls2 cls1 where jnAux c l l' cls1 [] = (c, l + l') : [ (c1, l1 + l') | (c1, l1) <- cls1 ] jnAux c l l' cls1 clcls2@((c2, l2) : cls2) | c <= c2 = jnAux c l l2 cls1 cls2 | otherwise = (c, l + l') : case cls1 of ((c1, l1) : cls1) | c1 > c2 -> jnAux c1 l1 l' cls1 clcls2 _ -> jnAux c2 l2 l cls2 cls1 -- ~~~~~~~~~~ Strict, non path tracking nchS :: [(Capacity, Length)] -> [(Capacity, Length)] -> [(Capacity, Length)] nchS [] cls2 = cls2 nchS cls1 [] = cls1 nchS clcls1@((c1, l1) : cls1) clcls2@((c2, l2) : cls2) | c1 == c2 = mkStrictPair c1 (min l1 l2) : chAux (min l1 l2) cls1 cls2 | c1 > c2 = (c1, l1) : chAux l1 cls1 clcls2 | otherwise = (c2, l2) : chAux l2 clcls1 cls2 where chAux _ [] [] = [] chAux l [] ((c2, l2) : cls2) = chAux' l c2 l2 [] cls2 chAux l ((c1, l1) : cls1) [] = chAux' l c1 l1 cls1 [] chAux l clcls1@((c1, l1) : cls1) clcls2@((c2, l2) : cls2) | c1 == c2 = chAux' l c1 (min l1 l2) cls1 cls2 | c1 > c2 = chAux' l c1 l1 cls1 clcls2 | otherwise = chAux' l c2 l2 clcls1 cls2 chAux' l c' l' cls1 cls2 | l > l' = (c', l') : chAux l' cls1 cls2 | otherwise = chAux l cls1 cls2 njnS :: [(Capacity, Length)] -> [(Capacity, Length)] -> [(Capacity, Length)] njnS [] _ = [] njnS _ [] = [] njnS ((c1, l1) : cls1) ((c2, l2) : cls2) | c1 <= c2 = jnAux c1 l1 l2 cls1 cls2 | otherwise = jnAux c2 l2 l1 cls2 cls1 where jnAux c l l' cls1 [] = mkStrictPair c (l+l') : [ mkStrictPair c1 (l1 + l') | (c1, l1) <- cls1 ] jnAux c l l' cls1 clcls2@((c2, l2) : cls2) | c <= c2 = jnAux c l l2 cls1 cls2 | otherwise = mkStrictPair c (l + l') : case cls1 of ((c1, l1) : cls1) | c1 > c2 -> jnAux c1 l1 l' cls1 clcls2 _ -> jnAux c2 l2 l cls2 cls1 -- ~~~~~~~~~~ Lazy with path tracking nchP :: [(Capacity, Length, Path)] -> [(Capacity, Length, Path)] -> [(Capacity, Length, Path)] nchP [] cls2 = cls2 nchP cls1 [] = cls1 nchP clcls1@((c1, l1, p1) : cls1) clcls2@((c2, l2, p2) : cls2) | c1 == c2 = if min l1 l2 == l2 then (c1, min l1 l2, p2) : chAux (min l1 l2) cls1 cls2 else (c1, min l1 l2, p1) : chAux (min l1 l2) cls1 cls2 | c1 > c2 = (c1, l1, p1) : chAux l1 cls1 clcls2 | otherwise = (c2, l2, p2) : chAux l2 clcls1 cls2 where chAux _ [] [] = [] chAux l [] ((c2, l2, p2) : cls2) = chAux' l c2 l2 p2 [] cls2 chAux l ((c1, l1, p1) : cls1) [] = chAux' l c1 l1 p1 cls1 [] chAux l clcls1@((c1, l1, p1) : cls1) clcls2@((c2, l2, p2) : cls2) | c1 == c2 = if min l1 l2 == l2 then chAux' l c1 (min l1 l2) p2 cls1 cls2 else chAux' l c1 (min l1 l2) p1 cls1 cls2 | c1 > c2 = chAux' l c1 l1 p1 cls1 clcls2 | otherwise = chAux' l c2 l2 p2 clcls1 cls2 chAux' l c' l' p cls1 cls2 | l > l' = (c', l', p) : chAux l' cls1 cls2 | otherwise = chAux l cls1 cls2 njnP :: [(Capacity, Length, Path)] -> [(Capacity, Length, Path)] -> [(Capacity, Length, Path)] njnP [] _ = [] njnP _ [] = [] njnP ((c1, l1, p1) : cls1) ((c2, l2, p2) : cls2) | c1 <= c2 = jnAux c1 l1 l2 p1 p2 cls1 cls2 | otherwise = jnAux c2 l2 l1 p2 p1 cls2 cls1 where jnAux c l l' p p' cls1 [] = (c, l + l', jnPath p p') : [ (c1, l1 + l', jnPath p' p1) | (c1, l1, p1) <- cls1 ] jnAux c l l' p p' cls1 clcls2@((c2, l2, p2) : cls2) | c <= c2 = jnAux c l l2 p p2 cls1 cls2 | otherwise = (c, l + l', jnPath p p') : case cls1 of ((c1, l1, p1) : cls1) | c1 > c2 -> jnAux c1 l1 l' p1 p' cls1 clcls2 _ -> jnAux c2 l2 l p2 p cls2 cls1 -- ~~~~~~~~~~ Strict with path tracking nchPS :: [(Capacity, Length, Path)] -> [(Capacity, Length, Path)] -> [(Capacity, Length, Path)] nchPS [] cls2 = cls2 nchPS cls1 [] = cls1 nchPS clcls1@((c1, l1, p1) : cls1) clcls2@((c2, l2, p2) : cls2) | c1 == c2 = if min l1 l2 == l2 then mkStrictTriple c1 (min l1 l2) p2 : chAux (min l1 l2) cls1 cls2 else mkStrictTriple c1 (min l1 l2) p1 : chAux (min l1 l2) cls1 cls2 | c1 > c2 = (c1, l1, p1) : chAux l1 cls1 clcls2 | otherwise = (c2, l2, p2) : chAux l2 clcls1 cls2 where chAux _ [] [] = [] chAux l [] ((c2, l2, p2) : cls2) = chAux' l c2 l2 p2 [] cls2 chAux l ((c1, l1, p1) : cls1) [] = chAux' l c1 l1 p1 cls1 [] chAux l clcls1@((c1, l1, p1) : cls1) clcls2@((c2, l2, p2) : cls2) | c1 == c2 = if min l1 l2 == l2 then chAux' l c1 (min l1 l2) p2 cls1 cls2 else chAux' l c1 (min l1 l2) p1 cls1 cls2 | c1 > c2 = chAux' l c1 l1 p1 cls1 clcls2 | otherwise = chAux' l c2 l2 p2 clcls1 cls2 chAux' l c' l' p cls1 cls2 | l > l' = (c', l', p) : chAux l' cls1 cls2 | otherwise = chAux l cls1 cls2 njnPS :: [(Capacity, Length, Path)] -> [(Capacity, Length, Path)] -> [(Capacity, Length, Path)] njnPS [] _ = [] njnPS _ [] = [] njnPS ((c1, l1, p1) : cls1) ((c2, l2, p2) : cls2) | c1 <= c2 = jnAux c1 l1 l2 p1 p2 cls1 cls2 | otherwise = jnAux c2 l2 l1 p2 p1 cls2 cls1 where jnAux c l l' p p' cls1 [] = (mkStrictTriple c (l + l') (jnPath p p')) : [ (mkStrictTriple c1 (l1 + l') (jnPath p' p1)) | (c1, l1, p1) <- cls1 ] jnAux c l l' p p' cls1 clcls2@((c2, l2, p2) : cls2) | c <= c2 = jnAux c l l2 p p2 cls1 cls2 | otherwise = (mkStrictTriple c (l + l') (jnPath p p')) : case cls1 of ((c1, l1, p1) : cls1) | c1 > c2 -> jnAux c1 l1 l' p1 p' cls1 clcls2 _ -> jnAux c2 l2 l p2 p cls2 cls1 -- ***************************** Knapsack Functions ******************************************* -- ~~~~~~~~~~ Lazy, non path tracking njnk :: Weight -> (Value,Weight) -> [(Value,Weight)] -> [(Value,Weight)] njnk wc (v,w) [] = if w > wc then [] else [(v,w)] njnk wc (v,w) vwss = if w > wc then vwss else njnAk wc (v,w) vwss njnAk :: Weight -> (Value,Weight) -> [(Value,Weight)] -> [(Value,Weight)] njnAk wc (v,w) [] = [(v,w)] njnAk wc (v,w) (vw:vws) | w + (snd vw) > wc = njnAk wc (v,w) vws | otherwise = (v+fst vw, w+snd vw) : njnAk wc (v,w) vws nchk :: [(Value,Weight)] -> [(Value,Weight)] -> [(Value,Weight)] nchk xs ys = nch xs ys -- ~~~~~~~~~~ Strict, non path tracking njnkS :: Weight -> (Value,Weight) -> [(Value,Weight)] -> [(Value,Weight)] njnkS wc (v,w) [] = if w > wc then [] else [(v,w)] njnkS wc (v,w) vwss = if w > wc then vwss else njnAkS wc (v,w) vwss njnAkS :: Weight -> (Value,Weight) -> [(Value,Weight)] -> [(Value,Weight)] njnAkS wc (v,w) [] = [(v,w)] njnAkS wc (v,w) (vw:vws) | w + (snd vw) > wc = njnAkS wc (v,w) vws | otherwise = mkStrictPair (v+fst vw) (w+snd vw) : njnAkS wc (v,w) vws nchkS :: [(Value,Weight)] -> [(Value,Weight)] -> [(Value,Weight)] nchkS xs ys = nchS xs ys -- ~~~~~~~~~~ Lazy with path tracking njnkP :: Weight -> (Value,Weight,Path) -> [(Value,Weight,Path)] -> [(Value,Weight,Path)] njnkP wc (v,w,p) [] = if w > wc then [] else [(v,w,p)] njnkP wc (v,w,p) vwss = if w > wc then vwss else njnAkP wc (v,w,p) vwss njnAkP :: Weight -> (Value,Weight,Path) -> [(Value,Weight,Path)] -> [(Value,Weight,Path)] njnAkP wc (v,w,p) [] = [(v,w,p)] njnAkP wc (v,w,p) (vw:vws) | w + (snd3 vw) > wc = njnAkP wc (v,w,p) vws | otherwise = (v+fst3 vw, w+snd3 vw, (trd3 vw)++p) : njnAkP wc (v,w,p) vws nchkP :: [(Value,Weight,Path)] -> [(Value,Weight,Path)] -> [(Value,Weight,Path)] nchkP xs ys = nchP xs ys -- ~~~~~~~~~~ Strict with path tracking njnkPS :: Weight -> (Value,Weight,Path) -> [(Value,Weight,Path)] -> [(Value,Weight,Path)] njnkPS wc (v,w,p) [] = if w > wc then [] else [(v,w,p)] njnkPS wc (v,w,p) vwss = if w > wc then vwss else njnAkPS wc (v,w,p) vwss njnAkPS :: Weight -> (Value,Weight,Path) -> [(Value,Weight,Path)] -> [(Value,Weight,Path)] njnAkPS wc (v,w,p) [] = [(v,w,p)] njnAkPS wc (v,w,p) (vw:vws) | w + (snd3 vw) > wc = njnAkPS wc (v,w,p) vws | otherwise = mkStrictTriple (v+fst3 vw) (w+snd3 vw) ((trd3 vw)++p) : njnAkPS wc (v,w,p) vws nchkPS :: [(Value,Weight,Path)] -> [(Value,Weight,Path)] -> [(Value,Weight,Path)] nchkPS xs ys = nchPS xs ys -- ********************* Auxiliar Functions ****************************** fst3 (x,_,_) = x snd3 (_,y,_) = y trd3 (_,_,z) = z mkStrictPair x y = let xy = (x, y) in deepseq xy xy mkStrictTriple x y z = let xyz = (x, y, z) in deepseq xyz xyz jnPath :: Path -> Path -> Path jnPath [] ys = ys jnPath xs [] = xs jnPath x'@(x:xs) y'@(y:ys) = if last x' == y then x'++ys else y'++xs mixListsPairs :: (Num a, Num b, Num c) => [[a]] -> [(b,c)] -> [[(a,b,c)]] mixListsPairs [] _ = [] mixListsPairs (x:xs) y = mixLP x y : mixListsPairs xs (drop (length x) y) where mixLP [] _ = [] mixLP [x] _ = [(x,2,1)] mixLP (x:xs) (y:ys) = (x, fst y, snd y) : mixLP xs ys -- ~~~~~~~~ Unit and Zero elements for choose and join operations ~~~~~ -- ~~~~~~~~ 1000 represents in this case the infinity value avoiding -- ~~~~~~~~ to handle a more elaborated data type zeroNonPath :: [(Int,Int)] zeroNonPath = [(0,1000)] oneNonPath :: [(Int,Int)] oneNonPath = [(1000,0)] zeroPath :: [(Int,Int,[Int])] zeroPath = [(0,1000,[])] onePath :: [(Int,Int,[Int])] onePath = [(1000,0,[])] zeroK = [(0,0)] :: [(Value,Weight)] oneK = [(0,0)] :: [(Value,Weight)]
jcsaenzcarrasco/MPhil-thesis
Nilsson.hs
mit
12,291
6
15
4,565
5,970
3,243
2,727
222
6
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} module IAFinance.Environment.Network( Has, EnvNetwork, Network(..), Manager, get ) where ----------------------------------------------------------------------------- -- import import Control.Concurrent.Async.Lifted.Safe () import Control.Monad.Reader (MonadReader, MonadIO, ask, liftIO) import Control.Concurrent.STM (readTVarIO) import Network.HTTP.Conduit (Manager) import IAFinance.Environment.Internal (Has(..), EnvNetwork, Network(..)) import IAFinance.Environment () ----------------------------------------------------------------------------- -- Network get :: (Has EnvNetwork env, MonadReader env m, MonadIO m) => m Network get = ask >>= \env -> io $ readTVarIO $ member env -- helper io :: (MonadIO m) => IO a -> m a io = liftIO
wiryls/HomeworkCollectionOfMYLS
2018.ProjectV/src/IAFinance/Environment/Network.hs
mit
880
0
8
122
209
129
80
20
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# OPTIONS_GHC -fplugin=HListPlugin #-} module Main where import HList import Data.Coerce newtype C = C Char deriving Eq main = print [coerce HNil == HNil -- This one doesn't work: ghc does not seem to call the plugin -- before deciding that there is no coercion. -- What's different when I inline q? -- , coerce (C 'a' `HCons` HNil) == ('a' `HCons` HNil) , q == 'a' `HCons` HNil , q == Record ('a' `HCons` HNil) ] -- should be (and is) a type error. -- bad = q `asTypeOf` (Proxy :: Proxy '[C]) -- should be -- q :: (Coercible t HList, Coercible b C) => t '[b] q = coerce (C 'a' `HCons` HNil)
aavogt/HListPlugin
ex/Coerce.hs
mit
746
0
10
177
105
66
39
13
1
{-# LANGUAGE FlexibleInstances #-} module System.Console.CmdArgs.AAI ( Desc , AAI (..) , aai , branch , param , flag , section ) where import Control.Applicative import Control.Monad (join) import Data.CanDefault import Data.Foldable (asum) import Data.List (nubBy) import System.Console.CmdArgs.AAI.CanMarshall import System.Environment (getArgs) import System.IO type Desc = Int -> String instance Show (Int -> String) where show f = show $ f 0 newtype AAI a = AAI { runAAI :: [String] -> [(a,Int,Desc,[String],[String])] } noValidMatch :: [String] -> [(IO (),Int,Desc,[String],[String])] -> IO () noValidMatch args rs = do putStrLn $ ">> " ++ unwords args ++ " <<" putStrLn "Did you mean one of these?" let for i rs = case rs of (_,_,d,pi,_):rs -> do putStrLn $ "[" ++ show i ++ "] " ++ unwords pi for (i + 1) rs _ -> putStrLn "" for 0 $ take 10 $ nubBy (\(_,_,_,l,_) (_,_,_,r,_) -> l == r) rs ambiguousMatch :: [String] -> [(IO (),Int,Desc,[String],[String])] -> IO () ambiguousMatch args rs = do putStrLn $ ">> " ++ unwords args ++ " <<" putStrLn "is ambiguos; it could mean the fhe following:" let for rs = case rs of (_,_,d,_,_):rs -> putStrLn (d 0) _ -> putStrLn "" for rs aai :: AAI (IO ()) -> [String] -> IO () aai a args = case args of "verbose":args -> let rs = runAAI a args ps = filter (\(_,i,_,_,_) -> i == 0) rs in case ps of [(a,_,_,_,_)] -> a [] -> noValidMatch args rs ps -> ambiguousMatch args ps args -> do putStrLn $ ">> " ++ unwords args ++ " <<" let rs = runAAI a args ps = filter (\(_,i,_,_,_) -> i == 0) rs in case ps of [(a,_,_,_,_)] -> a [] -> putStrLn "couldn't be resolved." _ -> putStrLn "is ambiguous." putStrLn "" branch :: [AAI d] -> AAI d branch ds = AAI $ \as -> asum $ map (`runAAI` as) ds param :: (Show a,CanDefault a,CanMarshall a) => AAI a param = AAI $ \as -> case as of a:as' -> case marshall a of Just a' -> [(a',0,const "",[a],as')] _ -> let a = def in [(a,10,const "",[show a],as')] _ -> let a = def in [(a,10,const "",[show a],[])] flag :: String -> AAI () flag f = AAI $ \as -> case as of a:as' -> if a == f then [((),0,const "",[f],as')] else [((),5,const "",[f],as'),((),10,const "",[f],as)] _ -> [((),10,const "",[f],[])] section :: String -> [AAI d] -> AAI d section n ds = flag n *> branch ds instance Functor AAI where fmap f a = AAI $ \as -> map (\(a,i,d,pi,as) -> (f a,i,d,pi,as)) (runAAI a as) instance Applicative AAI where pure a = AAI $ \as -> [(a,0,const "",[],as)] f <*> a = AAI $ \as -> asum $ map (\(g,i,d,pi,as') -> map (\(a,i',d',pi',as'') -> (g a,i+i',\i -> d i ++ d' i,pi ++ pi',as'')) (runAAI a as')) (runAAI f as) instance Alternative AAI where l <|> r = AAI $ \as -> runAAI l as <|> runAAI r as empty = AAI $ const empty
aka-bash0r/AAI
src/System/Console/CmdArgs/AAI.hs
mit
3,220
22
20
1,039
1,568
871
697
87
6
module Tests where import qualified Graphics.Bezier.Tests main :: IO () main = Graphics.Bezier.Tests.main
AaronShiny/Bezier
tests/Tests.hs
gpl-2.0
108
0
6
15
30
19
11
4
1
module Pipes.LHCO where import qualified Codec.Zlib as Zlib import qualified Data.Text as T import Pipes import Pipes.Attoparsec as PA import Pipes.ByteString as PB import qualified Pipes.Parse as PP import qualified Pipes.Zlib as PZ -- import HEP.Parser.LHCOAnalysis.PhysObj import HEP.Parser.LHCOAnalysis.Parse gunzip hin = (PZ.decompress (Zlib.WindowBits 31) (PB.fromHandle hin)) pipesLHCOEvent :: (Monad m) => Producer T.Text m r -> Producer PhyEventClassified m (Either (ParsingError, Producer T.Text m r) r) pipesLHCOEvent = parsed (header >> event)
wavewave/lhc-analysis-collection
heavyhiggs/Pipes/LHCO.hs
gpl-3.0
590
0
12
106
176
105
71
13
1
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} module QHaskell.Expression.Conversions.Evaluation.ADTUntypedDebruijn () where import QHaskell.MyPrelude import QHaskell.Expression.ADTUntypedDebruijn import qualified QHaskell.Expression.ADTValue as FAV import QHaskell.Environment.Plain import QHaskell.Conversion instance Cnv (Exp , (Env FAV.Exp , Env FAV.Exp)) FAV.Exp where cnv (ee , r@(s , g)) = join (case ee of Var x -> FAV.var <$> get x g Prm x es -> FAV.prm <$> get x s <*> mapM (\ e -> cnv (e , r)) es _ -> $(biGenOverloadedML 'ee ''Exp "FAV" ['Prm,'Var] (\ tt -> if | matchQ tt [t| Exp |] -> [| \ e -> cnv (e , r) |] | matchQ tt [t| Fun |] -> [| \ (Fun e) -> pure (\ v -> frmRgtZro (cnv (e , (s , v : g)))) |] | otherwise -> [| pure |])))
shayan-najd/QHaskell
QHaskell/Expression/Conversions/Evaluation/ADTUntypedDebruijn.hs
gpl-3.0
871
0
20
251
273
157
116
-1
-1
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grid is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with grid. If not, see <http://www.gnu.org/licenses/>. -- module Game.LevelPuzzle.LevelPuzzleWorld.OutputState.Fancy ( OutputState (..), makeOutputState, ) where import MyPrelude import Game import Game.Data.Color import Game.Grid import Linear data OutputState = OutputState { ostateBonusTick :: !Tick, ostateBonusAdd :: !UInt, ostateBonusRef :: !Segment, ostateBonusColor :: !Color, ostateColorIx0 :: !UInt, ostateColorIx1 :: !UInt, ostateAlpha :: !Float, ostateTick :: !Tick } makeOutputState :: MEnv' OutputState makeOutputState = do return OutputState { ostateBonusTick = 0.0, ostateBonusAdd = 0, ostateBonusRef = mempty, ostateBonusColor = colorNull, ostateColorIx0 = 0, ostateColorIx1 = 0, ostateAlpha = 0.0, ostateTick = 0.0 }
karamellpelle/grid
source/Game/LevelPuzzle/LevelPuzzleWorld/OutputState/Fancy.hs
gpl-3.0
1,668
0
9
461
194
126
68
46
1
{-# LANGUAGE OverloadedStrings #-} module TB.Crypto.Hash.Examples ( sha1File ) where import Control.Applicative import Control.Monad import Crypto.Hash.SHA1 import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.Char import Data.Word import Numeric -- | SHA1 a file sha1File :: FilePath -> IO String sha1File = liftM (bsToHex . hash) . B.readFile -- | Convert a bytestring to a hex string -- -- >>> bsToHex "hi" -- "6968" bsToHex :: ByteString -> String bsToHex = concat . B.foldl (\acc c -> (showHex c "") : acc) []
adarqui/ToyBox
haskell/vincenthz/cryptohash/src/TB/Crypto/Hash/Examples.hs
gpl-3.0
632
0
11
168
148
88
60
15
1
module Lex ( uncomment , isDel , isAlphanum', updown , myLex ) where import Char -------------------------------------------------------- uncomment :: String -> String uncomment [] = [] uncomment ('-' : '-' : cs) = uncomment (dropWhile (/= '\n') cs) uncomment ('{' : '-' : cs) = recomment cs uncomment (c : cs) = c : uncomment cs recomment :: String -> String recomment [] = [] recomment ('-' : '-' : cs) = recomment (dropWhile (/= '\n') cs) recomment ('-' : '}' : cs) = uncomment cs recomment (c : cs) = recomment cs ------------------------------------------------------- -- treat TeX operators updown c = c `elem` "_^'" isAlphanum' c = isAlphaNum c || updown c ------------------------------------------------------- myLex [] = [] myLex ('"' : cs) = let (as, bs) = span (/= '"') cs in ('"' : as ++ "\"") : myLex (drop 1 bs) myLex (c : cs) | isSpace c = myLex cs myLex (c : cs) | isAlpha c = let (ds, es) = span isAlphanum' cs in (c : ds) : myLex es myLex (c : cs) | isDigit c = let (ds, es) = span isDigit cs in (c : ds) : myLex es myLex (c : cs) | isDel c = [c] : myLex cs myLex (c : cs) = let (ds, es) = break (\ c -> isAlphanum' c || isSpace c || isDel c) cs in (c : ds) : myLex es ---------------------------------------------------------------------------- isDel '(' = True; isDel ')' = True isDel '[' = True; isDel ']' = True isDel '{' = True; isDel '}' = True isDel '`' = True isDel '"' = True isDel ',' = True -- isDel ';' = True NOT: semicolon is an operator, has semantics isDel _ = False
jwaldmann/rx
src/Lex.hs
gpl-3.0
1,571
8
14
357
687
350
337
41
1
module PolicyEffects.Init ( createPolicyEffects, policyEffectsEnvReplicator ) where import PolicyEffects.Model import PolicyEffects.Agent import FRP.Yampa import FRP.FrABS import System.Random import Control.Monad.Random createPolicyEffects :: Double -> NetworkType -> IO ([PolicyEffectsAgentDef], PolicyEffectsEnvironment) createPolicyEffects initWealth network = do e <- evalRandIO $ createRandEnvironment network let agentIds = nodesOfNetwork e adefs <- mapM (policyEffectsAgent initWealth) agentIds return (adefs, e) policyEffectsAgent :: Double -> AgentId -> IO PolicyEffectsAgentDef policyEffectsAgent initWealth agentId = do rng <- newStdGen return AgentDef { adId = agentId, adState = initWealth, adBeh = policyEffectsAgentBehaviour, adInitMessages = NoEvent, adConversation = Nothing, adRng = rng } createRandEnvironment :: NetworkType -> Rand StdGen PolicyEffectsEnvironment createRandEnvironment network = createNetwork network unitEdgeLabeler policyEffectsEnvReplicator :: NetworkType -> PolicyEffectsEnvironmentReplicator policyEffectsEnvReplicator network rng env = runRand (createRandEnvironment network) rng ------------------------------------------------------------------------------------------------------------------------
thalerjonathan/phd
coding/libraries/chimera/examples/ABS/PolicyEffects/Init.hs
gpl-3.0
1,562
0
10
436
273
145
128
34
1
{-# LANGUAGE OverloadedStrings #-} module WebParsing.TimeConverter (makeTimeSlots) where import qualified Data.Text as T --converts days into numbers, returns a tuple of the rest of the string (the times) --and a list of number representations of days convertTime :: (T.Text, [Double]) -> (T.Text, [Double]) convertTime (str, times) |T.null str = ("", times) |T.head str == 'M' = convertTime (T.drop 1 str, 0:times) |T.head str == 'T' = convertTime (T.drop 1 str, 1:times) |T.head str == 'W' = convertTime (T.drop 1 str, 2:times) |T.head str == 'R' = convertTime (T.drop 1 str, 3:times) |T.head str == 'F' = convertTime (T.drop 1 str, 4:times) |otherwise = (str, times) --given to numbers, creates a list of half-hours intervals between them --modifies 12-hour representation to 24 makeSlots :: Double -> Double -> [Double] makeSlots start end = if end < start then halfHourSlots start (12+end) else if start < 8.5 then halfHourSlots (start + 12) (end + 12) else (halfHourSlots start end) --extends functionality of makeSlots halfHourSlots :: Double -> Double -> [Double] halfHourSlots start end = let hours = [start .. end-1] in concat $ map (\h -> [h, h+0.5]) hours --converts the textual representation of time into numbers toDouble :: T.Text -> Double toDouble double = let splitIt = T.split (== ':') double list = reads $ T.unpack (head splitIt) halfHour= if (length splitIt) > 1 then 0.5 else 0 in if (length list) == 0 then 0.0 else (fst (head list)) + halfHour --zips togethor time slots with their days addList :: [a] -> [a] -> [[a]] addList days slots = concat $ map (\day -> map (\time -> [day,time]) slots) days --Takes in a string representation of timeslots, returns a list of days and half-hour timeslots makeTimeSlots :: T.Text -> [[Double]] makeTimeSlots str = let (times, days) = convertTime (str, []) doubles = map toDouble ( T.split (== '-') times) slots = if (length doubles) == 1 then makeSlots (head doubles) ((head doubles) + 1) else makeSlots (head doubles) (head (tail doubles)) in addList days slots
cchens/courseography
hs/WebParsing/TimeConverter.hs
gpl-3.0
2,201
0
14
509
800
425
375
44
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.TargetSSLProxies.SetProxyHeader -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Changes the ProxyHeaderType for TargetSslProxy. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetSslProxies.setProxyHeader@. module Network.Google.Resource.Compute.TargetSSLProxies.SetProxyHeader ( -- * REST Resource TargetSSLProxiesSetProxyHeaderResource -- * Creating a Request , targetSSLProxiesSetProxyHeader , TargetSSLProxiesSetProxyHeader -- * Request Lenses , tspsphProject , tspsphPayload , tspsphTargetSSLProxy ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetSslProxies.setProxyHeader@ method which the -- 'TargetSSLProxiesSetProxyHeader' request conforms to. type TargetSSLProxiesSetProxyHeaderResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "targetSslProxies" :> Capture "targetSslProxy" Text :> "setProxyHeader" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TargetSSLProxiesSetProxyHeaderRequest :> Post '[JSON] Operation -- | Changes the ProxyHeaderType for TargetSslProxy. -- -- /See:/ 'targetSSLProxiesSetProxyHeader' smart constructor. data TargetSSLProxiesSetProxyHeader = TargetSSLProxiesSetProxyHeader' { _tspsphProject :: !Text , _tspsphPayload :: !TargetSSLProxiesSetProxyHeaderRequest , _tspsphTargetSSLProxy :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetSSLProxiesSetProxyHeader' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tspsphProject' -- -- * 'tspsphPayload' -- -- * 'tspsphTargetSSLProxy' targetSSLProxiesSetProxyHeader :: Text -- ^ 'tspsphProject' -> TargetSSLProxiesSetProxyHeaderRequest -- ^ 'tspsphPayload' -> Text -- ^ 'tspsphTargetSSLProxy' -> TargetSSLProxiesSetProxyHeader targetSSLProxiesSetProxyHeader pTspsphProject_ pTspsphPayload_ pTspsphTargetSSLProxy_ = TargetSSLProxiesSetProxyHeader' { _tspsphProject = pTspsphProject_ , _tspsphPayload = pTspsphPayload_ , _tspsphTargetSSLProxy = pTspsphTargetSSLProxy_ } -- | Project ID for this request. tspsphProject :: Lens' TargetSSLProxiesSetProxyHeader Text tspsphProject = lens _tspsphProject (\ s a -> s{_tspsphProject = a}) -- | Multipart request metadata. tspsphPayload :: Lens' TargetSSLProxiesSetProxyHeader TargetSSLProxiesSetProxyHeaderRequest tspsphPayload = lens _tspsphPayload (\ s a -> s{_tspsphPayload = a}) -- | Name of the TargetSslProxy resource whose ProxyHeader is to be set. tspsphTargetSSLProxy :: Lens' TargetSSLProxiesSetProxyHeader Text tspsphTargetSSLProxy = lens _tspsphTargetSSLProxy (\ s a -> s{_tspsphTargetSSLProxy = a}) instance GoogleRequest TargetSSLProxiesSetProxyHeader where type Rs TargetSSLProxiesSetProxyHeader = Operation type Scopes TargetSSLProxiesSetProxyHeader = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetSSLProxiesSetProxyHeader'{..} = go _tspsphProject _tspsphTargetSSLProxy (Just AltJSON) _tspsphPayload computeService where go = buildClient (Proxy :: Proxy TargetSSLProxiesSetProxyHeaderResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetSSLProxies/SetProxyHeader.hs
mpl-2.0
4,445
0
17
998
472
281
191
82
1
module Iface (interfaceResource) where import Control.Monad import Control.Applicative import Control.Monad.Trans.Writer import Control.Exception import Data.Char import Data.Bool import Data.Maybe import Data.IP import System.Directory import System.Process hiding (system, rawSystem) import System.FilePath import System.Exit import System.IO.Error import Types import Resource import Utils import Files import IP import MAC interfaceResource :: Interface -> Maybe (Address IPv4) -> Address IPv6 -> [(VmName, (MAC, IPv4))] -> Bool -> ManyResources interfaceResource br@(unIface -> brn) maddr addr6 vms amRoot = ManyResources $ [ SomeResource $ SimpleFileResource { sfrPath = etcdir </> "network/interfaces.d/"++brn, sfrPerms = ((Nothing, Nothing), Just "644"), sfrNormalize = unlines . concatMap ifupdownNormalize . lines, sfrContent = brdef br addr6 vms $ fromMaybe [] $ net <$> maddr, sfrOwner = OwnerKib } ] ++ if amRoot then map (ifaceRes . fst) vms else [] where ifpf v = brn ++ "-" ++ v ifaceRes vm = SomeResource $ IOResource { rUpdateMsg = \(not_if_exists, if_down, bridge_iface) -> unlines $ execWriter $ do when not_if_exists $ tell ["interface for VM '"++vm++"' doesn't exist, configuring"] when if_down $ tell ["interface for VM '"++vm++"' down, upping"] when (not bridge_iface) $ tell ["interface for VM '"++vm++"' not connected to bridge, connecting"], rUpdate = \(not_if_exists, if_down, bridge_iface) -> do when not_if_exists $ pro $ tapAdd i usr when if_down $ pro $ setIfstate i (IfState "up") when (not bridge_iface) $ pro $ brAddIf br i, rCheck = do not_if_exists <- not <$> ifexists i if_down <- (== Right (IfState "down")) <$> tryJust (guard . isDoesNotExistError) (ifstate i) bridge_iface <- (i `elem`) <$> brIfaces br return (not_if_exists, if_down, bridge_iface) } where i = mkIface $ ifpf vm usr = kibVmUser vm net (ip, prefix) = [ "address " ++ showIP ip, "netmask " ++ show prefix ] brdef br@(unIface -> brn) addr6 vms lines = iface brn $ [ "bridge_ports none", "bridge_stp off", "bridge_maxwait 0", "bridge_fd 0", "up " ++ unwords (modIpv6 "add" br addr6), "down " ++ unwords (modIpv6 "del" br addr6), "up " ++ unwords ["sysctl", "-w", "net.ipv4.conf.$IFACE.proxy_arp_pvlan=1" ], "up " ++ unwords ["sysctl", "-w", "net.ipv4.conf.$IFACE.send_redirects=0" ], "up " ++ unwords ["sysctl", "-w", "net.ipv4.conf.$IFACE.accept_redirects=0" ], "up " ++ unwords ["sysctl", "-w", "net.ipv6.conf.$IFACE.accept_redirects=0" ] ] ++ lines ++ concatMap (downstreamIface brn addr6) vms iface name lines = unlines $ [ "auto "++name, "iface "++name++" inet static" -- static because downstream interfaces could hijack address by running a -- dhcp server themselves ] ++ map (" " ++) lines downstreamIface brn (ipv6, pfx) (vmn, (mac, showIP -> ipv4)) = let ifn = brn ++ "-" ++ vmn ifa = mkIface ifn ipv6_ll = showIP6 $ buildEUI64 (read "fe80::") mac ipv6_auto = showIP6 $ buildEUI64 ipv6 mac in [ "up " ++ unwords (tapAdd ifa (kibVmUser vmn)), "down " ++ unwords (tapDel ifa), "up ip link set dev "++ifn++" master $IFACE", "down ip link set dev "++ifn++" nomaster", "up bridge link set dev "++ifn++" isolated on learning off flood off mcast_flood off", "up bridge fdb replace "++showMAC mac++" dev "++ifn++" master static", "up ip neigh replace "++ipv4++" lladdr "++showMAC mac++" dev $IFACE nud permanent", "up ip neigh replace "++ipv6_ll++" lladdr "++showMAC mac++" dev $IFACE nud permanent", "up ip neigh replace "++ipv6_auto++" lladdr "++showMAC mac++" dev $IFACE nud permanent", "up " ++ unwords (setIfstate ifa (IfState "up")), "down " ++ unwords (setIfstate ifa (IfState "down")) ] where ifpf v = brn ++ "-" ++ v kibVmUser u = "kib-" ++ u data IfState = IfState String deriving (Eq, Show) type ShCommand = [String] isUp (IfState "up") = True isUp _ = False ifexists (unIface -> ifname) = doesDirectoryExist $ "/sys/class/net/" ++ ifname tapAdd (unIface -> ifname) owner = ["ip", "tuntap", "add", "dev", ifname, "mode", "tap", "user", owner] tapDel (unIface -> ifname) = ["ip", "tuntap", "del", "dev", ifname, "mode", "tap"] arp (unIface -> ifname) ip mac = ["arp", "-i", ifname, "-s", ip, mac] modIpv6 :: String -> Interface -> (IPv6, Prefix) -> [String] modIpv6 action (unIface -> ifname) iprange6 = ["ip", "-6", "addr", action, showIPRange iprange6, "dev", ifname] ifstate :: Interface -> IO IfState ifstate (unIface -> ifname) = do s <- readFile $ "/sys/class/net/"++ifname++"/operstate" return $ case takeWhile isAlphaNum s of "up" -> IfState "up" _ -> IfState "down" setIfstate :: Interface -> IfState -> ShCommand setIfstate (unIface -> ifname) (IfState ifs) = do ["ip", "link", "set", ifname, ifs] brIfaces :: Interface -> IO [Interface] brIfaces (unIface -> br) = map mkIface . filter (not . (`elem` [".", ".."])) <$> getDirectoryContents ("/sys/class/net/" </> br </> "brif") brAddIf (unIface -> brn) (unIface -> port) = ["ip", "link", "set", "dev", port, "master", brn] ifupdownNormalize :: String -> [String] ifupdownNormalize ('#':l) = [] ifupdownNormalize (c:l) | isSpace c = [' ' : wuws (dropWhile isSpace l)] ifupdownNormalize l = [wuws l] wuws = unwords . words
DanielG/kvm-in-a-box
src/Iface.hs
agpl-3.0
5,563
0
18
1,243
1,860
1,000
860
-1
-1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------------------- {-| Module : ParseC Copyright : (c) Daan Leijen 2003 License : BSD-style Maintainer : [email protected] Stability : provisional Portability : portable Parse the wxc C header files. -} ----------------------------------------------------------------------------------------- module ParseC( parseC, readHeaderFile ) where import Data.Char( isSpace ) import Data.List( isPrefixOf ) import Data.Maybe( isJust ) #if __GLASGOW_HASKELL__ < 710 import Data.Functor( (<$>) ) #endif import System.Process( readProcess ) import System.Environment (lookupEnv) import Text.ParserCombinators.Parsec import qualified Text.ParserCombinators.Parsec.Token as P import Text.ParserCombinators.Parsec.Language import Types {----------------------------------------------------------------------------------------- Parse C -----------------------------------------------------------------------------------------} parseC :: FilePath -> IO [Decl] parseC fname = do contents <- readHeaderFile fname declss <- mapM (parseDecl fname) (pairComments contents) return (concat declss) readHeaderFile :: FilePath -> IO [String] readHeaderFile fname = do includeDirectories <- getIncludeDirectories putStrLn ("Preprocessing and parsing file: " ++ fname ++ ",\n using include directories: " ++ (unwords includeDirectories)) flattenComments . filter (not . isPrefixOf "//") . filter (not . isPrefixOf "#") . lines <$> readProcess "cpp" ( includeDirectories ++ [ "-C" -- Keep the comments , "-DWXC_TYPES_H" -- Make sure wxc_types.h is not included, -- so the type macros are not replaced -- (the parser scans for certain macros) , fname -- The file to process ] ) "" readShellProcess :: FilePath -> [String] -> IO String readShellProcess f as = readProcess "sh" (f:as) "" isMsys :: IO Bool isMsys = isJust <$> lookupEnv "MSYSTEM" deMsysPaths :: String -> IO String deMsysPaths s = head . lines <$> readProcess "sh" ["-c", "cd " ++ s ++ "; pwd -W"] "" getIncludeDirectories :: IO [String] getIncludeDirectories = do im <- isMsys if im then readShellProcess "wx-config" ["--cppflags"] >>= mapM (fmap ("-I"++) . deMsysPaths . drop 2) . filter (isPrefixOf "-I") . words else filter (isPrefixOf "-I") . words <$> readProcess "wx-config" ["--cppflags"] "" -- flaky, but suitable flattenComments :: [String] -> [String] flattenComments inputLines = case inputLines of (('/':'*':_):_) -> let (incomment,comment:rest) = span (not . endsComment) inputLines in (concat (incomment ++ [comment]) : flattenComments rest) xs : xss -> xs : flattenComments xss [] -> [] where endsComment line = isPrefixOf "/*" (dropWhile isSpace (reverse line)) pairComments :: [String] -> [(String,String)] pairComments inputLines = case inputLines of ('/':'*':'*':xs) : ys : xss | not (classDef ys) -> (reverse (drop 2 (reverse xs)),ys) : pairComments xss xs : xss | not (classDef xs) -> ("",xs) : pairComments xss | otherwise -> pairComments xss [] -> [] where classDef xs = isPrefixOf "TClassDef" xs parseDecl :: FilePath -> (String,String) -> IO [Decl] parseDecl fname (comment,line) = case parse pdecl fname line of Left err -> do putStrLn ("ignore: parse error : " ++ show err ++ ", on : " ++ line) return [] Right mbd -> case mbd of Just d -> return [d{ declComment = comment }] Nothing -> return [] -- empty line {----------------------------------------------------------------------------------------- Parse declaration -----------------------------------------------------------------------------------------} -- parse a declaration: return Nothing on an empty declaration pdecl :: Parser (Maybe Decl) pdecl = do whiteSpace x <- (do f <- pfundecl; return (Just f)) <|> return Nothing eof return x pfundecl :: Parser Decl pfundecl = do optional (reserved "EXPORT") declRet' <- ptype optional (reserved "_stdcall" <|> reserved "__cdecl") declName' <- identifier <?> "function name" declArgs' <- pargs _ <- semi return (Decl declName' declRet' declArgs' "") <?> "function declaration" pargs :: Parser [Arg] pargs = parens (commaSep parg) <?> "arguments" parg :: Parser Arg parg = pargTypes <|> do argType' <- ptype argName' <- identifier return (Arg [argName'] argType') <?> "argument" ptype :: Parser Type ptype = do tp <- patomtype stars <- many (symbol "*") return (foldr (\_ tp' -> Ptr tp') tp stars) <?> "type" patomtype :: Parser Type patomtype = do reserved "void"; return Void <|> do reserved "int"; return (Int CInt) <|> do reserved "char"; return Char <|> do reserved "long"; return (Int CLong) <|> do reserved "double"; return Double <|> do reserved "float"; return Float <|> do reserved "size_t"; return (Int SizeT) <|> do reserved "time_t"; return (Int TimeT) <|> do reserved "uint8_t"; return Word8 <|> do reserved "uint32_t"; return Word32 <|> do reserved "uint64_t"; return Word64 <|> do reserved "intptr_t"; return IntPtr <|> do reserved "int64_t"; return Int64 <|> do reserved "TIntPtr"; return IntPtr <|> do reserved "TInt64"; return Int64 <|> do reserved "TUInt"; return Word <|> do reserved "TUInt8"; return Word8 <|> do reserved "TUInt32"; return Word32 <|> do reserved "TBool"; return Bool <|> do reserved "TBoolInt"; return Bool <|> do reserved "TChar"; return Char <|> do reserved "TString"; return (String CChar) <|> do reserved "TStringVoid"; return (String CVoid) <|> do reserved "TStringOut"; return (StringOut CChar) <|> do reserved "TStringOutVoid"; return (StringOut CVoid) <|> do reserved "TStringLen"; return StringLen <|> do reserved "TByteData"; return Char <|> do reserved "TByteStringOut"; return (ByteStringOut Strict) <|> do reserved "TByteStringLazyOut"; return (ByteStringOut Lazy) <|> do reserved "TByteStringLen"; return ByteStringLen <|> do reserved "TArrayLen"; return ArrayLen <|> do reserved "TArrayStringOut"; return (ArrayStringOut CChar) <|> do reserved "TArrayStringOutVoid"; return (ArrayStringOut CVoid) <|> do reserved "TArrayIntOut"; return (ArrayIntOut CInt) <|> do reserved "TArrayIntPtrOut"; return (ArrayIntPtrOut CInt) <|> do reserved "TArrayIntOutVoid"; return (ArrayIntOut CVoid) <|> do reserved "TArrayIntPtrOutVoid"; return (ArrayIntPtrOut CVoid) <|> do reserved "TClosureFun"; return (Fun "Ptr fun -> Ptr state -> Ptr (TEvent evt) -> IO ()") <|> do reserved "TClass" name <- parens identifier return (Object name) <|> do reserved "TSelf" name <- parens identifier return (Object name) <|> do reserved "TClassRef" name <- parens identifier return (RefObject name) <|> do reserved "TArrayObjectOut" name <- parens identifier return (ArrayObjectOut name CObject) <|> do reserved "TArrayObjectOutVoid" name <- parens identifier return (ArrayObjectOut name CVoid) pargTypes :: Parser Arg pargTypes = do tp <- pargType2 argnames <- parens pargs2 return (Arg argnames tp) <|> do tp <- pargType3 argnames <- parens pargs3 return (Arg argnames tp) <|> do tp <- pargType4 argnames <- parens pargs4 return (Arg argnames tp) <|> do reserved "TArrayObject" parens (do n <- identifier _ <- comma tp <- identifier _ <- comma p <- identifier return (Arg [n,p] (ArrayObject tp CVoid))) pargs2 :: Parser [String] pargs2 = do a1 <- identifier _ <- comma a2 <- identifier return [a1,a2] pargs3 :: Parser [String] pargs3 = do a1 <- identifier _ <- comma a2 <- identifier _ <- comma a3 <- identifier return [a1,a2,a3] pargs4 :: Parser [String] pargs4 = do a1 <- identifier _ <- comma a2 <- identifier _ <- comma a3 <- identifier _ <- comma a4 <- identifier return [a1,a2,a3,a4] pargType2 :: Parser Type pargType2 = do reserved "TPoint"; return (Point CInt) <|> do reserved "TSize"; return (Size CInt) <|> do reserved "TVector"; return (Vector CInt) <|> do reserved "TPointDouble"; return (Point CDouble) <|> do reserved "TPointLong"; return (Point CLong) <|> do reserved "TSizeDouble"; return (Size CDouble) <|> do reserved "TVectorDouble"; return (Vector CDouble) <|> do reserved "TPointOut"; return (PointOut CInt) <|> do reserved "TSizeOut"; return (SizeOut CInt) <|> do reserved "TVectorOut"; return (VectorOut CInt) <|> do reserved "TPointOutDouble"; return (PointOut CDouble) <|> do reserved "TPointOutVoid"; return (PointOut CVoid) <|> do reserved "TSizeOutDouble"; return (SizeOut CDouble) <|> do reserved "TSizeOutVoid"; return (SizeOut CVoid) <|> do reserved "TVectorOutDouble"; return (VectorOut CDouble) <|> do reserved "TVectorOutVoid"; return (VectorOut CVoid) <|> do reserved "TArrayString"; return (ArrayString CChar) <|> do reserved "TArrayInt"; return (ArrayInt CInt) <|> do reserved "TArrayIntPtr"; return (ArrayIntPtr CInt) <|> do reserved "TByteString"; return (ByteString Strict) <|> do reserved "TByteStringLazy"; return (ByteString Lazy) pargType3 :: Parser Type pargType3 = do reserved "TColorRGB"; return (ColorRGB CChar) pargType4 :: Parser Type pargType4 = do reserved "TRect"; return (Rect CInt) <|> do reserved "TRectDouble"; return (Rect CDouble) <|> do reserved "TRectOut"; return (RectOut CInt) <|> do reserved "TRectOutDouble"; return (RectOut CDouble) <|> do reserved "TRectOutVoid"; return (RectOut CVoid) {----------------------------------------------------------------------------------------- The lexer -----------------------------------------------------------------------------------------} lexer :: P.TokenParser () lexer = P.makeTokenParser $ emptyDef { commentStart = "/*" , commentEnd = "*/" , commentLine = "#" -- ignore pre-processor stuff, but fail to recognise "//" , nestedComments = False , identStart = letter <|> char '_' , identLetter = alphaNum <|> oneOf "_'" , caseSensitive = True , reservedNames = ["void","int","long","float","double","char","size_t","time_t","_stdcall","__cdecl" ,"TChar","TBool" ,"TIntPtr" ,"TClass","TSelf","TClassRef" ,"TByteData","TByteString","TByteStringOut","TByteStringLen" ,"TString","TStringOut","TStringLen", "TStringVoid" ,"TPoint","TSize","TVector","TRect" ,"TPointOut","TSizeOut","TVectorOut","TRectOut" ,"TPointOutVoid","TSizeOutVoid","TVectorOutVoid","TRectOutVoid" ,"TClosureFun" ,"TPointDouble", "TPointLong", "TSizeDouble", "TVectorDouble", "TRectDouble" ,"TPointOutDouble", "TSizeOutDouble", "TVectorOutDouble", "TRectOutDouble" ,"TArrayLen","TArrayStringOut","TArrayStringOutVoid","TArrayObjectOut","TArrayObjectOutVoid" ,"TColorRGB" ,"EXPORT" ] } whiteSpace :: Parser () whiteSpace = P.whiteSpace lexer symbol :: String -> Parser String symbol = P.symbol lexer parens :: Parser a -> Parser a parens = P.parens lexer semi :: Parser String semi = P.semi lexer comma :: Parser String comma = P.comma lexer commaSep :: Parser a -> Parser [a] commaSep = P.commaSep lexer identifier :: Parser String identifier = P.identifier lexer reserved :: String -> Parser () reserved = P.reserved lexer
sherwoodwang/wxHaskell
wxdirect/src/ParseC.hs
lgpl-2.1
12,580
0
51
3,300
3,722
1,782
1,940
280
3
{-# LANGUAGE OverloadedStrings, NamedFieldPuns, CPP #-} module FormStructure.Chapter0 (ch0GeneralInformation) where #ifndef __HASTE__ --import Data.Text.Lazy (Text) #endif import FormEngine.FormItem import FormStructure.Common import qualified FormStructure.Countries as Countries ch0GeneralInformation :: FormItem ch0GeneralInformation = Chapter { chDescriptor = defaultFIDescriptor { iLabel = Just "0.General Info" } , chItems = [identification, institution, remark] } where identification = SimpleGroup { sgDescriptor = defaultFIDescriptor { iLabel = Just "Registration of the responder" , iMandatory = True } , sgLevel = 0 , sgItems = [ StringFI { sfiDescriptor = defaultFIDescriptor { iLabel = Just "First name" } } , StringFI { sfiDescriptor = defaultFIDescriptor { iLabel = Just "Surname" , iMandatory = True } } , EmailFI { efiDescriptor = defaultFIDescriptor { iLabel = Just "Email" , iMandatory = True } } ] } institution :: FormItem institution = SimpleGroup { sgDescriptor = defaultFIDescriptor { iLabel = Just "Affiliation" , iMandatory = True } , sgLevel = 0 , sgItems = [ ListFI { lfiDescriptor = defaultFIDescriptor { iLabel = Just "Country" , iMandatory = True } , lfiAvailableOptions = Countries.countries } , StringFI { sfiDescriptor = defaultFIDescriptor { iLabel = Just "Institution name" , iMandatory = True } } , StringFI { sfiDescriptor = defaultFIDescriptor { iLabel = Just "Organisation unit" , iMandatory = True } } , ChoiceFI { chfiDescriptor = defaultFIDescriptor { iLabel = Just "Level of unit" , iMandatory = True } , chfiAvailableOptions = [ SimpleOption "institution" , SimpleOption "faculty" , SimpleOption "department" , SimpleOption "research group" ] } ] }
DataStewardshipPortal/ds-elixir-cz
FormStructure/Chapter0.hs
apache-2.0
2,909
0
14
1,464
396
242
154
52
1
-- {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {- Copyright 2019 The CodeWorld Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Main ( main ) where import GHCJS.DOM (currentDocument, ) import GHCJS.DOM.NonElementParentNode import GHCJS.DOM.GlobalEventHandlers import GHCJS.DOM.Document (getBody, Document(..)) import GHCJS.DOM.Element (setInnerHTML, Element) import GHCJS.DOM.HTMLButtonElement import GHCJS.DOM.EventM (on) import GHCJS.DOM.Types import GHCJS.Types import GHCJS.Foreign import GHCJS.Foreign.Callback import GHCJS.Marshal import Data.JSString.Text import qualified Data.JSString as JStr import qualified Data.Text as T import Control.Monad.Trans (liftIO, lift) import Blockly.Workspace hiding (workspaceToCode) import Blocks.Parser import Blocks.CodeGen import Blocks.Types import Blockly.Event import Blockly.General import Blockly.Block import Data.Monoid import Control.Monad pack = textToJSString unpack = textFromJSString setErrorMessage msg = do Just doc <- liftIO currentDocument -- Just msgEl <- getElementById doc "message" liftIO $ putStrLn msg liftIO $ js_stopErr (JStr.pack msg) -- setInnerHTML msgEl $ Just msg programBlocks :: [T.Text] programBlocks = map T.pack ["cwDrawingOf","cwAnimationOf", "cwSimulationOf", "cwInteractionOf"] btnStopClick = do liftIO js_stop runOrError :: Workspace -> IO () runOrError ws = do (code,errors) <- workspaceToCode ws case errors of ((Error msg block):es) -> do putStrLn $ T.unpack msg setWarningText block msg addErrorSelect block js_removeErrorsDelay setErrorMessage (T.unpack msg) [] -> do liftIO $ js_updateEditor (pack code) liftIO $ js_cwcompile (pack code) -- Update the hash on the workspace -- Mainly so that broken programs can be shared updateCode :: Workspace -> IO () updateCode ws = do (code,errors) <- workspaceToCode ws liftIO $ js_updateEditor (pack code) liftIO $ js_cwcompilesilent (pack code) btnRunClick ws = do Just doc <- liftIO currentDocument liftIO $ updateCode ws blocks <- liftIO $ getTopBlocks ws (block, w) <- liftIO $ isWarning ws if T.length w > 0 then do setErrorMessage (T.unpack w) liftIO $ addErrorSelect block liftIO $ js_removeErrorsDelay else do if not $ containsProgramBlock blocks then do setErrorMessage "No Program block on the workspace" else do liftIO $ runOrError ws return () where containsProgramBlock = any (\b -> getBlockType b `elem` programBlocks) hookEvent elementName evType func = do Just doc <- currentDocument Just btn <- getElementById doc elementName on (uncheckedCastTo HTMLButtonElement btn) evType func help = do js_injectReadOnly (JStr.pack "blocklyDiv") liftIO setBlockTypes funblocks = do Just doc <- currentDocument Just body <- getBody doc workspace <- liftIO $ setWorkspace "blocklyDiv" "toolbox" liftIO $ disableOrphans workspace -- Disable disconnected non-top level blocks liftIO $ warnOnInputs workspace -- Display warning if inputs are disconnected hookEvent "btnRun" click (btnRunClick workspace) hookEvent "btnStop" click btnStopClick liftIO setBlockTypes -- assign layout and types of Blockly blocks liftIO $ addChangeListener workspace (onChange workspace) liftIO js_showEast liftIO js_openEast -- Auto start liftIO $ setRunFunc workspace -- when (T.length hash > 0) $ liftIO $ runOrError workspace return () main = do Just doc <- currentDocument mayTool <- getElementById doc "toolbox" case mayTool of Just _ -> funblocks Nothing -> help -- Update code in real time onChange ws event = do (code, errs) <- workspaceToCode ws js_updateEditor (pack code) setRunFunc :: Workspace -> IO () setRunFunc ws = do cb <- syncCallback ContinueAsync (do runOrError ws) js_setRunFunc cb -- FFI -- call blockworld.js compile foreign import javascript unsafe "compile($1)" js_cwcompile :: JSString -> IO () foreign import javascript unsafe "compile($1,true)" js_cwcompilesilent :: JSString -> IO () -- call blockworld.js run -- run (xmlHash, codeHash, msg, error) foreign import javascript unsafe "run()" js_cwrun :: JSString -> JSString -> JSString -> Bool -> IO () -- call blockworld.js updateUI foreign import javascript unsafe "updateUI()" js_updateUI :: IO () -- funnily enough, If I'm calling run "" "" "" False I get errors foreign import javascript unsafe "run('','','',false)" js_stop :: IO () foreign import javascript unsafe "run('','',$1,true)" js_stopErr :: JSString -> IO () foreign import javascript unsafe "updateEditor($1)" js_updateEditor :: JSString -> IO () foreign import javascript unsafe "setTimeout(removeErrors,5000)" js_removeErrorsDelay :: IO () foreign import javascript unsafe "window.mainLayout.show('east')" js_showEast :: IO () foreign import javascript unsafe "window.mainLayout.open('east')" js_openEast :: IO () foreign import javascript unsafe "Blockly.inject($1, {});" js_injectReadOnly :: JSString -> IO Workspace foreign import javascript unsafe "runFunc = $1" js_setRunFunc :: Callback a -> IO ()
pranjaltale16/codeworld
funblocks-client/src/Main.hs
apache-2.0
6,083
24
16
1,415
1,362
679
683
133
3
{-# LANGUAGE ConstraintKinds #-} ----------------------------------------------------------------------------- -- | -- Module : Network.IP -- Copyright : (C) 2015 Ricky Elrod -- License : BSD2 (see LICENSE file) -- Maintainer : Ricky Elrod <[email protected]> -- Stability : experimental -- Portability : portable -- -- This library provides functions and types for handling/dealing with IP -- addressing and subnetting, along with parsing them. -- -- It is loosely based on Twitter\'s -- <https://github.com/twitter/util/blob/master/util-core/src/main/scala/com/twitter/util/NetUtil.scala util> -- and sebnow's -- <https://github.com/sebnow/haskell-network-address haskell-network-address> -- but gets away from usage of 'read' and hopefully fixes some other bugs. ---------------------------------------------------------------------------- module Network.IP ( -- Have to list things explicitly until -- https://github.com/haskell/haddock/issues/225 is fixed. module Network.IP.IPv4 ) where import Network.IP.IPv4
relrod/ip
src/Network/IP.hs
bsd-2-clause
1,021
0
5
119
42
35
7
4
0
module STLCCheck ( check, checkTop, TypeError(..) ) where import STLCSyntax import Control.Monad.Except import Control.Monad.Reader type Env = [(Name, Type)] extend :: (Name, Type) -> Env -> Env extend = (:) data TypeError = Mismatch Type Type | NotFunction Type | NotInScope Name type Check = ExceptT TypeError (Reader Env) inEnv :: (Name, Type) -> Check a -> Check a inEnv (x,t) = local (extend (x,t)) lookupVar :: Name -> Check Type lookupVar x = do env <- ask case lookup x env of Just e -> return e Nothing -> throwError $ NotInScope x check :: Expr -> Check Type check expr = case expr of Lit LInt {} -> return TInt Lit LBool {} -> return TBool Lam x t e -> do rhs <- inEnv (x,t) (check e) return (TArr t rhs) App e1 e2 -> do t1 <- check e1 t2 <- check e2 case t1 of (TArr a b) | a == t2 -> return b | otherwise -> throwError $ Mismatch t2 a ty -> throwError $ NotFunction ty Var x -> lookupVar x runCheck :: Env -> Check a -> Either TypeError a runCheck env = flip runReader env . runExceptT checkTop :: Env -> Expr -> Either TypeError Type checkTop env x = runCheck env $ check x
toonn/wyah
src/STLCCheck.hs
bsd-2-clause
1,350
0
16
477
522
261
261
42
6
{-# LANGUAGE CPP #-} {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} {-# LANGUAGE FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Narradar.Constraints.SAT.Solve ( BIEnv, EvalM, runEvalM , module Narradar.Constraints.SAT.Solve , decode, Var ) where import Bindings.Yices ( Context, mkContext, interrupt, setVerbosity, assertWeighted , setLogFile, delContext, isInconsistent) import Control.Applicative import Control.Arrow (first,second) import Control.Exception (evaluate, try, SomeException) import Control.Monad.RWS import Control.Monad.State import Data.Array.Unboxed import Data.List (unfoldr) import Data.Monoid import Data.Hashable import Data.Term.Rules (getAllSymbols) import Funsat.Circuit (BEnv, and,or,not) import Funsat.Types (Clause,Solution(..)) import Math.SMT.Yices.Syntax import System.Directory import System.FilePath import System.IO import System.IO.Unsafe import System.Process import System.TimeIt import Text.Printf import Narradar.Constraints.SAT.MonadSAT hiding (and,or) import Narradar.Constraints.SAT.RPOCircuit hiding (nat) import Narradar.Constraints.SAT.YicesCircuit as Serial (YicesSource, YMaps(..), emptyYMaps, runYices', generateDeclarations, solveDeclarations) import Narradar.Constraints.SAT.YicesFFICircuit as FFI (YicesSource, YMaps(..), emptyYMaps, computeBIEnv, runYicesSource) import Narradar.Framework (TimeoutException(..)) import Narradar.Framework.Ppr import Narradar.Utils ( debug, echo, echo', readProcessWithExitCodeBS ) import qualified Bindings.Yices as Yices import qualified Control.Exception as CE import qualified Funsat.Solver as Funsat import qualified Funsat.Types as Funsat import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.HashMap as HashMap import qualified Data.Map as Map import qualified Data.Set as Set import qualified Narradar.Types as Narradar import qualified Narradar.Constraints.SAT.RPOCircuit as RPOCircuit import Prelude hiding (and, not, or, any, all, lex, (>)) import qualified Prelude as P -- ---------------------------- -- SMT MonadSAT implementation -- ---------------------------- -- *** serialized data StY id = StY { poolY :: [Var] , cmdY :: [CmdY] , stY :: Serial.YMaps id Var } newtype SMTY id a = SMTY {unSMTY :: State (StY id) a} deriving (Functor, Monad, MonadState (StY id)) smtSerial :: (Hashable id, Ord id, Show id, Pretty id) => SMTY id (EvalM Var a) -> IO (Maybe a) smtSerial (SMTY my) = do let (me, StY{..}) = runState my (StY [V 1000 ..] [] Serial.emptyYMaps) -- let symbols = getAllSymbols $ mconcat [ Set.fromList [t, u] | ((t,u),_) <- HashMap.toList (termGtMap stY) ++ HashMap.toList (termEqMap stY)] bienv <- solveDeclarations Nothing (generateDeclarations stY ++ cmdY) -- debug (unlines $ map show $ Set.toList symbols) -- debug (show . vcat . map (uncurry printGt.second fst) . HashMap.toList . termGtMap $ stY) -- debug (show . vcat . map (uncurry printEq.second fst) . HashMap.toList . termEqMap $ stY) return ( (`runEvalM` me) <$> bienv ) where printEq (t,u) v = v <> colon <+> t <+> text "=" <+> u printGt (t,u) v = v <> colon <+> t <+> text ">" <+> u instance MonadSAT (Serial.YicesSource id) Var (SMTY id) where boolean = do {st <- get; put st{poolY=tail (poolY st)}; return (head $ poolY st)} natural = do {b <- boolean; return (Natural b)} assert [] = return () assert a = do st <- gets stY let (me, stY') = runYices' st $ foldr or false a modify $ \st -> st{cmdY = ASSERT me : cmdY st, stY = stY'} assertW w a = do st <- gets stY let (me, st') = runYices' st $ foldr or false a modify $ \st -> st{cmdY = ASSERT_P me (Just $ fromIntegral w) : cmdY st, stY = st'} -- *** FFI data StY' id = StY' { poolY' :: ![Var] , stY' :: !(FFI.YMaps id Var) } newtype SMTY' id a = SMTY' {unSMTY' :: RWST Context () (StY' id) IO a} deriving (Functor, Monad, MonadIO, MonadReader Context, MonadState (StY' id)) smtFFI :: (Hashable id, Ord id, Show id, Pretty id) => SMTY' id (EvalM Var a) -> IO (Maybe a) smtFFI (SMTY' my) = do ctx <- mkContext #ifdef DEBUG -- setVerbosity 10 -- setLogFile "yices.log" #endif (me, StY'{..}, _) <- runRWST my ctx (StY' [V 1000 ..] FFI.emptyYMaps) -- let symbols = getAllSymbols $ mconcat -- [ Set.fromList [t, u] | ((t,u),_) <- HashMap.toList (termGtMap stY) ++ HashMap.toList (termEqMap stY)] echo' "Calling Yices..." #ifdef DEBUG #endif (ti, bienv) <- timeItT(computeBIEnv ctx stY') -- debug (unlines $ map show $ Set.toList symbols) -- debug (show . vcat . map (uncurry printGt.second fst) . HashMap.toList . termGtMap $ stY) -- debug (show . vcat . map (uncurry printEq.second fst) . HashMap.toList . termEqMap $ stY) echo ("done (" ++ show ti ++ " seconds)") #ifdef DEBUG -- removeFile "yices.log" #endif delContext ctx return $ (`runEvalM` me) <$> bienv where printEq (t,u) v = v <> colon <+> t <+> text "=" <+> u printGt (t,u) v = v <> colon <+> t <+> text ">" <+> u instance MonadSAT (FFI.YicesSource id) Var (SMTY' id) where boolean = do {st <- get; put st{poolY'=tail (poolY' st)}; return (head $ poolY' st)} natural = do {b <- boolean; return (Natural b)} assert [] = return () assert a = do st <- gets stY' ctx <- ask (me, new_stY) <- liftIO $ runYicesSource ctx st $ orL a liftIO $ Yices.assert ctx me modify $ \st -> st{stY' = new_stY} assertW w a = do st <- gets stY' ctx <- ask (me, new_stY) <- liftIO $ runYicesSource ctx st $ orL a liftIO $ Yices.assertWeighted ctx me w modify $ \st -> st{stY' = new_stY} -- ------------------------------------------ -- Boolean Circuits MonadSAT implementation -- ------------------------------------------ data St tid tvar v = St { pool :: [v] , circuit :: !(Shared tid tvar v) , weightedClauses :: [(Weight, Clause)]} newtype SAT tid tvar v a = SAT {unSAT :: State (St tid tvar v) a} deriving (Functor, Monad, MonadState (St tid tvar v)) instance (Ord v, Hashable v, Show v) => MonadSAT (Shared tid tvar) v (SAT tid tvar v) where boolean = do {st <- get; put st{pool=tail (pool st)}; return (head $ pool st)} natural = do {b <- boolean; return (Natural b)} assert [] = return () assert a = do {st <- get; put st{circuit = orL a `and` circuit st}} assertW w a = return () -- = do {st <- get; put st{weightedClauses = ( w, a) : weightedClauses st}} st0 = St [minBound..] true [] -- *** SAT based (using Yices) solver data YicesOpts = YicesOpts {maxWeight :: Int, timeout :: Maybe Int} defaultYicesOpts = YicesOpts 0 Nothing satYices :: (Hashable id, Ord id, Show id) => YicesOpts -> SAT id Narradar.Var Var (EvalM Var a) -> IO (Maybe a) satYices = satYices' [toEnum 1 ..] satYices' pool0 yo (SAT m) = do let (val, St _ circuit weighted) = runState m (St pool0 true []) let circuitProb = toCNF(runShared circuit) mb_sol <- solveYices yo (rpoProblemCnf circuitProb) weighted val return $ fmap (\sol -> runEvalM (projectRPOCircuitSolution sol circuitProb) val) mb_sol satYicesSimp = satYicesSimp' [toEnum 1 ..] satYicesSimp' pool0 yo (SAT m) = do let (val, St pool circuit weighted) = runState m (St pool0 true []) (circuitProb, natbits) = toCNF' pool (runShared circuit) mb_sol <- solveYices yo (eproblemCnf circuitProb) weighted val return $ do sol <- mb_sol let bienv = reconstructNatsFromBits (HashMap.toList natbits) $ projectECircuitSolution sol circuitProb return $ runEvalM bienv val solveYices YicesOpts{..} cnf weighted val = do let nv = numVars cnf nc = numClauses cnf -- feed the problem to Yices cs = map (\c -> unwords (show maxWeight : map show c ++ ["0"] )) (clauses cnf) wcs = map (\(w,c) -> unwords (show w : map show c ++ ["0"])) weighted header = printf "p wcnf %d %d %d" nv (nc + length wcs) maxWeight opts = ["-e","-d","-ms", "-mw", show maxWeight] ++ maybe [] (\t -> ["-tm", show t]) timeout ( code, the_stdout, the_stderr ) <- readProcessWithExitCode "yices" opts (unlines $ header : wcs ++ cs) debug the_stderr mb_time <- either (\(e::SomeException) -> "") (\(t::Double) -> "(in " ++ show t ++ " seconds)") <$> (CE.try $ readIO (head $ words the_stderr)) case lines the_stdout of "sat" : xs : _ -> do debug ("satisfiable" ++ mb_time) return $ Just $ Sat $ array (Funsat.V 0, Funsat.V nv) [ (Funsat.V(abs x), x) | x <- map read (words xs)] _ -> do debug ("not satisfiable" ++ mb_time) return Nothing -- *** Funsat solver by simplification to vanilla Circuits solveFun :: ( Hashable id, Ord id, Bounded v , Enum v, Show v, Ord v, Hashable v , Ord tv, Hashable tv, Show tv) => SAT id tv v (EvalM v a) -> Maybe a solveFun = fmap (uncurry $ flip runEvalM) . runFun solveFunDirect :: ( Hashable id, Ord id, Show id , Bounded v, Enum v, Hashable v, Ord v, Show v , Hashable tv, Ord tv, Show tv) => SAT id tv v (EvalM v a) -> Maybe a solveFunDirect = fmap (uncurry $ flip runEvalM) . runFunDirect runFunDirect :: (Hashable id, Ord id, Show id ,Bounded v, Enum v, Ord v, Show v ,Hashable v, Hashable tv, Ord tv, Show tv) => SAT id tv v a -> Maybe (a, BIEnv v) runFunDirect (SAT m) = let (val, St _ circuit _weighted) = runState m st0 -- Skip weighted booleans as Funsat does not do weighted SAT circuitProb = toCNF (runShared circuit) (sol,_,_) = Funsat.solve1 $ rpoProblemCnf circuitProb in case sol of Sat{} -> Just (val, projectRPOCircuitSolution sol circuitProb) Unsat{} -> Nothing runFun :: (Hashable id, Ord id, Bounded v, Enum v, Ord v, Hashable v, Hashable tvar, Ord tvar, Show v) => SAT id tvar v a -> Maybe (a, BIEnv v) runFun (SAT m) = let (val, St pool circuit _weighted) = runState m st0 -- Skip weighted booleans as Funsat does not do weighted SAT (circuitProb, natbits) = toCNF' pool (runShared circuit) (sol,_,_) = Funsat.solve1 (eproblemCnf circuitProb) in case sol of Sat{} -> Just (val, reconstructNatsFromBits (HashMap.toList natbits) $ projectECircuitSolution sol circuitProb) Unsat{} -> Nothing
pepeiborra/narradar
src/Narradar/Constraints/SAT/Solve.hs
bsd-3-clause
11,835
0
19
3,405
3,747
2,005
1,742
200
2
{-# LANGUAGE TupleSections #-} module Haskell99Pointfree.P10 ( p10_1, p10_2 ) where import Control.Applicative import Control.Monad import Data.List (genericLength, group) import Haskell99Pointfree.P09 import Control.Arrow p10_1 :: Eq a => [a] -> [(Integer,a)] p10_1 = map (liftA2 (,) genericLength head) . p09_1 p10_2 :: Eq a => [a] -> [(Integer,a)] p10_2 = join (zipWith ( (. head) .(,) . genericLength ) ). p09_2 --using arrows p10_3 :: Eq a => [a] -> [(Int,a)] p10_3 = map ( length &&& head ) . p09_3 --solutions ignoring P09 --using until, takewhile and dropWhile p10_4 :: Eq a => [a] -> [(Integer,a)] p10_4 = snd . until (null . fst) nextStep . (,[]) .reverse where nextStep :: Eq a => ([a],[(Integer,a)]) -> ([a],[(Integer,a)]) nextStep = liftA2 (,) ( join ( dropWhile . (==) . head ) . fst) ( (. liftA2 (,) genericLength head) . flip (:) . snd <*> join (takeWhile . (==) . head) . fst ) --using until with splitAt and findIndex
SvenWille/Haskell99Pointfree
src/Haskell99Pointfree/P10.hs
bsd-3-clause
971
2
15
195
427
244
183
18
1
{-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} -- | The Config type. module Stack.Types.Config where import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception import Control.Monad (liftM, mzero, forM) import Control.Monad.Catch (MonadThrow, throwM) import Control.Monad.Logger (LogLevel(..)) import Control.Monad.Reader (MonadReader, ask, asks, MonadIO, liftIO) import Data.Aeson.Extended (ToJSON, toJSON, FromJSON, parseJSON, withText, object, (.=), (..:), (..:?), (..!=), Value(String, Object), withObjectWarnings, WarningParser, Object, jsonSubWarnings, JSONWarning, jsonSubWarningsT, jsonSubWarningsTT, tellJSONField) import Data.Attoparsec.Args import Data.Binary (Binary) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Either (partitionEithers) import Data.List (stripPrefix) import Data.Hashable (Hashable) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Map.Strict as M import Data.Maybe import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Data.Typeable import Data.Yaml (ParseException) import Distribution.System (Platform) import qualified Distribution.Text import Distribution.Version (anyVersion) import Network.HTTP.Client (parseUrl) import Path import qualified Paths_stack as Meta import Stack.Types.BuildPlan (SnapName, renderSnapName, parseSnapName) import Stack.Types.Compiler import Stack.Types.Docker import Stack.Types.FlagName import Stack.Types.Image import Stack.Types.PackageIdentifier import Stack.Types.PackageName import Stack.Types.Version import System.Process.Read (EnvOverride) -- | The top-level Stackage configuration. data Config = Config {configStackRoot :: !(Path Abs Dir) -- ^ ~/.stack more often than not ,configDocker :: !DockerOpts ,configEnvOverride :: !(EnvSettings -> IO EnvOverride) -- ^ Environment variables to be passed to external tools ,configLocalPrograms :: !(Path Abs Dir) -- ^ Path containing local installations (mainly GHC) ,configConnectionCount :: !Int -- ^ How many concurrent connections are allowed when downloading ,configHideTHLoading :: !Bool -- ^ Hide the Template Haskell "Loading package ..." messages from the -- console ,configPlatform :: !Platform -- ^ The platform we're building for, used in many directory names ,configGHCVariant0 :: !(Maybe GHCVariant) -- ^ The variant of GHC requested by the user. -- In most cases, use 'BuildConfig' or 'MiniConfig's version instead, -- which will have an auto-detected default. ,configLatestSnapshotUrl :: !Text -- ^ URL for a JSON file containing information on the latest -- snapshots available. ,configPackageIndices :: ![PackageIndex] -- ^ Information on package indices. This is left biased, meaning that -- packages in an earlier index will shadow those in a later index. -- -- Warning: if you override packages in an index vs what's available -- upstream, you may correct your compiled snapshots, as different -- projects may have different definitions of what pkg-ver means! This -- feature is primarily intended for adding local packages, not -- overriding. Overriding is better accomplished by adding to your -- list of packages. -- -- Note that indices specified in a later config file will override -- previous indices, /not/ extend them. -- -- Using an assoc list instead of a Map to keep track of priority ,configSystemGHC :: !Bool -- ^ Should we use the system-installed GHC (on the PATH) if -- available? Can be overridden by command line options. ,configInstallGHC :: !Bool -- ^ Should we automatically install GHC if missing or the wrong -- version is available? Can be overridden by command line options. ,configSkipGHCCheck :: !Bool -- ^ Don't bother checking the GHC version or architecture. ,configSkipMsys :: !Bool -- ^ On Windows: don't use a locally installed MSYS ,configCompilerCheck :: !VersionCheck -- ^ Specifies which versions of the compiler are acceptable. ,configLocalBin :: !(Path Abs Dir) -- ^ Directory we should install executables into ,configRequireStackVersion :: !VersionRange -- ^ Require a version of stack within this range. ,configJobs :: !Int -- ^ How many concurrent jobs to run, defaults to number of capabilities ,configExtraIncludeDirs :: !(Set Text) -- ^ --extra-include-dirs arguments ,configExtraLibDirs :: !(Set Text) -- ^ --extra-lib-dirs arguments ,configConfigMonoid :: !ConfigMonoid -- ^ @ConfigMonoid@ used to generate this ,configConcurrentTests :: !Bool -- ^ Run test suites concurrently ,configImage :: !ImageOpts ,configTemplateParams :: !(Map Text Text) -- ^ Parameters for templates. ,configScmInit :: !(Maybe SCM) -- ^ Initialize SCM (e.g. git) when creating new projects. ,configGhcOptions :: !(Map (Maybe PackageName) [Text]) -- ^ Additional GHC options to apply to either all packages (Nothing) -- or a specific package (Just). ,configSetupInfoLocations :: ![SetupInfoLocation] -- ^ Additional SetupInfo (inline or remote) to use to find tools. ,configPvpBounds :: !PvpBounds -- ^ How PVP upper bounds should be added to packages } -- | Information on a single package index data PackageIndex = PackageIndex { indexName :: !IndexName , indexLocation :: !IndexLocation , indexDownloadPrefix :: !Text -- ^ URL prefix for downloading packages , indexGpgVerify :: !Bool -- ^ GPG-verify the package index during download. Only applies to Git -- repositories for now. , indexRequireHashes :: !Bool -- ^ Require that hashes and package size information be available for packages in this index } deriving Show instance FromJSON (PackageIndex, [JSONWarning]) where parseJSON = withObjectWarnings "PackageIndex" $ \o -> do name <- o ..: "name" prefix <- o ..: "download-prefix" mgit <- o ..:? "git" mhttp <- o ..:? "http" loc <- case (mgit, mhttp) of (Nothing, Nothing) -> fail $ "Must provide either Git or HTTP URL for " ++ T.unpack (indexNameText name) (Just git, Nothing) -> return $ ILGit git (Nothing, Just http) -> return $ ILHttp http (Just git, Just http) -> return $ ILGitHttp git http gpgVerify <- o ..:? "gpg-verify" ..!= False reqHashes <- o ..:? "require-hashes" ..!= False return PackageIndex { indexName = name , indexLocation = loc , indexDownloadPrefix = prefix , indexGpgVerify = gpgVerify , indexRequireHashes = reqHashes } -- | Unique name for a package index newtype IndexName = IndexName { unIndexName :: ByteString } deriving (Show, Eq, Ord, Hashable, Binary) indexNameText :: IndexName -> Text indexNameText = decodeUtf8 . unIndexName instance ToJSON IndexName where toJSON = toJSON . indexNameText instance FromJSON IndexName where parseJSON = withText "IndexName" $ \t -> case parseRelDir (T.unpack t) of Left e -> fail $ "Invalid index name: " ++ show e Right _ -> return $ IndexName $ encodeUtf8 t -- | Location of the package index. This ensures that at least one of Git or -- HTTP is available. data IndexLocation = ILGit !Text | ILHttp !Text | ILGitHttp !Text !Text deriving (Show, Eq, Ord) -- | Controls which version of the environment is used data EnvSettings = EnvSettings { esIncludeLocals :: !Bool -- ^ include local project bin directory, GHC_PACKAGE_PATH, etc , esIncludeGhcPackagePath :: !Bool -- ^ include the GHC_PACKAGE_PATH variable , esStackExe :: !Bool -- ^ set the STACK_EXE variable to the current executable name , esLocaleUtf8 :: !Bool -- ^ set the locale to C.UTF-8 } deriving (Show, Eq, Ord) data ExecOpts = ExecOpts { eoCmd :: !(Maybe String) -- ^ Usage of @Maybe@ here is nothing more than a hack, to avoid some weird -- bug in optparse-applicative. See: -- https://github.com/commercialhaskell/stack/issues/806 , eoArgs :: ![String] , eoExtra :: !ExecOptsExtra } data ExecOptsExtra = ExecOptsPlain | ExecOptsEmbellished { eoEnvSettings :: !EnvSettings , eoPackages :: ![String] } -- | Parsed global command-line options. data GlobalOpts = GlobalOpts { globalReExec :: !Bool , globalLogLevel :: !LogLevel -- ^ Log level , globalConfigMonoid :: !ConfigMonoid -- ^ Config monoid, for passing into 'loadConfig' , globalResolver :: !(Maybe AbstractResolver) -- ^ Resolver override , globalTerminal :: !Bool -- ^ We're in a terminal? , globalStackYaml :: !(Maybe FilePath) -- ^ Override project stack.yaml , globalModifyCodePage :: !Bool -- ^ Force the code page to UTF-8 on Windows } deriving (Show) -- | Either an actual resolver value, or an abstract description of one (e.g., -- latest nightly). data AbstractResolver = ARLatestNightly | ARLatestLTS | ARLatestLTSMajor !Int | ARResolver !Resolver | ARGlobal deriving Show -- | Default logging level should be something useful but not crazy. defaultLogLevel :: LogLevel defaultLogLevel = LevelInfo -- | A superset of 'Config' adding information on how to build code. The reason -- for this breakdown is because we will need some of the information from -- 'Config' in order to determine the values here. data BuildConfig = BuildConfig { bcConfig :: !Config , bcResolver :: !Resolver -- ^ How we resolve which dependencies to install given a set of -- packages. , bcWantedCompiler :: !CompilerVersion -- ^ Compiler version wanted for this build , bcPackageEntries :: ![PackageEntry] -- ^ Local packages identified by a path, Bool indicates whether it is -- a non-dependency (the opposite of 'peExtraDep') , bcExtraDeps :: !(Map PackageName Version) -- ^ Extra dependencies specified in configuration. -- -- These dependencies will not be installed to a shared location, and -- will override packages provided by the resolver. , bcStackYaml :: !(Path Abs File) -- ^ Location of the stack.yaml file. -- -- Note: if the STACK_YAML environment variable is used, this may be -- different from bcRoot </> "stack.yaml" , bcFlags :: !(Map PackageName (Map FlagName Bool)) -- ^ Per-package flag overrides , bcImplicitGlobal :: !Bool -- ^ Are we loading from the implicit global stack.yaml? This is useful -- for providing better error messages. , bcGHCVariant :: !GHCVariant -- ^ The variant of GHC used to select a GHC bindist. } -- | Directory containing the project's stack.yaml file bcRoot :: BuildConfig -> Path Abs Dir bcRoot = parent . bcStackYaml -- | Directory containing the project's stack.yaml file bcWorkDir :: BuildConfig -> Path Abs Dir bcWorkDir = (</> workDirRel) . parent . bcStackYaml -- | Configuration after the environment has been setup. data EnvConfig = EnvConfig {envConfigBuildConfig :: !BuildConfig ,envConfigCabalVersion :: !Version ,envConfigCompilerVersion :: !CompilerVersion ,envConfigPackages :: !(Map (Path Abs Dir) Bool)} instance HasBuildConfig EnvConfig where getBuildConfig = envConfigBuildConfig instance HasConfig EnvConfig instance HasPlatform EnvConfig instance HasGHCVariant EnvConfig instance HasStackRoot EnvConfig class (HasBuildConfig r, HasGHCVariant r) => HasEnvConfig r where getEnvConfig :: r -> EnvConfig instance HasEnvConfig EnvConfig where getEnvConfig = id -- | Value returned by 'Stack.Config.loadConfig'. data LoadConfig m = LoadConfig { lcConfig :: !Config -- ^ Top-level Stack configuration. , lcLoadBuildConfig :: !(Maybe AbstractResolver -> m BuildConfig) -- ^ Action to load the remaining 'BuildConfig'. , lcProjectRoot :: !(Maybe (Path Abs Dir)) -- ^ The project root directory, if in a project. } data PackageEntry = PackageEntry { peExtraDepMaybe :: !(Maybe Bool) -- ^ Is this package a dependency? This means the local package will be -- treated just like an extra-deps: it will only be built as a dependency -- for others, and its test suite/benchmarks will not be run. -- -- Useful modifying an upstream package, see: -- https://github.com/commercialhaskell/stack/issues/219 -- https://github.com/commercialhaskell/stack/issues/386 , peValidWanted :: !(Maybe Bool) -- ^ Deprecated name meaning the opposite of peExtraDep. Only present to -- provide deprecation warnings to users. , peLocation :: !PackageLocation , peSubdirs :: ![FilePath] } deriving Show -- | Once peValidWanted is removed, this should just become the field name in PackageEntry. peExtraDep :: PackageEntry -> Bool peExtraDep pe = case peExtraDepMaybe pe of Just x -> x Nothing -> case peValidWanted pe of Just x -> not x Nothing -> False instance ToJSON PackageEntry where toJSON pe | not (peExtraDep pe) && null (peSubdirs pe) = toJSON $ peLocation pe toJSON pe = object [ "extra-dep" .= peExtraDep pe , "location" .= peLocation pe , "subdirs" .= peSubdirs pe ] instance FromJSON (PackageEntry, [JSONWarning]) where parseJSON (String t) = do (loc, _::[JSONWarning]) <- parseJSON $ String t return (PackageEntry { peExtraDepMaybe = Nothing , peValidWanted = Nothing , peLocation = loc , peSubdirs = [] }, []) parseJSON v = withObjectWarnings "PackageEntry" (\o -> PackageEntry <$> o ..:? "extra-dep" <*> o ..:? "valid-wanted" <*> jsonSubWarnings (o ..: "location") <*> o ..:? "subdirs" ..!= []) v data PackageLocation = PLFilePath FilePath -- ^ Note that we use @FilePath@ and not @Path@s. The goal is: first parse -- the value raw, and then use @canonicalizePath@ and @parseAbsDir@. | PLHttpTarball Text | PLGit Text Text -- ^ URL and commit deriving Show instance ToJSON PackageLocation where toJSON (PLFilePath fp) = toJSON fp toJSON (PLHttpTarball t) = toJSON t toJSON (PLGit x y) = toJSON $ T.unwords ["git", x, y] instance FromJSON (PackageLocation, [JSONWarning]) where parseJSON v = ((,[]) <$> withText "PackageLocation" (\t -> http t <|> file t) v) <|> git v where file t = pure $ PLFilePath $ T.unpack t http t = case parseUrl $ T.unpack t of Left _ -> mzero Right _ -> return $ PLHttpTarball t git = withObjectWarnings "PackageGitLocation" $ \o -> PLGit <$> o ..: "git" <*> o ..: "commit" -- | A project is a collection of packages. We can have multiple stack.yaml -- files, but only one of them may contain project information. data Project = Project { projectPackages :: ![PackageEntry] -- ^ Components of the package list , projectExtraDeps :: !(Map PackageName Version) -- ^ Components of the package list referring to package/version combos, -- see: https://github.com/fpco/stack/issues/41 , projectFlags :: !(Map PackageName (Map FlagName Bool)) -- ^ Per-package flag overrides , projectResolver :: !Resolver -- ^ How we resolve which dependencies to use } deriving Show instance ToJSON Project where toJSON p = object [ "packages" .= projectPackages p , "extra-deps" .= map fromTuple (Map.toList $ projectExtraDeps p) , "flags" .= projectFlags p , "resolver" .= projectResolver p ] -- | How we resolve which dependencies to install given a set of packages. data Resolver = ResolverSnapshot SnapName -- ^ Use an official snapshot from the Stackage project, either an LTS -- Haskell or Stackage Nightly | ResolverCompiler !CompilerVersion -- ^ Require a specific compiler version, but otherwise provide no build plan. -- Intended for use cases where end user wishes to specify all upstream -- dependencies manually, such as using a dependency solver. | ResolverCustom !Text !Text -- ^ A custom resolver based on the given name and URL. This file is assumed -- to be completely immutable. deriving (Show) instance ToJSON Resolver where toJSON (ResolverCustom name location) = object [ "name" .= name , "location" .= location ] toJSON x = toJSON $ resolverName x instance FromJSON (Resolver,[JSONWarning]) where -- Strange structuring is to give consistent error messages parseJSON v@(Object _) = withObjectWarnings "Resolver" (\o -> ResolverCustom <$> o ..: "name" <*> o ..: "location") v parseJSON (String t) = either (fail . show) return ((,[]) <$> parseResolverText t) parseJSON _ = fail $ "Invalid Resolver, must be Object or String" -- | Convert a Resolver into its @Text@ representation, as will be used by -- directory names resolverName :: Resolver -> Text resolverName (ResolverSnapshot name) = renderSnapName name resolverName (ResolverCompiler v) = compilerVersionText v resolverName (ResolverCustom name _) = "custom-" <> name -- | Try to parse a @Resolver@ from a @Text@. Won't work for complex resolvers (like custom). parseResolverText :: MonadThrow m => Text -> m Resolver parseResolverText t | Right x <- parseSnapName t = return $ ResolverSnapshot x | Just v <- parseCompilerVersion t = return $ ResolverCompiler v | otherwise = throwM $ ParseResolverException t -- | Class for environment values which have access to the stack root class HasStackRoot env where getStackRoot :: env -> Path Abs Dir default getStackRoot :: HasConfig env => env -> Path Abs Dir getStackRoot = configStackRoot . getConfig {-# INLINE getStackRoot #-} -- | Class for environment values which have a Platform class HasPlatform env where getPlatform :: env -> Platform default getPlatform :: HasConfig env => env -> Platform getPlatform = configPlatform . getConfig {-# INLINE getPlatform #-} instance HasPlatform Platform where getPlatform = id -- | Class for environment values which have a GHCVariant class HasGHCVariant env where getGHCVariant :: env -> GHCVariant default getGHCVariant :: HasBuildConfig env => env -> GHCVariant getGHCVariant = bcGHCVariant . getBuildConfig {-# INLINE getGHCVariant #-} instance HasGHCVariant GHCVariant where getGHCVariant = id -- | Class for environment values that can provide a 'Config'. class (HasStackRoot env, HasPlatform env) => HasConfig env where getConfig :: env -> Config default getConfig :: HasBuildConfig env => env -> Config getConfig = bcConfig . getBuildConfig {-# INLINE getConfig #-} instance HasStackRoot Config instance HasPlatform Config instance HasConfig Config where getConfig = id {-# INLINE getConfig #-} -- | Class for environment values that can provide a 'BuildConfig'. class HasConfig env => HasBuildConfig env where getBuildConfig :: env -> BuildConfig instance HasStackRoot BuildConfig instance HasPlatform BuildConfig instance HasGHCVariant BuildConfig instance HasConfig BuildConfig instance HasBuildConfig BuildConfig where getBuildConfig = id {-# INLINE getBuildConfig #-} -- An uninterpreted representation of configuration options. -- Configurations may be "cascaded" using mappend (left-biased). data ConfigMonoid = ConfigMonoid { configMonoidDockerOpts :: !DockerOptsMonoid -- ^ Docker options. , configMonoidConnectionCount :: !(Maybe Int) -- ^ See: 'configConnectionCount' , configMonoidHideTHLoading :: !(Maybe Bool) -- ^ See: 'configHideTHLoading' , configMonoidLatestSnapshotUrl :: !(Maybe Text) -- ^ See: 'configLatestSnapshotUrl' , configMonoidPackageIndices :: !(Maybe [PackageIndex]) -- ^ See: 'configPackageIndices' , configMonoidSystemGHC :: !(Maybe Bool) -- ^ See: 'configSystemGHC' ,configMonoidInstallGHC :: !(Maybe Bool) -- ^ See: 'configInstallGHC' ,configMonoidSkipGHCCheck :: !(Maybe Bool) -- ^ See: 'configSkipGHCCheck' ,configMonoidSkipMsys :: !(Maybe Bool) -- ^ See: 'configSkipMsys' ,configMonoidCompilerCheck :: !(Maybe VersionCheck) -- ^ See: 'configCompilerCheck' ,configMonoidRequireStackVersion :: !VersionRange -- ^ See: 'configRequireStackVersion' ,configMonoidOS :: !(Maybe String) -- ^ Used for overriding the platform ,configMonoidArch :: !(Maybe String) -- ^ Used for overriding the platform ,configMonoidGHCVariant :: !(Maybe GHCVariant) -- ^ Used for overriding the GHC variant ,configMonoidJobs :: !(Maybe Int) -- ^ See: 'configJobs' ,configMonoidExtraIncludeDirs :: !(Set Text) -- ^ See: 'configExtraIncludeDirs' ,configMonoidExtraLibDirs :: !(Set Text) -- ^ See: 'configExtraLibDirs' ,configMonoidConcurrentTests :: !(Maybe Bool) -- ^ See: 'configConcurrentTests' ,configMonoidLocalBinPath :: !(Maybe FilePath) -- ^ Used to override the binary installation dir ,configMonoidImageOpts :: !ImageOptsMonoid -- ^ Image creation options. ,configMonoidTemplateParameters :: !(Map Text Text) -- ^ Template parameters. ,configMonoidScmInit :: !(Maybe SCM) -- ^ Initialize SCM (e.g. git init) when making new projects? ,configMonoidGhcOptions :: !(Map (Maybe PackageName) [Text]) -- ^ See 'configGhcOptions' ,configMonoidExtraPath :: ![Path Abs Dir] -- ^ Additional paths to search for executables in ,configMonoidSetupInfoLocations :: ![SetupInfoLocation] -- ^ Additional setup info (inline or remote) to use for installing tools ,configMonoidPvpBounds :: !(Maybe PvpBounds) -- ^ See 'configPvpBounds' } deriving Show instance Monoid ConfigMonoid where mempty = ConfigMonoid { configMonoidDockerOpts = mempty , configMonoidConnectionCount = Nothing , configMonoidHideTHLoading = Nothing , configMonoidLatestSnapshotUrl = Nothing , configMonoidPackageIndices = Nothing , configMonoidSystemGHC = Nothing , configMonoidInstallGHC = Nothing , configMonoidSkipGHCCheck = Nothing , configMonoidSkipMsys = Nothing , configMonoidRequireStackVersion = anyVersion , configMonoidOS = Nothing , configMonoidArch = Nothing , configMonoidGHCVariant = Nothing , configMonoidJobs = Nothing , configMonoidExtraIncludeDirs = Set.empty , configMonoidExtraLibDirs = Set.empty , configMonoidConcurrentTests = Nothing , configMonoidLocalBinPath = Nothing , configMonoidImageOpts = mempty , configMonoidTemplateParameters = mempty , configMonoidScmInit = Nothing , configMonoidCompilerCheck = Nothing , configMonoidGhcOptions = mempty , configMonoidExtraPath = [] , configMonoidSetupInfoLocations = mempty , configMonoidPvpBounds = Nothing } mappend l r = ConfigMonoid { configMonoidDockerOpts = configMonoidDockerOpts l <> configMonoidDockerOpts r , configMonoidConnectionCount = configMonoidConnectionCount l <|> configMonoidConnectionCount r , configMonoidHideTHLoading = configMonoidHideTHLoading l <|> configMonoidHideTHLoading r , configMonoidLatestSnapshotUrl = configMonoidLatestSnapshotUrl l <|> configMonoidLatestSnapshotUrl r , configMonoidPackageIndices = configMonoidPackageIndices l <|> configMonoidPackageIndices r , configMonoidSystemGHC = configMonoidSystemGHC l <|> configMonoidSystemGHC r , configMonoidInstallGHC = configMonoidInstallGHC l <|> configMonoidInstallGHC r , configMonoidSkipGHCCheck = configMonoidSkipGHCCheck l <|> configMonoidSkipGHCCheck r , configMonoidSkipMsys = configMonoidSkipMsys l <|> configMonoidSkipMsys r , configMonoidRequireStackVersion = intersectVersionRanges (configMonoidRequireStackVersion l) (configMonoidRequireStackVersion r) , configMonoidOS = configMonoidOS l <|> configMonoidOS r , configMonoidArch = configMonoidArch l <|> configMonoidArch r , configMonoidGHCVariant = configMonoidGHCVariant l <|> configMonoidGHCVariant r , configMonoidJobs = configMonoidJobs l <|> configMonoidJobs r , configMonoidExtraIncludeDirs = Set.union (configMonoidExtraIncludeDirs l) (configMonoidExtraIncludeDirs r) , configMonoidExtraLibDirs = Set.union (configMonoidExtraLibDirs l) (configMonoidExtraLibDirs r) , configMonoidConcurrentTests = configMonoidConcurrentTests l <|> configMonoidConcurrentTests r , configMonoidLocalBinPath = configMonoidLocalBinPath l <|> configMonoidLocalBinPath r , configMonoidImageOpts = configMonoidImageOpts l <> configMonoidImageOpts r , configMonoidTemplateParameters = configMonoidTemplateParameters l <> configMonoidTemplateParameters r , configMonoidScmInit = configMonoidScmInit l <|> configMonoidScmInit r , configMonoidCompilerCheck = configMonoidCompilerCheck l <|> configMonoidCompilerCheck r , configMonoidGhcOptions = Map.unionWith (++) (configMonoidGhcOptions l) (configMonoidGhcOptions r) , configMonoidExtraPath = configMonoidExtraPath l ++ configMonoidExtraPath r , configMonoidSetupInfoLocations = configMonoidSetupInfoLocations l ++ configMonoidSetupInfoLocations r , configMonoidPvpBounds = configMonoidPvpBounds l <|> configMonoidPvpBounds r } instance FromJSON (ConfigMonoid, [JSONWarning]) where parseJSON = withObjectWarnings "ConfigMonoid" parseConfigMonoidJSON -- | Parse a partial configuration. Used both to parse both a standalone config -- file and a project file, so that a sub-parser is not required, which would interfere with -- warnings for missing fields. parseConfigMonoidJSON :: Object -> WarningParser ConfigMonoid parseConfigMonoidJSON obj = do configMonoidDockerOpts <- jsonSubWarnings (obj ..:? "docker" ..!= mempty) configMonoidConnectionCount <- obj ..:? "connection-count" configMonoidHideTHLoading <- obj ..:? "hide-th-loading" configMonoidLatestSnapshotUrl <- obj ..:? "latest-snapshot-url" configMonoidPackageIndices <- jsonSubWarningsTT (obj ..:? "package-indices") configMonoidSystemGHC <- obj ..:? "system-ghc" configMonoidInstallGHC <- obj ..:? "install-ghc" configMonoidSkipGHCCheck <- obj ..:? "skip-ghc-check" configMonoidSkipMsys <- obj ..:? "skip-msys" configMonoidRequireStackVersion <- unVersionRangeJSON <$> obj ..:? "require-stack-version" ..!= VersionRangeJSON anyVersion configMonoidOS <- obj ..:? "os" configMonoidArch <- obj ..:? "arch" configMonoidGHCVariant <- obj ..:? "ghc-variant" configMonoidJobs <- obj ..:? "jobs" configMonoidExtraIncludeDirs <- obj ..:? "extra-include-dirs" ..!= Set.empty configMonoidExtraLibDirs <- obj ..:? "extra-lib-dirs" ..!= Set.empty configMonoidConcurrentTests <- obj ..:? "concurrent-tests" configMonoidLocalBinPath <- obj ..:? "local-bin-path" configMonoidImageOpts <- jsonSubWarnings (obj ..:? "image" ..!= mempty) templates <- obj ..:? "templates" (configMonoidScmInit,configMonoidTemplateParameters) <- case templates of Nothing -> return (Nothing,M.empty) Just tobj -> do scmInit <- tobj ..:? "scm-init" params <- tobj ..:? "params" return (scmInit,fromMaybe M.empty params) configMonoidCompilerCheck <- obj ..:? "compiler-check" mghcoptions <- obj ..:? "ghc-options" configMonoidGhcOptions <- case mghcoptions of Nothing -> return mempty Just m -> fmap Map.fromList $ mapM handleGhcOptions $ Map.toList m extraPath <- obj ..:? "extra-path" ..!= [] configMonoidExtraPath <- forM extraPath $ either (fail . show) return . parseAbsDir . T.unpack configMonoidSetupInfoLocations <- maybeToList <$> jsonSubWarningsT (obj ..:? "setup-info") configMonoidPvpBounds <- obj ..:? "pvp-bounds" return ConfigMonoid {..} where handleGhcOptions :: Monad m => (Text, Text) -> m (Maybe PackageName, [Text]) handleGhcOptions (name', vals') = do name <- if name' == "*" then return Nothing else case parsePackageNameFromString $ T.unpack name' of Left e -> fail $ show e Right x -> return $ Just x case parseArgs Escaping vals' of Left e -> fail e Right vals -> return (name, map T.pack vals) -- | Newtype for non-orphan FromJSON instance. newtype VersionRangeJSON = VersionRangeJSON { unVersionRangeJSON :: VersionRange } -- | Parse VersionRange. instance FromJSON VersionRangeJSON where parseJSON = withText "VersionRange" (\s -> maybe (fail ("Invalid cabal-style VersionRange: " ++ T.unpack s)) (return . VersionRangeJSON) (Distribution.Text.simpleParse (T.unpack s))) data ConfigException = ParseConfigFileException (Path Abs File) ParseException | ParseResolverException Text | NoProjectConfigFound (Path Abs Dir) (Maybe Text) | UnexpectedTarballContents [Path Abs Dir] [Path Abs File] | BadStackVersionException VersionRange | NoMatchingSnapshot [SnapName] | NoSuchDirectory FilePath | ParseGHCVariantException String deriving Typeable instance Show ConfigException where show (ParseConfigFileException configFile exception) = concat [ "Could not parse '" , toFilePath configFile , "':\n" , show exception , "\nSee https://github.com/commercialhaskell/stack/blob/master/doc/yaml_configuration.md." ] show (ParseResolverException t) = concat [ "Invalid resolver value: " , T.unpack t , ". Possible valid values include lts-2.12, nightly-YYYY-MM-DD, ghc-7.10.2, and ghcjs-0.1.0_ghc-7.10.2. " , "See https://www.stackage.org/snapshots for a complete list." ] show (NoProjectConfigFound dir mcmd) = concat [ "Unable to find a stack.yaml file in the current directory (" , toFilePath dir , ") or its ancestors" , case mcmd of Nothing -> "" Just cmd -> "\nRecommended action: stack " ++ T.unpack cmd ] show (UnexpectedTarballContents dirs files) = concat [ "When unpacking a tarball specified in your stack.yaml file, " , "did not find expected contents. Expected: a single directory. Found: " , show ( map (toFilePath . dirname) dirs , map (toFilePath . filename) files ) ] show (BadStackVersionException requiredRange) = concat [ "The version of stack you are using (" , show (fromCabalVersion Meta.version) , ") is outside the required\n" ,"version range (" , T.unpack (versionRangeText requiredRange) , ") specified in stack.yaml." ] show (NoMatchingSnapshot names) = concat [ "There was no snapshot found that matched the package " , "bounds in your .cabal files.\n" , "Please choose one of the following commands to get started.\n\n" , unlines $ map (\name -> " stack init --resolver " ++ T.unpack (renderSnapName name)) names , "\nYou'll then need to add some extra-deps. See:\n\n" , " https://github.com/commercialhaskell/stack/blob/master/doc/yaml_configuration.md#extra-deps" , "\n\nYou can also try falling back to a dependency solver with:\n\n" , " stack init --solver" ] show (NoSuchDirectory dir) = concat ["No directory could be located matching the supplied path: " ,dir ] show (ParseGHCVariantException v) = concat [ "Invalid ghc-variant value: " , v ] instance Exception ConfigException -- | Helper function to ask the environment and apply getConfig askConfig :: (MonadReader env m, HasConfig env) => m Config askConfig = liftM getConfig ask -- | Get the URL to request the information on the latest snapshots askLatestSnapshotUrl :: (MonadReader env m, HasConfig env) => m Text askLatestSnapshotUrl = asks (configLatestSnapshotUrl . getConfig) -- | Root for a specific package index configPackageIndexRoot :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs Dir) configPackageIndexRoot (IndexName name) = do config <- asks getConfig dir <- parseRelDir $ S8.unpack name return (configStackRoot config </> $(mkRelDir "indices") </> dir) -- | Location of the 00-index.cache file configPackageIndexCache :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndexCache = liftM (</> $(mkRelFile "00-index.cache")) . configPackageIndexRoot -- | Location of the 00-index.tar file configPackageIndex :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndex = liftM (</> $(mkRelFile "00-index.tar")) . configPackageIndexRoot -- | Location of the 00-index.tar.gz file configPackageIndexGz :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndexGz = liftM (</> $(mkRelFile "00-index.tar.gz")) . configPackageIndexRoot -- | Location of a package tarball configPackageTarball :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> PackageIdentifier -> m (Path Abs File) configPackageTarball iname ident = do root <- configPackageIndexRoot iname name <- parseRelDir $ packageNameString $ packageIdentifierName ident ver <- parseRelDir $ versionString $ packageIdentifierVersion ident base <- parseRelFile $ packageIdentifierString ident ++ ".tar.gz" return (root </> $(mkRelDir "packages") </> name </> ver </> base) workDirRel :: Path Rel Dir workDirRel = $(mkRelDir ".stack-work") -- | Per-project work dir configProjectWorkDir :: (HasBuildConfig env, MonadReader env m) => m (Path Abs Dir) configProjectWorkDir = do bc <- asks getBuildConfig return (bcRoot bc </> workDirRel) -- | File containing the installed cache, see "Stack.PackageDump" configInstalledCache :: (HasBuildConfig env, MonadReader env m) => m (Path Abs File) configInstalledCache = liftM (</> $(mkRelFile "installed-cache.bin")) configProjectWorkDir -- | Relative directory for the platform identifier platformOnlyRelDir :: (MonadReader env m, HasPlatform env, MonadThrow m) => m (Path Rel Dir) platformOnlyRelDir = do platform <- asks getPlatform parseRelDir (Distribution.Text.display platform) -- | Relative directory for the platform identifier platformVariantRelDir :: (MonadReader env m, HasPlatform env, HasGHCVariant env, MonadThrow m) => m (Path Rel Dir) platformVariantRelDir = do platform <- asks getPlatform ghcVariant <- asks getGHCVariant parseRelDir (Distribution.Text.display platform <> ghcVariantSuffix ghcVariant) -- | Path to .shake files. configShakeFilesDir :: (MonadReader env m, HasBuildConfig env) => m (Path Abs Dir) configShakeFilesDir = liftM (</> $(mkRelDir "shake")) configProjectWorkDir -- | Where to unpack packages for local build configLocalUnpackDir :: (MonadReader env m, HasBuildConfig env) => m (Path Abs Dir) configLocalUnpackDir = liftM (</> $(mkRelDir "unpacked")) configProjectWorkDir -- | Directory containing snapshots snapshotsDir :: (MonadReader env m, HasConfig env, HasGHCVariant env, MonadThrow m) => m (Path Abs Dir) snapshotsDir = do config <- asks getConfig platform <- platformVariantRelDir return $ configStackRoot config </> $(mkRelDir "snapshots") </> platform -- | Installation root for dependencies installationRootDeps :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) installationRootDeps = do snapshots <- snapshotsDir bc <- asks getBuildConfig name <- parseRelDir $ T.unpack $ resolverName $ bcResolver bc ghc <- compilerVersionDir return $ snapshots </> name </> ghc -- | Installation root for locals installationRootLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) installationRootLocal = do bc <- asks getBuildConfig name <- parseRelDir $ T.unpack $ resolverName $ bcResolver bc ghc <- compilerVersionDir platform <- platformVariantRelDir return $ configProjectWorkDir bc </> $(mkRelDir "install") </> platform </> name </> ghc compilerVersionDir :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Rel Dir) compilerVersionDir = do compilerVersion <- asks (envConfigCompilerVersion . getEnvConfig) parseRelDir $ case compilerVersion of GhcVersion version -> versionString version GhcjsVersion {} -> compilerVersionString compilerVersion -- | Package database for installing dependencies into packageDatabaseDeps :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) packageDatabaseDeps = do root <- installationRootDeps return $ root </> $(mkRelDir "pkgdb") -- | Package database for installing local packages into packageDatabaseLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) packageDatabaseLocal = do root <- installationRootLocal return $ root </> $(mkRelDir "pkgdb") -- | Directory for holding flag cache information flagCacheLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) flagCacheLocal = do root <- installationRootLocal return $ root </> $(mkRelDir "flag-cache") -- | Where to store mini build plan caches configMiniBuildPlanCache :: (MonadThrow m, MonadReader env m, HasConfig env, HasGHCVariant env) => SnapName -> m (Path Abs File) configMiniBuildPlanCache name = do root <- asks getStackRoot platform <- platformVariantRelDir file <- parseRelFile $ T.unpack (renderSnapName name) ++ ".cache" -- Yes, cached plans differ based on platform return (root </> $(mkRelDir "build-plan-cache") </> platform </> file) -- | Suffix applied to an installation root to get the bin dir bindirSuffix :: Path Rel Dir bindirSuffix = $(mkRelDir "bin") -- | Suffix applied to an installation root to get the doc dir docDirSuffix :: Path Rel Dir docDirSuffix = $(mkRelDir "doc") -- | Suffix applied to an installation root to get the hpc dir hpcDirSuffix :: Path Rel Dir hpcDirSuffix = $(mkRelDir "hpc") -- | Get the extra bin directories (for the PATH). Puts more local first -- -- Bool indicates whether or not to include the locals extraBinDirs :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Bool -> [Path Abs Dir]) extraBinDirs = do deps <- installationRootDeps local <- installationRootLocal return $ \locals -> if locals then [local </> bindirSuffix, deps </> bindirSuffix] else [deps </> bindirSuffix] -- | Get the minimal environment override, useful for just calling external -- processes like git or ghc getMinimalEnvOverride :: (MonadReader env m, HasConfig env, MonadIO m) => m EnvOverride getMinimalEnvOverride = do config <- asks getConfig liftIO $ configEnvOverride config minimalEnvSettings minimalEnvSettings :: EnvSettings minimalEnvSettings = EnvSettings { esIncludeLocals = False , esIncludeGhcPackagePath = False , esStackExe = False , esLocaleUtf8 = False } getWhichCompiler :: (MonadReader env m, HasEnvConfig env) => m WhichCompiler getWhichCompiler = asks (whichCompiler . envConfigCompilerVersion . getEnvConfig) data ProjectAndConfigMonoid = ProjectAndConfigMonoid !Project !ConfigMonoid instance (warnings ~ [JSONWarning]) => FromJSON (ProjectAndConfigMonoid, warnings) where parseJSON = withObjectWarnings "ProjectAndConfigMonoid" $ \o -> do dirs <- jsonSubWarningsTT (o ..:? "packages") ..!= [packageEntryCurrDir] extraDeps' <- o ..:? "extra-deps" ..!= [] extraDeps <- case partitionEithers $ goDeps extraDeps' of ([], x) -> return $ Map.fromList x (errs, _) -> fail $ unlines errs flags <- o ..:? "flags" ..!= mempty resolver <- jsonSubWarnings (o ..: "resolver") config <- parseConfigMonoidJSON o let project = Project { projectPackages = dirs , projectExtraDeps = extraDeps , projectFlags = flags , projectResolver = resolver } return $ ProjectAndConfigMonoid project config where goDeps = map toSingle . Map.toList . Map.unionsWith Set.union . map toMap where toMap i = Map.singleton (packageIdentifierName i) (Set.singleton (packageIdentifierVersion i)) toSingle (k, s) = case Set.toList s of [x] -> Right (k, x) xs -> Left $ concat [ "Multiple versions for package " , packageNameString k , ": " , unwords $ map versionString xs ] -- | A PackageEntry for the current directory, used as a default packageEntryCurrDir :: PackageEntry packageEntryCurrDir = PackageEntry { peValidWanted = Nothing , peExtraDepMaybe = Nothing , peLocation = PLFilePath "." , peSubdirs = [] } -- | A software control system. data SCM = Git deriving (Show) instance FromJSON SCM where parseJSON v = do s <- parseJSON v case s of "git" -> return Git _ -> fail ("Unknown or unsupported SCM: " <> s) instance ToJSON SCM where toJSON Git = toJSON ("git" :: Text) -- | Specialized bariant of GHC (e.g. libgmp4 or integer-simple) data GHCVariant = GHCStandard -- ^ Standard bindist | GHCGMP4 -- ^ Bindist that supports libgmp4 (centos66) | GHCArch -- ^ Bindist built on Arch Linux (bleeding-edge) | GHCIntegerSimple -- ^ Bindist that uses integer-simple | GHCCustom String -- ^ Other bindists deriving (Show) instance FromJSON GHCVariant where -- Strange structuring is to give consistent error messages parseJSON = withText "GHCVariant" (either (fail . show) return . parseGHCVariant . T.unpack) -- | Render a GHC variant to a String. ghcVariantName :: GHCVariant -> String ghcVariantName GHCStandard = "standard" ghcVariantName GHCGMP4 = "gmp4" ghcVariantName GHCArch = "arch" ghcVariantName GHCIntegerSimple = "integersimple" ghcVariantName (GHCCustom name) = "custom-" ++ name -- | Render a GHC variant to a String suffix. ghcVariantSuffix :: GHCVariant -> String ghcVariantSuffix GHCStandard = "" ghcVariantSuffix v = "-" ++ ghcVariantName v -- | Parse GHC variant from a String. parseGHCVariant :: (MonadThrow m) => String -> m GHCVariant parseGHCVariant s = case stripPrefix "custom-" s of Just name -> return (GHCCustom name) Nothing | s == "" -> return GHCStandard | s == "standard" -> return GHCStandard | s == "gmp4" -> return GHCGMP4 | s == "arch" -> return GHCArch | s == "integersimple" -> return GHCIntegerSimple | otherwise -> return (GHCCustom s) -- | Information for a file to download. data DownloadInfo = DownloadInfo { downloadInfoUrl :: Text , downloadInfoContentLength :: Maybe Int , downloadInfoSha1 :: Maybe ByteString } deriving (Show) instance FromJSON (DownloadInfo, [JSONWarning]) where parseJSON = withObjectWarnings "DownloadInfo" parseDownloadInfoFromObject -- | Parse JSON in existing object for 'DownloadInfo' parseDownloadInfoFromObject :: Object -> WarningParser DownloadInfo parseDownloadInfoFromObject o = do url <- o ..: "url" contentLength <- o ..:? "content-length" sha1TextMay <- o ..:? "sha1" -- Don't warn about 'version' field that is sometimes included tellJSONField "version" return DownloadInfo { downloadInfoUrl = url , downloadInfoContentLength = contentLength , downloadInfoSha1 = fmap encodeUtf8 sha1TextMay } data VersionedDownloadInfo = VersionedDownloadInfo { vdiVersion :: Version , vdiDownloadInfo :: DownloadInfo } deriving Show instance FromJSON (VersionedDownloadInfo, [JSONWarning]) where parseJSON = withObjectWarnings "VersionedDownloadInfo" $ \o -> do version <- o ..: "version" downloadInfo <- parseDownloadInfoFromObject o return VersionedDownloadInfo { vdiVersion = version , vdiDownloadInfo = downloadInfo } data SetupInfo = SetupInfo { siSevenzExe :: Maybe DownloadInfo , siSevenzDll :: Maybe DownloadInfo , siMsys2 :: Map Text VersionedDownloadInfo , siGHCs :: Map Text (Map Version DownloadInfo) , siGHCJSs :: Map Text (Map CompilerVersion DownloadInfo) } deriving Show instance FromJSON (SetupInfo, [JSONWarning]) where parseJSON = withObjectWarnings "SetupInfo" $ \o -> do siSevenzExe <- jsonSubWarningsT (o ..:? "sevenzexe-info") siSevenzDll <- jsonSubWarningsT (o ..:? "sevenzdll-info") siMsys2 <- jsonSubWarningsT (o ..:? "msys2" ..!= mempty) siGHCs <- jsonSubWarningsTT (o ..:? "ghc" ..!= mempty) siGHCJSs <- jsonSubWarningsTT (o ..:? "ghcjs" ..!= mempty) -- Don't warn about 'portable-git' that is no-longer used tellJSONField "portable-git" return SetupInfo {..} instance Monoid SetupInfo where mempty = SetupInfo { siSevenzExe = Nothing , siSevenzDll = Nothing , siMsys2 = Map.empty , siGHCs = Map.empty , siGHCJSs = Map.empty } mappend l r = SetupInfo { siSevenzExe = siSevenzExe l <|> siSevenzExe r , siSevenzDll = siSevenzDll l <|> siSevenzDll r , siMsys2 = siMsys2 l <> siMsys2 r , siGHCs = siGHCs l <> siGHCs r , siGHCJSs = siGHCJSs l <> siGHCJSs r } -- | Remote or inline 'SetupInfo' data SetupInfoLocation = SetupInfoFileOrURL String | SetupInfoInline SetupInfo deriving (Show) instance FromJSON (SetupInfoLocation, [JSONWarning]) where parseJSON v = ((, []) <$> withText "SetupInfoFileOrURL" (pure . SetupInfoFileOrURL . T.unpack) v) <|> inline where inline = do (si,w) <- parseJSON v return (SetupInfoInline si, w) -- | How PVP bounds should be added to .cabal files data PvpBounds = PvpBoundsNone | PvpBoundsUpper | PvpBoundsLower | PvpBoundsBoth deriving (Show, Read, Eq, Typeable, Ord, Enum, Bounded) pvpBoundsText :: PvpBounds -> Text pvpBoundsText PvpBoundsNone = "none" pvpBoundsText PvpBoundsUpper = "upper" pvpBoundsText PvpBoundsLower = "lower" pvpBoundsText PvpBoundsBoth = "both" parsePvpBounds :: Text -> Either String PvpBounds parsePvpBounds t = case Map.lookup t m of Nothing -> Left $ "Invalid PVP bounds: " ++ T.unpack t Just x -> Right x where m = Map.fromList $ map (pvpBoundsText &&& id) [minBound..maxBound] instance ToJSON PvpBounds where toJSON = toJSON . pvpBoundsText instance FromJSON PvpBounds where parseJSON = withText "PvpBounds" (either fail return . parsePvpBounds)
robstewart57/stack
src/Stack/Types/Config.hs
bsd-3-clause
49,239
0
17
12,020
9,700
5,160
4,540
1,043
6
{-# LANGUAGE OverloadedStrings #-} module Trurl where import System.Directory import System.FilePath import Network.HTTP.Conduit import Codec.Archive.Tar import Data.List hiding (find) import Text.Hastache import Text.Hastache.Aeson import Data.Aeson import Data.String.Utils import System.FilePath.Find (find, always, fileName, extension, (==?), liftOp) import Safe import qualified Data.Text as T import qualified Data.Text.Lazy.IO as TL import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC8 constProjectName :: String constProjectName = "ProjectName" mainRepoFile :: String mainRepoFile = "mainRepo.tar" mainRepo :: String mainRepo = "https://github.com/dbushenko/trurl/raw/master/repository/" ++ mainRepoFile templateExt :: String templateExt = ".template" getLocalRepoDir :: IO FilePath getLocalRepoDir = do home <- getHomeDirectory return $ home ++ "/.trurl/repo/" printFile :: FilePath -> FilePath -> IO () printFile dir fp = do file <- readFile (dir ++ fp) putStrLn file printFileHeader :: FilePath -> FilePath -> IO () printFileHeader dir fp = do file <- readFile (dir ++ fp) putStrLn $ headDef "No info found..." $ lines file processTemplate :: String -> String -> FilePath -> IO () processTemplate projName paramsStr filePath = do generated <- hastacheFile defaultConfig filePath (mkProjContext projName paramsStr) TL.writeFile (dropExtension filePath) generated removeFile filePath return () getFileName :: FilePath -> FilePath getFileName template = if hasExtension template then template else template <.> "hs" getFullFileName :: FilePath -> String -> FilePath getFullFileName repoDir template = repoDir ++ getFileName template mkJsonContext :: Monad m => String -> MuContext m mkJsonContext = maybe mkEmptyContext jsonValueContext . decode . BLC8.pack mkEmptyContext :: Monad m => MuContext m mkEmptyContext = const $ return MuNothing mkProjContext :: Monad m => String -> String -> MuContext m mkProjContext projName paramsStr = assoc "ProjectName" projName $ mkJsonContext paramsStr mkFileContext :: Monad m => FilePath -> String -> MuContext m mkFileContext fname paramsStr = assoc "FileName" fname $ mkJsonContext paramsStr assoc :: (Monad m, MuVar a) => T.Text -> a -> MuContext m -> MuContext m assoc newKey newVal oldCtx k = if k == newKey then return $ MuVariable newVal else oldCtx k substituteProjectName :: String -> FilePath -> FilePath substituteProjectName projectName filePath = let (dirName, oldFileName) = splitFileName filePath newFileName = replace constProjectName projectName oldFileName in dirName </> newFileName ------------------------------------- -- API -- -- Команда "update" -- 1) Создать $HOME/.trurl/repo -- 2) Забрать из репозитория свежий tar-архив с апдейтами -- 3) Распаковать его в $HOME/.trurl/repo -- updateFromRepository :: IO () updateFromRepository = do repoDir <- getLocalRepoDir createDirectoryIfMissing True repoDir let tarFile = repoDir ++ mainRepoFile simpleHttp mainRepo >>= BL.writeFile tarFile extract repoDir tarFile removeFile tarFile -- Команда "create <name> <project> [parameters]" -- 1) Найти в $HOME/.trurl/repo архив с именем project.tar -- 2) Создать директорию ./name -- 3) Распаковать в ./name содержимое project.tar -- 4) Найти все файлы с расширением ".template" -- 5) Отрендерить эти темплейты c учетом переданных parameters -- 6) Сохранить отрендеренные файлы в новые файлы без ".template" -- 7) Удалить все файлы с расширением ".template" -- 8) Найти все файлы с именем ProjectName независимо от расширения -- 9) Переименовать эти файлы в соотествии с указанным ProjectName -- createProject :: String -> String -> String -> IO () createProject name project paramsStr = do -- Extract the archive repoDir <- getLocalRepoDir createDirectoryIfMissing True name extract name $ repoDir ++ project ++ ".tar" -- Process all templates templatePaths <- find always (extension ==? templateExt) name mapM_ (processTemplate name paramsStr) templatePaths -- Find 'ProjectName' files let checkFileName fname templname = isInfixOf templname fname projNamePaths <- find always (liftOp checkFileName fileName constProjectName) name -- Rename 'ProjectName' files let renameProjNameFile fpath = renameFile fpath (substituteProjectName name fpath) mapM_ renameProjNameFile projNamePaths -- Команда "new <file> [parameters]" -- 1) Найти в $HOME/.trurl/repo архив с именем file.hs. -- Если имя файла передано с расширением, то найти точное имя файла, не подставляя *.hs -- 2) Прочитать содержимое шаблона -- 3) Отрендерить его с применением hastache и переданных параметров -- 4) Записать файл в ./ -- newTemplate :: String -> String -> String -> IO () newTemplate name templateName paramsStr = do repoDir <- getLocalRepoDir let templPath = getFullFileName repoDir templateName generated <- hastacheFile defaultConfig templPath (mkFileContext name paramsStr) TL.writeFile (getFileName name) generated -- Команда "list" -- 1) Найти все файлы с расширением '.metainfo' -- 2) Для каждого найденного файла вывести первую строчку -- listTemplates :: IO () listTemplates = do repoDir <- getLocalRepoDir files <- getDirectoryContents repoDir let mpaths = filter (endswith ".metainfo") files mapM_ (printFileHeader repoDir) mpaths -- Команда "help <template>" -- 1) Найти указанный файл с расширением '.metainfo' -- 2) Вывести его содержимое -- helpTemplate :: String -> IO () helpTemplate template = do repoDir <- getLocalRepoDir templExists <- doesFileExist $ repoDir ++ template ++ ".metainfo" if templExists then printFile repoDir $ template ++ ".metainfo" else printFile repoDir ((getFileName template) ++ ".metainfo")
DNNX/trurl
src/Trurl.hs
bsd-3-clause
6,428
0
12
916
1,293
662
631
108
2
module Module4.Task3 where data Color = Red | Green | Blue deriving (Show, Read) stringToColor :: String -> Color stringToColor = read
dstarcev/stepic-haskell
src/Module4/Task3.hs
bsd-3-clause
143
0
6
30
44
26
18
4
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} module Servant.Docs.Internal.Pretty where import Data.Aeson (ToJSON(..)) import Data.Aeson.Encode.Pretty (encodePretty) import Data.Proxy (Proxy(Proxy)) import Network.HTTP.Media ((//)) import Servant.API -- | PrettyJSON content type. data PrettyJSON instance Accept PrettyJSON where contentType _ = "application" // "json" instance ToJSON a => MimeRender PrettyJSON a where mimeRender _ = encodePretty -- | Prettify generated JSON documentation. -- -- @ -- 'docs' ('pretty' ('Proxy' :: 'Proxy' MyAPI)) -- @ pretty :: Proxy api -> Proxy (Pretty api) pretty Proxy = Proxy -- | Replace all JSON content types with PrettyJSON. -- Kind-polymorphic so it can operate on kinds @*@ and @[*]@. type family Pretty (api :: k) :: k where Pretty (x :<|> y) = Pretty x :<|> Pretty y Pretty (x :> y) = Pretty x :> Pretty y Pretty (Get cs r) = Get (Pretty cs) r Pretty (Post cs r) = Post (Pretty cs) r Pretty (Put cs r) = Put (Pretty cs) r Pretty (Delete cs r) = Delete (Pretty cs) r Pretty (Patch cs r) = Patch (Pretty cs) r Pretty (ReqBody cs r) = ReqBody (Pretty cs) r Pretty (JSON ': xs) = PrettyJSON ': xs Pretty (x ': xs) = x ': Pretty xs Pretty x = x
zerobuzz/servant
servant-docs/src/Servant/Docs/Internal/Pretty.hs
bsd-3-clause
1,606
0
8
439
444
240
204
-1
-1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} module Sudoku.Cell (Cell(..)) where import Prelude hiding ((&&), (||), not, and, or, all, any) import Data.Typeable (Typeable) import Data.Word import Ersatz import GHC.Generics newtype Cell = Cell Bit4 deriving (Show, Typeable, Generic) instance Boolean Cell instance Variable Cell instance Equatable Cell instance Codec Cell where type Decoded Cell = Word8 decode s (Cell b) = decode s b encode n | 1 <= n && n <= 9 = Cell (encode n) | otherwise = error ("Cell encode: invalid value " ++ show n)
msakai/ersatz-toysat
examples/sudoku/Sudoku/Cell.hs
bsd-3-clause
623
0
11
124
211
116
95
19
0
module DotRace.FFI.Raw where import FFI import FFI.Types import SharedTypes (Track, readI) import Data.Text (Text) readTrackData :: Fay Text readTrackData = ffi "$('#track')['val']()" parseTrackData :: Text -> Fay Track parseTrackData = ffi "JSON['parse'](%1)" addWindowEvent :: Text -> (Event -> Fay ()) -> Fay () addWindowEvent = ffi "window['addEventListener'](%1, %2)" selectId :: Text -> Fay Element selectId = ffi "document['getElementById'](%1)" selectClass :: Text -> Fay [Element] selectClass = ffi "document['getElementsByClassName'](%1)" addEvent :: Element -> Text -> (Event -> Fay ()) -> Fay () addEvent = ffi "$(%1)['on'](%2, %3)" eventPageX, eventPageY :: Event -> Fay Double eventPageX = ffi "%1['pageX']" eventPageY = ffi "%1['pageY']" getBoundingClientRect :: Element -> Fay Element getBoundingClientRect = ffi "%1['getBoundingClientRect']()" rectLeft, rectTop, getScrollTop, getScrollLeft :: Element -> Fay Double rectLeft = ffi "%1['left']" rectTop = ffi "%1['top']" getScrollTop = ffi "%1['scrollTop']" getScrollLeft = ffi "%1['scrollLeft']" hide :: Element -> Fay () hide = ffi "%1['remove']()" getURL :: Fay Text getURL = ffi "document['URL']" getWSConnection :: Fay Connection getWSConnection = ffi "new WebSocket(document['URL']['replace']('http', 'ws'))" onMessage :: Connection -> (Event -> Fay ()) -> Fay () onMessage = ffi "%1['onmessage'] = %2" getText :: Event -> Fay Text getText = ffi "%1['data']" sendText :: Connection -> Text -> Fay () sendText = ffi "%1['send'](%2)" addChatMessage :: Text -> Fay () addChatMessage = ffi "$('#chat div').append('<p>'+%1+'</p>')" preventDefault :: Event -> Fay () preventDefault = ffi "%1['preventDefault']()" eventKey :: Event -> Int eventKey = ffi "%1['keyCode']" getChatMessage :: Fay Text getChatMessage = ffi "$('#chatInput')['val']()" clearChatMessage :: Fay () clearChatMessage = ffi "$('#chatInput')['val']('')" getSelectedValue :: Element -> Fay Text getSelectedValue = ffi "%1['options'][%1['selectedIndex']].value" setMax :: Element -> Int -> Fay () setMax = ffi "%1['setAttribute']('max', %2)" getValue :: Element -> Fay Text getValue = ffi "%1['value']" setValue :: Element -> Int -> Fay () setValue = ffi "%1['value'] = %2" setTextValue :: Element -> Text -> Fay () setTextValue = ffi "%1['value'] = %2" focusElement :: Element -> Fay () focusElement = ffi "%1['focus']()" showDialog :: Text -> Fay () showDialog = ffi "$('#'+%1+'')['modal']()" getPlayerName :: Fay Text getPlayerName = ffi "$('#inputName')['val']()" getNumPlayers :: Fay Int getNumPlayers = ffi "parseInt($('#numPlayers')['val'](), 10)" setWinner :: Text -> Fay () setWinner = ffi "$('#winner')['text'](%1)" displayThisPlayerName :: Text -> Fay () displayThisPlayerName = ffi "$('#thisPlayerName').text(%1)" displayThisPlayerNum :: Int -> Fay () displayThisPlayerNum = ffi "$('#thisPlayerName').addClass('player-'+%1)" displayGameStatus :: Text -> Fay () displayGameStatus = ffi "$('#gameStatus').html(%1)" displayChatMsgRaw :: Text -> Fay () displayChatMsgRaw = ffi "$('#chat div').append(%1)" scrollChat :: Fay () scrollChat = ffi "$('#chat div').stop().animate({scrollTop: $('#chat div')[0].scrollHeight}, 800)"
lubomir/dot-race
fay/DotRace/FFI/Raw.hs
bsd-3-clause
3,203
0
11
447
850
435
415
79
1
module IO.Arrays ( zip4, unzip4, fromImageToRepa, fromRepaToImage, RGBA8 ) where import System.Environment import Control.Monad import Data.Array.Repa as Repa import Codec.Picture import Data.Array.Repa.Stencil import Data.Array.Repa.Stencil.Dim2 import Filters.Types -- | -- Like zip, but for quadruples zip4 :: Array D DIM2 a -> Array D DIM2 a -> Array D DIM2 a -> Array D DIM2 a -> Array D DIM2 (a,a,a,a) zip4 m1 m2 m3 m4 = fromFunction (extent m1) (\(Z:. w :. h) -> (m1!(Z:. w :. h) , m2!(Z:. w :. h) , m3!(Z:. w :. h) , m4!(Z:. w :. h))) -- | -- Like unzip, but for quadruples unzip4 :: Array D DIM2 (a,a,a,a) -> (Array D DIM2 a, Array D DIM2 a, Array D DIM2 a, Array D DIM2 a) unzip4 matrix = (m1, m2, m3, m4) where m1 = unzip4' (\(a,b,c,d) -> a) m2 = unzip4' (\(a,b,c,d) -> b) m3 = unzip4' (\(a,b,c,d) -> c) m4 = unzip4' (\(a,b,c,d) -> d) unzip4' f = fromFunction (extent matrix) (\(Z:. w:. h) -> f (matrix!(Z:. w:. h))) fromImage :: (Pixel a) => Image a -> (a -> RGBA8) -> Array D DIM2 RGBA8 fromImage image f = fromFunction ( Z :. width :. height ) (\(Z :. w :. h) -> f $ (pixelAt image w h)) where width = imageWidth image height = imageHeight image -- | -- Convert an Image to REPA array representation fromImageToRepa :: DynamicImage -> Array D DIM2 RGBA8 fromImageToRepa image = fromImage (convertRGBA8 image) fromRGBA8 -- | -- Convert an Image from REPA array representation to DynamicImage from Juicy Pixels fromRepaToImage :: Array D DIM2 RGBA8-> DynamicImage fromRepaToImage matrix = ImageRGBA8 ( generateImage (\w h -> toRGBA8 $ matrix!(Z :. w :. h)) width height) where (Z :. width :. height) = extent matrix
MajronMan/Himage
src/IO/Arrays.hs
bsd-3-clause
1,809
0
15
474
758
419
339
46
1
{-# LANGUAGE ForeignFunctionInterface, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, Rank2Types #-} module FRP.Sodium.GameEngine2D.GLUT where import FRP.Sodium.GameEngine2D.Cache import FRP.Sodium.GameEngine2D.CommonAL (SoundInfo(..)) import qualified FRP.Sodium.GameEngine2D.CommonAL as CommonAL import FRP.Sodium.GameEngine2D.CommonGL import FRP.Sodium.GameEngine2D.Geometry import FRP.Sodium.GameEngine2D.Image import FRP.Sodium.GameEngine2D.Platform import Control.Applicative import Control.Concurrent (threadDelay, forkIO) import Control.Monad.Reader import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as C import Data.IORef import Data.Map (Map) import qualified Data.Map as M import Data.Monoid (Monoid(..)) import qualified Data.Sequence as Seq import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import FRP.Sodium import System.FilePath import Foreign hiding (unsafePerformIO) import Foreign.C --import qualified Graphics.Rendering.FTGL as FTGL import Graphics.Rendering.OpenGL.GL as GL hiding (Rect, normal) import Graphics.Rendering.OpenGL.Raw import qualified Graphics.UI.GLUT as GLUT hiding (Rect, translate) import System.Exit import System.FilePath import System.IO.Unsafe import System.Random (newStdGen) initGraphics :: Args GLUT -> ( Behavior (Int, Int) -> FilePath -> FilePath -> Internals GLUT -> (IO () -> IO () -> (Touch GLUT -> TouchPhase -> Coord -> Coord -> IO ()) -> IO ()) -> IO () ) -> IO () initGraphics (GLUTArgs title resPath) init = do _ <- GLUT.getArgsAndInitialize GLUT.initialDisplayMode $= [GLUT.DoubleBuffered] GLUT.createWindow title let width0 = 960 :: Int height0 = 640 :: Int resourceDir = "." (viewportSize, sendViewportSize) <- sync $ newBehavior (width0, height0) GLUT.windowSize $= GLUT.Size (fromIntegral width0) (fromIntegral height0) cache <- newCache let internals = GLUTInternals { inResPath = resPath, inCache = cache, inViewportSize = viewportSize } init viewportSize resourceDir resourceDir internals $ \updateFrame drawFrame touched -> do GLUT.displayCallback $= display updateFrame drawFrame GLUT.addTimerCallback (1000 `div` frameRate) $ repaint let motion (GLUT.Position x y) = do (x', y') <- toScreen viewportSize x y touched () TouchMoved x' y' GLUT.motionCallback $= Just motion GLUT.passiveMotionCallback $= Just motion GLUT.keyboardMouseCallback $= Just (\key keyState mods pos -> do case (key, keyState, pos) of (GLUT.MouseButton GLUT.LeftButton, GLUT.Down, GLUT.Position x y) -> do (x', y') <- toScreen viewportSize x y touched () TouchBegan x' y' (GLUT.MouseButton GLUT.LeftButton, GLUT.Up, GLUT.Position x y) -> do (x', y') <- toScreen viewportSize x y touched () TouchEnded x' y' (GLUT.MouseButton GLUT.MiddleButton, GLUT.Down, GLUT.Position x y) -> exitSuccess _ -> return () ) GLUT.reshapeCallback $= Just (\sz@(Size w h) -> do sync $ sendViewportSize (fromIntegral w, fromIntegral h) viewport $= (Position 0 0, sz) ) GLUT.mainLoop where toScreen :: Behavior (Int, Int) -> GLint -> GLint -> IO (Coord, Coord) toScreen viewportSize x y = do (w, h) <-sync $ sample viewportSize let aspect = fromIntegral w / fromIntegral h sx = 0.001/aspect sy = 0.001 xx = 2 * ((fromIntegral x / fromIntegral w) - 0.5) / sx yy = 2 * (0.5 - (fromIntegral y / fromIntegral h)) / sy return (xx, yy) repaint = do GLUT.postRedisplay Nothing GLUT.addTimerCallback (1000 `div` frameRate) $ repaint display :: IO () -> IO () -> IO () display updateFrame drawFrame = do updateFrame drawFrame GLUT.swapBuffers data SpriteState = SpriteState { ssFont :: Font GLUT, ssInternals :: Internals GLUT, ssBrightness :: GLfloat, ssScreenHt :: Int } data GLUT = GLUT { resKey :: Key, resDraw :: GLfloat -> IO () } appendCache :: Maybe (ReaderT SpriteState IO ()) -> Maybe (ReaderT SpriteState IO ()) -> Maybe (ReaderT SpriteState IO ()) appendCache (Just a) (Just b) = Just (a >> b) appendCache ja@(Just _) _ = ja appendCache _ mb = mb instance Monoid (Sprite GLUT) where mempty = Sprite NullKey ((0,0),(0,0)) Nothing $ return () Sprite ka ra ca a `mappend` Sprite kb rb cb b = Sprite (ka `appendKey` kb) (ra `appendRect` rb) (ca `appendCache` cb) (a >> b) frameRate :: Num a => a frameRate = 30 simulateIOSSpeed = True drawAt :: Key -> (GLfloat -> IO ()) -> Rect -> Sprite GLUT drawAt key action rect@((posX, posY),(sizeX, sizeY)) = Sprite key rect Nothing $ do brightness <- asks ssBrightness liftIO $ preservingMatrix $ do GL.translate $ Vector3 (realToFrac posX) (realToFrac posY) (0 :: GLfloat) GL.scale (realToFrac sizeX) (realToFrac sizeY) (1 :: GLfloat) action brightness glutImage :: Bool -> FilePath -> IO (Drawable GLUT) glutImage background path = do let key = ByteStringKey $ C.pack $ takeFileName path sizeRef <- newIORef Nothing return $ \rect@((posX, posY),(sizeX, sizeY)) -> let cacheIt = Just $ do resPath <- asks (inResPath . ssInternals) cache <- asks (inCache . ssInternals) liftIO $ writeCache cache key $ do --putStrLn $ "loading "++path when simulateIOSSpeed $ liftIO $ threadDelay 600 ti <- loadTexture (resPath </> path) False when background $ writeIORef sizeRef (Just (textureImageSize ti)) to <- createTexture ti let draw' (_, brightness) = do color $ Color4 1 1 1 brightness textureBinding Texture2D $= Just to texture Texture2D $= Enabled textureFilter Texture2D $= ((Linear', Nothing), Linear') drawBB cleanup' = do writeIORef sizeRef Nothing --putStrLn $ "unloading "++path deleteObjectNames [to] return (draw', cleanup') drawIt = do cache <- asks (inCache . ssInternals) brightness <- asks ssBrightness liftIO $ preservingMatrix $ do GL.translate $ Vector3 (realToFrac posX) (realToFrac posY) (0 :: GLfloat) GL.scale (realToFrac sizeX) (realToFrac sizeY) (1 :: GLfloat) mDraw <- readCache cache key case mDraw of Just draw -> draw ((posX, posY), brightness) Nothing -> return () drawBackground = do cache <- asks (inCache . ssInternals) brightness <- asks ssBrightness bVPSize <- asks (inViewportSize . ssInternals) liftIO $ do mSize <- readIORef sizeRef case mSize of Just (wid, hei) -> preservingMatrix $ do (vpWid, vpHei) <- sync $ sample bVPSize let vpAspect = fromIntegral vpWid / fromIntegral vpHei aspect = fromIntegral wid / fromIntegral hei screen = ((0,0),(1000 * vpAspect, 1000)) (_, (bgWid, bgHei)) = coverAspect aspect screen GL.scale (realToFrac bgWid) (realToFrac bgHei) (1 :: GLfloat) mDraw <- readCache cache key case mDraw of Just draw -> draw ((posX, posY), brightness) Nothing -> return () Nothing -> return () in Sprite key rect cacheIt (if background then drawBackground else drawIt) instance Platform GLUT where data Args GLUT = GLUTArgs { gaTitle :: String, gaResPath :: String } data Internals GLUT = GLUTInternals { inResPath :: FilePath, inCache :: Cache (Point, GLfloat), inViewportSize :: Behavior (Int, Int) } data Sprite GLUT = Sprite { spKey :: Key, spRect :: Rect, -- Bounding box spCache :: Maybe (ReaderT SpriteState IO ()), spDraw :: ReaderT SpriteState IO () } data Font GLUT = Font {- { ftFont :: FTGL.Font, ftYCorr :: Float } -} newtype Sound GLUT = Sound (IORef SoundInfo) type Touch GLUT = () engine' args game = glEngine (initGraphics args) game nullDrawable = drawAt NullKey $ \_ -> return () image path = glutImage False path backgroundImage path = ($ ((0,0),(0,0))) <$> glutImage True path -- give it a dummy rectangle sound file = Sound <$> newIORef (SoundPath file) retainSound (GLUTArgs _ resPath) (Sound siRef) = do si <- readIORef siRef si' <- CommonAL.loadSound resPath si writeIORef siRef si' translateSprite v@(vx, vy) (Sprite key rect cache action) = Sprite key (translateRect v rect) cache $ do r <- ask liftIO $ preservingMatrix $ do GL.translate $ Vector3 (realToFrac vx) (realToFrac vy) (0 :: GLfloat) runReaderT action r createFont = undefined "GLUT.createFont is not implemented" --createFont resPath ycorr = Font <$> FTGL.createPolygonFont resPath <*> pure ycorr {- uncachedLabel rect@((posX, posY), _) (Color4 r g b _) text = Sprite (TextKey text) rect Nothing $ do when simulateIOSSpeed $ liftIO $ threadDelay 10000 ft <- asks ssFont internals <- asks ssInternals brightness <- asks ssBrightness liftIO $ preservingMatrix $ do GL.translate $ Vector3 (realToFrac posX) (realToFrac posY) (0 :: GLfloat) glLabel (ftFont ft) (ftYCorr ft) rect (Color4 r g b brightness) text -} key k s = s { spKey = k } keyOf d = spKey $ d ((0,0),(0,0)) setBoundingBox r s = s { spRect = r } cache toMultisample (Sprite key rect@(pos, _) cache1 action) = let cache2 = do ss <- ask let draw brightness = runReaderT (do when simulateIOSSpeed $ liftIO $ threadDelay 600 action ) ss { ssBrightness = brightness } cache = inCache . ssInternals $ ss multisample = if toMultisample then Just $ \w h -> blitFramebuffer (Position 0 0) (Position w h) (Position 0 0) (Position w h) [ColorBuffer'] Nearest else Nothing screenHt = ssScreenHt ss liftIO $ writeCache cache key $ offscreen rect screenHt multisample draw return () draw = do ss <- ask let cache = inCache . ssInternals $ ss liftIO $ do mDraw' <- readCache cache key case mDraw' of Just draw' -> draw' (pos, ssBrightness ss) Nothing -> return () in Sprite key rect (cache1 `appendCache` Just cache2) draw fade brightness (Sprite key rect cache action) = Sprite key rect cache $ do ss <- ask liftIO $ runReaderT action (ss { ssBrightness = ssBrightness ss * realToFrac brightness }) shrink factor (Sprite key rect@((posX,posY),_) cache action) = Sprite key rect cache $ do ss <- ask let px = realToFrac posX py = realToFrac posY liftIO $ preservingMatrix $ do GL.translate $ Vector3 px py (0 :: GLfloat) GL.scale (realToFrac factor) (realToFrac factor) (1 :: GLfloat) GL.translate $ Vector3 (-px) (-py) (0 :: GLfloat) runReaderT action ss preRunSprite internals brightness (Sprite _ _ mCache action) = do (_, screenHt) <- sync $ sample (inViewportSize internals) let ss = SpriteState { ssFont = error "font not defined!", ssInternals = internals, ssBrightness = 1, ssScreenHt = screenHt } case mCache of Just cache -> runReaderT cache ss Nothing -> return () runSprite internals brightness (Sprite _ _ mCache action) flip = do (_, screenHt) <- sync $ sample (inViewportSize internals) let ss = SpriteState { ssFont = error "font not defined!", ssInternals = internals, ssBrightness = 1, ssScreenHt = screenHt } runReaderT action ss when flip $ flipCache (inCache internals) audioThread inn bSounds = do Just device <- CommonAL.alOpenDevice CommonAL.alAudioThread (inResPath inn) device $ (\(b, gain) -> (map (\(Sound si) -> si) <$> b, realToFrac gain)) <$> bSounds -- Rotate the sprite 90 degrees clockwise clockwiseSprite (Sprite key rect cache action) = Sprite key (clockwiseRect rect) cache $ do ss <- ask liftIO $ preservingMatrix $ do GL.rotate 90 normal runReaderT action ss -- Rotate the sprite 90 degrees anti-clockwise anticlockwiseSprite (Sprite key rect cache action) = Sprite key (anticlockwiseRect rect) cache $ do ss <- ask liftIO $ preservingMatrix $ do GL.rotate (-90) normal runReaderT action ss rotateSprite theta (Sprite key rect@((posX, posY), _) cache action) = Sprite key rect cache $ do ss <- ask let px = realToFrac posX py = realToFrac posY liftIO $ preservingMatrix $ do GL.translate $ Vector3 px py (0 :: GLfloat) GL.rotate (realToFrac theta) normal GL.translate $ Vector3 (-px) (-py) (0 :: GLfloat) runReaderT action ss -- Make this sprite invisible, but allow it to cache anything in the invisible sprite invisible (Sprite key rect cache _) = Sprite key rect cache (return ()) launchURL _ url = C.putStrLn $ "launch url: " `mappend` url getSystemLanguage _ = return "en"
the-real-blackh/sodium-2d-game-engine
FRP/Sodium/GameEngine2D/GLUT.hs
bsd-3-clause
15,215
6
30
5,426
4,411
2,256
2,155
293
5
module SMACCMPilot.GCS.Gateway.Queue ( QueueInput , QueueOutput , newQueue , queuePop , queuePush ) where import Control.Monad import Control.Concurrent.STM newtype QueueInput a = QueueInput { unQueueInput :: TQueue a } newtype QueueOutput a = QueueOutput { unQueueOutput :: TQueue a } newQueue :: IO (QueueOutput a, QueueInput a) newQueue = newTQueueIO >>= \q -> return (QueueOutput q, QueueInput q) queuePop :: QueueInput a -> IO a queuePop q = atomically (readTQueue (unQueueInput q)) queuePush :: QueueOutput a -> a -> IO () queuePush q v = void (atomically (writeTQueue (unQueueOutput q) v))
GaloisInc/smaccmpilot-gcs-gateway
SMACCMPilot/GCS/Gateway/Queue.hs
bsd-3-clause
616
0
11
110
211
115
96
16
1
{-# LANGUAGE RankNTypes, GADTs #-} module QueryArrow.RPC.Service where import QueryArrow.Semantics.TypeChecker import QueryArrow.Syntax.Type import QueryArrow.DB.DB import Data.Aeson class RPCService a where startService :: a -> AbstractDatabase MapResultRow FormulaT -> Value -> IO () data AbstractRPCService = forall a . RPCService a => AbstractRPCService a
xu-hao/QueryArrow
QueryArrow-rpc-common/src/QueryArrow/RPC/Service.hs
bsd-3-clause
366
0
11
49
88
49
39
-1
-1
{-# LANGUAGE DeriveGeneric #-} module S1Messages ( S1ApMessage (..) , encode , decode , EpsAttach (..) , S1MessageType (..) , LastMessage (..) ) where import Data.Binary import Data.Binary.Put import Data.Binary.Get import GHC.Generics import qualified Data.ByteString as BS import Identifiers import Control.Applicative import Network.Socket import RrcMessages data S1ApMessage = S1ApInitialUeMessage {enb_Ue_S1Ap_Id :: !Int ,epsAttachType :: EpsAttach ,identity :: !Imsi} | S1ApInitialContextSetupRequest {mme_Ue_S1Ap_Id :: !Int ,enb_Ue_S1Ap_Id :: !Int ,securityKey :: !Int ,epsBearerId :: !String} | S1ApInitialContextSetupResponse {enb_Ue_S1Ap_Id :: !Int ,eRabId :: !String} | EndOfProgramMme deriving (Eq, Generic, Show) instance Binary S1ApMessage where put m = do --Add a message type prefix case m of S1ApInitialUeMessage a b c -> putWord8 5 >> put a >> put b >> put c S1ApInitialContextSetupRequest a b c d -> putWord8 6 >> put a >> put b >> put c >> put d S1ApInitialContextSetupResponse a b -> putWord8 13 >> put a >> put b EndOfProgramMme -> putWord8 17 get = do id<- getWord8 case id of 5 -> S1ApInitialUeMessage <$> get <*> get <*> get 6 -> S1ApInitialContextSetupRequest <$> get <*> get <*> get <*> get 13 -> S1ApInitialContextSetupResponse <$> get <*> get 17 -> return (EndOfProgramMme) --Enumerated Data Types data EpsAttach = EpsAttach | EpsOther deriving (Eq, Generic, Show) instance Binary EpsAttach where put m = do case m of EpsAttach -> putWord8 0 EpsOther -> putWord8 1 get = do id<- getWord8 case id of 0 -> return EpsAttach 1 -> return EpsOther --Type for filtering the events data S1MessageType = S1ApIUeM | S1ApICSRequest | S1ApICSResponse | EndProgMme deriving (Eq, Show) --Specific type for the last message of the program data LastMessage = ReconfigurationFailed (RrcMessage,Socket) | ReconfigurationCompleted (S1ApMessage,Socket,RrcMessage, Socket) deriving (Eq,Show)
Ilydocus/frp-prototype
src/S1Messages.hs
bsd-3-clause
2,375
2
16
754
598
317
281
83
0
{-# LANGUAGE OverloadedStrings, DeriveGeneric, DeriveAnyClass #-} module Lib ( app ) where import GHC.Generics import Data.Monoid (mappend) import Data.Text (Text) import Control.Exception (finally) import Control.Monad (forM_, forever) import Control.Concurrent (MVar, newMVar, modifyMVar_, modifyMVar, readMVar) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy.Encoding as TL import qualified Data.Text.Lazy as TL import Data.Aeson as A import qualified Data.Maybe as M import Data.UUID.V4 as U import Data.UUID as U import qualified Network.WebSockets as WS --type Client = (Text, WS.Connection) data Client = Client { userId :: Text , dId :: Text , connection :: WS.Connection } deriving (Generic) instance Show Client where show (Client uId docId _) = show (docId, uId) type ServerState = [Client] data Event = Event { documentId :: Maybe String , user :: String , event :: String , payload :: Maybe A.Value } deriving (Generic, Show, ToJSON, FromJSON) newServerState :: ServerState newServerState = [] numClients :: ServerState -> Int numClients = length clientExists :: Client -> ServerState -> Bool clientExists client = any ((== userId client) . userId) addClient :: Client -> ServerState -> ServerState addClient client clients = client : clients removeClient :: Client -> ServerState -> ServerState removeClient client = filter ((/= userId client) . userId) broadcast :: Text -> ServerState -> IO () broadcast message clients = do T.putStrLn message forM_ clients $ \(Client { connection = conn }) -> WS.sendTextData conn message getUUID Event { documentId = Just "" } = do uuid <- U.nextRandom return $ Just (toString uuid) getUUID Event { documentId = Just "/" } = do uuid <- U.nextRandom return $ Just (toString uuid) getUUID Event { documentId = Just dId} = do return $ Just dId getUUID Event { documentId = Nothing} = do uuid <- U.nextRandom return $ Just (toString uuid) application :: MVar ServerState -> WS.ServerApp application state pending = do conn <- WS.acceptRequest pending WS.forkPingThread conn 30 msg <- WS.receiveData conn let message = A.decode (TL.encodeUtf8 (TL.fromStrict msg)) :: Maybe Event case message of Just mess -> case event mess of "connect" -> flip finally disconnect $ do uuid <- getUUID mess let client = Client (T.pack $ user mess) (T.pack $ M.fromJust uuid) conn modifyMVar_ state $ \s -> do let s' = addClient client s broadcast (TL.toStrict (TL.decodeUtf8 (A.encode $ Event uuid (user mess) "user-joined" (Just $ A.String (userId client))))) s' return s' talk conn state client _ -> do putStrLn "No message" putStrLn $ show mess where c = M.fromMaybe (A.String "") (payload mess) A.String cli = c -- client = (cli, conn) client = Client (T.pack $ M.fromJust $ documentId mess) (T.pack $ user mess) conn disconnect = do putStrLn "disconnected" putStrLn $ show $ user mess -- Remove client and return new state s <- modifyMVar state $ \s -> let s' = removeClient client s in return (s', s') broadcast ((userId client) `mappend` " disconnected") s Nothing -> putStrLn "No message" talk :: WS.Connection -> MVar ServerState -> Client -> IO () talk conn state Client { userId = user } = forever $ do msg <- WS.receiveData conn let message = A.decode (TL.encodeUtf8 (TL.fromStrict msg)) :: Maybe Event putStrLn "=====" putStrLn $ show message putStrLn "=====" clients <- readMVar state putStrLn $ show clients putStrLn "=====" case message of Just mess -> let maybeId = documentId mess in case maybeId of Just docId -> do putStrLn "=====FILTER=====" putStrLn docId putStrLn $ show (filter (\client -> dId client == T.pack docId) clients) putStrLn "=====FILTER=====" broadcast (TL.toStrict (TL.decodeUtf8 (A.encode $ Event (Just docId) (T.unpack user) (event mess) (payload mess)))) (filter (\client -> dId client == T.pack docId) clients) Nothing -> broadcast (TL.toStrict (TL.decodeUtf8 (A.encode $ Event (documentId mess) (T.unpack user) (event mess) (payload mess)))) clients Nothing -> broadcast msg clients app :: IO () app = do state <- newMVar newServerState WS.runServer "0.0.0.0" 9160 $ application state
ludvigsen/drawable-backend
src/Lib.hs
bsd-3-clause
4,762
10
26
1,295
1,596
812
784
114
3
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE StandaloneDeriving #-} module Calculator.Types where import Calculator.Value import Prelude hiding (exp) -- Typed expression trees. data Exp a where Val :: !Value -> Exp Val Neg :: CNeg x => !(Exp x) -> Exp Neg Bra :: CBra x => !(Exp x) -> Exp Bra Add :: CAdd x y => !(Exp x) -> !(Exp y) -> Exp Add Sub :: CAdd x y => !(Exp x) -> !(Exp y) -> Exp Add Mul :: CMul x y => !(Exp x) -> !(Exp y) -> Exp Mul Div :: CMul x y => !(Exp x) -> !(Exp y) -> Exp Mul class CNeg a -- 'a' can be negated class CBra a -- 'a' can be nested within brackets class CAddL a -- 'a' can be the left operand in an addition class CAddR a -- 'a' can be the right operand in an addition class CMulL a -- 'a' can be the left operand in a multiplication class CMulR a -- 'a' can be the right operand in a multiplication type CAdd a b = (CAddL a, CAddR b) -- 'a' and 'b' can be added together type CMul a b = (CMulL a, CMulR b) -- 'a' can 'b' can be multiplied together data Val; instance CNeg Val; ; instance CAddL Val; instance CAddR Val; instance CMulL Val; instance CMulR Val data Neg; ; instance CBra Neg; instance CAddL Neg; ; ; data Bra; instance CNeg Bra; ; instance CAddL Bra; instance CAddR Bra; instance CMulL Bra; instance CMulR Bra data Add; ; instance CBra Add; instance CAddL Add; ; ; data Mul; ; instance CBra Mul; instance CAddL Mul; instance CAddR Mul; instance CMulL Mul; data TExp = forall a . TExp (Exp a) data AddL = forall a . CAddL a => AddL !(Exp a) data AddR = forall a . CAddR a => AddR !(Exp a) data MulL = forall a . CMulL a => MulL !(Exp a) data MulR = forall a . CMulR a => MulR !(Exp a) addAny (AddL a) (AddR b) = Add a b subAny (AddL a) (AddR b) = Sub a b mulAny (MulL a) (MulR b) = Mul a b divAny (MulL a) (MulR b) = Div a b instance Eq (Exp a) where a == b = toUExp a == toUExp b instance Eq TExp where (TExp a) == (TExp b) = toUExp a == toUExp b deriving instance Show (Exp a) instance Show TExp where show (TExp e) = show e -- Untyped expression trees. data UExp = UVal !Value | UNeg !UExp | UAdd !UExp !UExp | USub !UExp !UExp | UMul !UExp !UExp | UDiv !UExp !UExp deriving (Eq, Show) {-| Converts expression trees from typed to untyped. -} toUExp :: Exp a -> UExp toUExp = \case Val a -> UVal a Neg a -> UNeg (toUExp a) Bra a -> toUExp a Add a b -> UAdd (toUExp a) (toUExp b) Sub a b -> USub (toUExp a) (toUExp b) Mul a b -> UMul (toUExp a) (toUExp b) Div a b -> UDiv (toUExp a) (toUExp b) {-| Converts expression trees from untyped to typed. -} toTExp :: UExp -> TExp toTExp = \case UVal a -> TExp $ Val a UNeg a -> TExp $ neg a UAdd a b -> TExp $ add a b USub a b -> TExp $ sub a b UMul a b -> TExp $ mul a b UDiv a b -> TExp $ div a b where neg = \case UVal a -> Neg $ Val a UNeg a -> Neg $ Bra $ neg a UAdd a b -> Neg $ Bra $ add a b USub a b -> Neg $ Bra $ sub a b UMul a b -> Neg $ Bra $ mul a b UDiv a b -> Neg $ Bra $ div a b add a b = addAny (addL a) (addR b) sub a b = subAny (addL a) (addR b) mul a b = mulAny (mulL a) (mulR b) div a b = divAny (mulL a) (mulR b) addL = \case UVal a -> AddL $ Val a UNeg a -> AddL $ neg a UAdd a b -> AddL $ add a b USub a b -> AddL $ sub a b UMul a b -> AddL $ mul a b UDiv a b -> AddL $ div a b addR = \case UVal a -> AddR $ Val a UNeg a -> AddR $ Bra $ neg a UAdd a b -> AddR $ Bra $ add a b USub a b -> AddR $ Bra $ sub a b UMul a b -> AddR $ mul a b UDiv a b -> AddR $ div a b mulL = \case UVal a -> MulL $ Val a UNeg a -> MulL $ Bra $ neg a UAdd a b -> MulL $ Bra $ add a b USub a b -> MulL $ Bra $ sub a b UMul a b -> MulL $ mul a b UDiv a b -> MulL $ div a b mulR = \case UVal a -> MulR $ Val a UNeg a -> MulR $ Bra $ neg a UAdd a b -> MulR $ Bra $ add a b USub a b -> MulR $ Bra $ sub a b UMul a b -> MulR $ Bra $ mul a b UDiv a b -> MulR $ Bra $ div a b
jonathanknowles/haskell-calculator
source/library/Calculator/Types.hs
bsd-3-clause
4,765
7
12
1,771
2,014
971
1,043
-1
-1
{-# OPTIONS_GHC -Wall #-} module System.Console.ShSh.Builtins.Util ( orDash, readFileOrStdin, readFileOrStdinWithFilename, readFilesOrStdin, readFilesOrStdinWithFilename ) where import System.Console.ShSh.Shell ( ShellT ) import System.Console.ShSh.IO ( iIsOpen, iGetContents ) import Control.Monad ( unless ) import Control.Monad.Trans ( liftIO ) import System.Directory ( doesFileExist, doesDirectoryExist ) orDash :: [String] -> [String] orDash [] = ["-"] orDash fs = fs readFileOrStdin :: String -> ShellT e String readFileOrStdin "-" = do open <- iIsOpen if open then iGetContents else return "" readFileOrStdin f = do exists <- liftIO $ doesFileExist f unless exists $ noExist liftIO $ readFile f where noExist = do isdir <- liftIO $ doesDirectoryExist f fail $ if isdir then die "Is a directory" else die "No such file or directory" die msg = fail $ f ++ ": " ++ msg readFileOrStdinWithFilename :: String -> ShellT e (String,String) readFileOrStdinWithFilename f = (,) (fname f) `fmap` readFileOrStdin f where fname "-" = "(standard input)" fname fn = fn readFilesOrStdin :: [String] -> ShellT e [String] readFilesOrStdin = mapM readFileOrStdin . orDash readFilesOrStdinWithFilename :: [String] -> ShellT e [(String,String)] readFilesOrStdinWithFilename = mapM readFileOrStdinWithFilename . orDash
shicks/shsh
System/Console/ShSh/Builtins/Util.hs
bsd-3-clause
1,686
0
11
563
408
220
188
32
3
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances, OverlappingInstances, TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts #-} {-# LANGUAGE PatternGuards, RecordWildCards, NamedFieldPuns #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} module Narradar.Types.Problem ( -- module MuTerm.Framework.Problem, module Narradar.Types.Problem, module Narradar.Constraints.ICap, module Narradar.Constraints.UsableRules) where import Control.Applicative import Control.Arrow (first, second) import Control.Exception (assert) import Control.Monad.List import Control.Monad.State import Data.Array as A import Data.Graph as G (Graph, edges, buildG) import Data.Foldable as F (Foldable(..), toList) import Data.Maybe (isJust, isNothing) import Data.Monoid import qualified Data.Map as Map import qualified Data.Set as Set import Data.Set (Set) import Data.Strict.Tuple ((:!:), Pair(..)) import Data.Traversable as T import qualified Language.Prolog.Syntax as Prolog hiding (ident) import Text.XHtml as H hiding ((!), rules, text) import qualified Text.XHtml as H import Prelude as P hiding (mapM, pi, sum) import qualified Prelude as P import MuTerm.Framework.Problem import MuTerm.Framework.Proof import Narradar.Types.ArgumentFiltering (AF_, ApplyAF(..)) import qualified Narradar.Types.ArgumentFiltering as AF import Narradar.Types.DPIdentifiers import Narradar.Types.TRS import Narradar.Types.Term hiding ((!)) import Narradar.Framework (FrameworkExtension(..)) import Narradar.Framework.Ppr as Ppr import Narradar.Utils import Narradar.Constraints.ICap import Narradar.Constraints.Unify import Narradar.Constraints.UsableRules import Narradar.Types.Var import Data.Term.Rules -- ------------------------- -- Constructing DP problems -- ------------------------- type NarradarProblem typ t = Problem typ (NarradarTRS t Var) type NProblem typ id = NarradarProblem typ (TermF id) mkNewProblem :: ( HasRules (TermF id) Var trs , Ord id, Pretty (DPIdentifier id), Pretty typ, GetPairs typ , Traversable (Problem typ) , MkDPProblem typ (NTRS (DPIdentifier id)) , NCap typ (DPIdentifier id) , NUsableRules typ (DPIdentifier id) ) => typ -> trs -> NProblem typ (DPIdentifier id) mkNewProblem typ trs = mkDPProblem typ (tRS rr') (tRS $ getPairs typ rr') where rr' = mapTermSymbols IdFunction <$$> rules trs -- --------------------------- -- Computing Dependency Pairs -- --------------------------- class GetPairs typ where getPairs :: ( HasRules t v trs, HasSignature trs, t ~ f (DPIdentifier id), Ord id , Functor t, Foldable t, MapId f, HasId t , SignatureId trs ~ TermId t) => typ -> trs -> [Rule t v] getPairsDefault typ trs = [ markDP l :-> markDP rp | l :-> r <- rules trs, rp <- collect (isRootDefined trs) r] -- I know, I'm gonna burn in hell ... instance (FrameworkExtension ext, GetPairs base) => GetPairs (ext base) where getPairs typ = getPairs (getBaseFramework typ) -- ---------------------------------------- -- Computing the estimated Dependency Graph -- ---------------------------------------- getEDG :: (Ord v, Enum v ,HasId t, Unify t ,Ord (Term t v) ,Pretty (Term t v), Pretty typ, Pretty v ,MkDPProblem typ (NarradarTRS t v) ,Traversable (Problem typ) ,ICap t v (typ, NarradarTRS t v) ,IUsableRules t v typ (NarradarTRS t v) ) => Problem typ (NarradarTRS t v) -> G.Graph getEDG p@(getP -> DPTRS _ _ gr _ _) = gr getEDG p = filterSEDG p $ getdirectEDG p getdirectEDG :: (Traversable (Problem typ) ,IsDPProblem typ, Enum v, Ord v, Unify t ,ICap t v (typ, NarradarTRS t v) ,Pretty v, Pretty (Term t v), Pretty typ ) => Problem typ (NarradarTRS t v) -> G.Graph getdirectEDG p@(getP -> DPTRS dps _ _ (unif :!: _) _) = assert (isValidUnif p) $ G.buildG (A.bounds dps) [ xy | (xy, Just _) <- A.assocs unif] getDirectEDG p = G.buildG (0, length dps - 1) edges where dps = rules $ getP p edges = runIcap p $ runListT $ do (x, _ :-> r) <- liftL $ zip [0..] dps (y, l :-> _) <- liftL $ zip [0..] dps r' <- lift(getFresh r >>= icap p) guard (unifies l r') return (x,y) liftL = ListT . return filterSEDG :: (Ord v, Enum v ,HasId t, Unify t ,Ord (Term t v) ,MkDPProblem typ (NarradarTRS t v) ,Traversable (Problem typ) ,ICap t v (typ, NarradarTRS t v) ,IUsableRules t v typ (NarradarTRS t v) ) => Problem typ (NarradarTRS t v) -> G.Graph -> G.Graph filterSEDG p gr | isCollapsing (getP p) = gr filterSEDG (getP -> dptrs@DPTRS{}) gr = G.buildG (A.bounds gr) [ (i,j) | (i,j) <- G.edges gr , isJust (dpUnifyInv dptrs j i)] filterSEDG p gr = G.buildG (bounds gr) edges where typ = getFramework p dps = A.listArray (bounds gr) (rules $ getP p) edges = runIcap p $ runListT $ do trs' <- lift $ getFresh (rules $ getR p) let p' = setR (tRS trs') p (i, j) <- liftL (G.edges gr) let _ :-> r = safeAt "filterSEDG" dps i l :-> _ = safeAt "filterSEDG" dps j (getR -> trs_u) <- iUsableRulesMp p' [r] let trs_inv = swapRule <$> rules trs_u l' <- lift (icap (typ, trs_inv) l) guard (unifies l' r) return (i,j) liftL = ListT . return emptyArray :: (Num i, Ix i) => Array i e emptyArray = A.listArray (0,-1) [] -- ---------------- -- Output -- ---------------- instance (IsDPProblem p, Pretty p, Pretty trs) => Pretty (Problem p trs) where pPrint p = pPrint (getFramework p) <+> text "Problem" $$ text "TRS:" <+> pPrint (getR p) $$ text "DPS:" <+> pPrint (getP p) instance (IsDPProblem typ, HTML typ, HTMLClass typ, HasRules t v trs, Pretty (Term t v) ) => HTML (Problem typ trs) where toHtml p | null $ rules (getP p) = H.table H.! [htmlClass typ] << ( H.td H.! [H.theclass "problem"] << H.bold << typ </> H.td H.! [H.theclass "TRS_TITLE" ] << "Rules"</> aboves' (rules $ getR p) </> "Dependency Pairs: none") | otherwise = H.table H.! [htmlClass typ] << ( H.td H.! [H.theclass "problem"] << H.bold << typ </> H.td H.! [H.theclass "TRS_TITLE" ] << "Rules" </> aboves' (rules $ getR p) </> H.td H.! [H.theclass "DPS" ] << "Dependency Pairs" </> aboves' (rules $ getP p)) where typ = getFramework p instance (Pretty (Term t v)) => HTMLTABLE (Rule t v) where cell (lhs :-> rhs ) = td H.! [theclass "lhs"] << show (pPrint lhs) <-> td H.! [theclass "arrow"] << (" " +++ H.primHtmlChar "#x2192" +++ " ") <-> td H.! [theclass "rhs"] << show (pPrint rhs) instance HTMLTABLE String where cell = cell . toHtml aboves' [] = cell noHtml aboves' xx = aboves xx class HTMLClass a where htmlClass :: a -> HtmlAttr -- ------------------- -- Narradar instances -- ------------------- instance (Ord v, ExtraVars v trs, IsDPProblem p) => ExtraVars v (Problem p trs) where extraVars p = extraVars (getP p) `mappend` extraVars (getR p) instance (MkDPProblem typ (NarradarTRS t v) ,Unify t ,ApplyAF (Term t v) ,Enum v, Ord v ,IUsableRules t v typ (NarradarTRS t v) ,ICap t v (typ, NarradarTRS t v) ,AFId (Term t v) ~ AFId (NarradarTRS t v) ,Pretty (t(Term t v)), Pretty v ) => ApplyAF (Problem typ (NarradarTRS t v)) where type AFId (Problem typ (NarradarTRS t v)) = AFId (Term t v) apply af p@(getP -> dps@DPTRS{})= mkDPProblem typ trs' dps' where typ = getFramework p trs' = apply af (getR p) dps' = dpTRS typ (trs' `asTypeOf` getR p) (apply af dps) {- instance (ApplyAF trs, IsDPProblem p) => ApplyAF (Problem p trs) where type AFId (Problem p trs) = AFId trs apply af = fmap (apply af) -} -- ------------------------------ -- Data.Term framework instances -- ------------------------------ getSignatureProblem p = getSignature (getR p) `mappend` getSignature (getP p) instance (Ord v, IsDPProblem typ, HasRules t v trs, Foldable (Problem typ)) => HasRules t v (Problem typ trs) where rules = foldMap rules instance (Ord v, GetFresh t v trs, Traversable (Problem typ)) => GetFresh t v (Problem typ trs) where getFreshM = getFreshMdefault instance (Ord v, GetVars v trs, Traversable (Problem typ)) => GetVars v (Problem typ trs) where getVars = foldMap getVars instance (HasSignature trs, IsDPProblem typ) => HasSignature (Problem typ trs) where type SignatureId (Problem typ trs) = SignatureId trs getSignature p = getSignature (getR p) `mappend` getSignature (getP p) -- ------------------------------------ -- Dealing with the pairs in a problem -- ------------------------------------ expandDPair :: ( v ~ Var , HasId t, Unify t, Ord (Term t v) , Traversable (Problem typ) , MkDPProblem typ (NarradarTRS t v) , ICap t v (typ, NarradarTRS t v) , IUsableRules t v typ (NarradarTRS t v) , Pretty (Term t v), Pretty typ ) => Problem typ (NarradarTRS t v) -> Int -> [Rule t v] -> Problem typ (NarradarTRS t v) expandDPair p@(getP -> DPTRS dps rr gr (unif :!: unifInv) _) i (filter (`notElem` elems dps) . snub -> newdps) = runIcap (rules p ++ newdps) $ do let dps' = dps1 ++ dps2 ++ newdps l_dps' = l_dps + l_newdps a_dps' = A.listArray (0,l_dps') dps' mkUnif' arr arr' = A.array ((0,0), (l_dps', l_dps')) ([((adjust x,adjust y), sigma) | ((x,y), sigma) <- assocs arr , x /= i, y /= i] ++ concat [ [(in1, safeAt "expandPair" arr' in1), (in2, safeAt "expandPair" arr' in2)] | j <- new_nodes, k <- [0..l_dps'] , let in1 = (j,k), let in2 = (k,j)]) adjust x = if x < i then x else x-1 unif_new :!: unifInv_new <- computeDPUnifiers (getFramework p) (getR p) (listTRS dps') -- The use of listTRS here is important ^^ let unif' = mkUnif' unif unif_new unifInv' = mkUnif' unifInv unifInv_new dptrs' = dpTRS' a_dps' rr (unif' :!: unifInv') -- dptrs_new= dpTRS' a_dps' (unif_new :!: unifInv_new) let res = setP dptrs' p assert (isValidUnif p) $ assert (isValidUnif res) $ return res where (dps1,_:dps2) = splitAt i (elems dps) new_nodes= [l_dps .. l_dps + l_newdps] l_dps = assert (fst (bounds dps) == 0) $ snd (bounds dps) l_newdps = length newdps - 1 expandDPair p i newdps = setP (tRS dps') p where dps' = dps1 ++ dps2 ++ newdps (dps1,_:dps2) = splitAt i (rules $ getP p) class MkDPProblem typ trs => InsertDPairs typ trs where insertDPairs :: Problem typ trs -> trs -> Problem typ trs insertDPairsDefault p newPairs = setP dps' p where dps' = assert (getR p == rulesUsed (getP p)) $ insertDPairs' (getFramework p) (getP p) (rules newPairs) insertDPairs' :: (trs ~ NTRS id ,MkDPProblem framework trs, Pretty framework, Traversable (Problem framework) ,Pretty id, Eq id ,NUsableRules framework id ,NCap framework id ) => framework -> NTRS id -> [Rule (TermF id) Var] -> NTRS id insertDPairs' framework p@(DPTRS dps rr _ (unif :!: unifInv) sig) newPairs = runIcap (getVars p `mappend` getVars newPairs) $ do let (zero,l_dps) = bounds dps l_newPairs = length $ rules newPairs dps' = A.elems dps ++ rules newPairs l_dps' = l_dps + l_newPairs a_dps' = A.listArray (0,l_dps') dps' new_nodes = [l_dps + 1 .. l_dps'] (!) = safeAt "insertDPairsDefault" mkUnif arr arr' = A.array ((zero,zero), (l_dps', l_dps')) (assocs arr ++ concat [ [(in1, arr' ! in1), (in2, arr' ! in2)] | j <- new_nodes, k <- [zero..l_dps'] , let in1 = (j,k), let in2 = (k,j)]) unif_new :!: unifInv_new <- computeDPUnifiers framework rr (listTRS dps') -- The use of listTRS here is important ^^ let unif' = mkUnif unif unif_new unifInv' = mkUnif unifInv unifInv_new dptrs' = dpTRS' a_dps' rr (unif' :!: unifInv') return dptrs' -- ------------- -- Sanity Checks -- ------------- isValidUnif :: ( p ~ Problem typ , Ord v, Enum v, Unify t , Traversable p, IsDPProblem typ, Pretty typ , ICap t v (typ, NarradarTRS t v) , Pretty v, Pretty (Term t v) ) => p (NarradarTRS t v) -> Bool isValidUnif p@(getP -> DPTRS dps _ _ (unif :!: _) _) | valid = True | otherwise = pprTrace (text "Warning: invalid set of unifiers" $$ text "Problem type:" <+> pPrint (getFramework p) $$ text "DPS:" <+> pPrint (elems dps) $$ text "Unifiers:" <+> pPrint unif $+$ Ppr.empty $+$ text "Computed:" <+> pPrint unif' $+$ Ppr.empty $+$ text "Expected:" <+> pPrint (fmap (\b -> if b then "Y" else "N") validUnif) ) valid where liftL = ListT . return l = length (rules $ getP p) - 1 unif' = runIcap (getP p) (getFresh (getR p) >>= \rr' -> computeDirectUnifiers (getFramework p,rr') (getP p)) validUnif = array ( (0,0), (l,l)) $ runIcap p $ runListT $ do (x, _ :-> r) <- liftL $ A.assocs dps (y, l :-> _) <- liftL $ A.assocs dps r' <- getFresh r >>= icap p -- pprTrace (text "unify" <+> pPrint l <+> pPrint r') (return ()) return ((x,y),unifies l r') valid = and $ zipWith (\subst unifies -> if unifies then isJust subst else isNothing subst) (elems unif) (elems validUnif) isValidUnif _ = True noDuplicateEdges gr = Set.size(Set.fromList (edges gr)) == length (edges gr)
pepeiborra/narradar
src/Narradar/Types/Problem.hs
bsd-3-clause
14,725
93
23
4,362
5,233
2,749
2,484
274
3
import qualified Data.Map as M import qualified Data.List as L digit2Word :: M.Map Char String digit2Word = M.fromList [('1', "one"), ('2' ,"two"), ('3', "three"), ('4', "four"), ('5', "five"), ('6', "six"), ('7', "seven"), ('8', "eight"), ('9', "nine")] getVal :: Maybe a -> a getVal Nothing = error "Nothing founded" getVal (Just a) = a fullWord :: String -> String fullWord ss = L.intercalate "-" $ map (\x -> getVal $ M.lookup x digit2Word) ss main :: IO () main = do putStrLn $ fullWord "175" putStrLn $ fullWord "1723"
m00nlight/99-problems
haskell/p-95.hs
bsd-3-clause
587
1
11
150
250
137
113
16
1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/Map/Strict.hs" #-} {-# LANGUAGE CPP #-} {-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Map.Strict -- Copyright : (c) Daan Leijen 2002 -- (c) Andriy Palamarchuk 2008 -- License : BSD-style -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- An efficient implementation of ordered maps from keys to values -- (dictionaries). -- -- API of this module is strict in both the keys and the values. -- If you need value-lazy maps, use "Data.Map.Lazy" instead. -- The 'Map' type is shared between the lazy and strict modules, -- meaning that the same 'Map' value can be passed to functions in -- both modules (although that is rarely needed). -- -- These modules are intended to be imported qualified, to avoid name -- clashes with Prelude functions, e.g. -- -- > import qualified Data.Map.Strict as Map -- -- The implementation of 'Map' is based on /size balanced/ binary trees (or -- trees of /bounded balance/) as described by: -- -- * Stephen Adams, \"/Efficient sets: a balancing act/\", -- Journal of Functional Programming 3(4):553-562, October 1993, -- <http://www.swiss.ai.mit.edu/~adams/BB/>. -- -- * J. Nievergelt and E.M. Reingold, -- \"/Binary search trees of bounded balance/\", -- SIAM journal of computing 2(1), March 1973. -- -- Note that the implementation is /left-biased/ -- the elements of a -- first argument are always preferred to the second, for example in -- 'union' or 'insert'. -- -- /Warning/: The size of the map must not exceed @maxBound::Int@. Violation of -- this condition is not detected and if the size limit is exceeded, its -- behaviour is undefined. -- -- Operation comments contain the operation time complexity in -- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>). -- -- Be aware that the 'Functor', 'Traversable' and 'Data' instances -- are the same as for the "Data.Map.Lazy" module, so if they are used -- on strict maps, the resulting maps will be lazy. ----------------------------------------------------------------------------- -- See the notes at the beginning of Data.Map.Base. module Data.Map.Strict ( -- * Strictness properties -- $strictness -- * Map type Map -- instance Eq,Show,Read -- * Operators , (!), (\\) -- * Query , null , size , member , notMember , lookup , findWithDefault , lookupLT , lookupGT , lookupLE , lookupGE -- * Construction , empty , singleton -- ** Insertion , insert , insertWith , insertWithKey , insertLookupWithKey -- ** Delete\/Update , delete , adjust , adjustWithKey , update , updateWithKey , updateLookupWithKey , alter -- * Combine -- ** Union , union , unionWith , unionWithKey , unions , unionsWith -- ** Difference , difference , differenceWith , differenceWithKey -- ** Intersection , intersection , intersectionWith , intersectionWithKey -- ** Universal combining function , mergeWithKey -- * Traversal -- ** Map , map , mapWithKey , traverseWithKey , mapAccum , mapAccumWithKey , mapAccumRWithKey , mapKeys , mapKeysWith , mapKeysMonotonic -- * Folds , foldr , foldl , foldrWithKey , foldlWithKey , foldMapWithKey -- ** Strict folds , foldr' , foldl' , foldrWithKey' , foldlWithKey' -- * Conversion , elems , keys , assocs , keysSet , fromSet -- ** Lists , toList , fromList , fromListWith , fromListWithKey -- ** Ordered lists , toAscList , toDescList , fromAscList , fromAscListWith , fromAscListWithKey , fromDistinctAscList -- * Filter , filter , filterWithKey , partition , partitionWithKey , mapMaybe , mapMaybeWithKey , mapEither , mapEitherWithKey , split , splitLookup , splitRoot -- * Submap , isSubmapOf, isSubmapOfBy , isProperSubmapOf, isProperSubmapOfBy -- * Indexed , lookupIndex , findIndex , elemAt , updateAt , deleteAt -- * Min\/Max , findMin , findMax , deleteMin , deleteMax , deleteFindMin , deleteFindMax , updateMin , updateMax , updateMinWithKey , updateMaxWithKey , minView , maxView , minViewWithKey , maxViewWithKey -- * Debugging , showTree , showTreeWith , valid ) where import Prelude hiding (lookup,map,filter,foldr,foldl,null) import Data.Map.Base hiding ( findWithDefault , singleton , insert , insertWith , insertWithKey , insertLookupWithKey , adjust , adjustWithKey , update , updateWithKey , updateLookupWithKey , alter , unionWith , unionWithKey , unionsWith , differenceWith , differenceWithKey , intersectionWith , intersectionWithKey , mergeWithKey , map , mapWithKey , mapAccum , mapAccumWithKey , mapAccumRWithKey , mapKeysWith , fromSet , fromList , fromListWith , fromListWithKey , fromAscList , fromAscListWith , fromAscListWithKey , fromDistinctAscList , mapMaybe , mapMaybeWithKey , mapEither , mapEitherWithKey , updateAt , updateMin , updateMax , updateMinWithKey , updateMaxWithKey ) import qualified Data.Set.Base as Set import Data.Utils.StrictFold import Data.Utils.StrictPair import Data.Bits (shiftL, shiftR) -- $strictness -- -- This module satisfies the following strictness properties: -- -- 1. Key arguments are evaluated to WHNF; -- -- 2. Keys and values are evaluated to WHNF before they are stored in -- the map. -- -- Here's an example illustrating the first property: -- -- > delete undefined m == undefined -- -- Here are some examples that illustrate the second property: -- -- > map (\ v -> undefined) m == undefined -- m is not empty -- > mapKeys (\ k -> undefined) m == undefined -- m is not empty {-------------------------------------------------------------------- Query --------------------------------------------------------------------} -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns -- the value at key @k@ or returns default value @def@ -- when the key is not in the map. -- -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x' -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a' -- See Map.Base.Note: Local 'go' functions and capturing findWithDefault :: Ord k => a -> k -> Map k a -> a findWithDefault def k = k `seq` go where go Tip = def go (Bin _ kx x l r) = case compare k kx of LT -> go l GT -> go r EQ -> x {-# INLINABLE findWithDefault #-} {-------------------------------------------------------------------- Construction --------------------------------------------------------------------} -- | /O(1)/. A map with a single element. -- -- > singleton 1 'a' == fromList [(1, 'a')] -- > size (singleton 1 'a') == 1 singleton :: k -> a -> Map k a singleton k x = x `seq` Bin 1 k x Tip Tip {-# INLINE singleton #-} {-------------------------------------------------------------------- Insertion --------------------------------------------------------------------} -- | /O(log n)/. Insert a new key and value in the map. -- If the key is already present in the map, the associated value is -- replaced with the supplied value. 'insert' is equivalent to -- @'insertWith' 'const'@. -- -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')] -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')] -- > insert 5 'x' empty == singleton 5 'x' -- See Map.Base.Note: Type of local 'go' function insert :: Ord k => k -> a -> Map k a -> Map k a insert = go where go :: Ord k => k -> a -> Map k a -> Map k a go arg _ _ | arg `seq` False = undefined go _ arg _ | arg `seq` False = undefined go kx x Tip = singleton kx x go kx x (Bin sz ky y l r) = case compare kx ky of LT -> balanceL ky y (go kx x l) r GT -> balanceR ky y l (go kx x r) EQ -> Bin sz kx x l r {-# INLINABLE insert #-} -- | /O(log n)/. Insert with a function, combining new value and old value. -- @'insertWith' f key value mp@ -- will insert the pair (key, value) into @mp@ if key does -- not exist in the map. If the key does exist, the function will -- insert the pair @(key, f new_value old_value)@. -- -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")] -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx" insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a insertWith f = insertWithKey (\_ x' y' -> f x' y') {-# INLINABLE insertWith #-} -- | /O(log n)/. Insert with a function, combining key, new value and old value. -- @'insertWithKey' f key value mp@ -- will insert the pair (key, value) into @mp@ if key does -- not exist in the map. If the key does exist, the function will -- insert the pair @(key,f key new_value old_value)@. -- Note that the key passed to f is the same key passed to 'insertWithKey'. -- -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")] -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx" -- See Map.Base.Note: Type of local 'go' function insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a insertWithKey = go where go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a go _ arg _ _ | arg `seq` False = undefined go _ kx x Tip = singleton kx x go f kx x (Bin sy ky y l r) = case compare kx ky of LT -> balanceL ky y (go f kx x l) r GT -> balanceR ky y l (go f kx x r) EQ -> let x' = f kx x y in x' `seq` Bin sy kx x' l r {-# INLINABLE insertWithKey #-} -- | /O(log n)/. Combines insert operation with old value retrieval. -- The expression (@'insertLookupWithKey' f k x map@) -- is a pair where the first element is equal to (@'lookup' k map@) -- and the second element equal to (@'insertWithKey' f k x map@). -- -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")]) -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")]) -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx") -- -- This is how to define @insertLookup@ using @insertLookupWithKey@: -- -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")]) -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")]) -- See Map.Base.Note: Type of local 'go' function insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a, Map k a) insertLookupWithKey f0 kx0 x0 t0 = toPair $ go f0 kx0 x0 t0 where go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> StrictPair (Maybe a) (Map k a) go _ arg _ _ | arg `seq` False = undefined go _ kx x Tip = Nothing :*: singleton kx x go f kx x (Bin sy ky y l r) = case compare kx ky of LT -> let (found :*: l') = go f kx x l in found :*: balanceL ky y l' r GT -> let (found :*: r') = go f kx x r in found :*: balanceR ky y l r' EQ -> let x' = f kx x y in x' `seq` (Just y :*: Bin sy kx x' l r) {-# INLINABLE insertLookupWithKey #-} {-------------------------------------------------------------------- Deletion --------------------------------------------------------------------} -- | /O(log n)/. Update a value at a specific key with the result of the provided function. -- When the key is not -- a member of the map, the original map is returned. -- -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > adjust ("new " ++) 7 empty == empty adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a adjust f = adjustWithKey (\_ x -> f x) {-# INLINABLE adjust #-} -- | /O(log n)/. Adjust a value at a specific key. When the key is not -- a member of the map, the original map is returned. -- -- > let f key x = (show key) ++ ":new " ++ x -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > adjustWithKey f 7 empty == empty adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x')) {-# INLINABLE adjustWithKey #-} -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@ -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@. -- -- > let f x = if x == "a" then Just "new a" else Nothing -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a update f = updateWithKey (\_ x -> f x) {-# INLINABLE update #-} -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing', -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound -- to the new value @y@. -- -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" -- See Map.Base.Note: Type of local 'go' function updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a updateWithKey = go where go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a go _ arg _ | arg `seq` False = undefined go _ _ Tip = Tip go f k(Bin sx kx x l r) = case compare k kx of LT -> balanceR kx x (go f k l) r GT -> balanceL kx x l (go f k r) EQ -> case f kx x of Just x' -> x' `seq` Bin sx kx x' l r Nothing -> glue l r {-# INLINABLE updateWithKey #-} -- | /O(log n)/. Lookup and update. See also 'updateWithKey'. -- The function returns changed value, if it is updated. -- Returns the original key value if the map entry is deleted. -- -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")]) -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")]) -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a") -- See Map.Base.Note: Type of local 'go' function updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a) updateLookupWithKey f0 k0 t0 = toPair $ go f0 k0 t0 where go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> StrictPair (Maybe a) (Map k a) go _ arg _ | arg `seq` False = undefined go _ _ Tip = (Nothing :*: Tip) go f k (Bin sx kx x l r) = case compare k kx of LT -> let (found :*: l') = go f k l in found :*: balanceR kx x l' r GT -> let (found :*: r') = go f k r in found :*: balanceL kx x l r' EQ -> case f kx x of Just x' -> x' `seq` (Just x' :*: Bin sx kx x' l r) Nothing -> (Just x :*: glue l r) {-# INLINABLE updateLookupWithKey #-} -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof. -- 'alter' can be used to insert, delete, or update a value in a 'Map'. -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@. -- -- > let f _ = Nothing -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" -- > -- > let f _ = Just "c" -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")] -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")] -- See Map.Base.Note: Type of local 'go' function alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a alter = go where go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a go _ arg _ | arg `seq` False = undefined go f k Tip = case f Nothing of Nothing -> Tip Just x -> singleton k x go f k (Bin sx kx x l r) = case compare k kx of LT -> balance kx x (go f k l) r GT -> balance kx x l (go f k r) EQ -> case f (Just x) of Just x' -> x' `seq` Bin sx kx x' l r Nothing -> glue l r {-# INLINABLE alter #-} {-------------------------------------------------------------------- Indexing --------------------------------------------------------------------} -- | /O(log n)/. Update the element at /index/. Calls 'error' when an -- invalid index is used. -- -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")] -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")] -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a updateAt f i t = i `seq` case t of Tip -> error "Map.updateAt: index out of range" Bin sx kx x l r -> case compare i sizeL of LT -> balanceR kx x (updateAt f i l) r GT -> balanceL kx x l (updateAt f (i-sizeL-1) r) EQ -> case f kx x of Just x' -> x' `seq` Bin sx kx x' l r Nothing -> glue l r where sizeL = size l {-------------------------------------------------------------------- Minimal, Maximal --------------------------------------------------------------------} -- | /O(log n)/. Update the value at the minimal key. -- -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")] -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateMin :: (a -> Maybe a) -> Map k a -> Map k a updateMin f m = updateMinWithKey (\_ x -> f x) m -- | /O(log n)/. Update the value at the maximal key. -- -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")] -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" updateMax :: (a -> Maybe a) -> Map k a -> Map k a updateMax f m = updateMaxWithKey (\_ x -> f x) m -- | /O(log n)/. Update the value at the minimal key. -- -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")] -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a updateMinWithKey _ Tip = Tip updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of Nothing -> r Just x' -> x' `seq` Bin sx kx x' Tip r updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r -- | /O(log n)/. Update the value at the maximal key. -- -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")] -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a updateMaxWithKey _ Tip = Tip updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of Nothing -> l Just x' -> x' `seq` Bin sx kx x' l Tip updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r) {-------------------------------------------------------------------- Union. --------------------------------------------------------------------} -- | The union of a list of maps, with a combining operation: -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@). -- -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")] unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a unionsWith f ts = foldlStrict (unionWith f) empty ts {-# INLINABLE unionsWith #-} {-------------------------------------------------------------------- Union with a combining function --------------------------------------------------------------------} -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm. -- -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")] unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a unionWith f m1 m2 = unionWithKey (\_ x y -> f x y) m1 m2 {-# INLINABLE unionWith #-} -- | /O(n+m)/. -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm. -- -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")] unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2 {-# INLINABLE unionWithKey #-} {-------------------------------------------------------------------- Difference --------------------------------------------------------------------} -- | /O(n+m)/. Difference with a combining function. -- When two equal keys are -- encountered, the combining function is applied to the values of these keys. -- If it returns 'Nothing', the element is discarded (proper set difference). If -- it returns (@'Just' y@), the element is updated with a new value @y@. -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/. -- -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")]) -- > == singleton 3 "b:B" differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a differenceWith f m1 m2 = differenceWithKey (\_ x y -> f x y) m1 m2 {-# INLINABLE differenceWith #-} -- | /O(n+m)/. Difference with a combining function. When two equal keys are -- encountered, the combining function is applied to the key and both values. -- If it returns 'Nothing', the element is discarded (proper set difference). If -- it returns (@'Just' y@), the element is updated with a new value @y@. -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/. -- -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")]) -- > == singleton 3 "3:b|B" differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2 {-# INLINABLE differenceWithKey #-} {-------------------------------------------------------------------- Intersection --------------------------------------------------------------------} -- | /O(n+m)/. Intersection with a combining function. The implementation uses -- an efficient /hedge/ algorithm comparable with /hedge-union/. -- -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA" intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c intersectionWith f m1 m2 = intersectionWithKey (\_ x y -> f x y) m1 m2 {-# INLINABLE intersectionWith #-} -- | /O(n+m)/. Intersection with a combining function. The implementation uses -- an efficient /hedge/ algorithm comparable with /hedge-union/. -- -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A" intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2 {-# INLINABLE intersectionWithKey #-} {-------------------------------------------------------------------- MergeWithKey --------------------------------------------------------------------} -- | /O(n+m)/. A high-performance universal combining function. This function -- is used to define 'unionWith', 'unionWithKey', 'differenceWith', -- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be -- used to define other custom combine functions. -- -- Please make sure you know what is going on when using 'mergeWithKey', -- otherwise you can be surprised by unexpected code growth or even -- corruption of the data structure. -- -- When 'mergeWithKey' is given three arguments, it is inlined to the call -- site. You should therefore use 'mergeWithKey' only to define your custom -- combining functions. For example, you could define 'unionWithKey', -- 'differenceWithKey' and 'intersectionWithKey' as -- -- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2 -- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2 -- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2 -- -- When calling @'mergeWithKey' combine only1 only2@, a function combining two -- 'IntMap's is created, such that -- -- * if a key is present in both maps, it is passed with both corresponding -- values to the @combine@ function. Depending on the result, the key is either -- present in the result with specified value, or is left out; -- -- * a nonempty subtree present only in the first map is passed to @only1@ and -- the output is added to the result; -- -- * a nonempty subtree present only in the second map is passed to @only2@ and -- the output is added to the result. -- -- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/. -- The values can be modified arbitrarily. Most common variants of @only1@ and -- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or -- @'filterWithKey' f@ could be used for any @f@. mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c) -> Map k a -> Map k b -> Map k c mergeWithKey f g1 g2 = go where go Tip t2 = g2 t2 go t1 Tip = g1 t1 go t1 t2 = hedgeMerge NothingS NothingS t1 t2 hedgeMerge _ _ t1 Tip = g1 t1 hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ link kx x (filterGt blo l) (filterLt bhi r) hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2) (found, trim_t2) = trimLookupLo kx bhi t2 r' = hedgeMerge bmi bhi r trim_t2 in case found of Nothing -> case g1 (singleton kx x) of Tip -> merge l' r' (Bin _ _ x' Tip Tip) -> link kx x' l' r' _ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)" Just x2 -> case f kx x x2 of Nothing -> merge l' r' Just x' -> x' `seq` link kx x' l' r' where bmi = JustS kx {-# INLINE mergeWithKey #-} {-------------------------------------------------------------------- Filter and partition --------------------------------------------------------------------} -- | /O(n)/. Map values and collect the 'Just' results. -- -- > let f x = if x == "a" then Just "new a" else Nothing -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a" mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b mapMaybe f = mapMaybeWithKey (\_ x -> f x) -- | /O(n)/. Map keys\/values and collect the 'Just' results. -- -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3" mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b mapMaybeWithKey _ Tip = Tip mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of Just y -> y `seq` link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r) Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r) -- | /O(n)/. Map values and separate the 'Left' and 'Right' results. -- -- > let f a = if a < "c" then Left a else Right a -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")]) -- > -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c) mapEither f m = mapEitherWithKey (\_ x -> f x) m -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results. -- -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a) -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")]) -- > -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")]) mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c) mapEitherWithKey f0 t0 = toPair $ go f0 t0 where go _ Tip = (Tip :*: Tip) go f (Bin _ kx x l r) = case f kx x of Left y -> y `seq` (link kx y l1 r1 :*: merge l2 r2) Right z -> z `seq` (merge l1 r1 :*: link kx z l2 r2) where (l1 :*: l2) = go f l (r1 :*: r2) = go f r {-------------------------------------------------------------------- Mapping --------------------------------------------------------------------} -- | /O(n)/. Map a function over all values in the map. -- -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")] map :: (a -> b) -> Map k a -> Map k b map _ Tip = Tip map f (Bin sx kx x l r) = let x' = f x in x' `seq` Bin sx kx x' (map f l) (map f r) {-# NOINLINE [1] map #-} {-# RULES "map/map" forall f g xs . map f (map g xs) = map (f . g) xs #-} -- | /O(n)/. Map a function over all values in the map. -- -- > let f key x = (show key) ++ ":" ++ x -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")] mapWithKey :: (k -> a -> b) -> Map k a -> Map k b mapWithKey _ Tip = Tip mapWithKey f (Bin sx kx x l r) = let x' = f kx x in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r) {-# NOINLINE [1] mapWithKey #-} {-# RULES "mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) = mapWithKey (\k a -> f k (g k a)) xs "mapWithKey/map" forall f g xs . mapWithKey f (map g xs) = mapWithKey (\k a -> f k (g a)) xs "map/mapWithKey" forall f g xs . map f (mapWithKey g xs) = mapWithKey (\k a -> f (g k a)) xs #-} -- | /O(n)/. The function 'mapAccum' threads an accumulating -- argument through the map in ascending order of keys. -- -- > let f a b = (a ++ b, b ++ "X") -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")]) mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c) mapAccum f a m = mapAccumWithKey (\a' _ x' -> f a' x') a m -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating -- argument through the map in ascending order of keys. -- -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X") -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")]) mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c) mapAccumWithKey f a t = mapAccumL f a t -- | /O(n)/. The function 'mapAccumL' threads an accumulating -- argument through the map in ascending order of keys. mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c) mapAccumL _ a Tip = (a,Tip) mapAccumL f a (Bin sx kx x l r) = let (a1,l') = mapAccumL f a l (a2,x') = f a1 kx x (a3,r') = mapAccumL f a2 r in x' `seq` (a3,Bin sx kx x' l' r') -- | /O(n)/. The function 'mapAccumR' threads an accumulating -- argument through the map in descending order of keys. mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c) mapAccumRWithKey _ a Tip = (a,Tip) mapAccumRWithKey f a (Bin sx kx x l r) = let (a1,r') = mapAccumRWithKey f a r (a2,x') = f a1 kx x (a3,l') = mapAccumRWithKey f a2 l in x' `seq` (a3,Bin sx kx x' l' r') -- | /O(n*log n)/. -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@. -- -- The size of the result may be smaller if @f@ maps two or more distinct -- keys to the same new key. In this case the associated values will be -- combined using @c@. -- -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab" -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab" mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) [] {-# INLINABLE mapKeysWith #-} {-------------------------------------------------------------------- Conversions --------------------------------------------------------------------} -- | /O(n)/. Build a map from a set of keys and a function which for each key -- computes its value. -- -- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")] -- > fromSet undefined Data.Set.empty == empty fromSet :: (k -> a) -> Set.Set k -> Map k a fromSet _ Set.Tip = Tip fromSet f (Set.Bin sz x l r) = case f x of v -> v `seq` Bin sz x v (fromSet f l) (fromSet f r) {-------------------------------------------------------------------- Lists use [foldlStrict] to reduce demand on the control-stack --------------------------------------------------------------------} -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'. -- If the list contains more than one value for the same key, the last value -- for the key is retained. -- -- If the keys of the list are ordered, linear-time implementation is used, -- with the performance equal to 'fromDistinctAscList'. -- -- > fromList [] == empty -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")] -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")] -- For some reason, when 'singleton' is used in fromList or in -- create, it is not inlined, so we inline it manually. fromList :: Ord k => [(k,a)] -> Map k a fromList [] = Tip fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0 | otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0 where not_ordered _ [] = False not_ordered kx ((ky,_) : _) = kx >= ky {-# INLINE not_ordered #-} fromList' t0 xs = foldlStrict ins t0 xs where ins t (k,x) = insert k x t go arg _ _ | arg `seq` False = undefined go _ t [] = t go _ t [(kx, x)] = x `seq` insertMax kx x t go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs | otherwise = case create s xss of (r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys (r, _, ys) -> x `seq` fromList' (link kx x l r) ys -- The create is returning a triple (tree, xs, ys). Both xs and ys -- represent not yet processed elements and only one of them can be nonempty. -- If ys is nonempty, the keys in ys are not ordered with respect to tree -- and must be inserted using fromList'. Otherwise the keys have been -- ordered so far. create arg _ | arg `seq` False = undefined create _ [] = (Tip, [], []) create s xs@(xp : xss) | s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss) | otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, []) | otherwise = case create (s `shiftR` 1) xs of res@(_, [], _) -> res (l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs) (l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys) | otherwise -> case create (s `shiftR` 1) yss of (r, zs, ws) -> y `seq` (link ky y l r, zs, ws) {-# INLINABLE fromList #-} -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'. -- -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")] -- > fromListWith (++) [] == empty fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a fromListWith f xs = fromListWithKey (\_ x y -> f x y) xs {-# INLINABLE fromListWith #-} -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'. -- -- > let f k a1 a2 = (show k) ++ a1 ++ a2 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")] -- > fromListWithKey f [] == empty fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a fromListWithKey f xs = foldlStrict ins empty xs where ins t (k,x) = insertWithKey f k x t {-# INLINABLE fromListWithKey #-} {-------------------------------------------------------------------- Building trees from ascending/descending lists can be done in linear time. Note that if [xs] is ascending that: fromAscList xs == fromList xs fromAscListWith f xs == fromListWith f xs --------------------------------------------------------------------} -- | /O(n)/. Build a map from an ascending list in linear time. -- /The precondition (input list is ascending) is not checked./ -- -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")] -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False fromAscList :: Eq k => [(k,a)] -> Map k a fromAscList xs = fromAscListWithKey (\_ x _ -> x) xs {-# INLINABLE fromAscList #-} -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys. -- /The precondition (input list is ascending) is not checked./ -- -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")] -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a fromAscListWith f xs = fromAscListWithKey (\_ x y -> f x y) xs {-# INLINABLE fromAscListWith #-} -- | /O(n)/. Build a map from an ascending list in linear time with a -- combining function for equal keys. -- /The precondition (input list is ascending) is not checked./ -- -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")] -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a fromAscListWithKey f xs = fromDistinctAscList (combineEq f xs) where -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs] combineEq _ xs' = case xs' of [] -> [] [x] -> [x] (x:xx) -> combineEq' x xx combineEq' z [] = [z] combineEq' z@(kz,zz) (x@(kx,xx):xs') | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs' | otherwise = z:combineEq' x xs' {-# INLINABLE fromAscListWithKey #-} -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time. -- /The precondition is not checked./ -- -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False -- For some reason, when 'singleton' is used in fromDistinctAscList or in -- create, it is not inlined, so we inline it manually. fromDistinctAscList :: [(k,a)] -> Map k a fromDistinctAscList [] = Tip fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0 where go arg _ _ | arg `seq` False = undefined go _ t [] = t go s l ((kx, x) : xs) = case create s xs of (r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys create arg _ | arg `seq` False = undefined create _ [] = (Tip, []) create s xs@(x' : xs') | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs') | otherwise = case create (s `shiftR` 1) xs of res@(_, []) -> res (l, (ky, y):ys) -> case create (s `shiftR` 1) ys of (r, zs) -> y `seq` (link ky y l r, zs)
phischu/fragnix
benchmarks/containers/Data.Map.Strict.hs
bsd-3-clause
44,357
0
23
11,607
8,387
4,538
3,849
451
10
main = putStr "Hello, world!\n"
irori/hs2lazy
examples/hello.hs
bsd-3-clause
32
0
5
5
9
4
5
1
1
module BPython.PyType where data PythonType = PyInt | PyFloat | PyString | PyBool | PyVoid | PyFun [PythonType] PythonType | PyAny | PyAnyOf [PythonType] | PyAnyFunction | PyList PythonType | PyVar String | PyForAll String PythonType | PyForAnyOf String [PythonType] PythonType | PyRange instance Eq PythonType where PyInt == PyInt = True PyFloat == PyFloat = True PyString == PyString = True PyBool == PyBool = True PyVoid == PyVoid = True (PyFun args ret) == (PyFun args' ret') = args == args' && ret == ret' (PyList t1) == (PyList t2) = t1 == t2 PyAny == _ = True _ == PyAny = True t == PyAnyOf ts = t `elem` ts PyAnyOf ts == t = t `elem` ts _ == _ = False instance Show PythonType where show PyInt = "Int" show PyFloat = "Float" show PyString = "String" show PyBool = "Bool" show PyVoid = "Void" show (PyFun arg_ts ret_t) = show arg_ts ++ "->" ++ show ret_t show PyAny = "Any" show (PyAnyOf args) = "AnyOf " ++ show args show (PyList t) = "ListOf " ++ show t show (PyVar x) = x show (PyForAll x t) = "forall " ++ x ++ ": " ++ show t show (PyForAnyOf x variants t) = "forany " ++ x ++ " of " ++ show variants ++ ": " ++ show t show PyRange = "Range" primitiveTypes :: [PythonType] primitiveTypes = [PyInt, PyFloat, PyString, PyBool]
feelout/mscthesiscode
BPython/PyType.hs
bsd-3-clause
1,277
4
10
282
537
273
264
33
1
module Data.TestCase1TcLiteral where import Language.Haskell.Exts import BuiltIn.BuiltInTypes import Tc.Class import qualified Utils.Env as Env import Utils.Id -- test1 a = TyVar (Ident "$0") test1 = (Char 'c', ([], tChar)) test2 = (String "", ([], tString)) test3 = (Int 0, ([numconstr a], a)) test4 = (Frac 0.6, ([fracconstr a], a))
rodrigogribeiro/mptc
test/Data/TestCase1TcLiteral.hs
bsd-3-clause
343
0
8
57
146
87
59
11
1
{-- snippet all --} import Data.Char(toUpper) main = interact (map toUpper . (++) "Your data, in uppercase, is:\n\n") {-- /snippet all --}
binesiyu/ifl
examples/ch07/toupper-lazy5.hs
mit
141
0
8
24
36
20
16
2
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} module Main where import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Text (Text, pack, unpack) import qualified Database.Redis as R import Language.Haskell.TH.Syntax import Database.Persist import Database.Persist.Redis import Database.Persist.TH let redisSettings = mkPersistSettings (ConT ''RedisBackend) in share [mkPersist redisSettings] [persistLowerCase| Person name String age Int deriving Show |] d :: R.ConnectInfo d = R.defaultConnectInfo host :: Text host = pack $ R.connectHost d redisConf :: RedisConf redisConf = RedisConf host (R.connectPort d) Nothing 10 mkKey :: (MonadIO m, PersistEntity val) => Text -> m (Key val) mkKey s = case keyFromValues [PersistText s] of Right z -> return z Left a -> liftIO $ fail (unpack a) main :: IO () main = withRedisConn redisConf $ runRedisPool $ do _ <- liftIO $ print "Inserting..." s <- insert $ Person "Test" 12 _ <- liftIO $ print ("Received the key" ++ show s) key <- mkKey (pack "person_test") insertKey key $ Person "Test2" 45 repsert s (Person "Test3" 55) g <- get key :: RedisT IO (Maybe Person) liftIO $ print g delete s return ()
yesodweb/persistent
persistent-redis/tests/basic-test.hs
mit
1,838
0
13
527
442
228
214
45
2
{- | Module : Camfort.Specification.Stencils.Annotation Description : Annotation with stencil information. Copyright : (c) 2017, Dominic Orchard, Andrew Rice, Mistral Contrastin, Matthew Danish License : Apache-2.0 Maintainer : [email protected] Stability : experimental Defines the 'StencilAnnotation' datatype, which is used for annotating a 'ProgramFile' with stencil information. -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module Camfort.Specification.Stencils.Annotation ( StencilAnnotation , SA , mkStencilAnnotation -- ** Specification Annotation Helpers , getAstSpec , getParseSpec , getRegionSpec , getStencilBlock , giveAstSpec , giveParseSpec , giveRegionSpec -- ** Base Annotation , getBaseAnnotation , modifyBaseAnnotation ) where import Data.Data (Data) import qualified Language.Fortran.AST as F import qualified Language.Fortran.Analysis as FA import qualified Camfort.Analysis.Annotations as Ann import Camfort.Analysis.CommentAnnotator import qualified Camfort.Specification.Stencils.Parser.Types as Gram import qualified Camfort.Specification.Stencils.Syntax as Syn -- | Specification annotation. data SpecAnnotation -- | Unprocessed syntax tree. = ParserSpec Gram.Specification -- | Region definition. | RegionDecl Syn.RegionDecl -- | Normalised AST specification. | ASTSpec Syn.SpecDecls deriving (Eq, Show, Data) data StencilAnnotation a = StencilAnnotation { prevAnnotation :: a -- | Assocatated specification. , stencilSpec :: Maybe SpecAnnotation -- | Associated assignment. , stencilBlock :: Maybe (F.Block (FA.Analysis (StencilAnnotation a))) } deriving (Show, Eq, Data) -- | Create a new stencil annotation. mkStencilAnnotation :: a -> StencilAnnotation a mkStencilAnnotation a = StencilAnnotation { prevAnnotation = a , stencilSpec = Nothing , stencilBlock = Nothing } -- | Convenience name for common annotation type. type SA = FA.Analysis (StencilAnnotation Ann.A) modifyBaseAnnotation :: (Ann.A -> Ann.A) -> SA -> SA modifyBaseAnnotation f = Ann.onPrev (\ann -> ann { prevAnnotation = f (prevAnnotation ann) }) -- | Retrieve the underlying (base) annotation from a stencil annotation. getBaseAnnotation :: SA -> Ann.A getBaseAnnotation = prevAnnotation . FA.prevAnnotation setSpec :: SpecAnnotation -> SA -> SA setSpec s = Ann.onPrev (\ann -> ann { stencilSpec = Just s }) -- | Set the annotation's stencil specification to a parsed specification. giveParseSpec :: Gram.Specification -> SA -> SA giveParseSpec spec = setSpec (ParserSpec spec) -- | Set the annotation's stencil specification to a region alias. giveRegionSpec :: Syn.RegionDecl -> SA -> SA giveRegionSpec spec = setSpec (RegionDecl spec) -- | Set the annotation's stencil specification to a normalized specification. giveAstSpec :: Syn.SpecDecls -> SA -> SA giveAstSpec spec = setSpec (ASTSpec spec) getSA :: SA -> StencilAnnotation Ann.A getSA = FA.prevAnnotation getSpec :: SA -> Maybe SpecAnnotation getSpec = stencilSpec . getSA -- | Retrieve a parsed specification from an annotation. getParseSpec :: SA -> Maybe Gram.Specification getParseSpec s = case getSpec s of (Just (ParserSpec spec)) -> Just spec _ -> Nothing -- | Retrieve a region environment from an annotation. getRegionSpec :: SA -> Maybe Syn.RegionDecl getRegionSpec s = case getSpec s of (Just (RegionDecl renv)) -> Just renv _ -> Nothing -- | Retrieve a normalized specification from an annotation. getAstSpec :: SA -> Maybe Syn.SpecDecls getAstSpec s = case getSpec s of (Just (ASTSpec ast)) -> Just ast _ -> Nothing getStencilBlock :: SA -> Maybe (F.Block SA) getStencilBlock = stencilBlock . getSA {- *** Routines for associating annotations to ASTs -} -- Instances for embedding parsed specifications into the AST instance ASTEmbeddable SA Gram.Specification where annotateWithAST ann ast = Ann.onPrev (\ann' -> ann' { stencilSpec = Just $ ParserSpec ast }) ann instance Linkable SA where link ann [email protected]{} = Ann.onPrev (\ann' -> ann' { stencilBlock = Just b }) ann link ann (b@(F.BlStatement _ _ _ F.StExpressionAssign{})) = Ann.onPrev (\ann' -> ann' { stencilBlock = Just b }) ann link ann _ = ann linkPU ann _ = ann
dorchard/camfort
src/Camfort/Specification/Stencils/Annotation.hs
apache-2.0
4,460
0
15
880
954
529
425
80
2
<?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="hr-HR"> <title>Export Report | ZAP Extension</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/exportreport/src/main/javahelp/org/zaproxy/zap/extension/exportreport/resources/help_hr_HR/helpset_hr_HR.hs
apache-2.0
975
80
66
160
415
210
205
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Benchmarks.Concat (benchmark) where import Control.Monad.Trans.Writer import Criterion (Benchmark, bgroup, bench, whnf) import Data.Text as T benchmark :: IO Benchmark benchmark = return $ bgroup "Concat" [ bench "append" $ whnf (append4 "Text 1" "Text 2" "Text 3") "Text 4" , bench "concat" $ whnf (concat4 "Text 1" "Text 2" "Text 3") "Text 4" , bench "write" $ whnf (write4 "Text 1" "Text 2" "Text 3") "Text 4" ] append4, concat4, write4 :: Text -> Text -> Text -> Text -> Text {-# NOINLINE append4 #-} append4 x1 x2 x3 x4 = x1 `append` x2 `append` x3 `append` x4 {-# NOINLINE concat4 #-} concat4 x1 x2 x3 x4 = T.concat [x1, x2, x3, x4] {-# NOINLINE write4 #-} write4 x1 x2 x3 x4 = execWriter $ tell x1 >> tell x2 >> tell x3 >> tell x4
text-utf8/text
benchmarks/haskell/Benchmarks/Concat.hs
bsd-2-clause
797
0
11
158
273
149
124
17
1
-- | -- Module : Codec.Binary.Uu -- Copyright : (c) 2007 Magnus Therning -- License : BSD3 -- -- Uuencoding is notoriously badly specified. This implementation is -- compatible with the GNU Sharutils -- (<http://www.gnu.org/software/sharutils/>). -- -- Further documentation and information can be found at -- <http://www.haskell.org/haskellwiki/Library/Data_encoding>. module Codec.Binary.Uu ( EncIncData(..) , EncIncRes(..) , encodeInc , encode , DecIncData(..) , DecIncRes(..) , decodeInc , decode , chop , unchop ) where import Codec.Binary.Util import Control.Monad import Data.Array import Data.Bits import Data.Maybe import Data.Word import qualified Data.Map as M -- {{{1 enc/dec map _encMap = zip [0..] "`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" -- {{{1 encodeArray encodeArray :: Array Word8 Char encodeArray = array (0, 64) _encMap -- {{{1 decodeMap decodeMap :: M.Map Char Word8 decodeMap = M.fromList [(snd i, fst i) | i <- _encMap] -- {{{1 encode -- | Incremental encoder function. encodeInc :: EncIncData -> EncIncRes String encodeInc e = eI [] e where enc3 [o1, o2, o3] = map (encodeArray !) [i1, i2, i3, i4] where i1 = o1 `shiftR` 2 i2 = (o1 `shiftL` 4 .|. o2 `shiftR` 4) .&. 0x3f i3 = (o2 `shiftL` 2 .|. o3 `shiftR` 6) .&. 0x3f i4 = o3 .&. 0x3f eI [] EDone = EFinal [] eI [o1] EDone = EFinal $ take 2 $ enc3 [o1, 0, 0] eI [o1, o2] EDone = EFinal $ take 3 $ enc3 [o1, o2, 0] eI lo (EChunk bs) = doEnc [] (lo ++ bs) where doEnc acc (o1:o2:o3:os) = doEnc (acc ++ enc3 [o1, o2, o3]) os doEnc acc os = EPart acc (eI os) -- | Encode data. encode :: [Word8] -> String encode = encoder encodeInc -- {{{1 decode -- | Incremental decoder function. decodeInc :: DecIncData String -> DecIncRes String decodeInc d = dI [] d where dec4 cs = let ds = map (flip M.lookup decodeMap) cs [e1, e2, e3, e4] = map fromJust ds o1 = e1 `shiftL` 2 .|. e2 `shiftR` 4 o2 = e2 `shiftL` 4 .|. e3 `shiftR` 2 o3 = e3 `shiftL` 6 .|. e4 allJust = and . map isJust in if allJust ds then Just [o1, o2, o3] else Nothing dI [] DDone = DFinal [] [] dI lo@[c1, c2] DDone = maybe (DFail [] lo) (\ bs -> DFinal (take 1 bs) []) (dec4 [c1, c2, '`', '`']) dI lo@[c1, c2, c3] DDone = maybe (DFail [] lo) (\ bs -> DFinal (take 2 bs) []) (dec4 [c1, c2, c3, '`']) dI lo DDone = DFail [] lo dI lo (DChunk s) = doDec [] (lo ++ s) where doDec acc s'@(c1:c2:c3:c4:cs) = maybe (DFail acc s') (\ bs -> doDec (acc ++ bs) cs) (dec4 [c1, c2, c3, c4]) doDec acc s' = DPart acc (dI s') -- | Decode data. decode :: String -> Maybe [Word8] decode = decoder decodeInc -- {{{1 chop -- | Chop up a string in parts. Each string in the resulting list is prepended -- with the length according to the uuencode \"specificiation\". -- -- /Notes:/ -- -- * The length of the strings in the result will be @(n -1) `div` 4 * 4 + -- 1@. The @-1@ comes from the need to prepend the length (which explains -- the final @+1@). Keeping it to a multiple of 4 means that strings -- returned from 'encode' can be chopped without requiring any changes. -- -- * The length of lines in GNU's sharutils is 61. chop :: Int -- ^ length (value should be in the range @[5..85]@) -> String -> [String] chop n "" = [] chop n s = let enc_len | n < 5 = 4 | n >= 85 = 84 | otherwise = (n - 1) `div` 4 * 4 enc_line = take enc_len s act_len = fromIntegral $ case (length enc_line `divMod` 4) of (l, 0) -> l * 3 (l, 2) -> l * 3 + 1 (l, 3) -> l * 3 + 2 len = (encodeArray ! act_len) in (len : enc_line) : chop n (drop enc_len s) -- {{{1 unchop -- | Concatenate the strings into one long string. Each string is assumed to -- be prepended with the length according to the uuencode specification. unchop :: [String] -> String unchop ss = let singleUnchop (l : cs) = let act_len = fromIntegral $ decodeMap M.! l enc_len = case (act_len `divMod` 3) of (n, 0) -> n * 4 (n, 1) -> n * 4 + 2 (n, 2) -> n * 4 + 3 in take enc_len cs in foldr ((++) . singleUnchop) "" ss
magthe/dataenc
src/Codec/Binary/Uu.hs
bsd-3-clause
4,763
0
17
1,621
1,492
826
666
94
7
{-# OPTIONS -XOverloadedStrings #-} module QueuePurgeSpec (main, spec) where import Test.Hspec import Network.AMQP import Data.ByteString.Lazy.Char8 as BL hiding (putStrLn) import Control.Concurrent (threadDelay) main :: IO () main = hspec spec spec :: Spec spec = do describe "purgeQueue" $ do context "when queue exists" $ do it "empties the queue" $ do conn <- openConnection "127.0.0.1" "/" "guest" "guest" ch <- openChannel conn (q, _, _) <- declareQueue ch (newQueue {queueName = "", queueDurable = True, queueExclusive = False, queueAutoDelete = False}) publishMsg ch "" q newMsg {msgBody = (BL.pack "payload")} threadDelay (1000 * 100) (_, n, _) <- declareQueue ch (newQueue {queueName = q, queuePassive = True}) n `shouldBe` 1 _ <- purgeQueue ch q threadDelay (1000 * 100) (_, n2, _) <- declareQueue ch (newQueue {queueName = q, queuePassive = True}) n2 `shouldBe` 0 closeConnection conn context "when queue DOES NOT exist" $ do it "empties the queue" $ do conn <- openConnection "127.0.0.1" "/" "guest" "guest" ch <- openChannel conn let ex = ChannelClosedException "NOT_FOUND - no queue 'haskell-amqp.queues.avjqmyG{CHrc66MRyzYVA+PwrMVARJ' in vhost '/'" (purgeQueue ch "haskell-amqp.queues.avjqmyG{CHrc66MRyzYVA+PwrMVARJ") `shouldThrow` (== ex) closeConnection conn
bitemyapp/amqp
test/QueuePurgeSpec.hs
bsd-3-clause
1,950
0
21
856
433
225
208
38
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeApplications #-} module Main where import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.Proxy (Proxy(Proxy)) import Data.Ratio ((%), numerator, denominator) import qualified Data.Text as T import Data.Word (Word8) import GHC.Exts (fromList) import GHC.TypeLits (Nat, Symbol, KnownSymbol, symbolVal) import qualified Money import qualified Test.Tasty as Tasty import Test.Tasty.HUnit ((@?=), (@=?)) import qualified Test.Tasty.HUnit as HU import qualified Test.Tasty.Runners as Tasty import Test.Tasty.QuickCheck ((===), (==>), (.&&.)) import qualified Test.Tasty.QuickCheck as QC import qualified Xmlbf import Money.Xmlbf () -------------------------------------------------------------------------------- main :: IO () main = Tasty.defaultMainWithIngredients [ Tasty.consoleTestReporter , Tasty.listingTests ] (Tasty.localOption (QC.QuickCheckTests 100) tests) tests :: Tasty.TestTree tests = Tasty.testGroup "root" [ testCurrencies , testCurrencyUnits , testExchange , testRawSerializations ] testCurrencies :: Tasty.TestTree testCurrencies = Tasty.testGroup "Currency" [ testDense (Proxy :: Proxy "BTC") -- A cryptocurrency. , testDense (Proxy :: Proxy "USD") -- A fiat currency with decimal fractions. , testDense (Proxy :: Proxy "VUV") -- A fiat currency with non-decimal fractions. , testDense (Proxy :: Proxy "XAU") -- A precious metal. ] testCurrencyUnits :: Tasty.TestTree testCurrencyUnits = Tasty.testGroup "Currency units" [ testDiscrete (Proxy :: Proxy "BTC") (Proxy :: Proxy "satoshi") , testDiscrete (Proxy :: Proxy "BTC") (Proxy :: Proxy "bitcoin") , testDiscrete (Proxy :: Proxy "USD") (Proxy :: Proxy "cent") , testDiscrete (Proxy :: Proxy "USD") (Proxy :: Proxy "dollar") , testDiscrete (Proxy :: Proxy "VUV") (Proxy :: Proxy "vatu") , testDiscrete (Proxy :: Proxy "XAU") (Proxy :: Proxy "gram") , testDiscrete (Proxy :: Proxy "XAU") (Proxy :: Proxy "grain") ] testDense :: forall currency . KnownSymbol currency => Proxy currency -> Tasty.TestTree testDense pc = Tasty.testGroup ("Dense " ++ show (symbolVal pc)) [ QC.testProperty "Xmlbf encoding roundtrip" $ QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) -> Right x === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x) , QC.testProperty "Xmlbf encoding roundtrip (SomeDense)" $ QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) -> let x' = Money.toSomeDense x in Right x' === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x') , QC.testProperty "Xmlbf encoding roundtrip (Dense through SomeDense)" $ QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) -> Right x === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml (Money.toSomeDense x)) , QC.testProperty "Xmlbf encoding roundtrip (SomeDense through Dense)" $ QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) -> Right (Money.toSomeDense x) === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x) ] testExchange :: Tasty.TestTree testExchange = Tasty.testGroup "Exchange" [ testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "BTC") , testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "USD") , testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "VUV") , testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "XAU") , testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "BTC") , testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "USD") , testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "VUV") , testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "XAU") , testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "BTC") , testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "USD") , testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "VUV") , testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "XAU") , testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "BTC") , testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "USD") , testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "VUV") , testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "XAU") ] testDiscrete :: forall (currency :: Symbol) (unit :: Symbol) . ( Money.GoodScale (Money.UnitScale currency unit) , KnownSymbol currency , KnownSymbol unit ) => Proxy currency -> Proxy unit -> Tasty.TestTree testDiscrete pc pu = Tasty.testGroup ("Discrete " ++ show (symbolVal pc) ++ " " ++ show (symbolVal pu)) [ QC.testProperty "Xmlbf encoding roundtrip" $ QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) -> Right x === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x) , QC.testProperty "Xmlbf encoding roundtrip (SomeDiscrete)" $ QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) -> let x' = Money.toSomeDiscrete x in Right x' === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x') , QC.testProperty "Xmlbf encoding roundtrip (Discrete through SomeDiscrete)" $ QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) -> Right x === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml (Money.toSomeDiscrete x)) , QC.testProperty "Xmlbf encoding roundtrip (SomeDiscrete through Discrete)" $ QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) -> Right (Money.toSomeDiscrete x) === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x) ] testExchangeRate :: forall (src :: Symbol) (dst :: Symbol) . (KnownSymbol src, KnownSymbol dst) => Proxy src -> Proxy dst -> Tasty.TestTree testExchangeRate ps pd = Tasty.testGroup ("ExchangeRate " ++ show (symbolVal ps) ++ " " ++ show (symbolVal pd)) [ QC.testProperty "Xmlbf encoding roundtrip" $ QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) -> Right x === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x) , QC.testProperty "Xmlbf encoding roundtrip (SomeExchangeRate)" $ QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) -> let x' = Money.toSomeExchangeRate x in Right x' === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x') , QC.testProperty "Xmlbf encoding roundtrip (ExchangeRate through SomeExchangeRate)" $ QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) -> Right x === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml (Money.toSomeExchangeRate x)) , QC.testProperty "Xmlbf encoding roundtrip (SomeExchangeRate through ExchangeRate)" $ QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) -> Right (Money.toSomeExchangeRate x) === Xmlbf.runParser Xmlbf.fromXml (Xmlbf.toXml x) ] -------------------------------------------------------------------------------- -- Raw parsing "golden tests" testRawSerializations :: Tasty.TestTree testRawSerializations = Tasty.testGroup "Raw serializations" [ Tasty.testGroup "xmlbf" [ Tasty.testGroup "decode" [ HU.testCase "Dense" $ do Right rawDns0 @=? Xmlbf.runParser Xmlbf.fromXml rawDns0_xmlbf , HU.testCase "Dense (negative)" $ do Right rawDns1 @=? Xmlbf.runParser Xmlbf.fromXml rawDns1_xmlbf , HU.testCase "Discrete" $ do Right rawDis0 @=? Xmlbf.runParser Xmlbf.fromXml rawDis0_xmlbf , HU.testCase "Discrete (negative)" $ do Right rawDis1 @=? Xmlbf.runParser Xmlbf.fromXml rawDis1_xmlbf , HU.testCase "ExchangeRate" $ do Right rawXr0 @=? Xmlbf.runParser Xmlbf.fromXml rawXr0_xmlbf ] , Tasty.testGroup "encode" [ HU.testCase "Dense" $ rawDns0_xmlbf @=? Xmlbf.toXml rawDns0 , HU.testCase "Dense (negative)" $ rawDns1_xmlbf @=? Xmlbf.toXml rawDns1 , HU.testCase "Discrete" $ rawDis0_xmlbf @=? Xmlbf.toXml rawDis0 , HU.testCase "Discrete (negative)" $ rawDis1_xmlbf @=? Xmlbf.toXml rawDis1 , HU.testCase "ExchangeRate" $ rawXr0_xmlbf @=? Xmlbf.toXml rawXr0 ] ] ] rawDns0 :: Money.Dense "USD" rawDns0 = Money.dense' (26%1) rawDns1 :: Money.Dense "USD" rawDns1 = Money.dense' (negate 26 % 1) rawDis0 :: Money.Discrete "USD" "cent" rawDis0 = Money.discrete 4 rawDis1 :: Money.Discrete "USD" "cent" rawDis1 = Money.discrete (negate 4) rawXr0 :: Money.ExchangeRate "USD" "BTC" Just rawXr0 = Money.exchangeRate (3%2) rawDns0_xmlbf :: [Xmlbf.Node] rawDns0_xmlbf = -- "<money-dense n=\"26\" d=\"1\" c=\"USD\"/>" [ either error id $ Xmlbf.element' "money-dense" (fromList [("n","26"), ("d","1"), ("c","USD")]) [] ] rawDns1_xmlbf :: [Xmlbf.Node] rawDns1_xmlbf = -- "<money-dense n=\"-26\" d=\"1\" c=\"USD\"/>" [ either error id $ Xmlbf.element' "money-dense" (fromList [("n","-26"), ("d","1"), ("c","USD")]) [] ] rawDis0_xmlbf :: [Xmlbf.Node] rawDis0_xmlbf = -- "<money-discrete n=\"100\" a=\"4\" d=\"1\" c=\"USD\"/>" [ either error id $ Xmlbf.element' "money-discrete" (fromList [("n","100"), ("d","1"), ("c","USD"), ("a","4")]) [] ] rawDis1_xmlbf :: [Xmlbf.Node] rawDis1_xmlbf = -- "<money-discrete n=\"100\" a=\"-4\" d=\"1\" c=\"USD\"/>" [ either error id $ Xmlbf.element' "money-discrete" (fromList [("n","100"), ("d","1"), ("c","USD"), ("a","-4")]) [] ] rawXr0_xmlbf :: [Xmlbf.Node] rawXr0_xmlbf = -- "<exchange-rate dst=\"BTC\" n=\"3\" d=\"2\" src=\"USD\"/>" [ either error id $ Xmlbf.element' "exchange-rate" (fromList [("n","3"), ("d","2"), ("src","USD"), ("dst","BTC")]) [] ]
k0001/haskell-money
safe-money-xmlbf/test/Main.hs
bsd-3-clause
9,669
0
16
1,776
3,003
1,592
1,411
187
1
-- | Rewrite ensures variable with return expression. module Ivory.Compile.C.Prop where import qualified Ivory.Language.Syntax as I -------------------------------------------------------------------------------- -- | Replace ensures variable with the return expression. ensTrans :: I.Expr -> I.Expr -> I.Expr ensTrans retE = loop where loop e = case e of I.ExpSym{} -> e I.ExpExtern{} -> e I.ExpVar v -> if v == I.retval then retE else e I.ExpLit{} -> e I.ExpOp op args -> I.ExpOp op (map loop args) I.ExpLabel t e0 s -> I.ExpLabel t (loop e0) s I.ExpIndex t e0 t1 e1 -> I.ExpIndex t (loop e0) t1 (loop e1) I.ExpSafeCast t e0 -> I.ExpSafeCast t (loop e0) I.ExpToIx e0 maxSz -> I.ExpToIx (loop e0) maxSz I.ExpAddrOfGlobal{} -> e I.ExpMaxMin{} -> e I.ExpSizeOf{} -> e --------------------------------------------------------------------------------
GaloisInc/ivory
ivory-backend-c/src/Ivory/Compile/C/Prop.hs
bsd-3-clause
992
0
12
266
309
157
152
17
13
{-# LANGUAGE CPP #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ConstraintKinds #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | The monad used for the command-line executable @stack@. module Stack.Types.StackT (StackT ,HasEnv ,StackM ,runStackT ,runStackTGlobal ,runInnerStackT ,logSticky ,logStickyDone) where import Control.Applicative import Control.Concurrent.MVar import Control.Monad import Control.Monad.Base import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader hiding (lift) import Control.Monad.Trans.Control import qualified Data.ByteString.Char8 as S8 import Data.Char import Data.List (stripPrefix) import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import qualified Data.Text.IO as T import Data.Time import GHC.Foreign (withCString, peekCString) import Language.Haskell.TH import Language.Haskell.TH.Syntax (lift) import Prelude -- Fix AMP warning import Stack.Types.Config (GlobalOpts (..), ColorWhen(..)) import Stack.Types.Internal import System.Console.ANSI import System.FilePath import System.IO import System.Log.FastLogger #ifndef MIN_VERSION_time #define MIN_VERSION_time(x, y, z) 0 #endif #if !MIN_VERSION_time(1, 5, 0) import System.Locale #endif -- | Constraint synonym for all of the common environment instances type HasEnv r = (HasLogOptions r, HasTerminal r, HasReExec r, HasSticky r) -- | Constraint synonym for constraints commonly satisifed by monads used in stack. type StackM r m = (MonadReader r m, MonadIO m, MonadBaseControl IO m, MonadLoggerIO m, MonadMask m, HasEnv r) -------------------------------------------------------------------------------- -- Main StackT monad transformer -- | The monad used for the executable @stack@. newtype StackT config m a = StackT {unStackT :: ReaderT (Env config) m a} deriving (Functor,Applicative,Monad,MonadIO,MonadReader (Env config),MonadThrow,MonadCatch,MonadMask,MonadTrans) deriving instance (MonadBase b m) => MonadBase b (StackT config m) instance MonadBaseControl b m => MonadBaseControl b (StackT config m) where type StM (StackT config m) a = ComposeSt (StackT config) m a liftBaseWith = defaultLiftBaseWith restoreM = defaultRestoreM instance MonadTransControl (StackT config) where type StT (StackT config) a = StT (ReaderT (Env config)) a liftWith = defaultLiftWith StackT unStackT restoreT = defaultRestoreT StackT -- | Takes the configured log level into account. instance MonadIO m => MonadLogger (StackT config m) where monadLoggerLog = stickyLoggerFunc instance MonadIO m => MonadLoggerIO (StackT config m) where askLoggerIO = getStickyLoggerFunc -- | Run a Stack action, using global options. runStackTGlobal :: (MonadIO m) => config -> GlobalOpts -> StackT config m a -> m a runStackTGlobal config GlobalOpts{..} = runStackT config globalLogLevel globalTimeInLog globalTerminal globalColorWhen (isJust globalReExecVersion) runStackT :: (MonadIO m) => config -> LogLevel -> Bool -> Bool -> ColorWhen -> Bool -> StackT config m a -> m a runStackT config logLevel useTime terminal colorWhen reExec m = do useColor <- case colorWhen of ColorNever -> return False ColorAlways -> return True ColorAuto -> liftIO $ hSupportsANSI stderr canUseUnicode <- liftIO getCanUseUnicode withSticky terminal $ \sticky -> runReaderT (unStackT m) Env { envConfig = config , envReExec = reExec , envLogOptions = LogOptions { logUseColor = useColor , logUseUnicode = canUseUnicode , logUseTime = useTime , logMinLevel = logLevel , logVerboseFormat = logLevel <= LevelDebug } , envTerminal = terminal , envSticky = sticky } -- | Taken from GHC: determine if we should use Unicode syntax getCanUseUnicode :: IO Bool getCanUseUnicode = do let enc = localeEncoding str = "\x2018\x2019" test = withCString enc str $ \cstr -> do str' <- peekCString enc cstr return (str == str') test `catchIOError` \_ -> return False runInnerStackT :: (HasEnv r, MonadReader r m, MonadIO m) => config -> StackT config IO a -> m a runInnerStackT config inner = do reExec <- view reExecL logOptions <- view logOptionsL terminal <- view terminalL sticky <- view stickyL liftIO $ runReaderT (unStackT inner) Env { envConfig = config , envReExec = reExec , envLogOptions = logOptions , envTerminal = terminal , envSticky = sticky } -------------------------------------------------------------------------------- -- Logging functionality stickyLoggerFunc :: (HasEnv r, ToLogStr msg, MonadReader r m, MonadIO m) => Loc -> LogSource -> LogLevel -> msg -> m () stickyLoggerFunc loc src level msg = do func <- getStickyLoggerFunc liftIO $ func loc src level msg getStickyLoggerFunc :: (HasEnv r, ToLogStr msg, MonadReader r m) => m (Loc -> LogSource -> LogLevel -> msg -> IO ()) getStickyLoggerFunc = do sticky <- view stickyL lo <- view logOptionsL return $ stickyLoggerFuncImpl sticky lo stickyLoggerFuncImpl :: ToLogStr msg => Sticky -> LogOptions -> (Loc -> LogSource -> LogLevel -> msg -> IO ()) stickyLoggerFuncImpl (Sticky mref) lo loc src level msg = case mref of Nothing -> loggerFunc lo out loc src (case level of LevelOther "sticky-done" -> LevelInfo LevelOther "sticky" -> LevelInfo _ -> level) msg Just ref -> do sticky <- takeMVar ref let backSpaceChar = '\8' repeating = S8.replicate (maybe 0 T.length sticky) clear = S8.hPutStr out (repeating backSpaceChar <> repeating ' ' <> repeating backSpaceChar) -- Convert some GHC-generated Unicode characters as necessary let msgText | logUseUnicode lo = msgTextRaw | otherwise = T.map replaceUnicode msgTextRaw newState <- case level of LevelOther "sticky-done" -> do clear T.hPutStrLn out msgText hFlush out return Nothing LevelOther "sticky" -> do clear T.hPutStr out msgText hFlush out return (Just msgText) _ | level >= logMinLevel lo -> do clear loggerFunc lo out loc src level $ toLogStr msgText case sticky of Nothing -> return Nothing Just line -> do T.hPutStr out line >> hFlush out return sticky | otherwise -> return sticky putMVar ref newState where out = stderr msgTextRaw = T.decodeUtf8With T.lenientDecode msgBytes msgBytes = fromLogStr (toLogStr msg) -- | Replace Unicode characters with non-Unicode equivalents replaceUnicode :: Char -> Char replaceUnicode '\x2018' = '`' replaceUnicode '\x2019' = '\'' replaceUnicode c = c -- | Logging function takes the log level into account. loggerFunc :: ToLogStr msg => LogOptions -> Handle -> Loc -> Text -> LogLevel -> msg -> IO () loggerFunc lo outputChannel loc _src level msg = when (level >= logMinLevel lo) (liftIO (do out <- getOutput T.hPutStrLn outputChannel out)) where getOutput = do timestamp <- getTimestamp l <- getLevel lc <- getLoc return $ T.concat [ T.pack timestamp , T.pack l , T.pack (ansi [Reset]) , T.decodeUtf8 (fromLogStr (toLogStr msg)) , T.pack lc , T.pack (ansi [Reset]) ] where ansi xs | logUseColor lo = setSGRCode xs | otherwise = "" getTimestamp | logVerboseFormat lo && logUseTime lo = do now <- getZonedTime return $ ansi [SetColor Foreground Vivid Black] ++ formatTime' now ++ ": " | otherwise = return "" where formatTime' = take timestampLength . formatTime defaultTimeLocale "%F %T.%q" getLevel | logVerboseFormat lo = return ((case level of LevelDebug -> ansi [SetColor Foreground Dull Green] LevelInfo -> ansi [SetColor Foreground Dull Blue] LevelWarn -> ansi [SetColor Foreground Dull Yellow] LevelError -> ansi [SetColor Foreground Dull Red] LevelOther _ -> ansi [SetColor Foreground Dull Magenta]) ++ "[" ++ map toLower (drop 5 (show level)) ++ "] ") | otherwise = return "" getLoc | logVerboseFormat lo = return $ ansi [SetColor Foreground Vivid Black] ++ "\n@(" ++ fileLocStr ++ ")" | otherwise = return "" fileLocStr = fromMaybe file (stripPrefix dirRoot file) ++ ':' : line loc ++ ':' : char loc where file = loc_filename loc line = show . fst . loc_start char = show . snd . loc_start dirRoot = $(lift . T.unpack . fromJust . T.stripSuffix (T.pack $ "Stack" </> "Types" </> "StackT.hs") . T.pack . loc_filename =<< location) -- | The length of a timestamp in the format "YYYY-MM-DD hh:mm:ss.μμμμμμ". -- This definition is top-level in order to avoid multiple reevaluation at runtime. timestampLength :: Int timestampLength = length (formatTime defaultTimeLocale "%F %T.000000" (UTCTime (ModifiedJulianDay 0) 0)) -- | With a sticky state, do the thing. withSticky :: (MonadIO m) => Bool -> (Sticky -> m b) -> m b withSticky terminal m = if terminal then do state <- liftIO (newMVar Nothing) originalMode <- liftIO (hGetBuffering stdout) liftIO (hSetBuffering stdout NoBuffering) a <- m (Sticky (Just state)) state' <- liftIO (takeMVar state) liftIO (when (isJust state') (S8.putStr "\n")) liftIO (hSetBuffering stdout originalMode) return a else m (Sticky Nothing) -- | Write a "sticky" line to the terminal. Any subsequent lines will -- overwrite this one, and that same line will be repeated below -- again. In other words, the line sticks at the bottom of the output -- forever. Running this function again will replace the sticky line -- with a new sticky line. When you want to get rid of the sticky -- line, run 'logStickyDone'. -- logSticky :: Q Exp logSticky = logOther "sticky" -- | This will print out the given message with a newline and disable -- any further stickiness of the line until a new call to 'logSticky' -- happens. -- -- It might be better at some point to have a 'runSticky' function -- that encompasses the logSticky->logStickyDone pairing. logStickyDone :: Q Exp logStickyDone = logOther "sticky-done"
AndreasPK/stack
src/Stack/Types/StackT.hs
bsd-3-clause
12,362
0
24
3,959
2,860
1,463
1,397
267
7
{- Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module Control.Category (module M) where import "base" Control.Category as M
xwysp/codeworld
codeworld-base/src/Control/Category.hs
apache-2.0
747
0
4
136
23
17
6
4
0
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# LANGUAGE MultiParamTypeClasses, Rank2Types #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Groups.Helpers -- Copyright : Quentin Moser <[email protected]> -- License : BSD-style (see LICENSE) -- -- Maintainer : orphaned -- Stability : stable -- Portability : unportable -- -- Utility functions for "XMonad.Layout.Groups". -- ----------------------------------------------------------------------------- module XMonad.Layout.Groups.Helpers ( -- * Usage -- $usage -- ** Layout-generic actions swapUp , swapDown , swapMaster , focusUp , focusDown , focusMaster , toggleFocusFloat -- ** 'G.Groups'-secific actions , swapGroupUp , swapGroupDown , swapGroupMaster , focusGroupUp , focusGroupDown , focusGroupMaster , moveToGroupUp , moveToGroupDown , moveToNewGroupUp , moveToNewGroupDown , splitGroup ) where import XMonad hiding ((|||)) import qualified XMonad.StackSet as W import qualified XMonad.Layout.Groups as G import XMonad.Actions.MessageFeedback import Control.Monad (unless) import qualified Data.Map as M -- $usage -- -- This module provides helpers functions for use with "XMonad.Layout.Groups"-based -- layouts. You can use its contents by adding -- -- > import XMonad.Layout.Groups.Helpers -- -- to the top of your @.\/.xmonad\/xmonad.hs@. -- -- "XMonad.Layout.Groups"-based layouts do not have the same notion -- of window ordering as the rest of XMonad. For this reason, the usual -- ways of reordering windows and moving focus do not work with them. -- "XMonad.Layout.Groups" provides 'Message's that can be used to obtain -- the right effect. -- -- But what if you want to use both 'G.Groups' and other layouts? -- This module provides actions that try to send 'G.GroupsMessage's, and -- fall back to the classic way if the current layout doesn't hande them. -- They are in the section called \"Layout-generic actions\". -- -- The sections \"Groups-specific actions\" contains actions that don't make -- sense for non-'G.Groups'-based layouts. These are simply wrappers around -- the equivalent 'G.GroupsMessage's, but are included so you don't have to -- write @sendMessage $ Modify $ ...@ everytime. -- -- This module exports many operations with the same names as -- 'G.ModifySpec's from "XMonad.Layout.Groups", so if you want -- to import both, we suggest to import "XMonad.Layout.Groups" -- qualified: -- -- > import qualified XMonad.Layout.Groups as G -- -- For more information on how to extend your layour hook and key bindings, see -- "XMonad.Doc.Extending". -- ** Layout-generic actions -- #Layout-generic actions# alt :: G.ModifySpec -> (WindowSet -> WindowSet) -> X () alt f g = alt2 (G.Modify f) $ windows g alt2 :: G.GroupsMessage -> X () -> X () alt2 m x = do b <- send m unless b x -- | Swap the focused window with the previous one swapUp :: X () swapUp = alt G.swapUp W.swapUp -- | Swap the focused window with the next one swapDown :: X () swapDown = alt G.swapDown W.swapDown -- | Swap the focused window with the master window swapMaster :: X () swapMaster = alt G.swapMaster W.swapMaster -- | If the focused window is floating, focus the next floating -- window. otherwise, focus the next non-floating one. focusUp :: X () focusUp = ifFloat focusFloatUp focusNonFloatUp -- | If the focused window is floating, focus the next floating -- window. otherwise, focus the next non-floating one. focusDown :: X () focusDown = ifFloat focusFloatDown focusNonFloatDown -- | Move focus to the master window focusMaster :: X () focusMaster = alt G.focusMaster W.shiftMaster -- | Move focus between the floating and non-floating layers toggleFocusFloat :: X () toggleFocusFloat = ifFloat focusNonFloat focusFloatUp -- *** Floating layer helpers getFloats :: X [Window] getFloats = gets $ M.keys . W.floating . windowset getWindows :: X [Window] getWindows = gets $ W.integrate' . W.stack . W.workspace . W.current . windowset ifFloat :: X () -> X () -> X () ifFloat x1 x2 = withFocused $ \w -> do floats <- getFloats if elem w floats then x1 else x2 focusNonFloat :: X () focusNonFloat = alt2 G.Refocus helper where helper = withFocused $ \w -> do ws <- getWindows floats <- getFloats let (before, after) = span (/=w) ws case filter (flip notElem floats) $ after ++ before of [] -> return () w':_ -> focus w' focusHelper :: (Bool -> Bool) -- ^ if you want to focus a floating window, 'id'. -- if you want a non-floating one, 'not'. -> ([Window] -> [Window]) -- ^ if you want the next window, 'id'. -- if you want the previous one, 'reverse'. -> X () focusHelper f g = withFocused $ \w -> do ws <- getWindows let (before, _:after) = span (/=w) ws let toFocus = g $ after ++ before floats <- getFloats case filter (f . flip elem floats) toFocus of [] -> return () w':_ -> focus w' focusNonFloatUp :: X () focusNonFloatUp = alt2 (G.Modify G.focusUp) $ focusHelper not reverse focusNonFloatDown :: X () focusNonFloatDown = alt2 (G.Modify G.focusDown) $ focusHelper not id focusFloatUp :: X () focusFloatUp = focusHelper id reverse focusFloatDown :: X () focusFloatDown = focusHelper id id -- ** Groups-specific actions wrap :: G.ModifySpec -> X () wrap = sendMessage . G.Modify -- | Swap the focused group with the previous one swapGroupUp :: X () swapGroupUp = wrap G.swapGroupUp -- | Swap the focused group with the next one swapGroupDown :: X () swapGroupDown = wrap G.swapGroupDown -- | Swap the focused group with the master group swapGroupMaster :: X () swapGroupMaster = wrap G.swapGroupMaster -- | Move the focus to the previous group focusGroupUp :: X () focusGroupUp = wrap G.focusGroupUp -- | Move the focus to the next group focusGroupDown :: X () focusGroupDown = wrap G.focusGroupDown -- | Move the focus to the master group focusGroupMaster :: X () focusGroupMaster = wrap G.focusGroupMaster -- | Move the focused window to the previous group. The 'Bool' argument -- determines what will be done if the focused window is in the very first -- group: Wrap back to the end ('True'), or create a new group before -- it ('False'). moveToGroupUp :: Bool -> X () moveToGroupUp b = wrap (G.moveToGroupUp b) -- | Move the focused window to the next group. The 'Bool' argument -- determines what will be done if the focused window is in the very last -- group: Wrap back to the beginning ('True'), or create a new group after -- it ('False'). moveToGroupDown :: Bool -> X () moveToGroupDown b = wrap (G.moveToGroupDown b) -- | Move the focused window to a new group before the current one moveToNewGroupUp :: X () moveToNewGroupUp = wrap G.moveToNewGroupUp -- | Move the focused window to a new group after the current one moveToNewGroupDown :: X () moveToNewGroupDown = wrap G.moveToNewGroupDown -- | Split the focused group in two at the position of the focused -- window. splitGroup :: X () splitGroup = wrap G.splitGroup
markus1189/xmonad-contrib-710
XMonad/Layout/Groups/Helpers.hs
bsd-3-clause
8,099
0
16
2,342
1,297
709
588
105
2
-- standard modules we almost always want module Util.Std( module Control.Applicative, module Control.Monad, module Control.Monad.Identity, module Data.Foldable, module Data.List, module Data.Maybe, module Data.Monoid, module Data.Traversable, module System.Environment )where import Control.Applicative import Control.Monad import Control.Monad.Identity import Data.List hiding(null) import Data.Maybe import Data.Monoid(Monoid(..),(<>)) import System.Environment(getArgs,getProgName) -- we want the names for deriving import Data.Traversable(Traversable()) import Data.Foldable(Foldable())
m-alvarez/jhc
src/Util/Std.hs
mit
673
0
6
135
155
101
54
19
0
module A1 where import Control.Parallel.Strategies fib t n | n <= 1 = 1 | otherwise = n1_2 + n2_2 + 1 where n1 = fib 20 (n-1) n2 = fib 20 (n-2) (n1_2, n2_2) = runEval (do n1_2 <- rpar_abs_1 n1 n2_2 <- rpar_abs_1 n2 return (n1_2, n2_2)) where rpar_abs_1 | n > t = rpar `dot` rdeepseq | otherwise = rseq n1_2 = fib 20 42
RefactoringTools/HaRe
old/testing/introDeepSeq/A1_TokOut.hs
bsd-3-clause
507
0
12
256
175
88
87
17
1
module A2 where fib 1 = 1 fib n = n1 + n2 + 1 where n1 = fib (n-1) n2 = fib (n-2)
RefactoringTools/HaRe
old/testing/evalMonad/A2.hs
bsd-3-clause
89
0
9
31
60
32
28
5
1
module FunIn3 where --The application of a function is replaced by the right-hand side of the definition, --with actual parameters replacing formals. --In this example, unfold 'addthree'. --This example aims to test the elimination of extra parentheses when unfolding --a function defintion. main :: Int -> Int main = \x -> case x of 1 -> 1 + main 0 0 ->(((addthree 1) 2) 3) addthree :: Int -> Int -> Int -> Int addthree a b c = a + b + c
kmate/HaRe
old/testing/unfoldDef/FunIn3.hs
bsd-3-clause
476
0
14
121
106
58
48
7
2
-- Dummy ParsecCombinator module module ParsecChar where import Parsec type CharParser st a = GenParser Char st a alphaNum :: CharParser st Char alphaNum = undefined char :: Char -> CharParser st Char char = undefined newline :: CharParser st Char newline = undefined
forste/haReFork
tools/base/tests/GhcLibraries/ParsecChar.hs
bsd-3-clause
275
0
6
51
72
41
31
9
1
module HAD.Y2014.M04.D10.Exercise where {- | onBothSide Apply the same argument on both side of a binary numeric function. The only interesting solution is point-free. It IS the easiest exercise so far, with the shortest solution. Examples: prop> onBothSide (+) x = x + x prop> onBothSide (*) x = x * x -} onBothSide :: Num a => (a -> a -> b) -> a -> b onBothSide = undefined
1HaskellADay/1HAD
exercises/HAD/Y2014/M04/D10/Exercise.hs
mit
401
0
9
95
46
27
19
3
1
import Q (message) main :: IO () main = putStrLn message
themoritz/cabal
cabal-testsuite/PackageTests/Sandbox/Reinstall/p/Main.hs
bsd-3-clause
58
0
6
12
27
14
13
3
1
{-# LANGUAGE TypeFamilies, GHCForeignImportPrim, MagicHash, UnliftedFFITypes #-} module Cc015 where import Foreign import Foreign.C.Types import GHC.Prim type family F a type instance F Int = Int# -> Int# foreign import prim "f" f :: F Int
urbanslug/ghc
testsuite/tests/ffi/should_compile/cc016.hs
bsd-3-clause
259
0
6
55
54
33
21
-1
-1
-- !!! Hiding an abstract (Prelude) type module M where import Prelude hiding ( Char ) import Data.Char hiding ( ord, Char ) import qualified Data.Char ( ord ) type Char = Int ord :: Char -> Int ord x = Data.Char.ord (chr x) + 1
urbanslug/ghc
testsuite/tests/module/mod111.hs
bsd-3-clause
235
0
8
52
78
47
31
7
1
{-# LANGUAGE OverloadedStrings #-} module Data.Mole.Watcher ( attachFileWatcher , detachFileWatcher ) where import Control.Concurrent.STM import Control.Concurrent import Control.Monad import qualified Data.Map as M import qualified Data.Set as S import Data.Maybe import System.FilePath import System.Directory import System.FSNotify hiding (defaultConfig) import Data.Mole.Types import Data.Mole.Core attachFileWatcher :: Handle -> IO () attachFileWatcher h = do cwd <- getCurrentDirectory void $ forkIO $ forever $ do withManager $ \mgr -> do stop <- watchTree mgr "." (const True) $ \ev -> do let p = eventPath ev rd <- reverseDependencies h cwd p forM_ rd $ \aId -> do logMessage h aId $ "Dirty (" ++ p ++ ")" markDirty h aId atomically $ modifyTVar (state h) (\s -> s { stopFileWatcher = stop }) forever $ threadDelay maxBound detachFileWatcher :: Handle -> IO () detachFileWatcher h = do stop <- atomically $ do st <- readTVar (state h) modifyTVar (state h) (\s -> s { stopFileWatcher = return () }) return $ stopFileWatcher st stop reverseDependencies :: Handle -> FilePath -> FilePath -> IO [AssetId] reverseDependencies h cwd p = do s <- atomically $ readTVar (state h) return $ catMaybes $ (flip map) (M.toList $ assets s) $ \(aId, ars) -> if (S.member p $ S.map (\x -> normalise (cwd </> x)) (arsSources ars)) then Just aId else Nothing
wereHamster/mole
src/Data/Mole/Watcher.hs
mit
1,680
0
26
548
537
275
262
42
2
module GitHub ( Client , newClient , Request , request , httpRequest , fetch , fetchJSON , fetchSingle , fetchAll , User(..) , Repository(..) , fetchRepos , fetchRepo , repoNWO , Organization(..) , fetchOrgs , fetchOrgRepos , MilestoneFilter(..) , StateFilter(..) , IssueState(..) , Issue(..) , fetchIssue , fetchIssues , MilestoneState(..) , Milestone(..) , fetchMilestone , fetchMilestones ) where import ClassyPrelude import Control.Monad.Trans.Resource import Data.Aeson import Data.Attoparsec.ByteString.Char8 import Data.Conduit import Data.Conduit.Attoparsec import Data.Default import qualified Network.HTTP.Conduit as HTTP import Network.HTTP.Types data Client = Client { getToken :: Text , getManager :: HTTP.Manager } data Request = Request { path :: Text , parameters :: [Text] , client :: Client } instance Show Request where show req = "Request \"" ++ show (path req) ++ "\" " ++ show (parameters req) -- Creates a request to the given path. request :: Client -> Text -> Request request client path = Request { path = path , parameters = [] , client = client } -- Adds required GitHub headers to any request. decorateHttpRequest :: Client -> HTTP.Request -> HTTP.Request decorateHttpRequest client req = let token = getToken client in req { HTTP.requestHeaders = [ ("User-Agent", "ScrumBut") , ("Authorization", "token " ++ encodeUtf8 token) ] } -- Creates a Conduit HTTP request for a GitHub resource. httpRequest :: Request -> HTTP.Request httpRequest req = let params = "per_page=100" : parameters req in decorateHttpRequest (client req) $ def { HTTP.method = methodGet , HTTP.secure = True , HTTP.host = "api.github.com" , HTTP.port = 443 , HTTP.path = encodeUtf8 $ path req , HTTP.queryString = encodeUtf8 $ intercalate "&" params } -- Sends a request and streams the results. fetch :: MonadResource m => HTTP.Request -> Client -> m (HTTP.Response (ResumableSource m ByteString)) fetch req client = HTTP.http req $ getManager client -- Sends a request, returning the response as a parsed JSON value. fetchJSON :: (MonadResource m, FromJSON a) => HTTP.Request -> Client -> m (HTTP.Response a) fetchJSON req client = do response <- fetch req client value <- HTTP.responseBody response $$+- sinkParser json case fromJSON value of Success a -> return $ fmap (const a) response Error str -> fail str data Link = Link { linkRelation :: Text , linkUrl :: String } deriving (Eq, Show) link :: Parser Link link = do skipSpace _ <- char '<' url <- decodeUtf8 <$> takeTill ((==) '>') _ <- char '>' _ <- char ';' skipSpace _ <- string "rel=\"" rel <- decodeUtf8 <$> takeTill ((==) '"') _ <- char '"' return $ Link { linkRelation = rel, linkUrl = unpack url } links :: Parser [Link] links = link `sepBy` (char ',') nextPageUrl :: HTTP.Response body -> Maybe String nextPageUrl response = do linkStrings <- lookup "Link" $ HTTP.responseHeaders response lnks <- either (const Nothing) Just $ parseOnly links linkStrings let isMatch = (==) "next" . linkRelation map linkUrl $ find isMatch lnks -- Sends a request and returns the result as a single JSON value. fetchSingle :: (MonadResource m, FromJSON a) => Request -> m a fetchSingle req = HTTP.responseBody <$> fetchJSON (httpRequest req) (client req) -- Fetches a page of results and all remaining pages thereafter. fetchRemaining :: (MonadResource m, FromJSON a) => HTTP.Request -> Client -> m [a] fetchRemaining req client = do response <- fetchJSON req client let values = HTTP.responseBody response nextUrl = nextPageUrl response >>= HTTP.parseUrl nextRequest = map (decorateHttpRequest client) nextUrl nextValues <- case nextRequest of Just nextRequest' -> fetchRemaining nextRequest' client Nothing -> return [] return $ values ++ nextValues -- Sends a request and returns all pages of results. fetchAll :: (MonadResource m, FromJSON a) => Request -> m [a] fetchAll req = fetchRemaining (httpRequest req) (client req) data User = User { userId :: Integer , userLogin :: Text , userAvatarUrl :: String , userName :: Maybe Text , userHtmlUrl :: String } deriving (Eq, Show) instance FromJSON User where parseJSON (Object v) = User <$> v .: "id" <*> v .: "login" <*> v .: "avatar_url" <*> v .:? "name" <*> v .: "html_url" parseJSON _ = mzero instance Ord User where compare = compare `on` toCaseFold . userLogin data Repository = Repository { repoId :: Integer , repoOwner :: User , repoName :: Text , repoDescription :: Text , repoApiUrl :: String , repoHtmlUrl :: String } deriving (Eq, Show) instance FromJSON Repository where parseJSON (Object v) = Repository <$> v .: "id" <*> v .: "owner" <*> v .: "name" <*> v .:? "description" .!= "" <*> v .: "url" <*> v .: "html_url" parseJSON _ = mzero instance Ord Repository where compare = compare `on` toCaseFold . repoNWO data Organization = Organization { orgId :: Integer , orgLogin :: Text , orgDescription :: Text } deriving (Eq, Show) instance FromJSON Organization where parseJSON (Object v) = Organization <$> v .: "id" <*> v .: "login" <*> v .:? "description" .!= "" parseJSON _ = mzero instance Ord Organization where compare = compare `on` toCaseFold . orgLogin data IssueState = IssueOpen | IssueClosed deriving (Eq, Show, Ord) instance FromJSON IssueState where parseJSON (String "open") = return IssueOpen parseJSON (String "closed") = return IssueClosed parseJSON _ = mzero data Issue = Issue { issueId :: Integer , issueNumber :: Integer , issueTitle :: Text , issueBody :: Text , issueCreator :: User , issueAssignee :: Maybe User , issueState :: IssueState , issueHtmlUrl :: String , issueApiUrl :: String , issueMilestone :: Maybe Milestone } deriving (Eq, Show) instance FromJSON Issue where parseJSON (Object v) = Issue <$> v .: "id" <*> v .: "number" <*> v .: "title" <*> v .:? "body" .!= "" <*> v .: "user" <*> v .:? "assignee" <*> v .: "state" <*> v .: "html_url" <*> v .: "url" <*> v .:? "milestone" parseJSON _ = mzero instance Ord Issue where compare = compare `on` issueNumber data MilestoneState = MilestoneOpen | MilestoneClosed deriving (Eq, Show, Ord) instance FromJSON MilestoneState where parseJSON (String "open") = return MilestoneOpen parseJSON (String "closed") = return MilestoneClosed parseJSON _ = mzero data Milestone = Milestone { milestoneId :: Integer , milestoneTitle :: Text , milestoneDescription :: Text , milestoneApiUrl :: String , milestoneCreator :: User , milestoneState :: MilestoneState } deriving (Eq, Show) instance FromJSON Milestone where parseJSON (Object v) = Milestone <$> v .: "number" <*> v .: "title" <*> v .:? "description" .!= "" <*> v .: "url" <*> v .: "creator" <*> v .: "state" parseJSON _ = mzero instance Ord Milestone where compare = compare `on` toCaseFold . milestoneTitle -- The fully qualified name of a repository. repoNWO :: Repository -> Text repoNWO repo = let ownerLogin = userLogin $ repoOwner repo in ownerLogin ++ "/" ++ repoName repo -- Creates a GitHub client with the given OAuth token. newClient :: MonadIO m => Text -> m Client newClient token = do manager <- liftIO $ HTTP.newManager HTTP.conduitManagerSettings return $ Client { getToken = token, getManager = manager } -- Creates a path relative to the repos/ namespace. repoRelativePath :: Repository -> Text -> Text repoRelativePath repo subpath = "repos/" ++ repoNWO repo ++ "/" ++ subpath -- Fetches repositories of the current user. fetchRepos :: MonadResource m => Client -> m [Repository] fetchRepos client = fetchAll $ request client "user/repos" -- Fetches a repository by NWO. fetchRepo :: MonadResource m => Client -> Text -> Text -> m Repository fetchRepo client ownerLogin name = fetchSingle $ request client $ "repos/" ++ ownerLogin ++ "/" ++ name -- Fetches orgs that the current user is a member of. fetchOrgs :: MonadResource m => Client -> m [Organization] fetchOrgs client = fetchAll $ request client "user/orgs" -- Fetches repositories in the given org. fetchOrgRepos :: MonadResource m => Client -> Organization -> m [Repository] fetchOrgRepos client org = fetchAll $ request client $ "orgs/" ++ orgLogin org ++ "/repos" data MilestoneFilter = AllMilestones | OnlyMilestone Milestone | NoMilestones deriving Eq instance Show MilestoneFilter where show AllMilestones = "milestone=*" show (OnlyMilestone m) = "milestone=" ++ (show $ milestoneId m) show NoMilestones = "milestone=none" data StateFilter = OnlyOpen | OnlyClosed | AllStates deriving Eq instance Show StateFilter where show OnlyOpen = "state=open" show OnlyClosed = "state=closed" show AllStates = "state=all" -- Fetches a single issue from a repository. fetchIssue :: MonadResource m => Client -> Repository -> Integer -> m Issue fetchIssue client repo issueNumber = fetchSingle $ request client $ repoRelativePath repo $ "issues/" ++ pack (show issueNumber) -- Fetches issues in the given repository. fetchIssues :: MonadResource m => Client -> Repository -> StateFilter -> MilestoneFilter -> m [Issue] fetchIssues client repo state milestone = let req = request client $ repoRelativePath repo "issues" in fetchAll $ req { parameters = [ pack $ show milestone, pack $ show state ] } -- Fetches a single milestone from a repository. fetchMilestone :: MonadResource m => Client -> Repository -> Integer -> m Milestone fetchMilestone client repo milestoneId = fetchSingle $ request client $ repoRelativePath repo $ "milestones/" ++ pack (show milestoneId) -- Fetches milestones in the given repository. fetchMilestones :: MonadResource m => Client -> Repository -> StateFilter -> m [Milestone] fetchMilestones client repo state = let req = request client $ repoRelativePath repo "milestones" in fetchAll $ req { parameters = [ pack $ show state ] }
jspahrsummers/ScrumBut
GitHub.hs
mit
11,519
0
26
3,480
3,037
1,600
1,437
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DeriveDataTypeable #-} --------------------------------------------------------- -- -- Module : Yesod.Handler -- Copyright : Michael Snoyman -- License : BSD3 -- -- Maintainer : Michael Snoyman <[email protected]> -- Stability : stable -- Portability : portable -- -- Define Handler stuff. -- --------------------------------------------------------- module Yesod.Core.Handler ( -- * Handler monad HandlerT -- ** Read information from handler , getYesod , getsYesod , getUrlRender , getUrlRenderParams , getCurrentRoute , getRequest , waiRequest , runRequestBody , rawRequestBody -- ** Request information -- *** Request datatype , RequestBodyContents , YesodRequest (..) , FileInfo , fileName , fileContentType , fileSource , fileMove -- *** Convenience functions , languages -- *** Lookup parameters , lookupGetParam , lookupPostParam , lookupCookie , lookupFile , lookupHeader -- **** Lookup authentication data , lookupBasicAuth , lookupBearerAuth -- **** Multi-lookup , lookupGetParams , lookupPostParams , lookupCookies , lookupFiles , lookupHeaders -- * Responses -- ** Pure , respond -- ** Streaming , respondSource , sendChunk , sendFlush , sendChunkBS , sendChunkLBS , sendChunkText , sendChunkLazyText , sendChunkHtml -- ** Redirecting , RedirectUrl (..) , redirect , redirectWith , redirectToPost , Fragment(..) -- ** Errors , notFound , badMethod , notAuthenticated , permissionDenied , permissionDeniedI , invalidArgs , invalidArgsI -- ** Short-circuit responses. , sendFile , sendFilePart , sendResponse , sendResponseStatus -- ** Type specific response with custom status , sendStatusJSON , sendResponseCreated , sendWaiResponse , sendWaiApplication , sendRawResponse , sendRawResponseNoConduit , notModified -- * Different representations -- $representations , selectRep , provideRep , provideRepType , ProvidedRep -- * Setting headers , setCookie , getExpires , deleteCookie , addHeader , setHeader , setLanguage -- ** Content caching and expiration , cacheSeconds , neverExpires , alreadyExpired , expiresAt , setEtag -- * Session , SessionMap , lookupSession , lookupSessionBS , getSession , setSession , setSessionBS , deleteSession , clearSession -- ** Ultimate destination , setUltDest , setUltDestCurrent , setUltDestReferer , redirectUltDest , clearUltDest -- ** Messages , addMessage , addMessageI , getMessages , setMessage , setMessageI , getMessage -- * Helpers for specific content -- ** Hamlet , hamletToRepHtml , giveUrlRenderer , withUrlRenderer -- ** Misc , newIdent -- * Lifting , handlerToIO , forkHandler -- * i18n , getMessageRender -- * Per-request caching , cached , cachedBy , stripHandlerT -- * AJAX CSRF protection -- $ajaxCSRFOverview -- ** Setting CSRF Cookies , setCsrfCookie , setCsrfCookieWithCookie , defaultCsrfCookieName -- ** Looking up CSRF Headers , checkCsrfHeaderNamed , hasValidCsrfHeaderNamed , defaultCsrfHeaderName -- ** Looking up CSRF POST Parameters , hasValidCsrfParamNamed , checkCsrfParamNamed , defaultCsrfParamName -- ** Checking CSRF Headers or POST Parameters , checkCsrfHeaderOrParam ) where import Data.Time (UTCTime, addUTCTime, getCurrentTime) import Yesod.Core.Internal.Request (langKey, mkFileInfoFile, mkFileInfoLBS, mkFileInfoSource) #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) import Data.Monoid (mempty, mappend) #endif import Control.Applicative ((<|>)) import Control.Exception (evaluate, SomeException, throwIO) import Control.Exception.Lifted (handle) import Control.Monad (void, liftM, unless) import qualified Control.Monad.Trans.Writer as Writer import Control.Monad.IO.Class (MonadIO, liftIO) import qualified Network.HTTP.Types as H import qualified Network.Wai as W import Network.Wai.Middleware.HttpAuth ( extractBasicAuth, extractBearerAuth ) import Control.Monad.Trans.Class (lift) import Data.Aeson (ToJSON(..)) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With, encodeUtf8) import Data.Text.Encoding.Error (lenientDecode) import qualified Data.Text.Lazy as TL import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import Text.Hamlet (Html, HtmlUrl, hamlet) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.Map as Map import qualified Data.HashMap.Strict as HM import Data.Byteable (constEqBytes) import Control.Arrow ((***)) import qualified Data.ByteString.Char8 as S8 import Data.Monoid (Endo (..)) import Data.Text (Text) import qualified Network.Wai.Parse as NWP import Text.Shakespeare.I18N (RenderMessage (..)) import Web.Cookie (SetCookie (..)) import Yesod.Core.Content (ToTypedContent (..), simpleContentType, contentTypeTypes, HasContentType (..), ToContent (..), ToFlushBuilder (..)) import Yesod.Core.Internal.Util (formatRFC1123) import Text.Blaze.Html (preEscapedToHtml, toHtml) import qualified Data.IORef.Lifted as I import Data.Maybe (listToMaybe, mapMaybe) import Data.Typeable (Typeable) import Web.PathPieces (PathPiece(..)) import Yesod.Core.Class.Handler import Yesod.Core.Types import Yesod.Routes.Class (Route) import Blaze.ByteString.Builder (Builder) import Safe (headMay) import Data.CaseInsensitive (CI) import qualified Data.Conduit.List as CL import Control.Monad.Trans.Resource (MonadResource, InternalState, runResourceT, withInternalState, getInternalState, liftResourceT, resourceForkIO) import qualified System.PosixCompat.Files as PC import Control.Monad.Trans.Control (control, MonadBaseControl) import Data.Conduit (Source, transPipe, Flush (Flush), yield, Producer, Sink) import qualified Yesod.Core.TypeCache as Cache import qualified Data.Word8 as W8 import qualified Data.Foldable as Fold import Data.Default import Control.Monad.Logger (MonadLogger, logWarnS) get :: MonadHandler m => m GHState get = liftHandlerT $ HandlerT $ I.readIORef . handlerState put :: MonadHandler m => GHState -> m () put x = liftHandlerT $ HandlerT $ flip I.writeIORef x . handlerState modify :: MonadHandler m => (GHState -> GHState) -> m () modify f = liftHandlerT $ HandlerT $ flip I.modifyIORef f . handlerState tell :: MonadHandler m => Endo [Header] -> m () tell hs = modify $ \g -> g { ghsHeaders = ghsHeaders g `mappend` hs } handlerError :: MonadHandler m => HandlerContents -> m a handlerError = liftIO . throwIO hcError :: MonadHandler m => ErrorResponse -> m a hcError = handlerError . HCError getRequest :: MonadHandler m => m YesodRequest getRequest = liftHandlerT $ HandlerT $ return . handlerRequest runRequestBody :: MonadHandler m => m RequestBodyContents runRequestBody = do HandlerData { handlerEnv = RunHandlerEnv {..} , handlerRequest = req } <- liftHandlerT $ HandlerT return let len = W.requestBodyLength $ reqWaiRequest req upload = rheUpload len x <- get case ghsRBC x of Just rbc -> return rbc Nothing -> do rr <- waiRequest internalState <- liftResourceT getInternalState rbc <- liftIO $ rbHelper upload rr internalState put x { ghsRBC = Just rbc } return rbc rbHelper :: FileUpload -> W.Request -> InternalState -> IO RequestBodyContents rbHelper upload req internalState = case upload of FileUploadMemory s -> rbHelper' s mkFileInfoLBS req FileUploadDisk s -> rbHelper' (s internalState) mkFileInfoFile req FileUploadSource s -> rbHelper' s mkFileInfoSource req rbHelper' :: NWP.BackEnd x -> (Text -> Text -> x -> FileInfo) -> W.Request -> IO ([(Text, Text)], [(Text, FileInfo)]) rbHelper' backend mkFI req = (map fix1 *** mapMaybe fix2) <$> NWP.parseRequestBody backend req where fix1 = go *** go fix2 (x, NWP.FileInfo a' b c) | S.null a = Nothing | otherwise = Just (go x, mkFI (go a) (go b) c) where a | S.length a' < 2 = a' | S8.head a' == '"' && S8.last a' == '"' = S.tail $ S.init a' | S8.head a' == '\'' && S8.last a' == '\'' = S.tail $ S.init a' | otherwise = a' go = decodeUtf8With lenientDecode askHandlerEnv :: MonadHandler m => m (RunHandlerEnv (HandlerSite m)) askHandlerEnv = liftHandlerT $ HandlerT $ return . handlerEnv -- | Get the master site application argument. getYesod :: MonadHandler m => m (HandlerSite m) getYesod = rheSite <$> askHandlerEnv -- | Get a specific component of the master site application argument. -- Analogous to the 'gets' function for operating on 'StateT'. getsYesod :: MonadHandler m => (HandlerSite m -> a) -> m a getsYesod f = (f . rheSite) <$> askHandlerEnv -- | Get the URL rendering function. getUrlRender :: MonadHandler m => m (Route (HandlerSite m) -> Text) getUrlRender = do x <- rheRender <$> askHandlerEnv return $ flip x [] -- | The URL rendering function with query-string parameters. getUrlRenderParams :: MonadHandler m => m (Route (HandlerSite m) -> [(Text, Text)] -> Text) getUrlRenderParams = rheRender <$> askHandlerEnv -- | Get the route requested by the user. If this is a 404 response- where the -- user requested an invalid route- this function will return 'Nothing'. getCurrentRoute :: MonadHandler m => m (Maybe (Route (HandlerSite m))) getCurrentRoute = rheRoute <$> askHandlerEnv -- | Returns a function that runs 'HandlerT' actions inside @IO@. -- -- Sometimes you want to run an inner 'HandlerT' action outside -- the control flow of an HTTP request (on the outer 'HandlerT' -- action). For example, you may want to spawn a new thread: -- -- @ -- getFooR :: Handler RepHtml -- getFooR = do -- runInnerHandler <- handlerToIO -- liftIO $ forkIO $ runInnerHandler $ do -- /Code here runs inside GHandler but on a new thread./ -- /This is the inner GHandler./ -- ... -- /Code here runs inside the request's control flow./ -- /This is the outer GHandler./ -- ... -- @ -- -- Another use case for this function is creating a stream of -- server-sent events using 'GHandler' actions (see -- @yesod-eventsource@). -- -- Most of the environment from the outer 'GHandler' is preserved -- on the inner 'GHandler', however: -- -- * The request body is cleared (otherwise it would be very -- difficult to prevent huge memory leaks). -- -- * The cache is cleared (see 'CacheKey'). -- -- Changes to the response made inside the inner 'GHandler' are -- ignored (e.g., session variables, cookies, response headers). -- This allows the inner 'GHandler' to outlive the outer -- 'GHandler' (e.g., on the @forkIO@ example above, a response -- may be sent to the client without killing the new thread). handlerToIO :: (MonadIO m1, MonadIO m2) => HandlerT site m1 (HandlerT site IO a -> m2 a) handlerToIO = HandlerT $ \oldHandlerData -> do -- Take just the bits we need from oldHandlerData. let newReq = oldReq { reqWaiRequest = newWaiReq } where oldReq = handlerRequest oldHandlerData oldWaiReq = reqWaiRequest oldReq newWaiReq = oldWaiReq { W.requestBody = return mempty , W.requestBodyLength = W.KnownLength 0 } oldEnv = handlerEnv oldHandlerData newState <- liftIO $ do oldState <- I.readIORef (handlerState oldHandlerData) return $ oldState { ghsRBC = Nothing , ghsIdent = 1 , ghsCache = mempty , ghsCacheBy = mempty , ghsHeaders = mempty } -- xx From this point onwards, no references to oldHandlerData xx liftIO $ evaluate (newReq `seq` oldEnv `seq` newState `seq` ()) -- Return GHandler running function. return $ \(HandlerT f) -> liftIO $ runResourceT $ withInternalState $ \resState -> do -- The state IORef needs to be created here, otherwise it -- will be shared by different invocations of this function. newStateIORef <- liftIO (I.newIORef newState) let newHandlerData = HandlerData { handlerRequest = newReq , handlerEnv = oldEnv , handlerState = newStateIORef , handlerToParent = const () , handlerResource = resState } liftIO (f newHandlerData) -- | forkIO for a Handler (run an action in the background) -- -- Uses 'handlerToIO', liftResourceT, and resourceForkIO -- for correctness and efficiency -- -- Since 1.2.8 forkHandler :: (SomeException -> HandlerT site IO ()) -- ^ error handler -> HandlerT site IO () -> HandlerT site IO () forkHandler onErr handler = do yesRunner <- handlerToIO void $ liftResourceT $ resourceForkIO $ yesRunner $ handle onErr handler -- | Redirect to the given route. -- HTTP status code 303 for HTTP 1.1 clients and 302 for HTTP 1.0 -- This is the appropriate choice for a get-following-post -- technique, which should be the usual use case. -- -- If you want direct control of the final status code, or need a different -- status code, please use 'redirectWith'. redirect :: (MonadHandler m, RedirectUrl (HandlerSite m) url) => url -> m a redirect url = do req <- waiRequest let status = if W.httpVersion req == H.http11 then H.status303 else H.status302 redirectWith status url -- | Redirect to the given URL with the specified status code. redirectWith :: (MonadHandler m, RedirectUrl (HandlerSite m) url) => H.Status -> url -> m a redirectWith status url = do urlText <- toTextUrl url handlerError $ HCRedirect status urlText ultDestKey :: Text ultDestKey = "_ULT" -- | Sets the ultimate destination variable to the given route. -- -- An ultimate destination is stored in the user session and can be loaded -- later by 'redirectUltDest'. setUltDest :: (MonadHandler m, RedirectUrl (HandlerSite m) url) => url -> m () setUltDest url = do urlText <- toTextUrl url setSession ultDestKey urlText -- | Same as 'setUltDest', but uses the current page. -- -- If this is a 404 handler, there is no current page, and then this call does -- nothing. setUltDestCurrent :: MonadHandler m => m () setUltDestCurrent = do route <- getCurrentRoute case route of Nothing -> return () Just r -> do gets' <- reqGetParams <$> getRequest setUltDest (r, gets') -- | Sets the ultimate destination to the referer request header, if present. -- -- This function will not overwrite an existing ultdest. setUltDestReferer :: MonadHandler m => m () setUltDestReferer = do mdest <- lookupSession ultDestKey maybe (waiRequest >>= maybe (return ()) setUltDestBS . lookup "referer" . W.requestHeaders) (const $ return ()) mdest where setUltDestBS = setUltDest . T.pack . S8.unpack -- | Redirect to the ultimate destination in the user's session. Clear the -- value from the session. -- -- The ultimate destination is set with 'setUltDest'. -- -- This function uses 'redirect', and thus will perform a temporary redirect to -- a GET request. redirectUltDest :: (RedirectUrl (HandlerSite m) url, MonadHandler m) => url -- ^ default destination if nothing in session -> m a redirectUltDest defaultDestination = do mdest <- lookupSession ultDestKey deleteSession ultDestKey maybe (redirect defaultDestination) redirect mdest -- | Remove a previously set ultimate destination. See 'setUltDest'. clearUltDest :: MonadHandler m => m () clearUltDest = deleteSession ultDestKey msgKey :: Text msgKey = "_MSG" -- | Adds a status and message in the user's session. -- -- See 'getMessages'. -- -- @since 1.4.20 addMessage :: MonadHandler m => Text -- ^ status -> Html -- ^ message -> m () addMessage status msg = do val <- lookupSessionBS msgKey setSessionBS msgKey $ addMsg val where addMsg = maybe msg' (S.append msg' . S.cons W8._nul) msg' = S.append (encodeUtf8 status) (W8._nul `S.cons` L.toStrict (renderHtml msg)) -- | Adds a message in the user's session but uses RenderMessage to allow for i18n -- -- See 'getMessages'. -- -- @since 1.4.20 addMessageI :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => Text -> msg -> m () addMessageI status msg = do mr <- getMessageRender addMessage status $ toHtml $ mr msg -- | Gets all messages in the user's session, and then clears the variable. -- -- See 'addMessage'. -- -- @since 1.4.20 getMessages :: MonadHandler m => m [(Text, Html)] getMessages = do bs <- lookupSessionBS msgKey let ms = maybe [] enlist bs deleteSession msgKey return ms where enlist = pairup . S.split W8._nul pairup [] = [] pairup [_] = [] pairup (s:v:xs) = (decode s, preEscapedToHtml (decode v)) : pairup xs decode = decodeUtf8With lenientDecode -- | Calls 'addMessage' with an empty status setMessage :: MonadHandler m => Html -> m () setMessage = addMessage "" -- | Calls 'addMessageI' with an empty status setMessageI :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => msg -> m () setMessageI = addMessageI "" -- | Gets just the last message in the user's session, -- discards the rest and the status getMessage :: MonadHandler m => m (Maybe Html) getMessage = fmap (fmap snd . headMay) getMessages -- | Bypass remaining handler code and output the given file. -- -- For some backends, this is more efficient than reading in the file to -- memory, since they can optimize file sending via a system call to sendfile. sendFile :: MonadHandler m => ContentType -> FilePath -> m a sendFile ct fp = handlerError $ HCSendFile ct fp Nothing -- | Same as 'sendFile', but only sends part of a file. sendFilePart :: MonadHandler m => ContentType -> FilePath -> Integer -- ^ offset -> Integer -- ^ count -> m a sendFilePart ct fp off count = do fs <- liftIO $ PC.getFileStatus fp handlerError $ HCSendFile ct fp $ Just W.FilePart { W.filePartOffset = off , W.filePartByteCount = count , W.filePartFileSize = fromIntegral $ PC.fileSize fs } -- | Bypass remaining handler code and output the given content with a 200 -- status code. sendResponse :: (MonadHandler m, ToTypedContent c) => c -> m a sendResponse = handlerError . HCContent H.status200 . toTypedContent -- | Bypass remaining handler code and output the given content with the given -- status code. sendResponseStatus :: (MonadHandler m, ToTypedContent c) => H.Status -> c -> m a sendResponseStatus s = handlerError . HCContent s . toTypedContent -- | Bypass remaining handler code and output the given JSON with the given -- status code. -- -- Since 1.4.18 sendStatusJSON :: (MonadHandler m, ToJSON c) => H.Status -> c -> m a #if MIN_VERSION_aeson(0, 11, 0) sendStatusJSON s v = sendResponseStatus s (toEncoding v) #else sendStatusJSON s v = sendResponseStatus s (toJSON v) #endif -- | Send a 201 "Created" response with the given route as the Location -- response header. sendResponseCreated :: MonadHandler m => Route (HandlerSite m) -> m a sendResponseCreated url = do r <- getUrlRender handlerError $ HCCreated $ r url -- | Send a 'W.Response'. Please note: this function is rarely -- necessary, and will /disregard/ any changes to response headers and session -- that you have already specified. This function short-circuits. It should be -- considered only for very specific needs. If you are not sure if you need it, -- you don't. sendWaiResponse :: MonadHandler m => W.Response -> m b sendWaiResponse = handlerError . HCWai -- | Switch over to handling the current request with a WAI @Application@. -- -- Since 1.2.17 sendWaiApplication :: MonadHandler m => W.Application -> m b sendWaiApplication = handlerError . HCWaiApp -- | Send a raw response without conduit. This is used for cases such as -- WebSockets. Requires WAI 3.0 or later, and a web server which supports raw -- responses (e.g., Warp). -- -- Since 1.2.16 sendRawResponseNoConduit :: (MonadHandler m, MonadBaseControl IO m) => (IO S8.ByteString -> (S8.ByteString -> IO ()) -> m ()) -> m a sendRawResponseNoConduit raw = control $ \runInIO -> liftIO $ throwIO $ HCWai $ flip W.responseRaw fallback $ \src sink -> void $ runInIO (raw src sink) where fallback = W.responseLBS H.status500 [("Content-Type", "text/plain")] "sendRawResponse: backend does not support raw responses" -- | Send a raw response. This is used for cases such as WebSockets. Requires -- WAI 2.1 or later, and a web server which supports raw responses (e.g., -- Warp). -- -- Since 1.2.7 sendRawResponse :: (MonadHandler m, MonadBaseControl IO m) => (Source IO S8.ByteString -> Sink S8.ByteString IO () -> m ()) -> m a sendRawResponse raw = control $ \runInIO -> liftIO $ throwIO $ HCWai $ flip W.responseRaw fallback $ \src sink -> void $ runInIO $ raw (src' src) (CL.mapM_ sink) where fallback = W.responseLBS H.status500 [("Content-Type", "text/plain")] "sendRawResponse: backend does not support raw responses" src' src = do bs <- liftIO src unless (S.null bs) $ do yield bs src' src -- | Send a 304 not modified response immediately. This is a short-circuiting -- action. -- -- Since 1.4.4 notModified :: MonadHandler m => m a notModified = sendWaiResponse $ W.responseBuilder H.status304 [] mempty -- | Return a 404 not found page. Also denotes no handler available. notFound :: MonadHandler m => m a notFound = hcError NotFound -- | Return a 405 method not supported page. badMethod :: MonadHandler m => m a badMethod = do w <- waiRequest hcError $ BadMethod $ W.requestMethod w -- | Return a 401 status code notAuthenticated :: MonadHandler m => m a notAuthenticated = hcError NotAuthenticated -- | Return a 403 permission denied page. permissionDenied :: MonadHandler m => Text -> m a permissionDenied = hcError . PermissionDenied -- | Return a 403 permission denied page. permissionDeniedI :: (RenderMessage (HandlerSite m) msg, MonadHandler m) => msg -> m a permissionDeniedI msg = do mr <- getMessageRender permissionDenied $ mr msg -- | Return a 400 invalid arguments page. invalidArgs :: MonadHandler m => [Text] -> m a invalidArgs = hcError . InvalidArgs -- | Return a 400 invalid arguments page. invalidArgsI :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => [msg] -> m a invalidArgsI msg = do mr <- getMessageRender invalidArgs $ map mr msg ------- Headers -- | Set the cookie on the client. setCookie :: MonadHandler m => SetCookie -> m () setCookie sc = do addHeaderInternal (DeleteCookie name path) addHeaderInternal (AddCookie sc) where name = setCookieName sc path = maybe "/" id (setCookiePath sc) -- | Helper function for setCookieExpires value getExpires :: MonadIO m => Int -- ^ minutes -> m UTCTime getExpires m = do now <- liftIO getCurrentTime return $ fromIntegral (m * 60) `addUTCTime` now -- | Unset the cookie on the client. -- -- Note: although the value used for key and path is 'Text', you should only -- use ASCII values to be HTTP compliant. deleteCookie :: MonadHandler m => Text -- ^ key -> Text -- ^ path -> m () deleteCookie a = addHeaderInternal . DeleteCookie (encodeUtf8 a) . encodeUtf8 -- | Set the language in the user session. Will show up in 'languages' on the -- next request. setLanguage :: MonadHandler m => Text -> m () setLanguage = setSession langKey -- | Set an arbitrary response header. -- -- Note that, while the data type used here is 'Text', you must provide only -- ASCII value to be HTTP compliant. -- -- Since 1.2.0 addHeader :: MonadHandler m => Text -> Text -> m () addHeader a = addHeaderInternal . Header (encodeUtf8 a) . encodeUtf8 -- | Deprecated synonym for addHeader. setHeader :: MonadHandler m => Text -> Text -> m () setHeader = addHeader {-# DEPRECATED setHeader "Please use addHeader instead" #-} -- | Set the Cache-Control header to indicate this response should be cached -- for the given number of seconds. cacheSeconds :: MonadHandler m => Int -> m () cacheSeconds i = setHeader "Cache-Control" $ T.concat [ "max-age=" , T.pack $ show i , ", public" ] -- | Set the Expires header to some date in 2037. In other words, this content -- is never (realistically) expired. neverExpires :: MonadHandler m => m () neverExpires = do setHeader "Expires" . rheMaxExpires =<< askHandlerEnv cacheSeconds oneYear where oneYear :: Int oneYear = 60 * 60 * 24 * 365 -- | Set an Expires header in the past, meaning this content should not be -- cached. alreadyExpired :: MonadHandler m => m () alreadyExpired = setHeader "Expires" "Thu, 01 Jan 1970 05:05:05 GMT" -- | Set an Expires header to the given date. expiresAt :: MonadHandler m => UTCTime -> m () expiresAt = setHeader "Expires" . formatRFC1123 -- | Check the if-none-match header and, if it matches the given value, return -- a 304 not modified response. Otherwise, set the etag header to the given -- value. -- -- Note that it is the responsibility of the caller to ensure that the provided -- value is a value etag value, no sanity checking is performed by this -- function. -- -- Since 1.4.4 setEtag :: MonadHandler m => Text -> m () setEtag etag = do mmatch <- lookupHeader "if-none-match" let matches = maybe [] parseMatch mmatch if encodeUtf8 etag `elem` matches then notModified else addHeader "etag" $ T.concat ["\"", etag, "\""] -- | Parse an if-none-match field according to the spec. Does not parsing on -- weak matches, which are not supported by setEtag. parseMatch :: S.ByteString -> [S.ByteString] parseMatch = map clean . S.split W8._comma where clean = stripQuotes . fst . S.spanEnd W8.isSpace . S.dropWhile W8.isSpace stripQuotes bs | S.length bs >= 2 && S.head bs == W8._quotedbl && S.last bs == W8._quotedbl = S.init $ S.tail bs | otherwise = bs -- | Set a variable in the user's session. -- -- The session is handled by the clientsession package: it sets an encrypted -- and hashed cookie on the client. This ensures that all data is secure and -- not tampered with. setSession :: MonadHandler m => Text -- ^ key -> Text -- ^ value -> m () setSession k = setSessionBS k . encodeUtf8 -- | Same as 'setSession', but uses binary data for the value. setSessionBS :: MonadHandler m => Text -> S.ByteString -> m () setSessionBS k = modify . modSession . Map.insert k -- | Unsets a session variable. See 'setSession'. deleteSession :: MonadHandler m => Text -> m () deleteSession = modify . modSession . Map.delete -- | Clear all session variables. -- -- Since: 1.0.1 clearSession :: MonadHandler m => m () clearSession = modify $ \x -> x { ghsSession = Map.empty } modSession :: (SessionMap -> SessionMap) -> GHState -> GHState modSession f x = x { ghsSession = f $ ghsSession x } -- | Internal use only, not to be confused with 'setHeader'. addHeaderInternal :: MonadHandler m => Header -> m () addHeaderInternal = tell . Endo . (:) -- | Some value which can be turned into a URL for redirects. class RedirectUrl master a where -- | Converts the value to the URL and a list of query-string parameters. toTextUrl :: (MonadHandler m, HandlerSite m ~ master) => a -> m Text instance RedirectUrl master Text where toTextUrl = return instance RedirectUrl master String where toTextUrl = toTextUrl . T.pack instance RedirectUrl master (Route master) where toTextUrl url = do r <- getUrlRender return $ r url instance (key ~ Text, val ~ Text) => RedirectUrl master (Route master, [(key, val)]) where toTextUrl (url, params) = do r <- getUrlRenderParams return $ r url params instance (key ~ Text, val ~ Text) => RedirectUrl master (Route master, Map.Map key val) where toTextUrl (url, params) = toTextUrl (url, Map.toList params) -- | Add a fragment identifier to a route to be used when -- redirecting. For example: -- -- > redirect (NewsfeedR :#: storyId) -- -- Since 1.2.9. data Fragment a b = a :#: b deriving (Show, Typeable) instance (RedirectUrl master a, PathPiece b) => RedirectUrl master (Fragment a b) where toTextUrl (a :#: b) = (\ua -> T.concat [ua, "#", toPathPiece b]) <$> toTextUrl a -- | Lookup for session data. lookupSession :: MonadHandler m => Text -> m (Maybe Text) lookupSession = (fmap . fmap) (decodeUtf8With lenientDecode) . lookupSessionBS -- | Lookup for session data in binary format. lookupSessionBS :: MonadHandler m => Text -> m (Maybe S.ByteString) lookupSessionBS n = do m <- fmap ghsSession get return $ Map.lookup n m -- | Get all session variables. getSession :: MonadHandler m => m SessionMap getSession = fmap ghsSession get -- | Get a unique identifier. newIdent :: MonadHandler m => m Text newIdent = do x <- get let i' = ghsIdent x + 1 put x { ghsIdent = i' } return $ T.pack $ "hident" ++ show i' -- | Redirect to a POST resource. -- -- This is not technically a redirect; instead, it returns an HTML page with a -- POST form, and some Javascript to automatically submit the form. This can be -- useful when you need to post a plain link somewhere that needs to cause -- changes on the server. redirectToPost :: (MonadHandler m, RedirectUrl (HandlerSite m) url) => url -> m a redirectToPost url = do urlText <- toTextUrl url req <- getRequest withUrlRenderer [hamlet| $newline never $doctype 5 <html> <head> <title>Redirecting... <body onload="document.getElementById('form').submit()"> <form id="form" method="post" action=#{urlText}> $maybe token <- reqToken req <input type=hidden name=#{defaultCsrfParamName} value=#{token}> <noscript> <p>Javascript has been disabled; please click on the button below to be redirected. <input type="submit" value="Continue"> |] >>= sendResponse -- | Wraps the 'Content' generated by 'hamletToContent' in a 'RepHtml'. hamletToRepHtml :: MonadHandler m => HtmlUrl (Route (HandlerSite m)) -> m Html hamletToRepHtml = withUrlRenderer {-# DEPRECATED hamletToRepHtml "Use withUrlRenderer instead" #-} -- | Deprecated synonym for 'withUrlRenderer'. -- -- Since 1.2.0 giveUrlRenderer :: MonadHandler m => ((Route (HandlerSite m) -> [(Text, Text)] -> Text) -> output) -> m output giveUrlRenderer = withUrlRenderer {-# DEPRECATED giveUrlRenderer "Use withUrlRenderer instead" #-} -- | Provide a URL rendering function to the given function and return the -- result. Useful for processing Shakespearean templates. -- -- Since 1.2.20 withUrlRenderer :: MonadHandler m => ((Route (HandlerSite m) -> [(Text, Text)] -> Text) -> output) -> m output withUrlRenderer f = do render <- getUrlRenderParams return $ f render -- | Get the request\'s 'W.Request' value. waiRequest :: MonadHandler m => m W.Request waiRequest = reqWaiRequest <$> getRequest getMessageRender :: (MonadHandler m, RenderMessage (HandlerSite m) message) => m (message -> Text) getMessageRender = do env <- askHandlerEnv l <- reqLangs <$> getRequest return $ renderMessage (rheSite env) l -- | Use a per-request cache to avoid performing the same action multiple times. -- Values are stored by their type, the result of typeOf from Typeable. -- Therefore, you should use different newtype wrappers at each cache site. -- -- For example, yesod-auth uses an un-exported newtype, CachedMaybeAuth and exports functions that utilize it such as maybeAuth. -- This means that another module can create its own newtype wrapper to cache the same type from a different action without any cache conflicts. -- -- See the original announcement: <http://www.yesodweb.com/blog/2013/03/yesod-1-2-cleaner-internals> -- -- Since 1.2.0 cached :: (MonadHandler m, Typeable a) => m a -> m a cached action = do cache <- ghsCache <$> get eres <- Cache.cached cache action case eres of Right res -> return res Left (newCache, res) -> do gs <- get let merged = newCache `HM.union` ghsCache gs put $ gs { ghsCache = merged } return res -- | a per-request cache. just like 'cached'. -- 'cached' can only cache a single value per type. -- 'cachedBy' stores multiple values per type by usage of a ByteString key -- -- 'cached' is ideal to cache an action that has only one value of a type, such as the session's current user -- 'cachedBy' is required if the action has parameters and can return multiple values per type. -- You can turn those parameters into a ByteString cache key. -- For example, caching a lookup of a Link by a token where multiple token lookups might be performed. -- -- Since 1.4.0 cachedBy :: (MonadHandler m, Typeable a) => S.ByteString -> m a -> m a cachedBy k action = do cache <- ghsCacheBy <$> get eres <- Cache.cachedBy cache k action case eres of Right res -> return res Left (newCache, res) -> do gs <- get let merged = newCache `HM.union` ghsCacheBy gs put $ gs { ghsCacheBy = merged } return res -- | Get the list of supported languages supplied by the user. -- -- Languages are determined based on the following three (in descending order -- of preference): -- -- * The _LANG get parameter. -- -- * The _LANG cookie. -- -- * The _LANG user session variable. -- -- * Accept-Language HTTP header. -- -- Yesod will seek the first language from the returned list matched with languages supporting by your application. This language will be used to render i18n templates. -- If a matching language is not found the default language will be used. -- -- This is handled by parseWaiRequest (not exposed). languages :: MonadHandler m => m [Text] languages = do mlang <- lookupSession langKey langs <- reqLangs <$> getRequest return $ maybe id (:) mlang langs lookup' :: Eq a => a -> [(a, b)] -> [b] lookup' a = map snd . filter (\x -> a == fst x) -- | Lookup a request header. -- -- Since 1.2.2 lookupHeader :: MonadHandler m => CI S8.ByteString -> m (Maybe S8.ByteString) lookupHeader = fmap listToMaybe . lookupHeaders -- | Lookup a request header. -- -- Since 1.2.2 lookupHeaders :: MonadHandler m => CI S8.ByteString -> m [S8.ByteString] lookupHeaders key = do req <- waiRequest return $ lookup' key $ W.requestHeaders req -- | Lookup basic authentication data from __Authorization__ header of -- request. Returns user name and password -- -- Since 1.4.9 lookupBasicAuth :: (MonadHandler m) => m (Maybe (Text, Text)) lookupBasicAuth = fmap (>>= getBA) (lookupHeader "Authorization") where getBA bs = (decodeUtf8With lenientDecode *** decodeUtf8With lenientDecode) <$> extractBasicAuth bs -- | Lookup bearer authentication datafrom __Authorization__ header of -- request. Returns bearer token value -- -- Since 1.4.9 lookupBearerAuth :: (MonadHandler m) => m (Maybe Text) lookupBearerAuth = fmap (>>= getBR) (lookupHeader "Authorization") where getBR bs = decodeUtf8With lenientDecode <$> extractBearerAuth bs -- | Lookup for GET parameters. lookupGetParams :: MonadHandler m => Text -> m [Text] lookupGetParams pn = do rr <- getRequest return $ lookup' pn $ reqGetParams rr -- | Lookup for GET parameters. lookupGetParam :: MonadHandler m => Text -> m (Maybe Text) lookupGetParam = fmap listToMaybe . lookupGetParams -- | Lookup for POST parameters. lookupPostParams :: (MonadResource m, MonadHandler m) => Text -> m [Text] lookupPostParams pn = do (pp, _) <- runRequestBody return $ lookup' pn pp lookupPostParam :: (MonadResource m, MonadHandler m) => Text -> m (Maybe Text) lookupPostParam = fmap listToMaybe . lookupPostParams -- | Lookup for POSTed files. lookupFile :: (MonadHandler m, MonadResource m) => Text -> m (Maybe FileInfo) lookupFile = fmap listToMaybe . lookupFiles -- | Lookup for POSTed files. lookupFiles :: (MonadHandler m, MonadResource m) => Text -> m [FileInfo] lookupFiles pn = do (_, files) <- runRequestBody return $ lookup' pn files -- | Lookup for cookie data. lookupCookie :: MonadHandler m => Text -> m (Maybe Text) lookupCookie = fmap listToMaybe . lookupCookies -- | Lookup for cookie data. lookupCookies :: MonadHandler m => Text -> m [Text] lookupCookies pn = do rr <- getRequest return $ lookup' pn $ reqCookies rr -- $representations -- -- HTTP allows content negotation to determine what /representation/ of data -- you would like to use. The most common example of this is providing both a -- user-facing HTML page and an API facing JSON response from the same URL. The -- means of achieving this is the Accept HTTP header, which provides a list of -- content types the client will accept, sorted by preference. -- -- By using 'selectRep' and 'provideRep', you can provide a number of different -- representations, e.g.: -- -- > selectRep $ do -- > provideRep produceHtmlOutput -- > provideRep produceJsonOutput -- -- The first provided representation will be used if no matches are found. -- | Select a representation to send to the client based on the representations -- provided inside this do-block. Should be used together with 'provideRep'. -- -- Since 1.2.0 selectRep :: MonadHandler m => Writer.Writer (Endo [ProvidedRep m]) () -> m TypedContent selectRep w = do -- the content types are already sorted by q values -- which have been stripped cts <- fmap reqAccept getRequest case mapMaybe tryAccept cts of [] -> case reps of [] -> sendResponseStatus H.status500 ("No reps provided to selectRep" :: Text) rep:_ -> if null cts then returnRep rep else sendResponseStatus H.status406 explainUnaccepted rep:_ -> returnRep rep where explainUnaccepted :: Text explainUnaccepted = "no match found for accept header" returnRep (ProvidedRep ct mcontent) = fmap (TypedContent ct) mcontent reps = appEndo (Writer.execWriter w) [] repMap = Map.unions $ map (\v@(ProvidedRep k _) -> Map.fromList [ (k, v) , (noSpace k, v) , (simpleContentType k, v) ]) reps -- match on the type for sub-type wildcards. -- If the accept is text/ * it should match a provided text/html mainTypeMap = Map.fromList $ reverse $ map (\v@(ProvidedRep ct _) -> (fst $ contentTypeTypes ct, v)) reps tryAccept ct = if subType == "*" then if mainType == "*" then headMay reps else Map.lookup mainType mainTypeMap else lookupAccept ct where (mainType, subType) = contentTypeTypes ct lookupAccept ct = Map.lookup ct repMap <|> Map.lookup (noSpace ct) repMap <|> Map.lookup (simpleContentType ct) repMap -- Mime types such as "text/html; charset=foo" get converted to -- "text/html;charset=foo" noSpace = S8.filter (/= ' ') -- | Internal representation of a single provided representation. -- -- Since 1.2.0 data ProvidedRep m = ProvidedRep !ContentType !(m Content) -- | Provide a single representation to be used, based on the request of the -- client. Should be used together with 'selectRep'. -- -- Since 1.2.0 provideRep :: (Monad m, HasContentType a) => m a -> Writer.Writer (Endo [ProvidedRep m]) () provideRep handler = provideRepType (getContentType handler) handler -- | Same as 'provideRep', but instead of determining the content type from the -- type of the value itself, you provide the content type separately. This can -- be a convenience instead of creating newtype wrappers for uncommonly used -- content types. -- -- > provideRepType "application/x-special-format" "This is the content" -- -- Since 1.2.0 provideRepType :: (Monad m, ToContent a) => ContentType -> m a -> Writer.Writer (Endo [ProvidedRep m]) () provideRepType ct handler = Writer.tell $ Endo (ProvidedRep ct (liftM toContent handler):) -- | Stream in the raw request body without any parsing. -- -- Since 1.2.0 rawRequestBody :: MonadHandler m => Source m S.ByteString rawRequestBody = do req <- lift waiRequest let loop = do bs <- liftIO $ W.requestBody req unless (S.null bs) $ do yield bs loop loop -- | Stream the data from the file. Since Yesod 1.2, this has been generalized -- to work in any @MonadResource@. fileSource :: MonadResource m => FileInfo -> Source m S.ByteString fileSource = transPipe liftResourceT . fileSourceRaw -- | Provide a pure value for the response body. -- -- > respond ct = return . TypedContent ct . toContent -- -- Since 1.2.0 respond :: (Monad m, ToContent a) => ContentType -> a -> m TypedContent respond ct = return . TypedContent ct . toContent -- | Use a @Source@ for the response body. -- -- Note that, for ease of use, the underlying monad is a @HandlerT@. This -- implies that you can run any @HandlerT@ action. However, since a streaming -- response occurs after the response headers have already been sent, some -- actions make no sense here. For example: short-circuit responses, setting -- headers, changing status codes, etc. -- -- Since 1.2.0 respondSource :: ContentType -> Source (HandlerT site IO) (Flush Builder) -> HandlerT site IO TypedContent respondSource ctype src = HandlerT $ \hd -> -- Note that this implementation relies on the fact that the ResourceT -- environment provided by the server is the same one used in HandlerT. -- This is a safe assumption assuming the HandlerT is run correctly. return $ TypedContent ctype $ ContentSource $ transPipe (lift . flip unHandlerT hd) src -- | In a streaming response, send a single chunk of data. This function works -- on most datatypes, such as @ByteString@ and @Html@. -- -- Since 1.2.0 sendChunk :: Monad m => ToFlushBuilder a => a -> Producer m (Flush Builder) sendChunk = yield . toFlushBuilder -- | In a streaming response, send a flush command, causing all buffered data -- to be immediately sent to the client. -- -- Since 1.2.0 sendFlush :: Monad m => Producer m (Flush Builder) sendFlush = yield Flush -- | Type-specialized version of 'sendChunk' for strict @ByteString@s. -- -- Since 1.2.0 sendChunkBS :: Monad m => S.ByteString -> Producer m (Flush Builder) sendChunkBS = sendChunk -- | Type-specialized version of 'sendChunk' for lazy @ByteString@s. -- -- Since 1.2.0 sendChunkLBS :: Monad m => L.ByteString -> Producer m (Flush Builder) sendChunkLBS = sendChunk -- | Type-specialized version of 'sendChunk' for strict @Text@s. -- -- Since 1.2.0 sendChunkText :: Monad m => T.Text -> Producer m (Flush Builder) sendChunkText = sendChunk -- | Type-specialized version of 'sendChunk' for lazy @Text@s. -- -- Since 1.2.0 sendChunkLazyText :: Monad m => TL.Text -> Producer m (Flush Builder) sendChunkLazyText = sendChunk -- | Type-specialized version of 'sendChunk' for @Html@s. -- -- Since 1.2.0 sendChunkHtml :: Monad m => Html -> Producer m (Flush Builder) sendChunkHtml = sendChunk -- | Converts a child handler to a parent handler -- -- Exported since 1.4.11 stripHandlerT :: HandlerT child (HandlerT parent m) a -> (parent -> child) -> (Route child -> Route parent) -> Maybe (Route child) -> HandlerT parent m a stripHandlerT (HandlerT f) getSub toMaster newRoute = HandlerT $ \hd -> do let env = handlerEnv hd ($ hd) $ unHandlerT $ f hd { handlerEnv = env { rheSite = getSub $ rheSite env , rheRoute = newRoute , rheRender = \url params -> rheRender env (toMaster url) params } , handlerToParent = toMaster } -- $ajaxCSRFOverview -- When a user has authenticated with your site, all requests made from the browser to your server will include the session information that you use to verify that the user is logged in. -- Unfortunately, this allows attackers to make unwanted requests on behalf of the user by e.g. submitting an HTTP request to your site when the user visits theirs. -- This is known as a <https://en.wikipedia.org/wiki/Cross-site_request_forgery Cross Site Request Forgery> (CSRF) attack. -- -- To combat this attack, you need a way to verify that the request is valid. -- This is achieved by generating a random string ("token"), storing it in your encrypted session so that the server can look it up (see 'reqToken'), and adding the token to HTTP requests made to your server. -- When a request comes in, the token in the request is compared to the one from the encrypted session. If they match, you can be sure the request is valid. -- -- Yesod implements this behavior in two ways: -- -- (1) The yesod-form package <http://www.yesodweb.com/book/forms#forms_running_forms stores the CSRF token in a hidden field> in the form, then validates it with functions like 'Yesod.Form.Functions.runFormPost'. -- -- (2) Yesod can store the CSRF token in a cookie which is accessible by Javascript. Requests made by Javascript can lookup this cookie and add it as a header to requests. The server then checks the token in the header against the one in the encrypted session. -- -- The form-based approach has the advantage of working for users with Javascript disabled, while adding the token to the headers with Javascript allows things like submitting JSON or binary data in AJAX requests. Yesod supports checking for a CSRF token in either the POST parameters of the form ('checkCsrfParamNamed'), the headers ('checkCsrfHeaderNamed'), or both options ('checkCsrfHeaderOrParam'). -- -- The easiest way to check both sources is to add the 'Yesod.Core.defaultCsrfMiddleware' to your Yesod Middleware. -- | The default cookie name for the CSRF token ("XSRF-TOKEN"). -- -- Since 1.4.14 defaultCsrfCookieName :: S8.ByteString defaultCsrfCookieName = "XSRF-TOKEN" -- | Sets a cookie with a CSRF token, using 'defaultCsrfCookieName' for the cookie name. -- -- The cookie's path is set to @/@, making it valid for your whole website. -- -- Since 1.4.14 setCsrfCookie :: MonadHandler m => m () setCsrfCookie = setCsrfCookieWithCookie def { setCookieName = defaultCsrfCookieName, setCookiePath = Just "/" } -- | Takes a 'SetCookie' and overrides its value with a CSRF token, then sets the cookie. -- -- Make sure to set the 'setCookiePath' to the root path of your application, otherwise you'll generate a new CSRF token for every path of your app. If your app is run from from e.g. www.example.com\/app1, use @app1@. The vast majority of sites will just use @/@. -- -- Since 1.4.14 setCsrfCookieWithCookie :: MonadHandler m => SetCookie -> m () setCsrfCookieWithCookie cookie = do mCsrfToken <- reqToken <$> getRequest Fold.forM_ mCsrfToken (\token -> setCookie $ cookie { setCookieValue = encodeUtf8 token }) -- | The default header name for the CSRF token ("X-XSRF-TOKEN"). -- -- Since 1.4.14 defaultCsrfHeaderName :: CI S8.ByteString defaultCsrfHeaderName = "X-XSRF-TOKEN" -- | Takes a header name to lookup a CSRF token. If the value doesn't match the token stored in the session, -- this function throws a 'PermissionDenied' error. -- -- Since 1.4.14 checkCsrfHeaderNamed :: MonadHandler m => CI S8.ByteString -> m () checkCsrfHeaderNamed headerName = do valid <- hasValidCsrfHeaderNamed headerName unless valid (permissionDenied csrfErrorMessage) -- | Takes a header name to lookup a CSRF token, and returns whether the value matches the token stored in the session. -- -- Since 1.4.14 hasValidCsrfHeaderNamed :: MonadHandler m => CI S8.ByteString -> m Bool hasValidCsrfHeaderNamed headerName = do mCsrfToken <- reqToken <$> getRequest mXsrfHeader <- lookupHeader headerName return $ validCsrf mCsrfToken mXsrfHeader -- CSRF Parameter checking -- | The default parameter name for the CSRF token ("_token") -- -- Since 1.4.14 defaultCsrfParamName :: Text defaultCsrfParamName = "_token" -- | Takes a POST parameter name to lookup a CSRF token. If the value doesn't match the token stored in the session, -- this function throws a 'PermissionDenied' error. -- -- Since 1.4.14 checkCsrfParamNamed :: MonadHandler m => Text -> m () checkCsrfParamNamed paramName = do valid <- hasValidCsrfParamNamed paramName unless valid (permissionDenied csrfErrorMessage) -- | Takes a POST parameter name to lookup a CSRF token, and returns whether the value matches the token stored in the session. -- -- Since 1.4.14 hasValidCsrfParamNamed :: MonadHandler m => Text -> m Bool hasValidCsrfParamNamed paramName = do mCsrfToken <- reqToken <$> getRequest mCsrfParam <- lookupPostParam paramName return $ validCsrf mCsrfToken (encodeUtf8 <$> mCsrfParam) -- | Checks that a valid CSRF token is present in either the request headers or POST parameters. -- If the value doesn't match the token stored in the session, this function throws a 'PermissionDenied' error. -- -- Since 1.4.14 checkCsrfHeaderOrParam :: (MonadHandler m, MonadLogger m) => CI S8.ByteString -- ^ The header name to lookup the CSRF token -> Text -- ^ The POST parameter name to lookup the CSRF token -> m () checkCsrfHeaderOrParam headerName paramName = do validHeader <- hasValidCsrfHeaderNamed headerName validParam <- hasValidCsrfParamNamed paramName unless (validHeader || validParam) $ do $logWarnS "yesod-core" csrfErrorMessage permissionDenied csrfErrorMessage validCsrf :: Maybe Text -> Maybe S.ByteString -> Bool -- It's important to use constant-time comparison (constEqBytes) in order to avoid timing attacks. validCsrf (Just token) (Just param) = encodeUtf8 token `constEqBytes` param validCsrf Nothing _param = True validCsrf (Just _token) Nothing = False csrfErrorMessage :: Text csrfErrorMessage = "A valid CSRF token wasn't present in HTTP headers or POST parameters. Because the request could have been forged, it's been rejected altogether. Check the Yesod.Core.Handler docs of the yesod-core package for details on CSRF protection."
tolysz/yesod
yesod-core/Yesod/Core/Handler.hs
mit
52,926
0
21
12,831
10,173
5,458
4,715
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE CPP #-} module Text.Namelist.Parser (namelist) where import Text.Parsec hiding (letter) import Data.Complex(Complex((:+))) import Data.Char (toUpper, toLower, isDigit) import Data.CaseInsensitive (CI, mk) #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>), (<$), (<*>), (<*), (*>), pure) #endif import Text.Namelist.Types isLetter :: Char -> Bool isLetter i | '\97' <= i && i <= '\122' = True | '\65' <= i && i <= '\90' = True | otherwise = False letter :: Stream s m Char => ParsecT s u m Char letter = satisfy isLetter <?> "letter" isAlphaNumeric :: Char -> Bool isAlphaNumeric a = isLetter a || isDigit a || a == '_' alphanumericCharacter :: Stream s m Char => ParsecT s u m Char alphanumericCharacter = satisfy isAlphaNumeric <?> "alphanumeric-character" name :: Stream s m Char => ParsecT s u m (CI String) name = do n <- (:) <$> letter <*> many alphanumericCharacter <?> "name" if length n > 31 then fail "name too long" else return $ mk n sign :: (Stream s m Char, Num a) => ParsecT s u m (a -> a) sign = (id <$ char '+') <|> (negate <$ char '-') <?> "sign" fDigit :: Stream s m Char => ParsecT s u m Int fDigit = (-) <$> (fromEnum <$> digit) <*> pure 48 <?> "digit" unsignedInteger :: Stream s m Char => ParsecT s u m Int unsignedInteger = chainl1 fDigit (pure $ \s d -> 10 * s + d) integerLiteral :: Stream s m Char => ParsecT s u m Int integerLiteral = ($) <$> option id sign <*> unsignedInteger <?> "integer" exponentialPart :: Stream s m Char => ParsecT s u m Int exponentialPart = oneOf "eEdDqQ" *> integerLiteral realExpLiteral :: Stream s m Char => ParsecT s u m Double realExpLiteral = do s <- option id sign i <- fromIntegral <$> unsignedInteger e <- fromIntegral <$> exponentialPart return $ s (i * 10 ** e) realDotLiteral :: Stream s m Char => ParsecT s u m Double realDotLiteral = do sgn <- option id sign mbi <- optionMaybe unsignedInteger _ <- char '.' (f, e) <- chainl ((,) <$> (fromIntegral <$> fDigit) <*> pure 1) (pure $ \(s, n) (d, _) -> (10 * s + d, n + 1)) (0 :: Integer,0) e2 <- option 0 exponentialPart i <- case mbi of Nothing | e == 0 -> fail "either decimal and floating part are missing" | otherwise -> return 0 Just i -> return i return $ sgn $ fromIntegral (fromIntegral i * 10 ^ e + f) / 10 ** (fromIntegral $ e - e2) realLiteral :: Stream s m Char => ParsecT s u m Double realLiteral = try realExpLiteral <|> realDotLiteral tokenize :: Stream s m Char => ParsecT s u m a -> ParsecT s u m a tokenize p = spaces *> p <* spaces complexLiteral :: Stream s m Char => ParsecT s u m (Complex Double) complexLiteral = (:+) <$> (char '(' *> tokenize realLiteral) <*> (char ',' *> tokenize realLiteral <* char ')') ciString :: Stream s m Char => String -> ParsecT s u m String ciString [] = return [] ciString (a:as) = (:) <$> oneOf [toUpper a, toLower a] <*> ciString as shortLogicalLiteral :: Stream s m Char => ParsecT s u m Bool shortLogicalLiteral = choice [ True <$ (char 'T' <|> char 't') , False <$ (char 'F' <|> char 'f') ] <* lookAhead (satisfy $ not . isAlphaNumeric) longLogicalLiteral :: Stream s m Char => ParsecT s u m Bool longLogicalLiteral = char '.' *> choice [ True <$ ciString "true." , False <$ ciString "false." ] logicalLiteral :: Stream s m Char => ParsecT s u m Bool logicalLiteral = shortLogicalLiteral <|> longLogicalLiteral stringLiteral :: Stream s m Char => ParsecT s u m String stringLiteral = sl '\'' <|> sl '"' where sl s = char s *> many (body s) <* char s body s = try (s <$ char s *> char s) <|> noneOf [s] literal :: Stream s m Char => ParsecT s u m Value literal = choice [ try mulValue , try mulNull , try $ Real <$> realLiteral , Integer <$> integerLiteral , Complex <$> complexLiteral , try $ Logical <$> logicalLiteral , String <$> stringLiteral ] mulNull :: Stream s m Char => ParsecT s u m Value mulNull = (:* Null) <$> unsignedInteger <* char '*' mulValue :: Stream s m Char => ParsecT s u m Value mulValue = (:*) <$> unsignedInteger <*> (char '*' *> literal) index :: Stream s m Char => ParsecT s u m Index index = choice [ try $ Range <$> optionMaybe u <*> s (optionMaybe u) <*> s (optionMaybe i) , try $ Range <$> optionMaybe u <*> s (optionMaybe u) <*> pure Nothing , try $ Index <$> u ] <?> "index" where u = tokenize unsignedInteger i = tokenize integerLiteral s = (char ':' *>) key :: Stream s m Char => ParsecT s u m Key key = choice [ try $ Indexed <$> name <*> (char '(' *> sepBy1 index (char ',') <* char ')') , try $ Sub <$> name <*> (char '%' *> key) , try $ Key <$> name ] <?> "key" keyVal :: Stream s m Char => ParsecT s u m Pair keyVal = do k <- key _ <- tokenize $ char '=' v <- tokenize (literal <|> pure Null) `sepEndBy` tokenize (char ',') return $ k := case reverse v of [a] -> a [Null,a] -> a Null:Null:as -> Array (reverse $ Null:as) Null:as -> Array (reverse as) as -> Array (reverse as) group :: Stream s m Char => ParsecT s u m Group group = Group <$> tokenize (char '&' *> name) <*> many keyVal <* tokenize (char '/') namelist :: Stream s m Char => ParsecT s u m [Group] namelist = many group
philopon/namelist-hs
src/Text/Namelist/Parser.hs
mit
5,464
0
15
1,401
2,300
1,157
1,143
124
5
#!/usr/bin/env runhaskell import Data.List (intercalate) import Text.Printf (printf) type Interval = (Double, Double) type Subdivisions = Double type Function = Double -> Double type Polynomial = Function type Spline = [(Interval, Polynomial)] delta = 0.1 :: Double pairs :: [a] -> [(a,a)] pairs xs = zip xs (drop 1 xs) uniform :: Interval -> Subdivisions -> [Interval] uniform (a,b) n = pairs $ map (\i -> a + (b-a)*(i-1)/n) [1..n+1] mesh :: Interval -> [Double] mesh (a,b) = [a,a+delta..b] ddx :: Function -> Function ddx f = \x -> (f(x+h)-f(x-h))/(2*h) where h = 1e-9 bb :: Interval -> (Function, Function) bb (a,b) = (\t -> (b-t)/h, \t -> (t-a)/h) where h = b-a type Scheme = Function -> Interval -> Polynomial hermiteCubic :: Scheme hermiteCubic f (a,b) = let (b0,b1) = bb (a,b) f' = ddx f h = b - a c30 = f(a) c21 = c30 + (h/3) * f'(a) c03 = f(b) c12 = c03 - (h/3) * f'(b) in \t -> c30 * b0(t)**3 + 3 * c21 * b0(t)**2 * b1(t) + 3 * c12 * b0(t) * b1(t)**2 + c03 * b1(t)**3 hermiteQuadratic :: Scheme hermiteQuadratic f (a,b) = let m = (a+b)/2 (b0,b1) = bb (a,m) (b0',b1') = bb (m,b) f' = ddx f h = b-a c20 = f(a) c02' = f(b) c11 = c20 + (h/4)*f'(a) c11' = c02' - (h/4)*f'(b) c02 = (c11+c11')/2 c20'= c02 in \t -> if t < m then c20 * b0(t)**2 + 2 * c11 * b0(t) * b1(t) + c02 * b1(t)**2 else c20' * b0'(t)**2 + 2 * c11' * b0'(t) * b1'(t) + c02' * b1'(t)**2 spline :: Function -> Interval -> Subdivisions -> Scheme -> Spline spline f i n s = map (\h -> (h, g h)) (uniform i n) where g = s f data Row = Row Double Double Double -- x, f(x), s(x) eval :: Function -> Spline -> [Row] eval f s = concatMap g s where g (i, p) = map (\x -> Row x (f x) (p x)) (mesh i) pr (Row x fx sx) = printf "%.5f \t%.5f \t%.5f\n" x fx sx main = do let f x = 1 / (1 + x**2) interval = (-5,5) n = 10 putStrLn "hermite quadratic:" putStrLn "x \t\tf(x)\t\t s(x)" let quadratic = spline f interval n hermiteQuadratic mapM_ pr (eval f quadratic) putStrLn "hermite cubic:" putStrLn "x \t\tf(x)\t\t s(x)" let cubic = spline f interval n hermiteCubic mapM_ pr (eval f cubic)
ergenekonyigit/Numerical-Analysis-Examples
Haskell/SplineInterpolation.hs
mit
3,027
0
24
1,396
1,319
703
616
69
2
module Text.Typeical.Writers.BNF (showBNF, showTerm, writeBNF, writeTerm, showSymbol) where import Text.Typeical.Gramma import Data.Bifunctor; import Data.Maybe; import Data.List; import Data.List.Split hiding (oneOf); import Control.Monad; import qualified Data.Map as M; writeBNF :: Gramma -> String writeBNF = flip showBNF "" showBNF :: Gramma -> ShowS showBNF bnf ss = M.foldrWithKey f ss (asMap bnf) where f :: Symbol -> Expression -> ShowS f key value = showSymbol key . showString " ::= " . expression value . showString "\n" expression = showIList " | " . map showTerm showSymbol :: Symbol -> ShowS showSymbol key = showChar '<' . showString (symbolName key) . showChar '>' writeTerm :: Term -> String writeTerm = flip showTerm "" showTerm :: Term -> ShowS showTerm = showIList " " . map showToken showToken :: Token -> ShowS showToken (Ref (Symbol x)) = showChar '<' . showString x . showChar '>' showToken (Const str) = showChar '"' . showString (replace "\"" "\\\"" str) . showChar '"' showIList :: String -> [ShowS] -> ShowS showIList str ts = foldr (.) id $ intersperse (showString str) ts -- From Data.String.Utils, MissingH edited to use spiltOn replace :: Eq a => [a] -> [a] -> [a] -> [a] replace old new = intercalate new . splitOn old
kalhauge/typeical
src/Text/Typeical/Writers/BNF.hs
mit
1,528
0
10
481
469
247
222
35
1
{-# LANGUAGE OverloadedStrings #-} module Network.ConcurrencySpec where import Test.Hspec import qualified Network.Freddy as Freddy import qualified Network.Freddy.Request as R import Control.Concurrent.Async (forConcurrently) import System.Timeout (timeout) import Data.Maybe (isJust) import SpecHelper ( randomQueueName, requestBody, withConnection, delayedResponder ) spec :: Spec spec = around withConnection $ describe "Concurrency" $ do let buildRequest queueName = R.newReq { R.queueName = queueName, R.body = requestBody } it "runs responder in parallel" $ \connection -> do let deliveryCount = 4 let responderDelayIsMs = 50 let minSequentialRespondTimeInMs = deliveryCount * responderDelayIsMs let maxParallelRespondTimeInMs = minSequentialRespondTimeInMs - responderDelayIsMs queueName <- randomQueueName Freddy.respondTo connection queueName $ delayedResponder responderDelayIsMs result <- timeout (maxParallelRespondTimeInMs * 1000) $ forConcurrently (replicate deliveryCount Nothing) $ \_ -> Freddy.deliverWithResponse connection $ buildRequest queueName let ranInParallel = return . isJust $ result ranInParallel `shouldReturn` True
salemove/freddy-hs
test/Network/ConcurrencySpec.hs
mit
1,263
0
17
245
295
155
140
31
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} import Control.Category ((>>>), id) import Control.Monad.Trans import Data.Functor.Identity import Data.Proxy import qualified Data.Vector.Generic as V import GHC.TypeLits import Prelude hiding (id) import Test.QuickCheck hiding (scale) import Test.QuickCheck.Gen import Test.QuickCheck.Gen.Unsafe import Test.QuickCheck.Monadic import Unsafe.Coerce import AI.Funn.CL.Blob import qualified AI.Funn.CL.Blob as Blob import qualified AI.Funn.CL.Buffer as Buffer import AI.Funn.CL.Flat import AI.Funn.CL.LSTM import AI.Funn.CL.Layers.Convolution import AI.Funn.CL.Layers.FullyConnected import AI.Funn.CL.Layers.Misc import qualified AI.Funn.CL.Layers.Tensor as LT import AI.Funn.CL.Layers.Upscale import AI.Funn.CL.Mixing import AI.Funn.CL.MonadCL import AI.Funn.CL.Network import AI.Funn.CL.Tensor (Tensor) import qualified AI.Funn.CL.Tensor as Tensor import AI.Funn.Diff.Diff (Diff(..), Derivable(..), runDiffForward) import qualified AI.Funn.Diff.Diff as Diff import qualified AI.Funn.Flat.Blob as C import qualified AI.Funn.Flat.Flat as C import qualified AI.Funn.Flat.LSTM as C import qualified AI.Funn.Flat.Mixing as C import AI.Funn.Space import Testing.Util -- Buffer properties. prop_Buffer_fromList :: Property prop_Buffer_fromList = monadic clProperty $ do xs <- pick (arbitrary :: Gen [Double]) buf <- lift $ Buffer.fromList xs ys <- lift $ Buffer.toList buf assert (xs == ys) prop_Buffer_concat :: Property prop_Buffer_concat = monadic clProperty $ do xs <- pick (arbitrary :: Gen [Double]) ys <- pick (arbitrary :: Gen [Double]) zs <- pick (arbitrary :: Gen [Double]) buf1 <- lift $ Buffer.fromList xs buf2 <- lift $ Buffer.fromList ys buf3 <- lift $ Buffer.fromList zs buf <- lift $ Buffer.toList (Buffer.concat [buf1, buf2, buf3]) assert (buf == xs ++ ys ++ zs) prop_Buffer_slice :: Property prop_Buffer_slice = monadic clProperty $ do xs <- pick (arbitrary :: Gen [Double]) offset <- pick (choose (0, length xs)) len <- pick (choose (0, length xs - offset)) sub <- lift $ Buffer.slice offset len <$> Buffer.fromList xs ys <- lift $ Buffer.toList sub assert (ys == take len (drop offset xs)) -- Blob properties. pickBlob :: (KnownNat n) => PropertyM IO (Blob Double n) pickBlob = lift . fromCPU =<< pick arbitrary assertEqual :: (KnownNat n) => Blob Double n -> Blob Double n -> PropertyM IO () assertEqual one two = do one_c <- lift (fromGPU one) two_c <- lift (fromGPU two) stop (one_c === two_c) prop_Blob_sub_zero :: Property prop_Blob_sub_zero = monadic clProperty $ do xs <- pickBlob @10 z <- lift zero ys <- lift (subBlob xs z) assertEqual xs ys prop_Blob_plus_zero :: Property prop_Blob_plus_zero = monadic clProperty $ do xs <- pickBlob @10 z <- lift zero ys <- lift (plus xs z) assertEqual xs ys prop_Blob_plus_comm :: Property prop_Blob_plus_comm = monadic clProperty $ do xs <- pickBlob @10 ys <- pickBlob @10 z1 <- lift (plus xs ys) z2 <- lift (plus ys xs) assertEqual z1 z2 prop_Blob_plus :: Property prop_Blob_plus = monadic clProperty $ do xs <- pickBlob @10 ys <- pickBlob @10 z1 <- lift (plus xs ys) xs_c <- lift (fromGPU xs) ys_c <- lift (fromGPU ys) z2 <- lift (fromCPU =<< plus xs_c ys_c) assertEqual z1 z2 prop_Blob_plusm :: Property prop_Blob_plusm = monadic clProperty $ do xs <- pickBlob @10 ys <- pickBlob @10 z1 <- lift (plus xs ys) z2 <- lift (plusm [xs, ys]) assertEqual z1 z2 prop_Blob_split :: Property prop_Blob_split = monadic clProperty $ do zs <- pickBlob @9 let (x1, y1) = Blob.splitBlob @2 @7 zs let z1 = Blob.catBlob x1 y1 assertEqual zs z1 -- Tensor properties. pickTensor :: forall ds. (KnownDims ds) => PropertyM IO (Tensor ds) pickTensor = do blob <- pickBlob :: PropertyM IO (Blob Double (Prod ds)) xs <- lift (Blob.toVector blob) lift (Tensor.fromVector xs) tensorsEqual :: (KnownDims ds) => Tensor ds -> Tensor ds -> PropertyM IO () tensorsEqual one two = do one_c <- lift (Tensor.toVector one) two_c <- lift (Tensor.toVector two) stop (one_c === two_c) prop_Tensor_sub_zero :: Property prop_Tensor_sub_zero = monadic clProperty $ do xs <- pickTensor @[3,4] zs <- zero ys <- Tensor.subTensor xs zs tensorsEqual xs ys prop_Tensor_plus_zero :: Property prop_Tensor_plus_zero = monadic clProperty $ do xs <- pickTensor @[3,4] z <- zero ys <- plus xs z tensorsEqual xs ys prop_Tensor_plus :: Property prop_Tensor_plus = monadic clProperty $ do xs <- pickTensor @[3,4] ys <- pickTensor @[3,4] z1 <- plus xs ys xs_c <- Tensor.toVector xs ys_c <- Tensor.toVector ys let zs_c = V.zipWith (+) xs_c ys_c z2 <- Tensor.fromVector zs_c tensorsEqual z1 z2 prop_Tensor_mul :: Property prop_Tensor_mul = monadic clProperty $ do xs <- pickTensor @[3,4] ys <- pickTensor @[3,4] z1 <- Tensor.mulTensor xs ys xs_c <- Tensor.toVector xs ys_c <- Tensor.toVector ys let zs_c = V.zipWith (*) xs_c ys_c z2 <- Tensor.fromVector zs_c tensorsEqual z1 z2 prop_Tensor_plusm :: Property prop_Tensor_plusm = monadic clProperty $ do xs <- pickTensor @[3,4] ys <- pickTensor @[3,4] z1 <- plus xs ys z2 <- plusm [xs, ys] tensorsEqual z1 z2 -- OpenCL flat diff prop_fcdiff :: Property prop_fcdiff = checkGradientCL (fcDiff @2 @2 @Double) prop_reludiff :: Property prop_reludiff = checkGradientCL (reluDiff @5 @IO @Double) prop_sigmoiddiff :: Property prop_sigmoiddiff = checkGradientCL (sigmoidDiff @3 @IO @Double) prop_tanhdiff :: Property prop_tanhdiff = checkGradientCL (tanhDiff @3 @IO @Double) prop_quadraticcost :: Property prop_quadraticcost = checkGradientCL (quadraticCost @5 @IO @Double) prop_lstmdiff :: Property prop_lstmdiff = checkGradientCL (lstmDiff @2 @IO @Double) prop_mixdiff :: Property prop_mixdiff = checkGradientCL (amixDiff @3 @2 @2 @Double Proxy) prop_softmaxcost :: Property prop_softmaxcost = checkGradientCL (putR 0 >>> softmaxCost @3 @IO @Double) -- Tensor gradient prop_iconv2d :: Property prop_iconv2d = checkGradientCL (iconv2dDiff @2 @3 @3 @2 @2 @IO) prop_conv2d :: Property prop_conv2d = checkGradientCL (conv2dDiff @3 @1 @3 @3 @2 @2 @IO Proxy) prop_doubleDiff :: Property prop_doubleDiff = checkGradientCL (doubleDiff @2 @2 @2) -- Tensor Net gradient prop_conv2d_net :: Property prop_conv2d_net = checkGradientNet (conv2d @3 @1 @3 @3 @2 @2 Proxy) prop_fc_net :: Property prop_fc_net = checkGradientNet (fcNet @3 @3) prop_quadcost_net :: Property prop_quadcost_net = checkGradientNet (LT.quadCostNet @[3,4]) prop_prelu_net :: Property prop_prelu_net = checkGradientNet (LT.preluNet @'[3]) -- Equality prop_fcdiff_eq :: Property prop_fcdiff_eq = checkSameCL (fcDiff @2 @2 @Double) (C.fcDiff @2 @2) prop_relu_eq :: Property prop_relu_eq = checkSameCL (reluDiff @3 @IO @Double) (C.reluDiff) prop_sigmoid_eq :: Property prop_sigmoid_eq = checkSameCL (sigmoidDiff @3 @IO @Double) (C.sigmoidDiff) prop_tanh_eq :: Property prop_tanh_eq = checkSameCL (tanhDiff @3 @IO @Double) (C.tanhDiff) prop_lstm_eq :: Property prop_lstm_eq = checkSameCL (lstmDiff @3 @IO @Double) (C.lstmDiff @3) prop_mix_eq :: Property prop_mix_eq = checkSameCL (amixDiff @3 @2 @2 @Double Proxy) (C.amixDiff @3 @2 @2 Proxy) prop_softmaxcost_eq :: Property prop_softmaxcost_eq = checkSameCL (putR 0 >>> softmaxCost @3 @IO @Double) (putR 0 >>> C.softmaxCost) -- Make TemplateHaskell aware of above definitions. $(return []) main :: IO Bool main = $(quickCheckAll)
nshepperd/funn
Testing/opencl.hs
mit
8,289
0
14
1,679
2,884
1,479
1,405
214
1
-- Character with longest repetition -- https://www.codewars.com/kata/586d6cefbcc21eed7a001155 module Kata(longestRepetition) where import Data.Ord (comparing) import Control.Arrow ((&&&)) import Data.List (group, maximumBy) longestRepetition :: String -> Maybe (Char, Int) longestRepetition [] = Nothing longestRepetition s = Just . maximumBy (comparing snd) . map (head &&& length) . group $ s
gafiatulin/codewars
src/6 kyu/LongestRepetition.hs
mit
399
0
11
51
117
66
51
7
1
--Project Euler Problem N problem_N = sum[x | x <- [1..999], mod x 3 == 0 || mod x 5 == 0] main :: IO() main = do y <- return (problem_N) putStrLn("Answer to problem N = " ++ show(y))
calewis/SmallProjectsAndDev
project_euler/haskell/template.hs
mit
195
0
11
51
99
49
50
5
1