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 DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE Trustworthy #-} -------------------------------------------------------------------- -- | -- Module : Data.MessagePack.Types.Assoc -- Copyright : (c) Daiki Handa, 2010-2011 -- License : BSD3 -- -- Maintainer: [email protected] -- Stability : experimental -- Portability: portable -- -- MessagePack map labeling type -- -------------------------------------------------------------------- module Data.MessagePack.Types.Assoc ( Assoc (..) ) where import Control.Applicative ((<$>)) import Control.DeepSeq (NFData) import Data.Typeable (Typeable) import Test.QuickCheck.Arbitrary (Arbitrary, arbitrary) -- not defined for general Functor for performance reason. -- (ie. you would want to write custom instances for each type using specialized mapM-like functions) newtype Assoc a = Assoc { unAssoc :: a } deriving (Show, Read, Eq, Ord, Typeable, NFData) instance Arbitrary a => Arbitrary (Assoc a) where arbitrary = Assoc <$> arbitrary
SX91/hs-msgpack-types
src/Data/MessagePack/Types/Assoc.hs
bsd-3-clause
1,147
0
7
237
152
98
54
14
0
module TranslationLister where import Control.Monad ( forM ) import System.Directory ( getDirectoryContents, doesFileExist, doesDirectoryExist ) import System.FilePath ( (</>) ) import Data.List ( isSuffixOf, stripPrefix, groupBy ) -- Directly lifted from http://book.realworldhaskell.org/read/io-case-study-a-library-for-searching-the-filesystem.html getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents topdir = do names <- getDirectoryContents topdir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = topdir </> name isDirectory <- doesDirectoryExist path if isDirectory then getRecursiveContents path else return [path] return (concat paths) getResxFiles :: FilePath -> IO [FilePath] getResxFiles topdir = do files <- getRecursiveContents topdir let resxs = filter (isSuffixOf ".resx") files return resxs data TranslationLanguage = TranslationLanguage String | DefaultLanguage deriving Show allAfterLastElementOf :: Eq a => a -> [a] -> [a] -> [a] allAfterLastElementOf _ [] acc = acc allAfterLastElementOf el (x : xs) acc = if el == x then allAfterLastElementOf el xs [] else allAfterLastElementOf el xs (acc ++ [x]) withoutSuffix :: Eq a => [a] -> [a] -> Maybe [a] withoutSuffix suff = (fmap reverse) . (stripPrefix (reverse suff)) . reverse resxFileLanguage :: FilePath -> TranslationLanguage resxFileLanguage fp = let withoutResx = withoutSuffix ".resx" fp in case withoutResx of Nothing -> DefaultLanguage Just sp -> let afterLastDot = allAfterLastElementOf '.' sp [] in if length afterLastDot > 6 then DefaultLanguage else if (elem '/' afterLastDot || elem '\\' afterLastDot) then DefaultLanguage else TranslationLanguage afterLastDot stripLanguage :: TranslationLanguage -> FilePath -> FilePath stripLanguage DefaultLanguage p = p stripLanguage (TranslationLanguage l) p = case withoutSuffix (('.' : l) ++ ".resx") p of Nothing -> p -- Technically shouldn't happen Just q -> q resxFileGroups :: [FilePath] -> [[(FilePath, TranslationLanguage)]] resxFileGroups items = let mappedWithLanguage = map (\p -> let fl = resxFileLanguage p in (p, fl, stripLanguage fl p)) items in let compareOnBasePath (_, _, basePath1) (_, _, basePath2) = basePath1 == basePath2 in let withoutBasePath (p, lang, _) = (p, lang) in let grouped = groupBy compareOnBasePath mappedWithLanguage in map (map withoutBasePath) grouped
sebug/TranslationLister
TranslationLister.hs
bsd-3-clause
2,715
0
16
657
807
418
389
60
4
{-# LANGUAGE TemplateHaskell #-} module HNN.Optimize.Vanilla ( VanillaT , runVanilla , vanilla ) where import Control.Monad.Reader import Data.VectorSpace import Control.Lens data VanillaReader s = VanillaReader { _learningRate :: s } makeLenses ''VanillaReader type VanillaT s = ReaderT (VanillaReader s) runVanilla learningRate action = runReaderT action (VanillaReader learningRate) vanilla :: (VectorSpace w, Monad m) => Scalar w -> w -> w -> VanillaT (Scalar w) m w vanilla cost grad w_t = do lr <- view learningRate return $ w_t ^-^ lr *^ grad
alexisVallet/hnn
src/HNN/Optimize/Vanilla.hs
bsd-3-clause
575
0
11
108
181
96
85
18
1
{-# language DataKinds #-} {-# language TypeFamilies #-} {-# language GADTs #-} {-# language MultiParamTypeClasses #-} {-# language DeriveDataTypeable #-} {-# language StandaloneDeriving #-} {-# language FlexibleInstances #-} {-# language FlexibleContexts #-} {-# language UndecidableInstances #-} {-# language Rank2Types #-} {-# language TemplateHaskell #-} {-# language ScopedTypeVariables #-} {-# language ConstraintKinds #-} {-# language DeriveAnyClass #-} {-# language OverloadedStrings #-} {-# language OverloadedLists #-} {-# language RecursiveDo #-} {-# language QuasiQuotes #-} {-# language TypeInType #-} {-# language ViewPatterns #-} {-# language OverloadedLists #-} {-# language NoMonomorphismRestriction #-} module UI.Proposal where import Data.Dependent.Map (DMap,DSum((:=>)), singleton) import qualified Data.Dependent.Map as DMap import Data.GADT.Compare (GCompare) import Data.GADT.Compare.TH import UI.Lib -- (MS,ES,DS, Reason, domMorph, EitherG(LeftG,RightG), rightG,leftG, Cable,sselect) import Reflex.Dom hiding (Delete, Insert, Link) import Data.Bifunctor import Control.Lens hiding (dropping) import Data.Data.Lens import Data.Data import Data.Typeable import Control.Lens.TH import System.Random import qualified Data.Map as M import Status import World import Data.Text (Text,pack,unpack) import Data.String.Here import Data.String import Control.Monad import Data.Maybe import Data.Monoid import Control.Monad.Trans import Data.Either import Text.Read (readMaybe) import Text.Printf import UI.Constraints import UI.ValueInput import Instance.Date import Control.Monad.Reader import UI.DateInput import qualified GHCJS.DOM.HTMLInputElement as J import qualified GHCJS.DOM.Element as J import HList validWhat x | length x > 10 = Just x | otherwise = Nothing openWidget :: forall a u m r. () => ( Enum (Zone u a), Bounded (Zone u a), Bargain a ~ [Char]) => (MonadReader (DS r) m, In Bool r, HasIcons m (Zone u a), HasInput m (Slot a), MS m) => Part u a -- who I am -> ((Bargain a,Slot a, Zone u a) -> World a) -> m (Cable (EitherG () (Slot a, World a))) openWidget u step = el "ul" $ do -- zone <- el "li" $ valueInput "where" readMaybe time <- el "li" $ do elAttr "span" [("class","field")] $ text "when" divClass "timeshow" $ getInput zone <- el "li" $ do elAttr "span" [("class","field")] $ text "where" divClass "placeshow" $ divClass "radiochecks" $ radioChecks $ [minBound .. maxBound] -- time :: DS (Maybe (Slot a)) <- el "li" $ valueInput "when" readMaybe -- camera bargain <- el "li" $ do elAttr "span" [("class","field")] $ text "what" divClass "bargainshow" $ valueInput "10 chars, minimum" validWhat (sub,close) <- el "li" . floater $ do sub <- submit (fmap (all id) . sequence $ (isJust <$> time): (isJust <$> zone): [isJust <$> bargain]) close <- icon ["close","3x"] "abandon" return (sub,close) let f b t z = (t, step (b,t,z)) return $ merge [ RightG :=> ((f <$> (fromJust <$> bargain) <*> (fromJust <$> time) <*> (fromJust <$> zone)) `tagPromptlyDyn` sub), LeftG :=> close ] open (EGiver u) w = do n <- liftIO $ randomIO (,) n <$> openWidget u (\(b,t,z) -> runIdentity $ step (New (Idx n) b t z) u w) open (ETaker u) w = do n <- liftIO $ randomIO (,) n <$> openWidget u (\(b,t,z) -> runIdentity $ step (New (Idx n) b t z) u w) data Section = ClosedSection | OpenSection proposalDriver u w = divClass "propose record" $ do let f ClosedSection = do e <- floater $ icon ["pencil","3x"] "new proposal" return $ wire (LeftG :=> OpenSection <$ e) f OpenSection = do (i,e) <- open u w return $ merge [LeftG :=> ClosedSection <$ pick LeftG e, RightG :=> (\(s,w) -> ((s,i),w)) <$> pick RightG e] rec s <- holdDyn ClosedSection $ pick LeftG e e <- domMorph f s return $ pick RightG e
paolino/book-a-visit
client/UI/Proposal.hs
bsd-3-clause
3,932
0
21
790
1,310
706
604
101
2
module Main where import Rsdlsb.Init main :: IO () main = run
Raveline/rsdlsb
app/Main.hs
bsd-3-clause
64
0
6
14
24
14
10
4
1
module Phil.Core.AST.Pattern where import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Phil.Core.AST.Identifier import Phil.Core.AST.Literal import Text.PrettyPrint.ANSI.Leijen hiding ((<>)) data Pattern = PatId Ident | PatCon Ctor [Ident] | PatLit Literal | PatWildcard deriving (Eq, Show) renderPattern :: Pattern -> Doc renderPattern (PatId a) = text . T.unpack $ getIdent a renderPattern (PatCon name args) = text . T.unpack $ getCtor name <> T.unwords (fmap getIdent args) renderPattern (PatLit lit) = renderLiteral lit renderPattern PatWildcard = text "_"
LightAndLight/hindley-milner
src/Phil/Core/AST/Pattern.hs
bsd-3-clause
610
0
8
98
208
117
91
19
1
module Main where -- | Unfortunately there is no test. There is only use cases -- where you can find how you can use telegram bot api methods import Control.Lens.Basic import Data.Text (Text) import Control.Applicative ((<$>)) import Data.Maybe (maybe) import Data.Configurator (Worth (Required)) import qualified Data.Configurator as C import Data.Configurator.Types (Name) import qualified Data.Text as T import Control.Monad.IO.Class (liftIO, MonadIO) import TelegramBotAPI getToken :: Name -> IO (Maybe Token) getToken name = C.load [Required "bot.config"] >>= \config -> C.lookup config (T.append name ".token") getTelegramToken :: MonadIO m => m (Maybe Token) getTelegramToken = liftIO (getToken "telegram") getUpdateId :: Update -> Int getUpdateId (Update u) = view @updateId u getMessage :: Update -> Maybe Message getMessage (Update u) = view @message u showMessage :: Message -> String showMessage (Message m) = "MessageId: " ++ show (view @messageId m) ++ "\nFrom: " ++ show (view @from m) ++ "\nText: " ++ show (view @text m) ++ "\nPhoto: " ++ show (view @photo m) ++ "\n" main :: IO () main = do Just token <- getTelegramToken config <- createTelegramConfig token me <- runTelegramAPI config getMe print me updates <- runTelegramAPI config (getUpdates Nothing Nothing Nothing) mapM_ (\update -> putStrLn ("update_id: " ++ (show (getUpdateId update)) ++ "\n" ++ (maybe "" showMessage (getMessage update)))) updates m1 <- runTelegramAPI config (sendMessage 111874928 "Hi from telegram-client" Nothing Nothing Nothing) print (showMessage m1)
DbIHbKA/telegram-client
test/Spec.hs
bsd-3-clause
1,934
0
18
609
546
281
265
-1
-1
{-# LANGUAGE BangPatterns #-} module Yarn ( Yarn (..) , IOMode (..) , stdin , stdout , withFile , openFile , close , foldl , foldl' , insert ) where import Control.Applicative import Control.Exception import Control.Monad import qualified Data.Aeson as Aeson import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as LBS import Prelude hiding (foldl) import qualified System.IO as IO import Fiber newtype Yarn = Yarn { unYarn :: IO.Handle } data IOMode = ReadMode | ReadWriteMode stdin :: Yarn stdin = Yarn IO.stdin stdout :: Yarn stdout = Yarn IO.stdout withFile :: FilePath -> IOMode -> (Yarn -> IO a) -> IO a withFile fp mode = bracket (openFile fp mode) close openFile :: FilePath -> IOMode -> IO Yarn openFile fp mode = Yarn <$> IO.openFile fp modeIO where modeIO = case mode of ReadMode -> IO.ReadMode ReadWriteMode -> IO.ReadWriteMode close :: Yarn -> IO () close = IO.hClose . unYarn foldl :: (a -> Fiber -> a) -> a -> Yarn -> IO a foldl f z y = do seekable <- IO.hIsSeekable $ unYarn y when seekable $ IO.hSeek h IO.AbsoluteSeek 0 loop id z where loop front x = do -- more bytes are needed eof <- IO.hIsEOF h if eof then finish front x else do buf <- BS.hGet h 4096 go front buf x go front more x = do -- 'more' is always the beginning of a line let (first, second) = BS.break (== '\n') more case BS.uncons second of Nothing -> loop (BS.append $ front more) x Just (_, second') -> do let l = front first if BS.null l then fail "Yarn.foldl: an empty line" else do let fib = either (error . ("Yarn.foldl: " ++)) id $ Aeson.eitherDecode $ LBS.fromStrict l let x' = f x fib go id second' x' finish front x = do let l = front BS.empty if BS.null l then return x else do let fib = either (error . ("Yarn.foldl: " ++)) id $ Aeson.eitherDecode $ LBS.fromStrict l let x' = f x fib return x' !h = unYarn y foldl' :: (a -> Fiber -> a) -> a -> Yarn -> IO a foldl' f z y = do seekable <- IO.hIsSeekable $ unYarn y when seekable $ IO.hSeek h IO.AbsoluteSeek 0 loop id z where loop front x = do -- more bytes are needed eof <- IO.hIsEOF h if eof then finish front x else do buf <- BS.hGet h 4096 go front buf x go front more x = do -- 'more' is always the beginning of a line let (first, second) = BS.break (== '\n') more case BS.uncons second of Nothing -> loop (BS.append $ front more) x Just (_, second') -> do let l = front first if BS.null l then fail "Yarn.foldl: an empty line" else do let fib = either (error . ("Yarn.foldl: " ++)) id $ Aeson.eitherDecode $ LBS.fromStrict l let !x' = f x fib go id second' x' finish front x = do let l = front BS.empty if BS.null l then return x else do let fib = either (error . ("Yarn.foldl: " ++)) id $ Aeson.eitherDecode $ LBS.fromStrict l let !x' = f x fib return x' !h = unYarn y insert :: Fiber -> Yarn -> IO () insert fib y = do seekable <- IO.hIsSeekable $ unYarn y when seekable $ IO.hSeek h IO.SeekFromEnd 0 LBS.hPutStrLn h $ Aeson.encode fib where !h = unYarn y
yuttie/fibers
Yarn.hs
bsd-3-clause
3,924
0
25
1,557
1,304
644
660
111
5
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveGeneric #-} module Blockchain.Data.Transaction ( Transaction(..), Transaction(transactionNonce, transactionGasPrice, transactionGasLimit, transactionTo, transactionValue, transactionData, transactionInit), createMessageTX, createContractCreationTX, isMessageTX, isContractCreationTX, whoSignedThisTransaction, transactionHash ) where import qualified Data.ByteString as B import qualified Data.ByteString.Base16 as B16 import Data.ByteString.Internal import Data.Word import Numeric import Text.PrettyPrint.ANSI.Leijen import qualified Blockchain.Colors as CL import Blockchain.Data.Address import Blockchain.Data.Code import Blockchain.Data.RLP import Blockchain.ExtWord import Blockchain.Format import Blockchain.SHA import Blockchain.Util --import Debug.Trace import Database.Persist import Database.Persist.TH import Database.Persist.Sql import Database.Persist.Types import Network.Haskoin.Internals hiding (Address) import Blockchain.ExtendedECDSA import Data.Aeson import GHC.Generics addLeadingZerosTo64::String->String addLeadingZerosTo64 x = replicate (64 - length x) '0' ++ x createMessageTX::Monad m=>Integer->Integer->Integer->Address->Integer->B.ByteString->PrvKey->SecretT m Transaction createMessageTX n gp gl to val theData prvKey = do let unsignedTX = MessageTX { transactionNonce = n, transactionGasPrice = gp, transactionGasLimit = gl, transactionTo = to, transactionValue = val, transactionData = theData, transactionR = 0, transactionS = 0, transactionV = 0 } let SHA theHash = hash $ rlpSerialize $ partialRLPEncode unsignedTX ExtendedSignature signature yIsOdd <- extSignMsg theHash prvKey return unsignedTX { transactionR = case B16.decode $ B.pack $ map c2w $ addLeadingZerosTo64 $ showHex (sigR signature) "" of (val, "") -> byteString2Integer val _ -> error ("error: sigR is: " ++ showHex (sigR signature) ""), transactionS = case B16.decode $ B.pack $ map c2w $ addLeadingZerosTo64 $ showHex (sigS signature) "" of (val, "") -> byteString2Integer val _ -> error ("error: sigS is: " ++ showHex (sigS signature) ""), transactionV = if yIsOdd then 0x1c else 0x1b } createContractCreationTX::Monad m=>Integer->Integer->Integer->Integer->Code->PrvKey->SecretT m Transaction createContractCreationTX n gp gl val init' prvKey = do let unsignedTX = ContractCreationTX { transactionNonce = n, transactionGasPrice = gp, transactionGasLimit = gl, transactionValue = val, transactionInit = init', transactionR = 0, transactionS = 0, transactionV = 0 } let SHA theHash = hash $ rlpSerialize $ partialRLPEncode unsignedTX ExtendedSignature signature yIsOdd <- extSignMsg theHash prvKey return unsignedTX { transactionR = case B16.decode $ B.pack $ map c2w $ addLeadingZerosTo64 $ showHex (sigR signature) "" of (val, "") -> byteString2Integer val _ -> error ("error: sigR is: " ++ showHex (sigR signature) ""), transactionS = case B16.decode $ B.pack $ map c2w $ addLeadingZerosTo64 $ showHex (sigS signature) "" of (val, "") -> byteString2Integer val _ -> error ("error: sigS is: " ++ showHex (sigS signature) ""), transactionV = if yIsOdd then 0x1c else 0x1b } whoSignedThisTransaction::Transaction->Maybe Address -- Signatures can be malformed, hence the Maybe whoSignedThisTransaction t = fmap pubKey2Address $ getPubKeyFromSignature xSignature theHash where xSignature = ExtendedSignature (Signature (fromInteger $ transactionR t) (fromInteger $ transactionS t)) (0x1c == transactionV t) SHA theHash = hash $ rlpSerialize $ partialRLPEncode t data Transaction = MessageTX { transactionNonce::Integer, transactionGasPrice::Integer, transactionGasLimit::Integer, transactionTo::Address, transactionValue::Integer, transactionData::B.ByteString, transactionR::Integer, transactionS::Integer, transactionV::Word8 } | ContractCreationTX { transactionNonce::Integer, transactionGasPrice::Integer, transactionGasLimit::Integer, transactionValue::Integer, transactionInit::Code, transactionR::Integer, transactionS::Integer, transactionV::Word8 } deriving (Show, Read, Eq, Generic) isMessageTX MessageTX{} = True isMessageTX _ = False isContractCreationTX ContractCreationTX{} = True isContractCreationTX _ = False instance Format Transaction where format MessageTX{transactionNonce=n, transactionGasPrice=gp, transactionGasLimit=gl, transactionTo=to', transactionValue=v, transactionData=d} = CL.blue "Message Transaction" ++ tab ( "\n" ++ "tNonce: " ++ show n ++ "\n" ++ "gasPrice: " ++ show gp ++ "\n" ++ "tGasLimit: " ++ show gl ++ "\n" ++ "to: " ++ show (pretty to') ++ "\n" ++ "value: " ++ show v ++ "\n" ++ "tData: " ++ tab ("\n" ++ format d) ++ "\n") format ContractCreationTX{transactionNonce=n, transactionGasPrice=gp, transactionGasLimit=gl, transactionValue=v, transactionInit=Code init'} = CL.blue "Contract Creation Transaction" ++ tab ( "\n" ++ "tNonce: " ++ show n ++ "\n" ++ "gasPrice: " ++ show gp ++ "\n" ++ "tGasLimit: " ++ show gl ++ "\n" ++ "value: " ++ show v ++ "\n" ++ "tInit: " ++ tab (format init') ++ "\n") --partialRLP(De|En)code are used for the signing algorithm partialRLPDecode::RLPObject->Transaction partialRLPDecode (RLPArray [n, gp, gl, RLPString "", val, i, _, _, _]) = --Note- Address 0 /= Address 000000.... Only Address 0 yields a ContractCreationTX ContractCreationTX { transactionNonce = rlpDecode n, transactionGasPrice = rlpDecode gp, transactionGasLimit = rlpDecode gl, transactionValue = rlpDecode val, transactionInit = rlpDecode i } partialRLPDecode (RLPArray [n, gp, gl, toAddr, val, i, _, _, _]) = MessageTX { transactionNonce = rlpDecode n, transactionGasPrice = rlpDecode gp, transactionGasLimit = rlpDecode gl, transactionTo = rlpDecode toAddr, transactionValue = rlpDecode val, transactionData = rlpDecode i } partialRLPDecode x = error ("rlp object has wrong format in call to partialRLPDecode: " ++ show x) partialRLPEncode::Transaction->RLPObject partialRLPEncode MessageTX{transactionNonce=n, transactionGasPrice=gp, transactionGasLimit=gl, transactionTo=to', transactionValue=v, transactionData=d} = RLPArray [ rlpEncode n, rlpEncode gp, rlpEncode gl, rlpEncode to', rlpEncode v, rlpEncode d ] partialRLPEncode ContractCreationTX{transactionNonce=n, transactionGasPrice=gp, transactionGasLimit=gl, transactionValue=v, transactionInit=init'} = RLPArray [ rlpEncode n, rlpEncode gp, rlpEncode gl, rlpEncode (0::Integer), rlpEncode v, rlpEncode init' ] instance RLPSerializable Transaction where rlpDecode (RLPArray [n, gp, gl, toAddr, val, i, vVal, rVal, sVal]) = partial { transactionV = fromInteger $ rlpDecode vVal, transactionR = rlpDecode rVal, transactionS = rlpDecode sVal } where partial = partialRLPDecode $ RLPArray [n, gp, gl, toAddr, val, i, RLPScalar 0, RLPScalar 0, RLPScalar 0] rlpDecode x = error ("rlp object has wrong format in call to rlpDecodeq: " ++ show x) rlpEncode t = RLPArray [ n, gp, gl, toAddr, val, i, rlpEncode $ toInteger $ transactionV t, rlpEncode $ transactionR t, rlpEncode $ transactionS t ] where (RLPArray [n, gp, gl, toAddr, val, i]) = partialRLPEncode t transactionHash::Transaction->SHA transactionHash = hash . rlpSerialize . rlpEncode
jamshidh/ethereum-data-sql
src/Blockchain/Data/Transaction.hs
bsd-3-clause
8,805
0
26
2,281
2,226
1,225
1,001
204
4
{-# LANGUAGE BangPatterns #-} ----------------------------------------------------------------------------- -- | Copyright : (c) 2010 Jasper Van der Jeugt -- (c) 2010-2011 Simon Meier -- License : BSD3-style (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Portability : GHC -- -- Extra functions for creating and executing 'Builder's. They are intended -- for application-specific fine-tuning the performance of 'Builder's. -- ----------------------------------------------------------------------------- module Data.ByteString.Builder.Extra ( -- * Execution strategies toLazyByteStringWith , AllocationStrategy , safeStrategy , untrimmedStrategy , smallChunkSize , defaultChunkSize -- * Controlling chunk boundaries , byteStringCopy , byteStringInsert , byteStringThreshold , lazyByteStringCopy , lazyByteStringInsert , lazyByteStringThreshold , flush -- * Low level execution , BufferWriter , Next(..) , runBuilder -- * Host-specific binary encodings , intHost , int16Host , int32Host , int64Host , wordHost , word16Host , word32Host , word64Host , floatHost , doubleHost ) where import Data.ByteString.Builder.Internal ( Builder, toLazyByteStringWith , AllocationStrategy, safeStrategy, untrimmedStrategy , smallChunkSize, defaultChunkSize, flush , byteStringCopy, byteStringInsert, byteStringThreshold , lazyByteStringCopy, lazyByteStringInsert, lazyByteStringThreshold ) import qualified Data.ByteString.Builder.Internal as I import qualified Data.ByteString.Builder.Prim as P import qualified Data.ByteString.Internal as S import qualified Data.ByteString.Lazy.Internal as L import Foreign ------------------------------------------------------------------------------ -- Builder execution public API ------------------------------------------------------------------------------ -- | A 'BufferWriter' represents the result of running a 'Builder'. -- It unfolds as a sequence of chunks of data. These chunks come in two forms: -- -- * an IO action for writing the Builder's data into a user-supplied memory -- buffer. -- -- * a pre-existing chunks of data represented by a strict 'ByteString' -- -- While this is rather low level, it provides you with full flexibility in -- how the data is written out. -- -- The 'BufferWriter' itself is an IO action: you supply it with a buffer -- (as a pointer and length) and it will write data into the buffer. -- It returns a number indicating how many bytes were actually written -- (which can be @0@). It also returns a 'Next' which describes what -- comes next. -- type BufferWriter = Ptr Word8 -> Int -> IO (Int, Next) -- | After running a 'BufferWriter' action there are three possibilities for -- what comes next: -- data Next = -- | This means we're all done. All the builder data has now been written. Done -- | This indicates that there may be more data to write. It -- gives you the next 'BufferWriter' action. You should call that action -- with an appropriate buffer. The int indicates the /minimum/ buffer size -- required by the next 'BufferWriter' action. That is, if you call the next -- action you /must/ supply it with a buffer length of at least this size. | More !Int BufferWriter -- | In addition to the data that has just been written into your buffer -- by the 'BufferWriter' action, it gives you a pre-existing chunk -- of data as a 'S.ByteString'. It also gives you the following 'BufferWriter' -- action. It is safe to run this following action using a buffer with as -- much free space as was left by the previous run action. | Chunk !S.ByteString BufferWriter -- | Turn a 'Builder' into its initial 'BufferWriter' action. -- runBuilder :: Builder -> BufferWriter runBuilder = run . I.runBuilder where run :: I.BuildStep () -> BufferWriter run step = \buf len -> do sig <- step (I.BufferRange buf (buf `plusPtr` len)) case sig of I.Done endPtr () -> let !wc = bytesWritten buf endPtr next = Done in return (wc, next) I.BufferFull minReq endPtr step' -> let !wc = bytesWritten buf endPtr next = More minReq (run step') in return (wc, next) I.InsertChunks endPtr _ lbsc step' -> let !wc = bytesWritten buf endPtr next = case lbsc L.Empty of L.Empty -> More (len - wc) (run step') L.Chunk c cs -> Chunk c (yieldChunks step' cs) in return (wc, next) yieldChunks :: I.BuildStep () -> L.ByteString -> BufferWriter yieldChunks step' cs = \buf len -> case cs of L.Empty -> run step' buf len L.Chunk c cs' -> let wc = 0 next = Chunk c (yieldChunks step' cs') in return (wc, next) bytesWritten startPtr endPtr = endPtr `minusPtr` startPtr ------------------------------------------------------------------------------ -- Host-specific encodings ------------------------------------------------------------------------------ -- | Encode a single native machine 'Int'. The 'Int' is encoded in host order, -- host endian form, for the machine you're on. On a 64 bit machine the 'Int' -- is an 8 byte value, on a 32 bit machine, 4 bytes. Values encoded this way -- are not portable to different endian or int sized machines, without -- conversion. -- {-# INLINE intHost #-} intHost :: Int -> Builder intHost = P.primFixed P.intHost -- | Encode a 'Int16' in native host order and host endianness. {-# INLINE int16Host #-} int16Host :: Int16 -> Builder int16Host = P.primFixed P.int16Host -- | Encode a 'Int32' in native host order and host endianness. {-# INLINE int32Host #-} int32Host :: Int32 -> Builder int32Host = P.primFixed P.int32Host -- | Encode a 'Int64' in native host order and host endianness. {-# INLINE int64Host #-} int64Host :: Int64 -> Builder int64Host = P.primFixed P.int64Host -- | Encode a single native machine 'Word'. The 'Word' is encoded in host order, -- host endian form, for the machine you're on. On a 64 bit machine the 'Word' -- is an 8 byte value, on a 32 bit machine, 4 bytes. Values encoded this way -- are not portable to different endian or word sized machines, without -- conversion. -- {-# INLINE wordHost #-} wordHost :: Word -> Builder wordHost = P.primFixed P.wordHost -- | Encode a 'Word16' in native host order and host endianness. {-# INLINE word16Host #-} word16Host :: Word16 -> Builder word16Host = P.primFixed P.word16Host -- | Encode a 'Word32' in native host order and host endianness. {-# INLINE word32Host #-} word32Host :: Word32 -> Builder word32Host = P.primFixed P.word32Host -- | Encode a 'Word64' in native host order and host endianness. {-# INLINE word64Host #-} word64Host :: Word64 -> Builder word64Host = P.primFixed P.word64Host -- | Encode a 'Float' in native host order. Values encoded this way are not -- portable to different endian machines, without conversion. {-# INLINE floatHost #-} floatHost :: Float -> Builder floatHost = P.primFixed P.floatHost -- | Encode a 'Double' in native host order. {-# INLINE doubleHost #-} doubleHost :: Double -> Builder doubleHost = P.primFixed P.doubleHost
markflorisson/hpack
testrepo/bytestring-0.10.2.0/Data/ByteString/Builder/Extra.hs
bsd-3-clause
7,459
0
22
1,663
962
563
399
108
5
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.NVX -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- A convenience module, combining all raw modules containing NVX extensions. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.NVX ( module Graphics.Rendering.OpenGL.Raw.NVX.ConditionalRender, module Graphics.Rendering.OpenGL.Raw.NVX.GPUMemoryInfo ) where import Graphics.Rendering.OpenGL.Raw.NVX.ConditionalRender import Graphics.Rendering.OpenGL.Raw.NVX.GPUMemoryInfo
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/NVX.hs
bsd-3-clause
756
0
5
86
62
51
11
5
0
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP -- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP ---------------------------------------------------------------------- -- | -- Module : ShapedTypes.Vec -- Copyright : (c) 2016 Conal Elliott -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- -- Length-typed lists/vectors ---------------------------------------------------------------------- -- {-# OPTIONS_GHC -fplugin=ReificationRules.Plugin -dcore-lint -fexpose-all-unfoldings #-} -- {-# OPTIONS_GHC -fplugin-opt=ReificationRules.Plugin:trace #-} -- {-# OPTIONS_GHC -ddump-rule-rewrites #-} module ShapedTypes.Vec (Vec(..)) where import Prelude hiding (id,(.)) import Control.Applicative (liftA2) import Data.Monoid ((<>)) import GHC.Generics (Generic1(..),U1(..),Par1(..),(:*:)(..)) import Data.Pointed import Data.Key import ShapedTypes.ApproxEq import ShapedTypes.Sized import ShapedTypes.Nat import ShapedTypes.Scan (LScan(..),lscanTraversable) import qualified ShapedTypes.ScanF as SF import ShapedTypes.Types.Vec #define SPEC(cls,n) {-# SPECIALISE instance cls (Vec n) #-} #define SPECS(cls) \ -- SPEC(cls,N1); SPEC(cls,N2); SPEC(cls,N3); SPEC(cls,N4);\ -- SPEC(cls,N5); SPEC(cls,N6); SPEC(cls,N7); SPEC(cls,N8) -- The more specializations we declare here, the more time it takes to compile -- this library code *and* the less time it takes to compile client code. We -- thus probably want to comment out all or some of the `SPEC`s in `SPECS` while -- developing. instance Functor (Vec Z) where fmap _ ZVec = ZVec {-# INLINE fmap #-} instance Functor (Vec n) => Functor (Vec (S n)) where fmap f (a :< u) = f a :< fmap f u {-# INLINE fmap #-} SPECS(Functor) instance Applicative (Vec Z) where pure _ = ZVec ZVec <*> ZVec = ZVec {-# INLINE pure #-} {-# INLINE (<*>) #-} instance Applicative (Vec n) => Applicative (Vec (S n)) where pure a = a :< pure a (f :< fs) <*> (a :< as) = f a :< (fs <*> as) {-# INLINE pure #-} {-# INLINE (<*>) #-} SPECS(Applicative) -- TODO: Monad instance Foldable (Vec Z) where foldMap _ ZVec = mempty {-# INLINE foldMap #-} instance Foldable (Vec n) => Foldable (Vec (S n)) where foldMap h (a :< as) = h a <> foldMap h as {-# INLINE foldMap #-} SPECS(Foldable) instance Traversable (Vec Z) where traverse _ ZVec = pure ZVec {-# INLINE traverse #-} instance Traversable (Vec n) => Traversable (Vec (S n)) where traverse f (a :< as) = liftA2 (:<) (f a) (traverse f as) {-# INLINE traverse #-} SPECS(Traversable) {-------------------------------------------------------------------- Other representations --------------------------------------------------------------------} instance Generic1 (Vec Z) where type Rep1 (Vec Z) = U1 from1 ZVec = U1 to1 U1 = ZVec instance Generic1 (Vec (S n)) where type Rep1 (Vec (S n)) = Par1 :*: Vec n from1 (a :< as) = Par1 a :*: as to1 (Par1 a :*: as) = a :< as {-------------------------------------------------------------------- pointed and keys packages --------------------------------------------------------------------} instance Applicative (Vec n) => Pointed (Vec n) where point = pure instance (Functor (Vec n), Applicative (Vec n)) => Zip (Vec n) where zipWith = liftA2 -- Needs UndecidableInstances -- Without the seemingly redundant Functor (Vec n) constraint, GHC 8.1.20160307 says -- -- • Could not deduce (Functor (Vec n)) -- arising from the superclasses of an instance declaration -- from the context: Applicative (Vec n) -- bound by the instance declaration -- at ShapedTypes/Vec.hs:(154,10)-(155,13) -- -- Perhaps <https://ghc.haskell.org/trac/ghc/ticket/11427>. #if 0 type instance Key (Vec n) = Fin n instance Keyed Pair where mapWithKey q = \ (a :# b) -> q False a :# q True b instance Lookup Pair where lookup k t = Just (index t k) instance Indexable Pair where index (a :# b) k = if k then b else a instance Adjustable Pair where adjust f k (a :# b) = if k then a :# f b else f a :# b instance ZipWithKey (Vec n) #endif {-------------------------------------------------------------------- shaped-types instances --------------------------------------------------------------------} instance (Foldable (Vec n), ApproxEq a) => ApproxEq (Vec n a) where (=~) = approxEqFoldable {-# INLINE (=~) #-} -- instance (Foldable (Vec n), Applicative (Vec n)) => Sized (Vec n) where -- size = sizeAF @(Vec n) -- -- size = length (pure () :: Vec n ()) -- {-# INLINE size #-} -- instance Sized (Rep1 (Vec n)) => Sized (Vec n) where -- size = genericSize @(Vec n) -- {-# INLINE size #-} instance Sized (Vec Z ) where size = 0 -- {-# INLINE size #-} instance Sized (Vec n) => Sized (Vec (S n)) where size = 1 + size @(Vec n) -- {-# INLINE size #-} -- Note the *absence* of `INLINE` pragmas, particularly for `S n`. Consequently, -- the `1 +` gets optimized into unboxed terms, defeating my reifier and giving -- GHC more opportunity for compile-time simplification. Seems a fragile hack. -- Find robust ways to let GHC do more simplification. #if 0 -- Experiment: use default lscan method. However, we'll get the quadratic version. instance LScan (Vec Z) instance LScan (Vec n) => LScan (Vec (S n)) instance SF.LScan (Vec Z) instance SF.LScan (Vec n) => SF.LScan (Vec (S n)) #else -- Generic lscan is terrible for Vec, so scan sequentially. instance (Functor (Vec n), Traversable (Vec n)) => LScan (Vec n) where lscan = lscanTraversable {-# INLINE lscan #-} -- Generic lscan is terrible for Vec, so scan sequentially. instance (Functor (Vec n), Traversable (Vec n)) => SF.LScan (Vec n) where lscan = SF.lscanTraversable {-# INLINE lscan #-} -- Needs UndecidableInstances #endif
conal/shaped-types
src/ShapedTypes/Vec.hs
bsd-3-clause
6,627
23
12
1,325
1,055
633
422
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Autonix.Analyze ( Analyzer , analyzeFiles , analyzePackages ) where import Codec.Archive import Control.Lens import Control.Monad.State import Control.Monad.Trans.Resource import Data.ByteString (ByteString) import Data.Conduit import Data.Map (Map) import Data.Semigroup import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Prelude hiding (mapM) import Autonix.Manifest (Manifest, readManifests) import qualified Autonix.Manifest as Manifest import Autonix.Package (Package, package) import Autonix.Renames type Analyzer m = Text -> Manifest -> Sink (FilePath, ByteString) (ResourceT m) () analyzePackages :: MonadIO m => (Text -> Manifest -> StateT (Map Text Package, Renames) m ()) -> FilePath -> m (Map Text Package, Renames) analyzePackages perPackage manifestPath = flip execStateT (mempty, mempty) $ do manifests <- readManifests manifestPath imapM_ perPackage manifests sequenceSinks_ :: (Traversable f, Monad m) => f (Sink i m ()) -> Sink i m () sequenceSinks_ = void . sequenceSinks analyzeFiles :: (MonadBaseControl IO m, MonadIO m, MonadState (Map Text Package, Renames) m, MonadThrow m) => [Analyzer m] -> Text -> Manifest -> m () analyzeFiles analyzers name m | null (m^.Manifest.store) = error (T.unpack noStore) | otherwise = do liftIO $ T.putStrLn $ "package " <> name let conduits = sourceArchive (m^.Manifest.store) $$ sequenceSinks_ sinks sinks = analyzers >>= \analyze -> return (analyze name m) pkg = package (m^.Manifest.name) (m^.Manifest.src) _1 . at name %= Just . maybe pkg (pkg <>) runResourceT conduits where noStore = "No store path specified for " <> (m^.Manifest.name)
ttuegel/autonix-deps
src/Autonix/Analyze.hs
bsd-3-clause
1,864
0
15
382
619
332
287
-1
-1
{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable , FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, CPP #-} module Transient.MapReduce ( Distributable(..),distribute, getText, getUrl, getFile,textUrl, textFile, mapKeyB, mapKeyU, reduce,eval, --v* internals DDS(..),Partition(..),PartRef(..)) where #ifdef ghcjs_HOST_OS import Transient.Base import Transient.Move hiding (pack) import Transient.Logged -- dummy Transient.MapReduce module, reduce _ _ = local stop :: Loggable a => Cloud a mapKeyB _ _= undefined mapKeyU _ _= undefined distribute _ = undefined getText _ _ = undefined textFile _ = undefined getUrl _ _ = undefined textUrl _ = undefined getFile _ _ = undefined eval _= local stop data Partition data DDS= DDS class Distributable data PartRef a=PartRef a #else import Transient.Internals hiding (Ref) import Transient.Move.Internals hiding (pack) import Transient.Indeterminism import Control.Applicative import System.Random import Control.Monad.State import Control.Monad import Data.Monoid import Data.Typeable import Data.List hiding (delete, foldl') import Control.Exception import Control.Concurrent --import Data.Time.Clock import Network.HTTP import Data.TCache hiding (onNothing) import Data.TCache.Defs import Data.ByteString.Lazy.Char8 (pack,unpack) import qualified Data.Map.Strict as M import Control.Arrow (second) import qualified Data.Vector.Unboxed as DVU import qualified Data.Vector as DV import Data.Hashable import System.IO.Unsafe import qualified Data.Foldable as F import qualified Data.Text as Text import Data.IORef data DDS a= Loggable a => DDS (Cloud (PartRef a)) data PartRef a= Ref Node Path Save deriving (Typeable, Read, Show) data Partition a= Part Node Path Save a deriving (Typeable,Read,Show) type Save= Bool instance Indexable (Partition a) where key (Part _ string b _)= keyp string b keyp s True= "PartP@"++s :: String keyp s False="PartT@"++s instance Loggable a => IResource (Partition a) where keyResource= key readResourceByKey k= r where typePart :: IO (Maybe a) -> a typePart = undefined r = if k !! 4 /= 'P' then return Nothing else defaultReadByKey (defPath (typePart r) ++ k) >>= return . fmap ( read . unpack) writeResource (s@(Part _ _ save _))= unless (not save) $ defaultWrite (defPath s ++ key s) (pack $ show s) eval :: DDS a -> Cloud (PartRef a) eval (DDS mx) = mx type Path=String instance F.Foldable DVU.Vector where {-# INLINE foldr #-} foldr = foldr {-# INLINE foldl #-} foldl = foldl {-# INLINE foldr1 #-} foldr1 = foldr1 {-# INLINE foldl1 #-} foldl1 = foldl1 --foldlIt' :: V.Unbox a => (b -> a -> b) -> b -> V.Vector a -> b --foldlIt' f z0 xs= V.foldr f' id xs z0 -- where f' x k z = k $! f z x -- --foldlIt1 :: V.Unbox a => (a -> a -> a) -> V.Vector a -> a --foldlIt1 f xs = fromMaybe (error "foldl1: empty structure") -- (V.foldl mf Nothing xs) -- where -- mf m y = Just (case m of -- Nothing -> y -- Just x -> f x y) class (F.Foldable c, Typeable c, Typeable a, Monoid (c a), Loggable (c a)) => Distributable c a where singleton :: a -> c a splitAt :: Int -> c a -> (c a, c a) fromList :: [a] -> c a instance (Loggable a) => Distributable DV.Vector a where singleton = DV.singleton splitAt= DV.splitAt fromList = DV.fromList instance (Loggable a,DVU.Unbox a) => Distributable DVU.Vector a where singleton= DVU.singleton splitAt= DVU.splitAt fromList= DVU.fromList -- | perform a map and partition the result with different keys using boxed vectors -- The final result will be used by reduce. mapKeyB :: (Loggable a, Loggable b, Loggable k,Ord k) => (a -> (k,b)) -> DDS (DV.Vector a) -> DDS (M.Map k(DV.Vector b)) mapKeyB= mapKey -- | perform a map and partition the result with different keys using unboxed vectors -- The final result will be used by reduce. mapKeyU :: (Loggable a, DVU.Unbox a, Loggable b, DVU.Unbox b, Loggable k,Ord k) => (a -> (k,b)) -> DDS (DVU.Vector a) -> DDS (M.Map k(DVU.Vector b)) mapKeyU= mapKey -- | perform a map and partition the result with different keys. -- The final result will be used by reduce. mapKey :: (Distributable vector a,Distributable vector b, Loggable k,Ord k) => (a -> (k,b)) -> DDS (vector a) -> DDS (M.Map k (vector b)) mapKey f (DDS mx)= DDS $ loggedc $ do refs <- mx process refs -- !> ("process",refs) where -- process :: Partition a -> Cloud [Partition b] process (ref@(Ref node path sav))= runAt node $ local $ do xs <- getPartitionData ref -- !> ("CMAP", ref,node) (generateRef $ map1 f xs) -- map1 :: (Ord k, F.Foldable vector) => (a -> (k,b)) -> vector a -> M.Map k(vector b) map1 f v= F.foldl' f1 M.empty v where f1 map x= let (k,r) = f x in M.insertWith (<>) k (Transient.MapReduce.singleton r) map data ReduceChunk a= EndReduce | Reduce a deriving (Typeable, Read, Show) boxids= unsafePerformIO $ newIORef (0 :: Int) reduce :: (Hashable k,Ord k, Distributable vector a, Loggable k,Loggable a) => (a -> a -> a) -> DDS (M.Map k (vector a)) ->Cloud (M.Map k a) reduce red (dds@(DDS mx))= loggedc $ do mboxid <- localIO $ atomicModifyIORef boxids $ \n -> let n'= n+1 in (n',n') nodes <- local getEqualNodes let lengthNodes = length nodes shuffler nodes = do localIO $ threadDelay 100000 ref@(Ref node path sav) <- mx -- return the resulting blocks of the map runAt node $ foldAndSend node nodes ref stop -- groupByDestiny :: (Hashable k, Distributable vector a) => M.Map k (vector a) -> M.Map Int [(k ,vector a)] groupByDestiny map = M.foldlWithKey' f M.empty map where -- f :: M.Map Int [(k ,vector a)] -> k -> vector a -> M.Map Int [(k ,vector a)] f map k vs= M.insertWith (<>) (hash1 k) [(k,vs)] map hash1 k= abs $ hash k `rem` length nodes -- foldAndSend :: (Hashable k, Distributable vector a)=> (Int,[(k,vector a)]) -> Cloud () foldAndSend node nodes ref= do pairs <- onAll $ getPartitionData1 ref <|> return (error $ "DDS computed out of his node:"++ show ref ) let mpairs = groupByDestiny pairs length <- local . return $ M.size mpairs let port2= nodePort node if length == 0 then sendEnd nodes else do nsent <- onAll $ liftIO $ newMVar 0 (i,folded) <- local $ parallelize foldthem (M.assocs mpairs) n <- localIO $ modifyMVar nsent $ \r -> return (r+1, r+1) (runAt (nodes !! i) $ local $ putMailbox' mboxid (Reduce folded)) !> ("SENDDDDDDDDDDDDDDDDDDDDDDD",n,length,i,folded) -- return () !> (port,n,length) when (n == length) $ sendEnd nodes empty where foldthem (i,kvs)= async . return $ (i,map (\(k,vs) -> (k,foldl1 red vs)) kvs) sendEnd nodes = onNodes nodes $ local $ do node <- getMyNode putMailbox' mboxid (EndReduce `asTypeOf` paramOf dds) !> ("SEEEEEEEEEEEEEEEEEEEEEEEEND ENDREDUCE FROM", node) onNodes nodes f = foldr (<|>) empty $ map (\n -> runAt n f) nodes sumNodes nodes f= do foldr (<>) mempty $ map (\n -> runAt n f) nodes reducer nodes= sumNodes nodes reduce1 -- a reduce1 process in each node, get the results and mappend them -- reduce :: (Ord k) => Cloud (M.Map k v) reduce1 = local $ do reduceResults <- liftIO $ newMVar M.empty numberSent <- liftIO $ newMVar 0 minput <- getMailbox' mboxid -- get the chunk once it arrives to the mailbox case minput of EndReduce -> do n <- liftIO $ modifyMVar numberSent $ \r -> let r'= r+1 in return (r', r') if n == lengthNodes !> ("END REDUCE RECEIVEDDDDDDDDDDDDDDDDDDDDDDDDDD",n, lengthNodes) then do cleanMailbox' mboxid (EndReduce `asTypeOf` paramOf dds) r <- liftIO $ readMVar reduceResults rem <- getState <|> return NoRemote return r !> ("RETURNING",r,rem) else stop Reduce kvs -> do let addIt (k,inp) = do let input= inp `asTypeOf` atype dds liftIO $ modifyMVar_ reduceResults $ \map -> do let maccum = M.lookup k map return $ M.insert k (case maccum of Just accum -> red input accum Nothing -> input) map mapM addIt (kvs `asTypeOf` paramOf' dds) !> ("RECEIVED REDUCEEEEEEEEEEEEE",kvs) stop reducer nodes <|> shuffler nodes where atype ::DDS(M.Map k (vector a)) -> a atype = undefined -- type level paramOf :: DDS (M.Map k (vector a)) -> ReduceChunk [( k, a)] paramOf = undefined -- type level paramOf' :: DDS (M.Map k (vector a)) -> [( k, a)] paramOf' = undefined -- type level -- parallelize :: Loggable b => (a -> Cloud b) -> [a] -> Cloud b parallelize f xs = foldr (<|>) empty $ map f xs mparallelize f xs = loggedc $ foldr (<>) mempty $ map f xs getPartitionData :: Loggable a => PartRef a -> TransIO a getPartitionData (Ref node path save) = Transient $ do mp <- (liftIO $ atomically $ readDBRef $ getDBRef $ keyp path save) `onNothing` error ("not found DDS data: "++ keyp path save) case mp of (Part _ _ _ xs) -> return $ Just xs getPartitionData1 :: Loggable a => PartRef a -> TransIO a getPartitionData1 (Ref node path save) = Transient $ do mp <- liftIO $ atomically $ readDBRef $ getDBRef $ keyp path save case mp of Just (Part _ _ _ xs) -> return $ Just xs Nothing -> return Nothing getPartitionData2 :: Loggable a => PartRef a -> IO a getPartitionData2 (Ref node path save) = do mp <- ( atomically $ readDBRef $ getDBRef $ keyp path save) `onNothing` error ("not found DDS data: "++ keyp path save) case mp of (Part _ _ _ xs) -> return xs -- en caso de fallo de Node, se lanza un clustered en busca del path -- si solo uno lo tiene, se copia a otro -- se pone ese nodo de referencia en Part runAtP :: Loggable a => Node -> (Path -> IO a) -> Path -> Cloud a runAtP node f uuid= do r <- runAt node $ onAll . liftIO $ (SLast <$> f uuid) `catch` sendAnyError case r of SLast r -> return r SError e -> do nodes <- mclustered $ search uuid when(length nodes < 1) $ asyncDuplicate node uuid runAtP ( head nodes) f uuid search uuid= error $ "chunk failover not yet defined. Lookin for: "++ uuid asyncDuplicate node uuid= do forkTo node nodes <- onAll getEqualNodes let node'= head $ nodes \\ [node] content <- onAll . liftIO $ readFile uuid runAt node' $ local $ liftIO $ writeFile uuid content sendAnyError :: SomeException -> IO (StreamData a) sendAnyError e= return $ SError e -- | distribute a vector of values among many nodes. -- If the vector is static and sharable, better use the get* primitives -- since each node will load the data independently. distribute :: (Loggable a, Distributable vector a ) => vector a -> DDS (vector a) distribute = DDS . distribute' distribute' xs= loggedc $ do nodes <- local getEqualNodes -- !> "DISTRIBUTE" let lnodes = length nodes let size= case F.length xs `div` (length nodes) of 0 ->1 ; n -> n xss= split size lnodes 1 xs -- !> size r <- distribute'' xss nodes return r where split n s s' xs | s==s' = [xs] split n s s' xs= let (h,t)= Transient.MapReduce.splitAt n xs in h : split n s (s'+1) t distribute'' :: (Loggable a, Distributable vector a) => [vector a] -> [Node] -> Cloud (PartRef (vector a)) distribute'' xss nodes = parallelize move $ zip nodes xss -- !> show xss where move (node, xs)= runAt node $ local $ do par <- generateRef xs return par -- !> ("move", node,xs) -- | input data from a text that must be static and shared by all the nodes. -- The function parameter partition the text in words getText :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a) getText part str= DDS $ loggedc $ do nodes <- local getEqualNodes -- !> "getText" return () !> ("DISTRIBUTE TEXT IN NODES:",nodes) let lnodes = length nodes parallelize (process lnodes) $ zip nodes [0..lnodes-1] where process lnodes (node,i)= runAt node $ local $ do let xs = part str size= case length xs `div` lnodes of 0 ->1 ; n -> n xss= Transient.MapReduce.fromList $ if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs generateRef xss -- | get the worlds of an URL textUrl :: String -> DDS (DV.Vector Text.Text) textUrl= getUrl (map Text.pack . words) -- | generate a DDS from the content of a URL. -- The first parameter is a function that divide the text in words getUrl :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a) getUrl partitioner url= DDS $ do nodes <- local getEqualNodes -- !> "DISTRIBUTE" let lnodes = length nodes parallelize (process lnodes) $ zip nodes [0..lnodes-1] -- !> show xss where process lnodes (node,i)= runAt node $ local $ do r <- liftIO . simpleHTTP $ getRequest url body <- liftIO $ getResponseBody r let xs = partitioner body size= case length xs `div` lnodes of 0 ->1 ; n -> n xss= Transient.MapReduce.fromList $ if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs generateRef xss -- | get the words of a file textFile :: String -> DDS (DV.Vector Text.Text) textFile= getFile (map Text.pack . words) -- | generate a DDS from a file. All the nodes must access the file with the same path -- the first parameter is the parser that generates elements from the content getFile :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a) getFile partitioner file= DDS $ do nodes <- local getEqualNodes -- !> "DISTRIBUTE" let lnodes = length nodes parallelize (process lnodes) $ zip nodes [0..lnodes-1] -- !> show xss where process lnodes (node, i)= runAt node $ local $ do content <- do c <- liftIO $ readFile file length c `seq` return c let xs = partitioner content size= case length xs `div` lnodes of 0 ->1 ; n -> n xss= Transient.MapReduce.fromList $ if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs generateRef xss generateRef :: Loggable a => a -> TransIO (PartRef a) generateRef x= do node <- getMyNode liftIO $ do temp <- getTempName let reg= Part node temp False x atomically $ newDBRef reg -- syncCache (return $ getRef reg) -- !> ("generateRef",reg,node) getRef (Part n t s x)= Ref n t s getTempName :: IO String getTempName= ("DDS" ++) <$> replicateM 5 (randomRIO ('a','z')) -------------- Distributed Datasource Streams --------- -- | produce a stream of DDS's that can be map-reduced. Similar to spark streams. -- each interval of time,a new DDS is produced.(to be tested) streamDDS :: (Loggable a, Distributable vector a) => Int -> IO (StreamData a) -> DDS (vector a) streamDDS time io= DDS $ do xs <- local . groupByTime time $ do r <- parallel io case r of SDone -> empty SLast x -> return [x] SMore x -> return [x] SError e -> error $ show e distribute' $ Transient.MapReduce.fromList xs #endif
transient-haskell/transient-universe
src/Transient/MapReduce.hs
mit
17,359
0
6
5,762
228
131
97
-1
-1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import qualified Yesod.Core as YC import qualified Yesod.Static as YS --import qualified Network.EngineIO as EIO import qualified Network.SocketIO as SIO import qualified Data.Text as T import qualified Control.OperationalTransformation.Server as OTS import qualified Control.OperationalTransformation.Text as OTT import qualified Control.OperationalTransformation.Selection as Sel import Network.EngineIO.Yesod (yesodAPI) import Control.Monad.State.Strict (StateT) import Control.Monad.Trans.Reader (ReaderT (..)) import Control.Monad.Reader (MonadReader (..)) import Control.Monad.IO.Class (liftIO) import Control.Monad (mzero) import Control.Applicative import qualified Control.Concurrent.STM as STM import Data.Aeson import qualified Data.Map as M import qualified Data.ByteString.Char8 as BSC8 import Control.Monad (unless) import Data.Monoid import qualified Control.Monad.Logger as ML {- TODO: import file paths from cabal -} data ClientState = ClientState { clientName :: !T.Text , clientSelection :: !Sel.Selection } deriving (Show) instance ToJSON ClientState where toJSON (ClientState name sel) = object $ [ "name" .= name ] ++ (if sel == mempty then [] else [ "selection" .= sel ]) data OTDemo = OTDemo { getStatic :: YS.Static , socketIOHandler :: YC.HandlerT OTDemo IO () , serverState :: STM.TVar (OTS.ServerState T.Text OTT.TextOperation) , clients :: STM.TVar (M.Map T.Text ClientState) } YC.mkYesod "OTDemo" [YC.parseRoutes| / IndexR GET /static StaticR YS.Static getStatic /socket.io/ SocketIOR |] instance YC.Yesod OTDemo where -- do not redirect /socket.io/?bla=blub to /socket.io?bla=blub cleanPath _ ["socket.io",""] = Right ["socket.io"] cleanPath _ s = if corrected == s then Right $ map dropDash s else Left corrected where corrected = filter (not . T.null) s dropDash t | T.all (== '-') t = T.drop 1 t | otherwise = t getIndexR :: Handler () getIndexR = YC.sendFile "text/html" "../../public/index.html" handleSocketIOR :: Handler () handleSocketIOR = YC.getYesod >>= socketIOHandler main :: IO () main = do getStatic <- YS.static "../../public" socketIOHandler <- SIO.initialize yesodAPI server serverState <- STM.newTVarIO (OTS.initialServerState "baba links") clients <- STM.newTVarIO M.empty YC.warp 8000 (OTDemo {..}) ----------------------- newtype Revision = Revision { getRevisionNumber :: Integer } deriving (Num, FromJSON, ToJSON) data UserLogin = UserLogin T.Text instance FromJSON UserLogin where parseJSON (Object o) = UserLogin <$> o .: "name" parseJSON _ = mzero server :: StateT SIO.RoutingTable (ReaderT SIO.Socket Handler) () server = do OTDemo {..} <- YC.getYesod s <- ask let sid = T.pack . BSC8.unpack $ SIO.socketId s runLogging <- flip ML.runLoggingT <$> ML.askLoggerIO $(YC.logDebug) $ "New client joined: " <> sid mayEditTV <- liftIO $ STM.newTVarIO False let mayEdit = liftIO $ STM.readTVarIO mayEditTV SIO.on "login" $ \(UserLogin name) -> do let client = ClientState name mempty liftIO $ STM.atomically $ do STM.writeTVar mayEditTV True STM.modifyTVar clients (M.insert sid client) runLogging $ $(YC.logDebug) $ "Client logged in: " <> sid <> " is now '" <> name <> "'" SIO.broadcastJSON "set_name" [toJSON sid, toJSON name] SIO.emitJSON "logged_in" [] SIO.on "operation" $ \rev op (sel :: Sel.Selection) -> do me <- mayEdit unless me $ fail "user is not allowed to make any changes" runLogging $ $(YC.logDebug) $ "New operation from client " <> sid res <- liftIO $ STM.atomically $ do ss <- STM.readTVar serverState case OTS.applyOperation ss rev op sel of Left err -> return (Left err) Right (op', sel', ss') -> do STM.writeTVar serverState ss' return $ Right (op', sel') case res of Left err -> liftIO $ putStrLn err Right (op', sel') -> do liftIO $ putStrLn $ "new operation: " ++ show op' SIO.emitJSON "ack" [] SIO.broadcastJSON "operation" [toJSON sid, toJSON op', toJSON sel'] SIO.on "selection" $ \sel -> do me <- mayEdit unless me $ fail "user is not allowed to select anything" liftIO $ STM.atomically $ STM.modifyTVar clients (M.adjust (\u -> u { clientSelection = sel }) sid) SIO.broadcastJSON "selection" [toJSON sid, toJSON sel] SIO.appendDisconnectHandler $ do runLogging $ $(YC.logDebug) $ "Client disconnected: " <> sid liftIO $ STM.atomically $ STM.modifyTVar clients (M.delete sid) SIO.broadcast "client_left" sid -- send initial message currClients <- liftIO $ STM.readTVarIO clients OTS.ServerState rev doc _ <- liftIO $ STM.readTVarIO serverState SIO.emit "doc" $ object [ "str" .= doc , "revision" .= rev , "clients" .= currClients ]
Operational-Transformation/ot-demo
backends/haskell/OTDemo.hs
mit
5,137
0
22
1,011
1,569
811
758
123
3
{- | Module : $Header$ Description : pretty printing for CSMOF Copyright : (c) Daniel Calegari Universidad de la Republica, Uruguay 2013 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable -} module CSMOF.Print where import CSMOF.As import Common.Doc import Common.DocUtils instance Pretty Metamodel where pretty (Metamodel nam ele mode) = text "metamodel" <+> text nam <+> lbrace $++$ space <+> space <+> foldr (($++$) . pretty) empty ele $+$ rbrace $++$ foldr (($+$) . pretty) empty mode instance Show Metamodel where show m = show $ pretty m instance Pretty NamedElement where pretty (NamedElement _ _ nes) = pretty nes instance Show NamedElement where show m = show $ pretty m instance Pretty TypeOrTypedElement where pretty (TType typ) = pretty typ pretty (TTypedElement _) = empty -- Do not show properties at top level but inside classes instance Show TypeOrTypedElement where show m = show $ pretty m instance Pretty Type where pretty (Type _ sub) = pretty sub instance Show Type where show m = show $ pretty m instance Pretty DataTypeOrClass where pretty (DDataType dat) = pretty dat pretty (DClass cla) = pretty cla instance Show DataTypeOrClass where show m = show $ pretty m instance Pretty Datatype where pretty (Datatype sup) = text "datatype" <+> text (namedElementName (typeSuper sup)) instance Show Datatype where show m = show $ pretty m instance Pretty Class where pretty (Class sup isa supC own) = text (if isa then "abstract class" else "class") <+> text (namedElementName (typeSuper sup)) <+> (case supC of [] -> lbrace _ : _ -> text "extends" <+> foldr ( (<+>) . text . namedElementName . typeSuper . classSuperType) empty supC <+> lbrace) $+$ space <+> space <+> foldr (($+$) . pretty) empty own $+$ rbrace instance Show Class where show m = show $ pretty m instance Pretty TypedElement where pretty (TypedElement _ _ sub) = pretty sub instance Show TypedElement where show m = show $ pretty m instance Pretty Property where pretty (Property sup mul opp _) = text "property" <+> text (namedElementName (typedElementSuper sup)) <> pretty mul <+> colon <+> text (namedElementName (typeSuper (typedElementType sup))) <+> (case opp of Just n -> text "oppositeOf" <+> text (namedElementName (typedElementSuper (propertySuper n))) Nothing -> empty) instance Show Property where show m = show $ pretty m instance Pretty MultiplicityElement where pretty (MultiplicityElement low upp _) = lbrack <> pretty low <> comma <> (if upp == -1 then text "*" else pretty upp) <> rbrack instance Show MultiplicityElement where show m = show $ pretty m -- Model part of CSMOF instance Pretty Model where pretty (Model mon obj lin mode) = text "model" <+> text mon <+> text "conformsTo" <+> text (metamodelName mode) <+> lbrace $++$ space <+> space <+> foldr (($+$) . pretty) empty obj $++$ space <+> space <+> foldr (($+$) . pretty) empty lin $+$ rbrace instance Show Model where show m = show $ pretty m instance Pretty Object where pretty (Object on ot _) = text "object " <> text on <+> colon <+> text (namedElementName (typeSuper ot)) instance Show Object where show m = show $ pretty m instance Pretty Link where pretty (Link lt sou tar _) = text "link" <+> text (namedElementName (typedElementSuper (propertySuper lt))) <> lparen <> text (objectName sou) <> comma <> text (objectName tar) <> rparen $+$ empty instance Show Link where show m = show $ pretty m
keithodulaigh/Hets
CSMOF/Print.hs
gpl-2.0
3,771
0
22
904
1,273
627
646
92
0
module Data.Bson.Binary.Tests ( tests ) where import Test.Framework (Test, testGroup) tests :: Test tests = testGroup "Data.Bson.Binary.Tests" []
mongodb-haskell/bson
tests/Data/Bson/Binary/Tests.hs
apache-2.0
155
0
6
27
43
26
17
5
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Qt.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:01:40 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qt ( module Qth , module Qtc ) where import Qth import Qtc
keera-studios/hsQt
Qt.hs
bsd-2-clause
481
0
4
98
24
18
6
6
0
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/Attoparsec/Internal/Fhthagn.hs" #-} {-# LANGUAGE BangPatterns, Rank2Types, OverloadedStrings, RecordWildCards, MagicHash, UnboxedTuples #-} module Data.Attoparsec.Internal.Fhthagn ( inlinePerformIO ) where import GHC.Base (realWorld#) import GHC.IO (IO(IO)) -- | Just like unsafePerformIO, but we inline it. Big performance gains as -- it exposes lots of things to further inlining. /Very unsafe/. In -- particular, you should do no memory allocation inside an -- 'inlinePerformIO' block. On Hugs this is just @unsafePerformIO@. inlinePerformIO :: IO a -> a inlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r {-# INLINE inlinePerformIO #-}
phischu/fragnix
tests/packages/scotty/Data.Attoparsec.Internal.Fhthagn.hs
bsd-3-clause
716
0
8
119
89
54
35
12
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ElasticBeanstalk.DescribeApplications -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns the descriptions of existing applications. -- -- <http://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_DescribeApplications.html> module Network.AWS.ElasticBeanstalk.DescribeApplications ( -- * Request DescribeApplications -- ** Request constructor , describeApplications -- ** Request lenses , daApplicationNames -- * Response , DescribeApplicationsResponse -- ** Response constructor , describeApplicationsResponse -- ** Response lenses , darApplications ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.ElasticBeanstalk.Types import qualified GHC.Exts newtype DescribeApplications = DescribeApplications { _daApplicationNames :: List "member" Text } deriving (Eq, Ord, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeApplications where type Item DescribeApplications = Text fromList = DescribeApplications . GHC.Exts.fromList toList = GHC.Exts.toList . _daApplicationNames -- | 'DescribeApplications' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'daApplicationNames' @::@ ['Text'] -- describeApplications :: DescribeApplications describeApplications = DescribeApplications { _daApplicationNames = mempty } -- | If specified, AWS Elastic Beanstalk restricts the returned descriptions to -- only include those with the specified names. daApplicationNames :: Lens' DescribeApplications [Text] daApplicationNames = lens _daApplicationNames (\s a -> s { _daApplicationNames = a }) . _List newtype DescribeApplicationsResponse = DescribeApplicationsResponse { _darApplications :: List "member" ApplicationDescription } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeApplicationsResponse where type Item DescribeApplicationsResponse = ApplicationDescription fromList = DescribeApplicationsResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _darApplications -- | 'DescribeApplicationsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'darApplications' @::@ ['ApplicationDescription'] -- describeApplicationsResponse :: DescribeApplicationsResponse describeApplicationsResponse = DescribeApplicationsResponse { _darApplications = mempty } -- | This parameter contains a list of 'ApplicationDescription'. darApplications :: Lens' DescribeApplicationsResponse [ApplicationDescription] darApplications = lens _darApplications (\s a -> s { _darApplications = a }) . _List instance ToPath DescribeApplications where toPath = const "/" instance ToQuery DescribeApplications where toQuery DescribeApplications{..} = mconcat [ "ApplicationNames" =? _daApplicationNames ] instance ToHeaders DescribeApplications instance AWSRequest DescribeApplications where type Sv DescribeApplications = ElasticBeanstalk type Rs DescribeApplications = DescribeApplicationsResponse request = post "DescribeApplications" response = xmlResponse instance FromXML DescribeApplicationsResponse where parseXML = withElement "DescribeApplicationsResult" $ \x -> DescribeApplicationsResponse <$> x .@? "Applications" .!@ mempty
kim/amazonka
amazonka-elasticbeanstalk/gen/Network/AWS/ElasticBeanstalk/DescribeApplications.hs
mpl-2.0
4,331
0
10
812
530
319
211
62
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.NormalMap -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable module Yi.Keymap.Vim.NormalMap (defNormalMap) where import Prelude hiding (lookup) import Lens.Micro.Platform (use, (.=)) import Control.Monad (replicateM_, unless, void, when) import Data.Char (ord) import Data.HashMap.Strict (lookup, singleton) import Data.List (group) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import qualified Data.Text as T (drop, empty, pack, replicate, unpack) import System.Directory (doesFileExist) import System.FriendlyPath (expandTilda) import Yi.Buffer.Adjusted hiding (Insert) import Yi.Core (closeWindow, quitEditor) import Yi.Editor import Yi.Event (Event (Event), Key (KASCII, KEnter, KEsc, KTab), Modifier (MCtrl)) import Yi.File (fwriteE, openNewFile) import Yi.History (historyPrefixSet, historyStart) import Yi.Keymap (YiM) import Yi.Keymap.Keys (char, ctrlCh, spec) import Yi.Keymap.Vim.Common import Yi.Keymap.Vim.Eval (scheduleActionStringForEval) import Yi.Keymap.Vim.Motion (CountedMove (CountedMove), regionOfMoveB, stringToMove) import Yi.Keymap.Vim.Operator (VimOperator (..), opChange, opDelete, opYank) import Yi.Keymap.Vim.Search (doVimSearch) import Yi.Keymap.Vim.StateUtils import Yi.Keymap.Vim.StyledRegion (StyledRegion (StyledRegion), transformCharactersInLineN) import Yi.Keymap.Vim.Tag (gotoTag, popTag) import Yi.Keymap.Vim.Utils import Yi.MiniBuffer (spawnMinibufferE) import Yi.Misc (printFileInfoE) import Yi.Monad (maybeM, whenM) import Yi.Regex (makeSearchOptsM, seInput) import qualified Yi.Rope as R (fromText, null, toString, toText) import Yi.Search (getRegexE, isearchInitE, makeSimpleSearch, setRegexE) import Yi.String (showT) import Yi.Tag (Tag (..)) import Yi.Utils (io) data EOLStickiness = Sticky | NonSticky deriving Eq mkDigitBinding :: Char -> VimBinding mkDigitBinding c = mkBindingE Normal Continue (char c, return (), mutate) where mutate vs@(VimState {vsCount = Nothing}) = vs { vsCount = Just d } mutate vs@(VimState {vsCount = Just count}) = vs { vsCount = Just $ count * 10 + d } d = ord c - ord '0' defNormalMap :: [VimOperator] -> [VimBinding] defNormalMap operators = [recordMacroBinding, finishRecordingMacroBinding, playMacroBinding] <> [zeroBinding, repeatBinding, motionBinding, searchBinding] <> [chooseRegisterBinding, setMarkBinding] <> fmap mkDigitBinding ['1' .. '9'] <> operatorBindings operators <> finishingBingings <> continuingBindings <> nonrepeatableBindings <> jumpBindings <> fileEditBindings <> [tabTraversalBinding] <> [tagJumpBinding, tagPopBinding] tagJumpBinding :: VimBinding tagJumpBinding = mkBindingY Normal (Event (KASCII ']') [MCtrl], f, id) where f = withCurrentBuffer readCurrentWordB >>= g . Tag . R.toText g tag = gotoTag tag 0 Nothing tagPopBinding :: VimBinding tagPopBinding = mkBindingY Normal (Event (KASCII 't') [MCtrl], f, id) where f = popTag motionBinding :: VimBinding motionBinding = mkMotionBinding Drop $ \m -> case m of Normal -> True _ -> False chooseRegisterBinding :: VimBinding chooseRegisterBinding = mkChooseRegisterBinding ((== Normal) . vsMode) zeroBinding :: VimBinding zeroBinding = VimBindingE f where f "0" (VimState {vsMode = Normal}) = WholeMatch $ do currentState <- getEditorDyn case vsCount currentState of Just c -> do setCountE (10 * c) return Continue Nothing -> do withCurrentBuffer moveToSol resetCountE withCurrentBuffer $ stickyEolA .= False return Drop f _ _ = NoMatch repeatBinding :: VimBinding repeatBinding = VimBindingE (f . T.unpack . _unEv) where f "." (VimState {vsMode = Normal}) = WholeMatch $ do currentState <- getEditorDyn case vsRepeatableAction currentState of Nothing -> return () Just (RepeatableAction prevCount (Ev actionString)) -> do let count = showT $ fromMaybe prevCount (vsCount currentState) scheduleActionStringForEval . Ev $ count <> actionString resetCountE return Drop f _ _ = NoMatch jumpBindings :: [VimBinding] jumpBindings = fmap (mkBindingE Normal Drop) [ (ctrlCh 'o', jumpBackE, id) , (spec KTab, jumpForwardE, id) , (ctrlCh '^', controlCarrot, resetCount) , (ctrlCh '6', controlCarrot, resetCount) ] where controlCarrot = alternateBufferE . (+ (-1)) =<< getCountE finishingBingings :: [VimBinding] finishingBingings = fmap (mkStringBindingE Normal Finish) [ ("x", cutCharE Forward NonSticky =<< getCountE, resetCount) , ("<Del>", cutCharE Forward NonSticky =<< getCountE, resetCount) , ("X", cutCharE Backward NonSticky =<< getCountE, resetCount) , ("D", do region <- withCurrentBuffer $ regionWithTwoMovesB (return ()) moveToEol void $ operatorApplyToRegionE opDelete 1 $ StyledRegion Exclusive region , id) -- Pasting , ("p", pasteAfter, id) , ("P", pasteBefore, id) -- Miscellaneous. , ("~", do count <- getCountE withCurrentBuffer $ do transformCharactersInLineN count switchCaseChar leftOnEol , resetCount) , ("J", do count <- fmap (flip (-) 1 . max 2) getCountE withCurrentBuffer $ do (StyledRegion s r) <- case stringToMove "j" of WholeMatch m -> regionOfMoveB $ CountedMove (Just count) m _ -> error "can't happen" void $ lineMoveRel $ count - 1 moveToEol joinLinesB =<< convertRegionToStyleB r s , resetCount) ] pasteBefore :: EditorM () pasteBefore = do -- TODO: use count register <- getRegisterE . vsActiveRegister =<< getEditorDyn case register of Nothing -> return () Just (Register LineWise rope) -> withCurrentBuffer $ unless (R.null rope) $ -- Beware of edge cases ahead insertRopeWithStyleB (addNewLineIfNecessary rope) LineWise Just (Register style rope) -> withCurrentBuffer $ pasteInclusiveB rope style pasteAfter :: EditorM () pasteAfter = do -- TODO: use count register <- getRegisterE . vsActiveRegister =<< getEditorDyn case register of Nothing -> return () Just (Register LineWise rope) -> withCurrentBuffer $ do -- Beware of edge cases ahead moveToEol eof <- atEof when eof $ insertB '\n' rightB insertRopeWithStyleB (addNewLineIfNecessary rope) LineWise when eof $ savingPointB $ do newSize <- sizeB moveTo (newSize - 1) curChar <- readB when (curChar == '\n') $ deleteN 1 Just (Register style rope) -> withCurrentBuffer $ do whenM (fmap not atEol) rightB pasteInclusiveB rope style operatorBindings :: [VimOperator] -> [VimBinding] operatorBindings = fmap mkOperatorBinding where mkT (Op o) = (Ev o, return (), switchMode . NormalOperatorPending $ Op o) mkOperatorBinding (VimOperator {operatorName = opName}) = mkStringBindingE Normal Continue $ mkT opName continuingBindings :: [VimBinding] continuingBindings = fmap (mkStringBindingE Normal Continue) [ ("r", return (), switchMode ReplaceSingleChar) -- TODO make it just a binding -- Transition to insert mode , ("i", return (), switchMode $ Insert 'i') , ("<Ins>", return (), switchMode $ Insert 'i') , ("I", withCurrentBuffer firstNonSpaceB, switchMode $ Insert 'I') , ("a", withCurrentBuffer $ moveXorEol 1, switchMode $ Insert 'a') , ("A", withCurrentBuffer moveToEol, switchMode $ Insert 'A') , ("o", withCurrentBuffer $ do moveToEol newlineB indentAsTheMostIndentedNeighborLineB , switchMode $ Insert 'o') , ("O", withCurrentBuffer $ do moveToSol newlineB leftB indentAsNextB , switchMode $ Insert 'O') -- Transition to visual , ("v", enableVisualE Inclusive, resetCount . switchMode (Visual Inclusive)) , ("V", enableVisualE LineWise, resetCount . switchMode (Visual LineWise)) , ("<C-v>", enableVisualE Block, resetCount . switchMode (Visual Block)) ] nonrepeatableBindings :: [VimBinding] nonrepeatableBindings = fmap (mkBindingE Normal Drop) [ (spec KEsc, return (), resetCount) , (ctrlCh 'c', return (), resetCount) -- Changing , (char 'C', do region <- withCurrentBuffer $ regionWithTwoMovesB (return ()) moveToEol void $ operatorApplyToRegionE opChange 1 $ StyledRegion Exclusive region , switchMode $ Insert 'C') , (char 's', cutCharE Forward Sticky =<< getCountE, switchMode $ Insert 's') , (char 'S', do region <- withCurrentBuffer $ regionWithTwoMovesB firstNonSpaceB moveToEol void $ operatorApplyToRegionE opDelete 1 $ StyledRegion Exclusive region , switchMode $ Insert 'S') -- Replacing , (char 'R', return (), switchMode Replace) -- Yanking , ( char 'Y' , do region <- withCurrentBuffer $ regionWithTwoMovesB (return ()) moveToEol void $ operatorApplyToRegionE opYank 1 $ StyledRegion Exclusive region , id ) -- Search , (char '*', addVimJumpHereE >> searchWordE True Forward, resetCount) , (char '#', addVimJumpHereE >> searchWordE True Backward, resetCount) , (char 'n', addVimJumpHereE >> withCount (continueSearching id), resetCount) , (char 'N', addVimJumpHereE >> withCount (continueSearching reverseDir), resetCount) , (char ';', repeatGotoCharE id, id) , (char ',', repeatGotoCharE reverseDir, id) -- Repeat , (char '&', return (), id) -- TODO -- Transition to ex , (char ':', do void (spawnMinibufferE ":" id) historyStart historyPrefixSet "" , switchMode Ex) -- Undo , (char 'u', withCountOnBuffer undoB >> withCurrentBuffer leftOnEol, id) , (char 'U', withCountOnBuffer undoB >> withCurrentBuffer leftOnEol, id) -- TODO , (ctrlCh 'r', withCountOnBuffer redoB >> withCurrentBuffer leftOnEol, id) -- scrolling ,(ctrlCh 'b', getCountE >>= withCurrentBuffer . upScreensB, id) ,(ctrlCh 'f', getCountE >>= withCurrentBuffer . downScreensB, id) ,(ctrlCh 'u', getCountE >>= withCurrentBuffer . vimScrollByB (negate . (`div` 2)), id) ,(ctrlCh 'd', getCountE >>= withCurrentBuffer . vimScrollByB (`div` 2), id) ,(ctrlCh 'y', getCountE >>= withCurrentBuffer . vimScrollB . negate, id) ,(ctrlCh 'e', getCountE >>= withCurrentBuffer . vimScrollB, id) -- unsorted TODO , (char '-', return (), id) , (char '+', return (), id) , (spec KEnter, return (), id) ] <> fmap (mkStringBindingE Normal Drop) [ ("g*", searchWordE False Forward, resetCount) , ("g#", searchWordE False Backward, resetCount) , ("gd", withCurrentBuffer $ withModeB modeGotoDeclaration, resetCount) , ("gD", withCurrentBuffer $ withModeB modeGotoDeclaration, resetCount) , ("<C-g>", printFileInfoE, resetCount) , ("<C-w>c", tryCloseE, resetCount) , ("<C-w>o", closeOtherE, resetCount) , ("<C-w>s", splitE, resetCount) , ("<C-w>w", nextWinE, resetCount) , ("<C-w><Down>", nextWinE, resetCount) -- TODO: please implement downWinE , ("<C-w><Right>", nextWinE, resetCount) -- TODO: please implement rightWinE , ("<C-w><C-w>", nextWinE, resetCount) , ("<C-w>W", prevWinE, resetCount) , ("<C-w>p", prevWinE, resetCount) , ("<C-w><Up>", prevWinE, resetCount) -- TODO: please implement upWinE , ("<C-w><Left>", prevWinE, resetCount) -- TODO: please implement leftWinE , ("<C-w>l", layoutManagersNextE, resetCount) , ("<C-w>L", layoutManagersPreviousE, resetCount) --, ("<C-w> ", layoutManagersNextE, resetCount) , ("<C-w>v", layoutManagerNextVariantE, resetCount) , ("<C-w>V", layoutManagerPreviousVariantE, resetCount) , ("<C-a>", getCountE >>= withCurrentBuffer . incrementNextNumberByB, resetCount) , ("<C-x>", getCountE >>= withCurrentBuffer . incrementNextNumberByB . negate, resetCount) -- z commands -- TODO Add prefix count , ("zt", withCurrentBuffer scrollCursorToTopB, resetCount) , ("zb", withCurrentBuffer scrollCursorToBottomB, resetCount) , ("zz", withCurrentBuffer scrollToCursorB, resetCount) {- -- TODO Horizantal scrolling , ("ze", withCurrentBuffer .., resetCount) , ("zs", withCurrentBuffer .., resetCount) , ("zH", withCurrentBuffer .., resetCount) , ("zL", withCurrentBuffer .., resetCount) , ("zh", withCurrentBuffer .., resetCount) , ("zl", withCurrentBuffer .., resetCount) -} , ("z.", withCurrentBuffer $ scrollToCursorB >> moveToSol, resetCount) , ("z+", withCurrentBuffer scrollToLineBelowWindowB, resetCount) , ("z-", withCurrentBuffer $ scrollCursorToBottomB >> moveToSol, resetCount) , ("z^", withCurrentBuffer scrollToLineAboveWindowB, resetCount) {- -- TODO Code folding , ("zf", .., resetCount) , ("zc", .., resetCount) , ("zo", .., resetCount) , ("za", .., resetCount) , ("zC", .., resetCount) , ("zO", .., resetCount) , ("zA", .., resetCount) , ("zr", .., resetCount) , ("zR", .., resetCount) , ("zm", .., resetCount) , ("zM", .., resetCount) -} -- Z commands ] <> fmap (mkStringBindingY Normal) [ ("ZQ", quitEditor, id) -- TODO ZZ should replicate :x not :wq , ("ZZ", fwriteE >> closeWindow, id) ] fileEditBindings :: [VimBinding] fileEditBindings = fmap (mkStringBindingY Normal) [ ("gf", openFileUnderCursor Nothing, resetCount) , ("<C-w>gf", openFileUnderCursor $ Just newTabE, resetCount) , ("<C-w>f", openFileUnderCursor $ Just (splitE >> prevWinE), resetCount) ] setMarkBinding :: VimBinding setMarkBinding = VimBindingE (f . T.unpack . _unEv) where f _ s | vsMode s /= Normal = NoMatch f "m" _ = PartialMatch f ('m':c:[]) _ = WholeMatch $ do withCurrentBuffer $ setNamedMarkHereB [c] return Drop f _ _ = NoMatch searchWordE :: Bool -> Direction -> EditorM () searchWordE wholeWord dir = do word <- withCurrentBuffer readCurrentWordB let search re = do setRegexE re searchDirectionA .= dir withCount $ continueSearching (const dir) if wholeWord then case makeSearchOptsM [] $ "\\<" <> R.toString word <> "\\>" of Right re -> search re Left _ -> return () else search $ makeSimpleSearch word searchBinding :: VimBinding searchBinding = VimBindingE (f . T.unpack . _unEv) where f evs (VimState { vsMode = Normal }) | evs `elem` group ['/', '?'] = WholeMatch $ do state <- fmap vsMode getEditorDyn let dir = if evs == "/" then Forward else Backward switchModeE $ Search state dir isearchInitE dir historyStart historyPrefixSet T.empty return Continue f _ _ = NoMatch continueSearching :: (Direction -> Direction) -> EditorM () continueSearching fdir = getRegexE >>= \case Just regex -> do dir <- fdir <$> use searchDirectionA printMsg . T.pack $ (if dir == Forward then '/' else '?') : seInput regex void $ doVimSearch Nothing [] dir Nothing -> printMsg "No previous search pattern" repeatGotoCharE :: (Direction -> Direction) -> EditorM () repeatGotoCharE mutateDir = do prevCommand <- fmap vsLastGotoCharCommand getEditorDyn count <- getCountE withCurrentBuffer $ case prevCommand of Just (GotoCharCommand c dir style) -> do let newDir = mutateDir dir let move = gotoCharacterB c newDir style True p0 <- pointB replicateM_ (count - 1) $ do move when (style == Exclusive) $ moveB Character newDir p1 <- pointB move p2 <- pointB when (p1 == p2) $ moveTo p0 Nothing -> return () enableVisualE :: RegionStyle -> EditorM () enableVisualE style = withCurrentBuffer $ do putRegionStyle style rectangleSelectionA .= (Block == style) setVisibleSelection True pointB >>= setSelectionMarkPointB cutCharE :: Direction -> EOLStickiness -> Int -> EditorM () cutCharE dir stickiness count = do r <- withCurrentBuffer $ do p0 <- pointB (if dir == Forward then moveXorEol else moveXorSol) count p1 <- pointB let region = mkRegion p0 p1 rope <- readRegionB region deleteRegionB $ mkRegion p0 p1 when (stickiness == NonSticky) leftOnEol return rope regName <- fmap vsActiveRegister getEditorDyn setRegisterE regName Inclusive r tabTraversalBinding :: VimBinding tabTraversalBinding = VimBindingE (f . T.unpack . _unEv) where f "g" (VimState { vsMode = Normal }) = PartialMatch f ('g':c:[]) (VimState { vsMode = Normal }) | c `elem` ['t', 'T'] = WholeMatch $ do count <- getCountE replicateM_ count $ if c == 'T' then previousTabE else nextTabE resetCountE return Drop f _ _ = NoMatch openFileUnderCursor :: Maybe (EditorM ()) -> YiM () openFileUnderCursor editorAction = do fileName <- fmap R.toString . withCurrentBuffer $ readUnitB unitViWORD fileExists <- io $ doesFileExist =<< expandTilda fileName if fileExists then do maybeM withEditor editorAction openNewFile $ fileName else withEditor . fail $ "Can't find file \"" <> fileName <> "\"" recordMacroBinding :: VimBinding recordMacroBinding = VimBindingE (f . T.unpack . _unEv) where f "q" (VimState { vsMode = Normal , vsCurrentMacroRecording = Nothing }) = PartialMatch f ['q', c] (VimState { vsMode = Normal }) = WholeMatch $ do modifyStateE $ \s -> s { vsCurrentMacroRecording = Just (c, mempty) } return Finish f _ _ = NoMatch finishRecordingMacroBinding :: VimBinding finishRecordingMacroBinding = VimBindingE (f . T.unpack . _unEv) where f "q" (VimState { vsMode = Normal , vsCurrentMacroRecording = Just (macroName, Ev macroBody) }) = WholeMatch $ do let reg = Register Exclusive (R.fromText (T.drop 2 macroBody)) modifyStateE $ \s -> s { vsCurrentMacroRecording = Nothing , vsRegisterMap = singleton macroName reg <> vsRegisterMap s } return Finish f _ _ = NoMatch playMacroBinding :: VimBinding playMacroBinding = VimBindingE (f . T.unpack . _unEv) where f "@" (VimState { vsMode = Normal }) = PartialMatch f ['@', c] (VimState { vsMode = Normal , vsRegisterMap = registers , vsCount = mbCount }) = WholeMatch $ do resetCountE case lookup c registers of Just (Register _ evs) -> do let count = fromMaybe 1 mbCount mkAct = Ev . T.replicate count . R.toText scheduleActionStringForEval . mkAct $ evs return Finish Nothing -> return Drop f _ _ = NoMatch -- TODO: withCount name implies that parameter has type (Int -> EditorM ()) -- Is there a better name for this function? withCount :: EditorM () -> EditorM () withCount action = flip replicateM_ action =<< getCountE withCountOnBuffer :: BufferM () -> EditorM () withCountOnBuffer action = withCount $ withCurrentBuffer action
siddhanathan/yi
yi-keymap-vim/src/Yi/Keymap/Vim/NormalMap.hs
gpl-2.0
21,110
120
21
6,206
5,563
2,998
2,565
405
4
{-| Auto-repair task of the maintenance daemon. This module implements the non-pure parts of harep-style repairs carried out by the maintenance daemon. -} {- Copyright (C) 2015 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.MaintD.Autorepairs ( harepTasks ) where import Control.Arrow (second, (***)) import Control.Monad (forM) import Control.Exception (bracket) import Data.Maybe (isJust, fromJust) import qualified Data.Set as Set import System.IO.Error (tryIOError) import System.Time (getClockTime) import Ganeti.BasicTypes import Ganeti.Errors (formatError) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Node as Node import Ganeti.HTools.Repair import Ganeti.HTools.Types import Ganeti.JQueue (currentTimestamp) import Ganeti.Jobs (execJobsWaitOkJid, submitJobs) import Ganeti.Logging.Lifted import qualified Ganeti.Luxi as L import Ganeti.MaintD.Utils (annotateOpCode) import Ganeti.OpCodes (OpCode(..)) import qualified Ganeti.Path as Path import Ganeti.Types (JobId, JobStatus(..), TagKind(..), mkNonNegative) import Ganeti.Utils (newUUID, logAndBad) -- | Apply and remove tags form an instance indicated by `InstanceData`. commitChange :: L.Client -> InstanceData -> ResultT String IO (InstanceData, [JobId]) commitChange client instData = do now <- liftIO currentTimestamp let arData = getArData $ arState instData iname = Instance.name $ arInstance instData rmTags = tagsToRemove instData addJobs <- if isJust arData then do let tag = arTag $ fromJust arData logDebug $ "Adding tag " ++ tag ++ " to " ++ iname mkResultT $ execJobsWaitOkJid [[ annotateOpCode "harep state tagging" now . OpTagsSet TagKindInstance [tag] $ Just iname ]] client else return [] rmJobs <- if null rmTags then return [] else do logDebug $ "Removing tags " ++ show rmTags ++ " from " ++ iname mkResultT $ execJobsWaitOkJid [[ annotateOpCode "harep state tag removal" now . OpTagsDel TagKindInstance rmTags $ Just iname ]] client return (instData { tagsToRemove = [] }, addJobs ++ rmJobs) -- | Query jobs of a pending repair, returning the new instance data. processPending :: L.Client -> InstanceData -> IO (Result (InstanceData, [JobId])) processPending client instData = runResultT $ case arState instData of (ArPendingRepair arData) -> do sts <- liftIO . L.queryJobsStatus client $ arJobs arData time <- liftIO getClockTime case sts of Bad e -> mkResultT . logAndBad $ "Could not check job status: " ++ formatError e Ok sts' -> if any (<= JOB_STATUS_RUNNING) sts' then return (instData, []) else do let iname = Instance.name $ arInstance instData srcSt = arStateName $ arState instData arState' = if all (== JOB_STATUS_SUCCESS) sts' then ArHealthy . Just . updateTag $ arData { arResult = Just ArSuccess , arTime = time } else ArFailedRepair . updateTag $ arData { arResult = Just ArFailure, arTime = time } destSt = arStateName arState' instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } logInfo $ "Moving " ++ iname ++ " form " ++ show srcSt ++ " to " ++ show destSt commitChange client instData' _ -> return (instData, []) -- | Perfom the suggested repair on an instance if its policy allows it -- and return the list of submitted jobs. doRepair :: L.Client -> InstanceData -> (AutoRepairType, [OpCode]) -> IO (Result ([Idx], [JobId])) doRepair client instData (rtype, opcodes) = runResultT $ do let inst = arInstance instData ipol = Instance.arPolicy inst iname = Instance.name inst case ipol of ArEnabled maxtype -> do uuid <- liftIO newUUID time <- liftIO getClockTime if rtype > maxtype then do let arState' = ArNeedsRepair ( updateTag $ AutoRepairData rtype uuid time [] (Just ArEnoperm) "") instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } logInfo $ "Not performing repair of type " ++ show rtype ++ " on " ++ iname ++ " because only repairs up to " ++ show maxtype ++ " are allowed" (_, jobs) <- commitChange client instData' return ([], jobs) else do now <- liftIO currentTimestamp logInfo $ "Executing " ++ show rtype ++ " repair on " ++ iname -- As in harep, we delay the actual repair, to allow the tagging -- to happen first; again this is only about speeding up the harep -- round, not about correctness. let opcodes' = OpTestDelay { opDelayDuration = 10 , opDelayOnMaster = True , opDelayOnNodes = [] , opDelayOnNodeUuids = Nothing , opDelayRepeat = fromJust $ mkNonNegative 0 , opDelayInterruptible = False , opDelayNoLocks = False } : opcodes jids <- liftIO $ submitJobs [ map (annotateOpCode "harep-style repair" now) opcodes'] client case jids of Bad e -> mkResultT . logAndBad $ "Failure submitting repair jobs: " ++ e Ok jids' -> do let arState' = ArPendingRepair ( updateTag $ AutoRepairData rtype uuid time jids' Nothing "") instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } (_, tagjobs) <- commitChange client instData' let nodes = filter (>= 0) [Instance.pNode inst, Instance.sNode inst] return (nodes, jids' ++ tagjobs) otherSt -> do logDebug $ "Not repairing " ++ iname ++ " because it is in state " ++ show otherSt return ([], []) -- | Harep-like repair tasks. harepTasks :: (Node.List, Instance.List) -- ^ Current cluster configuration -> Set.Set Int -- ^ Node indices on which actions may be taken -> ResultT String IO (Set.Set Int, [JobId]) -- ^ untouched nodes and jobs submitted harepTasks (nl, il) nidxs = do logDebug $ "harep tasks on nodes " ++ show (Set.toList nidxs) iniData <- mkResultT . return . mapM setInitialState $ Container.elems il -- First step: check all pending repairs, see if they are completed. luxiSocket <- liftIO Path.defaultQuerySocket either_iData <- liftIO . tryIOError . bracket (L.getLuxiClient luxiSocket) L.closeClient $ forM iniData . processPending (iData', jobs) <- mkResultT $ case either_iData of Left e -> logAndBad $ "Error while harep status update: " ++ show e Right r -> if any isBad r then logAndBad $ "Bad harep processing pending: " ++ show (justBad r) else return . Ok . second concat . unzip $ justOk r -- Second step: detect any problems. let repairs = map (detectBroken nl . arInstance) iData' -- Third step: create repair jobs for broken instances that are in ArHealthy. let repairIfHealthy c i = case arState i of ArHealthy _ -> doRepair c i _ -> const . return $ Ok ([], []) maybeRepair c (i, r) = maybe (return $ Ok ([], [])) (repairIfHealthy c i) r either_repairJobs <- liftIO . tryIOError . bracket (L.getLuxiClient luxiSocket) L.closeClient $ forM (zip iData' repairs) . maybeRepair (ntouched, jobs') <- mkResultT $ case either_repairJobs of Left e -> logAndBad $ "Error while attempting repair: " ++ show e Right r -> if any isBad r then logAndBad $ "Error submitting repair jobs: " ++ show (justBad r) else return . Ok . (concat *** concat) . unzip $ justOk r return (nidxs Set.\\ Set.fromList ntouched, jobs ++ jobs' )
leshchevds/ganeti
src/Ganeti/MaintD/Autorepairs.hs
bsd-2-clause
10,592
0
27
3,754
2,135
1,106
1,029
171
6
{-# LANGUAGE DeriveGeneric #-} module Auto.G.BigProduct where import Control.DeepSeq import Data.Aeson import GHC.Generics (Generic) import Options data BigProduct = BigProduct !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int !Int deriving (Show, Eq, Generic) instance NFData BigProduct where rnf a = a `seq` () instance ToJSON BigProduct where toJSON = genericToJSON opts toEncoding = genericToEncoding opts instance FromJSON BigProduct where parseJSON = genericParseJSON opts bigProduct :: BigProduct bigProduct = BigProduct 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
dmjio/aeson
benchmarks/bench/Auto/G/BigProduct.hs
bsd-3-clause
808
1
7
254
255
121
134
76
1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.DynamicWorkspaces -- Copyright : (c) David Roundy <[email protected]> -- License : BSD3-style (see LICENSE) -- -- Maintainer : none -- Stability : unstable -- Portability : unportable -- -- Provides bindings to add and delete workspaces. -- ----------------------------------------------------------------------------- module XMonad.Actions.DynamicWorkspaces ( -- * Usage -- $usage addWorkspace, addWorkspacePrompt, removeWorkspace, removeEmptyWorkspace, removeEmptyWorkspaceAfter, removeEmptyWorkspaceAfterExcept, addHiddenWorkspace, withWorkspace, selectWorkspace, renameWorkspace, toNthWorkspace, withNthWorkspace ) where import XMonad hiding (workspaces) import XMonad.StackSet hiding (filter, modify, delete) import XMonad.Prompt.Workspace ( Wor(Wor), workspacePrompt ) import XMonad.Prompt ( XPConfig, mkXPrompt ) import XMonad.Util.WorkspaceCompare ( getSortByIndex ) import Data.List (find) import Data.Maybe (isNothing) import Control.Monad (when) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@ file: -- -- > import XMonad.Actions.DynamicWorkspaces -- > import XMonad.Actions.CopyWindow(copy) -- -- Then add keybindings like the following: -- -- > , ((modm .|. shiftMask, xK_BackSpace), removeWorkspace) -- > , ((modm .|. shiftMask, xK_v ), selectWorkspace defaultXPConfig) -- > , ((modm, xK_m ), withWorkspace defaultXPConfig (windows . W.shift)) -- > , ((modm .|. shiftMask, xK_m ), withWorkspace defaultXPConfig (windows . copy)) -- > , ((modm .|. shiftMask, xK_r ), renameWorkspace defaultXPConfig) -- -- > -- mod-[1..9] %! Switch to workspace N -- > -- mod-shift-[1..9] %! Move client to workspace N -- > ++ -- > zip (zip (repeat (modm)) [xK_1..xK_9]) (map (withNthWorkspace W.greedyView) [0..]) -- > ++ -- > zip (zip (repeat (modm .|. shiftMask)) [xK_1..xK_9]) (map (withNthWorkspace W.shift) [0..]) -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". See also the documentation for -- "XMonad.Actions.CopyWindow", 'windows', 'shift', and 'defaultXPConfig'. mkCompl :: [String] -> String -> IO [String] mkCompl l s = return $ filter (\x -> take (length s) x == s) l withWorkspace :: XPConfig -> (String -> X ()) -> X () withWorkspace c job = do ws <- gets (workspaces . windowset) sort <- getSortByIndex let ts = map tag $ sort ws job' t | t `elem` ts = job t | otherwise = addHiddenWorkspace t >> job t mkXPrompt (Wor "") c (mkCompl ts) job' renameWorkspace :: XPConfig -> X () renameWorkspace conf = workspacePrompt conf $ \w -> windows $ \s -> let sett wk = wk { tag = w } setscr scr = scr { workspace = sett $ workspace scr } sets q = q { current = setscr $ current q } in sets $ removeWorkspace' w s toNthWorkspace :: (String -> X ()) -> Int -> X () toNthWorkspace job wnum = do sort <- getSortByIndex ws <- gets (map tag . sort . workspaces . windowset) case drop wnum ws of (w:_) -> job w [] -> return () withNthWorkspace :: (String -> WindowSet -> WindowSet) -> Int -> X () withNthWorkspace job wnum = do sort <- getSortByIndex ws <- gets (map tag . sort . workspaces . windowset) case drop wnum ws of (w:_) -> windows $ job w [] -> return () selectWorkspace :: XPConfig -> X () selectWorkspace conf = workspacePrompt conf $ \w -> do s <- gets windowset if tagMember w s then windows $ greedyView w else addWorkspace w -- | Add a new workspace with the given name, or do nothing if a -- workspace with the given name already exists; then switch to the -- newly created workspace. addWorkspace :: String -> X () addWorkspace newtag = addHiddenWorkspace newtag >> windows (greedyView newtag) -- | Prompt for the name of a new workspace, add it if it does not -- already exist, and switch to it. addWorkspacePrompt :: XPConfig -> X () addWorkspacePrompt conf = mkXPrompt (Wor "New workspace name: ") conf (const (return [])) addWorkspace -- | Add a new hidden workspace with the given name, or do nothing if -- a workspace with the given name already exists. addHiddenWorkspace :: String -> X () addHiddenWorkspace newtag = whenX (gets (not . tagMember newtag . windowset)) $ do l <- asks (layoutHook . config) windows (addHiddenWorkspace' newtag l) -- | Remove the current workspace if it contains no windows. removeEmptyWorkspace :: X () removeEmptyWorkspace = gets (currentTag . windowset) >>= removeEmptyWorkspaceByTag -- | Remove the current workspace. removeWorkspace :: X () removeWorkspace = gets (currentTag . windowset) >>= removeWorkspaceByTag -- | Remove workspace with specific tag if it contains no windows. Only works -- on the current or the last workspace. removeEmptyWorkspaceByTag :: String -> X () removeEmptyWorkspaceByTag t = whenX (isEmpty t) $ removeWorkspaceByTag t -- | Remove workspace with specific tag. Only works on the current or the last workspace. removeWorkspaceByTag :: String -> X () removeWorkspaceByTag torem = do s <- gets windowset case s of StackSet { current = Screen { workspace = cur }, hidden = (w:_) } -> do when (torem==tag cur) $ windows $ view $ tag w windows $ removeWorkspace' torem _ -> return () -- | Remove the current workspace after an operation if it is empty and hidden. -- Can be used to remove a workspace if it is empty when leaving it. The -- operation may only change workspace once, otherwise the workspace will not -- be removed. removeEmptyWorkspaceAfter :: X () -> X () removeEmptyWorkspaceAfter = removeEmptyWorkspaceAfterExcept [] -- | Like 'removeEmptyWorkspaceAfter' but use a list of sticky workspaces, -- whose entries will never be removed. removeEmptyWorkspaceAfterExcept :: [String] -> X () -> X () removeEmptyWorkspaceAfterExcept sticky f = do before <- gets (currentTag . windowset) f after <- gets (currentTag . windowset) when (before/=after && before `notElem` sticky) $ removeEmptyWorkspaceByTag before isEmpty :: String -> X Bool isEmpty t = do wsl <- gets $ workspaces . windowset let mws = find (\ws -> tag ws == t) wsl return $ maybe True (isNothing . stack) mws addHiddenWorkspace' :: i -> l -> StackSet i l a sid sd -> StackSet i l a sid sd addHiddenWorkspace' newtag l s@(StackSet { hidden = ws }) = s { hidden = Workspace newtag l Nothing:ws } removeWorkspace' :: (Eq i) => i -> StackSet i l a sid sd -> StackSet i l a sid sd removeWorkspace' torem s@(StackSet { current = scr@(Screen { workspace = wc }) , hidden = (w:ws) }) | tag w == torem = s { current = scr { workspace = wc { stack = meld (stack w) (stack wc) } } , hidden = ws } where meld Nothing Nothing = Nothing meld x Nothing = x meld Nothing x = x meld (Just x) (Just y) = differentiate (integrate x ++ integrate y) removeWorkspace' _ s = s
adinapoli/xmonad-contrib
XMonad/Actions/DynamicWorkspaces.hs
bsd-3-clause
8,186
0
18
2,551
1,770
921
849
98
4
module PackageTests.BuildDeps.GlobalBuildDepsNotAdditive1.Check where import Test.HUnit import PackageTests.PackageTester import System.FilePath import Data.List import Control.Exception import Prelude hiding (catch) suite :: FilePath -> Test suite ghcPath = TestCase $ do let spec = PackageSpec ("PackageTests" </> "BuildDeps" </> "GlobalBuildDepsNotAdditive1") [] result <- cabal_build spec ghcPath do assertEqual "cabal build should fail - see test-log.txt" False (successful result) let sb = "Could not find module `Prelude'" assertBool ("cabal output should be "++show sb) $ sb `isInfixOf` outputText result `catch` \exc -> do putStrLn $ "Cabal result was "++show result throwIO (exc :: SomeException)
jwiegley/ghc-release
libraries/Cabal/cabal/tests/PackageTests/BuildDeps/GlobalBuildDepsNotAdditive1/Check.hs
gpl-3.0
780
0
16
163
196
101
95
19
1
-- This script processes the following source file: -- -- http://unicode.org/Public/UNIDATA/SpecialCasing.txt module SpecialCasing ( SpecialCasing(..) , Case(..) , parseSC , mapSC ) where import Arsec data SpecialCasing = SC { scComments :: [Comment], scCasing :: [Case] } deriving (Show) data Case = Case { code :: Char , lower :: [Char] , title :: [Char] , upper :: [Char] , conditions :: String , name :: String } deriving (Eq, Ord, Show) entries :: Parser SpecialCasing entries = SC <$> many comment <*> many (entry <* many comment) where entry = Case <$> unichar <* semi <*> unichars <*> unichars <*> unichars <*> manyTill anyToken (string "# ") <*> manyTill anyToken (char '\n') parseSC :: FilePath -> IO (Either ParseError SpecialCasing) parseSC name = parse entries name <$> readFile name mapSC :: String -> (Case -> String) -> (Char -> Char) -> SpecialCasing -> [String] mapSC which access twiddle (SC _ ms) = typ ++ (map nice . filter p $ ms) ++ [last] where typ = [which ++ "Mapping :: forall s. Char -> s -> Step (CC s) Char" ,"{-# NOINLINE " ++ which ++ "Mapping #-}"] last = which ++ "Mapping c s = Yield (to" ++ ucFirst which ++ " c) (CC s '\\0' '\\0')" nice c = "-- " ++ name c ++ "\n" ++ which ++ "Mapping " ++ showC (code c) ++ " s = Yield " ++ x ++ " (CC s " ++ y ++ " " ++ z ++ ")" where [x,y,z] = (map showC . take 3) (access c ++ repeat '\0') p c = [k] /= a && a /= [twiddle k] && null (conditions c) where a = access c k = code c ucFirst (c:cs) = toUpper c : cs ucFirst [] = []
spencerjanssen/text
scripts/SpecialCasing.hs
bsd-2-clause
1,761
0
19
558
610
325
285
42
1
{-# LANGUAGE TypeFamilies #-} module T4179 where class DoC a where type A2 a type A3 a op :: a -> A2 a -> A3 a data Con x = InCon (x (Con x)) type FCon x = x (Con x) -- should have been changed to this, which works -- foldDoC :: Functor f => (f a -> a) -> A2 (FCon f) -> Con f -> a -- foldDoC f i (InCon t) = f (fmap (foldDoC f i) t) -- this original version causes GHC to hang foldDoC :: Functor f => (f a -> a) -> Con f -> a foldDoC f (InCon t) = f (fmap (foldDoC f) t) doCon :: (DoC (FCon x)) => Con x -> A2 (FCon x) -> A3 (FCon x) doCon (InCon x) = op x -- Note that if this is commented out then there's no hang: -- presumably because GHC doesn't have to perform type deduction for foldDoC. fCon :: (Functor x, DoC (FCon x)) => Con x -> A2 (FCon x) -> A3 (FCon x) fCon = foldDoC op
urbanslug/ghc
testsuite/tests/indexed-types/should_fail/T4179.hs
bsd-3-clause
814
0
10
209
280
145
135
-1
-1
-- Copyright 2012 Mitchell Kember. Subject to the MIT License. -- | The 'Scene' type, several other types that it contains, and the 'trace' -- function for ray tracing scenes. This module is responsible for transforming -- a single ray into a colour. module Luminosity.Trace ( -- * Types Scene(..) , Settings(..) , World(..) , Camera(..) , Object(..) , Light(..) , Material(..) -- * Ray tracing , trace ) where import Control.Applicative ((<$>), (<*>)) import Data.Maybe (mapMaybe) import Data.Monoid ((<>), mconcat, mempty) import Data.Ord (comparing) import qualified Data.Map as M import Luminosity.Colour (Colour) import Luminosity.Vector import Luminosity.Intersect import Luminosity.Misc (maybeMinBy) data Scene = Scene { mSettings :: Settings , mWorld :: World , mCamera :: Camera , mObjects :: [Object] , mLights :: [Light] , mMaterials :: M.Map String Material } deriving (Eq, Show) data Settings = Settings { mResolutionX :: Int , mResolutionY :: Int , mSamples :: Int , mDepth :: Int } deriving (Eq, Show) data World = World { mSky :: Colour } deriving (Eq, Show) data Camera = Orthographic { mSight :: Ray , mUpward :: Vector , mOrthoScale :: Scalar } | Perspective { mSight :: Ray , mUpward :: Vector , mFocalLength :: Scalar } deriving (Eq, Show) data Object = Object { mSurface :: Surface , mMaterialID :: String } deriving (Eq, Show) data Light = Light { mPosition :: Vector , mIntensity :: Colour } deriving (Eq, Show) data Material = Material { mDiffuse :: Colour , mReflect :: Double } deriving (Eq, Show) -- | Calculate all the intersections made by a ray with a list of objects, and -- with each object return the point of intersection's distance from the ray's -- initial point. intersections :: [Object] -> Ray -> [(Object, Scalar)] intersections xs r = mapMaybe (\x -> fmap ((,) x) (mSurface x `intersect` r)) xs -- | Calculate the nearest intersection made by a ray with a list of objects, -- and with each object return the point of intersection's distance from the -- ray's initial point. Returns 'Nothing' if no intersections were made. fstIntersection :: [Object] -> Ray -> Maybe (Object, Scalar) fstIntersection = (maybeMinBy (comparing snd) .) . intersections -- | Trace a ray through a scene and compute its colour. trace :: Scene -> Ray -> Colour trace scene ray = trace' scene ray (mDepth $ mSettings scene) -- | Recursive ray tracing implementation used by 'trace'. trace' :: Scene -> Ray -> Int -> Colour trace' _ _ 0 = mempty trace' scene@(Scene _ world _ objs lights mats) ray@(Ray _ v) level = case fstIntersection objs ray of Nothing -> mSky world Just (obj, t) -> let mat = mats M.! mMaterialID obj x' = extend t ray n = normal (mSurface obj) x' col = mconcat . map (lighting mat x' n objs) $ lights ray' = Ray x' $ normalize $ v <-> 2 * v <.> n *> n ref = mReflect mat in if ref == 0 then col else col <> ref *> trace' scene ray' (level - 1) -- | Compute the colour that a light source contributes at a particular point. lighting :: Material -- ^ The material of the object which the point is on. -> Vector -- ^ The position vector of the point. -> Vector -- ^ The normal vector of the point. -> [Object] -- ^ The objects in the scene (for tracing shadows). -> Light -- ^ The light source. -> Colour -- ^ The colour that the light source contributes. lighting mat p n objs (Light x c) | lambert <= 0 || not (null ints) = mempty | otherwise = (*) <$> lambert *> c <*> mDiffuse mat where shadow = normalize $ x <-> p lambert = shadow <.> n dist = norm $ x <-> p ints = filter ((<= dist) . snd) $ intersections objs (Ray p shadow)
mk12/luminosity
src/Luminosity/Trace.hs
mit
3,985
0
18
1,068
1,057
605
452
92
3
module Main where -- initialized import Init -- Handlers import Handler.Home mkYesodDispatch "Ember" resourcesEmber main :: IO () main = do pool <- createSqlitePool "database.sqlite" 10 -- create a new pool -- perform any necessary migration runSqlPersistMPool (runMigration migrateAll) pool manager <- newManager def -- create a new HTTP manager warpEnv $ Ember pool manager -- start our server
mkrull/yesod-ember-skel
src/Main.hs
mit
424
0
9
87
89
45
44
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} module Data.Aeson.Config.Parser ( Parser , runParser , typeMismatch , withObject , withText , withString , withArray , withNumber , withBool , explicitParseField , explicitParseFieldMaybe , Aeson.JSONPathElement(..) , (<?>) , Value(..) , Object , Array , liftParser , fromAesonPath , formatPath ) where import Imports import qualified Control.Monad.Fail as Fail import Control.Monad.Trans.Class import Control.Monad.Trans.Writer import Data.Scientific import Data.Set (Set, notMember) import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Vector as V import Data.Aeson.Config.Key (Key) import qualified Data.Aeson.Config.Key as Key import qualified Data.Aeson.Config.KeyMap as KeyMap import Data.Aeson.Types (Value(..), Object, Array) import qualified Data.Aeson.Types as Aeson import Data.Aeson.Internal (IResult(..), iparse) #if !MIN_VERSION_aeson(1,4,5) import qualified Data.Aeson.Internal as Aeson #endif -- This is needed so that we have an Ord instance for aeson < 1.2.4. data JSONPathElement = Key Text | Index Int deriving (Eq, Show, Ord) type JSONPath = [JSONPathElement] fromAesonPath :: Aeson.JSONPath -> JSONPath fromAesonPath = reverse . map fromAesonPathElement fromAesonPathElement :: Aeson.JSONPathElement -> JSONPathElement fromAesonPathElement e = case e of Aeson.Key k -> Key (Key.toText k) Aeson.Index n -> Index n newtype Parser a = Parser {unParser :: WriterT (Set JSONPath) Aeson.Parser a} deriving (Functor, Applicative, Alternative, Monad, Fail.MonadFail) liftParser :: Aeson.Parser a -> Parser a liftParser = Parser . lift runParser :: (Value -> Parser a) -> Value -> Either String (a, [String]) runParser p v = case iparse (runWriterT . unParser <$> p) v of IError path err -> Left ("Error while parsing " ++ formatPath (fromAesonPath path) ++ " - " ++ err) ISuccess (a, consumed) -> Right (a, map formatPath (determineUnconsumed consumed v)) formatPath :: JSONPath -> String formatPath = go "$" . reverse where go :: String -> JSONPath -> String go acc path = case path of [] -> acc Index n : xs -> go (acc ++ "[" ++ show n ++ "]") xs Key key : xs -> go (acc ++ "." ++ T.unpack key) xs determineUnconsumed :: Set JSONPath -> Value -> [JSONPath] determineUnconsumed ((<> Set.singleton []) -> consumed) = Set.toList . execWriter . go [] where go :: JSONPath -> Value -> Writer (Set JSONPath) () go path value | path `notMember` consumed = tell (Set.singleton path) | otherwise = case value of Number _ -> return () String _ -> return () Bool _ -> return () Null -> return () Object o -> do forM_ (KeyMap.toList o) $ \ (Key.toText -> k, v) -> do unless ("_" `T.isPrefixOf` k) $ do go (Key k : path) v Array xs -> do forM_ (zip [0..] $ V.toList xs) $ \ (n, v) -> do go (Index n : path) v (<?>) :: Parser a -> Aeson.JSONPathElement -> Parser a (<?>) (Parser (WriterT p)) e = do Parser (WriterT (p Aeson.<?> e)) <* markConsumed (fromAesonPathElement e) markConsumed :: JSONPathElement -> Parser () markConsumed e = do path <- getPath Parser $ tell (Set.singleton $ e : path) getPath :: Parser JSONPath getPath = liftParser $ Aeson.parserCatchError empty $ \ path _ -> return (fromAesonPath path) explicitParseField :: (Value -> Parser a) -> Object -> Key -> Parser a explicitParseField p o key = case KeyMap.lookup key o of Nothing -> fail $ "key " ++ show key ++ " not present" Just v -> p v <?> Aeson.Key key explicitParseFieldMaybe :: (Value -> Parser a) -> Object -> Key -> Parser (Maybe a) explicitParseFieldMaybe p o key = case KeyMap.lookup key o of Nothing -> pure Nothing Just v -> Just <$> p v <?> Aeson.Key key typeMismatch :: String -> Value -> Parser a typeMismatch expected = liftParser . Aeson.typeMismatch expected withObject :: (Object -> Parser a) -> Value -> Parser a withObject p (Object o) = p o withObject _ v = typeMismatch "Object" v withText :: (Text -> Parser a) -> Value -> Parser a withText p (String s) = p s withText _ v = typeMismatch "String" v withString :: (String -> Parser a) -> Value -> Parser a withString p = withText (p . T.unpack) withArray :: (Array -> Parser a) -> Value -> Parser a withArray p (Array xs) = p xs withArray _ v = typeMismatch "Array" v withNumber :: (Scientific -> Parser a) -> Value -> Parser a withNumber p (Number n) = p n withNumber _ v = typeMismatch "Number" v withBool :: (Bool -> Parser a) -> Value -> Parser a withBool p (Bool b) = p b withBool _ v = typeMismatch "Boolean" v
sol/hpack
src/Data/Aeson/Config/Parser.hs
mit
4,847
0
23
1,070
1,791
936
855
117
6
module GHCJS.DOM.SVGScriptElement ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGScriptElement.hs
mit
46
0
3
7
10
7
3
1
0
{-| Module : Main Description : Entry point for GGg Copyright : (c) Carter Hinsley, 2015 License : MIT Maintainer : [email protected] -} module Main where import CLI import System.Environment -- | Retrieve command-line arguments and process them. main :: IO () main = parseArgs =<< getArgs
xnil/GGg
src/Main.hs
mit
311
0
6
62
33
20
13
5
1
{-# htermination showList :: [()] -> String -> String #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_showList_2.hs
mit
58
0
2
10
3
2
1
1
0
{-# LANGUAGE CPP #-} module GHCJS.DOM.SVGFilterElement ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.SVGFilterElement #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.SVGFilterElement #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/SVGFilterElement.hs
mit
361
0
5
33
33
26
7
4
0
-- file: ch03/add.hs myNot True = False myNot False = True -- We've defined a function as a series of equations. -- Another example: sumList (x:xs) = x + sumList xs sumList [] = 0
supermitch/learn-haskell
real-world-haskell/ch03/add.hs
mit
188
0
7
43
52
27
25
4
1
module FrontEnd.Lex.Parse(parseM,parse,parseStmt) where import Util.Std import FrontEnd.HsSyn import FrontEnd.Lex.Layout import FrontEnd.Lex.Lexer import FrontEnd.Lex.ParseMonad import FrontEnd.Warning import Options import PackedString import qualified FlagDump as FD import qualified FrontEnd.Lex.Parser as P parseM :: MonadWarn m => Opt -> FilePath -> String -> m (Maybe HsModule) parseM opt fp s = case scanner opt s of Left s -> fail s Right s -> do s <- doLayout opt fp s case runP (withSrcLoc bogusASrcLoc { srcLocFileName = packString fp } $ P.parseModule s) opt of (ws, ~(Just p)) -> do mapM_ addWarning ws if null ws then return $ Just p { hsModuleOpt = opt } else return Nothing parse :: Opt -> FilePath -> String -> IO HsModule parse opt fp s = case scanner opt s of Left s -> fail s Right s -> do wdump FD.Tokens $ do putStrLn "-- scanned" putStrLn $ unwords [ s | L _ _ s <- s ] let pp = preprocessLexemes opt fp s putStrLn "-- preprocessed" forM_ pp $ \c -> case c of Token (L _ _ s) -> putStr s >> putStr " " TokenNL n -> putStr ('\n':replicate (n - 1) ' ') TokenVLCurly _ i -> putStr $ "{" ++ show (i - 1) ++ " " putStrLn "" laidOut <- doLayout opt fp s wdump FD.Tokens $ do putStrLn "-- after layout" putStrLn $ unwords [ s | L _ _ s <- laidOut ] case runP (withSrcLoc bogusASrcLoc { srcLocFileName = packString fp } $ P.parseModule laidOut) opt of (ws, ~(Just p)) -> do processErrors ws return p { hsModuleOpt = opt } parseStmt :: (Applicative m,MonadWarn m) => Opt -> FilePath -> String -> m HsStmt parseStmt opt fp s = case scanner opt s of Left s -> fail s Right s -> do s <- doLayout opt fp s case runP (withSrcLoc bogusASrcLoc { srcLocFileName = packString fp } $ P.parseStmt s) opt of (ws, ~(Just p)) -> do mapM_ addWarning ws return p
m-alvarez/jhc
src/FrontEnd/Lex/Parse.hs
mit
2,170
0
23
742
805
389
416
53
4
module GraphGen ( list, GraphGen.cycle, star, complete, binaryTree, ) where import qualified Graph (graphFromEdgeList, LabeledGraph) list :: (Enum a, Num a, Show a) => a -> Graph.LabeledGraph list n = Graph.graphFromEdgeList [(show v, show (v+1)) | v <- [1..(n-1)]] cycle :: (Integral a, Show a) => a -> Graph.LabeledGraph cycle n = Graph.graphFromEdgeList edges where edges = map (\(a, b) -> (show (a+1), show (b+1))) [(v, (((v+1) `mod` n))) | v <- [0..n-1]] star :: (Enum a, Num a, Show a) => a -> Graph.LabeledGraph star n = Graph.graphFromEdgeList [("1", (show v)) | v <- [2..n]] complete :: (Enum a, Eq a, Num a, Show a) => a -> Graph.LabeledGraph complete n = Graph.graphFromEdgeList [((show a), (show b)) | a <- [1..n], b <- [1..n], a /= b] binaryTree :: (Ord a, Enum a, Num a, Show a) => a -> Graph.LabeledGraph binaryTree n = Graph.graphFromEdgeList (map (\(a,b) -> (show a, show b)) (concat [map (\x -> (v, x)) (neighbors v) | v <- [1..n]])) where neighbors v | (2*v) > n = [] | (2*v + 1) > n = [2*v] | otherwise = [2*v, (2*v) + 1]
cjlarose/Haskell-Graphs
GraphGen.hs
mit
1,138
0
14
285
660
358
302
26
1
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, TupleSections, GADTs #-} module Day21 where import AdventPrelude import qualified Data.Sequence as S input :: IO Text input = readFile "data/day21.txt" -- input = pure -- "swap position 4 with position 0\n\ -- \swap letter d with letter b\n\ -- \reverse positions 0 through 4\n\ -- \rotate left 1 step\n\ -- \move position 1 to position 4\n\ -- \move position 3 to position 0\n\ -- \rotate based on position of letter b\n\ -- \rotate based on position of letter d" data Op = SwapPos Int Int | SwapLetter Char Char | Rotate Int | RotateLetter Char | Reverse Int Int | Move Int Int deriving (Show) parser = SwapPos <$> ("swap position " *> decimal) <*> (" with position " *> decimal) <|> SwapLetter <$> ("swap letter " *> letter) <*> (" with letter " *> letter) <|> Rotate <$> ("rotate " *> lr) <* (" step" *> many "s") <|> Reverse <$> ("reverse positions " *> decimal) <*> (" through " *> decimal) <|> RotateLetter <$> ("rotate based on position of letter " *> letter) <|> Move <$> ("move position " *> decimal) <*> (" to position " *> decimal) where lr = "left " *> decimal <|> "right " *> (neg <$> decimal) neg x = - x update :: Seq Char -> Op -> Seq Char update cs (SwapPos ix iy) = let x = cs `S.index` ix y = cs `S.index` iy in S.update ix y (S.update iy x cs) update cs (SwapLetter x y) = let (Just ix) = S.elemIndexL x cs (Just iy) = S.elemIndexL y cs in S.update ix y (S.update iy x cs) update cs (Rotate n) | n > 0 = let (h, t) = S.splitAt n cs in t >< h | otherwise = update cs (Rotate (S.length cs + n)) update cs (RotateLetter l) = let Just i = S.findIndexL (== l) cs j = if i >= 4 then 1 else 0 in update cs (Rotate (- (i + j + 1))) update cs (Reverse a b) = let (h, t) = S.splitAt (b + 1) cs (h', m) = S.splitAt a h in h' >< (S.reverse m) >< t update cs (Move src tgt) = let c = cs `S.index` src in S.insertAt tgt c (S.deleteAt src cs) result1 = runEitherT $ do i <- EitherT (parseOnly (parser `sepBy` endOfLine) <$> input) -- let s = "abcde" let s = "abcdefgh" pure (foldl' update s i) invert :: Seq Char -> Op -> Seq Char invert cs op@(RotateLetter _) = let css = map (\x -> update cs (Rotate x)) [0 .. (S.length cs - 1)] cs' : _ = filter (\xs -> update xs op == cs) css in cs' invert cs (Move src tgt) = update cs (Move tgt src) invert cs (Rotate i) = update cs (Rotate (- i)) invert cs op = update cs op result2 = runEitherT $ do i <- EitherT (parseOnly (parser `sepBy` endOfLine) <$> input) -- let s = "decab" -- let s = "bdfhgeca" let s = "fbgdceah" pure (foldl' invert s (reverse i))
farrellm/advent-2016
src/Day21.hs
mit
2,786
0
22
751
1,098
565
533
72
2
{-# LANGUAGE CPP #-} module GHCJS.DOM.SVGLengthList ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.SVGLengthList #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.SVGLengthList #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/SVGLengthList.hs
mit
352
0
5
33
33
26
7
4
0
import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck import qualified TestWeighted import qualified TestEnumerator import qualified TestPopulation import qualified TestSequential import qualified TestTrace import qualified TestInference import qualified TestSMCObservations import qualified TestGradient import qualified TestConditional main :: IO () main = hspec $ do describe "Weighted" $ do it "accumulates likelihood correctly" $ do passed <- TestWeighted.passed passed `shouldBe` True describe "Dist" $ do it "normalizes categorical" $ do TestEnumerator.passed1 `shouldBe` True it "sorts samples and aggregates weights" $ do TestEnumerator.passed2 `shouldBe` True it "gives correct answer for the sprinkler model" $ do TestEnumerator.passed3 `shouldBe` True it "computes expectation correctly" $ do TestEnumerator.passed4 `shouldBe` True describe "Empirical" $ do context "controlling population" $ do it "preserves the population when not expicitly altered" $ do pop_size <- TestPopulation.pop_size pop_size `shouldBe` 5 it "multiplies the number of samples when spawn invoked twice" $ do many_size <- TestPopulation.many_size many_size `shouldBe` 15 it "correctly computes population average" $ do TestPopulation.popAvg_check `shouldBe` True -- context "checking properties of samples" $ do -- it "correctly checks if all particles satisfy a property" $ do -- TestPopulation.all_check `shouldBe` True context "distribution-preserving transformations" $ do it "transform preserves the distribution" $ do TestPopulation.trans_check1 `shouldBe` True TestPopulation.trans_check2 `shouldBe` True it "resample preserves the distribution" $ do TestPopulation.resample_check 1 `shouldBe` True TestPopulation.resample_check 2 `shouldBe` True describe "Particle" $ do it "stops at every factor" $ do TestSequential.check_two_sync 0 `shouldBe` True TestSequential.check_two_sync 1 `shouldBe` True TestSequential.check_two_sync 2 `shouldBe` True it "preserves the distribution" $ do TestSequential.check_preserve `shouldBe` True it "produces correct intermediate weights" $ do TestSequential.check_sync 0 `shouldBe` True TestSequential.check_sync 1 `shouldBe` True TestSequential.check_sync 2 `shouldBe` True -- describe "Trace" $ do -- context "RandomDB = [Cache]" $ do -- it "correctly records values" $ do -- TestTrace.check_writing `shouldBe` True -- it "correctly reuses values" $ do -- TestTrace.check_reading `shouldBe` True -- it "has reuse ratio 1 on an empty database" $ do -- TestTrace.check_reuse_ratio TestTrace.m `shouldBe` True -- TestTrace.check_reuse_ratio TestSequential.sprinkler `shouldBe` True describe "Density" $ do it "correctly evaluates conditional distribution" $ do TestConditional.check_missing_conditional `shouldBe` True TestConditional.check_longer_conditional `shouldBe` True it "correctly computes pseudo-marginal density" $ do TestConditional.check_first_density `shouldBe` True it "correctly computes joint density" $ do TestConditional.check_joint_density_true `shouldBe` True TestConditional.check_joint_density_false `shouldBe` True describe "SMC" $ do it "terminates" $ do seq TestInference.check_terminate_smc () `shouldBe` () it "preserves the distribution on the sprinkler model" $ do TestInference.check_preserve_smc `shouldBe` True prop "number of particles is equal to its second parameter" $ \observations particles -> observations >= 0 && particles >= 1 ==> ioProperty $ do check_particles <- TestInference.check_particles observations particles return $ check_particles == particles describe "MH" $ do -- it "MH from prior leaves posterior invariant" $ do -- TestInference.check_prior_trans `shouldBe` True it "Trace MH produces correct number of samples" $ do trace_mh_length <- TestInference.trace_mh_length 11 trace_mh_length `shouldBe` 11 it "Trace MH leaves posterior invariant" $ do TestInference.check_trace_trans `shouldBe` True it "Trace MH leaves posterior invariant when the model has shifting support" $ do TestInference.check_trace_support `shouldBe` True describe "Population/Trace/Particle hybrids" $ do it "ISMH preserves the posterior on the sprinkler model" $ do TestInference.check_preserve_ismh `shouldBe` True it "SMH preserves the posterior on the sprinkler model" $ do TestInference.check_preserve_smh `shouldBe` True it "Resample-move SMC preserves the posterior on the sprinkler model" $ do TestInference.check_preserve_smcrm `shouldBe` True -- too large to execute -- it "PIMH leaves posterior invariant" $ do -- TestInference.check_pimh_trans `shouldBe` True -- describe "Number of SMC observations sufficient for each models" $ do -- check_smc_observations 5 "Gamma.model" Gamma.model -- check_smc_observations 0 "Gamma.exact" Gamma.exact -- check_smc_observations 0 "Dice.dice" (Dice.dice 4) -- check_smc_observations 1 "Dice.dice_soft" Dice.dice_soft -- check_smc_observations 1 "Dice.dice_hard" Dice.dice_hard -- check_smc_observations 0 "BetaBin.latent" (BetaBin.latent 5) -- check_smc_observations 0 "BetaBin.urn" (BetaBin.urn 5) -- check_smc_observations 16 "HMM.hmm" HMM.hmm describe "Density computation" $ do it "gives correct value on gamma-normal-beta model" $ do TestGradient.check_density `shouldBe` True it "gives correct gradient on gamma-normal-beta model" $ do TestGradient.check_gradient `shouldBe` True check_smc_observations n modelName model = it (show n ++ " observations for " ++ modelName) $ do check_smc_weight <- TestSMCObservations.check_smc_weight n 30 model check_smc_weight `shouldBe` True
ocramz/monad-bayes
test/Spec.hs
mit
6,086
0
19
1,236
1,026
507
519
98
1
module Test where -- (append xs ys) returns the lists xs and ys appended -- For example: -- append [1,2,3] [5,2] = [1,2,3,5,2] append :: [a] -> [a] -> [a] append [] ys = ys append (x:xs) ys = x : (append xs ys) -- addup xs returns the sum of the numbers in -- the list xs. For example: -- addup [1,2,3] = 6 addup :: [Int] -> Int addup [] = 0 addup (x:xs) = x + (addup xs) -- rev xs returns the list of values in xs in -- reverse order. For example: -- rev [1,2,3] = [3,2,1] rev :: [Int] -> [Int] rev [] = [] rev (x:xs) = (rev xs) ++ [x] -- insert n ns inserts the integer n into the list -- of integers ns. You can assume that the numbers -- in the list ns are already arranged in ascending -- order. For example: -- insert 3 [1,2,4,5] = [1,2,3,4,5] -- insert 5 [1,2,3,4] = [1,2,3,4,5] -- insert 0 [1,2,3,4] = [0,1,2,3,4] -- insert 2 [1,2,3,4] = [1,2,2,3,4] -- As this last example shows, insert does not attempt -- to eliminate duplicate elements from the list. insert :: Int -> [Int] -> [Int] insert x [] = [x] insert x (y:ys) | x > y = y : (insert x ys) | x <= y = x : y : ys -- sort ns returns a sorted version of the list ns. -- For example: -- sort [1,2,3,4] = [1,2,3,4] -- sort [4,3,2,1] = [1,2,3,4] -- sort [3,1,4,2] = [1,2,3,4] -- sort [3,2,3,1] = [1,2,3,3] -- Hint: I suggest that you try to implement an -- ***insert***ion sort :-) sort :: [Int] -> [Int] sort [] = [] sort (n:ns) = insert n (sort ns) -- splits ns returns the list of all triples (us, v, ws) -- such that us ++ [v] ++ ws == ns. For example: -- splits [0,1,2] = [ ([], 0, [1,2]), -- ([0], 1, [2]), -- ([0,1], 2, []) ] splits :: [Int] -> [([Int], Int, [Int])] splits [x] = [ ( [], x, [])] splits (x:xs) = ([], x, xs) : [ (x : us, v, ws) | (us, v, ws) <- splits xs ] scheck :: [Int] -> [([Int], Int, [Int])] -> Bool scheck (n:ns) [(us, v, ws)] = (us ++ [v] ++ ws) == (n:ns) scheck (n:ns) ((us, v, ws):xs) = ((us ++ [v] ++ ws) == (n:ns)) && (scheck (n:ns) xs) data Bit = O | I deriving (Show, Eq) type BinNum = [Bit] toBinNum :: Integer -> BinNum fromBinNum :: BinNum -> Integer inc :: BinNum -> BinNum add :: BinNum -> BinNum -> BinNum mul :: BinNum -> BinNum -> BinNum addr :: BinNum -> BinNum -> BinNum mulr :: BinNum -> BinNum -> BinNum toBinNum n | n==0 = [O] | even n = O : toBinNum(halfOfN) | odd n = I : tail (toBinNum (n - 1)) where halfOfN = n `div` 2 fromBinNum [] = 0 fromBinNum (O:ds) = 2 * fromBinNum ds fromBinNum (I:ds) = 1 + (2 * fromBinNum ds) inc [I] = [O, I] inc (O:xs) = I : xs inc (I:xs) = O : inc xs add [] ds = ds add ds [] = ds add (O:ds) (e:es) = e : add ds es add (I:ds) (O:es) = I : add ds es add (I:ds) (I:es) = O : add (add [I] ds) es mul [O] bs = [O] mul bs [O] = [O] mul as bs = mull as bs [I] where mull xs ys count | count /= xs = add ys (mull xs ys (inc count)) | otherwise = ys mulr x y = toBinNum (fromBinNum x * fromBinNum y) addr x y = toBinNum (fromBinNum x + fromBinNum y) testMul x y = fb (mulr (tb x) (tb y)) == fb (mul (tb x) (tb y)) where tb = toBinNum fb = fromBinNum testAdd x y = fb (addr (tb x) (tb y)) == fb (add (tb x) (tb y)) where tb = toBinNum fb = fromBinNum
ladinu/cs457
src/Test.hs
mit
3,459
0
12
1,052
1,391
754
637
61
1
{-# LANGUAGE FlexibleInstances, FlexibleContexts, TypeFamilies, OverloadedStrings #-} module Main where import Happstack.Server import Text.Blaze ((!)) import qualified Control.Monad as CM import qualified Data.Monoid as DM import qualified Control.Applicative.Indexed as CAI import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import qualified Data.ByteString.Char8 as C import qualified Text.Blaze.Html5 as BH import qualified Text.Blaze.Html5.Attributes as BA import qualified Text.Reform as TR import qualified Text.Reform.Blaze.String as TRBS import Text.Reform.Happstack (environment) import SharedForm main :: IO () main = simpleHTTP nullConf $ CM.msum [ dir "static" $ serveDirectory DisableBrowsing [] "static" , dir "home" $ homePage , dir "index" $ indexPage , dir "good" $ goodPage , dir "table" $ tablePage , dir "params" $ paramsPage , dir "form" $ formPage , seeOther ("/index" :: String) (toResponse ("Page not found. Redirecting to /index\n" :: String)) ] indexPage :: ServerPart Response indexPage = appTemplate "Index" $ BH.div $ do BH.p $ BH.a ! BA.href "/home" $ "Home." BH.p $ BH.a ! BA.href "/table" $ "Look at a lovely table" BH.p $ BH.a ! BA.href "/form" $ "Play with a form" BH.p $ BH.a ! BA.href "/good" $ "Star wars secret" appTemplate :: BH.Html -> BH.Html -> ServerPart Response appTemplate title body = ok $ toResponse $ renderHtml $ do BH.head $ do BH.title title BH.meta ! BA.httpEquiv "Content-Type" ! BA.content "text/html;charset=utf-8" BH.link ! BA.rel "stylesheet" ! BA.style "text/css" ! BA.href "static/css/stdtheme.css" BH.body $ do body (BH.div $ BH.a ! BA.href "/index" $ "Index") homePage :: ServerPart Response homePage = appTemplate "Home page" (BH.p "Hello, from Happstack\n") goodPage :: ServerPart Response goodPage = appTemplate "The emporer's secret to good dialogue" $ do BH.p "Something, something, something dark side" BH.p "Something, something, something complete" paramsPage :: ServerPart Response paramsPage = look "str" >>= \s -> appTemplate "Passing parameters in the url" (BH.div $ showParams s) where showParams :: String -> BH.Html showParams s = BH.toHtml $ "str: " ++ s formPage :: ServerPart Response formPage = decodeBody (defaultBodyPolicy "/tmp" 0 10000 10000) >> formHandler (userForm "" "") tablePage :: ServerPart Response tablePage = appTemplate "What a Table!" $ table testData instance BH.ToMarkup (DemoFormError [Input]) where toMarkup InvalidEmail = "Email address must contain a @." toMarkup InvalidUsername = "Username must not be blank." toMarkup (CommonError (TR.InputMissing fid)) = BH.toMarkup $ "Internal Error. Input missing: " ++ show fid toMarkup (CommonError (TR.NoStringFound input)) = BH.toMarkup $ "Internal Error. Could not extract a String from: " ++ show input toMarkup (CommonError (TR.MultiStringsFound input)) = BH.toMarkup $ "Internal Error. Found more than one String in: " ++ show input usernameForm :: (Monad m, TR.FormInput input, BH.ToMarkup (DemoFormError input)) => String -> TR.Form m input (DemoFormError input) BH.Html TR.NotNull Username usernameForm initialValue = TRBS.errorList TR.++> (TRBS.label ("username: " :: String) TR.++> (Username CAI.<<$>> TR.prove (TRBS.inputText initialValue) (TR.notNullProof InvalidUsername))) emailForm :: (Monad m, TR.FormInput input, BH.ToMarkup (DemoFormError input)) => String -> TR.Form m input (DemoFormError input) BH.Html ValidEmail Email emailForm initialValue = TRBS.errorList TR.++> (TRBS.label ("email: " :: String) TR.++> (Email CAI.<<$>> TR.prove (TRBS.inputText initialValue) (validEmailProof InvalidEmail))) userForm :: (Monad m, TR.FormInput input, BH.ToMarkup (DemoFormError input)) => String -> -- ^ initial username String -> -- ^ initial email TR.Form m input (DemoFormError input) BH.Html ValidUser User userForm nm eml = mkUser CAI.<<*>> (usernameForm nm) CAI.<<*>> (emailForm eml) blazeForm :: BH.Html -> BH.Html blazeForm html = BH.form ! BA.action "/form" ! BA.method "POST" ! BA.enctype "multipart/form-data" $ html >> BH.input ! BA.type_ "submit" formHandler :: (BH.ToMarkup error, Show a) => TR.Form (ServerPartT IO) [Input] error BH.Html proof a -> ServerPart Response formHandler form = CM.msum [ do method GET html <- TR.viewForm "user" form appTemplate "Sample Form" $ blazeForm html , do method POST r <- TR.eitherForm environment "user" form case r of (Right a) -> appTemplate "Form result" $ BH.toHtml $ show a (Left view) -> appTemplate "Form result" $ blazeForm view ] data TestTable = TestTable { string1 :: String, string2 :: String, num :: Int } testData :: [TestTable] testData = TestTable "sding" "abnwsn" 3 : TestTable "rfnsn" "sn" 3892 : TestTable "d" "dignaprinb" (-39) : [] tableRow :: TestTable -> BH.Html tableRow t = BH.tr $ BH.td (BH.toHtml $ string1 t) >> BH.td (BH.toHtml $ string2 t) >> BH.td (BH.toHtml $ num t) tableHeader :: BH.Html tableHeader = BH.tr $ BH.th "String 1" >> BH.th "String 2" >> BH.th "Number" table :: [TestTable] -> BH.Html table t = BH.table ! BA.style "width:100%" $ tableHeader >> CM.forM_ t tableRow
lhoghu/yahoo-portfolio-manager
ypm-server/Data/YahooPortfolioManager/Server/Main.hs
mit
6,168
0
15
1,871
1,741
884
857
133
2
{-# LANGUAGE OverloadedStrings, TypeFamilies, RankNTypes, DeriveFunctor #-} {- | Module : Routes.Monad Copyright : (c) Anupam Jain 2013 License : MIT (see the file LICENSE) Maintainer : [email protected] Stability : experimental Portability : non-portable (uses ghc extensions) Defines a Routing Monad that provides easy composition of Routes -} module Routes.Monad ( -- * Route Monad RouteM -- * Compose Routes , DefaultMaster(..) , Route(DefaultRoute) , handler , middleware , route , catchall , defaultAction -- * Convert to Wai Application , waiApp , toWaiApp ) where import Network.Wai import Routes.Routes import Routes.DefaultRoute import Network.HTTP.Types (status404) import Util.Free (F(..), liftF) -- A Router functor can either add a middleware, or resolve to an app itself. data RouterF x = M Middleware x | D Application deriving Functor -- Router type type RouteM = F RouterF -- | Catch all routes and process them with the supplied application. -- Note: As expected from the name, no request proceeds past a catchall. catchall :: Application -> RouteM () catchall a = liftF $ D a -- | Synonym of `catchall`. Kept for backwards compatibility defaultAction :: Application -> RouteM () defaultAction = catchall -- | Add a middleware to the application -- Middleware are ordered so the one declared earlier wraps the ones later middleware :: Middleware -> RouteM () middleware m = liftF $ M m () -- | Add a wai-routes handler handler :: HandlerS DefaultMaster DefaultMaster -> RouteM () handler h = middleware $ customRouteDispatch dispatcher' DefaultMaster where dispatcher' env req = runHandler h env (Just $ DefaultRoute $ getRoute req) req getRoute req = (pathInfo $ waiReq req, readQueryString $ queryString $ waiReq req) -- | Add a route to the application. -- Routes are ordered so the one declared earlier is matched first. route :: (Routable master master) => master -> RouteM () route = middleware . routeDispatch -- The final "catchall" application, simply returns a 404 response -- Ideally you should put your own default application defaultApplication :: Application defaultApplication _req h = h $ responseLBS status404 [("Content-Type", "text/plain")] "Error : 404 - Document not found" -- | Convert a RouteM monad into a wai application. -- Note: We ignore the return type of the monad waiApp :: RouteM () -> Application waiApp (F r) = r (const defaultApplication) f where f (M m r') = m r' f (D a) = a -- | Similar to waiApp but returns the app in an arbitrary monad -- Kept for backwards compatibility toWaiApp :: Monad m => RouteM () -> m Application toWaiApp = return . waiApp
ajnsit/wai-routes
src/Routes/Monad.hs
mit
2,729
0
10
550
499
275
224
43
2
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE OverloadedStrings #-} -- | -- Module: Main -- Description: Exampe for using wai-cors with scotty -- Copyright: © 2015 Lars Kuhtz <[email protected]> -- License: MIT -- Maintainer: Lars Kuhtz <[email protected]> -- Stability: experimental -- module Main ( main ) where import Network.Wai.Middleware.Cors import Web.Scotty main ∷ IO () main = scotty 8080 $ do middleware simpleCors matchAny "/" $ text "Success"
larskuhtz/wai-cors
examples/Scotty.hs
mit
470
0
9
80
72
42
30
10
1
{- | Copyright : (c) Takayuki Muranushi, 2015 License : MIT Maintainer : [email protected] Stability : experimental A virtual machine with multidimensional vector instructions that operates on structured lattices, as described in http://arxiv.org/abs/1204.4779 . -} {-# LANGUAGE DataKinds, DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable, FlexibleInstances, FunctionalDependencies, GeneralizedNewtypeDeriving, MultiParamTypeClasses, PatternSynonyms,TemplateHaskell, TypeSynonymInstances, ViewPatterns #-} module Formura.OrthotopeMachine.Graph where import Algebra.Lattice import Control.Lens import Data.Data import qualified Data.Map as M import Text.Read (Read(..)) import qualified Formura.Annotation as A import Formura.GlobalEnvironment import Formura.Language.Combinator import Formura.Syntax import Formura.Type import Formura.Vec -- | The functor for orthotope machine-specific instructions. Note that arithmetic operations are outsourced. data LoadUncursoredF x = LoadF IdentName deriving (Eq, Ord, Show, Functor, Foldable, Traversable) data DataflowInstF x = StoreF IdentName x | LoadIndexF Int | LoadExtentF Int deriving (Eq, Ord, Show, Functor, Foldable, Traversable) -- | The functor for language that support shift operations. data ShiftF x = ShiftF (Vec Int) x deriving (Eq, Ord, Show, Functor, Foldable, Traversable) -- | The functor for language that support cursored load of graph nodes. data LoadCursorF x = LoadCursorF (Vec Int) OMNodeID | LoadCursorStaticF (Vec Int) IdentName deriving (Eq, Ord, Show, Functor, Foldable, Traversable) -- | smart patterns pattern Load n <- ((^? match) -> Just (LoadF n)) where Load n = match # LoadF n pattern Store n x <- ((^? match) -> Just (StoreF n x)) where Store n x = match # StoreF n x pattern LoadIndex n <- ((^? match) -> Just (LoadIndexF n)) where LoadIndex n = match # LoadIndexF n pattern LoadExtent n <- ((^? match) -> Just (LoadExtentF n)) where LoadExtent n = match # LoadExtentF n pattern Shift v x <- ((^? match) -> Just (ShiftF v x)) where Shift v x = match # ShiftF v x pattern LoadCursor v x <- ((^? match) -> Just (LoadCursorF v x)) where LoadCursor v x = match # LoadCursorF v x pattern LoadCursorStatic v x <- ((^? match) -> Just (LoadCursorStaticF v x)) where LoadCursorStatic v x = match # LoadCursorStaticF v x newtype OMNodeID = OMNodeID Int deriving (Eq, Ord, Num, Data) instance Show OMNodeID where showsPrec n (OMNodeID x) = showsPrec n x instance Read OMNodeID where readPrec = fmap OMNodeID readPrec newtype MMNodeID = MMNodeID Int deriving (Eq, Ord, Num, Data) instance Show MMNodeID where showsPrec n (MMNodeID x) = showsPrec n x instance Read MMNodeID where readPrec = fmap MMNodeID readPrec -- | The instruction type for Orthotope Machine. type OMInstF = Sum '[DataflowInstF, LoadUncursoredF, ShiftF, OperatorF, ImmF] type OMInstruction = OMInstF OMNodeID -- | The instruction type for Manifest Machine, where every node is manifest, -- and each instruction is actually a subgraph for delayed computation type MMInstF = Sum '[DataflowInstF, LoadCursorF, OperatorF, ImmF] type MMInstruction = M.Map MMNodeID (Node MicroInstruction MicroNodeType) type MicroInstruction = MMInstF MMNodeID data MMLocation = MMLocation { _mmlOMNodeID :: OMNodeID, _mmlCursor :: (Vec Int)} deriving(Eq, Ord, Show) mmInstTails :: MMInstruction -> [MMInstF MMNodeID] mmInstTails mminst = rets where rets = [_nodeInst nd | nd <- M.elems mminst, let Just (MMLocation omnid2 _) = A.viewMaybe nd, omnid2==omnid ] Just (MMLocation omnid _) = A.viewMaybe maxNode maxNode :: MicroNode maxNode = snd $ M.findMax mminst type OMNodeType = Fix OMNodeTypeF type OMNodeTypeF = Sum '[ TopTypeF, GridTypeF, ElemTypeF ] type MicroNodeType = Fix MicroNodeTypeF type MicroNodeTypeF = Sum '[ ElemTypeF ] instance MeetSemiLattice OMNodeType where (/\) = semiLatticeOfOMNodeType semiLatticeOfOMNodeType :: OMNodeType -> OMNodeType -> OMNodeType semiLatticeOfOMNodeType a b = case go a b of TopType -> case go b a of TopType -> TopType c -> c c -> c where go :: OMNodeType -> OMNodeType -> OMNodeType go a b | a == b = a go (ElemType ea) (ElemType eb) = subFix (ElemType ea /\ ElemType eb :: ElementalType) go a@(ElemType _) b@(GridType v c) = let d = a /\ c in if d==TopType then TopType else GridType v d go (GridType v1 c1) (GridType v2 c2) = (if v1 == v2 then GridType v1 (c1 /\ c2) else TopType) go _ _ = TopType mapElemType :: (IdentName -> IdentName) -> OMNodeType -> OMNodeType mapElemType f (ElemType t) = ElemType $ f t mapElemType f (GridType v t) = GridType v $ mapElemType f t mapElemType _ TopType = TopType data Node instType typeType = Node {_nodeInst :: instType, _nodeType :: typeType, _nodeAnnot :: A.Annotation} instance (Eq i, Eq t) => Eq (Node i t) where (Node a b _) == (Node c d _) = (a,b) == (c,d) instance (Ord i, Ord t) => Ord (Node i t) where compare (Node a b _) (Node c d _) = compare (a,b) (c,d) instance (Show v, Show t) => Show (Node v t) where show (Node v t _) = show v ++ " :: " ++ show t type OMNode = Node OMInstruction OMNodeType type MMNode = Node MMInstruction OMNodeType type MicroNode = Node MicroInstruction MicroNodeType makeLenses ''Node instance A.Annotated (Node v t) where annotation = nodeAnnot -- instance (Data instType) => Data (Node instType typeType) where -- gfoldl (*) z x = x{_nodeInst = gfoldl (*) z (_nodeInst x)} type Graph instType typeType = M.Map OMNodeID (Node instType typeType) type OMGraph = Graph OMInstruction OMNodeType type MMGraph = Graph MMInstruction OMNodeType data NodeValueF x = NodeValueF OMNodeID OMNodeType deriving (Eq, Ord, Show, Functor, Foldable, Traversable) pattern NodeValue n t <- ((^? match) -> Just (NodeValueF n t)) where NodeValue n t = match # NodeValueF n t pattern n :. t <- ((^? match) -> Just (NodeValueF n t)) where n :. t = match # NodeValueF n t data FunValueF x = FunValueF LExpr RXExpr deriving (Eq, Ord, Show, Functor, Foldable, Traversable) pattern FunValue l r <- ((^? match) -> Just (FunValueF l r)) where FunValue l r = match # FunValueF l r -- | RXExpr is RExpr extended with NodeValue constructors type RXExpr = Fix RXExprF type RXExprF = Sum '[ LetF, LambdaF, ApplyF, GridF, TupleF, OperatorF, IdentF, FunValueF, NodeValueF, ImmF ] -- | 'ValueExpr' represents final forms of orthotope machine evaluation. type ValueExpr = Fix ValueExprF type ValueExprF = Sum '[TupleF, FunValueF, NodeValueF, ImmF] -- | 'ValueLexExpr' extends 'ValueExpr' with unresolved identifiers. Expressions with free variables evaluate to 'ValueLexExpr' , not 'ValueExpr' . type ValueLexExpr = Fix ValueLexExprF type ValueLexExprF = Sum '[TupleF, FunValueF, NodeValueF, IdentF, ImmF] instance Typed ValueExpr where typeExprOf (Imm _) = ElemType "Rational" typeExprOf (NodeValue _ t) = subFix t typeExprOf (FunValue _ _) = FunType typeExprOf (Tuple xs) = Tuple $ map typeExprOf xs data MachineProgram instType typeType = MachineProgram { _omGlobalEnvironment :: GlobalEnvironment , _omInitGraph :: Graph instType typeType , _omStepGraph :: Graph instType typeType , _omStateSignature :: M.Map IdentName TypeExpr } makeClassy ''MachineProgram type OMProgram = MachineProgram OMInstruction OMNodeType type MMProgram = MachineProgram MMInstruction OMNodeType instance HasGlobalEnvironment (MachineProgram v t) where globalEnvironment = omGlobalEnvironment makeClassy ''MMLocation
nushio3/formura
src/Formura/OrthotopeMachine/Graph.hs
mit
7,729
0
14
1,533
2,372
1,264
1,108
133
9
module Example.Example05 where import qualified Com.Mysql.Cj.Mysqlx.Protobuf.Ok as POk import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import DataBase.MySQLX.Util import DataBase.MySQLX.Model example01 = do putStrLn "start Example02#example01" bin <- B.readFile "src/DataBase/MySQLX/Example/Example02_getIntFromLE.bin" print $ getIntFromLE bin -- 112 putStrLn "end Example02#example01" test_insertUUID = do putStrLn "start Example02#test_insertUUID" let a = (insertUUID "aaaa{bbbbbbb}" "***") putStrLn $ show $ "aaaa{\"id\" : ***, bbbbbbb}" == a putStrLn "end Example02#test_insertUUID" {- $ protoc-3/bin/protoc --decode_raw < src/DataBase/MySQLX/Example/dump_server_response_of_close.bin 1: "bye!" -} example_model_close :: IO POk.Ok example_model_close = readObj "src/DataBase/MySQLX/Example/dump_server_response_of_close.bin"
naoto-ogawa/h-xproto-mysql
src/Example/Example05.hs
mit
938
0
11
158
155
84
71
18
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-licensespecification.html module Stratosphere.ResourceProperties.EC2InstanceLicenseSpecification where import Stratosphere.ResourceImports -- | Full data type definition for EC2InstanceLicenseSpecification. See -- 'ec2InstanceLicenseSpecification' for a more convenient constructor. data EC2InstanceLicenseSpecification = EC2InstanceLicenseSpecification { _eC2InstanceLicenseSpecificationLicenseConfigurationArn :: Val Text } deriving (Show, Eq) instance ToJSON EC2InstanceLicenseSpecification where toJSON EC2InstanceLicenseSpecification{..} = object $ catMaybes [ (Just . ("LicenseConfigurationArn",) . toJSON) _eC2InstanceLicenseSpecificationLicenseConfigurationArn ] -- | Constructor for 'EC2InstanceLicenseSpecification' containing required -- fields as arguments. ec2InstanceLicenseSpecification :: Val Text -- ^ 'ecilsLicenseConfigurationArn' -> EC2InstanceLicenseSpecification ec2InstanceLicenseSpecification licenseConfigurationArnarg = EC2InstanceLicenseSpecification { _eC2InstanceLicenseSpecificationLicenseConfigurationArn = licenseConfigurationArnarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-licensespecification.html#cfn-ec2-instance-licensespecification-licenseconfigurationarn ecilsLicenseConfigurationArn :: Lens' EC2InstanceLicenseSpecification (Val Text) ecilsLicenseConfigurationArn = lens _eC2InstanceLicenseSpecificationLicenseConfigurationArn (\s a -> s { _eC2InstanceLicenseSpecificationLicenseConfigurationArn = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EC2InstanceLicenseSpecification.hs
mit
1,763
0
13
164
174
100
74
23
1
-------------------------------------------------------------------------------- {- | Module : Data.Acid.Centered Copyright : MIT Maintainer : [email protected] Portability : non-portable (uses GHC extensions) A replication backend for acid-state that is centered around a Master node. Slave nodes connect to the Master, are synchronized and get updated by the Master continuously. This backend offers two flavors of operation: [@Regular operation@] No redundancy guarantees but fast. [@Redundant operation@] Guarantees redundant replication on /n/ nodes but slower. In both cases Slaves' Updates block (and eventually time out) if the Master is unreachable. Queries operate on the local state with the performance known from acid-state. Note that state on all nodes is eventually consistent, i.e. it might differ shortly (for Queries run concurrently to Updates being serialized). -} module Data.Acid.Centered ( -- * Usage -- | -- Open your AcidState using one of the functions below. Take care to use the -- same initial-state on all nodes. Afterwards the usual interface of acid state -- is available. -- -- Always make sure to have sensible exception management since naturally a lot -- more error sources exist with this backend than do for a 'Data.Acid.Local' -- AcidState. -- Using 'Control.Exception.bracket' is recommended for achieving this -- conveniently: -- -- > main = bracket -- > (enslaveState ...) -- > closeAcidState -- > $ \acid -> do -- > ... -- -- 'Data.Acid.createCheckpoint' issued on Master is a global operation, -- while issued on a Slave it is not. Note that Checkpoints on Master reduce the -- amount of Updates to be transferred when a Slave (re-)connects. -- -- 'Data.Acid.createArchive' is an operation local to each node since usually -- further action is required. For global Archives see 'createArchiveGlobally'. -- * Regular operation -- | -- Running Updates on Master works as known from acid-state and with -- negligible performance loss. -- On Slaves Updates are delayed by approximately one round trip time (RTT). -- When no Slaves are connected Updates are only serialized on the Master, -- i.e. there is no redundancy. openMasterState , openMasterStateFrom , enslaveState , enslaveStateFrom -- * Redundant operation -- | -- When Updates are scheduled they are sent out and written to disk on all -- nodes. However, an Update is visible to Queries (and its result returned) -- /only/ as soon as at least /n/ nodes are done replicating it. Thus each -- Update is delayed for at least one RTT. -- -- If less than /n-1/ Slave nodes are connected, all Updates are blocked -- until enough nodes are available again. Queries are not affected and -- operate on the last /n/-replicated state. -- -- /Note:/ Shutting down and restarting the Master resumes the last state -- including even Updates that were not /n/-replicated. , openRedMasterState , openRedMasterStateFrom , enslaveRedState , enslaveRedStateFrom -- * Types , PortNumber ) where import Data.Acid.Centered.Master import Data.Acid.Centered.Slave import Data.Acid.Centered.Common
sdx23/acid-state-dist
src/Data/Acid/Centered.hs
mit
3,339
0
4
728
104
86
18
14
0
module AnotherParser where import List import Data.Char import System.IO -- |A line is string of characters (end-of-line has been stripped) paired with -- its line number. type Line = (Int, String) -- |A line group is either a list of a single line representing a directive or -- a list of multiple lines representing an entry; in the latter case, the -- head of the group is the entry declaration and the tail is the list of -- transactions for the entry. type LineGroup = [Line] -- Put your favorite file name here fileName = "fxt.ledger" main = do input <- readFile fileName let items = journal input mapM_ (putStrLn . show) items putStrLn ("Found " ++ show (length items) ++ " items") journal :: String -> [LineGroup] journal = groupLines . mkLines -- |Break down the input into a list of lines, paired them up with line -- numbers, and drop all comment and empty lines. mkLines :: String -> [Line] mkLines s = filter (not . isComment . snd) (zip [1..](lines s)) -- |A comment is a line that is empty or starts with ';' or only contains -- white space. isComment :: String -> Bool isComment [] = True isComment (c:cs) | c == ';' = True | otherwise = and . map isSpace $ (c:cs) -- |Lines are grouped so that all transactions lines for an entry are in the same -- line group as the entry line. -- We accomplish this by passing around an extra parameter used to accumulate -- all the lines for the current group. groupLines :: LineGroup -> [LineGroup] groupLines = tail . groupLines' [] where groupLines' cg [] = [cg] groupLines' cg (l:ls) | isTrans . snd $ l = groupLines' (cg ++ [l]) ls | otherwise = cg : groupLines' [l] ls -- |A transaction is a line that starts with space. -- This function should not be called on lines that consists only of white space. isTrans :: String -> Bool isTrans (c:cs) = isSpace c
mgax/beancount
lib/haskell/AnotherParser.hs
gpl-2.0
1,931
0
13
454
410
221
189
26
2
import qualified Data.Map as M import System.Environment (getArgs) type Prog = [[String]] data LabelData = L (M.Map String LabelData) Prog value v vs = M.findWithDefault False v vs x `nand` y = not (x && y) runCmds :: M.Map String Bool -> M.Map String LabelData -> [[String]] -> String runCmds vars labels prog@([label]:rest) = case (value label vars, M.lookup label labels) of (True, Just (L labels' prog')) -> runCmds vars labels' prog' _ -> runCmds vars labels' rest where labels' = M.insert label (L labels' rest) labels runCmds vars labels ([v1,v2,v3]:rest) = runCmds (M.insert v1 (value v2 vars `nand` value v3 vars) vars) labels rest runCmds vars labels (vs@[_,_,_,_,_,_,_,_]:rest) = c : runCmds vars labels rest where c = toEnum $ foldl (\n b -> n*2 + fromEnum (value b vars)) 0 vs runCmds _ _ [] = "" runCmds _ _ (snt:_) = error $ "Undefined sentence: " ++ unwords snt interpret = runCmds M.empty M.empty . map words . lines main = do args <- getArgs case args of [] -> interact interpret [fileName] -> putStr . interpret =<< readFile fileName _ -> error "Too many arguments, only one supported"
shinh/ags
be/fetcher/fernando.hs
gpl-2.0
1,208
0
14
295
543
283
260
28
3
{- arch-tag: srcinst main file Copyright (C) 2004 John Goerzen <[email protected]> This program 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 2 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} module Main where import System.Environment import System.Directory import System.Exit import Builder import Dpkg import System.Log.Logger syntaxError :: IO () syntaxError = do putStrLn "Syntax: srcinst install package1 [package2 ... packagen]" exitFailure main = do args <- getArgs setCurrentDirectory "/var/cache/srcinst" updateGlobalLogger rootLoggerName (setLevel DEBUG) updateGlobalLogger "System.Cmd.Utils.pOpen3" (setLevel CRITICAL) case args of "install":xs -> mapM_ buildOrInstall xs _ -> syntaxError
jgoerzen/srcinst
srcinst.hs
gpl-2.0
1,361
0
10
273
130
65
65
18
2
{- | Module : $Header$ Copyright : (c) T.Mossakowski, W.Herding, C.Maeder, Uni Bremen 2004-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Abstract syntax for modal logic extension of CASL Only the added syntax is specified -} module Modal.AS_Modal where import Common.Id import Common.AS_Annotation import CASL.AS_Basic_CASL -- DrIFT command {-! global: GetRange !-} type M_BASIC_SPEC = BASIC_SPEC M_BASIC_ITEM M_SIG_ITEM M_FORMULA type AnModFORM = Annoted (FORMULA M_FORMULA) data M_BASIC_ITEM = Simple_mod_decl [Annoted SIMPLE_ID] [AnModFORM] Range | Term_mod_decl [Annoted SORT] [AnModFORM] Range deriving Show data RIGOR = Rigid | Flexible deriving Show data M_SIG_ITEM = Rigid_op_items RIGOR [Annoted (OP_ITEM M_FORMULA)] Range -- pos: op, semi colons | Rigid_pred_items RIGOR [Annoted (PRED_ITEM M_FORMULA)] Range -- pos: pred, semi colons deriving Show data MODALITY = Simple_mod SIMPLE_ID | Term_mod (TERM M_FORMULA) deriving (Eq, Ord, Show) data M_FORMULA = BoxOrDiamond Bool MODALITY (FORMULA M_FORMULA) Range {- The identifier and the term specify the kind of the modality pos: "[]" or "<>", True if Box, False if Diamond -} deriving (Eq, Ord, Show)
nevrenato/HetsAlloy
Modal/AS_Modal.der.hs
gpl-2.0
1,446
0
10
369
231
130
101
18
0
{- - A simple interpreter for a Turing machine - This is all the machinery for actually simulating the running of such a machine - It can move the tape, write to the tape, read from the tape - When run is supplied with a transition function and initial tape, it should output the final result of the TM - Each TM is assumed to transition to a special state Q "END", where the transition function will not be applied again, but the value of the tape at the current head and right will be returned - Run assumes that the TM starts on a special Q "START". - -} -- Imports --import Data.List main :: IO () main = return () -- Type definitions. data Alphabet = Zero | One | Blank deriving (Eq, Ord, Show) data Move = L | R | S data Tape = Tape { left :: [Alphabet], current :: Alphabet, right :: [Alphabet]} data InternalState = Q { label :: String } type TransitionFunc = (InternalState, Alphabet) -> (InternalState, Alphabet, Move) -- Moves the tape shift :: Tape -> Move -> Tape shift t S = t shift t L = Tape (extendingTail (left t)) (extendingHead (left t)) (current t : right t) shift t R = Tape (current t : left t) (extendingHead (right t)) (extendingTail (right t)) -- Because partial functions are _bad_ extendingHead :: [Alphabet] -> Alphabet extendingHead [] = Blank extendingHead (x:_) = x extendingTail :: [Alphabet] -> [Alphabet] extendingTail [] = [Blank] extendingTail (_:x) = x -- Writes a character to the current head of the tape write :: Tape -> Alphabet -> Tape write t s = Tape (left t) s (right t) -- Convenience functions toList :: Tape -> [Alphabet] toList t = (reverse (left t)) ++ [current t] ++ (right t) fromList :: [Alphabet] -> Tape fromList l = Tape [] (extendingHead l) (extendingTail l) encodeNumber :: Integer -> [Alphabet] encodeNumber n = toBinary $ n where toBinary 0 = [Zero] toBinary 1 = [One] toBinary n | n `mod` 2 == 0 = Zero : toBinary (n `div` 2) | otherwise = One : toBinary ((n-1) `div` 2) -- So we can see things instance Show Tape where show = show . toList -- Applies the transition function runTM :: TransitionFunc -> (InternalState, Tape) -> (InternalState, Tape) runTM f (q,t) = (q', writeAndMove (s, m) t) where (q', s, m) = f (q, current t) -- Writes the character to the tape, and then moves the tape writeAndMove :: (Alphabet, Move) -> Tape -> Tape writeAndMove (s, m) t = shift t' m where t' = write t s -- Runs the TM, and outputs the final result as a list run :: TransitionFunc -> Tape -> (Integer, [Alphabet]) run f t = run' 0 f (Q "START", t) run' :: Integer -> TransitionFunc -> (InternalState, Tape) -> (Integer, [Alphabet]) run' n f (q, t) | label q == "END" = (n, current t : right t) | otherwise = run' (n + 1) f $ runTM f (q, t) -- Runs the TM, showing the tape and state label at each stage showTM :: TransitionFunc -> Tape -> IO () showTM f t = showTM' f (Q "START") t 0 showTM' :: TransitionFunc -> InternalState -> Tape -> Integer -> IO () showTM' f q t n | label q == "END" = putStrLn $ "STEP " ++ show n ++ ": FINAL RESULT: " ++ show (current t : right t) | otherwise = do putStrLn $ "STEP " ++ show n ++ ": STATE: " ++ label q ++ " => " ++ show t let (q', t') = runTM f (q, t) showTM' f q' t' (n + 1) -- the output tape from one TM is written as the input to the next, counting the total number of steps and returning the eventual result -- TODO: replace the output of run with (Integer, Tape) so that actual composition will work. compose :: TransitionFunc -> TransitionFunc -> Tape -> (Integer, [Alphabet]) compose f g t = (count, result) where count = m + n (n, result) = run f (fromList intermediate) (m, intermediate) = run g t {- Definitions of TMs follow -} trivial :: TransitionFunc trivial (q, s) = (Q "END", s, S) oddOnes :: TransitionFunc oddOnes (Q "START", Zero) = (Q "START", Zero, R) oddOnes (Q "START", One) = (Q "ODD", One, R) oddOnes (Q "START", Blank) = (Q "END", Zero, S) oddOnes (Q "ODD", Zero) = (Q "ODD", Zero, R) oddOnes (Q "ODD", One) = (Q "START", One, R) oddOnes (Q "ODD", Blank) = (Q "END", One, S) increment :: TransitionFunc increment (Q "START", Zero) = (Q "DONE", One, L) increment (Q "START", One) = (Q "START", Zero, R) increment (Q "START", Blank) = (Q "DONE", One, L) increment (Q "DONE", Blank) = (Q "END", Blank, R) increment (Q "DONE", a) = (Q "DONE", a, L) palindrome :: TransitionFunc palindrome (Q "START", Zero) = (Q "ZERO", Blank, R) palindrome (Q "START", One) = (Q "ONE", Blank, R) palindrome (Q "START", Blank) = (Q "END", One, S) palindrome (Q "ZERO", Blank) = (Q "CHECKZERO", Blank, L) palindrome (Q "ZERO", s) = (Q "ZERO", s, R) palindrome (Q "ONE", Blank) = (Q "CHECKONE", Blank, L) palindrome (Q "ONE", s) = (Q "ONE", s, R) palindrome (Q "CHECKONE", Zero) = (Q "END", Zero, S) palindrome (Q "CHECKONE", One) = (Q "GOBACK", Blank, L) palindrome (Q "CHECKONE", Blank) = (Q "END", One, S) palindrome (Q "CHECKZERO", Blank) = (Q "END", One, S) palindrome (Q "CHECKZERO", Zero) = (Q "GOBACK", Blank, L) palindrome (Q "CHECKZERO", One) = (Q "END", Zero, S) palindrome (Q "GOBACK", Blank) = (Q "START", Blank, R) palindrome (Q "GOBACK", s) = (Q "GOBACK", s, L) decrement :: TransitionFunc decrement (Q "START", Zero) = (Q "START", One, R) decrement (Q "START", One) = (Q "GOBACK", Zero, L) decrement (Q "START", Blank) = (Q "GOBACK", Blank, L) decrement (Q "GOBACK", Blank) = (Q "END", Blank, R) decrement (Q "GOBACK", s) = (Q "GOBACK", s, L) moveRightThree :: TransitionFunc moveRightThree (Q "START", s) = (Q "TWO", s, R) moveRightThree (Q "TWO", s) = (Q "ONE", s, R) moveRightThree (Q "ONE", s) = (Q "END", s, R) moveUntilZero :: TransitionFunc moveUntilZero (Q "START", One) = (Q "START", One, R) moveUntilZero (Q "START", s) = (Q "END", s, S) insert :: Alphabet -> TransitionFunc insert x (q, s) | label q == "START" = case s of Zero -> (Q "COPYZERO", x, R) One -> (Q "COPYONE", x, R) Blank -> (Q "END", x, S) | label q == "COPYONE" = case s of Zero -> (Q "COPYZERO", One, R) One -> (q, One, R) Blank -> (Q "GOBACK", One, L) | label q == "COPYZERO" = case s of Zero -> (q, Zero, R) One -> (Q "COPYONE", Zero, R) Blank -> (Q "GOBACK", Zero, L) | label q == "GOBACK" = case s of Blank -> (Q "END", Blank, R) s -> (q, s, L) delete :: TransitionFunc delete (Q "START", s) = (Q "GOTOEND", Blank, R) -- starts at the cell to delete, replaces it with a Blank and then tracks until the end delete (Q "GOTOEND", Blank) = (Q "COPYBACK", Blank, L) -- moves to the end of the input delete (Q "GOTOEND", s) = (Q "GOTOEND", s, R) delete (Q "COPYBACK", One) = (Q "COPYONE", Blank, L) -- the results are now shifted Left by one cell, until we hit the blank we wrote (we can't hit a blank before!) delete (Q "COPYBACK", Zero) = (Q "COPYZERO", Blank, L) delete (Q "COPYBACK", Blank) = (Q "DONE", Blank, L) delete (Q "COPYONE", Zero) = (Q "COPYZERO", One, L) delete (Q "COPYONE", One) = (Q "COPYONE", One, L) delete (Q "COPYONE", Blank) = (Q "DONE", One, L) delete (Q "COPYZERO", Zero) = (Q "COPYZERO", Zero, L) delete (Q "COPYZERO", One) = (Q "COPYONE", Zero, L) delete (Q "COPYZERO", Blank) = (Q "DONE", Zero, L) delete (Q "DONE", Blank) = (Q "END", Blank, R) -- Once we've hit the blank, we stop copying, and we track to the start of the input. Once we hit Blank for a second time, we are done delete (Q "DONE", s) = (Q "DONE", s, L)
icendoan/Fun
haskell/turing.hs
gpl-2.0
7,339
0
13
1,479
3,064
1,665
1,399
134
8
module Render (clearCanvas, CPosition(..), CSize(..), toDouble, renderWave, renderTurtle, renderPngFit, renderPngInline, renderLayoutG, renderLayoutM, yposSequence, renderSlide) where import System.FilePath ((</>),(<.>)) import Control.Monad import Control.Monad.Reader import Text.Pandoc (Attr) import qualified Graphics.UI.Gtk as G import qualified Graphics.Rendering.Cairo as C -- import FormatPangoMarkup import Config import WrapPaths (wrapGetDataFileName) data CPosition = CPosition Double | CCenter deriving (Show, Eq, Ord) data CSize = CSize Double | CFit deriving (Show, Eq, Ord) type CXy = (CPosition, CPosition) type CWl = (CSize, CSize) toDouble :: Integral a => a -> Double toDouble = fromIntegral type LayoutFunc = G.PangoLayout -> G.Markup -> IO () type LayoutFuncGlowing = String -> CXy -> Double -> String -> IO (G.PangoLayout, G.PangoLayout, Double, Double) stringToLayout :: String -> LayoutFunc -> CXy -> Double -> String -> IO (G.PangoLayout, Double, Double) stringToLayout fname func (x, _) fsize text = do lay <- G.cairoCreateContext Nothing >>= G.layoutEmpty void $ func lay text G.layoutSetWrap lay G.WrapPartialWords setAW lay x fd <- liftIO G.fontDescriptionNew G.fontDescriptionSetSize fd fsize G.fontDescriptionSetFamily fd fname G.layoutSetFontDescription lay (Just fd) (_, G.PangoRectangle _ _ lw lh) <- G.layoutGetExtents lay -- xxx inkとlogicalの違いは? return (lay, lw, lh) where screenW = toDouble (canvasW gCfg) setAW lay CCenter = do G.layoutSetWidth lay (Just screenW) G.layoutSetAlignment lay G.AlignCenter setAW lay (CPosition x') = do G.layoutSetWidth lay (Just $ screenW - x' * 2) G.layoutSetAlignment lay G.AlignLeft truePosition :: Double -> Double -> (CPosition, CPosition) -> (Double, Double) truePosition fsize _ (CPosition x', CPosition y') = (x', y' + fsize) truePosition _ _ (CCenter, CPosition y') = (0, y') truePosition _ _ (x', y') = error $ "called with x=" ++ show x' ++ " y=" ++ show y' stringToLayoutGlowing :: LayoutFunc -> LayoutFunc -> LayoutFuncGlowing stringToLayoutGlowing funcBack funcFront fname xy fsize text = do (layB, _, _) <- stringToLayout fname funcBack xy fsize text (lay, lw, lh) <- stringToLayout fname funcFront xy fsize text return (layB, lay, lw, lh) renderLayout' :: String -> LayoutFuncGlowing -> CXy -> Double -> String -> C.Render Double renderLayout' fname func (x, y) fsize text = do C.save (layB, lay, lw, lh) <- liftIO $ func fname (x, y) fsize text let (xt, yt) = truePosition fsize lw (x, y) mapM_ (moveShowLayout layB) [(xt + xd, yt + yd) | xd <- [-0.7, 0.7], yd <- [-0.7, 0.7]] moveShowLayout lay (xt, yt) C.restore return $ yt + lh where moveShowLayout l (x', y') = C.moveTo x' y' >> G.showLayout l renderLayoutM :: CXy -> Double -> String -> C.Render Double renderLayoutM = renderLayout' "IPA P明朝" (stringToLayoutGlowing fb ff) where fb l t = void $ G.layoutSetMarkup l ("<span foreground=\"white\">" ++ G.escapeMarkup t ++ "</span>") ff = G.layoutSetText renderLayoutG' :: LayoutFuncGlowing -> CXy -> Double -> String -> C.Render Double renderLayoutG' = renderLayout' "IPAゴシック" renderLayoutG :: Attr -> CXy -> Double -> String -> C.Render Double renderLayoutG (_, [], _) = renderLayoutG' (stringToLayoutGlowing fb ff) where fb l t = void $ G.layoutSetMarkup l ("<span foreground=\"white\">" ++ G.escapeMarkup t ++ "</span>") ff = G.layoutSetText renderLayoutG (_, classs, _) = renderLayoutG' (stringToLayoutGlowing fb ff) where fb l t = void $ G.layoutSetMarkup l (formatPangoMarkupWhite (head classs) t) ff l t = void $ G.layoutSetMarkup l (formatPangoMarkup (head classs) t) renderSurface :: Double -> Double -> Double -> C.Surface -> C.Render () renderSurface x y alpha surface = do C.save C.setSourceSurface surface x y C.paintWithAlpha alpha C.restore pngSurfaceSize :: FilePath -> C.Render (C.Surface, Int, Int) pngSurfaceSize file = do surface <- liftIO $ C.imageSurfaceCreateFromPNG file w <- C.imageSurfaceGetWidth surface h <- C.imageSurfaceGetHeight surface ret surface w h where ret _ 0 0 = do surface' <- liftIO $ wrapGetDataFileName ("data" </> "notfound" <.> "png") >>= C.imageSurfaceCreateFromPNG w' <- C.imageSurfaceGetWidth surface' h' <- C.imageSurfaceGetHeight surface' return (surface', w', h') ret s w h = return (s, w, h) renderPngSize :: Double -> Double -> Double -> Double -> Double -> FilePath -> C.Render Double renderPngSize = f where f x y w h alpha file = do C.save (surface, iw, ih) <- pngSurfaceSize file let xscale = w / toDouble iw let yscale = h / toDouble ih C.scale xscale yscale renderSurface (x / xscale) (y / yscale) alpha surface C.surfaceFinish surface C.restore return $ y + h renderPngInline :: CXy -> CWl -> Double -> FilePath -> C.Render Double renderPngInline = f where f (CCenter, CPosition y) (CFit, CFit) alpha file = do C.save (surface, iw, ih) <- pngSurfaceSize file let diw = toDouble iw dih = toDouble ih cw = toDouble (canvasW gCfg) ch = toDouble (canvasH gCfg) wratio = cw / diw hratio = (ch - y) / dih scale = if wratio > hratio then hratio * 0.95 else wratio * 0.95 tiw = diw * scale tih = dih * scale y' = y + 10 C.scale scale scale renderSurface ((cw / 2 - tiw / 2) / scale) (y' / scale) alpha surface C.surfaceFinish surface C.restore return $ y' + tih f _ _ _ _ = return 0 -- xxx renerPngFit統合して一関数にすべき renderPngFit :: Double -> FilePath -> C.Render () renderPngFit = f where f alpha file = do C.save (surface, iw, ih) <- pngSurfaceSize file let cw = toDouble $ canvasW gCfg ch = toDouble $ canvasH gCfg C.scale (cw / toDouble iw) (ch / toDouble ih) renderSurface 0 0 alpha surface C.surfaceFinish surface C.restore clearCanvas :: Int -> Int -> C.Render () clearCanvas w h = do C.save C.setSourceRGB 1 1 1 C.rectangle 0 0 (toDouble w) (toDouble h) C.fill >> C.stroke >> C.restore -- xxx プレゼン時間に応じて波表示 renderWave :: C.Render () renderWave = do sec <- liftIO elapsedSecFromStart smin <- queryCarettahState speechMinutes let ws = waveSize gCfg ch = toDouble $ canvasH gCfg speechSec = 60 * smin charMax = waveCharMax gCfg numChar = round $ charMax * sec / speechSec void $ renderLayoutM (CPosition 0, CPosition $ ch - ws * 2) ws $ replicate numChar '>' return () renderTurtle :: Double -> C.Render () renderTurtle progress = do fn <- liftIO . wrapGetDataFileName $ "data" </> "turtle" <.> "png" renderPngSize (ts / 2 + (cw - ts * 2) * progress) (ch - ts) ts ts 1 fn >> return () where ts = turtleSize gCfg cw = toDouble $ canvasW gCfg ch = toDouble $ canvasH gCfg yposSequence :: Double -> [Double -> C.Render Double] -> C.Render Double yposSequence ypos (x:xs) = x ypos >>= (`yposSequence` xs) yposSequence ypos [] = return ypos renderSlideFilter :: Int -> Int -> [Double -> C.Render Double] -> C.Render () renderSlideFilter w h s = do clearCanvas w h let cw = toDouble $ canvasW gCfg ch = toDouble $ canvasH gCfg tcy = textContextY gCfg C.scale (toDouble w / cw) (toDouble h / ch) void $ yposSequence tcy s renderWave renderSlide :: [[Double -> C.Render Double]] -> Int -> Int -> Int -> C.Render () renderSlide s p w h = do renderSlideFilter w h (s !! p) renderTurtle $ toDouble p / toDouble (length s - 1)
uemurax/carettah
Render.hs
gpl-2.0
7,947
11
17
1,968
2,958
1,497
1,461
183
3
{-# LANGUAGE CPP #-} {- | Module : $Header$ Description : Writing various formats, according to Hets options Copyright : (c) Klaus Luettich, C.Maeder, Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable(DevGraph) Writing various formats, according to Hets options -} module Driver.WriteFn (writeSpecFiles, writeVerbFile) where import Control.Monad import Text.ParserCombinators.Parsec import Text.XML.Light import Data.List (partition, (\\)) import Common.AS_Annotation import Common.Id import Common.IRI (IRI, simpleIdToIRI, iriToStringShortUnsecure) import Common.DocUtils import Common.ExtSign import Common.LibName import Common.Result import Common.Parsec (forget) import Common.GlobalAnnotations (GlobalAnnos) import qualified Data.Map as Map import Common.SExpr import Common.IO import Logic.Coerce import Logic.Comorphism (targetLogic) import Logic.Logic import Logic.Grothendieck import Comorphisms.LogicGraph import qualified Static.ToXml as ToXml import CASL.Logic_CASL import CASL.CompositionTable.Pretty import CASL.CompositionTable.ToXml import CASL.CompositionTable.ComputeTable import CASL.CompositionTable.ModelChecker import CASL.CompositionTable.ParseSparQ #ifdef PROGRAMATICA import Haskell.CreateModules #endif import Isabelle.CreateTheories import Isabelle.IsaParse import Isabelle.IsaPrint (printIsaTheory) import SoftFOL.CreateDFGDoc import SoftFOL.DFGParser import SoftFOL.ParseTPTP import FreeCAD.XMLPrinter (exportXMLFC) import FreeCAD.Logic_FreeCAD import VSE.Logic_VSE import VSE.ToSExpr #ifndef NOOWLLOGIC import OWL2.Logic_OWL2 import qualified OWL2.ManchesterPrint as OWL2 (printOWLBasicTheory) import qualified OWL2.ManchesterParser as OWL2 (basicSpec) #endif #ifdef RDFLOGIC import RDF.Logic_RDF import qualified RDF.Print as RDF (printRDFBasicTheory) #endif import CommonLogic.Logic_CommonLogic import qualified CommonLogic.AS_CommonLogic as CL_AS (exportCLIF) import qualified CommonLogic.Parse_CLIF as CL_Parse (cltext) import Logic.Prover import Static.GTheory import Static.DevGraph import Static.CheckGlobalContext import Static.DotGraph import qualified Static.PrintDevGraph as DG import Proofs.StatusUtils import Static.ComputeTheory import Driver.Options import Driver.ReadFn (libNameToFile) import Driver.WriteLibDefn import OMDoc.XmlInterface (xmlOut) import OMDoc.Export (exportLibEnv) writeVerbFile :: HetcatsOpts -> FilePath -> String -> IO () writeVerbFile opts f str = do putIfVerbose opts 2 $ "Writing file: " ++ f writeEncFile (ioEncoding opts) f str -- | compute for each LibName in the List a path relative to the given FilePath writeVerbFiles :: HetcatsOpts -- ^ Hets options -> String -- ^ A suffix to be combined with the libname -> [(LibName, String)] -- ^ An output list -> IO () writeVerbFiles opts suffix = mapM_ f where f (ln, s) = writeVerbFile opts (libNameToFile ln ++ suffix) s writeLibEnv :: HetcatsOpts -> FilePath -> LibEnv -> LibName -> OutType -> IO () writeLibEnv opts filePrefix lenv ln ot = let f = filePrefix ++ "." ++ show ot dg = lookupDGraph ln lenv in case ot of Prf -> toShATermString (ln, lookupHistory ln lenv) >>= writeVerbFile opts f XmlOut -> writeVerbFile opts f $ ppTopElement $ ToXml.dGraph lenv ln dg OmdocOut -> do let Result ds mOmd = exportLibEnv (recurse opts) (outdir opts) ln lenv showDiags opts ds case mOmd of Just omd -> writeVerbFiles opts ".omdoc" $ map (\ (libn, od) -> (libn, xmlOut od)) omd Nothing -> putIfVerbose opts 0 "could not translate to OMDoc" GraphOut (Dot showInternalNodeLabels) -> writeVerbFile opts f $ dotGraph f showInternalNodeLabels "" dg _ -> return () writeSoftFOL :: HetcatsOpts -> FilePath -> G_theory -> IRI -> SPFType -> Int -> String -> IO () writeSoftFOL opts f gTh i c n msg = do let cc = case c of ConsistencyCheck -> True ProveTheory -> False mDoc <- printTheoryAsSoftFOL i n cc $ (if cc then theoremsToAxioms else id) gTh maybe (putIfVerbose opts 0 $ "could not translate to " ++ msg ++ " file: " ++ f) ( \ d -> do let str = shows d "\n" case parse (if n == 0 then forget parseSPASS else forget tptp) f str of Left err -> putIfVerbose opts 0 $ show err _ -> putIfVerbose opts 3 $ "reparsed: " ++ f writeVerbFile opts f str) mDoc writeFreeCADFile :: HetcatsOpts -> FilePath -> G_theory -> IO () writeFreeCADFile opts filePrefix (G_theory lid (ExtSign sign _) _ _ _) = do fcSign <- coercePlainSign lid FreeCAD "Expecting a FreeCAD signature for writing FreeCAD xml" sign writeVerbFile opts (filePrefix ++ ".xml") $ exportXMLFC fcSign writeIsaFile :: HetcatsOpts -> FilePath -> G_theory -> LibName -> IRI -> IO () writeIsaFile opts filePrefix raw_gTh ln i = do let Result ds mTh = createIsaTheory raw_gTh addThn = (++ '_' : iriToStringShortUnsecure i) fp = addThn filePrefix showDiags opts ds case mTh of Nothing -> putIfVerbose opts 0 $ "could not translate to Isabelle theory: " ++ fp Just (sign, sens) -> do let tn = addThn . reverse . takeWhile (/= '/') . reverse $ case show $ getLibId ln of [] -> filePrefix lstr -> lstr sf = shows (printIsaTheory tn sign sens) "\n" f = fp ++ ".thy" case parse parseTheory f sf of Left err -> putIfVerbose opts 0 $ show err _ -> putIfVerbose opts 3 $ "reparsed: " ++ f writeVerbFile opts f sf when (hasPrfOut opts && verbose opts >= 3) $ let (axs, rest) = partition ( \ s -> isAxiom s || isDef s) sens in mapM_ ( \ s -> let tnf = tn ++ "_" ++ senAttr s tf = fp ++ "_" ++ senAttr s ++ ".thy" in writeVerbFile opts tf $ shows (printIsaTheory tnf sign $ s : axs) "\n") rest writeTheory :: [String] -> String -> HetcatsOpts -> FilePath -> GlobalAnnos -> G_theory -> LibName -> IRI -> OutType -> IO () writeTheory ins nam opts filePrefix ga raw_gTh@(G_theory lid (ExtSign sign0 _) _ sens0 _) ln i ot = let fp = filePrefix ++ "_" ++ iriToStringShortUnsecure i f = fp ++ "." ++ show ot th = (sign0, toNamedList sens0) lang = language_name lid in case ot of FreeCADOut -> writeFreeCADFile opts filePrefix raw_gTh ThyFile -> writeIsaFile opts filePrefix raw_gTh ln i DfgFile c -> writeSoftFOL opts f raw_gTh i c 0 "DFG" TPTPFile c -> writeSoftFOL opts f raw_gTh i c 1 "TPTP" TheoryFile d -> do if null $ show d then writeVerbFile opts f $ shows (DG.printTh ga i raw_gTh) "\n" else putIfVerbose opts 0 "printing theory delta is not implemented" when (lang == language_name VSE) $ do (sign, sens) <- coerceBasicTheory lid VSE "" th let (sign', sens') = addUniformRestr sign sens lse = map (namedSenToSExpr sign') sens' unless (null lse) $ writeVerbFile opts (fp ++ ".sexpr") $ shows (prettySExpr $ SList lse) "\n" SigFile d -> do if null $ show d then writeVerbFile opts f $ shows (pretty $ signOf raw_gTh) "\n" else putIfVerbose opts 0 "printing signature delta is not implemented" when (lang == language_name VSE) $ do (sign, sens) <- coerceBasicTheory lid VSE "" th let (sign', _sens') = addUniformRestr sign sens writeVerbFile opts (f ++ ".sexpr") $ shows (prettySExpr $ vseSignToSExpr sign') "\n" SymXml -> writeVerbFile opts f $ ppTopElement $ ToXml.showSymbolsTh ins nam ga raw_gTh #ifdef PROGRAMATICA HaskellOut -> case printModule raw_gTh of Nothing -> putIfVerbose opts 0 $ "could not translate to Haskell file: " ++ f Just d -> writeVerbFile opts f $ shows d "\n" #endif ComptableXml -> if lang == language_name CASL then do th2 <- coerceBasicTheory lid CASL "" th let Result ds res = computeCompTable i th2 showDiags opts ds case res of Just td -> writeVerbFile opts f $ tableXmlStr td Nothing -> return () else putIfVerbose opts 0 $ "expected CASL theory for: " ++ f #ifndef NOOWLLOGIC OWLOut | lang == language_name OWL2 -> do th2 <- coerceBasicTheory lid OWL2 "" th let owltext = shows (OWL2.printOWLBasicTheory th2) "\n" case parse (OWL2.basicSpec >> eof) f owltext of Left err -> putIfVerbose opts 0 $ show err _ -> putIfVerbose opts 3 $ "reparsed: " ++ f writeVerbFile opts f owltext | otherwise -> putIfVerbose opts 0 $ "expected OWL theory for: " ++ f #endif #ifdef RDFLOGIC RDFOut | lang == language_name RDF -> do th2 <- coerceBasicTheory lid RDF "" th let rdftext = shows (RDF.printRDFBasicTheory th2) "\n" writeVerbFile opts f rdftext | otherwise -> putIfVerbose opts 0 $ "expected RDF theory for: " ++ f #endif CLIFOut | lang == language_name CommonLogic -> do (_, th2) <- coerceBasicTheory lid CommonLogic "" th let cltext = shows (CL_AS.exportCLIF th2) "\n" case parse (many CL_Parse.cltext >> eof) f cltext of Left err -> putIfVerbose opts 0 $ show err _ -> putIfVerbose opts 3 $ "reparsed: " ++ f writeVerbFile opts f cltext | otherwise -> putIfVerbose opts 0 $ "expected Common Logic theory for: " ++ f _ -> return () -- ignore other file types modelSparQCheck :: HetcatsOpts -> G_theory -> IRI -> IO () modelSparQCheck opts gTh@(G_theory lid (ExtSign sign0 _) _ sens0 _) i = case coerceBasicTheory lid CASL "" (sign0, toNamedList sens0) of Just th2 -> do table <- parseSparQTableFromFile $ modelSparQ opts case table of Left err -> putIfVerbose opts 0 $ "could not parse SparQTable from file: " ++ modelSparQ opts ++ "\n" ++ show err Right y -> do putIfVerbose opts 4 $ unlines ["lisp file content:", show $ table2Doc y, "lisp file end."] let Result d _ = modelCheck i th2 y if null d then putIfVerbose opts 0 "Modelcheck succeeded, no errors found" else showDiags (if verbose opts >= 2 then opts else opts {verbose = 2}) $ reverse d _ -> putIfVerbose opts 0 $ "could not translate Theory to CASL:\n " ++ showDoc gTh "" writeTheoryFiles :: HetcatsOpts -> [OutType] -> FilePath -> LibEnv -> GlobalAnnos -> LibName -> IRI -> Int -> IO () writeTheoryFiles opts specOutTypes filePrefix lenv ga ln i n = let dg = lookupDGraph ln lenv nam = getDGNodeName $ labDG dg n ins = getImportNames dg n in case globalNodeTheory dg n of Nothing -> putIfVerbose opts 0 $ "could not compute theory of spec " ++ show i Just raw_gTh0 -> do let tr = transNames opts Result es mTh = if null tr then return (raw_gTh0, "") else do comor <- lookupCompComorphism (map tokStr tr) logicGraph tTh <- mapG_theory comor raw_gTh0 return (tTh, show comor) showDiags opts es case mTh of Nothing -> putIfVerbose opts 0 "could not translate theory" Just (raw_gTh, tStr) -> do unless (null tStr) $ putIfVerbose opts 2 $ "Translated using comorphism " ++ tStr putIfVerbose opts 4 $ "Sublogic of " ++ show i ++ ": " ++ show (sublogicOfTh raw_gTh) unless (modelSparQ opts == "") $ modelSparQCheck opts (theoremsToAxioms raw_gTh) i mapM_ (writeTheory ins nam opts filePrefix ga raw_gTh ln i) specOutTypes writeSpecFiles :: HetcatsOpts -> FilePath -> LibEnv -> LibName -> DGraph -> IO () writeSpecFiles opts file lenv ln dg = do let gctx = globalEnv dg gns = Map.keys gctx mns = map $ \ t -> Map.findWithDefault (simpleIdToIRI t) (tokStr t) $ Map.fromList $ map (\ i -> (iriToStringShortUnsecure i, i)) gns ga = globalAnnos dg ns = mns $ specNames opts vs = mns $ viewNames opts filePrefix = snd $ getFilePrefix opts file outTypes = outtypes opts specOutTypes = filter ( \ ot -> case ot of ThyFile -> True DfgFile _ -> True TPTPFile _ -> True XmlOut -> True OmdocOut -> True TheoryFile _ -> True SigFile _ -> True OWLOut -> True CLIFOut -> True FreeCADOut -> True HaskellOut -> True ComptableXml -> True SymXml -> True _ -> False) outTypes allSpecs = null ns noViews = null vs ignore = null specOutTypes && modelSparQ opts == "" mapM_ (writeLibEnv opts filePrefix lenv ln) $ if null $ dumpOpts opts then outTypes else EnvOut : outTypes mapM_ ( \ i -> case Map.lookup i gctx of Just (SpecEntry (ExtGenSig _ (NodeSig n _))) -> writeTheoryFiles opts specOutTypes filePrefix lenv ga ln i n _ -> unless allSpecs $ putIfVerbose opts 0 $ "Unknown spec name: " ++ show i ) $ if ignore then [] else if allSpecs then gns else ns unless noViews $ mapM_ ( \ i -> case Map.lookup i gctx of Just (ViewOrStructEntry _ (ExtViewSig _ (GMorphism cid _ _ m _) _)) -> writeVerbFile opts (filePrefix ++ "_" ++ show i ++ ".view") $ shows (pretty $ Map.toList $ symmap_of (targetLogic cid) m) "\n" _ -> putIfVerbose opts 0 $ "Unknown view name: " ++ show i ) vs mapM_ ( \ n -> writeTheoryFiles opts specOutTypes filePrefix lenv ga ln (simpleIdToIRI $ genToken $ 'n' : show n) n) $ if ignore || not allSpecs then [] else nodesDG dg \\ Map.fold ( \ e l -> case e of SpecEntry (ExtGenSig _ (NodeSig n _)) -> n : l _ -> l) [] gctx doDump opts "GlobalAnnos" $ putStrLn $ showGlobalDoc ga ga "" doDump opts "PrintStat" $ putStrLn $ printStatistics dg doDump opts "DGraph" $ putStrLn $ showDoc dg "" doDump opts "DuplicateDefEdges" $ let es = duplicateDefEdges dg in unless (null es) $ print es doDump opts "LogicGraph" $ putStrLn $ showDoc logicGraph "" doDump opts "LibEnv" $ writeVerbFile opts (filePrefix ++ ".lenv") $ shows (DG.prettyLibEnv lenv) "\n"
nevrenato/Hets_Fork
Driver/WriteFn.hs
gpl-2.0
15,112
289
21
4,520
4,304
2,228
2,076
312
21
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, RecordWildCards #-} module Lamdu.GUI.ParamEdit ( Info(..), make , eventMapAddFirstParam , diveToNameEdit ) where import Control.Lens.Operators import Control.Lens.Tuple import Control.MonadA (MonadA) import qualified Data.Map as Map import Data.Store.Transaction (Transaction) import qualified Graphics.UI.Bottle.EventMap as E import Graphics.UI.Bottle.ModKey (ModKey) import qualified Graphics.UI.Bottle.Widget as Widget import Lamdu.Config (Config) import qualified Lamdu.Config as Config import Lamdu.GUI.ExpressionGui (ExpressionGui) import qualified Lamdu.GUI.ExpressionGui as ExpressionGui import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM) import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT import qualified Lamdu.GUI.WidgetIds as WidgetIds import qualified Lamdu.Sugar.Types as Sugar import Prelude.Compat type T = Transaction singletonIdMap :: Sugar.EntityId -> Sugar.EntityId -> Map.Map Widget.Id Widget.Id singletonIdMap key val = Map.singleton (WidgetIds.fromEntityId key) (WidgetIds.fromEntityId val) chooseAddResultEntityId :: Sugar.ParamAddResult -> Widget.EventResult chooseAddResultEntityId (Sugar.ParamAddResultVarToTags Sugar.VarToTags {..}) = eventResultFromEntityId (vttNewTag ^. Sugar.tagInstance) & Widget.applyIdMapping widgetIdMap where widgetIdMap = singletonIdMap vttReplacedVarEntityId (vttReplacedByTag ^. Sugar.tagInstance) chooseAddResultEntityId (Sugar.ParamAddResultNewVar entityId _) = eventResultFromEntityId entityId chooseAddResultEntityId (Sugar.ParamAddResultNewTag newParamTag) = eventResultFromEntityId $ newParamTag ^. Sugar.tagInstance eventResultFromEntityId :: Sugar.EntityId -> Widget.EventResult eventResultFromEntityId = Widget.eventResultFromCursor . cursorFromEntityId cursorFromEntityId :: Sugar.EntityId -> Widget.Id cursorFromEntityId = diveToNameEdit . WidgetIds.fromEntityId diveToNameEdit :: Widget.Id -> Widget.Id diveToNameEdit = ExpressionGui.diveToNameEdit eventMapAddFirstParam :: Functor m => Config -> Maybe (T m Sugar.ParamAddResult) -> Widget.EventHandlers (T m) eventMapAddFirstParam _ Nothing = mempty eventMapAddFirstParam config (Just addFirstParam) = addFirstParam <&> chooseAddResultEntityId & E.keyPresses (Config.addNextParamKeys config) (E.Doc ["Edit", "Add parameter"]) eventMapAddNextParam :: Functor m => Config -> Maybe (T m Sugar.ParamAddResult) -> Widget.EventHandlers (T m) eventMapAddNextParam _ Nothing = mempty eventMapAddNextParam config (Just fpAdd) = fpAdd <&> chooseAddResultEntityId & E.keyPresses (Config.addNextParamKeys config) (E.Doc ["Edit", "Add next parameter"]) eventParamDelEventMap :: MonadA m => Maybe (T m Sugar.ParamDelResult) -> [ModKey] -> String -> Widget.Id -> Widget.EventHandlers (T m) eventParamDelEventMap Nothing _ _ _ = mempty eventParamDelEventMap (Just fpDel) keys docSuffix dstPosId = do res <- fpDel let widgetIdMap = case res of Sugar.ParamDelResultTagsToVar Sugar.TagsToVar {..} -> singletonIdMap (ttvReplacedTag ^. Sugar.tagInstance) ttvReplacedByVarEntityId _ -> Map.empty Widget.eventResultFromCursor dstPosId & Widget.applyIdMapping widgetIdMap & return & E.keyPresses keys (E.Doc ["Edit", "Delete parameter" ++ docSuffix]) data Info m = Info { iMakeNameEdit :: Widget.Id -> ExprGuiM m (ExpressionGui m) , iMDel :: Maybe (T m Sugar.ParamDelResult) , iMAddNext :: Maybe (T m Sugar.ParamAddResult) } -- exported for use in definition sugaring. make :: MonadA m => ExpressionGui.AnnotationOptions -> ExprGuiT.ShowAnnotation -> Widget.Id -> Widget.Id -> Sugar.FuncParam (Info m) -> ExprGuiM m (ExpressionGui m) make annotationOpts showType prevId nextId param = assignCursor $ do config <- ExprGuiM.readConfig let paramEventMap = mconcat [ eventParamDelEventMap mFpDel (Config.delForwardKeys config) "" nextId , eventParamDelEventMap mFpDel (Config.delBackwardKeys config) " backwards" prevId , eventMapAddNextParam config mFpAdd ] makeNameEdit myId <&> ExpressionGui.egWidget %~ Widget.weakerEvents paramEventMap <&> ExpressionGui.egAlignment . _1 .~ 0.5 >>= ExpressionGui.maybeAddAnnotationWith annotationOpts showType (param ^. Sugar.fpAnnotation) (param ^. Sugar.fpId) where entityId = param ^. Sugar.fpId myId = WidgetIds.fromEntityId entityId Info makeNameEdit mFpDel mFpAdd = param ^. Sugar.fpInfo hiddenIds = map WidgetIds.fromEntityId $ param ^. Sugar.fpHiddenIds assignCursor x = foldr (`ExprGuiM.assignCursorPrefix` const myId) x hiddenIds
rvion/lamdu
Lamdu/GUI/ParamEdit.hs
gpl-3.0
5,151
0
17
1,140
1,248
664
584
-1
-1
-- Haskell Practical 3 Code - N1 Parser -- By James Cowgill import Prac2.Alex import Prac3.LLParser {- Original Grammar e = e + e | e - e | e * e | N | V | (e) b = not b (logical) | b and b (logical) | b or b (logical) | e = e | e < e | e > e | (b) s = skip | print e | s; s | v := e | if b then s else s | while b s | (s) Precedence + Associativity not right * left + - left < > left = left and right or right ; left Disambiguated e = e + e1 | e - e1 | e1 e1 = e1 * e2 | e2 e2 = N | V | (e) b = b1 or b | b1 b1 = b2 and b1 | b2 b2 = not b2 | e = e | e < e | e > e | true | false | (b) Remove left recursion e = e1 e' e' = + e | - e | λ e1 = e2 e1' e1' = * e1 | λ e2 = N | V | (e) b = b1 b' b' = or b | λ b1 = b2 b1' b1' = and b1 | λ b2 = e b2Op e | not b2 | true | false | (b) b2Op= = | < | > s = s1 s' s' = ; s | λ s1 = skip | print e | v := e | if b then s1 else s1 | while b s1 | (s) -} data NonTerminal = E | E' | E1 | E1' | E2 | B | B' | B1 | B1' | B2 | B2Op | S | S' | S1 deriving (Show) -- Main parse table parseTable :: NonTerminal -> Maybe Token -> [Symbol NonTerminal Token] parseTable E _ = [SymNont E1, SymNont E'] parseTable E' (Just TokPlus) = [SymTerm TokPlus, SymNont E] parseTable E' (Just TokMinus) = [SymTerm TokMinus, SymNont E] parseTable E' _ = [] parseTable E1 _ = [SymNont E2, SymNont E1'] parseTable E1' (Just TokTimes) = [SymTerm TokTimes, SymNont E1] parseTable E1' _ = [] parseTable E2 (Just (TokNum n)) = [SymTerm (TokNum n)] parseTable E2 (Just (TokVar v)) = [SymTerm (TokVar v)] parseTable E2 (Just TokLeft) = [SymTerm TokLeft, SymNont E, SymTerm TokRight] parseTable E2 _ = [SymError] parseTable B _ = [SymNont B1, SymNont B'] parseTable B' (Just TokOr) = [SymTerm TokOr, SymNont B] parseTable B' _ = [] parseTable B1 _ = [SymNont B2, SymNont B1'] parseTable B1' (Just TokAnd) = [SymTerm TokAnd, SymNont B1] parseTable B1' _ = [] parseTable B2 (Just TokLeft) = [SymTerm TokLeft, SymNont B, SymTerm TokRight] parseTable B2 (Just TokNot) = [SymTerm TokNot, SymNont B2] parseTable B2 (Just (TokBool b)) = [SymTerm (TokBool b)] parseTable B2 _ = [SymNont E, SymNont B2Op, SymNont E] parseTable B2Op (Just TokEquals) = [SymTerm TokEquals] parseTable B2Op (Just TokLess) = [SymTerm TokLess] parseTable B2Op (Just TokGreater) = [SymTerm TokGreater] parseTable B2Op _ = [SymError] parseTable S _ = [SymNont S1, SymNont S'] parseTable S' (Just TokSeq) = [SymTerm TokSeq, SymNont S] parseTable S' _ = [] parseTable S1 (Just TokSkip) = [SymTerm TokSkip] parseTable S1 (Just TokPrint) = [SymTerm TokPrint, SymNont E] parseTable S1 (Just (TokVar v)) = [SymTerm (TokVar v), SymTerm TokAssign, SymNont E] parseTable S1 (Just TokIf) = [SymTerm TokIf, SymNont B, SymTerm TokThen, SymNont S1, SymTerm TokElse, SymNont S1] parseTable S1 (Just TokWhile) = [SymTerm TokWhile, SymNont B, SymNont S1] parseTable S1 (Just TokLeft) = [SymTerm TokLeft, SymNont S, SymTerm TokRight] parseTable S1 _ = [SymError] -- Returns true if an N1 program is syntactically correct isN1String :: String -> Bool isN1String str = llparse parseTable S (alexScanTokens str)
jcowgill/cs-work
syac/compilers/Prac3/5NParser.hs
gpl-3.0
4,104
0
9
1,678
1,008
516
492
43
1
import Data.List keepsInside :: [[Int]] -> (Int -> Int) -> [[Int]] keepsInside matrix f = filter isMember (transpose matrix) where isMember x = helper x x where helper (x:xs) y = if (elem (f x) y) then helper xs y else False helper [] y = True main :: IO() main = do print (keepsInside [[1,0,5],[-1,0,2]] (\x -> x^2))
deni-sl/Functional-programming
Homework 3/hw3.81275.task1.hs
gpl-3.0
354
8
13
95
209
111
98
12
3
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE GHCForeignImportPrim #-} -- foreign import prim {-# LANGUAGE MagicHash #-} -- postfix # on identifiers {-# LANGUAGE UnboxedTuples #-} -- (# #) {-# LANGUAGE UnliftedFFITypes #-} -- argument type of foreign import {-# LANGUAGE BangPatterns #-} -- | module Data.Approximate.MPFR.Types ( constf, unary, unary2, unary_,binary,binary_,ternary, cmpf,rounding, test, rtest, Rounded (..), RoundMode (..), Precision, Const, Unary, Unary2, Binary,Ternary, Comparison, Rounding, Test, RTest, CExp#, CPrec#, CSignPrec#, mode#, prec#, RoundedOut#, RoundedOut_#, CRounding#, Exp, CPrecision#, getPrec ) where import Prelude hiding (isNaN, isInfinite, div, sqrt, exp, log, sin, cos, tan, asin, acos, atan) import Data.Bits import GHC.Int -- Int32# import GHC.Prim -- Int#, ByteArray#, import GHC.Types -- Word {- Basic data -} type CPrec# = Int# type CSignPrec# = Int# type CPrecision# = Int# type CExp# = Int# type CRounding# = Int# data Rounded = Rounded { roundedSignPrec :: CSignPrec# -- Sign# << 64/32 | Precision# , roundedExp :: CExp# , roundedLimbs :: ByteArray# } {- TODO is squeezing sign and prec together really faster? -} {- 4.2 Nomenclature and Types - precision -} {- gmp.h: #if defined (_CRAY) && ! defined (_CRAYMPP) /* plain `int' is much faster (48 bits) */ #define __GMP_MP_SIZE_T_INT 1 typedef int mp_size_t; typedef int mp_exp_t; #else #define __GMP_MP_SIZE_T_INT 0 <--- typedef long int mp_size_t typedef long int mp_exp_t; #endif mpfr.h: # if __GMP_MP_SIZE_T_INT == 1 # define _MPFR_PREC_FORMAT 2 # else # define _MPFR_PREC_FORMAT 3 <--- # endif #elif _MPFR_PREC_FORMAT == 3 typedef long mpfr_prec_t; -} type Precision = Int prec# :: Precision -> Int# prec# (I# i#) = i# prec_bit :: Int prec_bit | b63 == 0 = b31 | otherwise = b63 where b63 = bit 63 b31 = bit 31 {-| Return the precision of @x@, i.e., the number of bits used to store its significand. -} getPrec :: Rounded -> Precision getPrec (Rounded s _ _) = (I# s) .&. complement prec_bit {- 4.4 Rounding Modes -} {- Haskel model of MPFR precision Definition of rounding modes (DON'T USE MPFR_RNDNA!). typedef enum { MPFR_RNDN=0, /* round to nearest, with ties to even */ MPFR_RNDZ, /* round toward zero */ MPFR_RNDU, /* round toward +Inf */ MPFR_RNDD, /* round toward -Inf */ MPFR_RNDA, /* round away from zero */ MPFR_RNDF, /* faithful rounding (not implemented yet) */ MPFR_RNDNA=-1 /* round to nearest, with ties away from zero (mpfr_round) */ } mpfr_rnd_t; -} data RoundMode = Near | Zero | Up | Down | AwayFromZero instance Enum RoundMode where toEnum 0 = Near toEnum 1 = Zero toEnum 2 = Up toEnum 3 = Down toEnum 4 = AwayFromZero toEnum 5 = error "RoundMode: Not implemented" toEnum (-1) = error "RoundMode: Don't use!" toEnum _ = error "RoundMode: Unknown" fromEnum Near = 0 fromEnum Zero = 1 fromEnum Up = 2 fromEnum Down = 3 fromEnum AwayFromZero = 4 mode# :: RoundMode -> Int# mode# r = case fromEnum r of I# i# -> i# {- General types, method signatures -} type Exp = GHC.Int.Int64 type RoundedOut# = (# CSignPrec#, CExp#, ByteArray# #) type RoundedOut_# = (# CSignPrec#, CExp#, ByteArray#, Int# #) type RoundedOut2# = (# CSignPrec#, CExp#, ByteArray#, CSignPrec#, CExp#, ByteArray# #) type Const = CRounding# -> CPrec# -> RoundedOut# type Unary = CRounding# -> CPrec# -> CSignPrec# -> CExp# -> ByteArray# -> RoundedOut# type Unary2 = CRounding# -> CPrec# -> CSignPrec# -> CExp# -> ByteArray# -> RoundedOut2# type Unary_ = CRounding# -> CPrec# -> CSignPrec# -> CExp# -> ByteArray# -> RoundedOut_# type Binary = CRounding# -> CPrec# -> CSignPrec# -> CExp# -> ByteArray# -> CSignPrec# -> CExp# -> ByteArray# -> RoundedOut# type Ternary = CRounding# -> CPrec# -> CSignPrec# -> CExp# -> ByteArray# -> CSignPrec# -> CExp# -> ByteArray# -> CSignPrec# -> CExp# -> ByteArray# -> RoundedOut# type Binary_ = CRounding# -> CPrec# -> CSignPrec# -> CExp# -> ByteArray# -> CSignPrec# -> CExp# -> ByteArray# -> RoundedOut_# type Comparison = CSignPrec# -> CExp# -> ByteArray# -> CSignPrec# -> CExp# -> ByteArray# -> Int# type Rounding = CPrec# -> CSignPrec# -> CExp# -> ByteArray# -> RoundedOut# type RTest = CRounding# -> CSignPrec# -> CExp# -> ByteArray# -> Int# type Test = CSignPrec# -> CExp# -> ByteArray# -> Int# constf :: Const -> RoundMode -> Precision -> Rounded constf f r p = Rounded s' e' l' where (# s', e', l' #) = f (mode# r) (prec# p) {-# INLINE constf #-} unary :: Unary -> RoundMode -> Precision -> Rounded -> Rounded unary f r p (Rounded s e l) = Rounded s' e' l' where (# s', e', l' #) = f (mode# r) (prec# p) s e l {-# INLINE unary #-} unary2 :: Unary2 -> RoundMode -> Precision -> Rounded -> (Rounded, Rounded) unary2 f r p (Rounded s e l) = (Rounded s1' e1' l1', Rounded s2' e2' l2') where (# s1', e1', l1', s2', e2', l2' #) = f (mode# r) (prec# p) s e l {-# INLINE unary2 #-} unary_ :: Unary_ -> RoundMode -> Precision -> Rounded -> ( Rounded, Int ) unary_ f r p (Rounded s e l) = ( Rounded s' e' l', I# t) where (# s', e', l', t #) = f (mode# r) (prec# p) s e l {-# INLINE unary_ #-} binary :: Binary -> RoundMode -> Precision -> Rounded -> Rounded -> Rounded binary f r p (Rounded s e l) (Rounded s' e' l') = Rounded s'' e'' l'' where (# s'', e'', l'' #) = f (mode# r) (prec# p) s e l s' e' l' {-# INLINE binary #-} binary_ :: Binary_ -> RoundMode -> Precision -> Rounded -> Rounded -> (Rounded, Int) binary_ f r p (Rounded s e l) (Rounded s' e' l') = (Rounded s'' e'' l'', I# t) where (# s'', e'', l'', t #) = f (mode# r) (prec# p) s e l s' e' l' {-# INLINE binary_ #-} ternary :: Ternary -> RoundMode -> Precision -> Rounded -> Rounded -> Rounded -> Rounded ternary f r p (Rounded s e l) (Rounded s' e' l') (Rounded s'' e'' l'') = Rounded s''' e''' l''' where (# s''', e''', l''' #) = f (mode# r) (prec# p) s e l s' e' l' s'' e'' l'' {-# INLINE ternary #-} cmpf :: Comparison -> Rounded -> Rounded -> Bool cmpf f (Rounded s e l) (Rounded s' e' l') = I# (f s e l s' e' l') /= 0 {-# INLINE cmpf #-} rounding :: Rounding -> Precision -> Rounded -> Rounded rounding f p (Rounded s e l) = Rounded s' e' l' where (# s', e', l' #) = f (prec# p) s e l {-# INLINE rounding #-} rtest :: RTest -> RoundMode -> Rounded -> Bool rtest f r (Rounded s e l) = I# (f (mode# r) s e l) /= 0 {-# INLINE rtest #-} test :: Test -> Rounded -> Bool test f (Rounded s e l) = I# (f s e l) /= 0 {-# INLINE test #-}
comius/haskell-mpfr
src/Data/Approximate/MPFR/Types.hs
lgpl-3.0
6,714
12
16
1,548
1,983
1,074
909
-1
-1
module GCrypt.MPI.Comp ( cmp, cmpUi, ) where import GCrypt.Base import GCrypt.Util cmp :: MPI -> MPI -> IO Ordering cmp u v = gcry_mpi_cmp u v >>= return . int2ord cmpUi :: MPI -> ULong -> IO Ordering cmpUi u v = gcry_mpi_cmp_ui u v >>= return . int2ord int2ord :: Integral a => a -> Ordering int2ord a | a < 0 = LT | a == 0 = EQ | otherwise = GT
sw17ch/hsgcrypt
src/GCrypt/MPI/Comp.hs
lgpl-3.0
379
0
8
107
160
81
79
13
1
module Main where import Test.QuickCheck import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) main = defaultMain tests tests = [ testGroup "boring" boringTests ] -- boring tests! boring :: Int -> Bool boring x = const "hello" x == "hello" boringTests = [ testProperty "boring" boring ]
k0001/hacker-rank
tests/Main.hs
unlicense
384
0
6
91
95
54
41
10
1
import System.IO main = do contents <- readFile "./Learn_You_a_Haskell_programs/girlfriend.txt" putStr contents {- equivalent to all: main = do withFile "./Learn_You_a_Haskell_programs/girlfriend.txt" ReadMode (\handle -> do contents <- hGetContents handle putStr contents) main = do handle <- openFile "./Learn_You_a_Haskell_programs/girlfriend.txt" ReadMode contents <- hGetContents handle putStr contents hClose handle -}
haroldcarr/learn-haskell-coq-ml-etc
haskell/book/2011-Learn_You_a_Haskell/girlfriend.hs
unlicense
488
0
8
110
28
13
15
4
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE NoImplicitPrelude, OverloadedStrings, UnicodeSyntax, TypeOperators, TypeFamilies, FlexibleInstances, FlexibleContexts, MultiParamTypeClasses, ScopedTypeVariables, DataKinds, QuasiQuotes, TemplateHaskell, DeriveGeneric, LambdaCase #-} -- | The IndieAuth/rel-me-auth implementation, using JSON Web Tokens. module Sweetroll.Auth ( JWT , VerifiedJWT , AuthProtect , module Sweetroll.Auth ) where import Sweetroll.Prelude as SP hiding (iat, au, host) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Data.Maybe (fromJust) import Data.Text (dropWhileEnd) import qualified Data.Map as M import qualified Data.ByteString.Char8 as S8 import Web.JWT hiding (Header) import qualified Network.Wai as Wai import Servant.Server.Experimental.Auth import Servant.Server import Web.Cookie (parseCookies) import Web.FormUrlEncoded as FU import Sweetroll.Context import Sweetroll.Conf type instance AuthServerData (AuthProtect "jwt") = JWT VerifiedJWT instance HasLink sub ⇒ HasLink (AuthProtect "jwt" :> sub) where type MkLink (AuthProtect "jwt" :> sub) a = MkLink sub a toLink toA _ = toLink toA (Proxy ∷ Proxy sub) data AccessToken = AccessToken { accessToken ∷ Text , scope ∷ Text , clientId ∷ Text , me ∷ Text } deriving (Generic) instance ToJSON AccessToken where toEncoding = genericToEncoding defaultOptions { SP.fieldLabelModifier = camelTo2 '_' } instance ToForm AccessToken where toForm = genericToForm FormOptions { FU.fieldLabelModifier = camelTo2 '_' } authHandler ∷ Text → AuthHandler Wai.Request (JWT VerifiedJWT) authHandler secKey = mkAuthHandler h where h req = Servant.Server.Handler $ case asum [ fromHeader =<< lookup hAuthorization (Wai.requestHeaders req) , join $ lookup "access_token" $ Wai.queryString req , lookup "Bearer" =<< parseCookies <$> lookup hCookie (Wai.requestHeaders req) ] of Nothing → throwM errNoAuth Just tok → case decodeAndVerifySignature (hmacSecret secKey) (cs tok) of Nothing → throwM errWrongAuth Just decodedToken → do -- !!! Only allow tokens issued by the current Host !!! if (fromMaybe "" $ lookup "Host" $ Wai.requestHeaders req) == (cs $ show $ fromJust $ iss $ claims decodedToken) then return decodedToken else throwM errWrongAuth fromHeader ∷ ByteString → Maybe ByteString fromHeader "" = Nothing fromHeader au = return $ drop 7 au -- 7 chars in "Bearer " getAuth ∷ JWT VerifiedJWT → Sweetroll [(Text, Text)] getAuth token = return $ ("me", maybe "" tshow $ sub $ claims token) : unregClaims token getSub ∷ JWT VerifiedJWT → Text getSub = maybe "" tshow . sub . claims mkAcl ∷ JWT VerifiedJWT → [Text] mkAcl token = "*" : withTrailingSlash (getSub token) unregClaims ∷ JWT VerifiedJWT → [(Text, Text)] unregClaims = mapMaybe unValue . M.toList . unClaimsMap . unregisteredClaims . claims where unValue (k, String s) = Just (k, s) unValue _ = Nothing signAccessToken ∷ Text → Text → Text → UTCTime → Text → Text → Text signAccessToken sec domain me now scope clientId = encodeSigned (hmacSecret sec) t where t = mempty { iss = stringOrURI domain , sub = stringOrURI $ dropWhileEnd (== '/') me , iat = numericDate $ utcTimeToPOSIXSeconds now , unregisteredClaims = ClaimsMap $ M.fromList [ ("scope", String scope) , ("client_id", String clientId) ] } makeAccessToken ∷ Text → Text → Text → Text → Sweetroll AccessToken makeAccessToken domain me scope clientId = do secs ← getSecs now ← liftIO getCurrentTime return $ AccessToken { accessToken = signAccessToken (secretKey secs) domain me now scope clientId , scope = scope , clientId = clientId , me = me } -- | Token endpoint postLogin ∷ Maybe Text → [(Text, Text)] → Sweetroll AccessToken postLogin host params = do let domain = fromMaybe "localhost" host isTestMode ← getConfOpt testMode --let isTestMode = False if isTestMode then makeAccessToken domain (fromMaybe "unknown" $ lookup "me" params) (fromMaybe "post create update delete read follow mute block channels" $ lookup "scope" params) "example.com" else do checkURI ← getConfOpt indieauthCheckEndpoint resp0 ← runHTTP $ reqS checkURI >>= postForm params >>= performWithBytes case (note "Could not read form" . readForm) =<< responseBody <$> resp0 of Right (indieAuthRespParams ∷ [(Text, Text)]) → do let me = orEmptyMaybe $ lookup "me" indieAuthRespParams guardBool errWrongAuth $ Just domain == fmap (cs . uriRegName) (uriAuthority $ fromMaybe nullURI $ parseURI $ cs me) logWarn $ "Authenticated a client: " ++ display (fromMaybe "unknown" $ lookup "client_id" params) makeAccessToken domain me (fromMaybe "post" $ lookup "scope" indieAuthRespParams) (fromMaybe "" $ lookup "client_id" params) Left e → do logInfo $ "Authentication error: " ++ display e ++ " / params: " ++ display (tshow params) throwM errWrongAuth -- | Internal "client" (redirect_uri target) getSelfLogin ∷ Maybe Text → Maybe Text → Maybe Text → Maybe Text → Sweetroll NoContent getSelfLogin host me code scope = do let domain = fromMaybe "localhost" host isTestMode ← getConfOpt testMode --let isTestMode = False isHttpOnly ← not <$> getConfOpt allowJsCookieAccess let security = if isTestMode then "" else "; Secure; SameSite=Strict" ++ if isHttpOnly then "; HttpOnly" else "" result ← postLogin host [ ("me", fromMaybe ("https://" ++ domain) me) , ("code", fromMaybe "" code) , ("scope", fromMaybe "post create update delete read follow mute block channels" scope) , ("redirect_uri", "https://" ++ domain ++ "/login/self") , ("client_id", "https://" ++ domain ++ "/") , ("grant_type", "authorization_code") ] throwM err303 { errHeaders = [ ("Set-Cookie", "Bearer=" ++ (cs $ accessToken result) ++ "; Path=/; Max-Age=5184000" ++ security) , (hLocation, "/") ] } getTestLogin ∷ Maybe Text → Maybe Text → Maybe Text → Sweetroll NoContent getTestLogin host state redirect_uri = do isTestMode ← getConfOpt testMode guardBool errWrongAuth isTestMode let reduri = fromMaybe "" redirect_uri throwM err302 { errHeaders = [ (hLocation, cs $ reduri ++ (if "?" `isInfixOf` reduri then "&" else "?") ++ "state=" ++ fromMaybe "" state ++ "&code=test") ] } errNoAuth ∷ ServantErr errNoAuth = errText err401 "Authorization/access_token not found." errWrongAuth ∷ ServantErr errWrongAuth = errText err401 "Invalid auth token." errWrongAuthScope ∷ ServantErr errWrongAuthScope = errText err401 "Your access token is not authorized for this action." ensureScope ∷ MonadThrow μ ⇒ JWT VerifiedJWT → ([Text] → Bool) → μ () ensureScope token p = guardBool errWrongAuthScope $ p scopes where scopes = words $ fromMaybe "" $ lookup "scope" $ unregClaims token supportFormAuth ∷ Wai.Middleware supportFormAuth app req respond = do let headers = Wai.requestHeaders req if "urlencoded" `isInfixOf` (fromMaybe "" $ lookup hContentType headers) && not ("Bearer" `isInfixOf` (fromMaybe "" $ lookup hAuthorization headers)) && not ("Bearer" `isInfixOf` (fromMaybe "" $ lookup hCookie headers)) then do (req', body) ← getRequestBody req let form = fromMaybe [] $ readForm $ S8.concat body ∷ [(ByteString, ByteString)] let token = fromMaybe "" $ lookup "access_token" form app req' { Wai.requestHeaders = (hAuthorization, "Bearer " ++ token) : headers } respond else app req respond where getRequestBody rq = do -- https://hackage.haskell.org/package/wai-extra-3.0.16.1/docs/src/Network.Wai.Middleware.rquestLogger.html let loop front = do bs ← Wai.requestBody rq if S8.null bs then return $ front [] else loop $ front . (bs:) body ← loop id ichunks ← newIORef body let rbody = atomicModifyIORef ichunks $ \case [] → ([], S8.empty) x:y → (y, x) let rq' = rq { Wai.requestBody = rbody } return (rq', body)
myfreeweb/sweetroll
sweetroll-be/library/Sweetroll/Auth.hs
unlicense
8,920
0
22
2,336
2,442
1,251
1,191
155
4
----------------------------------------------------------------------------- -- -- Module : IniConfiguration -- Description : -- Copyright : (c) Tobias Reinhardt, 2015 <[email protected] -- License : Apache License, Version 2.0 -- -- Maintainer : Tobias Reinhardt <[email protected]> -- Portability : tested only on linux -- | -- ----------------------------------------------------------------------------- module IniConfiguration( module Encoder, module Decoder, module Types, module Manipulation )where import Encoder import Decoder import Types import Manipulation -- TODO Add convenient function for fetching the defaul section
tobiasreinhardt/show
IniConfiguration/src/IniConfiguration.hs
apache-2.0
672
0
4
99
47
37
10
9
0
module RemainderGame.A268060 (a268060) where import Helpers.RemainderGame (shrinkingDivisorIterations) import RemainderGame.A268058 (a268058) import Data.Maybe (fromJust) import Data.List (find) a268060 :: Int -> Integer a268060 n = toInteger $ fromJust $ find f [1..n] where f k = shrinkingDivisorIterations n k == a268058 n
peterokagey/haskellOEIS
src/RemainderGame/A268060.hs
apache-2.0
329
0
8
44
108
59
49
8
1
module Emulator.Types where import Data.Array.IO import Data.Array.Unboxed import qualified Data.Word type Byte = Data.Word.Word8 type HalfWord = Data.Word.Word16 type MWord = Data.Word.Word32 type Address = Data.Word.Word32 type DWord = Data.Word.Word64 type RegisterVal = Address type Memory = UArray Address Byte type MemoryIO = IOUArray Address Byte newtype RegisterName = RegisterName Int deriving (Show, Read, Eq, Ord) data Rotated a = Rotated Int a deriving (Show, Read, Eq, Ord, Functor)
intolerable/GroupProject
src/Emulator/Types.hs
bsd-2-clause
511
0
6
84
159
96
63
16
0
module Database.VCache.Read ( readAddrIO , readRefctIO , withBytesIO ) where import Control.Monad import qualified Data.Map.Strict as Map import Control.Concurrent.MVar import Data.Word import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Alloc import Database.LMDB.Raw import Database.VCache.Types import Database.VCache.VGetInit import Database.VCache.VGetAux import Database.VCache.Refct -- | Parse contents at a given address. Returns both the value and the -- cache weight, or fails. This first tries reading the database, then -- falls back to reading from recent allocation frames. If the address -- does not have defined data at either location, this will fail. readAddrIO :: VSpace -> Address -> VGet a -> IO (a, Int) readAddrIO vc addr = withAddrValIO vc addr . readVal vc {-# INLINE readAddrIO #-} withAddrValIO :: VSpace -> Address -> (MDB_val -> IO a) -> IO a withAddrValIO vc addr action = alloca $ \ pAddr -> poke pAddr addr >> let vAddr = MDB_val { mv_data = castPtr pAddr , mv_size = fromIntegral (sizeOf addr) } in withRdOnlyTxn vc $ \ txn -> mdb_get' txn (vcache_db_memory vc) vAddr >>= \case Just vData -> action vData -- found data in database (ideal) Nothing -> -- since not in the database, try the allocator let ff = Map.lookup addr . alloc_list in readMVar (vcache_memory vc) >>= \ memory -> let ac = mem_alloc memory in case allocFrameSearch ff ac of Just _data -> withByteStringVal _data action -- found data in allocator Nothing -> fail $ "VCache: address " ++ show addr ++ " is undefined!" {-# NOINLINE withAddrValIO #-} readVal :: VSpace -> VGet a -> MDB_val -> IO (a, Int) readVal vc p v = _vget (vgetFull p) s0 >>= retv where size = fromIntegral (mv_size v) s0 = VGetS { vget_children = [] , vget_target = mv_data v , vget_limit = mv_data v `plusPtr` size , vget_space = vc } retv (VGetR result _) = return (result, size) retv (VGetE eMsg) = fail eMsg -- vget with initializer for dependencies. -- asserts that we parse all available input. vgetFull :: VGet a -> VGet a vgetFull parse = do vgetInit r <- parse assertDone return r assertDone :: VGet () assertDone = isEmpty >>= \ b -> unless b (fail emsg) where emsg = "VCache: failed to read full input" {-# INLINE assertDone #-} -- | Read a reference count for a given address. readRefctIO :: VSpace -> Address -> IO Int readRefctIO vc addr = alloca $ \ pAddr -> withRdOnlyTxn vc $ \ txn -> poke pAddr addr >> let vAddr = MDB_val { mv_data = castPtr pAddr , mv_size = fromIntegral (sizeOf addr) } in mdb_get' txn (vcache_db_refcts vc) vAddr >>= \ mbData -> maybe (return 0) readRefctBytes mbData -- | Zero-copy access to raw bytes for an address. withBytesIO :: VSpace -> Address -> (Ptr Word8 -> Int -> IO a) -> IO a withBytesIO vc addr action = withAddrValIO vc addr $ \ v -> action (mv_data v) (fromIntegral (mv_size v)) {-# INLINE withBytesIO #-}
dmbarbour/haskell-vcache
hsrc_lib/Database/VCache/Read.hs
bsd-2-clause
3,203
0
27
846
854
445
409
-1
-1
import qualified Platform.Test as Test main = Test.main
mit-plv/riscv-semantics
src/Platform/MainTest.hs
bsd-3-clause
58
0
5
10
16
10
6
2
1
{-# OPTIONS -Wall #-} module Language.Pck.Tool ( -- * Assembler parseInst , parseInstFile -- * Debugger , runDbg , runDbgIO , DbgTrc(..) , DbgBrk(..) , DbgOrd(..) , TrcLog -- * Interactive Debugger , runIdbIO -- * Profiler , runProf , runProfIO , prof , ProfMode(..) ) where import Language.Pck.Tool.Assembler (parseInst, parseInstFile) import Language.Pck.Tool.Debugger (runDbg, runDbgIO ,DbgTrc(..), DbgBrk(..), DbgOrd(..), TrcLog) import Language.Pck.Tool.InteractiveDebugger (runIdbIO) import Language.Pck.Tool.Profiler (runProfIO, runProf, prof, ProfMode(..))
takenobu-hs/processor-creative-kit
Language/Pck/Tool.hs
bsd-3-clause
746
0
6
249
160
111
49
20
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} module Servant.API.WithNamedContext where import GHC.TypeLits -- | 'WithNamedContext' names a specific tagged context to use for the -- combinators in the API. (See also in @servant-server@, -- @Servant.Server.Context@.) For example: -- -- > type UseNamedContextAPI = WithNamedContext "myContext" '[String] ( -- > ReqBody '[JSON] Int :> Get '[JSON] Int) -- -- Both the 'ReqBody' and 'Get' combinators will use the 'WithNamedContext' with -- type tag "myContext" as their context. -- -- 'Context's are only relevant for @servant-server@. -- -- For more information, see the tutorial. data WithNamedContext (name :: Symbol) (subContext :: [*]) subApi
zerobuzz/servant
servant/src/Servant/API/WithNamedContext.hs
bsd-3-clause
715
0
6
109
48
38
10
-1
-1
{-# LANGUAGE PackageImports #-} module Control.Monad.ST.Lazy (module M) where import "base" Control.Monad.ST.Lazy as M
silkapp/base-noprelude
src/Control/Monad/ST/Lazy.hs
bsd-3-clause
124
0
4
18
25
19
6
3
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE BangPatterns #-} module VCS.Multirec where import Data.Kind import Data.Type.Equality hiding (apply) import Control.Applicative import qualified Data.Map as M import Control.Monad.Reader import Unsafe.Coerce import GHC.Generics import Data.Constraint (Constraint, (:-), (\\), Dict(..)) import Data.Constraint.Forall (Forall, ForallF, ForallT, inst, instF, instT) import Debug.Trace import Language.Common import Language.Clojure.Lang -- The actual puzzle data Spine (at :: U -> *)(al :: [U] -> [U] -> *) :: U -> * where Scp :: Spine at al u Scns :: ConstrFor u s -> (All at (TypeOf s)) -> Spine at al u Schg :: ConstrFor u s -> ConstrFor u r -> (al (TypeOf s) (TypeOf r)) -> Spine at al u data Al (at :: U -> *) :: [U] -> [U] -> * where A0 :: Al at '[] '[] Ains :: Usingl u -> (Al at xs ys) -> Al at xs (u ': ys) Adel :: Usingl u -> (Al at xs ys) -> Al at (u ': xs) ys Amod :: at u -> (Al at xs ys) -> Al at (u ': xs) (u ': ys) data At (recP :: U -> *) :: U -> * where Ai :: (IsRecEl u) => (recP u) -> At recP u As :: TrivialA u -> At recP u data Almu :: U -> U -> * where Alspn :: (Spine (At AlmuH) (Al (At AlmuH)) u) -> Almu u u Alins :: ConstrFor v s -> (Ctx (AtmuPos u) (TypeOf s)) -> Almu u v Aldel :: ConstrFor u s -> (Ctx (AtmuNeg v) (TypeOf s)) -> Almu u v data PartialAlmu :: U -> U -> * where TSpn :: Spine (At (AlmuP)) (Al (At (AlmuP))) u -> PartialAlmu u u TIns :: ConstrFor v s -> Ctx (PartialPos u) (TypeOf s) -> PartialAlmu u v TDel :: ConstrFor u s -> Ctx (PartialNeg v) (TypeOf s) -> PartialAlmu u v data AlmuP :: U -> * where AlmuBase :: TrivialA u -> AlmuP u AlmuF :: f (PartialAlmu u u) -> AlmuP u data AlmuH :: U -> * where AlmuH :: (Almu u u) -> AlmuH u deriving (Show, Generic) unH :: AlmuH u -> Almu u u unH (AlmuH u) = u data PartialPos (v :: U) :: U -> * where TPos :: (Usingl v, Usingl u) -> PartialPos v u data PartialNeg (v :: U) :: U -> * where TNeg :: (Usingl u, Usingl v) -> PartialNeg v u -- Atmu positive and negative variations data AtmuPos (v :: U) :: U -> * where FixPos :: (Almu v u) -> AtmuPos v u deriving (Show, Generic) unPos :: AtmuPos v u -> Almu v u unPos (FixPos p) = p data AtmuNeg (v :: U) :: U -> * where FixNeg :: (Almu u v) -> AtmuNeg v u deriving (Show, Generic) unNeg :: AtmuNeg u v -> Almu v u unNeg (FixNeg n) = n data Ctx (r :: U -> *) :: [U] -> * where Here :: (IsRecEl u) => r u -> (All Usingl l) -> Ctx r (u ': l) There :: Usingl u -> (Ctx r l) -> Ctx r (u ': l) -- Library stuff newtype Contract (f :: k -> *) (x :: k) = Contract { unContract :: (f x , f x) } type TrivialA = Contract Usingl data TrivialP :: [U] -> [U] -> * where Pair :: All Usingl l -> All Usingl r -> TrivialP l r deriving (Generic) -- -- mkEnv :: [Path] -> History -- mkEnv p = History { path = p, deOpt = False } mapAll :: (forall a . p a -> q a) -> All p l -> All q l mapAll f An = An mapAll f (a `Ac` as) = f a `Ac` mapAll f as foldAll :: (forall a . p a -> b -> b) -> b -> All p a -> b foldAll f b An = b foldAll f b (a `Ac` as) = f a (foldAll f b as) foldCtx :: (forall u . r u -> b -> b) -> (forall u . Usingl u -> b -> b) -> b -> Ctx r l -> b foldCtx f g b (Here r p) = f r (foldAll g b p) foldCtx f g b (There u c) = foldCtx f g b c mapAllM :: Monad m => (forall a . p a -> m (q a)) -> All p xs -> m (All q xs) mapAllM f An = return An mapAllM f (px `Ac` pxs) = Ac <$> f px <*> mapAllM f pxs zipP :: All p a -> All p a -> All (Contract p) a zipP An An = An zipP (a `Ac` as) (b `Ac` bs) = Contract (a, b) .@. zipP as bs mapSpineM :: Monad m => (forall a . at1 a -> m (at2 a)) -> (forall s d . al1 s d -> m (al2 s d)) -> Spine at1 al1 u -> m (Spine at2 al2 u) mapSpineM f g Scp = return Scp mapSpineM f g (Scns c ps) = Scns c <$> mapAllM f ps mapSpineM f g (Schg c1 c2 al) = Schg c1 c2 <$> g al mapAlM :: Monad m => (forall a . at1 a -> m (at2 a)) -> Al at1 s d -> m (Al at2 s d) mapAlM f A0 = return A0 mapAlM f (Adel at al) = Adel at <$> mapAlM f al mapAlM f (Ains at al) = Ains at <$> mapAlM f al mapAlM f (Amod at al) = Amod <$> f at <*> mapAlM f al mapAt :: (forall a . rec1 a -> rec2 a) -> At rec1 a -> At rec2 a mapAt f (Ai r) = Ai (f r) mapAt f (As t) = As t unsafeCoerceEquality :: Usingl a -> Usingl b -> Maybe (a :~: b) unsafeCoerceEquality a b = unsafeCoerce $ Just Refl sameDepth :: (IsRecEl u, IsRecEl v) => Usingl u -> Usingl v -> Bool sameDepth u v = hasRecursiveArgument u == hasRecursiveArgument v hasRecursiveArgument :: (IsRecEl u) => Usingl u -> Bool hasRecursiveArgument u = case view u of (Tag c p) -> foldAll (onRecursiveGuy_ (const True) id) False p -- useful wrappers for instances data Predicate (a :: * -> Constraint) = Predicate data Proxy (a :: *) = Proxy proxy :: a -> Proxy a proxy _ = Proxy inst_ :: Predicate p -> Proxy a -> Forall p :- p a inst_ _ _ = inst instF_ :: Predicate p -> Proxy (u a) -> ForallF p u :- p (u a) instF_ _ _ = instF -- Show instances deriving instance Show (Almu u v) deriving instance Show (Al (At AlmuH) p1 p2) deriving instance Show (At AlmuH u) deriving instance Show (Spine (At AlmuH) (Al (At AlmuH)) u) deriving instance Show (All Usingl l) deriving instance Show (All (At AlmuH) l) deriving instance Show (Ctx (AtmuPos u) p) deriving instance Show (Ctx (Almu u) p) deriving instance Show (Ctx (AtmuNeg u) p) deriving instance Show (f x) => Show (Contract f x) -- Eq instances instance Eq (Almu u v) where (Alspn s1) == (Alspn s2) = s1 == s2 (Alins c1 ctx1) == (Alins c2 ctx2) = case testEquality c1 c2 of Nothing -> False Just Refl -> ctx1 == ctx2 (Aldel c1 ctx1) == (Aldel c2 ctx2) = case testEquality c1 c2 of Nothing -> False Just Refl -> ctx1 == ctx2 _ == _ = False instance (ForallF Eq p) => Eq (Spine p (Al p) u) where Scp == Scp = True (Scns c1 p1) == (Scns c2 p2) = case testEquality c1 c2 of Nothing -> False Just Refl -> p1 == p2 (Schg i1 j1 p1) == (Schg i2 j2 p2) = case testEquality i1 i2 of Nothing -> False Just Refl -> case testEquality j1 j2 of Nothing -> False Just Refl -> p1 == p2 _ == _ = False equality :: Predicate Eq equality = Predicate -- withEqualityOf :: (Eq (u a) => c) -> (u a) -> c withEqualityOf e p = e \\ instF_ equality (proxy p) -- deriving instance Eq (Ctx (AtmuPos u) p) -- deriving instance Eq (Ctx (AtmuNeg u) p) instance (ForallF Eq almu) => Eq (Ctx almu p) where (Here al1 rest1) == (Here al2 rest2) = (al1 == al2 \\ instF_ equality (proxy al1)) && rest1 == rest2 (There u1 ctx1) == (There u2 ctx2) = (u1 == u2 && ctx1 == ctx2) instance (ForallF Eq u) => Eq (All u l) where (u1 `Ac` us1) == (u2 `Ac` us2) = (u1 == u2 \\ instF_ equality (proxy u1)) && us1 == us2 An == An = True deriving instance Eq (AtmuPos u v) deriving instance Eq (AtmuNeg u v) deriving instance Eq (AlmuH u) instance (ForallF Eq p) => Eq (Al p p1 p2) where A0 == A0 = True (Ains p1 rest1) == (Ains p2 rest2) = p1 == p2 && rest1 == rest2 (Amod m1 rest1) == (Amod m2 rest2) = (m1 == m2 \\ instF_ equality (proxy m1)) && rest1 == rest2 deriving instance Eq (At AlmuH u) deriving instance Eq (TrivialA u) showAll :: All (At AlmuH) l -> String showAll An = "" showAll (x `Ac` xs) = show x ++ show xs showSpine :: Spine (At AlmuH) (Al (At AlmuH)) u -> String showSpine (Scp) = "Scp. " showSpine (Scns i p) = "Scns " ++ show i ++ " (" ++ show p ++ ") " showSpine (Schg i j p) = "Schg From: " ++ show i ++ " to " ++ show j ++ showAl p showAlmu :: Almu u v -> String showAlmu (Alspn s) = "M-" ++ show s showAlmu (Alins c d) = "I-{" ++ show c ++ "}" ++ show d showAlmu (Aldel c d) = "D-{" ++ show c ++ "}" ++ show d showCtxP :: Ctx (AtmuPos u) p -> String showCtxP (Here r p) = show r showCtxP (There u c) = show c showCtxN :: Ctx (AtmuNeg u) p -> String showCtxN (Here r p) = show r showCtxN (There u c) = show c showAt :: At AlmuH u -> String showAt (Ai r) = show r showAt (As t) = show t showAl :: Al (At AlmuH) p1 p2 -> String showAl A0 = "" showAl (Ains i al) = "+{" ++ show i ++ "}" ++ showAl al showAl (Adel d al) = "-{" ++ show d ++ "}" ++ showAl al showAl (Amod m al) = "%{" ++ show m ++ "}" ++ showAl al showNonRecAl :: Al TrivialA s d -> String showNonRecAl A0 = "" showNonRecAl (Ains i al) = "+{" ++ show i ++ "}" ++ showNonRecAl al showNonRecAl (Adel d al) = "-{" ++ show d ++ "}" ++ showNonRecAl al showNonRecAl (Amod m al) = "%{" ++ show m ++ "}" ++ showNonRecAl al
nazrhom/vcs-clojure
src/VCS/Multirec.hs
bsd-3-clause
8,949
1
13
2,268
4,444
2,264
2,180
-1
-1
{-# language CPP #-} -- | = Name -- -- VK_EXT_sampler_filter_minmax - device extension -- -- == VK_EXT_sampler_filter_minmax -- -- [__Name String__] -- @VK_EXT_sampler_filter_minmax@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 131 -- -- [__Revision__] -- 2 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_get_physical_device_properties2@ -- -- [__Deprecation state__] -- -- - /Promoted/ to -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.2-promotions Vulkan 1.2> -- -- [__Contact__] -- -- - Jeff Bolz -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_sampler_filter_minmax] @jeffbolznv%0A<<Here describe the issue or question you have about the VK_EXT_sampler_filter_minmax extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2017-05-19 -- -- [__Interactions and External Dependencies__] -- -- - Promoted to Vulkan 1.2 Core -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Jeff Bolz, NVIDIA -- -- - Piers Daniell, NVIDIA -- -- == Description -- -- In unextended Vulkan, minification and magnification filters such as -- LINEAR allow sampled image lookups to return a filtered texel value -- produced by computing a weighted average of a collection of texels in -- the neighborhood of the texture coordinate provided. -- -- This extension provides a new sampler parameter which allows -- applications to produce a filtered texel value by computing a -- component-wise minimum (MIN) or maximum (MAX) of the texels that would -- normally be averaged. The reduction mode is orthogonal to the -- minification and magnification filter parameters. The filter parameters -- are used to identify the set of texels used to produce a final filtered -- value; the reduction mode identifies how these texels are combined. -- -- == Promotion to Vulkan 1.2 -- -- All functionality in this extension is included in core Vulkan 1.2, with -- the EXT suffix omitted. The original type, enum and command names are -- still available as aliases of the core functionality. -- -- == New Structures -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2': -- -- - 'PhysicalDeviceSamplerFilterMinmaxPropertiesEXT' -- -- - Extending 'Vulkan.Core10.Sampler.SamplerCreateInfo': -- -- - 'SamplerReductionModeCreateInfoEXT' -- -- == New Enums -- -- - 'SamplerReductionModeEXT' -- -- == New Enum Constants -- -- - 'EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME' -- -- - 'EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION' -- -- - Extending -- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FormatFeatureFlagBits': -- -- - 'FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT_EXT' -- -- - Extending -- 'Vulkan.Core12.Enums.SamplerReductionMode.SamplerReductionMode': -- -- - 'SAMPLER_REDUCTION_MODE_MAX_EXT' -- -- - 'SAMPLER_REDUCTION_MODE_MIN_EXT' -- -- - 'SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT' -- -- - 'STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT' -- -- == Version History -- -- - Revision 2, 2017-05-19 (Piers Daniell) -- -- - Renamed to EXT -- -- - Revision 1, 2017-03-25 (Jeff Bolz) -- -- - Internal revisions -- -- == See Also -- -- 'PhysicalDeviceSamplerFilterMinmaxPropertiesEXT', -- 'SamplerReductionModeCreateInfoEXT', 'SamplerReductionModeEXT' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_sampler_filter_minmax Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_EXT_sampler_filter_minmax ( pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT , pattern STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT , pattern FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT_EXT , pattern SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT , pattern SAMPLER_REDUCTION_MODE_MIN_EXT , pattern SAMPLER_REDUCTION_MODE_MAX_EXT , SamplerReductionModeEXT , PhysicalDeviceSamplerFilterMinmaxPropertiesEXT , SamplerReductionModeCreateInfoEXT , EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION , pattern EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION , EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME , pattern EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME ) where import Data.String (IsString) import Vulkan.Core12.Promoted_From_VK_EXT_sampler_filter_minmax (PhysicalDeviceSamplerFilterMinmaxProperties) import Vulkan.Core12.Enums.SamplerReductionMode (SamplerReductionMode) import Vulkan.Core12.Promoted_From_VK_EXT_sampler_filter_minmax (SamplerReductionModeCreateInfo) import Vulkan.Core10.Enums.FormatFeatureFlagBits (FormatFeatureFlags) import Vulkan.Core10.Enums.FormatFeatureFlagBits (FormatFeatureFlagBits(FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT)) import Vulkan.Core12.Enums.SamplerReductionMode (SamplerReductionMode(SAMPLER_REDUCTION_MODE_MAX)) import Vulkan.Core12.Enums.SamplerReductionMode (SamplerReductionMode(SAMPLER_REDUCTION_MODE_MIN)) import Vulkan.Core12.Enums.SamplerReductionMode (SamplerReductionMode(SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO)) -- No documentation found for TopLevel "VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT" pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT = STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES -- No documentation found for TopLevel "VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT" pattern STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT = STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO -- No documentation found for TopLevel "VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT_EXT" pattern FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT_EXT = FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT -- No documentation found for TopLevel "VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT" pattern SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT = SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE -- No documentation found for TopLevel "VK_SAMPLER_REDUCTION_MODE_MIN_EXT" pattern SAMPLER_REDUCTION_MODE_MIN_EXT = SAMPLER_REDUCTION_MODE_MIN -- No documentation found for TopLevel "VK_SAMPLER_REDUCTION_MODE_MAX_EXT" pattern SAMPLER_REDUCTION_MODE_MAX_EXT = SAMPLER_REDUCTION_MODE_MAX -- No documentation found for TopLevel "VkSamplerReductionModeEXT" type SamplerReductionModeEXT = SamplerReductionMode -- No documentation found for TopLevel "VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT" type PhysicalDeviceSamplerFilterMinmaxPropertiesEXT = PhysicalDeviceSamplerFilterMinmaxProperties -- No documentation found for TopLevel "VkSamplerReductionModeCreateInfoEXT" type SamplerReductionModeCreateInfoEXT = SamplerReductionModeCreateInfo type EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION = 2 -- No documentation found for TopLevel "VK_EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION" pattern EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION :: forall a . Integral a => a pattern EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION = 2 type EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME = "VK_EXT_sampler_filter_minmax" -- No documentation found for TopLevel "VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME" pattern EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME = "VK_EXT_sampler_filter_minmax"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_EXT_sampler_filter_minmax.hs
bsd-3-clause
8,690
0
8
1,622
504
367
137
-1
-1
{- The following is modified by Lee Pike (2014) and still retains the following license: Copyright (c) 2000-2012, Koen Claessen Copyright (c) 2006-2008, Björn Bringert Copyright (c) 2009-2012, Nick Smallbone All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the names of the copyright owners nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE ExistentialQuantification #-} -- | SmartCheck's interface to QuickCheck. module Test.SmartCheck.Test ( scQuickCheckWithResult , stdArgs ) where -------------------------------------------------------------------------- -- imports import Prelude hiding (break) import Test.QuickCheck import Test.QuickCheck.Gen import Test.QuickCheck.Property hiding ( Result( reason, theException), labels ) import qualified Test.QuickCheck.Property as P import Test.QuickCheck.Text import qualified Test.QuickCheck.State as S import Test.QuickCheck.Exception import Test.QuickCheck.Random import System.Random (split) import qualified Data.Map as M import qualified Data.Set as Set import Data.Char ( isSpace ) import Data.List ( sort , group , groupBy , intersperse ) -------------------------------------------------------------------------- -- quickCheck -- | Our SmartCheck reimplementation of the main QuickCheck driver. We want to -- distinguish the first argument to a 'Testable' property to be SmartChecked. -- In particular: the first argument will not be shrunk (even if there are -- default shrink instances for the type). However, the argument will be grown -- according to the the 'maxSize' argument to QuickCheck, in accordance with its -- generator. Other arguments will be shrunk, if they have shrinking instances. scQuickCheckWithResult :: forall a prop. (Show a, Arbitrary a, Testable prop) => Args -> (a -> prop) -> IO (Maybe a, Result) scQuickCheckWithResult a p = (if chatty a then withStdioTerminal else withNullTerminal) $ \tm -> do rnd <- case replay a of Nothing -> newQCGen Just (rnd,_) -> return rnd test S.MkState{ S.terminal = tm , S.maxSuccessTests = maxSuccess a , S.maxDiscardedTests = maxDiscardRatio a * maxSuccess a , S.computeSize = case replay a of Nothing -> computeSize' Just (_,s) -> computeSize' `at0` s , S.numSuccessTests = 0 , S.numDiscardedTests = 0 , S.labels = M.empty , S.numRecentlyDiscardedTests = 0 , S.collected = [] , S.expectedFailure = False , S.randomSeed = rnd , S.numSuccessShrinks = 0 , S.numTryShrinks = 0 , S.numTotTryShrinks = 0 } flipProp where computeSize' n d -- e.g. with maxSuccess = 250, maxSize = 100, goes like this: -- 0, 1, 2, ..., 99, 0, 1, 2, ..., 99, 0, 2, 4, ..., 98. | n `roundTo` maxSize a + maxSize a <= maxSuccess a || n >= maxSuccess a || maxSuccess a `mod` maxSize a == 0 = (n `mod` maxSize a + d `div` 10) `min` maxSize a | otherwise = ((n `mod` maxSize a) * maxSize a `div` (maxSuccess a `mod` maxSize a) + d `div` 10) `min` maxSize a n `roundTo` m = (n `div` m) * m at0 _f s 0 0 = s at0 f _s n d = f n d flipProp :: QCGen -> Int -> (a -> Prop) flipProp q i = \a' -> let p' = p a' in let g = unGen (unProperty (property p')) in g q i -------------------------------------------------------------------------- -- main test loop test :: Arbitrary a => S.State -> (QCGen -> Int -> (a -> Prop)) -> IO (Maybe a, Result) test st f | S.numSuccessTests st >= S.maxSuccessTests st = doneTesting st f | S.numDiscardedTests st >= S.maxDiscardedTests st = giveUp st f | otherwise = runATest st f doneTesting :: S.State -> (QCGen -> Int -> (a -> Prop)) -> IO (Maybe a, Result) doneTesting st _f = do -- CALLBACK done_testing? if S.expectedFailure st then putPart (S.terminal st) ( "+++ OK, passed " ++ show (S.numSuccessTests st) ++ " tests" ) else putPart (S.terminal st) ( bold ("*** Failed!") ++ " Passed " ++ show (S.numSuccessTests st) ++ " tests (expected failure)" ) success st theOutput <- terminalOutput (S.terminal st) return $ (Nothing, if S.expectedFailure st then Success{ labels = summary st, numTests = S.numSuccessTests st, output = theOutput } else NoExpectedFailure{ labels = summary st, numTests = S.numSuccessTests st, output = theOutput }) giveUp :: S.State -> (QCGen -> Int -> (a -> Prop)) -> IO (Maybe a, Result) giveUp st _f = do -- CALLBACK gave_up? putPart (S.terminal st) ( bold ("*** Gave up!") ++ " Passed only " ++ show (S.numSuccessTests st) ++ " tests" ) success st theOutput <- terminalOutput (S.terminal st) return ( Nothing , GaveUp{ numTests = S.numSuccessTests st , labels = summary st , output = theOutput } ) runATest :: forall a. (Arbitrary a) => S.State -> (QCGen -> Int -> (a -> Prop)) -> IO (Maybe a, Result) runATest st f = do -- CALLBACK before_test putTemp (S.terminal st) ( "(" ++ number (S.numSuccessTests st) "test" ++ concat [ "; " ++ show (S.numDiscardedTests st) ++ " discarded" | S.numDiscardedTests st > 0 ] ++ ")" ) let size = S.computeSize st (S.numSuccessTests st) (S.numRecentlyDiscardedTests st) let p :: a -> Prop p = f rnd1 size let genA :: QCGen -> Int -> a genA = unGen arbitrary let rndA = genA rnd1 size let mkRes res = return (Just rndA, res) MkRose res ts <- protectRose (reduceRose (unProp (p rndA))) callbackPostTest st res let continue break st' | abort res = break st' | otherwise = test st' case res of MkResult{ok = Just True, stamp, expect} -> -- successful test do continue doneTesting st{ S.numSuccessTests = S.numSuccessTests st + 1 , S.numRecentlyDiscardedTests = 0 , S.randomSeed = rnd2 , S.collected = stamp : S.collected st , S.expectedFailure = expect } f MkResult{ok = Nothing, expect = expect} -> -- discarded test do continue giveUp st{ S.numDiscardedTests = S.numDiscardedTests st + 1 , S.numRecentlyDiscardedTests = S.numRecentlyDiscardedTests st + 1 , S.randomSeed = rnd2 , S.expectedFailure = expect } f MkResult{ok = Just False} -> -- failed test do if expect res then putPart (S.terminal st) (bold "*** Failed! ") else putPart (S.terminal st) "+++ OK, failed as expected. " (numShrinks, totFailed, lastFailed) <- foundFailure st res ts theOutput <- terminalOutput (S.terminal st) if not (expect res) then mkRes Success{ labels = summary st, numTests = S.numSuccessTests st+1, output = theOutput } else mkRes Failure{ -- correct! (this will be split first) usedSeed = S.randomSeed st , usedSize = size , numTests = S.numSuccessTests st+1 , numShrinks = numShrinks , numShrinkTries = totFailed , numShrinkFinal = lastFailed , output = theOutput , reason = P.reason res , theException = P.theException res , labels = summary st } where (rnd1,rnd2) = split (S.randomSeed st) summary :: S.State -> [(String,Int)] summary st = reverse . sort . map (\ss -> (head ss, (length ss * 100) `div` S.numSuccessTests st)) . group . sort $ [ concat (intersperse ", " (Set.toList s)) | s <- S.collected st , not (Set.null s) ] success :: S.State -> IO () success st = case allLabels ++ covers of [] -> do putLine (S.terminal st) "." [pt] -> do putLine (S.terminal st) ( " (" ++ dropWhile isSpace pt ++ ")." ) cases -> do putLine (S.terminal st) ":" sequence_ [ putLine (S.terminal st) pt | pt <- cases ] where allLabels = reverse . sort . map (\ss -> (showP ((length ss * 100) `div` S.numSuccessTests st) ++ head ss)) . group . sort $ [ concat (intersperse ", " s') | s <- S.collected st , let s' = [ t | t <- Set.toList s, M.lookup t (S.labels st) == Just 0 ] , not (null s') ] covers = [ ("only " ++ show (labelPercentage l st) ++ "% " ++ l ++ ", not " ++ show reqP ++ "%") | (l, reqP) <- M.toList (S.labels st) , labelPercentage l st < reqP ] -- (x,_) `first` (y,_) = x == y showP p = (if p < 10 then " " else "") ++ show p ++ "% " labelPercentage :: String -> S.State -> Int labelPercentage l st = -- XXX in case of a disjunction, a label can occur several times, -- need to think what to do there (100 * occur) `div` S.maxSuccessTests st where occur = length [ l' | l' <- concat (map Set.toList (S.collected st)), l == l' ] -------------------------------------------------------------------------- -- main shrinking loop foundFailure :: S.State -> P.Result -> [Rose P.Result] -> IO (Int, Int, Int) foundFailure st res ts = do localMin st{ S.numTryShrinks = 0 } res res ts localMin :: S.State -> P.Result -> P.Result -> [Rose P.Result] -> IO (Int, Int, Int) localMin st MkResult{P.theException = Just e} lastRes _ | isInterrupt e = localMinFound st lastRes localMin st res _ ts = do putTemp (S.terminal st) ( short 26 (oneLine (P.reason res)) ++ " (after " ++ number (S.numSuccessTests st+1) "test" ++ concat [ " and " ++ show (S.numSuccessShrinks st) ++ concat [ "." ++ show (S.numTryShrinks st) | S.numTryShrinks st > 0 ] ++ " shrink" ++ (if S.numSuccessShrinks st == 1 && S.numTryShrinks st == 0 then "" else "s") | S.numSuccessShrinks st > 0 || S.numTryShrinks st > 0 ] ++ ")..." ) r <- tryEvaluate ts case r of Left err -> localMinFound st (exception "Exception while generating shrink-list" err) { callbacks = callbacks res } Right ts' -> localMin' st res ts' localMin' :: S.State -> P.Result -> [Rose P.Result] -> IO (Int, Int, Int) localMin' st res [] = localMinFound st res localMin' st res (t:ts) = do -- CALLBACK before_test MkRose res' ts' <- protectRose (reduceRose t) callbackPostTest st res' if ok res' == Just False then localMin st{ S.numSuccessShrinks = S.numSuccessShrinks st + 1, S.numTryShrinks = 0 } res' res ts' else localMin st{ S.numTryShrinks = S.numTryShrinks st + 1, S.numTotTryShrinks = S.numTotTryShrinks st + 1 } res res ts localMinFound :: S.State -> P.Result -> IO (Int, Int, Int) localMinFound st res = do let report = concat [ "(after " ++ number (S.numSuccessTests st+1) "test", concat [ " and " ++ number (S.numSuccessShrinks st) "shrink" | S.numSuccessShrinks st > 0 ], "): " ] if isOneLine (P.reason res) then putLine (S.terminal st) (P.reason res ++ " " ++ report) else do putLine (S.terminal st) report sequence_ [ putLine (S.terminal st) msg | msg <- lines (P.reason res) ] putLine (S.terminal st) "*** Non SmartChecked arguments:" callbackPostFinalFailure st res return (S.numSuccessShrinks st, S.numTotTryShrinks st - S.numTryShrinks st, S.numTryShrinks st) -------------------------------------------------------------------------- -- callbacks callbackPostTest :: S.State -> P.Result -> IO () callbackPostTest st res = sequence_ [ safely st (f st res) | PostTest _ f <- callbacks res ] callbackPostFinalFailure :: S.State -> P.Result -> IO () callbackPostFinalFailure st res = sequence_ [ safely st (f st res) | PostFinalFailure _ f <- callbacks res ] safely :: S.State -> IO () -> IO () safely st x = do r <- tryEvaluateIO x case r of Left e -> putLine (S.terminal st) ("*** Exception in callback: " ++ show e) Right x' -> return x' -------------------------------------------------------------------------- -- the end.
markus1189/SmartCheck
src/Test/SmartCheck/Test.hs
bsd-3-clause
15,241
0
22
5,208
4,005
2,054
1,951
268
5
{-# LANGUAGE DeriveGeneric #-} {-# OPTIONS_GHC -fplugin Brisk.Plugin #-} {-# OPTIONS_GHC -fplugin-opt Brisk.Plugin:runDataNode #-} module Managed where import Data.Binary import GHC.Generics (Generic) import qualified Data.HashMap.Strict as M import Control.Distributed.Process hiding (call) import Control.Distributed.Process.Extras.Time import Control.Distributed.Process.ManagedProcess import GHC.Base.Brisk import Control.Distributed.Process.Brisk hiding (call) import Control.Distributed.Process.ManagedProcess.Brisk {- DataNode: 1. register datanode service 2. start "space reporter" ??? 3. start RPC service -} dataNodeService :: String dataNodeService = "theque:dataNode" type BlobId = String type DataNodeMap = M.HashMap BlobId String data DataNodeState = DNS { master :: ProcessId , blobs :: !DataNodeMap } data DataNodeAPI = AddBlob String String deriving (Eq, Ord, Show, Generic) pushBlob :: ProcessId -> String -> String -> Process DataNodeResponse pushBlob p bn bdata = call p (AddBlob bn bdata) instance Binary DataNodeAPI data DataNodeResponse = OK | BlobExists deriving (Eq, Ord, Show, Generic) instance Binary DataNodeResponse initState :: ProcessId -> DataNodeState initState m = DNS { blobs = M.empty, master = m } runDataNode :: ProcessId -> Process () runDataNode m = serve (initState m) initializeDataNode dataNodeProcess initializeDataNode :: DataNodeState -> Process (InitResult DataNodeState) initializeDataNode x = return (InitOk x NoDelay) dataNodeProcess :: ProcessDefinition DataNodeState dataNodeProcess = defaultProcess { apiHandlers = [dataNodeAPIHandler] } type DataNodeReply = Process (ProcessReply DataNodeResponse DataNodeState) dataNodeAPIHandler :: Dispatcher DataNodeState dataNodeAPIHandler = handleCall dataNodeAPIHandler' dataNodeAPIHandler' :: DataNodeState -> DataNodeAPI -> DataNodeReply dataNodeAPIHandler' st (AddBlob bn blob) = case M.lookup bn (blobs st) of Nothing -> reply OK st' where st' = st { blobs = M.insert bn blob (blobs st) } Just bdata -> do say (bn ++ " := " ++ show bdata) reply BlobExists st
abakst/brisk-prelude
examples/Managed.hs
bsd-3-clause
2,213
0
14
417
543
297
246
54
2
{-# LANGUAGE DeriveGeneric #-} module Interfaces.Entropia ( queryEntropia , formatEntropia ) where import Data.Aeson (eitherDecode, FromJSON(..)) import Control.Applicative ((<$>)) import GHC.Generics import Network.Curl import Interfaces.HTML (fetchLazy) -- |URL to Entropia's JSON status file entropiaJSON :: String entropiaJSON = "http://club.entropia.de/" -- |The Entropia record for parsing the JSON data Entropia = Entropia { last_event :: String -- ^ Time of last update , club_offen :: Bool -- ^ Whether the club is open , fenster_offen :: Bool -- ^ Whether the window is open } deriving (Show, Generic) instance FromJSON Entropia -- |Given a record, print whether the club is open or not. formatEntropia :: Entropia -> String formatEntropia = status . club_offen where status True = "Club ist offen." status False = "Club ist geschlossen." -- |Fetch and decode the JSON file. Results in 'Either String Entropia', -- signaling parse status. queryEntropia :: IO (Either String Entropia) queryEntropia = eitherDecode <$> respBody <$> fetchLazy entropiaJSON
vehk/Indoril
src/Interfaces/Entropia.hs
bsd-3-clause
1,212
0
8
304
195
116
79
22
2
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Main -- Copyright : (c) David Himmelstrup 2005 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Entry point to the default cabal-install front-end. ----------------------------------------------------------------------------- module Main (main) where import Distribution.Client.Setup ( GlobalFlags(..), globalCommand, withGlobalRepos , ConfigFlags(..) , ConfigExFlags(..), defaultConfigExFlags, configureExCommand , BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..) , buildCommand, replCommand, testCommand, benchmarkCommand , InstallFlags(..), defaultInstallFlags , installCommand, upgradeCommand, uninstallCommand , FetchFlags(..), fetchCommand , FreezeFlags(..), freezeCommand , GetFlags(..), getCommand, unpackCommand , checkCommand , formatCommand , updateCommand , ListFlags(..), listCommand , InfoFlags(..), infoCommand , UploadFlags(..), uploadCommand , ReportFlags(..), reportCommand , runCommand , InitFlags(initVerbosity), initCommand , SDistFlags(..), SDistExFlags(..), sdistCommand , Win32SelfUpgradeFlags(..), win32SelfUpgradeCommand , ActAsSetupFlags(..), actAsSetupCommand , SandboxFlags(..), sandboxCommand , ExecFlags(..), execCommand , UserConfigFlags(..), userConfigCommand , reportCommand , manpageCommand ) import Distribution.Simple.Setup ( HaddockFlags(..), haddockCommand, defaultHaddockFlags , HscolourFlags(..), hscolourCommand , ReplFlags(..) , CopyFlags(..), copyCommand , RegisterFlags(..), registerCommand , CleanFlags(..), cleanCommand , TestFlags(..), BenchmarkFlags(..) , Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe, toFlag , configAbsolutePaths ) import Distribution.Client.SetupWrapper ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions ) import Distribution.Client.Config ( SavedConfig(..), loadConfig, defaultConfigFile, userConfigDiff , userConfigUpdate ) import Distribution.Client.Targets ( readUserTargets ) import qualified Distribution.Client.List as List ( list, info ) import Distribution.Client.Install (install) import Distribution.Client.Configure (configure) import Distribution.Client.Update (update) import Distribution.Client.Exec (exec) import Distribution.Client.Fetch (fetch) import Distribution.Client.Freeze (freeze) import Distribution.Client.Check as Check (check) --import Distribution.Client.Clean (clean) import qualified Distribution.Client.Upload as Upload import Distribution.Client.Run (run, splitRunArgs) import Distribution.Client.HttpUtils (configureTransport) import Distribution.Client.SrcDist (sdist) import Distribution.Client.Get (get) import Distribution.Client.Sandbox (sandboxInit ,sandboxAddSource ,sandboxDelete ,sandboxDeleteSource ,sandboxListSources ,sandboxHcPkg ,dumpPackageEnvironment ,getSandboxConfigFilePath ,loadConfigOrSandboxConfig ,findSavedDistPref ,initPackageDBIfNeeded ,maybeWithSandboxDirOnSearchPath ,maybeWithSandboxPackageInfo ,WereDepsReinstalled(..) ,maybeReinstallAddSourceDeps ,tryGetIndexFilePath ,sandboxBuildDir ,updateSandboxConfigFileFlag ,updateInstallDirs ,configCompilerAux' ,getPersistOrConfigCompiler ,configPackageDB') import Distribution.Client.Sandbox.PackageEnvironment (setPackageDB ,userPackageEnvironmentFile) import Distribution.Client.Sandbox.Timestamp (maybeAddCompilerTimestampRecord) import Distribution.Client.Sandbox.Types (UseSandbox(..), whenUsingSandbox) import Distribution.Client.Tar (createTarGzFile) import Distribution.Client.Types (Password (..)) import Distribution.Client.Init (initCabal) import Distribution.Client.Manpage (manpage) import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade import Distribution.Client.Utils (determineNumJobs #if defined(mingw32_HOST_OS) ,relaxEncodingErrors #endif ,existsAndIsMoreRecentThan) import Distribution.Package (packageId) import Distribution.PackageDescription ( BuildType(..), Executable(..), benchmarkName, benchmarkBuildInfo , testName, testBuildInfo, buildable ) import Distribution.PackageDescription.Parse ( readPackageDescription ) import Distribution.PackageDescription.PrettyPrint ( writeGenericPackageDescription ) import qualified Distribution.Simple as Simple import qualified Distribution.Make as Make import Distribution.Simple.Build ( startInterpreter ) import Distribution.Simple.Command ( CommandParse(..), CommandUI(..), Command, CommandSpec(..), CommandType(..) , commandsRun, commandAddAction, hiddenCommand, commandFromSpec) import Distribution.Simple.Compiler ( Compiler(..) ) import Distribution.Simple.Configure ( checkPersistBuildConfigOutdated, configCompilerAuxEx , ConfigStateFileError(..), localBuildInfoFile , getPersistBuildConfig, tryGetPersistBuildConfig ) import qualified Distribution.Simple.LocalBuildInfo as LBI import Distribution.Simple.Program (defaultProgramConfiguration ,configureAllKnownPrograms ,simpleProgramInvocation ,getProgramInvocationOutput) import Distribution.Simple.Program.Db (reconfigurePrograms) import qualified Distribution.Simple.Setup as Cabal import Distribution.Simple.Utils ( cabalVersion, die, notice, info, topHandler , findPackageDesc, tryFindPackageDesc ) import Distribution.Text ( display ) import Distribution.Verbosity as Verbosity ( Verbosity, normal ) import Distribution.Version ( Version(..), orLaterVersion ) import qualified Paths_cabal_install (version) import System.Environment (getArgs, getProgName) import System.Exit (exitFailure) import System.FilePath (splitExtension, takeExtension, (</>), (<.>)) import System.IO ( BufferMode(LineBuffering), hSetBuffering #ifdef mingw32_HOST_OS , stderr #endif , stdout ) import System.Directory (doesFileExist, getCurrentDirectory) import Data.List (intercalate) import Data.Maybe (mapMaybe, listToMaybe) #if !MIN_VERSION_base(4,8,0) import Data.Monoid (Monoid(..)) import Control.Applicative (pure, (<$>)) #endif import Control.Monad (when, unless) -- | Entry point -- main :: IO () main = do -- Enable line buffering so that we can get fast feedback even when piped. -- This is especially important for CI and build systems. hSetBuffering stdout LineBuffering -- The default locale encoding for Windows CLI is not UTF-8 and printing -- Unicode characters to it will fail unless we relax the handling of encoding -- errors when writing to stderr and stdout. #ifdef mingw32_HOST_OS relaxEncodingErrors stdout relaxEncodingErrors stderr #endif getArgs >>= mainWorker mainWorker :: [String] -> IO () mainWorker args = topHandler $ case commandsRun (globalCommand commands) commands args of CommandHelp help -> printGlobalHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo (globalFlags, commandParse) -> case commandParse of _ | fromFlagOrDefault False (globalVersion globalFlags) -> printVersion | fromFlagOrDefault False (globalNumericVersion globalFlags) -> printNumericVersion CommandHelp help -> printCommandHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo action -> do globalFlags' <- updateSandboxConfigFileFlag globalFlags action globalFlags' where printCommandHelp help = do pname <- getProgName putStr (help pname) printGlobalHelp help = do pname <- getProgName configFile <- defaultConfigFile putStr (help pname) putStr $ "\nYou can edit the cabal configuration file to set defaults:\n" ++ " " ++ configFile ++ "\n" exists <- doesFileExist configFile when (not exists) $ putStrLn $ "This file will be generated with sensible " ++ "defaults if you run 'cabal update'." printOptionsList = putStr . unlines printErrors errs = die $ intercalate "\n" errs printNumericVersion = putStrLn $ display Paths_cabal_install.version printVersion = putStrLn $ "cabal-install version " ++ display Paths_cabal_install.version ++ "\ncompiled using version " ++ display cabalVersion ++ " of the Cabal library " commands = map commandFromSpec commandSpecs commandSpecs = [ regularCmd installCommand installAction , regularCmd updateCommand updateAction , regularCmd listCommand listAction , regularCmd infoCommand infoAction , regularCmd fetchCommand fetchAction , regularCmd freezeCommand freezeAction , regularCmd getCommand getAction , hiddenCmd unpackCommand unpackAction , regularCmd checkCommand checkAction , regularCmd sdistCommand sdistAction , regularCmd uploadCommand uploadAction , regularCmd reportCommand reportAction , regularCmd runCommand runAction , regularCmd initCommand initAction , regularCmd configureExCommand configureAction , regularCmd buildCommand buildAction , regularCmd replCommand replAction , regularCmd sandboxCommand sandboxAction , regularCmd haddockCommand haddockAction , regularCmd execCommand execAction , regularCmd userConfigCommand userConfigAction , regularCmd cleanCommand cleanAction , wrapperCmd copyCommand copyVerbosity copyDistPref , wrapperCmd hscolourCommand hscolourVerbosity hscolourDistPref , wrapperCmd registerCommand regVerbosity regDistPref , regularCmd testCommand testAction , regularCmd benchmarkCommand benchmarkAction , hiddenCmd uninstallCommand uninstallAction , hiddenCmd formatCommand formatAction , hiddenCmd upgradeCommand upgradeAction , hiddenCmd win32SelfUpgradeCommand win32SelfUpgradeAction , hiddenCmd actAsSetupCommand actAsSetupAction , hiddenCmd manpageCommand (manpageAction commandSpecs) ] type Action = GlobalFlags -> IO () regularCmd :: CommandUI flags -> (flags -> [String] -> action) -> CommandSpec action regularCmd ui action = CommandSpec ui ((flip commandAddAction) action) NormalCommand hiddenCmd :: CommandUI flags -> (flags -> [String] -> action) -> CommandSpec action hiddenCmd ui action = CommandSpec ui (\ui' -> hiddenCommand (commandAddAction ui' action)) HiddenCommand wrapperCmd :: Monoid flags => CommandUI flags -> (flags -> Flag Verbosity) -> (flags -> Flag String) -> CommandSpec Action wrapperCmd ui verbosity distPref = CommandSpec ui (\ui' -> wrapperAction ui' verbosity distPref) NormalCommand wrapperAction :: Monoid flags => CommandUI flags -> (flags -> Flag Verbosity) -> (flags -> Flag String) -> Command Action wrapperAction command verbosityFlag distPrefFlag = commandAddAction command { commandDefaultFlags = mempty } $ \flags extraArgs globalFlags -> do let verbosity = fromFlagOrDefault normal (verbosityFlag flags) (_, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config (distPrefFlag flags) let setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref } setupWrapper verbosity setupScriptOptions Nothing command (const flags) extraArgs configureAction :: (ConfigFlags, ConfigExFlags) -> [String] -> Action configureAction (configFlags, configExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (configVerbosity configFlags) (useSandbox, config) <- fmap (updateInstallDirs (configUserInstall configFlags)) (loadConfigOrSandboxConfig verbosity globalFlags) let configFlags' = savedConfigureFlags config `mappend` configFlags configExFlags' = savedConfigureExFlags config `mappend` configExFlags globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, platform, conf) <- configCompilerAuxEx configFlags' -- If we're working inside a sandbox and the user has set the -w option, we -- may need to create a sandbox-local package DB for this compiler and add a -- timestamp record for this compiler to the timestamp file. let configFlags'' = case useSandbox of NoSandbox -> configFlags' (UseSandbox sandboxDir) -> setPackageDB sandboxDir comp platform configFlags' whenUsingSandbox useSandbox $ \sandboxDir -> do initPackageDBIfNeeded verbosity configFlags'' comp conf -- NOTE: We do not write the new sandbox package DB location to -- 'cabal.sandbox.config' here because 'configure -w' must not affect -- subsequent 'install' (for UI compatibility with non-sandboxed mode). indexFile <- tryGetIndexFilePath config maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile (compilerId comp) platform maybeWithSandboxDirOnSearchPath useSandbox $ withGlobalRepos verbosity globalFlags' $ \globalRepos -> configure verbosity (configPackageDB' configFlags'') globalRepos comp platform conf configFlags'' configExFlags' extraArgs buildAction :: (BuildFlags, BuildExFlags) -> [String] -> Action buildAction (buildFlags, buildExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags) noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) -- Calls 'configureAction' to do the real work, so nothing special has to be -- done to support sandboxes. (useSandbox, config, distPref) <- reconfigure verbosity (buildDistPref buildFlags) mempty [] globalFlags noAddSource (buildNumJobs buildFlags) (const Nothing) maybeWithSandboxDirOnSearchPath useSandbox $ build verbosity config distPref buildFlags extraArgs -- | Actually do the work of building the package. This is separate from -- 'buildAction' so that 'testAction' and 'benchmarkAction' do not invoke -- 'reconfigure' twice. build :: Verbosity -> SavedConfig -> FilePath -> BuildFlags -> [String] -> IO () build verbosity config distPref buildFlags extraArgs = setupWrapper verbosity setupOptions Nothing (Cabal.buildCommand progConf) mkBuildFlags extraArgs where progConf = defaultProgramConfiguration setupOptions = defaultSetupScriptOptions { useDistPref = distPref } mkBuildFlags version = filterBuildFlags version config buildFlags' buildFlags' = buildFlags { buildVerbosity = toFlag verbosity , buildDistPref = toFlag distPref } -- | Make sure that we don't pass new flags to setup scripts compiled against -- old versions of Cabal. filterBuildFlags :: Version -> SavedConfig -> BuildFlags -> BuildFlags filterBuildFlags version config buildFlags | version >= Version [1,19,1] [] = buildFlags_latest -- Cabal < 1.19.1 doesn't support 'build -j'. | otherwise = buildFlags_pre_1_19_1 where buildFlags_pre_1_19_1 = buildFlags { buildNumJobs = NoFlag } buildFlags_latest = buildFlags { -- Take the 'jobs' setting '~/.cabal/config' into account. buildNumJobs = Flag . Just . determineNumJobs $ (numJobsConfigFlag `mappend` numJobsCmdLineFlag) } numJobsConfigFlag = installNumJobs . savedInstallFlags $ config numJobsCmdLineFlag = buildNumJobs buildFlags replAction :: (ReplFlags, BuildExFlags) -> [String] -> Action replAction (replFlags, buildExFlags) extraArgs globalFlags = do cwd <- getCurrentDirectory pkgDesc <- findPackageDesc cwd either (const onNoPkgDesc) (const onPkgDesc) pkgDesc where verbosity = fromFlagOrDefault normal (replVerbosity replFlags) -- There is a .cabal file in the current directory: start a REPL and load -- the project's modules. onPkgDesc = do let noAddSource = case replReload replFlags of Flag True -> SkipAddSourceDepsCheck _ -> fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) -- Calls 'configureAction' to do the real work, so nothing special has to -- be done to support sandboxes. (useSandbox, _config, distPref) <- reconfigure verbosity (replDistPref replFlags) mempty [] globalFlags noAddSource NoFlag (const Nothing) let progConf = defaultProgramConfiguration setupOptions = defaultSetupScriptOptions { useCabalVersion = orLaterVersion $ Version [1,18,0] [] , useDistPref = distPref } replFlags' = replFlags { replVerbosity = toFlag verbosity , replDistPref = toFlag distPref } maybeWithSandboxDirOnSearchPath useSandbox $ setupWrapper verbosity setupOptions Nothing (Cabal.replCommand progConf) (const replFlags') extraArgs -- No .cabal file in the current directory: just start the REPL (possibly -- using the sandbox package DB). onNoPkgDesc = do (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags let configFlags = savedConfigureFlags config (comp, _platform, programDb) <- configCompilerAux' configFlags programDb' <- reconfigurePrograms verbosity (replProgramPaths replFlags) (replProgramArgs replFlags) programDb startInterpreter verbosity programDb' comp (configPackageDB' configFlags) -- | Re-configure the package in the current directory if needed. Deciding -- when to reconfigure and with which options is convoluted: -- -- If we are reconfiguring, we must always run @configure@ with the -- verbosity option we are given; however, that a previous configuration -- uses a different verbosity setting is not reason enough to reconfigure. -- -- The package should be configured to use the same \"dist\" prefix as -- given to the @build@ command, otherwise the build will probably -- fail. Not only does this determine the \"dist\" prefix setting if we -- need to reconfigure anyway, but an existing configuration should be -- invalidated if its \"dist\" prefix differs. -- -- If the package has never been configured (i.e., there is no -- LocalBuildInfo), we must configure first, using the default options. -- -- If the package has been configured, there will be a 'LocalBuildInfo'. -- If there no package description file, we assume that the -- 'PackageDescription' is up to date, though the configuration may need -- to be updated for other reasons (see above). If there is a package -- description file, and it has been modified since the 'LocalBuildInfo' -- was generated, then we need to reconfigure. -- -- The caller of this function may also have specific requirements -- regarding the flags the last configuration used. For example, -- 'testAction' requires that the package be configured with test suites -- enabled. The caller may pass the required settings to this function -- along with a function to check the validity of the saved 'ConfigFlags'; -- these required settings will be checked first upon determining that -- a previous configuration exists. reconfigure :: Verbosity -- ^ Verbosity setting -> Flag FilePath -- ^ \"dist\" prefix -> ConfigFlags -- ^ Additional config flags to set. These flags -- will be 'mappend'ed to the last used or -- default 'ConfigFlags' as appropriate, so -- this value should be 'mempty' with only the -- required flags set. The required verbosity -- and \"dist\" prefix flags will be set -- automatically because they are always -- required; therefore, it is not necessary to -- set them here. -> [String] -- ^ Extra arguments -> GlobalFlags -- ^ Global flags -> SkipAddSourceDepsCheck -- ^ Should we skip the timestamp check for modified -- add-source dependencies? -> Flag (Maybe Int) -- ^ -j flag for reinstalling add-source deps. -> (ConfigFlags -> Maybe String) -- ^ Check that the required flags are set in -- the last used 'ConfigFlags'. If the required -- flags are not set, provide a message to the -- user explaining the reason for -- reconfiguration. Because the correct \"dist\" -- prefix setting is always required, it is checked -- automatically; this function need not check -- for it. -> IO (UseSandbox, SavedConfig, FilePath) reconfigure verbosity flagDistPref addConfigFlags extraArgs globalFlags skipAddSourceDepsCheck numJobsFlag checkFlags = do (useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config flagDistPref eLbi <- tryGetPersistBuildConfig distPref config' <- case eLbi of Left err -> onNoBuildConfig (useSandbox, config) distPref err Right lbi -> onBuildConfig (useSandbox, config) distPref lbi return (useSandbox, config', distPref) where -- We couldn't load the saved package config file. -- -- If we're in a sandbox: add-source deps don't have to be reinstalled -- (since we don't know the compiler & platform). onNoBuildConfig :: (UseSandbox, SavedConfig) -> FilePath -> ConfigStateFileError -> IO SavedConfig onNoBuildConfig (_, config) distPref err = do let msg = case err of ConfigStateFileMissing -> "Package has never been configured." ConfigStateFileNoParse -> "Saved package config file seems " ++ "to be corrupt." _ -> show err case err of ConfigStateFileBadVersion _ _ _ -> info verbosity msg _ -> do let distVerbFlags = mempty { configVerbosity = toFlag verbosity , configDistPref = toFlag distPref } defaultFlags = mappend addConfigFlags distVerbFlags notice verbosity $ msg ++ " Configuring with default flags." ++ configureManually configureAction (defaultFlags, defaultConfigExFlags) extraArgs globalFlags return config -- Package has been configured, but the configuration may be out of -- date or required flags may not be set. -- -- If we're in a sandbox: reinstall the modified add-source deps and -- force reconfigure if we did. onBuildConfig :: (UseSandbox, SavedConfig) -> FilePath -> LBI.LocalBuildInfo -> IO SavedConfig onBuildConfig (useSandbox, config) distPref lbi = do let configFlags = LBI.configFlags lbi distVerbFlags = mempty { configVerbosity = toFlag verbosity , configDistPref = toFlag distPref } flags = mconcat [configFlags, addConfigFlags, distVerbFlags] -- Was the sandbox created after the package was already configured? We -- may need to skip reinstallation of add-source deps and force -- reconfigure. let buildConfig = localBuildInfoFile distPref sandboxConfig <- getSandboxConfigFilePath globalFlags isSandboxConfigNewer <- sandboxConfig `existsAndIsMoreRecentThan` buildConfig let skipAddSourceDepsCheck' | isSandboxConfigNewer = SkipAddSourceDepsCheck | otherwise = skipAddSourceDepsCheck when (skipAddSourceDepsCheck' == SkipAddSourceDepsCheck) $ info verbosity "Skipping add-source deps check..." let (_, config') = updateInstallDirs (configUserInstall flags) (useSandbox, config) depsReinstalled <- case skipAddSourceDepsCheck' of DontSkipAddSourceDepsCheck -> maybeReinstallAddSourceDeps verbosity numJobsFlag flags globalFlags (useSandbox, config') SkipAddSourceDepsCheck -> do return NoDepsReinstalled -- Is the @cabal.config@ file newer than @dist/setup.config@? Then we need -- to force reconfigure. Note that it's possible to use @cabal.config@ -- even without sandboxes. isUserPackageEnvironmentFileNewer <- userPackageEnvironmentFile `existsAndIsMoreRecentThan` buildConfig -- Determine whether we need to reconfigure and which message to show to -- the user if that is the case. mMsg <- determineMessageToShow distPref lbi configFlags depsReinstalled isSandboxConfigNewer isUserPackageEnvironmentFileNewer case mMsg of -- No message for the user indicates that reconfiguration -- is not required. Nothing -> return config' -- Show the message and reconfigure. Just msg -> do notice verbosity msg configureAction (flags, defaultConfigExFlags) extraArgs globalFlags return config' -- Determine what message, if any, to display to the user if reconfiguration -- is required. determineMessageToShow :: FilePath -> LBI.LocalBuildInfo -> ConfigFlags -> WereDepsReinstalled -> Bool -> Bool -> IO (Maybe String) determineMessageToShow _ _ _ _ True _ = -- The sandbox was created after the package was already configured. return $! Just $! sandboxConfigNewerMessage determineMessageToShow _ _ _ _ False True = -- The user package environment file was modified. return $! Just $! userPackageEnvironmentFileModifiedMessage determineMessageToShow distPref lbi configFlags depsReinstalled False False = do let savedDistPref = fromFlagOrDefault (useDistPref defaultSetupScriptOptions) (configDistPref configFlags) case depsReinstalled of ReinstalledSomeDeps -> -- Some add-source deps were reinstalled. return $! Just $! reinstalledDepsMessage NoDepsReinstalled -> case checkFlags configFlags of -- Flag required by the caller is not set. Just msg -> return $! Just $! msg ++ configureManually Nothing -- Required "dist" prefix is not set. | savedDistPref /= distPref -> return $! Just distPrefMessage -- All required flags are set, but the configuration -- may be outdated. | otherwise -> case LBI.pkgDescrFile lbi of Nothing -> return Nothing Just pdFile -> do outdated <- checkPersistBuildConfigOutdated distPref pdFile return $! if outdated then Just $! outdatedMessage pdFile else Nothing reconfiguringMostRecent = " Re-configuring with most recently used options." configureManually = " If this fails, please run configure manually." sandboxConfigNewerMessage = "The sandbox was created after the package was already configured." ++ reconfiguringMostRecent ++ configureManually userPackageEnvironmentFileModifiedMessage = "The user package environment file ('" ++ userPackageEnvironmentFile ++ "') was modified." ++ reconfiguringMostRecent ++ configureManually distPrefMessage = "Package previously configured with different \"dist\" prefix." ++ reconfiguringMostRecent ++ configureManually outdatedMessage pdFile = pdFile ++ " has been changed." ++ reconfiguringMostRecent ++ configureManually reinstalledDepsMessage = "Some add-source dependencies have been reinstalled." ++ reconfiguringMostRecent ++ configureManually installAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags) -> [String] -> Action installAction (configFlags, _, installFlags, _) _ globalFlags | fromFlagOrDefault False (installOnly installFlags) = do let verbosity = fromFlagOrDefault normal (configVerbosity configFlags) (_, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config (configDistPref configFlags) let setupOpts = defaultSetupScriptOptions { useDistPref = distPref } setupWrapper verbosity setupOpts Nothing installCommand (const mempty) [] installAction (configFlags, configExFlags, installFlags, haddockFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (configVerbosity configFlags) (useSandbox, config) <- fmap (updateInstallDirs (configUserInstall configFlags)) (loadConfigOrSandboxConfig verbosity globalFlags) targets <- readUserTargets verbosity extraArgs -- TODO: It'd be nice if 'cabal install' picked up the '-w' flag passed to -- 'configure' when run inside a sandbox. Right now, running -- -- $ cabal sandbox init && cabal configure -w /path/to/ghc -- && cabal build && cabal install -- -- performs the compilation twice unless you also pass -w to 'install'. -- However, this is the same behaviour that 'cabal install' has in the normal -- mode of operation, so we stick to it for consistency. let sandboxDistPref = case useSandbox of NoSandbox -> NoFlag UseSandbox sandboxDir -> Flag $ sandboxBuildDir sandboxDir distPref <- findSavedDistPref config (configDistPref configFlags `mappend` sandboxDistPref) let configFlags' = maybeForceTests installFlags' $ savedConfigureFlags config `mappend` configFlags { configDistPref = toFlag distPref } configExFlags' = defaultConfigExFlags `mappend` savedConfigureExFlags config `mappend` configExFlags installFlags' = defaultInstallFlags `mappend` savedInstallFlags config `mappend` installFlags haddockFlags' = defaultHaddockFlags `mappend` savedHaddockFlags config `mappend` haddockFlags { haddockDistPref = toFlag distPref } globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, platform, conf) <- configCompilerAux' configFlags' -- TODO: Redesign ProgramDB API to prevent such problems as #2241 in the future. conf' <- configureAllKnownPrograms verbosity conf -- If we're working inside a sandbox and the user has set the -w option, we -- may need to create a sandbox-local package DB for this compiler and add a -- timestamp record for this compiler to the timestamp file. configFlags'' <- case useSandbox of NoSandbox -> configAbsolutePaths $ configFlags' (UseSandbox sandboxDir) -> return $ setPackageDB sandboxDir comp platform configFlags' whenUsingSandbox useSandbox $ \sandboxDir -> do initPackageDBIfNeeded verbosity configFlags'' comp conf' indexFile <- tryGetIndexFilePath config maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile (compilerId comp) platform -- TODO: Passing 'SandboxPackageInfo' to install unconditionally here means -- that 'cabal install some-package' inside a sandbox will sometimes reinstall -- modified add-source deps, even if they are not among the dependencies of -- 'some-package'. This can also prevent packages that depend on older -- versions of add-source'd packages from building (see #1362). maybeWithSandboxPackageInfo verbosity configFlags'' globalFlags' comp platform conf useSandbox $ \mSandboxPkgInfo -> maybeWithSandboxDirOnSearchPath useSandbox $ withGlobalRepos verbosity globalFlags' $ \globalRepos -> install verbosity (configPackageDB' configFlags'') globalRepos comp platform conf' useSandbox mSandboxPkgInfo globalFlags' configFlags'' configExFlags' installFlags' haddockFlags' targets where -- '--run-tests' implies '--enable-tests'. maybeForceTests installFlags' configFlags' = if fromFlagOrDefault False (installRunTests installFlags') then configFlags' { configTests = toFlag True } else configFlags' testAction :: (TestFlags, BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO () testAction (testFlags, buildFlags, buildExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (testVerbosity testFlags) addConfigFlags = mempty { configTests = toFlag True } noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) buildFlags' = buildFlags { buildVerbosity = testVerbosity testFlags } checkFlags flags | fromFlagOrDefault False (configTests flags) = Nothing | otherwise = Just "Re-configuring with test suites enabled." -- reconfigure also checks if we're in a sandbox and reinstalls add-source -- deps if needed. (useSandbox, config, distPref) <- reconfigure verbosity (testDistPref testFlags) addConfigFlags [] globalFlags noAddSource (buildNumJobs buildFlags') checkFlags let setupOptions = defaultSetupScriptOptions { useDistPref = distPref } testFlags' = testFlags { testDistPref = toFlag distPref } -- the package was just configured, so the LBI must be available lbi <- getPersistBuildConfig distPref let pkgDescr = LBI.localPkgDescr lbi nameTestsOnly = LBI.foldComponent (const Nothing) (const Nothing) (\t -> if buildable (testBuildInfo t) then Just (testName t) else Nothing) (const Nothing) tests = mapMaybe nameTestsOnly $ LBI.pkgComponents pkgDescr extraArgs' | null extraArgs = tests | otherwise = extraArgs if null tests then notice verbosity "Package has no buildable test suites." else do maybeWithSandboxDirOnSearchPath useSandbox $ build verbosity config distPref buildFlags' extraArgs' maybeWithSandboxDirOnSearchPath useSandbox $ setupWrapper verbosity setupOptions Nothing Cabal.testCommand (const testFlags') extraArgs' benchmarkAction :: (BenchmarkFlags, BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO () benchmarkAction (benchmarkFlags, buildFlags, buildExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (benchmarkVerbosity benchmarkFlags) addConfigFlags = mempty { configBenchmarks = toFlag True } buildFlags' = buildFlags { buildVerbosity = benchmarkVerbosity benchmarkFlags } checkFlags flags | fromFlagOrDefault False (configBenchmarks flags) = Nothing | otherwise = Just "Re-configuring with benchmarks enabled." noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) -- reconfigure also checks if we're in a sandbox and reinstalls add-source -- deps if needed. (useSandbox, config, distPref) <- reconfigure verbosity (benchmarkDistPref benchmarkFlags) addConfigFlags [] globalFlags noAddSource (buildNumJobs buildFlags') checkFlags let setupOptions = defaultSetupScriptOptions { useDistPref = distPref } benchmarkFlags'= benchmarkFlags { benchmarkDistPref = toFlag distPref } -- the package was just configured, so the LBI must be available lbi <- getPersistBuildConfig distPref let pkgDescr = LBI.localPkgDescr lbi nameBenchsOnly = LBI.foldComponent (const Nothing) (const Nothing) (const Nothing) (\b -> if buildable (benchmarkBuildInfo b) then Just (benchmarkName b) else Nothing) benchs = mapMaybe nameBenchsOnly $ LBI.pkgComponents pkgDescr extraArgs' | null extraArgs = benchs | otherwise = extraArgs if null benchs then notice verbosity "Package has no buildable benchmarks." else do maybeWithSandboxDirOnSearchPath useSandbox $ build verbosity config distPref buildFlags' extraArgs' maybeWithSandboxDirOnSearchPath useSandbox $ setupWrapper verbosity setupOptions Nothing Cabal.benchmarkCommand (const benchmarkFlags') extraArgs' haddockAction :: HaddockFlags -> [String] -> Action haddockAction haddockFlags extraArgs globalFlags = do let verbosity = fromFlag (haddockVerbosity haddockFlags) (_useSandbox, config, distPref) <- reconfigure verbosity (haddockDistPref haddockFlags) mempty [] globalFlags DontSkipAddSourceDepsCheck NoFlag (const Nothing) let haddockFlags' = defaultHaddockFlags `mappend` savedHaddockFlags config `mappend` haddockFlags { haddockDistPref = toFlag distPref } setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref } setupWrapper verbosity setupScriptOptions Nothing haddockCommand (const haddockFlags') extraArgs when (fromFlagOrDefault False $ haddockForHackage haddockFlags) $ do pkg <- fmap LBI.localPkgDescr (getPersistBuildConfig distPref) let dest = distPref </> name <.> "tar.gz" name = display (packageId pkg) ++ "-docs" docDir = distPref </> "doc" </> "html" createTarGzFile dest docDir name notice verbosity $ "Documentation tarball created: " ++ dest cleanAction :: CleanFlags -> [String] -> Action cleanAction cleanFlags extraArgs globalFlags = do (_, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config (cleanDistPref cleanFlags) let setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref , useWin32CleanHack = True } cleanFlags' = cleanFlags { cleanDistPref = toFlag distPref } setupWrapper verbosity setupScriptOptions Nothing cleanCommand (const cleanFlags') extraArgs where verbosity = fromFlagOrDefault normal (cleanVerbosity cleanFlags) listAction :: ListFlags -> [String] -> Action listAction listFlags extraArgs globalFlags = do let verbosity = fromFlag (listVerbosity listFlags) (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let configFlags' = savedConfigureFlags config configFlags = configFlags' { configPackageDBs = configPackageDBs configFlags' `mappend` listPackageDBs listFlags } globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, _, conf) <- configCompilerAux' configFlags withGlobalRepos verbosity globalFlags' $ \globalRepos -> List.list verbosity (configPackageDB' configFlags) globalRepos comp conf listFlags extraArgs infoAction :: InfoFlags -> [String] -> Action infoAction infoFlags extraArgs globalFlags = do let verbosity = fromFlag (infoVerbosity infoFlags) targets <- readUserTargets verbosity extraArgs (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let configFlags' = savedConfigureFlags config configFlags = configFlags' { configPackageDBs = configPackageDBs configFlags' `mappend` infoPackageDBs infoFlags } globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, _, conf) <- configCompilerAuxEx configFlags withGlobalRepos verbosity globalFlags' $ \globalRepos -> List.info verbosity (configPackageDB' configFlags) globalRepos comp conf globalFlags' infoFlags targets updateAction :: Flag Verbosity -> [String] -> Action updateAction verbosityFlag extraArgs globalFlags = do unless (null extraArgs) $ die $ "'update' doesn't take any extra arguments: " ++ unwords extraArgs let verbosity = fromFlag verbosityFlag (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let globalFlags' = savedGlobalFlags config `mappend` globalFlags transport <- configureTransport verbosity (flagToMaybe (globalHttpTransport globalFlags')) withGlobalRepos verbosity globalFlags' $ \globalRepos -> do let ignoreExpiry = fromFlagOrDefault False (globalIgnoreExpiry globalFlags) update transport verbosity ignoreExpiry globalRepos upgradeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags) -> [String] -> Action upgradeAction _ _ _ = die $ "Use the 'cabal install' command instead of 'cabal upgrade'.\n" ++ "You can install the latest version of a package using 'cabal install'. " ++ "The 'cabal upgrade' command has been removed because people found it " ++ "confusing and it often led to broken packages.\n" ++ "If you want the old upgrade behaviour then use the install command " ++ "with the --upgrade-dependencies flag (but check first with --dry-run " ++ "to see what would happen). This will try to pick the latest versions " ++ "of all dependencies, rather than the usual behaviour of trying to pick " ++ "installed versions of all dependencies. If you do use " ++ "--upgrade-dependencies, it is recommended that you do not upgrade core " ++ "packages (e.g. by using appropriate --constraint= flags)." fetchAction :: FetchFlags -> [String] -> Action fetchAction fetchFlags extraArgs globalFlags = do let verbosity = fromFlag (fetchVerbosity fetchFlags) targets <- readUserTargets verbosity extraArgs config <- loadConfig verbosity (globalConfigFile globalFlags) let configFlags = savedConfigureFlags config globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, platform, conf) <- configCompilerAux' configFlags withGlobalRepos verbosity globalFlags' $ \globalRepos -> fetch verbosity (configPackageDB' configFlags) globalRepos comp platform conf globalFlags' fetchFlags targets freezeAction :: FreezeFlags -> [String] -> Action freezeAction freezeFlags _extraArgs globalFlags = do let verbosity = fromFlag (freezeVerbosity freezeFlags) (useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags let configFlags = savedConfigureFlags config globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, platform, conf) <- configCompilerAux' configFlags maybeWithSandboxPackageInfo verbosity configFlags globalFlags' comp platform conf useSandbox $ \mSandboxPkgInfo -> maybeWithSandboxDirOnSearchPath useSandbox $ withGlobalRepos verbosity globalFlags' $ \globalRepos -> freeze verbosity (configPackageDB' configFlags) globalRepos comp platform conf mSandboxPkgInfo globalFlags' freezeFlags uploadAction :: UploadFlags -> [String] -> Action uploadAction uploadFlags extraArgs globalFlags = do config <- loadConfig verbosity (globalConfigFile globalFlags) let uploadFlags' = savedUploadFlags config `mappend` uploadFlags globalFlags' = savedGlobalFlags config `mappend` globalFlags tarfiles = extraArgs when (null tarfiles && not (fromFlag (uploadDoc uploadFlags'))) $ die "the 'upload' command expects at least one .tar.gz archive." when (fromFlag (uploadCheck uploadFlags') && fromFlag (uploadDoc uploadFlags')) $ die "--check and --doc cannot be used together." checkTarFiles extraArgs maybe_password <- case uploadPasswordCmd uploadFlags' of Flag (xs:xss) -> Just . Password <$> getProgramInvocationOutput verbosity (simpleProgramInvocation xs xss) _ -> pure $ flagToMaybe $ uploadPassword uploadFlags' transport <- configureTransport verbosity (flagToMaybe (globalHttpTransport globalFlags')) if fromFlag (uploadCheck uploadFlags') then do Upload.check transport verbosity tarfiles else if fromFlag (uploadDoc uploadFlags') then do when (length tarfiles > 1) $ die "the 'upload' command can only upload documentation for one package at a time." tarfile <- maybe (generateDocTarball config) return $ listToMaybe tarfiles withGlobalRepos verbosity globalFlags' $ \globalRepos -> Upload.uploadDoc transport verbosity globalRepos (flagToMaybe $ uploadUsername uploadFlags') maybe_password tarfile else do withGlobalRepos verbosity globalFlags' $ \globalRepos -> Upload.upload transport verbosity globalRepos (flagToMaybe $ uploadUsername uploadFlags') maybe_password tarfiles where verbosity = fromFlag (uploadVerbosity uploadFlags) checkTarFiles tarfiles | not (null otherFiles) = die $ "the 'upload' command expects only .tar.gz archives: " ++ intercalate ", " otherFiles | otherwise = sequence_ [ do exists <- doesFileExist tarfile unless exists $ die $ "file not found: " ++ tarfile | tarfile <- tarfiles ] where otherFiles = filter (not . isTarGzFile) tarfiles isTarGzFile file = case splitExtension file of (file', ".gz") -> takeExtension file' == ".tar" _ -> False generateDocTarball config = do notice verbosity "No documentation tarball specified. Building documentation tarball..." haddockAction (defaultHaddockFlags { haddockForHackage = Flag True }) [] globalFlags distPref <- findSavedDistPref config NoFlag pkg <- fmap LBI.localPkgDescr (getPersistBuildConfig distPref) return $ distPref </> display (packageId pkg) ++ "-docs" <.> "tar.gz" checkAction :: Flag Verbosity -> [String] -> Action checkAction verbosityFlag extraArgs _globalFlags = do unless (null extraArgs) $ die $ "'check' doesn't take any extra arguments: " ++ unwords extraArgs allOk <- Check.check (fromFlag verbosityFlag) unless allOk exitFailure formatAction :: Flag Verbosity -> [String] -> Action formatAction verbosityFlag extraArgs _globalFlags = do let verbosity = fromFlag verbosityFlag path <- case extraArgs of [] -> do cwd <- getCurrentDirectory tryFindPackageDesc cwd (p:_) -> return p pkgDesc <- readPackageDescription verbosity path -- Uses 'writeFileAtomic' under the hood. writeGenericPackageDescription path pkgDesc uninstallAction :: Flag Verbosity -> [String] -> Action uninstallAction _verbosityFlag extraArgs _globalFlags = do let package = case extraArgs of p:_ -> p _ -> "PACKAGE_NAME" die $ "This version of 'cabal-install' does not support the 'uninstall' operation. " ++ "It will likely be implemented at some point in the future; in the meantime " ++ "you're advised to use either 'ghc-pkg unregister " ++ package ++ "' or " ++ "'cabal sandbox hc-pkg -- unregister " ++ package ++ "'." sdistAction :: (SDistFlags, SDistExFlags) -> [String] -> Action sdistAction (sdistFlags, sdistExFlags) extraArgs globalFlags = do unless (null extraArgs) $ die $ "'sdist' doesn't take any extra arguments: " ++ unwords extraArgs let verbosity = fromFlag (sDistVerbosity sdistFlags) (_, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config (sDistDistPref sdistFlags) let sdistFlags' = sdistFlags { sDistDistPref = toFlag distPref } sdist sdistFlags' sdistExFlags reportAction :: ReportFlags -> [String] -> Action reportAction reportFlags extraArgs globalFlags = do unless (null extraArgs) $ die $ "'report' doesn't take any extra arguments: " ++ unwords extraArgs let verbosity = fromFlag (reportVerbosity reportFlags) config <- loadConfig verbosity (globalConfigFile globalFlags) let globalFlags' = savedGlobalFlags config `mappend` globalFlags reportFlags' = savedReportFlags config `mappend` reportFlags withGlobalRepos verbosity globalFlags' $ \globalRepos -> Upload.report verbosity globalRepos (flagToMaybe $ reportUsername reportFlags') (flagToMaybe $ reportPassword reportFlags') runAction :: (BuildFlags, BuildExFlags) -> [String] -> Action runAction (buildFlags, buildExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags) let noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) -- reconfigure also checks if we're in a sandbox and reinstalls add-source -- deps if needed. (useSandbox, config, distPref) <- reconfigure verbosity (buildDistPref buildFlags) mempty [] globalFlags noAddSource (buildNumJobs buildFlags) (const Nothing) lbi <- getPersistBuildConfig distPref (exe, exeArgs) <- splitRunArgs verbosity lbi extraArgs maybeWithSandboxDirOnSearchPath useSandbox $ build verbosity config distPref buildFlags ["exe:" ++ exeName exe] maybeWithSandboxDirOnSearchPath useSandbox $ run verbosity lbi exe exeArgs getAction :: GetFlags -> [String] -> Action getAction getFlags extraArgs globalFlags = do let verbosity = fromFlag (getVerbosity getFlags) targets <- readUserTargets verbosity extraArgs (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let globalFlags' = savedGlobalFlags config `mappend` globalFlags withGlobalRepos verbosity (savedGlobalFlags config) $ \globalRepos -> get verbosity globalRepos globalFlags' getFlags targets unpackAction :: GetFlags -> [String] -> Action unpackAction getFlags extraArgs globalFlags = do getAction getFlags extraArgs globalFlags initAction :: InitFlags -> [String] -> Action initAction initFlags extraArgs globalFlags = do when (extraArgs /= []) $ die $ "'init' doesn't take any extra arguments: " ++ unwords extraArgs let verbosity = fromFlag (initVerbosity initFlags) (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let configFlags = savedConfigureFlags config let globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, _, conf) <- configCompilerAux' configFlags withGlobalRepos verbosity globalFlags' $ \globalRepos -> initCabal verbosity (configPackageDB' configFlags) globalRepos comp conf initFlags sandboxAction :: SandboxFlags -> [String] -> Action sandboxAction sandboxFlags extraArgs globalFlags = do let verbosity = fromFlag (sandboxVerbosity sandboxFlags) case extraArgs of -- Basic sandbox commands. ["init"] -> sandboxInit verbosity sandboxFlags globalFlags ["delete"] -> sandboxDelete verbosity sandboxFlags globalFlags ("add-source":extra) -> do when (noExtraArgs extra) $ die "The 'sandbox add-source' command expects at least one argument" sandboxAddSource verbosity extra sandboxFlags globalFlags ("delete-source":extra) -> do when (noExtraArgs extra) $ die ("The 'sandbox delete-source' command expects " ++ "at least one argument") sandboxDeleteSource verbosity extra sandboxFlags globalFlags ["list-sources"] -> sandboxListSources verbosity sandboxFlags globalFlags -- More advanced commands. ("hc-pkg":extra) -> do when (noExtraArgs extra) $ die $ "The 'sandbox hc-pkg' command expects at least one argument" sandboxHcPkg verbosity sandboxFlags globalFlags extra ["buildopts"] -> die "Not implemented!" -- Hidden commands. ["dump-pkgenv"] -> dumpPackageEnvironment verbosity sandboxFlags globalFlags -- Error handling. [] -> die $ "Please specify a subcommand (see 'help sandbox')" _ -> die $ "Unknown 'sandbox' subcommand: " ++ unwords extraArgs where noExtraArgs = (<1) . length execAction :: ExecFlags -> [String] -> Action execAction execFlags extraArgs globalFlags = do let verbosity = fromFlag (execVerbosity execFlags) (useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags let configFlags = savedConfigureFlags config (comp, platform, conf) <- getPersistOrConfigCompiler configFlags exec verbosity useSandbox comp platform conf extraArgs userConfigAction :: UserConfigFlags -> [String] -> Action userConfigAction ucflags extraArgs globalFlags = do let verbosity = fromFlag (userConfigVerbosity ucflags) case extraArgs of ("diff":_) -> mapM_ putStrLn =<< userConfigDiff globalFlags ("update":_) -> userConfigUpdate verbosity globalFlags -- Error handling. [] -> die $ "Please specify a subcommand (see 'help user-config')" _ -> die $ "Unknown 'user-config' subcommand: " ++ unwords extraArgs -- | See 'Distribution.Client.Install.withWin32SelfUpgrade' for details. -- win32SelfUpgradeAction :: Win32SelfUpgradeFlags -> [String] -> Action win32SelfUpgradeAction selfUpgradeFlags (pid:path:_extraArgs) _globalFlags = do let verbosity = fromFlag (win32SelfUpgradeVerbosity selfUpgradeFlags) Win32SelfUpgrade.deleteOldExeFile verbosity (read pid) path win32SelfUpgradeAction _ _ _ = return () -- | Used as an entry point when cabal-install needs to invoke itself -- as a setup script. This can happen e.g. when doing parallel builds. -- actAsSetupAction :: ActAsSetupFlags -> [String] -> Action actAsSetupAction actAsSetupFlags args _globalFlags = let bt = fromFlag (actAsSetupBuildType actAsSetupFlags) in case bt of Simple -> Simple.defaultMainArgs args Configure -> Simple.defaultMainWithHooksArgs Simple.autoconfUserHooks args Make -> Make.defaultMainArgs args Custom -> error "actAsSetupAction Custom" (UnknownBuildType _) -> error "actAsSetupAction UnknownBuildType" manpageAction :: [CommandSpec action] -> Flag Verbosity -> [String] -> Action manpageAction commands _ extraArgs _ = do unless (null extraArgs) $ die $ "'manpage' doesn't take any extra arguments: " ++ unwords extraArgs pname <- getProgName putStrLn (manpage pname commands)
randen/cabal
cabal-install/Main.hs
bsd-3-clause
57,895
0
24
15,538
10,567
5,500
5,067
942
13
#!/usr/bin/env stack -- stack --resolver lts-3.2 --install-ghc runghc --package hedis --package disque {-# LANGUAGE OverloadedStrings #-} import Control.Monad.IO.Class import Database.Disque main :: IO () main = do conn <- connect disqueConnectInfo runDisque conn $ do let timeout = 0 addjob "test_queue" "test data" timeout >>= liftIO . print getjob ["test_queue"] >>= liftIO . print
creichert/disque.hs
example.hs
bsd-3-clause
404
0
13
73
95
47
48
10
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Json ( JValue(..) , JAry(..) , JObj(..) ) where import Control.Arrow (second) import ApplicativeParsec import qualified Numeric as N newtype JAry a = JAry { fromJAry :: [a] } deriving (Eq, Ord, Show) newtype JObj a = JObj { fromJObj :: [(String, a)] } deriving (Eq, Ord, Show) data JValue = JString String | JNumber Double | JBool Bool | JNull | JObject (JObj JValue) | JArray (JAry JValue) deriving (Eq, Ord, Show) type JSONError = String class JSON a where toJValue :: a -> JValue fromJValue :: JValue -> Either JSONError a instance JSON JValue where toJValue = id fromJValue = Right instance JSON Bool where toJValue = JBool fromJValue (JBool b) = Right b fromJValue _ = Left "not a JSON boolean" instance JSON String where toJValue = JString fromJValue (JString s) = Right s fromJValue _ = Left "not a JSON string" doubleToJValue :: (Double -> a) -> JValue -> Either JSONError a doubleToJValue f (JNumber v) = Right (f v) doubleToJValue _ _ = Left "not a JSON number" instance JSON Int where toJValue = JNumber . realToFrac fromJValue = doubleToJValue round instance JSON Integer where toJValue = JNumber . realToFrac fromJValue = doubleToJValue round instance JSON Double where toJValue = JNumber fromJValue = doubleToJValue id whenRight :: (b -> c) -> Either a b -> Either a c whenRight _ (Left err) = Left err whenRight f (Right a) = Right (f a) mapEithers :: (a -> Either b c) -> [a] -> Either b [c] mapEithers f (x:xs) = case mapEithers f xs of Left err -> Left err Right ys -> case f x of Left err -> Left err Right y -> Right (y:ys) mapEithers _ _ = Right [] instance (JSON a) => JSON (JAry a) where toJValue = JArray . JAry . map toJValue . fromJAry fromJValue (JArray (JAry a)) = whenRight JAry (mapEithers fromJValue a) fromJValue _ = Left "not a JSON array" instance (JSON a) => JSON (JObj a) where toJValue = JObject . JObj . map (second toJValue) . fromJObj fromJValue (JObject (JObj o)) = whenRight JObj (mapEithers unwrap o) where unwrap (k, v) = whenRight ((,) k) (fromJValue v) fromJValue _ = Left "not a JSON object" p_text :: CharParser () JValue p_text = space *> text <?> "JSON text" where text = JObject <$> p_object <|> JArray <$> p_array p_series :: Char -> CharParser () a -> Char -> CharParser () [a] p_series left parser right = between (char left <* spaces) (char right) $ (parser <* spaces) `sepBy` (char ',' <* spaces) p_object :: CharParser () (JObj JValue) p_object = JObj <$> p_series '{' p_field '}' where p_field = (,) <$> (p_string <* char ':' <* spaces) <*> p_value p_array :: CharParser () (JAry JValue) p_array = JAry <$> p_series '[' p_value ']' p_value :: CharParser () JValue p_value = value <* spaces where value = JString <$> p_string <|> JNumber <$> p_number <|> JObject <$> p_object <|> JArray <$> p_array <|> JBool <$> p_bool <|> JNull <$ string "null" <?> "JSON value" p_bool :: CharParser () Bool p_bool = True <$ string "true" <|> False <$ string "false" p_number :: CharParser () Double p_number = do s <- getInput case N.readSigned N.readFloat s of [(n, s')] -> n <$ setInput s' _ -> empty p_string :: CharParser () String p_string = between (char '\"') (char '\"') (many jchar) where jchar = char '\\' *> (p_escape <|> p_unicode) <|> satisfy (`notElem` "\"\\") p_escape = choice (zipWith decode "bnfrt\\\"/" "\b\n\f\r\t\\\"/") where decode c r = r <$ char c p_unicode :: CharParser () Char p_unicode = char 'u' *> (decode <$> count 4 hexDigit) where decode x = toEnum code where ((code,_):_) = N.readHex x -- result :: JValue -- result = JObject . JObj $ [ -- ("query", JString "awkward squad haskell"), -- ("estimatedCount", JNumber 3920), -- ("moreResults", JBool True), -- ("results", JArray . JAry $ [ -- JObject . JObj $ [ -- ("title", JString "Simon Peyton Jones: papers"), -- ("snippet", JString "Tackling the awkward ..."), -- ("url", JString "http://.../marktoberdorf/") -- ]]) -- ] text = " { \"query\": \"awkward squad haskell\", \"estimatedCount\": 3920, \"moreResults\": true, \"results\": [{ \"title\": \"Simon Peyton Jones: papers\", \"snippet\": \"Tackling the awkward squad: monadic input/output ...\", \"url\": \"http://research.microsoft.com/~simonpj/papers/marktoberdorf/\" }, { \"title\": \"Haskell for C Programmers | Lambda the Ultimate\", \"snippet\": \"... the best job of all the tutorials I've read ...\", \"url\": \"http://lambda-the-ultimate.org/node/724\" } ] }" main = parse p_text "(json)" text
Danl2620/htads
src/Json.hs
bsd-3-clause
5,267
0
18
1,526
1,513
789
724
112
3
module Internal.Sparc.Default where import Foreign import Foreign.C.Types import Hapstone.Internal.Sparc import Test.QuickCheck import Test.QuickCheck.Instances -- generators for our datatypes instance Arbitrary SparcCc where arbitrary = elements [minBound..maxBound] instance Arbitrary SparcHint where arbitrary = elements [minBound..maxBound] instance Arbitrary SparcOpType where arbitrary = elements [minBound..maxBound] instance Arbitrary SparcOpMemStruct where arbitrary = SparcOpMemStruct <$> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary CsSparcOp where arbitrary = oneof [ Reg <$> arbitrary , Imm <$> arbitrary , Mem <$> arbitrary , pure Undefined ] instance Arbitrary CsSparc where arbitrary = CsSparc <$> arbitrary <*> arbitrary <*> (take 4 <$> arbitrary) instance Arbitrary SparcReg where arbitrary = elements [minBound..maxBound] instance Arbitrary SparcInsn where arbitrary = elements [minBound..maxBound] instance Arbitrary SparcInsnGroup where arbitrary = elements [minBound..maxBound]
ibabushkin/hapstone
test/Internal/Sparc/Default.hs
bsd-3-clause
1,097
0
9
203
263
143
120
28
0
-- | Provide a Buck/Bazel style UI. module Development.Shake.Internal.CompactUI( compactUI ) where import Development.Shake.Internal.CmdOption import Development.Shake.Internal.Options import Development.Shake.Internal.Progress import System.Time.Extra import General.Extra import Control.Exception import General.Thread import General.EscCodes import Data.IORef.Extra import Control.Monad.Extra data S = S {sOutput :: [String] -- ^ Messages that haven't yet been printed, in reverse. ,sProgress :: String -- ^ Last progress message. ,sTraces :: [Maybe (String, String, Seconds)] -- ^ the traced items, in the order we display them ,sUnwind :: Int -- ^ Number of lines we used last time around } emptyS = S [] "Starting..." [] 0 addOutput pri msg s = s{sOutput = msg : sOutput s} addProgress x s = s{sProgress = x} addTrace key msg start time s | start = s{sTraces = insert (key,msg,time) $ sTraces s} | otherwise = s{sTraces = remove (\(a,b,_) -> a == key && b == msg) $ sTraces s} where insert v (Nothing:xs) = Just v:xs insert v (x:xs) = x : insert v xs insert v [] = [Just v] remove f (Just x:xs) | f x = Nothing:xs remove f (x:xs) = x : remove f xs remove f [] = [] display :: Seconds -> S -> (S, String) display time s = (s{sOutput=[], sUnwind=length post}, escCursorUp (sUnwind s) ++ unlines (map pad $ pre ++ post)) where pre = sOutput s post = "" : (escForeground Green ++ "Status: " ++ sProgress s ++ escNormal) : map f (sTraces s) pad x = x ++ escClearLine f Nothing = " *" f (Just (k,m,t)) = " * " ++ k ++ " (" ++ g (time - t) m ++ ")" g i m | showDurationSecs i == "0s" = m | i < 10 = s | otherwise = escForeground (if i > 20 then Red else Yellow) ++ s ++ escNormal where s = m ++ " " ++ showDurationSecs i -- | Run a compact UI, with the ShakeOptions modifier, combined with compactUI :: ShakeOptions -> IO (ShakeOptions, IO ()) compactUI opts = do unlessM checkEscCodes $ putStrLn "Your terminal does not appear to support escape codes, --compact mode may not work" ref <- newIORef emptyS let tweak = atomicModifyIORef_ ref time <- offsetTime opts <- pure $ opts {shakeTrace = \a b c -> do t <- time; tweak (addTrace a b c t) ,shakeOutput = \a b -> tweak (addOutput a b) ,shakeProgress = \x -> void $ progressDisplay 1 (tweak . addProgress) x `withThreadsBoth` shakeProgress opts x ,shakeCommandOptions = [EchoStdout False, EchoStderr False] ++ shakeCommandOptions opts ,shakeVerbosity = Error } let tick = do t <- time; mask_ $ putStr =<< atomicModifyIORef ref (display t) pure (opts, forever (tick >> sleep 0.4) `finally` tick)
ndmitchell/shake
src/Development/Shake/Internal/CompactUI.hs
bsd-3-clause
2,824
0
16
730
1,031
542
489
55
5
{-# LANGUAGE StandaloneDeriving, GeneralizedNewtypeDeriving, OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.Hangouts.SQLite (dumpToSQLite, extendSQLite, initSQLite) where import Data.Hangouts import Database.SQLite.Simple import Database.SQLite.Simple.ToField import qualified Data.Map.Strict as M import Control.Monad deriving instance ToField UID instance ToField Content where toField = toField . textOnly -- | Initialize an SQLite database for storing Hangouts logs. initSQLite :: FilePath -> IO () initSQLite db = withConnection db $ \sqlite -> do execute_ sqlite "DROP TABLE IF EXISTS messages;" execute_ sqlite "DROP TABLE IF EXISTS people;" execute_ sqlite "DROP TABLE IF EXISTS conversations;" createTables sqlite -- | Dump zero or more logs into a SQLite database. -- The resulting database will have three tables: @people@, @conversations@, -- and @messages@. -- @people@ maps user identifiers (@id@) to names (@name@). -- -- @conversations@ maps conversation IDs to Hangouts conversation IDs. -- (Fields called @id@ and @hangouts_id@)) -- -- @messages@ contains all messages together with the user identifier of -- whoever wrote them. (Fields called @sender@ and @text@.) dumpToSQLite :: ToField a => FilePath -> [Log a] -> IO () dumpToSQLite db logs = initSQLite db >> extendSQLite db logs -- | Extend a previous SQLite dump with more logs. extendSQLite :: ToField a => FilePath -> [Log a] -> IO () extendSQLite db logs = withConnection db $ \sqlite -> mapM_ (insertLog sqlite) logs -- | Create the people and text tables. createTables :: Connection -> IO () createTables sqlite = do execute_ sqlite userTable execute_ sqlite convTable execute_ sqlite textTable -- | Insert a whole 'Log' into a SQLite table insertLog :: ToField a => Connection -> Log a -> IO () insertLog sqlite l = withTransaction sqlite $ do mapM_ insertName (M.toList $ logNames l) forM_ (M.toList $ logConversations l) $ \(cid, msgs) -> do insertConv cid cid' <- lastInsertRowId sqlite mapM_ (insertText cid') msgs where insertConv cid = execute sqlite "INSERT INTO conversations (hangouts_id) VALUES (?)" [toField cid] insertName (uid, name) = execute sqlite "INSERT INTO people VALUES (?,?)" [toField uid, toField name] insertText cid (Message uid ts text)= execute sqlite "INSERT INTO messages VALUES (?,?,?,?)" [toField uid, toField cid, toField ts, toField text] textTable :: Query textTable = "CREATE TABLE `messages`\ \(`sender` INTEGER NOT NULL,\ \ `conversation` INTEGER NOT NULL,\ \ `timestamp` INTEGER NOT NULL,\ \ `text` TEXT NOT NULL,\ \ FOREIGN KEY(sender) REFERENCES people(id),\ \ FOREIGN KEY(conversation) REFERENCES conversations(id));" userTable :: Query userTable = "CREATE TABLE `people`\ \(`id` INTEGER NOT NULL PRIMARY KEY,\ \`name` TEXT NOT NULL);" convTable :: Query convTable = "CREATE TABLE `conversations`\ \(`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\ \`hangouts_id` TEXT NOT NULL);"
valderman/hangouts-logbaker
Data/Hangouts/SQLite.hs
bsd-3-clause
3,242
0
14
737
583
297
286
51
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.SES.GetSendQuota -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns the user\'s current sending limits. -- -- This action is throttled at one request per second. -- -- /See:/ <http://docs.aws.amazon.com/ses/latest/APIReference/API_GetSendQuota.html AWS API Reference> for GetSendQuota. module Network.AWS.SES.GetSendQuota ( -- * Creating a Request getSendQuota , GetSendQuota -- * Destructuring the Response , getSendQuotaResponse , GetSendQuotaResponse -- * Response Lenses , gsqrsMaxSendRate , gsqrsSentLast24Hours , gsqrsMax24HourSend , gsqrsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.SES.Types import Network.AWS.SES.Types.Product -- | /See:/ 'getSendQuota' smart constructor. data GetSendQuota = GetSendQuota' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetSendQuota' with the minimum fields required to make a request. -- getSendQuota :: GetSendQuota getSendQuota = GetSendQuota' instance AWSRequest GetSendQuota where type Rs GetSendQuota = GetSendQuotaResponse request = postQuery sES response = receiveXMLWrapper "GetSendQuotaResult" (\ s h x -> GetSendQuotaResponse' <$> (x .@? "MaxSendRate") <*> (x .@? "SentLast24Hours") <*> (x .@? "Max24HourSend") <*> (pure (fromEnum s))) instance ToHeaders GetSendQuota where toHeaders = const mempty instance ToPath GetSendQuota where toPath = const "/" instance ToQuery GetSendQuota where toQuery = const (mconcat ["Action" =: ("GetSendQuota" :: ByteString), "Version" =: ("2010-12-01" :: ByteString)]) -- | Represents the user\'s current activity limits returned from a -- successful 'GetSendQuota' request. -- -- /See:/ 'getSendQuotaResponse' smart constructor. data GetSendQuotaResponse = GetSendQuotaResponse' { _gsqrsMaxSendRate :: !(Maybe Double) , _gsqrsSentLast24Hours :: !(Maybe Double) , _gsqrsMax24HourSend :: !(Maybe Double) , _gsqrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetSendQuotaResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gsqrsMaxSendRate' -- -- * 'gsqrsSentLast24Hours' -- -- * 'gsqrsMax24HourSend' -- -- * 'gsqrsResponseStatus' getSendQuotaResponse :: Int -- ^ 'gsqrsResponseStatus' -> GetSendQuotaResponse getSendQuotaResponse pResponseStatus_ = GetSendQuotaResponse' { _gsqrsMaxSendRate = Nothing , _gsqrsSentLast24Hours = Nothing , _gsqrsMax24HourSend = Nothing , _gsqrsResponseStatus = pResponseStatus_ } -- | The maximum number of emails that Amazon SES can accept from the user\'s -- account per second. -- -- The rate at which Amazon SES accepts the user\'s messages might be less -- than the maximum send rate. gsqrsMaxSendRate :: Lens' GetSendQuotaResponse (Maybe Double) gsqrsMaxSendRate = lens _gsqrsMaxSendRate (\ s a -> s{_gsqrsMaxSendRate = a}); -- | The number of emails sent during the previous 24 hours. gsqrsSentLast24Hours :: Lens' GetSendQuotaResponse (Maybe Double) gsqrsSentLast24Hours = lens _gsqrsSentLast24Hours (\ s a -> s{_gsqrsSentLast24Hours = a}); -- | The maximum number of emails the user is allowed to send in a 24-hour -- interval. A value of -1 signifies an unlimited quota. gsqrsMax24HourSend :: Lens' GetSendQuotaResponse (Maybe Double) gsqrsMax24HourSend = lens _gsqrsMax24HourSend (\ s a -> s{_gsqrsMax24HourSend = a}); -- | The response status code. gsqrsResponseStatus :: Lens' GetSendQuotaResponse Int gsqrsResponseStatus = lens _gsqrsResponseStatus (\ s a -> s{_gsqrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ses/gen/Network/AWS/SES/GetSendQuota.hs
mpl-2.0
4,575
0
14
964
639
384
255
80
1
module Language.K3.TypeSystem.Data.Result where import Data.Map import Data.Monoid import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Type import Language.K3.TypeSystem.Data.Types import Language.K3.TypeSystem.Data.ConstraintSet import Language.K3.TypeSystem.Data.Environments.Type -- |Describes a typechecking result. Each value in the record is a @Maybe@ -- value so that a partial @TypecheckResult@ can be generated even if an error -- occurs during typechecking. @tcAEnv@ is the decided alias environment; -- @tcEnv@ is the decided type environment. @tcExprTypes@ is a mapping from -- subexpression UID to a type and representative constraint set. data TypecheckResult = TypecheckResult { tcAEnv :: Maybe TAliasEnv , tcEnv :: Maybe TNormEnv , tcREnv :: Maybe TGlobalQuantEnv , tcExprTypes :: Maybe (Map UID AnyTVar, ConstraintSet) , tcExprBounds :: Maybe (Map UID (K3 Type, K3 Type)) } deriving (Eq, Show) instance Monoid TypecheckResult where mempty = TypecheckResult Nothing Nothing Nothing Nothing Nothing mappend (TypecheckResult a b c d e) (TypecheckResult a' b' c' d' e') = TypecheckResult (a `mappend` a') (b `mappend` b') (c `mappend` c') (d `mappend` d') (e `mappend` e')
DaMSL/K3
src/Language/K3/TypeSystem/Data/Result.hs
apache-2.0
1,290
0
13
227
284
170
114
22
0
{-# LANGUAGE CPP, NamedFieldPuns, NondecreasingIndentation #-} {-# OPTIONS_GHC -fno-cse #-} -- -fno-cse is needed for GLOBAL_VAR's to behave properly ----------------------------------------------------------------------------- -- -- GHC Driver -- -- (c) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module DriverPipeline ( -- Run a series of compilation steps in a pipeline, for a -- collection of source files. oneShot, compileFile, -- Interfaces for the batch-mode driver linkBinary, -- Interfaces for the compilation manager (interpreted/batch-mode) preprocess, compileOne, compileOne', link, -- Exports for hooks to override runPhase and link PhasePlus(..), CompPipeline(..), PipeEnv(..), PipeState(..), phaseOutputFilename, getOutputFilename, getPipeState, getPipeEnv, hscPostBackendPhase, getLocation, setModLocation, setDynFlags, runPhase, exeFileName, mkExtraObjToLinkIntoBinary, mkNoteObjsToLinkIntoBinary, maybeCreateManifest, linkingNeeded, checkLinkInfo, writeInterfaceOnlyMode ) where #include "HsVersions.h" import PipelineMonad import Packages import HeaderInfo import DriverPhases import SysTools import Elf import HscMain import Finder import HscTypes hiding ( Hsc ) import Outputable import Module import ErrUtils import DynFlags import Config import Panic import Util import StringBuffer ( hGetStringBuffer ) import BasicTypes ( SuccessFlag(..) ) import Maybes ( expectJust ) import SrcLoc import LlvmCodeGen ( llvmFixupAsm ) import MonadUtils import Platform import TcRnTypes import Hooks import qualified GHC.LanguageExtensions as LangExt import Exception import System.Directory import System.FilePath import System.IO import Control.Monad import Data.List ( isSuffixOf ) import Data.Maybe import Data.Version -- --------------------------------------------------------------------------- -- Pre-process -- | Just preprocess a file, put the result in a temp. file (used by the -- compilation manager during the summary phase). -- -- We return the augmented DynFlags, because they contain the result -- of slurping in the OPTIONS pragmas preprocess :: HscEnv -> (FilePath, Maybe Phase) -- ^ filename and starting phase -> IO (DynFlags, FilePath) preprocess hsc_env (filename, mb_phase) = ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename) runPipeline anyHsc hsc_env (filename, fmap RealPhase mb_phase) Nothing Temporary Nothing{-no ModLocation-} Nothing{-no stub-} -- --------------------------------------------------------------------------- -- | Compile -- -- Compile a single module, under the control of the compilation manager. -- -- This is the interface between the compilation manager and the -- compiler proper (hsc), where we deal with tedious details like -- reading the OPTIONS pragma from the source file, converting the -- C or assembly that GHC produces into an object file, and compiling -- FFI stub files. -- -- NB. No old interface can also mean that the source has changed. compileOne :: HscEnv -> ModSummary -- ^ summary for module being compiled -> Int -- ^ module N ... -> Int -- ^ ... of M -> Maybe ModIface -- ^ old interface, if we have one -> Maybe Linkable -- ^ old linkable, if we have one -> SourceModified -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful compileOne = compileOne' Nothing (Just batchMsg) compileOne' :: Maybe TcGblEnv -> Maybe Messager -> HscEnv -> ModSummary -- ^ summary for module being compiled -> Int -- ^ module N ... -> Int -- ^ ... of M -> Maybe ModIface -- ^ old interface, if we have one -> Maybe Linkable -- ^ old linkable, if we have one -> SourceModified -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful compileOne' m_tc_result mHscMessage hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable source_modified0 = do debugTraceMsg dflags1 2 (text "compile: input file" <+> text input_fnpp) (status, hmi0) <- hscIncrementalCompile always_do_basic_recompilation_check m_tc_result mHscMessage hsc_env summary source_modified mb_old_iface (mod_index, nmods) let flags = hsc_dflags hsc_env0 in do unless (gopt Opt_KeepHiFiles flags) $ addFilesToClean flags [ml_hi_file $ ms_location summary] unless (gopt Opt_KeepOFiles flags) $ addFilesToClean flags [ml_obj_file $ ms_location summary] case (status, hsc_lang) of (HscUpToDate, _) -> -- TODO recomp014 triggers this assert. What's going on?! -- ASSERT( isJust maybe_old_linkable || isNoLink (ghcLink dflags) ) return hmi0 { hm_linkable = maybe_old_linkable } (HscNotGeneratingCode, HscNothing) -> let mb_linkable = if isHsBootOrSig src_flavour then Nothing -- TODO: Questionable. else Just (LM (ms_hs_date summary) this_mod []) in return hmi0 { hm_linkable = mb_linkable } (HscNotGeneratingCode, _) -> panic "compileOne HscNotGeneratingCode" (_, HscNothing) -> panic "compileOne HscNothing" (HscUpdateBoot, HscInterpreted) -> do return hmi0 (HscUpdateBoot, _) -> do touchObjectFile dflags object_filename return hmi0 (HscUpdateSig, HscInterpreted) -> let linkable = LM (ms_hs_date summary) this_mod [] in return hmi0 { hm_linkable = Just linkable } (HscUpdateSig, _) -> do output_fn <- getOutputFilename next_phase Temporary basename dflags next_phase (Just location) -- #10660: Use the pipeline instead of calling -- compileEmptyStub directly, so -dynamic-too gets -- handled properly _ <- runPipeline StopLn hsc_env (output_fn, Just (HscOut src_flavour mod_name HscUpdateSig)) (Just basename) Persistent (Just location) Nothing o_time <- getModificationUTCTime object_filename let linkable = LM o_time this_mod [DotO object_filename] return hmi0 { hm_linkable = Just linkable } (HscRecomp cgguts summary, HscInterpreted) -> do (hasStub, comp_bc) <- hscInteractive hsc_env cgguts summary stub_o <- case hasStub of Nothing -> return [] Just stub_c -> do stub_o <- compileStub hsc_env stub_c return [DotO stub_o] let hs_unlinked = [BCOs comp_bc] unlinked_time = ms_hs_date summary -- Why do we use the timestamp of the source file here, -- rather than the current time? This works better in -- the case where the local clock is out of sync -- with the filesystem's clock. It's just as accurate: -- if the source is modified, then the linkable will -- be out of date. let linkable = LM unlinked_time (ms_mod summary) (hs_unlinked ++ stub_o) return hmi0 { hm_linkable = Just linkable } (HscRecomp cgguts summary, _) -> do output_fn <- getOutputFilename next_phase Temporary basename dflags next_phase (Just location) -- We're in --make mode: finish the compilation pipeline. _ <- runPipeline StopLn hsc_env (output_fn, Just (HscOut src_flavour mod_name (HscRecomp cgguts summary))) (Just basename) Persistent (Just location) Nothing -- The object filename comes from the ModLocation o_time <- getModificationUTCTime object_filename let linkable = LM o_time this_mod [DotO object_filename] return hmi0 { hm_linkable = Just linkable } where dflags0 = ms_hspp_opts summary this_mod = ms_mod summary location = ms_location summary input_fn = expectJust "compile:hs" (ml_hs_file location) input_fnpp = ms_hspp_file summary mod_graph = hsc_mod_graph hsc_env0 needsTH = any (xopt LangExt.TemplateHaskell . ms_hspp_opts) mod_graph needsQQ = any (xopt LangExt.QuasiQuotes . ms_hspp_opts) mod_graph needsLinker = needsTH || needsQQ isDynWay = any (== WayDyn) (ways dflags0) isProfWay = any (== WayProf) (ways dflags0) internalInterpreter = not (gopt Opt_ExternalInterpreter dflags0) src_flavour = ms_hsc_src summary mod_name = ms_mod_name summary next_phase = hscPostBackendPhase dflags src_flavour hsc_lang object_filename = ml_obj_file location -- #8180 - when using TemplateHaskell, switch on -dynamic-too so -- the linker can correctly load the object files. This isn't necessary -- when using -fexternal-interpreter. dflags1 = if needsLinker && dynamicGhc && internalInterpreter && not isDynWay && not isProfWay then gopt_set dflags0 Opt_BuildDynamicToo else dflags0 basename = dropExtension input_fn -- We add the directory in which the .hs files resides) to the import -- path. This is needed when we try to compile the .hc file later, if it -- imports a _stub.h file that we created here. current_dir = takeDirectory basename old_paths = includePaths dflags1 dflags = dflags1 { includePaths = current_dir : old_paths } hsc_env = hsc_env0 {hsc_dflags = dflags} -- Figure out what lang we're generating hsc_lang = hscTarget dflags -- -fforce-recomp should also work with --make force_recomp = gopt Opt_ForceRecomp dflags source_modified | force_recomp = SourceModified | otherwise = source_modified0 always_do_basic_recompilation_check = case hsc_lang of HscInterpreted -> True _ -> False ----------------------------------------------------------------------------- -- stub .h and .c files (for foreign export support) -- The _stub.c file is derived from the haskell source file, possibly taking -- into account the -stubdir option. -- -- The object file created by compiling the _stub.c file is put into a -- temporary file, which will be later combined with the main .o file -- (see the MergeStubs phase). compileStub :: HscEnv -> FilePath -> IO FilePath compileStub hsc_env stub_c = do (_, stub_o) <- runPipeline StopLn hsc_env (stub_c,Nothing) Nothing Temporary Nothing{-no ModLocation-} Nothing return stub_o compileEmptyStub :: DynFlags -> HscEnv -> FilePath -> ModLocation -> ModuleName -> IO () compileEmptyStub dflags hsc_env basename location mod_name = do -- To maintain the invariant that every Haskell file -- compiles to object code, we make an empty (but -- valid) stub object file for signatures. However, -- we make sure this object file has a unique symbol, -- so that ranlib on OS X doesn't complain, see -- http://ghc.haskell.org/trac/ghc/ticket/12673 -- and https://github.com/haskell/cabal/issues/2257 empty_stub <- newTempName dflags "c" let src = text "int" <+> ppr (mkModule (thisPackage dflags) mod_name) <+> text "= 0;" writeFile empty_stub (showSDoc dflags (pprCode CStyle src)) _ <- runPipeline StopLn hsc_env (empty_stub, Nothing) (Just basename) Persistent (Just location) Nothing return () -- --------------------------------------------------------------------------- -- Link link :: GhcLink -- interactive or batch -> DynFlags -- dynamic flags -> Bool -- attempt linking in batch mode? -> HomePackageTable -- what to link -> IO SuccessFlag -- For the moment, in the batch linker, we don't bother to tell doLink -- which packages to link -- it just tries all that are available. -- batch_attempt_linking should only be *looked at* in batch mode. It -- should only be True if the upsweep was successful and someone -- exports main, i.e., we have good reason to believe that linking -- will succeed. link ghcLink dflags = lookupHook linkHook l dflags ghcLink dflags where l LinkInMemory _ _ _ = if cGhcWithInterpreter == "YES" then -- Not Linking...(demand linker will do the job) return Succeeded else panicBadLink LinkInMemory l NoLink _ _ _ = return Succeeded l LinkBinary dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt l LinkStaticLib dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt l LinkDynLib dflags batch_attempt_linking hpt = link' dflags batch_attempt_linking hpt panicBadLink :: GhcLink -> a panicBadLink other = panic ("link: GHC not built to link this way: " ++ show other) link' :: DynFlags -- dynamic flags -> Bool -- attempt linking in batch mode? -> HomePackageTable -- what to link -> IO SuccessFlag link' dflags batch_attempt_linking hpt | batch_attempt_linking = do let staticLink = case ghcLink dflags of LinkStaticLib -> True _ -> platformBinariesAreStaticLibs (targetPlatform dflags) home_mod_infos = eltsHpt hpt -- the packages we depend on pkg_deps = concatMap (map fst . dep_pkgs . mi_deps . hm_iface) home_mod_infos -- the linkables to link linkables = map (expectJust "link".hm_linkable) home_mod_infos debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables)) -- check for the -no-link flag if isNoLink (ghcLink dflags) then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).") return Succeeded else do let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us) obj_files = concatMap getOfiles linkables exe_file = exeFileName staticLink dflags linking_needed <- linkingNeeded dflags staticLink linkables pkg_deps if not (gopt Opt_ForceRecomp dflags) && not linking_needed then do debugTraceMsg dflags 2 (text exe_file <+> text "is up to date, linking not required.") return Succeeded else do compilationProgressMsg dflags ("Linking " ++ exe_file ++ " ...") -- Don't showPass in Batch mode; doLink will do that for us. let link = case ghcLink dflags of LinkBinary -> linkBinary LinkStaticLib -> linkStaticLibCheck LinkDynLib -> linkDynLibCheck other -> panicBadLink other link dflags obj_files pkg_deps debugTraceMsg dflags 3 (text "link: done") -- linkBinary only returns if it succeeds return Succeeded | otherwise = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$ text " Main.main not exported; not linking.") return Succeeded linkingNeeded :: DynFlags -> Bool -> [Linkable] -> [InstalledUnitId] -> IO Bool linkingNeeded dflags staticLink linkables pkg_deps = do -- if the modification time on the executable is later than the -- modification times on all of the objects and libraries, then omit -- linking (unless the -fforce-recomp flag was given). let exe_file = exeFileName staticLink dflags e_exe_time <- tryIO $ getModificationUTCTime exe_file case e_exe_time of Left _ -> return True Right t -> do -- first check object files and extra_ld_inputs let extra_ld_inputs = [ f | FileOption _ f <- ldInputs dflags ] e_extra_times <- mapM (tryIO . getModificationUTCTime) extra_ld_inputs let (errs,extra_times) = splitEithers e_extra_times let obj_times = map linkableTime linkables ++ extra_times if not (null errs) || any (t <) obj_times then return True else do -- next, check libraries. XXX this only checks Haskell libraries, -- not extra_libraries or -l things from the command line. let pkg_hslibs = [ (collectLibraryPaths dflags [c], lib) | Just c <- map (lookupInstalledPackage dflags) pkg_deps, lib <- packageHsLibs dflags c ] pkg_libfiles <- mapM (uncurry (findHSLib dflags)) pkg_hslibs if any isNothing pkg_libfiles then return True else do e_lib_times <- mapM (tryIO . getModificationUTCTime) (catMaybes pkg_libfiles) let (lib_errs,lib_times) = splitEithers e_lib_times if not (null lib_errs) || any (t <) lib_times then return True else checkLinkInfo dflags pkg_deps exe_file -- Returns 'False' if it was, and we can avoid linking, because the -- previous binary was linked with "the same options". checkLinkInfo :: DynFlags -> [InstalledUnitId] -> FilePath -> IO Bool checkLinkInfo dflags pkg_deps exe_file | not (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags))) -- ToDo: Windows and OS X do not use the ELF binary format, so -- readelf does not work there. We need to find another way to do -- this. = return False -- conservatively we should return True, but not -- linking in this case was the behaviour for a long -- time so we leave it as-is. | otherwise = do link_info <- getLinkInfo dflags pkg_deps debugTraceMsg dflags 3 $ text ("Link info: " ++ link_info) m_exe_link_info <- readElfNoteAsString dflags exe_file ghcLinkInfoSectionName ghcLinkInfoNoteName let sameLinkInfo = (Just link_info == m_exe_link_info) debugTraceMsg dflags 3 $ case m_exe_link_info of Nothing -> text "Exe link info: Not found" Just s | sameLinkInfo -> text ("Exe link info is the same") | otherwise -> text ("Exe link info is different: " ++ s) return (not sameLinkInfo) platformSupportsSavingLinkOpts :: OS -> Bool platformSupportsSavingLinkOpts os | os == OSSolaris2 = False -- see #5382 | otherwise = osElfTarget os -- See Note [LinkInfo section] ghcLinkInfoSectionName :: String ghcLinkInfoSectionName = ".debug-ghc-link-info" -- if we use the ".debug" prefix, then strip will strip it by default -- Identifier for the note (see Note [LinkInfo section]) ghcLinkInfoNoteName :: String ghcLinkInfoNoteName = "GHC link info" findHSLib :: DynFlags -> [String] -> String -> IO (Maybe FilePath) findHSLib dflags dirs lib = do let batch_lib_file = if WayDyn `notElem` ways dflags then "lib" ++ lib <.> "a" else mkSOName (targetPlatform dflags) lib found <- filterM doesFileExist (map (</> batch_lib_file) dirs) case found of [] -> return Nothing (x:_) -> return (Just x) -- ----------------------------------------------------------------------------- -- Compile files in one-shot mode. oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO () oneShot hsc_env stop_phase srcs = do o_files <- mapM (compileFile hsc_env stop_phase) srcs doLink (hsc_dflags hsc_env) stop_phase o_files compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath compileFile hsc_env stop_phase (src, mb_phase) = do exists <- doesFileExist src when (not exists) $ throwGhcExceptionIO (CmdLineError ("does not exist: " ++ src)) let dflags = hsc_dflags hsc_env split = gopt Opt_SplitObjs dflags mb_o_file = outputFile dflags ghc_link = ghcLink dflags -- Set by -c or -no-link -- When linking, the -o argument refers to the linker's output. -- otherwise, we use it as the name for the pipeline's output. output -- If we are dong -fno-code, then act as if the output is -- 'Temporary'. This stops GHC trying to copy files to their -- final location. | HscNothing <- hscTarget dflags = Temporary | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent -- -o foo applies to linker | isJust mb_o_file = SpecificFile -- -o foo applies to the file we are compiling now | otherwise = Persistent stop_phase' = case stop_phase of As _ | split -> SplitAs _ -> stop_phase ( _, out_file) <- runPipeline stop_phase' hsc_env (src, fmap RealPhase mb_phase) Nothing output Nothing{-no ModLocation-} Nothing return out_file doLink :: DynFlags -> Phase -> [FilePath] -> IO () doLink dflags stop_phase o_files | not (isStopLn stop_phase) = return () -- We stopped before the linking phase | otherwise = case ghcLink dflags of NoLink -> return () LinkBinary -> linkBinary dflags o_files [] LinkStaticLib -> linkStaticLibCheck dflags o_files [] LinkDynLib -> linkDynLibCheck dflags o_files [] other -> panicBadLink other -- --------------------------------------------------------------------------- -- | Run a compilation pipeline, consisting of multiple phases. -- -- This is the interface to the compilation pipeline, which runs -- a series of compilation steps on a single source file, specifying -- at which stage to stop. -- -- The DynFlags can be modified by phases in the pipeline (eg. by -- OPTIONS_GHC pragmas), and the changes affect later phases in the -- pipeline. runPipeline :: Phase -- ^ When to stop -> HscEnv -- ^ Compilation environment -> (FilePath,Maybe PhasePlus) -- ^ Input filename (and maybe -x suffix) -> Maybe FilePath -- ^ original basename (if different from ^^^) -> PipelineOutput -- ^ Output filename -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module -> Maybe FilePath -- ^ stub object, if we have one -> IO (DynFlags, FilePath) -- ^ (final flags, output filename) runPipeline stop_phase hsc_env0 (input_fn, mb_phase) mb_basename output maybe_loc maybe_stub_o = do let dflags0 = hsc_dflags hsc_env0 -- Decide where dump files should go based on the pipeline output dflags = dflags0 { dumpPrefix = Just (basename ++ ".") } hsc_env = hsc_env0 {hsc_dflags = dflags} (input_basename, suffix) = splitExtension input_fn suffix' = drop 1 suffix -- strip off the . basename | Just b <- mb_basename = b | otherwise = input_basename -- If we were given a -x flag, then use that phase to start from start_phase = fromMaybe (RealPhase (startPhase suffix')) mb_phase isHaskell (RealPhase (Unlit _)) = True isHaskell (RealPhase (Cpp _)) = True isHaskell (RealPhase (HsPp _)) = True isHaskell (RealPhase (Hsc _)) = True isHaskell (HscOut {}) = True isHaskell _ = False isHaskellishFile = isHaskell start_phase env = PipeEnv{ stop_phase, src_filename = input_fn, src_basename = basename, src_suffix = suffix', output_spec = output } -- We want to catch cases of "you can't get there from here" before -- we start the pipeline, because otherwise it will just run off the -- end. let happensBefore' = happensBefore dflags case start_phase of RealPhase start_phase' -> -- See Note [Partial ordering on phases] -- Not the same as: (stop_phase `happensBefore` start_phase') when (not (start_phase' `happensBefore'` stop_phase || start_phase' `eqPhase` stop_phase)) $ throwGhcExceptionIO (UsageError ("cannot compile this file to desired target: " ++ input_fn)) HscOut {} -> return () debugTraceMsg dflags 4 (text "Running the pipeline") r <- runPipeline' start_phase hsc_env env input_fn maybe_loc maybe_stub_o -- If we are compiling a Haskell module, and doing -- -dynamic-too, but couldn't do the -dynamic-too fast -- path, then rerun the pipeline for the dyn way let dflags = hsc_dflags hsc_env -- NB: Currently disabled on Windows (ref #7134, #8228, and #5987) when (not $ platformOS (targetPlatform dflags) == OSMinGW32) $ do when isHaskellishFile $ whenCannotGenerateDynamicToo dflags $ do debugTraceMsg dflags 4 (text "Running the pipeline again for -dynamic-too") let dflags' = dynamicTooMkDynamicDynFlags dflags hsc_env' <- newHscEnv dflags' _ <- runPipeline' start_phase hsc_env' env input_fn maybe_loc maybe_stub_o return () return r runPipeline' :: PhasePlus -- ^ When to start -> HscEnv -- ^ Compilation environment -> PipeEnv -> FilePath -- ^ Input filename -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module -> Maybe FilePath -- ^ stub object, if we have one -> IO (DynFlags, FilePath) -- ^ (final flags, output filename) runPipeline' start_phase hsc_env env input_fn maybe_loc maybe_stub_o = do -- Execute the pipeline... let state = PipeState{ hsc_env, maybe_loc, maybe_stub_o = maybe_stub_o } evalP (pipeLoop start_phase input_fn) env state -- --------------------------------------------------------------------------- -- outer pipeline loop -- | pipeLoop runs phases until we reach the stop phase pipeLoop :: PhasePlus -> FilePath -> CompPipeline (DynFlags, FilePath) pipeLoop phase input_fn = do env <- getPipeEnv dflags <- getDynFlags -- See Note [Partial ordering on phases] let happensBefore' = happensBefore dflags stopPhase = stop_phase env case phase of RealPhase realPhase | realPhase `eqPhase` stopPhase -- All done -> -- Sometimes, a compilation phase doesn't actually generate any output -- (eg. the CPP phase when -fcpp is not turned on). If we end on this -- stage, but we wanted to keep the output, then we have to explicitly -- copy the file, remembering to prepend a {-# LINE #-} pragma so that -- further compilation stages can tell what the original filename was. case output_spec env of Temporary -> return (dflags, input_fn) output -> do pst <- getPipeState final_fn <- liftIO $ getOutputFilename stopPhase output (src_basename env) dflags stopPhase (maybe_loc pst) when (final_fn /= input_fn) $ do let msg = ("Copying `" ++ input_fn ++"' to `" ++ final_fn ++ "'") line_prag = Just ("{-# LINE 1 \"" ++ src_filename env ++ "\" #-}\n") liftIO $ copyWithHeader dflags msg line_prag input_fn final_fn return (dflags, final_fn) | not (realPhase `happensBefore'` stopPhase) -- Something has gone wrong. We'll try to cover all the cases when -- this could happen, so if we reach here it is a panic. -- eg. it might happen if the -C flag is used on a source file that -- has {-# OPTIONS -fasm #-}. -> panic ("pipeLoop: at phase " ++ show realPhase ++ " but I wanted to stop at phase " ++ show stopPhase) _ -> do liftIO $ debugTraceMsg dflags 4 (text "Running phase" <+> ppr phase) (next_phase, output_fn) <- runHookedPhase phase input_fn dflags r <- pipeLoop next_phase output_fn case phase of HscOut {} -> whenGeneratingDynamicToo dflags $ do setDynFlags $ dynamicTooMkDynamicDynFlags dflags -- TODO shouldn't ignore result: _ <- pipeLoop phase input_fn return () _ -> return () return r runHookedPhase :: PhasePlus -> FilePath -> DynFlags -> CompPipeline (PhasePlus, FilePath) runHookedPhase pp input dflags = lookupHook runPhaseHook runPhase dflags pp input dflags -- ----------------------------------------------------------------------------- -- In each phase, we need to know into what filename to generate the -- output. All the logic about which filenames we generate output -- into is embodied in the following function. -- | Computes the next output filename after we run @next_phase@. -- Like 'getOutputFilename', but it operates in the 'CompPipeline' monad -- (which specifies all of the ambient information.) phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath phaseOutputFilename next_phase = do PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv PipeState{maybe_loc, hsc_env} <- getPipeState let dflags = hsc_dflags hsc_env liftIO $ getOutputFilename stop_phase output_spec src_basename dflags next_phase maybe_loc -- | Computes the next output filename for something in the compilation -- pipeline. This is controlled by several variables: -- -- 1. 'Phase': the last phase to be run (e.g. 'stopPhase'). This -- is used to tell if we're in the last phase or not, because -- in that case flags like @-o@ may be important. -- 2. 'PipelineOutput': is this intended to be a 'Temporary' or -- 'Persistent' build output? Temporary files just go in -- a fresh temporary name. -- 3. 'String': what was the basename of the original input file? -- 4. 'DynFlags': the obvious thing -- 5. 'Phase': the phase we want to determine the output filename of. -- 6. @Maybe ModLocation@: the 'ModLocation' of the module we're -- compiling; this can be used to override the default output -- of an object file. (TODO: do we actually need this?) getOutputFilename :: Phase -> PipelineOutput -> String -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath getOutputFilename stop_phase output basename dflags next_phase maybe_location | is_last_phase, Persistent <- output = persistent_fn | is_last_phase, SpecificFile <- output = case outputFile dflags of Just f -> return f Nothing -> panic "SpecificFile: No filename" | keep_this_output = persistent_fn | otherwise = newTempName dflags suffix where hcsuf = hcSuf dflags odir = objectDir dflags osuf = objectSuf dflags keep_hc = gopt Opt_KeepHcFiles dflags keep_s = gopt Opt_KeepSFiles dflags keep_bc = gopt Opt_KeepLlvmFiles dflags myPhaseInputExt HCc = hcsuf myPhaseInputExt MergeStub = osuf myPhaseInputExt StopLn = osuf myPhaseInputExt other = phaseInputExt other is_last_phase = next_phase `eqPhase` stop_phase -- sometimes, we keep output from intermediate stages keep_this_output = case next_phase of As _ | keep_s -> True LlvmOpt | keep_bc -> True HCc | keep_hc -> True _other -> False suffix = myPhaseInputExt next_phase -- persistent object files get put in odir persistent_fn | StopLn <- next_phase = return odir_persistent | otherwise = return persistent persistent = basename <.> suffix odir_persistent | Just loc <- maybe_location = ml_obj_file loc | Just d <- odir = d </> persistent | otherwise = persistent -- ----------------------------------------------------------------------------- -- | Each phase in the pipeline returns the next phase to execute, and the -- name of the file in which the output was placed. -- -- We must do things dynamically this way, because we often don't know -- what the rest of the phases will be until part-way through the -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning -- of a source file can change the latter stages of the pipeline from -- taking the LLVM route to using the native code generator. -- runPhase :: PhasePlus -- ^ Run this phase -> FilePath -- ^ name of the input file -> DynFlags -- ^ for convenience, we pass the current dflags in -> CompPipeline (PhasePlus, -- next phase to run FilePath) -- output filename -- Invariant: the output filename always contains the output -- Interesting case: Hsc when there is no recompilation to do -- Then the output filename is still a .o file ------------------------------------------------------------------------------- -- Unlit phase runPhase (RealPhase (Unlit sf)) input_fn dflags = do output_fn <- phaseOutputFilename (Cpp sf) let flags = [ -- The -h option passes the file name for unlit to -- put in a #line directive SysTools.Option "-h" -- See Note [Don't normalise input filenames]. , SysTools.Option $ escape input_fn , SysTools.FileOption "" input_fn , SysTools.FileOption "" output_fn ] liftIO $ SysTools.runUnlit dflags flags return (RealPhase (Cpp sf), output_fn) where -- escape the characters \, ", and ', but don't try to escape -- Unicode or anything else (so we don't use Util.charToC -- here). If we get this wrong, then in -- Coverage.isGoodTickSrcSpan where we check that the filename in -- a SrcLoc is the same as the source filenaame, the two will -- look bogusly different. See test: -- libraries/hpc/tests/function/subdir/tough2.hs escape ('\\':cs) = '\\':'\\': escape cs escape ('\"':cs) = '\\':'\"': escape cs escape ('\'':cs) = '\\':'\'': escape cs escape (c:cs) = c : escape cs escape [] = [] ------------------------------------------------------------------------------- -- Cpp phase : (a) gets OPTIONS out of file -- (b) runs cpp if necessary runPhase (RealPhase (Cpp sf)) input_fn dflags0 = do src_opts <- liftIO $ getOptionsFromFile dflags0 input_fn (dflags1, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags0 src_opts setDynFlags dflags1 liftIO $ checkProcessArgsResult dflags1 unhandled_flags if not (xopt LangExt.Cpp dflags1) then do -- we have to be careful to emit warnings only once. unless (gopt Opt_Pp dflags1) $ liftIO $ handleFlagWarnings dflags1 warns -- no need to preprocess CPP, just pass input file along -- to the next phase of the pipeline. return (RealPhase (HsPp sf), input_fn) else do output_fn <- phaseOutputFilename (HsPp sf) liftIO $ doCpp dflags1 True{-raw-} input_fn output_fn -- re-read the pragmas now that we've preprocessed the file -- See #2464,#3457 src_opts <- liftIO $ getOptionsFromFile dflags0 output_fn (dflags2, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags0 src_opts liftIO $ checkProcessArgsResult dflags2 unhandled_flags unless (gopt Opt_Pp dflags2) $ liftIO $ handleFlagWarnings dflags2 warns -- the HsPp pass below will emit warnings setDynFlags dflags2 return (RealPhase (HsPp sf), output_fn) ------------------------------------------------------------------------------- -- HsPp phase runPhase (RealPhase (HsPp sf)) input_fn dflags = do if not (gopt Opt_Pp dflags) then -- no need to preprocess, just pass input file along -- to the next phase of the pipeline. return (RealPhase (Hsc sf), input_fn) else do PipeEnv{src_basename, src_suffix} <- getPipeEnv let orig_fn = src_basename <.> src_suffix output_fn <- phaseOutputFilename (Hsc sf) liftIO $ SysTools.runPp dflags ( [ SysTools.Option orig_fn , SysTools.Option input_fn , SysTools.FileOption "" output_fn ] ) -- re-read pragmas now that we've parsed the file (see #3674) src_opts <- liftIO $ getOptionsFromFile dflags output_fn (dflags1, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags src_opts setDynFlags dflags1 liftIO $ checkProcessArgsResult dflags1 unhandled_flags liftIO $ handleFlagWarnings dflags1 warns return (RealPhase (Hsc sf), output_fn) ----------------------------------------------------------------------------- -- Hsc phase -- Compilation of a single module, in "legacy" mode (_not_ under -- the direction of the compilation manager). runPhase (RealPhase (Hsc src_flavour)) input_fn dflags0 = do -- normal Hsc mode, not mkdependHS PipeEnv{ stop_phase=stop, src_basename=basename, src_suffix=suff } <- getPipeEnv -- we add the current directory (i.e. the directory in which -- the .hs files resides) to the include path, since this is -- what gcc does, and it's probably what you want. let current_dir = takeDirectory basename paths = includePaths dflags0 dflags = dflags0 { includePaths = current_dir : paths } setDynFlags dflags -- gather the imports and module name (hspp_buf,mod_name,imps,src_imps) <- liftIO $ do do buf <- hGetStringBuffer input_fn (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff) return (Just buf, mod_name, imps, src_imps) -- Take -o into account if present -- Very like -ohi, but we must *only* do this if we aren't linking -- (If we're linking then the -o applies to the linked thing, not to -- the object file for one module.) -- Note the nasty duplication with the same computation in compileFile above location <- getLocation src_flavour mod_name let o_file = ml_obj_file location -- The real object file hi_file = ml_hi_file location dest_file | writeInterfaceOnlyMode dflags = hi_file | otherwise = o_file -- Figure out if the source has changed, for recompilation avoidance. -- -- Setting source_unchanged to True means that M.o seems -- to be up to date wrt M.hs; so no need to recompile unless imports have -- changed (which the compiler itself figures out). -- Setting source_unchanged to False tells the compiler that M.o is out of -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless. src_timestamp <- liftIO $ getModificationUTCTime (basename <.> suff) source_unchanged <- liftIO $ if not (isStopLn stop) -- SourceModified unconditionally if -- (a) recompilation checker is off, or -- (b) we aren't going all the way to .o file (e.g. ghc -S) then return SourceModified -- Otherwise look at file modification dates else do dest_file_exists <- doesFileExist dest_file if not dest_file_exists then return SourceModified -- Need to recompile else do t2 <- getModificationUTCTime dest_file if t2 > src_timestamp then return SourceUnmodified else return SourceModified PipeState{hsc_env=hsc_env'} <- getPipeState -- Tell the finder cache about this module mod <- liftIO $ addHomeModuleToFinder hsc_env' mod_name location -- Make the ModSummary to hand to hscMain let mod_summary = ModSummary { ms_mod = mod, ms_hsc_src = src_flavour, ms_hspp_file = input_fn, ms_hspp_opts = dflags, ms_hspp_buf = hspp_buf, ms_location = location, ms_hs_date = src_timestamp, ms_obj_date = Nothing, ms_parsed_mod = Nothing, ms_iface_date = Nothing, ms_textual_imps = imps, ms_srcimps = src_imps } -- run the compiler! let msg hsc_env _ what _ = oneShotMsg hsc_env what (result, _) <- liftIO $ hscIncrementalCompile True Nothing (Just msg) hsc_env' mod_summary source_unchanged Nothing (1,1) return (HscOut src_flavour mod_name result, panic "HscOut doesn't have an input filename") runPhase (HscOut src_flavour mod_name result) _ dflags = do location <- getLocation src_flavour mod_name setModLocation location let o_file = ml_obj_file location -- The real object file hsc_lang = hscTarget dflags next_phase = hscPostBackendPhase dflags src_flavour hsc_lang case result of HscNotGeneratingCode -> return (RealPhase StopLn, panic "No output filename from Hsc when no-code") HscUpToDate -> do liftIO $ touchObjectFile dflags o_file -- The .o file must have a later modification date -- than the source file (else we wouldn't get Nothing) -- but we touch it anyway, to keep 'make' happy (we think). return (RealPhase StopLn, o_file) HscUpdateBoot -> do -- In the case of hs-boot files, generate a dummy .o-boot -- stamp file for the benefit of Make liftIO $ touchObjectFile dflags o_file return (RealPhase StopLn, o_file) HscUpdateSig -> do -- We need to create a REAL but empty .o file -- because we are going to attempt to put it in a library PipeState{hsc_env=hsc_env'} <- getPipeState let input_fn = expectJust "runPhase" (ml_hs_file location) basename = dropExtension input_fn liftIO $ compileEmptyStub dflags hsc_env' basename location mod_name return (RealPhase StopLn, o_file) HscRecomp cgguts mod_summary -> do output_fn <- phaseOutputFilename next_phase PipeState{hsc_env=hsc_env'} <- getPipeState (outputFilename, mStub) <- liftIO $ hscGenHardCode hsc_env' cgguts mod_summary output_fn case mStub of Nothing -> return () Just stub_c -> do stub_o <- liftIO $ compileStub hsc_env' stub_c setStubO stub_o return (RealPhase next_phase, outputFilename) ----------------------------------------------------------------------------- -- Cmm phase runPhase (RealPhase CmmCpp) input_fn dflags = do output_fn <- phaseOutputFilename Cmm liftIO $ doCpp dflags False{-not raw-} input_fn output_fn return (RealPhase Cmm, output_fn) runPhase (RealPhase Cmm) input_fn dflags = do let hsc_lang = hscTarget dflags let next_phase = hscPostBackendPhase dflags HsSrcFile hsc_lang output_fn <- phaseOutputFilename next_phase PipeState{hsc_env} <- getPipeState liftIO $ hscCompileCmmFile hsc_env input_fn output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- Cc phase -- we don't support preprocessing .c files (with -E) now. Doing so introduces -- way too many hacks, and I can't say I've ever used it anyway. runPhase (RealPhase cc_phase) input_fn dflags | any (cc_phase `eqPhase`) [Cc, Ccxx, HCc, Cobjc, Cobjcxx] = do let platform = targetPlatform dflags hcc = cc_phase `eqPhase` HCc let cmdline_include_paths = includePaths dflags -- HC files have the dependent packages stamped into them pkgs <- if hcc then liftIO $ getHCFilePackages input_fn else return [] -- add package include paths even if we're just compiling .c -- files; this is the Value Add(TM) that using ghc instead of -- gcc gives you :) pkg_include_dirs <- liftIO $ getPackageIncludePath dflags pkgs let include_paths = foldr (\ x xs -> ("-I" ++ x) : xs) [] (cmdline_include_paths ++ pkg_include_dirs) let gcc_extra_viac_flags = extraGccViaCFlags dflags let pic_c_flags = picCCOpts dflags let verbFlags = getVerbFlags dflags -- cc-options are not passed when compiling .hc files. Our -- hc code doesn't not #include any header files anyway, so these -- options aren't necessary. pkg_extra_cc_opts <- liftIO $ if cc_phase `eqPhase` HCc then return [] else getPackageExtraCcOpts dflags pkgs framework_paths <- if platformUsesFrameworks platform then do pkgFrameworkPaths <- liftIO $ getPackageFrameworkPath dflags pkgs let cmdlineFrameworkPaths = frameworkPaths dflags return $ map ("-F"++) (cmdlineFrameworkPaths ++ pkgFrameworkPaths) else return [] let split_objs = gopt Opt_SplitObjs dflags split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ] | otherwise = [ ] let cc_opt | optLevel dflags >= 2 = [ "-O2" ] | optLevel dflags >= 1 = [ "-O" ] | otherwise = [] -- Decide next phase let next_phase = As False output_fn <- phaseOutputFilename next_phase let more_hcc_opts = -- on x86 the floating point regs have greater precision -- than a double, which leads to unpredictable results. -- By default, we turn this off with -ffloat-store unless -- the user specified -fexcess-precision. (if platformArch platform == ArchX86 && not (gopt Opt_ExcessPrecision dflags) then [ "-ffloat-store" ] else []) ++ -- gcc's -fstrict-aliasing allows two accesses to memory -- to be considered non-aliasing if they have different types. -- This interacts badly with the C code we generate, which is -- very weakly typed, being derived from C--. ["-fno-strict-aliasing"] ghcVersionH <- liftIO $ getGhcVersionPathName dflags let gcc_lang_opt | cc_phase `eqPhase` Ccxx = "c++" | cc_phase `eqPhase` Cobjc = "objective-c" | cc_phase `eqPhase` Cobjcxx = "objective-c++" | otherwise = "c" liftIO $ SysTools.runCc dflags ( -- force the C compiler to interpret this file as C when -- compiling .hc files, by adding the -x c option. -- Also useful for plain .c files, just in case GHC saw a -- -x c option. [ SysTools.Option "-x", SysTools.Option gcc_lang_opt , SysTools.FileOption "" input_fn , SysTools.Option "-o" , SysTools.FileOption "" output_fn ] ++ map SysTools.Option ( pic_c_flags -- Stub files generated for foreign exports references the runIO_closure -- and runNonIO_closure symbols, which are defined in the base package. -- These symbols are imported into the stub.c file via RtsAPI.h, and the -- way we do the import depends on whether we're currently compiling -- the base package or not. ++ (if platformOS platform == OSMinGW32 && thisPackage dflags == baseUnitId then [ "-DCOMPILING_BASE_PACKAGE" ] else []) -- We only support SparcV9 and better because V8 lacks an atomic CAS -- instruction. Note that the user can still override this -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag -- regardless of the ordering. -- -- This is a temporary hack. See #2872, commit -- 5bd3072ac30216a505151601884ac88bf404c9f2 ++ (if platformArch platform == ArchSPARC then ["-mcpu=v9"] else []) -- GCC 4.6+ doesn't like -Wimplicit when compiling C++. ++ (if (cc_phase /= Ccxx && cc_phase /= Cobjcxx) then ["-Wimplicit"] else []) ++ (if hcc then gcc_extra_viac_flags ++ more_hcc_opts else []) ++ verbFlags ++ [ "-S" ] ++ cc_opt ++ [ "-include", ghcVersionH ] ++ framework_paths ++ split_opt ++ include_paths ++ pkg_extra_cc_opts )) return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- Splitting phase runPhase (RealPhase Splitter) input_fn dflags = do -- tmp_pfx is the prefix used for the split .s files split_s_prefix <- liftIO $ SysTools.newTempName dflags "split" let n_files_fn = split_s_prefix liftIO $ SysTools.runSplit dflags [ SysTools.FileOption "" input_fn , SysTools.FileOption "" split_s_prefix , SysTools.FileOption "" n_files_fn ] -- Save the number of split files for future references s <- liftIO $ readFile n_files_fn let n_files = read s :: Int dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) } setDynFlags dflags' -- Remember to delete all these files liftIO $ addFilesToClean dflags' [ split_s_prefix ++ "__" ++ show n ++ ".s" | n <- [1..n_files]] return (RealPhase SplitAs, "**splitter**") -- we don't use the filename in SplitAs ----------------------------------------------------------------------------- -- As, SpitAs phase : Assembler -- This is for calling the assembler on a regular assembly file (not split). runPhase (RealPhase (As with_cpp)) input_fn dflags = do -- LLVM from version 3.0 onwards doesn't support the OS X system -- assembler, so we use clang as the assembler instead. (#5636) let whichAsProg | hscTarget dflags == HscLlvm && platformOS (targetPlatform dflags) == OSDarwin = return SysTools.runClang | otherwise = return SysTools.runAs as_prog <- whichAsProg let cmdline_include_paths = includePaths dflags let pic_c_flags = picCCOpts dflags next_phase <- maybeMergeStub output_fn <- phaseOutputFilename next_phase -- we create directories for the object file, because it -- might be a hierarchical module. liftIO $ createDirectoryIfMissing True (takeDirectory output_fn) ccInfo <- liftIO $ getCompilerInfo dflags let runAssembler inputFilename outputFilename = liftIO $ as_prog dflags ([ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ] -- See Note [-fPIC for assembler] ++ map SysTools.Option pic_c_flags -- We only support SparcV9 and better because V8 lacks an atomic CAS -- instruction so we have to make sure that the assembler accepts the -- instruction set. Note that the user can still override this -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag -- regardless of the ordering. -- -- This is a temporary hack. ++ (if platformArch (targetPlatform dflags) == ArchSPARC then [SysTools.Option "-mcpu=v9"] else []) ++ (if any (ccInfo ==) [Clang, AppleClang, AppleClang51] then [SysTools.Option "-Qunused-arguments"] else []) ++ [ SysTools.Option "-x" , if with_cpp then SysTools.Option "assembler-with-cpp" else SysTools.Option "assembler" , SysTools.Option "-c" , SysTools.FileOption "" inputFilename , SysTools.Option "-o" , SysTools.FileOption "" outputFilename ]) liftIO $ debugTraceMsg dflags 4 (text "Running the assembler") runAssembler input_fn output_fn return (RealPhase next_phase, output_fn) -- This is for calling the assembler on a split assembly file (so a collection -- of assembly files) runPhase (RealPhase SplitAs) _input_fn dflags = do -- we'll handle the stub_o file in this phase, so don't MergeStub, -- just jump straight to StopLn afterwards. let next_phase = StopLn output_fn <- phaseOutputFilename next_phase let base_o = dropExtension output_fn osuf = objectSuf dflags split_odir = base_o ++ "_" ++ osuf ++ "_split" let pic_c_flags = picCCOpts dflags -- this also creates the hierarchy liftIO $ createDirectoryIfMissing True split_odir -- remove M_split/ *.o, because we're going to archive M_split/ *.o -- later and we don't want to pick up any old objects. fs <- liftIO $ getDirectoryContents split_odir liftIO $ mapM_ removeFile $ map (split_odir </>) $ filter (osuf `isSuffixOf`) fs let (split_s_prefix, n) = case splitInfo dflags of Nothing -> panic "No split info" Just x -> x let split_s n = split_s_prefix ++ "__" ++ show n <.> "s" split_obj :: Int -> FilePath split_obj n = split_odir </> takeFileName base_o ++ "__" ++ show n <.> osuf let assemble_file n = SysTools.runAs dflags ( -- We only support SparcV9 and better because V8 lacks an atomic CAS -- instruction so we have to make sure that the assembler accepts the -- instruction set. Note that the user can still override this -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag -- regardless of the ordering. -- -- This is a temporary hack. (if platformArch (targetPlatform dflags) == ArchSPARC then [SysTools.Option "-mcpu=v9"] else []) ++ -- See Note [-fPIC for assembler] map SysTools.Option pic_c_flags ++ [ SysTools.Option "-c" , SysTools.Option "-o" , SysTools.FileOption "" (split_obj n) , SysTools.FileOption "" (split_s n) ]) liftIO $ mapM_ assemble_file [1..n] -- Note [pipeline-split-init] -- If we have a stub file, it may contain constructor -- functions for initialisation of this module. We can't -- simply leave the stub as a separate object file, because it -- will never be linked in: nothing refers to it. We need to -- ensure that if we ever refer to the data in this module -- that needs initialisation, then we also pull in the -- initialisation routine. -- -- To that end, we make a DANGEROUS ASSUMPTION here: the data -- that needs to be initialised is all in the FIRST split -- object. See Note [codegen-split-init]. PipeState{maybe_stub_o} <- getPipeState case maybe_stub_o of Nothing -> return () Just stub_o -> liftIO $ do tmp_split_1 <- newTempName dflags osuf let split_1 = split_obj 1 copyFile split_1 tmp_split_1 removeFile split_1 joinObjectFiles dflags [tmp_split_1, stub_o] split_1 -- join them into a single .o file liftIO $ joinObjectFiles dflags (map split_obj [1..n]) output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- LlvmOpt phase runPhase (RealPhase LlvmOpt) input_fn dflags = do let opt_lvl = max 0 (min 2 $ optLevel dflags) -- don't specify anything if user has specified commands. We do this -- for opt but not llc since opt is very specifically for optimisation -- passes only, so if the user is passing us extra options we assume -- they know what they are doing and don't get in the way. optFlag = if null (getOpts dflags opt_lo) then map SysTools.Option $ words (llvmOpts !! opt_lvl) else [] tbaa | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true" | otherwise = "--enable-tbaa=false" output_fn <- phaseOutputFilename LlvmLlc liftIO $ SysTools.runLlvmOpt dflags ([ SysTools.FileOption "" input_fn, SysTools.Option "-o", SysTools.FileOption "" output_fn] ++ optFlag ++ [SysTools.Option tbaa]) return (RealPhase LlvmLlc, output_fn) where -- we always (unless -optlo specified) run Opt since we rely on it to -- fix up some pretty big deficiencies in the code we generate llvmOpts = [ "-mem2reg -globalopt" , "-O1 -globalopt" , "-O2" ] ----------------------------------------------------------------------------- -- LlvmLlc phase runPhase (RealPhase LlvmLlc) input_fn dflags = do let opt_lvl = max 0 (min 2 $ optLevel dflags) -- iOS requires external references to be loaded indirectly from the -- DATA segment or dyld traps at runtime writing into TEXT: see #7722 rmodel | platformOS (targetPlatform dflags) == OSiOS = "dynamic-no-pic" | gopt Opt_PIC dflags = "pic" | WayDyn `elem` ways dflags = "dynamic-no-pic" | otherwise = "static" tbaa | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true" | otherwise = "--enable-tbaa=false" -- hidden debugging flag '-dno-llvm-mangler' to skip mangling let next_phase = case gopt Opt_NoLlvmMangler dflags of False -> LlvmMangle True | gopt Opt_SplitObjs dflags -> Splitter True -> As False output_fn <- phaseOutputFilename next_phase liftIO $ SysTools.runLlvmLlc dflags ([ SysTools.Option (llvmOpts !! opt_lvl), SysTools.Option $ "-relocation-model=" ++ rmodel, SysTools.FileOption "" input_fn, SysTools.Option "-o", SysTools.FileOption "" output_fn] ++ [SysTools.Option tbaa] ++ map SysTools.Option fpOpts ++ map SysTools.Option abiOpts ++ map SysTools.Option sseOpts ++ map SysTools.Option avxOpts ++ map SysTools.Option avx512Opts ++ map SysTools.Option stackAlignOpts) return (RealPhase next_phase, output_fn) where -- Bug in LLVM at O3 on OSX. llvmOpts = if platformOS (targetPlatform dflags) == OSDarwin then ["-O1", "-O2", "-O2"] else ["-O1", "-O2", "-O3"] -- On ARMv7 using LLVM, LLVM fails to allocate floating point registers -- while compiling GHC source code. It's probably due to fact that it -- does not enable VFP by default. Let's do this manually here fpOpts = case platformArch (targetPlatform dflags) of ArchARM ARMv7 ext _ -> if (elem VFPv3 ext) then ["-mattr=+v7,+vfp3"] else if (elem VFPv3D16 ext) then ["-mattr=+v7,+vfp3,+d16"] else [] ArchARM ARMv6 ext _ -> if (elem VFPv2 ext) then ["-mattr=+v6,+vfp2"] else ["-mattr=+v6"] _ -> [] -- On Ubuntu/Debian with ARM hard float ABI, LLVM's llc still -- compiles into soft-float ABI. We need to explicitly set abi -- to hard abiOpts = case platformArch (targetPlatform dflags) of ArchARM _ _ HARD -> ["-float-abi=hard"] ArchARM _ _ _ -> [] _ -> [] sseOpts | isSse4_2Enabled dflags = ["-mattr=+sse42"] | isSse2Enabled dflags = ["-mattr=+sse2"] | isSseEnabled dflags = ["-mattr=+sse"] | otherwise = [] avxOpts | isAvx512fEnabled dflags = ["-mattr=+avx512f"] | isAvx2Enabled dflags = ["-mattr=+avx2"] | isAvxEnabled dflags = ["-mattr=+avx"] | otherwise = [] avx512Opts = [ "-mattr=+avx512cd" | isAvx512cdEnabled dflags ] ++ [ "-mattr=+avx512er" | isAvx512erEnabled dflags ] ++ [ "-mattr=+avx512pf" | isAvx512pfEnabled dflags ] stackAlignOpts = case platformArch (targetPlatform dflags) of ArchX86_64 | isAvxEnabled dflags -> ["-stack-alignment=32"] _ -> [] ----------------------------------------------------------------------------- -- LlvmMangle phase runPhase (RealPhase LlvmMangle) input_fn dflags = do let next_phase = if gopt Opt_SplitObjs dflags then Splitter else As False output_fn <- phaseOutputFilename next_phase liftIO $ llvmFixupAsm dflags input_fn output_fn return (RealPhase next_phase, output_fn) ----------------------------------------------------------------------------- -- merge in stub objects runPhase (RealPhase MergeStub) input_fn dflags = do PipeState{maybe_stub_o} <- getPipeState output_fn <- phaseOutputFilename StopLn liftIO $ createDirectoryIfMissing True (takeDirectory output_fn) case maybe_stub_o of Nothing -> panic "runPhase(MergeStub): no stub" Just stub_o -> do liftIO $ joinObjectFiles dflags [input_fn, stub_o] output_fn return (RealPhase StopLn, output_fn) -- warning suppression runPhase (RealPhase other) _input_fn _dflags = panic ("runPhase: don't know how to run phase " ++ show other) maybeMergeStub :: CompPipeline Phase maybeMergeStub = do PipeState{maybe_stub_o} <- getPipeState if isJust maybe_stub_o then return MergeStub else return StopLn getLocation :: HscSource -> ModuleName -> CompPipeline ModLocation getLocation src_flavour mod_name = do dflags <- getDynFlags PipeEnv{ src_basename=basename, src_suffix=suff } <- getPipeEnv -- Build a ModLocation to pass to hscMain. -- The source filename is rather irrelevant by now, but it's used -- by hscMain for messages. hscMain also needs -- the .hi and .o filenames, and this is as good a way -- as any to generate them, and better than most. (e.g. takes -- into account the -osuf flags) location1 <- liftIO $ mkHomeModLocation2 dflags mod_name basename suff -- Boot-ify it if necessary let location2 | HsBootFile <- src_flavour = addBootSuffixLocn location1 | otherwise = location1 -- Take -ohi into account if present -- This can't be done in mkHomeModuleLocation because -- it only applies to the module being compiles let ohi = outputHi dflags location3 | Just fn <- ohi = location2{ ml_hi_file = fn } | otherwise = location2 -- Take -o into account if present -- Very like -ohi, but we must *only* do this if we aren't linking -- (If we're linking then the -o applies to the linked thing, not to -- the object file for one module.) -- Note the nasty duplication with the same computation in compileFile above let expl_o_file = outputFile dflags location4 | Just ofile <- expl_o_file , isNoLink (ghcLink dflags) = location3 { ml_obj_file = ofile } | otherwise = location3 return location4 mkExtraObj :: DynFlags -> Suffix -> String -> IO FilePath mkExtraObj dflags extn xs = do cFile <- newTempName dflags extn oFile <- newTempName dflags "o" writeFile cFile xs ccInfo <- liftIO $ getCompilerInfo dflags SysTools.runCc dflags ([Option "-c", FileOption "" cFile, Option "-o", FileOption "" oFile] ++ if extn /= "s" then cOpts else asmOpts ccInfo) return oFile where -- Pass a different set of options to the C compiler depending one whether -- we're compiling C or assembler. When compiling C, we pass the usual -- set of include directories and PIC flags. cOpts = map Option (picCCOpts dflags) ++ map (FileOption "-I") (includeDirs $ getPackageDetails dflags rtsUnitId) -- When compiling assembler code, we drop the usual C options, and if the -- compiler is Clang, we add an extra argument to tell Clang to ignore -- unused command line options. See trac #11684. asmOpts ccInfo = if any (ccInfo ==) [Clang, AppleClang, AppleClang51] then [Option "-Qunused-arguments"] else [] -- When linking a binary, we need to create a C main() function that -- starts everything off. This used to be compiled statically as part -- of the RTS, but that made it hard to change the -rtsopts setting, -- so now we generate and compile a main() stub as part of every -- binary and pass the -rtsopts setting directly to the RTS (#5373) -- mkExtraObjToLinkIntoBinary :: DynFlags -> IO FilePath mkExtraObjToLinkIntoBinary dflags = do when (gopt Opt_NoHsMain dflags && haveRtsOptsFlags dflags) $ do log_action dflags dflags NoReason SevInfo noSrcSpan defaultUserStyle (text "Warning: -rtsopts and -with-rtsopts have no effect with -no-hs-main." $$ text " Call hs_init_ghc() from your main() function to set these options.") mkExtraObj dflags "c" (showSDoc dflags main) where main | gopt Opt_NoHsMain dflags = Outputable.empty | otherwise = vcat [ text "#include \"Rts.h\"", text "extern StgClosure ZCMain_main_closure;", text "int main(int argc, char *argv[])", char '{', text " RtsConfig __conf = defaultRtsConfig;", text " __conf.rts_opts_enabled = " <> text (show (rtsOptsEnabled dflags)) <> semi, text " __conf.rts_opts_suggestions = " <> text (if rtsOptsSuggestions dflags then "true" else "false") <> semi, case rtsOpts dflags of Nothing -> Outputable.empty Just opts -> text " __conf.rts_opts= " <> text (show opts) <> semi, text " __conf.rts_hs_main = true;", text " return hs_main(argc,argv,&ZCMain_main_closure,__conf);", char '}', char '\n' -- final newline, to keep gcc happy ] -- Write out the link info section into a new assembly file. Previously -- this was included as inline assembly in the main.c file but this -- is pretty fragile. gas gets upset trying to calculate relative offsets -- that span the .note section (notably .text) when debug info is present mkNoteObjsToLinkIntoBinary :: DynFlags -> [InstalledUnitId] -> IO [FilePath] mkNoteObjsToLinkIntoBinary dflags dep_packages = do link_info <- getLinkInfo dflags dep_packages if (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags))) then fmap (:[]) $ mkExtraObj dflags "s" (showSDoc dflags (link_opts link_info)) else return [] where link_opts info = hcat [ -- "link info" section (see Note [LinkInfo section]) makeElfNote dflags ghcLinkInfoSectionName ghcLinkInfoNoteName 0 info, -- ALL generated assembly must have this section to disable -- executable stacks. See also -- compiler/nativeGen/AsmCodeGen.hs for another instance -- where we need to do this. if platformHasGnuNonexecStack (targetPlatform dflags) then text ".section .note.GNU-stack,\"\",@progbits\n" else Outputable.empty ] -- | Return the "link info" string -- -- See Note [LinkInfo section] getLinkInfo :: DynFlags -> [InstalledUnitId] -> IO String getLinkInfo dflags dep_packages = do package_link_opts <- getPackageLinkOpts dflags dep_packages pkg_frameworks <- if platformUsesFrameworks (targetPlatform dflags) then getPackageFrameworks dflags dep_packages else return [] let extra_ld_inputs = ldInputs dflags let link_info = (package_link_opts, pkg_frameworks, rtsOpts dflags, rtsOptsEnabled dflags, gopt Opt_NoHsMain dflags, map showOpt extra_ld_inputs, getOpts dflags opt_l) -- return (show link_info) {- Note [LinkInfo section] ~~~~~~~~~~~~~~~~~~~~~~~ The "link info" is a string representing the parameters of the link. We save this information in the binary, and the next time we link, if nothing else has changed, we use the link info stored in the existing binary to decide whether to re-link or not. The "link info" string is stored in a ELF section called ".debug-ghc-link-info" (see ghcLinkInfoSectionName) with the SHT_NOTE type. For some time, it used to not follow the specified record-based format (see #11022). -} ----------------------------------------------------------------------------- -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file getHCFilePackages :: FilePath -> IO [InstalledUnitId] getHCFilePackages filename = Exception.bracket (openFile filename ReadMode) hClose $ \h -> do l <- hGetLine h case l of '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest -> return (map stringToInstalledUnitId (words rest)) _other -> return [] ----------------------------------------------------------------------------- -- Static linking, of .o files -- The list of packages passed to link is the list of packages on -- which this program depends, as discovered by the compilation -- manager. It is combined with the list of packages that the user -- specifies on the command line with -package flags. -- -- In one-shot linking mode, we can't discover the package -- dependencies (because we haven't actually done any compilation or -- read any interface files), so the user must explicitly specify all -- the packages. linkBinary :: DynFlags -> [FilePath] -> [InstalledUnitId] -> IO () linkBinary = linkBinary' False linkBinary' :: Bool -> DynFlags -> [FilePath] -> [InstalledUnitId] -> IO () linkBinary' staticLink dflags o_files dep_packages = do let platform = targetPlatform dflags mySettings = settings dflags verbFlags = getVerbFlags dflags output_fn = exeFileName staticLink dflags -- get the full list of packages to link with, by combining the -- explicit packages with the auto packages and all of their -- dependencies, and eliminating duplicates. full_output_fn <- if isAbsolute output_fn then return output_fn else do d <- getCurrentDirectory return $ normalise (d </> output_fn) pkg_lib_paths <- getPackageLibraryPath dflags dep_packages let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths get_pkg_lib_path_opts l | osElfTarget (platformOS platform) && dynLibLoader dflags == SystemDependent && WayDyn `elem` ways dflags = let libpath = if gopt Opt_RelativeDynlibPaths dflags then "$ORIGIN" </> (l `makeRelativeTo` full_output_fn) else l rpath = if gopt Opt_RPath dflags then ["-Wl,-rpath", "-Wl," ++ libpath] else [] -- Solaris 11's linker does not support -rpath-link option. It silently -- ignores it and then complains about next option which is -l<some -- dir> as being a directory and not expected object file, E.g -- ld: elf error: file -- /tmp/ghc-src/libraries/base/dist-install/build: -- elf_begin: I/O error: region read: Is a directory rpathlink = if (platformOS platform) == OSSolaris2 then [] else ["-Wl,-rpath-link", "-Wl," ++ l] in ["-L" ++ l] ++ rpathlink ++ rpath | osMachOTarget (platformOS platform) && dynLibLoader dflags == SystemDependent && WayDyn `elem` ways dflags && gopt Opt_RPath dflags = let libpath = if gopt Opt_RelativeDynlibPaths dflags then "@loader_path" </> (l `makeRelativeTo` full_output_fn) else l in ["-L" ++ l] ++ ["-Wl,-rpath", "-Wl," ++ libpath] | otherwise = ["-L" ++ l] let lib_paths = libraryPaths dflags let lib_path_opts = map ("-L"++) lib_paths extraLinkObj <- mkExtraObjToLinkIntoBinary dflags noteLinkObjs <- mkNoteObjsToLinkIntoBinary dflags dep_packages pkg_link_opts <- do (package_hs_libs, extra_libs, other_flags) <- getPackageLinkOpts dflags dep_packages return $ if staticLink then package_hs_libs -- If building an executable really means making a static -- library (e.g. iOS), then we only keep the -l options for -- HS packages, because libtool doesn't accept other options. -- In the case of iOS these need to be added by hand to the -- final link in Xcode. else other_flags ++ package_hs_libs ++ extra_libs -- -Wl,-u,<sym> contained in other_flags -- needs to be put before -l<package>, -- otherwise Solaris linker fails linking -- a binary with unresolved symbols in RTS -- which are defined in base package -- the reason for this is a note in ld(1) about -- '-u' option: "The placement of this option -- on the command line is significant. -- This option must be placed before the library -- that defines the symbol." -- frameworks pkg_framework_opts <- getPkgFrameworkOpts dflags platform dep_packages let framework_opts = getFrameworkOpts dflags platform -- probably _stub.o files let extra_ld_inputs = ldInputs dflags -- Here are some libs that need to be linked at the *end* of -- the command line, because they contain symbols that are referred to -- by the RTS. We can't therefore use the ordinary way opts for these. let debug_opts | WayDebug `elem` ways dflags = [ #if defined(HAVE_LIBBFD) "-lbfd", "-liberty" #endif ] | otherwise = [] let thread_opts | WayThreaded `elem` ways dflags = let os = platformOS (targetPlatform dflags) in if os `elem` [OSMinGW32, OSFreeBSD, OSOpenBSD, OSNetBSD, OSHaiku, OSQNXNTO, OSiOS, OSDarwin] then [] else ["-lpthread"] | otherwise = [] rc_objs <- maybeCreateManifest dflags output_fn let link = if staticLink then SysTools.runLibtool else SysTools.runLink link dflags ( map SysTools.Option verbFlags ++ [ SysTools.Option "-o" , SysTools.FileOption "" output_fn ] ++ map SysTools.Option ( [] -- See Note [No PIE eating when linking] ++ (if sGccSupportsNoPie mySettings then ["-no-pie"] else []) -- Permit the linker to auto link _symbol to _imp_symbol. -- This lets us link against DLLs without needing an "import library". ++ (if platformOS platform == OSMinGW32 then ["-Wl,--enable-auto-import"] else []) -- '-no_compact_unwind' -- C++/Objective-C exceptions cannot use optimised -- stack unwinding code. The optimised form is the -- default in Xcode 4 on at least x86_64, and -- without this flag we're also seeing warnings -- like -- ld: warning: could not create compact unwind for .LFB3: non-standard register 5 being saved in prolog -- on x86. ++ (if sLdSupportsCompactUnwind mySettings && not staticLink && (platformOS platform == OSDarwin || platformOS platform == OSiOS) && case platformArch platform of ArchX86 -> True ArchX86_64 -> True ArchARM {} -> True ArchARM64 -> True _ -> False then ["-Wl,-no_compact_unwind"] else []) -- '-no_pie' -- iOS uses 'dynamic-no-pic', so we must pass this to ld to suppress a warning; see #7722 ++ (if platformOS platform == OSiOS && not staticLink then ["-Wl,-no_pie"] else []) -- '-Wl,-read_only_relocs,suppress' -- ld gives loads of warnings like: -- ld: warning: text reloc in _base_GHCziArr_unsafeArray_info to _base_GHCziArr_unsafeArray_closure -- when linking any program. We're not sure -- whether this is something we ought to fix, but -- for now this flags silences them. ++ (if platformOS platform == OSDarwin && platformArch platform == ArchX86 && not staticLink then ["-Wl,-read_only_relocs,suppress"] else []) ++ (if sLdIsGnuLd mySettings then ["-Wl,--gc-sections"] else []) ++ o_files ++ lib_path_opts) ++ extra_ld_inputs ++ map SysTools.Option ( rc_objs ++ framework_opts ++ pkg_lib_path_opts ++ extraLinkObj:noteLinkObjs ++ pkg_link_opts ++ pkg_framework_opts ++ debug_opts ++ thread_opts )) exeFileName :: Bool -> DynFlags -> FilePath exeFileName staticLink dflags | Just s <- outputFile dflags = case platformOS (targetPlatform dflags) of OSMinGW32 -> s <?.> "exe" _ -> if staticLink then s <?.> "a" else s | otherwise = if platformOS (targetPlatform dflags) == OSMinGW32 then "main.exe" else if staticLink then "liba.a" else "a.out" where s <?.> ext | null (takeExtension s) = s <.> ext | otherwise = s maybeCreateManifest :: DynFlags -> FilePath -- filename of executable -> IO [FilePath] -- extra objects to embed, maybe maybeCreateManifest dflags exe_filename | platformOS (targetPlatform dflags) == OSMinGW32 && gopt Opt_GenManifest dflags = do let manifest_filename = exe_filename <.> "manifest" writeFile manifest_filename $ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++ " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++ " <assemblyIdentity version=\"1.0.0.0\"\n"++ " processorArchitecture=\"X86\"\n"++ " name=\"" ++ dropExtension exe_filename ++ "\"\n"++ " type=\"win32\"/>\n\n"++ " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++ " <security>\n"++ " <requestedPrivileges>\n"++ " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++ " </requestedPrivileges>\n"++ " </security>\n"++ " </trustInfo>\n"++ "</assembly>\n" -- Windows will find the manifest file if it is named -- foo.exe.manifest. However, for extra robustness, and so that -- we can move the binary around, we can embed the manifest in -- the binary itself using windres: if not (gopt Opt_EmbedManifest dflags) then return [] else do rc_filename <- newTempName dflags "rc" rc_obj_filename <- newTempName dflags (objectSuf dflags) writeFile rc_filename $ "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n" -- magic numbers :-) -- show is a bit hackish above, but we need to escape the -- backslashes in the path. runWindres dflags $ map SysTools.Option $ ["--input="++rc_filename, "--output="++rc_obj_filename, "--output-format=coff"] -- no FileOptions here: windres doesn't like seeing -- backslashes, apparently removeFile manifest_filename return [rc_obj_filename] | otherwise = return [] linkDynLibCheck :: DynFlags -> [String] -> [InstalledUnitId] -> IO () linkDynLibCheck dflags o_files dep_packages = do when (haveRtsOptsFlags dflags) $ do log_action dflags dflags NoReason SevInfo noSrcSpan defaultUserStyle (text "Warning: -rtsopts and -with-rtsopts have no effect with -shared." $$ text " Call hs_init_ghc() from your main() function to set these options.") linkDynLib dflags o_files dep_packages linkStaticLibCheck :: DynFlags -> [String] -> [InstalledUnitId] -> IO () linkStaticLibCheck dflags o_files dep_packages = do when (platformOS (targetPlatform dflags) `notElem` [OSiOS, OSDarwin]) $ throwGhcExceptionIO (ProgramError "Static archive creation only supported on Darwin/OS X/iOS") linkBinary' True dflags o_files dep_packages -- ----------------------------------------------------------------------------- -- Running CPP doCpp :: DynFlags -> Bool -> FilePath -> FilePath -> IO () doCpp dflags raw input_fn output_fn = do let hscpp_opts = picPOpts dflags let cmdline_include_paths = includePaths dflags pkg_include_dirs <- getPackageIncludePath dflags [] let include_paths = foldr (\ x xs -> "-I" : x : xs) [] (cmdline_include_paths ++ pkg_include_dirs) let verbFlags = getVerbFlags dflags let cpp_prog args | raw = SysTools.runCpp dflags args | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args) let target_defs = [ "-D" ++ HOST_OS ++ "_BUILD_OS", "-D" ++ HOST_ARCH ++ "_BUILD_ARCH", "-D" ++ TARGET_OS ++ "_HOST_OS", "-D" ++ TARGET_ARCH ++ "_HOST_ARCH" ] -- remember, in code we *compile*, the HOST is the same our TARGET, -- and BUILD is the same as our HOST. let sse_defs = [ "-D__SSE__" | isSseEnabled dflags ] ++ [ "-D__SSE2__" | isSse2Enabled dflags ] ++ [ "-D__SSE4_2__" | isSse4_2Enabled dflags ] let avx_defs = [ "-D__AVX__" | isAvxEnabled dflags ] ++ [ "-D__AVX2__" | isAvx2Enabled dflags ] ++ [ "-D__AVX512CD__" | isAvx512cdEnabled dflags ] ++ [ "-D__AVX512ER__" | isAvx512erEnabled dflags ] ++ [ "-D__AVX512F__" | isAvx512fEnabled dflags ] ++ [ "-D__AVX512PF__" | isAvx512pfEnabled dflags ] backend_defs <- getBackendDefs dflags let th_defs = [ "-D__GLASGOW_HASKELL_TH__" ] -- Default CPP defines in Haskell source ghcVersionH <- getGhcVersionPathName dflags let hsSourceCppOpts = [ "-include", ghcVersionH ] -- MIN_VERSION macros let uids = explicitPackages (pkgState dflags) pkgs = catMaybes (map (lookupPackage dflags) uids) mb_macro_include <- if not (null pkgs) && gopt Opt_VersionMacros dflags then do macro_stub <- newTempName dflags "h" writeFile macro_stub (generatePackageVersionMacros pkgs) -- Include version macros for every *exposed* package. -- Without -hide-all-packages and with a package database -- size of 1000 packages, it takes cpp an estimated 2 -- milliseconds to process this file. See Trac #10970 -- comment 8. return [SysTools.FileOption "-include" macro_stub] else return [] cpp_prog ( map SysTools.Option verbFlags ++ map SysTools.Option include_paths ++ map SysTools.Option hsSourceCppOpts ++ map SysTools.Option target_defs ++ map SysTools.Option backend_defs ++ map SysTools.Option th_defs ++ map SysTools.Option hscpp_opts ++ map SysTools.Option sse_defs ++ map SysTools.Option avx_defs ++ mb_macro_include -- Set the language mode to assembler-with-cpp when preprocessing. This -- alleviates some of the C99 macro rules relating to whitespace and the hash -- operator, which we tend to abuse. Clang in particular is not very happy -- about this. ++ [ SysTools.Option "-x" , SysTools.Option "assembler-with-cpp" , SysTools.Option input_fn -- We hackily use Option instead of FileOption here, so that the file -- name is not back-slashed on Windows. cpp is capable of -- dealing with / in filenames, so it works fine. Furthermore -- if we put in backslashes, cpp outputs #line directives -- with *double* backslashes. And that in turn means that -- our error messages get double backslashes in them. -- In due course we should arrange that the lexer deals -- with these \\ escapes properly. , SysTools.Option "-o" , SysTools.FileOption "" output_fn ]) getBackendDefs :: DynFlags -> IO [String] getBackendDefs dflags | hscTarget dflags == HscLlvm = do llvmVer <- figureLlvmVersion dflags return $ case llvmVer of Just n -> [ "-D__GLASGOW_HASKELL_LLVM__=" ++ format n ] _ -> [] where format (major, minor) | minor >= 100 = error "getBackendDefs: Unsupported minor version" | otherwise = show $ (100 * major + minor :: Int) -- Contract is Int getBackendDefs _ = return [] -- --------------------------------------------------------------------------- -- Macros (cribbed from Cabal) generatePackageVersionMacros :: [PackageConfig] -> String generatePackageVersionMacros pkgs = concat -- Do not add any C-style comments. See Trac #3389. [ generateMacros "" pkgname version | pkg <- pkgs , let version = packageVersion pkg pkgname = map fixchar (packageNameString pkg) ] fixchar :: Char -> Char fixchar '-' = '_' fixchar c = c generateMacros :: String -> String -> Version -> String generateMacros prefix name version = concat ["#define ", prefix, "VERSION_",name," ",show (showVersion version),"\n" ,"#define MIN_", prefix, "VERSION_",name,"(major1,major2,minor) (\\\n" ," (major1) < ",major1," || \\\n" ," (major1) == ",major1," && (major2) < ",major2," || \\\n" ," (major1) == ",major1," && (major2) == ",major2," && (minor) <= ",minor,")" ,"\n\n" ] where (major1:major2:minor:_) = map show (versionBranch version ++ repeat 0) -- --------------------------------------------------------------------------- -- join object files into a single relocatable object file, using ld -r joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO () joinObjectFiles dflags o_files output_fn = do let mySettings = settings dflags ldIsGnuLd = sLdIsGnuLd mySettings osInfo = platformOS (targetPlatform dflags) ld_r args cc = SysTools.runLink dflags ([ SysTools.Option "-nostdlib", SysTools.Option "-Wl,-r" ] -- See Note [No PIE eating while linking] in SysTools ++ (if sGccSupportsNoPie mySettings then [SysTools.Option "-no-pie"] else []) ++ (if any (cc ==) [Clang, AppleClang, AppleClang51] then [] else [SysTools.Option "-nodefaultlibs"]) ++ (if osInfo == OSFreeBSD then [SysTools.Option "-L/usr/lib"] else []) -- gcc on sparc sets -Wl,--relax implicitly, but -- -r and --relax are incompatible for ld, so -- disable --relax explicitly. ++ (if platformArch (targetPlatform dflags) `elem` [ArchSPARC, ArchSPARC64] && ldIsGnuLd then [SysTools.Option "-Wl,-no-relax"] else []) ++ map SysTools.Option ld_build_id ++ [ SysTools.Option "-o", SysTools.FileOption "" output_fn ] ++ args) -- suppress the generation of the .note.gnu.build-id section, -- which we don't need and sometimes causes ld to emit a -- warning: ld_build_id | sLdSupportsBuildId mySettings = ["-Wl,--build-id=none"] | otherwise = [] ccInfo <- getCompilerInfo dflags if ldIsGnuLd then do script <- newTempName dflags "ldscript" cwd <- getCurrentDirectory let o_files_abs = map (\x -> "\"" ++ (cwd </> x) ++ "\"") o_files writeFile script $ "INPUT(" ++ unwords o_files_abs ++ ")" ld_r [SysTools.FileOption "" script] ccInfo else if sLdSupportsFilelist mySettings then do filelist <- newTempName dflags "filelist" writeFile filelist $ unlines o_files ld_r [SysTools.Option "-Wl,-filelist", SysTools.FileOption "-Wl," filelist] ccInfo else do ld_r (map (SysTools.FileOption "") o_files) ccInfo -- ----------------------------------------------------------------------------- -- Misc. writeInterfaceOnlyMode :: DynFlags -> Bool writeInterfaceOnlyMode dflags = gopt Opt_WriteInterface dflags && HscNothing == hscTarget dflags -- | What phase to run after one of the backend code generators has run hscPostBackendPhase :: DynFlags -> HscSource -> HscTarget -> Phase hscPostBackendPhase _ HsBootFile _ = StopLn hscPostBackendPhase _ HsigFile _ = StopLn hscPostBackendPhase dflags _ hsc_lang = case hsc_lang of HscC -> HCc HscAsm | gopt Opt_SplitObjs dflags -> Splitter | otherwise -> As False HscLlvm -> LlvmOpt HscNothing -> StopLn HscInterpreted -> StopLn touchObjectFile :: DynFlags -> FilePath -> IO () touchObjectFile dflags path = do createDirectoryIfMissing True $ takeDirectory path SysTools.touch dflags "Touching object file" path haveRtsOptsFlags :: DynFlags -> Bool haveRtsOptsFlags dflags = isJust (rtsOpts dflags) || case rtsOptsEnabled dflags of RtsOptsSafeOnly -> False _ -> True -- | Find out path to @ghcversion.h@ file getGhcVersionPathName :: DynFlags -> IO FilePath getGhcVersionPathName dflags = do dirs <- getPackageIncludePath dflags [toInstalledUnitId rtsUnitId] found <- filterM doesFileExist (map (</> "ghcversion.h") dirs) case found of [] -> throwGhcExceptionIO (InstallationError ("ghcversion.h missing")) (x:_) -> return x -- Note [-fPIC for assembler] -- When compiling .c source file GHC's driver pipeline basically -- does the following two things: -- 1. ${CC} -S 'PIC_CFLAGS' source.c -- 2. ${CC} -x assembler -c 'PIC_CFLAGS' source.S -- -- Why do we need to pass 'PIC_CFLAGS' both to C compiler and assembler? -- Because on some architectures (at least sparc32) assembler also chooses -- the relocation type! -- Consider the following C module: -- -- /* pic-sample.c */ -- int v; -- void set_v (int n) { v = n; } -- int get_v (void) { return v; } -- -- $ gcc -S -fPIC pic-sample.c -- $ gcc -c pic-sample.s -o pic-sample.no-pic.o # incorrect binary -- $ gcc -c -fPIC pic-sample.s -o pic-sample.pic.o # correct binary -- -- $ objdump -r -d pic-sample.pic.o > pic-sample.pic.o.od -- $ objdump -r -d pic-sample.no-pic.o > pic-sample.no-pic.o.od -- $ diff -u pic-sample.pic.o.od pic-sample.no-pic.o.od -- -- Most of architectures won't show any difference in this test, but on sparc32 -- the following assembly snippet: -- -- sethi %hi(_GLOBAL_OFFSET_TABLE_-8), %l7 -- -- generates two kinds or relocations, only 'R_SPARC_PC22' is correct: -- -- 3c: 2f 00 00 00 sethi %hi(0), %l7 -- - 3c: R_SPARC_PC22 _GLOBAL_OFFSET_TABLE_-0x8 -- + 3c: R_SPARC_HI22 _GLOBAL_OFFSET_TABLE_-0x8 {- Note [Don't normalise input filenames] Summary We used to normalise input filenames when starting the unlit phase. This broke hpc in `--make` mode with imported literate modules (#2991). Introduction 1) --main When compiling a module with --main, GHC scans its imports to find out which other modules it needs to compile too. It turns out that there is a small difference between saying `ghc --make A.hs`, when `A` imports `B`, and specifying both modules on the command line with `ghc --make A.hs B.hs`. In the former case, the filename for B is inferred to be './B.hs' instead of 'B.hs'. 2) unlit When GHC compiles a literate haskell file, the source code first needs to go through unlit, which turns it into normal Haskell source code. At the start of the unlit phase, in `Driver.Pipeline.runPhase`, we call unlit with the option `-h` and the name of the original file. We used to normalise this filename using System.FilePath.normalise, which among other things removes an initial './'. unlit then uses that filename in #line directives that it inserts in the transformed source code. 3) SrcSpan A SrcSpan represents a portion of a source code file. It has fields linenumber, start column, end column, and also a reference to the file it originated from. The SrcSpans for a literate haskell file refer to the filename that was passed to unlit -h. 4) -fhpc At some point during compilation with -fhpc, in the function `deSugar.Coverage.isGoodTickSrcSpan`, we compare the filename that a `SrcSpan` refers to with the name of the file we are currently compiling. For some reason I don't yet understand, they can sometimes legitimally be different, and then hpc ignores that SrcSpan. Problem When running `ghc --make -fhpc A.hs`, where `A.hs` imports the literate module `B.lhs`, `B` is inferred to be in the file `./B.lhs` (1). At the start of the unlit phase, the name `./B.lhs` is normalised to `B.lhs` (2). Therefore the SrcSpans of `B` refer to the file `B.lhs` (3), but we are still compiling `./B.lhs`. Hpc thinks these two filenames are different (4), doesn't include ticks for B, and we have unhappy customers (#2991). Solution Do not normalise `input_fn` when starting the unlit phase. Alternative solution Another option would be to not compare the two filenames on equality, but to use System.FilePath.equalFilePath. That function first normalises its arguments. The problem is that by the time we need to do the comparison, the filenames have been turned into FastStrings, probably for performance reasons, so System.FilePath.equalFilePath can not be used directly. Archeology The call to `normalise` was added in a commit called "Fix slash direction on Windows with the new filePath code" (c9b6b5e8). The problem that commit was addressing has since been solved in a different manner, in a commit called "Fix the filename passed to unlit" (1eedbc6b). So the `normalise` is no longer necessary. -}
olsner/ghc
compiler/main/DriverPipeline.hs
bsd-3-clause
102,547
0
31
34,471
16,297
8,260
8,037
1,378
43
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} -- | Constants used throughout the project. module Stack.Constants (buildPlanDir ,distDirFromDir ,workDirFromDir ,distRelativeDir ,haskellModuleExts ,imageStagingDir ,projectDockerSandboxDir ,stackDotYaml ,stackWorkEnvVar ,stackRootEnvVar ,stackRootOptionName ,deprecatedStackRootOptionName ,inContainerEnvVar ,inNixShellEnvVar ,configCacheFile ,configCabalMod ,buildCacheFile ,testSuccessFile ,testBuiltFile ,stackProgName ,stackProgNameUpper ,wiredInPackages ,ghcjsBootPackages ,cabalPackageName ,implicitGlobalProjectDirDeprecated ,implicitGlobalProjectDir ,hpcRelativeDir ,hpcDirFromDir ,objectInterfaceDirL ,templatesDir ,defaultUserConfigPathDeprecated ,defaultUserConfigPath ,defaultGlobalConfigPathDeprecated ,defaultGlobalConfigPath ,platformVariantEnvVar ,compilerOptionsCabalFlag ) where import Control.Monad.Catch (MonadThrow) import Control.Monad.Reader import Data.Char (toUpper) import Data.HashSet (HashSet) import qualified Data.HashSet as HashSet import Data.Text (Text) import Lens.Micro (Getting) import Path as FL import Prelude import Stack.Types.Compiler import Stack.Types.Config import Stack.Types.PackageIdentifier import Stack.Types.PackageName -- | Extensions for anything that can be a Haskell module. haskellModuleExts :: [Text] haskellModuleExts = haskellFileExts ++ haskellPreprocessorExts -- | Extensions used for Haskell modules. Excludes preprocessor ones. haskellFileExts :: [Text] haskellFileExts = ["hs", "hsc", "lhs"] -- | Extensions for modules that are preprocessed by common preprocessors. haskellPreprocessorExts :: [Text] haskellPreprocessorExts = ["gc", "chs", "hsc", "x", "y", "ly", "cpphs"] -- | Output .o/.hi directory. objectInterfaceDirL :: HasBuildConfig env => Getting r env (Path Abs Dir) objectInterfaceDirL = to $ \env -> -- FIXME is this idomatic lens code? let workDir = view workDirL env root = view projectRootL env in root </> workDir </> $(mkRelDir "odir/") -- | The filename used for dirtiness check of source files. buildCacheFile :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => Path Abs Dir -- ^ Package directory. -> m (Path Abs File) buildCacheFile dir = liftM (</> $(mkRelFile "stack-build-cache")) (distDirFromDir dir) -- | The filename used to mark tests as having succeeded testSuccessFile :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => Path Abs Dir -- ^ Package directory -> m (Path Abs File) testSuccessFile dir = liftM (</> $(mkRelFile "stack-test-success")) (distDirFromDir dir) -- | The filename used to mark tests as having built testBuiltFile :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => Path Abs Dir -- ^ Package directory -> m (Path Abs File) testBuiltFile dir = liftM (</> $(mkRelFile "stack-test-built")) (distDirFromDir dir) -- | The filename used for dirtiness check of config. configCacheFile :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => Path Abs Dir -- ^ Package directory. -> m (Path Abs File) configCacheFile dir = liftM (</> $(mkRelFile "stack-config-cache")) (distDirFromDir dir) -- | The filename used for modification check of .cabal configCabalMod :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => Path Abs Dir -- ^ Package directory. -> m (Path Abs File) configCabalMod dir = liftM (</> $(mkRelFile "stack-cabal-mod")) (distDirFromDir dir) -- | Directory for HPC work. hpcDirFromDir :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => Path Abs Dir -- ^ Package directory. -> m (Path Abs Dir) hpcDirFromDir fp = liftM (fp </>) hpcRelativeDir -- | Relative location of directory for HPC work. hpcRelativeDir :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Rel Dir) hpcRelativeDir = liftM (</> $(mkRelDir "hpc")) distRelativeDir -- | Package's build artifacts directory. distDirFromDir :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => Path Abs Dir -> m (Path Abs Dir) distDirFromDir fp = liftM (fp </>) distRelativeDir -- | Package's working directory. workDirFromDir :: (MonadReader env m, HasEnvConfig env) => Path Abs Dir -> m (Path Abs Dir) workDirFromDir fp = view $ workDirL.to (fp </>) -- | Directory for project templates. templatesDir :: Config -> Path Abs Dir templatesDir config = configStackRoot config </> $(mkRelDir "templates") -- | Relative location of build artifacts. distRelativeDir :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Rel Dir) distRelativeDir = do cabalPkgVer <- view cabalVersionL platform <- platformGhcRelDir wc <- view $ actualCompilerVersionL.to whichCompiler -- Cabal version, suffixed with "_ghcjs" if we're using GHCJS. envDir <- parseRelDir $ (if wc == Ghcjs then (++ "_ghcjs") else id) $ packageIdentifierString $ PackageIdentifier cabalPackageName cabalPkgVer platformAndCabal <- useShaPathOnWindows (platform </> envDir) workDir <- view workDirL return $ workDir </> $(mkRelDir "dist") </> platformAndCabal -- | Docker sandbox from project root. projectDockerSandboxDir :: (MonadReader env m, HasConfig env) => Path Abs Dir -- ^ Project root -> m (Path Abs Dir) -- ^ Docker sandbox projectDockerSandboxDir projectRoot = do workDir <- view workDirL return $ projectRoot </> workDir </> $(mkRelDir "docker/") -- | Image staging dir from project root. imageStagingDir :: (MonadReader env m, HasConfig env, MonadThrow m) => Path Abs Dir -- ^ Project root -> Int -- ^ Index of image -> m (Path Abs Dir) -- ^ Docker sandbox imageStagingDir projectRoot imageIdx = do workDir <- view workDirL idxRelDir <- parseRelDir (show imageIdx) return $ projectRoot </> workDir </> $(mkRelDir "image") </> idxRelDir -- | Name of the 'stack' program, uppercased stackProgNameUpper :: String stackProgNameUpper = map toUpper stackProgName -- | Name of the 'stack' program. stackProgName :: String stackProgName = "stack" -- | The filename used for the stack config file. stackDotYaml :: Path Rel File stackDotYaml = $(mkRelFile "stack.yaml") -- | Environment variable used to override the '.stack-work' relative dir. stackWorkEnvVar :: String stackWorkEnvVar = "STACK_WORK" -- | Environment variable used to override the '~/.stack' location. stackRootEnvVar :: String stackRootEnvVar = "STACK_ROOT" -- | Option name for the global stack root. stackRootOptionName :: String stackRootOptionName = "stack-root" -- | Deprecated option name for the global stack root. -- -- Deprecated since stack-1.1.0. -- -- TODO: Remove occurences of this variable and use 'stackRootOptionName' only -- after an appropriate deprecation period. deprecatedStackRootOptionName :: String deprecatedStackRootOptionName = "global-stack-root" -- | Environment variable used to indicate stack is running in container. inContainerEnvVar :: String inContainerEnvVar = stackProgNameUpper ++ "_IN_CONTAINER" -- | Environment variable used to indicate stack is running in container. -- although we already have STACK_IN_NIX_EXTRA_ARGS that is set in the same conditions, -- it can happen that STACK_IN_NIX_EXTRA_ARGS is set to empty. inNixShellEnvVar :: String inNixShellEnvVar = map toUpper stackProgName ++ "_IN_NIXSHELL" -- See https://downloads.haskell.org/~ghc/7.10.1/docs/html/libraries/ghc/src/Module.html#integerPackageKey wiredInPackages :: HashSet PackageName wiredInPackages = maybe (error "Parse error in wiredInPackages") HashSet.fromList mparsed where mparsed = mapM parsePackageName [ "ghc-prim" , "integer-gmp" , "integer-simple" , "base" , "rts" , "template-haskell" , "dph-seq" , "dph-par" , "ghc" , "interactive" ] -- TODO: Get this unwieldy list out of here and into a datafile -- generated by GHCJS! See https://github.com/ghcjs/ghcjs/issues/434 ghcjsBootPackages :: HashSet PackageName ghcjsBootPackages = maybe (error "Parse error in ghcjsBootPackages") HashSet.fromList mparsed where mparsed = mapM parsePackageName -- stage1a [ "array" , "base" , "binary" , "bytestring" , "containers" , "deepseq" , "integer-gmp" , "pretty" , "primitive" , "integer-gmp" , "pretty" , "primitive" , "template-haskell" , "transformers" -- stage1b , "directory" , "filepath" , "old-locale" , "process" , "time" -- stage2 , "async" , "aeson" , "attoparsec" , "case-insensitive" , "dlist" , "extensible-exceptions" , "hashable" , "mtl" , "old-time" , "parallel" , "scientific" , "stm" , "syb" , "text" , "unordered-containers" , "vector" ] -- | Just to avoid repetition and magic strings. cabalPackageName :: PackageName cabalPackageName = $(mkPackageName "Cabal") -- | Deprecated implicit global project directory used when outside of a project. implicitGlobalProjectDirDeprecated :: Path Abs Dir -- ^ Stack root. -> Path Abs Dir implicitGlobalProjectDirDeprecated p = p </> $(mkRelDir "global") -- | Implicit global project directory used when outside of a project. -- Normally, @getImplicitGlobalProjectDir@ should be used instead. implicitGlobalProjectDir :: Path Abs Dir -- ^ Stack root. -> Path Abs Dir implicitGlobalProjectDir p = p </> $(mkRelDir "global-project") -- | Deprecated default global config path. defaultUserConfigPathDeprecated :: Path Abs Dir -> Path Abs File defaultUserConfigPathDeprecated = (</> $(mkRelFile "stack.yaml")) -- | Default global config path. -- Normally, @getDefaultUserConfigPath@ should be used instead. defaultUserConfigPath :: Path Abs Dir -> Path Abs File defaultUserConfigPath = (</> $(mkRelFile "config.yaml")) -- | Deprecated default global config path. -- Note that this will be @Nothing@ on Windows, which is by design. defaultGlobalConfigPathDeprecated :: Maybe (Path Abs File) defaultGlobalConfigPathDeprecated = parseAbsFile "/etc/stack/config" -- | Default global config path. -- Normally, @getDefaultGlobalConfigPath@ should be used instead. -- Note that this will be @Nothing@ on Windows, which is by design. defaultGlobalConfigPath :: Maybe (Path Abs File) defaultGlobalConfigPath = parseAbsFile "/etc/stack/config.yaml" -- | Path where build plans are stored. buildPlanDir :: Path Abs Dir -- ^ Stack root -> Path Abs Dir buildPlanDir = (</> $(mkRelDir "build-plan")) -- | Environment variable that stores a variant to append to platform-specific directory -- names. Used to ensure incompatible binaries aren't shared between Docker builds and host platformVariantEnvVar :: String platformVariantEnvVar = stackProgNameUpper ++ "_PLATFORM_VARIANT" -- | Provides --ghc-options for 'Ghc', and similarly, --ghcjs-options -- for 'Ghcjs'. compilerOptionsCabalFlag :: WhichCompiler -> String compilerOptionsCabalFlag Ghc = "--ghc-options" compilerOptionsCabalFlag Ghcjs = "--ghcjs-options"
mrkkrp/stack
src/Stack/Constants.hs
bsd-3-clause
11,753
0
13
2,649
2,107
1,158
949
250
2
-- an example where we want to compile and load a file import System.Plugins import API main = do make "../Null.hs" ["-i../api"] m_v <- load "../Null.o" ["../api"] [] "resource" v <- case m_v of LoadSuccess _ v -> return v _ -> error "load failed" putStrLn ( show (a v) )
abuiles/turbinado-blog
tmp/dependencies/hs-plugins-1.3.1/testsuite/make/null/prog/Main.hs
bsd-3-clause
323
0
11
101
99
47
52
9
2
module Cabal2Nix.Package where import qualified Cabal2Nix.Hackage as DB import Control.Applicative import qualified Control.Exception as Exception import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Maybe import Data.List ( isSuffixOf, isPrefixOf ) import Data.Maybe import Data.Version import Distribution.Nixpkgs.Fetch import qualified Distribution.Package as Cabal import qualified Distribution.PackageDescription as Cabal import qualified Distribution.PackageDescription.Parse as Cabal import qualified Distribution.ParseUtils as ParseUtils import Distribution.Text ( simpleParse ) import System.Directory ( doesDirectoryExist, doesFileExist, createDirectoryIfMissing, getHomeDirectory, getDirectoryContents ) import System.Exit ( exitFailure ) import System.FilePath ( (</>), (<.>) ) import System.IO ( hPutStrLn, stderr, hPutStr ) data Package = Package { pkgSource :: DerivationSource , pkgCabal :: Cabal.GenericPackageDescription } deriving (Show) getPackage :: Maybe String -> Source -> IO Package getPackage optHackageDB source = do (derivSource, pkgDesc) <- fetchOrFromDB optHackageDB source flip Package pkgDesc <$> maybe (sourceFromHackage (sourceHash source) $ showPackageIdentifier pkgDesc) return derivSource fetchOrFromDB :: Maybe String -> Source -> IO (Maybe DerivationSource, Cabal.GenericPackageDescription) fetchOrFromDB optHackageDB src | "cabal://" `isPrefixOf` sourceUrl src = fmap ((,) Nothing) . fromDB optHackageDB . drop (length "cabal://") $ sourceUrl src | otherwise = do r <- fetch cabalFromPath src case r of Nothing -> hPutStrLn stderr "*** failed to fetch source. Does the URL exist?" >> exitFailure Just (derivSource, (externalSource, pkgDesc)) -> return (derivSource <$ guard externalSource, pkgDesc) fromDB :: Maybe String -> String -> IO Cabal.GenericPackageDescription fromDB optHackageDB pkg = do pkgDesc <- (lookupVersion <=< DB.lookup name) <$> maybe DB.readHashedHackage DB.readHackage' optHackageDB case pkgDesc of Just r -> return r Nothing -> hPutStrLn stderr "*** no such package in the cabal database (did you run cabal update?). " >> exitFailure where pkgId = fromMaybe (error ("invalid Haskell package id " ++ show pkg)) (simpleParse pkg) Cabal.PackageName name = Cabal.pkgName pkgId version = Cabal.pkgVersion pkgId lookupVersion :: DB.Map DB.Version Cabal.GenericPackageDescription -> Maybe Cabal.GenericPackageDescription lookupVersion | null (versionBranch version) = fmap snd . listToMaybe . reverse . DB.toAscList | otherwise = DB.lookup version readFileMay :: String -> IO (Maybe String) readFileMay file = do e <- doesFileExist file if e then Just <$> readFile file else return Nothing hashCachePath :: String -> IO String hashCachePath pid = do home <- getHomeDirectory let cacheDir = home </> ".cache/cabal2nix" createDirectoryIfMissing True cacheDir return $ cacheDir </> pid <.> "sha256" sourceFromHackage :: Maybe String -> String -> IO DerivationSource sourceFromHackage optHash pkgId = do cacheFile <- hashCachePath pkgId let cachedHash = MaybeT $ maybe (readFileMay cacheFile) (return . Just) optHash url = "mirror://hackage/" ++ pkgId ++ ".tar.gz" -- Use the cached hash (either from cache file or given on cmdline via sha256 opt) -- if available, otherwise download from hackage to compute hash. maybeHash <- runMaybeT $ cachedHash <|> derivHash . fst <$> fetchWith (False, "url", []) (Source url "" Nothing) case maybeHash of Just hash -> -- We need to force the hash here. If we didn't do this, then when reading the -- hash from the cache file, the cache file will still be open for reading -- (because lazy io) when writeFile opens the file again for writing. By forcing -- the hash here, we ensure that the file is closed before opening it again. seq (length hash) $ DerivationSource "url" url "" hash <$ writeFile cacheFile hash Nothing -> do hPutStr stderr $ unlines [ "*** cannot compute hash. (Not a hackage project?)" , " If your project is not on hackage, please supply the path to the root directory of" , " the project, not to the cabal file." , "" , " If your project is on hackage but you still want to specify the hash manually, you" , " can use the --sha256 option." ] exitFailure showPackageIdentifier :: Cabal.GenericPackageDescription -> String showPackageIdentifier pkgDesc = name ++ "-" ++ showVersion version where pkgId = Cabal.package . Cabal.packageDescription $ pkgDesc Cabal.PackageName name = Cabal.packageName pkgId version = Cabal.packageVersion pkgId cabalFromPath :: FilePath -> MaybeT IO (Bool, Cabal.GenericPackageDescription) cabalFromPath path = do d <- liftIO $ doesDirectoryExist path (,) d <$> if d then cabalFromDirectory path else cabalFromFile False path cabalFromDirectory :: FilePath -> MaybeT IO Cabal.GenericPackageDescription cabalFromDirectory dir = do cabals <- liftIO $ getDirectoryContents dir >>= filterM doesFileExist . map (dir </>) . filter (".cabal" `isSuffixOf`) case cabals of [cabalFile] -> cabalFromFile True cabalFile _ -> liftIO $ hPutStrLn stderr "*** found zero or more than one cabal file. Exiting." >> exitFailure handleIO :: (Exception.IOException -> IO a) -> IO a -> IO a handleIO = Exception.handle cabalFromFile :: Bool -> FilePath -> MaybeT IO Cabal.GenericPackageDescription cabalFromFile failHard file = -- readFile throws an error if it's used on binary files which contain sequences -- that do not represent valid characters. To catch that exception, we need to -- wrap the whole block in `catchIO`, because of lazy IO. The `case` will force -- the reading of the file, so we will always catch the expression here. MaybeT $ handleIO (\err -> Nothing <$ hPutStrLn stderr ("*** parsing cabal file: " ++ show err)) $ do content <- readFile file case Cabal.parsePackageDescription content of Cabal.ParseFailed e | failHard -> do let (line, err) = ParseUtils.locatedErrorMsg e msg = maybe "" ((++ ": ") . show) line ++ err putStrLn $ "*** error parsing cabal file: " ++ msg exitFailure Cabal.ParseFailed _ -> return Nothing Cabal.ParseOk _ a -> return (Just a)
jb55/cabal2nix
src/Cabal2Nix/Package.hs
bsd-3-clause
6,438
0
21
1,280
1,558
792
766
-1
-1
module Grammatik.CF.Kettenfrei where -- -- $Id$ import Grammatik.Type import Autolib.Fix import Autolib.Set import Autolib.FiniteMap import qualified Autolib.Relation as Relation import Data.List (partition) import Control.Monad (guard) -- | eingabe: kontextfreie Grammatik G1 -- ausgabe: kontextfreie Grammatik G2 mit L(G2) = L(G1) -- und G2 enthält keine Regeln V -> V kettenfrei :: Grammatik -> Grammatik kettenfrei g = let ( pairs, nopairs ) = partition ( \ ( [lhs], rhs) -> length rhs == 1 && head rhs `elementOf` nichtterminale g ) ( rules g ) chains = Relation.trans $ Relation.plus ( Relation.identic $ mkSet $ vars g ) ( Relation.make $ do ([l],[r]) <- pairs return (l, r) ) rewrite "" = return "" rewrite (c : cs) = do rest <- rewrite cs [ c : rest ] ++ [ rhs ++ rest | let ds = Relation.images chains c , ( [ d ], rhs ) <- nopairs , d `elementOf` ds ] neu = do (lhs, rhs) <- pairs rhs' <- rewrite rhs guard $ rhs' /= rhs return (lhs, rhs') in g { regeln = mkSet $ neu ++ nopairs }
florianpilz/autotool
src/Grammatik/CF/Kettenfrei.hs
gpl-2.0
1,134
12
13
326
387
212
175
32
2
{-# LANGUAGE FlexibleInstances, GADTs, MultiParamTypeClasses, TypeOperators, TypeSynonymInstances, ViewPatterns #-} module Data.Type.Equality.Generics where import Data.Type.Equality import GHC.Generics import Unsafe.Coerce (unsafeCoerce) sameRep' :: (Generic a, Generic b, Rep a ~ D1 d f, Rep b ~ D1 d' f', Datatype d, Datatype d', SameStructure f f') => Rep a x -> Rep b x -> Maybe (a :~: b) sameRep' l r = do Refl <- sameRep l r return $ unsafeCoerce Refl sameRep :: (Datatype d, Datatype d', SameStructure f f') => D1 d f a -> D1 d' f' a -> Maybe (D1 d f :~: D1 d' f') sameRep l@(M1 l') r@(M1 r') = do Refl <- sameDatatype l r Refl <- sameStructure l' r' return Refl nameAndMod :: Datatype d => D1 d f a -> (String, String) nameAndMod d = (datatypeName d, moduleName d) sameDatatype :: (Datatype d, Datatype d') => D1 d f a -> D1 d' f' a' -> Maybe (d :~: d') sameDatatype (nameAndMod -> l) (nameAndMod -> r) | l == r = Just $ unsafeCoerce Refl sameDatatype _ _ = Nothing class SameStructure f f' where sameStructure :: f a -> f' a -> Maybe (f :~: f') both :: (f :+: g) a -> (f a, g a) both = const (undefined, undefined) instance (SameStructure f f', SameStructure g g') => SameStructure (f :+: g) (f' :+: g') where sameStructure (both -> (x, y)) (both -> (x', y')) = do Refl <- x `sameStructure` x' Refl <- y `sameStructure` y' return Refl instance (Constructor c, Constructor c') => SameStructure (C1 c f) (C1 c' f') where sameStructure l r = do Refl <- sameConstructor l r; return Refl sameConstructor :: (Constructor c, Constructor c') => C1 c f a -> C1 c' f' a' -> Maybe (C1 c f a :~: C1 c' f' a') sameConstructor (conName -> l) (conName -> r) | l == r = Just $ unsafeCoerce Refl sameConstructor _ _ = Nothing {- data (:+:) (f :: * -> *) (g :: * -> *) p = L1 (f p) | R1 (g p) -}
minad/omega
mosaic/TyEqGen.hs
bsd-3-clause
1,892
6
11
452
827
416
411
30
1
{-# LANGUAGE NoImplicitPrelude #-} import Prelude (Bool, Char) class Eq a where (==) :: a -> a -> Bool undefined = undefined not :: Bool -> Bool not = undefined const :: a -> b -> a const = undefined toUpper :: Char -> Char toUpper = undefined test x = let y = x == x in not x
themattchan/tandoori
input/boolchar-class.hs
bsd-3-clause
294
0
9
77
120
63
57
13
1
module A2 where --Any type/data constructor name declared in this module can be renamed. --Any type variable can be renamed. --Rename type Constructor 'BTree' to 'MyBTree' data BTree a = Empty | T a (BTree a) (BTree a) deriving Show buildtree :: Ord a => [a] -> BTree a buildtree [] = Empty buildtree (x:xs) = insert x (buildtree xs) insert :: Ord a => a -> BTree a -> BTree a insert val Empty = T val Empty Empty insert val t@(T tval left right) | val > tval = T tval left (insert val right) | otherwise = (T tval left right) main :: BTree Int main = buildtree [3,1,2]
SAdams601/HaRe
old/testing/unfoldAsPatterns/A2_TokOut.hs
bsd-3-clause
610
0
8
152
232
119
113
13
1
module D4 where {- generalise function 'f' on the sub-expression '1' with a new parameter 'z', This refactoring affects the modules 'D4' and 'A4'-} y=0 f x =x + ( y + 1) sumFun xs = sum $ map f xs
RefactoringTools/HaRe
test/GenDef/D4.hs
bsd-3-clause
206
0
7
50
46
25
21
4
1
{- | Module : Language.Javascript.JMacro Copyright : (c) Gershom Bazerman, 2010 License : BSD 3 Clause Maintainer : [email protected] Stability : experimental Simple DSL for lightweight (untyped) programmatic generation of Javascript. A number of examples are available in the source of "Language.Javascript.JMacro.Prelude". Functions to generate generic RPC wrappers (using json serialization) are available in "Language.Javascript.JMacro.Rpc". usage: > renderJs [$jmacro|fun id x -> x|] The above produces the id function at the top level. > renderJs [$jmacro|var id = \x -> x;|] So does the above here. However, as id is brought into scope by the keyword var, you do not get a variable named id in the generated javascript, but a variable with an arbitrary unique identifier. > renderJs [$jmacro|var !id = \x -> x;|] The above, by using the bang special form in a var declaration, produces a variable that really is named id. > renderJs [$jmacro|function id(x) {return x;}|] The above is also id. > renderJs [$jmacro|function !id(x) {return x;}|] As is the above (with the correct name). > renderJs [$jmacro|fun id x {return x;}|] As is the above. > renderJs [$jmacroE|foo(x,y)|] The above is an expression representing the application of foo to x and y. > renderJs [$jmacroE|foo x y|]] As is the above. > renderJs [$jmacroE|foo (x,y)|] While the above is an error. (i.e. standard javascript function application cannot seperate the leading parenthesis of the argument from the function being applied) > \x -> [$jmacroE|foo `(x)`|] The above is a haskell expression that provides a function that takes an x, and yields an expression representing the application of foo to the value of x as transformed to a Javascript expression. > [$jmacroE|\x ->`(foo x)`|] Meanwhile, the above lambda is in Javascript, and brings the variable into scope both in javascript and in the enclosed antiquotes. The expression is a Javascript function that takes an x, and yields an expression produced by the application of the Haskell function foo as applied to the identifier x (which is of type JExpr -- i.e. a Javascript expression). Other than that, the language is essentially Javascript (1.5). Note however that one must use semicolons in a principled fashion -- i.e. to end statements consistently. Otherwise, the parser will mistake the whitespace for a whitespace application, and odd things will occur. A further gotcha exists in regex literals, whicch cannot begin with a space. @x / 5 / 4@ parses as ((x / 5) / 4). However, @x /5 / 4@ will parse as x(/5 /, 4). Such are the perils of operators used as delimeters in the presence of whitespace application. Additional features in jmacro (documented on the wiki) include an infix application operator, and an enhanced destructuring bind. Additional datatypes can be marshalled to Javascript by proper instance declarations for the ToJExpr class. An experimental typechecker is available in the "Language.Javascript.JMacro.Typed" module. -} -- module names have been changed for temporary inclusion in GHCJS tree module Compiler.JMacro ( module Compiler.JMacro.QQ, module Compiler.JMacro.Base, module Compiler.JMacro.Lens, j, je ) where import Language.Haskell.TH.Quote (QuasiQuoter) import Compiler.JMacro.Base hiding (expr2stat) import Compiler.JMacro.QQ import Compiler.JMacro.Lens -- shorter names for jmacro / jmacroE j :: QuasiQuoter j = jmacro je :: QuasiQuoter je = jmacroE
k-bx/ghcjs
src/Compiler/JMacro.hs
mit
3,494
0
5
597
94
63
31
13
1
{-# LANGUAGE TypeOperators #-} module T7609 where data X a b f :: (a `X` a, Maybe) f = undefined g :: (a `X` a) => Maybe g = undefined
urbanslug/ghc
testsuite/tests/typecheck/should_fail/T7609.hs
bsd-3-clause
138
0
7
33
57
36
21
-1
-1
{-# LANGUAGE ImpredicativeTypes, FlexibleContexts #-} module T2846 where f :: String f = show ([1,2,3] :: [Num a => a])
siddhanathan/ghc
testsuite/tests/typecheck/should_fail/T2846b.hs
bsd-3-clause
122
0
9
22
43
26
17
-1
-1
{- rrdgraph-haskell – Haskell DSL for rendering RRD graphs using RRDtool Copyright © 2011 Johan Kiviniemi <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -} {-# LANGUAGE OverloadedStrings #-} module Data.RRDGraph.VDef ( VDef (..) , vMaximum , vMinimum , vAverage , vStDev , vLast , vFirst , vTotal , vLslSlope , vLslInt , vLslCorrel , vPercent , vPercentNAN ) where import Data.RRDGraph.CDef import Data.RRDGraph.Internal -- | A representation of VDEF. data VDef = VDefStack [CDef] [StackItem] deriving (Eq, Ord, Read, Show) vMaximum :: CDef -> VDef vMinimum :: CDef -> VDef vAverage :: CDef -> VDef vStDev :: CDef -> VDef vLast :: CDef -> VDef vFirst :: CDef -> VDef vTotal :: CDef -> VDef vLslSlope :: CDef -> VDef vLslInt :: CDef -> VDef vLslCorrel :: CDef -> VDef vPercent :: CDef -> CDefNum -> VDef vPercentNAN :: CDef -> CDefNum -> VDef vMaximum a = VDefStack [a] ["MAXIMUM"] vMinimum a = VDefStack [a] ["MINIMUM"] vAverage a = VDefStack [a] ["AVERAGE"] vStDev a = VDefStack [a] ["STDEV"] vLast a = VDefStack [a] ["LAST"] vFirst a = VDefStack [a] ["FIRST"] vTotal a = VDefStack [a] ["TOTAL"] vLslSlope a = VDefStack [a] ["LSLSLOPE"] vLslInt a = VDefStack [a] ["LSLINT"] vLslCorrel a = VDefStack [a] ["LSLCORREL"] vPercent a n = VDefStack [a] [StackItem . numericField $ n, "PERCENT"] vPercentNAN a n = VDefStack [a] [StackItem . numericField $ n, "PERCENTNAN"]
ion1/rrdgraph-haskell
Data/RRDGraph/VDef.hs
isc
2,120
0
8
406
473
264
209
43
1
{-# LANGUAGE DeriveFunctor #-} module Shakespeare.Dynamic.Event where import Data.Aeson import Control.Applicative import Control.Monad import Data.Foldable import Data.Monoid import Data.Traversable -- | An event type that allows for a base event type -- so that you have a base state for all applications that take an event data Event a = Unfired -- ^ The state of an eveent that has never been used | Fired a -- ^ The value of an event. deriving (Show, Read, Eq, Ord, Functor) fromEvent :: Event a -> a -> a fromEvent Unfired x = x fromEvent (Fired x) _ = x instance Applicative Event where pure a = Fired a (Fired f) <*> (Fired x) = Fired $ f x _ <*> _ = Unfired instance Alternative Event where empty = Unfired Unfired <|> f = f f <|> _ = f instance Monad Event where (Fired a) >>= f = f a Unfired >>= _ = Unfired return a = Fired a instance MonadPlus Event where mzero = Unfired mplus Unfired x = x mplus f@(Fired _) _ = f instance Foldable Event where foldMap f (Fired e) = f e foldMap _ _ = mempty foldr f b (Fired e) = f e b foldr _ b _ = b instance Traversable Event where traverse f (Fired e) = Fired <$> f e traverse _ Unfired = pure $ Unfired instance (Monoid m) => Monoid (Event m) where mempty = Unfired mappend (Fired e1) (Fired e2) = Fired $ e1 <> e2 mappend Unfired (Fired e) = Fired e mappend (Fired e) Unfired = Fired e mappend Unfired Unfired = Unfired instance (FromJSON a) => FromJSON (Event a) where parseJSON Null = pure Unfired parseJSON obj = Fired <$> parseJSON obj instance (ToJSON a) => ToJSON (Event a) where toJSON Unfired = Null toJSON (Fired a) = toJSON a
plow-technologies/shakespeare-dynamic
ghcjs-shakespeare-dynamic/src/Shakespeare/Dynamic/Event.hs
mit
1,730
0
9
448
627
317
310
50
1
{-# LANGUAGE TypeFamilies #-} module Light.Geometry.AABB -- ADT ( AABB(..), isEmpty, fromPoint, fromPoints -- Arithmetic , addPoint, addPoints, aabbUnion, overlaps, isInside, aabbSurfaceArea, volume, corners ) where import Light.Geometry.Point import Light.Geometry.Vector data AABB = EmptyAABB | AABB { aabbMin :: !Point , aabbMax :: !Point } deriving (Eq, Show, Read) isEmpty :: AABB -> Bool isEmpty EmptyAABB = True isEmpty _ = False fromPoint :: Point -> AABB fromPoint = addPoint EmptyAABB fromPoints :: [Point] -> AABB fromPoints = addPoints EmptyAABB addPoint :: AABB -> Point -> AABB addPoint EmptyAABB p = AABB p p addPoint (AABB n x) p = AABB (Point (min (px n) (px p)) (min (py n) (py p)) (min (pz n) (pz p))) (Point (max (px x) (px p)) (max (py x) (py p)) (max (pz x) (pz p))) addPoints :: AABB -> [Point] -> AABB addPoints = foldl addPoint aabbUnion :: AABB -> AABB -> AABB aabbUnion EmptyAABB b = b aabbUnion b EmptyAABB = b aabbUnion (AABB n x) (AABB o y) = AABB (Point (min (px n) (px o)) (min (py n) (py o)) (min (pz n) (pz o))) (Point (max (px x) (px y)) (max (py x) (py y)) (max (pz x) (pz y))) overlaps :: AABB -> AABB -> Bool overlaps _ EmptyAABB = False overlaps EmptyAABB _ = False overlaps b (AABB n x) = isInside b n || isInside b x isInside :: AABB -> Point -> Bool isInside EmptyAABB _ = False isInside (AABB n x) p = px p >= px n && px p <= px x && py p >= py n && py p <= py x && pz p >= pz n && pz p <= pz x aabbSurfaceArea :: AABB -> Double aabbSurfaceArea EmptyAABB = 0 aabbSurfaceArea (AABB n x) = 2 * ((dx d * dy d) + (dx d * dz d) + (dy d * dz d)) where d = x .-. n volume :: AABB -> Double volume EmptyAABB = 0 volume (AABB x n) = dx d * dy d * dz d where d = x .-. n corners :: AABB -> [Point] corners EmptyAABB = [] corners (AABB n x) = [ Point nx ny nz, Point nx ny xz, Point nx xy nz, Point nx xy xz , Point xx ny nz, Point xx ny xz, Point xx xy nz, Point xx xy xz ] where nx=px n; ny=py n; nz=pz n xx=px x; xy=py x; xz=pz x -- TODO: convert to bounding sphere
jtdubs/Light
src/Light/Geometry/AABB.hs
mit
2,240
0
16
659
1,104
566
538
55
1
{-# htermination fmToList_GE :: (Ord a, Ord k) => FiniteMap (a,k) b -> (a,k) -> [((a,k),b)] #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_fmToList_GE_12.hs
mit
114
0
3
20
5
3
2
1
0