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
{-# OPTIONS_GHC -fno-warn-orphans #-} module UnitTests.PopulationSpec (spec, Arbitrary) where import Test.Hspec import Test.QuickCheck import System.Random import Data.Random import qualified Data.MultiSet as MultiSet import Genes import Individual import Population.Internal import Phenotype import UnitTests.GenesSpec() import UnitTests.PhenotypeSpec() instance Arbitrary Individual where arbitrary = do s <- elements [M, F] g <- arbitrary d1 <- arbitrary d2 <- arbitrary p <- arbitrary return $ Individual s g (d1, d2) p instance Arbitrary Population where arbitrary = Population <$> arbitrary <*> arbitrary instance Arbitrary Sex where arbitrary = elements [F, M] spec :: Spec spec = parallel $ do describe "Population" $ do it "consist of males and females" $ property ( \p -> MultiSet.fromList p == MultiSet.fromList (males p ++ females p) ) it "males are all males" $ property $ all (\i -> sex i == M) . males it "females are all females" $ property $ all (\i -> sex i == F) . females describe "allSurvive selection" $ it "doesn't change the population" $ property ( \p i -> let survivors = fst $ sampleState (allSurvive p) $ mkStdGen i in p == survivors ) describe "extinction" $ it "has no surviors" $ property ( \p i -> let survivingPopulation = fst $ sampleState (extinction p) $ mkStdGen i in [] == survivingPopulation ) describe "chosenPairs" $ do it "there are no chosen pairs when chosing from empty population" $ property $ forAll (choose (1, 33)) (\fraction i -> let chosen = fst $ sampleState (chosenPairs fraction []) $ mkStdGen i in [] == chosen ) it "there is less chosen pairs when choosing a smaller fraction from a population" $ property $ forAll (choose (3, 33)) (\fraction i p -> let chosen1 = fst $ sampleState (chosenPairs fraction p) $ mkStdGen i chosen2 = fst $ sampleState (chosenPairs 2 p) $ mkStdGen i in length chosen1 <= length chosen2 ) describe "fittest" $ it "produces population of limited size" $ property ( \p i -> let survivingPopulation = fst $ sampleState (fittest 3 (const 1.0) p) $ mkStdGen i in 3 >= length survivingPopulation ) describe "hard selection" $ do it "keeps all members of population, that have fitness greater than treshold" $ property ( \p i threshold -> let fitness' = const $ threshold + 0.1 survivingPopulation = fst $ sampleState (hardSelection fitness' threshold p) $ mkStdGen i in survivingPopulation `shouldBe` p ) it "kills all members of population, that have fitness smaller than treshold" $ property ( \p i threshold -> let fitness' = const $ threshold - 0.1 survivingPopulation = fst $ sampleState (hardSelection fitness' threshold p) $ mkStdGen i in survivingPopulation `shouldBe` [] ) it "kills all members of population, that are too old" $ property ( \p i currentGeneration maximumAge -> let survivingPopulation = fst $ sampleState (killOld maximumAge currentGeneration p) $ mkStdGen i age :: Individual -> Int age individual = currentGeneration - birthGeneration individual in survivingPopulation `shouldSatisfy` (\survivors -> null survivors || maximum (map age survivors) <= maximumAge) ) it "keeps young enough individuals" $ property ( \i -> let youngling = Individual { sex=F, birthGeneration=10, chromosomes=(DnaString [], DnaString[]), phenotype=Phenotype [] } population = [youngling] survivingPopulation = fst $ sampleState (killOld 5 13 population) $ mkStdGen i in survivingPopulation `shouldBe` [youngling] ) it "can keep only part of the population" $ property ( \ populationPart1 populationPart2 i g1 g2 g3 g4 macho1 macho2 -> let fitness' :: Fitness fitness' p | macho1 == p = 100.0 | macho2 == p = 111.0 | otherwise = 0.1 populationWithMacho = [Individual M 1 (g1, g2) macho1] ++ populationPart1 ++ [Individual M 0 (g3, g4) macho2] ++ populationPart2 survivingPopulation = fst $ sampleState (hardSelection fitness' 10.0 populationWithMacho) $ mkStdGen i in map phenotype survivingPopulation `shouldBe` [macho1, macho2] )
satai/FrozenBeagle
Simulation/Lib/testsuite/UnitTests/PopulationSpec.hs
bsd-3-clause
5,348
0
24
2,056
1,358
675
683
98
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {- | This module contains some code to deal with HTTP 1.1 that can possibly be used in other REST projects. -} module HttpUtil ( -- * HTTP 1.1 tools. finishWithCode , err , errIfNothing , supportedMethods , routeByMethodWith405 , checkExpect , checkContent -- * 'Etag' manipulation and checking. , EtagPattern , pEtagPattern , etag , checkMatch -- * HTTP 1.1 IO. , maxBodyLen , readLBS , finishWithLBS ) where import Data.Int (Int64) import Data.List import qualified Data.Foldable as F import Data.Maybe import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Char8 as C8 import Blaze.ByteString.Builder import Data.Attoparsec import Data.Attoparsec.ByteString.Char8 import Control.Monad import qualified Control.Monad.CatchIO as MIO (catch) import Crypto.Hash ------------------------------------------------------------------------------ import Snap import qualified Snap.Iteratee as I import Snap.Internal.Parsing ------------------------------------------------------------------------------ import Type ------------------------------------------------------------------------------ -- HTTP 1.1 tools specialized in JSON. ------------------------------------------------------------------------------ -- | Finish with an empty response, along with the code and the @ETag@ (if available). finishWithCode :: Int -> Maybe Etag -> Handler b v a finishWithCode code maybetag = finishWith $ setResponseCode code $ maybe id (setHeader "Etag" . quoteEtag) maybetag emptyResponse -- | A specialized 'finishWithCode' without @ETag@. err :: Int -> Handler b v a err code = finishWithCode code Nothing -- | A convenience function which calls 'err' when the result is 'Nothing'. errIfNothing :: Int -> Maybe a -> Handler b v a errIfNothing code = maybe (err code) return -- | A convenience function which calls 'err' when the result is 'Left x'. errIfLeft :: Int -> Either a' a -> Handler b v a errIfLeft code = either (const $ err code) return -- | Supported methods in this module. supportedMethods :: [Method] supportedMethods = [GET, HEAD, POST, PUT, DELETE] -- | Method-based routing. The mapping needs to be exhaustive so that -- a proper HTTP @405@ error message can be generated, -- where methods without handlers are assumed to be disallowed. -- Multiple handlers for the same method are joined with '<|>'. -- HTTP error @501@ is generated for any method not in 'supportedMethods'. -- -- Assigning a handler to an unsupported method has no effect -- (except increasing the computation time). routeByMethodWith405 :: [([Method], Handler b v a)] -> Handler b v a routeByMethodWith405 r = do m <- rqMethod <$> getRequest when (m `notElem` supportedMethods) $ err 501 let handlers = matchedHandlers m when (null handlers) err405 foldl1 (<|>) handlers where matchedHandlers m = map snd $ filter (elem m . fst) r ------------------------------------------- err405 = finishWith $ setResponseCode 405 $ setHeader "Allow" assigned' emptyResponse where assigned = nub $ concatMap fst r assigned' = C8.intercalate ", " $ map (C8.pack . show) assigned -- | Check the HTTP 1.1 header @Expect@. checkExpect :: Handler b v () checkExpect = do rq <- getRequest when (isJust $ getHeader "Expect" rq) $ err 417 -- | Check @Content-*@. This is required for the @PUT@ method. -- TODO: Take a MIME and check @Content-Type@. checkContent :: Handler b v () checkContent = do rq <- getRequest when (isJust $ getHeader "Content-Encoding" rq) $ err 501 when (isJust $ getHeader "Content-Language" rq) $ err 501 when (isJust $ getHeader "Content-MD5" rq) $ err 501 when (isJust $ getHeader "Content-Range" rq) $ err 501 ------------------------------------------------------------------------------ -- Etag ------------------------------------------------------------------------------ -- | The data type for the content of the headers @If-Match@ and @If-None-Match@. data NormalEtag = StrongNE Etag | WeakNE Etag deriving (Eq, Show) -- | The data type for the content of the headers @If-Match@ and @If-None-Match@. data EtagPattern = WildE | NormalE [NormalEtag] deriving Show -- | The parser for the headers @If-Match@ and @If-None-Match@. pEtagPattern :: Parser EtagPattern pEtagPattern = pSpaces *> (pWildPattern <|> pNormalPatterns) <* pSpaces where pWildPattern = char '*' *> return WildE pNormalPatterns = do a <- pNormalPattern b <- many (pSpaces *> char ',' *> pSpaces *> pNormalPattern) return . NormalE $ a:b pNormalPattern = choice [ StrongNE <$> pQuotedString , WeakNE <$> (string "W/" *> pQuotedString) ] -- | Matching for @ETags@. etagMatch :: EtagPattern -> Maybe Etag -> Bool etagMatch _ Nothing = False etagMatch WildE (Just _) = True etagMatch (NormalE l) (Just t) = StrongNE t `elem` l -- | A function to generate @ETag@ for a body. etag :: LB.ByteString -> Etag etag str = digestToHexByteString (hashlazy str :: Digest Skein256_256) -- | A function to quote an @ETag@ according to the standard. quoteEtag :: Etag -> ByteString quoteEtag tag = C8.concat ["\"", C8.concatMap quote tag, "\""] where quote '"' = "\"" quote x = C8.singleton x -- | Check @If-Match@, @If-None-Match@ and @If-Unmodified-Since@ -- with respect to the @ETag@ of the resource on the server. -- 'Nothing' is given if the requested resource does not exist. -- The check is still required in that case because HTTP 1.1 allows -- wild patterns. -- -- We always reject @If-Unmodified-Since@ with @501@ -- because we don't use timestamps. The HTTP 1.1 standard -- is not crystal clear on the proper error code, but we think -- this is a more reasonable choice than the @412@ error code -- when the timestamps are intentionally avoided. checkMatch :: Maybe Etag -> Handler b v () checkMatch tag = do rq <- getRequest when (isJust $ getHeader "If-Unmodified-Since" rq) $ err 501 F.forM_ (getHeader "If-Match" rq) $ parseEP >=> ifMatchHandler F.forM_ (getHeader "If-None-Match" rq) $ parseEP >=> ifNoneMatchHandler where parseEP = errIfLeft 400 . parseOnly pEtagPattern ifMatchHandler pat = unless (pat `etagMatch` tag) $ err 412 ifNoneMatchHandler pat = when (pat `etagMatch` tag) $ methods [GET, HEAD] (finishWithCode 304 tag) <|> err 412 ------------------------------------------------------------------------------ -- HTTP 1.1 IO specilized in JSON. ------------------------------------------------------------------------------ -- | Maximum length for the request body. maxBodyLen :: Int64 maxBodyLen = 4096 -- | Read the HTTP request up to 'maxBodyLen'. readLBS :: Handler b v LB.ByteString readLBS = readRequestBody maxBodyLen `MIO.catch` \(_ :: I.TooManyBytesReadException) -> err 413 -- | Finish with the given body immediately. finishWithLBS :: Mime -> LB.ByteString -> Maybe Etag -> Handler b v c finishWithLBS mime str tag = finishWith $ setResponseBody body $ maybe id (setHeader "ETag" . quoteEtag) tag $ setContentType mime emptyResponse where body = I.enumBuilder $ fromLazyByteString str
g0v/encoding-mashup-server
src/HttpUtil.hs
bsd-3-clause
7,427
0
15
1,459
1,515
805
710
118
2
{-# LANGUAGE ScopedTypeVariables #-} module Math.Probably.IterLap where import Math.Probably.Sampler import Math.Probably.FoldingStats import Math.Probably.MCMC (empiricalMean, empiricalCovariance) import Math.Probably.PDF (posdefify) import Debug.Trace import Data.Maybe weightedMeanCov :: [(Vector Double, Double)] -> (Vector Double, Matrix Double) weightedMeanCov pts = (mu, cov) where mu = sum $ flip map pts $ \(x,w) -> scale w x npts = dim $ fst $ head pts sumSqrWs = sum $ flip map pts $ \(x,w) -> w*w factor = 1/(1-sumSqrWs) xmeans :: [Double] xmeans = flip map [0..npts-1] $ \i -> mean $ flip map pts $ \(x,w) -> x@>i cov = scale factor $ buildMatrix npts npts $ \(j,k) -> sum $ flip map pts $ \(xi,wi) -> wi*(xi@>j - xmeans!!j)* (xi@>k - xmeans!!k) mean :: [Double] -> Double mean xs = sum xs / realToFrac (length xs) improve :: Int -> (Vector Double -> Double) -> (Vector Double, Matrix Double) -> Sampler (Vector Double, Matrix Double) improve n f (mu, cov) = do xs <- sequence $ replicate n $ multiNormal mu cov let xps = catMaybes $ map (\x-> let fx = f x in if isNaN fx || isInfinite fx then Nothing else Just (x,fx)) xs pmin = runStat (before (minFrom 1e80) snd) xps psubmin = map (\(x,p)-> (x, exp $ p - pmin)) xps psum = sum $ map snd psubmin ws = map (\(x,p)-> (x,p/psum)) psubmin (mu', cov') = weightedMeanCov $ ws return $ (mu', posdefify $ scale 2 cov') iterateM :: Int -> (a -> Sampler a) -> a-> Sampler a iterateM 0 _ x = return x iterateM n f x = do newx <- f x iterateM (n-1) f newx iterLap :: [Int] -> (Vector Double -> Double) -> (Vector Double, Matrix Double) -> Sampler (Vector Double, Matrix Double) iterLap [] _ x = return x iterLap (n:ns) f x = do newx <- improve n f x iterLap (ns) f newx
glutamate/probably-base
Math/Probably/IterLap.hs
bsd-3-clause
1,897
0
18
488
911
479
432
46
2
{-# LANGUAGE OverloadedStrings #-} module System.Network.ZMQ.MDP.Util where import System.ZMQ as Z import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as BS import Control.Applicative -- Receive until no more messages receiveUntilEnd :: Socket a -> IO [ByteString] receiveUntilEnd sock = do more <- Z.moreToReceive sock if more then (:) <$> Z.receive sock [] <*> receiveUntilEnd sock else return [] -- Receive until an empty frame receiveUntilEmpty :: Socket a -> IO [ByteString] receiveUntilEmpty sock = do frame <- Z.receive sock [] if BS.null frame then return [] else (frame:) <$> receiveUntilEmpty sock -- -- Sends a multipart message -- sendAll :: Socket a -> [ByteString] -> IO () sendAll sock = go where go [x] = Z.send sock x [] go (x:xs) = Z.send sock x [SndMore] >> go xs go [] = error "empty send not allowed"
mwotton/majordomo
lib/System/Network/ZMQ/MDP/Util.hs
bsd-3-clause
946
0
11
230
300
159
141
23
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ForeignFunctionInterface #-} module Tinfoil.Internal.Sodium.Foreign ( sodiumInit , aesgcmSupported ) where import Foreign.C (CInt(..)) import P import System.IO (IO) import Tinfoil.Internal.Sodium.Data -- | -- Performs global init stuff in the C library. Some libsodium functionality -- can be used without this function being called, but will generally result -- in loss of thread-safety - in other words, don't do it. -- -- This function is thread-safe and idempotent. It doesn't allocate anything on -- the heap, but does keep one file descriptor open (for /dev/urandom); it -- will only do this once. foreign import ccall safe "sodium_init" sodium_init :: IO CInt sodiumInit :: IO SodiumInitStatus sodiumInit = sodium_init >>= \x -> case x of 0 -> pure SodiumInitialised -- init succeeded 1 -> pure SodiumInitialised -- already initialised _ -> pure SodiumNotInitialised -- | -- Whether or not the CPU supports the x86 extensions required for -- hardware-accelerated AES-GCM (the only kind libsodium supports). -- -- sodium_init must be called before this function. aesgcmSupported :: IO AESGCMSupport aesgcmSupported = sodium_aesgcm_is_available >>= \x -> case x of 1 -> pure AESGCMSupported _ -> pure AESGCMNotSupported foreign import ccall safe "crypto_aead_aes256gcm_is_available" sodium_aesgcm_is_available :: IO CInt
ambiata/tinfoil
src/Tinfoil/Internal/Sodium/Foreign.hs
bsd-3-clause
1,495
0
10
287
199
117
82
25
3
module Markup where import Lucid (Html, toHtml) import Lucid.Html5 homepage :: Html () homepage = withHeader $ form_ [method_ "POST", action_ "/upload", enctype_ "multipart/form-data"] $ do input_ [type_ "file", name_ "upload", accept_ "image/png"] br_ [] input_ [type_ "submit", value_ "compress"] uploadNotFound :: Html () uploadNotFound = withHeader "uploaded file not found" withHeader :: Html () -> Html () withHeader x = do doctype_ head_ $ do title_ "crusher" link_ [rel_ "stylesheet", href_ "/stylesheet.css", type_ "text/css"] body_ $ div_ [id_ "main"] $ do a_ [href_ "/"] $ h1_ "crusher" x error :: String -> Html () error err = withHeader $ do "an error occurred:" pre_ $ toHtml err
intolerable/crusher
src/Markup.hs
bsd-3-clause
751
0
13
165
280
132
148
26
1
-- #hide -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.PrimitiveMode -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- This is a purely internal module for (un-)marshaling PrimitiveMode. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.PrimitiveMode ( PrimitiveMode(..), marshalPrimitiveMode, unmarshalPrimitiveMode ) where import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum ) -------------------------------------------------------------------------------- -- | Specification of the way the vertices given during 'renderPrimitive' are -- interpreted. In the description of the constructors, /n/ is an integer count -- starting at one, and /N/ is the total number of vertices specified. data PrimitiveMode = Points -- ^ Treats each vertex as a single point. Vertex /n/ defines point /n/. -- /N/ points are drawn. | Lines -- ^ Treats each pair of vertices as an independent line segment. Vertices -- 2/n/-1 and 2/n/ define line /n/. /N/\/2 lines are drawn. | LineLoop -- ^ Draws a connected group of line segments from the first vertex to the -- last, then back to the first. Vertices /n/ and /n/+1 define line /n/. -- The last line, however, is defined by vertices /N/ and 1. /N/ lines -- are drawn. | LineStrip -- ^ Draws a connected group of line segments from the first vertex to the -- last. Vertices /n/ and /n/+1 define line /n/. /N/-1 lines are drawn. | Triangles -- ^ Treats each triplet of vertices as an independent triangle. Vertices -- /3n-2/, /3n-1/, and /3n/ define triangle /n/. /N\/3/ triangles are drawn. | TriangleStrip -- ^ Draws a connected group of triangles. One triangle is defined for each -- vertex presented after the first two vertices. For odd /n/, vertices -- /n/, /n/+1, and /n/+2 define triangle /n/. For even /n/, vertices /n/+1, -- /n/, and /n/+2 define triangle /n/. /N/-2 triangles are drawn. | TriangleFan -- ^ Draws a connected group of triangles. One triangle is defined for each -- vertex presented after the first two vertices. Vertices 1, /n/+1, and -- /n/+2 define triangle /n/. /N/-2 triangles are drawn. | Quads -- ^ Treats each group of four vertices as an independent quadrilateral. -- Vertices 4/n/-3, 4/n/-2, 4/n/-1, and 4/n/ define quadrilateral /n/. -- /N/\/4 quadrilaterals are drawn. | QuadStrip -- ^ Draws a connected group of quadrilaterals. One quadrilateral is --defined for each pair of vertices presented after the first pair. -- Vertices 2/n/-1, 2/n/, 2/n/+2, and 2/n/+1 define quadrilateral /n/. -- /N/\/2-1 quadrilaterals are drawn. Note that the order in which vertices -- are used to construct a quadrilateral from strip data is different from -- that used with independent data. | Polygon -- ^ Draws a single, convex polygon. Vertices 1 through /N/ define this -- polygon. deriving ( Eq, Ord, Show ) marshalPrimitiveMode :: PrimitiveMode -> GLenum marshalPrimitiveMode x = case x of Points -> 0x0 Lines -> 0x1 LineLoop -> 0x2 LineStrip -> 0x3 Triangles -> 0x4 TriangleStrip -> 0x5 TriangleFan -> 0x6 Quads -> 0x7 QuadStrip -> 0x8 Polygon -> 0x9 unmarshalPrimitiveMode :: GLenum -> PrimitiveMode unmarshalPrimitiveMode x | x == 0x0 = Points | x == 0x1 = Lines | x == 0x2 = LineLoop | x == 0x3 = LineStrip | x == 0x4 = Triangles | x == 0x5 = TriangleStrip | x == 0x6 = TriangleFan | x == 0x7 = Quads | x == 0x8 = QuadStrip | x == 0x9 = Polygon | otherwise = error ("unmarshalPrimitiveMode: illegal value " ++ show x)
FranklinChen/hugs98-plus-Sep2006
packages/OpenGL/Graphics/Rendering/OpenGL/GL/PrimitiveMode.hs
bsd-3-clause
3,968
0
9
860
381
222
159
40
10
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Trustworthy #-} #endif -- -- | -- Module : Data.ByteString.UTF8 -- Copyright : (c) Iavor S. Diatchki 2009 -- License : BSD3-style (see LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This module provides fast, validated encoding and decoding functions -- between 'ByteString's and 'String's. It does not exactly match the -- output of the Codec.Binary.UTF8.String output for invalid encodings -- as the number of replacement characters is sometimes longer. module Data.ByteString.UTF8 ( B.ByteString , decode , replacement_char , uncons , splitAt , take , drop , span , break , fromString , toString , foldl , foldr , length , lines , lines' ) where import Data.Bits import Data.Word import qualified Data.ByteString as B import Prelude hiding (take,drop,splitAt,span,break,foldr,foldl,length,lines) import Codec.Binary.UTF8.String(encode) import Codec.Binary.UTF8.Generic (buncons) -- | Converts a Haskell string into a UTF8 encoded bytestring. fromString :: String -> B.ByteString fromString xs = B.pack (encode xs) -- | Convert a UTF8 encoded bytestring into a Haskell string. -- Invalid characters are replaced with '\xFFFD'. toString :: B.ByteString -> String toString bs = foldr (:) [] bs -- | This character is used to mark errors in a UTF8 encoded string. replacement_char :: Char replacement_char = '\xfffd' -- | Try to extract a character from a byte string. -- Returns 'Nothing' if there are no more bytes in the byte string. -- Otherwise, it returns a decoded character and the number of -- bytes used in its representation. -- Errors are replaced by character '\0xFFFD'. -- XXX: Should we combine sequences of errors into a single replacement -- character? decode :: B.ByteString -> Maybe (Char,Int) decode bs = do (c,cs) <- buncons bs return (choose (fromEnum c) cs) where choose :: Int -> B.ByteString -> (Char, Int) choose c cs | c < 0x80 = (toEnum $ fromEnum c, 1) | c < 0xc0 = (replacement_char, 1) | c < 0xe0 = bytes2 (mask c 0x1f) cs | c < 0xf0 = bytes3 (mask c 0x0f) cs | c < 0xf8 = bytes4 (mask c 0x07) cs | otherwise = (replacement_char, 1) mask :: Int -> Int -> Int mask c m = fromEnum (c .&. m) combine :: Int -> Word8 -> Int combine acc r = shiftL acc 6 .|. fromEnum (r .&. 0x3f) follower :: Int -> Word8 -> Maybe Int follower acc r | r .&. 0xc0 == 0x80 = Just (combine acc r) follower _ _ = Nothing {-# INLINE get_follower #-} get_follower :: Int -> B.ByteString -> Maybe (Int, B.ByteString) get_follower acc cs = do (x,xs) <- buncons cs acc1 <- follower acc x return (acc1,xs) bytes2 :: Int -> B.ByteString -> (Char, Int) bytes2 c cs = case get_follower c cs of Just (d, _) | d >= 0x80 -> (toEnum d, 2) | otherwise -> (replacement_char, 1) _ -> (replacement_char, 1) bytes3 :: Int -> B.ByteString -> (Char, Int) bytes3 c cs = case get_follower c cs of Just (d1, cs1) -> case get_follower d1 cs1 of Just (d, _) | (d >= 0x800 && d < 0xd800) || (d > 0xdfff && d < 0xfffe) -> (toEnum d, 3) | otherwise -> (replacement_char, 3) _ -> (replacement_char, 2) _ -> (replacement_char, 1) bytes4 :: Int -> B.ByteString -> (Char, Int) bytes4 c cs = case get_follower c cs of Just (d1, cs1) -> case get_follower d1 cs1 of Just (d2, cs2) -> case get_follower d2 cs2 of Just (d,_) | d >= 0x10000 && d < 0x110000 -> (toEnum d, 4) | otherwise -> (replacement_char, 4) _ -> (replacement_char, 3) _ -> (replacement_char, 2) _ -> (replacement_char, 1) -- | Split after a given number of characters. -- Negative values are treated as if they are 0. splitAt :: Int -> B.ByteString -> (B.ByteString,B.ByteString) splitAt x bs = loop 0 x bs where loop a n _ | n <= 0 = B.splitAt a bs loop a n bs1 = case decode bs1 of Just (_,y) -> loop (a+y) (n-1) (B.drop y bs1) Nothing -> (bs, B.empty) -- | @take n s@ returns the first @n@ characters of @s@. -- If @s@ has less than @n@ characters, then we return the whole of @s@. take :: Int -> B.ByteString -> B.ByteString take n bs = fst (splitAt n bs) -- | @drop n s@ returns the @s@ without its first @n@ characters. -- If @s@ has less than @n@ characters, then we return an empty string. drop :: Int -> B.ByteString -> B.ByteString drop n bs = snd (splitAt n bs) -- | Split a string into two parts: the first is the longest prefix -- that contains only characters that satisfy the predicate; the second -- part is the rest of the string. -- Invalid characters are passed as '\0xFFFD' to the predicate. span :: (Char -> Bool) -> B.ByteString -> (B.ByteString, B.ByteString) span p bs = loop 0 bs where loop a cs = case decode cs of Just (c,n) | p c -> loop (a+n) (B.drop n cs) _ -> B.splitAt a bs -- | Split a string into two parts: the first is the longest prefix -- that contains only characters that do not satisfy the predicate; the second -- part is the rest of the string. -- Invalid characters are passed as '\0xFFFD' to the predicate. break :: (Char -> Bool) -> B.ByteString -> (B.ByteString, B.ByteString) break p bs = span (not . p) bs -- | Get the first character of a byte string, if any. -- Malformed characters are replaced by '\0xFFFD'. uncons :: B.ByteString -> Maybe (Char,B.ByteString) uncons bs = do (c,n) <- decode bs return (c, B.drop n bs) -- | Traverse a bytestring (right biased). foldr :: (Char -> a -> a) -> a -> B.ByteString -> a foldr cons nil cs = case uncons cs of Just (a,as) -> cons a (foldr cons nil as) Nothing -> nil -- | Traverse a bytestring (left biased). -- This function is strict in the accumulator. foldl :: (a -> Char -> a) -> a -> B.ByteString -> a foldl add acc cs = case uncons cs of Just (a,as) -> let v = add acc a in seq v (foldl add v as) Nothing -> acc -- | Counts the number of characters encoded in the bytestring. -- Note that this includes replacement characters. length :: B.ByteString -> Int length b = loop 0 b where loop n xs = case decode xs of Just (_,m) -> loop (n+1) (B.drop m xs) Nothing -> n -- | Split a string into a list of lines. -- Lines are terminated by '\n' or the end of the string. -- Empty lines may not be terminated by the end of the string. -- See also 'lines\''. lines :: B.ByteString -> [B.ByteString] lines bs | B.null bs = [] lines bs = case B.elemIndex 10 bs of Just x -> let (xs,ys) = B.splitAt x bs in xs : lines (B.tail ys) Nothing -> [bs] -- | Split a string into a list of lines. -- Lines are terminated by '\n' or the end of the string. -- Empty lines may not be terminated by the end of the string. -- This function preserves the terminators. -- See also 'lines'. lines' :: B.ByteString -> [B.ByteString] lines' bs | B.null bs = [] lines' bs = case B.elemIndex 10 bs of Just x -> let (xs,ys) = B.splitAt (x+1) bs in xs : lines' ys Nothing -> [bs]
ghc/packages-utf8-string
Data/ByteString/UTF8.hs
bsd-3-clause
7,652
0
21
2,202
2,128
1,127
1,001
126
8
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <[email protected]> -- Stability : experimental -- Portability : portable -- -- Shadows can be cast from lights into scene. ---------------------------------------------------------------------------- module Quaazar.Lighting.Shadow ( -- * Shadows ShadowLOD(..) ) where import Data.Aeson -- |'ShadowLOD' represents the level of detail of a shadow. There’re currently -- three levels of detail: -- -- - 'LowShadow' is a /low-detail/ shadow. You should use that LOD when you -- don’t need details (distant shadows or very big shadows); -- - 'MediumShadow' is a /medium-detail/ shadow. Used for common shadowing; -- - 'HighShadow' is a /high-detail/ shadow. You can use that LOD for close -- and/or small shadows the user might see pretty well. data ShadowLOD = LowShadow | MediumShadow | HighShadow deriving (Eq,Ord,Read,Show) instance FromJSON ShadowLOD where parseJSON = withText "shadow level of detail" parseText where parseText t | t == "low" = return LowShadow | t == "medium" = return MediumShadow | t == "high" = return HighShadow | otherwise = fail "unknown shadow level of detail"
phaazon/quaazar
src/Quaazar/Lighting/Shadow.hs
bsd-3-clause
1,412
0
11
288
159
91
68
16
0
{-# LANGUAGE CPP, BangPatterns, FlexibleContexts, FlexibleInstances #-} #ifdef GENERICS {-# LANGUAGE DefaultSignatures , TypeOperators , BangPatterns , KindSignatures , ScopedTypeVariables #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Blaze.Binary -- Copyright : 2012, Simon Meier <[email protected]> -- License : BSD3-style (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Stability : -- Portability : -- ----------------------------------------------------------------------------- module Data.Blaze.Binary ( -- * The Binary class Binary(..) , toByteString , toLazyByteString ) where import Control.Applicative import Data.Blaze.Binary.Encoding import qualified Data.Blaze.Binary.Decoding as D import Data.Word import Data.Monoid import Data.Foldable (foldMap) import Foreign -- And needed for the instances: import Data.Array.Unboxed import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as L (foldrChunks, ByteString(..)) import qualified Data.ByteString.Lazy.Builder as B import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.IntMap as IntMap import qualified Data.IntSet as IntSet import qualified Data.Ratio as R import qualified Data.Tree as T import qualified Data.Sequence as Seq #ifdef GENERICS import GHC.Generics #endif ------------------------------------------------------------------------ -- | If your compiler has support for the @DeriveGeneric@ and -- @DefaultSignatures@ language extensions (@ghc >= 7.2.1@), the 'encode' and 'decode' -- methods will have default generic implementations. -- -- To use this option, simply add a @deriving 'Generic'@ clause to your datatype -- and declare a 'Binary' instance for it without giving a definition for -- 'encode' and 'decode'. class Binary t where -- | Encode a value in the Put monad. encode :: Encoding t decode :: D.Decoder t #ifdef GENERICS default encode :: (Generic t, GBinary (Rep t)) => Encoding t encode = gEncode . from {-# INLINE encode #-} default decode :: (Generic t, GBinary (Rep t)) => D.Decoder t decode = to <$> gDecode {-# INLINE decode #-} #endif -- | Encode a value to a strict 'S.ByteString'. toByteString :: Binary t => t -> S.ByteString -- FIXME: Use more efficient conversion. toByteString = S.concat . L.toChunks . toLazyByteString -- | Encode a value to a lazy 'L.ByteString'. toLazyByteString :: Binary t => t -> L.ByteString toLazyByteString = B.toLazyByteString . render . encode ------------------------------------------------------------------------ -- Simple instances wrongTag :: Show a => String -> a -> D.Decoder b wrongTag loc tag = fail $ "decode " ++ loc ++ ": could not parse tag " ++ show tag -- The () type need never be written to disk: values of singleton type -- can be reconstructed from the type alone instance Binary () where {-# INLINE encode #-} encode () = mempty {-# INLINE decode #-} decode = return () -- Bools are encoded as a byte in the range 0 .. 1 instance Binary Bool where {-# INLINE encode #-} encode = \x -> word8 (if x then 1 else 0) decode = do tag <- D.word8 case tag of 0 -> return False 1 -> return True _ -> wrongTag "Bool" tag -- Values of type 'Ordering' are encoded as a byte in the range 0 .. 2 instance Binary Ordering where {-# INLINE encode #-} encode = \x -> word8 (case x of LT -> 0; EQ -> 1; GT -> 2) decode = do tag <- D.word8 case tag of 0 -> return LT 1 -> return EQ 2 -> return GT _ -> wrongTag "Ordering" tag ------------------------------------------------------------------------ -- Words and Ints -- Words8s are written as bytes instance Binary Word8 where {-# INLINE encode #-} encode = word8 {-# INLINE decode #-} decode = D.word8 -- Words16s are written as 2 bytes in big-endian (network) order instance Binary Word16 where {-# INLINE encode #-} encode = word16 {-# INLINE decode #-} decode = D.word16 -- Words32s are written as 4 bytes in big-endian (network) order instance Binary Word32 where {-# INLINE encode #-} encode = word32 {-# INLINE decode #-} decode = D.word32 -- Words64s are written as 8 bytes in big-endian (network) order instance Binary Word64 where {-# INLINE encode #-} encode = word64 {-# INLINE decode #-} decode = D.word64 -- Int8s are written as a single byte. instance Binary Int8 where {-# INLINE encode #-} encode = int8 {-# INLINE decode #-} decode = D.int8 -- Int16s are written as a 2 bytes in big endian format instance Binary Int16 where {-# INLINE encode #-} encode = int16 {-# INLINE decode #-} decode = D.int16 -- Int32s are written as a 4 bytes in big endian format instance Binary Int32 where {-# INLINE encode #-} encode = int32 {-# INLINE decode #-} decode = D.int32 -- Int64s are written as a 8 bytes in big endian format instance Binary Int64 where {-# INLINE encode #-} encode = int64 {-# INLINE decode #-} decode = D.int64 ------------------------------------------------------------------------ -- Words are are written as Word64s, that is, 8 bytes in big endian format instance Binary Word where {-# INLINE encode #-} encode = word {-# INLINE decode #-} decode = D.word -- Ints are are written as Int64s, that is, 8 bytes in big endian format instance Binary Int where {-# INLINE encode #-} encode = int {-# INLINE decode #-} decode = D.int instance Binary Integer where {-# INLINE encode #-} encode = integer decode = error "TODO: decode Integer!" instance (Binary a, Integral a) => Binary (R.Ratio a) where {-# INLINE encode #-} encode = \r -> encode (R.numerator r, R.denominator r) decode = error "TODO: decode Ratio!" instance Binary Char where {-# INLINE encode #-} encode = char {-# INLINE decode #-} decode = D.char instance (Binary a, Binary b) => Binary (a,b) where {-# INLINE encode #-} encode (a,b) = encode a <> encode b {-# INLINE decode #-} decode = (,) <$> decode <*> decode instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where {-# INLINE encode #-} encode (a,b,c) = encode a <> encode b <> encode c {-# INLINE decode #-} decode = (,,) <$> decode <*> decode <*> decode instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where encode (a,b,c,d) = encode a <> encode b <> encode c <> encode d decode = (,,,) <$> decode <*> decode <*> decode <*> decode instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a,b,c,d,e) where encode (a,b,c,d,e) = encode a <> encode b <> encode c <> encode d <> encode e decode = (,,,,) <$> decode <*> decode <*> decode <*> decode <*> decode -- -- and now just recurse: -- instance (Binary a, Binary b, Binary c, Binary d, Binary e , Binary f) => Binary (a,b,c,d,e,f) where encode (a,b,c,d,e,f) = encode a <> encode b <> encode c <> encode d <> encode e <> encode f decode = (,,,,,) <$> decode <*> decode <*> decode <*> decode <*> decode <*> decode instance (Binary a, Binary b, Binary c, Binary d, Binary e , Binary f, Binary g) => Binary (a,b,c,d,e,f,g) where encode (a,b,c,d,e,f,g) = encode a <> encode b <> encode c <> encode d <> encode e <> encode f <> encode g decode = (,,,,,,) <$> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f, Binary g, Binary h) => Binary (a,b,c,d,e,f,g,h) where encode (a,b,c,d,e,f,g,h) = encode a <> encode b <> encode c <> encode d <> encode e <> encode f <> encode g <> encode h decode = (,,,,,,,) <$> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f, Binary g, Binary h, Binary i) => Binary (a,b,c,d,e,f,g,h,i) where encode (a,b,c,d,e,f,g,h,i) = encode a <> encode b <> encode c <> encode d <> encode e <> encode f <> encode g <> encode h <> encode i decode = (,,,,,,,,) <$> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f, Binary g, Binary h, Binary i, Binary j) => Binary (a,b,c,d,e,f,g,h,i,j) where encode (a,b,c,d,e,f,g,h,i,j) = encode a <> encode b <> encode c <> encode d <> encode e <> encode f <> encode g <> encode h <> encode i <> encode j decode = (,,,,,,,,,) <$> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode ------------------------------------------------------------------------ -- Container types -- | Share list encoding, as it is required for faster tree encoding. {-# INLINE encodeList #-} encodeList :: Encoding a -> Encoding [a] -- encodeList f = (<> word8 0) . foldMap ((word8 1 <>) . f) -- encodeList = \f xs -> encode (length xs) <> foldMap f xs encodeList f = go (0 :: Int) mempty where go !len acc [] = encode len <> acc go !len acc (x:xs) = go (len + 1) (f x <> acc) xs -- \f xs -> encode (length xs) <> foldMap f xs -- Encoding the list in reverse order might be interesting to simplify its -- parsing. It just depends on which side is easier to get up to speed :-) -- encodeList f = (<> word8 0) . foldl (\lhs x -> word8 1 <> f x <> lhs) mempty instance Binary a => Binary [a] where {-# INLINE encode #-} encode = encodeList encode {-# INLINE decode #-} decode = D.decodeList decode instance (Binary a) => Binary (Maybe a) where {-# INLINE encode #-} encode = maybe (word8 0) ((word8 1 <>) . encode) {-# INLINE decode #-} decode = D.decodeMaybe decode instance (Binary a, Binary b) => Binary (Either a b) where {-# INLINE encode #-} encode = either ((word8 0 <>) . encode) ((word8 1 <>) . encode) {-# INLINE decode #-} decode = D.decodeEither decode decode ------------------------------------------------------------------------ -- ByteStrings (have specially efficient instances) instance Binary S.ByteString where {-# INLINE encode #-} encode = byteString {-# INLINE decode #-} decode = D.byteString instance Binary L.ByteString where encode = L.foldrChunks (\bs s -> encode bs <> s) (encode S.empty) decode = do bs <- decode if S.null bs then return L.Empty else L.Chunk bs <$> decode ------------------------------------------------------------------------ -- Maps and Sets instance (Ord a, Binary a) => Binary (Set.Set a) where {-# INLINE encode #-} encode = encode . Set.toAscList {-# INLINE decode #-} decode = Set.fromAscList <$> decode instance (Ord k, Binary k, Binary e) => Binary (Map.Map k e) where {-# INLINE encode #-} encode = encode . Map.toAscList {-# INLINE decode #-} decode = Map.fromAscList <$> decode instance Binary IntSet.IntSet where {-# INLINE encode #-} encode = encode . IntSet.toAscList {-# INLINE decode #-} decode = IntSet.fromAscList <$> decode instance (Binary e) => Binary (IntMap.IntMap e) where {-# INLINE encode #-} encode = encode . IntMap.toAscList {-# INLINE decode #-} decode = IntMap.fromAscList <$> decode ------------------------------------------------------------------------ -- Queues and Sequences instance (Binary e) => Binary (Seq.Seq e) where {-# INLINE encode #-} encode = \s -> int (Seq.length s) <> foldMap encode s {-# INLINE decode #-} decode = do D.int >>= go Seq.empty where go !s !len | len <= 0 = return s | otherwise = do x <- decode go (s Seq.|> x) (len - 1) ------------------------------------------------------------------------ -- Floating point instance Binary Double where {-# INLINE encode #-} encode = double {-# INLINE decode #-} decode = D.double instance Binary Float where {-# INLINE encode #-} encode = float {-# INLINE decode #-} decode = D.float ------------------------------------------------------------------------ -- Trees instance (Binary e) => Binary (T.Tree e) where {-# INLINE encode #-} encode = go where go (T.Node x cs) = encode x <> encodeList go cs {-# INLINE decode #-} decode = go where go = T.Node <$> decode <*> D.decodeList go ------------------------------------------------------------------------ -- Arrays instance (Binary i, Ix i, Binary e) => Binary (Array i e) where {-# INLINE encode #-} encode = \a -> encode (bounds a) <> encode (elems a) {-# INLINE decode #-} decode = listArray <$> decode <*> decode -- -- The IArray UArray e constraint is non portable. Requires flexible instances -- instance (Binary i, Ix i, Binary e, IArray UArray e) => Binary (UArray i e) where {-# INLINE encode #-} encode = \a -> encode (bounds a) <> encode (elems a) {-# INLINE decode #-} decode = listArray <$> decode <*> decode #ifdef GENERICS ------------------------------------------------------------------------ -- Generic Binary class GBinary f where gEncode :: Encoding (f a) gDecode :: D.Decoder (f a) instance GBinary a => GBinary (M1 i c a) where gEncode = gEncode . unM1 gDecode = M1 <$> gDecode {-# INLINE gEncode #-} {-# INLINE gDecode #-} instance Binary a => GBinary (K1 i a) where gEncode = encode . unK1 gDecode = K1 <$> decode {-# INLINE gEncode #-} {-# INLINE gDecode #-} instance GBinary U1 where gEncode = const mempty gDecode = pure U1 {-# INLINE gEncode #-} {-# INLINE gDecode #-} instance (GBinary a, GBinary b) => GBinary (a :*: b) where gEncode (a :*: b) = gEncode a <> gEncode b gDecode = (:*:) <$> gDecode <*> gDecode {-# INLINE gEncode #-} {-# INLINE gDecode #-} -- The following GBinary instance for sums has support for serializing types -- with up to 2^64-1 constructors. It will use the minimal number of bytes -- needed to encode the constructor. For example when a type has 2^8 -- constructors or less it will use a single byte to encode the constructor. If -- it has 2^16 constructors or less it will use two bytes, and so on till 2^64-1. #define GUARD(WORD) (size - 1) <= fromIntegral (maxBound :: WORD) #define ENCODESUM(WORD) GUARD(WORD) = encodeSum (0 :: WORD) (fromIntegral size) #define DECODESUM(WORD) GUARD(WORD) = (decode :: D.Decoder WORD) >>= checkDecodeSum (fromIntegral size) instance ( EncodeSum a, EncodeSum b , DecodeSum a, DecodeSum b , GBinary a, GBinary b , SumSize a, SumSize b) => GBinary (a :+: b) where gEncode | ENCODESUM(Word8) | ENCODESUM(Word16) | ENCODESUM(Word32) | ENCODESUM(Word64) | otherwise = sizeError "encode" size where size = unTagged (sumSize :: Tagged (a :+: b) Word64) gDecode | DECODESUM(Word8) | DECODESUM(Word16) | DECODESUM(Word32) | DECODESUM(Word64) | otherwise = sizeError "decode" size where size = unTagged (sumSize :: Tagged (a :+: b) Word64) {-# INLINE gEncode #-} {-# INLINE gDecode #-} sizeError :: Show size => String -> size -> error sizeError s size = error $ "Can't " ++ s ++ " a type with " ++ show size ++ " constructors" ------------------------------------------------------------------------ class EncodeSum f where encodeSum :: (Num word, Bits word, Binary word) => word -> word -> Encoding (f a) instance (EncodeSum a, EncodeSum b, GBinary a, GBinary b) => EncodeSum (a :+: b) where encodeSum !tag !size s = case s of L1 x -> encodeSum tag sizeL x R1 x -> encodeSum (tag + sizeL) sizeR x where sizeL = size `shiftR` 1 sizeR = size - sizeL {-# INLINE encodeSum #-} instance GBinary a => EncodeSum (C1 c a) where encodeSum !tag _ x = encode tag <> gEncode x {-# INLINE encodeSum #-} ------------------------------------------------------------------------ checkDecodeSum :: (Ord word, Bits word, DecodeSum f) => word -> word -> D.Decoder (f a) checkDecodeSum size tag | tag < size = decodeSum tag size | otherwise = fail "Unknown encoding for constructor" {-# INLINE checkDecodeSum #-} class DecodeSum f where decodeSum :: (Ord word, Num word, Bits word) => word -> word -> D.Decoder (f a) instance (DecodeSum a, DecodeSum b, GBinary a, GBinary b) => DecodeSum (a :+: b) where decodeSum !tag !size | tag < sizeL = L1 <$> decodeSum tag sizeL | otherwise = R1 <$> decodeSum (tag - sizeL) sizeR where sizeL = size `shiftR` 1 sizeR = size - sizeL {-# INLINE decodeSum #-} instance GBinary a => DecodeSum (C1 c a) where decodeSum _ _ = gDecode {-# INLINE decodeSum #-} ------------------------------------------------------------------------ class SumSize f where sumSize :: Tagged f Word64 newtype Tagged (s :: * -> *) b = Tagged {unTagged :: b} instance (SumSize a, SumSize b) => SumSize (a :+: b) where sumSize = Tagged $ unTagged (sumSize :: Tagged a Word64) + unTagged (sumSize :: Tagged b Word64) {-# INLINE sumSize #-} instance SumSize (C1 c a) where sumSize = Tagged 1 {-# INLINE sumSize #-} #endif
meiersi/blaze-binary
src/Data/Blaze/Binary.hs
bsd-3-clause
18,060
8
16
4,549
4,777
2,605
2,172
254
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.SetupWrapper -- Copyright : (c) The University of Glasgow 2006, -- Duncan Coutts 2008 -- -- Maintainer : [email protected] -- Stability : alpha -- Portability : portable -- -- An interface to building and installing Faction packages. -- If the @Built-Type@ field is specified as something other than -- 'Custom', and the current version of Faction is acceptable, this performs -- setup actions directly. Otherwise it builds the setup script and -- runs it with the given arguments. module Distribution.Client.SetupWrapper ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions, ) where import Distribution.Client.Types ( InstalledPackage ) import qualified Distribution.Simple as Simple import Distribution.Version ( Version(..), VersionRange, anyVersion , intersectVersionRanges, orLaterVersion , withinRange ) import Distribution.Package ( PackageIdentifier(..), PackageName(..), Package(..), packageName , packageVersion, Dependency(..) ) import Distribution.PackageDescription ( GenericPackageDescription(packageDescription) , PackageDescription(..), specVersion , BuildType(..), knownBuildTypes ) import Distribution.PackageDescription.Parse ( readPackageDescription ) import Distribution.Simple.Configure ( configCompiler ) import Distribution.Simple.Compiler ( CompilerFlavor(GHC), Compiler, PackageDB(..), PackageDBStack ) import Distribution.Simple.Program ( ProgramConfiguration, emptyProgramConfiguration , rawSystemProgramConf, ghcProgram ) import Distribution.Simple.BuildPaths ( defaultDistPref, exeExtension ) import Distribution.Simple.Command ( CommandUI(..), commandShowOptions ) import Distribution.Simple.GHC ( ghcVerbosityOptions ) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.PackageIndex (PackageIndex) import Distribution.Client.IndexUtils ( getInstalledPackages ) import Distribution.Simple.Utils ( die, debug, info, factionVersion, findPackageDesc, comparing , createDirectoryIfMissingVerbose, rewriteFile, intercalate ) import Distribution.Client.Utils ( moreRecentFile, inDir ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity ) import System.Directory ( doesFileExist, getCurrentDirectory ) import System.FilePath ( (</>), (<.>) ) import System.IO ( Handle ) import System.Exit ( ExitCode(..), exitWith ) import System.Process ( runProcess, waitForProcess ) import Control.Exception ( catch, SomeException ) import Control.Monad ( when, unless ) import Data.List ( maximumBy ) import Data.Maybe ( fromMaybe, isJust ) import Data.Char ( isSpace ) data SetupScriptOptions = SetupScriptOptions { useFactionVersion :: VersionRange, useCompiler :: Maybe Compiler, usePackageDB :: PackageDBStack, usePackageIndex :: Maybe PackageIndex, useProgramConfig :: ProgramConfiguration, useDistPref :: FilePath, useLoggingHandle :: Maybe Handle, useWorkingDir :: Maybe FilePath } defaultSetupScriptOptions :: SetupScriptOptions defaultSetupScriptOptions = SetupScriptOptions { useFactionVersion = anyVersion, useCompiler = Nothing, usePackageDB = [GlobalPackageDB, UserPackageDB], usePackageIndex = Nothing, useProgramConfig = emptyProgramConfiguration, useDistPref = defaultDistPref, useLoggingHandle = Nothing, useWorkingDir = Nothing } setupWrapper :: Verbosity -> SetupScriptOptions -> Maybe PackageDescription -> CommandUI flags -> (Version -> flags) -> [String] -> IO () setupWrapper verbosity options mpkg cmd flags extraArgs = do pkg <- maybe getPkg return mpkg let setupMethod = determineSetupMethod options' buildType' options' = options { useFactionVersion = intersectVersionRanges (useFactionVersion options) (orLaterVersion (specVersion pkg)) } buildType' = fromMaybe Custom (buildType pkg) mkArgs libfactionVersion = commandName cmd : commandShowOptions cmd (flags libfactionVersion) ++ extraArgs checkBuildType buildType' setupMethod verbosity options' (packageId pkg) buildType' mkArgs where getPkg = findPackageDesc (fromMaybe "." (useWorkingDir options)) >>= readPackageDescription verbosity >>= return . packageDescription checkBuildType (UnknownBuildType name) = die $ "The build-type '" ++ name ++ "' is not known. Use one of: " ++ intercalate ", " (map display knownBuildTypes) ++ "." checkBuildType _ = return () -- | Decide if we're going to be able to do a direct internal call to the -- entry point in libfaction or if we're going to have to compile -- and execute an external Setup.hs script. -- determineSetupMethod :: SetupScriptOptions -> BuildType -> SetupMethod determineSetupMethod options buildType' | isJust (useLoggingHandle options) || buildType' == Custom = externalSetupMethod | factionVersion `withinRange` useFactionVersion options = internalSetupMethod | otherwise = externalSetupMethod type SetupMethod = Verbosity -> SetupScriptOptions -> PackageIdentifier -> BuildType -> (Version -> [String]) -> IO () -- ------------------------------------------------------------ -- * Internal SetupMethod -- ------------------------------------------------------------ internalSetupMethod :: SetupMethod internalSetupMethod verbosity options _ bt mkargs = do let args = mkargs factionVersion debug verbosity $ "Using internal setup method with build-type " ++ show bt ++ " and args:\n " ++ show args inDir (useWorkingDir options) $ buildTypeAction bt args buildTypeAction :: BuildType -> ([String] -> IO ()) buildTypeAction Simple = Simple.defaultMainArgs buildTypeAction Configure = Simple.defaultMainWithHooksArgs Simple.autoconfUserHooks buildTypeAction Custom = error "buildTypeAction Custom" buildTypeAction (UnknownBuildType _) = error "buildTypeAction UnknownBuildType" -- ------------------------------------------------------------ -- * External SetupMethod -- ------------------------------------------------------------ externalSetupMethod :: SetupMethod externalSetupMethod verbosity options pkg bt mkargs = do debug verbosity $ "Using external setup method with build-type " ++ show bt createDirectoryIfMissingVerbose verbosity True setupDir (libfactionVersion, options') <- libfactionVersionToUse debug verbosity $ "Using libfaction version " ++ display libfactionVersion setupHs <- updateSetupScript libfactionVersion bt debug verbosity $ "Using " ++ setupHs ++ " as setup script." compileSetupExecutable options' libfactionVersion setupHs invokeSetupScript (mkargs libfactionVersion) where workingDir = case fromMaybe "" (useWorkingDir options) of [] -> "." dir -> dir setupDir = workingDir </> useDistPref options </> "setup" setupVersionFile = setupDir </> "setup" <.> "version" setupProgFile = setupDir </> "setup" <.> exeExtension libfactionVersionToUse :: IO (Version, SetupScriptOptions) libfactionVersionToUse = do savedVersion <- savedFactionVersion case savedVersion of Just version | version `withinRange` useFactionVersion options -> return (version, options) _ -> do (comp, conf, options') <- configureCompiler options version <- installedFactionVersion options comp conf writeFile setupVersionFile (show version ++ "\n") return (version, options') savedFactionVersion = do versionString <- readFile setupVersionFile `catch` \e -> do return (e :: SomeException) return "" case reads versionString of [(version,s)] | all isSpace s -> return (Just version) _ -> return Nothing installedFactionVersion :: SetupScriptOptions -> Compiler -> ProgramConfiguration -> IO Version installedFactionVersion _ _ _ | packageName pkg == PackageName "libfaction" = return (packageVersion pkg) installedFactionVersion options' comp conf = do index <- case usePackageIndex options' of Just index -> return index Nothing -> getInstalledPackages verbosity comp (usePackageDB options') conf let factionDep = Dependency (PackageName "libfaction") (useFactionVersion options) case PackageIndex.lookupDependency index factionDep of [] -> die $ "The package requires libfaction version " ++ display (useFactionVersion options) ++ " but no suitable version is installed." pkgs -> return $ bestVersion (map fst pkgs) where bestVersion = maximumBy (comparing preference) preference version = (sameVersion, sameMajorVersion ,stableVersion, latestVersion) where sameVersion = version == factionVersion sameMajorVersion = majorVersion version == majorVersion factionVersion majorVersion = take 2 . versionBranch stableVersion = case versionBranch version of (_:x:_) -> even x _ -> False latestVersion = version configureCompiler :: SetupScriptOptions -> IO (Compiler, ProgramConfiguration, SetupScriptOptions) configureCompiler options' = do (comp, conf) <- case useCompiler options' of Just comp -> return (comp, useProgramConfig options') Nothing -> configCompiler (Just GHC) Nothing Nothing (useProgramConfig options') verbosity return (comp, conf, options' { useCompiler = Just comp, useProgramConfig = conf }) -- | Decide which Setup.hs script to use, creating it if necessary. -- updateSetupScript :: Version -> BuildType -> IO FilePath updateSetupScript _ Custom = do useHs <- doesFileExist setupHs useLhs <- doesFileExist setupLhs unless (useHs || useLhs) $ die "Using 'build-type: Custom' but there is no Setup.hs or Setup.lhs script." return (if useHs then setupHs else setupLhs) where setupHs = workingDir </> "Setup.hs" setupLhs = workingDir </> "Setup.lhs" updateSetupScript libfactionVersion _ = do rewriteFile setupHs (buildTypeScript libfactionVersion) return setupHs where setupHs = setupDir </> "setup.hs" buildTypeScript :: Version -> String buildTypeScript libfactionVersion = case bt of Simple -> "import Distribution.Simple; main = defaultMain\n" Configure -> "import Distribution.Simple; main = defaultMainWithHooks " ++ if libfactionVersion >= Version [1,3,10] [] then "autoconfUserHooks\n" else "defaultUserHooks\n" Custom -> error "buildTypeScript Custom" UnknownBuildType _ -> error "buildTypeScript UnknownBuildType" -- | If the Setup.hs is out of date wrt the executable then recompile it. -- Currently this is GHC only. It should really be generalised. -- compileSetupExecutable :: SetupScriptOptions -> Version -> FilePath -> IO () compileSetupExecutable options' libfactionVersion setupHsFile = do setupHsNewer <- setupHsFile `moreRecentFile` setupProgFile cabalVersionNewer <- setupVersionFile `moreRecentFile` setupProgFile let outOfDate = setupHsNewer || cabalVersionNewer when outOfDate $ do debug verbosity "Setup script is out of date, compiling..." (_, conf, _) <- configureCompiler options' --TODO: get Faction's GHC module to export a GhcOptions type and render func rawSystemProgramConf verbosity ghcProgram conf $ ghcVerbosityOptions verbosity ++ ["--make", setupHsFile, "-o", setupProgFile ,"-odir", setupDir, "-hidir", setupDir ,"-i", "-i" ++ workingDir ] ++ ghcPackageDbOptions (usePackageDB options') ++ if packageName pkg == PackageName "libfaction" then [] else ["-package", display libfactionPkgid] where libfactionPkgid = PackageIdentifier (PackageName "libfaction") libfactionVersion ghcPackageDbOptions :: PackageDBStack -> [String] ghcPackageDbOptions dbstack = case dbstack of (GlobalPackageDB:UserPackageDB:dbs) -> concatMap specific dbs (GlobalPackageDB:dbs) -> "-no-user-package-conf" : concatMap specific dbs _ -> ierror where specific (SpecificPackageDB db) = [ "-package-conf", db ] specific _ = ierror ierror = error "internal error: unexpected package db stack" invokeSetupScript :: [String] -> IO () invokeSetupScript args = do info verbosity $ unwords (setupProgFile : args) case useLoggingHandle options of Nothing -> return () Just logHandle -> info verbosity $ "Redirecting build log to " ++ show logHandle currentDir <- getCurrentDirectory process <- runProcess (currentDir </> setupProgFile) args (useWorkingDir options) Nothing Nothing (useLoggingHandle options) (useLoggingHandle options) exitCode <- waitForProcess process unless (exitCode == ExitSuccess) $ exitWith exitCode
IreneKnapp/Faction
faction/Distribution/Client/SetupWrapper.hs
bsd-3-clause
14,150
0
17
3,661
2,869
1,515
1,354
258
20
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[Demand]{@Demand@: A decoupled implementation of a demand domain} -} {-# LANGUAGE CPP, FlexibleInstances, TypeSynonymInstances, RecordWildCards #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} module Demand ( StrDmd, UseDmd(..), Count, Demand, DmdShell, CleanDemand, getStrDmd, getUseDmd, mkProdDmd, mkOnceUsedDmd, mkManyUsedDmd, mkHeadStrict, oneifyDmd, toCleanDmd, absDmd, topDmd, botDmd, seqDmd, lubDmd, bothDmd, lazyApply1Dmd, lazyApply2Dmd, strictApply1Dmd, isTopDmd, isAbsDmd, isSeqDmd, peelUseCall, cleanUseDmd_maybe, strictenDmd, bothCleanDmd, addCaseBndrDmd, DmdType(..), dmdTypeDepth, lubDmdType, bothDmdType, nopDmdType, botDmdType, mkDmdType, addDemand, ensureArgs, BothDmdArg, mkBothDmdArg, toBothDmdArg, DmdEnv, emptyDmdEnv, peelFV, findIdDemand, DmdResult, CPRResult, isBotRes, isTopRes, topRes, botRes, cprProdRes, vanillaCprProdRes, cprSumRes, appIsBottom, isBottomingSig, pprIfaceStrictSig, trimCPRInfo, returnsCPR_maybe, StrictSig(..), mkStrictSigForArity, mkClosedStrictSig, nopSig, botSig, cprProdSig, isTopSig, hasDemandEnvSig, splitStrictSig, strictSigDmdEnv, increaseStrictSigArity, etaExpandStrictSig, seqDemand, seqDemandList, seqDmdType, seqStrictSig, evalDmd, cleanEvalDmd, cleanEvalProdDmd, isStrictDmd, splitDmdTy, splitFVs, deferAfterIO, postProcessUnsat, postProcessDmdType, splitProdDmd_maybe, peelCallDmd, peelManyCalls, mkCallDmd, mkCallDmds, mkWorkerDemand, dmdTransformSig, dmdTransformDataConSig, dmdTransformDictSelSig, argOneShots, argsOneShots, saturatedByOneShots, TypeShape(..), peelTsFuns, trimToType, useCount, isUsedOnce, reuseEnv, killUsageDemand, killUsageSig, zapUsageDemand, zapUsageEnvSig, zapUsedOnceDemand, zapUsedOnceSig, strictifyDictDmd, strictifyDmd ) where #include "HsVersions.h" import GhcPrelude import DynFlags import Outputable import Var ( Var ) import VarEnv import UniqFM import Util import BasicTypes import Binary import Maybes ( orElse ) import Type ( Type ) import TyCon ( isNewTyCon, isClassTyCon ) import DataCon ( splitDataProductType_maybe ) {- ************************************************************************ * * Joint domain for Strictness and Absence * * ************************************************************************ -} data JointDmd s u = JD { sd :: s, ud :: u } deriving ( Eq, Show ) getStrDmd :: JointDmd s u -> s getStrDmd = sd getUseDmd :: JointDmd s u -> u getUseDmd = ud -- Pretty-printing instance (Outputable s, Outputable u) => Outputable (JointDmd s u) where ppr (JD {sd = s, ud = u}) = angleBrackets (ppr s <> char ',' <> ppr u) -- Well-formedness preserving constructors for the joint domain mkJointDmd :: s -> u -> JointDmd s u mkJointDmd s u = JD { sd = s, ud = u } mkJointDmds :: [s] -> [u] -> [JointDmd s u] mkJointDmds ss as = zipWithEqual "mkJointDmds" mkJointDmd ss as {- ************************************************************************ * * Strictness domain * * ************************************************************************ Lazy | HeadStr / \ SCall SProd \ / HyperStr Note [Exceptions and strictness] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to smart about catching exceptions, but we aren't anymore. See #14998 for the way it's resolved at the moment. Here's a historic breakdown: Apparently, exception handling prim-ops didn't use to have any special strictness signatures, thus defaulting to topSig, which assumes they use their arguments lazily. Joachim was the first to realise that we could provide richer information. Thus, in 0558911f91c (Dec 13), he added signatures to primops.txt.pp indicating that functions like `catch#` and `catchRetry#` call their argument, which is useful information for usage analysis. Still with a 'Lazy' strictness demand (i.e. 'lazyApply1Dmd'), though, and the world was fine. In 7c0fff4 (July 15), Simon argued that giving `catch#` et al. a 'strictApply1Dmd' leads to substantial performance gains. That was at the cost of correctness, as #10712 proved. So, back to 'lazyApply1Dmd' in 28638dfe79e (Dec 15). Motivated to reproduce the gains of 7c0fff4 without the breakage of #10712, Ben opened #11222. Simon made the demand analyser "understand catch" in 9915b656 (Jan 16) by adding a new 'catchArgDmd', which basically said to call its argument strictly, but also swallow any thrown exceptions in 'postProcessDmdResult'. This was realized by extending the 'Str' constructor of 'ArgStr' with a 'ExnStr' field, indicating that it catches the exception, and adding a 'ThrowsExn' constructor to the 'Termination' lattice as an element between 'Dunno' and 'Diverges'. Then along came #11555 and finally #13330, so we had to revert to 'lazyApply1Dmd' again in 701256df88c (Mar 17). This left the other variants like 'catchRetry#' having 'catchArgDmd', which is where #14998 picked up. Item 1 was concerned with measuring the impact of also making `catchRetry#` and `catchSTM#` have 'lazyApply1Dmd'. The result was that there was none. We removed the last usages of 'catchArgDmd' in 00b8ecb7 (Apr 18). There was a lot of dead code resulting from that change, that we removed in ef6b283 (Jan 19): We got rid of 'ThrowsExn' and 'ExnStr' again and removed any code that was dealing with the peculiarities. Where did the speed-ups vanish to? In #14998, item 3 established that turning 'catch#' strict in its first argument didn't bring back any of the alleged performance benefits. Item 2 of that ticket finally found out that it was entirely due to 'catchException's new (since #11555) definition, which was simply catchException !io handler = catch io handler While 'catchException' is arguably the saner semantics for 'catch', it is an internal helper function in "GHC.IO". Its use in "GHC.IO.Handle.Internals.do_operation" made for the huge allocation differences: Remove the bang and you find the regressions we originally wanted to avoid with 'catchArgDmd'. See also #exceptions_and_strictness# in "GHC.IO". So history keeps telling us that the only possibly correct strictness annotation for the first argument of 'catch#' is 'lazyApply1Dmd', because 'catch#' really is not strict in its argument: Just try this in GHCi :set -XScopedTypeVariables import Control.Exception catch undefined (\(_ :: SomeException) -> putStrLn "you'll see this") Any analysis that assumes otherwise will be broken in some way or another (beyond `-fno-pendantic-bottoms`). -} -- | Vanilla strictness domain data StrDmd = HyperStr -- ^ Hyper-strict (bottom of the lattice). -- See Note [HyperStr and Use demands] | SCall StrDmd -- ^ Call demand -- Used only for values of function type | SProd [ArgStr] -- ^ Product -- Used only for values of product type -- Invariant: not all components are HyperStr (use HyperStr) -- not all components are Lazy (use HeadStr) | HeadStr -- ^ Head-Strict -- A polymorphic demand: used for values of all types, -- including a type variable deriving ( Eq, Show ) -- | Strictness of a function argument. type ArgStr = Str StrDmd -- | Strictness demand. data Str s = Lazy -- ^ Lazy (top of the lattice) | Str s -- ^ Strict deriving ( Eq, Show ) -- Well-formedness preserving constructors for the Strictness domain strBot, strTop :: ArgStr strBot = Str HyperStr strTop = Lazy mkSCall :: StrDmd -> StrDmd mkSCall HyperStr = HyperStr mkSCall s = SCall s mkSProd :: [ArgStr] -> StrDmd mkSProd sx | any isHyperStr sx = HyperStr | all isLazy sx = HeadStr | otherwise = SProd sx isLazy :: ArgStr -> Bool isLazy Lazy = True isLazy (Str {}) = False isHyperStr :: ArgStr -> Bool isHyperStr (Str HyperStr) = True isHyperStr _ = False -- Pretty-printing instance Outputable StrDmd where ppr HyperStr = char 'B' ppr (SCall s) = char 'C' <> parens (ppr s) ppr HeadStr = char 'S' ppr (SProd sx) = char 'S' <> parens (hcat (map ppr sx)) instance Outputable ArgStr where ppr (Str s) = ppr s ppr Lazy = char 'L' lubArgStr :: ArgStr -> ArgStr -> ArgStr lubArgStr Lazy _ = Lazy lubArgStr _ Lazy = Lazy lubArgStr (Str s1) (Str s2) = Str (s1 `lubStr` s2) lubStr :: StrDmd -> StrDmd -> StrDmd lubStr HyperStr s = s lubStr (SCall s1) HyperStr = SCall s1 lubStr (SCall _) HeadStr = HeadStr lubStr (SCall s1) (SCall s2) = SCall (s1 `lubStr` s2) lubStr (SCall _) (SProd _) = HeadStr lubStr (SProd sx) HyperStr = SProd sx lubStr (SProd _) HeadStr = HeadStr lubStr (SProd s1) (SProd s2) | s1 `equalLength` s2 = mkSProd (zipWith lubArgStr s1 s2) | otherwise = HeadStr lubStr (SProd _) (SCall _) = HeadStr lubStr HeadStr _ = HeadStr bothArgStr :: ArgStr -> ArgStr -> ArgStr bothArgStr Lazy s = s bothArgStr s Lazy = s bothArgStr (Str s1) (Str s2) = Str (s1 `bothStr` s2) bothStr :: StrDmd -> StrDmd -> StrDmd bothStr HyperStr _ = HyperStr bothStr HeadStr s = s bothStr (SCall _) HyperStr = HyperStr bothStr (SCall s1) HeadStr = SCall s1 bothStr (SCall s1) (SCall s2) = SCall (s1 `bothStr` s2) bothStr (SCall _) (SProd _) = HyperStr -- Weird bothStr (SProd _) HyperStr = HyperStr bothStr (SProd s1) HeadStr = SProd s1 bothStr (SProd s1) (SProd s2) | s1 `equalLength` s2 = mkSProd (zipWith bothArgStr s1 s2) | otherwise = HyperStr -- Weird bothStr (SProd _) (SCall _) = HyperStr -- utility functions to deal with memory leaks seqStrDmd :: StrDmd -> () seqStrDmd (SProd ds) = seqStrDmdList ds seqStrDmd (SCall s) = seqStrDmd s seqStrDmd _ = () seqStrDmdList :: [ArgStr] -> () seqStrDmdList [] = () seqStrDmdList (d:ds) = seqArgStr d `seq` seqStrDmdList ds seqArgStr :: ArgStr -> () seqArgStr Lazy = () seqArgStr (Str s) = seqStrDmd s -- Splitting polymorphic demands splitArgStrProdDmd :: Int -> ArgStr -> Maybe [ArgStr] splitArgStrProdDmd n Lazy = Just (replicate n Lazy) splitArgStrProdDmd n (Str s) = splitStrProdDmd n s splitStrProdDmd :: Int -> StrDmd -> Maybe [ArgStr] splitStrProdDmd n HyperStr = Just (replicate n strBot) splitStrProdDmd n HeadStr = Just (replicate n strTop) splitStrProdDmd n (SProd ds) = WARN( not (ds `lengthIs` n), text "splitStrProdDmd" $$ ppr n $$ ppr ds ) Just ds splitStrProdDmd _ (SCall {}) = Nothing -- This can happen when the programmer uses unsafeCoerce, -- and we don't then want to crash the compiler (#9208) {- ************************************************************************ * * Absence domain * * ************************************************************************ Used / \ UCall UProd \ / UHead | Count x - | Abs -} -- | Domain for genuine usage data UseDmd = UCall Count UseDmd -- ^ Call demand for absence. -- Used only for values of function type | UProd [ArgUse] -- ^ Product. -- Used only for values of product type -- See Note [Don't optimise UProd(Used) to Used] -- -- Invariant: Not all components are Abs -- (in that case, use UHead) | UHead -- ^ May be used but its sub-components are -- definitely *not* used. For product types, UHead -- is equivalent to U(AAA); see mkUProd. -- -- UHead is needed only to express the demand -- of 'seq' and 'case' which are polymorphic; -- i.e. the scrutinised value is of type 'a' -- rather than a product type. That's why we -- can't use UProd [A,A,A] -- -- Since (UCall _ Abs) is ill-typed, UHead doesn't -- make sense for lambdas | Used -- ^ May be used and its sub-components may be used. -- (top of the lattice) deriving ( Eq, Show ) -- Extended usage demand for absence and counting type ArgUse = Use UseDmd data Use u = Abs -- Definitely unused -- Bottom of the lattice | Use Count u -- May be used with some cardinality deriving ( Eq, Show ) -- | Abstract counting of usages data Count = One | Many deriving ( Eq, Show ) -- Pretty-printing instance Outputable ArgUse where ppr Abs = char 'A' ppr (Use Many a) = ppr a ppr (Use One a) = char '1' <> char '*' <> ppr a instance Outputable UseDmd where ppr Used = char 'U' ppr (UCall c a) = char 'C' <> ppr c <> parens (ppr a) ppr UHead = char 'H' ppr (UProd as) = char 'U' <> parens (hcat (punctuate (char ',') (map ppr as))) instance Outputable Count where ppr One = char '1' ppr Many = text "" useBot, useTop :: ArgUse useBot = Abs useTop = Use Many Used mkUCall :: Count -> UseDmd -> UseDmd --mkUCall c Used = Used c mkUCall c a = UCall c a mkUProd :: [ArgUse] -> UseDmd mkUProd ux | all (== Abs) ux = UHead | otherwise = UProd ux lubCount :: Count -> Count -> Count lubCount _ Many = Many lubCount Many _ = Many lubCount x _ = x lubArgUse :: ArgUse -> ArgUse -> ArgUse lubArgUse Abs x = x lubArgUse x Abs = x lubArgUse (Use c1 a1) (Use c2 a2) = Use (lubCount c1 c2) (lubUse a1 a2) lubUse :: UseDmd -> UseDmd -> UseDmd lubUse UHead u = u lubUse (UCall c u) UHead = UCall c u lubUse (UCall c1 u1) (UCall c2 u2) = UCall (lubCount c1 c2) (lubUse u1 u2) lubUse (UCall _ _) _ = Used lubUse (UProd ux) UHead = UProd ux lubUse (UProd ux1) (UProd ux2) | ux1 `equalLength` ux2 = UProd $ zipWith lubArgUse ux1 ux2 | otherwise = Used lubUse (UProd {}) (UCall {}) = Used -- lubUse (UProd {}) Used = Used lubUse (UProd ux) Used = UProd (map (`lubArgUse` useTop) ux) lubUse Used (UProd ux) = UProd (map (`lubArgUse` useTop) ux) lubUse Used _ = Used -- Note [Used should win] -- `both` is different from `lub` in its treatment of counting; if -- `both` is computed for two used, the result always has -- cardinality `Many` (except for the inner demands of UCall demand -- [TODO] explain). -- Also, x `bothUse` x /= x (for anything but Abs). bothArgUse :: ArgUse -> ArgUse -> ArgUse bothArgUse Abs x = x bothArgUse x Abs = x bothArgUse (Use _ a1) (Use _ a2) = Use Many (bothUse a1 a2) bothUse :: UseDmd -> UseDmd -> UseDmd bothUse UHead u = u bothUse (UCall c u) UHead = UCall c u -- Exciting special treatment of inner demand for call demands: -- use `lubUse` instead of `bothUse`! bothUse (UCall _ u1) (UCall _ u2) = UCall Many (u1 `lubUse` u2) bothUse (UCall {}) _ = Used bothUse (UProd ux) UHead = UProd ux bothUse (UProd ux1) (UProd ux2) | ux1 `equalLength` ux2 = UProd $ zipWith bothArgUse ux1 ux2 | otherwise = Used bothUse (UProd {}) (UCall {}) = Used -- bothUse (UProd {}) Used = Used -- Note [Used should win] bothUse Used (UProd ux) = UProd (map (`bothArgUse` useTop) ux) bothUse (UProd ux) Used = UProd (map (`bothArgUse` useTop) ux) bothUse Used _ = Used -- Note [Used should win] peelUseCall :: UseDmd -> Maybe (Count, UseDmd) peelUseCall (UCall c u) = Just (c,u) peelUseCall _ = Nothing addCaseBndrDmd :: Demand -- On the case binder -> [Demand] -- On the components of the constructor -> [Demand] -- Final demands for the components of the constructor -- See Note [Demand on case-alternative binders] addCaseBndrDmd (JD { sd = ms, ud = mu }) alt_dmds = case mu of Abs -> alt_dmds Use _ u -> zipWith bothDmd alt_dmds (mkJointDmds ss us) where Just ss = splitArgStrProdDmd arity ms -- Guaranteed not to be a call Just us = splitUseProdDmd arity u -- Ditto where arity = length alt_dmds {- Note [Demand on case-alternative binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The demand on a binder in a case alternative comes (a) From the demand on the binder itself (b) From the demand on the case binder Forgetting (b) led directly to #10148. Example. Source code: f x@(p,_) = if p then foo x else True foo (p,True) = True foo (p,q) = foo (q,p) After strictness analysis: f = \ (x_an1 [Dmd=<S(SL),1*U(U,1*U)>] :: (Bool, Bool)) -> case x_an1 of wild_X7 [Dmd=<L,1*U(1*U,1*U)>] { (p_an2 [Dmd=<S,1*U>], ds_dnz [Dmd=<L,A>]) -> case p_an2 of _ { False -> GHC.Types.True; True -> foo wild_X7 } It's true that ds_dnz is *itself* absent, but the use of wild_X7 means that it is very much alive and demanded. See #10148 for how the consequences play out. This is needed even for non-product types, in case the case-binder is used but the components of the case alternative are not. Note [Don't optimise UProd(Used) to Used] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ These two UseDmds: UProd [Used, Used] and Used are semantically equivalent, but we do not turn the former into the latter, for a regrettable-subtle reason. Suppose we did. then f (x,y) = (y,x) would get StrDmd = Str = SProd [Lazy, Lazy] UseDmd = Used = UProd [Used, Used] But with the joint demand of <Str, Used> doesn't convey any clue that there is a product involved, and so the worthSplittingFun will not fire. (We'd need to use the type as well to make it fire.) Moreover, consider g h p@(_,_) = h p This too would get <Str, Used>, but this time there really isn't any point in w/w since the components of the pair are not used at all. So the solution is: don't aggressively collapse UProd [Used,Used] to Used; instead leave it as-is. In effect we are using the UseDmd to do a little bit of boxity analysis. Not very nice. Note [Used should win] ~~~~~~~~~~~~~~~~~~~~~~ Both in lubUse and bothUse we want (Used `both` UProd us) to be Used. Why? Because Used carries the implication the whole thing is used, box and all, so we don't want to w/w it. If we use it both boxed and unboxed, then we are definitely using the box, and so we are quite likely to pay a reboxing cost. So we make Used win here. Example is in the Buffer argument of GHC.IO.Handle.Internals.writeCharBuffer Baseline: (A) Not making Used win (UProd wins) Compare with: (B) making Used win for lub and both Min -0.3% -5.6% -10.7% -11.0% -33.3% Max +0.3% +45.6% +11.5% +11.5% +6.9% Geometric Mean -0.0% +0.5% +0.3% +0.2% -0.8% Baseline: (B) Making Used win for both lub and both Compare with: (C) making Used win for both, but UProd win for lub Min -0.1% -0.3% -7.9% -8.0% -6.5% Max +0.1% +1.0% +21.0% +21.0% +0.5% Geometric Mean +0.0% +0.0% -0.0% -0.1% -0.1% -} -- If a demand is used multiple times (i.e. reused), than any use-once -- mentioned there, that is not protected by a UCall, can happen many times. markReusedDmd :: ArgUse -> ArgUse markReusedDmd Abs = Abs markReusedDmd (Use _ a) = Use Many (markReused a) markReused :: UseDmd -> UseDmd markReused (UCall _ u) = UCall Many u -- No need to recurse here markReused (UProd ux) = UProd (map markReusedDmd ux) markReused u = u isUsedMU :: ArgUse -> Bool -- True <=> markReusedDmd d = d isUsedMU Abs = True isUsedMU (Use One _) = False isUsedMU (Use Many u) = isUsedU u isUsedU :: UseDmd -> Bool -- True <=> markReused d = d isUsedU Used = True isUsedU UHead = True isUsedU (UProd us) = all isUsedMU us isUsedU (UCall One _) = False isUsedU (UCall Many _) = True -- No need to recurse -- Squashing usage demand demands seqUseDmd :: UseDmd -> () seqUseDmd (UProd ds) = seqArgUseList ds seqUseDmd (UCall c d) = c `seq` seqUseDmd d seqUseDmd _ = () seqArgUseList :: [ArgUse] -> () seqArgUseList [] = () seqArgUseList (d:ds) = seqArgUse d `seq` seqArgUseList ds seqArgUse :: ArgUse -> () seqArgUse (Use c u) = c `seq` seqUseDmd u seqArgUse _ = () -- Splitting polymorphic Maybe-Used demands splitUseProdDmd :: Int -> UseDmd -> Maybe [ArgUse] splitUseProdDmd n Used = Just (replicate n useTop) splitUseProdDmd n UHead = Just (replicate n Abs) splitUseProdDmd n (UProd ds) = WARN( not (ds `lengthIs` n), text "splitUseProdDmd" $$ ppr n $$ ppr ds ) Just ds splitUseProdDmd _ (UCall _ _) = Nothing -- This can happen when the programmer uses unsafeCoerce, -- and we don't then want to crash the compiler (#9208) useCount :: Use u -> Count useCount Abs = One useCount (Use One _) = One useCount _ = Many {- ************************************************************************ * * Clean demand for Strictness and Usage * * ************************************************************************ This domain differst from JointDemand in the sense that pure absence is taken away, i.e., we deal *only* with non-absent demands. Note [Strict demands] ~~~~~~~~~~~~~~~~~~~~~ isStrictDmd returns true only of demands that are both strict and used In particular, it is False for <HyperStr, Abs>, which can and does arise in, say (#7319) f x = raise# <some exception> Then 'x' is not used, so f gets strictness <HyperStr,Abs> -> . Now the w/w generates fx = let x <HyperStr,Abs> = absentError "unused" in raise <some exception> At this point we really don't want to convert to fx = case absentError "unused" of x -> raise <some exception> Since the program is going to diverge, this swaps one error for another, but it's really a bad idea to *ever* evaluate an absent argument. In #7319 we get T7319.exe: Oops! Entered absent arg w_s1Hd{v} [lid] [base:GHC.Base.String{tc 36u}] Note [Dealing with call demands] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Call demands are constructed and deconstructed coherently for strictness and absence. For instance, the strictness signature for the following function f :: (Int -> (Int, Int)) -> (Int, Bool) f g = (snd (g 3), True) should be: <L,C(U(AU))>m -} type CleanDemand = JointDmd StrDmd UseDmd -- A demand that is at least head-strict bothCleanDmd :: CleanDemand -> CleanDemand -> CleanDemand bothCleanDmd (JD { sd = s1, ud = a1}) (JD { sd = s2, ud = a2}) = JD { sd = s1 `bothStr` s2, ud = a1 `bothUse` a2 } mkHeadStrict :: CleanDemand -> CleanDemand mkHeadStrict cd = cd { sd = HeadStr } mkOnceUsedDmd, mkManyUsedDmd :: CleanDemand -> Demand mkOnceUsedDmd (JD {sd = s,ud = a}) = JD { sd = Str s, ud = Use One a } mkManyUsedDmd (JD {sd = s,ud = a}) = JD { sd = Str s, ud = Use Many a } evalDmd :: Demand -- Evaluated strictly, and used arbitrarily deeply evalDmd = JD { sd = Str HeadStr, ud = useTop } mkProdDmd :: [Demand] -> CleanDemand mkProdDmd dx = JD { sd = mkSProd $ map getStrDmd dx , ud = mkUProd $ map getUseDmd dx } -- | Wraps the 'CleanDemand' with a one-shot call demand: @d@ -> @C1(d)@. mkCallDmd :: CleanDemand -> CleanDemand mkCallDmd (JD {sd = d, ud = u}) = JD { sd = mkSCall d, ud = mkUCall One u } -- | @mkCallDmds n d@ returns @C1(C1...(C1 d))@ where there are @n@ @C1@'s. mkCallDmds :: Arity -> CleanDemand -> CleanDemand mkCallDmds arity cd = iterate mkCallDmd cd !! arity -- See Note [Demand on the worker] in WorkWrap mkWorkerDemand :: Int -> Demand mkWorkerDemand n = JD { sd = Lazy, ud = Use One (go n) } where go 0 = Used go n = mkUCall One $ go (n-1) cleanEvalDmd :: CleanDemand cleanEvalDmd = JD { sd = HeadStr, ud = Used } cleanEvalProdDmd :: Arity -> CleanDemand cleanEvalProdDmd n = JD { sd = HeadStr, ud = UProd (replicate n useTop) } {- ************************************************************************ * * Demand: Combining Strictness and Usage * * ************************************************************************ -} type Demand = JointDmd ArgStr ArgUse lubDmd :: Demand -> Demand -> Demand lubDmd (JD {sd = s1, ud = a1}) (JD {sd = s2, ud = a2}) = JD { sd = s1 `lubArgStr` s2 , ud = a1 `lubArgUse` a2 } bothDmd :: Demand -> Demand -> Demand bothDmd (JD {sd = s1, ud = a1}) (JD {sd = s2, ud = a2}) = JD { sd = s1 `bothArgStr` s2 , ud = a1 `bothArgUse` a2 } lazyApply1Dmd, lazyApply2Dmd, strictApply1Dmd :: Demand strictApply1Dmd = JD { sd = Str (SCall HeadStr) , ud = Use Many (UCall One Used) } lazyApply1Dmd = JD { sd = Lazy , ud = Use One (UCall One Used) } -- Second argument of catch#: -- uses its arg at most once, applies it once -- but is lazy (might not be called at all) lazyApply2Dmd = JD { sd = Lazy , ud = Use One (UCall One (UCall One Used)) } absDmd :: Demand absDmd = JD { sd = Lazy, ud = Abs } topDmd :: Demand topDmd = JD { sd = Lazy, ud = useTop } botDmd :: Demand botDmd = JD { sd = strBot, ud = useBot } seqDmd :: Demand seqDmd = JD { sd = Str HeadStr, ud = Use One UHead } oneifyDmd :: JointDmd s (Use u) -> JointDmd s (Use u) oneifyDmd (JD { sd = s, ud = Use _ a }) = JD { sd = s, ud = Use One a } oneifyDmd jd = jd isTopDmd :: Demand -> Bool -- Used to suppress pretty-printing of an uninformative demand isTopDmd (JD {sd = Lazy, ud = Use Many Used}) = True isTopDmd _ = False isAbsDmd :: JointDmd (Str s) (Use u) -> Bool isAbsDmd (JD {ud = Abs}) = True -- The strictness part can be HyperStr isAbsDmd _ = False -- for a bottom demand isSeqDmd :: Demand -> Bool isSeqDmd (JD {sd = Str HeadStr, ud = Use _ UHead}) = True isSeqDmd _ = False isUsedOnce :: JointDmd (Str s) (Use u) -> Bool isUsedOnce (JD { ud = a }) = case useCount a of One -> True Many -> False -- More utility functions for strictness seqDemand :: Demand -> () seqDemand (JD {sd = s, ud = u}) = seqArgStr s `seq` seqArgUse u seqDemandList :: [Demand] -> () seqDemandList [] = () seqDemandList (d:ds) = seqDemand d `seq` seqDemandList ds isStrictDmd :: JointDmd (Str s) (Use u) -> Bool -- See Note [Strict demands] isStrictDmd (JD {ud = Abs}) = False isStrictDmd (JD {sd = Lazy}) = False isStrictDmd _ = True isWeakDmd :: Demand -> Bool isWeakDmd (JD {sd = s, ud = a}) = isLazy s && isUsedMU a cleanUseDmd_maybe :: Demand -> Maybe UseDmd cleanUseDmd_maybe (JD { ud = Use _ u }) = Just u cleanUseDmd_maybe _ = Nothing splitFVs :: Bool -- Thunk -> DmdEnv -> (DmdEnv, DmdEnv) splitFVs is_thunk rhs_fvs | is_thunk = nonDetFoldUFM_Directly add (emptyVarEnv, emptyVarEnv) rhs_fvs -- It's OK to use nonDetFoldUFM_Directly because we -- immediately forget the ordering by putting the elements -- in the envs again | otherwise = partitionVarEnv isWeakDmd rhs_fvs where add uniq dmd@(JD { sd = s, ud = u }) (lazy_fv, sig_fv) | Lazy <- s = (addToUFM_Directly lazy_fv uniq dmd, sig_fv) | otherwise = ( addToUFM_Directly lazy_fv uniq (JD { sd = Lazy, ud = u }) , addToUFM_Directly sig_fv uniq (JD { sd = s, ud = Abs }) ) data TypeShape = TsFun TypeShape | TsProd [TypeShape] | TsUnk instance Outputable TypeShape where ppr TsUnk = text "TsUnk" ppr (TsFun ts) = text "TsFun" <> parens (ppr ts) ppr (TsProd tss) = parens (hsep $ punctuate comma $ map ppr tss) -- | @peelTsFuns n ts@ tries to peel off @n@ 'TsFun' constructors from @ts@ and -- returns 'Just' the wrapped 'TypeShape' on success, and 'Nothing' otherwise. peelTsFuns :: Arity -> TypeShape -> Maybe TypeShape peelTsFuns 0 ts = Just ts peelTsFuns n (TsFun ts) = peelTsFuns (n-1) ts peelTsFuns _ _ = Nothing trimToType :: Demand -> TypeShape -> Demand -- See Note [Trimming a demand to a type] trimToType (JD { sd = ms, ud = mu }) ts = JD (go_ms ms ts) (go_mu mu ts) where go_ms :: ArgStr -> TypeShape -> ArgStr go_ms Lazy _ = Lazy go_ms (Str s) ts = Str (go_s s ts) go_s :: StrDmd -> TypeShape -> StrDmd go_s HyperStr _ = HyperStr go_s (SCall s) (TsFun ts) = SCall (go_s s ts) go_s (SProd mss) (TsProd tss) | equalLength mss tss = SProd (zipWith go_ms mss tss) go_s _ _ = HeadStr go_mu :: ArgUse -> TypeShape -> ArgUse go_mu Abs _ = Abs go_mu (Use c u) ts = Use c (go_u u ts) go_u :: UseDmd -> TypeShape -> UseDmd go_u UHead _ = UHead go_u (UCall c u) (TsFun ts) = UCall c (go_u u ts) go_u (UProd mus) (TsProd tss) | equalLength mus tss = UProd (zipWith go_mu mus tss) go_u _ _ = Used {- Note [Trimming a demand to a type] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: f :: a -> Bool f x = case ... of A g1 -> case (x |> g1) of (p,q) -> ... B -> error "urk" where A,B are the constructors of a GADT. We'll get a U(U,U) demand on x from the A branch, but that's a stupid demand for x itself, which has type 'a'. Indeed we get ASSERTs going off (notably in splitUseProdDmd, #8569). Bottom line: we really don't want to have a binder whose demand is more deeply-nested than its type. There are various ways to tackle this. When processing (x |> g1), we could "trim" the incoming demand U(U,U) to match x's type. But I'm currently doing so just at the moment when we pin a demand on a binder, in DmdAnal.findBndrDmd. Note [Threshold demands] ~~~~~~~~~~~~~~~~~~~~~~~~ Threshold usage demand is generated to figure out if cardinality-instrumented demands of a binding's free variables should be unleashed. See also [Aggregated demand for cardinality]. Note [Replicating polymorphic demands] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some demands can be considered as polymorphic. Generally, it is applicable to such beasts as tops, bottoms as well as Head-Used and Head-stricts demands. For instance, S ~ S(L, ..., L) Also, when top or bottom is occurred as a result demand, it in fact can be expanded to saturate a callee's arity. -} splitProdDmd_maybe :: Demand -> Maybe [Demand] -- Split a product into its components, iff there is any -- useful information to be extracted thereby -- The demand is not necessarily strict! splitProdDmd_maybe (JD { sd = s, ud = u }) = case (s,u) of (Str (SProd sx), Use _ u) | Just ux <- splitUseProdDmd (length sx) u -> Just (mkJointDmds sx ux) (Str s, Use _ (UProd ux)) | Just sx <- splitStrProdDmd (length ux) s -> Just (mkJointDmds sx ux) (Lazy, Use _ (UProd ux)) -> Just (mkJointDmds (replicate (length ux) Lazy) ux) _ -> Nothing {- ************************************************************************ * * Demand results * * ************************************************************************ DmdResult: Dunno CPRResult / Diverges CPRResult: NoCPR / \ RetProd RetSum ConTag Product constructors return (Dunno (RetProd rs)) In a fixpoint iteration, start from Diverges We have lubs, but not glbs; but that is ok. -} ------------------------------------------------------------------------ -- Constructed Product Result ------------------------------------------------------------------------ data Termination r = Diverges -- Definitely diverges | Dunno r -- Might diverge or converge deriving( Eq, Show ) -- At this point, Termination is just the 'Lifted' lattice over 'r' -- (https://hackage.haskell.org/package/lattices/docs/Algebra-Lattice-Lifted.html) type DmdResult = Termination CPRResult data CPRResult = NoCPR -- Top of the lattice | RetProd -- Returns a constructor from a product type | RetSum ConTag -- Returns a constructor from a data type deriving( Eq, Show ) lubCPR :: CPRResult -> CPRResult -> CPRResult lubCPR (RetSum t1) (RetSum t2) | t1 == t2 = RetSum t1 lubCPR RetProd RetProd = RetProd lubCPR _ _ = NoCPR lubDmdResult :: DmdResult -> DmdResult -> DmdResult lubDmdResult Diverges r = r lubDmdResult r Diverges = r lubDmdResult (Dunno c1) (Dunno c2) = Dunno (c1 `lubCPR` c2) -- This needs to commute with defaultDmd, i.e. -- defaultDmd (r1 `lubDmdResult` r2) = defaultDmd r1 `lubDmd` defaultDmd r2 -- (See Note [Default demand on free variables] for why) bothDmdResult :: DmdResult -> Termination () -> DmdResult -- See Note [Asymmetry of 'both' for DmdType and DmdResult] bothDmdResult _ Diverges = Diverges bothDmdResult r (Dunno {}) = r -- This needs to commute with defaultDmd, i.e. -- defaultDmd (r1 `bothDmdResult` r2) = defaultDmd r1 `bothDmd` defaultDmd r2 -- (See Note [Default demand on free variables] for why) instance Outputable r => Outputable (Termination r) where ppr Diverges = char 'b' ppr (Dunno c) = ppr c instance Outputable CPRResult where ppr NoCPR = empty ppr (RetSum n) = char 'm' <> int n ppr RetProd = char 'm' seqDmdResult :: DmdResult -> () seqDmdResult Diverges = () seqDmdResult (Dunno c) = seqCPRResult c seqCPRResult :: CPRResult -> () seqCPRResult NoCPR = () seqCPRResult (RetSum n) = n `seq` () seqCPRResult RetProd = () ------------------------------------------------------------------------ -- Combined demand result -- ------------------------------------------------------------------------ -- [cprRes] lets us switch off CPR analysis -- by making sure that everything uses TopRes topRes, botRes :: DmdResult topRes = Dunno NoCPR botRes = Diverges cprSumRes :: ConTag -> DmdResult cprSumRes tag = Dunno $ RetSum tag cprProdRes :: [DmdType] -> DmdResult cprProdRes _arg_tys = Dunno $ RetProd vanillaCprProdRes :: Arity -> DmdResult vanillaCprProdRes _arity = Dunno $ RetProd isTopRes :: DmdResult -> Bool isTopRes (Dunno NoCPR) = True isTopRes _ = False -- | True if the result diverges or throws an exception isBotRes :: DmdResult -> Bool isBotRes Diverges = True isBotRes (Dunno {}) = False trimCPRInfo :: Bool -> Bool -> DmdResult -> DmdResult trimCPRInfo trim_all trim_sums res = trimR res where trimR (Dunno c) = Dunno (trimC c) trimR res = res trimC (RetSum n) | trim_all || trim_sums = NoCPR | otherwise = RetSum n trimC RetProd | trim_all = NoCPR | otherwise = RetProd trimC NoCPR = NoCPR returnsCPR_maybe :: DmdResult -> Maybe ConTag returnsCPR_maybe (Dunno c) = retCPR_maybe c returnsCPR_maybe _ = Nothing retCPR_maybe :: CPRResult -> Maybe ConTag retCPR_maybe (RetSum t) = Just t retCPR_maybe RetProd = Just fIRST_TAG retCPR_maybe NoCPR = Nothing -- See Notes [Default demand on free variables] -- and [defaultDmd vs. resTypeArgDmd] defaultDmd :: Termination r -> Demand defaultDmd (Dunno {}) = absDmd defaultDmd _ = botDmd -- Diverges resTypeArgDmd :: Termination r -> Demand -- TopRes and BotRes are polymorphic, so that -- BotRes === (Bot -> BotRes) === ... -- TopRes === (Top -> TopRes) === ... -- This function makes that concrete -- Also see Note [defaultDmd vs. resTypeArgDmd] resTypeArgDmd (Dunno _) = topDmd resTypeArgDmd _ = botDmd -- Diverges {- Note [defaultDmd and resTypeArgDmd] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ These functions are similar: They express the demand on something not explicitly mentioned in the environment resp. the argument list. Yet they are different: * Variables not mentioned in the free variables environment are definitely unused, so we can use absDmd there. * Further arguments *can* be used, of course. Hence topDmd is used. ************************************************************************ * * Demand environments and types * * ************************************************************************ -} type DmdEnv = VarEnv Demand -- See Note [Default demand on free variables] data DmdType = DmdType DmdEnv -- Demand on explicitly-mentioned -- free variables [Demand] -- Demand on arguments DmdResult -- See [Nature of result demand] {- Note [Nature of result demand] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A DmdResult contains information about termination (currently distinguishing definite divergence and no information; it is possible to include definite convergence here), and CPR information about the result. The semantics of this depends on whether we are looking at a DmdType, i.e. the demand put on by an expression _under a specific incoming demand_ on its environment, or at a StrictSig describing a demand transformer. For a * DmdType, the termination information is true given the demand it was generated with, while for * a StrictSig it holds after applying enough arguments. The CPR information, though, is valid after the number of arguments mentioned in the type is given. Therefore, when forgetting the demand on arguments, as in dmdAnalRhs, this needs to be considered (via removeDmdTyArgs). Consider b2 x y = x `seq` y `seq` error (show x) this has a strictness signature of <S><S>b meaning that "b2 `seq` ()" and "b2 1 `seq` ()" might well terminate, but for "b2 1 2 `seq` ()" we get definite divergence. For comparison, b1 x = x `seq` error (show x) has a strictness signature of <S>b and "b1 1 `seq` ()" is known to terminate. Now consider a function h with signature "<C(S)>", and the expression e1 = h b1 now h puts a demand of <C(S)> onto its argument, and the demand transformer turns it into <S>b Now the DmdResult "b" does apply to us, even though "b1 `seq` ()" does not diverge, and we do not anything being passed to b. Note [Asymmetry of 'both' for DmdType and DmdResult] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'both' for DmdTypes is *asymmetrical*, because there is only one result! For example, given (e1 e2), we get a DmdType dt1 for e1, use its arg demand to analyse e2 giving dt2, and then do (dt1 `bothType` dt2). Similarly with case e of { p -> rhs } we get dt_scrut from the scrutinee and dt_rhs from the RHS, and then compute (dt_rhs `bothType` dt_scrut). We 1. combine the information on the free variables, 2. take the demand on arguments from the first argument 3. combine the termination results, but 4. take CPR info from the first argument. 3 and 4 are implemented in bothDmdResult. -} -- Equality needed for fixpoints in DmdAnal instance Eq DmdType where (==) (DmdType fv1 ds1 res1) (DmdType fv2 ds2 res2) = nonDetUFMToList fv1 == nonDetUFMToList fv2 -- It's OK to use nonDetUFMToList here because we're testing for -- equality and even though the lists will be in some arbitrary -- Unique order, it is the same order for both && ds1 == ds2 && res1 == res2 lubDmdType :: DmdType -> DmdType -> DmdType lubDmdType d1 d2 = DmdType lub_fv lub_ds lub_res where n = max (dmdTypeDepth d1) (dmdTypeDepth d2) (DmdType fv1 ds1 r1) = ensureArgs n d1 (DmdType fv2 ds2 r2) = ensureArgs n d2 lub_fv = plusVarEnv_CD lubDmd fv1 (defaultDmd r1) fv2 (defaultDmd r2) lub_ds = zipWithEqual "lubDmdType" lubDmd ds1 ds2 lub_res = lubDmdResult r1 r2 {- Note [The need for BothDmdArg] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Previously, the right argument to bothDmdType, as well as the return value of dmdAnalStar via postProcessDmdType, was a DmdType. But bothDmdType only needs to know about the free variables and termination information, but nothing about the demand put on arguments, nor cpr information. So we make that explicit by only passing the relevant information. -} type BothDmdArg = (DmdEnv, Termination ()) mkBothDmdArg :: DmdEnv -> BothDmdArg mkBothDmdArg env = (env, Dunno ()) toBothDmdArg :: DmdType -> BothDmdArg toBothDmdArg (DmdType fv _ r) = (fv, go r) where go (Dunno {}) = Dunno () go Diverges = Diverges bothDmdType :: DmdType -> BothDmdArg -> DmdType bothDmdType (DmdType fv1 ds1 r1) (fv2, t2) -- See Note [Asymmetry of 'both' for DmdType and DmdResult] -- 'both' takes the argument/result info from its *first* arg, -- using its second arg just for its free-var info. = DmdType (plusVarEnv_CD bothDmd fv1 (defaultDmd r1) fv2 (defaultDmd t2)) ds1 (r1 `bothDmdResult` t2) instance Outputable DmdType where ppr (DmdType fv ds res) = hsep [hcat (map ppr ds) <> ppr res, if null fv_elts then empty else braces (fsep (map pp_elt fv_elts))] where pp_elt (uniq, dmd) = ppr uniq <> text "->" <> ppr dmd fv_elts = nonDetUFMToList fv -- It's OK to use nonDetUFMToList here because we only do it for -- pretty printing emptyDmdEnv :: VarEnv Demand emptyDmdEnv = emptyVarEnv -- nopDmdType is the demand of doing nothing -- (lazy, absent, no CPR information, no termination information). -- Note that it is ''not'' the top of the lattice (which would be "may use everything"), -- so it is (no longer) called topDmd nopDmdType, botDmdType :: DmdType nopDmdType = DmdType emptyDmdEnv [] topRes botDmdType = DmdType emptyDmdEnv [] botRes cprProdDmdType :: Arity -> DmdType cprProdDmdType arity = DmdType emptyDmdEnv [] (vanillaCprProdRes arity) isTopDmdType :: DmdType -> Bool isTopDmdType (DmdType env [] res) | isTopRes res && isEmptyVarEnv env = True isTopDmdType _ = False mkDmdType :: DmdEnv -> [Demand] -> DmdResult -> DmdType mkDmdType fv ds res = DmdType fv ds res dmdTypeDepth :: DmdType -> Arity dmdTypeDepth (DmdType _ ds _) = length ds -- | This makes sure we can use the demand type with n arguments. -- It extends the argument list with the correct resTypeArgDmd. -- It also adjusts the DmdResult: Divergence survives additional arguments, -- CPR information does not (and definite converge also would not). ensureArgs :: Arity -> DmdType -> DmdType ensureArgs n d | n == depth = d | otherwise = DmdType fv ds' r' where depth = dmdTypeDepth d DmdType fv ds r = d ds' = take n (ds ++ repeat (resTypeArgDmd r)) r' = case r of -- See [Nature of result demand] Dunno _ -> topRes _ -> r seqDmdType :: DmdType -> () seqDmdType (DmdType env ds res) = seqDmdEnv env `seq` seqDemandList ds `seq` seqDmdResult res `seq` () seqDmdEnv :: DmdEnv -> () seqDmdEnv env = seqEltsUFM seqDemandList env splitDmdTy :: DmdType -> (Demand, DmdType) -- Split off one function argument -- We already have a suitable demand on all -- free vars, so no need to add more! splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty) splitDmdTy ty@(DmdType _ [] res_ty) = (resTypeArgDmd res_ty, ty) -- When e is evaluated after executing an IO action, and d is e's demand, then -- what of this demand should we consider, given that the IO action can cleanly -- exit? -- * We have to kill all strictness demands (i.e. lub with a lazy demand) -- * We can keep usage information (i.e. lub with an absent demand) -- * We have to kill definite divergence -- * We can keep CPR information. -- See Note [IO hack in the demand analyser] in DmdAnal deferAfterIO :: DmdType -> DmdType deferAfterIO d@(DmdType _ _ res) = case d `lubDmdType` nopDmdType of DmdType fv ds _ -> DmdType fv ds (defer_res res) where defer_res r@(Dunno {}) = r defer_res _ = topRes -- Diverges strictenDmd :: Demand -> CleanDemand strictenDmd (JD { sd = s, ud = u}) = JD { sd = poke_s s, ud = poke_u u } where poke_s Lazy = HeadStr poke_s (Str s) = s poke_u Abs = UHead poke_u (Use _ u) = u -- Deferring and peeling type DmdShell -- Describes the "outer shell" -- of a Demand = JointDmd (Str ()) (Use ()) toCleanDmd :: Demand -> (DmdShell, CleanDemand) -- Splits a Demand into its "shell" and the inner "clean demand" toCleanDmd (JD { sd = s, ud = u }) = (JD { sd = ss, ud = us }, JD { sd = s', ud = u' }) -- See Note [Analyzing with lazy demand and lambdas] -- See Note [Analysing with absent demand] where (ss, s') = case s of Str s' -> (Str (), s') Lazy -> (Lazy, HeadStr) (us, u') = case u of Use c u' -> (Use c (), u') Abs -> (Abs, Used) -- This is used in dmdAnalStar when post-processing -- a function's argument demand. So we only care about what -- does to free variables, and whether it terminates. -- see Note [The need for BothDmdArg] postProcessDmdType :: DmdShell -> DmdType -> BothDmdArg postProcessDmdType du@(JD { sd = ss }) (DmdType fv _ res_ty) = (postProcessDmdEnv du fv, term_info) where term_info = case postProcessDmdResult ss res_ty of Dunno _ -> Dunno () Diverges -> Diverges postProcessDmdResult :: Str () -> DmdResult -> DmdResult postProcessDmdResult Lazy _ = topRes postProcessDmdResult _ res = res postProcessDmdEnv :: DmdShell -> DmdEnv -> DmdEnv postProcessDmdEnv ds@(JD { sd = ss, ud = us }) env | Abs <- us = emptyDmdEnv -- In this case (postProcessDmd ds) == id; avoid a redundant rebuild -- of the environment. Be careful, bad things will happen if this doesn't -- match postProcessDmd (see #13977). | Str _ <- ss , Use One _ <- us = env | otherwise = mapVarEnv (postProcessDmd ds) env -- For the Absent case just discard all usage information -- We only processed the thing at all to analyse the body -- See Note [Always analyse in virgin pass] reuseEnv :: DmdEnv -> DmdEnv reuseEnv = mapVarEnv (postProcessDmd (JD { sd = Str (), ud = Use Many () })) postProcessUnsat :: DmdShell -> DmdType -> DmdType postProcessUnsat ds@(JD { sd = ss }) (DmdType fv args res_ty) = DmdType (postProcessDmdEnv ds fv) (map (postProcessDmd ds) args) (postProcessDmdResult ss res_ty) postProcessDmd :: DmdShell -> Demand -> Demand postProcessDmd (JD { sd = ss, ud = us }) (JD { sd = s, ud = a}) = JD { sd = s', ud = a' } where s' = case ss of Lazy -> Lazy Str _ -> s a' = case us of Abs -> Abs Use Many _ -> markReusedDmd a Use One _ -> a -- Peels one call level from the demand, and also returns -- whether it was unsaturated (separately for strictness and usage) peelCallDmd :: CleanDemand -> (CleanDemand, DmdShell) -- Exploiting the fact that -- on the strictness side C(B) = B -- and on the usage side C(U) = U peelCallDmd (JD {sd = s, ud = u}) = (JD { sd = s', ud = u' }, JD { sd = ss, ud = us }) where (s', ss) = case s of SCall s' -> (s', Str ()) HyperStr -> (HyperStr, Str ()) _ -> (HeadStr, Lazy) (u', us) = case u of UCall c u' -> (u', Use c ()) _ -> (Used, Use Many ()) -- The _ cases for usage includes UHead which seems a bit wrong -- because the body isn't used at all! -- c.f. the Abs case in toCleanDmd -- Peels that multiple nestings of calls clean demand and also returns -- whether it was unsaturated (separately for strictness and usage -- see Note [Demands from unsaturated function calls] peelManyCalls :: Int -> CleanDemand -> DmdShell peelManyCalls n (JD { sd = str, ud = abs }) = JD { sd = go_str n str, ud = go_abs n abs } where go_str :: Int -> StrDmd -> Str () -- True <=> unsaturated, defer go_str 0 _ = Str () go_str _ HyperStr = Str () -- == go_str (n-1) HyperStr, as HyperStr = Call(HyperStr) go_str n (SCall d') = go_str (n-1) d' go_str _ _ = Lazy go_abs :: Int -> UseDmd -> Use () -- Many <=> unsaturated, or at least go_abs 0 _ = Use One () -- one UCall Many in the demand go_abs n (UCall One d') = go_abs (n-1) d' go_abs _ _ = Use Many () {- Note [Demands from unsaturated function calls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider a demand transformer d1 -> d2 -> r for f. If a sufficiently detailed demand is fed into this transformer, e.g <C(C(S)), C1(C1(S))> arising from "f x1 x2" in a strict, use-once context, then d1 and d2 is precisely the demand unleashed onto x1 and x2 (similar for the free variable environment) and furthermore the result information r is the one we want to use. An anonymous lambda is also an unsaturated function all (needs one argument, none given), so this applies to that case as well. But the demand fed into f might be less than <C(C(S)), C1(C1(S))>. There are a few cases: * Not enough demand on the strictness side: - In that case, we need to zap all strictness in the demand on arguments and free variables. - Furthermore, we remove CPR information. It could be left, but given the incoming demand is not enough to evaluate so far we just do not bother. - And finally termination information: If r says that f diverges for sure, then this holds when the demand guarantees that two arguments are going to be passed. If the demand is lower, we may just as well converge. If we were tracking definite convegence, than that would still hold under a weaker demand than expected by the demand transformer. * Not enough demand from the usage side: The missing usage can be expanded using UCall Many, therefore this is subsumed by the third case: * At least one of the uses has a cardinality of Many. - Even if f puts a One demand on any of its argument or free variables, if we call f multiple times, we may evaluate this argument or free variable multiple times. So forget about any occurrence of "One" in the demand. In dmdTransformSig, we call peelManyCalls to find out if we are in any of these cases, and then call postProcessUnsat to reduce the demand appropriately. Similarly, dmdTransformDictSelSig and dmdAnal, when analyzing a Lambda, use peelCallDmd, which peels only one level, but also returns the demand put on the body of the function. -} peelFV :: DmdType -> Var -> (DmdType, Demand) peelFV (DmdType fv ds res) id = -- pprTrace "rfv" (ppr id <+> ppr dmd $$ ppr fv) (DmdType fv' ds res, dmd) where fv' = fv `delVarEnv` id -- See Note [Default demand on free variables] dmd = lookupVarEnv fv id `orElse` defaultDmd res addDemand :: Demand -> DmdType -> DmdType addDemand dmd (DmdType fv ds res) = DmdType fv (dmd:ds) res findIdDemand :: DmdType -> Var -> Demand findIdDemand (DmdType fv _ res) id = lookupVarEnv fv id `orElse` defaultDmd res {- Note [Default demand on free variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the variable is not mentioned in the environment of a demand type, its demand is taken to be a result demand of the type. For the strictness component, if the result demand is a Diverges, then we use HyperStr else we use Lazy For the usage component, we use Absent. So we use either absDmd or botDmd. Also note the equations for lubDmdResult (resp. bothDmdResult) noted there. Note [Always analyse in virgin pass] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tricky point: make sure that we analyse in the 'virgin' pass. Consider rec { f acc x True = f (...rec { g y = ...g... }...) f acc x False = acc } In the virgin pass for 'f' we'll give 'f' a very strict (bottom) type. That might mean that we analyse the sub-expression containing the E = "...rec g..." stuff in a bottom demand. Suppose we *didn't analyse* E, but just returned botType. Then in the *next* (non-virgin) iteration for 'f', we might analyse E in a weaker demand, and that will trigger doing a fixpoint iteration for g. But *because it's not the virgin pass* we won't start g's iteration at bottom. Disaster. (This happened in $sfibToList' of nofib/spectral/fibheaps.) So in the virgin pass we make sure that we do analyse the expression at least once, to initialise its signatures. Note [Analyzing with lazy demand and lambdas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The insight for analyzing lambdas follows from the fact that for strictness S = C(L). This polymorphic expansion is critical for cardinality analysis of the following example: {-# NOINLINE build #-} build g = (g (:) [], g (:) []) h c z = build (\x -> let z1 = z ++ z in if c then \y -> x (y ++ z1) else \y -> x (z1 ++ y)) One can see that `build` assigns to `g` demand <L,C(C1(U))>. Therefore, when analyzing the lambda `(\x -> ...)`, we expect each lambda \y -> ... to be annotated as "one-shot" one. Therefore (\x -> \y -> x (y ++ z)) should be analyzed with a demand <C(C(..), C(C1(U))>. This is achieved by, first, converting the lazy demand L into the strict S by the second clause of the analysis. Note [Analysing with absent demand] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we analyse an expression with demand <L,A>. The "A" means "absent", so this expression will never be needed. What should happen? There are several wrinkles: * We *do* want to analyse the expression regardless. Reason: Note [Always analyse in virgin pass] But we can post-process the results to ignore all the usage demands coming back. This is done by postProcessDmdType. * In a previous incarnation of GHC we needed to be extra careful in the case of an *unlifted type*, because unlifted values are evaluated even if they are not used. Example (see #9254): f :: (() -> (# Int#, () #)) -> () -- Strictness signature is -- <C(S(LS)), 1*C1(U(A,1*U()))> -- I.e. calls k, but discards first component of result f k = case k () of (# _, r #) -> r g :: Int -> () g y = f (\n -> (# case y of I# y2 -> y2, n #)) Here f's strictness signature says (correctly) that it calls its argument function and ignores the first component of its result. This is correct in the sense that it'd be fine to (say) modify the function so that always returned 0# in the first component. But in function g, we *will* evaluate the 'case y of ...', because it has type Int#. So 'y' will be evaluated. So we must record this usage of 'y', else 'g' will say 'y' is absent, and will w/w so that 'y' is bound to an aBSENT_ERROR thunk. However, the argument of toCleanDmd always satisfies the let/app invariant; so if it is unlifted it is also okForSpeculation, and so can be evaluated in a short finite time -- and that rules out nasty cases like the one above. (I'm not quite sure why this was a problem in an earlier version of GHC, but it isn't now.) ************************************************************************ * * Demand signatures * * ************************************************************************ In a let-bound Id we record its strictness info. In principle, this strictness info is a demand transformer, mapping a demand on the Id into a DmdType, which gives a) the free vars of the Id's value b) the Id's arguments c) an indication of the result of applying the Id to its arguments However, in fact we store in the Id an extremely emascuated demand transfomer, namely a single DmdType (Nevertheless we dignify StrictSig as a distinct type.) This DmdType gives the demands unleashed by the Id when it is applied to as many arguments as are given in by the arg demands in the DmdType. Also see Note [Nature of result demand] for the meaning of a DmdResult in a strictness signature. If an Id is applied to less arguments than its arity, it means that the demand on the function at a call site is weaker than the vanilla call demand, used for signature inference. Therefore we place a top demand on all arguments. Otherwise, the demand is specified by Id's signature. For example, the demand transformer described by the demand signature StrictSig (DmdType {x -> <S,1*U>} <L,A><L,U(U,U)>m) says that when the function is applied to two arguments, it unleashes demand <S,1*U> on the free var x, <L,A> on the first arg, and <L,U(U,U)> on the second, then returning a constructor. If this same function is applied to one arg, all we can say is that it uses x with <L,U>, and its arg with demand <L,U>. Note [Understanding DmdType and StrictSig] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Demand types are sound approximations of an expression's semantics relative to the incoming demand we put the expression under. Consider the following expression: \x y -> x `seq` (y, 2*x) Here is a table with demand types resulting from different incoming demands we put that expression under. Note the monotonicity; a stronger incoming demand yields a more precise demand type: incoming demand | demand type ---------------------------------------------------- <S ,HU > | <L,U><L,U>{} <C(C(S )),C1(C1(U ))> | <S,U><L,U>{} <C(C(S(S,L))),C1(C1(U(1*U,A)))> | <S,1*HU><S,1*U>{} Note that in the first example, the depth of the demand type was *higher* than the arity of the incoming call demand due to the anonymous lambda. The converse is also possible and happens when we unleash demand signatures. In @f x y@, the incoming call demand on f has arity 2. But if all we have is a demand signature with depth 1 for @f@ (which we can safely unleash, see below), the demand type of @f@ under a call demand of arity 2 has a *lower* depth of 1. So: Demand types are elicited by putting an expression under an incoming (call) demand, the arity of which can be lower or higher than the depth of the resulting demand type. In contrast, a demand signature summarises a function's semantics *without* immediately specifying the incoming demand it was produced under. Despite StrSig being a newtype wrapper around DmdType, it actually encodes two things: * The threshold (i.e., minimum arity) to unleash the signature * A demand type that is sound to unleash when the minimum arity requirement is met. Here comes the subtle part: The threshold is encoded in the wrapped demand type's depth! So in mkStrictSigForArity we make sure to trim the list of argument demands to the given threshold arity. Call sites will make sure that this corresponds to the arity of the call demand that elicited the wrapped demand type. See also Note [What are demand signatures?] in DmdAnal. Besides trimming argument demands, mkStrictSigForArity will also trim CPR information if necessary. -} -- | The depth of the wrapped 'DmdType' encodes the arity at which it is safe -- to unleash. Better construct this through 'mkStrictSigForArity'. -- See Note [Understanding DmdType and StrictSig] newtype StrictSig = StrictSig DmdType deriving( Eq ) instance Outputable StrictSig where ppr (StrictSig ty) = ppr ty -- Used for printing top-level strictness pragmas in interface files pprIfaceStrictSig :: StrictSig -> SDoc pprIfaceStrictSig (StrictSig (DmdType _ dmds res)) = hcat (map ppr dmds) <> ppr res -- | Turns a 'DmdType' computed for the particular 'Arity' into a 'StrictSig' -- unleashable at that arity. See Note [Understanding DmdType and StrictSig] mkStrictSigForArity :: Arity -> DmdType -> StrictSig mkStrictSigForArity arity dmd_ty = StrictSig (ensureArgs arity dmd_ty) mkClosedStrictSig :: [Demand] -> DmdResult -> StrictSig mkClosedStrictSig ds res = mkStrictSigForArity (length ds) (DmdType emptyDmdEnv ds res) splitStrictSig :: StrictSig -> ([Demand], DmdResult) splitStrictSig (StrictSig (DmdType _ dmds res)) = (dmds, res) increaseStrictSigArity :: Int -> StrictSig -> StrictSig -- ^ Add extra arguments to a strictness signature. -- In contrast to 'etaExpandStrictSig', this /prepends/ additional argument -- demands and leaves CPR info intact. increaseStrictSigArity arity_increase sig@(StrictSig dmd_ty@(DmdType env dmds res)) | isTopDmdType dmd_ty = sig | arity_increase == 0 = sig | arity_increase < 0 = WARN( True, text "increaseStrictSigArity:" <+> text "negative arity increase" <+> ppr arity_increase ) nopSig | otherwise = StrictSig (DmdType env dmds' res) where dmds' = replicate arity_increase topDmd ++ dmds etaExpandStrictSig :: Arity -> StrictSig -> StrictSig -- ^ We are expanding (\x y. e) to (\x y z. e z). -- In contrast to 'increaseStrictSigArity', this /appends/ extra arg demands if -- necessary, potentially destroying the signature's CPR property. etaExpandStrictSig arity (StrictSig dmd_ty) | arity < dmdTypeDepth dmd_ty -- an arity decrease must zap the whole signature, because it was possibly -- computed for a higher incoming call demand. = nopSig | otherwise = StrictSig $ ensureArgs arity dmd_ty isTopSig :: StrictSig -> Bool isTopSig (StrictSig ty) = isTopDmdType ty hasDemandEnvSig :: StrictSig -> Bool hasDemandEnvSig (StrictSig (DmdType env _ _)) = not (isEmptyVarEnv env) strictSigDmdEnv :: StrictSig -> DmdEnv strictSigDmdEnv (StrictSig (DmdType env _ _)) = env -- | True if the signature diverges or throws an exception isBottomingSig :: StrictSig -> Bool isBottomingSig (StrictSig (DmdType _ _ res)) = isBotRes res nopSig, botSig :: StrictSig nopSig = StrictSig nopDmdType botSig = StrictSig botDmdType cprProdSig :: Arity -> StrictSig cprProdSig arity = StrictSig (cprProdDmdType arity) seqStrictSig :: StrictSig -> () seqStrictSig (StrictSig ty) = seqDmdType ty dmdTransformSig :: StrictSig -> CleanDemand -> DmdType -- (dmdTransformSig fun_sig dmd) considers a call to a function whose -- signature is fun_sig, with demand dmd. We return the demand -- that the function places on its context (eg its args) dmdTransformSig (StrictSig dmd_ty@(DmdType _ arg_ds _)) cd = postProcessUnsat (peelManyCalls (length arg_ds) cd) dmd_ty -- see Note [Demands from unsaturated function calls] dmdTransformDataConSig :: Arity -> StrictSig -> CleanDemand -> DmdType -- Same as dmdTransformSig but for a data constructor (worker), -- which has a special kind of demand transformer. -- If the constructor is saturated, we feed the demand on -- the result into the constructor arguments. dmdTransformDataConSig arity (StrictSig (DmdType _ _ con_res)) (JD { sd = str, ud = abs }) | Just str_dmds <- go_str arity str , Just abs_dmds <- go_abs arity abs = DmdType emptyDmdEnv (mkJointDmds str_dmds abs_dmds) con_res -- Must remember whether it's a product, hence con_res, not TopRes | otherwise -- Not saturated = nopDmdType where go_str 0 dmd = splitStrProdDmd arity dmd go_str n (SCall s') = go_str (n-1) s' go_str n HyperStr = go_str (n-1) HyperStr go_str _ _ = Nothing go_abs 0 dmd = splitUseProdDmd arity dmd go_abs n (UCall One u') = go_abs (n-1) u' go_abs _ _ = Nothing dmdTransformDictSelSig :: StrictSig -> CleanDemand -> DmdType -- Like dmdTransformDataConSig, we have a special demand transformer -- for dictionary selectors. If the selector is saturated (ie has one -- argument: the dictionary), we feed the demand on the result into -- the indicated dictionary component. dmdTransformDictSelSig (StrictSig (DmdType _ [dict_dmd] _)) cd | (cd',defer_use) <- peelCallDmd cd , Just jds <- splitProdDmd_maybe dict_dmd = postProcessUnsat defer_use $ DmdType emptyDmdEnv [mkOnceUsedDmd $ mkProdDmd $ map (enhance cd') jds] topRes | otherwise = nopDmdType -- See Note [Demand transformer for a dictionary selector] where enhance cd old | isAbsDmd old = old | otherwise = mkOnceUsedDmd cd -- This is the one! dmdTransformDictSelSig _ _ = panic "dmdTransformDictSelSig: no args" {- Note [Demand transformer for a dictionary selector] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we evaluate (op dict-expr) under demand 'd', then we can push the demand 'd' into the appropriate field of the dictionary. What *is* the appropriate field? We just look at the strictness signature of the class op, which will be something like: U(AAASAAAAA). Then replace the 'S' by the demand 'd'. For single-method classes, which are represented by newtypes the signature of 'op' won't look like U(...), so the splitProdDmd_maybe will fail. That's fine: if we are doing strictness analysis we are also doing inlining, so we'll have inlined 'op' into a cast. So we can bale out in a conservative way, returning nopDmdType. It is (just.. #8329) possible to be running strictness analysis *without* having inlined class ops from single-method classes. Suppose you are using ghc --make; and the first module has a local -O0 flag. So you may load a class without interface pragmas, ie (currently) without an unfolding for the class ops. Now if a subsequent module in the --make sweep has a local -O flag you might do strictness analysis, but there is no inlining for the class op. This is weird, so I'm not worried about whether this optimises brilliantly; but it should not fall over. -} argsOneShots :: StrictSig -> Arity -> [[OneShotInfo]] -- See Note [Computing one-shot info] argsOneShots (StrictSig (DmdType _ arg_ds _)) n_val_args | unsaturated_call = [] | otherwise = go arg_ds where unsaturated_call = arg_ds `lengthExceeds` n_val_args go [] = [] go (arg_d : arg_ds) = argOneShots arg_d `cons` go arg_ds -- Avoid list tail like [ [], [], [] ] cons [] [] = [] cons a as = a:as -- saturatedByOneShots n C1(C1(...)) = True, -- <=> -- there are at least n nested C1(..) calls -- See Note [Demand on the worker] in WorkWrap saturatedByOneShots :: Int -> Demand -> Bool saturatedByOneShots n (JD { ud = usg }) = case usg of Use _ arg_usg -> go n arg_usg _ -> False where go 0 _ = True go n (UCall One u) = go (n-1) u go _ _ = False argOneShots :: Demand -- depending on saturation -> [OneShotInfo] argOneShots (JD { ud = usg }) = case usg of Use _ arg_usg -> go arg_usg _ -> [] where go (UCall One u) = OneShotLam : go u go (UCall Many u) = NoOneShotInfo : go u go _ = [] {- Note [Computing one-shot info] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider a call f (\pqr. e1) (\xyz. e2) e3 where f has usage signature C1(C(C1(U))) C1(U) U Then argsOneShots returns a [[OneShotInfo]] of [[OneShot,NoOneShotInfo,OneShot], [OneShot]] The occurrence analyser propagates this one-shot infor to the binders \pqr and \xyz; see Note [Use one-shot information] in OccurAnal. -} -- | Returns true if an application to n args -- would diverge or throw an exception -- See Note [Unsaturated applications] appIsBottom :: StrictSig -> Int -> Bool appIsBottom (StrictSig (DmdType _ ds res)) n | isBotRes res = not $ lengthExceeds ds n appIsBottom _ _ = False {- Note [Unsaturated applications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If a function having bottom as its demand result is applied to a less number of arguments than its syntactic arity, we cannot say for sure that it is going to diverge. This is the reason why we use the function appIsBottom, which, given a strictness signature and a number of arguments, says conservatively if the function is going to diverge or not. Zap absence or one-shot information, under control of flags Note [Killing usage information] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The flags -fkill-one-shot and -fkill-absence let you switch off the generation of absence or one-shot information altogether. This is only used for performance tests, to see how important they are. -} zapUsageEnvSig :: StrictSig -> StrictSig -- Remove the usage environment from the demand zapUsageEnvSig (StrictSig (DmdType _ ds r)) = mkClosedStrictSig ds r zapUsageDemand :: Demand -> Demand -- Remove the usage info, but not the strictness info, from the demand zapUsageDemand = kill_usage $ KillFlags { kf_abs = True , kf_used_once = True , kf_called_once = True } -- | Remove all 1* information (but not C1 information) from the demand zapUsedOnceDemand :: Demand -> Demand zapUsedOnceDemand = kill_usage $ KillFlags { kf_abs = False , kf_used_once = True , kf_called_once = False } -- | Remove all 1* information (but not C1 information) from the strictness -- signature zapUsedOnceSig :: StrictSig -> StrictSig zapUsedOnceSig (StrictSig (DmdType env ds r)) = StrictSig (DmdType env (map zapUsedOnceDemand ds) r) killUsageDemand :: DynFlags -> Demand -> Demand -- See Note [Killing usage information] killUsageDemand dflags dmd | Just kfs <- killFlags dflags = kill_usage kfs dmd | otherwise = dmd killUsageSig :: DynFlags -> StrictSig -> StrictSig -- See Note [Killing usage information] killUsageSig dflags sig@(StrictSig (DmdType env ds r)) | Just kfs <- killFlags dflags = StrictSig (DmdType env (map (kill_usage kfs) ds) r) | otherwise = sig data KillFlags = KillFlags { kf_abs :: Bool , kf_used_once :: Bool , kf_called_once :: Bool } killFlags :: DynFlags -> Maybe KillFlags -- See Note [Killing usage information] killFlags dflags | not kf_abs && not kf_used_once = Nothing | otherwise = Just (KillFlags {..}) where kf_abs = gopt Opt_KillAbsence dflags kf_used_once = gopt Opt_KillOneShot dflags kf_called_once = kf_used_once kill_usage :: KillFlags -> Demand -> Demand kill_usage kfs (JD {sd = s, ud = u}) = JD {sd = s, ud = zap_musg kfs u} zap_musg :: KillFlags -> ArgUse -> ArgUse zap_musg kfs Abs | kf_abs kfs = useTop | otherwise = Abs zap_musg kfs (Use c u) | kf_used_once kfs = Use Many (zap_usg kfs u) | otherwise = Use c (zap_usg kfs u) zap_usg :: KillFlags -> UseDmd -> UseDmd zap_usg kfs (UCall c u) | kf_called_once kfs = UCall Many (zap_usg kfs u) | otherwise = UCall c (zap_usg kfs u) zap_usg kfs (UProd us) = UProd (map (zap_musg kfs) us) zap_usg _ u = u -- If the argument is a used non-newtype dictionary, give it strict -- demand. Also split the product type & demand and recur in order to -- similarly strictify the argument's contained used non-newtype -- superclass dictionaries. We use the demand as our recursive measure -- to guarantee termination. strictifyDictDmd :: Type -> Demand -> Demand strictifyDictDmd ty dmd = case getUseDmd dmd of Use n _ | Just (tycon, _arg_tys, _data_con, inst_con_arg_tys) <- splitDataProductType_maybe ty, not (isNewTyCon tycon), isClassTyCon tycon -- is a non-newtype dictionary -> seqDmd `bothDmd` -- main idea: ensure it's strict case splitProdDmd_maybe dmd of -- superclass cycles should not be a problem, since the demand we are -- consuming would also have to be infinite in order for us to diverge Nothing -> dmd -- no components have interesting demand, so stop -- looking for superclass dicts Just dmds | all (not . isAbsDmd) dmds -> evalDmd -- abstract to strict w/ arbitrary component use, since this -- smells like reboxing; results in CBV boxed -- -- TODO revisit this if we ever do boxity analysis | otherwise -> case mkProdDmd $ zipWith strictifyDictDmd inst_con_arg_tys dmds of JD {sd = s,ud = a} -> JD (Str s) (Use n a) -- TODO could optimize with an aborting variant of zipWith since -- the superclass dicts are always a prefix _ -> dmd -- unused or not a dictionary strictifyDmd :: Demand -> Demand strictifyDmd dmd@(JD { sd = str }) = dmd { sd = str `bothArgStr` Str HeadStr } {- Note [HyperStr and Use demands] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The information "HyperStr" needs to be in the strictness signature, and not in the demand signature, because we still want to know about the demand on things. Consider f (x,y) True = error (show x) f (x,y) False = x+1 The signature of f should be <S(SL),1*U(1*U(U),A)><S,1*U>m. If we were not distinguishing the uses on x and y in the True case, we could either not figure out how deeply we can unpack x, or that we do not have to pass y. ************************************************************************ * * Serialisation * * ************************************************************************ -} instance Binary StrDmd where put_ bh HyperStr = do putByte bh 0 put_ bh HeadStr = do putByte bh 1 put_ bh (SCall s) = do putByte bh 2 put_ bh s put_ bh (SProd sx) = do putByte bh 3 put_ bh sx get bh = do h <- getByte bh case h of 0 -> do return HyperStr 1 -> do return HeadStr 2 -> do s <- get bh return (SCall s) _ -> do sx <- get bh return (SProd sx) instance Binary ArgStr where put_ bh Lazy = do putByte bh 0 put_ bh (Str s) = do putByte bh 1 put_ bh s get bh = do h <- getByte bh case h of 0 -> return Lazy _ -> do s <- get bh return $ Str s instance Binary Count where put_ bh One = do putByte bh 0 put_ bh Many = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> return One _ -> return Many instance Binary ArgUse where put_ bh Abs = do putByte bh 0 put_ bh (Use c u) = do putByte bh 1 put_ bh c put_ bh u get bh = do h <- getByte bh case h of 0 -> return Abs _ -> do c <- get bh u <- get bh return $ Use c u instance Binary UseDmd where put_ bh Used = do putByte bh 0 put_ bh UHead = do putByte bh 1 put_ bh (UCall c u) = do putByte bh 2 put_ bh c put_ bh u put_ bh (UProd ux) = do putByte bh 3 put_ bh ux get bh = do h <- getByte bh case h of 0 -> return $ Used 1 -> return $ UHead 2 -> do c <- get bh u <- get bh return (UCall c u) _ -> do ux <- get bh return (UProd ux) instance (Binary s, Binary u) => Binary (JointDmd s u) where put_ bh (JD { sd = x, ud = y }) = do put_ bh x; put_ bh y get bh = do x <- get bh y <- get bh return $ JD { sd = x, ud = y } instance Binary StrictSig where put_ bh (StrictSig aa) = do put_ bh aa get bh = do aa <- get bh return (StrictSig aa) instance Binary DmdType where -- Ignore DmdEnv when spitting out the DmdType put_ bh (DmdType _ ds dr) = do put_ bh ds put_ bh dr get bh = do ds <- get bh dr <- get bh return (DmdType emptyDmdEnv ds dr) instance Binary DmdResult where put_ bh (Dunno c) = do { putByte bh 0; put_ bh c } put_ bh Diverges = putByte bh 1 get bh = do { h <- getByte bh ; case h of 0 -> do { c <- get bh; return (Dunno c) } _ -> return Diverges } instance Binary CPRResult where put_ bh (RetSum n) = do { putByte bh 0; put_ bh n } put_ bh RetProd = putByte bh 1 put_ bh NoCPR = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do { n <- get bh; return (RetSum n) } 1 -> return RetProd _ -> return NoCPR
sdiehl/ghc
compiler/basicTypes/Demand.hs
bsd-3-clause
79,177
6
19
21,681
13,981
7,323
6,658
922
9
module Karamaan.Plankton.Arrow.Lens where import Prelude hiding (id) import Control.Arrow (Arrow, arr, (<<<), second) import Control.Category (id) import qualified Lens.Family as L viewA :: Arrow arr => L.FoldLike a s t a b -> arr s a viewA = arr . L.view overA :: Arrow p => L.LensLike (Context a b) s t a b -> p a b -> p s t overA l p = arr (uncurry id) <<< second p <<< arr go where go s = case l sell s of Context f a -> (f, a) -- This is %%~ from Control.Lens but I prefer a name rather than symbols -- It isn't to do with /Arrow/ lenses per se, but I put it here rather than -- starting a new module just for one function. -- NB: It's probably better just to use 'traverseOf' overf :: Functor f => L.LensLike f s t a b -> (a -> f b) -> s -> f t overf = id -- Context stuff which is from lens. Since we don't want to import -- lens we replicate it here. Arguably it could be in -- lens-family-core. data Context a b t = Context (b -> t) a sell :: a -> Context a b b sell = Context id instance Functor (Context a b) where fmap f (Context g t) = Context (f . g) t {-# INLINE fmap #-}
karamaan/karamaan-plankton
Karamaan/Plankton/Arrow/Lens.hs
bsd-3-clause
1,111
0
10
257
375
200
175
19
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Install -- Copyright : Isaac Jones 2003-2004 -- -- Maintainer : [email protected] -- Portability : portable -- -- This is the entry point into installing a built package. Performs the -- \"@.\/setup install@\" and \"@.\/setup copy@\" actions. It moves files into -- place based on the prefix argument. It does the generic bits and then calls -- compiler-specific functions to do the rest. {- 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 name of Isaac Jones nor the names of other 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. -} module Distribution.Simple.Install ( install, ) where import Distribution.PackageDescription ( PackageDescription(..), BuildInfo(..), Library(..), hasLibs, withLib, hasExes, withExe ) import Distribution.Package (Package(..)) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), InstallDirs(..), absoluteInstallDirs, substPathTemplate, withLibLBI) import Distribution.Simple.BuildPaths (haddockName, haddockPref) import Distribution.Simple.Utils ( createDirectoryIfMissingVerbose , installDirectoryContents, installOrdinaryFile, isInSearchPath , die, info, notice, warn, matchDirFileGlob ) import Distribution.Simple.Compiler ( CompilerFlavor(..), compilerFlavor ) import Distribution.Simple.Setup (CopyFlags(..), CopyDest(..), fromFlag) import qualified Distribution.Simple.GHC as GHC import qualified Distribution.Simple.NHC as NHC import qualified Distribution.Simple.JHC as JHC import qualified Distribution.Simple.LHC as LHC import qualified Distribution.Simple.Hugs as Hugs import qualified Distribution.Simple.UHC as UHC import qualified Distribution.Simple.HaskellSuite as HaskellSuite import Control.Monad (when, unless) import System.Directory ( doesDirectoryExist, doesFileExist ) import System.FilePath ( takeFileName, takeDirectory, (</>), isAbsolute ) import Distribution.Verbosity import Distribution.Text ( display ) -- |Perform the \"@.\/setup install@\" and \"@.\/setup copy@\" -- actions. Move files into place based on the prefix argument. FIX: -- nhc isn't implemented yet. install :: PackageDescription -- ^information from the .cabal file -> LocalBuildInfo -- ^information from the configure step -> CopyFlags -- ^flags sent to copy or install -> IO () install pkg_descr lbi flags = do let distPref = fromFlag (copyDistPref flags) verbosity = fromFlag (copyVerbosity flags) copydest = fromFlag (copyDest flags) installDirs@(InstallDirs { bindir = binPref, libdir = libPref, -- dynlibdir = dynlibPref, --see TODO below datadir = dataPref, progdir = progPref, docdir = docPref, htmldir = htmlPref, haddockdir = interfacePref, includedir = incPref}) = absoluteInstallDirs pkg_descr lbi copydest --TODO: decide if we need the user to be able to control the libdir -- for shared libs independently of the one for static libs. If so -- it should also have a flag in the command line UI -- For the moment use dynlibdir = libdir dynlibPref = libPref progPrefixPref = substPathTemplate (packageId pkg_descr) lbi (progPrefix lbi) progSuffixPref = substPathTemplate (packageId pkg_descr) lbi (progSuffix lbi) docExists <- doesDirectoryExist $ haddockPref distPref pkg_descr info verbosity ("directory " ++ haddockPref distPref pkg_descr ++ " does exist: " ++ show docExists) installDataFiles verbosity pkg_descr dataPref when docExists $ do createDirectoryIfMissingVerbose verbosity True htmlPref installDirectoryContents verbosity (haddockPref distPref pkg_descr) htmlPref -- setPermissionsRecursive [Read] htmlPref -- The haddock interface file actually already got installed -- in the recursive copy, but now we install it where we actually -- want it to be (normally the same place). We could remove the -- copy in htmlPref first. let haddockInterfaceFileSrc = haddockPref distPref pkg_descr </> haddockName pkg_descr haddockInterfaceFileDest = interfacePref </> haddockName pkg_descr -- We only generate the haddock interface file for libs, So if the -- package consists only of executables there will not be one: exists <- doesFileExist haddockInterfaceFileSrc when exists $ do createDirectoryIfMissingVerbose verbosity True interfacePref installOrdinaryFile verbosity haddockInterfaceFileSrc haddockInterfaceFileDest let lfile = licenseFile pkg_descr unless (null lfile) $ do createDirectoryIfMissingVerbose verbosity True docPref installOrdinaryFile verbosity lfile (docPref </> takeFileName lfile) let buildPref = buildDir lbi when (hasLibs pkg_descr) $ notice verbosity ("Installing library in " ++ libPref) when (hasExes pkg_descr) $ do notice verbosity ("Installing executable(s) in " ++ binPref) inPath <- isInSearchPath binPref when (not inPath) $ warn verbosity ("The directory " ++ binPref ++ " is not in the system search path.") -- install include files for all compilers - they may be needed to compile -- haskell files (using the CPP extension) when (hasLibs pkg_descr) $ installIncludeFiles verbosity pkg_descr incPref case compilerFlavor (compiler lbi) of GHC -> do withLibLBI pkg_descr lbi $ GHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr withExe pkg_descr $ GHC.installExe verbosity lbi installDirs buildPref (progPrefixPref, progSuffixPref) pkg_descr LHC -> do withLibLBI pkg_descr lbi $ LHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr withExe pkg_descr $ LHC.installExe verbosity lbi installDirs buildPref (progPrefixPref, progSuffixPref) pkg_descr JHC -> do withLib pkg_descr $ JHC.installLib verbosity libPref buildPref pkg_descr withExe pkg_descr $ JHC.installExe verbosity binPref buildPref (progPrefixPref, progSuffixPref) pkg_descr Hugs -> do let targetProgPref = progdir (absoluteInstallDirs pkg_descr lbi NoCopyDest) let scratchPref = scratchDir lbi Hugs.install verbosity lbi libPref progPref binPref targetProgPref scratchPref (progPrefixPref, progSuffixPref) pkg_descr NHC -> do withLibLBI pkg_descr lbi $ NHC.installLib verbosity libPref buildPref (packageId pkg_descr) withExe pkg_descr $ NHC.installExe verbosity binPref buildPref (progPrefixPref, progSuffixPref) UHC -> do withLib pkg_descr $ UHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr HaskellSuite {} -> withLib pkg_descr $ HaskellSuite.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr _ -> die $ "installing with " ++ display (compilerFlavor (compiler lbi)) ++ " is not implemented" -- register step should be performed by caller. -- | Install the files listed in data-files -- installDataFiles :: Verbosity -> PackageDescription -> FilePath -> IO () installDataFiles verbosity pkg_descr destDataDir = flip mapM_ (dataFiles pkg_descr) $ \ file -> do let srcDataDir = dataDir pkg_descr files <- matchDirFileGlob srcDataDir file let dir = takeDirectory file createDirectoryIfMissingVerbose verbosity True (destDataDir </> dir) sequence_ [ installOrdinaryFile verbosity (srcDataDir </> file') (destDataDir </> file') | file' <- files ] -- | Install the files listed in install-includes -- installIncludeFiles :: Verbosity -> PackageDescription -> FilePath -> IO () installIncludeFiles verbosity PackageDescription { library = Just lib } destIncludeDir = do incs <- mapM (findInc relincdirs) (installIncludes lbi) sequence_ [ do createDirectoryIfMissingVerbose verbosity True destDir installOrdinaryFile verbosity srcFile destFile | (relFile, srcFile) <- incs , let destFile = destIncludeDir </> relFile destDir = takeDirectory destFile ] where relincdirs = "." : filter (not.isAbsolute) (includeDirs lbi) lbi = libBuildInfo lib findInc [] file = die ("can't find include file " ++ file) findInc (dir:dirs) file = do let path = dir </> file exists <- doesFileExist path if exists then return (file, path) else findInc dirs file installIncludeFiles _ _ _ = die "installIncludeFiles: Can't happen?"
fpco/cabal
Cabal/Distribution/Simple/Install.hs
bsd-3-clause
10,283
0
17
2,344
1,763
922
841
137
8
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE CPP #-} -- ghc options {-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- {-# OPTIONS_GHC -fno-warn-missing-signatures #-} -- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-} -- {-# OPTIONS_GHC -fno-warn-name-shadowing #-} -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <[email protected]> -- Stability : experimental -- Portability: non-portable -- -- This module provides pretty printing functionality for Pire's -- abstract and concrete syntax: token module Pire.Pretty.Token where import Pire.Syntax.Token import Pire.Pretty.Common import Pire.Pretty.Ws () import Text.PrettyPrint as TPP -- import Control.Monad.Error #ifdef MIN_VERSION_GLASGOW_HASKELL #if MIN_VERSION_GLASGOW_HASKELL(7,10,3,0) -- ghc >= 7.10.3 #else -- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined #endif #else -- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x) import Control.Applicative #endif -- instance Disp t => Disp (Token ty t) where -- -- shorter? -- disp (LamTok lam ws) = (<>) <$> disp lam <*> disp ws -- disp (Dot txt ws) = (<>) <$> disp txt <*> disp ws -- disp (LetTok txt ws) = (<>) <$> disp txt <*> disp ws -- disp (BracketOpen txt ws) = (<>) <$> disp txt <*> disp ws -- disp (BracketClose txt ws) = (<>) <$> disp txt <*> disp ws -- disp (ParenOpen txt ws) = (<>) <$> disp txt <*> disp ws -- disp (ParenClose txt ws) = (<>) <$> disp txt <*> disp ws -- but can continue to define them separately as well... -- but have to use either one: cannot use a combination of the above with some instance decls below instance Disp t => Disp (Token 'LamTokTy t) where disp (LamTok bo ws) = (<>) <$> disp bo <*> disp ws instance Disp t => Disp (Token 'DotTy t) where disp (Dot bo ws) = (<>) <$> disp bo <*> disp ws instance Disp t => Disp (Token 'LetTokTy t) where disp (LetTok bo ws) = (<>) <$> disp bo <*> disp ws instance Disp t => Disp (Token 'BracketOpenTy t) where disp (BracketOpen bo ws) = (<>) <$> disp bo <*> disp ws instance Disp t => Disp (Token 'BracketCloseTy t) where disp (BracketClose bc ws) = (<>) <$> disp bc <*> disp ws instance Disp t => Disp (Token 'ParenOpenTy t) where disp (ParenOpen bo ws) = (<>) <$> disp bo <*> disp ws instance Disp t => Disp (Token 'ParenCloseTy t) where disp (ParenClose bc ws) = (<>) <$> disp bc <*> disp ws instance Disp t => Disp (Token 'BraceOpenTy t) where disp (BraceOpen bo ws) = (<>) <$> disp bo <*> disp ws instance Disp t => Disp (Token 'BraceCloseTy t) where disp (BraceClose bc ws) = (<>) <$> disp bc <*> disp ws -- the maybe's instance Disp t => Disp (Maybe (Token 'BraceOpenTy t)) where disp (Just bo) = disp bo disp Nothing = return TPP.empty instance Disp t => Disp (Maybe (Token 'BraceCloseTy t)) where disp (Just bo) = disp bo disp Nothing = return TPP.empty instance Disp t => Disp (Token 'InTy t) where disp (In in' ws) = (<>) <$> disp in' <*> disp ws instance Disp t => Disp (Token 'ColonTy t) where disp (Colon col ws) = (<>) <$> disp col <*> disp ws instance Disp t => Disp (Token 'EqualTy t) where disp (Equal eq ws) = (<>) <$> disp eq <*> disp ws instance Disp t => Disp (Token 'SubstTokTy t) where disp (SubstTok s ws) = (<>) <$> disp s <*> disp ws instance Disp t => Disp (Token 'ContraTokTy t) where disp (ContraTok c ws) = (<>) <$> disp c <*> disp ws instance Disp t => Disp (Token 'ByTy t) where disp (By b ws) = (<>) <$> disp b <*> disp ws instance Disp t => Disp (Token 'ArrowTy t) where disp (Arrow arr ws) = (<>) <$> disp arr <*> disp ws instance Disp t => Disp (Token 'IfTokTy t) where disp (IfTok if' ws) = (<>) <$> disp if' <*> disp ws instance Disp t => Disp (Token 'ThenTokTy t) where disp (ThenTok then' ws) = (<>) <$> disp then' <*> disp ws instance Disp t => Disp (Token 'ElseTokTy t) where disp (ElseTok else' ws) = (<>) <$> disp else' <*> disp ws instance Disp t => Disp (Token 'VBarTy t) where disp (VBar vb ws) = (<>) <$> disp vb <*> disp ws -- disp (Where ws) = do { dws <- disp ws ; return $ text "where" <> dws } instance Disp t => Disp (Token 'WhereTy t) where disp (Where w ws) = (<>) <$> disp w <*> disp ws instance Disp t => Disp (Token 'DataTokTy t) where disp (DataTok w ws) = (<>) <$> disp w <*> disp ws instance Disp t => Disp (Token 'OfTy t) where disp (Of o ws) = (<>) <$> disp o <*> disp ws -- + Maybe token instance Disp t => Disp (Maybe (Token 'OfTy t)) where disp Nothing = return TPP.empty disp (Just of') = disp of' instance Disp t => Disp (Token 'CaseTokTy t) where disp (CaseTok c ws) = (<>) <$> disp c <*> disp ws instance Disp t => Disp (Token 'PcaseTokTy t) where disp (PcaseTok c ws) = (<>) <$> disp c <*> disp ws instance Disp t => Disp (Token 'CommaTy t) where disp (Comma c ws) = (<>) <$> disp c <*> disp ws instance Disp t => Disp (Token 'ModuleTokTy t) where disp (ModuleTok m ws) = (<>) <$> disp m <*> disp ws instance Disp t => Disp (Token 'SemiColonTy t) where disp (SemiColon sem ws) = (<>) <$> disp sem <*> disp ws instance Disp t => Disp (Maybe (Token 'SemiColonTy t)) where disp (Just semicolon) = disp semicolon disp Nothing = return TPP.empty instance Disp t => Disp (Token 'ImportTokTy t) where disp (ImportTok i ws) = (<>) <$> disp i <*> disp ws
reuleaux/pire
src/Pire/Pretty/Token.hs
bsd-3-clause
5,905
0
10
1,434
1,978
998
980
84
0
module Algebra.PartialOrd ( -- * Partial orderings PartialOrd(..), partialOrdEq, -- * Fixed points of chains in partial orders lfpFrom, unsafeLfpFrom, gfpFrom, unsafeGfpFrom ) where import Algebra.Enumerable import qualified Data.Set as S import qualified Data.IntSet as IS import qualified Data.Map as M import qualified Data.IntMap as IM -- | A partial ordering on sets: <http://en.wikipedia.org/wiki/Partially_ordered_set> -- -- This can be defined using either |joinLeq| or |meetLeq|, or a more efficient definition -- can be derived directly. -- -- Reflexive: a `leq` a -- Antisymmetric: a `leq` b && b `leq` a ==> a == b -- Transitive: a `leq` b && b `leq` c ==> a `leq` c -- -- The superclass equality (which can be defined using |partialOrdEq|) must obey these laws: -- -- Reflexive: a == a -- Transitive: a == b && b == c ==> a == b class Eq a => PartialOrd a where leq :: a -> a -> Bool -- | The equality relation induced by the partial-order structure partialOrdEq :: PartialOrd a => a -> a -> Bool partialOrdEq x y = leq x y && leq y x instance Ord a => PartialOrd (S.Set a) where leq = S.isSubsetOf instance PartialOrd IS.IntSet where leq = IS.isSubsetOf instance (Ord k, PartialOrd v) => PartialOrd (M.Map k v) where m1 `leq` m2 = m1 `M.isSubmapOf` m2 && M.fold (\(x1, x2) b -> b && x1 `leq` x2) True (M.intersectionWith (,) m1 m2) instance PartialOrd v => PartialOrd (IM.IntMap v) where im1 `leq` im2 = im1 `IM.isSubmapOf` im2 && IM.fold (\(x1, x2) b -> b && x1 `leq` x2) True (IM.intersectionWith (,) im1 im2) instance (Eq v, Enumerable k) => Eq (k -> v) where f == g = all (\k -> f k == g k) universe instance (PartialOrd v, Enumerable k) => PartialOrd (k -> v) where f `leq` g = all (\k -> f k `leq` g k) universe instance (PartialOrd a, PartialOrd b) => PartialOrd (a, b) where -- NB: *not* a lexical ordering. This is because for some component partial orders, lexical -- ordering is incompatible with the transitivity axiom we require for the derived partial order (x1, y1) `leq` (x2, y2) = x1 `leq` x2 && y1 `leq` y2 -- | Least point of a partially ordered monotone function. Checks that the function is monotone. lfpFrom :: PartialOrd a => a -> (a -> a) -> a lfpFrom = lfpFrom' leq -- | Least point of a partially ordered monotone function. Does not checks that the function is monotone. unsafeLfpFrom :: Eq a => a -> (a -> a) -> a unsafeLfpFrom = lfpFrom' (\_ _ -> True) {-# INLINE lfpFrom' #-} lfpFrom' :: Eq a => (a -> a -> Bool) -> a -> (a -> a) -> a lfpFrom' check init_x f = go init_x where go x | x' == x = x | x `check` x' = go x' | otherwise = error "lfpFrom: non-monotone function" where x' = f x -- | Greatest fixed point of a partially ordered antinone function. Checks that the function is antinone. {-# INLINE gfpFrom #-} gfpFrom :: PartialOrd a => a -> (a -> a) -> a gfpFrom = gfpFrom' leq -- | Greatest fixed point of a partially ordered antinone function. Does not check that the function is antinone. {-# INLINE unsafeGfpFrom #-} unsafeGfpFrom :: Eq a => a -> (a -> a) -> a unsafeGfpFrom = gfpFrom' (\_ _ -> True) {-# INLINE gfpFrom' #-} gfpFrom' :: Eq a => (a -> a -> Bool) -> a -> (a -> a) -> a gfpFrom' check init_x f = go init_x where go x | x' == x = x | x' `check` x = go x' | otherwise = error "gfpFrom: non-antinone function" where x' = f x
batterseapower/lattices
Algebra/PartialOrd.hs
bsd-3-clause
3,482
0
11
824
1,015
551
464
52
1
{-# LANGUAGE BangPatterns, CPP, GeneralizedNewtypeDeriving, MagicHash, Rank2Types, UnboxedTuples #-} #ifdef GENERICS {-# LANGUAGE DeriveGeneric, ScopedTypeVariables #-} #endif -- | QuickCheck tests for the 'Data.Hashable' module. We test -- functions by comparing the C and Haskell implementations. module Properties (properties) where import Data.Hashable (Hashable, hash, hashByteArray, hashPtr, Hashed, hashed, unhashed, hashWithSalt) import Data.Hashable.Lifted (hashWithSalt1) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.List (nub) import Control.Monad (ap, liftM) import System.IO.Unsafe (unsafePerformIO) import Foreign.Marshal.Array (withArray) import GHC.Base (ByteArray#, Int(..), newByteArray#, unsafeCoerce#, writeWord8Array#) import GHC.ST (ST(..), runST) import GHC.Word (Word8(..)) import Test.QuickCheck hiding ((.&.)) import Test.Framework (Test, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) #ifdef GENERICS import GHC.Generics #endif #if MIN_VERSION_bytestring(0,10,4) import qualified Data.ByteString.Short as BS #endif ------------------------------------------------------------------------ -- * Properties instance Arbitrary T.Text where arbitrary = T.pack `fmap` arbitrary instance Arbitrary TL.Text where arbitrary = TL.pack `fmap` arbitrary instance Arbitrary B.ByteString where arbitrary = B.pack `fmap` arbitrary instance Arbitrary BL.ByteString where arbitrary = sized $ \n -> resize (round (sqrt (toEnum n :: Double))) ((BL.fromChunks . map (B.pack . nonEmpty)) `fmap` arbitrary) where nonEmpty (NonEmpty a) = a #if MIN_VERSION_bytestring(0,10,4) instance Arbitrary BS.ShortByteString where arbitrary = BS.pack `fmap` arbitrary #endif -- | Validate the implementation by comparing the C and Haskell -- versions. pHash :: [Word8] -> Bool pHash xs = unsafePerformIO $ withArray xs $ \ p -> (hashByteArray (fromList xs) 0 len ==) `fmap` hashPtr p len where len = length xs -- | Content equality implies hash equality. pText :: T.Text -> T.Text -> Bool pText a b = if (a == b) then (hash a == hash b) else True -- | Content equality implies hash equality. pTextLazy :: TL.Text -> TL.Text -> Bool pTextLazy a b = if (a == b) then (hash a == hash b) else True -- | A small positive integer. newtype ChunkSize = ChunkSize { unCS :: Int } deriving (Eq, Ord, Num, Integral, Real, Enum) instance Show ChunkSize where show = show . unCS instance Arbitrary ChunkSize where arbitrary = (ChunkSize . (`mod` maxChunkSize)) `fmap` (arbitrary `suchThat` ((/=0) . (`mod` maxChunkSize))) where maxChunkSize = 16 -- | Ensure that the rechunk function causes a rechunked string to -- still match its original form. pTextRechunk :: T.Text -> NonEmptyList ChunkSize -> Bool pTextRechunk t cs = TL.fromStrict t == rechunkText t cs -- | Lazy strings must hash to the same value no matter how they are -- chunked. pTextLazyRechunked :: T.Text -> NonEmptyList ChunkSize -> NonEmptyList ChunkSize -> Bool pTextLazyRechunked t cs0 cs1 = hash (rechunkText t cs0) == hash (rechunkText t cs1) -- | Break up a string into chunks of different sizes. rechunkText :: T.Text -> NonEmptyList ChunkSize -> TL.Text rechunkText t0 (NonEmpty cs0) = TL.fromChunks . go t0 . cycle $ cs0 where go t _ | T.null t = [] go t (c:cs) = a : go b cs where (a,b) = T.splitAt (unCS c) t go _ [] = error "Properties.rechunk - The 'impossible' happened!" #if MIN_VERSION_bytestring(0,10,4) -- | Content equality implies hash equality. pBSShort :: BS.ShortByteString -> BS.ShortByteString -> Bool pBSShort a b = if (a == b) then (hash a == hash b) else True #endif -- | Content equality implies hash equality. pBS :: B.ByteString -> B.ByteString -> Bool pBS a b = if (a == b) then (hash a == hash b) else True -- | Content equality implies hash equality. pBSLazy :: BL.ByteString -> BL.ByteString -> Bool pBSLazy a b = if (a == b) then (hash a == hash b) else True -- | Break up a string into chunks of different sizes. rechunkBS :: B.ByteString -> NonEmptyList ChunkSize -> BL.ByteString rechunkBS t0 (NonEmpty cs0) = BL.fromChunks . go t0 . cycle $ cs0 where go t _ | B.null t = [] go t (c:cs) = a : go b cs where (a,b) = B.splitAt (unCS c) t go _ [] = error "Properties.rechunkBS - The 'impossible' happened!" -- | Ensure that the rechunk function causes a rechunked string to -- still match its original form. pBSRechunk :: B.ByteString -> NonEmptyList ChunkSize -> Bool pBSRechunk t cs = fromStrict t == rechunkBS t cs -- | Lazy bytestrings must hash to the same value no matter how they -- are chunked. pBSLazyRechunked :: B.ByteString -> NonEmptyList ChunkSize -> NonEmptyList ChunkSize -> Bool pBSLazyRechunked t cs1 cs2 = hash (rechunkBS t cs1) == hash (rechunkBS t cs2) -- This wrapper is required by 'runST'. data ByteArray = BA { unBA :: ByteArray# } -- | Create a 'ByteArray#' from a list of 'Word8' values. fromList :: [Word8] -> ByteArray# fromList xs0 = unBA (runST $ ST $ \ s1# -> case newByteArray# len# s1# of (# s2#, marr# #) -> case go s2# 0 marr# xs0 of s3# -> (# s3#, BA (unsafeCoerce# marr#) #)) where !(I# len#) = length xs0 go s# _ _ [] = s# go s# i@(I# i#) marr# ((W8# x):xs) = case writeWord8Array# marr# i# x s# of s2# -> go s2# (i + 1) marr# xs -- Generics #ifdef GENERICS data Product2 a b = Product2 a b deriving (Generic) instance (Arbitrary a, Arbitrary b) => Arbitrary (Product2 a b) where arbitrary = Product2 `liftM` arbitrary `ap` arbitrary instance (Hashable a, Hashable b) => Hashable (Product2 a b) data Product3 a b c = Product3 a b c deriving (Generic) instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (Product3 a b c) where arbitrary = Product3 `liftM` arbitrary `ap` arbitrary `ap` arbitrary instance (Hashable a, Hashable b, Hashable c) => Hashable (Product3 a b c) -- Hashes of all product types of the same shapes should be the same. pProduct2 :: Int -> String -> Bool pProduct2 x y = hash (x, y) == hash (Product2 x y) pProduct3 :: Double -> Maybe Bool -> (Int, String) -> Bool pProduct3 x y z = hash (x, y, z) == hash (Product3 x y z) data Sum2 a b = S2a a | S2b b deriving (Eq, Ord, Show, Generic) instance (Hashable a, Hashable b) => Hashable (Sum2 a b) data Sum3 a b c = S3a a | S3b b | S3c c deriving (Eq, Ord, Show, Generic) instance (Hashable a, Hashable b, Hashable c) => Hashable (Sum3 a b c) -- Hashes of the same parameter, but with different sum constructors, -- should differ. (They might legitimately collide, but that's -- vanishingly unlikely.) pSum2_differ :: Int -> Bool pSum2_differ x = nub hs == hs where hs = [ hash (S2a x :: Sum2 Int Int) , hash (S2b x :: Sum2 Int Int) ] pSum3_differ :: Int -> Bool pSum3_differ x = nub hs == hs where hs = [ hash (S3a x :: Sum3 Int Int Int) , hash (S3b x :: Sum3 Int Int Int) , hash (S3c x :: Sum3 Int Int Int) ] #endif instance (Arbitrary a, Hashable a) => Arbitrary (Hashed a) where arbitrary = fmap hashed arbitrary shrink xs = map hashed $ shrink $ unhashed xs pLiftedHashed :: Int -> Hashed (Either Int String) -> Bool pLiftedHashed s h = hashWithSalt s h == hashWithSalt1 s h properties :: [Test] properties = [ testProperty "bernstein" pHash , testGroup "text" [ testProperty "text/strict" pText , testProperty "text/lazy" pTextLazy , testProperty "text/rechunk" pTextRechunk , testProperty "text/rechunked" pTextLazyRechunked ] , testGroup "bytestring" [ testProperty "bytestring/strict" pBS , testProperty "bytestring/lazy" pBSLazy #if MIN_VERSION_bytestring(0,10,4) , testProperty "bytestring/short" pBSShort #endif , testProperty "bytestring/rechunk" pBSRechunk , testProperty "bytestring/rechunked" pBSLazyRechunked ] #ifdef GENERICS , testGroup "generics" [ -- Note: "product2" and "product3" have been temporarily -- disabled until we have added a 'hash' method to the GHashable -- class. Until then (a,b) hashes to a different value than (a -- :*: b). While this is not incorrect, it would be nicer if -- they didn't. testProperty "product2" pProduct2 , testProperty -- "product3" pProduct3 testProperty "sum2_differ" pSum2_differ , testProperty "sum3_differ" pSum3_differ ] #endif , testGroup "lifted law" [ testProperty "Hashed" pLiftedHashed ] ] ------------------------------------------------------------------------ -- Utilities fromStrict :: B.ByteString -> BL.ByteString #if MIN_VERSION_bytestring(0,10,0) fromStrict = BL.fromStrict #else fromStrict b = BL.fromChunks [b] #endif
pacak/cuddly-bassoon
hashable-1.2.6.0/tests/Properties.hs
bsd-3-clause
9,105
0
18
2,017
2,593
1,411
1,182
106
3
{-# OPTIONS_GHC -Wall -fno-warn-orphans #-} module Language.Haskell.Exts.Desugar.Pattern where import qualified Prelude import Language.Haskell.Exts hiding (name) import Language.Haskell.Exts.Unique import Language.Haskell.Exts.Desugar import Language.Haskell.Exts.Desugar.Basic () import Prelude (($),(++),return,length,foldr,concat) import Control.Applicative ((<$>)) instance Desugar Pat where -- no desugaring desugar (PVar name) = PVar $$ name -- no desugaring desugar (PLit literal) = PLit $$ literal -- no desugaring desugar (PApp qName pats) = PApp $$ qName ** pats -- no desugaring desugar (PAsPat name pat) = PAsPat $$ name ** pat -- no desugaring desugar (PNPlusK name integer) = PNPlusK $$ name ** integer -- no desugaring desugar (PViewPat eexp pat) = PViewPat eexp $$ pat -- no desugaring desugar (PIrrPat pat) = PIrrPat $$ pat -- no desugaring desugar (PBangPat pat) = PBangPat $$ pat -- no desugaring desugar PWildCard = return $ PWildCard -- no desugaring desugar (PRec qName patFields) = PRec $$ qName ** patFields -- no desugaring -- should be removed from HSE -- and replaced with literals desugar (PNeg (PLit (Int x))) = desugar $ PLit (Int (-x)) desugar (PNeg (PLit (Frac y))) = desugar $ PLit (Frac (-y)) desugar (PNeg _other) = error $ "In Patterns, negation can only " ++ "be applied to numeric literals!" -- HSE desugar (PParen pat) = desugar $ pat -- HSE desugar (PInfixApp pat1 qName pat2) = desugar $ PApp qName [pat1,pat2] -- HSE desugar (PTuple []) = desugar $ PApp (Special UnitCon) [] desugar (PTuple [p]) = desugar $ p desugar (PTuple pats) = desugar $ PApp (Special $ TupleCon Boxed $ length pats) pats -- HSE desugar (PList []) = desugar $ PApp (Special ListCon) [] desugar (PList pats) = desugar $ foldr (\p a -> PApp (Special Cons) [p,a]) (PList []) pats -- not supported desugar (PatTypeSig {}) = error "Not supported!" desugar (PExplTypeArg {}) = error "Not supported!" desugar (PQuasiQuote {}) = error "Not supported!" desugar (PRPat {}) = error "Not supported!" desugar (PXTag {}) = error "Not supported!" desugar (PXETag {}) = error "Not supported!" desugar (PXPcdata {}) = error "Not supported!" desugar (PXPatTag {}) = error "Not supported!" desugar (PXRPats {}) = error "Not supported!" instance Desugar PatField where desugar (PFieldPat qName p) = PFieldPat $$ qName ** p desugar (PFieldPun n) = desugar $ PFieldPat (UnQual n) (PVar n) desugar PFieldWildcard = error "PFieldWildcard is not supported!" -- variables / name bound in a pattern patVar :: Pat -> [Name] patVar (PVar name) = [name] patVar (PLit _) = [] patVar (PatTypeSig _ pat _) = patVar pat patVar (PApp _ pats) = concat (patVar <$> pats) patVar (PAsPat name pat) = name : (patVar pat) patVar (PParen pat) = patVar pat patVar (PIrrPat pat) = patVar pat patVar (PBangPat pat) = patVar pat patVar (PNeg _) = [] patVar (PInfixApp pat1 _ pat2) = (patVar pat1) ++ (patVar pat2) patVar (PTuple pats) = concat $ patVar <$> pats patVar (PList pats) = concat $ patVar <$> pats patVar PWildCard = [] patVar (PNPlusK _ _) = [] patVar (PViewPat _ pat) = patVar pat patVar x = Prelude.error $ "Pattern " ++ (prettyPrint x) ++ " is not supported!"
shayan-najd/Haskell-Desugar
Language/Haskell/Exts/Desugar/Pattern.hs
bsd-3-clause
3,786
0
12
1,157
1,246
649
597
84
1
module Text.Tagset.TagParser ( tagParser , parseTag ) where import Text.Parsec import Text.Parsec.Text import qualified Data.Map as Map import Data.Maybe (catMaybes) import qualified Data.Text as T import qualified Data.Text.IO as T import Text.Tagset.Data import Text.Tagset.DefParser (parseTagset) (<<) :: Monad m => m a -> m b -> m a (<<) x y = do {v <- x; y; return v} sepTagParser tagset = tagParser tagset tagParser tagset = choice [ ruleParser tagset rule | rule <- ruleDefs tagset ] ruleParser tagset rule = do xs <- try $ do pos <- let (attr, val) = head $ rulePred rule in valueParser attr val atts <- sequence [ valueParser attr val | (attr, val) <- tail $ rulePred rule ] return $ pos : atts xs' <- fmap catMaybes $ sequence [ withOptionParser optionMaybe optional (attrParser tagset attr) | (attr, optional) <- attsFor rule ] return $ xs ++ xs' withOptionParser optionParser optional p = if not optional then justify p else optionParser p where justify p = do {x <- p; return $ Just x} attrParser tagset attr = choice [ valueParser attr val | val <- attrValues tagset attr ] <?> (attr ++ " value") -- Version with separators valueParser attr val = do try $ string val (char ':' >> return ()) <|> eof return (T.pack attr, T.pack val) parseTag :: Tagset -> String -> T.Text -> Label parseTag tagset src contents = case parse (tagParser tagset) src contents of Left e -> error $ "\nerror in tag parsing:\n" ++ show (T.unpack contents) ++ show e ++ "\n" Right r -> r
kawu/tagger
src/Text/Tagset/TagParser.hs
bsd-3-clause
1,686
0
17
473
618
312
306
50
2
{-# LANGUAGE TypeFamilies #-} module EFA.Flow.Sequence.Symbolic ( module EFA.Flow.Sequence.Symbolic, (.=), (%=), (=%%=), Verify.Ignore, ) where import qualified EFA.Flow.SequenceState.Symbolic as SymVar import EFA.Flow.SequenceState.Symbolic (VarTerm, Symbol, varSymbol) import EFA.Utility (Pointed) import qualified EFA.Flow.Sequence.EquationSystem as EqSys import qualified EFA.Flow.Sequence.Quantity as SeqFlow import qualified EFA.Flow.SequenceState.Variable as Var import qualified EFA.Flow.SequenceState.Index as Idx import EFA.Flow.Sequence.EquationSystem ((.=), (%=), (=%%=)) import qualified EFA.Graph.Topology.Node as Node import qualified EFA.Equation.RecordIndex as RecIdx import qualified EFA.Equation.Record as EqRecord import qualified EFA.Equation.Verify as Verify import qualified UniqueLogic.ST.TF.System as Sys import Data.Monoid ((<>)) type ScalarTerm term recIdx node = SymVar.ScalarTerm term recIdx Idx.Section node type ScalarAtom term recIdx node = SymVar.ScalarAtom term recIdx Idx.Section node type SignalTerm term recIdx node = SymVar.SignalTerm term recIdx Idx.Section node type EquationSystem mode rec node s term = EqSys.EquationSystem mode rec node s (ScalarTerm term (EqRecord.ToIndex rec) node) (SignalTerm term (EqRecord.ToIndex rec) node) given :: (Sys.Value mode t, t ~ VarTerm var term recIdx node, t ~ SeqFlow.Element idx (ScalarTerm term recIdx node) (SignalTerm term recIdx node), EqSys.Record rec, recIdx ~ EqRecord.ToIndex rec, Pointed term, Var.Type idx ~ var, Symbol var, SeqFlow.Lookup idx, Node.C node) => RecIdx.Record recIdx (idx node) -> EquationSystem mode rec node s term given idx = idx .= varSymbol idx infixr 6 =<> (=<>) :: (Sys.Value mode t, t ~ VarTerm var term recIdx node, t ~ SeqFlow.Element idx (ScalarTerm term recIdx node) (SignalTerm term recIdx node), EqSys.Record rec, recIdx ~ EqRecord.ToIndex rec, Pointed term, Var.Type idx ~ var, Symbol var, SeqFlow.Lookup idx, Node.C node) => RecIdx.Record recIdx (idx node) -> EquationSystem mode rec node s term -> EquationSystem mode rec node s term idx =<> eqsys = given idx <> eqsys
energyflowanalysis/efa-2.1
src/EFA/Flow/Sequence/Symbolic.hs
bsd-3-clause
2,230
0
10
408
708
409
299
54
1
module TypeCheck where import Text.Parsec import Control.Monad import AST() import CheckedAST import Environment typeCheck :: CheckedProgram -> Either String () typeCheck = mapM_ eDeclTypeCheck getRetFuncType :: (Kind, ChType, Level) -> Maybe ChType getRetFuncType (_, t, _) = case t of (ChFunc ct _) -> Just ct _ -> Nothing eDeclTypeCheck :: CheckedEDecl -> Either String () eDeclTypeCheck (CheckedDecl _ _) = return () --eDeclTypeCheck (CheckedFuncProt pos info args) = return () eDeclTypeCheck (CheckedFuncDef pos (fname, finfo) _ stmt) = let maybeExpectedRetType = getRetFuncType finfo in do case maybeExpectedRetType of (Just expType) -> let eitherType = stmtTypeCheck (fname, finfo) stmt in do case eitherType of (Left err) -> fail err (Right actType) -> if (expType == actType || fname == "main") then return () else fail $ concat [show pos, " invalid type error: \n Expected:" ,show expType, "\n Actual:", show actType] Nothing -> fail $ concat [show pos, " invalid function return type ", show (getType finfo)] typeMaximum :: [ChType] -> ChType typeMaximum [] = ChVoid typeMaximum [x] = x typeMaximum (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = typeMaximum xs stmtTypeCheck :: Info -> CheckedStmt -> Either String ChType stmtTypeCheck _ (CheckedEmptyStmt) = return ChVoid stmtTypeCheck _ (CheckedExprStmt e) = exprTypeCheck e >> return ChVoid stmtTypeCheck info (CheckedCompoundStmt _ stmts) = do stmtsType <- mapM (stmtTypeCheck info) stmts return $ typeMaximum stmtsType stmtTypeCheck info (CheckedIfStmt pos cond true false) = let eitherExprTy = exprTypeCheck cond in case eitherExprTy of (Left err) -> fail err (Right expTy) -> if (expTy /= ChInt) then fail $ concat [show pos, "invalid expression ", show cond, " - it must be int"] else liftM2 max trueTy falseTy where trueTy = stmtTypeCheck info true falseTy = stmtTypeCheck info false stmtTypeCheck info (CheckedWhileStmt pos cond stmt) = let eitherExprTy = exprTypeCheck cond in case eitherExprTy of (Left err) -> fail err (Right expTy) -> if expTy /= ChInt then fail $ concat [show pos, "invalid expression", show cond, " - it must be int"] else stmtTypeCheck info stmt stmtTypeCheck (_, finfo) (CheckedReturnStmt pos e) = let maybeExpectedRetType = getRetFuncType finfo in do case maybeExpectedRetType of (Just expType) -> do actualType <- exprTypeCheck e if expType == actualType then return actualType else fail $ concat [show pos, "type mismatch \n Expected: ", show expType, "\n Actual: ", show actualType] Nothing -> fail $ concat [show pos, " invalid function return type", show (getType finfo)] exprTypeCheck :: CheckedExpr -> Either String ChType exprTypeCheck (CheckedAssignExpr pos e1 e2) = do checkAssignForm pos e1 ty1 <- exprTypeCheck e1 ty2 <- exprTypeCheck e2 if ty1 == ty2 then return ty1 else fail $ concat [show pos, "type mismatch", show ty1, " and ", show ty2] exprTypeCheck (CheckedOr pos e1 e2) = checkBothInt pos e1 e2 exprTypeCheck (CheckedAnd pos e1 e2) = checkBothInt pos e1 e2 exprTypeCheck (CheckedEqual pos e1 e2) = checkCompare pos e1 e2 exprTypeCheck (CheckedNotEqual pos e1 e2) = checkCompare pos e1 e2 exprTypeCheck (CheckedLt pos e1 e2) = checkCompare pos e1 e2 exprTypeCheck (CheckedGt pos e1 e2) = checkCompare pos e1 e2 exprTypeCheck (CheckedLte pos e1 e2) = checkCompare pos e1 e2 exprTypeCheck (CheckedGte pos e1 e2) = checkCompare pos e1 e2 exprTypeCheck (CheckedPlus pos e1 e2) = checkAddSub pos e1 e2 exprTypeCheck (CheckedMinus pos e1 e2) = checkAddSub pos e1 e2 exprTypeCheck (CheckedMultiple pos e1 e2) = checkBothInt pos e1 e2 exprTypeCheck (CheckedDivide pos e1 e2) = checkBothInt pos e1 e2 exprTypeCheck (CheckedUnaryAddress pos e) = do checkAddressRefer pos e ty <- exprTypeCheck e if ty == ChInt then return $ ChPointer ChInt else fail $ concat [show pos, "invalid operand &: it must be use for int type"] exprTypeCheck (CheckedUnaryPointer pos e) = do ty <- exprTypeCheck e case ty of (ChPointer pty) -> return pty --ChInt -> return ChInt _ -> fail $ concat [show pos, "invalid pointer refer, you cannot refer ", show ty] exprTypeCheck (CheckedCallFunc pos funcInfo args) = do argTypes <- mapM exprTypeCheck args case (snd $ funcInfo) of (Func, ChFunc ty paramTypes, _) -> if argTypes == paramTypes then return ty else fail $ concat [show pos ,"type mismatch in func params\n Expected: " ,show paramTypes, "\n Actual: ", show argTypes] _ -> fail $ concat ["invalid call function: " ,show $ fst funcInfo, " is not function"] exprTypeCheck (CheckedExprList _ exprs) = liftM typeLast (mapM exprTypeCheck exprs) exprTypeCheck (CheckedConstant _ _) = return ChInt exprTypeCheck (CheckedIdentExpr _ (_, info)) = return $ getType info typeLast :: [ChType] -> ChType typeLast [x] = x typeLast (_:xs) = last xs typeLast [] = ChVoid checkBothInt :: SourcePos -> CheckedExpr -> CheckedExpr -> Either String ChType checkBothInt pos e1 e2 = do ty1 <- exprTypeCheck e1 ty2 <- exprTypeCheck e2 if ty1 == ChInt && ty2 == ChInt then return ChInt else fail $ concat [show pos, " type mismatch: both ", show e1, " and ", show e2, " must be int"] checkCompare :: SourcePos -> CheckedExpr -> CheckedExpr -> Either String ChType checkCompare pos e1 e2 = do ty1 <- exprTypeCheck e1 ty2 <- exprTypeCheck e2 if ty1 == ty2 then return ChInt else fail $ concat [show pos, " type mismatch: \n", show e1, ": ", show ty1, "\n", show e2, ": ", show ty2] checkAddSub :: SourcePos -> CheckedExpr -> CheckedExpr -> Either String ChType checkAddSub pos e1 e2 = do ty1 <- exprTypeCheck e1 ty2 <- exprTypeCheck e2 case (ty1, ty2) of (ChInt, ChInt) -> return ChInt (ChPointer ty, ChInt) -> return $ ChPointer ty --(ChInt, ChPointer Chint) -> return $ ChPointer ChInt (ChArray ty _, ChInt) -> return $ ChPointer ty _ -> fail $ concat [show pos, " type mismatch: \n", show e1, ": ", show ty1, "\n", show e2, ": ", show ty2] {- 式の形の検査 -} checkAssignForm :: SourcePos -> CheckedExpr -> Either String () checkAssignForm pos (CheckedIdentExpr _ (name, (kind, ty, _))) = case (kind, ty) of (Var, (ChArray _ _ )) -> fail $ concat [show pos, "invalid assignment to: ", name] (Var, _) -> return () (Func, _) -> fail $ concat [show pos, "invalid assignment to: ", name] (FProt, _) -> fail $ concat [show pos, "invalid assignment to: ", name] (Param, (ChArray _ _ )) -> fail $ concat [show pos, "invalid assignment to: ", name] (Param, _) -> return () checkAssignForm _ (CheckedUnaryPointer _ _) = return () checkAssignForm pos _ = fail $ concat [show pos, " invalid assign form : " ,"dest must be Identifier of Pointer"] checkAddressRefer :: SourcePos -> CheckedExpr -> Either String () checkAddressRefer _ (CheckedIdentExpr _ _) = return () checkAddressRefer _ (CheckedUnaryPointer _ _) = return () checkAddressRefer pos _ = fail $ concat [show pos, "invalid operand &: it must be used for Identifier"]
tanishiking/hscc
src/TypeCheck.hs
mit
8,045
0
23
2,359
2,563
1,284
1,279
151
7
{- DATX02-17-26, automated assessment of imperative programs. - Copyright, 2017, see AUTHORS.md. - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} {-# LANGUAGE TypeFamilies, RankNTypes #-} -- | Product types that provide a Traversal' of indices corresponding -- to the length of the list of components making up the product. module Class.Product.PTravIx ( -- * Classes PTravIx -- * Types , PIndex -- * Primitive operations , pTravIx ) where import Data.Maybe (fromMaybe) import Data.List (uncons) import Control.Lens (Traversal', Traversal) import Class.Product.Uncons import Class.Product.Flatten -------------------------------------------------------------------------------- -- Class: -------------------------------------------------------------------------------- -- | Product types that provide a Traversal' of indices corresponding -- to the length of the list of components making up the product. class PTravIx p where -- | The indices type. type PIndex p i :: * -- | Provides the Traversal'. pTravIx :: [i] -> Traversal' p (PIndex p i) -------------------------------------------------------------------------------- -- Instances: -------------------------------------------------------------------------------- -- | Helper for making instances. inst :: Maybe t -> Traversal s s t b inst mit = fromMaybe (const pure) $ do it <- mit pure $ \f x -> const x <$> f it mkinst :: (UnconsL h e, HFlatten h t, Applicative f) => [e] -> (t -> f b) -> s -> f s mkinst = inst . fmap fst . unconsF instance PTravIx (x0, x1) where type PIndex (x0, x1) i = F2 i pTravIx is0 = inst $ fst <$> unconsL is0 instance PTravIx (x0, x1, x2) where type PIndex (x0, x1, x2) i = F3 i pTravIx = mkinst instance PTravIx (x0, x1, x2, x3) where type PIndex (x0, x1, x2, x3) i = F4 i pTravIx = mkinst instance PTravIx (x0, x1, x2, x3, x4) where type PIndex (x0, x1, x2, x3, x4) i = F5 i pTravIx = mkinst instance PTravIx (x0, x1, x2, x3, x4, x5) where type PIndex (x0, x1, x2, x3, x4, x5) i = F6 i pTravIx = mkinst instance PTravIx (x0, x1, x2, x3, x4, x5, x6) where type PIndex (x0, x1, x2, x3, x4, x5, x6) i = F7 i pTravIx = mkinst instance PTravIx (x0, x1, x2, x3, x4, x5, x6, x7) where type PIndex (x0, x1, x2, x3, x4, x5, x6, x7) i = F8 i pTravIx = mkinst instance PTravIx (x0, x1, x2, x3, x4, x5, x6, x7, x8) where type PIndex (x0, x1, x2, x3, x4, x5, x6, x7, x8) i = F9 i pTravIx = mkinst instance PTravIx (x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) where type PIndex (x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) i = F10 i pTravIx = mkinst
DATX02-17-26/DATX02-17-26
libsrc/Class/Product/PTravIx.hs
gpl-2.0
3,312
0
11
687
851
501
350
47
1
{-# LANGUAGE GADTs #-} module DeepGADT where import Prelude hiding ((+),(-)) import qualified Prelude as Prelude import qualified Data.Vector.Unboxed as V import Types import qualified ShallowVector as Shallow -- evaluation with the host language data Exp a where Img :: VectorImage -> Exp VectorImage I :: Int -> Exp Int BrightenBy :: Exp Int -> Exp VectorImage -> Exp VectorImage DarkenBy :: Exp Int -> Exp VectorImage -> Exp VectorImage BlurX :: Exp VectorImage -> Exp VectorImage BlurY :: Exp VectorImage -> Exp VectorImage integer = I image = Img (+) = BrightenBy (-) = DarkenBy blurX = BlurX blurY = BlurY -- | interpret optimised AST eval :: Exp a -> a eval (I i) = i eval (Img img) = img eval (BrightenBy i exp) = Shallow.brightenBy (eval i) (eval exp) eval (DarkenBy i exp) = Shallow.darkenBy (eval i) (eval exp) eval (BlurX exp) = Shallow.blurX (eval exp) eval (BlurY exp) = Shallow.blurY (eval exp) run :: Exp a -> a run ast = eval (optimiseAST ast) -- | AST optimiser contains 2 optimisations: -- (brighten n . darken n) = id -- (darken n . brighten n) = id -- -- this simple optimiser traverses from the -- outer most constructor, inwards. optimiseAST :: Exp a -> Exp a optimiseAST (BrightenBy (I i) (DarkenBy (I j) subExp)) | i == j = optimiseAST subExp -- eliminate (brighten n . darken n) | otherwise = BrightenBy (I i) (DarkenBy (I j) (optimiseAST subExp)) optimiseAST exp@(DarkenBy (I i) (BrightenBy (I j) subExp)) | i == j = optimiseAST subExp -- eliminate (darken n . brighten n) | otherwise = DarkenBy (I i) (BrightenBy (I j) (optimiseAST subExp)) optimiseAST (BrightenBy i exp) = (BrightenBy i (optimiseAST exp)) optimiseAST (DarkenBy i exp) = (DarkenBy i (optimiseAST exp)) optimiseAST (BlurX exp) = BlurX (optimiseAST exp) optimiseAST (BlurY exp) = BlurY (optimiseAST exp) optimiseAST exp@Img{} = exp optimiseAST exp@I{} = exp
robstewart57/small-image-processing-dsl-implementations
haskell/small-image-processing-dsl/src/DeepGADT.hs
bsd-3-clause
2,009
0
12
476
713
370
343
42
1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Dependency.Types -- Copyright : (c) Duncan Coutts 2008 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Common types for dependency resolution. ----------------------------------------------------------------------------- module Distribution.Client.Dependency.TopDown ( topDownResolver ) where import Distribution.Client.Dependency.TopDown.Types import qualified Distribution.Client.Dependency.TopDown.Constraints as Constraints import Distribution.Client.Dependency.TopDown.Constraints ( Satisfiable(..) ) import Distribution.Client.IndexUtils ( convert ) import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Client.InstallPlan ( PlanPackage(..) ) import Distribution.Client.Types ( SourcePackage(..), ConfiguredPackage(..), InstalledPackage(..) , enableStanzas, ConfiguredId(..), fakeInstalledPackageId ) import Distribution.Client.Dependency.Types ( DependencyResolver, PackageConstraint(..) , PackagePreferences(..), InstalledPreference(..) , Progress(..), foldProgress ) import qualified Distribution.Client.PackageIndex as PackageIndex import Distribution.Client.PackageIndex ( PackageIndex ) import Distribution.Package ( PackageName(..), PackageId, Package(..), packageVersion, packageName , Dependency(Dependency), thisPackageVersion , simplifyDependency ) import Distribution.PackageDescription ( PackageDescription(buildDepends) ) import Distribution.Client.PackageUtils ( externalBuildDepends ) import Distribution.PackageDescription.Configuration ( finalizePackageDescription, flattenPackageDescription ) import Distribution.Version ( VersionRange, withinRange, simplifyVersionRange , UpperBound(..), asVersionIntervals ) import Distribution.Compiler ( CompilerInfo ) import Distribution.System ( Platform ) import Distribution.Simple.Utils ( equating, comparing ) import Distribution.Text ( display ) import Data.List ( foldl', maximumBy, minimumBy, nub, sort, sortBy, groupBy ) import Data.Maybe ( fromJust, fromMaybe, catMaybes ) #if !MIN_VERSION_base(4,8,0) import Data.Monoid ( Monoid(mempty) ) #endif import Control.Monad ( guard ) import qualified Data.Set as Set import Data.Set (Set) import qualified Data.Map as Map import qualified Data.Graph as Graph import qualified Data.Array as Array import Control.Exception ( assert ) -- ------------------------------------------------------------ -- * Search state types -- ------------------------------------------------------------ type Constraints = Constraints.Constraints InstalledPackageEx UnconfiguredPackage ExclusionReason type SelectedPackages = PackageIndex SelectedPackage -- ------------------------------------------------------------ -- * The search tree type -- ------------------------------------------------------------ data SearchSpace inherited pkg = ChoiceNode inherited [[(pkg, SearchSpace inherited pkg)]] | Failure Failure -- ------------------------------------------------------------ -- * Traverse a search tree -- ------------------------------------------------------------ explore :: (PackageName -> PackagePreferences) -> SearchSpace (SelectedPackages, Constraints, SelectionChanges) SelectablePackage -> Progress Log Failure (SelectedPackages, Constraints) explore _ (Failure failure) = Fail failure explore _ (ChoiceNode (s,c,_) []) = Done (s,c) explore pref (ChoiceNode _ choices) = case [ choice | [choice] <- choices ] of ((_, node'):_) -> Step (logInfo node') (explore pref node') [] -> Step (logInfo node') (explore pref node') where choice = minimumBy (comparing topSortNumber) choices pkgname = packageName . fst . head $ choice (_, node') = maximumBy (bestByPref pkgname) choice where topSortNumber choice = case fst (head choice) of InstalledOnly (InstalledPackageEx _ i _) -> i SourceOnly (UnconfiguredPackage _ i _ _) -> i InstalledAndSource _ (UnconfiguredPackage _ i _ _) -> i bestByPref pkgname = case packageInstalledPreference of PreferLatest -> comparing (\(p,_) -> ( isPreferred p, packageId p)) PreferInstalled -> comparing (\(p,_) -> (isInstalled p, isPreferred p, packageId p)) where isInstalled (SourceOnly _) = False isInstalled _ = True isPreferred p = packageVersion p `withinRange` preferredVersions (PackagePreferences preferredVersions packageInstalledPreference) = pref pkgname logInfo node = Select selected discarded where (selected, discarded) = case node of Failure _ -> ([], []) ChoiceNode (_,_,changes) _ -> changes -- ------------------------------------------------------------ -- * Generate a search tree -- ------------------------------------------------------------ type ConfigurePackage = PackageIndex SelectablePackage -> SelectablePackage -> Either [Dependency] SelectedPackage -- | (packages selected, packages discarded) type SelectionChanges = ([SelectedPackage], [PackageId]) searchSpace :: ConfigurePackage -> Constraints -> SelectedPackages -> SelectionChanges -> Set PackageName -> SearchSpace (SelectedPackages, Constraints, SelectionChanges) SelectablePackage searchSpace configure constraints selected changes next = assert (Set.null (selectedSet `Set.intersection` next)) $ assert (selectedSet `Set.isSubsetOf` Constraints.packages constraints) $ assert (next `Set.isSubsetOf` Constraints.packages constraints) $ ChoiceNode (selected, constraints, changes) [ [ (pkg, select name pkg) | pkg <- PackageIndex.lookupPackageName available name ] | name <- Set.elems next ] where available = Constraints.choices constraints selectedSet = Set.fromList (map packageName (PackageIndex.allPackages selected)) select name pkg = case configure available pkg of Left missing -> Failure $ ConfigureFailed pkg [ (dep, Constraints.conflicting constraints dep) | dep <- missing ] Right pkg' -> case constrainDeps pkg' newDeps (addDeps constraints newPkgs) [] of Left failure -> Failure failure Right (constraints', newDiscarded) -> searchSpace configure constraints' selected' (newSelected, newDiscarded) next' where selected' = foldl' (flip PackageIndex.insert) selected newSelected newSelected = case Constraints.isPaired constraints (packageId pkg) of Nothing -> [pkg'] Just pkgid' -> [pkg', pkg''] where Just pkg'' = fmap (\(InstalledOnly p) -> InstalledOnly p) (PackageIndex.lookupPackageId available pkgid') newPkgs = [ name' | (Dependency name' _, _) <- newDeps , null (PackageIndex.lookupPackageName selected' name') ] newDeps = concatMap packageConstraints newSelected next' = Set.delete name $ foldl' (flip Set.insert) next newPkgs packageConstraints :: SelectedPackage -> [(Dependency, Bool)] packageConstraints = either installedConstraints availableConstraints . preferSource where preferSource (InstalledOnly pkg) = Left pkg preferSource (SourceOnly pkg) = Right pkg preferSource (InstalledAndSource _ pkg) = Right pkg installedConstraints (InstalledPackageEx _ _ deps) = [ (thisPackageVersion dep, True) | dep <- deps ] availableConstraints (SemiConfiguredPackage _ _ _ deps) = [ (dep, False) | dep <- deps ] addDeps :: Constraints -> [PackageName] -> Constraints addDeps = foldr $ \pkgname cs -> case Constraints.addTarget pkgname cs of Satisfiable cs' () -> cs' _ -> impossible "addDeps unsatisfiable" constrainDeps :: SelectedPackage -> [(Dependency, Bool)] -> Constraints -> [PackageId] -> Either Failure (Constraints, [PackageId]) constrainDeps pkg [] cs discard = case addPackageSelectConstraint (packageId pkg) cs of Satisfiable cs' discard' -> Right (cs', discard' ++ discard) _ -> impossible "constrainDeps unsatisfiable(1)" constrainDeps pkg ((dep, installedConstraint):deps) cs discard = case addPackageDependencyConstraint (packageId pkg) dep installedConstraint cs of Satisfiable cs' discard' -> constrainDeps pkg deps cs' (discard' ++ discard) Unsatisfiable -> impossible "constrainDeps unsatisfiable(2)" ConflictsWith conflicts -> Left (DependencyConflict pkg dep installedConstraint conflicts) -- ------------------------------------------------------------ -- * The main algorithm -- ------------------------------------------------------------ search :: ConfigurePackage -> (PackageName -> PackagePreferences) -> Constraints -> Set PackageName -> Progress Log Failure (SelectedPackages, Constraints) search configure pref constraints = explore pref . searchSpace configure constraints mempty ([], []) -- ------------------------------------------------------------ -- * The top level resolver -- ------------------------------------------------------------ -- | The main exported resolver, with string logging and failure types to fit -- the standard 'DependencyResolver' interface. -- topDownResolver :: DependencyResolver topDownResolver platform cinfo installedPkgIndex sourcePkgIndex preferences constraints targets = mapMessages (topDownResolver' platform cinfo (convert installedPkgIndex) sourcePkgIndex preferences constraints targets) where mapMessages :: Progress Log Failure a -> Progress String String a mapMessages = foldProgress (Step . showLog) (Fail . showFailure) Done -- | The native resolver with detailed structured logging and failure types. -- topDownResolver' :: Platform -> CompilerInfo -> PackageIndex InstalledPackage -> PackageIndex SourcePackage -> (PackageName -> PackagePreferences) -> [PackageConstraint] -> [PackageName] -> Progress Log Failure [PlanPackage] topDownResolver' platform cinfo installedPkgIndex sourcePkgIndex preferences constraints targets = fmap (uncurry finalise) . (\cs -> search configure preferences cs initialPkgNames) =<< pruneBottomUp platform cinfo =<< addTopLevelConstraints constraints =<< addTopLevelTargets targets emptyConstraintSet where configure = configurePackage platform cinfo emptyConstraintSet :: Constraints emptyConstraintSet = Constraints.empty (annotateInstalledPackages topSortNumber installedPkgIndex') (annotateSourcePackages constraints topSortNumber sourcePkgIndex') (installedPkgIndex', sourcePkgIndex') = selectNeededSubset installedPkgIndex sourcePkgIndex initialPkgNames topSortNumber = topologicalSortNumbering installedPkgIndex' sourcePkgIndex' initialPkgNames = Set.fromList targets finalise selected' constraints' = PackageIndex.allPackages . fst . improvePlan installedPkgIndex' constraints' . PackageIndex.fromList $ finaliseSelectedPackages preferences selected' constraints' addTopLevelTargets :: [PackageName] -> Constraints -> Progress a Failure Constraints addTopLevelTargets [] cs = Done cs addTopLevelTargets (pkg:pkgs) cs = case Constraints.addTarget pkg cs of Satisfiable cs' () -> addTopLevelTargets pkgs cs' Unsatisfiable -> Fail (NoSuchPackage pkg) ConflictsWith _conflicts -> impossible "addTopLevelTargets conflicts" addTopLevelConstraints :: [PackageConstraint] -> Constraints -> Progress Log Failure Constraints addTopLevelConstraints [] cs = Done cs addTopLevelConstraints (PackageConstraintFlags _ _ :deps) cs = addTopLevelConstraints deps cs addTopLevelConstraints (PackageConstraintVersion pkg ver:deps) cs = case addTopLevelVersionConstraint pkg ver cs of Satisfiable cs' pkgids -> Step (AppliedVersionConstraint pkg ver pkgids) (addTopLevelConstraints deps cs') Unsatisfiable -> Fail (TopLevelVersionConstraintUnsatisfiable pkg ver) ConflictsWith conflicts -> Fail (TopLevelVersionConstraintConflict pkg ver conflicts) addTopLevelConstraints (PackageConstraintInstalled pkg:deps) cs = case addTopLevelInstalledConstraint pkg cs of Satisfiable cs' pkgids -> Step (AppliedInstalledConstraint pkg InstalledConstraint pkgids) (addTopLevelConstraints deps cs') Unsatisfiable -> Fail (TopLevelInstallConstraintUnsatisfiable pkg InstalledConstraint) ConflictsWith conflicts -> Fail (TopLevelInstallConstraintConflict pkg InstalledConstraint conflicts) addTopLevelConstraints (PackageConstraintSource pkg:deps) cs = case addTopLevelSourceConstraint pkg cs of Satisfiable cs' pkgids -> Step (AppliedInstalledConstraint pkg SourceConstraint pkgids) (addTopLevelConstraints deps cs') Unsatisfiable -> Fail (TopLevelInstallConstraintUnsatisfiable pkg SourceConstraint) ConflictsWith conflicts -> Fail (TopLevelInstallConstraintConflict pkg SourceConstraint conflicts) addTopLevelConstraints (PackageConstraintStanzas _ _ : deps) cs = addTopLevelConstraints deps cs -- | Add exclusion on available packages that cannot be configured. -- pruneBottomUp :: Platform -> CompilerInfo -> Constraints -> Progress Log Failure Constraints pruneBottomUp platform comp constraints = foldr prune Done (initialPackages constraints) constraints where prune pkgs rest cs = foldr addExcludeConstraint rest unconfigurable cs where unconfigurable = [ (pkg, missing) -- if necessary we could look up missing reasons | (Just pkg', pkg) <- zip (map getSourcePkg pkgs) pkgs , Left missing <- [configure cs pkg'] ] addExcludeConstraint (pkg, missing) rest cs = let reason = ExcludedByConfigureFail missing in case addPackageExcludeConstraint (packageId pkg) reason cs of Satisfiable cs' [pkgid]| packageId pkg == pkgid -> Step (ExcludeUnconfigurable pkgid) (rest cs') Satisfiable _ _ -> impossible "pruneBottomUp satisfiable" _ -> Fail $ ConfigureFailed pkg [ (dep, Constraints.conflicting cs dep) | dep <- missing ] configure cs (UnconfiguredPackage (SourcePackage _ pkg _ _) _ flags stanzas) = finalizePackageDescription flags (dependencySatisfiable cs) platform comp [] (enableStanzas stanzas pkg) dependencySatisfiable cs = not . null . PackageIndex.lookupDependency (Constraints.choices cs) -- collect each group of packages (by name) in reverse topsort order initialPackages = reverse . sortBy (comparing (topSortNumber . head)) . PackageIndex.allPackagesByName . Constraints.choices topSortNumber (InstalledOnly (InstalledPackageEx _ i _)) = i topSortNumber (SourceOnly (UnconfiguredPackage _ i _ _)) = i topSortNumber (InstalledAndSource _ (UnconfiguredPackage _ i _ _)) = i getSourcePkg (InstalledOnly _ ) = Nothing getSourcePkg (SourceOnly spkg) = Just spkg getSourcePkg (InstalledAndSource _ spkg) = Just spkg configurePackage :: Platform -> CompilerInfo -> ConfigurePackage configurePackage platform cinfo available spkg = case spkg of InstalledOnly ipkg -> Right (InstalledOnly ipkg) SourceOnly apkg -> fmap SourceOnly (configure apkg) InstalledAndSource ipkg apkg -> fmap (InstalledAndSource ipkg) (configure apkg) where configure (UnconfiguredPackage apkg@(SourcePackage _ p _ _) _ flags stanzas) = case finalizePackageDescription flags dependencySatisfiable platform cinfo [] (enableStanzas stanzas p) of Left missing -> Left missing Right (pkg, flags') -> Right $ SemiConfiguredPackage apkg flags' stanzas (externalBuildDepends pkg) dependencySatisfiable = not . null . PackageIndex.lookupDependency available -- | Annotate each installed packages with its set of transitive dependencies -- and its topological sort number. -- annotateInstalledPackages :: (PackageName -> TopologicalSortNumber) -> PackageIndex InstalledPackage -> PackageIndex InstalledPackageEx annotateInstalledPackages dfsNumber installed = PackageIndex.fromList [ InstalledPackageEx pkg (dfsNumber (packageName pkg)) (transitiveDepends pkg) | pkg <- PackageIndex.allPackages installed ] where transitiveDepends :: InstalledPackage -> [PackageId] transitiveDepends = map (packageId . toPkg) . tail . Graph.reachable graph . fromJust . toVertex . packageId (graph, toPkg, toVertex) = dependencyGraph installed -- | Annotate each available packages with its topological sort number and any -- user-supplied partial flag assignment. -- annotateSourcePackages :: [PackageConstraint] -> (PackageName -> TopologicalSortNumber) -> PackageIndex SourcePackage -> PackageIndex UnconfiguredPackage annotateSourcePackages constraints dfsNumber sourcePkgIndex = PackageIndex.fromList [ UnconfiguredPackage pkg (dfsNumber name) (flagsFor name) (stanzasFor name) | pkg <- PackageIndex.allPackages sourcePkgIndex , let name = packageName pkg ] where flagsFor = fromMaybe [] . flip Map.lookup flagsMap flagsMap = Map.fromList [ (name, flags) | PackageConstraintFlags name flags <- constraints ] stanzasFor = fromMaybe [] . flip Map.lookup stanzasMap stanzasMap = Map.fromListWith (++) [ (name, stanzas) | PackageConstraintStanzas name stanzas <- constraints ] -- | One of the heuristics we use when guessing which path to take in the -- search space is an ordering on the choices we make. It's generally better -- to make decisions about packages higer in the dep graph first since they -- place constraints on packages lower in the dep graph. -- -- To pick them in that order we annotate each package with its topological -- sort number. So if package A depends on package B then package A will have -- a lower topological sort number than B and we'll make a choice about which -- version of A to pick before we make a choice about B (unless there is only -- one possible choice for B in which case we pick that immediately). -- -- To construct these topological sort numbers we combine and flatten the -- installed and source package sets. We consider only dependencies between -- named packages, not including versions and for not-yet-configured packages -- we look at all the possible dependencies, not just those under any single -- flag assignment. This means we can actually get impossible combinations of -- edges and even cycles, but that doesn't really matter here, it's only a -- heuristic. -- topologicalSortNumbering :: PackageIndex InstalledPackage -> PackageIndex SourcePackage -> (PackageName -> TopologicalSortNumber) topologicalSortNumbering installedPkgIndex sourcePkgIndex = \pkgname -> let Just vertex = toVertex pkgname in topologicalSortNumbers Array.! vertex where topologicalSortNumbers = Array.array (Array.bounds graph) (zip (Graph.topSort graph) [0..]) (graph, _, toVertex) = Graph.graphFromEdges $ [ ((), packageName pkg, nub deps) | pkgs@(pkg:_) <- PackageIndex.allPackagesByName installedPkgIndex , let deps = [ packageName dep | pkg' <- pkgs , dep <- sourceDeps pkg' ] ] ++ [ ((), packageName pkg, nub deps) | pkgs@(pkg:_) <- PackageIndex.allPackagesByName sourcePkgIndex , let deps = [ depName | SourcePackage _ pkg' _ _ <- pkgs , Dependency depName _ <- buildDepends (flattenPackageDescription pkg') ] ] -- | We don't need the entire index (which is rather large and costly if we -- force it by examining the whole thing). So trace out the maximul subset of -- each index that we could possibly ever need. Do this by flattening packages -- and looking at the names of all possible dependencies. -- selectNeededSubset :: PackageIndex InstalledPackage -> PackageIndex SourcePackage -> Set PackageName -> (PackageIndex InstalledPackage ,PackageIndex SourcePackage) selectNeededSubset installedPkgIndex sourcePkgIndex = select mempty mempty where select :: PackageIndex InstalledPackage -> PackageIndex SourcePackage -> Set PackageName -> (PackageIndex InstalledPackage ,PackageIndex SourcePackage) select installedPkgIndex' sourcePkgIndex' remaining | Set.null remaining = (installedPkgIndex', sourcePkgIndex') | otherwise = select installedPkgIndex'' sourcePkgIndex'' remaining'' where (next, remaining') = Set.deleteFindMin remaining moreInstalled = PackageIndex.lookupPackageName installedPkgIndex next moreSource = PackageIndex.lookupPackageName sourcePkgIndex next moreRemaining = -- we filter out packages already included in the indexes -- this avoids an infinite loop if a package depends on itself -- like base-3.0.3.0 with base-4.0.0.0 filter notAlreadyIncluded $ [ packageName dep | pkg <- moreInstalled , dep <- sourceDeps pkg ] ++ [ name | SourcePackage _ pkg _ _ <- moreSource , Dependency name _ <- buildDepends (flattenPackageDescription pkg) ] installedPkgIndex'' = foldl' (flip PackageIndex.insert) installedPkgIndex' moreInstalled sourcePkgIndex'' = foldl' (flip PackageIndex.insert) sourcePkgIndex' moreSource remaining'' = foldl' (flip Set.insert) remaining' moreRemaining notAlreadyIncluded name = null (PackageIndex.lookupPackageName installedPkgIndex' name) && null (PackageIndex.lookupPackageName sourcePkgIndex' name) -- ------------------------------------------------------------ -- * Post processing the solution -- ------------------------------------------------------------ finaliseSelectedPackages :: (PackageName -> PackagePreferences) -> SelectedPackages -> Constraints -> [PlanPackage] finaliseSelectedPackages pref selected constraints = map finaliseSelected (PackageIndex.allPackages selected) where remainingChoices = Constraints.choices constraints finaliseSelected (InstalledOnly ipkg ) = finaliseInstalled ipkg finaliseSelected (SourceOnly apkg) = finaliseSource Nothing apkg finaliseSelected (InstalledAndSource ipkg apkg) = case PackageIndex.lookupPackageId remainingChoices (packageId ipkg) of --picked package not in constraints Nothing -> impossible "finaliseSelected no pkg" -- to constrain to avail only: Just (SourceOnly _) -> impossible "finaliseSelected src only" Just (InstalledOnly _) -> finaliseInstalled ipkg Just (InstalledAndSource _ _) -> finaliseSource (Just ipkg) apkg finaliseInstalled (InstalledPackageEx pkg _ _) = InstallPlan.PreExisting pkg finaliseSource mipkg (SemiConfiguredPackage pkg flags stanzas deps) = InstallPlan.Configured (ConfiguredPackage pkg flags stanzas deps') where deps' = map (confId . pickRemaining mipkg) deps -- InstalledOrSource indicates that we either have a source package -- available, or an installed one, or both. In the case that we have both -- available, we don't yet know if we can pick the installed one (the -- dependencies may not match up, for instance); this is verified in -- `improvePlan`. -- -- This means that at this point we cannot construct a valid installed -- package ID yet for the dependencies. We therefore have two options: -- -- * We could leave the installed package ID undefined here, and have a -- separate pass over the output of the top-down solver, fixing all -- dependencies so that if we depend on an already installed package we -- use the proper installed package ID. -- -- * We can _always_ use fake installed IDs, irrespective of whether we the -- dependency is on an already installed package or not. This is okay -- because (i) the top-down solver does not (and never will) support -- multiple package instances, and (ii) we initialize the FakeMap with -- fake IDs for already installed packages. -- -- For now we use the second option; if however we change the implementation -- of these fake IDs so that we do away with the FakeMap and update a -- package reverse dependencies as we execute the install plan and discover -- real package IDs, then this is no longer possible and we have to -- implement the first option (see also Note [FakeMap] in Cabal). confId :: InstalledOrSource InstalledPackageEx UnconfiguredPackage -> ConfiguredId confId pkg = ConfiguredId { confSrcId = packageId pkg , confInstId = fakeInstalledPackageId (packageId pkg) } pickRemaining mipkg dep@(Dependency _name versionRange) = case PackageIndex.lookupDependency remainingChoices dep of [] -> impossible "pickRemaining no pkg" [pkg'] -> pkg' remaining -> assert (checkIsPaired remaining) $ maximumBy bestByPref remaining where -- We order candidate packages to pick for a dependency by these -- three factors. The last factor is just highest version wins. bestByPref = comparing (\p -> (isCurrent p, isPreferred p, packageVersion p)) -- Is the package already used by the installed version of this -- package? If so we should pick that first. This stops us from doing -- silly things like deciding to rebuild haskell98 against base 3. isCurrent = case mipkg :: Maybe InstalledPackageEx of Nothing -> \_ -> False Just ipkg -> \p -> packageId p `elem` sourceDeps ipkg -- If there is no upper bound on the version range then we apply a -- preferred version according to the hackage or user's suggested -- version constraints. TODO: distinguish hacks from prefs bounded = boundedAbove versionRange isPreferred p | bounded = True -- any constant will do | otherwise = packageVersion p `withinRange` preferredVersions where (PackagePreferences preferredVersions _) = pref (packageName p) boundedAbove :: VersionRange -> Bool boundedAbove vr = case asVersionIntervals vr of [] -> True -- this is the inconsistent version range. intervals -> case last intervals of (_, UpperBound _ _) -> True (_, NoUpperBound ) -> False -- We really only expect to find more than one choice remaining when -- we're finalising a dependency on a paired package. checkIsPaired [p1, p2] = case Constraints.isPaired constraints (packageId p1) of Just p2' -> packageId p2' == packageId p2 Nothing -> False checkIsPaired _ = False -- | Improve an existing installation plan by, where possible, swapping -- packages we plan to install with ones that are already installed. -- This may add additional constraints due to the dependencies of installed -- packages on other installed packages. -- improvePlan :: PackageIndex InstalledPackage -> Constraints -> PackageIndex PlanPackage -> (PackageIndex PlanPackage, Constraints) improvePlan installed constraints0 selected0 = foldl' improve (selected0, constraints0) (reverseTopologicalOrder selected0) where improve (selected, constraints) = fromMaybe (selected, constraints) . improvePkg selected constraints -- The idea is to improve the plan by swapping a configured package for -- an equivalent installed one. For a particular package the condition is -- that the package be in a configured state, that a the same version be -- already installed with the exact same dependencies and all the packages -- in the plan that it depends on are in the installed state improvePkg selected constraints pkgid = do Configured pkg <- PackageIndex.lookupPackageId selected pkgid ipkg <- PackageIndex.lookupPackageId installed pkgid guard $ all (isInstalled selected) (sourceDeps pkg) tryInstalled selected constraints [ipkg] isInstalled selected pkgid = case PackageIndex.lookupPackageId selected pkgid of Just (PreExisting _) -> True _ -> False tryInstalled :: PackageIndex PlanPackage -> Constraints -> [InstalledPackage] -> Maybe (PackageIndex PlanPackage, Constraints) tryInstalled selected constraints [] = Just (selected, constraints) tryInstalled selected constraints (pkg:pkgs) = case constraintsOk (packageId pkg) (sourceDeps pkg) constraints of Nothing -> Nothing Just constraints' -> tryInstalled selected' constraints' pkgs' where selected' = PackageIndex.insert (PreExisting pkg) selected pkgs' = catMaybes (map notSelected (sourceDeps pkg)) ++ pkgs notSelected pkgid = case (PackageIndex.lookupPackageId installed pkgid ,PackageIndex.lookupPackageId selected pkgid) of (Just pkg', Nothing) -> Just pkg' _ -> Nothing constraintsOk _ [] constraints = Just constraints constraintsOk pkgid (pkgid':pkgids) constraints = case addPackageDependencyConstraint pkgid dep True constraints of Satisfiable constraints' _ -> constraintsOk pkgid pkgids constraints' _ -> Nothing where dep = thisPackageVersion pkgid' reverseTopologicalOrder :: PackageIndex PlanPackage -> [PackageId] reverseTopologicalOrder index = map (packageId . toPkg) . Graph.topSort . Graph.transposeG $ graph where (graph, toPkg, _) = dependencyGraph index -- ------------------------------------------------------------ -- * Adding and recording constraints -- ------------------------------------------------------------ addPackageSelectConstraint :: PackageId -> Constraints -> Satisfiable Constraints [PackageId] ExclusionReason addPackageSelectConstraint pkgid = Constraints.constrain pkgname constraint reason where pkgname = packageName pkgid constraint ver _ = ver == packageVersion pkgid reason = SelectedOther pkgid addPackageExcludeConstraint :: PackageId -> ExclusionReason -> Constraints -> Satisfiable Constraints [PackageId] ExclusionReason addPackageExcludeConstraint pkgid reason = Constraints.constrain pkgname constraint reason where pkgname = packageName pkgid constraint ver installed | ver == packageVersion pkgid = installed | otherwise = True addPackageDependencyConstraint :: PackageId -> Dependency -> Bool -> Constraints -> Satisfiable Constraints [PackageId] ExclusionReason addPackageDependencyConstraint pkgid dep@(Dependency pkgname verrange) installedConstraint = Constraints.constrain pkgname constraint reason where constraint ver installed = ver `withinRange` verrange && if installedConstraint then installed else True reason = ExcludedByPackageDependency pkgid dep installedConstraint addTopLevelVersionConstraint :: PackageName -> VersionRange -> Constraints -> Satisfiable Constraints [PackageId] ExclusionReason addTopLevelVersionConstraint pkgname verrange = Constraints.constrain pkgname constraint reason where constraint ver _installed = ver `withinRange` verrange reason = ExcludedByTopLevelConstraintVersion pkgname verrange addTopLevelInstalledConstraint, addTopLevelSourceConstraint :: PackageName -> Constraints -> Satisfiable Constraints [PackageId] ExclusionReason addTopLevelInstalledConstraint pkgname = Constraints.constrain pkgname constraint reason where constraint _ver installed = installed reason = ExcludedByTopLevelConstraintInstalled pkgname addTopLevelSourceConstraint pkgname = Constraints.constrain pkgname constraint reason where constraint _ver installed = not installed reason = ExcludedByTopLevelConstraintSource pkgname -- ------------------------------------------------------------ -- * Reasons for constraints -- ------------------------------------------------------------ -- | For every constraint we record we also record the reason that constraint -- is needed. So if we end up failing due to conflicting constraints then we -- can give an explnanation as to what was conflicting and why. -- data ExclusionReason = -- | We selected this other version of the package. That means we exclude -- all the other versions. SelectedOther PackageId -- | We excluded this version of the package because it failed to -- configure probably because of unsatisfiable deps. | ExcludedByConfigureFail [Dependency] -- | We excluded this version of the package because another package that -- we selected imposed a dependency which this package did not satisfy. | ExcludedByPackageDependency PackageId Dependency Bool -- | We excluded this version of the package because it did not satisfy -- a dependency given as an original top level input. -- | ExcludedByTopLevelConstraintVersion PackageName VersionRange | ExcludedByTopLevelConstraintInstalled PackageName | ExcludedByTopLevelConstraintSource PackageName deriving Eq -- | Given an excluded package and the reason it was excluded, produce a human -- readable explanation. -- showExclusionReason :: PackageId -> ExclusionReason -> String showExclusionReason pkgid (SelectedOther pkgid') = display pkgid ++ " was excluded because " ++ display pkgid' ++ " was selected instead" showExclusionReason pkgid (ExcludedByConfigureFail missingDeps) = display pkgid ++ " was excluded because it could not be configured. " ++ "It requires " ++ listOf displayDep missingDeps showExclusionReason pkgid (ExcludedByPackageDependency pkgid' dep installedConstraint) = display pkgid ++ " was excluded because " ++ display pkgid' ++ " requires " ++ (if installedConstraint then "an installed instance of " else "") ++ displayDep dep showExclusionReason pkgid (ExcludedByTopLevelConstraintVersion pkgname verRange) = display pkgid ++ " was excluded because of the top level constraint " ++ displayDep (Dependency pkgname verRange) showExclusionReason pkgid (ExcludedByTopLevelConstraintInstalled pkgname) = display pkgid ++ " was excluded because of the top level constraint '" ++ display pkgname ++ " installed' which means that only installed instances " ++ "of the package may be selected." showExclusionReason pkgid (ExcludedByTopLevelConstraintSource pkgname) = display pkgid ++ " was excluded because of the top level constraint '" ++ display pkgname ++ " source' which means that only source versions " ++ "of the package may be selected." -- ------------------------------------------------------------ -- * Logging progress and failures -- ------------------------------------------------------------ data Log = Select [SelectedPackage] [PackageId] | AppliedVersionConstraint PackageName VersionRange [PackageId] | AppliedInstalledConstraint PackageName InstalledConstraint [PackageId] | ExcludeUnconfigurable PackageId data Failure = NoSuchPackage PackageName | ConfigureFailed SelectablePackage [(Dependency, [(PackageId, [ExclusionReason])])] | DependencyConflict SelectedPackage Dependency Bool [(PackageId, [ExclusionReason])] | TopLevelVersionConstraintConflict PackageName VersionRange [(PackageId, [ExclusionReason])] | TopLevelVersionConstraintUnsatisfiable PackageName VersionRange | TopLevelInstallConstraintConflict PackageName InstalledConstraint [(PackageId, [ExclusionReason])] | TopLevelInstallConstraintUnsatisfiable PackageName InstalledConstraint showLog :: Log -> String showLog (Select selected discarded) = case (selectedMsg, discardedMsg) of ("", y) -> y (x, "") -> x (x, y) -> x ++ " and " ++ y where selectedMsg = "selecting " ++ case selected of [] -> "" [s] -> display (packageId s) ++ " " ++ kind s (s:ss) -> listOf id $ (display (packageId s) ++ " " ++ kind s) : [ display (packageVersion s') ++ " " ++ kind s' | s' <- ss ] kind (InstalledOnly _) = "(installed)" kind (SourceOnly _) = "(source)" kind (InstalledAndSource _ _) = "(installed or source)" discardedMsg = case discarded of [] -> "" _ -> "discarding " ++ listOf id [ element | (pkgid:pkgids) <- groupBy (equating packageName) (sort discarded) , element <- display pkgid : map (display . packageVersion) pkgids ] showLog (AppliedVersionConstraint pkgname ver pkgids) = "applying constraint " ++ display (Dependency pkgname ver) ++ if null pkgids then "" else " which excludes " ++ listOf display pkgids showLog (AppliedInstalledConstraint pkgname inst pkgids) = "applying constraint " ++ display pkgname ++ " '" ++ (case inst of InstalledConstraint -> "installed"; _ -> "source") ++ "' " ++ if null pkgids then "" else "which excludes " ++ listOf display pkgids showLog (ExcludeUnconfigurable pkgid) = "excluding " ++ display pkgid ++ " (it cannot be configured)" showFailure :: Failure -> String showFailure (NoSuchPackage pkgname) = "The package " ++ display pkgname ++ " is unknown." showFailure (ConfigureFailed pkg missingDeps) = "cannot configure " ++ displayPkg pkg ++ ". It requires " ++ listOf (displayDep . fst) missingDeps ++ '\n' : unlines (map (uncurry whyNot) missingDeps) where whyNot (Dependency name ver) [] = "There is no available version of " ++ display name ++ " that satisfies " ++ displayVer ver whyNot dep conflicts = "For the dependency on " ++ displayDep dep ++ " there are these packages: " ++ listOf display pkgs ++ ". However none of them are available.\n" ++ unlines [ showExclusionReason (packageId pkg') reason | (pkg', reasons) <- conflicts, reason <- reasons ] where pkgs = map fst conflicts showFailure (DependencyConflict pkg dep installedConstraint conflicts) = "dependencies conflict: " ++ displayPkg pkg ++ " requires " ++ (if installedConstraint then "an installed instance of " else "") ++ displayDep dep ++ " however:\n" ++ unlines [ showExclusionReason (packageId pkg') reason | (pkg', reasons) <- conflicts, reason <- reasons ] showFailure (TopLevelVersionConstraintConflict name ver conflicts) = "constraints conflict: we have the top level constraint " ++ displayDep (Dependency name ver) ++ ", but\n" ++ unlines [ showExclusionReason (packageId pkg') reason | (pkg', reasons) <- conflicts, reason <- reasons ] showFailure (TopLevelVersionConstraintUnsatisfiable name ver) = "There is no available version of " ++ display name ++ " that satisfies " ++ displayVer ver showFailure (TopLevelInstallConstraintConflict name InstalledConstraint conflicts) = "constraints conflict: " ++ "top level constraint '" ++ display name ++ " installed' however\n" ++ unlines [ showExclusionReason (packageId pkg') reason | (pkg', reasons) <- conflicts, reason <- reasons ] showFailure (TopLevelInstallConstraintUnsatisfiable name InstalledConstraint) = "There is no installed version of " ++ display name showFailure (TopLevelInstallConstraintConflict name SourceConstraint conflicts) = "constraints conflict: " ++ "top level constraint '" ++ display name ++ " source' however\n" ++ unlines [ showExclusionReason (packageId pkg') reason | (pkg', reasons) <- conflicts, reason <- reasons ] showFailure (TopLevelInstallConstraintUnsatisfiable name SourceConstraint) = "There is no available source version of " ++ display name displayVer :: VersionRange -> String displayVer = display . simplifyVersionRange displayDep :: Dependency -> String displayDep = display . simplifyDependency -- ------------------------------------------------------------ -- * Utils -- ------------------------------------------------------------ impossible :: String -> a impossible msg = internalError $ "assertion failure: " ++ msg internalError :: String -> a internalError msg = error $ "internal error: " ++ msg displayPkg :: Package pkg => pkg -> String displayPkg = display . packageId listOf :: (a -> String) -> [a] -> String listOf _ [] = [] listOf disp [x0] = disp x0 listOf disp (x0:x1:xs) = disp x0 ++ go x1 xs where go x [] = " and " ++ disp x go x (x':xs') = ", " ++ disp x ++ go x' xs' -- ------------------------------------------------------------ -- * Construct a dependency graph -- ------------------------------------------------------------ -- | Builds a graph of the package dependencies. -- -- Dependencies on other packages that are not in the index are discarded. -- You can check if there are any such dependencies with 'brokenPackages'. -- -- The top-down solver gets its own implementation, because both -- `dependencyGraph` in `Distribution.Client.PlanIndex` (in cabal-install) and -- `dependencyGraph` in `Distribution.Simple.PackageIndex` (in Cabal) both work -- with `PackageIndex` from `Cabal` (that is, a package index indexed by -- installed package IDs rather than package names). -- -- Ideally we would switch the top-down solver over to use that too, so that -- this duplication could be avoided, but that's a bit of work and the top-down -- solver is legacy code anyway. -- -- (NOTE: This is called at two types: InstalledPackage and PlanPackage.) dependencyGraph :: PackageSourceDeps pkg => PackageIndex pkg -> (Graph.Graph, Graph.Vertex -> pkg, PackageId -> Maybe Graph.Vertex) dependencyGraph index = (graph, vertexToPkg, pkgIdToVertex) where graph = Array.listArray bounds $ map (catMaybes . map pkgIdToVertex . sourceDeps) pkgs vertexToPkg vertex = pkgTable Array.! vertex pkgIdToVertex = binarySearch 0 topBound pkgTable = Array.listArray bounds pkgs pkgIdTable = Array.listArray bounds (map packageId pkgs) pkgs = sortBy (comparing packageId) (PackageIndex.allPackages index) topBound = length pkgs - 1 bounds = (0, topBound) binarySearch a b key | a > b = Nothing | otherwise = case compare key (pkgIdTable Array.! mid) of LT -> binarySearch a (mid-1) key EQ -> Just mid GT -> binarySearch (mid+1) b key where mid = (a + b) `div` 2
seereason/cabal
cabal-install/Distribution/Client/Dependency/TopDown.hs
bsd-3-clause
45,782
0
21
11,688
9,006
4,691
4,315
699
13
{- Copyright (C) 2009-2011 John Goerzen <[email protected]> All rights reserved. For license and copyright information, see the file LICENSE -} {- | Module : Data.Convertible.Instances Copyright : Copyright (C) 2009-2011 John Goerzen License : BSD3 Maintainer : John Goerzen <[email protected]> Stability : provisional Portability: portable Collection of ready-made 'Data.Convertible.Convertible' instances. See each individual module for more docs: "Data.Convertible.Instances.C" "Data.Convertible.Instances.Map" "Data.Convertible.Instances.Num" "Data.Convertible.Instances.Time" You can find a list of these instances at 'Data.Convertible.Base.Convertible'. -} module Data.Convertible.Instances( ) where import Data.Convertible.Instances.C() import Data.Convertible.Instances.Map() import Data.Convertible.Instances.Num() import Data.Convertible.Instances.Text() import Data.Convertible.Instances.Time()
hdbc/convertible
Data/Convertible/Instances.hs
bsd-3-clause
988
0
4
160
62
44
18
6
0
--Factorial implementation using Tail recursion fact :: Int -> Int fact n = facTail n 1 facTail :: (Int) -> (Int) -> (Int) facTail 0 r = r facTail n r = facTail (n-1) (n*r) --Fibonnaci implementation using Tail Recursion fib :: Int -> Int fib n | n == 0 =0 | n < 0 =0 | otherwise = fibTail n 1 0 fibTail :: Int -> Int -> Int -> Int fibTail n result previous |n==0 =result |otherwise = fibTail (n-1) (result +previous) result -- Sum of the first Integers sumInteger :: Int -> Int sumInteger n |n < 0 =0 |n== 0 = 0 |otherwise = sumTail n 0 sumTail :: Int -> Int -> Int sumTail n result |n == 0 = result |otherwise = sumTail (n-1) (n+result)
caiorss/Functional-Programming
codes/TailRecursion.hs
unlicense
669
5
8
162
332
165
167
23
1
{-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : System.Mem.Weak -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- -- In general terms, a weak pointer is a reference to an object that is -- not followed by the garbage collector - that is, the existence of a -- weak pointer to an object has no effect on the lifetime of that -- object. A weak pointer can be de-referenced to find out -- whether the object it refers to is still alive or not, and if so -- to return the object itself. -- -- Weak pointers are particularly useful for caches and memo tables. -- To build a memo table, you build a data structure -- mapping from the function argument (the key) to its result (the -- value). When you apply the function to a new argument you first -- check whether the key\/value pair is already in the memo table. -- The key point is that the memo table itself should not keep the -- key and value alive. So the table should contain a weak pointer -- to the key, not an ordinary pointer. The pointer to the value must -- not be weak, because the only reference to the value might indeed be -- from the memo table. -- -- So it looks as if the memo table will keep all its values -- alive for ever. One way to solve this is to purge the table -- occasionally, by deleting entries whose keys have died. -- -- The weak pointers in this library -- support another approach, called /finalization/. -- When the key referred to by a weak pointer dies, the storage manager -- arranges to run a programmer-specified finalizer. In the case of memo -- tables, for example, the finalizer could remove the key\/value pair -- from the memo table. -- -- Another difficulty with the memo table is that the value of a -- key\/value pair might itself contain a pointer to the key. -- So the memo table keeps the value alive, which keeps the key alive, -- even though there may be no other references to the key so both should -- die. The weak pointers in this library provide a slight -- generalisation of the basic weak-pointer idea, in which each -- weak pointer actually contains both a key and a value. -- ----------------------------------------------------------------------------- module System.Mem.Weak ( -- * The @Weak@ type Weak, -- abstract -- * The general interface mkWeak, deRefWeak, finalize, -- * Specialised versions mkWeakPtr, addFinalizer, mkWeakPair, -- replaceFinaliser -- * A precise semantics -- $precise ) where import GHC.Weak -- | A specialised version of 'mkWeak', where the key and the value are -- the same object: -- -- > mkWeakPtr key finalizer = mkWeak key key finalizer -- mkWeakPtr :: k -> Maybe (IO ()) -> IO (Weak k) mkWeakPtr key finalizer = mkWeak key key finalizer {-| A specialised version of 'mkWeakPtr', where the 'Weak' object returned is simply thrown away (however the finalizer will be remembered by the garbage collector, and will still be run when the key becomes unreachable). Note: adding a finalizer to a 'Foreign.ForeignPtr.ForeignPtr' using 'addFinalizer' won't work; use the specialised version 'Foreign.ForeignPtr.addForeignPtrFinalizer' instead. For discussion see the 'Weak' type. . -} addFinalizer :: key -> IO () -> IO () addFinalizer key finalizer = do _ <- mkWeakPtr key (Just finalizer) -- throw it away return () -- | A specialised version of 'mkWeak' where the value is actually a pair -- of the key and value passed to 'mkWeakPair': -- -- > mkWeakPair key val finalizer = mkWeak key (key,val) finalizer -- -- The advantage of this is that the key can be retrieved by 'deRefWeak' -- in addition to the value. mkWeakPair :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v)) mkWeakPair key val finalizer = mkWeak key (key,val) finalizer {- $precise The above informal specification is fine for simple situations, but matters can get complicated. In particular, it needs to be clear exactly when a key dies, so that any weak pointers that refer to it can be finalized. Suppose, for example, the value of one weak pointer refers to the key of another...does that keep the key alive? The behaviour is simply this: * If a weak pointer (object) refers to an /unreachable/ key, it may be finalized. * Finalization means (a) arrange that subsequent calls to 'deRefWeak' return 'Nothing'; and (b) run the finalizer. This behaviour depends on what it means for a key to be reachable. Informally, something is reachable if it can be reached by following ordinary pointers from the root set, but not following weak pointers. We define reachability more precisely as follows. A heap object is /reachable/ if: * It is a member of the /root set/. * It is directly pointed to by a reachable object, other than a weak pointer object. * It is a weak pointer object whose key is reachable. * It is the value or finalizer of a weak pointer object whose key is reachable. -}
alexander-at-github/eta
libraries/base/System/Mem/Weak.hs
bsd-3-clause
5,244
0
11
1,088
284
181
103
18
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ur-PK"> <title>Token Generator | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/tokengen/src/main/javahelp/org/zaproxy/zap/extension/tokengen/resources/help_ur_PK/helpset_ur_PK.hs
apache-2.0
976
78
66
159
413
209
204
-1
-1
{-# LANGUAGE BangPatterns, MagicHash, UnboxedTuples, FlexibleContexts #-} -- | Efficient serialisation for GHCi Instruction arrays -- -- Author: Ben Gamari -- module GHCi.BinaryArray(putArray, getArray) where import Prelude import Foreign.Ptr import Data.Binary import Data.Binary.Put (putBuilder) import qualified Data.Binary.Get.Internal as Binary import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Builder.Internal as BB import qualified Data.Array.Base as A import qualified Data.Array.IO.Internals as A import qualified Data.Array.Unboxed as A import GHC.Exts import GHC.IO -- | An efficient serialiser of 'A.UArray'. putArray :: Binary i => A.UArray i a -> Put putArray (A.UArray l u _ arr#) = do put l put u putBuilder $ byteArrayBuilder arr# byteArrayBuilder :: ByteArray# -> BB.Builder byteArrayBuilder arr# = BB.builder $ go 0 (I# (sizeofByteArray# arr#)) where go :: Int -> Int -> BB.BuildStep a -> BB.BuildStep a go !inStart !inEnd k (BB.BufferRange outStart outEnd) -- There is enough room in this output buffer to write all remaining array -- contents | inRemaining <= outRemaining = do copyByteArrayToAddr arr# inStart outStart inRemaining k (BB.BufferRange (outStart `plusPtr` inRemaining) outEnd) -- There is only enough space for a fraction of the remaining contents | otherwise = do copyByteArrayToAddr arr# inStart outStart outRemaining let !inStart' = inStart + outRemaining return $! BB.bufferFull 1 outEnd (go inStart' inEnd k) where inRemaining = inEnd - inStart outRemaining = outEnd `minusPtr` outStart copyByteArrayToAddr :: ByteArray# -> Int -> Ptr a -> Int -> IO () copyByteArrayToAddr src# (I# src_off#) (Ptr dst#) (I# len#) = IO $ \s -> case copyByteArrayToAddr# src# src_off# dst# len# s of s' -> (# s', () #) -- | An efficient deserialiser of 'A.UArray'. getArray :: (Binary i, A.Ix i, A.MArray A.IOUArray a IO) => Get (A.UArray i a) getArray = do l <- get u <- get arr@(A.IOUArray (A.STUArray _ _ _ arr#)) <- return $ unsafeDupablePerformIO $ A.newArray_ (l,u) let go 0 _ = return () go !remaining !off = do Binary.readNWith n $ \ptr -> copyAddrToByteArray ptr arr# off n go (remaining - n) (off + n) where n = min chunkSize remaining go (I# (sizeofMutableByteArray# arr#)) 0 return $! unsafeDupablePerformIO $ unsafeFreezeIOUArray arr where chunkSize = 10*1024 copyAddrToByteArray :: Ptr a -> MutableByteArray# RealWorld -> Int -> Int -> IO () copyAddrToByteArray (Ptr src#) dst# (I# dst_off#) (I# len#) = IO $ \s -> case copyAddrToByteArray# src# dst# dst_off# len# s of s' -> (# s', () #) -- this is inexplicably not exported in currently released array versions unsafeFreezeIOUArray :: A.IOUArray ix e -> IO (A.UArray ix e) unsafeFreezeIOUArray (A.IOUArray marr) = stToIO (A.unsafeFreezeSTUArray marr)
sdiehl/ghc
libraries/ghci/GHCi/BinaryArray.hs
bsd-3-clause
3,093
0
14
743
921
474
447
58
2
{-# LANGUAGE ScopedTypeVariables #-} {-@ LIQUID "--no-termination" @-} module LinSpace (dotPV, sameSpace, enumCVP) where import Language.Haskell.Liquid.Prelude (liquidAssume, liquidAssert, liquidError) import Prelude hiding (zipWith) data PVector = PVector { vec :: [Integer] -- vector coordinates , muCoeff :: [Integer] -- <vec,bn*>det^2(b[1..n-1]) : ... , orthSpace :: Space PVector -- lattice basis } deriving (Show, Eq) -- | Orthogonalized vector bn* and squared lattice determinant data Space a = Null | Real a Integer deriving (Show, Eq) {-@ data PVector = PVector { vec_ :: [Integer] , mu_ :: [Integer] , orth_ :: {v: (Space (PVectorN (len vec_))) | (dim v) = (len mu_)} } @-} {-@ data Space [dim] @-} {-@ measure dim :: (Space PVector) -> Int dim (Null) = 0 dim (Real pv n) = 1 + (dim (orthSpace pv)) @-} {-@ measure spaceVec :: (Space PVector) -> PVector spaceVec (Real pv n) = pv @-} {-@ measure vec :: PVector -> [Integer] vec (PVector v m o) = v @-} {-@ measure muCoeff :: PVector -> [Integer] muCoeff (PVector v m o) = m @-} {-@ measure orthSpace :: PVector -> (Space PVector) orthSpace (PVector p m o) = o @-} {-@ invariant {v: PVector | (Inv v) } @-} {-@ invariant {v: Space PVector | (dim v) >= 0 } @-} -- RJ: Helpers for defining properties {-@ predicate Inv V = (dim (orthSpace V)) = (len (muCoeff V)) @-} {-@ predicate SameLen X Y = ((len (vec X)) = (len (vec Y))) @-} {-@ predicate SameOrth X Y = ((orthSpace X) = (orthSpace Y)) @-} -- RJ: Useful type aliases for specs {-@ type SameSpace X = {v:PVector | ((Inv v) && (SameLen X v) && (SameOrth X v))} @-} {-@ type PVectorN N = {v: PVector | (len (vec v)) = N} @-} {-@ type PVectorP P = {v: PVector | (SameLen v P)} @-} -------------------- {-@ dim :: s:(Space PVector) -> {v:Int | v = (dim s)} @-} dim Null = (0 :: Int) dim (Real pv _) = 1 + dim (orthSpace_ pv) sameSpace :: PVector -> PVector -> Bool sameSpace pv1 pv2 = (length (vec pv1) == length (vec pv2)) && (orthSpace pv1 == orthSpace pv2) {-@ muCoeff_ :: p:PVector -> {v:[Integer] | v = (muCoeff p) } @-} muCoeff_ (PVector v m o) = m {-@ orthSpace_ :: p:PVector -> {v:(Space (PVectorP p)) | v = (orthSpace p)} @-} orthSpace_ (PVector v m o) = o {-@ vec_ :: p:PVector -> {v:[Integer] | v = (vec p)} @-} vec_ (PVector v m o) = v -------------------- -- squared determinant of orthSpace detPV :: PVector -> Integer detPV (PVector _ _ Null) = 1 detPV (PVector _ _ (Real _ n)) = n {-@ liftPV :: pv:PVector -> {v:(PVectorP pv) | ((orthSpace v) = (orthSpace (spaceVec (orthSpace pv))) && ((dim (orthSpace v)) = (dim (orthSpace pv)) - 1))} @-} liftPV (PVector v (m:mu) (Real pv _)) = PVector v mu (orthSpace_ pv) {-@ dot :: (Num a) => xs:[a] -> {v:[a] | (len v) = (len xs)} -> a @-} dot xs ys = sum (zipWith (*) xs ys) -- scaled dot product of two projected vectors: output is <v*,w*>det^2(orthSpace) {-@ dotPV :: pv1:PVector -> pv2:(SameSpace pv1) -> Integer @-} dotPV (PVector v1 [] _) (PVector v2 [] _) = dot v1 v2 dotPV pv1@(PVector _ mu1 _) pv2@(PVector _ mu2 _) = liquidAssert (length mu1 == length mu2) q where dd = dotPV (liftPV pv1) (liftPV pv2) Real pv0 rr = orthSpace_ pv1 -- same as orthSpace v2 x = dd * rr - (head mu1) * (head mu2) (q, 0) = divMod x (liquidAssume (rem /= 0) rem) -- check remainder is 0 rem = detPV pv0 -- ASSERT: (x .+. y) ==> sameSpace x y {-@ (.+.) :: x:PVector -> (SameSpace x) -> (SameSpace x) @-} (PVector v1 m1 o) .+. (PVector v2 m2 _) = PVector (zipWith (+) v1 v2) (zipWith (+) m1 m2) o -- ASSERT: (x .-. y) ==> sameSpace x y {-@ (.-.) :: x:PVector -> (SameSpace x) -> (SameSpace x) @-} (PVector v1 m1 o) .-. (PVector v2 m2 _) = PVector (zipWith (-) v1 v2) (zipWith (-) m1 m2) o {-@ (*.) :: Integer -> x:PVector -> (SameSpace x) @-} (*.) :: Integer -> PVector -> PVector x *. (PVector v m o) = PVector (map (x *) v) (map (x *) m) o -- Some auxiliary functions {-@ space2vec :: n:Int -> s:(Space (PVectorN n)) -> {v: (PVectorN n) | (orthSpace v) = s} @-} space2vec (n :: Int) sp@(Real bn r) = PVector (vec_ bn) (r : muCoeff_ bn) sp {-@ makeSpace :: p:PVector -> (Space (PVectorP p)) @-} makeSpace pvec = Real pvec (dotPV pvec pvec) {-@ makePVector :: vs:[Integer] -> s:(Space (PVectorN (len vs))) -> {v: (PVectorN (len vs)) | (orthSpace v) = s} @-} makePVector :: [Integer] -> Space PVector -> PVector makePVector v s@Null = PVector v [] s makePVector v s@(Real s1 _) = let v1 = makePVector v (orthSpace_ s1) in PVector v (dotPV v1 s1 : muCoeff_ v1) s {-@ gramSchmidt :: n:Nat -> [(List Integer n)] -> (Space (PVectorN n)) @-} gramSchmidt (n :: Int) = foldl (\sp v -> makeSpace (makePVector v sp)) Null {-@ getBasis :: n:Nat -> Space (PVectorN n) -> [(List Integer n)] @-} getBasis (n::Int) s = worker s [] where worker Null bs = bs worker (Real pv _) bs = worker (orthSpace_ pv) (vec pv : bs) {-@ qualif EqMu(v:PVector, x:PVector): (len (muCoeff v)) = (len (muCoeff x)) @-} sizeReduce1 :: PVector -> PVector sizeReduce1 pv@(PVector v (m:_) sn@(Real _ r)) = let c = div (2*m + r) (liquidAssume (r2 /= 0) r2) -- division with rounded remainder r2 = 2 * r n = length v in pv .-. (c *. (space2vec n sn)) -- ASSERT: sameSpace (sizeReduce x) x {-@ sizeReduce :: x:PVector -> (SameSpace x) @-} sizeReduce pv@(PVector v [] Null) = pv sizeReduce pv@(PVector _ _ sp@(Real _ _)) = let pv1 = sizeReduce1 pv (PVector v mu _) = sizeReduce (liftPV pv1) in PVector v (head (muCoeff_ pv1) : mu) sp -- Two example algorithms using the library: enumCVP and lll enumCVP :: PVector -> Integer -> Maybe [Integer] enumCVP (PVector v mu Null) r | dot v v < r = Just v | otherwise = Nothing enumCVP t@(PVector _ (_:_) (Real bn _)) r = let t0 = sizeReduce1 t cs = if (head (muCoeff_ t0) < 0) then 0 : concat [[x,negate x] | x <- [1,2..]] else 0 : concat [[negate x,x] | x <- [1,2..]] branch :: (Integer, Maybe [Integer]) -> [PVector] -> (Integer, Maybe [Integer]) branch (r,v) (t:ts) = if (dotPV t t >= r * detPV t) then (r,v) else case enumCVP t r of Nothing -> branch (r,v) ts Just w -> branch (dot w w, Just w) ts in snd $ branch (r,Nothing) [liftPV t0 .+. (c *. bn) | c <- cs] -- make this parametric on n {- Fraction free LLL Algorithm with exact arithmetic and delta=99/100 -} {-@ lll :: n:Nat -> [(List Integer n)] -> [(List Integer n)] @-} lll :: Int -> [[Integer]] -> [[Integer]] lll n = getBasis n . lll_worker n Null Nothing {-@ lll_worker :: n:Nat -> (Space (PVectorN n)) -> (Maybe (PVectorN n)) -> [(List Integer n)] -> (Space (PVectorN n)) @-} lll_worker (n :: Int) bs Nothing [] = bs lll_worker n bs Nothing (v:vs) = lll_worker n bs (Just (makePVector v bs)) vs lll_worker n Null (Just pv) vs = lll_worker n (makeSpace pv) Nothing vs lll_worker n (Real bn r) (Just pv) vs = let pv1 = sizeReduce pv pv2 = liftPV pv1 in if (100*(dotPV pv2 pv2) < 99*r) then lll_worker n (orthSpace_ bn) (Just pv2) (vec bn : vs) else lll_worker n (makeSpace pv1) Nothing vs ------------------------------------------------------------------------------------ -- RJ: Included for illustration... ------------------------------------------------------------------------------------ {-@ type List a N = {v : [a] | (len v) = N} @-} {-@ zipWith :: (a -> b -> c) -> xs:[a] -> (List b (len xs)) -> (List c (len xs)) @-} zipWith f (a:as) (b:bs) = f a b : zipWith f as bs zipWith _ [] [] = [] zipWith _ (_:_) [] = liquidError "Dead Code" zipWith _ [] (_:_) = liquidError "Dead Code"
mightymoose/liquidhaskell
tests/todo/linspace.hs
bsd-3-clause
7,877
0
15
1,961
2,177
1,149
1,028
89
4
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} module YesodCoreTest.JsLoader (specs, Widget) where import YesodCoreTest.JsLoaderSites.Bottom (B(..)) import Test.Hspec import Yesod.Core import Network.Wai.Test data H = H mkYesod "H" [parseRoutes| / HeadR GET |] instance Yesod H where jsLoader _ = BottomOfHeadBlocking getHeadR :: Handler Html getHeadR = defaultLayout $ addScriptRemote "load.js" specs :: Spec specs = describe "Test.JsLoader" $ do it "link from head" $ runner H $ do res <- request defaultRequest assertBody "<!DOCTYPE html>\n<html><head><title></title><script src=\"load.js\"></script></head><body></body></html>" res it "link from bottom" $ runner B $ do res <- request defaultRequest assertBody "<!DOCTYPE html>\n<html><head><title></title></head><body><script src=\"load.js\"></script></body></html>" res runner :: YesodDispatch master => master -> Session () -> IO () runner app f = toWaiApp app >>= runSession f
ygale/yesod
yesod-core/test/YesodCoreTest/JsLoader.hs
mit
1,085
0
12
168
240
121
119
24
1
{-# LANGUAGE UnboxedSums #-} module Main where import Lib import Prelude (print, IO) main :: IO () main = do print (getInt (flip (# 123 | #)))
ezyang/ghc
testsuite/tests/unboxedsums/module/Main.hs
bsd-3-clause
151
0
12
35
55
31
24
7
1
{-# LANGUAGE MultiParamTypeClasses #-} -- Test Trac #3265 module T3265 where data a :+: b = Left a | Right b class a :*: b where {}
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/rename/should_fail/T3265.hs
bsd-3-clause
136
0
6
31
36
22
14
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE TypeFamilies #-} module Futhark.Internalise.Monad ( InternaliseM, runInternaliseM, throwError, VarSubsts, InternaliseEnv (..), FunInfo, substitutingVars, lookupSubst, addFunDef, lookupFunction, lookupFunction', lookupConst, bindFunction, bindConstant, localConstsScope, assert, -- * Convenient reexports module Futhark.Tools, ) where import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State import qualified Data.Map.Strict as M import Futhark.IR.SOACS import Futhark.MonadFreshNames import Futhark.Tools type FunInfo = ( [VName], [DeclType], [FParam SOACS], [(SubExp, Type)] -> Maybe [DeclExtType] ) type FunTable = M.Map VName FunInfo -- | A mapping from external variable names to the corresponding -- internalised subexpressions. type VarSubsts = M.Map VName [SubExp] data InternaliseEnv = InternaliseEnv { envSubsts :: VarSubsts, envDoBoundsChecks :: Bool, envSafe :: Bool, envAttrs :: Attrs } data InternaliseState = InternaliseState { stateNameSource :: VNameSource, stateFunTable :: FunTable, stateConstSubsts :: VarSubsts, stateConstScope :: Scope SOACS, stateFuns :: [FunDef SOACS] } newtype InternaliseM a = InternaliseM (BuilderT SOACS (ReaderT InternaliseEnv (State InternaliseState)) a) deriving ( Functor, Applicative, Monad, MonadReader InternaliseEnv, MonadState InternaliseState, MonadFreshNames, HasScope SOACS, LocalScope SOACS ) instance MonadFreshNames (State InternaliseState) where getNameSource = gets stateNameSource putNameSource src = modify $ \s -> s {stateNameSource = src} instance MonadBuilder InternaliseM where type Rep InternaliseM = SOACS mkExpDecM pat e = InternaliseM $ mkExpDecM pat e mkBodyM stms res = InternaliseM $ mkBodyM stms res mkLetNamesM pat e = InternaliseM $ mkLetNamesM pat e addStms = InternaliseM . addStms collectStms (InternaliseM m) = InternaliseM $ collectStms m runInternaliseM :: MonadFreshNames m => Bool -> InternaliseM () -> m (Stms SOACS, [FunDef SOACS]) runInternaliseM safe (InternaliseM m) = modifyNameSource $ \src -> let ((_, consts), s) = runState (runReaderT (runBuilderT m mempty) newEnv) (newState src) in ((consts, reverse $ stateFuns s), stateNameSource s) where newEnv = InternaliseEnv { envSubsts = mempty, envDoBoundsChecks = True, envSafe = safe, envAttrs = mempty } newState src = InternaliseState { stateNameSource = src, stateFunTable = mempty, stateConstSubsts = mempty, stateConstScope = mempty, stateFuns = mempty } substitutingVars :: VarSubsts -> InternaliseM a -> InternaliseM a substitutingVars substs = local $ \env -> env {envSubsts = substs <> envSubsts env} lookupSubst :: VName -> InternaliseM (Maybe [SubExp]) lookupSubst v = do env_substs <- asks $ M.lookup v . envSubsts const_substs <- gets $ M.lookup v . stateConstSubsts return $ env_substs `mplus` const_substs -- | Add a function definition to the program being constructed. addFunDef :: FunDef SOACS -> InternaliseM () addFunDef fd = modify $ \s -> s {stateFuns = fd : stateFuns s} lookupFunction' :: VName -> InternaliseM (Maybe FunInfo) lookupFunction' fname = gets $ M.lookup fname . stateFunTable lookupFunction :: VName -> InternaliseM FunInfo lookupFunction fname = maybe bad return =<< lookupFunction' fname where bad = error $ "Internalise.lookupFunction: Function '" ++ pretty fname ++ "' not found." lookupConst :: VName -> InternaliseM (Maybe [SubExp]) lookupConst fname = gets $ M.lookup fname . stateConstSubsts bindFunction :: VName -> FunDef SOACS -> FunInfo -> InternaliseM () bindFunction fname fd info = do addFunDef fd modify $ \s -> s {stateFunTable = M.insert fname info $ stateFunTable s} bindConstant :: VName -> FunDef SOACS -> InternaliseM () bindConstant cname fd = do let stms = bodyStms $ funDefBody fd substs = drop (length (shapeContext (funDefRetType fd))) $ map resSubExp $ bodyResult $ funDefBody fd addStms stms modify $ \s -> s { stateConstSubsts = M.insert cname substs $ stateConstSubsts s, stateConstScope = scopeOf stms <> stateConstScope s } localConstsScope :: InternaliseM a -> InternaliseM a localConstsScope m = do scope <- gets stateConstScope localScope scope m -- | Construct an 'Assert' statement, but taking attributes into -- account. Always use this function, and never construct 'Assert' -- directly in the internaliser! assert :: String -> SubExp -> ErrorMsg SubExp -> SrcLoc -> InternaliseM Certs assert desc se msg loc = assertingOne $ do attrs <- asks $ attrsForAssert . envAttrs attributing attrs $ letExp desc $ BasicOp $ Assert se msg (loc, mempty) -- | Execute the given action if 'envDoBoundsChecks' is true, otherwise -- just return an empty list. asserting :: InternaliseM Certs -> InternaliseM Certs asserting m = do doBoundsChecks <- asks envDoBoundsChecks if doBoundsChecks then m else return mempty -- | Execute the given action if 'envDoBoundsChecks' is true, otherwise -- just return an empty list. assertingOne :: InternaliseM VName -> InternaliseM Certs assertingOne m = asserting $ Certs . pure <$> m
diku-dk/futhark
src/Futhark/Internalise/Monad.hs
isc
5,644
0
19
1,226
1,486
788
698
152
2
module Properties (properties) where import Test.Tasty.QuickCheck (testProperty) import Data.Serialize (encode, decode) import Test.Tasty (TestTree, testGroup) import Yeast.Feed import Yeast.Parse import Yeast.Render ------------------------------------------------------------------------ -- * Properties prop_serialize :: Feed -> Bool prop_serialize f = decode (encode f) == Right f prop_parseRender :: Feed -> Bool prop_parseRender f = either (const False) ((==) f) . parseText . renderText (def { rsPretty = True }) $ f -- XXX: Test renderer against external feed validator? -- https://validator.w3.org/feed/ ------------------------------------------------------------------------ properties :: TestTree properties = testGroup "Properties" [ testProperty "serialize" prop_serialize , testProperty "parseRender" prop_parseRender ]
stevana/yeast
tests/Properties.hs
isc
966
0
10
222
192
108
84
20
1
{-# LANGUAGE OverloadedStrings #-} module Templates where import Prelude hiding (head) import Text.Blaze import Text.Blaze.Html5 import qualified Text.Blaze.Html5.Attributes as A import qualified Settings as Settings mainMenu :: Bool -> Html mainMenu authorized = p $ do a ! A.href "/" $ "Bookmarks" _ <- " " if authorized then a ! A.href "/logout" $ "Logout" else do a ! A.href "/login" $ "Login" _ <- " " a ! A.href "/register" $ "Register" index :: Html index = html $ do head $ do title (toHtml Settings.name) body $ do h1 (toHtml Settings.name) h2 (toHtml Settings.slogan) mainMenu False p "Some Text!"
fredmorcos/attic
projects/intramarks/markr_happstack/Templates.hs
isc
691
0
14
184
230
116
114
26
2
{-# LANGUAGE NoImplicitPrelude #-} module Handler.Download ( getDownloadR , getDownloadSnapshotsJsonR , getDownloadLtsSnapshotsJsonR , getGhcMajorVersionR , getDownloadGhcLinksR ) where import RIO (textDisplay) import Import import Data.GhcLinks import Yesod.GitRepo (grContent) import Stackage.Database getDownloadR :: Handler Html getDownloadR = track "Hoogle.Download.getDownloadR" $ redirectWith status301 InstallR getDownloadSnapshotsJsonR :: Handler Value getDownloadSnapshotsJsonR = track "Hoogle.Download.getDownloadSnapshotsJsonR" getDownloadLtsSnapshotsJsonR getDownloadLtsSnapshotsJsonR :: Handler Value getDownloadLtsSnapshotsJsonR = track "Hoogle.Download.getDownloadLtsSnapshotsJsonR" snapshotsJSON -- Print the ghc major version for the given snapshot. ghcMajorVersionText :: Snapshot -> Text ghcMajorVersionText = textDisplay . keepMajorVersion . ghcVersion . snapshotCompiler getGhcMajorVersionR :: SnapName -> Handler Text getGhcMajorVersionR name = track "Hoogle.Download.getGhcMajorVersionR" $ do snapshot <- lookupSnapshot name >>= maybe notFound return return $ ghcMajorVersionText $ entityVal snapshot getDownloadGhcLinksR :: SupportedArch -> Text -> Handler TypedContent getDownloadGhcLinksR arch fName = track "Hoogle.Download.getDownloadGhcLinksR" $ do ver <- maybe notFound return $ stripPrefix "ghc-" >=> stripSuffix "-links.yaml" >=> ghcMajorVersionFromText $ fName ghcLinks <- getYesod >>= fmap wcGhcLinks . liftIO . grContent . appWebsiteContent case lookup (arch, ver) (ghcLinksMap ghcLinks) of Just text -> return $ TypedContent yamlMimeType $ toContent text Nothing -> notFound where yamlMimeType = "text/yaml"
fpco/stackage-server
src/Handler/Download.hs
mit
1,762
0
13
295
356
179
177
37
2
module Jumper where -------------------- -- Global Imports -- import FRP.Spice ---------- -- Code -- -- The Jumper datatype data Jumper = Jumper { pos :: Vector Float , dir :: Vector Float , size :: Vector Float , groundLevel :: Float }
crockeo/spice-test
src/jumper/Jumper.hs
mit
347
0
9
152
56
35
21
6
0
{-# LANGUAGE OverloadedStrings #-} module Control.OperationalTransformation.Text0.Gen (genOperation, genMultiOperation) where import Control.OperationalTransformation import Control.OperationalTransformation.Text0 import qualified Data.Text as T import Test.QuickCheck hiding (Result) instance Arbitrary T.Text where arbitrary = T.pack <$> listOf (choose ('!', '~')) genOperation :: T.Text -> Gen Text0Operation genOperation s = oneof [ -- Insert a string (elements [0 .. (T.length s)]) >>= \i -> do randomStr <- randomString return $ T0 [TextInsert i randomStr], -- Delete a string (elements [0 .. (T.length s)]) >>= \i1 -> (elements [i1 .. (T.length s)]) >>= \i2 -> return $ T0 [TextDelete i1 (T.take (i2 - i1) $ T.drop i1 s)] ] genMultiOperation :: T.Text -> Gen Text0Operation genMultiOperation s = do n <- elements [2..10] genMultiOperation' n s (T0 []) genMultiOperation' :: Int -> T.Text -> Text0Operation -> Gen Text0Operation genMultiOperation' 0 doc ops = return ops genMultiOperation' n doc (T0 ops) = do op@(T0 [singleOp]) <- genOperation doc let Right doc' = apply op doc genMultiOperation' (n - 1) doc' (T0 (ops ++ [singleOp])) -- | Random strings are ordered sequences of lowercase letters randomString :: Gen T.Text randomString = (elements [0..26]) >>= \x -> return $ T.take x "abcdefghijklmnopqrstuvwxyz"
thomasjm/ot.hs
test/Control/OperationalTransformation/Text0/Gen.hs
mit
1,376
0
19
244
499
261
238
28
1
import ImageLoader import Brain -------------------------------------------------------------------------------- import Control.Exception (SomeException (..)) import System.Random (mkStdGen, randomR) import Numeric.LinearAlgebra import Data.List import qualified Numeric.LinearAlgebra.Data as V import Debug.Trace -------------------------------------------------------------------------------- type Samples = [(V.Vector Double, V.Vector Double)] main :: IO () main = loadFiles loadFiles :: IO () loadFiles = do ex <- loadExamples notEx <- loadNonExamples case (ex, notEx) of (Left (SomeException e), _) -> printError e (_, Left (SomeException e)) -> printError e (Right v1, Right v2) -> runTraining v1 v2 where printError e = putStrLn $ "Exception: " ++ (show e) runTraining :: Samples -> Samples -> IO () runTraining s1 s2 = do net <- constructNeuralNetwork 256 [512, 256, 128, 64] 1 all_ putStrLn "----" printSamples all_ net putStrLn "----" let net' = trainN net 800 printSamples all_ net' where all_ = s1 ++ s2 printSamples :: Samples -> NetworkWithSamples -> IO () printSamples [] _ = return () printSamples (x:xs) net = do putStrLn $ vid ++ " --> " ++ output ++ " ? " ++ expectedOut printSamples xs net where in_ = fst x expectedOut = show $ snd x vid = show $ (vecId in_) output = show $ (activate net in_) -- Given a list of examples, separates into a list of -- test data (fst) and training data (snd) sepExTest :: [a] -> ([a], [a]) sepExTest xs = go xs ([], []) (mkStdGen 10) where go [] a _ = a go (v:vs) (a, b) gen = case randomR (0, 99) gen of (n, gen') -> if n < (20 :: Int) then go vs (v:a, b) gen' else go vs (a, v:b) gen' vecId :: V.Vector Double -> Double vecId v = v <.> V.fromList (replicate 256 (1 :: Double))
robmcl4/A-Neural
src/Main.hs
mit
2,038
0
13
592
705
370
335
47
3
module Users ( User (..) , UserMetaData (..) , toResource , getUsers , getUser ) where import Data.Aeson.TH import Data.Maybe (fromJust) import Data.Monoid ((<>)) import Data.Text (pack) import Network.URL import Network.JSONApi ( Links , Meta , MetaObject (..) , ResourcefulEntity (..) , mkMeta ) import qualified Network.JSONApi as JSONApi data User = User { userId :: Int , userFirstName :: String , userLastName :: String } deriving (Eq, Show) $(deriveJSON defaultOptions ''User) data UserMetaData = UserMetaData { count :: Int } deriving (Eq, Show) $(deriveJSON defaultOptions ''UserMetaData) instance MetaObject UserMetaData where typeName _ = "userCount" instance ResourcefulEntity User where resourceIdentifier = pack . show . userId resourceType _ = "User" resourceLinks = Just . userLinks resourceMetaData _ = Just userMetaData resourceRelationships _ = Nothing -- helper function to build links for a User resource userLinks :: User -> Links userLinks user = JSONApi.mkLinks [ ("self", selfLink) ] where selfLink = toURL selfPath selfPath = "/users/" <> (show $ userId user) userMetaData :: Meta userMetaData = mkMeta (UserMetaData $ length getUsers) toURL :: String -> URL toURL = fromJust . importURL getUser :: Int -> Maybe User getUser 1 = Just isacc getUser 2 = Just albert getUser _ = Nothing getUsers :: [User] getUsers = [isacc, albert] isacc :: User isacc = User 1 "Isaac" "Newton" albert :: User albert = User 2 "Albert" "Einstein"
toddmohney/json-api
example/src/Users.hs
mit
1,533
0
10
305
472
265
207
-1
-1
{- - By Yue Wang 13.12.2014 - proj03 linear search. - @note this is a non monad version, return the size of the list when nothing found - -} linearSearch :: (Eq a)=> [a] -> a -> Int linearSearch [] val = error "empty list" linearSearch [x]val = if x == val then 0 else 1 linearSearch (x:xs) val = if x == val then 0 else 1 + linearSearch xs val
Mooophy/DMA
ch02/proj03.hs
mit
372
0
7
99
105
56
49
4
3
-- | -- Module: Args -- Copyright: Copyright (c) 2009-2014, Sebastian Schwarz <[email protected]> -- License: MIT -- Maintainer: Sebastian Schwarz <[email protected]> -- {-# LANGUAGE OverloadedStrings #-} module Args ( Config(..) , parseArgs ) where import Control.Applicative (Applicative(..), liftA2, (<$>)) import Control.Arrow ((+++)) import Control.Category ((>>>)) import Data.Char (toLower) import Data.List (isPrefixOf, nub, union, (\\)) import Data.String (IsString(..)) import Data.ByteString.Lazy.Char8 (ByteString) import Data.Map (Map, empty, insert, singleton) import Text.Parsec hiding (satisfy, token) import Text.Parsec.Error import MailKwds (foldHeaders) -- | The configuration options for the program. data Config a = Config { catenate :: [a] -> [a] -- ^ whether to catenate or refold headers , command :: [a] -> [a] -> [a] -- ^ the command to apply to the 'Label's , help :: Bool , input :: Map a a -- ^ the headers to parse , keywords :: [a] -- ^ the 'Label's to be added/removed , output :: [(a, a)] -- ^ the headers to print , version :: Bool } -- For debugging proposes instance Show a => Show (Config a) where show x = "Config " ++ "{ catenate :: [a] -> [a]" ++ ", command :: [a] -> [a] -> [a]" ++ ", help = " ++ show (help x) ++ ", input = " ++ show (input x) ++ ", keywords = " ++ show (keywords x) ++ ", output = " ++ show (output x) ++ ", version = " ++ show (version x) ++ " }" -- | Generalization of 'Text.Parsec.Char.char'. token :: (Eq a, Show a, Stream s m a) => a -> ParsecT s u m a token t = satisfy (== t) <?> show [t] -- | Generalization of 'Text.Parsec.Char.satisfy'. satisfy :: (Show a, Stream s m a) => (a -> Bool) -> ParsecT s u m a satisfy f = tokenPrim (\c -> show [c]) (\pos _ _ -> incSourceColumn pos 1) (\c -> if f c then Just c else Nothing) -- | Parse the command line arguments and create an appropriate configuration. parseArgs :: [String] -> Either String (Config ByteString) parseArgs args = sanitizeError +++ (sanitizeConfig . \x -> foldr (>>>) id x config) $ parse pArgs "Args" args -- (>>>) ensures that the map's values where -- get overwritten correctly config = Config { catenate = foldHeaders , command = flip const , help = False , input = empty , keywords = [] , output = [] , version = False } -- | Print @UnExpect@ed errors @Message@s or the complete @ParseError@ if there -- is none. sanitizeError :: ParseError -> String sanitizeError e = if null msg then "Unable to parse command line arguments:\n" ++ show e else msg ++ "Try `mailkwds --help` for help." where msg = unlines . map messageString . errorMessages $ e -- | Ensure a halfway sane configuration. sanitizeConfig :: (Eq a, IsString a) => Config a -> Config a sanitizeConfig c = c { input = sanitizeInput $ input c , output = sanitizeOutput $ output c , keywords = nub . reverse $ keywords c -- output keywords in the same order } -- as specified on the command line where sanitizeInput x | x == empty = singleton "keywords" "," | otherwise = x sanitizeOutput [] = [("Keywords", ", ")] sanitizeOutput x = nub $ reverse x -- adjust order to command line -------------------------------------------------------------------------------- -- The command line argument parser. -- | Parse a list of 'String's to a list of 'Config' modifying functions. pArgs :: (IsString a, Monad m, Ord a) => ParsecT [String] u m [Config a -> Config a] pArgs = many pOption <+> pSep <+> pCommand where (<+>) = liftA2 (++) pOption :: (IsString a, Monad m, Ord a) => ParsecT [String] u m (Config a -> Config a) pOption = pCat <|> pHelp <|> pInput <|> pOutput <|> pVersion <|> unexpected . (++) "unrecognized option: " =<< satisfy (liftA2 (&&) (isPrefixOf "-") (/= "--")) pCat :: Monad m => ParsecT [String] u m (Config a -> Config a) pCat = (token "-c" <|> token "--catenate") *> pure (cat id) <?> "catenate" where cat x c = c { catenate = x } pHelp :: Monad m => ParsecT [String] u m (Config a -> Config a) pHelp = (token "-h" <|> token "--help") *> pure (hel True) <?> "help" where hel x c = c { help = x } pInput :: (IsString a, Monad m, Ord a) => ParsecT [String] u m (Config a -> Config a) pInput = (choice $ map token ["-f", "--from", "-i", "--input"]) *> (inp <$> anyToken <*> anyToken) <?> "input" where inp x y c = c { input = insert (fromString $ map toLower x) (fromString y) (input c) } pOutput :: (IsString a, Monad m) => ParsecT [String] u m (Config a -> Config a) pOutput = (choice $ map token ["-o", "--output", "-t", "--to"]) *> (out <$> anyToken <*> anyToken) <?> "output" where out x y c = c { output = (fromString x, fromString y) : output c } pVersion :: Monad m => ParsecT [String] u m (Config a -> Config a) pVersion = (token "-v" <|> token "--version") *> pure (ver True) <?> "version" where ver x c = c { version = x } pSep :: Monad m => ParsecT [String] u m [a] pSep = optional (token "--") *> pure [] <?> "separator" pCommand :: (Eq a, IsString a, Monad m) => ParsecT [String] u m [Config a -> Config a] pCommand = option [] $ liftA2 (++) (fmap (:[]) pCommands) (many pLabel) pCommands :: (Eq a, Monad m) => ParsecT [String] u m (Config a -> Config a) pCommands = (choice . map (\(c, f) -> token c *> pure (com f) <?> "command") $ cmds) <|> unexpected . (++) "unknown command: " =<< anyToken <|> unexpected "no command given" where com x c = c { command = x } cmds = [ ("add", flip union) , ("clear", const $ const []) , ("set", const) , ("remove", flip (\\)) , ("tidy", flip const) ] pLabel :: (IsString a, Monad m) => ParsecT [String] u m (Config a -> Config a) pLabel = lab <$> anyToken <?> "keyword" where lab x c = c { keywords = fromString x : keywords c }
seschwar/mailkwds
src/Args.hs
mit
6,356
0
19
1,812
2,140
1,159
981
-1
-1
module Distill.Expr.Tests ( tests , WellTypedExpr(..) , arbitraryExpr , arbitraryType , arbitraryDecls ) where import System.IO import Test.HUnit import Test.QuickCheck (Arbitrary(..)) import Test.QuickCheck.Gen import Test.QuickCheck.Property import Text.Parsec import Distill.Expr.Representation import Distill.Expr.Syntax import Distill.Expr.TypeCheck import Distill.TestUtil import Distill.UniqueName import Distill.UniqueName.Tests import Distill.Util tests :: Test tests = TestLabel "Distill.Expr.Tests" $ TestList [ TestLabel "prop_exprsWellTyped" $ quickCheckToHUnit prop_exprsWellTyped , TestLabel "simpleTest" $ simpleTest , TestLabel "prop_parsePprInverses" $ quickCheckToHUnit prop_parsePprInverses ] newtype WellTypedExpr = WellTypedExpr Expr deriving (Show, Read) instance Arbitrary WellTypedExpr where arbitrary = do (_, m, _) <- arbitraryExpr [] 0 return (WellTypedExpr m) -- | Generate an arbitrary well-typed expression. arbitraryExpr :: [(UniqueName, Type)] -> Int -> Gen (Int, Expr, Type) arbitraryExpr bound s = sized $ \size -> do let atomic = size <= 1 oneof . concat $ [ [arbitraryVar bound s | atomic && not (null bound)] , [arbitraryType' bound s | True] , [arbitraryLambda bound s | not atomic] , [arbitraryApply bound s | not atomic] , [arbitraryFold bound s | not atomic] , [arbitraryUnfold bound s | not atomic] ] where arbitraryVar bound s = do (x, t) <- elements bound return (s, Var x, t) arbitraryType' bound s = do (s, t) <- smaller $ arbitraryType bound s return (s, t, Star) arbitraryLambda bound s = do (s, x) <- arbitraryUniqueName s (s, t) <- smaller $ arbitraryType bound s (s, m, t') <- smaller $ arbitraryExpr ((x, t):bound) s return (s, Lambda x t m, Forall x t t') arbitraryApply bound s = do (s, x) <- arbitraryUniqueName s (s, n, t) <- smaller $ arbitraryExpr bound s (s, body, t') <- smaller $ arbitraryExpr ((x, t):bound) s let m = Lambda x t body return (s, Apply m n, subst' x n t') arbitraryFold bound s = do (s, x) <- arbitraryUniqueName s (s, m, t) <- smaller $ arbitraryExpr bound s let foldedType = Mu x Star t return (s, Fold m foldedType, foldedType) arbitraryUnfold bound s = do let boundMus = filter (isMu . snd) bound if not (null boundMus) then do (y, Mu x t t') <- elements boundMus return (s, Unfold (Var y), subst' x (Mu x t t') t') else do (s, m, Mu x t t') <- arbitraryFold bound s return (s, Unfold m, subst' x (Mu x t t') t') isMu Mu{} = True isMu _ = False subst' x m n = fromRight $ runTCM undefined $ subst x m n -- | Generate an arbitrary well-formed type. arbitraryType :: [(UniqueName, Type)] -> Int -> Gen (Int, Type) arbitraryType bound s = sized $ \size -> do let atomic = size <= 1 oneof . concat $ [ [arbitraryStar bound s | atomic] , [arbitraryForall bound s | not atomic] , [arbitraryMu bound s | not atomic] ] where arbitraryStar _ s = return (s, Star) arbitraryForall bound s = do (s, x) <- arbitraryUniqueName s (s, t) <- smaller $ arbitraryType bound s (s, t') <- smaller $ arbitraryType ((x, t):bound) s return (s, Forall x t t') arbitraryMu bound s = do (s, x) <- arbitraryUniqueName s (s, t) <- smaller $ arbitraryType ((x, Star):bound) s return (s, Mu x Star t) -- | Generate an arbitrary set of declarations. arbitraryDecls :: [(UniqueName, Type)] -> Int -> Gen (Int, [Decl]) arbitraryDecls bound s = sized (arbitraryDecls' bound s) where arbitraryDecls' _ s 0 = return (s, []) arbitraryDecls' bound s n = do (s, name) <- arbitraryUniqueName s (s, expr, type_) <- arbitraryExpr bound s let decl = Decl' name type_ expr (s, decls) <- arbitraryDecls' ((name, type_):bound) s (pred n) return (s, decl:decls) -- | The property that generated expressions are well-typed. prop_exprsWellTyped :: WellTypedExpr -> Result prop_exprsWellTyped (WellTypedExpr expr) = let unique = nextAvailableUnique expr in case runTCM (uniqueRenamer unique) (inferType expr) of Right _ -> succeeded Left err -> failed {reason = err} -- | A simple test on parsing and type-checking a file of declarations. simpleTest :: Test simpleTest = TestCase $ do let fileName = "./test/simple.distill" withFile fileName ReadMode $ \file -> do contents <- hGetContents file let parsed = parse parseFile fileName contents decls <- case parsed of Left err -> assertFalse (show err) Right decls -> return decls let decls' = renumberDecls UniqueName decls let assumes = map (\(Decl' x t _) -> (x, t)) decls' let defines = map (\(Decl' x _ m) -> (x, m)) decls' let tcm = flip mapM_ decls' $ \(Decl' _ t m) -> checkType m t let unique = maximum (map nextAvailableUniqueDecl decls') let renamer = uniqueRenamer unique case runTCM renamer $ assumesIn assumes $ definesIn defines $ tcm of Left err -> assertFalse err Right _ -> return () -- | The property that parsing and pretty-printing are inverse functions. prop_parsePprInverses :: WellTypedExpr -> Result prop_parsePprInverses (WellTypedExpr expr) = let pprinted = prettyShow expr parsed = parse parseExpr "" pprinted in case parsed of Left err -> failed { reason = "Failed to parse pretty-printed expr.\n" ++ introSpiel pprinted ++ "\tWhile parsing, the following error occured:\n" ++ show err } Right expr' -> let renumbered = renumber UniqueName expr' unique = nextAvailableUnique renumbered renamer = uniqueRenamer unique in case runTCM renamer (checkEqual expr renumbered) of Left err -> failed { reason = "Failed to check original expression was " ++ "equal to pretty-printed and parsed " ++ "expression.\n" ++ introSpiel pprinted ++ "\tWhile checking expressions to be equal, " ++ "the following error occured:\n" ++ err } Right () -> succeeded where introSpiel pprinted = "\tStarted with the expression:\n" ++ show expr ++ "\n" ++ "\tWhich was pretty-printed as:\n" ++ pprinted ++ "\n"
DNoved1/distill
test/Distill/Expr/Tests.hs
mit
6,959
0
22
2,202
2,251
1,141
1,110
152
3
module Data.Maybe.Extra ( module Data.Maybe , rightToMaybe ) where import Data.Maybe rightToMaybe :: Either t a -> Maybe a rightToMaybe (Right x) = Just x rightToMaybe (Left _) = Nothing
expipiplus1/spir-v
generate/src/Data/Maybe/Extra.hs
mit
195
0
7
38
71
38
33
7
1
-- Intermission: Exercises -- Note the following exercises are from source code files, not written for use -- directly in the REPL. Of course, you can change them to test directly in the -- REPL if you prefer. -- 1. Which (two or more) of the following are equivalent? -- a) mTh x y z = x * y * z -- b) mTh x y = \z -> x * y * z -- c) mTh x = \y -> \z -> x * y * z -- d) mTh = \x -> \y -> \z -> x * y * z -- All of them? -- 2. The type of mTh (above) isNum a => a -> a -> a -> a. Which is the type of mTh 3? -- a) Integer -> Integer -> Integer -- b) Num a => a -> a -> a -> a -- c) Num a => a -> a -- d) Num a => a -> a -> a -- d -- 3. Next, we’ll practice writing anonymous lambda syntax. For example, one -- could rewrite: -- addOne x = x + 1 -- Into: -- addOne = \x -> x + 1 -- Try to make it so it can still be loaded as a top-level definition by GHCi. -- This will make it easier to validate your answers. -- a) Rewrite the f function in the where clause. addOneIfOdd n = case odd n of True -> f n False -> n where f = \n -> n + 1 -- b) Rewrite the following to use anonymous lambda syntax: --addFive x y = (if x > y then y else x) + 5 addFive x = \y -> (if x > y then y else x) + 5 -- c) Rewrite the following so that it doesn’t use anonymous lambda syntax: mflip f x y = f y x
diminishedprime/.org
reading-list/haskell_programming_from_first_principles/07_03.hs
mit
1,308
0
9
341
123
76
47
6
2
module ConnectFour.BoardSpec where import Test.Hspec import ConnectFour.Board main :: IO () main = hspec spec spec :: Spec spec = do describe "Board" $ do context "when dropping coins on board" $ do it "should be able to drop a coin in an empty column" $ do dropCoin [[],[],[],[],[],[],[]] Yellow 0 `shouldBe` Just [[Yellow],[],[],[],[],[],[]] dropCoin [[],[],[],[],[],[],[]] Yellow 6 `shouldBe` Just [[],[],[],[],[],[],[Yellow]] it "should be able to drop a coin in a column with coins" $ do dropCoin [[Yellow],[],[],[],[],[],[]] Yellow 0 `shouldBe` Just [[Yellow, Yellow],[],[],[],[],[],[]] it "should not be able to drop a coin in a column that is full" $ do dropCoin [[Yellow, Yellow, Yellow, Yellow, Yellow, Yellow],[],[],[],[],[],[]] Yellow 0 `shouldBe` Nothing context "when finding fields" $ do it "should give the right coin on the lower left position" $ do index [[Yellow],[],[],[],[],[],[]] (0,0) `shouldBe` Just Yellow it "should give the right coin on the upper right position" $ do index [[],[],[],[],[],[],[Empty, Empty, Empty, Empty, Empty, Yellow]] (6,5) `shouldBe` Just Yellow it "should give the Empty coin on a valid, yet empty position" $ do index [[],[],[],[],[],[],[]] (0, 0) `shouldBe` Just Empty it "should not give any coin on an invalid position" $ do index [[],[],[],[],[],[],[]] (-1, 0) `shouldBe` Nothing index [[],[],[],[],[],[],[]] (0, -1) `shouldBe` Nothing index [[],[],[],[],[],[],[]] (7, 5) `shouldBe` Nothing index [[],[],[],[],[],[],[]] (6, 6) `shouldBe` Nothing context "when winning moves on board are made horizontally" $ do it "should detect a horizontal strike from the start" $ do winningColumn [[Yellow],[Yellow],[Yellow],[Yellow],[],[],[]] 0 `shouldBe` True it "should detect a horizontal strike halfway" $ do winningColumn [[Yellow],[Yellow],[Yellow],[Yellow],[],[],[]] 2 `shouldBe` True it "should detect a horizontal strike on the end" $ do winningColumn [[Yellow],[Yellow],[Yellow],[Yellow],[],[],[]] 3 `shouldBe` True it "should detect a not long enough horizontal strike" $ do winningColumn [[Yellow],[Yellow],[Yellow],[],[],[],[]] 1 `shouldBe` False it "should detect a not connected horizontal strike" $ do winningColumn [[Yellow],[Yellow],[],[Yellow],[Yellow],[],[]] 1 `shouldBe` False context "when winning moves on board are made vertically" $ do it "should detect a vertical strike on the end" $ do winningColumn [[Yellow,Yellow,Yellow,Yellow],[],[],[],[],[],[]] 0 `shouldBe` True it "should detect a not long enough horizontal strike" $ do winningColumn [[Yellow,Yellow,Yellow],[],[],[],[],[],[]] 0 `shouldBe` False it "should detect a not connected vertical strike" $ do winningColumn [[Yellow,Yellow,Empty,Yellow,Yellow],[],[],[],[],[],[]] 0 `shouldBe` False context "when winning moves on board are made diagonally" $ do it "should detect an increasing diagonal strike from the start" $ do winningColumn [[Yellow],[Empty,Yellow],[Empty,Empty,Yellow],[Empty,Empty,Empty,Yellow],[],[],[]] 0 `shouldBe` True it "should detect an increasing diagonal strike halfway" $ do winningColumn [[Yellow],[Empty,Yellow],[Empty,Empty,Yellow],[Empty,Empty,Empty,Yellow],[],[],[]] 2 `shouldBe` True it "should detect an increasing diagonal strike on the end" $ do winningColumn [[Yellow],[Yellow],[Yellow],[Yellow],[],[],[]] 3 `shouldBe` True it "should detect a not long enough increasing diagonal strike" $ do winningColumn [[Yellow],[Empty,Yellow],[Empty,Empty,Yellow],[],[],[],[]] 1 `shouldBe` False it "should detect a not connected increasing diagonal strike" $ do winningColumn [[Yellow],[Empty,Yellow],[],[Empty,Empty,Empty,Yellow],[Empty,Empty,Empty,Empty,Yellow],[],[]] 1 `shouldBe` False it "should detect an decreasing diagonal strike from the start" $ do winningColumn [[Empty,Empty,Empty,Yellow],[Empty,Empty,Yellow],[Empty,Yellow],[Yellow],[],[],[]] 0 `shouldBe` True it "should detect an decreasing diagonal strike halfway" $ do winningColumn [[Empty,Empty,Empty,Yellow],[Empty,Empty,Yellow],[Empty,Yellow],[Yellow],[],[],[]] 2 `shouldBe` True it "should detect an decreasing diagonal strike on the end" $ do winningColumn [[Empty,Empty,Empty,Yellow],[Empty,Empty,Yellow],[Empty,Yellow],[Yellow],[],[],[]] 3 `shouldBe` True it "should detect a not long enough decreasing diagonal strike" $ do winningColumn [[Empty,Empty,Yellow],[Empty,Yellow],[Yellow],[],[],[],[]] 1 `shouldBe` False it "should detect a not connected decreasing diagonal strike" $ do winningColumn [[Empty,Empty,Empty,Empty,Yellow],[Empty,Empty,Empty,Yellow],[],[Empty,Yellow],[Yellow],[],[]] 1 `shouldBe` False context "when board is about to be full" $ do it "should detect an almost full board to be not full" $ do let fullColumn = [Yellow,Yellow,Yellow,Yellow,Yellow,Yellow] full [fullColumn,fullColumn,fullColumn,fullColumn,fullColumn,take 5 fullColumn] `shouldBe` False it "should detect an almost full board to be not full" $ do let fullColumn = [Yellow,Yellow,Yellow,Yellow,Yellow,Yellow] full [fullColumn,fullColumn,fullColumn,fullColumn,fullColumn,fullColumn] `shouldBe` True
tcoenraad/connect-four
test/ConnectFour/BoardSpec.hs
mit
5,721
0
19
1,299
2,384
1,357
1,027
80
1
import Test.Hspec import Data.Either (isLeft) import qualified Language.Python.Parser.Lexer as P main :: IO () main = hspec $ do describe "Language.Python.Parser.Lexer.lex" $ do it "parses Python numeric literals" $ do "0" `lexesTo` [P.Number (P.IntLiteral 0)] "00000" `lexesTo` [P.Number (P.IntLiteral 0)] "0." `lexesTo` [P.Number (P.FloatLiteral 0.0)] ".0" `lexesTo` [P.Number (P.FloatLiteral 0.0)] "0.0" `lexesTo` [P.Number (P.FloatLiteral 0.0)] "1" `lexesTo` [P.Number (P.IntLiteral 1)] "1." `lexesTo` [P.Number (P.FloatLiteral 1.0)] "1.0" `lexesTo` [P.Number (P.FloatLiteral 1.0)] "1.e0" `lexesTo` [P.Number (P.FloatLiteral 1.0)] it "does not parse invalid Python numeric literals" $ do lexFailsFor "01" where lexFailsFor input = P.lex "<spec>" input `shouldSatisfy` isLeft lexesTo input tokens = let result = map P.ptToken <$> P.lex "<spec>" input in result `shouldBe` Right (tokens ++ [P.NewLine, P.EndMarker])
Garciat/Hucc
test/Spec.hs
mit
1,072
0
19
271
392
202
190
23
1
import Control.Monad (guard) import Data.Char import Data.Bits data Literal = Literal Bool Int Int Int deriving Show type Clause = [Literal] readValue v | v `elem` ['1'..'9'] = (ord v) - (ord '1') + 1 | v `elem` ['A'..'Z'] = (ord v) - (ord 'A') + 1 | otherwise = error ("WTF? Cell value out of range: '" ++ (show v) ++ "'") formatLiteral :: Int -> Int -> Literal -> Int formatLiteral m n (Literal b r c bi) = if b then i else -i where i = bi + (c-1) * (m) + (r-1) * (m*(n^2)) formatClauses :: Int -> Int -> [Clause] -> [[Int]] formatClauses m n cs = map f cs where f c = (map (formatLiteral m n) c) ++ [0] printClauses :: Int -> Int -> [Clause] -> IO () printClauses m n cs = mapM_ f (formatClauses m n cs) where f c = putStrLn $ unwords $ map show c ithBit v bi = testBit (v - 1) (bi - 1) validValues m n = [1..n^2] invalidValues m n = [n^2+1..2^m] g :: Int -> (Int, Int, Int) -> Clause g m (r, c, v) = [(Literal (ithBit v bi) r c bi) | bi <- [1..m]] deMorgan clause = map f clause where f (Literal b r c bi) = (Literal (not b) r c bi) c1 :: Int -> Int -> [Clause] c1 m n = do r <- [1..n^2]; c <- [1..n^2] r' <- [1..n^2]; v <- validValues m n guard (r /= r') return $ (deMorgan (g m (r, c, v))) ++ (deMorgan (g m (r', c, v))) c2 :: Int -> Int -> [Clause] c2 m n = do r <- [1..n^2]; c <- [1..n^2] c' <- [1..n^2]; v <- validValues m n guard (c /= c') return $ (deMorgan (g m (r, c, v))) ++ (deMorgan (g m (r, c', v))) c3 :: Int -> Int -> [Clause] c3 m n = do r <- [1..n^2]; c <- [1..n^2]; let i = (r-1) `div` n let j = (c-1) `div` n r' <- [(i*n+1)..(i*n+n)] c' <- [(j*n+1)..(j*n+n)] guard (r /= r') guard (c /= c') v <- validValues m n return $ (deMorgan (g m (r, c, v))) ++ (deMorgan (g m (r', c', v))) c4 :: Int -> Int -> [Clause] c4 m n = map (deMorgan . (g m)) rcvs where rcvs = [(r, c, v) | r <- [1..n^2], c <- [1..n^2], v <- invalidValues m n] c5 :: Int -> Int -> String -> [Clause] c5 m n q = map (:[]) $ concat $ map toLit rcvs where rcvs = filter ((/= '_') . snd) $ zip rcs $ filter (/= '\n') q rcs = [(r, c) | r <- [1..n^2], c <- [1..n^2]] toLit ((r, c), v) = g m (r, c, (readValue v)) main = do input <- getContents let nsqrd = length $ head $ lines input let n = floor $ sqrt $ (fromInteger (toInteger (nsqrd))::Float) let m = ceiling $ logBase 2 (fromInteger (toInteger (n^2))::Float) let cs = (c1 m n) ++ (c2 m n) ++ (c3 m n) ++ (c4 m n) ++ (c5 m n input) putStrLn ("p cnf " ++ show (m*(n^4)) ++ " " ++ show (length cs)) printClauses m n cs
damelang/sdk2cnf
sdk2cnf-2.hs
mit
2,740
0
17
837
1,730
904
826
60
2
-- Lightweight and reusable Haskeline alternative module Flowskell.InputLine ( InputLine, newInputLine, showInputLine, getInput, input, backspace, pos1, end, del, left, right ) where import System.IO import Control.Monad.State import Data.Char type InputLine = (String -- String before cursor , String) -- String after cursor type InputLineModifier = InputLine -> InputLine showInputLine (b, a) = b ++ "|" ++ a newInputLine :: InputLine newInputLine = ("", "") getInput :: InputLine -> String getInput (b, a) = b ++ a input :: Char -> InputLineModifier input c (b, a) = (b ++ [c], a) backspace :: InputLineModifier backspace (b, a) = (drop1FromEnd b, a) pos1 :: InputLineModifier pos1 (b, a) = ("", b ++ a) end :: InputLineModifier end (b, a) = (b ++ a, "") del :: InputLineModifier del (b, a) = (b, drop 1 a) left :: InputLineModifier left (b, a) = (drop1FromEnd b, (last1 b) ++ a) right :: InputLineModifier right (b, a) = (b ++ (take 1 a), drop 1 a) drop1FromEnd s = take (length s - 1) s last1 s = drop (length s - 1) s -- The following functionality is only for testing/evaluating. ansiInput :: String -> StateT InputLine IO () ansiInput prompt = do liftIO $ putStr prompt forever $ do c <- liftIO $ getChar if (c == ansiEsc) then do escCode <- liftIO $ getChar >> getChar modify (handleEscapeSequence escCode) else modify (handleChar c) (b, a) <- get liftIO $ putStr $ "\r" ++ prompt ++ b ++ a ++ "\x1b[K\r" ++ prompt ++ b where ansiEsc = '\x1b' handleChar '\x08' = backspace handleChar '\x7e' = del handleChar c = input c handleEscapeSequence 'H' = pos1 handleEscapeSequence 'F' = end handleEscapeSequence 'D' = left handleEscapeSequence 'C' = right handleEscapeSequence _ = id main = do hSetBuffering stdin NoBuffering hSetEcho stdin False hSetBuffering stdout NoBuffering runStateT (ansiInput ">>> ") newInputLine
lordi/flowskell
src/Flowskell/InputLine.hs
gpl-2.0
2,070
0
17
553
701
377
324
59
8
#!/usr/bin/env runhaskell -- | Computing GC Content -- Usage: GC <dataset.txt> import System.Environment(getArgs) import qualified Data.ByteString.Char8 as C import Data.Ord(comparing) import Data.List(sortBy) parseFastaMultiline :: C.ByteString -> [(C.ByteString, C.ByteString)] parseFastaMultiline f = zip (map (C.takeWhile (/='\n')) xs) (map (C.filter (/='\n') . C.dropWhile (/='\n')) xs) where xs = filter (\x -> C.length x > 0) . C.split '>' $ f gcContent :: Fractional a => C.ByteString -> a gcContent seq = (C.foldr ((+) . ifS) 0.0 seq) / (fromIntegral $ C.length seq) where ifS x = if x == 'C' || x == 'G' then 1 else 0 pairs :: [t] -> [(t, t)] pairs [] = [] pairs (x:[]) = [] -- abnormal case pairs (x:y:xs) = (x, y) : pairs xs main = do (file:_) <- getArgs fasta <- C.readFile file let result = last . sortBy (comparing $ gcContent . snd) . parseFastaMultiline $ fasta C.putStrLn $ fst result putStrLn $ show $ 100.0 * (gcContent . snd $ result)
kerkomen/rosalind-haskell
stronghold/GC.hs
gpl-2.0
977
0
16
182
455
243
212
20
2
-- file: ch4/exA2.hs -- A function that acts similarly to `words`, but takes a predicate and a -- list of any type, and splits its input list on every element for which -- the predicate returns `False`. splitWith :: (a -> Bool) -> [a] -> [[a]] splitWith _ [] = [] splitWith p xs = pre : (splitWith p $ suf' suf) where (pre, suf) = break (not . p) xs suf' [] = [] suf' xs = tail xs
friedbrice/RealWorldHaskell
ch4/exA2.hs
gpl-2.0
396
0
9
95
124
66
58
6
2
module Ocram.Main (main) where -- imports {{{1 import Ocram.Analysis (analysis, Analysis(anaCritical, anaBlocking, anaCallgraph), footprint) import Ocram.Backend (tcode_2_ecode) import Ocram.Debug (create_debug_info) import Ocram.Intermediate (ast_2_ir) import Ocram.Options (options) import Ocram.IO (parse, generate_pal, dump_ecode, dump_debug_info, dump_pcode) import Ocram.Print (render_with_log') import Ocram.Ruab (encode_debug_info) import Ocram.Text (OcramError, show_errors) import Ocram.Test (runTests) import System.Directory (getCurrentDirectory) import System.Environment (getArgs, getProgName) import System.Exit (exitWith, ExitCode(ExitFailure)) import System.IO (stderr, hPutStrLn) main :: IO () -- {{{1 main = do argv <- getArgs case argv of ("--test":rest) -> runTests rest _ -> runCompiler argv runCompiler :: [String] -> IO () -- {{{1 runCompiler argv = do prg <- getProgName cwd <- getCurrentDirectory opt <- exitOnError "options" $ options prg cwd argv (tcode, pcode, tAst) <- exitOnError "parser" =<< parse opt ana <- exitOnError "analysis" $ analysis tAst cfs <- exitOnError "intermediate" $ ast_2_ir (anaBlocking ana) (anaCritical ana) let (eAst, pal, vm) = tcode_2_ecode ana cfs let (ecode, bps) = render_with_log' eAst let di = encode_debug_info $ create_debug_info opt tcode pcode ana vm bps ecode exitOnError "output" =<< generate_pal opt (footprint (anaCallgraph ana)) pal exitOnError "output" =<< dump_ecode opt ecode exitOnError "output" =<< dump_debug_info opt di exitOnError "output" =<< dump_pcode opt pcode return () exitOnError :: String -> Either [OcramError] a -> IO a -- {{{2 exitOnError module_ (Left es) = hPutStrLn stderr (show_errors module_ es) >> exitWith (ExitFailure 1) exitOnError _ (Right x) = return x _tests :: String -> IO () -- {{{1 _tests args = runTests $ words $ "--hide-successes --plain -j 3 " ++ args
copton/ocram
ocram/src/Ocram/Main.hs
gpl-2.0
2,030
0
12
417
658
340
318
42
2
{-# LANGUAGE FlexibleInstances #-} module Algebraic.Nested.Op where import Algebraic.Nested.Type import Expression.Op import Autolib.ToDoc import qualified Autolib.Set as S import qualified Autolib.TES.Binu as B instance Ops ( Type Integer ) where bops = B.Binu { B.nullary = map zahl [ 0 .. 9 ] , B.unary = [ Op { name = "pow", arity = 1 , precedence = Nothing, assoc = AssocNone , inter = lift1 power } ] , B.binary = [ Op { name = "+", arity = 2, precedence = Just 5, assoc = AssocLeft , inter = lift2 union } , Op { name = "-", arity = 2, precedence = Just 5, assoc = AssocLeft , inter = lift2 difference } , Op { name = "&", arity = 2, precedence = Just 7, assoc = AssocLeft , inter = lift2 intersection } ] } zahl :: Integer -> Op ( Type Integer ) zahl i = Op { name = show i, arity = 0, precedence = Nothing, assoc = AssocNone , inter = lift0 $ unit i } is_empty :: Type a -> Bool is_empty ( Make xs ) = S.isEmptySet xs unit :: Ord a => a -> Type a unit x = Make $ S.mkSet [ Unit x ] empty :: Type a empty = Make $ S.emptySet union :: Ord a => Type a -> Type a -> Type a union ( Make xs ) ( Make ys ) = Make $ S.union xs ys difference :: Ord a => Type a -> Type a -> Type a difference ( Make xs ) ( Make ys ) = Make $ S.minusSet xs ys intersection :: Ord a => Type a -> Type a -> Type a intersection ( Make xs ) ( Make ys ) = Make $ S.intersect xs ys power :: Ord a => Type a -> Type a power ( Make xs ) = Make $ S.mkSet $ map ( Packed . Make ) $ S.subsets xs
Erdwolf/autotool-bonn
src/Algebraic/Nested/Op.hs
gpl-2.0
1,602
66
8
465
626
353
273
38
1
module Language.Lambda.Types where -- Primitive types (String, Int, Bool), and composite (union) types. data Type = StringType | IntType | BoolType | TupleType [Type] | FunctionType { _from :: Type , _to :: Type }
justinmanley/lambda
src/Language/Lambda/Types.hs
gpl-3.0
262
0
8
83
46
30
16
9
0
-- | Playing with fix points. module PwFix where import Data.Function (fix) -- | Factorial function, open recursion style. -- -- The last parenthesis are not needed. They are put there just for the sake of -- clarity. faco :: (Int -> Int) -> (Int -> Int) faco _ 1 = 1 faco r n = n * r (n - 1) -- How do we make 'fac' to call itself?, remember fix! -- -- > fix :: (a -> a) -> a -- -- Making a ~ Int -> Int gives -- -- > fix :: ((Int -> Int) -> (Int -> Int)) -> (Int -> Int) -- -- Then our factorial function becomes: -- fac :: Int -> Int fac = fix faco -- What just happened? -- -- > fix faco 5 -- > = { def. 'fix' } -- > faco (fix faco) 5 -- > = { def. 'faco'} -- > 5 * (fix faco) 4 -- > ... -- -- I hope you see what's happening now, and that you can prove by induction -- that @fix faco = facr@, where @facr@ is the factorial function defined using -- recursion. -- skimo :: (Int -> Int) -> Int -> Int skimo _ 1 = 1 skimo r n = faco r n - 1 skim :: Int -> Int skim = fix skimo
capitanbatata/sandbox
pw-fix/src/PwFix.hs
gpl-3.0
996
0
8
246
182
110
72
12
1
module Common ( test_selectBestCells_group, test_culturalComputation_group ) where import FRP.FrABS import SugarScape.Model import SugarScape.Common import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck as QC ------------------------------------------------------------------------------- -- cultural computation ------------------------------------------------------------------------------- test_culturalComputation_group = testGroup "flipCulturalTag" [test_calculateTribe] test_calculateTribe = QC.testProperty "flipCulturalTag " $ test_calculateTribeAux test_calculateTribeAux tagActive tagPassive i = -- TODO: QuickCheck is giving up because pre-conditions too strong, need to generate test-data somehow different (length tagActive == length tagPassive && i >= 0 && i < length tagActive) ==> flipCulturalTag tagActive tagPassive i == tagRequiredResult where tagPassiveFront = take i tagPassive tagPassiveBack = drop (i+1) tagPassive tagActiveAtIdx = tagActive !! i tagRequiredResult = tagPassiveFront ++ [tagActiveAtIdx] ++ tagPassiveBack ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- selectBestCells ------------------------------------------------------------------------------- {- Assuming the following cells layout with X is the reference coord (0,0) (1,0) (1,1) (0,1) X (2,1) (0,2) (1,2) (2,2) -} ------------------------------------------------------------------------------- test_selectBestCells_group = testGroup "selectBestCells bestSugarLevel" [test_selectBestCells_bestSugarLevel_empty, test_selectBestCells_bestSugarLevel_singlebestsamedist, test_selectBestCells_bestSugarLevel_multibestsamedist, test_selectBestCells_bestSugarLevel_singlebestdiffdist, test_selectBestCells_bestSugarLevel_allbestsamedist] test_selectBestCells_bestSugarLevel_empty = testCase "empty cells" $ do let bcs = selectBestCells bestMeasureSugarLevel (0,0) [] assertBool "cells should be empty" (null bcs) test_selectBestCells_bestSugarLevel_singlebestsamedist = testCase "single best same distances" $ do let cells = [((1,0), pc { sugEnvSugarLevel = 0 }), ((0,1), pc { sugEnvSugarLevel = 1 }), ((2,1), pc { sugEnvSugarLevel = 2 }), ((1,2), pc { sugEnvSugarLevel = 3 })] let bcs = selectBestCells bestMeasureSugarLevel (1,1) cells assertEqual "should return only 1 cell" 1 (length bcs) let (bcCoord, bc) = head bcs assertEqual "expected different cell" (1,2) bcCoord assertEqual "level does not match original level" 3 (sugEnvSugarLevel bc) test_selectBestCells_bestSugarLevel_multibestsamedist = testCase "multi best same distances" $ do let cells = [((1,0), pc { sugEnvSugarLevel = 4 }), ((0,1), pc { sugEnvSugarLevel = 1 }), ((2,1), pc { sugEnvSugarLevel = 2 }), ((1,2), pc { sugEnvSugarLevel = 4 })] let bcs = selectBestCells bestMeasureSugarLevel (1,1) cells assertEqual "should return 2 cells" 2 (length bcs) let ((bc1Coord, bc1):(bc2Coord, bc2):_) = bcs assertEqual "expected different cell 1" (1,0) bc1Coord assertEqual "level does not match original level of cell 1" 4 (sugEnvSugarLevel bc1) assertEqual "expected different cell 2" (1,2) bc2Coord assertEqual "level does not match original level of cell 2" 4 (sugEnvSugarLevel bc2) assertEqual "sugarlevels do not match although must be same" (sugEnvSugarLevel bc1) (sugEnvSugarLevel bc2) test_selectBestCells_bestSugarLevel_singlebestdiffdist = testCase "single best different distances" $ do let cells = [((1,10), pc { sugEnvSugarLevel = 4 }), ((0,1), pc { sugEnvSugarLevel = 1 }), ((2,1), pc { sugEnvSugarLevel = 2 }), ((1,2), pc { sugEnvSugarLevel = 4 })] let bcs = selectBestCells bestMeasureSugarLevel (1,1) cells assertEqual "should return only 1 cell" 1 (length bcs) let (bcCoord, bc) = head bcs assertEqual "expected different cell" (1,2) bcCoord assertEqual "level does not match original level" 4 (sugEnvSugarLevel bc) test_selectBestCells_bestSugarLevel_allbestsamedist = testCase "all best same distances" $ do let cells = [((1,0), pc { sugEnvSugarLevel = 1 }), ((0,1), pc { sugEnvSugarLevel = 1 }), ((2,1), pc { sugEnvSugarLevel = 1 }), ((1,2), pc { sugEnvSugarLevel = 1 })] let bcs = selectBestCells bestMeasureSugarLevel (1,1) cells assertEqual "should return 4 cells" 4 (length bcs) let ((bc1Coord, bc1):(bc2Coord, bc2):(bc3Coord, bc3):(bc4Coord, bc4):_) = bcs assertEqual "expected different cell 1" (1,0) bc1Coord assertEqual "level does not match original level of cell 1" 1 (sugEnvSugarLevel bc1) assertEqual "expected different cell 2" (0,1) bc2Coord assertEqual "level does not match original level of cell 2" 1 (sugEnvSugarLevel bc2) assertEqual "expected different cell 3" (2,1) bc3Coord assertEqual "level does not match original level of cell 1" 1 (sugEnvSugarLevel bc3) assertEqual "expected different cell 4" (1,2) bc4Coord assertEqual "level does not match original level of cell 2" 1 (sugEnvSugarLevel bc4) assertEqual "sugarlevels do not match although must be same" (sugEnvSugarLevel bc1) (sugEnvSugarLevel bc2) assertEqual "sugarlevels do not match although must be same" (sugEnvSugarLevel bc2) (sugEnvSugarLevel bc3) assertEqual "sugarlevels do not match although must be same" (sugEnvSugarLevel bc3) (sugEnvSugarLevel bc4) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- UTILS ------------------------------------------------------------------------------- -- a proto-cell pc = SugarScapeEnvCell { sugEnvSugarCapacity = 0, sugEnvSugarLevel = 0, sugEnvSpiceCapacity = 0, sugEnvSpiceLevel = 0, sugEnvPolutionLevel = 0, sugEnvOccupier = Nothing } -------------------------------------------------------------------------------
thalerjonathan/phd
coding/libraries/chimera/examples/ABS/SugarScape/Tests/Common.hs
gpl-3.0
6,522
0
16
1,407
1,392
762
630
94
1
module SCSI.Command.Inquiry ( Inquiry(..), DeviceType(..), inquiry ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad import qualified Data.ByteString as BS import Data.Word import Parser import SCSI data Inquiry = Inquiry { deviceType :: DeviceType, vendor :: String, product :: String, version :: String, serial :: String } deriving Show data DeviceType = DirectAccessBlock -- SBC-3 | SequentialAccessBlock -- SSC-3 | Printer -- SSC | Processor -- SPC-2 | WriteOnce -- SBC | MultiMedia -- MMC-6 | Scanner | OpticalMemory -- SBC | MediumChanger -- SMC-3 | Communications | ObsoleteA | ObsoleteB | StorageArrayController -- SCC-2 | EnclosureServices -- SES | SimplifiedDirectAccess -- RBC | OpticalCardReaderWriter -- OCRW | BrideControllerCommands -- BCC | ObjectBasedStorage -- OSD | AutomationDriveInterface -- ADC-2 | Reserved13 | Reserved14 | Reserved15 | Reserved16 | Reserved17 | Reserved18 | Reserved19 | Reserved1A | Reserved1B | Reserved1C | Reserved1D | WellKnownLogicalUnit | Unknown deriving (Enum, Show) parseInquiry :: Parser Inquiry parseInquiry = do [deviceType, _] <- bits8 [5,3] replicateM 7 word8 vendor <- ascii 8 product <- ascii 16 version <- ascii 4 serial <- ascii 8 return $ Inquiry (toEnum (fromIntegral deviceType)) vendor product version serial inquiry :: ScsiDevice -> IO Inquiry inquiry device = do Left res <- commandR device 65536 [0x12, 0x00, 0x00, 0x00, 0xff, 0x00] return (runParser parseInquiry res)
ruudkoot/odin
src/SCSI/Command/Inquiry.hs
gpl-3.0
1,967
0
12
724
417
247
170
64
1
module Model.Kind ( Kinded(..) ) where import Data.String (IsString) -- | Types with a self-describing short name for their type class Kinded a where kindOf :: IsString s => a -> s
databrary/databrary
src/Model/Kind.hs
agpl-3.0
189
0
8
40
51
29
22
5
0
{-# LANGUAGE LambdaCase #-} module Data.GI.CodeGen.Callable ( genCCallableWrapper , genDynamicCallableWrapper , ForeignSymbol(..) , ExposeClosures(..) , hOutType , skipRetVal , arrayLengths , arrayLengthsMap , callableSignature , Signature(..) , fixupCallerAllocates , callableHInArgs , callableHOutArgs , wrapMaybe , inArgInterfaces ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif import Control.Monad (forM, forM_, when, void) import Data.Bool (bool) import Data.List (nub, (\\)) import Data.Maybe (isJust) import Data.Monoid ((<>)) import Data.Tuple (swap) import Data.Typeable (TypeRep, typeOf) import qualified Data.Map as Map import qualified Data.Text as T import Data.Text (Text) import Data.GI.CodeGen.API import Data.GI.CodeGen.Code import Data.GI.CodeGen.Conversions import Data.GI.CodeGen.Haddock (deprecatedPragma, writeDocumentation, RelativeDocPosition(..), writeArgDocumentation, writeReturnDocumentation) import Data.GI.CodeGen.SymbolNaming import Data.GI.CodeGen.Transfer import Data.GI.CodeGen.Type import Data.GI.CodeGen.Util import Text.Show.Pretty (ppShow) -- | Whether to expose closures and the associated destroy notify -- handlers in the Haskell wrapper. data ExposeClosures = WithClosures | WithoutClosures hOutType :: Callable -> [Arg] -> ExcCodeGen TypeRep hOutType callable outArgs = do hReturnType <- case returnType callable of Nothing -> return $ typeOf () Just r -> if skipRetVal callable then return $ typeOf () else haskellType r hOutArgTypes <- forM outArgs $ \outarg -> wrapMaybe outarg >>= bool (haskellType (argType outarg)) (maybeT <$> haskellType (argType outarg)) nullableReturnType <- maybe (return False) typeIsNullable (returnType callable) let maybeHReturnType = if returnMayBeNull callable && not (skipRetVal callable) && nullableReturnType then maybeT hReturnType else hReturnType return $ case (outArgs, tshow maybeHReturnType) of ([], _) -> maybeHReturnType (_, "()") -> "(,)" `con` hOutArgTypes _ -> "(,)" `con` (maybeHReturnType : hOutArgTypes) -- | Generate a foreign import for the given C symbol. Return the name -- of the corresponding Haskell identifier. mkForeignImport :: Text -> Callable -> CodeGen Text mkForeignImport cSymbol callable = do line first indent $ do mapM_ (\a -> line =<< fArgStr a) (args callable) when (callableThrows callable) $ line $ padTo 40 "Ptr (Ptr GError) -> " <> "-- error" line =<< last return hSymbol where hSymbol = cSymbol first = "foreign import ccall \"" <> cSymbol <> "\" " <> hSymbol <> " :: " fArgStr arg = do ft <- foreignType $ argType arg let ft' = if direction arg == DirectionIn || argCallerAllocates arg then ft else ptr ft let start = tshow ft' <> " -> " return $ padTo 40 start <> "-- " <> (argCName arg) <> " : " <> tshow (argType arg) last = tshow <$> io <$> case returnType callable of Nothing -> return $ typeOf () Just r -> foreignType r -- | Make a wrapper for foreign `FunPtr`s of the given type. Return -- the name of the resulting dynamic Haskell wrapper. mkDynamicImport :: Text -> CodeGen Text mkDynamicImport typeSynonym = do line $ "foreign import ccall \"dynamic\" " <> dynamic <> " :: FunPtr " <> typeSynonym <> " -> " <> typeSynonym return dynamic where dynamic = "__dynamic_" <> typeSynonym -- | Given an argument to a function, return whether it should be -- wrapped in a maybe type (useful for nullable types). We do some -- sanity checking to make sure that the argument is actually nullable -- (a relatively common annotation mistake is to mix up (optional) -- with (nullable)). wrapMaybe :: Arg -> CodeGen Bool wrapMaybe arg = if mayBeNull arg then typeIsNullable (argType arg) else return False -- Given the list of arguments returns the list of constraints and the -- list of types in the signature. inArgInterfaces :: [Arg] -> ExcCodeGen ([Text], [Text]) inArgInterfaces inArgs = consAndTypes (['a'..'z'] \\ ['m']) inArgs where consAndTypes :: [Char] -> [Arg] -> ExcCodeGen ([Text], [Text]) consAndTypes _ [] = return ([], []) consAndTypes letters (arg:args) = do (ls, t, cons) <- argumentType letters $ argType arg t' <- wrapMaybe arg >>= bool (return t) (return $ "Maybe (" <> t <> ")") (restCons, restTypes) <- consAndTypes ls args return (cons <> restCons, t' : restTypes) -- Given a callable, return a list of (array, length) pairs, where in -- each pair "length" is the argument holding the length of the -- (non-zero-terminated, non-fixed size) C array. arrayLengthsMap :: Callable -> [(Arg, Arg)] -- List of (array, length) arrayLengthsMap callable = go (args callable) [] where go :: [Arg] -> [(Arg, Arg)] -> [(Arg, Arg)] go [] acc = acc go (a:as) acc = case argType a of TCArray False fixedSize length _ -> if fixedSize > -1 || length == -1 then go as acc else go as $ (a, (args callable)!!length) : acc _ -> go as acc -- Return the list of arguments of the callable that contain length -- arguments, including a possible length for the result of calling -- the function. arrayLengths :: Callable -> [Arg] arrayLengths callable = map snd (arrayLengthsMap callable) <> -- Often one of the arguments is just the length of -- the result. case returnType callable of Just (TCArray False (-1) length _) -> if length > -1 then [(args callable)!!length] else [] _ -> [] -- This goes through a list of [(a,b)], and tags every entry where the -- "b" field has occurred before with the value of "a" for which it -- occurred. (The first appearance is not tagged.) classifyDuplicates :: Ord b => [(a, b)] -> [(a, b, Maybe a)] classifyDuplicates args = doClassify Map.empty args where doClassify :: Ord b => Map.Map b a -> [(a, b)] -> [(a, b, Maybe a)] doClassify _ [] = [] doClassify found ((value, key):args) = (value, key, Map.lookup key found) : doClassify (Map.insert key value found) args -- Read the length of in array arguments from the corresponding -- Haskell objects. A subtlety is that sometimes a single length -- argument is expected from the C side to encode the length of -- various lists. Ideally we would encode this in the types, but the -- resulting API would be rather cumbersome. We insted perform runtime -- checks to make sure that the given lists have the same length. readInArrayLengths :: Name -> Callable -> [Arg] -> ExcCodeGen () readInArrayLengths name callable hInArgs = do let lengthMaps = classifyDuplicates $ arrayLengthsMap callable forM_ lengthMaps $ \(array, length, duplicate) -> when (array `elem` hInArgs) $ case duplicate of Nothing -> readInArrayLength array length Just previous -> checkInArrayLength name array length previous -- Read the length of an array into the corresponding variable. readInArrayLength :: Arg -> Arg -> ExcCodeGen () readInArrayLength array length = do let lvar = escapedArgName length avar = escapedArgName array wrapMaybe array >>= bool (do al <- computeArrayLength avar (argType array) line $ "let " <> lvar <> " = " <> al) (do line $ "let " <> lvar <> " = case " <> avar <> " of" indent $ indent $ do line $ "Nothing -> 0" let jarray = "j" <> ucFirst avar al <- computeArrayLength jarray (argType array) line $ "Just " <> jarray <> " -> " <> al) -- Check that the given array has a length equal to the given length -- variable. checkInArrayLength :: Name -> Arg -> Arg -> Arg -> ExcCodeGen () checkInArrayLength n array length previous = do let name = lowerName n funcName = namespace n <> "." <> name lvar = escapedArgName length avar = escapedArgName array expectedLength = avar <> "_expected_length_" pvar = escapedArgName previous wrapMaybe array >>= bool (do al <- computeArrayLength avar (argType array) line $ "let " <> expectedLength <> " = " <> al) (do line $ "let " <> expectedLength <> " = case " <> avar <> " of" indent $ indent $ do line $ "Nothing -> 0" let jarray = "j" <> ucFirst avar al <- computeArrayLength jarray (argType array) line $ "Just " <> jarray <> " -> " <> al) line $ "when (" <> expectedLength <> " /= " <> lvar <> ") $" indent $ line $ "error \"" <> funcName <> " : length of '" <> avar <> "' does not agree with that of '" <> pvar <> "'.\"" -- | Whether to skip the return value in the generated bindings. The -- C convention is that functions throwing an error and returning -- a gboolean set the boolean to TRUE iff there is no error, so -- the information is always implicit in whether we emit an -- exception or not, so the return value can be omitted from the -- generated bindings without loss of information (and omitting it -- gives rise to a nicer API). See -- https://bugzilla.gnome.org/show_bug.cgi?id=649657 skipRetVal :: Callable -> Bool skipRetVal callable = (skipReturn callable) || (callableThrows callable && returnType callable == Just (TBasicType TBoolean)) freeInArgs' :: (Arg -> Text -> Text -> ExcCodeGen [Text]) -> Callable -> Map.Map Text Text -> ExcCodeGen [Text] freeInArgs' freeFn callable nameMap = concat <$> actions where actions :: ExcCodeGen [[Text]] actions = forM (args callable) $ \arg -> case Map.lookup (escapedArgName arg) nameMap of Just name -> freeFn arg name $ -- Pass in the length argument in case it's needed. case argType arg of TCArray False (-1) (-1) _ -> undefined TCArray False (-1) length _ -> escapedArgName $ (args callable)!!length _ -> undefined Nothing -> badIntroError $ "freeInArgs: do not understand " <> tshow arg -- Return the list of actions freeing the memory associated with the -- callable variables. This is run if the call to the C function -- succeeds, if there is an error freeInArgsOnError below is called -- instead. freeInArgs = freeInArgs' freeInArg -- Return the list of actions freeing the memory associated with the -- callable variables. This is run in case there is an error during -- the call. freeInArgsOnError = freeInArgs' freeInArgOnError -- Marshall the haskell arguments into their corresponding C -- equivalents. omitted gives a list of DirectionIn arguments that -- should be ignored, as they will be dealt with separately. prepareArgForCall :: [Arg] -> Arg -> ExcCodeGen Text prepareArgForCall omitted arg = do callback <- findAPI (argType arg) >>= \case Just (APICallback c) -> return (Just c) _ -> return Nothing when (isJust callback && direction arg /= DirectionIn) $ notImplementedError "Only callbacks with DirectionIn are supported" case direction arg of DirectionIn -> if arg `elem` omitted then return . escapedArgName $ arg else case callback of Just c -> if callableThrows (cbCallable c) -- See [Note: Callables that throw] then return (escapedArgName arg) else prepareInCallback arg c Nothing -> prepareInArg arg DirectionInout -> prepareInoutArg arg DirectionOut -> prepareOutArg arg prepareInArg :: Arg -> ExcCodeGen Text prepareInArg arg = do let name = escapedArgName arg wrapMaybe arg >>= bool (convert name $ hToF (argType arg) (transfer arg)) (do let maybeName = "maybe" <> ucFirst name line $ maybeName <> " <- case " <> name <> " of" indent $ do line $ "Nothing -> return nullPtr" let jName = "j" <> ucFirst name line $ "Just " <> jName <> " -> do" indent $ do converted <- convert jName $ hToF (argType arg) (transfer arg) line $ "return " <> converted return maybeName) -- | Callbacks are a fairly special case, we treat them separately. prepareInCallback :: Arg -> Callback -> CodeGen Text prepareInCallback arg (Callback {cbCallable = cb}) = do let name = escapedArgName arg ptrName = "ptr" <> name scope = argScope arg (maker, wrapper, drop) <- case argType arg of TInterface tn@(Name _ n) -> do drop <- if callableHasClosures cb then Just <$> qualifiedSymbol (callbackDropClosures n) tn else return Nothing wrapper <- qualifiedSymbol (callbackHaskellToForeign n) tn maker <- qualifiedSymbol (callbackWrapperAllocator n) tn return (maker, wrapper, drop) _ -> terror $ "prepareInCallback : Not an interface! " <> T.pack (ppShow arg) when (scope == ScopeTypeAsync) $ do ft <- tshow <$> foreignType (argType arg) line $ ptrName <> " <- callocMem :: IO (Ptr (" <> ft <> "))" wrapMaybe arg >>= bool (do let name' = prime name p = if (scope == ScopeTypeAsync) then parenthesize $ "Just " <> ptrName else "Nothing" dropped = case drop of Just dropper -> parenthesize (dropper <> " " <> name) Nothing -> name line $ name' <> " <- " <> maker <> " " <> parenthesize (wrapper <> " " <> p <> " " <> dropped) when (scope == ScopeTypeAsync) $ line $ "poke " <> ptrName <> " " <> name' return name') (do let maybeName = "maybe" <> ucFirst name line $ maybeName <> " <- case " <> name <> " of" indent $ do line $ "Nothing -> return (castPtrToFunPtr nullPtr)" let jName = "j" <> ucFirst name jName' = prime jName line $ "Just " <> jName <> " -> do" indent $ do let p = if (scope == ScopeTypeAsync) then parenthesize $ "Just " <> ptrName else "Nothing" dropped = case drop of Just dropper -> parenthesize (dropper <> " " <> jName) Nothing -> jName line $ jName' <> " <- " <> maker <> " " <> parenthesize (wrapper <> " " <> p <> " " <> dropped) when (scope == ScopeTypeAsync) $ line $ "poke " <> ptrName <> " " <> jName' line $ "return " <> jName' return maybeName) prepareInoutArg :: Arg -> ExcCodeGen Text prepareInoutArg arg = do name' <- prepareInArg arg ft <- foreignType $ argType arg allocInfo <- typeAllocInfo (argType arg) case allocInfo of Just (TypeAllocInfo isBoxed n) -> do let allocator = if isBoxed then "callocBoxedBytes" else "callocBytes" wrapMaybe arg >>= bool (do name'' <- genConversion (prime name') $ literal $ M $ allocator <> " " <> tshow n <> " :: " <> tshow (io ft) line $ "memcpy " <> name'' <> " " <> name' <> " " <> tshow n return name'') -- The semantics of this case are somewhat undefined. (notImplementedError "Nullable inout structs not supported") Nothing -> do if argCallerAllocates arg then return name' else do name'' <- genConversion (prime name') $ literal $ M $ "allocMem :: " <> tshow (io $ ptr ft) line $ "poke " <> name'' <> " " <> name' return name'' prepareOutArg :: Arg -> ExcCodeGen Text prepareOutArg arg = do let name = escapedArgName arg ft <- foreignType $ argType arg if argCallerAllocates arg then do allocInfo <- typeAllocInfo (argType arg) case allocInfo of Just (TypeAllocInfo isBoxed n) -> do let allocator = if isBoxed then "callocBoxedBytes" else "callocBytes" genConversion name $ literal $ M $ allocator <> " " <> tshow n <> " :: " <> tshow (io ft) Nothing -> notImplementedError $ ("Don't know how to allocate \"" <> argCName arg <> "\" of type " <> tshow (argType arg)) else genConversion name $ literal $ M $ "allocMem :: " <> tshow (io $ ptr ft) -- Convert a non-zero terminated out array, stored in a variable -- named "aname", into the corresponding Haskell object. convertOutCArray :: Callable -> Type -> Text -> Map.Map Text Text -> Transfer -> (Text -> Text) -> ExcCodeGen Text convertOutCArray callable t@(TCArray False fixed length _) aname nameMap transfer primeLength = do if fixed > -1 then do unpacked <- convert aname $ unpackCArray (tshow fixed) t transfer -- Free the memory associated with the array freeContainerType transfer t aname undefined return unpacked else do when (length == -1) $ badIntroError $ "Unknown length for \"" <> aname <> "\"" let lname = escapedArgName $ (args callable)!!length lname' <- case Map.lookup lname nameMap of Just n -> return n Nothing -> badIntroError $ "Couldn't find out array length " <> lname let lname'' = primeLength lname' unpacked <- convert aname $ unpackCArray lname'' t transfer -- Free the memory associated with the array freeContainerType transfer t aname lname'' return unpacked -- Remove the warning, this should never be reached. convertOutCArray _ t _ _ _ _ = terror $ "convertOutCArray : unexpected " <> tshow t -- Read the array lengths for out arguments. readOutArrayLengths :: Callable -> Map.Map Text Text -> ExcCodeGen () readOutArrayLengths callable nameMap = do let lNames = nub $ map escapedArgName $ filter ((/= DirectionIn) . direction) $ arrayLengths callable forM_ lNames $ \lname -> do lname' <- case Map.lookup lname nameMap of Just n -> return n Nothing -> badIntroError $ "Couldn't find out array length " <> lname genConversion lname' $ apply $ M "peek" -- Touch DirectionIn arguments so we are sure that they exist when the -- C function was called. touchInArg :: Arg -> ExcCodeGen () touchInArg arg = when (direction arg /= DirectionOut) $ do let name = escapedArgName arg case elementType (argType arg) of Just a -> do managed <- isManaged a when managed $ wrapMaybe arg >>= bool (line $ "mapM_ touchManagedPtr " <> name) (line $ "whenJust " <> name <> " (mapM_ touchManagedPtr)") Nothing -> do managed <- isManaged (argType arg) when managed $ wrapMaybe arg >>= bool (line $ "touchManagedPtr " <> name) (line $ "whenJust " <> name <> " touchManagedPtr") -- Find the association between closure arguments and their -- corresponding callback. closureToCallbackMap :: Callable -> ExcCodeGen (Map.Map Int Arg) closureToCallbackMap callable = -- The introspection info does not specify the closure for destroy -- notify's associated with a callback, since it is implicitly the -- same one as the ScopeTypeNotify callback associated with the -- DestroyNotify. go (filter (not . (`elem` destroyers)) $ args callable) Map.empty where destroyers = map (args callable!!) . filter (/= -1) . map argDestroy $ args callable go :: [Arg] -> Map.Map Int Arg -> ExcCodeGen (Map.Map Int Arg) go [] m = return m go (arg:as) m = if argScope arg == ScopeTypeInvalid then go as m else case argClosure arg of (-1) -> go as m c -> case Map.lookup c m of Just _ -> notImplementedError $ "Closure for multiple callbacks unsupported" <> T.pack (ppShow arg) <> "\n" <> T.pack (ppShow callable) Nothing -> go as $ Map.insert c arg m -- user_data style arguments. prepareClosures :: Callable -> Map.Map Text Text -> ExcCodeGen () prepareClosures callable nameMap = do m <- closureToCallbackMap callable let closures = filter (/= -1) . map argClosure $ args callable forM_ closures $ \closure -> case Map.lookup closure m of Nothing -> badIntroError $ "Closure not found! " <> T.pack (ppShow callable) <> "\n" <> T.pack (ppShow m) <> "\n" <> tshow closure Just cb -> do let closureName = escapedArgName $ (args callable)!!closure n = escapedArgName cb n' <- case Map.lookup n nameMap of Just n -> return n Nothing -> badIntroError $ "Cannot find closure name!! " <> T.pack (ppShow callable) <> "\n" <> T.pack (ppShow nameMap) case argScope cb of ScopeTypeInvalid -> badIntroError $ "Invalid scope! " <> T.pack (ppShow callable) ScopeTypeNotified -> do line $ "let " <> closureName <> " = castFunPtrToPtr " <> n' case argDestroy cb of (-1) -> badIntroError $ "ScopeTypeNotified without destructor! " <> T.pack (ppShow callable) k -> let destroyName = escapedArgName $ (args callable)!!k in line $ "let " <> destroyName <> " = safeFreeFunPtrPtr" ScopeTypeAsync -> line $ "let " <> closureName <> " = nullPtr" ScopeTypeCall -> line $ "let " <> closureName <> " = nullPtr" freeCallCallbacks :: Callable -> Map.Map Text Text -> ExcCodeGen () freeCallCallbacks callable nameMap = forM_ (args callable) $ \arg -> do let name = escapedArgName arg name' <- case Map.lookup name nameMap of Just n -> return n Nothing -> badIntroError $ "Could not find " <> name <> " in " <> T.pack (ppShow callable) <> "\n" <> T.pack (ppShow nameMap) when (argScope arg == ScopeTypeCall) $ line $ "safeFreeFunPtr $ castFunPtrToPtr " <> name' -- | Format the signature of the Haskell binding for the `Callable`. formatHSignature :: Callable -> ForeignSymbol -> ExcCodeGen () formatHSignature callable symbol = do sig <- callableSignature callable symbol indent $ do let constraints = "B.CallStack.HasCallStack" : signatureConstraints sig line $ "(" <> T.intercalate ", " constraints <> ") =>" forM_ (zip ("" : repeat "-> ") (signatureArgTypes sig)) $ \(prefix, (maybeArg, t)) -> do line $ prefix <> t case maybeArg of Nothing -> return () Just arg -> writeArgDocumentation arg let resultPrefix = if null (signatureArgTypes sig) then "" else "-> " line $ resultPrefix <> signatureReturnType sig writeReturnDocumentation (signatureCallable sig) (skipRetVal callable) -- | Name for the first argument in dynamic wrappers (the `FunPtr`). funPtr :: Text funPtr = "__funPtr" -- | Signature for a callable. data Signature = Signature { signatureCallable :: Callable , signatureConstraints :: [Text] , signatureArgTypes :: [(Maybe Arg, Text)] , signatureReturnType :: Text } -- | The Haskell signature for the given callable. It returns a tuple -- ([constraints], [(type, argname)]). callableSignature :: Callable -> ForeignSymbol -> ExcCodeGen Signature callableSignature callable symbol = do let (hInArgs, _) = callableHInArgs callable (case symbol of KnownForeignSymbol _ -> WithoutClosures DynamicForeignSymbol _ -> WithClosures) (argConstraints, types) <- inArgInterfaces hInArgs let constraints = ("MonadIO m" : argConstraints) outType <- hOutType callable (callableHOutArgs callable) return $ Signature { signatureCallable = callable, signatureConstraints = constraints, signatureReturnType = tshow ("m" `con` [outType]), signatureArgTypes = case symbol of KnownForeignSymbol _ -> zip (map Just hInArgs) types DynamicForeignSymbol w -> zip (Nothing : map Just hInArgs) ("FunPtr " <> dynamicType w : types) } -- | "In" arguments for the given callable on the Haskell side, -- together with the omitted arguments. callableHInArgs :: Callable -> ExposeClosures -> ([Arg], [Arg]) callableHInArgs callable expose = let inArgs = filter ((/= DirectionOut) . direction) $ args callable -- We do not expose user_data arguments, -- destroynotify arguments, and C array length -- arguments to Haskell code. closures = map (args callable!!) . filter (/= -1) . map argClosure $ inArgs destroyers = map (args callable!!) . filter (/= -1) . map argDestroy $ inArgs omitted = case expose of WithoutClosures -> arrayLengths callable <> closures <> destroyers WithClosures -> arrayLengths callable in (filter (`notElem` omitted) inArgs, omitted) -- | "Out" arguments for the given callable on the Haskell side. callableHOutArgs :: Callable -> [Arg] callableHOutArgs callable = let outArgs = filter ((/= DirectionIn) . direction) $ args callable in filter (`notElem` (arrayLengths callable)) outArgs -- | Convert the result of the foreign call to Haskell. convertResult :: Name -> Callable -> Map.Map Text Text -> ExcCodeGen Text convertResult n callable nameMap = if skipRetVal callable || returnType callable == Nothing then return (error "convertResult: unreachable code reached, bug!") else do nullableReturnType <- maybe (return False) typeIsNullable (returnType callable) if returnMayBeNull callable && nullableReturnType then do line $ "maybeResult <- convertIfNonNull result $ \\result' -> do" indent $ do converted <- unwrappedConvertResult "result'" line $ "return " <> converted return "maybeResult" else do when nullableReturnType $ line $ "checkUnexpectedReturnNULL \"" <> lowerName n <> "\" result" unwrappedConvertResult "result" where unwrappedConvertResult rname = case returnType callable of -- Arrays without length information are just passed -- along. Just (TCArray False (-1) (-1) _) -> return rname -- Not zero-terminated C arrays require knowledge of the -- length, so we deal with them directly. Just (t@(TCArray False _ _ _)) -> convertOutCArray callable t rname nameMap (returnTransfer callable) prime Just t -> do result <- convert rname $ fToH t (returnTransfer callable) freeContainerType (returnTransfer callable) t rname undefined return result Nothing -> return (error "unwrappedConvertResult: bug!") -- | Marshal a foreign out argument to Haskell, returning the name of -- the variable containing the converted Haskell value. convertOutArg :: Callable -> Map.Map Text Text -> Arg -> ExcCodeGen Text convertOutArg callable nameMap arg = do let name = escapedArgName arg inName <- case Map.lookup name nameMap of Just name' -> return name' Nothing -> badIntroError $ "Parameter " <> name <> " not found!" case argType arg of -- Passed along as a raw pointer TCArray False (-1) (-1) _ -> if argCallerAllocates arg then return inName else genConversion inName $ apply $ M "peek" t@(TCArray False _ _ _) -> do aname' <- if argCallerAllocates arg then return inName else genConversion inName $ apply $ M "peek" let arrayLength = if argCallerAllocates arg then id else prime wrapArray a = convertOutCArray callable t a nameMap (transfer arg) arrayLength wrapMaybe arg >>= bool (wrapArray aname') (do line $ "maybe" <> ucFirst aname' <> " <- convertIfNonNull " <> aname' <> " $ \\" <> prime aname' <> " -> do" indent $ do wrapped <- wrapArray (prime aname') line $ "return " <> wrapped return $ "maybe" <> ucFirst aname') t -> do peeked <- if argCallerAllocates arg then return inName else genConversion inName $ apply $ M "peek" -- If we alloc we always take control of the resulting -- memory, otherwise we may leak. let transfer' = if argCallerAllocates arg then TransferEverything else transfer arg result <- do let wrap ptr = convert ptr $ fToH (argType arg) transfer' wrapMaybe arg >>= bool (wrap peeked) (do line $ "maybe" <> ucFirst peeked <> " <- convertIfNonNull " <> peeked <> " $ \\" <> prime peeked <> " -> do" indent $ do wrapped <- wrap (prime peeked) line $ "return " <> wrapped return $ "maybe" <> ucFirst peeked) -- Free the memory associated with the out argument freeContainerType transfer' t peeked undefined return result -- | Convert the list of out arguments to Haskell, returning the -- names of the corresponding variables containing the marshaled values. convertOutArgs :: Callable -> Map.Map Text Text -> [Arg] -> ExcCodeGen [Text] convertOutArgs callable nameMap hOutArgs = forM hOutArgs (convertOutArg callable nameMap) -- | Invoke the given C function, taking care of errors. invokeCFunction :: Callable -> ForeignSymbol -> [Text] -> CodeGen () invokeCFunction callable symbol argNames = do let returnBind = case returnType callable of Nothing -> "" _ -> if skipRetVal callable then "_ <- " else "result <- " maybeCatchGErrors = if callableThrows callable then "propagateGError $ " else "" call = case symbol of KnownForeignSymbol s -> s DynamicForeignSymbol w -> parenthesize (dynamicWrapper w <> " " <> funPtr) line $ returnBind <> maybeCatchGErrors <> call <> (T.concat . map (" " <>)) argNames -- | Return the result of the call, possibly including out arguments. returnResult :: Callable -> Text -> [Text] -> CodeGen () returnResult callable result pps = if skipRetVal callable || returnType callable == Nothing then case pps of [] -> line "return ()" (pp:[]) -> line $ "return " <> pp _ -> line $ "return (" <> T.intercalate ", " pps <> ")" else case pps of [] -> line $ "return " <> result _ -> line $ "return (" <> T.intercalate ", " (result : pps) <> ")" -- | Generate a Haskell wrapper for the given foreign function. genHaskellWrapper :: Name -> ForeignSymbol -> Callable -> ExposeClosures -> ExcCodeGen Text genHaskellWrapper n symbol callable expose = group $ do let name = case symbol of KnownForeignSymbol _ -> lowerName n DynamicForeignSymbol _ -> callbackDynamicWrapper (upperName n) (hInArgs, omitted) = callableHInArgs callable expose hOutArgs = callableHOutArgs callable line $ name <> " ::" formatHSignature callable symbol let argNames = case symbol of KnownForeignSymbol _ -> map escapedArgName hInArgs DynamicForeignSymbol _ -> funPtr : map escapedArgName hInArgs line $ name <> " " <> T.intercalate " " argNames <> " = liftIO $ do" indent (genWrapperBody n symbol callable hInArgs hOutArgs omitted) return name -- | Generate the body of the Haskell wrapper for the given foreign symbol. genWrapperBody :: Name -> ForeignSymbol -> Callable -> [Arg] -> [Arg] -> [Arg] -> ExcCodeGen () genWrapperBody n symbol callable hInArgs hOutArgs omitted = do readInArrayLengths n callable hInArgs inArgNames <- forM (args callable) $ \arg -> prepareArgForCall omitted arg -- Map from argument names to names passed to the C function let nameMap = Map.fromList $ flip zip inArgNames $ map escapedArgName $ args callable prepareClosures callable nameMap if callableThrows callable then do line "onException (do" indent $ do invokeCFunction callable symbol inArgNames readOutArrayLengths callable nameMap result <- convertResult n callable nameMap pps <- convertOutArgs callable nameMap hOutArgs freeCallCallbacks callable nameMap forM_ (args callable) touchInArg mapM_ line =<< freeInArgs callable nameMap returnResult callable result pps line " ) (do" indent $ do freeCallCallbacks callable nameMap actions <- freeInArgsOnError callable nameMap case actions of [] -> line $ "return ()" _ -> mapM_ line actions line " )" else do invokeCFunction callable symbol inArgNames readOutArrayLengths callable nameMap result <- convertResult n callable nameMap pps <- convertOutArgs callable nameMap hOutArgs freeCallCallbacks callable nameMap forM_ (args callable) touchInArg mapM_ line =<< freeInArgs callable nameMap returnResult callable result pps -- | caller-allocates arguments are arguments that the caller -- allocates, and the called function modifies. They are marked as -- 'out' argumens in the introspection data, we sometimes treat them -- as 'inout' arguments instead. The semantics are somewhat tricky: -- for memory management purposes they should be treated as "in" -- arguments, but from the point of view of the exposed API they -- should be treated as "out" or "inout". Unfortunately we cannot -- always just assume that they are purely "out", so in many cases the -- generated API is somewhat suboptimal (since the initial values are -- not important): for example for g_io_channel_read_chars the size of -- the buffer to read is determined by the caller-allocates -- argument. As a compromise, we assume that we can allocate anything -- that is not a TCArray of length determined by an argument. fixupCallerAllocates :: Callable -> Callable fixupCallerAllocates c = c{args = map (fixupLength . fixupDir) (args c)} where fixupDir :: Arg -> Arg fixupDir a = case argType a of TCArray _ _ l _ -> if argCallerAllocates a && l > -1 then a {direction = DirectionInout} else a _ -> a lengthsMap :: Map.Map Arg Arg lengthsMap = Map.fromList (map swap (arrayLengthsMap c)) -- Length arguments of caller-allocates arguments should be -- treated as "in". fixupLength :: Arg -> Arg fixupLength a = case Map.lookup a lengthsMap of Nothing -> a Just array -> if argCallerAllocates array then a {direction = DirectionIn} else a -- | The foreign symbol to wrap. It is either a foreign symbol wrapped -- in a foreign import, in which case we are given the name of the -- Haskell wrapper, or alternatively the information about a "dynamic" -- wrapper in scope. data ForeignSymbol = KnownForeignSymbol Text -- ^ Haskell symbol in scope. | DynamicForeignSymbol DynamicWrapper -- ^ Info about the dynamic wrapper. -- | Information about a dynamic wrapper. data DynamicWrapper = DynamicWrapper { dynamicWrapper :: Text -- ^ Haskell dynamic wrapper , dynamicType :: Text -- ^ Name of the type synonym for the -- type of the function to be wrapped. } -- | Some debug info for the callable. genCallableDebugInfo :: Callable -> CodeGen () genCallableDebugInfo callable = group $ do line $ "-- Args : " <> (tshow $ args callable) line $ "-- Lengths : " <> (tshow $ arrayLengths callable) line $ "-- returnType : " <> (tshow $ returnType callable) line $ "-- throws : " <> (tshow $ callableThrows callable) line $ "-- Skip return : " <> (tshow $ skipReturn callable) when (skipReturn callable && returnType callable /= Just (TBasicType TBoolean)) $ do line "-- XXX return value ignored, but it is not a boolean." line "-- This may be a memory leak?" -- | Generate a wrapper for a known C symbol. genCCallableWrapper :: Name -> Text -> Callable -> ExcCodeGen () genCCallableWrapper n cSymbol callable = do genCallableDebugInfo callable let callable' = fixupCallerAllocates callable hSymbol <- mkForeignImport cSymbol callable' blank deprecatedPragma (lowerName n) (callableDeprecated callable) writeDocumentation DocBeforeSymbol (callableDocumentation callable) void (genHaskellWrapper n (KnownForeignSymbol hSymbol) callable' WithoutClosures) -- | For callbacks we do not need to keep track of which arguments are -- closures. forgetClosures :: Callable -> Callable forgetClosures c = c {args = map forgetClosure (args c)} where forgetClosure :: Arg -> Arg forgetClosure arg = arg {argClosure = -1} -- | Generate a wrapper for a dynamic C symbol (i.e. a Haskell -- function that will invoke its first argument, which should be a -- `FunPtr` of the appropriate type). The caller should have created a -- type synonym with the right type for the foreign symbol. genDynamicCallableWrapper :: Name -> Text -> Callable -> ExcCodeGen Text genDynamicCallableWrapper n typeSynonym callable = do genCallableDebugInfo callable let callable' = forgetClosures (fixupCallerAllocates callable) wrapper <- mkDynamicImport typeSynonym blank let dyn = DynamicWrapper { dynamicWrapper = wrapper , dynamicType = typeSynonym } genHaskellWrapper n (DynamicForeignSymbol dyn) callable' WithClosures
ford-prefect/haskell-gi
lib/Data/GI/CodeGen/Callable.hs
lgpl-2.1
41,591
331
27
14,094
8,822
4,616
4,206
719
9
-- file "Ch04/InteractWith.hs" import System.Environment (getArgs) import Data.Char (toUpper, isUpper) import Data.List --(isPrefixOf, isSuffixOf, null, length, head, tail) --NOTE ghc --make InteractWith.hs produce the excutable file. --NOTE this is function as the first class. interactWith function inputFile outputFile = do input <- readFile inputFile let turn = function input writeFile outputFile turn mainWith function = do args <- getArgs case args of [input, output] -> interactWith function input output _ -> putStrLn "error input" main = mainWith myFunction where myFunction = id splitLines :: String -> [String] splitLines cs = let (pre, suf) = break isLineTerminator cs in pre : case suf of --NOTE ** ('\r': '\n' : rest) -> splitLines rest ('\r' : rest) -> splitLines rest ('\n' : rest) -> splitLines rest _ -> [] isLineTerminator c = c `elem` ['\r', '\n'] breakUpper cs = break isUpper cs fixLines :: String -> String fixLines input = unlines (splitLines input) fixInteract = interactWith fixLines --NOTE infix functions a `plus` b = a + b data a `Pair` b = a `Pair` b deriving (Show) -- we can use the constructor either prefix or infix,more like a operator foo = Pair 1 2 bar = True `Pair` "quux" infixOps = do let a = "abc" `isPrefixOf` "abcde" b = "de" `isSuffixOf` "abcde" print $ (a, b) --NOTE List Functions: length,null,head, tail, last, init, (++), concat, reverse,and, or, all, any listOps = do let xs = [1, 3..14] ys = splitAt 2 xs zs = takeWhile (< 3) xs hs = dropWhile (<= 3) xs a = 1 `elem` filter even xs b = zip "abcd" xs c = zipWith (+) ([1..]) xs print $ null xs print $ all (> 3) xs print $ all (>= 3) $ take 2 (tail xs) print $ any (< 2) $ drop 1 xs print $ span odd xs --NOTE Partial and total functions, head is partial for not handling [] myDumbExample xs = if length xs > 0 then head xs -- head [] will cause a Exception else 'Z' mySmartExample xs = if not (null xs) then head xs else 'Z' myOtherExample (x:_) = x myOtherExample [] = 'Z' --NOTE STRING functions str = unlines . lines wrd = unwords . words --NOTE Excersice safeListFunc func [] = Nothing safeListFunc func xs = Just (func xs) safeHead = safeListFunc head safeTail = safeListFunc tail safeLast = safeListFunc last safeInit = safeListFunc init splitWith :: (a -> Bool) -> [a] -> [[a]] splitWith _ [] = [] splitWith p xs | null r = [ok] | null ok = splitWith p (tail r) | otherwise = ok : splitWith p (tail r) where (ok, r) = span p xs firstWordOfEachLine :: String -> String firstWordOfEachLine = unlines . map (head . words) . lines --NOTE loop loop acc [] = acc loop acc (x:xs) = loop (acc * 10 + x) xs upperCase2 xs = map toUpper xs --NOTE left and right is associated with associative {-Both foldr and foldl consume the list from left to right, so that's not the reason we refer to foldl as "left fold". foldl _evaluates_ from left to right (left-associative) foldr _evaluates_ from right to left (right-associative)-} foldlD :: (a -> b -> a) -> a -> [b] -> a foldlD step zero (x:xs) = foldlD step (step zero x) xs foldlD _ zero [] = zero foldrD step zero (x:xs) = step x (foldrD step zero xs) foldrD _ zero [] = zero mysum xs = foldlD (+) 0 xs {-foldl (+) 0 (1:2:3:[]) == foldl (+) (0 + 1) (2:3:[]) == foldl (+) ((0 + 1) + 2) (3:[]) == foldl (+) (((0 + 1) + 2) + 3) [] == (((0 + 1) + 2) + 3) foldr (+) 0 (1:2:3:[]) == 1 + foldr (+) 0 (2:3:[]) == 1 + (2 + foldr (+) 0 (3:[]) == 1 + (2 + (3 + foldr (+) 0 [])) == 1 + (2 + (3 + 0)) -} --NOTE primitive recursive wicth can express as foldr myFilter p xs = foldr step [] xs where step x ys | p x = x : ys | otherwise = ys myMap p xs = foldr step [] xs where step x ys = p x : ys --NOTE these two expressions are worth thinking everyday. foldlR f lzero xs = foldrD step id xs lzero where step x g a = g (f a x) myFoldl :: (b -> a -> b) -> b -> [a] -> b myFoldl fl z xs = (foldr fr id xs) z where l `fr` r = r . (`fl` l) inf = [1..] init1 = take 3 inf
Numberartificial/Realworld-Haskell
code/Ch04/InteractWith.hs
apache-2.0
4,366
0
13
1,245
1,397
723
674
95
4
{-# OPTIONS -fno-warn-type-defaults #-} {-| Constants contains the Haskell constants The constants in this module are used in Haskell and are also converted to Python. Do not write any definitions in this file other than constants. Do not even write helper functions. The definitions in this module are automatically stripped to build the Makefile.am target 'ListConstants.hs'. If there are helper functions in this module, they will also be dragged and it will cause compilation to fail. Therefore, all helper functions should go to a separate module and imported. -} {- Copyright (C) 2013, 2014 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.Constants where import Control.Arrow ((***),(&&&)) import Data.List ((\\)) import Data.Map (Map) import qualified Data.Map as Map (empty, fromList, keys, insert) import Data.Monoid import qualified AutoConf import Ganeti.ConstantUtils (PythonChar(..), FrozenSet, Protocol(..), buildVersion) import qualified Ganeti.ConstantUtils as ConstantUtils import qualified Ganeti.HTools.Types as Types import Ganeti.HTools.Types (AutoRepairResult(..), AutoRepairType(..)) import Ganeti.Logging (SyslogUsage(..)) import qualified Ganeti.Logging as Logging (syslogUsageToRaw) import qualified Ganeti.Runtime as Runtime import Ganeti.Runtime (GanetiDaemon(..), MiscGroup(..), GanetiGroup(..), ExtraLogReason(..)) import Ganeti.THH (PyValueEx(..)) import Ganeti.Types import qualified Ganeti.Types as Types import Ganeti.Confd.Types (ConfdRequestType(..), ConfdReqField(..), ConfdReplyStatus(..), ConfdNodeRole(..), ConfdErrorType(..)) import qualified Ganeti.Confd.Types as Types import qualified Ganeti.HTools.Tags.Constants as Tags {-# ANN module "HLint: ignore Use camelCase" #-} -- * 'autoconf' constants for Python only ('autotools/build-bash-completion') htoolsProgs :: [String] htoolsProgs = AutoConf.htoolsProgs -- * 'autoconf' constants for Python only ('lib/constants.py') drbdBarriers :: String drbdBarriers = AutoConf.drbdBarriers drbdNoMetaFlush :: Bool drbdNoMetaFlush = AutoConf.drbdNoMetaFlush lvmStripecount :: Int lvmStripecount = AutoConf.lvmStripecount hasGnuLn :: Bool hasGnuLn = AutoConf.hasGnuLn -- * 'autoconf' constants for Python only ('lib/pathutils.py') -- ** Build-time constants exportDir :: String exportDir = AutoConf.exportDir backupDir :: String backupDir = AutoConf.backupDir osSearchPath :: [String] osSearchPath = AutoConf.osSearchPath esSearchPath :: [String] esSearchPath = AutoConf.esSearchPath sshConfigDir :: String sshConfigDir = AutoConf.sshConfigDir xenConfigDir :: String xenConfigDir = AutoConf.xenConfigDir sysconfdir :: String sysconfdir = AutoConf.sysconfdir toolsdir :: String toolsdir = AutoConf.toolsdir localstatedir :: String localstatedir = AutoConf.localstatedir -- ** Paths which don't change for a virtual cluster pkglibdir :: String pkglibdir = AutoConf.pkglibdir sharedir :: String sharedir = AutoConf.sharedir -- * 'autoconf' constants for Python only ('lib/build/sphinx_ext.py') manPages :: Map String Int manPages = Map.fromList AutoConf.manPages -- * 'autoconf' constants for QA cluster only ('qa/qa_cluster.py') versionedsharedir :: String versionedsharedir = AutoConf.versionedsharedir -- * 'autoconf' constants for Python only ('tests/py/docs_unittest.py') gntScripts :: [String] gntScripts = AutoConf.gntScripts -- * Various versions releaseVersion :: String releaseVersion = AutoConf.packageVersion versionMajor :: Int versionMajor = AutoConf.versionMajor versionMinor :: Int versionMinor = AutoConf.versionMinor versionRevision :: Int versionRevision = AutoConf.versionRevision dirVersion :: String dirVersion = AutoConf.dirVersion osApiV10 :: Int osApiV10 = 10 osApiV15 :: Int osApiV15 = 15 osApiV20 :: Int osApiV20 = 20 osApiVersions :: FrozenSet Int osApiVersions = ConstantUtils.mkSet [osApiV10, osApiV15, osApiV20] -- | The version of the backup/export instance description file format we are -- producing when exporting and accepting when importing. The two are currently -- tightly intertwined. exportVersion :: Int exportVersion = 0 rapiVersion :: Int rapiVersion = 2 configMajor :: Int configMajor = AutoConf.versionMajor configMinor :: Int configMinor = AutoConf.versionMinor -- | The configuration is supposed to remain stable across -- revisions. Therefore, the revision number is cleared to '0'. configRevision :: Int configRevision = 0 configVersion :: Int configVersion = buildVersion configMajor configMinor configRevision -- | Similarly to the configuration (see 'configRevision'), the -- protocols are supposed to remain stable across revisions. protocolVersion :: Int protocolVersion = buildVersion configMajor configMinor configRevision -- * User separation daemonsGroup :: String daemonsGroup = Runtime.daemonGroup (ExtraGroup DaemonsGroup) adminGroup :: String adminGroup = Runtime.daemonGroup (ExtraGroup AdminGroup) masterdUser :: String masterdUser = Runtime.daemonUser GanetiMasterd masterdGroup :: String masterdGroup = Runtime.daemonGroup (DaemonGroup GanetiMasterd) metadUser :: String metadUser = Runtime.daemonUser GanetiMetad metadGroup :: String metadGroup = Runtime.daemonGroup (DaemonGroup GanetiMetad) rapiUser :: String rapiUser = Runtime.daemonUser GanetiRapi rapiGroup :: String rapiGroup = Runtime.daemonGroup (DaemonGroup GanetiRapi) confdUser :: String confdUser = Runtime.daemonUser GanetiConfd confdGroup :: String confdGroup = Runtime.daemonGroup (DaemonGroup GanetiConfd) wconfdUser :: String wconfdUser = Runtime.daemonUser GanetiWConfd wconfdGroup :: String wconfdGroup = Runtime.daemonGroup (DaemonGroup GanetiWConfd) kvmdUser :: String kvmdUser = Runtime.daemonUser GanetiKvmd kvmdGroup :: String kvmdGroup = Runtime.daemonGroup (DaemonGroup GanetiKvmd) luxidUser :: String luxidUser = Runtime.daemonUser GanetiLuxid luxidGroup :: String luxidGroup = Runtime.daemonGroup (DaemonGroup GanetiLuxid) nodedUser :: String nodedUser = Runtime.daemonUser GanetiNoded nodedGroup :: String nodedGroup = Runtime.daemonGroup (DaemonGroup GanetiNoded) mondUser :: String mondUser = Runtime.daemonUser GanetiMond mondGroup :: String mondGroup = Runtime.daemonGroup (DaemonGroup GanetiMond) sshLoginUser :: String sshLoginUser = AutoConf.sshLoginUser sshConsoleUser :: String sshConsoleUser = AutoConf.sshConsoleUser -- * Cpu pinning separators and constants cpuPinningSep :: String cpuPinningSep = ":" cpuPinningAll :: String cpuPinningAll = "all" -- | Internal representation of "all" cpuPinningAllVal :: Int cpuPinningAllVal = -1 -- | One "all" entry in a CPU list means CPU pinning is off cpuPinningOff :: [Int] cpuPinningOff = [cpuPinningAllVal] -- | A Xen-specific implementation detail is that there is no way to -- actually say "use any cpu for pinning" in a Xen configuration file, -- as opposed to the command line, where you can say -- @ -- xm vcpu-pin <domain> <vcpu> all -- @ -- -- The workaround used in Xen is "0-63" (see source code function -- "xm_vcpu_pin" in @<xen-source>/tools/python/xen/xm/main.py@). -- -- To support future changes, the following constant is treated as a -- blackbox string that simply means "use any cpu for pinning under -- xen". cpuPinningAllXen :: String cpuPinningAllXen = "0-63" -- * Image and wipe ddCmd :: String ddCmd = "dd" -- | 1 MiB -- The default block size for the 'dd' command ddBlockSize :: Int ddBlockSize = 1024^2 -- | 1GB maxWipeChunk :: Int maxWipeChunk = 1024 minWipeChunkPercent :: Int minWipeChunkPercent = 10 -- * Directories runDirsMode :: Int runDirsMode = 0o775 secureDirMode :: Int secureDirMode = 0o700 secureFileMode :: Int secureFileMode = 0o600 adoptableBlockdevRoot :: String adoptableBlockdevRoot = "/dev/disk/" -- * 'autoconf' enable/disable enableMond :: Bool enableMond = AutoConf.enableMond enableMetad :: Bool enableMetad = AutoConf.enableMetad enableRestrictedCommands :: Bool enableRestrictedCommands = AutoConf.enableRestrictedCommands -- * SSH constants ssh :: String ssh = "ssh" scp :: String scp = "scp" -- * Daemons confd :: String confd = Runtime.daemonName GanetiConfd masterd :: String masterd = Runtime.daemonName GanetiMasterd metad :: String metad = Runtime.daemonName GanetiMetad mond :: String mond = Runtime.daemonName GanetiMond maintd :: String maintd = Runtime.daemonName GanetiMaintd noded :: String noded = Runtime.daemonName GanetiNoded wconfd :: String wconfd = Runtime.daemonName GanetiWConfd luxid :: String luxid = Runtime.daemonName GanetiLuxid rapi :: String rapi = Runtime.daemonName GanetiRapi kvmd :: String kvmd = Runtime.daemonName GanetiKvmd -- Set of daemons which only run on the master. -- Keep in sync with the 'daemon-util' script. daemonsMaster :: FrozenSet String daemonsMaster = ConstantUtils.mkSet [wconfd, luxid, rapi] daemons :: FrozenSet String daemons = ConstantUtils.mkSet $ map Runtime.daemonName [minBound .. maxBound] defaultConfdPort :: Int defaultConfdPort = 1814 defaultMondPort :: Int defaultMondPort = 1815 defaultMaintdPort :: Int defaultMaintdPort = 1816 defaultMetadPort :: Int defaultMetadPort = 80 defaultNodedPort :: Int defaultNodedPort = 1811 defaultRapiPort :: Int defaultRapiPort = 5080 daemonsPorts :: Map String (Protocol, Int) daemonsPorts = Map.fromList [ (confd, (Udp, defaultConfdPort)) , (metad, (Tcp, defaultMetadPort)) , (mond, (Tcp, defaultMondPort)) , (maintd, (Tcp, defaultMaintdPort)) , (noded, (Tcp, defaultNodedPort)) , (rapi, (Tcp, defaultRapiPort)) , (ssh, (Tcp, 22)) ] firstDrbdPort :: Int firstDrbdPort = 11000 lastDrbdPort :: Int lastDrbdPort = 14999 daemonsLogbase :: Map String String daemonsLogbase = Map.fromList [ (Runtime.daemonName d, Runtime.daemonLogBase d) | d <- [minBound..] ] daemonsExtraLogbase :: Map String (Map String String) daemonsExtraLogbase = Map.fromList $ map (Runtime.daemonName *** id) [ (GanetiMond, Map.fromList [ ("access", Runtime.daemonsExtraLogbase GanetiMond AccessLog) , ("error", Runtime.daemonsExtraLogbase GanetiMond ErrorLog) ]) ] extraLogreasonAccess :: String extraLogreasonAccess = Runtime.daemonsExtraLogbase GanetiMond AccessLog extraLogreasonError :: String extraLogreasonError = Runtime.daemonsExtraLogbase GanetiMond ErrorLog devConsole :: String devConsole = ConstantUtils.devConsole procMounts :: String procMounts = "/proc/mounts" -- * Luxi (Local UniX Interface) related constants luxiEom :: PythonChar luxiEom = PythonChar '\x03' -- | Environment variable for the luxi override socket luxiOverride :: String luxiOverride = "FORCE_LUXI_SOCKET" luxiOverrideMaster :: String luxiOverrideMaster = "master" luxiOverrideQuery :: String luxiOverrideQuery = "query" luxiVersion :: Int luxiVersion = configVersion -- * Syslog syslogUsage :: String syslogUsage = AutoConf.syslogUsage syslogNo :: String syslogNo = Logging.syslogUsageToRaw SyslogNo syslogYes :: String syslogYes = Logging.syslogUsageToRaw SyslogYes syslogOnly :: String syslogOnly = Logging.syslogUsageToRaw SyslogOnly syslogSocket :: String syslogSocket = "/dev/log" exportConfFile :: String exportConfFile = "config.ini" -- * Xen xenBootloader :: String xenBootloader = AutoConf.xenBootloader xenCmdXl :: String xenCmdXl = "xl" xenCmdXm :: String xenCmdXm = "xm" xenInitrd :: String xenInitrd = AutoConf.xenInitrd xenKernel :: String xenKernel = AutoConf.xenKernel xlSocatCmd :: String xlSocatCmd = "socat -b524288 - TCP:%s:%d #" xlMigrationPidfile :: String xlMigrationPidfile = "socat.pid" -- FIXME: perhaps rename to 'validXenCommands' for consistency with -- other constants knownXenCommands :: FrozenSet String knownXenCommands = ConstantUtils.mkSet [xenCmdXl, xenCmdXm] -- * KVM and socat kvmPath :: String kvmPath = AutoConf.kvmPath kvmKernel :: String kvmKernel = AutoConf.kvmKernel socatEscapeCode :: String socatEscapeCode = "0x1d" socatPath :: String socatPath = AutoConf.socatPath socatUseCompress :: Bool socatUseCompress = AutoConf.socatUseCompress socatUseEscape :: Bool socatUseEscape = AutoConf.socatUseEscape -- * LXC -- If you are trying to change the value of these default constants, you also -- need to edit the default value declaration in man/gnt-instance.rst. lxcDevicesDefault :: String lxcDevicesDefault = "c 1:3 rw" -- /dev/null ++ ",c 1:5 rw" -- /dev/zero ++ ",c 1:7 rw" -- /dev/full ++ ",c 1:8 rw" -- /dev/random ++ ",c 1:9 rw" -- /dev/urandom ++ ",c 1:10 rw" -- /dev/aio ++ ",c 5:0 rw" -- /dev/tty ++ ",c 5:1 rw" -- /dev/console ++ ",c 5:2 rw" -- /dev/ptmx ++ ",c 136:* rw" -- first block of Unix98 PTY slaves lxcDropCapabilitiesDefault :: String lxcDropCapabilitiesDefault = "mac_override" -- Allow MAC configuration or state changes ++ ",sys_boot" -- Use reboot(2) and kexec_load(2) ++ ",sys_module" -- Load and unload kernel modules ++ ",sys_time" -- Set system clock, set real-time (hardware) clock ++ ",sys_admin" -- Various system administration operations lxcStateRunning :: String lxcStateRunning = "RUNNING" -- * Console types -- | Display a message for console access consMessage :: String consMessage = "msg" -- | Console as SPICE server consSpice :: String consSpice = "spice" -- | Console as SSH command consSsh :: String consSsh = "ssh" -- | Console as VNC server consVnc :: String consVnc = "vnc" consAll :: FrozenSet String consAll = ConstantUtils.mkSet [consMessage, consSpice, consSsh, consVnc] -- | RSA key bit length -- -- For RSA keys more bits are better, but they also make operations -- more expensive. NIST SP 800-131 recommends a minimum of 2048 bits -- from the year 2010 on. rsaKeyBits :: Int rsaKeyBits = 2048 -- | Ciphers allowed for SSL connections. -- -- For the format, see ciphers(1). A better way to disable ciphers -- would be to use the exclamation mark (!), but socat versions below -- 1.5 can't parse exclamation marks in options properly. When -- modifying the ciphers, ensure not to accidentially add something -- after it's been removed. Use the "openssl" utility to check the -- allowed ciphers, e.g. "openssl ciphers -v HIGH:-DES". opensslCiphers :: String opensslCiphers = "HIGH:-DES:-3DES:-EXPORT:-DH" -- * X509 -- | commonName (CN) used in certificates x509CertCn :: String x509CertCn = "ganeti.example.com" -- | Default validity of certificates in days x509CertDefaultValidity :: Int x509CertDefaultValidity = 365 * 5 x509CertSignatureHeader :: String x509CertSignatureHeader = "X-Ganeti-Signature" -- | Digest used to sign certificates ("openssl x509" uses SHA1 by default) x509CertSignDigest :: String x509CertSignDigest = "SHA1" -- * Import/export daemon mode iemExport :: String iemExport = "export" iemImport :: String iemImport = "import" -- * Import/export transport compression iecGzip :: String iecGzip = "gzip" iecGzipFast :: String iecGzipFast = "gzip-fast" iecGzipSlow :: String iecGzipSlow = "gzip-slow" iecLzop :: String iecLzop = "lzop" iecNone :: String iecNone = "none" iecAll :: [String] iecAll = [iecGzip, iecGzipFast, iecGzipSlow, iecLzop, iecNone] iecDefaultTools :: [String] iecDefaultTools = [iecGzip, iecGzipFast, iecGzipSlow] iecCompressionUtilities :: Map String String iecCompressionUtilities = Map.fromList [ (iecGzipFast, iecGzip) , (iecGzipSlow, iecGzip) ] ieCustomSize :: String ieCustomSize = "fd" -- * Import/export I/O -- | Direct file I/O, equivalent to a shell's I/O redirection using -- '<' or '>' ieioFile :: String ieioFile = "file" -- | Raw block device I/O using "dd" ieioRawDisk :: String ieioRawDisk = "raw" -- | OS definition import/export script ieioScript :: String ieioScript = "script" -- * Values valueDefault :: String valueDefault = "default" valueAuto :: String valueAuto = "auto" valueGenerate :: String valueGenerate = "generate" valueNone :: String valueNone = "none" valueTrue :: String valueTrue = "true" valueFalse :: String valueFalse = "false" -- * Hooks hooksNameCfgupdate :: String hooksNameCfgupdate = "config-update" hooksNameWatcher :: String hooksNameWatcher = "watcher" hooksPath :: String hooksPath = "/sbin:/bin:/usr/sbin:/usr/bin" hooksPhasePost :: String hooksPhasePost = "post" hooksPhasePre :: String hooksPhasePre = "pre" hooksVersion :: Int hooksVersion = 2 -- * Global hooks related constants globalHooksDir :: String globalHooksDir = "global" globalHooksMaster :: String globalHooksMaster = "master" globalHooksNotMaster :: String globalHooksNotMaster = "not_master" postHooksStatusSuccess :: String postHooksStatusSuccess = "success" postHooksStatusError :: String postHooksStatusError = "error" postHooksStatusDisappeared :: String postHooksStatusDisappeared = "disappeared" -- * Hooks subject type (what object type does the LU deal with) htypeCluster :: String htypeCluster = "CLUSTER" htypeGroup :: String htypeGroup = "GROUP" htypeInstance :: String htypeInstance = "INSTANCE" htypeNetwork :: String htypeNetwork = "NETWORK" htypeNode :: String htypeNode = "NODE" -- * Hkr hkrSkip :: Int hkrSkip = 0 hkrFail :: Int hkrFail = 1 hkrSuccess :: Int hkrSuccess = 2 -- * Storage types stBlock :: String stBlock = Types.storageTypeToRaw StorageBlock stDiskless :: String stDiskless = Types.storageTypeToRaw StorageDiskless stExt :: String stExt = Types.storageTypeToRaw StorageExt stFile :: String stFile = Types.storageTypeToRaw StorageFile stSharedFile :: String stSharedFile = Types.storageTypeToRaw StorageSharedFile stGluster :: String stGluster = Types.storageTypeToRaw StorageGluster stLvmPv :: String stLvmPv = Types.storageTypeToRaw StorageLvmPv stLvmVg :: String stLvmVg = Types.storageTypeToRaw StorageLvmVg stRados :: String stRados = Types.storageTypeToRaw StorageRados storageTypes :: FrozenSet String storageTypes = ConstantUtils.mkSet $ map Types.storageTypeToRaw [minBound..] -- | The set of storage types for which full storage reporting is available stsReport :: FrozenSet String stsReport = ConstantUtils.mkSet [stFile, stLvmPv, stLvmVg] -- | The set of storage types for which node storage reporting is available -- | (as used by LUQueryNodeStorage) stsReportNodeStorage :: FrozenSet String stsReportNodeStorage = ConstantUtils.union stsReport $ ConstantUtils.mkSet [ stSharedFile , stGluster ] -- * Storage fields -- ** First two are valid in LU context only, not passed to backend sfNode :: String sfNode = "node" sfType :: String sfType = "type" -- ** and the rest are valid in backend sfAllocatable :: String sfAllocatable = Types.storageFieldToRaw SFAllocatable sfFree :: String sfFree = Types.storageFieldToRaw SFFree sfName :: String sfName = Types.storageFieldToRaw SFName sfSize :: String sfSize = Types.storageFieldToRaw SFSize sfUsed :: String sfUsed = Types.storageFieldToRaw SFUsed validStorageFields :: FrozenSet String validStorageFields = ConstantUtils.mkSet $ map Types.storageFieldToRaw [minBound..] ++ [sfNode, sfType] modifiableStorageFields :: Map String (FrozenSet String) modifiableStorageFields = Map.fromList [(Types.storageTypeToRaw StorageLvmPv, ConstantUtils.mkSet [sfAllocatable])] -- * Storage operations soFixConsistency :: String soFixConsistency = "fix-consistency" validStorageOperations :: Map String (FrozenSet String) validStorageOperations = Map.fromList [(Types.storageTypeToRaw StorageLvmVg, ConstantUtils.mkSet [soFixConsistency])] -- * Volume fields vfDev :: String vfDev = "dev" vfInstance :: String vfInstance = "instance" vfName :: String vfName = "name" vfNode :: String vfNode = "node" vfPhys :: String vfPhys = "phys" vfSize :: String vfSize = "size" vfVg :: String vfVg = "vg" -- * Local disk status ldsFaulty :: Int ldsFaulty = Types.localDiskStatusToRaw DiskStatusFaulty ldsOkay :: Int ldsOkay = Types.localDiskStatusToRaw DiskStatusOk ldsUnknown :: Int ldsUnknown = Types.localDiskStatusToRaw DiskStatusUnknown ldsSync :: Int ldsSync = Types.localDiskStatusToRaw DiskStatusSync ldsNames :: Map Int String ldsNames = Map.fromList [ (Types.localDiskStatusToRaw ds, localDiskStatusName ds) | ds <- [minBound..] ] -- * Disk template types dtDiskless :: String dtDiskless = Types.diskTemplateToRaw DTDiskless dtFile :: String dtFile = Types.diskTemplateToRaw DTFile dtSharedFile :: String dtSharedFile = Types.diskTemplateToRaw DTSharedFile dtPlain :: String dtPlain = Types.diskTemplateToRaw DTPlain dtBlock :: String dtBlock = Types.diskTemplateToRaw DTBlock dtDrbd8 :: String dtDrbd8 = Types.diskTemplateToRaw DTDrbd8 dtRbd :: String dtRbd = Types.diskTemplateToRaw DTRbd dtExt :: String dtExt = Types.diskTemplateToRaw DTExt dtGluster :: String dtGluster = Types.diskTemplateToRaw DTGluster dtMixed :: String dtMixed = "mixed" -- | This is used to order determine the default disk template when -- the list of enabled disk templates is inferred from the current -- state of the cluster. This only happens on an upgrade from a -- version of Ganeti that did not support the 'enabled_disk_templates' -- so far. diskTemplatePreference :: [String] diskTemplatePreference = map Types.diskTemplateToRaw [DTBlock, DTDiskless, DTDrbd8, DTExt, DTFile, DTPlain, DTRbd, DTSharedFile, DTGluster] diskTemplates :: FrozenSet String diskTemplates = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [minBound..] -- | Disk templates that are enabled by default defaultEnabledDiskTemplates :: [String] defaultEnabledDiskTemplates = map Types.diskTemplateToRaw [DTDrbd8, DTPlain] -- | Mapping of disk templates to storage types mapDiskTemplateStorageType :: Map String String mapDiskTemplateStorageType = Map.fromList $ map ( Types.diskTemplateToRaw &&& Types.storageTypeToRaw . diskTemplateToStorageType) [minBound..maxBound] -- | The set of network-mirrored disk templates dtsIntMirror :: FrozenSet String dtsIntMirror = ConstantUtils.mkSet [dtDrbd8] -- | 'DTDiskless' is 'trivially' externally mirrored dtsExtMirror :: FrozenSet String dtsExtMirror = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTDiskless, DTBlock, DTExt, DTSharedFile, DTRbd, DTGluster] -- | The set of non-lvm-based disk templates dtsNotLvm :: FrozenSet String dtsNotLvm = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTSharedFile, DTDiskless, DTBlock, DTExt, DTFile, DTRbd, DTGluster] -- | The set of disk templates which can be grown dtsGrowable :: FrozenSet String dtsGrowable = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTSharedFile, DTDrbd8, DTPlain, DTExt, DTFile, DTRbd, DTGluster] -- | The set of disk templates that allow adoption dtsMayAdopt :: FrozenSet String dtsMayAdopt = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTBlock, DTPlain] -- | The set of disk templates that *must* use adoption dtsMustAdopt :: FrozenSet String dtsMustAdopt = ConstantUtils.mkSet [Types.diskTemplateToRaw DTBlock] -- | The set of disk templates that allow migrations dtsMirrored :: FrozenSet String dtsMirrored = dtsIntMirror `ConstantUtils.union` dtsExtMirror -- | The set of file based disk templates dtsFilebased :: FrozenSet String dtsFilebased = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTSharedFile, DTFile, DTGluster] -- | The set of file based disk templates whose path is tied to the instance -- name dtsInstanceDependentPath :: FrozenSet String dtsInstanceDependentPath = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTSharedFile, DTFile] -- | The set of disk templates that can be moved by copying -- -- Note: a requirement is that they're not accessed externally or -- shared between nodes; in particular, sharedfile is not suitable. dtsCopyable :: FrozenSet String dtsCopyable = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTPlain, DTFile] -- | The set of disk templates which can be snapshot. dtsSnapshotCapable :: FrozenSet String dtsSnapshotCapable = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTPlain, DTDrbd8, DTExt] -- | The set of disk templates that are supported by exclusive_storage dtsExclStorage :: FrozenSet String dtsExclStorage = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTPlain] -- | Templates for which we don't perform checks on free space dtsNoFreeSpaceCheck :: FrozenSet String dtsNoFreeSpaceCheck = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTExt, DTSharedFile, DTFile, DTRbd, DTGluster] dtsBlock :: FrozenSet String dtsBlock = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTPlain, DTDrbd8, DTBlock, DTRbd, DTExt] -- | The set of lvm-based disk templates dtsLvm :: FrozenSet String dtsLvm = diskTemplates `ConstantUtils.difference` dtsNotLvm -- | The set of lvm-based disk templates dtsHaveAccess :: FrozenSet String dtsHaveAccess = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTRbd, DTGluster, DTExt] -- | The set of disk templates that cannot convert from dtsNotConvertibleFrom :: FrozenSet String dtsNotConvertibleFrom = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTDiskless] -- | The set of disk templates that cannot convert to dtsNotConvertibleTo :: FrozenSet String dtsNotConvertibleTo = ConstantUtils.mkSet $ map Types.diskTemplateToRaw [DTDiskless, DTBlock] -- * Drbd drbdHmacAlg :: String drbdHmacAlg = "md5" drbdDefaultNetProtocol :: String drbdDefaultNetProtocol = "C" drbdMigrationNetProtocol :: String drbdMigrationNetProtocol = "C" drbdStatusFile :: String drbdStatusFile = "/proc/drbd" -- | The length of generated DRBD secrets (see also TempRes module). drbdSecretLength :: Int drbdSecretLength = 20 -- | Size of DRBD meta block device drbdMetaSize :: Int drbdMetaSize = 128 -- * Drbd barrier types drbdBDiskBarriers :: String drbdBDiskBarriers = "b" drbdBDiskDrain :: String drbdBDiskDrain = "d" drbdBDiskFlush :: String drbdBDiskFlush = "f" drbdBNone :: String drbdBNone = "n" -- | Valid barrier combinations: "n" or any non-null subset of "bfd" drbdValidBarrierOpt :: FrozenSet (FrozenSet String) drbdValidBarrierOpt = ConstantUtils.mkSet [ ConstantUtils.mkSet [drbdBNone] , ConstantUtils.mkSet [drbdBDiskBarriers] , ConstantUtils.mkSet [drbdBDiskDrain] , ConstantUtils.mkSet [drbdBDiskFlush] , ConstantUtils.mkSet [drbdBDiskDrain, drbdBDiskFlush] , ConstantUtils.mkSet [drbdBDiskBarriers, drbdBDiskDrain] , ConstantUtils.mkSet [drbdBDiskBarriers, drbdBDiskFlush] , ConstantUtils.mkSet [drbdBDiskBarriers, drbdBDiskFlush, drbdBDiskDrain] ] -- | Rbd tool command rbdCmd :: String rbdCmd = "rbd" -- * File backend driver fdBlktap :: String fdBlktap = Types.fileDriverToRaw FileBlktap fdBlktap2 :: String fdBlktap2 = Types.fileDriverToRaw FileBlktap2 fdLoop :: String fdLoop = Types.fileDriverToRaw FileLoop fdDefault :: String fdDefault = fdLoop fileDriver :: FrozenSet String fileDriver = ConstantUtils.mkSet $ map Types.fileDriverToRaw [minBound..] -- | The set of drbd-like disk types dtsDrbd :: FrozenSet String dtsDrbd = ConstantUtils.mkSet [Types.diskTemplateToRaw DTDrbd8] -- * Disk access mode diskRdonly :: String diskRdonly = Types.diskModeToRaw DiskRdOnly diskRdwr :: String diskRdwr = Types.diskModeToRaw DiskRdWr diskAccessSet :: FrozenSet String diskAccessSet = ConstantUtils.mkSet $ map Types.diskModeToRaw [minBound..] -- * Disk replacement mode replaceDiskAuto :: String replaceDiskAuto = Types.replaceDisksModeToRaw ReplaceAuto replaceDiskChg :: String replaceDiskChg = Types.replaceDisksModeToRaw ReplaceNewSecondary replaceDiskPri :: String replaceDiskPri = Types.replaceDisksModeToRaw ReplaceOnPrimary replaceDiskSec :: String replaceDiskSec = Types.replaceDisksModeToRaw ReplaceOnSecondary replaceModes :: FrozenSet String replaceModes = ConstantUtils.mkSet $ map Types.replaceDisksModeToRaw [minBound..] -- * Instance export mode exportModeLocal :: String exportModeLocal = Types.exportModeToRaw ExportModeLocal exportModeRemote :: String exportModeRemote = Types.exportModeToRaw ExportModeRemote exportModes :: FrozenSet String exportModes = ConstantUtils.mkSet $ map Types.exportModeToRaw [minBound..] -- * Instance creation modes instanceCreate :: String instanceCreate = Types.instCreateModeToRaw InstCreate instanceImport :: String instanceImport = Types.instCreateModeToRaw InstImport instanceRemoteImport :: String instanceRemoteImport = Types.instCreateModeToRaw InstRemoteImport instanceCreateModes :: FrozenSet String instanceCreateModes = ConstantUtils.mkSet $ map Types.instCreateModeToRaw [minBound..] -- * Remote import/export handshake message and version rieHandshake :: String rieHandshake = "Hi, I'm Ganeti" rieVersion :: Int rieVersion = 0 -- | Remote import/export certificate validity (seconds) rieCertValidity :: Int rieCertValidity = 24 * 60 * 60 -- | Export only: how long to wait per connection attempt (seconds) rieConnectAttemptTimeout :: Int rieConnectAttemptTimeout = 20 -- | Export only: number of attempts to connect rieConnectRetries :: Int rieConnectRetries = 10 -- | Overall timeout for establishing connection rieConnectTimeout :: Int rieConnectTimeout = 180 -- | Give child process up to 5 seconds to exit after sending a signal childLingerTimeout :: Double childLingerTimeout = 5.0 -- * Import/export config options inisectBep :: String inisectBep = "backend" inisectExp :: String inisectExp = "export" inisectHyp :: String inisectHyp = "hypervisor" inisectIns :: String inisectIns = "instance" inisectOsp :: String inisectOsp = "os" inisectOspPrivate :: String inisectOspPrivate = "os_private" -- * Dynamic device modification ddmAdd :: String ddmAdd = Types.ddmFullToRaw DdmFullAdd ddmAttach :: String ddmAttach = Types.ddmFullToRaw DdmFullAttach ddmModify :: String ddmModify = Types.ddmFullToRaw DdmFullModify ddmRemove :: String ddmRemove = Types.ddmFullToRaw DdmFullRemove ddmDetach :: String ddmDetach = Types.ddmFullToRaw DdmFullDetach ddmsValues :: FrozenSet String ddmsValues = ConstantUtils.mkSet [ddmAdd, ddmAttach, ddmRemove, ddmDetach] ddmsValuesWithModify :: FrozenSet String ddmsValuesWithModify = ConstantUtils.mkSet $ map Types.ddmFullToRaw [minBound..] -- * Common exit codes exitSuccess :: Int exitSuccess = 0 exitFailure :: Int exitFailure = ConstantUtils.exitFailure exitNotcluster :: Int exitNotcluster = 5 exitNotmaster :: Int exitNotmaster = 11 exitNodesetupError :: Int exitNodesetupError = 12 -- | Need user confirmation exitConfirmation :: Int exitConfirmation = 13 -- | Exit code for query operations with unknown fields exitUnknownField :: Int exitUnknownField = 14 -- * Tags tagCluster :: String tagCluster = Types.tagKindToRaw TagKindCluster tagInstance :: String tagInstance = Types.tagKindToRaw TagKindInstance tagNetwork :: String tagNetwork = Types.tagKindToRaw TagKindNetwork tagNode :: String tagNode = Types.tagKindToRaw TagKindNode tagNodegroup :: String tagNodegroup = Types.tagKindToRaw TagKindGroup validTagTypes :: FrozenSet String validTagTypes = ConstantUtils.mkSet $ map Types.tagKindToRaw [minBound..] maxTagLen :: Int maxTagLen = 128 maxTagsPerObj :: Int maxTagsPerObj = 4096 -- * Others defaultBridge :: String defaultBridge = AutoConf.defaultBridge defaultOvs :: String defaultOvs = "switch1" -- | 60 MiB/s, expressed in KiB/s classicDrbdSyncSpeed :: Int classicDrbdSyncSpeed = 60 * 1024 ip4AddressAny :: String ip4AddressAny = "0.0.0.0" ip4AddressLocalhost :: String ip4AddressLocalhost = "127.0.0.1" ip6AddressAny :: String ip6AddressAny = "::" ip6AddressLocalhost :: String ip6AddressLocalhost = "::1" ip4Version :: Int ip4Version = 4 ip6Version :: Int ip6Version = 6 validIpVersions :: FrozenSet Int validIpVersions = ConstantUtils.mkSet [ip4Version, ip6Version] tcpPingTimeout :: Int tcpPingTimeout = 10 defaultVg :: String defaultVg = AutoConf.defaultVg defaultDrbdHelper :: String defaultDrbdHelper = "/bin/true" minVgSize :: Int minVgSize = 20480 defaultMacPrefix :: String defaultMacPrefix = "aa:00:00" -- | Default maximum instance wait time (seconds) defaultShutdownTimeout :: Int defaultShutdownTimeout = 120 -- | Node clock skew (seconds) nodeMaxClockSkew :: Int nodeMaxClockSkew = 150 -- | Time for an intra-cluster disk transfer to wait for a connection diskTransferConnectTimeout :: Int diskTransferConnectTimeout = 60 -- | Disk index separator diskSeparator :: String diskSeparator = AutoConf.diskSeparator ipCommandPath :: String ipCommandPath = AutoConf.ipPath -- | Key for job IDs in opcode result jobIdsKey :: String jobIdsKey = "jobs" -- * Runparts results runpartsErr :: Int runpartsErr = 2 runpartsRun :: Int runpartsRun = 1 runpartsSkip :: Int runpartsSkip = 0 runpartsStatus :: [Int] runpartsStatus = [runpartsErr, runpartsRun, runpartsSkip] -- * RPC rpcEncodingNone :: Int rpcEncodingNone = 0 rpcEncodingZlibBase64 :: Int rpcEncodingZlibBase64 = 1 -- * Timeout table -- -- Various time constants for the timeout table rpcTmoUrgent :: Int rpcTmoUrgent = Types.rpcTimeoutToRaw Urgent rpcTmoFast :: Int rpcTmoFast = Types.rpcTimeoutToRaw Fast rpcTmoNormal :: Int rpcTmoNormal = Types.rpcTimeoutToRaw Normal rpcTmoSlow :: Int rpcTmoSlow = Types.rpcTimeoutToRaw Slow -- | 'rpcTmo_4hrs' contains an underscore to circumvent a limitation -- in the 'Ganeti.THH.deCamelCase' function and generate the correct -- Python name. rpcTmo_4hrs :: Int rpcTmo_4hrs = Types.rpcTimeoutToRaw FourHours -- | 'rpcTmo_1day' contains an underscore to circumvent a limitation -- in the 'Ganeti.THH.deCamelCase' function and generate the correct -- Python name. rpcTmo_1day :: Int rpcTmo_1day = Types.rpcTimeoutToRaw OneDay -- | Timeout for connecting to nodes (seconds) rpcConnectTimeout :: Int rpcConnectTimeout = 5 -- OS osScriptCreate :: String osScriptCreate = "create" osScriptCreateUntrusted :: String osScriptCreateUntrusted = "create_untrusted" osScriptExport :: String osScriptExport = "export" osScriptImport :: String osScriptImport = "import" osScriptRename :: String osScriptRename = "rename" osScriptVerify :: String osScriptVerify = "verify" osScripts :: [String] osScripts = [osScriptCreate, osScriptCreateUntrusted, osScriptExport, osScriptImport, osScriptRename, osScriptVerify] osApiFile :: String osApiFile = "ganeti_api_version" osVariantsFile :: String osVariantsFile = "variants.list" osParametersFile :: String osParametersFile = "parameters.list" osValidateParameters :: String osValidateParameters = "parameters" osValidateCalls :: FrozenSet String osValidateCalls = ConstantUtils.mkSet [osValidateParameters] -- | External Storage (ES) related constants esActionAttach :: String esActionAttach = "attach" esActionCreate :: String esActionCreate = "create" esActionDetach :: String esActionDetach = "detach" esActionGrow :: String esActionGrow = "grow" esActionRemove :: String esActionRemove = "remove" esActionSetinfo :: String esActionSetinfo = "setinfo" esActionVerify :: String esActionVerify = "verify" esActionSnapshot :: String esActionSnapshot = "snapshot" esActionOpen :: String esActionOpen = "open" esActionClose :: String esActionClose = "close" esScriptCreate :: String esScriptCreate = esActionCreate esScriptRemove :: String esScriptRemove = esActionRemove esScriptGrow :: String esScriptGrow = esActionGrow esScriptAttach :: String esScriptAttach = esActionAttach esScriptDetach :: String esScriptDetach = esActionDetach esScriptSetinfo :: String esScriptSetinfo = esActionSetinfo esScriptVerify :: String esScriptVerify = esActionVerify esScriptSnapshot :: String esScriptSnapshot = esActionSnapshot esScriptOpen :: String esScriptOpen = esActionOpen esScriptClose :: String esScriptClose = esActionClose esScripts :: FrozenSet String esScripts = ConstantUtils.mkSet [esScriptAttach, esScriptCreate, esScriptDetach, esScriptGrow, esScriptRemove, esScriptSetinfo, esScriptVerify, esScriptSnapshot, esScriptOpen, esScriptClose] esParametersFile :: String esParametersFile = "parameters.list" -- * Reboot types instanceRebootSoft :: String instanceRebootSoft = Types.rebootTypeToRaw RebootSoft instanceRebootHard :: String instanceRebootHard = Types.rebootTypeToRaw RebootHard instanceRebootFull :: String instanceRebootFull = Types.rebootTypeToRaw RebootFull rebootTypes :: FrozenSet String rebootTypes = ConstantUtils.mkSet $ map Types.rebootTypeToRaw [minBound..] -- * Instance reboot behaviors instanceRebootAllowed :: String instanceRebootAllowed = "reboot" instanceRebootExit :: String instanceRebootExit = "exit" rebootBehaviors :: [String] rebootBehaviors = [instanceRebootAllowed, instanceRebootExit] -- * VTypes vtypeBool :: VType vtypeBool = VTypeBool vtypeInt :: VType vtypeInt = VTypeInt vtypeFloat :: VType vtypeFloat = VTypeFloat vtypeMaybeString :: VType vtypeMaybeString = VTypeMaybeString -- | Size in MiBs vtypeSize :: VType vtypeSize = VTypeSize vtypeString :: VType vtypeString = VTypeString enforceableTypes :: FrozenSet VType enforceableTypes = ConstantUtils.mkSet [minBound..] -- | Constant representing that the user does not specify any IP version ifaceNoIpVersionSpecified :: Int ifaceNoIpVersionSpecified = 0 validSerialSpeeds :: [Int] validSerialSpeeds = [75, 110, 300, 600, 1200, 1800, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200, 230400, 345600, 460800] -- * HV parameter names (global namespace) hvAcpi :: String hvAcpi = "acpi" hvBlockdevPrefix :: String hvBlockdevPrefix = "blockdev_prefix" hvBootloaderArgs :: String hvBootloaderArgs = "bootloader_args" hvBootloaderPath :: String hvBootloaderPath = "bootloader_path" hvBootOrder :: String hvBootOrder = "boot_order" hvCdromImagePath :: String hvCdromImagePath = "cdrom_image_path" hvCpuCap :: String hvCpuCap = "cpu_cap" hvCpuCores :: String hvCpuCores = "cpu_cores" hvCpuMask :: String hvCpuMask = "cpu_mask" hvWorkerCpuMask :: String hvWorkerCpuMask = "worker_cpu_mask" hvCpuSockets :: String hvCpuSockets = "cpu_sockets" hvCpuThreads :: String hvCpuThreads = "cpu_threads" hvCpuType :: String hvCpuType = "cpu_type" hvCpuWeight :: String hvCpuWeight = "cpu_weight" hvDeviceModel :: String hvDeviceModel = "device_model" hvDiskCache :: String hvDiskCache = "disk_cache" hvDiskType :: String hvDiskType = "disk_type" hvInitrdPath :: String hvInitrdPath = "initrd_path" hvInitScript :: String hvInitScript = "init_script" hvKernelArgs :: String hvKernelArgs = "kernel_args" hvKernelPath :: String hvKernelPath = "kernel_path" hvKeymap :: String hvKeymap = "keymap" hvKvmCdrom2ImagePath :: String hvKvmCdrom2ImagePath = "cdrom2_image_path" hvKvmCdromDiskType :: String hvKvmCdromDiskType = "cdrom_disk_type" hvKvmExtra :: String hvKvmExtra = "kvm_extra" hvKvmFlag :: String hvKvmFlag = "kvm_flag" hvKvmFloppyImagePath :: String hvKvmFloppyImagePath = "floppy_image_path" hvKvmMachineVersion :: String hvKvmMachineVersion = "machine_version" hvKvmMigrationCaps :: String hvKvmMigrationCaps = "migration_caps" hvKvmPath :: String hvKvmPath = "kvm_path" hvKvmDiskAio :: String hvKvmDiskAio = "disk_aio" hvKvmScsiControllerType :: String hvKvmScsiControllerType = "scsi_controller_type" hvKvmPciReservations :: String hvKvmPciReservations = "kvm_pci_reservations" hvKvmSpiceAudioCompr :: String hvKvmSpiceAudioCompr = "spice_playback_compression" hvKvmSpiceBind :: String hvKvmSpiceBind = "spice_bind" hvKvmSpiceIpVersion :: String hvKvmSpiceIpVersion = "spice_ip_version" hvKvmSpiceJpegImgCompr :: String hvKvmSpiceJpegImgCompr = "spice_jpeg_wan_compression" hvKvmSpiceLosslessImgCompr :: String hvKvmSpiceLosslessImgCompr = "spice_image_compression" hvKvmSpicePasswordFile :: String hvKvmSpicePasswordFile = "spice_password_file" hvKvmSpiceStreamingVideoDetection :: String hvKvmSpiceStreamingVideoDetection = "spice_streaming_video" hvKvmSpiceTlsCiphers :: String hvKvmSpiceTlsCiphers = "spice_tls_ciphers" hvKvmSpiceUseTls :: String hvKvmSpiceUseTls = "spice_use_tls" hvKvmSpiceUseVdagent :: String hvKvmSpiceUseVdagent = "spice_use_vdagent" hvKvmSpiceZlibGlzImgCompr :: String hvKvmSpiceZlibGlzImgCompr = "spice_zlib_glz_wan_compression" hvKvmUseChroot :: String hvKvmUseChroot = "use_chroot" hvKvmUserShutdown :: String hvKvmUserShutdown = "user_shutdown" hvLxcStartupTimeout :: String hvLxcStartupTimeout = "startup_timeout" hvLxcExtraCgroups :: String hvLxcExtraCgroups = "extra_cgroups" hvLxcDevices :: String hvLxcDevices = "devices" hvLxcDropCapabilities :: String hvLxcDropCapabilities = "drop_capabilities" hvLxcExtraConfig :: String hvLxcExtraConfig = "extra_config" hvLxcNumTtys :: String hvLxcNumTtys = "num_ttys" hvMemPath :: String hvMemPath = "mem_path" hvMigrationBandwidth :: String hvMigrationBandwidth = "migration_bandwidth" hvMigrationDowntime :: String hvMigrationDowntime = "migration_downtime" hvMigrationMode :: String hvMigrationMode = "migration_mode" hvMigrationPort :: String hvMigrationPort = "migration_port" hvNicType :: String hvNicType = "nic_type" hvPae :: String hvPae = "pae" hvPassthrough :: String hvPassthrough = "pci_pass" hvRebootBehavior :: String hvRebootBehavior = "reboot_behavior" hvRootPath :: String hvRootPath = "root_path" hvSecurityDomain :: String hvSecurityDomain = "security_domain" hvSecurityModel :: String hvSecurityModel = "security_model" hvSerialConsole :: String hvSerialConsole = "serial_console" hvSerialSpeed :: String hvSerialSpeed = "serial_speed" hvSoundhw :: String hvSoundhw = "soundhw" hvUsbDevices :: String hvUsbDevices = "usb_devices" hvUsbMouse :: String hvUsbMouse = "usb_mouse" hvUseBootloader :: String hvUseBootloader = "use_bootloader" hvUseLocaltime :: String hvUseLocaltime = "use_localtime" hvVga :: String hvVga = "vga" hvVhostNet :: String hvVhostNet = "vhost_net" hvVirtioNetQueues :: String hvVirtioNetQueues = "virtio_net_queues" hvVifScript :: String hvVifScript = "vif_script" hvVifType :: String hvVifType = "vif_type" hvViridian :: String hvViridian = "viridian" hvVncBindAddress :: String hvVncBindAddress = "vnc_bind_address" hvVncPasswordFile :: String hvVncPasswordFile = "vnc_password_file" hvVncTls :: String hvVncTls = "vnc_tls" hvVncX509 :: String hvVncX509 = "vnc_x509_path" hvVncX509Verify :: String hvVncX509Verify = "vnc_x509_verify" hvVnetHdr :: String hvVnetHdr = "vnet_hdr" hvXenCmd :: String hvXenCmd = "xen_cmd" hvXenCpuid :: String hvXenCpuid = "cpuid" hvsParameterTitles :: Map String String hvsParameterTitles = Map.fromList [(hvAcpi, "ACPI"), (hvBootOrder, "Boot_order"), (hvCdromImagePath, "CDROM_image_path"), (hvCpuType, "cpu_type"), (hvDiskType, "Disk_type"), (hvInitrdPath, "Initrd_path"), (hvKernelPath, "Kernel_path"), (hvNicType, "NIC_type"), (hvPae, "PAE"), (hvPassthrough, "pci_pass"), (hvVncBindAddress, "VNC_bind_address")] hvsParameters :: FrozenSet String hvsParameters = ConstantUtils.mkSet $ Map.keys hvsParameterTypes hvsParameterTypes :: Map String VType hvsParameterTypes = Map.fromList [ (hvAcpi, VTypeBool) , (hvBlockdevPrefix, VTypeString) , (hvBootloaderArgs, VTypeString) , (hvBootloaderPath, VTypeString) , (hvBootOrder, VTypeString) , (hvCdromImagePath, VTypeString) , (hvCpuCap, VTypeInt) , (hvCpuCores, VTypeInt) , (hvCpuMask, VTypeString) , (hvWorkerCpuMask, VTypeString) , (hvCpuSockets, VTypeInt) , (hvCpuThreads, VTypeInt) , (hvCpuType, VTypeString) , (hvCpuWeight, VTypeInt) , (hvDeviceModel, VTypeString) , (hvDiskCache, VTypeString) , (hvDiskType, VTypeString) , (hvInitrdPath, VTypeString) , (hvInitScript, VTypeString) , (hvKernelArgs, VTypeString) , (hvKernelPath, VTypeString) , (hvKeymap, VTypeString) , (hvKvmCdrom2ImagePath, VTypeString) , (hvKvmCdromDiskType, VTypeString) , (hvKvmExtra, VTypeString) , (hvKvmFlag, VTypeString) , (hvKvmFloppyImagePath, VTypeString) , (hvKvmMachineVersion, VTypeString) , (hvKvmMigrationCaps, VTypeString) , (hvKvmPath, VTypeString) , (hvKvmDiskAio, VTypeString) , (hvKvmScsiControllerType, VTypeString) , (hvKvmPciReservations, VTypeInt) , (hvKvmSpiceAudioCompr, VTypeBool) , (hvKvmSpiceBind, VTypeString) , (hvKvmSpiceIpVersion, VTypeInt) , (hvKvmSpiceJpegImgCompr, VTypeString) , (hvKvmSpiceLosslessImgCompr, VTypeString) , (hvKvmSpicePasswordFile, VTypeString) , (hvKvmSpiceStreamingVideoDetection, VTypeString) , (hvKvmSpiceTlsCiphers, VTypeString) , (hvKvmSpiceUseTls, VTypeBool) , (hvKvmSpiceUseVdagent, VTypeBool) , (hvKvmSpiceZlibGlzImgCompr, VTypeString) , (hvKvmUseChroot, VTypeBool) , (hvKvmUserShutdown, VTypeBool) , (hvLxcDevices, VTypeString) , (hvLxcDropCapabilities, VTypeString) , (hvLxcExtraCgroups, VTypeString) , (hvLxcExtraConfig, VTypeString) , (hvLxcNumTtys, VTypeInt) , (hvLxcStartupTimeout, VTypeInt) , (hvMemPath, VTypeString) , (hvMigrationBandwidth, VTypeInt) , (hvMigrationDowntime, VTypeInt) , (hvMigrationMode, VTypeString) , (hvMigrationPort, VTypeInt) , (hvNicType, VTypeString) , (hvPae, VTypeBool) , (hvPassthrough, VTypeString) , (hvRebootBehavior, VTypeString) , (hvRootPath, VTypeMaybeString) , (hvSecurityDomain, VTypeString) , (hvSecurityModel, VTypeString) , (hvSerialConsole, VTypeBool) , (hvSerialSpeed, VTypeInt) , (hvSoundhw, VTypeString) , (hvUsbDevices, VTypeString) , (hvUsbMouse, VTypeString) , (hvUseBootloader, VTypeBool) , (hvUseLocaltime, VTypeBool) , (hvVga, VTypeString) , (hvVhostNet, VTypeBool) , (hvVirtioNetQueues, VTypeInt) , (hvVifScript, VTypeString) , (hvVifType, VTypeString) , (hvViridian, VTypeBool) , (hvVncBindAddress, VTypeString) , (hvVncPasswordFile, VTypeString) , (hvVncTls, VTypeBool) , (hvVncX509, VTypeString) , (hvVncX509Verify, VTypeBool) , (hvVnetHdr, VTypeBool) , (hvXenCmd, VTypeString) , (hvXenCpuid, VTypeString) ] -- * Migration statuses hvMigrationActive :: String hvMigrationActive = "active" hvMigrationCancelled :: String hvMigrationCancelled = "cancelled" hvMigrationCompleted :: String hvMigrationCompleted = "completed" hvMigrationFailed :: String hvMigrationFailed = "failed" hvMigrationValidStatuses :: FrozenSet String hvMigrationValidStatuses = ConstantUtils.mkSet [hvMigrationActive, hvMigrationCancelled, hvMigrationCompleted, hvMigrationFailed] hvMigrationFailedStatuses :: FrozenSet String hvMigrationFailedStatuses = ConstantUtils.mkSet [hvMigrationFailed, hvMigrationCancelled] -- | KVM-specific statuses -- -- FIXME: this constant seems unnecessary hvKvmMigrationValidStatuses :: FrozenSet String hvKvmMigrationValidStatuses = hvMigrationValidStatuses -- | Node info keys hvNodeinfoKeyVersion :: String hvNodeinfoKeyVersion = "hv_version" -- * Hypervisor state hvstCpuNode :: String hvstCpuNode = "cpu_node" hvstCpuTotal :: String hvstCpuTotal = "cpu_total" hvstMemoryHv :: String hvstMemoryHv = "mem_hv" hvstMemoryNode :: String hvstMemoryNode = "mem_node" hvstMemoryTotal :: String hvstMemoryTotal = "mem_total" hvstsParameters :: FrozenSet String hvstsParameters = ConstantUtils.mkSet [hvstCpuNode, hvstCpuTotal, hvstMemoryHv, hvstMemoryNode, hvstMemoryTotal] hvstDefaults :: Map String Int hvstDefaults = Map.fromList [ (hvstCpuNode , ConstantUtils.hvstDefaultCpuNode ) , (hvstCpuTotal , ConstantUtils.hvstDefaultCpuTotal ) , (hvstMemoryHv , ConstantUtils.hvstDefaultMemoryHv ) , (hvstMemoryTotal, ConstantUtils.hvstDefaultMemoryTotal) , (hvstMemoryNode , ConstantUtils.hvstDefaultMemoryNode ) ] hvstsParameterTypes :: Map String VType hvstsParameterTypes = Map.fromList [(hvstMemoryTotal, VTypeInt), (hvstMemoryNode, VTypeInt), (hvstMemoryHv, VTypeInt), (hvstCpuTotal, VTypeInt), (hvstCpuNode, VTypeInt)] -- * Disk state dsDiskOverhead :: String dsDiskOverhead = "disk_overhead" dsDiskReserved :: String dsDiskReserved = "disk_reserved" dsDiskTotal :: String dsDiskTotal = "disk_total" dsDefaults :: Map String Int dsDefaults = Map.fromList [(dsDiskTotal, 0), (dsDiskReserved, 0), (dsDiskOverhead, 0)] dssParameterTypes :: Map String VType dssParameterTypes = Map.fromList [(dsDiskTotal, VTypeInt), (dsDiskReserved, VTypeInt), (dsDiskOverhead, VTypeInt)] dssParameters :: FrozenSet String dssParameters = ConstantUtils.mkSet [dsDiskTotal, dsDiskReserved, dsDiskOverhead] dsValidTypes :: FrozenSet String dsValidTypes = ConstantUtils.mkSet [Types.diskTemplateToRaw DTPlain] -- Backend parameter names beAlwaysFailover :: String beAlwaysFailover = "always_failover" beAutoBalance :: String beAutoBalance = "auto_balance" beMaxmem :: String beMaxmem = "maxmem" -- | Deprecated and replaced by max and min mem beMemory :: String beMemory = "memory" beMinmem :: String beMinmem = "minmem" beSpindleUse :: String beSpindleUse = "spindle_use" beVcpus :: String beVcpus = "vcpus" besParameterTypes :: Map String VType besParameterTypes = Map.fromList [(beAlwaysFailover, VTypeBool), (beAutoBalance, VTypeBool), (beMaxmem, VTypeSize), (beMinmem, VTypeSize), (beSpindleUse, VTypeInt), (beVcpus, VTypeInt)] besParameterTitles :: Map String String besParameterTitles = Map.fromList [(beAutoBalance, "Auto_balance"), (beMinmem, "ConfigMinMem"), (beVcpus, "ConfigVCPUs"), (beMaxmem, "ConfigMaxMem")] besParameterCompat :: Map String VType besParameterCompat = Map.insert beMemory VTypeSize besParameterTypes besParameters :: FrozenSet String besParameters = ConstantUtils.mkSet [beAlwaysFailover, beAutoBalance, beMaxmem, beMinmem, beSpindleUse, beVcpus] -- | Instance specs -- -- FIXME: these should be associated with 'Ganeti.HTools.Types.ISpec' ispecMemSize :: String ispecMemSize = ConstantUtils.ispecMemSize ispecCpuCount :: String ispecCpuCount = ConstantUtils.ispecCpuCount ispecDiskCount :: String ispecDiskCount = ConstantUtils.ispecDiskCount ispecDiskSize :: String ispecDiskSize = ConstantUtils.ispecDiskSize ispecNicCount :: String ispecNicCount = ConstantUtils.ispecNicCount ispecSpindleUse :: String ispecSpindleUse = ConstantUtils.ispecSpindleUse ispecsParameterTypes :: Map String VType ispecsParameterTypes = Map.fromList [(ConstantUtils.ispecDiskSize, VTypeInt), (ConstantUtils.ispecCpuCount, VTypeInt), (ConstantUtils.ispecSpindleUse, VTypeInt), (ConstantUtils.ispecMemSize, VTypeInt), (ConstantUtils.ispecNicCount, VTypeInt), (ConstantUtils.ispecDiskCount, VTypeInt)] ispecsParameters :: FrozenSet String ispecsParameters = ConstantUtils.mkSet [ConstantUtils.ispecCpuCount, ConstantUtils.ispecDiskCount, ConstantUtils.ispecDiskSize, ConstantUtils.ispecMemSize, ConstantUtils.ispecNicCount, ConstantUtils.ispecSpindleUse] ispecsMinmax :: String ispecsMinmax = ConstantUtils.ispecsMinmax ispecsMax :: String ispecsMax = "max" ispecsMin :: String ispecsMin = "min" ispecsStd :: String ispecsStd = ConstantUtils.ispecsStd ipolicyDts :: String ipolicyDts = ConstantUtils.ipolicyDts ipolicyVcpuRatio :: String ipolicyVcpuRatio = ConstantUtils.ipolicyVcpuRatio ipolicySpindleRatio :: String ipolicySpindleRatio = ConstantUtils.ipolicySpindleRatio ipolicyMemoryRatio :: String ipolicyMemoryRatio = ConstantUtils.ipolicyMemoryRatio ispecsMinmaxKeys :: FrozenSet String ispecsMinmaxKeys = ConstantUtils.mkSet [ispecsMax, ispecsMin] ipolicyParameters :: FrozenSet String ipolicyParameters = ConstantUtils.mkSet [ConstantUtils.ipolicyVcpuRatio, ConstantUtils.ipolicySpindleRatio, ConstantUtils.ipolicyMemoryRatio] ipolicyAllKeys :: FrozenSet String ipolicyAllKeys = ConstantUtils.union ipolicyParameters $ ConstantUtils.mkSet [ConstantUtils.ipolicyDts, ConstantUtils.ispecsMinmax, ispecsStd] -- | Node parameter names ndExclusiveStorage :: String ndExclusiveStorage = "exclusive_storage" ndOobProgram :: String ndOobProgram = "oob_program" ndSpindleCount :: String ndSpindleCount = "spindle_count" ndOvs :: String ndOvs = "ovs" ndOvsLink :: String ndOvsLink = "ovs_link" ndOvsName :: String ndOvsName = "ovs_name" ndSshPort :: String ndSshPort = "ssh_port" ndCpuSpeed :: String ndCpuSpeed = "cpu_speed" ndsParameterTypes :: Map String VType ndsParameterTypes = Map.fromList [(ndExclusiveStorage, VTypeBool), (ndOobProgram, VTypeString), (ndOvs, VTypeBool), (ndOvsLink, VTypeMaybeString), (ndOvsName, VTypeMaybeString), (ndSpindleCount, VTypeInt), (ndSshPort, VTypeInt), (ndCpuSpeed, VTypeFloat)] ndsParameters :: FrozenSet String ndsParameters = ConstantUtils.mkSet (Map.keys ndsParameterTypes) ndsParameterTitles :: Map String String ndsParameterTitles = Map.fromList [(ndExclusiveStorage, "ExclusiveStorage"), (ndOobProgram, "OutOfBandProgram"), (ndOvs, "OpenvSwitch"), (ndOvsLink, "OpenvSwitchLink"), (ndOvsName, "OpenvSwitchName"), (ndSpindleCount, "SpindleCount")] -- * Logical Disks parameters ldpAccess :: String ldpAccess = "access" ldpBarriers :: String ldpBarriers = "disabled-barriers" ldpDefaultMetavg :: String ldpDefaultMetavg = "default-metavg" ldpDelayTarget :: String ldpDelayTarget = "c-delay-target" ldpDiskCustom :: String ldpDiskCustom = "disk-custom" ldpDynamicResync :: String ldpDynamicResync = "dynamic-resync" ldpFillTarget :: String ldpFillTarget = "c-fill-target" ldpMaxRate :: String ldpMaxRate = "c-max-rate" ldpMinRate :: String ldpMinRate = "c-min-rate" ldpNetCustom :: String ldpNetCustom = "net-custom" ldpNoMetaFlush :: String ldpNoMetaFlush = "disable-meta-flush" ldpPlanAhead :: String ldpPlanAhead = "c-plan-ahead" ldpPool :: String ldpPool = "pool" ldpProtocol :: String ldpProtocol = "protocol" ldpResyncRate :: String ldpResyncRate = "resync-rate" ldpStripes :: String ldpStripes = "stripes" diskLdTypes :: Map String VType diskLdTypes = Map.fromList [(ldpAccess, VTypeString), (ldpResyncRate, VTypeInt), (ldpStripes, VTypeInt), (ldpBarriers, VTypeString), (ldpNoMetaFlush, VTypeBool), (ldpDefaultMetavg, VTypeString), (ldpDiskCustom, VTypeString), (ldpNetCustom, VTypeString), (ldpProtocol, VTypeString), (ldpDynamicResync, VTypeBool), (ldpPlanAhead, VTypeInt), (ldpFillTarget, VTypeInt), (ldpDelayTarget, VTypeInt), (ldpMaxRate, VTypeInt), (ldpMinRate, VTypeInt), (ldpPool, VTypeString)] diskLdParameters :: FrozenSet String diskLdParameters = ConstantUtils.mkSet (Map.keys diskLdTypes) -- * Disk template parameters -- -- Disk template parameters can be set/changed by the user via -- gnt-cluster and gnt-group) drbdResyncRate :: String drbdResyncRate = "resync-rate" drbdDataStripes :: String drbdDataStripes = "data-stripes" drbdMetaStripes :: String drbdMetaStripes = "meta-stripes" drbdDiskBarriers :: String drbdDiskBarriers = "disk-barriers" drbdMetaBarriers :: String drbdMetaBarriers = "meta-barriers" drbdDefaultMetavg :: String drbdDefaultMetavg = "metavg" drbdDiskCustom :: String drbdDiskCustom = "disk-custom" drbdNetCustom :: String drbdNetCustom = "net-custom" drbdProtocol :: String drbdProtocol = "protocol" drbdDynamicResync :: String drbdDynamicResync = "dynamic-resync" drbdPlanAhead :: String drbdPlanAhead = "c-plan-ahead" drbdFillTarget :: String drbdFillTarget = "c-fill-target" drbdDelayTarget :: String drbdDelayTarget = "c-delay-target" drbdMaxRate :: String drbdMaxRate = "c-max-rate" drbdMinRate :: String drbdMinRate = "c-min-rate" lvStripes :: String lvStripes = "stripes" rbdAccess :: String rbdAccess = "access" rbdPool :: String rbdPool = "pool" diskDtTypes :: Map String VType diskDtTypes = Map.fromList [(drbdResyncRate, VTypeInt), (drbdDataStripes, VTypeInt), (drbdMetaStripes, VTypeInt), (drbdDiskBarriers, VTypeString), (drbdMetaBarriers, VTypeBool), (drbdDefaultMetavg, VTypeString), (drbdDiskCustom, VTypeString), (drbdNetCustom, VTypeString), (drbdProtocol, VTypeString), (drbdDynamicResync, VTypeBool), (drbdPlanAhead, VTypeInt), (drbdFillTarget, VTypeInt), (drbdDelayTarget, VTypeInt), (drbdMaxRate, VTypeInt), (drbdMinRate, VTypeInt), (lvStripes, VTypeInt), (rbdAccess, VTypeString), (rbdPool, VTypeString), (glusterHost, VTypeString), (glusterVolume, VTypeString), (glusterPort, VTypeInt) ] diskDtParameters :: FrozenSet String diskDtParameters = ConstantUtils.mkSet (Map.keys diskDtTypes) -- * Dynamic disk parameters ddpLocalIp :: String ddpLocalIp = "local-ip" ddpRemoteIp :: String ddpRemoteIp = "remote-ip" ddpPort :: String ddpPort = "port" ddpLocalMinor :: String ddpLocalMinor = "local-minor" ddpRemoteMinor :: String ddpRemoteMinor = "remote-minor" -- * OOB supported commands oobPowerOn :: String oobPowerOn = Types.oobCommandToRaw OobPowerOn oobPowerOff :: String oobPowerOff = Types.oobCommandToRaw OobPowerOff oobPowerCycle :: String oobPowerCycle = Types.oobCommandToRaw OobPowerCycle oobPowerStatus :: String oobPowerStatus = Types.oobCommandToRaw OobPowerStatus oobHealth :: String oobHealth = Types.oobCommandToRaw OobHealth oobCommands :: FrozenSet String oobCommands = ConstantUtils.mkSet $ map Types.oobCommandToRaw [minBound..] oobPowerStatusPowered :: String oobPowerStatusPowered = "powered" -- | 60 seconds oobTimeout :: Int oobTimeout = 60 -- | 2 seconds oobPowerDelay :: Double oobPowerDelay = 2.0 oobStatusCritical :: String oobStatusCritical = Types.oobStatusToRaw OobStatusCritical oobStatusOk :: String oobStatusOk = Types.oobStatusToRaw OobStatusOk oobStatusUnknown :: String oobStatusUnknown = Types.oobStatusToRaw OobStatusUnknown oobStatusWarning :: String oobStatusWarning = Types.oobStatusToRaw OobStatusWarning oobStatuses :: FrozenSet String oobStatuses = ConstantUtils.mkSet $ map Types.oobStatusToRaw [minBound..] -- | Instance Parameters Profile ppDefault :: String ppDefault = "default" -- * nic* constants are used inside the ganeti config nicLink :: String nicLink = "link" nicMode :: String nicMode = "mode" nicVlan :: String nicVlan = "vlan" nicsParameterTypes :: Map String VType nicsParameterTypes = Map.fromList [(nicMode, vtypeString), (nicLink, vtypeString), (nicVlan, vtypeString)] nicsParameters :: FrozenSet String nicsParameters = ConstantUtils.mkSet (Map.keys nicsParameterTypes) nicModeBridged :: String nicModeBridged = Types.nICModeToRaw NMBridged nicModeRouted :: String nicModeRouted = Types.nICModeToRaw NMRouted nicModeOvs :: String nicModeOvs = Types.nICModeToRaw NMOvs nicIpPool :: String nicIpPool = Types.nICModeToRaw NMPool nicValidModes :: FrozenSet String nicValidModes = ConstantUtils.mkSet $ map Types.nICModeToRaw [minBound..] releaseAction :: String releaseAction = "release" reserveAction :: String reserveAction = "reserve" -- * idisk* constants are used in opcodes, to create/change disks idiskAdopt :: String idiskAdopt = "adopt" idiskMetavg :: String idiskMetavg = "metavg" idiskMode :: String idiskMode = "mode" idiskName :: String idiskName = "name" idiskSize :: String idiskSize = "size" idiskSpindles :: String idiskSpindles = "spindles" idiskVg :: String idiskVg = "vg" idiskProvider :: String idiskProvider = "provider" idiskAccess :: String idiskAccess = "access" idiskType :: String idiskType = "dev_type" idiskParamsTypes :: Map String VType idiskParamsTypes = Map.fromList [ (idiskSize, VTypeSize) , (idiskSpindles, VTypeInt) , (idiskMode, VTypeString) , (idiskAdopt, VTypeString) , (idiskVg, VTypeString) , (idiskMetavg, VTypeString) , (idiskProvider, VTypeString) , (idiskAccess, VTypeString) , (idiskName, VTypeMaybeString) , (idiskType, VTypeString) ] idiskParams :: FrozenSet String idiskParams = ConstantUtils.mkSet (Map.keys idiskParamsTypes) modifiableIdiskParamsTypes :: Map String VType modifiableIdiskParamsTypes = Map.fromList [(idiskMode, VTypeString), (idiskName, VTypeString)] modifiableIdiskParams :: FrozenSet String modifiableIdiskParams = ConstantUtils.mkSet (Map.keys modifiableIdiskParamsTypes) -- * inic* constants are used in opcodes, to create/change nics inicBridge :: String inicBridge = "bridge" inicIp :: String inicIp = "ip" inicLink :: String inicLink = "link" inicMac :: String inicMac = "mac" inicMode :: String inicMode = "mode" inicName :: String inicName = "name" inicNetwork :: String inicNetwork = "network" inicVlan :: String inicVlan = "vlan" inicParamsTypes :: Map String VType inicParamsTypes = Map.fromList [(inicBridge, VTypeMaybeString), (inicIp, VTypeMaybeString), (inicLink, VTypeString), (inicMac, VTypeString), (inicMode, VTypeString), (inicName, VTypeMaybeString), (inicNetwork, VTypeMaybeString), (inicVlan, VTypeMaybeString)] inicParams :: FrozenSet String inicParams = ConstantUtils.mkSet (Map.keys inicParamsTypes) -- * Hypervisor constants htXenPvm :: String htXenPvm = Types.hypervisorToRaw XenPvm htFake :: String htFake = Types.hypervisorToRaw Fake htXenHvm :: String htXenHvm = Types.hypervisorToRaw XenHvm htKvm :: String htKvm = Types.hypervisorToRaw Kvm htChroot :: String htChroot = Types.hypervisorToRaw Chroot htLxc :: String htLxc = Types.hypervisorToRaw Lxc hyperTypes :: FrozenSet String hyperTypes = ConstantUtils.mkSet $ map Types.hypervisorToRaw [minBound..] htsReqPort :: FrozenSet String htsReqPort = ConstantUtils.mkSet [htXenHvm, htKvm] vncBasePort :: Int vncBasePort = 5900 vncDefaultBindAddress :: String vncDefaultBindAddress = ip4AddressAny qemuPciSlots :: Int qemuPciSlots = 32 qemuDefaultPciReservations :: Int qemuDefaultPciReservations = 12 -- * NIC types htNicE1000 :: String htNicE1000 = "e1000" htNicI82551 :: String htNicI82551 = "i82551" htNicI8259er :: String htNicI8259er = "i82559er" htNicI85557b :: String htNicI85557b = "i82557b" htNicNe2kIsa :: String htNicNe2kIsa = "ne2k_isa" htNicNe2kPci :: String htNicNe2kPci = "ne2k_pci" htNicParavirtual :: String htNicParavirtual = "paravirtual" htNicPcnet :: String htNicPcnet = "pcnet" htNicRtl8139 :: String htNicRtl8139 = "rtl8139" htHvmValidNicTypes :: FrozenSet String htHvmValidNicTypes = ConstantUtils.mkSet [htNicE1000, htNicNe2kIsa, htNicNe2kPci, htNicParavirtual, htNicRtl8139] htKvmValidNicTypes :: FrozenSet String htKvmValidNicTypes = ConstantUtils.mkSet [htNicE1000, htNicI82551, htNicI8259er, htNicI85557b, htNicNe2kIsa, htNicNe2kPci, htNicParavirtual, htNicPcnet, htNicRtl8139] -- * Vif types -- | Default vif type in xen-hvm htHvmVifIoemu :: String htHvmVifIoemu = "ioemu" htHvmVifVif :: String htHvmVifVif = "vif" htHvmValidVifTypes :: FrozenSet String htHvmValidVifTypes = ConstantUtils.mkSet [htHvmVifIoemu, htHvmVifVif] -- * Disk types htDiskIde :: String htDiskIde = "ide" htDiskIoemu :: String htDiskIoemu = "ioemu" htDiskMtd :: String htDiskMtd = "mtd" htDiskParavirtual :: String htDiskParavirtual = "paravirtual" htDiskPflash :: String htDiskPflash = "pflash" htDiskScsi :: String htDiskScsi = "scsi" htDiskSd :: String htDiskSd = "sd" htDiskScsiGeneric :: String htDiskScsiGeneric = "scsi-generic" htDiskScsiBlock :: String htDiskScsiBlock = "scsi-block" htDiskScsiCd :: String htDiskScsiCd = "scsi-cd" htDiskScsiHd :: String htDiskScsiHd = "scsi-hd" htScsiDeviceTypes :: FrozenSet String htScsiDeviceTypes = ConstantUtils.mkSet [htDiskScsiGeneric, htDiskScsiBlock, htDiskScsiCd, htDiskScsiHd] htHvmValidDiskTypes :: FrozenSet String htHvmValidDiskTypes = ConstantUtils.mkSet [htDiskIoemu, htDiskParavirtual] htKvmValidDiskTypes :: FrozenSet String htKvmValidDiskTypes = ConstantUtils.mkSet [htDiskIde, htDiskMtd, htDiskParavirtual, htDiskPflash, htDiskScsi, htDiskSd, htDiskScsiGeneric, htDiskScsiBlock, htDiskScsiHd, htDiskScsiCd] -- * SCSI controller types htScsiControllerLsi :: String htScsiControllerLsi = "lsi" htScsiControllerVirtio :: String htScsiControllerVirtio = "virtio-scsi-pci" htScsiControllerMegasas :: String htScsiControllerMegasas = "megasas" htKvmValidScsiControllerTypes :: FrozenSet String htKvmValidScsiControllerTypes = ConstantUtils.mkSet [htScsiControllerLsi, htScsiControllerVirtio, htScsiControllerMegasas] htCacheDefault :: String htCacheDefault = "default" htCacheNone :: String htCacheNone = "none" htCacheWback :: String htCacheWback = "writeback" htCacheWthrough :: String htCacheWthrough = "writethrough" htValidCacheTypes :: FrozenSet String htValidCacheTypes = ConstantUtils.mkSet [htCacheDefault, htCacheNone, htCacheWback, htCacheWthrough] htKvmAioThreads :: String htKvmAioThreads = "threads" htKvmAioNative :: String htKvmAioNative = "native" htKvmValidAioTypes :: FrozenSet String htKvmValidAioTypes = ConstantUtils.mkSet [htKvmAioThreads, htKvmAioNative] -- * Mouse types htMouseMouse :: String htMouseMouse = "mouse" htMouseTablet :: String htMouseTablet = "tablet" htKvmValidMouseTypes :: FrozenSet String htKvmValidMouseTypes = ConstantUtils.mkSet [htMouseMouse, htMouseTablet] -- * Boot order htBoCdrom :: String htBoCdrom = "cdrom" htBoDisk :: String htBoDisk = "disk" htBoFloppy :: String htBoFloppy = "floppy" htBoNetwork :: String htBoNetwork = "network" htKvmValidBoTypes :: FrozenSet String htKvmValidBoTypes = ConstantUtils.mkSet [htBoCdrom, htBoDisk, htBoFloppy, htBoNetwork] -- * SPICE lossless image compression options htKvmSpiceLosslessImgComprAutoGlz :: String htKvmSpiceLosslessImgComprAutoGlz = "auto_glz" htKvmSpiceLosslessImgComprAutoLz :: String htKvmSpiceLosslessImgComprAutoLz = "auto_lz" htKvmSpiceLosslessImgComprGlz :: String htKvmSpiceLosslessImgComprGlz = "glz" htKvmSpiceLosslessImgComprLz :: String htKvmSpiceLosslessImgComprLz = "lz" htKvmSpiceLosslessImgComprOff :: String htKvmSpiceLosslessImgComprOff = "off" htKvmSpiceLosslessImgComprQuic :: String htKvmSpiceLosslessImgComprQuic = "quic" htKvmSpiceValidLosslessImgComprOptions :: FrozenSet String htKvmSpiceValidLosslessImgComprOptions = ConstantUtils.mkSet [htKvmSpiceLosslessImgComprAutoGlz, htKvmSpiceLosslessImgComprAutoLz, htKvmSpiceLosslessImgComprGlz, htKvmSpiceLosslessImgComprLz, htKvmSpiceLosslessImgComprOff, htKvmSpiceLosslessImgComprQuic] htKvmSpiceLossyImgComprAlways :: String htKvmSpiceLossyImgComprAlways = "always" htKvmSpiceLossyImgComprAuto :: String htKvmSpiceLossyImgComprAuto = "auto" htKvmSpiceLossyImgComprNever :: String htKvmSpiceLossyImgComprNever = "never" htKvmSpiceValidLossyImgComprOptions :: FrozenSet String htKvmSpiceValidLossyImgComprOptions = ConstantUtils.mkSet [htKvmSpiceLossyImgComprAlways, htKvmSpiceLossyImgComprAuto, htKvmSpiceLossyImgComprNever] -- * SPICE video stream detection htKvmSpiceVideoStreamDetectionAll :: String htKvmSpiceVideoStreamDetectionAll = "all" htKvmSpiceVideoStreamDetectionFilter :: String htKvmSpiceVideoStreamDetectionFilter = "filter" htKvmSpiceVideoStreamDetectionOff :: String htKvmSpiceVideoStreamDetectionOff = "off" htKvmSpiceValidVideoStreamDetectionOptions :: FrozenSet String htKvmSpiceValidVideoStreamDetectionOptions = ConstantUtils.mkSet [htKvmSpiceVideoStreamDetectionAll, htKvmSpiceVideoStreamDetectionFilter, htKvmSpiceVideoStreamDetectionOff] -- * Security models htSmNone :: String htSmNone = "none" htSmPool :: String htSmPool = "pool" htSmUser :: String htSmUser = "user" htKvmValidSmTypes :: FrozenSet String htKvmValidSmTypes = ConstantUtils.mkSet [htSmNone, htSmPool, htSmUser] -- * Kvm flag values htKvmDisabled :: String htKvmDisabled = "disabled" htKvmEnabled :: String htKvmEnabled = "enabled" htKvmFlagValues :: FrozenSet String htKvmFlagValues = ConstantUtils.mkSet [htKvmDisabled, htKvmEnabled] -- * Migration type htMigrationLive :: String htMigrationLive = Types.migrationModeToRaw MigrationLive htMigrationNonlive :: String htMigrationNonlive = Types.migrationModeToRaw MigrationNonLive htMigrationModes :: FrozenSet String htMigrationModes = ConstantUtils.mkSet $ map Types.migrationModeToRaw [minBound..] -- * Cluster verify steps verifyNplusoneMem :: String verifyNplusoneMem = Types.verifyOptionalChecksToRaw VerifyNPlusOneMem verifyOptionalChecks :: FrozenSet String verifyOptionalChecks = ConstantUtils.mkSet $ map Types.verifyOptionalChecksToRaw [minBound..] -- * Cluster Verify error classes cvTcluster :: String cvTcluster = "cluster" cvTgroup :: String cvTgroup = "group" cvTnode :: String cvTnode = "node" cvTinstance :: String cvTinstance = "instance" -- * Cluster Verify error levels cvWarning :: String cvWarning = "WARNING" cvError :: String cvError = "ERROR" -- * Cluster Verify error codes and documentation cvEclustercert :: (String, String, String) cvEclustercert = ("cluster", Types.cVErrorCodeToRaw CvECLUSTERCERT, "Cluster certificate files verification failure") cvEclusterclientcert :: (String, String, String) cvEclusterclientcert = ("cluster", Types.cVErrorCodeToRaw CvECLUSTERCLIENTCERT, "Cluster client certificate files verification failure") cvEclustercfg :: (String, String, String) cvEclustercfg = ("cluster", Types.cVErrorCodeToRaw CvECLUSTERCFG, "Cluster configuration verification failure") cvEclusterdanglinginst :: (String, String, String) cvEclusterdanglinginst = ("node", Types.cVErrorCodeToRaw CvECLUSTERDANGLINGINST, "Some instances have a non-existing primary node") cvEclusterdanglingnodes :: (String, String, String) cvEclusterdanglingnodes = ("node", Types.cVErrorCodeToRaw CvECLUSTERDANGLINGNODES, "Some nodes belong to non-existing groups") cvEclusterfilecheck :: (String, String, String) cvEclusterfilecheck = ("cluster", Types.cVErrorCodeToRaw CvECLUSTERFILECHECK, "Cluster configuration verification failure") cvEgroupdifferentpvsize :: (String, String, String) cvEgroupdifferentpvsize = ("group", Types.cVErrorCodeToRaw CvEGROUPDIFFERENTPVSIZE, "PVs in the group have different sizes") cvEinstancebadnode :: (String, String, String) cvEinstancebadnode = ("instance", Types.cVErrorCodeToRaw CvEINSTANCEBADNODE, "Instance marked as running lives on an offline node") cvEinstancedown :: (String, String, String) cvEinstancedown = ("instance", Types.cVErrorCodeToRaw CvEINSTANCEDOWN, "Instance not running on its primary node") cvEinstancefaultydisk :: (String, String, String) cvEinstancefaultydisk = ("instance", Types.cVErrorCodeToRaw CvEINSTANCEFAULTYDISK, "Impossible to retrieve status for a disk") cvEinstancelayout :: (String, String, String) cvEinstancelayout = ("instance", Types.cVErrorCodeToRaw CvEINSTANCELAYOUT, "Instance has multiple secondary nodes") cvEinstancemissingcfgparameter :: (String, String, String) cvEinstancemissingcfgparameter = ("instance", Types.cVErrorCodeToRaw CvEINSTANCEMISSINGCFGPARAMETER, "A configuration parameter for an instance is missing") cvEinstancemissingdisk :: (String, String, String) cvEinstancemissingdisk = ("instance", Types.cVErrorCodeToRaw CvEINSTANCEMISSINGDISK, "Missing volume on an instance") cvEinstancepolicy :: (String, String, String) cvEinstancepolicy = ("instance", Types.cVErrorCodeToRaw CvEINSTANCEPOLICY, "Instance does not meet policy") cvEinstancesplitgroups :: (String, String, String) cvEinstancesplitgroups = ("instance", Types.cVErrorCodeToRaw CvEINSTANCESPLITGROUPS, "Instance with primary and secondary nodes in different groups") cvEinstanceunsuitablenode :: (String, String, String) cvEinstanceunsuitablenode = ("instance", Types.cVErrorCodeToRaw CvEINSTANCEUNSUITABLENODE, "Instance running on nodes that are not suitable for it") cvEinstancewrongnode :: (String, String, String) cvEinstancewrongnode = ("instance", Types.cVErrorCodeToRaw CvEINSTANCEWRONGNODE, "Instance running on the wrong node") cvEnodedrbd :: (String, String, String) cvEnodedrbd = ("node", Types.cVErrorCodeToRaw CvENODEDRBD, "Error parsing the DRBD status file") cvEnodedrbdhelper :: (String, String, String) cvEnodedrbdhelper = ("node", Types.cVErrorCodeToRaw CvENODEDRBDHELPER, "Error caused by the DRBD helper") cvEnodedrbdversion :: (String, String, String) cvEnodedrbdversion = ("node", Types.cVErrorCodeToRaw CvENODEDRBDVERSION, "DRBD version mismatch within a node group") cvEnodefilecheck :: (String, String, String) cvEnodefilecheck = ("node", Types.cVErrorCodeToRaw CvENODEFILECHECK, "Error retrieving the checksum of the node files") cvEnodefilestoragepaths :: (String, String, String) cvEnodefilestoragepaths = ("node", Types.cVErrorCodeToRaw CvENODEFILESTORAGEPATHS, "Detected bad file storage paths") cvEnodefilestoragepathunusable :: (String, String, String) cvEnodefilestoragepathunusable = ("node", Types.cVErrorCodeToRaw CvENODEFILESTORAGEPATHUNUSABLE, "File storage path unusable") cvEnodehooks :: (String, String, String) cvEnodehooks = ("node", Types.cVErrorCodeToRaw CvENODEHOOKS, "Communication failure in hooks execution") cvEnodehv :: (String, String, String) cvEnodehv = ("node", Types.cVErrorCodeToRaw CvENODEHV, "Hypervisor parameters verification failure") cvEnodelvm :: (String, String, String) cvEnodelvm = ("node", Types.cVErrorCodeToRaw CvENODELVM, "LVM-related node error") cvEnoden1 :: (String, String, String) cvEnoden1 = ("node", Types.cVErrorCodeToRaw CvENODEN1, "Not enough memory to accommodate instance failovers") cvEextags :: (String, String, String) cvEextags = ("node", Types.cVErrorCodeToRaw CvEEXTAGS, "Instances with same exclusion tag on the same node") cvEnodenet :: (String, String, String) cvEnodenet = ("node", Types.cVErrorCodeToRaw CvENODENET, "Network-related node error") cvEnodeoobpath :: (String, String, String) cvEnodeoobpath = ("node", Types.cVErrorCodeToRaw CvENODEOOBPATH, "Invalid Out Of Band path") cvEnodeorphaninstance :: (String, String, String) cvEnodeorphaninstance = ("node", Types.cVErrorCodeToRaw CvENODEORPHANINSTANCE, "Unknown intance running on a node") cvEnodeorphanlv :: (String, String, String) cvEnodeorphanlv = ("node", Types.cVErrorCodeToRaw CvENODEORPHANLV, "Unknown LVM logical volume") cvEnodeos :: (String, String, String) cvEnodeos = ("node", Types.cVErrorCodeToRaw CvENODEOS, "OS-related node error") cvEnoderpc :: (String, String, String) cvEnoderpc = ("node", Types.cVErrorCodeToRaw CvENODERPC, "Error during connection to the primary node of an instance") cvEnodesetup :: (String, String, String) cvEnodesetup = ("node", Types.cVErrorCodeToRaw CvENODESETUP, "Node setup error") cvEnodesharedfilestoragepathunusable :: (String, String, String) cvEnodesharedfilestoragepathunusable = ("node", Types.cVErrorCodeToRaw CvENODESHAREDFILESTORAGEPATHUNUSABLE, "Shared file storage path unusable") cvEnodeglusterstoragepathunusable :: (String, String, String) cvEnodeglusterstoragepathunusable = ("node", Types.cVErrorCodeToRaw CvENODEGLUSTERSTORAGEPATHUNUSABLE, "Gluster storage path unusable") cvEnodessh :: (String, String, String) cvEnodessh = ("node", Types.cVErrorCodeToRaw CvENODESSH, "SSH-related node error") cvEnodetime :: (String, String, String) cvEnodetime = ("node", Types.cVErrorCodeToRaw CvENODETIME, "Node returned invalid time") cvEnodeuserscripts :: (String, String, String) cvEnodeuserscripts = ("node", Types.cVErrorCodeToRaw CvENODEUSERSCRIPTS, "User scripts not present or not executable") cvEnodeversion :: (String, String, String) cvEnodeversion = ("node", Types.cVErrorCodeToRaw CvENODEVERSION, "Protocol version mismatch or Ganeti version mismatch") cvAllEcodes :: FrozenSet (String, String, String) cvAllEcodes = ConstantUtils.mkSet [cvEclustercert, cvEclustercfg, cvEclusterdanglinginst, cvEclusterdanglingnodes, cvEclusterfilecheck, cvEgroupdifferentpvsize, cvEinstancebadnode, cvEinstancedown, cvEinstancefaultydisk, cvEinstancelayout, cvEinstancemissingcfgparameter, cvEinstancemissingdisk, cvEinstancepolicy, cvEinstancesplitgroups, cvEinstanceunsuitablenode, cvEinstancewrongnode, cvEnodedrbd, cvEnodedrbdhelper, cvEnodedrbdversion, cvEnodefilecheck, cvEnodefilestoragepaths, cvEnodefilestoragepathunusable, cvEnodehooks, cvEnodehv, cvEnodelvm, cvEnoden1, cvEnodenet, cvEnodeoobpath, cvEnodeorphaninstance, cvEnodeorphanlv, cvEnodeos, cvEnoderpc, cvEnodesetup, cvEnodesharedfilestoragepathunusable, cvEnodeglusterstoragepathunusable, cvEnodessh, cvEnodetime, cvEnodeuserscripts, cvEnodeversion] cvAllEcodesStrings :: FrozenSet String cvAllEcodesStrings = ConstantUtils.mkSet $ map Types.cVErrorCodeToRaw [minBound..] -- * Node verify constants nvBridges :: String nvBridges = "bridges" nvClientCert :: String nvClientCert = "client-cert" nvDrbdhelper :: String nvDrbdhelper = "drbd-helper" nvDrbdversion :: String nvDrbdversion = "drbd-version" nvDrbdlist :: String nvDrbdlist = "drbd-list" nvExclusivepvs :: String nvExclusivepvs = "exclusive-pvs" nvFilelist :: String nvFilelist = "filelist" nvAcceptedStoragePaths :: String nvAcceptedStoragePaths = "allowed-file-storage-paths" nvFileStoragePath :: String nvFileStoragePath = "file-storage-path" nvSharedFileStoragePath :: String nvSharedFileStoragePath = "shared-file-storage-path" nvGlusterStoragePath :: String nvGlusterStoragePath = "gluster-storage-path" nvHvinfo :: String nvHvinfo = "hvinfo" nvHvparams :: String nvHvparams = "hvparms" nvHypervisor :: String nvHypervisor = "hypervisor" nvInstancelist :: String nvInstancelist = "instancelist" nvLvlist :: String nvLvlist = "lvlist" nvMasterip :: String nvMasterip = "master-ip" nvNodelist :: String nvNodelist = "nodelist" nvNodenettest :: String nvNodenettest = "node-net-test" nvNodesetup :: String nvNodesetup = "nodesetup" nvOobPaths :: String nvOobPaths = "oob-paths" nvOslist :: String nvOslist = "oslist" nvPvlist :: String nvPvlist = "pvlist" nvTime :: String nvTime = "time" nvUserscripts :: String nvUserscripts = "user-scripts" nvVersion :: String nvVersion = "version" nvVglist :: String nvVglist = "vglist" nvNonvmnodes :: String nvNonvmnodes = "nonvmnodes" nvSshSetup :: String nvSshSetup = "ssh-setup" nvSshClutter :: String nvSshClutter = "ssh-clutter" -- * Instance status inststAdmindown :: String inststAdmindown = Types.instanceStatusToRaw StatusDown inststAdminoffline :: String inststAdminoffline = Types.instanceStatusToRaw StatusOffline inststErrordown :: String inststErrordown = Types.instanceStatusToRaw ErrorDown inststErrorup :: String inststErrorup = Types.instanceStatusToRaw ErrorUp inststNodedown :: String inststNodedown = Types.instanceStatusToRaw NodeDown inststNodeoffline :: String inststNodeoffline = Types.instanceStatusToRaw NodeOffline inststRunning :: String inststRunning = Types.instanceStatusToRaw Running inststUserdown :: String inststUserdown = Types.instanceStatusToRaw UserDown inststWrongnode :: String inststWrongnode = Types.instanceStatusToRaw WrongNode inststAll :: FrozenSet String inststAll = ConstantUtils.mkSet $ map Types.instanceStatusToRaw [minBound..] -- * Admin states adminstDown :: String adminstDown = Types.adminStateToRaw AdminDown adminstOffline :: String adminstOffline = Types.adminStateToRaw AdminOffline adminstUp :: String adminstUp = Types.adminStateToRaw AdminUp adminstAll :: FrozenSet String adminstAll = ConstantUtils.mkSet $ map Types.adminStateToRaw [minBound..] -- * Admin state sources adminSource :: AdminStateSource adminSource = AdminSource userSource :: AdminStateSource userSource = UserSource adminStateSources :: FrozenSet AdminStateSource adminStateSources = ConstantUtils.mkSet [minBound..] -- * Node roles nrDrained :: String nrDrained = Types.nodeRoleToRaw NRDrained nrMaster :: String nrMaster = Types.nodeRoleToRaw NRMaster nrMcandidate :: String nrMcandidate = Types.nodeRoleToRaw NRCandidate nrOffline :: String nrOffline = Types.nodeRoleToRaw NROffline nrRegular :: String nrRegular = Types.nodeRoleToRaw NRRegular nrAll :: FrozenSet String nrAll = ConstantUtils.mkSet $ map Types.nodeRoleToRaw [minBound..] -- * SSL certificate check constants (in days) sslCertExpirationError :: Int sslCertExpirationError = 7 sslCertExpirationWarn :: Int sslCertExpirationWarn = 30 -- * Allocator framework constants iallocatorVersion :: Int iallocatorVersion = 2 iallocatorDirIn :: String iallocatorDirIn = Types.iAllocatorTestDirToRaw IAllocatorDirIn iallocatorDirOut :: String iallocatorDirOut = Types.iAllocatorTestDirToRaw IAllocatorDirOut validIallocatorDirections :: FrozenSet String validIallocatorDirections = ConstantUtils.mkSet $ map Types.iAllocatorTestDirToRaw [minBound..] iallocatorModeAlloc :: String iallocatorModeAlloc = Types.iAllocatorModeToRaw IAllocatorAlloc iallocatorModeAllocateSecondary :: String iallocatorModeAllocateSecondary = Types.iAllocatorModeToRaw IAllocatorAllocateSecondary iallocatorModeChgGroup :: String iallocatorModeChgGroup = Types.iAllocatorModeToRaw IAllocatorChangeGroup iallocatorModeMultiAlloc :: String iallocatorModeMultiAlloc = Types.iAllocatorModeToRaw IAllocatorMultiAlloc iallocatorModeNodeEvac :: String iallocatorModeNodeEvac = Types.iAllocatorModeToRaw IAllocatorNodeEvac iallocatorModeReloc :: String iallocatorModeReloc = Types.iAllocatorModeToRaw IAllocatorReloc validIallocatorModes :: FrozenSet String validIallocatorModes = ConstantUtils.mkSet $ map Types.iAllocatorModeToRaw [minBound..] iallocatorSearchPath :: [String] iallocatorSearchPath = AutoConf.iallocatorSearchPath defaultIallocatorShortcut :: String defaultIallocatorShortcut = "." -- * Opportunistic allocator usage -- | Time delay in seconds between repeated opportunistic instance creations. -- Rather than failing with an informative error message if the opportunistic -- creation cannot grab enough nodes, for some uses it is better to retry the -- creation with an interval between attempts. This is a reasonable default. defaultOpportunisticRetryInterval :: Int defaultOpportunisticRetryInterval = 30 -- * Node evacuation nodeEvacPri :: String nodeEvacPri = Types.evacModeToRaw ChangePrimary nodeEvacSec :: String nodeEvacSec = Types.evacModeToRaw ChangeSecondary nodeEvacAll :: String nodeEvacAll = Types.evacModeToRaw ChangeAll nodeEvacModes :: FrozenSet String nodeEvacModes = ConstantUtils.mkSet $ map Types.evacModeToRaw [minBound..] -- * Job queue jobQueueVersion :: Int jobQueueVersion = 1 jobQueueSizeHardLimit :: Int jobQueueSizeHardLimit = 5000 jobQueueFilesPerms :: Int jobQueueFilesPerms = 0o640 -- * Unchanged job return jobNotchanged :: String jobNotchanged = "nochange" -- * Job status jobStatusQueued :: String jobStatusQueued = Types.jobStatusToRaw JOB_STATUS_QUEUED jobStatusWaiting :: String jobStatusWaiting = Types.jobStatusToRaw JOB_STATUS_WAITING jobStatusCanceling :: String jobStatusCanceling = Types.jobStatusToRaw JOB_STATUS_CANCELING jobStatusRunning :: String jobStatusRunning = Types.jobStatusToRaw JOB_STATUS_RUNNING jobStatusCanceled :: String jobStatusCanceled = Types.jobStatusToRaw JOB_STATUS_CANCELED jobStatusSuccess :: String jobStatusSuccess = Types.jobStatusToRaw JOB_STATUS_SUCCESS jobStatusError :: String jobStatusError = Types.jobStatusToRaw JOB_STATUS_ERROR jobsPending :: FrozenSet String jobsPending = ConstantUtils.mkSet [jobStatusQueued, jobStatusWaiting, jobStatusCanceling] jobsFinalized :: FrozenSet String jobsFinalized = ConstantUtils.mkSet $ map Types.finalizedJobStatusToRaw [minBound..] jobStatusAll :: FrozenSet String jobStatusAll = ConstantUtils.mkSet $ map Types.jobStatusToRaw [minBound..] -- * OpCode status -- ** Not yet finalized opcodes opStatusCanceling :: String opStatusCanceling = "canceling" opStatusQueued :: String opStatusQueued = "queued" opStatusRunning :: String opStatusRunning = "running" opStatusWaiting :: String opStatusWaiting = "waiting" -- ** Finalized opcodes opStatusCanceled :: String opStatusCanceled = "canceled" opStatusError :: String opStatusError = "error" opStatusSuccess :: String opStatusSuccess = "success" opsFinalized :: FrozenSet String opsFinalized = ConstantUtils.mkSet [opStatusCanceled, opStatusError, opStatusSuccess] -- * OpCode priority opPrioLowest :: Int opPrioLowest = 19 opPrioHighest :: Int opPrioHighest = -20 opPrioLow :: Int opPrioLow = Types.opSubmitPriorityToRaw OpPrioLow opPrioNormal :: Int opPrioNormal = Types.opSubmitPriorityToRaw OpPrioNormal opPrioHigh :: Int opPrioHigh = Types.opSubmitPriorityToRaw OpPrioHigh opPrioSubmitValid :: FrozenSet Int opPrioSubmitValid = ConstantUtils.mkSet [opPrioLow, opPrioNormal, opPrioHigh] opPrioDefault :: Int opPrioDefault = opPrioNormal -- * Lock recalculate mode locksAppend :: String locksAppend = "append" locksReplace :: String locksReplace = "replace" -- * Lock timeout -- -- The lock timeout (sum) before we transition into blocking acquire -- (this can still be reset by priority change). Computed as max time -- (10 hours) before we should actually go into blocking acquire, -- given that we start from the default priority level. lockAttemptsMaxwait :: Double lockAttemptsMaxwait = 75.0 lockAttemptsMinwait :: Double lockAttemptsMinwait = 5.0 lockAttemptsTimeout :: Int lockAttemptsTimeout = (10 * 3600) `div` (opPrioDefault - opPrioHighest) -- * Execution log types elogMessage :: String elogMessage = Types.eLogTypeToRaw ELogMessage -- ELogMessageList is internal to Python code only, used to distinguish -- calling conventions in Feedback(), but is never serialized or loaded -- in Luxi. elogMessageList :: String elogMessageList = Types.eLogTypeToRaw ELogMessageList elogRemoteImport :: String elogRemoteImport = Types.eLogTypeToRaw ELogRemoteImport elogJqueueTest :: String elogJqueueTest = Types.eLogTypeToRaw ELogJqueueTest elogDelayTest :: String elogDelayTest = Types.eLogTypeToRaw ELogDelayTest -- * /etc/hosts modification etcHostsAdd :: String etcHostsAdd = "add" etcHostsRemove :: String etcHostsRemove = "remove" -- * Job queue test jqtMsgprefix :: String jqtMsgprefix = "TESTMSG=" jqtExec :: String jqtExec = "exec" jqtExpandnames :: String jqtExpandnames = "expandnames" jqtLogmsg :: String jqtLogmsg = "logmsg" jqtStartmsg :: String jqtStartmsg = "startmsg" jqtAll :: FrozenSet String jqtAll = ConstantUtils.mkSet [jqtExec, jqtExpandnames, jqtLogmsg, jqtStartmsg] -- * Query resources qrCluster :: String qrCluster = "cluster" qrExport :: String qrExport = "export" qrExtstorage :: String qrExtstorage = "extstorage" qrGroup :: String qrGroup = "group" qrInstance :: String qrInstance = "instance" qrJob :: String qrJob = "job" qrLock :: String qrLock = "lock" qrNetwork :: String qrNetwork = "network" qrFilter :: String qrFilter = "filter" qrNode :: String qrNode = "node" qrOs :: String qrOs = "os" -- | List of resources which can be queried using 'Ganeti.OpCodes.OpQuery' qrViaOp :: FrozenSet String qrViaOp = ConstantUtils.mkSet [qrCluster, qrOs, qrExtstorage] -- | List of resources which can be queried using Local UniX Interface qrViaLuxi :: FrozenSet String qrViaLuxi = ConstantUtils.mkSet [qrGroup, qrExport, qrInstance, qrJob, qrLock, qrNetwork, qrNode, qrFilter] -- | List of resources which can be queried using RAPI qrViaRapi :: FrozenSet String qrViaRapi = qrViaLuxi -- | List of resources which can be queried via RAPI including PUT requests qrViaRapiPut :: FrozenSet String qrViaRapiPut = ConstantUtils.mkSet [qrLock, qrJob, qrFilter] -- * Query field types qftBool :: String qftBool = "bool" qftNumber :: String qftNumber = "number" qftNumberFloat :: String qftNumberFloat = "float" qftOther :: String qftOther = "other" qftText :: String qftText = "text" qftTimestamp :: String qftTimestamp = "timestamp" qftUnit :: String qftUnit = "unit" qftUnknown :: String qftUnknown = "unknown" qftAll :: FrozenSet String qftAll = ConstantUtils.mkSet [qftBool, qftNumber, qftNumberFloat, qftOther, qftText, qftTimestamp, qftUnit, qftUnknown] -- * Query result field status -- -- Don't change or reuse values as they're used by clients. -- -- FIXME: link with 'Ganeti.Query.Language.ResultStatus' -- | No data (e.g. RPC error), can be used instead of 'rsOffline' rsNodata :: Int rsNodata = 2 rsNormal :: Int rsNormal = 0 -- | Resource marked offline rsOffline :: Int rsOffline = 4 -- | Value unavailable/unsupported for item; if this field is -- supported but we cannot get the data for the moment, 'rsNodata' or -- 'rsOffline' should be used rsUnavail :: Int rsUnavail = 3 rsUnknown :: Int rsUnknown = 1 rsAll :: FrozenSet Int rsAll = ConstantUtils.mkSet [rsNodata, rsNormal, rsOffline, rsUnavail, rsUnknown] -- | Special field cases and their verbose/terse formatting rssDescription :: Map Int (String, String) rssDescription = Map.fromList [(rsUnknown, ("(unknown)", "??")), (rsNodata, ("(nodata)", "?")), (rsOffline, ("(offline)", "*")), (rsUnavail, ("(unavail)", "-"))] -- * Max dynamic devices maxDisks :: Int maxDisks = Types.maxDisks maxNics :: Int maxNics = Types.maxNics -- | SSCONF file prefix ssconfFileprefix :: String ssconfFileprefix = "ssconf_" -- * SSCONF keys ssClusterName :: String ssClusterName = "cluster_name" ssClusterTags :: String ssClusterTags = "cluster_tags" ssFileStorageDir :: String ssFileStorageDir = "file_storage_dir" ssSharedFileStorageDir :: String ssSharedFileStorageDir = "shared_file_storage_dir" ssGlusterStorageDir :: String ssGlusterStorageDir = "gluster_storage_dir" ssMasterCandidates :: String ssMasterCandidates = "master_candidates" ssMasterCandidatesIps :: String ssMasterCandidatesIps = "master_candidates_ips" ssMasterCandidatesCerts :: String ssMasterCandidatesCerts = "master_candidates_certs" ssMasterIp :: String ssMasterIp = "master_ip" ssMasterNetdev :: String ssMasterNetdev = "master_netdev" ssMasterNetmask :: String ssMasterNetmask = "master_netmask" ssMasterNode :: String ssMasterNode = "master_node" ssNodeList :: String ssNodeList = "node_list" ssNodePrimaryIps :: String ssNodePrimaryIps = "node_primary_ips" ssNodeSecondaryIps :: String ssNodeSecondaryIps = "node_secondary_ips" ssNodeVmCapable :: String ssNodeVmCapable = "node_vm_capable" ssOfflineNodes :: String ssOfflineNodes = "offline_nodes" ssOnlineNodes :: String ssOnlineNodes = "online_nodes" ssPrimaryIpFamily :: String ssPrimaryIpFamily = "primary_ip_family" ssInstanceList :: String ssInstanceList = "instance_list" ssReleaseVersion :: String ssReleaseVersion = "release_version" ssHypervisorList :: String ssHypervisorList = "hypervisor_list" ssMaintainNodeHealth :: String ssMaintainNodeHealth = "maintain_node_health" ssUidPool :: String ssUidPool = "uid_pool" ssNodegroups :: String ssNodegroups = "nodegroups" ssNetworks :: String ssNetworks = "networks" -- | This is not a complete SSCONF key, but the prefix for the -- hypervisor keys ssHvparamsPref :: String ssHvparamsPref = "hvparams_" -- * Hvparams keys ssHvparamsXenChroot :: String ssHvparamsXenChroot = ssHvparamsPref ++ htChroot ssHvparamsXenFake :: String ssHvparamsXenFake = ssHvparamsPref ++ htFake ssHvparamsXenHvm :: String ssHvparamsXenHvm = ssHvparamsPref ++ htXenHvm ssHvparamsXenKvm :: String ssHvparamsXenKvm = ssHvparamsPref ++ htKvm ssHvparamsXenLxc :: String ssHvparamsXenLxc = ssHvparamsPref ++ htLxc ssHvparamsXenPvm :: String ssHvparamsXenPvm = ssHvparamsPref ++ htXenPvm validSsHvparamsKeys :: FrozenSet String validSsHvparamsKeys = ConstantUtils.mkSet [ssHvparamsXenChroot, ssHvparamsXenLxc, ssHvparamsXenFake, ssHvparamsXenHvm, ssHvparamsXenKvm, ssHvparamsXenPvm] ssFilePerms :: Int ssFilePerms = 0o444 ssEnabledUserShutdown :: String ssEnabledUserShutdown = "enabled_user_shutdown" ssSshPorts :: String ssSshPorts = "ssh_ports" validSsKeys :: FrozenSet String validSsKeys = ConstantUtils.mkSet [ ssClusterName , ssClusterTags , ssFileStorageDir , ssSharedFileStorageDir , ssGlusterStorageDir , ssMasterCandidates , ssMasterCandidatesIps , ssMasterCandidatesCerts , ssMasterIp , ssMasterNetdev , ssMasterNetmask , ssMasterNode , ssNodeList , ssNodePrimaryIps , ssNodeSecondaryIps , ssNodeVmCapable , ssOfflineNodes , ssOnlineNodes , ssPrimaryIpFamily , ssInstanceList , ssReleaseVersion , ssHypervisorList , ssMaintainNodeHealth , ssUidPool , ssNodegroups , ssNetworks , ssEnabledUserShutdown , ssSshPorts ] <> validSsHvparamsKeys -- | Cluster wide default parameters defaultEnabledHypervisor :: String defaultEnabledHypervisor = htXenPvm hvcDefaults :: Map Hypervisor (Map String PyValueEx) hvcDefaults = Map.fromList [ (XenPvm, Map.fromList [ (hvUseBootloader, PyValueEx False) , (hvBootloaderPath, PyValueEx xenBootloader) , (hvBootloaderArgs, PyValueEx "") , (hvKernelPath, PyValueEx xenKernel) , (hvInitrdPath, PyValueEx "") , (hvRootPath, PyValueEx "/dev/xvda1") , (hvKernelArgs, PyValueEx "ro") , (hvMigrationPort, PyValueEx (8002 :: Int)) , (hvMigrationMode, PyValueEx htMigrationLive) , (hvBlockdevPrefix, PyValueEx "sd") , (hvRebootBehavior, PyValueEx instanceRebootAllowed) , (hvCpuMask, PyValueEx cpuPinningAll) , (hvCpuCap, PyValueEx (0 :: Int)) , (hvCpuWeight, PyValueEx (256 :: Int)) , (hvVifScript, PyValueEx "") , (hvXenCmd, PyValueEx xenCmdXm) , (hvXenCpuid, PyValueEx "") , (hvSoundhw, PyValueEx "") ]) , (XenHvm, Map.fromList [ (hvBootOrder, PyValueEx "cd") , (hvCdromImagePath, PyValueEx "") , (hvNicType, PyValueEx htNicRtl8139) , (hvDiskType, PyValueEx htDiskParavirtual) , (hvVncBindAddress, PyValueEx ip4AddressAny) , (hvAcpi, PyValueEx True) , (hvPae, PyValueEx True) , (hvKernelPath, PyValueEx "/usr/lib/xen/boot/hvmloader") , (hvDeviceModel, PyValueEx "/usr/lib/xen/bin/qemu-dm") , (hvMigrationPort, PyValueEx (8002 :: Int)) , (hvMigrationMode, PyValueEx htMigrationNonlive) , (hvUseLocaltime, PyValueEx False) , (hvBlockdevPrefix, PyValueEx "hd") , (hvPassthrough, PyValueEx "") , (hvRebootBehavior, PyValueEx instanceRebootAllowed) , (hvCpuMask, PyValueEx cpuPinningAll) , (hvCpuCap, PyValueEx (0 :: Int)) , (hvCpuWeight, PyValueEx (256 :: Int)) , (hvVifType, PyValueEx htHvmVifIoemu) , (hvVifScript, PyValueEx "") , (hvViridian, PyValueEx False) , (hvXenCmd, PyValueEx xenCmdXm) , (hvXenCpuid, PyValueEx "") , (hvSoundhw, PyValueEx "") ]) , (Kvm, Map.fromList [ (hvKvmPath, PyValueEx kvmPath) , (hvKernelPath, PyValueEx kvmKernel) , (hvInitrdPath, PyValueEx "") , (hvKernelArgs, PyValueEx "ro") , (hvRootPath, PyValueEx "/dev/vda1") , (hvAcpi, PyValueEx True) , (hvSerialConsole, PyValueEx True) , (hvSerialSpeed, PyValueEx (38400 :: Int)) , (hvVncBindAddress, PyValueEx "") , (hvVncTls, PyValueEx False) , (hvVncX509, PyValueEx "") , (hvVncX509Verify, PyValueEx False) , (hvVncPasswordFile, PyValueEx "") , (hvKvmScsiControllerType, PyValueEx htScsiControllerLsi) , (hvKvmPciReservations, PyValueEx qemuDefaultPciReservations) , (hvKvmSpiceBind, PyValueEx "") , (hvKvmSpiceIpVersion, PyValueEx ifaceNoIpVersionSpecified) , (hvKvmSpicePasswordFile, PyValueEx "") , (hvKvmSpiceLosslessImgCompr, PyValueEx "") , (hvKvmSpiceJpegImgCompr, PyValueEx "") , (hvKvmSpiceZlibGlzImgCompr, PyValueEx "") , (hvKvmSpiceStreamingVideoDetection, PyValueEx "") , (hvKvmSpiceAudioCompr, PyValueEx True) , (hvKvmSpiceUseTls, PyValueEx False) , (hvKvmSpiceTlsCiphers, PyValueEx opensslCiphers) , (hvKvmSpiceUseVdagent, PyValueEx True) , (hvKvmFloppyImagePath, PyValueEx "") , (hvCdromImagePath, PyValueEx "") , (hvKvmCdrom2ImagePath, PyValueEx "") , (hvBootOrder, PyValueEx htBoDisk) , (hvNicType, PyValueEx htNicParavirtual) , (hvDiskType, PyValueEx htDiskParavirtual) , (hvKvmCdromDiskType, PyValueEx "") , (hvKvmDiskAio, PyValueEx htKvmAioThreads) , (hvUsbMouse, PyValueEx "") , (hvKeymap, PyValueEx "") , (hvMigrationPort, PyValueEx (8102 :: Int)) , (hvMigrationBandwidth, PyValueEx (32 :: Int)) , (hvMigrationDowntime, PyValueEx (30 :: Int)) , (hvMigrationMode, PyValueEx htMigrationLive) , (hvUseLocaltime, PyValueEx False) , (hvDiskCache, PyValueEx htCacheDefault) , (hvSecurityModel, PyValueEx htSmNone) , (hvSecurityDomain, PyValueEx "") , (hvKvmFlag, PyValueEx "") , (hvVhostNet, PyValueEx False) , (hvVirtioNetQueues, PyValueEx (1 :: Int)) , (hvKvmUseChroot, PyValueEx False) , (hvKvmUserShutdown, PyValueEx False) , (hvMemPath, PyValueEx "") , (hvRebootBehavior, PyValueEx instanceRebootAllowed) , (hvCpuMask, PyValueEx cpuPinningAll) , (hvWorkerCpuMask, PyValueEx cpuPinningAll) , (hvCpuType, PyValueEx "") , (hvCpuCores, PyValueEx (0 :: Int)) , (hvCpuThreads, PyValueEx (0 :: Int)) , (hvCpuSockets, PyValueEx (0 :: Int)) , (hvSoundhw, PyValueEx "") , (hvUsbDevices, PyValueEx "") , (hvVga, PyValueEx "") , (hvKvmExtra, PyValueEx "") , (hvKvmMachineVersion, PyValueEx "") , (hvKvmMigrationCaps, PyValueEx "") , (hvVnetHdr, PyValueEx True)]) , (Fake, Map.fromList [(hvMigrationMode, PyValueEx htMigrationLive)]) , (Chroot, Map.fromList [(hvInitScript, PyValueEx "/ganeti-chroot")]) , (Lxc, Map.fromList [ (hvCpuMask, PyValueEx "") , (hvLxcDevices, PyValueEx lxcDevicesDefault) , (hvLxcDropCapabilities, PyValueEx lxcDropCapabilitiesDefault) , (hvLxcExtraCgroups, PyValueEx "") , (hvLxcExtraConfig, PyValueEx "") , (hvLxcNumTtys, PyValueEx (6 :: Int)) , (hvLxcStartupTimeout, PyValueEx (30 :: Int)) ]) ] hvcGlobals :: FrozenSet String hvcGlobals = ConstantUtils.mkSet [hvMigrationBandwidth, hvMigrationMode, hvMigrationPort, hvXenCmd] becDefaults :: Map String PyValueEx becDefaults = Map.fromList [ (beMinmem, PyValueEx (128 :: Int)) , (beMaxmem, PyValueEx (128 :: Int)) , (beVcpus, PyValueEx (1 :: Int)) , (beAutoBalance, PyValueEx True) , (beAlwaysFailover, PyValueEx False) , (beSpindleUse, PyValueEx (1 :: Int)) ] ndcDefaults :: Map String PyValueEx ndcDefaults = Map.fromList [ (ndOobProgram, PyValueEx "") , (ndSpindleCount, PyValueEx (1 :: Int)) , (ndExclusiveStorage, PyValueEx False) , (ndOvs, PyValueEx False) , (ndOvsName, PyValueEx defaultOvs) , (ndOvsLink, PyValueEx "") , (ndSshPort, PyValueEx (22 :: Int)) , (ndCpuSpeed, PyValueEx (1 :: Double)) ] ndcGlobals :: FrozenSet String ndcGlobals = ConstantUtils.mkSet [ndExclusiveStorage] -- | Default delay target measured in sectors defaultDelayTarget :: Int defaultDelayTarget = 1 defaultDiskCustom :: String defaultDiskCustom = "" defaultDiskResync :: Bool defaultDiskResync = False -- | Default fill target measured in sectors defaultFillTarget :: Int defaultFillTarget = 0 -- | Default mininum rate measured in KiB/s defaultMinRate :: Int defaultMinRate = 4 * 1024 defaultNetCustom :: String defaultNetCustom = "" -- | Default plan ahead measured in sectors -- -- The default values for the DRBD dynamic resync speed algorithm are -- taken from the drbsetup 8.3.11 man page, except for c-plan-ahead -- (that we don't need to set to 0, because we have a separate option -- to enable it) and for c-max-rate, that we cap to the default value -- for the static resync rate. defaultPlanAhead :: Int defaultPlanAhead = 20 defaultRbdPool :: String defaultRbdPool = "rbd" diskLdDefaults :: Map DiskTemplate (Map String PyValueEx) diskLdDefaults = Map.fromList [ (DTBlock, Map.empty) , (DTDrbd8, Map.fromList [ (ldpBarriers, PyValueEx drbdBarriers) , (ldpDefaultMetavg, PyValueEx defaultVg) , (ldpDelayTarget, PyValueEx defaultDelayTarget) , (ldpDiskCustom, PyValueEx defaultDiskCustom) , (ldpDynamicResync, PyValueEx defaultDiskResync) , (ldpFillTarget, PyValueEx defaultFillTarget) , (ldpMaxRate, PyValueEx classicDrbdSyncSpeed) , (ldpMinRate, PyValueEx defaultMinRate) , (ldpNetCustom, PyValueEx defaultNetCustom) , (ldpNoMetaFlush, PyValueEx drbdNoMetaFlush) , (ldpPlanAhead, PyValueEx defaultPlanAhead) , (ldpProtocol, PyValueEx drbdDefaultNetProtocol) , (ldpResyncRate, PyValueEx classicDrbdSyncSpeed) ]) , (DTExt, Map.fromList [ (ldpAccess, PyValueEx diskKernelspace) ]) , (DTFile, Map.empty) , (DTPlain, Map.fromList [(ldpStripes, PyValueEx lvmStripecount)]) , (DTRbd, Map.fromList [ (ldpPool, PyValueEx defaultRbdPool) , (ldpAccess, PyValueEx diskKernelspace) ]) , (DTSharedFile, Map.empty) , (DTGluster, Map.fromList [ (rbdAccess, PyValueEx diskKernelspace) , (glusterHost, PyValueEx glusterHostDefault) , (glusterVolume, PyValueEx glusterVolumeDefault) , (glusterPort, PyValueEx glusterPortDefault) ]) ] diskDtDefaults :: Map DiskTemplate (Map String PyValueEx) diskDtDefaults = Map.fromList [ (DTBlock, Map.empty) , (DTDiskless, Map.empty) , (DTDrbd8, Map.fromList [ (drbdDataStripes, PyValueEx lvmStripecount) , (drbdDefaultMetavg, PyValueEx defaultVg) , (drbdDelayTarget, PyValueEx defaultDelayTarget) , (drbdDiskBarriers, PyValueEx drbdBarriers) , (drbdDiskCustom, PyValueEx defaultDiskCustom) , (drbdDynamicResync, PyValueEx defaultDiskResync) , (drbdFillTarget, PyValueEx defaultFillTarget) , (drbdMaxRate, PyValueEx classicDrbdSyncSpeed) , (drbdMetaBarriers, PyValueEx drbdNoMetaFlush) , (drbdMetaStripes, PyValueEx lvmStripecount) , (drbdMinRate, PyValueEx defaultMinRate) , (drbdNetCustom, PyValueEx defaultNetCustom) , (drbdPlanAhead, PyValueEx defaultPlanAhead) , (drbdProtocol, PyValueEx drbdDefaultNetProtocol) , (drbdResyncRate, PyValueEx classicDrbdSyncSpeed) ]) , (DTExt, Map.fromList [ (rbdAccess, PyValueEx diskKernelspace) ]) , (DTFile, Map.empty) , (DTPlain, Map.fromList [(lvStripes, PyValueEx lvmStripecount)]) , (DTRbd, Map.fromList [ (rbdPool, PyValueEx defaultRbdPool) , (rbdAccess, PyValueEx diskKernelspace) ]) , (DTSharedFile, Map.empty) , (DTGluster, Map.fromList [ (rbdAccess, PyValueEx diskKernelspace) , (glusterHost, PyValueEx glusterHostDefault) , (glusterVolume, PyValueEx glusterVolumeDefault) , (glusterPort, PyValueEx glusterPortDefault) ]) ] niccDefaults :: Map String PyValueEx niccDefaults = Map.fromList [ (nicMode, PyValueEx nicModeBridged) , (nicLink, PyValueEx defaultBridge) , (nicVlan, PyValueEx "") ] -- | All of the following values are quite arbitrary - there are no -- "good" defaults, these must be customised per-site ispecsMinmaxDefaults :: Map String (Map String Int) ispecsMinmaxDefaults = Map.fromList [(ispecsMin, Map.fromList [(ConstantUtils.ispecMemSize, Types.iSpecMemorySize Types.defMinISpec), (ConstantUtils.ispecCpuCount, Types.iSpecCpuCount Types.defMinISpec), (ConstantUtils.ispecDiskCount, Types.iSpecDiskCount Types.defMinISpec), (ConstantUtils.ispecDiskSize, Types.iSpecDiskSize Types.defMinISpec), (ConstantUtils.ispecNicCount, Types.iSpecNicCount Types.defMinISpec), (ConstantUtils.ispecSpindleUse, Types.iSpecSpindleUse Types.defMinISpec)]), (ispecsMax, Map.fromList [(ConstantUtils.ispecMemSize, Types.iSpecMemorySize Types.defMaxISpec), (ConstantUtils.ispecCpuCount, Types.iSpecCpuCount Types.defMaxISpec), (ConstantUtils.ispecDiskCount, Types.iSpecDiskCount Types.defMaxISpec), (ConstantUtils.ispecDiskSize, Types.iSpecDiskSize Types.defMaxISpec), (ConstantUtils.ispecNicCount, Types.iSpecNicCount Types.defMaxISpec), (ConstantUtils.ispecSpindleUse, Types.iSpecSpindleUse Types.defMaxISpec)])] ipolicyDefaults :: Map String PyValueEx ipolicyDefaults = Map.fromList [ (ispecsMinmax, PyValueEx [ispecsMinmaxDefaults]) , (ispecsStd, PyValueEx (Map.fromList [ (ispecMemSize, 128) , (ispecCpuCount, 1) , (ispecDiskCount, 1) , (ispecDiskSize, 1024) , (ispecNicCount, 1) , (ispecSpindleUse, 1) ] :: Map String Int)) , (ipolicyDts, PyValueEx (ConstantUtils.toList diskTemplates)) , (ipolicyVcpuRatio, PyValueEx ConstantUtils.ipolicyDefaultsVcpuRatio) , (ipolicySpindleRatio, PyValueEx ConstantUtils.ipolicyDefaultsSpindleRatio) , (ipolicyMemoryRatio, PyValueEx ConstantUtils.ipolicyDefaultsMemoryRatio) ] masterPoolSizeDefault :: Int masterPoolSizeDefault = 10 -- * Exclusive storage -- | Error margin used to compare physical disks partMargin :: Double partMargin = 0.01 -- | Space reserved when creating instance disks partReserved :: Double partReserved = 0.02 -- * Luxid job scheduling -- | Time intervall in seconds for polling updates on the job queue. This -- intervall is only relevant if the number of running jobs reaches the maximal -- allowed number, as otherwise new jobs will be started immediately anyway. -- Also, as jobs are watched via inotify, scheduling usually works independent -- of polling. Therefore we chose a sufficiently large interval, in the order of -- 5 minutes. As with the interval for reloading the configuration, we chose a -- prime number to avoid accidental 'same wakeup' with other processes. luxidJobqueuePollInterval :: Int luxidJobqueuePollInterval = 307 -- | The default value for the maximal number of jobs to be running at the same -- time. Once the maximal number is reached, new jobs will just be queued and -- only started, once some of the other jobs have finished. luxidMaximalRunningJobsDefault :: Int luxidMaximalRunningJobsDefault = 20 -- | The default value for the maximal number of jobs that luxid tracks via -- inotify. If the number of running jobs exceeds this limit (which only happens -- if the user increases the default value of maximal running jobs), new forked -- jobs are no longer tracked by inotify; progress will still be noticed on the -- regular polls. luxidMaximalTrackedJobsDefault :: Int luxidMaximalTrackedJobsDefault = 25 -- | The number of retries when trying to @fork@ a new job. -- Due to a bug in GHC, this can fail even though we synchronize all forks -- and restrain from other @IO@ operations in the thread. luxidRetryForkCount :: Int luxidRetryForkCount = 5 -- | The average time period (in /us/) to wait between two @fork@ attempts. -- The forking thread wait a random time period between @0@ and twice the -- number, and with each attempt it doubles the step. -- See 'luxidRetryForkCount'. luxidRetryForkStepUS :: Int luxidRetryForkStepUS = 500000 -- * Luxid job death testing -- | The number of attempts to prove that a job is dead after sending it a -- KILL signal. luxidJobDeathDetectionRetries :: Int luxidJobDeathDetectionRetries = 3 -- | Time to delay (in /us/) after unsucessfully verifying the death of a -- job we believe to be dead. This is best choosen to be the average time -- sending a SIGKILL to take effect. luxidJobDeathDelay :: Int luxidJobDeathDelay = 100000 -- * WConfD -- | Time itnervall in seconds between checks that all lock owners are still -- alive, and cleaning up the resources for the dead ones. As jobs dying without -- releasing resources is the exception, not the rule, we don't want this task -- to take up too many cycles itself. Hence we choose a sufficiently large -- intervall, in the order of 5 minutes. To avoid accidental 'same wakeup' -- with other tasks, we choose the next unused prime number. wconfdDeathdetectionIntervall :: Int wconfdDeathdetectionIntervall = 311 wconfdDefCtmo :: Int wconfdDefCtmo = 10 wconfdDefRwto :: Int wconfdDefRwto = 60 -- | The prefix of the WConfD livelock file name. wconfLivelockPrefix :: String wconfLivelockPrefix = "wconf-daemon" -- * Confd confdProtocolVersion :: Int confdProtocolVersion = ConstantUtils.confdProtocolVersion -- Confd request type confdReqPing :: Int confdReqPing = Types.confdRequestTypeToRaw ReqPing confdReqNodeRoleByname :: Int confdReqNodeRoleByname = Types.confdRequestTypeToRaw ReqNodeRoleByName confdReqNodePipByInstanceIp :: Int confdReqNodePipByInstanceIp = Types.confdRequestTypeToRaw ReqNodePipByInstPip confdReqClusterMaster :: Int confdReqClusterMaster = Types.confdRequestTypeToRaw ReqClusterMaster confdReqNodePipList :: Int confdReqNodePipList = Types.confdRequestTypeToRaw ReqNodePipList confdReqMcPipList :: Int confdReqMcPipList = Types.confdRequestTypeToRaw ReqMcPipList confdReqInstancesIpsList :: Int confdReqInstancesIpsList = Types.confdRequestTypeToRaw ReqInstIpsList confdReqNodeDrbd :: Int confdReqNodeDrbd = Types.confdRequestTypeToRaw ReqNodeDrbd confdReqNodeInstances :: Int confdReqNodeInstances = Types.confdRequestTypeToRaw ReqNodeInstances confdReqInstanceDisks :: Int confdReqInstanceDisks = Types.confdRequestTypeToRaw ReqInstanceDisks confdReqConfigQuery :: Int confdReqConfigQuery = Types.confdRequestTypeToRaw ReqConfigQuery confdReqDataCollectors :: Int confdReqDataCollectors = Types.confdRequestTypeToRaw ReqDataCollectors confdReqs :: FrozenSet Int confdReqs = ConstantUtils.mkSet . map Types.confdRequestTypeToRaw $ [minBound..] \\ [ReqNodeInstances] -- * Confd request type confdReqfieldName :: Int confdReqfieldName = Types.confdReqFieldToRaw ReqFieldName confdReqfieldIp :: Int confdReqfieldIp = Types.confdReqFieldToRaw ReqFieldIp confdReqfieldMnodePip :: Int confdReqfieldMnodePip = Types.confdReqFieldToRaw ReqFieldMNodePip -- * Confd repl status confdReplStatusOk :: Int confdReplStatusOk = Types.confdReplyStatusToRaw ReplyStatusOk confdReplStatusError :: Int confdReplStatusError = Types.confdReplyStatusToRaw ReplyStatusError confdReplStatusNotimplemented :: Int confdReplStatusNotimplemented = Types.confdReplyStatusToRaw ReplyStatusNotImpl confdReplStatuses :: FrozenSet Int confdReplStatuses = ConstantUtils.mkSet $ map Types.confdReplyStatusToRaw [minBound..] -- * Confd node role confdNodeRoleMaster :: Int confdNodeRoleMaster = Types.confdNodeRoleToRaw NodeRoleMaster confdNodeRoleCandidate :: Int confdNodeRoleCandidate = Types.confdNodeRoleToRaw NodeRoleCandidate confdNodeRoleOffline :: Int confdNodeRoleOffline = Types.confdNodeRoleToRaw NodeRoleOffline confdNodeRoleDrained :: Int confdNodeRoleDrained = Types.confdNodeRoleToRaw NodeRoleDrained confdNodeRoleRegular :: Int confdNodeRoleRegular = Types.confdNodeRoleToRaw NodeRoleRegular -- * A few common errors for confd confdErrorUnknownEntry :: Int confdErrorUnknownEntry = Types.confdErrorTypeToRaw ConfdErrorUnknownEntry confdErrorInternal :: Int confdErrorInternal = Types.confdErrorTypeToRaw ConfdErrorInternal confdErrorArgument :: Int confdErrorArgument = Types.confdErrorTypeToRaw ConfdErrorArgument -- * Confd request query fields confdReqqLink :: String confdReqqLink = ConstantUtils.confdReqqLink confdReqqIp :: String confdReqqIp = ConstantUtils.confdReqqIp confdReqqIplist :: String confdReqqIplist = ConstantUtils.confdReqqIplist confdReqqFields :: String confdReqqFields = ConstantUtils.confdReqqFields -- | Each request is "salted" by the current timestamp. -- -- This constant decides how many seconds of skew to accept. -- -- TODO: make this a default and allow the value to be more -- configurable confdMaxClockSkew :: Int confdMaxClockSkew = 2 * nodeMaxClockSkew -- | When we haven't reloaded the config for more than this amount of -- seconds, we force a test to see if inotify is betraying us. Using a -- prime number to ensure we get less chance of 'same wakeup' with -- other processes. confdConfigReloadTimeout :: Int confdConfigReloadTimeout = 17 -- | If we receive more than one update in this amount of -- microseconds, we move to polling every RATELIMIT seconds, rather -- than relying on inotify, to be able to serve more requests. confdConfigReloadRatelimit :: Int confdConfigReloadRatelimit = 250000 -- | Magic number prepended to all confd queries. -- -- This allows us to distinguish different types of confd protocols -- and handle them. For example by changing this we can move the whole -- payload to be compressed, or move away from json. confdMagicFourcc :: String confdMagicFourcc = "plj0" -- | By default a confd request is sent to the minimum between this -- number and all MCs. 6 was chosen because even in the case of a -- disastrous 50% response rate, we should have enough answers to be -- able to compare more than one. confdDefaultReqCoverage :: Int confdDefaultReqCoverage = 6 -- | Timeout in seconds to expire pending query request in the confd -- client library. We don't actually expect any answer more than 10 -- seconds after we sent a request. confdClientExpireTimeout :: Int confdClientExpireTimeout = 10 -- | Maximum UDP datagram size. -- -- On IPv4: 64K - 20 (ip header size) - 8 (udp header size) = 65507 -- On IPv6: 64K - 40 (ip6 header size) - 8 (udp header size) = 65487 -- (assuming we can't use jumbo frames) -- We just set this to 60K, which should be enough maxUdpDataSize :: Int maxUdpDataSize = 61440 -- * User-id pool minimum/maximum acceptable user-ids uidpoolUidMin :: Int uidpoolUidMin = 0 -- | Assuming 32 bit user-ids uidpoolUidMax :: Integer uidpoolUidMax = 2 ^ 32 - 1 -- | Name or path of the pgrep command pgrep :: String pgrep = "pgrep" -- | Name of the node group that gets created at cluster init or -- upgrade initialNodeGroupName :: String initialNodeGroupName = "default" -- * Possible values for NodeGroup.alloc_policy allocPolicyLastResort :: String allocPolicyLastResort = Types.allocPolicyToRaw AllocLastResort allocPolicyPreferred :: String allocPolicyPreferred = Types.allocPolicyToRaw AllocPreferred allocPolicyUnallocable :: String allocPolicyUnallocable = Types.allocPolicyToRaw AllocUnallocable validAllocPolicies :: [String] validAllocPolicies = map Types.allocPolicyToRaw [minBound..] -- | Temporary external/shared storage parameters blockdevDriverManual :: String blockdevDriverManual = Types.blockDriverToRaw BlockDrvManual -- | 'qemu-img' path, required for 'ovfconverter' qemuimgPath :: String qemuimgPath = AutoConf.qemuimgPath -- | The hail iallocator iallocHail :: String iallocHail = "hail" -- * Fake opcodes for functions that have hooks attached to them via -- backend.RunLocalHooks fakeOpMasterTurndown :: String fakeOpMasterTurndown = "OP_CLUSTER_IP_TURNDOWN" fakeOpMasterTurnup :: String fakeOpMasterTurnup = "OP_CLUSTER_IP_TURNUP" -- * Crypto Types -- Types of cryptographic tokens used in node communication cryptoTypeSslDigest :: String cryptoTypeSslDigest = "ssl" cryptoTypeSsh :: String cryptoTypeSsh = "ssh" -- So far only ssl keys are used in the context of this constant cryptoTypes :: FrozenSet String cryptoTypes = ConstantUtils.mkSet [cryptoTypeSslDigest] -- * Crypto Actions -- Actions that can be performed on crypto tokens cryptoActionGet :: String cryptoActionGet = "get" cryptoActionCreate :: String cryptoActionCreate = "create" cryptoActionDelete :: String cryptoActionDelete = "delete" cryptoActions :: FrozenSet String cryptoActions = ConstantUtils.mkSet [ cryptoActionCreate , cryptoActionGet , cryptoActionDelete] -- Key word for master candidate cert list for bootstrapping. cryptoBootstrap :: String cryptoBootstrap = "bootstrap" -- * Options for CryptoActions -- Filename of the certificate cryptoOptionCertFile :: String cryptoOptionCertFile = "cert_file" -- Serial number of the certificate cryptoOptionSerialNo :: String cryptoOptionSerialNo = "serial_no" -- * SSH key types sshkDsa :: String sshkDsa = Types.sshKeyTypeToRaw DSA sshkEcdsa :: String sshkEcdsa = Types.sshKeyTypeToRaw ECDSA sshkRsa :: String sshkRsa = Types.sshKeyTypeToRaw RSA sshkAll :: FrozenSet String sshkAll = ConstantUtils.mkSet [sshkRsa, sshkDsa, sshkEcdsa] -- * SSH authorized key types sshakDss :: String sshakDss = "ssh-dss" sshakRsa :: String sshakRsa = "ssh-rsa" sshakAll :: FrozenSet String sshakAll = ConstantUtils.mkSet [sshakDss, sshakRsa] -- * SSH key default values -- Document the change in gnt-cluster.rst when changing these sshDefaultKeyType :: String sshDefaultKeyType = sshkRsa sshDefaultKeyBits :: Int sshDefaultKeyBits = 2048 -- * SSH setup sshsClusterName :: String sshsClusterName = "cluster_name" sshsSshHostKey :: String sshsSshHostKey = "ssh_host_key" sshsSshRootKey :: String sshsSshRootKey = "ssh_root_key" sshsSshAuthorizedKeys :: String sshsSshAuthorizedKeys = "authorized_keys" sshsSshPublicKeys :: String sshsSshPublicKeys = "public_keys" sshsNodeDaemonCertificate :: String sshsNodeDaemonCertificate = "node_daemon_certificate" sshsSshKeyType :: String sshsSshKeyType = "ssh_key_type" sshsSshKeyBits :: String sshsSshKeyBits = "ssh_key_bits" -- Number of maximum retries when contacting nodes per SSH -- during SSH update operations. sshsMaxRetries :: Integer sshsMaxRetries = 3 sshsAdd :: String sshsAdd = "add" sshsReplaceOrAdd :: String sshsReplaceOrAdd = "replace_or_add" sshsRemove :: String sshsRemove = "remove" sshsOverride :: String sshsOverride = "override" sshsClear :: String sshsClear = "clear" sshsGenerate :: String sshsGenerate = "generate" sshsSuffix :: String sshsSuffix = "suffix" sshsMasterSuffix :: String sshsMasterSuffix = "_master_tmp" sshsActions :: FrozenSet String sshsActions = ConstantUtils.mkSet [ sshsAdd , sshsRemove , sshsOverride , sshsClear , sshsReplaceOrAdd] -- * Key files for SSH daemon sshHostDsaPriv :: String sshHostDsaPriv = sshConfigDir ++ "/ssh_host_dsa_key" sshHostDsaPub :: String sshHostDsaPub = sshHostDsaPriv ++ ".pub" sshHostEcdsaPriv :: String sshHostEcdsaPriv = sshConfigDir ++ "/ssh_host_ecdsa_key" sshHostEcdsaPub :: String sshHostEcdsaPub = sshHostEcdsaPriv ++ ".pub" sshHostRsaPriv :: String sshHostRsaPriv = sshConfigDir ++ "/ssh_host_rsa_key" sshHostRsaPub :: String sshHostRsaPub = sshHostRsaPriv ++ ".pub" sshDaemonKeyfiles :: Map String (String, String) sshDaemonKeyfiles = Map.fromList [ (sshkRsa, (sshHostRsaPriv, sshHostRsaPub)) , (sshkDsa, (sshHostDsaPriv, sshHostDsaPub)) , (sshkEcdsa, (sshHostEcdsaPriv, sshHostEcdsaPub)) ] -- * Node daemon setup ndsClusterName :: String ndsClusterName = "cluster_name" ndsNodeDaemonCertificate :: String ndsNodeDaemonCertificate = "node_daemon_certificate" ndsSsconf :: String ndsSsconf = "ssconf" ndsHmac :: String ndsHmac = "hmac_key" ndsStartNodeDaemon :: String ndsStartNodeDaemon = "start_node_daemon" ndsNodeName :: String ndsNodeName = "node_name" ndsAction :: String ndsAction = "action" -- * VCluster related constants vClusterEtcHosts :: String vClusterEtcHosts = "/etc/hosts" vClusterVirtPathPrefix :: String vClusterVirtPathPrefix = "/###-VIRTUAL-PATH-###," vClusterRootdirEnvname :: String vClusterRootdirEnvname = "GANETI_ROOTDIR" vClusterHostnameEnvname :: String vClusterHostnameEnvname = "GANETI_HOSTNAME" vClusterVpathWhitelist :: FrozenSet String vClusterVpathWhitelist = ConstantUtils.mkSet [ vClusterEtcHosts ] -- * The source reasons for the execution of an OpCode opcodeReasonSrcClient :: String opcodeReasonSrcClient = "gnt:client" _opcodeReasonSrcDaemon :: String _opcodeReasonSrcDaemon = "gnt:daemon" _opcodeReasonSrcMasterd :: String _opcodeReasonSrcMasterd = _opcodeReasonSrcDaemon ++ ":masterd" opcodeReasonSrcNoded :: String opcodeReasonSrcNoded = _opcodeReasonSrcDaemon ++ ":noded" opcodeReasonSrcMaintd :: String opcodeReasonSrcMaintd = _opcodeReasonSrcDaemon ++ ":maintd" opcodeReasonSrcOpcode :: String opcodeReasonSrcOpcode = "gnt:opcode" opcodeReasonSrcPickup :: String opcodeReasonSrcPickup = _opcodeReasonSrcMasterd ++ ":pickup" opcodeReasonSrcWatcher :: String opcodeReasonSrcWatcher = "gnt:watcher" opcodeReasonSrcRlib2 :: String opcodeReasonSrcRlib2 = "gnt:library:rlib2" opcodeReasonSrcUser :: String opcodeReasonSrcUser = "gnt:user" opcodeReasonSources :: FrozenSet String opcodeReasonSources = ConstantUtils.mkSet [opcodeReasonSrcClient, opcodeReasonSrcNoded, opcodeReasonSrcOpcode, opcodeReasonSrcPickup, opcodeReasonSrcWatcher, opcodeReasonSrcRlib2, opcodeReasonSrcUser] -- | A reason content prefix for RAPI auth user opcodeReasonAuthUser :: String opcodeReasonAuthUser = "RAPI-Auth:" -- | Path generating random UUID randomUuidFile :: String randomUuidFile = ConstantUtils.randomUuidFile -- * Auto-repair levels autoRepairFailover :: String autoRepairFailover = Types.autoRepairTypeToRaw ArFailover autoRepairFixStorage :: String autoRepairFixStorage = Types.autoRepairTypeToRaw ArFixStorage autoRepairMigrate :: String autoRepairMigrate = Types.autoRepairTypeToRaw ArMigrate autoRepairReinstall :: String autoRepairReinstall = Types.autoRepairTypeToRaw ArReinstall autoRepairAllTypes :: FrozenSet String autoRepairAllTypes = ConstantUtils.mkSet [autoRepairFailover, autoRepairFixStorage, autoRepairMigrate, autoRepairReinstall] -- * Auto-repair results autoRepairEnoperm :: String autoRepairEnoperm = Types.autoRepairResultToRaw ArEnoperm autoRepairFailure :: String autoRepairFailure = Types.autoRepairResultToRaw ArFailure autoRepairSuccess :: String autoRepairSuccess = Types.autoRepairResultToRaw ArSuccess autoRepairAllResults :: FrozenSet String autoRepairAllResults = ConstantUtils.mkSet [autoRepairEnoperm, autoRepairFailure, autoRepairSuccess] -- | The version identifier for builtin data collectors builtinDataCollectorVersion :: String builtinDataCollectorVersion = "B" -- | The reason trail opcode parameter name opcodeReason :: String opcodeReason = "reason" -- | The reason trail opcode parameter name opcodeSequential :: String opcodeSequential = "sequential" diskstatsFile :: String diskstatsFile = "/proc/diskstats" -- * CPU load collector statFile :: String statFile = "/proc/stat" cpuavgloadBufferSize :: Int cpuavgloadBufferSize = 150 -- | Window size for averaging in seconds. cpuavgloadWindowSize :: Int cpuavgloadWindowSize = 600 -- * Xen cpu load collector xentopCommand :: String xentopCommand = "xentop" -- | Minimal observation time in seconds, the xen cpu load collector -- can report load averages for the first time. xentopAverageThreshold :: Int xentopAverageThreshold = 100 -- * Monitoring daemon -- | Mond's variable for periodical data collection mondTimeInterval :: Int mondTimeInterval = 5 -- | Mond's waiting time for requesting the current configuration. mondConfigTimeInterval :: Int mondConfigTimeInterval = 15 -- | Mond's latest API version mondLatestApiVersion :: Int mondLatestApiVersion = 1 mondDefaultCategory :: String mondDefaultCategory = "default" -- * Maintenance daemon -- | Default wait in seconds time between maintenance rounds. maintdDefaultRoundDelay :: Int maintdDefaultRoundDelay = 300 -- * Disk access modes diskUserspace :: String diskUserspace = Types.diskAccessModeToRaw DiskUserspace diskKernelspace :: String diskKernelspace = Types.diskAccessModeToRaw DiskKernelspace diskValidAccessModes :: FrozenSet String diskValidAccessModes = ConstantUtils.mkSet $ map Types.diskAccessModeToRaw [minBound..] -- | Timeout for queue draining in upgrades upgradeQueueDrainTimeout :: Int upgradeQueueDrainTimeout = 36 * 60 * 60 -- 1.5 days -- | Intervall at which the queue is polled during upgrades upgradeQueuePollInterval :: Int upgradeQueuePollInterval = 10 -- * Hotplug Actions hotplugActionAdd :: String hotplugActionAdd = Types.hotplugActionToRaw HAAdd hotplugActionRemove :: String hotplugActionRemove = Types.hotplugActionToRaw HARemove hotplugActionModify :: String hotplugActionModify = Types.hotplugActionToRaw HAMod hotplugAllActions :: FrozenSet String hotplugAllActions = ConstantUtils.mkSet $ map Types.hotplugActionToRaw [minBound..] -- * Hotplug Device Targets hotplugTargetNic :: String hotplugTargetNic = Types.hotplugTargetToRaw HTNic hotplugTargetDisk :: String hotplugTargetDisk = Types.hotplugTargetToRaw HTDisk hotplugAllTargets :: FrozenSet String hotplugAllTargets = ConstantUtils.mkSet $ map Types.hotplugTargetToRaw [minBound..] -- | Timeout for disk removal (seconds) diskRemoveRetryTimeout :: Int diskRemoveRetryTimeout = 30 -- | Interval between disk removal retries (seconds) diskRemoveRetryInterval :: Int diskRemoveRetryInterval = 3 -- * UUID regex uuidRegex :: String uuidRegex = "^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$" dummyUuid :: String dummyUuid = "deadbeef-dead-beed-dead-beefdeadbeef" -- * Luxi constants luxiSocketPerms :: Int luxiSocketPerms = 0o660 luxiKeyMethod :: String luxiKeyMethod = "method" luxiKeyArgs :: String luxiKeyArgs = "args" luxiKeySuccess :: String luxiKeySuccess = "success" luxiKeyResult :: String luxiKeyResult = "result" luxiKeyVersion :: String luxiKeyVersion = "version" luxiReqSubmitJob :: String luxiReqSubmitJob = "SubmitJob" luxiReqSubmitJobToDrainedQueue :: String luxiReqSubmitJobToDrainedQueue = "SubmitJobToDrainedQueue" luxiReqSubmitManyJobs :: String luxiReqSubmitManyJobs = "SubmitManyJobs" luxiReqWaitForJobChange :: String luxiReqWaitForJobChange = "WaitForJobChange" luxiReqPickupJob :: String luxiReqPickupJob = "PickupJob" luxiReqCancelJob :: String luxiReqCancelJob = "CancelJob" luxiReqArchiveJob :: String luxiReqArchiveJob = "ArchiveJob" luxiReqChangeJobPriority :: String luxiReqChangeJobPriority = "ChangeJobPriority" luxiReqAutoArchiveJobs :: String luxiReqAutoArchiveJobs = "AutoArchiveJobs" luxiReqQuery :: String luxiReqQuery = "Query" luxiReqQueryFields :: String luxiReqQueryFields = "QueryFields" luxiReqQueryJobs :: String luxiReqQueryJobs = "QueryJobs" luxiReqQueryFilters :: String luxiReqQueryFilters = "QueryFilters" luxiReqReplaceFilter :: String luxiReqReplaceFilter = "ReplaceFilter" luxiReqDeleteFilter :: String luxiReqDeleteFilter = "DeleteFilter" luxiReqQueryInstances :: String luxiReqQueryInstances = "QueryInstances" luxiReqQueryNodes :: String luxiReqQueryNodes = "QueryNodes" luxiReqQueryGroups :: String luxiReqQueryGroups = "QueryGroups" luxiReqQueryNetworks :: String luxiReqQueryNetworks = "QueryNetworks" luxiReqQueryExports :: String luxiReqQueryExports = "QueryExports" luxiReqQueryConfigValues :: String luxiReqQueryConfigValues = "QueryConfigValues" luxiReqQueryClusterInfo :: String luxiReqQueryClusterInfo = "QueryClusterInfo" luxiReqQueryTags :: String luxiReqQueryTags = "QueryTags" luxiReqSetDrainFlag :: String luxiReqSetDrainFlag = "SetDrainFlag" luxiReqSetWatcherPause :: String luxiReqSetWatcherPause = "SetWatcherPause" luxiReqAll :: FrozenSet String luxiReqAll = ConstantUtils.mkSet [ luxiReqArchiveJob , luxiReqAutoArchiveJobs , luxiReqCancelJob , luxiReqChangeJobPriority , luxiReqQuery , luxiReqQueryClusterInfo , luxiReqQueryConfigValues , luxiReqQueryExports , luxiReqQueryFields , luxiReqQueryGroups , luxiReqQueryInstances , luxiReqQueryJobs , luxiReqQueryNodes , luxiReqQueryNetworks , luxiReqQueryTags , luxiReqSetDrainFlag , luxiReqSetWatcherPause , luxiReqSubmitJob , luxiReqSubmitJobToDrainedQueue , luxiReqSubmitManyJobs , luxiReqWaitForJobChange , luxiReqPickupJob , luxiReqQueryFilters , luxiReqReplaceFilter , luxiReqDeleteFilter ] luxiDefCtmo :: Int luxiDefCtmo = 30 luxiDefRwto :: Int luxiDefRwto = 180 -- | Luxi 'WaitForJobChange' timeout luxiWfjcTimeout :: Int luxiWfjcTimeout = (luxiDefRwto - 1) `div` 2 -- | The prefix of the LUXI livelock file name luxiLivelockPrefix :: String luxiLivelockPrefix = "luxi-daemon" -- | The LUXI daemon waits this number of seconds for ensuring that a canceled -- job terminates before giving up. luxiCancelJobTimeout :: Int luxiCancelJobTimeout = (luxiDefRwto - 1) `div` 4 -- * Master voting constants -- | Number of retries to carry out if nodes do not answer masterVotingRetries :: Int masterVotingRetries = 6 -- | Retry interval (in seconds) in master voting, if not enough answers -- could be gathered. masterVotingRetryIntervall :: Int masterVotingRetryIntervall = 10 -- * Query language constants -- ** Logic operators with one or more operands, each of which is a -- filter on its own qlangOpAnd :: String qlangOpAnd = "&" qlangOpOr :: String qlangOpOr = "|" -- ** Unary operators with exactly one operand qlangOpNot :: String qlangOpNot = "!" qlangOpTrue :: String qlangOpTrue = "?" -- ** Binary operators with exactly two operands, the field name and -- an operator-specific value qlangOpContains :: String qlangOpContains = "=[]" qlangOpEqual :: String qlangOpEqual = "==" qlangOpEqualLegacy :: String qlangOpEqualLegacy = "=" qlangOpGe :: String qlangOpGe = ">=" qlangOpGt :: String qlangOpGt = ">" qlangOpLe :: String qlangOpLe = "<=" qlangOpLt :: String qlangOpLt = "<" qlangOpNotEqual :: String qlangOpNotEqual = "!=" qlangOpRegexp :: String qlangOpRegexp = "=~" -- | Characters used for detecting user-written filters (see -- L{_CheckFilter}) qlangFilterDetectionChars :: FrozenSet String qlangFilterDetectionChars = ConstantUtils.mkSet ["!", " ", "\"", "\'", ")", "(", "\x0b", "\n", "\r", "\x0c", "/", "<", "\t", ">", "=", "\\", "~"] -- | Characters used to detect globbing filters qlangGlobDetectionChars :: FrozenSet String qlangGlobDetectionChars = ConstantUtils.mkSet ["*", "?"] -- * Error related constants -- -- 'OpPrereqError' failure types -- | Environment error (e.g. node disk error) errorsEcodeEnviron :: String errorsEcodeEnviron = "environment_error" -- | Entity already exists errorsEcodeExists :: String errorsEcodeExists = "already_exists" -- | Internal cluster error errorsEcodeFault :: String errorsEcodeFault = "internal_error" -- | Wrong arguments (at syntax level) errorsEcodeInval :: String errorsEcodeInval = "wrong_input" -- | Entity not found errorsEcodeNoent :: String errorsEcodeNoent = "unknown_entity" -- | Not enough resources (iallocator failure, disk space, memory, etc) errorsEcodeNores :: String errorsEcodeNores = "insufficient_resources" -- | Resource not unique (e.g. MAC or IP duplication) errorsEcodeNotunique :: String errorsEcodeNotunique = "resource_not_unique" -- | Resolver errors errorsEcodeResolver :: String errorsEcodeResolver = "resolver_error" -- | Wrong entity state errorsEcodeState :: String errorsEcodeState = "wrong_state" -- | Temporarily out of resources; operation can be tried again errorsEcodeTempNores :: String errorsEcodeTempNores = "temp_insufficient_resources" errorsEcodeAll :: FrozenSet String errorsEcodeAll = ConstantUtils.mkSet [ errorsEcodeNores , errorsEcodeExists , errorsEcodeState , errorsEcodeNotunique , errorsEcodeTempNores , errorsEcodeNoent , errorsEcodeFault , errorsEcodeResolver , errorsEcodeInval , errorsEcodeEnviron ] -- * Jstore related constants jstoreJobsPerArchiveDirectory :: Int jstoreJobsPerArchiveDirectory = 10000 -- * Gluster settings -- | Name of the Gluster host setting glusterHost :: String glusterHost = "host" -- | Default value of the Gluster host setting glusterHostDefault :: String glusterHostDefault = "127.0.0.1" -- | Name of the Gluster volume setting glusterVolume :: String glusterVolume = "volume" -- | Default value of the Gluster volume setting glusterVolumeDefault :: String glusterVolumeDefault = "gv0" -- | Name of the Gluster port setting glusterPort :: String glusterPort = "port" -- | Default value of the Gluster port setting glusterPortDefault :: Int glusterPortDefault = 24007 -- * Instance communication -- -- The instance communication attaches an additional NIC, named -- @instanceCommunicationNicPrefix@:@instanceName@ with MAC address -- prefixed by @instanceCommunicationMacPrefix@, to the instances that -- have instance communication enabled. This NIC is part of the -- instance communication network which is supplied by the user via -- -- gnt-cluster modify --instance-communication=mynetwork -- -- This network is defined as @instanceCommunicationNetwork4@ for IPv4 -- and @instanceCommunicationNetwork6@ for IPv6. instanceCommunicationDoc :: String instanceCommunicationDoc = "Enable or disable the communication mechanism for an instance" instanceCommunicationMacPrefix :: String instanceCommunicationMacPrefix = "52:54:00" -- | The instance communication network is a link-local IPv4/IPv6 -- network because the communication is meant to be exclusive between -- the host and the guest and not routed outside the node. instanceCommunicationNetwork4 :: String instanceCommunicationNetwork4 = "169.254.0.0/16" -- | See 'instanceCommunicationNetwork4'. instanceCommunicationNetwork6 :: String instanceCommunicationNetwork6 = "fe80::/10" instanceCommunicationNetworkLink :: String instanceCommunicationNetworkLink = "communication_rt" instanceCommunicationNetworkMode :: String instanceCommunicationNetworkMode = nicModeRouted instanceCommunicationNicPrefix :: String instanceCommunicationNicPrefix = "ganeti:communication:" -- | Parameters that should be protected -- -- Python does not have a type system and can't automatically infer what should -- be the resulting type of a JSON request. As a result, it must rely on this -- list of parameter names to protect values correctly. -- -- Names ending in _cluster will be treated as dicts of dicts of private values. -- Otherwise they are considered dicts of private values. privateParametersBlacklist :: [String] privateParametersBlacklist = [ "osparams_private" , "osparams_secret" , "osparams_private_cluster" ] -- | Warn the user that the logging level is too low for production use. debugModeConfidentialityWarning :: String debugModeConfidentialityWarning = "ALERT: %s started in debug mode.\n\ \ Private and secret parameters WILL be logged!\n" -- | Use to hide secret parameter value redacted :: String redacted = Types.redacted -- * Stat dictionary entries -- -- The get_file_info RPC returns a number of values as a dictionary, and the -- following constants are both descriptions and means of accessing them. -- | The size of the file statSize :: String statSize = "size" -- * Helper VM-related timeouts -- | The default fixed timeout needed to startup the helper VM. helperVmStartup :: Int helperVmStartup = 5 * 60 -- | The default fixed timeout needed until the helper VM is finally -- shutdown, for example, after installing the OS. helperVmShutdown :: Int helperVmShutdown = 2 * 60 * 60 -- | The zeroing timeout per MiB of disks to zero -- -- Determined by estimating that a disk writes at a relatively slow -- speed of 1/5 of the max speed of current drives. zeroingTimeoutPerMib :: Double zeroingTimeoutPerMib = 1.0 / (100.0 / 5.0) -- * Networking -- The minimum size of a network. ipv4NetworkMinSize :: Int ipv4NetworkMinSize = 30 -- The maximum size of a network. -- -- FIXME: This limit is for performance reasons. Remove when refactoring -- for performance tuning was successful. ipv4NetworkMaxSize :: Int ipv4NetworkMaxSize = 30 -- * Data Collectors dataCollectorCPULoad :: String dataCollectorCPULoad = "cpu-avg-load" dataCollectorXenCpuLoad :: String dataCollectorXenCpuLoad = "xen-cpu-avg-load" dataCollectorDiskStats :: String dataCollectorDiskStats = "diskstats" dataCollectorDrbd :: String dataCollectorDrbd = "drbd" dataCollectorLv :: String dataCollectorLv = "lv" -- | Collector for the resident set size of kvm processes, i.e., -- the number of pages the kvm process has in RAM. dataCollectorKvmRSS :: String dataCollectorKvmRSS = "kvm-inst-rss" dataCollectorInstStatus :: String dataCollectorInstStatus = "inst-status-xen" dataCollectorDiagnose :: String dataCollectorDiagnose = "diagnose" dataCollectorParameterInterval :: String dataCollectorParameterInterval = "interval" dataCollectorNames :: FrozenSet String dataCollectorNames = ConstantUtils.mkSet [ dataCollectorCPULoad , dataCollectorDiskStats , dataCollectorDrbd , dataCollectorLv , dataCollectorInstStatus , dataCollectorXenCpuLoad , dataCollectorKvmRSS , dataCollectorDiagnose ] dataCollectorStateActive :: String dataCollectorStateActive = "active" dataCollectorsEnabledName :: String dataCollectorsEnabledName = "enabled_data_collectors" dataCollectorsIntervalName :: String dataCollectorsIntervalName = "data_collector_interval" dataCollectorDiagnoseDirectory :: String dataCollectorDiagnoseDirectory = sysconfdir ++ "/ganeti/node-diagnose-commands" -- * HTools tag prefixes exTagsPrefix :: String exTagsPrefix = Tags.exTagsPrefix -- * MaintD tag prefixes maintdPrefix :: String maintdPrefix = "maintd:" maintdSuccessTagPrefix :: String maintdSuccessTagPrefix = maintdPrefix ++ "repairready:" maintdFailureTagPrefix :: String maintdFailureTagPrefix = maintdPrefix ++ "repairfailed:" -- * RAPI PAM auth related constants -- | The name of ganeti rapi specific http header containing additional user -- credentials httpRapiPamCredential :: String httpRapiPamCredential = "Ganeti-RAPI-Credential" -- | The polling frequency to wait for a job status change cliWfjcFrequency :: Int cliWfjcFrequency = 20 -- | Default 'WaitForJobChange' timeout in seconds defaultWfjcTimeout :: Int defaultWfjcTimeout = 60
leshchevds/ganeti
src/Ganeti/Constants.hs
bsd-2-clause
146,887
0
13
28,629
24,889
14,752
10,137
-1
-1
module ConvexHull ( convexHull ) where import Data.List (sort) import GHC.Int (Int32) -- Coordinate type type R = Int32 -- Vector / point type type R2 = (R, R) -- Checks if it's shortest to rotate from the OA to the OB vector in a clockwise -- direction. clockwise :: R2 -> R2 -> R2 -> Bool clockwise o a b = (a `sub` o) `cross` (b `sub` o) <= 0 -- 2D cross product. cross :: R2 -> R2 -> R cross (x1, y1) (x2, y2) = x1 * y2 - x2 * y1 -- Subtract two vectors. sub :: R2 -> R2 -> R2 sub (x1, y1) (x2, y2) = (x1 - x2, y1 - y2) -- Implements the monotone chain algorithm convexHull :: [R2] -> [R2] convexHull [] = [] convexHull [p] = [p] convexHull points = lower ++ upper where sorted = sort points lower = chain sorted upper = chain (reverse sorted) chain :: [R2] -> [R2] chain = go [] where -- The first parameter accumulates a monotone chain where the most recently -- added element is at the front of the list. go :: [R2] -> [R2] -> [R2] go acc@(r1:r2:rs) (x:xs) = if clockwise r2 r1 x -- Made a clockwise turn - remove the most recent part of the chain. then go (r2:rs) (x:xs) -- Made a counter-clockwise turn - append to the chain. else go (x:acc) xs -- If there's only one point in the chain, just add the next visited point. go acc (x:xs) = go (x:acc) xs -- No more points to consume - finished! Note: the reverse here causes the -- result to be consistent with the other examples (a ccw hull), but -- removing that and using (upper ++ lower) above will make it cw. go acc [] = reverse $ tail acc
Chuck-Aguilar/haskell-opencv-work
src/ConvexHull.hs
bsd-3-clause
1,618
2
11
423
476
271
205
29
4
{-| Module : Network.Kademlia.Implementation Description : The details of the lookup algorithm "Network.Kademlia.Implementation" contains the actual implementations of the different Kademlia Network Algorithms. -} module Network.Kademlia.Implementation ( lookup , store , joinNetwork , JoinResult(..) , Network.Kademlia.Implementation.lookupNode ) where import Network.Kademlia.Networking import Network.Kademlia.Instance import qualified Network.Kademlia.Tree as T import Network.Kademlia.Types import Network.Kademlia.ReplyQueue import Prelude hiding (lookup) import Control.Monad (forM_, unless, when) import Control.Monad.Trans.State hiding (state) import Control.Concurrent.Chan import Control.Concurrent.STM import Control.Monad.IO.Class (liftIO) import Data.List (delete, find, (\\)) import Data.Maybe (isJust, fromJust) -- | Lookup the value corresponding to a key in the DHT and return it, together -- with the Node that was the first to answer the lookup lookup :: (Serialize i, Serialize a, Eq i, Ord i) => KademliaInstance i a -> i -> IO (Maybe (a, Node i)) lookup inst id = runLookup go inst id where go = startLookup sendS cancel checkSignal -- Return Nothing on lookup failure cancel = return Nothing -- When receiving a RETURN_VALUE command, finish the lookup, then -- cache the value in the closest peer that didn't return it and -- finally return the value checkSignal (Signal origin (RETURN_VALUE _ value)) = do -- Abuse the known list for saving the peers that are *known* to -- store the value modify $ \s -> s { known = [origin] } -- Finish the lookup, recording which nodes returned the value finish -- Store the value in the closest peer that didn't return the -- value known <- gets known polled <- gets polled let rest = polled \\ known unless (null rest) $ do let cachePeer = peer . head . sortByDistanceTo rest $ id liftIO . send (handle inst) cachePeer . STORE id $ value -- Return the value return . Just $ (value, origin) -- When receiving a RETURN_NODES command, throw the nodes into the -- lookup loop and continue the lookup checkSignal (Signal _ (RETURN_NODES _ nodes)) = continueLookup nodes sendS continue cancel -- Continuing always means waiting for the next signal continue = waitForReply cancel checkSignal -- Send a FIND_VALUE command, looking for the supplied id sendS = sendSignal (FIND_VALUE id) -- As long as there still are pending requests, wait for the next one finish = do pending <- gets pending unless (null pending) $ waitForReply (return ()) finishCheck -- Record the nodes which return the value finishCheck (Signal origin (RETURN_VALUE _ _)) = do known <- gets known modify $ \s -> s { known = origin:known } finish finishCheck _ = finish -- | Store assign a value to a key and store it in the DHT store :: (Serialize i, Serialize a, Eq i, Ord i) => KademliaInstance i a -> i -> a -> IO () store inst key val = runLookup go inst key where go = startLookup sendS end checkSignal -- Always add the nodes into the loop and continue the lookup checkSignal (Signal _ (RETURN_NODES _ nodes)) = continueLookup nodes sendS continue end -- Continuing always means waiting for the next signal continue = waitForReply end checkSignal -- Send a FIND_NODE command, looking for the node corresponding to the -- key sendS = sendSignal (FIND_NODE key) -- Run the lookup as long as possible, to make sure the nodes closest -- to the key were polled. end = do polled <- gets polled unless (null polled) $ do let h = handle inst -- Don't select more than 7 peers peerNum = if length polled > 7 then 7 else length polled -- Select the peers closest to the key storePeers = map peer . take peerNum . sortByDistanceTo polled $ key -- Send them a STORE command forM_ storePeers $ \storePeer -> liftIO . send h storePeer . STORE key $ val -- | The different possibel results of joinNetwork data JoinResult = JoinSucces | NodeDown | IDClash deriving (Eq, Ord, Show) -- | Make a KademliaInstance join the network a supplied Node is in joinNetwork :: (Serialize i, Serialize a, Eq i, Ord i) => KademliaInstance i a -> Node i -> IO JoinResult joinNetwork inst node = ownId >>= runLookup go inst where go = do -- Poll the supplied node sendS node -- Run a normal lookup from thereon out waitForReply nodeDown checkSignal -- No answer to the first signal means, that that Node is down nodeDown = return NodeDown -- Retrieve your own id ownId = fmap T.extractId . atomically . readTVar . sTree . state $ inst -- Check wether the own id was encountered. If so, return a IDClash -- error, otherwise, continue the lookup. checkSignal (Signal _ (RETURN_NODES _ nodes)) = do tId <- gets targetId case find (\node -> nodeId node == tId) nodes of Just _ -> return IDClash _ -> continueLookup nodes sendS continue finish -- Continuing always means waiting for the next signal continue = waitForReply finish checkSignal -- Send a FIND_NODE command, looking up your own id sendS node = liftIO ownId >>= flip sendSignal node . FIND_NODE -- Return a success, when the operation finished cleanly finish = return JoinSucces -- | Lookup the Node corresponding to the supplied ID lookupNode :: (Serialize i, Serialize a, Eq i, Ord i) => KademliaInstance i a -> i -> IO (Maybe (Node i)) lookupNode inst id = runLookup go inst id where go = startLookup sendS end checkSignal -- Return Nothing on lookup failure end = return Nothing -- Check wether the Node we are looking for was found. If so, return -- it, otherwise continue the lookup. checkSignal (Signal _ (RETURN_NODES _ nodes)) = case find (\(Node _ nId) -> nId == id) nodes of Just node -> return . Just $ node _ -> continueLookup nodes sendS continue end -- Continuing always means waiting for the next signal continue = waitForReply end checkSignal -- Send a FIND_NODE command looking for the Node corresponding to the -- id sendS = sendSignal (FIND_NODE id) -- | The state of a lookup data LookupState i a = LookupState { inst :: KademliaInstance i a , targetId :: i , replyChan :: Chan (Reply i a) , known :: [Node i] , pending :: [Node i] , polled :: [Node i] } -- | MonadTransformer context of a lookup type LookupM i a = StateT (LookupState i a) IO -- Run a LookupM, returning its result runLookup :: LookupM i a b -> KademliaInstance i a -> i ->IO b runLookup lookup inst id = do chan <- newChan let state = LookupState inst id chan [] [] [] evalStateT lookup state -- The initial phase of the normal kademlia lookup operation startLookup :: (Serialize i, Serialize a, Eq i, Ord i) => (Node i -> LookupM i a ()) -> LookupM i a b -> (Signal i a -> LookupM i a b) -> LookupM i a b startLookup sendSignal cancel onSignal = do inst <- gets inst tree <- liftIO . atomically . readTVar . sTree . state $ inst chan <- gets replyChan id <- gets targetId -- Find the three nodes closest to the supplied id case T.findClosest tree id 3 of [] -> cancel closest -> do -- Send a signal to each of the Nodes forM_ closest sendSignal -- Add them to the list of known nodes. At this point, it will -- be empty, therfore just overwrite it. modify $ \s -> s { known = closest } -- Start the recursive lookup waitForReply cancel onSignal -- Wait for the next reply and handle it appropriately waitForReply :: (Serialize i, Serialize a, Ord i) => LookupM i a b -> (Signal i a -> LookupM i a b) -> LookupM i a b waitForReply cancel onSignal = do chan <- gets replyChan sPending <- gets pending known <- gets known inst <- gets inst polled <- gets polled result <- liftIO . readChan $ chan case result of -- If there was a reply Answer sig@(Signal node _) -> do -- Insert the node into the tree, as it might be a new one or it -- would have to be refreshed liftIO . insertNode inst $ node -- Remove the node from the list of nodes with pending replies modify $ \s -> s { pending = delete node sPending } -- Call the signal handler onSignal sig -- On timeout Timeout registration -> do let id = replyOrigin registration -- Find the node corresponding to the id -- -- ReplyQueue guarantees us, that it will be in polled, therefore -- we can use fromJust let node = fromJust . find (\n -> nodeId n == id) $ polled -- Remove every trace of the node's existance modify $ \s -> s { pending = delete node sPending , known = delete node known , polled = delete node polled } -- Continue, if there still are pending responses updatedPending <- gets pending if not . null $ updatedPending then waitForReply cancel onSignal else cancel Closed -> cancel -- Decide wether, and which node to poll and react appropriately. -- -- This is the meat of kademlia lookups continueLookup :: (Serialize i, Serialize a, Eq i) => [Node i] -> (Node i -> LookupM i a ()) -> LookupM i a b -> LookupM i a b -> LookupM i a b continueLookup nodes sendSignal continue end = do known <- gets known id <- gets targetId pending <- gets pending polled <- gets polled -- Pick the k closest known nodes, that haven't been polled yet let newKnown = take 7 . filter (`notElem` polled) $ nodes ++ known -- If there the k closest nodes haven't been polled yet closestPolled <- closestPolled newKnown if (not . null $ newKnown) && not closestPolled then do -- Send signal to the closest node, that hasn't -- been polled yet let next = head . sortByDistanceTo newKnown $ id sendSignal next -- Update known modify $ \s -> s { known = newKnown } -- Continue the lookup continue -- If there are still pending replies else if not . null $ pending -- Wait for the pending replies to finish then continue -- Stop recursive lookup else end where closestPolled known = do polled <- gets polled closest <- closest known return . all (`elem` polled) $ closest closest known = do id <- gets targetId polled <- gets polled -- Return the 7 closest nodes, the lookup had contact with return . take 7 . sortByDistanceTo (known ++ polled) $ id -- Send a signal to a node sendSignal :: (Serialize i, Serialize a, Eq i) => Command i a -> Node i -> LookupM i a () sendSignal cmd node = do h <- fmap handle . gets $ inst chan <- gets replyChan polled <- gets polled pending <- gets pending -- Send the signal liftIO . send h (peer node) $ cmd -- Expect an appropriate reply to the command liftIO . expect h regs $ chan -- Mark the node as polled and pending modify $ \s -> s { polled = node:polled , pending = node:pending } -- Determine the appropriate ReplyRegistrations to the command where regs = case cmd of (FIND_NODE id) -> RR [R_RETURN_NODES id] (nodeId node) (FIND_VALUE id) -> RR [R_RETURN_NODES id, R_RETURN_VALUE id] (nodeId node)
froozen/kademlia
src/Network/Kademlia/Implementation.hs
bsd-3-clause
12,928
0
21
4,381
2,870
1,461
1,409
187
4
module Main where import Prelude hiding ( null ) import Data.List ( intercalate ) import Youtan.Lexical.Tokenizer import Youtan.Syntax.Parser import qualified Data.Map as Map data JS = JSNull | JSBool !Bool | JSRational !Double | JSString !String | JSArray ![ JS ] | JSObject !( Map.Map String JS ) deriving ( Eq ) instance Show JS where show JSNull = "null" show ( JSBool True ) = "true" show ( JSBool False ) = "false" show ( JSRational v ) = show v show ( JSString str ) = show str show ( JSArray arr ) = show arr show ( JSObject list ) = concat [ "{" , intercalate "," ( map ( \ ( n, v ) -> show n ++ ":" ++ show v ) $ Map.toList list ) , "}" ] data Token = OpenBrace | CloseBrace | OpenSquareBrace | CloseSquareBrace | Colon | Comma | Space | Number { _num :: !Double } | RawString { _str :: !String } | Literal !String deriving ( Show, Eq ) rules :: Rules Token rules = [ ( ":", const Colon ) , ( ",", const Comma ) , ( "\\{", const OpenBrace ) , ( "\\}", const CloseBrace ) , ( "\\[", const OpenSquareBrace ) , ( "\\]", const CloseSquareBrace ) , ( "-?(0|\\d+)(\\.\\d+)?", Number . read ) , ( "\\\"[^\"]*\\\"", RawString . tail . init ) , ( "\\s+", const Space ) , ( "(true|false|null)", Literal ) ] isNum, isStr :: Token -> Bool isNum s = case s of Number _ -> True _ -> False isStr s = case s of RawString _ -> True _ -> False with :: Parser Token a -> String -> Either [ ( a, [ Token ] ) ] a with parser = runParser parser . tokenize rules grammar :: Parser Token JS grammar = value value :: Parser Token JS value = lexem ( null <|> true <|> false <|> number <|> string <|> array <|> object ) null, true, false, number, string, array, object :: Parser Token JS null = const JSNull <$> term ( Literal "null" ) true = const ( JSBool True ) <$> term ( Literal "true" ) false = const ( JSBool False ) <$> term ( Literal "false" ) number = ( JSRational . _num ) <$> satisfy isNum string = ( JSString . _str ) <$> satisfy isStr array = JSArray <$> pad openSquareBrace ( joins comma value ) closeSquareBrace object = JSObject . Map.fromList <$> pad openBrace ( joins comma objectPair ) closeBrace lexem :: Parser Token a -> Parser Token a lexem p = pad ( opt Space ) p ( opt Space ) comma, colon :: Parser Token () comma = lexem ( term Comma ) colon = lexem ( term Colon ) openSquareBrace, closeSquareBrace, openBrace, closeBrace :: Parser Token () openSquareBrace = lexem ( term OpenSquareBrace ) closeSquareBrace = lexem ( term CloseSquareBrace ) openBrace = lexem ( term OpenBrace ) closeBrace = lexem ( term CloseBrace ) objectPair :: Parser Token ( String, JS ) objectPair = do name <- _str <$> lexem ( satisfy isStr ) colon val <- value return ( name, val ) main :: IO () main = ( with grammar <$> readFile "/Users/Smelkov/Source/ex.json" ) >>= print
triplepointfive/Youtan
app/Main.hs
bsd-3-clause
2,927
0
16
713
1,095
584
511
104
2
module Main where import System.IO(hFlush, stdout) import System.Environment(getArgs) import System.Exit(exitFailure) import Control.Applicative((<$>)) import Control.Arrow((&&&)) import Control.Monad.Tools(doWhile, doWhile_) import LojysambanLib(ask, readRules, end) main :: IO () main = do args <- getArgs rules <- readRules <$> case args of [] -> doWhile "" $ \s -> (id &&& not . end) . (s ++) <$> getLine [fp] -> readFile fp _ -> putStrLn "Usage: lojysamban [FILEPATH]" >> exitFailure doWhile_ $ do q <- putStr ".i " >> hFlush stdout >> getLine maybe (return False) ((>> return True) . putStrLn) $ ask q rules
YoshikuniJujo/lojysamban
src/lojysamban.hs
bsd-3-clause
629
0
18
107
259
140
119
-1
-1
{-# LANGUAGE CPP , GADTs , KindSignatures , DataKinds , PolyKinds , TypeFamilies , FlexibleContexts , FlexibleInstances , TypeSynonymInstances , StandaloneDeriving #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- 2015.12.15 -- | -- Module : Language.Hakaru.Types.HClasses -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC-only -- -- A collection of type classes for encoding Hakaru's numeric hierarchy. ---------------------------------------------------------------- module Language.Hakaru.Types.HClasses ( -- * Equality HEq(..) , HEq_(..) , sing_HEq , hEq_Sing -- * Ordering , HOrd(..) , hEq_HOrd , HOrd_(..) , sing_HOrd , hOrd_Sing -- * HIntegrable , HIntegrable(..) , sing_HIntegrable , hIntegrable_Sing -- * Semirings , HSemiring(..) , HSemiring_(..) , sing_HSemiring , hSemiring_Sing -- * Rings , HRing(..) , hSemiring_HRing , hSemiring_NonNegativeHRing , HRing_(..) , sing_HRing , hRing_Sing , sing_NonNegative -- * Fractional types , HFractional(..) , hSemiring_HFractional , HFractional_(..) , sing_HFractional , hFractional_Sing -- * Radical types , HRadical(..) , hSemiring_HRadical , HRadical_(..) , sing_HRadical , hRadical_Sing -- * Discrete types , HDiscrete(..) , HDiscrete_(..) , sing_HDiscrete , hDiscrete_Sing -- * Continuous types , HContinuous(..) , hFractional_HContinuous , hSemiring_HIntegralContinuous , HContinuous_(..) , sing_HContinuous , hContinuous_Sing , sing_HIntegral ) where #if __GLASGOW_HASKELL__ < 710 import Data.Functor ((<$>)) #endif import Control.Applicative ((<|>)) import Language.Hakaru.Syntax.IClasses (TypeEq(..), Eq1(..), JmEq1(..)) import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing ---------------------------------------------------------------- -- | Concrete dictionaries for Hakaru types with decidable equality. data HEq :: Hakaru -> * where HEq_Nat :: HEq 'HNat HEq_Int :: HEq 'HInt HEq_Prob :: HEq 'HProb HEq_Real :: HEq 'HReal HEq_Array :: !(HEq a) -> HEq ('HArray a) HEq_Bool :: HEq HBool HEq_Unit :: HEq HUnit HEq_Pair :: !(HEq a) -> !(HEq b) -> HEq (HPair a b) HEq_Either :: !(HEq a) -> !(HEq b) -> HEq (HEither a b) deriving instance Eq (HEq a) -- TODO: instance JmEq1 HEq -- BUG: deriving instance Read (HEq a) deriving instance Show (HEq a) -- N.B., we do case analysis so that we don't need the class constraint! sing_HEq :: HEq a -> Sing a sing_HEq HEq_Nat = SNat sing_HEq HEq_Int = SInt sing_HEq HEq_Prob = SProb sing_HEq HEq_Real = SReal sing_HEq (HEq_Array a) = SArray (sing_HEq a) sing_HEq HEq_Bool = sBool sing_HEq HEq_Unit = sUnit sing_HEq (HEq_Pair a b) = sPair (sing_HEq a) (sing_HEq b) sing_HEq (HEq_Either a b) = sEither (sing_HEq a) (sing_HEq b) hEq_Sing :: Sing a -> Maybe (HEq a) hEq_Sing SNat = Just HEq_Nat hEq_Sing SInt = Just HEq_Int hEq_Sing SProb = Just HEq_Prob hEq_Sing SReal = Just HEq_Real hEq_Sing (SArray a) = HEq_Array <$> hEq_Sing a hEq_Sing s = (jmEq1 s sUnit >>= \Refl -> Just HEq_Unit) <|> (jmEq1 s sBool >>= \Refl -> Just HEq_Bool) {- hEq_Sing (sPair a b) = HEq_Pair <$> hEq_Sing a <*> hEq_Sing b hEq_Sing (sEither a b) = HEq_Either <$> hEq_Sing a <*> hEq_Sing b -} -- | Haskell type class for automatic 'HEq' inference. class HEq_ (a :: Hakaru) where hEq :: HEq a instance HEq_ 'HNat where hEq = HEq_Nat instance HEq_ 'HInt where hEq = HEq_Int instance HEq_ 'HProb where hEq = HEq_Prob instance HEq_ 'HReal where hEq = HEq_Real instance HEq_ HBool where hEq = HEq_Bool instance HEq_ HUnit where hEq = HEq_Unit instance (HEq_ a) => HEq_ ('HArray a) where hEq = HEq_Array hEq instance (HEq_ a, HEq_ b) => HEq_ (HPair a b) where hEq = HEq_Pair hEq hEq instance (HEq_ a, HEq_ b) => HEq_ (HEither a b) where hEq = HEq_Either hEq hEq ---------------------------------------------------------------- -- | Concrete dictionaries for Hakaru types with decidable total ordering. data HOrd :: Hakaru -> * where HOrd_Nat :: HOrd 'HNat HOrd_Int :: HOrd 'HInt HOrd_Prob :: HOrd 'HProb HOrd_Real :: HOrd 'HReal HOrd_Array :: !(HOrd a) -> HOrd ('HArray a) HOrd_Bool :: HOrd HBool HOrd_Unit :: HOrd HUnit HOrd_Pair :: !(HOrd a) -> !(HOrd b) -> HOrd (HPair a b) HOrd_Either :: !(HOrd a) -> !(HOrd b) -> HOrd (HEither a b) deriving instance Eq (HOrd a) -- TODO: instance JmEq1 HOrd -- BUG: deriving instance Read (HOrd a) deriving instance Show (HOrd a) sing_HOrd :: HOrd a -> Sing a sing_HOrd HOrd_Nat = SNat sing_HOrd HOrd_Int = SInt sing_HOrd HOrd_Prob = SProb sing_HOrd HOrd_Real = SReal sing_HOrd (HOrd_Array a) = SArray (sing_HOrd a) sing_HOrd HOrd_Bool = sBool sing_HOrd HOrd_Unit = sUnit sing_HOrd (HOrd_Pair a b) = sPair (sing_HOrd a) (sing_HOrd b) sing_HOrd (HOrd_Either a b) = sEither (sing_HOrd a) (sing_HOrd b) hOrd_Sing :: Sing a -> Maybe (HOrd a) hOrd_Sing SNat = Just HOrd_Nat hOrd_Sing SInt = Just HOrd_Int hOrd_Sing SProb = Just HOrd_Prob hOrd_Sing SReal = Just HOrd_Real hOrd_Sing (SArray a) = HOrd_Array <$> hOrd_Sing a hOrd_Sing _ = Nothing -- | Every 'HOrd' type is 'HEq'. hEq_HOrd :: HOrd a -> HEq a hEq_HOrd HOrd_Nat = HEq_Nat hEq_HOrd HOrd_Int = HEq_Int hEq_HOrd HOrd_Prob = HEq_Prob hEq_HOrd HOrd_Real = HEq_Real hEq_HOrd (HOrd_Array a) = HEq_Array (hEq_HOrd a) hEq_HOrd HOrd_Bool = HEq_Bool hEq_HOrd HOrd_Unit = HEq_Unit hEq_HOrd (HOrd_Pair a b) = HEq_Pair (hEq_HOrd a) (hEq_HOrd b) hEq_HOrd (HOrd_Either a b) = HEq_Either (hEq_HOrd a) (hEq_HOrd b) -- | Haskell type class for automatic 'HOrd' inference. class HEq_ a => HOrd_ (a :: Hakaru) where hOrd :: HOrd a instance HOrd_ 'HNat where hOrd = HOrd_Nat instance HOrd_ 'HInt where hOrd = HOrd_Int instance HOrd_ 'HProb where hOrd = HOrd_Prob instance HOrd_ 'HReal where hOrd = HOrd_Real instance HOrd_ HBool where hOrd = HOrd_Bool instance HOrd_ HUnit where hOrd = HOrd_Unit instance (HOrd_ a) => HOrd_ ('HArray a) where hOrd = HOrd_Array hOrd instance (HOrd_ a, HOrd_ b) => HOrd_ (HPair a b) where hOrd = HOrd_Pair hOrd hOrd instance (HOrd_ a, HOrd_ b) => HOrd_ (HEither a b) where hOrd = HOrd_Either hOrd hOrd -- TODO: class HPER (a :: Hakaru) -- TODO: class HPartialOrder (a :: Hakaru) ---------------------------------------------------------------- -- | Concrete dictionaries for Hakaru types which are semirings. -- N.B., even though these particular semirings are commutative, -- we don't necessarily assume that. data HSemiring :: Hakaru -> * where HSemiring_Nat :: HSemiring 'HNat HSemiring_Int :: HSemiring 'HInt HSemiring_Prob :: HSemiring 'HProb HSemiring_Real :: HSemiring 'HReal instance Eq (HSemiring a) where -- This one could be derived... (==) = eq1 instance Eq1 HSemiring where eq1 x y = maybe False (const True) (jmEq1 x y) instance JmEq1 HSemiring where jmEq1 HSemiring_Nat HSemiring_Nat = Just Refl jmEq1 HSemiring_Int HSemiring_Int = Just Refl jmEq1 HSemiring_Prob HSemiring_Prob = Just Refl jmEq1 HSemiring_Real HSemiring_Real = Just Refl jmEq1 _ _ = Nothing -- BUG: deriving instance Read (HSemiring a) deriving instance Show (HSemiring a) sing_HSemiring :: HSemiring a -> Sing a sing_HSemiring HSemiring_Nat = SNat sing_HSemiring HSemiring_Int = SInt sing_HSemiring HSemiring_Prob = SProb sing_HSemiring HSemiring_Real = SReal hSemiring_Sing :: Sing a -> Maybe (HSemiring a) hSemiring_Sing SNat = Just HSemiring_Nat hSemiring_Sing SInt = Just HSemiring_Int hSemiring_Sing SProb = Just HSemiring_Prob hSemiring_Sing SReal = Just HSemiring_Real hSemiring_Sing _ = Nothing -- | Haskell type class for automatic 'HSemiring' inference. class HSemiring_ (a :: Hakaru) where hSemiring :: HSemiring a instance HSemiring_ 'HNat where hSemiring = HSemiring_Nat instance HSemiring_ 'HInt where hSemiring = HSemiring_Int instance HSemiring_ 'HProb where hSemiring = HSemiring_Prob instance HSemiring_ 'HReal where hSemiring = HSemiring_Real ---------------------------------------------------------------- -- | Concrete dictionaries for Hakaru types which are rings. N.B., -- even though these particular rings are commutative, we don't -- necessarily assume that. data HRing :: Hakaru -> * where HRing_Int :: HRing 'HInt HRing_Real :: HRing 'HReal instance Eq (HRing a) where -- This one could be derived... (==) = eq1 instance Eq1 HRing where eq1 x y = maybe False (const True) (jmEq1 x y) instance JmEq1 HRing where jmEq1 HRing_Int HRing_Int = Just Refl jmEq1 HRing_Real HRing_Real = Just Refl jmEq1 _ _ = Nothing -- BUG: deriving instance Read (HRing a) deriving instance Show (HRing a) sing_HRing :: HRing a -> Sing a sing_HRing HRing_Int = SInt sing_HRing HRing_Real = SReal hRing_Sing :: Sing a -> Maybe (HRing a) hRing_Sing SInt = Just HRing_Int hRing_Sing SReal = Just HRing_Real hRing_Sing _ = Nothing sing_NonNegative :: HRing a -> Sing (NonNegative a) sing_NonNegative = sing_HSemiring . hSemiring_NonNegativeHRing -- hNonNegative_Sing :: Sing (NonNegative a) -> Maybe (HRing a) -- | Every 'HRing' is a 'HSemiring'. hSemiring_HRing :: HRing a -> HSemiring a hSemiring_HRing HRing_Int = HSemiring_Int hSemiring_HRing HRing_Real = HSemiring_Real -- | The non-negative type of every 'HRing' is a 'HSemiring'. hSemiring_NonNegativeHRing :: HRing a -> HSemiring (NonNegative a) hSemiring_NonNegativeHRing HRing_Int = HSemiring_Nat hSemiring_NonNegativeHRing HRing_Real = HSemiring_Prob -- | Haskell type class for automatic 'HRing' inference. -- -- Every 'HRing' has an associated type for the semiring of its -- non-negative elements. This type family captures two notions. -- First, if we take the semiring and close it under negation\/subtraction -- then we will generate this ring. Second, when we take the absolute -- value of something in the ring we will get back something in the -- non-negative semiring. For 'HInt' and 'HReal' these two notions -- coincide; however for Complex and Vector types, the notions -- diverge. -- -- TODO: Can we somehow specify that the @HSemiring (NonNegative -- a)@ semantics coincides with the @HSemiring a@ semantics? Or -- should we just assume that? class (HSemiring_ (NonNegative a), HSemiring_ a) => HRing_ (a :: Hakaru) where type NonNegative (a :: Hakaru) :: Hakaru hRing :: HRing a instance HRing_ 'HInt where type NonNegative 'HInt = 'HNat hRing = HRing_Int instance HRing_ 'HReal where type NonNegative 'HReal = 'HProb hRing = HRing_Real ---------------------------------------------------------------- -- N.B., We're assuming two-sided inverses here. That doesn't entail -- commutativity, though it does strongly suggest it... (cf., -- Wedderburn's little theorem) -- -- N.B., the (Nat,"+"=lcm,"*"=gcd) semiring is sometimes called -- "the division semiring" -- -- HACK: tracking the generating carriers here wouldn't be quite -- right b/c we get more than just the (non-negative)rationals -- generated from HNat/HInt! However, we should have some sort of -- associated type so we can add rationals and non-negative -- rationals... -- -- TODO: associated type for non-zero elements. To guarantee the -- safety of division\/recip? For now, we have Infinity, so it's -- actually safe for these two types. But if we want to add the -- rationals... -- -- | Concrete dictionaries for Hakaru types which are division-semirings; -- i.e., division-rings without negation. This is called a \"semifield\" -- in ring theory, but should not be confused with the \"semifields\" -- of geometry. data HFractional :: Hakaru -> * where HFractional_Prob :: HFractional 'HProb HFractional_Real :: HFractional 'HReal instance Eq (HFractional a) where -- This one could be derived... (==) = eq1 instance Eq1 HFractional where eq1 x y = maybe False (const True) (jmEq1 x y) instance JmEq1 HFractional where jmEq1 HFractional_Prob HFractional_Prob = Just Refl jmEq1 HFractional_Real HFractional_Real = Just Refl jmEq1 _ _ = Nothing -- BUG: deriving instance Read (HFractional a) deriving instance Show (HFractional a) sing_HFractional :: HFractional a -> Sing a sing_HFractional HFractional_Prob = SProb sing_HFractional HFractional_Real = SReal hFractional_Sing :: Sing a -> Maybe (HFractional a) hFractional_Sing SProb = Just HFractional_Prob hFractional_Sing SReal = Just HFractional_Real hFractional_Sing _ = Nothing -- | Every 'HFractional' is a 'HSemiring'. hSemiring_HFractional :: HFractional a -> HSemiring a hSemiring_HFractional HFractional_Prob = HSemiring_Prob hSemiring_HFractional HFractional_Real = HSemiring_Real -- | Haskell type class for automatic 'HFractional' inference. class (HSemiring_ a) => HFractional_ (a :: Hakaru) where hFractional :: HFractional a instance HFractional_ 'HProb where hFractional = HFractional_Prob instance HFractional_ 'HReal where hFractional = HFractional_Real -- type HDivisionRing a = (HFractional a, HRing a) -- type HField a = (HDivisionRing a, HCommutativeSemiring a) ---------------------------------------------------------------- -- Numbers formed by finitely many uses of integer addition, -- subtraction, multiplication, division, and nat-roots are all -- algebraic; however, N.B., not all algebraic numbers can be formed -- this way (cf., Abel–Ruffini theorem) -- TODO: ought we require HFractional rather than HSemiring? -- TODO: any special associated type? -- -- | Concrete dictionaries for semirings which are closed under all -- 'HNat'-roots. This means it's closed under all positive rational -- powers as well. (If the type happens to be 'HFractional', then -- it's closed under /all/ rational powers.) -- -- N.B., 'HReal' is not 'HRadical' because we do not have real-valued -- roots for negative reals. -- -- N.B., we assume not only that the type is surd-complete, but -- also that it's still complete under the semiring operations. -- Thus we have values like @sqrt 2 + sqrt 3@ which cannot be -- expressed as a single root. Thus, in order to solve for zeros\/roots, -- we'll need solutions to more general polynomials than just the -- @x^n - a@ polynomials. However, the Galois groups of these are -- all solvable, so this shouldn't be too bad. data HRadical :: Hakaru -> * where HRadical_Prob :: HRadical 'HProb instance Eq (HRadical a) where -- This one could be derived... (==) = eq1 instance Eq1 HRadical where eq1 x y = maybe False (const True) (jmEq1 x y) instance JmEq1 HRadical where jmEq1 HRadical_Prob HRadical_Prob = Just Refl -- BUG: deriving instance Read (HRadical a) deriving instance Show (HRadical a) sing_HRadical :: HRadical a -> Sing a sing_HRadical HRadical_Prob = SProb hRadical_Sing :: Sing a -> Maybe (HRadical a) hRadical_Sing SProb = Just HRadical_Prob hRadical_Sing _ = Nothing -- | Every 'HRadical' is a 'HSemiring'. hSemiring_HRadical :: HRadical a -> HSemiring a hSemiring_HRadical HRadical_Prob = HSemiring_Prob -- | Haskell type class for automatic 'HRadical' inference. class (HSemiring_ a) => HRadical_ (a :: Hakaru) where hRadical :: HRadical a instance HRadical_ 'HProb where hRadical = HRadical_Prob -- TODO: class (HDivisionRing a, HRadical a) => HAlgebraic a where... -- | Concrete dictionaries for types where Infinity can have data HIntegrable :: Hakaru -> * where HIntegrable_Nat :: HIntegrable 'HNat HIntegrable_Prob :: HIntegrable 'HProb instance Eq (HIntegrable a) where -- This one could be derived... (==) = eq1 instance Eq1 HIntegrable where eq1 x y = maybe False (const True) (jmEq1 x y) instance JmEq1 HIntegrable where jmEq1 HIntegrable_Nat HIntegrable_Nat = Just Refl jmEq1 HIntegrable_Prob HIntegrable_Prob = Just Refl jmEq1 _ _ = Nothing -- BUG: deriving instance Read (HIntegrable a) deriving instance Show (HIntegrable a) sing_HIntegrable :: HIntegrable a -> Sing a sing_HIntegrable HIntegrable_Nat = SNat sing_HIntegrable HIntegrable_Prob = SProb hIntegrable_Sing :: Sing a -> Maybe (HIntegrable a) hIntegrable_Sing SNat = Just HIntegrable_Nat hIntegrable_Sing SProb = Just HIntegrable_Prob hIntegrable_Sing _ = Nothing -- | Concrete dictionaries for Hakaru types which are \"discrete\". data HDiscrete :: Hakaru -> * where HDiscrete_Nat :: HDiscrete 'HNat HDiscrete_Int :: HDiscrete 'HInt instance Eq (HDiscrete a) where -- This one could be derived... (==) = eq1 instance Eq1 HDiscrete where eq1 x y = maybe False (const True) (jmEq1 x y) instance JmEq1 HDiscrete where jmEq1 HDiscrete_Nat HDiscrete_Nat = Just Refl jmEq1 HDiscrete_Int HDiscrete_Int = Just Refl jmEq1 _ _ = Nothing -- BUG: deriving instance Read (HDiscrete a) deriving instance Show (HDiscrete a) sing_HDiscrete :: HDiscrete a -> Sing a sing_HDiscrete HDiscrete_Nat = SNat sing_HDiscrete HDiscrete_Int = SInt hDiscrete_Sing :: Sing a -> Maybe (HDiscrete a) hDiscrete_Sing SNat = Just HDiscrete_Nat hDiscrete_Sing SInt = Just HDiscrete_Int hDiscrete_Sing _ = Nothing -- | Haskell type class for automatic 'HDiscrete' inference. class (HSemiring_ a) => HDiscrete_ (a :: Hakaru) where hDiscrete :: HDiscrete a instance HDiscrete_ 'HNat where hDiscrete = HDiscrete_Nat instance HDiscrete_ 'HInt where hDiscrete = HDiscrete_Int ---------------------------------------------------------------- -- TODO: find better names than HContinuous and HIntegral -- TODO: how to require that "if HRing a, then HRing b too"? -- TODO: should we call this something like Dedekind-complete? -- That's what distinguishes the reals from the rationals. Of course, -- calling it that suggests (but does not require) that we should -- have some supremum operator; but supremum only differs from -- maximum if we have some way of talking about infinite sets of -- values (which is surely too much to bother with). -- -- | Concrete dictionaries for Hakaru types which are \"continuous\". -- This is an ad-hoc class for (a) lifting 'HNat'\/'HInt' into -- 'HProb'\/'HReal', and (b) handling the polymorphism of monotonic -- functions like @etf@. data HContinuous :: Hakaru -> * where HContinuous_Prob :: HContinuous 'HProb HContinuous_Real :: HContinuous 'HReal instance Eq (HContinuous a) where -- This one could be derived... (==) = eq1 instance Eq1 HContinuous where eq1 x y = maybe False (const True) (jmEq1 x y) instance JmEq1 HContinuous where jmEq1 HContinuous_Prob HContinuous_Prob = Just Refl jmEq1 HContinuous_Real HContinuous_Real = Just Refl jmEq1 _ _ = Nothing -- BUG: deriving instance Read (HContinuous a) deriving instance Show (HContinuous a) sing_HContinuous :: HContinuous a -> Sing a sing_HContinuous HContinuous_Prob = SProb sing_HContinuous HContinuous_Real = SReal hContinuous_Sing :: Sing a -> Maybe (HContinuous a) hContinuous_Sing SProb = Just HContinuous_Prob hContinuous_Sing SReal = Just HContinuous_Real hContinuous_Sing _ = Nothing sing_HIntegral :: HContinuous a -> Sing (HIntegral a) sing_HIntegral = sing_HSemiring . hSemiring_HIntegralContinuous -- hIntegral_Sing :: Sing (HIntegral a) -> Maybe (HContinuous a) -- | Every 'HContinuous' is a 'HFractional'. hFractional_HContinuous :: HContinuous a -> HFractional a hFractional_HContinuous HContinuous_Prob = HFractional_Prob hFractional_HContinuous HContinuous_Real = HFractional_Real -- | The integral type of every 'HContinuous' is a 'HSemiring'. hSemiring_HIntegralContinuous :: HContinuous a -> HSemiring (HIntegral a) hSemiring_HIntegralContinuous HContinuous_Prob = HSemiring_Nat hSemiring_HIntegralContinuous HContinuous_Real = HSemiring_Int -- | Haskell type class for automatic 'HContinuous' inference. -- -- Every 'HContinuous' has an associated type for the semiring of -- its integral elements. -- -- TODO: Can we somehow specify that the @HSemiring (HIntegral a)@ -- semantics coincides with the @HSemiring a@ semantics? Or should -- we just assume that? class (HSemiring_ (HIntegral a), HFractional_ a) => HContinuous_ (a :: Hakaru) where type HIntegral (a :: Hakaru) :: Hakaru hContinuous :: HContinuous a instance HContinuous_ 'HProb where type HIntegral 'HProb = 'HNat hContinuous = HContinuous_Prob instance HContinuous_ 'HReal where type HIntegral 'HReal = 'HInt hContinuous = HContinuous_Real ---------------------------------------------------------------- ----------------------------------------------------------- fin.
zaxtax/hakaru
haskell/Language/Hakaru/Types/HClasses.hs
bsd-3-clause
21,509
0
10
4,552
4,359
2,322
2,037
369
1
{-# LANGUAGE TypeOperators, GADTs #-} -- | Simple support for new behavior primitives in Sirea, requires -- the processing be isolated to one signal. -- -- These shouldn't be necessary often, since it will only take a few -- common abstractions to support most new ideas and resources. But -- unsafeLinkB ensures that unforseen corner cases can be handled. -- -- Processing multiple signals will require deeper access to Sirea's -- representations. -- module Sirea.UnsafeLink ( unsafeFmapB , unsafeLinkB, unsafeLinkB_, unsafeLinkBL, unsafeLinkBLN , unsafeLinkWB, unsafeLinkWB_, unsafeLinkWBL, unsafeLinkWBLN , LnkUpM(..), LnkUp, StableT(..), inStableT , ln_zero, ln_sfmap, ln_lumap, ln_append ) where import Data.Function (fix) import Control.Applicative import Control.Exception (assert) import Sirea.Internal.LTypes import Sirea.Internal.B0Impl (mkLnkB0, mkLnkPure, forceDelayB0 ,undeadB0, keepAliveB0) import Sirea.Internal.B0 import Sirea.Behavior import Sirea.Signal import Sirea.B import Sirea.PCX import Sirea.Partition (W, Partition) -- | pure signal transforms, but might not respect RDP invariants. unsafeFmapB :: (Sig a -> Sig b) -> B (S p a) (S p b) unsafeFmapB = wrapB . const . unsafeFmapB0 unsafeFmapB0 :: (Monad m) => (Sig a -> Sig b) -> B0 m (S p a) (S p b) unsafeFmapB0 = mkLnkPure lc_fwd . ln_lumap . ln_sfmap lpcx1 :: (Partition p) => B (S p x) z -> PCX W -> IO (PCX p) lpcx1 _ = findInPCX lpcx2 :: (Partition p) => B (S p x :&: y) z -> PCX W -> IO (PCX p) lpcx2 _ = findInPCX -- | unsafeLinkB is used when the link has some side-effects other -- than processing the signal, and thus needs to receive a signal -- even if it is not going to pass one on. unsafeLinkB :: (Partition p) => (PCX p -> LnkUp y -> IO (LnkUp x)) -> B (S p x) (S p y) unsafeLinkB fn = fix $ unsafeLinkWB . fn' where fn' b cw lu = lpcx1 b cw >>= \ cp -> fn cp lu -- | unsafeLinkB_ describes a sink, cases where the response signal -- is unused. Usually, this is used by wrapping it with `bvoid`. unsafeLinkB_ :: (Partition p) => (PCX p -> IO (LnkUp x)) -> B (S p x) S1 unsafeLinkB_ fn = fix $ unsafeLinkWB_ . fn' where fn' b cw = lpcx1 b cw >>= fn -- | unsafeLinkBL is the lazy form of unsafeLinkB; it is inactive -- unless the response signal is necessary downstream. unsafeLinkBL :: (Partition p) => (PCX p -> LnkUp y -> IO (LnkUp x)) -> B (S p x) (S p y) unsafeLinkBL fn = fix $ unsafeLinkWBL . fn' where fn' b cw lu = lpcx1 b cw >>= \ cp -> fn cp lu -- | unsafeLinkBLN is a semi-lazy form of unsafeLinkB; it is active -- if any of the input signals are needed downstream, but operates -- only on the first input (even if its particular output is not -- used downstream). unsafeLinkBLN :: (Partition p) => (PCX p -> LnkUp y -> IO (LnkUp x)) -> B (S p x :&: z) (S p y :&: z) unsafeLinkBLN fn = fix $ unsafeLinkWBLN . fn' where fn' b cw lu = lpcx2 b cw >>= \ cp -> fn cp lu -- | same as unsafeLinkB, but with world context unsafeLinkWB :: (PCX W -> LnkUp y -> IO (LnkUp x)) -> B (S p x) (S p y) unsafeLinkWB fn = unsafeLinkWBL fn >>> (wrapB . const) undeadB0 -- | same as unsafeLinkB_, but with world context unsafeLinkWB_ :: (PCX W -> IO (LnkUp x)) -> B (S p x) S1 unsafeLinkWB_ fn = wrapB b0 where b0 cw = forceDelayB0 >>> mkLnkB0 lc_dupCaps (ul cw) ul cw _ ln = assert (ln_dead ln) $ LnkSig <$> fn cw -- | same as unsafeLinkBL, but with world context unsafeLinkWBL :: (PCX W -> LnkUp y -> IO (LnkUp x)) -> B (S p x) (S p y) unsafeLinkWBL fn = wrapB b0 where b0 cw = forceDelayB0 >>> mkLnkB0 lc_fwd (ul cw) ul cw _ (LnkSig lu) = LnkSig <$> fn cw lu ul _ _ LnkDead = return LnkDead -- | same as unsafeLinkBLN, but with world context unsafeLinkWBLN :: (PCX W -> LnkUp y -> IO (LnkUp x)) -> B (S p x :&: z) (S p y :&: z) unsafeLinkWBLN fn = bfirst (unsafeLinkWBL fn) >>> (wrapB . const) keepAliveB0
dmbarbour/Sirea
src/Sirea/UnsafeLink.hs
bsd-3-clause
3,905
0
12
836
1,283
665
618
52
2
module Numeric.BMML where
DbIHbKA/BMML
src/Numeric/BMML.hs
bsd-3-clause
29
0
3
6
6
4
2
1
0
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE CPP #-} -- | Dealing with Cabal. module Stack.Package (readPackage ,readPackageBS ,readPackageDir ,readPackageUnresolved ,readPackageUnresolvedBS ,resolvePackage ,getCabalFileName ,Package(..) ,GetPackageFiles(..) ,GetPackageOpts(..) ,PackageConfig(..) ,buildLogPath ,PackageException (..) ,resolvePackageDescription ,packageToolDependencies ,packageDependencies ,packageIdentifier ,autogenDir ,checkCabalFileName ,printCabalFileWarning) where import Control.Exception hiding (try,catch) import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger,logWarn) import Control.Monad.Reader import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C8 import Data.Either import Data.Function import Data.List import Data.List.Extra (nubOrd) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe import Data.Maybe.Extra import Data.Monoid import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8, decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Distribution.Compiler import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as Cabal import Distribution.Package hiding (Package,PackageName,packageName,packageVersion,PackageIdentifier) import Distribution.PackageDescription hiding (FlagName) import Distribution.PackageDescription.Parse import Distribution.ParseUtils import Distribution.Simple.Utils import Distribution.System (OS (..), Arch, Platform (..)) import Distribution.Text (display, simpleParse) import Path as FL import Path.Extra import Path.Find import Path.IO import Prelude import Safe (headDef, tailSafe) import Stack.Build.Installed import Stack.Constants import Stack.Types import qualified Stack.Types.PackageIdentifier import System.Directory (doesFileExist, getDirectoryContents) import System.FilePath (splitExtensions, replaceExtension) import qualified System.FilePath as FilePath import System.IO.Error packageIdentifier :: Package -> Stack.Types.PackageIdentifier.PackageIdentifier packageIdentifier pkg = Stack.Types.PackageIdentifier.PackageIdentifier (packageName pkg) (packageVersion pkg) -- | Read the raw, unresolved package information. readPackageUnresolved :: (MonadIO m, MonadThrow m) => Path Abs File -> m ([PWarning],GenericPackageDescription) readPackageUnresolved cabalfp = liftIO (BS.readFile (FL.toFilePath cabalfp)) >>= readPackageUnresolvedBS (Just cabalfp) -- | Read the raw, unresolved package information from a ByteString. readPackageUnresolvedBS :: (MonadThrow m) => Maybe (Path Abs File) -> BS.ByteString -> m ([PWarning],GenericPackageDescription) readPackageUnresolvedBS mcabalfp bs = case parsePackageDescription chars of ParseFailed per -> throwM (PackageInvalidCabalFile mcabalfp per) ParseOk warnings gpkg -> return (warnings,gpkg) where chars = T.unpack (dropBOM (decodeUtf8With lenientDecode bs)) -- https://github.com/haskell/hackage-server/issues/351 dropBOM t = fromMaybe t $ T.stripPrefix "\xFEFF" t -- | Reads and exposes the package information readPackage :: (MonadLogger m, MonadIO m, MonadThrow m, MonadCatch m) => PackageConfig -> Path Abs File -> m ([PWarning],Package) readPackage packageConfig cabalfp = do (warnings,gpkg) <- readPackageUnresolved cabalfp return (warnings,resolvePackage packageConfig gpkg) -- | Reads and exposes the package information, from a ByteString readPackageBS :: (MonadThrow m) => PackageConfig -> BS.ByteString -> m ([PWarning],Package) readPackageBS packageConfig bs = do (warnings,gpkg) <- readPackageUnresolvedBS Nothing bs return (warnings,resolvePackage packageConfig gpkg) -- | Convenience wrapper around @readPackage@ that first finds the cabal file -- in the given directory. readPackageDir :: (MonadLogger m, MonadIO m, MonadThrow m, MonadCatch m) => PackageConfig -> Path Abs Dir -> m (Path Abs File, [PWarning], Package) readPackageDir packageConfig dir = do cabalfp <- getCabalFileName dir (warnings,pkg) <- readPackage packageConfig cabalfp checkCabalFileName (packageName pkg) cabalfp return (cabalfp, warnings, pkg) -- | Print cabal file warnings. printCabalFileWarning :: (MonadLogger m) => Path Abs File -> PWarning -> m () printCabalFileWarning cabalfp = \case (PWarning x) -> $logWarn ("Cabal file warning in " <> T.pack (toFilePath cabalfp) <> ": " <> T.pack x) (UTFWarning line msg) -> $logWarn ("Cabal file warning in " <> T.pack (toFilePath cabalfp) <> ":" <> T.pack (show line) <> ": " <> T.pack msg) -- | Check if the given name in the @Package@ matches the name of the .cabal file checkCabalFileName :: MonadThrow m => PackageName -> Path Abs File -> m () checkCabalFileName name cabalfp = do -- Previously, we just use parsePackageNameFromFilePath. However, that can -- lead to confusing error messages. See: -- https://github.com/commercialhaskell/stack/issues/895 let expected = packageNameString name ++ ".cabal" when (expected /= toFilePath (filename cabalfp)) $ throwM $ MismatchedCabalName cabalfp name -- | Resolve a parsed cabal file into a 'Package'. resolvePackage :: PackageConfig -> GenericPackageDescription -> Package resolvePackage packageConfig gpkg = Package { packageName = name , packageVersion = fromCabalVersion (pkgVersion pkgId) , packageDeps = deps , packageFiles = pkgFiles , packageTools = packageDescTools pkg , packageFlags = packageConfigFlags packageConfig , packageAllDeps = S.fromList (M.keys deps) , packageHasLibrary = maybe False (buildable . libBuildInfo) (library pkg) , packageTests = S.fromList $ [T.pack (testName t) | t <- testSuites pkg , buildable (testBuildInfo t)] , packageBenchmarks = S.fromList $ [T.pack (benchmarkName b) | b <- benchmarks pkg , buildable (benchmarkBuildInfo b)] , packageExes = S.fromList $ [T.pack (exeName b) | b <- executables pkg , buildable (buildInfo b)] , packageOpts = GetPackageOpts $ \sourceMap installedMap omitPkgs cabalfp -> do (componentsModules,componentFiles,_,_) <- getPackageFiles pkgFiles cabalfp (componentsOpts,generalOpts) <- generatePkgDescOpts sourceMap installedMap omitPkgs cabalfp pkg componentFiles return (componentsModules,componentFiles,componentsOpts,generalOpts) , packageHasExposedModules = maybe False (not . null . exposedModules) (library pkg) , packageSimpleType = buildType (packageDescription gpkg) == Just Simple , packageDefinedFlags = S.fromList $ map (fromCabalFlagName . flagName) $ genPackageFlags gpkg } where pkgFiles = GetPackageFiles $ \cabalfp -> do distDir <- distDirFromDir (parent cabalfp) (componentModules,componentFiles,dataFiles',warnings) <- runReaderT (packageDescModulesAndFiles pkg) (cabalfp, buildDir distDir) return (componentModules, componentFiles, S.insert cabalfp dataFiles', warnings) pkgId = package (packageDescription gpkg) name = fromCabalPackageName (pkgName pkgId) pkg = resolvePackageDescription packageConfig gpkg deps = M.filterWithKey (const . (/= name)) (packageDependencies pkg) -- | Generate GHC options for the package's components, and a list of -- options which apply generally to the package, not one specific -- component. generatePkgDescOpts :: (HasEnvConfig env, HasPlatform env, MonadThrow m, MonadReader env m, MonadIO m) => SourceMap -> InstalledMap -> [PackageName] -- ^ Packages to omit from the "-package" / "-package-id" flags -> Path Abs File -> PackageDescription -> Map NamedComponent (Set DotCabalPath) -> m (Map NamedComponent [String],[String]) generatePkgDescOpts sourceMap installedMap omitPkgs cabalfp pkg componentPaths = do distDir <- distDirFromDir cabalDir let cabalmacros = autogenDir distDir </> $(mkRelFile "cabal_macros.h") exists <- fileExists cabalmacros let mcabalmacros = if exists then Just cabalmacros else Nothing let generate namedComponent binfo = ( namedComponent , generateBuildInfoOpts sourceMap installedMap mcabalmacros cabalDir distDir omitPkgs binfo (fromMaybe mempty (M.lookup namedComponent componentPaths)) namedComponent) return ( M.fromList (concat [ maybe [] (return . generate CLib . libBuildInfo) (library pkg) , map (\exe -> (generate (CExe (T.pack (exeName exe))) (buildInfo exe))) (executables pkg) , map (\bench -> (generate (CBench (T.pack (benchmarkName bench))) (benchmarkBuildInfo bench))) (benchmarks pkg) , map (\test -> (generate (CTest (T.pack (testName test))) (testBuildInfo test))) (testSuites pkg)]) , ["-hide-all-packages"]) where cabalDir = parent cabalfp -- | Generate GHC options for the target. generateBuildInfoOpts :: SourceMap -> InstalledMap -> Maybe (Path Abs File) -> Path Abs Dir -> Path Abs Dir -> [PackageName] -> BuildInfo -> Set DotCabalPath -> NamedComponent -> [String] generateBuildInfoOpts sourceMap installedMap mcabalmacros cabalDir distDir omitPkgs b dotCabalPaths componentName = nubOrd (concat [ghcOpts b, extOpts b, srcOpts, includeOpts, macros, deps, extra b, extraDirs, fworks b, cObjectFiles]) where cObjectFiles = mapMaybe (fmap toFilePath . makeObjectFilePathFromC cabalDir componentName distDir) cfiles cfiles = mapMaybe dotCabalCFilePath (S.toList dotCabalPaths) deps = concat [ case M.lookup (fromCabalPackageName name) installedMap of Just (_, Stack.Types.Library _ident ipid) -> ["-package-id=" <> ghcPkgIdString ipid] _ -> ["-package=" <> display name <> maybe "" -- This empty case applies to e.g. base. ((("-" <>) . versionString) . sourceVersion) (M.lookup (fromCabalPackageName name) sourceMap)] | Dependency name _ <- targetBuildDepends b , not (elem name (map toCabalPackageName omitPkgs))] -- Generates: -package=base -package=base16-bytestring-0.1.1.6 ... sourceVersion (PSUpstream ver _ _) = ver sourceVersion (PSLocal localPkg) = packageVersion (lpPackage localPkg) macros = case mcabalmacros of Nothing -> [] Just cabalmacros -> ["-optP-include", "-optP" <> toFilePath cabalmacros] ghcOpts = concatMap snd . filter (isGhc . fst) . options where isGhc GHC = True isGhc _ = False extOpts = map (("-X" ++) . display) . usedExtensions srcOpts = -- This initial "-i" resets the include directories to not -- include CWD. "-i" : map (("-i" <>) . toFilePath) ((if null (hsSourceDirs b) then [cabalDir] else []) <> map (cabalDir </>) (mapMaybe parseRelDir (hsSourceDirs b)) <> [autogenDir distDir,buildDir distDir]) ++ ["-stubdir=" ++ toFilePath (buildDir distDir)] includeOpts = [ "-I" <> toFilePath absDir | dir <- includeDirs b , absDir <- case (parseAbsDir dir, parseRelDir dir) of (Just ab, _ ) -> [ab] (_ , Just rel) -> [cabalDir </> rel] (Nothing, Nothing ) -> [] ] extra = map ("-l" <>) . extraLibs extraDirs = [ "-L" <> toFilePath absDir | dir <- extraLibDirs b , absDir <- case (parseAbsDir dir, parseRelDir dir) of (Just ab, _ ) -> [ab] (_ , Just rel) -> [cabalDir </> rel] (Nothing, Nothing ) -> [] ] fworks = map (\fwk -> "-framework=" <> fwk) . frameworks -- | Make the .o path from the .c file path for a component. Example: -- -- @ -- executable FOO -- c-sources: cbits/text_search.c -- @ -- -- Produces -- -- <dist-dir>/build/FOO/FOO-tmp/cbits/text_search.o -- -- Example: -- -- λ> makeObjectFilePathFromC -- $(mkAbsDir "/Users/chris/Repos/hoogle") -- CLib -- $(mkAbsDir "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist") -- $(mkAbsFile "/Users/chris/Repos/hoogle/cbits/text_search.c") -- Just "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist/build/cbits/text_search.o" -- λ> makeObjectFilePathFromC -- $(mkAbsDir "/Users/chris/Repos/hoogle") -- (CExe "hoogle") -- $(mkAbsDir "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist") -- $(mkAbsFile "/Users/chris/Repos/hoogle/cbits/text_search.c") -- Just "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist/build/hoogle/hoogle-tmp/cbits/text_search.o" -- λ> makeObjectFilePathFromC :: MonadThrow m => Path Abs Dir -- ^ The cabal directory. -> NamedComponent -- ^ The name of the component. -> Path Abs Dir -- ^ Dist directory. -> Path Abs File -- ^ The path to the .c file. -> m (Path Abs File) -- ^ The path to the .o file for the component. makeObjectFilePathFromC cabalDir namedComponent distDir cFilePath = do relCFilePath <- stripDir cabalDir cFilePath relOFilePath <- parseRelFile (replaceExtension (toFilePath relCFilePath) "o") addComponentPrefix <- fromComponentName return (addComponentPrefix (buildDir distDir) </> relOFilePath) where fromComponentName = case namedComponent of CLib -> return id CExe name -> makeTmp name CTest name -> makeTmp name CBench name -> makeTmp name makeTmp name = do prefix <- parseRelDir (T.unpack name <> "/" <> T.unpack name <> "-tmp") return (</> prefix) -- | Make the autogen dir. autogenDir :: Path Abs Dir -> Path Abs Dir autogenDir distDir = buildDir distDir </> $(mkRelDir "autogen") -- | Make the build dir. buildDir :: Path Abs Dir -> Path Abs Dir buildDir distDir = distDir </> $(mkRelDir "build") -- | Make the component-specific subdirectory of the build directory. getBuildComponentDir :: Maybe String -> Maybe (Path Rel Dir) getBuildComponentDir Nothing = Nothing getBuildComponentDir (Just name) = parseRelDir (name FilePath.</> (name ++ "-tmp")) -- | Get all dependencies of the package (buildable targets only). packageDependencies :: PackageDescription -> Map PackageName VersionRange packageDependencies = M.fromListWith intersectVersionRanges . concatMap (map (\dep -> ((depName dep),depRange dep)) . targetBuildDepends) . allBuildInfo' -- | Get all build tool dependencies of the package (buildable targets only). packageToolDependencies :: PackageDescription -> Map BS.ByteString VersionRange packageToolDependencies = M.fromList . concatMap (map (\dep -> ((packageNameByteString $ depName dep),depRange dep)) . buildTools) . allBuildInfo' -- | Get all dependencies of the package (buildable targets only). packageDescTools :: PackageDescription -> [Dependency] packageDescTools = concatMap buildTools . allBuildInfo' -- | This is a copy-paste from Cabal's @allBuildInfo@ function, but with the -- @buildable@ test removed. The reason is that (surprise) Cabal is broken, -- see: https://github.com/haskell/cabal/issues/1725 allBuildInfo' :: PackageDescription -> [BuildInfo] allBuildInfo' pkg_descr = [ bi | Just lib <- [library pkg_descr] , let bi = libBuildInfo lib , True || buildable bi ] ++ [ bi | exe <- executables pkg_descr , let bi = buildInfo exe , True || buildable bi ] ++ [ bi | tst <- testSuites pkg_descr , let bi = testBuildInfo tst , True || buildable bi , testEnabled tst ] ++ [ bi | tst <- benchmarks pkg_descr , let bi = benchmarkBuildInfo tst , True || buildable bi , benchmarkEnabled tst ] -- | Get all files referenced by the package. packageDescModulesAndFiles :: (MonadLogger m, MonadIO m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m, MonadCatch m) => PackageDescription -> m (Map NamedComponent (Set ModuleName), Map NamedComponent (Set DotCabalPath), Set (Path Abs File), [PackageWarning]) packageDescModulesAndFiles pkg = do (libraryMods,libDotCabalFiles,libWarnings) <- maybe (return (M.empty, M.empty, [])) (asModuleAndFileMap libComponent libraryFiles) (library pkg) (executableMods,exeDotCabalFiles,exeWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap exeComponent executableFiles) (executables pkg)) (testMods,testDotCabalFiles,testWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap testComponent testFiles) (testSuites pkg)) (benchModules,benchDotCabalPaths,benchWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap benchComponent benchmarkFiles) (benchmarks pkg)) (dfiles) <- resolveGlobFiles (map (dataDir pkg FilePath.</>) (dataFiles pkg)) let modules = libraryMods <> executableMods <> testMods <> benchModules files = libDotCabalFiles <> exeDotCabalFiles <> testDotCabalFiles <> benchDotCabalPaths warnings = libWarnings <> exeWarnings <> testWarnings <> benchWarnings return (modules, files, dfiles, warnings) where libComponent = const CLib exeComponent = CExe . T.pack . exeName testComponent = CTest . T.pack . testName benchComponent = CBench . T.pack . benchmarkName asModuleAndFileMap label f lib = do (a,b,c) <- f lib return (M.singleton (label lib) a, M.singleton (label lib) b, c) foldTuples = foldl' (<>) (M.empty, M.empty, []) -- | Resolve globbing of files (e.g. data files) to absolute paths. resolveGlobFiles :: (MonadLogger m,MonadIO m,MonadThrow m,MonadReader (Path Abs File, Path Abs Dir) m,MonadCatch m) => [String] -> m (Set (Path Abs File)) resolveGlobFiles = liftM (S.fromList . catMaybes . concat) . mapM resolve where resolve name = if any (== '*') name then explode name else liftM return (resolveFileOrWarn name) explode name = do dir <- asks (parent . fst) names <- matchDirFileGlob' (FL.toFilePath dir) name mapM resolveFileOrWarn names matchDirFileGlob' dir glob = catch (liftIO (matchDirFileGlob_ dir glob)) (\(e :: IOException) -> if isUserError e then do $logWarn ("Wildcard does not match any files: " <> T.pack glob <> "\n" <> "in directory: " <> T.pack dir) return [] else throwM e) -- | This is a copy/paste of the Cabal library function, but with -- -- @ext == ext'@ -- -- Changed to -- -- @isSuffixOf ext ext'@ -- -- So that this will work: -- -- @ -- λ> matchDirFileGlob_ "." "test/package-dump/*.txt" -- ["test/package-dump/ghc-7.8.txt","test/package-dump/ghc-7.10.txt"] -- @ -- matchDirFileGlob_ :: String -> String -> IO [String] matchDirFileGlob_ dir filepath = case parseFileGlob filepath of Nothing -> die $ "invalid file glob '" ++ filepath ++ "'. Wildcards '*' are only allowed in place of the file" ++ " name, not in the directory name or file extension." ++ " If a wildcard is used it must be with an file extension." Just (NoGlob filepath') -> return [filepath'] Just (FileGlob dir' ext) -> do files <- getDirectoryContents (dir FilePath.</> dir') case [ dir' FilePath.</> file | file <- files , let (name, ext') = splitExtensions file , not (null name) && isSuffixOf ext ext' ] of [] -> die $ "filepath wildcard '" ++ filepath ++ "' does not match any files." matches -> return matches -- | Get all files referenced by the benchmark. benchmarkFiles :: (MonadLogger m, MonadIO m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => Benchmark -> m (Set ModuleName, Set DotCabalPath, [PackageWarning]) benchmarkFiles bench = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . fst) (modules,files,warnings) <- resolveFilesAndDeps (Just $ benchmarkName bench) (dirs ++ [dir]) (bnames <> exposed) haskellModuleExts cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where exposed = case benchmarkInterface bench of BenchmarkExeV10 _ fp -> [DotCabalMain fp] BenchmarkUnsupported _ -> [] bnames = map DotCabalModule (otherModules build) build = benchmarkBuildInfo bench -- | Get all files referenced by the test. testFiles :: (MonadLogger m, MonadIO m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => TestSuite -> m (Set ModuleName, Set DotCabalPath, [PackageWarning]) testFiles test = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . fst) (modules,files,warnings) <- resolveFilesAndDeps (Just $ testName test) (dirs ++ [dir]) (bnames <> exposed) haskellModuleExts cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where exposed = case testInterface test of TestSuiteExeV10 _ fp -> [DotCabalMain fp] TestSuiteLibV09 _ mn -> [DotCabalModule mn] TestSuiteUnsupported _ -> [] bnames = map DotCabalModule (otherModules build) build = testBuildInfo test -- | Get all files referenced by the executable. executableFiles :: (MonadLogger m, MonadIO m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => Executable -> m (Set ModuleName, Set DotCabalPath, [PackageWarning]) executableFiles exe = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . fst) (modules,files,warnings) <- resolveFilesAndDeps (Just $ exeName exe) (dirs ++ [dir]) (map DotCabalModule (otherModules build) ++ [DotCabalMain (modulePath exe)]) haskellModuleExts cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where build = buildInfo exe -- | Get all files referenced by the library. libraryFiles :: (MonadLogger m, MonadIO m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => Library -> m (Set ModuleName, Set DotCabalPath, [PackageWarning]) libraryFiles lib = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . fst) (modules,files,warnings) <- resolveFilesAndDeps Nothing (dirs ++ [dir]) (names <> exposed) haskellModuleExts cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where names = concat [bnames, exposed] exposed = map DotCabalModule (exposedModules lib) bnames = map DotCabalModule (otherModules build) build = libBuildInfo lib -- | Get all C sources and extra source files in a build. buildOtherSources :: (MonadLogger m,MonadIO m,MonadThrow m,MonadReader (Path Abs File, Path Abs Dir) m) => BuildInfo -> m (Set DotCabalPath) buildOtherSources build = do csources <- liftM (S.map DotCabalCFilePath . S.fromList) (mapMaybeM resolveFileOrWarn (cSources build)) jsources <- liftM (S.map DotCabalFilePath . S.fromList) (mapMaybeM resolveFileOrWarn (targetJsSources build)) return (csources <> jsources) -- | Get the target's JS sources. targetJsSources :: BuildInfo -> [FilePath] #if MIN_VERSION_Cabal(1, 22, 0) targetJsSources = jsSources #else targetJsSources = const [] #endif -- | Get all dependencies of a package, including library, -- executables, tests, benchmarks. resolvePackageDescription :: PackageConfig -> GenericPackageDescription -> PackageDescription resolvePackageDescription packageConfig (GenericPackageDescription desc defaultFlags mlib exes tests benches) = desc {library = fmap (resolveConditions rc updateLibDeps) mlib ,executables = map (\(n, v) -> (resolveConditions rc updateExeDeps v){exeName=n}) exes ,testSuites = map (\(n,v) -> (resolveConditions rc updateTestDeps v){testName=n}) tests ,benchmarks = map (\(n,v) -> (resolveConditions rc updateBenchmarkDeps v){benchmarkName=n}) benches} where flags = M.union (packageConfigFlags packageConfig) (flagMap defaultFlags) rc = mkResolveConditions (packageConfigCompilerVersion packageConfig) (packageConfigPlatform packageConfig) flags updateLibDeps lib deps = lib {libBuildInfo = ((libBuildInfo lib) {targetBuildDepends = deps})} updateExeDeps exe deps = exe {buildInfo = (buildInfo exe) {targetBuildDepends = deps}} updateTestDeps test deps = test {testBuildInfo = (testBuildInfo test) {targetBuildDepends = deps} ,testEnabled = packageConfigEnableTests packageConfig} updateBenchmarkDeps benchmark deps = benchmark {benchmarkBuildInfo = (benchmarkBuildInfo benchmark) {targetBuildDepends = deps} ,benchmarkEnabled = packageConfigEnableBenchmarks packageConfig} -- | Make a map from a list of flag specifications. -- -- What is @flagManual@ for? flagMap :: [Flag] -> Map FlagName Bool flagMap = M.fromList . map pair where pair :: Flag -> (FlagName, Bool) pair (MkFlag (fromCabalFlagName -> name) _desc def _manual) = (name,def) data ResolveConditions = ResolveConditions { rcFlags :: Map FlagName Bool , rcCompilerVersion :: CompilerVersion , rcOS :: OS , rcArch :: Arch } -- | Generic a @ResolveConditions@ using sensible defaults. mkResolveConditions :: CompilerVersion -- ^ Compiler version -> Platform -- ^ installation target platform -> Map FlagName Bool -- ^ enabled flags -> ResolveConditions mkResolveConditions compilerVersion (Platform arch os) flags = ResolveConditions { rcFlags = flags , rcCompilerVersion = compilerVersion , rcOS = os , rcArch = arch } -- | Resolve the condition tree for the library. resolveConditions :: (Monoid target,Show target) => ResolveConditions -> (target -> cs -> target) -> CondTree ConfVar cs target -> target resolveConditions rc addDeps (CondNode lib deps cs) = basic <> children where basic = addDeps lib deps children = mconcat (map apply cs) where apply (cond,node,mcs) = if (condSatisfied cond) then resolveConditions rc addDeps node else maybe mempty (resolveConditions rc addDeps) mcs condSatisfied c = case c of Var v -> varSatisifed v Lit b -> b CNot c' -> not (condSatisfied c') COr cx cy -> or [condSatisfied cx,condSatisfied cy] CAnd cx cy -> and [condSatisfied cx,condSatisfied cy] varSatisifed v = case v of OS os -> os == rcOS rc Arch arch -> arch == rcArch rc Flag flag -> case M.lookup (fromCabalFlagName flag) (rcFlags rc) of Just x -> x Nothing -> -- NOTE: This should never happen, as all flags -- which are used must be declared. Defaulting -- to False False Impl flavor range -> case (flavor, rcCompilerVersion rc) of (GHC, GhcVersion vghc) -> vghc `withinRange` range (GHC, GhcjsVersion _ vghc) -> vghc `withinRange` range #if MIN_VERSION_Cabal(1, 22, 0) (GHCJS, GhcjsVersion vghcjs _) -> #else (OtherCompiler "ghcjs", GhcjsVersion vghcjs _) -> #endif vghcjs `withinRange` range _ -> False -- | Get the name of a dependency. depName :: Dependency -> PackageName depName = \(Dependency n _) -> fromCabalPackageName n -- | Get the version range of a dependency. depRange :: Dependency -> VersionRange depRange = \(Dependency _ r) -> r -- | Try to resolve the list of base names in the given directory by -- looking for unique instances of base names applied with the given -- extensions, plus find any of their module and TemplateHaskell -- dependencies. resolveFilesAndDeps :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => Maybe (String) -- ^ Package component name -> [Path Abs Dir] -- ^ Directories to look in. -> [DotCabalDescriptor] -- ^ Base names. -> [Text] -- ^ Extentions. -> m (Set ModuleName,Set DotCabalPath,[PackageWarning]) resolveFilesAndDeps component dirs names0 exts = do (dotCabalPaths,foundModules) <- loop names0 S.empty warnings <- warnUnlisted foundModules return (foundModules, dotCabalPaths, warnings) where loop [] doneModules = return (S.empty, doneModules) loop names doneModules0 = do resolvedFiles <- resolveFiles dirs names exts pairs <- mapM (getDependencies component) resolvedFiles let doneModules' = S.union doneModules0 (S.fromList (mapMaybe dotCabalModule names)) moduleDeps = S.unions (map fst pairs) thDepFiles = concatMap snd pairs modulesRemaining = S.difference moduleDeps doneModules' (resolvedFiles',doneModules'') <- loop (map DotCabalModule (S.toList modulesRemaining)) doneModules' return ( S.union (S.fromList (resolvedFiles <> map DotCabalFilePath thDepFiles)) resolvedFiles' , doneModules'') warnUnlisted foundModules = do let unlistedModules = foundModules `S.difference` (S.fromList $ mapMaybe dotCabalModule names0) cabalfp <- asks fst return $ if S.null unlistedModules then [] else [ UnlistedModulesWarning cabalfp component (S.toList unlistedModules)] -- | Get the dependencies of a Haskell module file. getDependencies :: (MonadReader (Path Abs File, Path Abs Dir) m, MonadIO m) => Maybe String -> DotCabalPath -> m (Set ModuleName, [Path Abs File]) getDependencies component dotCabalPath = case dotCabalPath of DotCabalModulePath resolvedFile -> readResolvedHi resolvedFile DotCabalMainPath resolvedFile -> readResolvedHi resolvedFile DotCabalFilePath{} -> return (S.empty, []) DotCabalCFilePath{} -> return (S.empty, []) where readResolvedHi resolvedFile = do dumpHIDir <- getDumpHIDir dir <- asks (parent . fst) case stripDir dir resolvedFile of Nothing -> return (S.empty, []) Just fileRel -> do let dumpHIPath = FilePath.replaceExtension (toFilePath (dumpHIDir </> fileRel)) ".dump-hi" dumpHIExists <- liftIO $ doesFileExist dumpHIPath if dumpHIExists then parseDumpHI dumpHIPath else return (S.empty, []) getDumpHIDir = do bld <- asks snd return $ maybe bld (bld </>) (getBuildComponentDir component) -- | Parse a .dump-hi file into a set of modules and files. parseDumpHI :: (MonadReader (Path Abs File, void) m, MonadIO m) => FilePath -> m (Set ModuleName, [Path Abs File]) parseDumpHI dumpHIPath = do dir <- asks (parent . fst) dumpHI <- liftIO $ fmap C8.lines (C8.readFile dumpHIPath) let startModuleDeps = dropWhile (not . ("module dependencies:" `C8.isPrefixOf`)) dumpHI moduleDeps = S.fromList $ mapMaybe (simpleParse . T.unpack . decodeUtf8) $ C8.words $ C8.concat $ C8.dropWhile (/= ' ') (headDef "" startModuleDeps) : takeWhile (" " `C8.isPrefixOf`) (tailSafe startModuleDeps) thDeps = -- The dependent file path is surrounded by quotes but is not escaped. -- It can be an absolute or relative path. mapMaybe (parseAbsOrRelFile dir <=< (fmap T.unpack . (T.stripSuffix "\"" <=< T.stripPrefix "\"") . T.dropWhileEnd (== '\r') . decodeUtf8 . C8.dropWhile (/= '"'))) $ filter ("addDependentFile \"" `C8.isPrefixOf`) dumpHI return (moduleDeps, thDeps) where parseAbsOrRelFile dir fp = case parseRelFile fp of Just rel -> Just (dir </> rel) Nothing -> parseAbsFile fp -- | Try to resolve the list of base names in the given directory by -- looking for unique instances of base names applied with the given -- extensions. resolveFiles :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => [Path Abs Dir] -- ^ Directories to look in. -> [DotCabalDescriptor] -- ^ Base names. -> [Text] -- ^ Extentions. -> m [DotCabalPath] resolveFiles dirs names exts = do liftM catMaybes (forM names (findCandidate dirs exts)) -- | Find a candidate for the given module-or-filename from the list -- of directories and given extensions. findCandidate :: (MonadIO m, MonadLogger m, MonadThrow m, MonadReader (Path Abs File, Path Abs Dir) m) => [Path Abs Dir] -> [Text] -> DotCabalDescriptor -> m (Maybe DotCabalPath) findCandidate dirs exts name = do pkg <- asks fst >>= parsePackageNameFromFilePath candidates <- liftIO makeNameCandidates case candidates of [candidate] -> return (Just (cons candidate)) [] -> do case name of DotCabalModule mn | not (display mn == paths_pkg pkg) -> do logPossibilities dirs mn _ -> return () return Nothing (candidate:rest) -> do warnMultiple name candidate rest return (Just (cons candidate)) where cons = case name of DotCabalModule{} -> DotCabalModulePath DotCabalMain{} -> DotCabalMainPath DotCabalFile{} -> DotCabalFilePath DotCabalCFile{} -> DotCabalCFilePath paths_pkg pkg = "Paths_" ++ packageNameString pkg makeNameCandidates = liftM (nubOrd . rights . concat) (mapM makeDirCandidates dirs) makeDirCandidates :: Path Abs Dir -> IO [Either ResolveException (Path Abs File)] makeDirCandidates dir = case name of DotCabalMain fp -> liftM return (try (resolveFile' dir fp)) DotCabalFile fp -> liftM return (try (resolveFile' dir fp)) DotCabalCFile fp -> liftM return (try (resolveFile' dir fp)) DotCabalModule mn -> mapM (\ext -> try (resolveFile' dir (Cabal.toFilePath mn ++ "." ++ ext))) (map T.unpack exts) resolveFile' :: (MonadIO m, MonadThrow m) => Path Abs Dir -> FilePath.FilePath -> m (Path Abs File) resolveFile' x y = do p <- parseCollapsedAbsFile (toFilePath x FilePath.</> y) exists <- fileExists p if exists then return p else throwM $ ResolveFileFailed x y (toFilePath p) -- | Warn the user that multiple candidates are available for an -- entry, but that we picked one anyway and continued. warnMultiple :: MonadLogger m => DotCabalDescriptor -> Path b t -> [Path b t] -> m () warnMultiple name candidate rest = $logWarn ("There were multiple candidates for the Cabal entry \"" <> showName name <> "\" (" <> T.intercalate "," (map (T.pack . toFilePath) rest) <> "), picking " <> T.pack (toFilePath candidate)) where showName (DotCabalModule name') = T.pack (display name') showName (DotCabalMain fp) = T.pack fp showName (DotCabalFile fp) = T.pack fp showName (DotCabalCFile fp) = T.pack fp -- | Log that we couldn't find a candidate, but there are -- possibilities for custom preprocessor extensions. -- -- For example: .erb for a Ruby file might exist in one of the -- directories. logPossibilities :: (MonadIO m, MonadThrow m, MonadLogger m) => [Path Abs Dir] -> ModuleName -> m () logPossibilities dirs mn = do possibilities <- liftM concat (makePossibilities mn) case possibilities of [] -> return () _ -> $logWarn ("Unable to find a known candidate for the Cabal entry \"" <> T.pack (display mn) <> "\", but did find: " <> T.intercalate ", " (map (T.pack . toFilePath) possibilities) <> ". If you are using a custom preprocessor for this module " <> "with its own file extension, consider adding the file(s) " <> "to your .cabal under extra-source-files.") where makePossibilities name = mapM (\dir -> do (_,files) <- listDirectory dir return (map filename (filter (isPrefixOf (display name) . toFilePath . filename) files))) dirs -- | Get the filename for the cabal file in the given directory. -- -- If no .cabal file is present, or more than one is present, an exception is -- thrown via 'throwM'. getCabalFileName :: (MonadThrow m, MonadIO m) => Path Abs Dir -- ^ package directory -> m (Path Abs File) getCabalFileName pkgDir = do files <- liftIO $ findFiles pkgDir (flip hasExtension "cabal" . FL.toFilePath) (const False) case files of [] -> throwM $ PackageNoCabalFileFound pkgDir [x] -> return x _:_ -> throwM $ PackageMultipleCabalFilesFound pkgDir files where hasExtension fp x = FilePath.takeExtension fp == "." ++ x -- | Path for the package's build log. buildLogPath :: (MonadReader env m, HasBuildConfig env, MonadThrow m) => Package -> Maybe String -> m (Path Abs File) buildLogPath package' msuffix = do env <- ask let stack = configProjectWorkDir env fp <- parseRelFile $ concat $ (packageIdentifierString (packageIdentifier package')) : (maybe id (\suffix -> ("-" :) . (suffix :)) msuffix) [".log"] return $ stack </> $(mkRelDir "logs") </> fp -- Internal helper to define resolveFileOrWarn and resolveDirOrWarn resolveOrWarn :: (MonadLogger m, MonadIO m, MonadReader (Path Abs File, Path Abs Dir) m) => Text -> (Path Abs Dir -> String -> m (Maybe a)) -> FilePath.FilePath -> m (Maybe a) resolveOrWarn subject resolver path = do cwd <- getWorkingDir file <- asks fst dir <- asks (parent . fst) result <- resolver dir path when (isNothing result) $ $logWarn ("Warning: " <> subject <> " listed in " <> T.pack (maybe (FL.toFilePath file) FL.toFilePath (stripDir cwd file)) <> " file does not exist: " <> T.pack path) return result -- | Resolve the file, if it can't be resolved, warn for the user -- (purely to be helpful). resolveFileOrWarn :: (MonadThrow m,MonadIO m,MonadLogger m,MonadReader (Path Abs File, Path Abs Dir) m) => FilePath.FilePath -> m (Maybe (Path Abs File)) resolveFileOrWarn = resolveOrWarn "File" resolveFileMaybe -- | Resolve the directory, if it can't be resolved, warn for the user -- (purely to be helpful). resolveDirOrWarn :: (MonadThrow m,MonadIO m,MonadLogger m,MonadReader (Path Abs File, Path Abs Dir) m) => FilePath.FilePath -> m (Maybe (Path Abs Dir)) resolveDirOrWarn = resolveOrWarn "Directory" resolveDirMaybe
supermario/stack
src/Stack/Package.hs
bsd-3-clause
43,869
0
23
13,668
10,699
5,533
5,166
889
13
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -Wno-orphans #-} module Hasmin.TestUtils ( module Hasmin.TestUtils , module Test.QuickCheck , module Test.Hspec , module Test.Hspec.Attoparsec ) where import Test.Hspec import Test.QuickCheck hiding (NonZero) import Test.QuickCheck.Instances() import Test.Hspec.Attoparsec (parseSatisfies, (~>)) import Control.Applicative (liftA2, liftA3) import Control.Monad (liftM4) import Control.Monad.Reader (runReader) import Data.Text (Text, unpack, singleton) import Data.Attoparsec.Text (Parser) import Hasmin.Types.BgSize import Hasmin.Class import Hasmin.Config import Hasmin.Types.Color import Hasmin.Types.Declaration import Hasmin.Types.Dimension import Hasmin.Types.FilterFunction import Hasmin.Types.Numeric import Hasmin.Types.Position import Hasmin.Types.TimingFunction import Hasmin.Types.RepeatStyle import Hasmin.Types.BasicShape import Hasmin.Types.BorderRadius import Hasmin.Utils minifyWithTestConfig :: Minifiable a => a -> a minifyWithTestConfig x = runReader (minify x) cfg where cfg = defaultConfig { dimensionSettings = DimMinOn } -- | Check that a color is equivalent to their minified representation form prop_minificationEq :: (Minifiable a, Eq a) => a -> Bool prop_minificationEq d = minifyWithTestConfig d == d -- Given a parser and a 3-tuple, prints a test description, -- applies the parser, and compares its result with the expected result matchSpecWithDesc :: ToText a => Parser a -> (String, Text, Text) -> Spec matchSpecWithDesc parser (description, textToParse, expectedResult) = it description $ (toText <$> (textToParse ~> parser)) `parseSatisfies` (== expectedResult) matchSpec :: ToText a => Parser a -> (Text, Text) -> Spec matchSpec parser (textToParse, expectedResult) = it (unpack textToParse) $ (toText <$> (textToParse ~> parser)) `parseSatisfies` (== expectedResult) chooseConstructor :: (Enum a, Bounded a) => Gen a chooseConstructor = oneof $ fmap pure [minBound..] newtype Declarations = Declarations [Declaration] instance ToText Declarations where toText (Declarations ds) = mconcatIntersperse toText (singleton ';') ds instance Arbitrary Length where arbitrary = liftA2 Length arbitrary chooseConstructor instance Arbitrary Angle where arbitrary = liftA2 Angle arbitrary chooseConstructor instance Arbitrary Time where arbitrary = liftA2 Time arbitrary chooseConstructor instance Arbitrary Frequency where arbitrary = liftA2 Frequency arbitrary chooseConstructor instance Arbitrary Resolution where arbitrary = liftA2 Resolution arbitrary chooseConstructor instance Arbitrary Number where arbitrary = toNumber <$> (arbitrary :: Gen Rational) instance Arbitrary PosKeyword where arbitrary = chooseConstructor instance Arbitrary Percentage where arbitrary = fmap Percentage (arbitrary :: Gen Rational) instance Arbitrary FilterFunction where arbitrary = oneof [ Blur <$> arbitrary , Brightness <$> arbitrary , Contrast <$> arbitrary , Grayscale <$> arbitrary , Invert <$> arbitrary , Opacity <$> arbitrary , Saturate <$> arbitrary , Sepia <$> arbitrary , HueRotate <$> arbitrary , liftM4 DropShadow arbitrary arbitrary arbitrary arbitrary ] instance Arbitrary BgSize where arbitrary = oneof [ liftA2 BgSize2 arbitrary arbitrary , fmap BgSize1 arbitrary ] instance Arbitrary Auto where arbitrary = pure Auto instance Arbitrary StepPosition where arbitrary = chooseConstructor instance Arbitrary TimingFunction where arbitrary = oneof [ liftM4 CubicBezier arbitrary arbitrary arbitrary arbitrary , liftA2 Steps arbitrary arbitrary , pure Ease , pure EaseIn , pure EaseInOut , pure EaseOut , pure Linear , pure StepEnd , pure StepStart ] instance Arbitrary Color where arbitrary = oneof [ fmap Named colorKeyword , liftA3 mkHex3 hexChar hexChar hexChar , liftA3 mkHex6 hexString hexString hexString , liftM4 mkHex4 hexChar hexChar hexChar hexChar , liftM4 mkHex8 hexString hexString hexString hexString , liftA3 mkRGBInt intRange intRange intRange , liftA3 mkRGBPer ratRange ratRange ratRange , liftM4 mkRGBAInt intRange intRange intRange alphaRange , liftM4 mkRGBAPer ratRange ratRange ratRange alphaRange , liftA3 mkHSL hueRange ratRange ratRange , liftM4 mkHSLA hueRange ratRange ratRange alphaRange ] where intRange = choose (0, 255) ratRange = toPercentage <$> (choose (0, 100) :: Gen Float) alphaRange = toAlphavalue <$> (choose (0, 1) :: Gen Float) hueRange = choose (0, 360) instance Arbitrary RepeatStyle where arbitrary = frequency [(1, pure RepeatX) ,(1, pure RepeatY) ,(8, liftA2 RepeatStyle2 arbitrary arbitrary) ,(8, fmap RepeatStyle1 arbitrary) ] instance Arbitrary RSKeyword where arbitrary = oneof $ fmap pure [minBound..] instance Arbitrary BasicShape where arbitrary = oneof [liftA2 Inset arbitrary arbitrary ,liftA2 Circle arbitrary arbitrary ,liftA2 Ellipse arbitrary arbitrary ,liftA2 Polygon arbitrary arbitrary ] instance Arbitrary FillRule where arbitrary = oneof [pure NonZero, pure EvenOdd] instance Arbitrary a => Arbitrary (AtMost2 a) where arbitrary = oneof [pure None ,One <$> arbitrary ,liftA2 Two arbitrary arbitrary ] instance Arbitrary ShapeRadius where arbitrary = oneof [SRLength <$> arbitrary ,SRPercentage <$> arbitrary ,pure SRClosestSide ,pure SRFarthestSide ] instance Arbitrary Position where arbitrary = Position <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary BorderRadius where arbitrary = BorderRadius <$> arbitrary <*> arbitrary -- | Generates color keywords uniformly distributed colorKeyword :: Gen Text colorKeyword = oneof $ fmap (pure . fst) keywordColors -- | Generates a hexadecimal character uniformly distributed hexChar :: Gen Char hexChar = oneof $ fmap pure hexadecimals hexString :: Gen String hexString = liftA2 (\x y -> [x,y]) hexChar hexChar hexadecimals :: String hexadecimals = "0123456789abcdef"
contivero/hasmin
tests/Hasmin/TestUtils.hs
bsd-3-clause
6,597
0
11
1,579
1,624
882
742
147
1
module Problem19 where getDayOfWeek :: Int -> Int -> Int -> Int getDayOfWeek 1900 1 1 = 1 getDayOfWeek year 1 1 = (base + (foldl1 (+) $ map daysOfYear [1900..(year-1)])) `mod` 7 where base = getDayOfWeek 1900 1 1 getDayOfWeek year 1 day = (day - 1 + (getDayOfWeek year 1 1)) `mod` 7 getDayOfWeek year month day = ((getDayOfWeek year 1 day) + (foldl1 (+) $ map (daysOfMonth year) [1..(month-1)])) `mod` 7 daysOfMonth :: Int -> Int -> Int daysOfMonth _ 1 = 31 daysOfMonth year 2 | isLeapYear(year) = 29 | otherwise = 28 daysOfMonth _ 3 = 31 daysOfMonth _ 4 = 30 daysOfMonth _ 5 = 31 daysOfMonth _ 6 = 30 daysOfMonth _ 7 = 31 daysOfMonth _ 8 = 31 daysOfMonth _ 9 = 30 daysOfMonth _ 10 = 31 daysOfMonth _ 11 = 30 daysOfMonth _ 12 = 31 daysOfYear :: Int -> Int daysOfYear year | isLeapYear(year) = 366 | otherwise = 365 isLeapYear :: Int -> Bool isLeapYear year = year `mod` 4 == 0 && (not (year `mod` 100 == 0) || year `mod` 400 == 0) sunday :: Int -> Int -> Int -> Int sunday year month day = if getDayOfWeek year month day == 0 then 1 else 0 isFirstSunday :: Int -> Int -> Int isFirstSunday year month = sunday year month 1 firstSundaysInYear :: Int -> Int firstSundaysInYear year = foldl1 (+) (map (isFirstSunday year) [1..12]) main :: IO () main = putStrLn $ show $ foldl1 (+) (map firstSundaysInYear [1901..2000])
noraesae/euler
src/Problem19.hs
bsd-3-clause
1,361
0
13
303
630
330
300
41
2
module Data.List.TypeLevel.Witness.OrdList where import Prelude hiding (head, tail) import Data.Constraint import Data.List.TypeLevel.Cmp import Data.List.TypeLevel.Union (Union) import qualified Data.List.TypeLevel.Union as Union import Data.List.TypeLevel.Witness import Data.Proxy import Data.Tuple.TypeLevel import Data.Type.Equality import Data.Vinyl.Core (Rec (..)) import Data.Vinyl.DictFun tail :: OrdList (c ': cs) -> OrdList cs tail OrdListSingle = OrdListNil tail (OrdListCons x) = x head :: OrdList (c ': cs) -> Proxy c head OrdListSingle = Proxy head (OrdListCons _) = Proxy removalBounded :: RemoveElem a rs ss -> OrdList (b ': rs) -> BoundedList b ss removalBounded RemoveElemDone (OrdListCons OrdListSingle) = BoundedListNil removalBounded RemoveElemDone ol'@(OrdListCons ol''@(OrdListCons ol''')) = case transitiveLT (proxyFst $ head ol''') (proxyFst $ head ol'') (proxyFst $ head ol') of Sub Dict -> BoundedListCons remove :: RemoveElem a rs ss -> OrdList rs -> OrdList ss remove = go where go :: forall a rs ss. RemoveElem a rs ss -> OrdList rs -> OrdList ss go RemoveElemDone OrdListSingle = OrdListNil go RemoveElemDone (OrdListCons olNext) = olNext go (RemoveElemNext rmNext) ol = case olRes of OrdListCons _ -> case removalBounded rmNext ol of BoundedListCons -> OrdListCons olRes OrdListSingle -> case removalBounded rmNext ol of BoundedListCons -> OrdListCons olRes where olRes = go rmNext (tail ol) insert :: InsertElemOrd a rs ss -> OrdList rs -> OrdList ss insert ieo ol = case ieo of InsertElemOrdSpecial s -> case s of SpecialInsertSingle -> case ol of OrdListNil -> OrdListSingle SpecialInsertFirst -> case ol of OrdListSingle -> OrdListCons ol OrdListCons _ -> OrdListCons ol InsertElemOrdRecursive r -> go r ol where go :: forall a rs ss. RecursiveInsert a rs ss -> OrdList rs -> OrdList ss go RecursiveInsertLast OrdListSingle = OrdListCons OrdListSingle go RecursiveInsertMiddle (OrdListCons olNext) = OrdListCons (OrdListCons olNext) go (RecursiveInsertNext inext) (OrdListCons onext) = case resNext of OrdListCons _ -> case recInsertSameHead inext of Refl -> OrdListCons resNext OrdListSingle -> case recInsertSameHead inext of Refl -> OrdListCons resNext where resNext = go inext onext recInsertSameHead :: RecursiveInsert r (a ': rs) (b ': ss) -> a :~: b recInsertSameHead RecursiveInsertLast = Refl recInsertSameHead RecursiveInsertMiddle = Refl recInsertSameHead (RecursiveInsertNext _) = Refl downgradeInsert :: InsertElemOrd r rs ss -> RemoveElem r ss rs downgradeInsert ins = case ins of InsertElemOrdSpecial s -> case s of SpecialInsertSingle -> RemoveElemDone SpecialInsertFirst -> RemoveElemDone InsertElemOrdRecursive r -> go r where go :: forall r rs ss. RecursiveInsert r rs ss -> RemoveElem r ss rs go RecursiveInsertLast = RemoveElemNext RemoveElemDone go RecursiveInsertMiddle = RemoveElemNext RemoveElemDone go (RecursiveInsertNext inext) = RemoveElemNext (go inext) union :: Rec CmpDict ls -> Rec CmpDict rs -> OrdList ls -> OrdList rs -> OrdList (Union ls rs) union = go where go :: forall ls rs. Rec CmpDict ls -> Rec CmpDict rs -> OrdList ls -> OrdList rs -> OrdList (Union ls rs) go RNil RNil OrdListNil OrdListNil = OrdListNil go ls RNil lsOrd OrdListNil = case Union.rightIdentity ls of Refl -> lsOrd go RNil rs OrdListNil rsOrd = case Union.leftIdentity rs of Refl -> rsOrd go ls@(l@DictFun :& lsNext) rs@(r@DictFun :& rsNext) lsOrd rsOrd = let lsOrdNext = tail lsOrd rsOrdNext = tail rsOrd in case compareTypes (proxyFst l) (proxyFst r) of CmpGT -> case upperBound (toBoundedList lsOrd) BoundedListCons lsNext rs of BoundedListNil -> OrdListSingle BoundedListCons -> OrdListCons (go lsNext rs lsOrdNext rsOrd) CmpLT -> case upperBound BoundedListCons (toBoundedList rsOrd) ls rsNext of BoundedListNil -> OrdListSingle BoundedListCons -> OrdListCons (go ls rsNext lsOrd rsOrdNext) CmpEQ -> case eqTProxy (proxySnd l) (proxySnd r) of Nothing -> error "ordlist union: messed up" Just Refl -> case tupleEquality l r of Sub Dict -> case upperBound (toBoundedList lsOrd) (toBoundedList rsOrd) lsNext rsNext of BoundedListNil -> OrdListSingle BoundedListCons -> OrdListCons (go lsNext rsNext lsOrdNext rsOrdNext) toBoundedList :: OrdList (a ': as) -> BoundedList a as toBoundedList o = case o of OrdListSingle -> BoundedListNil OrdListCons _ -> BoundedListCons sublist :: Sublist super sub -> OrdList super -> OrdList sub sublist = go where go :: Sublist super sub -> OrdList super -> OrdList sub go SublistNil OrdListNil = OrdListNil go (SublistBoth SublistNil) OrdListSingle = OrdListSingle go (SublistSuper SublistNil) OrdListSingle = OrdListNil go (SublistSuper snext) (OrdListCons onext) = go snext onext go (SublistBoth snext) ol@(OrdListCons onext) = case lemma1 snext ol of BoundedListCons -> OrdListCons (go snext onext) BoundedListNil -> OrdListSingle lemma1 :: Sublist super sub -> OrdList (b ': super) -> BoundedList b sub lemma1 SublistNil OrdListSingle = BoundedListNil lemma1 (SublistBoth s') (OrdListCons o') = BoundedListCons lemma1 (SublistSuper SublistNil) o@(OrdListCons OrdListSingle) = BoundedListNil lemma1 (SublistSuper s') o@(OrdListCons o'@(OrdListCons o'')) = case transitiveLT (proxyFst $ head o'') (proxyFst $ head o') (proxyFst $ head o) of Sub Dict -> lemma1 s' (OrdListCons o'') upperBound :: BoundedList u as -> BoundedList u bs -> Rec CmpDict as -> Rec CmpDict bs -> BoundedList u (Union as bs) upperBound = go where go :: forall u as bs. BoundedList u as -> BoundedList u bs -> Rec CmpDict as -> Rec CmpDict bs -> BoundedList u (Union as bs) go BoundedListNil BoundedListNil RNil RNil = BoundedListNil go BoundedListNil BoundedListCons RNil (_ :& _) = BoundedListCons go BoundedListCons BoundedListNil (_ :& _) RNil = BoundedListCons go bl@BoundedListCons br@BoundedListCons asCmp@(a@DictFun :& asCmpNext) bsCmp@(b@DictFun :& bsCmpNext) = case compareTypes (proxyFst a) (proxyFst b) of CmpLT -> BoundedListCons CmpGT -> BoundedListCons CmpEQ -> case eqTProxy (proxySnd a) (proxySnd b) of Just Refl -> BoundedListCons Nothing -> error "upperBound: eq refl failure"
andrewthad/vinyl-vectors
src/Data/List/TypeLevel/Witness/OrdList.hs
bsd-3-clause
6,586
0
23
1,417
2,199
1,097
1,102
-1
-1
{-# LANGUAGE DeriveDataTypeable, BangPatterns, ScopedTypeVariables #-} {-# LANGUAGE ExistentialQuantification #-} {-# OPTIONS_GHC -Wall -fno-warn-orphans #-} module Development.Cake.Core where import Development.Cake.Core.Types import Development.Cake.Options import Control.Applicative import Control.Concurrent.MVar import Control.DeepSeq import Control.Exception as Exception hiding ( unblock ) import Control.Monad import Control.Monad.IO.Class import Control.Concurrent.ParallelIO.Local import Data.Binary import Data.Either import Data.List import Data.Maybe ( catMaybes ) import Data.Typeable ( Typeable(..) ) import GHC.Conc ( numCapabilities ) import System.Directory ( getModificationTime ) import System.FilePath.Canonical import System.IO.Error ( isDoesNotExistError ) import System.Time ( ClockTime(..) ) import qualified Data.Map as M newtype ModTime = M ClockTime instance Binary ModTime where put (M (TOD t1 t2)) = put t1 >> put t2 get = do t1 <- get; t2 <- get; return (M (TOD t1 t2)) instance Eq ModTime where M t1 == M t2 = t1 == t2 instance Show ModTime where show (M t) = show t newtype Database = DB { unDB :: M.Map CanonicalFilePath Status } deriving Show printDatabase :: Database -> IO () printDatabase (DB db) = mapM_ print (M.toList db) instance Binary Database where put (DB db) = put db get = DB <$> get type Target = CanonicalFilePath -- | A question with a namespace and a question as an arbitrary string. -- -- The user usually shouldn't use this type. Instead, the oracle provider -- should implement wrappers that construct the question of the right form -- and pass it to 'query'. -- -- See also: 'installOracle'. -- data Question = Question String String -- namespace + question deriving (Eq, Ord) instance Show Question where show (Question namespace question) = "Q[" ++ namespace ++ "]: " ++ show question instance Binary Question where put (Question n q) = put n >> put q get = Question <$> get <*> get -- TODO: ATM, Oracles are expected to do their own answer-caching. -- | Install a new oracle for answering non-file requirements. -- -- Oracles are used for things such as listing directory contents or -- querying environment variables. It's called an oracle because all -- it does is answer questions, but we don't care how it does that. -- -- An oracle should typically be total. The @Nothing@ result is intended -- to communicate the fact that the given oracle didn't understand the -- question. Each question has a namespace, and an oracle should only -- answer questions for its namespace. Use exceptions if partiality is -- really required, e.g., @ls@ may fail due to access control errors. -- installOracle :: (Question -> IO (Maybe Answer)) -> Cake () installOracle fn = Cake $ \mst -> do modifyMVar_ mst $ \st -> return st{ csOracle = fn `combineOracle` csOracle st } where combineOracle oracle1 oracle2 question = do mb_ans <- oracle1 question case mb_ans of Nothing -> oracle2 question Just _ -> return mb_ans query :: Question -> Act Answer query question = do oracle <- aeOracle <$> askActEnv mb_answer <- liftIO (try (oracle question)) case mb_answer of Right (Just answer) -> do appendHistory (Oracle question answer) return answer Right Nothing -> fail $ "Could not answer question: " ++ show question ++ "\nMissing oracle?" Left err -> liftIO (throwIO (WrappedException err)) type Answer = [String] data Status = Dirty History ModTime | Building WaitHandle | Clean History ModTime | Failed CakeException deriving Show instance Binary Status where put (Dirty hist t) = putWord8 1 >> put hist >> put t put (Clean hist t) = putWord8 2 >> put hist >> put t put (Building _) = error "Cannot serialise in-progress database" put (Failed msg) = putWord8 3 >> put (showCakeException msg) get = do tag <- getWord8 case tag of 1 -> Dirty <$> get <*> get 2 -> Dirty <$> get <*> get -- load all files as dirty! 3 -> Failed . RuleError <$> get _ -> error "Invalid tag when deserialising Status" -- State transitions: -- -- Dirty|not-in-DB -> Building -> Clean|Failed type Reason = String data ActEnv = ActEnv { aeDatabase :: MVar Database , aeRules :: [Rule] , aeOracle :: Question -> IO (Maybe Answer) , aePool :: Pool , aeLogLock :: MVar () -- ^ Lock for printing messages. Without the lock, single -- characters might be interleaved when using 'putStrLn'. Use -- 'report' instead. , aeNestLevel :: Int , aeVerbosity :: Verbosity } report :: Verbosity -> String -> Act () report verb msg = do env <- askActEnv liftIO $ report' env verb msg report' :: ActEnv -> Verbosity -> String -> IO () report' env verb _msg | verb > aeVerbosity env = return () report' env _verb msg = withMVar (aeLogLock env) $ \() -> do let indentStr = replicate (2 * (aeNestLevel env)) ' ' let msg_lines = unlines (map (indentStr++) (lines msg)) putStr msg_lines -- | Rules within a rule set are in the same order in which they were -- added. type RuleSet = [Rule] newtype History = H [QA] deriving Show instance Binary History where put (H qas) = put qas get = H <$> get -- | An entry in the history. -- -- For files, it generates data QA = Oracle Question Answer | Need [(CanonicalFilePath, ModTime)] deriving Show instance Binary QA where put (Need entries) = putWord8 1 >> put entries put (Oracle question ans) = putWord8 2 >> put question >> put ans get = do tag <- getWord8 case tag of 1 -> Need <$> get 2 -> Oracle <$> get <*> get _ -> error "Cannot decode QA" instance Binary CanonicalFilePath where put cfp = put (originalFilePath cfp) >> put (canonicalFilePath cfp) get = unsafeCanonicalise <$> get <*> get newtype Act a = Act { unAct :: ActEnv -> MVar ActState -> IO a } askActEnv :: Act ActEnv askActEnv = Act (\env _ -> return env) tryAct :: Exception e => Act a -> Act (Either e a) tryAct body = Act (\env mst -> try (unAct body env mst)) instance Functor Act where fmap f act = Act (\env mst -> fmap f (unAct act env mst)) instance Monad Act where return x = Act (\_env _mst -> return x) act >>= k = Act (\env mst -> do a <- unAct act env mst unAct (k a) env mst) fail msg = Act (\_env _mst -> throwIO (RuleError msg)) instance MonadIO Act where liftIO ioact = Act (\_env _mst -> ioact) data ActState = ActState { asHistory :: History } appendHistory :: QA -> Act () appendHistory qa = Act (\_env mst -> modifyMVar_ mst $ \st -> let H hist = asHistory st in return st{ asHistory = H (hist ++ [qa]) }) newtype Cake a = Cake { unCake :: MVar CakeState -> IO a } data CakeState = CakeState { csRules :: [Rule], csActs :: [Act ()], csOracle :: Question -> IO (Maybe Answer) } instance Monad Cake where return x = Cake (\_mst -> return x) act >>= k = Cake (\mst -> do a <- unCake act mst unCake (k a) mst) instance MonadIO Cake where liftIO act = Cake (\_mst -> act) -- | Queue an action to be run when all rules have been loaded. -- -- There is no guarantee about the order in which items scheduled by -- multiple calls to this function are executed. I.e., if we have -- -- > queueAct act1 >> queueAct act2 -- -- then @act1@ and @act2@ will be executed in any order or in -- parallel. queueAct :: Act () -> Cake () queueAct act = Cake $ \mst -> modifyMVar_ mst $ \st -> return st{ csActs = act : csActs st } type Rule = CanonicalFilePath -> IO (Maybe Generates) -- | Specification of a rule result. data Generates = Generates { genOutputs :: [CanonicalFilePath] -- ^ The files that the rule generates. , genAction :: Act [ModTime] -- ^ The action to generate the specified files. Returns -- modification times of the generated files (in the same order). } mkDatabase :: IO (MVar Database) mkDatabase = newMVar (DB M.empty) type Pattern = String data CakeException = RuleError String | RecursiveError [(TargetDescr, CakeException)] | WrappedException SomeException deriving Typeable type TargetDescr = String instance Show CakeException where show = unlines . showCakeException showCakeException :: CakeException -> [String] showCakeException (RuleError s) = ["Error in rule definition: " ++ s] showCakeException (WrappedException e) = ["Error while executing rule: " ++ show e] showCakeException (RecursiveError nested_errs) = ["The following dependenc" ++ plural_y ++ " failed to build: "] ++ map indent (concatMap showNested nested_errs) where indent line = " " ++ line showNested (target, exception) = [ target ++ ":" ] ++ map indent (showCakeException exception) plural_y = case nested_errs of [_] -> "y" _ -> "ies" instance Exception.Exception CakeException instance NFData CakeException where rnf (RuleError a) = rnf a rnf (RecursiveError nesteds) = rnf nesteds rnf (WrappedException _) = () type CakeSuccess a = Either CakeException a cakeError :: String -> IO a cakeError s = Exception.throwIO $ RuleError s panic :: String -> IO a panic s = Exception.throwIO $ RuleError ("PANIC: " ++ s) -- | Find a single rule matching the given file. -- -- Returns: -- -- * The targets that would be produced by the matched rule. -- -- * The action to run in order to produce these targets. The returned -- modification times are in the same order as the list of targets. -- -- This is in 'IO' because looking up a rule may fail (in which case -- an exception will be thrown). findRule :: ActEnv -> RuleSet -> CanonicalFilePath -> IO ([CanonicalFilePath], ActEnv -> IO (History, [ModTime])) findRule env ruleSet goal = do mb_gens <- mapMaybeM (tryToMatch goal) ruleSet case mb_gens of [] -> do report' env chatty $ "NORULE " ++ show goal ++ ": using default rule" mb_dflt <- defaultRule env goal case mb_dflt of Nothing -> cakeError $ "No rule to build " ++ show goal Just (outs, act) -> return (outs, \_env -> do modtimes <- liftIO act return (H [], modtimes)) [gen] -> do report' env chatty $ "RULE " ++ show goal ++ ": outputs: " ++ show (genOutputs gen) return (genOutputs gen, \e -> runAct e (genAction gen)) (gen:_) -> do report' env silent $ "Ambiguous rules for " ++ show goal ++ ": choosing first one." return (genOutputs gen, \e -> runAct e (genAction gen)) where tryToMatch gl rule = rule gl -- | Returns the default rule for the given target (if any). -- -- For a file we have a default rule if the file already exists on -- disk. The returned action merely returns the modification date of -- the file. defaultRule :: ActEnv -> CanonicalFilePath -> IO (Maybe ([CanonicalFilePath], IO [ModTime])) defaultRule env file = do mb_time <- getFileModTime file case mb_time of Nothing -> return Nothing Just modtime -> return (Just ([file], do report' env chatty $ "MODTIME: " ++ show file ++ " = " ++ show modtime return [modtime])) -- | Monadic map over a list keeping the @Just x@ results of the function. -- -- In other words, @mapMaybeM = liftM catMaybes . mapM@ but it's slightly -- more efficient. mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b] mapMaybeM f = go where go [] = return [] go (x:xs) = do mb_y <- f x case mb_y of Nothing -> go xs Just y -> liftM (y:) (go xs) -- | Run an @Act a@ action with an initially empty history and return -- final history. runAct :: ActEnv -> Act a -> IO (History, a) runAct env (Act act) = do mst <- newMVar (ActState{ asHistory = H [] }) res <- act env mst st <- readMVar mst return (asHistory st, res) -- Check whether the given targets are up to date. -- type NeedsRebuilding = Either CakeException [ModTime] -- | The result of checking a history entry. data CheckQAResult = QAFailure CakeException -- ^ The target (or any of its dependencies) failed to build. | QAClean -- ^ The target (and all its dependencies) is up to date. | QARebuild -- ^ The target needs to be rebuilt. -- | Check a single history entry. -- -- Checking a single dependency means also checking its dependencies -- and their dependencies, etc. If any of the dependencies need -- rebuilding, we do so right away. In these cases, the checked -- target needs rebuilding as well, so we return 'QARebuild' (or -- 'QAFailure'). checkQA :: ActEnv -> QA -> IO CheckQAResult checkQA env (Need entries) = do let (outputs, old_modtimes) = unzip entries result <- need' env outputs case result of Right new_modtimes -> do let oks = zipWith3 check outputs new_modtimes old_modtimes report' env chatty $ "CHECKQA " ++ show (zip new_modtimes old_modtimes) ++ "\n" ++ show oks return (if and oks then QAClean else QARebuild) Left err -> return (QAFailure err) where check _goal new_time old_time = old_time == new_time checkQA env (Oracle question old_answer) = do mb_new_answer <- try (aeOracle env question) report' env chatty $ "CHECKQA " ++ show (question, old_answer, mb_new_answer) case mb_new_answer of Right Nothing -> -- Weird, the current oracle couldn't answer the old question. -- Perhaps we updated the build file, so let's try to just -- rebuild. If we ask the same question again we'll get the -- error during rebuilding. return QARebuild Right (Just new_answer) -> if new_answer /= old_answer then return QARebuild else return QAClean Left err -> return (QAFailure (WrappedException err)) -- TODO: Example: We question the environment and a variable is no -- longer defined checkHistory :: ActEnv -> History -> IO CheckQAResult checkHistory env (H hist) = do report' env chatty $ "HISTCHECK (" ++ show (length hist) ++ ")" go hist where go [] = return QAClean go (qa:qas) = do rebuild <- checkQA env qa case rebuild of QAClean -> go qas _ -> return rebuild checkOne :: ActEnv -> CanonicalFilePath -> IO (Either CakeException ModTime) checkOne env goal_ = do todo <- grabTodo goal_ result <- case todo of UptoDate modtime -> do report' env chatty $ "CLEAN " ++ show goal_ return (Right modtime) BlockOn waitHandle -> do -- We are about to block on the wait handle, make sure we -- release the worker as required by "parallel-io" report' env chatty $ "BLOCK " ++ show goal_ extraWorkerWhileBlocked (aePool env) $ do result <- waitOnWaitHandle waitHandle report' env chatty $ "UNBLOCK " ++ show goal_ return result CheckHistory _hist _modtime unblock targets Nothing action -> do -- One of the targets produced by the action is already known -- to require rebuilding. We can shortcut this case here. let reason = "One of its rule targets needs rebuilding" runRule reason unblock targets action CheckHistory hist modtime unblock targets (Just modtimes) action -> do -- TODO: Do we want to check the history of all 'targets'? -- This rule creates all our targets. Nevertheless, some -- targets may have different modtimes. However, we're only -- checking one file and we can assume that all targets share -- the same history (really?). Rules that conditionally -- create targets are forbidden. -- -- Note: Checking history involves recursively -- checking/building all dependencies first. -- -- Should we check history of all rule outputs? No - they -- must have the same history! (Unless we have overlapping -- rules.) needs_rebuild <- checkHistory env hist case needs_rebuild of QARebuild -> runRule "history check failed, one or more dependencies changed" unblock targets action QAFailure err -> do modifyMVar_ (aeDatabase env) $ \db -> return $ updateStatus db (targets `zip` (repeat (Failed err))) _ <- unblock (Left err) return (Left err) QAClean -> do -- The history might be clean, but the file has been -- modified. This could be the case if it's a file on disk -- (which doesn't have any dependencies) or it's an -- auto-generated file and the user has accidentally edited -- it. In that case we must rebuild the file. mb_time <- getFileModTime goal_ case mb_time of Nothing -> do -- History is clean, but file doesn't exist? May have -- been deleted in a clean action. Just rebuild. runRule "history clean, but file does not exist" unblock targets action Just newtime | newtime /= modtime -> do report' env chatty $ "MODIFIED " ++ show goal_ ++ show (modtime, newtime) runRule "history clean, but file has been modified" unblock targets action _ -> do -- NOW the target is actually clean. report' env chatty $ "HISTCLEAN " ++ show goal_ ++ " No rebuild needed" modifyMVar_ (aeDatabase env) (\db -> do let db' = updateStatus db $ zip targets (map (Clean hist) modtimes) return db') unblock (Right modtimes) return (Right modtime) Rebuild reason unblock targets _modtimes action -> do runRule reason unblock targets action PropagateFailure exc -> do return (Left exc) report' env chatty $ "DONE " ++ show goal_ ++ " " ++ show result return result where -- Atomically grab a BuildTodo. -- -- If the Todo requires action, we immediately change the current -- state of the item in the database to Building, so that other -- workers will wait for us. grabTodo :: CanonicalFilePath -> IO BuildTodo grabTodo goal = do modifyMVar (aeDatabase env) $ \db@(DB mdb) -> case M.lookup goal mdb of Nothing -> do markItemAsBuilding goal db (Rebuild "Not in database") Just (Dirty hist modtime) -> markItemAsBuilding goal db (CheckHistory hist modtime) Just (Clean _hist modtime) -> return (db, UptoDate modtime) Just (Building waitHandle) -> return (db, BlockOn waitHandle) Just (Failed exception) -> return (db, PropagateFailure exception) -- markItemAsFailed goal db exception -- TODO: mark all rule targets as failed, too. --return (db, PropagateFailure exception) -- panic "NYE: Something failed" -- When we discover that an item *may* need rebuilding, we have to -- lock it in the database before we release the lock. markItemAsBuilding :: CanonicalFilePath -> Database -> ((Either CakeException [ModTime] -> IO ()) -> [CanonicalFilePath] -> Maybe [ModTime] -> (ActEnv -> IO (History, [ModTime])) -> BuildTodo) -> IO (Database, BuildTodo) markItemAsBuilding goal db todo_kont = do -- TODO: Sanity check (goal `member` outputs) -- TODO: Sanity check: none of the other outputs are already building -- TODO: findRule may throw an exception! mb_rule <- try $ findRule env (aeRules env) goal case mb_rule of Right (outputs, action) -> do (unblock, waitHandles) <- newWaitHandle outputs -- We need to lock all possibly generated targets at once. let db' = updateStatus db (zip outputs (map Building waitHandles)) let mtimes = targetModTimes db outputs return (db', todo_kont unblock outputs mtimes action) Left exc -> do let db' = updateStatus db (zip [goal] [Failed exc]) return (db', PropagateFailure exc) -- return (db', runRule rebuildReason unblock targets action = do report' env chatty $ "REBUILD " ++ show goal_ ++ ": " ++ rebuildReason -- Execute the action actResult <- try (action env) case actResult of Right (hist, modtimes) -> do modifyMVar_ (aeDatabase env) $ \db -> return $ updateStatus db (targets `zip` map (Clean hist) modtimes) _ <- unblock (Right modtimes) let Just idx = elemIndex goal_ targets -- return modification date of current goal return (Right (modtimes !! idx)) Left (someExc :: SomeException) -> do -- Yes, we're catching *all* exceptions. This should be -- fine, because we're going to abort building anyway. We -- only unroll the dependency chain to build a more -- informative error. -- -- The final top-level 'need' will then rethrow the resulting -- exception. A problem is that the top-level exception will -- always be a 'CakeException', if the user pressed -- Control-C that information will be hidden inside the -- CakeException. let exc = wrapException someExc modifyMVar_ (aeDatabase env) $ \db -> return $ updateStatus db (targets `zip` (repeat (Failed exc))) _ <- unblock (Left exc) return (Left exc) wrapException :: SomeException -> CakeException wrapException exc = case fromException exc of Just e -> e Nothing -> WrappedException exc -- | Updates each 'Target''s status in the database. updateStatus :: Database -> [(Target, Status)] -> Database updateStatus db [] = db updateStatus (DB db) ((goal, st):goals) = let !db' = M.insert goal st db in updateStatus (DB db') goals -- | Find modification times for targets if available for all targets. -- -- Returns @Just modtimes@ iff a modification date was available for -- each of the targets, i.e., for each file we either have a history -- or have already built it. @Nothing@, otherwise. targetModTimes :: Database -> [Target] -> Maybe [ModTime] targetModTimes (DB db) targets = go targets [] where go [] modtimes = Just (reverse modtimes) go (tgt:tgts) modtimes = case M.lookup tgt db of Just (Dirty _hist modtime) -> go tgts (modtime:modtimes) Just (Clean _hist modtime) -> go tgts (modtime:modtimes) _ -> Nothing -- The 'Building' race: -- -- We concurrently check targets for some to rebuild. We want to -- ensure that each target is only built by one thread. If a worker -- decides to build a target, the worker must lock it in the database. -- -- Some rules may create multiple targets, say [A, B]. Now consider -- the case where two workers concurrently check A and B. If one -- worker decides to build A it cannot just lock A, it must lock B, -- too. This in turn requires that we find the rule to build A while -- holding the database lock. -- -- This means that we need to look up the rule, even if we just need -- to check the history, because we have to lock all files while -- checking the history. -- | A wait handle. -- -- If we discover that a file is building, we store a @WaitHandle@ in -- the database. If another worker thread comes along it will block -- on the wait handle. When the building thread is done, it will -- unblock the wait handle and wake up any waiting threads. -- -- A rule may build multiple targets. This means that multiple -- threads may wait on the same action to finish, but actually want to -- read different files. We therefore create multiple wait handles -- (one for each output) but they all share the same internal @MVar@. -- -- When a wait handle is unblocked we return the modification time -- of the corresponding target. We therefore store a selector function -- to pick the modification time. data WaitHandle = WaitHandle (MVar [BuildResult]) ([BuildResult] -> BuildResult) type BuildResult = Either CakeException ModTime instance Show WaitHandle where show _ = "<waithandle>" -- | Create a new 'WaitHandle' for the given targets. -- -- This returns: -- -- * A function to unblock the handle. It takes as argument the -- modification times of the targets. Note that the order of the -- modification times must match the order of the targets. I.e., -- the first modification time, must be the modification time of -- the first target and so on. -- -- * multiple handles that get unblocked simultaneously, but may -- return different 'ModTime's. The order matches the order of the -- targets. -- newWaitHandle :: [CanonicalFilePath] -> IO (Either CakeException [ModTime] -> IO (), [WaitHandle]) newWaitHandle goals = do mvar <- newEmptyMVar let ngoals = length goals return (\modtimes -> case modtimes of Left exc -> putMVar mvar (replicate ngoals (Left exc)) Right mtimes -> putMVar mvar (map Right mtimes), map (WaitHandle mvar) (take (length goals) selectorFunctions)) -- | Block on a @WaitHandle@ until it's done. waitOnWaitHandle :: WaitHandle -> IO BuildResult waitOnWaitHandle (WaitHandle mvar f) = do modtimes <- readMVar mvar return (f modtimes) -- | The infinite list of element selector functions. That is: -- -- > [(!! 0), (!! 1), (!! 2), ...] selectorFunctions :: [[a] -> a] selectorFunctions = map nth [0..] where nth n xs = xs !! n -- | Describes what we should do with the target. data BuildTodo = Rebuild Reason -- why are we rebuilding? UnblockAction -- unblock function of wait handle. [CanonicalFilePath] -- the targets we're goint to build (Maybe [ModTime]) -- their modification times if all known (ActEnv -> IO (History, [ModTime])) -- build action -- ^ The target must be rebuilt. The 'Reason' is a human-readable -- description of why it needs to be rebuilt. | CheckHistory History ModTime UnblockAction -- same as above [CanonicalFilePath] (Maybe [ModTime]) (ActEnv -> IO (History, [ModTime])) -- ^ The target may not be up to date, so we have to check its -- history. | UptoDate ModTime -- ^ The target is up to date. Nothing needs to be done. | BlockOn WaitHandle -- ^ The target is currently being processed by another worker, -- (or that worker is blocked on another dependency and so on) so -- we have to wait for it. | PropagateFailure CakeException -- ^ We previously tried to build the target and got an error. We -- now propagate this error to its dependents. type UnblockAction = Either CakeException [ModTime] -> IO () ------------------------------------------------------------------------ -- * User API -- | Ensure all given targets are up to date. need' :: MonadIO m => ActEnv -> [CanonicalFilePath] -> m (Either CakeException [ModTime]) need' env goals = do results <- liftIO $ parallel (aePool env) $ map (checkOne env{ aeNestLevel = aeNestLevel env + 1 }) goals case partitionEithers results of ([], modtimes) -> return (Right modtimes) (_:_, _) -> return (Left (mkRecursiveError (zip goals results))) mkRecursiveError :: [(CanonicalFilePath, Either CakeException ModTime)] -> CakeException mkRecursiveError = RecursiveError . mapFilter keepError where keepError (fp, Left err) = Just (show fp, err) keepError _ = Nothing -- | Combines 'map' and 'filter' into one operation. If the function -- argument returns @Just y@, then @y@ will appear in the result list. -- Preserves ordering of the input list. mapFilter :: (a -> Maybe b) -> [a] -> [b] mapFilter f = catMaybes . map f need :: [CanonicalFilePath] -> Act [ModTime] need goals = do env <- askActEnv result <- need' env goals case result of Right modtimes -> do appendHistory (Need (goals `zip` modtimes)) return modtimes Left err -> liftIO $ throwIO err cakeWithOptions :: Options -> Cake () -> IO () cakeWithOptions opts collectRules = do mst <- newMVar (CakeState{ csRules = [] , csActs = [] , csOracle = \_ -> return Nothing }) unCake collectRules mst st <- takeMVar mst let rules = reverse (csRules st) acts = reverse (csActs st) oracle = csOracle st db <- loadDatabase databaseFilePath mdb <- newMVar db logLock <- newMVar () -- | TODO: Make customisable let poolSize = numCapabilities + 1 withPool poolSize $ \pool -> do let env = ActEnv{ aeDatabase = mdb, aeRules = reverse rules, aeOracle = oracle, aePool = pool, aeLogLock = logLock, aeNestLevel = 0, aeVerbosity = optionVerbosity opts } -- This is where we kick off the actual work parallel_ pool $ map (runAct env) acts report' env chatty $ "Writing database" db' <- takeMVar mdb writeDatabase databaseFilePath db' return () addRule :: Rule -> Cake () addRule rule = Cake (\mst -> do modifyMVar_ mst (\st -> return st{ csRules = rule : csRules st })) databaseFilePath :: FilePath databaseFilePath = ".cake-db" loadDatabase :: FilePath -> IO Database loadDatabase fp = stripFailures <$> handleDoesNotExist (return (DB M.empty)) (decodeFile fp) where -- TODO: We need to think about what should happen to on-disk DB -- entries for Failed builds. Currently, we strip them from the -- loaded DB, so that we try to build them again this time around. -- Is there anything better we can do? stripFailures (DB mp) = DB (M.filter (not . isFailure) mp) isFailure (Failed _) = True isFailure _ = False writeDatabase :: FilePath -> Database -> IO () writeDatabase = encodeFile -- | Get file modification time (if the file exists). getFileModTime :: CanonicalFilePath -> IO (Maybe ModTime) getFileModTime cfp = handleDoesNotExist (return Nothing) $ Just . M <$> getModificationTime (canonicalFilePath cfp) -- | Do an action in case we get a file-does-not-exist exception. -- -- Argument order is the same as for 'handle'. handleDoesNotExist :: IO a -- ^ Do this in case of error -> IO a -- ^ Try doing this. -> IO a handleDoesNotExist = handleIf isDoesNotExistError -- | Variant of 'handleJust' with a predicate instead of a 'Just b' -- transformer. handleIf :: Exception.Exception e => (e -> Bool) -- ^ Handle exception if this function returns 'True'. -> IO a -- ^ Handler (executed if body raises an exception). -> IO a -- ^ Body. -> IO a handleIf p handler act = Exception.handleJust (guard . p) (\() -> handler) act
nominolo/cake
src/Development/Cake/Core.hs
bsd-3-clause
31,419
10
55
8,407
7,405
3,790
3,615
534
16
{-# LANGUAGE BangPatterns, RecordWildCards, FlexibleContexts, TemplateHaskell, RankNTypes, KindSignatures #-} module RollingVector where import qualified Data.Vector.Generic as G import Data.Word import Data.Bits import Control.Monad.ST import Control.Monad.State.Strict import Control.Lens import Control.Monad.Morph (hoist) import Conduit import qualified Test.QuickCheck as QC import qualified Data.Vector as V -- import Debug.Trace import Control.Exception (assert) import Data.List hashCombine :: Word64 -> Word64 -> Word64 hashCombine !x !y = (x `rotateL` 1) `xor` y {-# INLINE hashCombine #-} data HashType a = HashType { hash :: a -> Word64 , window :: Int , mask :: Word64 } addRemove :: Int -> Word64 -> Word64 -> Word64 addRemove !w !o !n = (o `rotateL` w) `xor` n {-# INLINE addRemove #-} prehash :: (G.Vector v a, G.Vector v Word64) => HashType a -> v a -> Word64 -> Word64 prehash HashType{..} v h = G.foldl' hashCombine h x where x = G.map hash v nextBoundary :: (G.Vector v a, MonadState Word64 m) => HashType a -> v a -> v a -> m (Maybe Int) nextBoundary HashType{..} !old !new = state $ \h0 -> runST (go h0 0) where inputSize = G.length new go !h !iIn | iIn < inputSize = do case (h' .&. mask) == mask of True -> return (Just $ iIn + 1, h') False -> go h' (iIn + 1) | otherwise = return (Nothing, h) where hi = addRemove window (hash (old G.! iIn)) (hash (new G.! iIn)) -- TODO: G.unsafeIndex h' = hashCombine h hi {-# INLINE nextBoundary #-} contiguous :: (Monad m, G.Vector v a) => HashType a -> v a -> v a -> Producer (StateT Word64 m) (Bool, v a) contiguous ht = go where go !old !new = do x <- nextBoundary ht old new case x of Nothing -> yield (False, new) Just n -> do yield (True, a) go old' new' where (a, new') = G.splitAt n new old' = G.drop n old data HashState a = HashState { _lastHash :: !Word64, _lastWindow :: !a } makeLenses ''HashState initialHashState :: G.Vector v a => HashState (v a) initialHashState = HashState 0 G.empty initial :: (Monad m, G.Vector v a, G.Vector v Word64) => HashType a -> Maybe (v a) -> Conduit (v a) (StateT (HashState (v a)) m) (Bool, v a) initial _ Nothing = return () initial ht@HashType{..} (Just x) = do w <- use lastWindow if G.length w < window then do let n = window - G.length w (xi, xn) = G.splitAt n x w' = w G.++ xi lastWindow .= w' lastHash %= prehash ht xi yield (False, xi) if G.length w' < window then await >>= initial ht else leftover xn else leftover x warm :: (Monad m, G.Vector v a) => HashType a -> Maybe (v a) -> Conduit (v a) (StateT (HashState (v a)) m) (Bool, v a) warm _ Nothing = return () warm ht@HashType{..} (Just x) = do w <- use lastWindow w' <- hoist (zoom lastHash) $ assert (G.length w == window) $ do contiguous ht w (G.take window x) let len = G.length x when (len > window) $ contiguous ht x (G.drop window x) return $ G.drop len w G.++ G.drop (len - window) x lastWindow .= w' await >>= warm ht rollsplit :: (Monad m, G.Vector v a, G.Vector v Word64) => HashType a -> Conduit (v a) (StateT (HashState (v a)) m) (Bool, v a) rollsplit ht = do await >>= initial ht await >>= warm ht clamp :: (Monad m, G.Vector v a) => Int -> Int -> Conduit (Bool, v a) m (Bool, v a) clamp nmin nmax = loop 0 where loop n = await >>= maybe (return ()) (go n) go n (t, d) = do let t' = not (G.null d2) || (t && n' >= nmin) yield (t', d1) unless (G.null d2) $ leftover (t, d2) loop (if t' then 0 else n') where (d1, d2) = G.splitAt (nmax - n) d n' = n + G.length d1 recombine :: (Monad m, G.Vector v a) => Conduit (Bool, v a) m (v a) recombine = go G.empty where go x = do n <- await case n of Nothing -> yield x Just (False, y) -> go (x G.++ y) Just (True, y) -> yield (x G.++ y) >> go G.empty simpleRollsplit :: (G.Vector v a, G.Vector v Word64) => HashType a -> [v a] -> [v a] simpleRollsplit ht xs = runIdentity (yieldMany xs $$ evalStateC initialHashState (rollsplit ht =$= recombine) =$= sinkList) simpleRollsplit' :: (G.Vector v a, G.Vector v Word64) => HashType a -> [v a] -> [(Bool, v a)] simpleRollsplit' ht xs = runIdentity (yieldMany xs $$ evalStateC initialHashState (rollsplit ht) =$= sinkList) byteHashShort :: HashType Word8 byteHashShort = HashType { hash = \x -> 31 * fromIntegral x, window = 16, mask = 0xf } prop_allInputIsOutput :: (QC.Arbitrary a, Show a, Eq a) => HashType a -> QC.Property prop_allInputIsOutput ht = QC.forAll (QC.listOf (fmap V.fromList QC.arbitrary)) $ \xs -> V.concat (simpleRollsplit ht xs) == V.concat xs prop_inputSplit :: (QC.Arbitrary a, Show a, Eq a) => HashType a -> QC.Property prop_inputSplit ht = QC.forAll (QC.listOf (fmap V.fromList QC.arbitrary)) $ \xs -> simpleRollsplit ht xs == simpleRollsplit ht [V.concat xs] prop_prefix :: (QC.Arbitrary a, Show a, Eq a) => HashType a -> QC.Property prop_prefix ht = QC.forAll (fmap V.fromList QC.arbitrary) $ \xs -> QC.forAll (fmap V.fromList QC.arbitrary) $ \ys -> let a = simpleRollsplit ht [xs, ys]; b = simpleRollsplit ht [xs] in init' b `isPrefixOf` a prop_suffix :: (QC.Arbitrary a, Show a, Eq a) => HashType a -> QC.Property prop_suffix ht = QC.forAll (fmap V.fromList QC.arbitrary) $ \xs -> QC.forAll (fmap V.fromList QC.arbitrary) $ \ys -> let a = simpleRollsplit ht [xs, ys]; c = simpleRollsplit ht [ys] in tail' c `isSuffixOf` a prop_valid :: (QC.Arbitrary a, Show a, Eq a) => HashType a -> QC.Property prop_valid ht = prop_allInputIsOutput ht QC..&&. prop_inputSplit ht QC..&&. prop_prefix ht QC..&&. prop_suffix ht init' :: [a] -> [a] init' xs = take (length xs - 1) xs tail' :: [a] -> [a] tail' xs = drop 1 xs
aristidb/datastorage
src/RollingVector.hs
bsd-3-clause
6,254
0
16
1,765
2,762
1,396
1,366
130
3
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} module Y2017.Day14 (answer1, answer2) where import Control.Monad import GHC.Word import Numeric import Data.Bits import Data.Foldable import Data.Array ((!)) import qualified Data.Array as A import qualified Data.Vector as V import qualified Y2017.Day10 as H -- knot hash related stuff import qualified Data.Tree as T import qualified Data.Graph as G answer1, answer2 :: IO () answer1 = print $ countGridFree input answer2 = let grid = toGrid input (_, (bx, by)) = A.bounds grid graph = toGraph grid rootNodes = fmap T.rootLabel (G.components graph) -- assume bx == by rootCoords = fmap (\n -> let (y,x) = n `quotRem` (by+1) in (x,y)) rootNodes usedCoords = filter (\c -> isUsed $ grid ! c) rootCoords in print $ length usedCoords data Status = Free | Used deriving Show toGrid :: String -> A.Array (Int, Int) Status toGrid key = let hashes = fmap (\i -> H.knotHash (key ++ "-" ++ show i)) [0..127] bits = fmap (concatMap hexToBits . toBytes) hashes statuses = (fmap . fmap) (\x -> if x then Used else Free) bits withIdxs = fmap (zip [0..]) statuses assocList = [((x, y), s) | (y, row) <- zip [0..] withIdxs, (x, s) <- row] in A.array ((0,0), (127,127)) assocList toGraph :: A.Array (Int, Int) Status -> G.Graph toGraph arr = let (_, (mx, my)) = A.bounds arr in G.buildG (0, (mx+1) * (my+1) - 1) (toEdges arr) toEdges :: A.Array (Int, Int) Status -> [G.Edge] toEdges arr = concatMap (getEdges arr) (A.indices arr) getEdges :: A.Array (Int, Int) Status -> (Int, Int) -> [G.Edge] getEdges arr (x,y) = let bounds = A.bounds arr (_, (bx,by)) = bounds ns = filter (inBounds bounds) [(x-1, y), (x+1, y), (x, y-1), (x, y+1)] a = y * (bx+1) + x in case arr ! (x,y) of Used -> do (nx, ny) <- ns guard $ isUsed (arr ! (nx, ny)) let b = ny * (bx+1) + nx pure (a, b) Free -> [] inBounds :: (Ord a) => ((a, a), (a, a)) -> (a, a) -> Bool inBounds ((minx, miny), (maxx, maxy)) (x, y) = minx <= x && x <= maxx && miny <= y && y <= maxy isUsed Free = False isUsed Used = True countGridFree key = sum $ map (\s -> countFree $ H.knotHash (key ++ "-" ++ show s)) [0..127] countFree :: String -> Int countFree h = length $ filter id $ concatMap hexToBits $ toBytes h hexToBits :: Word8 -> [Bool] hexToBits w = map (/= 0) [w .&. 8, w .&. 4, w .&. 2, w .&. 1] toBytes :: String -> [Word8] toBytes "" = [] toBytes (x:xs) = case readHex (x:"") of [(n, "")] -> fromIntegral n : toBytes xs _ -> error "invalid hex" input = "jxqlasbh" test = "flqrgnkx"
geekingfrog/advent-of-code
src/Y2017/Day14.hs
bsd-3-clause
2,774
0
18
755
1,317
728
589
69
2
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} -- | Build project(s). module Stack.Build (build ,clean ,withLoadPackage ,mkBaseConfigOpts) where import Control.Monad import Control.Monad.Catch (MonadCatch, MonadMask) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import Data.Function import qualified Data.Map as Map import Data.Map.Strict (Map) import Data.Set (Set) import qualified Data.Set as Set import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Path.IO import Prelude hiding (FilePath, writeFile) import Stack.Build.ConstructPlan import Stack.Build.Execute import Stack.Build.Haddock import Stack.Build.Installed import Stack.Build.Source import Stack.Build.Target import Stack.Constants import Stack.Fetch as Fetch import Stack.GhcPkg import Stack.Package import Stack.Types import Stack.Types.Internal import System.FileLock (FileLock, unlockFile) type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasBuildConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env,HasEnvConfig env,HasTerminal env) -- | Build. -- -- If a buildLock is passed there is an important contract here. That lock must -- protect the snapshot, and it must be safe to unlock it if there are no further -- modifications to the snapshot to be performed by this build. build :: M env m => (Set (Path Abs File) -> IO ()) -- ^ callback after discovering all local files -> Maybe FileLock -> BuildOpts -> m () build setLocalFiles mbuildLk bopts = do menv <- getMinimalEnvOverride (_, mbp, locals, extraToBuild, sourceMap) <- loadSourceMap NeedTargets bopts -- Set local files, necessary for file watching stackYaml <- asks $ bcStackYaml . getBuildConfig liftIO $ setLocalFiles $ Set.insert stackYaml $ Set.unions $ map lpFiles locals (installedMap, globallyRegistered, locallyRegistered) <- getInstalled menv GetInstalledOpts { getInstalledProfiling = profiling , getInstalledHaddock = shouldHaddockDeps bopts } sourceMap baseConfigOpts <- mkBaseConfigOpts bopts plan <- withLoadPackage menv $ \loadPackage -> constructPlan mbp baseConfigOpts locals extraToBuild locallyRegistered loadPackage sourceMap installedMap -- If our work to do is all local, let someone else have a turn with the snapshot. -- They won't damage what's already in there. case (mbuildLk, allLocal plan) of -- NOTE: This policy is too conservative. In the future we should be able to -- schedule unlocking as an Action that happens after all non-local actions are -- complete. (Just lk,True) -> do $logDebug "All installs are local; releasing snapshot lock early." liftIO $ unlockFile lk _ -> return () when (boptsPreFetch bopts) $ preFetch plan if boptsDryrun bopts then printPlan plan else executePlan menv bopts baseConfigOpts locals globallyRegistered sourceMap installedMap plan where profiling = boptsLibProfile bopts || boptsExeProfile bopts -- | If all the tasks are local, they don't mutate anything outside of our local directory. allLocal :: Plan -> Bool allLocal = all (== Local) . map taskLocation . Map.elems . planTasks -- | Get the @BaseConfigOpts@ necessary for constructing configure options mkBaseConfigOpts :: (MonadIO m, MonadReader env m, HasEnvConfig env, MonadThrow m) => BuildOpts -> m BaseConfigOpts mkBaseConfigOpts bopts = do snapDBPath <- packageDatabaseDeps localDBPath <- packageDatabaseLocal snapInstallRoot <- installationRootDeps localInstallRoot <- installationRootLocal return BaseConfigOpts { bcoSnapDB = snapDBPath , bcoLocalDB = localDBPath , bcoSnapInstallRoot = snapInstallRoot , bcoLocalInstallRoot = localInstallRoot , bcoBuildOpts = bopts } -- | Provide a function for loading package information from the package index withLoadPackage :: ( MonadIO m , HasHttpManager env , MonadReader env m , MonadBaseControl IO m , MonadCatch m , MonadLogger m , HasEnvConfig env) => EnvOverride -> ((PackageName -> Version -> Map FlagName Bool -> IO Package) -> m a) -> m a withLoadPackage menv inner = do econfig <- asks getEnvConfig withCabalLoader menv $ \cabalLoader -> inner $ \name version flags -> do bs <- cabalLoader $ PackageIdentifier name version -- TODO automatically update index the first time this fails readPackageBS (depPackageConfig econfig flags) bs where -- | Package config to be used for dependencies depPackageConfig :: EnvConfig -> Map FlagName Bool -> PackageConfig depPackageConfig econfig flags = PackageConfig { packageConfigEnableTests = False , packageConfigEnableBenchmarks = False , packageConfigFlags = flags , packageConfigCompilerVersion = envConfigCompilerVersion econfig , packageConfigPlatform = configPlatform (getConfig econfig) } -- | Reset the build (remove Shake database and .gen files). clean :: (M env m) => m () clean = do econfig <- asks getEnvConfig forM_ (Map.keys (envConfigPackages econfig)) (distDirFromDir >=> removeTreeIfExists)
athanclark/stack
src/Stack/Build.hs
bsd-3-clause
6,322
0
15
1,793
1,171
634
537
129
3
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-} module Cataskell.Server.Main where import Control.Applicative import Control.Lens import Cataskell.Server.App (server, ServerState (..), startingState) import qualified Snap.Core as Snap import qualified Snap.Snaplet as Snap import qualified Snap.Util.FileServe as Snap import qualified Snap.Http.Server as Snap import qualified Control.Concurrent.STM as STM import qualified Network.SocketIO as SocketIO import qualified Network.EngineIO.Snap as EIOSnap import Data.ByteString (ByteString) import Data.Maybe (maybe) import Data.Monoid (mempty) import Control.Monad (liftM) import Control.Monad.IO.Class (liftIO) import System.Environment (lookupEnv) import Paths_cataskell (getDataDir) data App = App { _serverState :: ServerState } makeLenses ''App socketIoHandler :: IO (Snap.Handler App App ()) socketIoHandler = do state <- startingState SocketIO.initialize EIOSnap.snapAPI (server state) staticFiles :: Snap.Handler App App () staticFiles = liftIO getDataDir >>= Snap.serveDirectory routes :: IO [(ByteString, Snap.Handler App App ())] routes = do handler <- socketIoHandler return [ ("/socket.io", handler) , ("/", staticFiles) ] app :: Snap.SnapletInit App App app = Snap.makeSnaplet "app" "Cataskell websocket server" (Just getDataDir) $ do s <- liftIO startingState routes' <- liftIO routes Snap.addRoutes routes' return $ App s config :: IO (Snap.Config m a) config = do portNo <- lookupEnv "PORT" return $ Snap.setPort (maybe 8080 read portNo) mempty serverMain :: IO () serverMain = do config' <- liftIO config config'' <- Snap.commandLineConfig config' Snap.serveSnaplet config'' app
corajr/cataskell
src/Cataskell/Server/Main.hs
bsd-3-clause
1,737
0
10
267
516
283
233
48
1
module Control.Lens.TH.SharedFields ( generateField , generateFields ) where import Data.Char import Language.Haskell.TH -- | Generate classes for a field that will be shared between modules -- without using 'makeFields' (which would create an extra -- instance at minimum) generateField :: String -> Q [Dec] generateField = return . return . make -- | Generate classes for multiple fields. Use this if you want to -- define a bunch of fields. generateFields :: [String] -> Q [Dec] generateFields = return . map make make :: String -> Dec make name = ClassD [] (mkName $ "Has" ++ name) [PlainTV s, PlainTV a] [FunDep [s] [a]] [SigD (mkName $ functionName name) methodType] where s = mkName "s" a = mkName "a" f = mkName "f" vs = VarT s va = VarT a vf = VarT f methodType = ForallT [PlainTV f] [AppT (ConT ''Functor) vf] ((va `arrow` AppT vf va) `arrow` (vs `arrow` AppT vf vs)) arrow :: Type -> Type -> Type arrow x y = AppT (AppT ArrowT x) y functionName :: String -> String functionName (x:xs) = toLower x : xs functionName _ = error "invalid class name"
intolerable/shared-fields
src/Control/Lens/TH/SharedFields.hs
bsd-3-clause
1,161
0
12
294
374
201
173
-1
-1
module Main where import Network.Simple.TCP import Network.Socket (isWritable, isReadable) import Control.Concurrent import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy as BS (null, append) import Data.ByteString.Lazy (empty, fromStrict) import Mqtt.Broker (unsubscribe, serviceRequest, Reply, Subscription, Response(ClientMessages), Response(CloseConnection)) import Mqtt.Stream (nextMessage, mqttStream) import Data.IORef type Subscriptions = IORef [Subscription Socket] main :: IO () main = withSocketsDo $ do subsVar <- newIORef [] -- empty subscriptions list serve HostAny "1883" (handleConnection subsVar) handleConnection :: Subscriptions -> (Socket, SockAddr) -> IO () handleConnection subsVar (socket, _) = do handleConnectionImpl socket subsVar empty return () handleConnectionImpl :: Socket -> Subscriptions -> BS.ByteString -> IO () handleConnectionImpl socket subsVar bytes = do let (msg, bytes') = nextMessage bytes if BS.null msg then do received <- recv socket 1024 case received of Nothing -> return () Just strictBytes -> do let bytes'' = fromStrict strictBytes if BS.null bytes'' then handleConnectionImpl socket subsVar bytes' else handleConnectionImpl socket subsVar (bytes' `BS.append` bytes'') else do subs <- readIORef subsVar let response = serviceRequest socket msg subs handleResponse socket subsVar bytes' response handleResponse :: Socket -> Subscriptions -> BS.ByteString -> Response Socket -> IO () handleResponse socket subsVar bytes response = case response of CloseConnection -> return () ClientMessages (replies, subs') -> do writeIORef subsVar subs' handleReplies replies readable <- isReadable socket let closed = not readable if null replies || closed then return () else handleConnectionImpl socket subsVar bytes handleReply :: Reply Socket -> IO () handleReply (socket, packet) = do writable <- isWritable socket if writable then sendLazy socket packet else return () handleReplies :: [Reply Socket] -> IO () handleReplies replies = mapM_ handleReply replies
atilaneves/mqtt_hs
src/main.hs
bsd-3-clause
2,224
0
18
462
677
344
333
57
4
{-# LINE 1 "GHC.Conc.Windows.hs" #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples #-} {-# OPTIONS_GHC -Wno-missing-signatures #-} {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Conc.Windows -- Copyright : (c) The University of Glasgow, 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- Windows I/O manager -- ----------------------------------------------------------------------------- -- #not-home module GHC.Conc.Windows ( ensureIOManagerIsRunning -- * Waiting , threadDelay , registerDelay -- * Miscellaneous , asyncRead , asyncWrite , asyncDoProc , asyncReadBA , asyncWriteBA , ConsoleEvent(..) , win32ConsoleHandler , toWin32ConsoleEvent ) where import Data.Bits (shiftR) import GHC.Base import GHC.Conc.Sync import GHC.Enum (Enum) import GHC.IO (unsafePerformIO) import GHC.IORef import GHC.MVar import GHC.Num (Num(..)) import GHC.Ptr import GHC.Read (Read) import GHC.Real (div, fromIntegral) import GHC.Show (Show) import GHC.Word (Word32, Word64) import GHC.Windows -- ---------------------------------------------------------------------------- -- Thread waiting -- Note: threadWaitRead and threadWaitWrite aren't really functional -- on Win32, but left in there because lib code (still) uses them (the manner -- in which they're used doesn't cause problems on a Win32 platform though.) asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int) asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) = IO $ \s -> case asyncRead# fd isSock len buf s of (# s', len#, err# #) -> (# s', (I# len#, I# err#) #) asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int) asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) = IO $ \s -> case asyncWrite# fd isSock len buf s of (# s', len#, err# #) -> (# s', (I# len#, I# err#) #) asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int asyncDoProc (FunPtr proc) (Ptr param) = -- the 'length' value is ignored; simplifies implementation of -- the async*# primops to have them all return the same result. IO $ \s -> case asyncDoProc# proc param s of (# s', _len#, err# #) -> (# s', I# err# #) -- to aid the use of these primops by the IO Handle implementation, -- provide the following convenience funs: -- this better be a pinned byte array! asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int) asyncReadBA fd isSock len off bufB = asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off) asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int) asyncWriteBA fd isSock len off bufB = asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off) -- ---------------------------------------------------------------------------- -- Threaded RTS implementation of threadDelay -- | Suspends the current thread for a given number of microseconds -- (GHC only). -- -- There is no guarantee that the thread will be rescheduled promptly -- when the delay has expired, but the thread will never continue to -- run /earlier/ than specified. -- threadDelay :: Int -> IO () threadDelay time | threaded = waitForDelayEvent time | otherwise = IO $ \s -> case time of { I# time# -> case delay# time# s of { s' -> (# s', () #) }} -- | Set the value of returned TVar to True after a given number of -- microseconds. The caveats associated with threadDelay also apply. -- registerDelay :: Int -> IO (TVar Bool) registerDelay usecs | threaded = waitForDelayEventSTM usecs | otherwise = errorWithoutStackTrace "registerDelay: requires -threaded" foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool waitForDelayEvent :: Int -> IO () waitForDelayEvent usecs = do m <- newEmptyMVar target <- calculateTarget usecs atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ())) prodServiceThread takeMVar m -- Delays for use in STM waitForDelayEventSTM :: Int -> IO (TVar Bool) waitForDelayEventSTM usecs = do t <- atomically $ newTVar False target <- calculateTarget usecs atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ())) prodServiceThread return t calculateTarget :: Int -> IO USecs calculateTarget usecs = do now <- getMonotonicUSec return $ now + (fromIntegral usecs) data DelayReq = Delay {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ()) | DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool) {-# NOINLINE pendingDelays #-} pendingDelays :: IORef [DelayReq] pendingDelays = unsafePerformIO $ do m <- newIORef [] sharedCAF m getOrSetGHCConcWindowsPendingDelaysStore foreign import ccall unsafe "getOrSetGHCConcWindowsPendingDelaysStore" getOrSetGHCConcWindowsPendingDelaysStore :: Ptr a -> IO (Ptr a) {-# NOINLINE ioManagerThread #-} ioManagerThread :: MVar (Maybe ThreadId) ioManagerThread = unsafePerformIO $ do m <- newMVar Nothing sharedCAF m getOrSetGHCConcWindowsIOManagerThreadStore foreign import ccall unsafe "getOrSetGHCConcWindowsIOManagerThreadStore" getOrSetGHCConcWindowsIOManagerThreadStore :: Ptr a -> IO (Ptr a) ensureIOManagerIsRunning :: IO () ensureIOManagerIsRunning | threaded = startIOManagerThread | otherwise = return () startIOManagerThread :: IO () startIOManagerThread = do modifyMVar_ ioManagerThread $ \old -> do let create = do t <- forkIO ioManager; return (Just t) case old of Nothing -> create Just t -> do s <- threadStatus t case s of ThreadFinished -> create ThreadDied -> create _other -> return (Just t) insertDelay :: DelayReq -> [DelayReq] -> [DelayReq] insertDelay d [] = [d] insertDelay d1 ds@(d2 : rest) | delayTime d1 <= delayTime d2 = d1 : ds | otherwise = d2 : insertDelay d1 rest delayTime :: DelayReq -> USecs delayTime (Delay t _) = t delayTime (DelaySTM t _) = t type USecs = Word64 type NSecs = Word64 foreign import ccall unsafe "getMonotonicNSec" getMonotonicNSec :: IO NSecs getMonotonicUSec :: IO USecs getMonotonicUSec = fmap (`div` 1000) getMonotonicNSec {-# NOINLINE prodding #-} prodding :: IORef Bool prodding = unsafePerformIO $ do r <- newIORef False sharedCAF r getOrSetGHCConcWindowsProddingStore foreign import ccall unsafe "getOrSetGHCConcWindowsProddingStore" getOrSetGHCConcWindowsProddingStore :: Ptr a -> IO (Ptr a) prodServiceThread :: IO () prodServiceThread = do -- NB. use atomicModifyIORef here, otherwise there are race -- conditions in which prodding is left at True but the server is -- blocked in select(). was_set <- atomicModifyIORef prodding $ \b -> (True,b) when (not was_set) wakeupIOManager -- ---------------------------------------------------------------------------- -- Windows IO manager thread ioManager :: IO () ioManager = do wakeup <- c_getIOManagerEvent service_loop wakeup [] service_loop :: HANDLE -- read end of pipe -> [DelayReq] -- current delay requests -> IO () service_loop wakeup old_delays = do -- pick up new delay requests new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a)) let delays = foldr insertDelay old_delays new_delays now <- getMonotonicUSec (delays', timeout) <- getDelay now delays r <- c_WaitForSingleObject wakeup timeout case r of 0xffffffff -> do throwGetLastError "service_loop" 0 -> do r2 <- c_readIOManagerEvent exit <- case r2 of _ | r2 == io_MANAGER_WAKEUP -> return False _ | r2 == io_MANAGER_DIE -> return True 0 -> return False -- spurious wakeup _ -> do start_console_handler (r2 `shiftR` 1); return False when (not exit) $ service_cont wakeup delays' _other -> service_cont wakeup delays' -- probably timeout service_cont :: HANDLE -> [DelayReq] -> IO () service_cont wakeup delays = do r <- atomicModifyIORef prodding (\_ -> (False,False)) r `seq` return () -- avoid space leak service_loop wakeup delays -- must agree with rts/win32/ThrIOManager.c io_MANAGER_WAKEUP, io_MANAGER_DIE :: Word32 io_MANAGER_WAKEUP = 0xffffffff io_MANAGER_DIE = 0xfffffffe data ConsoleEvent = ControlC | Break | Close -- these are sent to Services only. | Logoff | Shutdown deriving (Eq, Ord, Enum, Show, Read) start_console_handler :: Word32 -> IO () start_console_handler r = case toWin32ConsoleEvent r of Just x -> withMVar win32ConsoleHandler $ \handler -> do _ <- forkIO (handler x) return () Nothing -> return () toWin32ConsoleEvent :: (Eq a, Num a) => a -> Maybe ConsoleEvent toWin32ConsoleEvent ev = case ev of 0 {- CTRL_C_EVENT-} -> Just ControlC 1 {- CTRL_BREAK_EVENT-} -> Just Break 2 {- CTRL_CLOSE_EVENT-} -> Just Close 5 {- CTRL_LOGOFF_EVENT-} -> Just Logoff 6 {- CTRL_SHUTDOWN_EVENT-} -> Just Shutdown _ -> Nothing win32ConsoleHandler :: MVar (ConsoleEvent -> IO ()) win32ConsoleHandler = unsafePerformIO (newMVar (errorWithoutStackTrace "win32ConsoleHandler")) wakeupIOManager :: IO () wakeupIOManager = c_sendIOManagerEvent io_MANAGER_WAKEUP -- Walk the queue of pending delays, waking up any that have passed -- and return the smallest delay to wait for. The queue of pending -- delays is kept ordered. getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD) getDelay _ [] = return ([], iNFINITE) getDelay now all@(d : rest) = case d of Delay time m | now >= time -> do putMVar m () getDelay now rest DelaySTM time t | now >= time -> do atomically $ writeTVar t True getDelay now rest _otherwise -> -- delay is in millisecs for WaitForSingleObject let micro_seconds = delayTime d - now milli_seconds = (micro_seconds + 999) `div` 1000 in return (all, fromIntegral milli_seconds) foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c) c_getIOManagerEvent :: IO HANDLE foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c) c_readIOManagerEvent :: IO Word32 foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c) c_sendIOManagerEvent :: Word32 -> IO () foreign import ccall "WaitForSingleObject" c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
phischu/fragnix
builtins/base/GHC.Conc.Windows.hs
bsd-3-clause
10,820
0
21
2,385
2,737
1,410
1,327
217
6
{-# LANGUAGE MultiParamTypeClasses #-} module Beetle.Datasets.Streaming where import qualified Streaming.Prelude as S import Streaming.Prelude (Stream, Of) import qualified Data.ByteString.Streaming as SBS import Streaming.Cassava import Numeric.Datasets import Control.Monad.IO.Class import Data.Maybe import System.IO.Error (userError) import Control.Monad.Error.Class (throwError) unCsvException :: CsvParseException -> String unCsvException (CsvParseException s) = s streamDataset :: Dataset a -> Stream (Of (Either String a)) IO () streamDataset ds = do dir <- liftIO $ tempDirForDataset ds lbs <- liftIO $ fmap (fromMaybe id $ preProcess ds) $ getFileFromSource dir $ source ds readStreamDataset (readAs ds) $ SBS.fromLazy lbs readStreamDataset :: ReadAs a -> SBS.ByteString IO () -> Stream (Of (Either String a)) IO () readStreamDataset (CSVRecord hhdr opts) sbs = fmap (const ()) $ S.map (either (Left . unCsvException) Right) $ decodeWithErrors opts hhdr sbs readStreamDataset _ _ = throwError $ userError "readStreamDataset: only CSVRecord implemented " foldDataset :: Dataset a -> b -> (b -> Either String a -> IO b) -> IO b foldDataset ds x0 accf = do let s = streamDataset ds S.foldM_ accf (return x0) (return) s mapDataset_ :: Dataset a -> (Either String a -> IO ()) -> IO () mapDataset_ ds f = foldDataset ds () (\() x -> f x)
filopodia/open
beetle/src/Beetle/Datasets/Streaming.hs
mit
1,361
0
14
218
515
261
254
28
1
-- This module contains settings used by multiple benchmarking functions. -- See my blog for more discussion on this. module BenchParam where sigSize :: Int sigSize = 8192 shiftSize :: Int shiftSize = 1
oqc/hqt
QuranBench/BenchParam.hs
gpl-3.0
205
0
4
36
26
17
9
5
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.EC2.DescribeCustomerGateways -- 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) -- -- Describes one or more of your VPN customer gateways. -- -- For more information about VPN customer gateways, see -- <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html Adding a Hardware Virtual Private Gateway to Your VPC> -- in the /Amazon Virtual Private Cloud User Guide/. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeCustomerGateways.html AWS API Reference> for DescribeCustomerGateways. module Network.AWS.EC2.DescribeCustomerGateways ( -- * Creating a Request describeCustomerGateways , DescribeCustomerGateways -- * Request Lenses , dcgCustomerGatewayIds , dcgFilters , dcgDryRun -- * Destructuring the Response , describeCustomerGatewaysResponse , DescribeCustomerGatewaysResponse -- * Response Lenses , dcgrsCustomerGateways , dcgrsResponseStatus ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeCustomerGateways' smart constructor. data DescribeCustomerGateways = DescribeCustomerGateways' { _dcgCustomerGatewayIds :: !(Maybe [Text]) , _dcgFilters :: !(Maybe [Filter]) , _dcgDryRun :: !(Maybe Bool) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeCustomerGateways' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcgCustomerGatewayIds' -- -- * 'dcgFilters' -- -- * 'dcgDryRun' describeCustomerGateways :: DescribeCustomerGateways describeCustomerGateways = DescribeCustomerGateways' { _dcgCustomerGatewayIds = Nothing , _dcgFilters = Nothing , _dcgDryRun = Nothing } -- | One or more customer gateway IDs. -- -- Default: Describes all your customer gateways. dcgCustomerGatewayIds :: Lens' DescribeCustomerGateways [Text] dcgCustomerGatewayIds = lens _dcgCustomerGatewayIds (\ s a -> s{_dcgCustomerGatewayIds = a}) . _Default . _Coerce; -- | One or more filters. -- -- - 'bgp-asn' - The customer gateway\'s Border Gateway Protocol (BGP) -- Autonomous System Number (ASN). -- -- - 'customer-gateway-id' - The ID of the customer gateway. -- -- - 'ip-address' - The IP address of the customer gateway\'s -- Internet-routable external interface. -- -- - 'state' - The state of the customer gateway ('pending' | 'available' -- | 'deleting' | 'deleted'). -- -- - 'type' - The type of customer gateway. Currently, the only supported -- type is 'ipsec.1'. -- -- - 'tag':/key/=/value/ - The key\/value combination of a tag assigned -- to the resource. -- -- - 'tag-key' - The key of a tag assigned to the resource. This filter -- is independent of the 'tag-value' filter. For example, if you use -- both the filter \"tag-key=Purpose\" and the filter \"tag-value=X\", -- you get any resources assigned both the tag key Purpose (regardless -- of what the tag\'s value is), and the tag value X (regardless of -- what the tag\'s key is). If you want to list only resources where -- Purpose is X, see the 'tag':/key/=/value/ filter. -- -- - 'tag-value' - The value of a tag assigned to the resource. This -- filter is independent of the 'tag-key' filter. -- dcgFilters :: Lens' DescribeCustomerGateways [Filter] dcgFilters = lens _dcgFilters (\ s a -> s{_dcgFilters = a}) . _Default . _Coerce; -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have -- the required permissions, the error response is 'DryRunOperation'. -- Otherwise, it is 'UnauthorizedOperation'. dcgDryRun :: Lens' DescribeCustomerGateways (Maybe Bool) dcgDryRun = lens _dcgDryRun (\ s a -> s{_dcgDryRun = a}); instance AWSRequest DescribeCustomerGateways where type Rs DescribeCustomerGateways = DescribeCustomerGatewaysResponse request = postQuery eC2 response = receiveXML (\ s h x -> DescribeCustomerGatewaysResponse' <$> (x .@? "customerGatewaySet" .!@ mempty >>= may (parseXMLList "item")) <*> (pure (fromEnum s))) instance ToHeaders DescribeCustomerGateways where toHeaders = const mempty instance ToPath DescribeCustomerGateways where toPath = const "/" instance ToQuery DescribeCustomerGateways where toQuery DescribeCustomerGateways'{..} = mconcat ["Action" =: ("DescribeCustomerGateways" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), toQuery (toQueryList "CustomerGatewayId" <$> _dcgCustomerGatewayIds), toQuery (toQueryList "Filter" <$> _dcgFilters), "DryRun" =: _dcgDryRun] -- | /See:/ 'describeCustomerGatewaysResponse' smart constructor. data DescribeCustomerGatewaysResponse = DescribeCustomerGatewaysResponse' { _dcgrsCustomerGateways :: !(Maybe [CustomerGateway]) , _dcgrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeCustomerGatewaysResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcgrsCustomerGateways' -- -- * 'dcgrsResponseStatus' describeCustomerGatewaysResponse :: Int -- ^ 'dcgrsResponseStatus' -> DescribeCustomerGatewaysResponse describeCustomerGatewaysResponse pResponseStatus_ = DescribeCustomerGatewaysResponse' { _dcgrsCustomerGateways = Nothing , _dcgrsResponseStatus = pResponseStatus_ } -- | Information about one or more customer gateways. dcgrsCustomerGateways :: Lens' DescribeCustomerGatewaysResponse [CustomerGateway] dcgrsCustomerGateways = lens _dcgrsCustomerGateways (\ s a -> s{_dcgrsCustomerGateways = a}) . _Default . _Coerce; -- | The response status code. dcgrsResponseStatus :: Lens' DescribeCustomerGatewaysResponse Int dcgrsResponseStatus = lens _dcgrsResponseStatus (\ s a -> s{_dcgrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DescribeCustomerGateways.hs
mpl-2.0
6,976
0
15
1,436
802
488
314
93
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.CloudHSM.ListHsms -- 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. -- | Retrieves the identifiers of all of the HSMs provisioned for the current -- customer. -- -- This operation supports pagination with the use of the /NextToken/ member. If -- more results are available, the /NextToken/ member of the response contains a -- token that you pass in the next call to 'ListHsms' to retrieve the next set of -- items. -- -- <http://docs.aws.amazon.com/cloudhsm/latest/dg/API_ListHsms.html> module Network.AWS.CloudHSM.ListHsms ( -- * Request ListHsms -- ** Request constructor , listHsms -- ** Request lenses , lh1NextToken -- * Response , ListHsmsResponse -- ** Response constructor , listHsmsResponse -- ** Response lenses , lhrHsmList , lhrNextToken ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CloudHSM.Types import qualified GHC.Exts newtype ListHsms = ListHsms { _lh1NextToken :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'ListHsms' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lh1NextToken' @::@ 'Maybe' 'Text' -- listHsms :: ListHsms listHsms = ListHsms { _lh1NextToken = Nothing } -- | The /NextToken/ value from a previous call to 'ListHsms'. Pass null if this is -- the first call. lh1NextToken :: Lens' ListHsms (Maybe Text) lh1NextToken = lens _lh1NextToken (\s a -> s { _lh1NextToken = a }) data ListHsmsResponse = ListHsmsResponse { _lhrHsmList :: List "HsmList" Text , _lhrNextToken :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'ListHsmsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lhrHsmList' @::@ ['Text'] -- -- * 'lhrNextToken' @::@ 'Maybe' 'Text' -- listHsmsResponse :: ListHsmsResponse listHsmsResponse = ListHsmsResponse { _lhrHsmList = mempty , _lhrNextToken = Nothing } -- | The list of ARNs that identify the HSMs. lhrHsmList :: Lens' ListHsmsResponse [Text] lhrHsmList = lens _lhrHsmList (\s a -> s { _lhrHsmList = a }) . _List -- | If not null, more results are available. Pass this value to 'ListHsms' to -- retrieve the next set of items. lhrNextToken :: Lens' ListHsmsResponse (Maybe Text) lhrNextToken = lens _lhrNextToken (\s a -> s { _lhrNextToken = a }) instance ToPath ListHsms where toPath = const "/" instance ToQuery ListHsms where toQuery = const mempty instance ToHeaders ListHsms instance ToJSON ListHsms where toJSON ListHsms{..} = object [ "NextToken" .= _lh1NextToken ] instance AWSRequest ListHsms where type Sv ListHsms = CloudHSM type Rs ListHsms = ListHsmsResponse request = post "ListHsms" response = jsonResponse instance FromJSON ListHsmsResponse where parseJSON = withObject "ListHsmsResponse" $ \o -> ListHsmsResponse <$> o .:? "HsmList" .!= mempty <*> o .:? "NextToken"
kim/amazonka
amazonka-cloudhsm/gen/Network/AWS/CloudHSM/ListHsms.hs
mpl-2.0
3,955
0
12
886
540
327
213
61
1
{- - Copyright (c) 2017 The Agile Monkeys S.L. <[email protected]> - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -} module HaskellDo ( run ) where import qualified Ulmus import HaskellDo.View import HaskellDo.State import qualified HaskellDo.CodeMirror.View as CodeMirror import qualified HaskellDo.Style.View as Style initializeHeaders :: IO () initializeHeaders = do CodeMirror.initialize Style.initialize -- | Executes Haskell.do in designated 'port' run :: Integer -> IO () run appPort = Ulmus.initializeApp Ulmus.AppConfig { Ulmus._update = update , Ulmus._view = view , Ulmus._updateDisplays = updateDisplays , Ulmus._initialState = initialAppState , Ulmus._port = appPort , Ulmus._setup = initializeHeaders }
J2RGEZ/haskell-do
src/common/HaskellDo.hs
apache-2.0
1,298
0
7
263
147
88
59
19
1
module Solution where import Primes import Data.List isPrimitiveRootModulo :: Integer -> Integer -> Bool isPrimitiveRootModulo base p = [1..p-1] == sort modules where modules = map (\power -> (base^power) `mod` p) [0..p-2] findLongestCyclicNumberBefore :: Int -> Integer findLongestCyclicNumberBefore maxNum = last $ filter (10 `isPrimitiveRootModulo`) allMatchingPrimes where allMatchingPrimes = map fromIntegral $ takeWhile (< maxNum) primes {-main = print $ findLongestCyclicNumberBefore 1000-}
nothiphop/project-euler
026/Solution.hs
apache-2.0
514
0
12
78
149
83
66
9
1
{-# LANGUAGE ScopedTypeVariables #-} module AnnRun01 where import GHC import MonadUtils ( liftIO ) import DynFlags ( defaultFatalMessager, defaultFlushOut ) import Annotations ( AnnTarget(..), CoreAnnTarget ) import GHC.Serialized ( deserializeWithData ) import Panic import Config import Annrun01_Help import qualified Language.Haskell.TH as TH import Data.List import Data.Function main :: IO () main = defaultErrorHandler defaultFatalMessager defaultFlushOut $ runGhc (Just cTop) $ do liftIO $ putStrLn "Initializing Package Database" dflags <- getSessionDynFlags let dflags' = dflags setSessionDynFlags dflags' let mod_nm = mkModuleName "Annrun01_Help" liftIO $ putStrLn "Setting Target" setTargets [Target (TargetModule mod_nm) True Nothing] liftIO $ putStrLn "Loading Targets" load LoadAllTargets liftIO $ putStrLn "Finding Module" mod <- findModule mod_nm Nothing liftIO $ putStrLn "Getting Module Info" Just mod_info <- getModuleInfo mod liftIO $ putStrLn "Showing Details For Module" showTargetAnns (ModuleTarget mod) liftIO $ putStrLn "Showing Details For Exports" let exports = sortBy (compare `on` getOccName) $ modInfoExports mod_info mapM_ (showTargetAnns . NamedTarget) exports showTargetAnns :: CoreAnnTarget -> Ghc () showTargetAnns target = do (int_anns :: [Int]) <- findGlobalAnns deserializeWithData target (mb_bool_anns :: [Maybe Bool]) <- findGlobalAnns deserializeWithData target (string_anns :: [String]) <- findGlobalAnns deserializeWithData target (name_anns :: [TH.Name]) <- findGlobalAnns deserializeWithData target liftIO $ print (int_anns, mb_bool_anns, string_anns, name_anns)
rahulmutt/ghcvm
tests/suite/annotations/run/annrun01/AnnRun01.hs
bsd-3-clause
1,742
0
14
332
466
230
236
41
1
-- | -- Module : Foundation.Class.Bifunctor -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : portable -- -- Formally, the class 'Bifunctor' represents a bifunctor -- from @Hask@ -> @Hask@. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a 'Bifunctor' by either defining 'bimap' or by -- defining both 'first' and 'second'. -- {-# LANGUAGE CPP #-} module Foundation.Class.Bifunctor ( module Basement.Compat.Bifunctor ) where import Basement.Compat.Bifunctor
vincenthz/hs-foundation
foundation/Foundation/Class/Bifunctor.hs
bsd-3-clause
614
0
5
105
39
32
7
4
0
{-# OPTIONS_GHC -Wall #-} module Elm.Compiler ( version , parseDependencies , compile, Context(..), Result(..) , Dealiaser, dummyDealiaser , Error, errorToString, errorToJson, printError , Warning, warningToString, warningToJson, printWarning ) where import qualified Data.Aeson as Json import qualified Data.Map as Map import qualified AST.Module as Module import qualified AST.Module.Name as ModuleName import qualified Compile import qualified Docs.Check as Docs import qualified Elm.Compiler.Version import qualified Elm.Compiler.Module as PublicModule import qualified Elm.Docs as Docs import qualified Elm.Package as Package import qualified Generate.JavaScript as JS import qualified Parse.Module as Parse import qualified Parse.Parse as Parse import qualified Reporting.Annotation as A import qualified Reporting.Error as Error import qualified Reporting.PrettyPrint as P import qualified Reporting.Result as Result import qualified Reporting.Warning as Warning -- VERSION version :: Package.Version version = Elm.Compiler.Version.version -- DEPENDENCIES parseDependencies :: String -> Either [Error] (PublicModule.Name, [PublicModule.Name]) parseDependencies sourceCode = let (Result.Result _warnings rawResult) = Parse.parse sourceCode Parse.header in case rawResult of Result.Err msgs -> Left $ map (Error . A.map Error.Syntax) msgs Result.Ok (Module.Header name _docs _exports imports) -> Right ( PublicModule.Name name , map (PublicModule.Name . fst . A.drop) imports ) -- COMPILATION {-| Compiles Elm source code to JavaScript. -} compile :: Context -> String -> PublicModule.Interfaces -> (Dealiaser, [Warning], Either [Error] Result) compile context source interfaces = let (Context packageName isRoot isExposed dependencies) = context (Result.Result (dealiaser, warnings) rawResult) = do modul <- Compile.compile packageName isRoot dependencies interfaces source docs <- docsGen isExposed modul let interface = Module.toInterface packageName modul let javascript = JS.generate modul return (Result docs interface javascript) in ( maybe dummyDealiaser Dealiaser dealiaser , map Warning warnings , Result.destruct (Left . map Error) Right rawResult ) data Context = Context { _packageName :: Package.Name , _isRoot :: Bool , _isExposed :: Bool , _dependencies :: [PublicModule.CanonicalName] } data Result = Result { _docs :: Maybe Docs.Documentation , _interface :: PublicModule.Interface , _js :: String } docsGen :: Bool -> Module.Optimized -> Result.Result w Error.Error (Maybe Docs.Documentation) docsGen isExposed modul = if not isExposed then Result.ok Nothing else let getChecked = Docs.check (Module.exports modul) (Module.docs modul) name = PublicModule.Name (ModuleName._module (Module.name modul)) toDocs checked = Docs.fromCheckedDocs name checked in (Just . toDocs) `fmap` Result.mapError Error.Docs getChecked -- DEALIASER newtype Dealiaser = Dealiaser P.Dealiaser dummyDealiaser :: Dealiaser dummyDealiaser = Dealiaser Map.empty -- ERRORS newtype Error = Error (A.Located Error.Error) errorToString :: Dealiaser -> String -> String -> Error -> String errorToString (Dealiaser dealiaser) location source (Error err) = Error.toString dealiaser location source err printError :: Dealiaser -> String -> String -> Error -> IO () printError (Dealiaser dealiaser) location source (Error err) = Error.print dealiaser location source err errorToJson :: Dealiaser -> String -> Error -> Json.Value errorToJson (Dealiaser dealiaser) location (Error err) = Error.toJson dealiaser location err -- WARNINGS newtype Warning = Warning (A.Located Warning.Warning) warningToString :: Dealiaser -> String -> String -> Warning -> String warningToString (Dealiaser dealiaser) location source (Warning err) = Warning.toString dealiaser location source err printWarning :: Dealiaser -> String -> String -> Warning -> IO () printWarning (Dealiaser dealiaser) location source (Warning err) = Warning.print dealiaser location source err warningToJson :: Dealiaser -> String -> Warning -> Json.Value warningToJson (Dealiaser dealiaser) location (Warning err) = Warning.toJson dealiaser location err
Axure/elm-compiler
src/Elm/Compiler.hs
bsd-3-clause
4,524
0
16
948
1,245
681
564
112
2
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[RnPat]{Renaming of patterns} Basically dependency analysis. Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In general, all of these functions return a renamed thing, and a set of free variables. -} {-# LANGUAGE CPP, RankNTypes, ScopedTypeVariables #-} module RnPat (-- main entry points rnPat, rnPats, rnBindPat, rnPatAndThen, NameMaker, applyNameMaker, -- a utility for making names: localRecNameMaker, topRecNameMaker, -- sometimes we want to make local names, -- sometimes we want to make top (qualified) names. isTopRecNameMaker, rnHsRecFields, HsRecFieldContext(..), rnHsRecUpdFields, -- CpsRn monad CpsRn, liftCps, -- Literals rnLit, rnOverLit, -- Pattern Error messages that are also used elsewhere checkTupSize, patSigErr ) where -- ENH: thin imports to only what is necessary for patterns import {-# SOURCE #-} RnExpr ( rnLExpr ) import {-# SOURCE #-} RnSplice ( rnSplicePat ) #include "HsVersions.h" import HsSyn import TcRnMonad import TcHsSyn ( hsOverLitName ) import RnEnv import RnTypes import PrelNames import TyCon ( tyConName ) import ConLike import Type ( TyThing(..) ) import Name import NameSet import RdrName import BasicTypes import Util import ListSetOps ( removeDups ) import Outputable import SrcLoc import Literal ( inCharRange ) import TysWiredIn ( nilDataCon ) import DataCon import qualified GHC.LanguageExtensions as LangExt import Control.Monad ( when, liftM, ap ) import Data.Ratio {- ********************************************************* * * The CpsRn Monad * * ********************************************************* Note [CpsRn monad] ~~~~~~~~~~~~~~~~~~ The CpsRn monad uses continuation-passing style to support this style of programming: do { ... ; ns <- bindNames rs ; ...blah... } where rs::[RdrName], ns::[Name] The idea is that '...blah...' a) sees the bindings of ns b) returns the free variables it mentions so that bindNames can report unused ones In particular, mapM rnPatAndThen [p1, p2, p3] has a *left-to-right* scoping: it makes the binders in p1 scope over p2,p3. -} newtype CpsRn b = CpsRn { unCpsRn :: forall r. (b -> RnM (r, FreeVars)) -> RnM (r, FreeVars) } -- See Note [CpsRn monad] instance Functor CpsRn where fmap = liftM instance Applicative CpsRn where pure x = CpsRn (\k -> k x) (<*>) = ap instance Monad CpsRn where (CpsRn m) >>= mk = CpsRn (\k -> m (\v -> unCpsRn (mk v) k)) runCps :: CpsRn a -> RnM (a, FreeVars) runCps (CpsRn m) = m (\r -> return (r, emptyFVs)) liftCps :: RnM a -> CpsRn a liftCps rn_thing = CpsRn (\k -> rn_thing >>= k) liftCpsFV :: RnM (a, FreeVars) -> CpsRn a liftCpsFV rn_thing = CpsRn (\k -> do { (v,fvs1) <- rn_thing ; (r,fvs2) <- k v ; return (r, fvs1 `plusFV` fvs2) }) wrapSrcSpanCps :: (a -> CpsRn b) -> Located a -> CpsRn (Located b) -- Set the location, and also wrap it around the value returned wrapSrcSpanCps fn (L loc a) = CpsRn (\k -> setSrcSpan loc $ unCpsRn (fn a) $ \v -> k (L loc v)) lookupConCps :: Located RdrName -> CpsRn (Located Name) lookupConCps con_rdr = CpsRn (\k -> do { con_name <- lookupLocatedOccRn con_rdr ; (r, fvs) <- k con_name ; return (r, addOneFV fvs (unLoc con_name)) }) -- We add the constructor name to the free vars -- See Note [Patterns are uses] {- Note [Patterns are uses] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider module Foo( f, g ) where data T = T1 | T2 f T1 = True f T2 = False g _ = T1 Arguably we should report T2 as unused, even though it appears in a pattern, because it never occurs in a constructed position. See Trac #7336. However, implementing this in the face of pattern synonyms would be less straightforward, since given two pattern synonyms pattern P1 <- P2 pattern P2 <- () we need to observe the dependency between P1 and P2 so that type checking can be done in the correct order (just like for value bindings). Dependencies between bindings is analyzed in the renamer, where we don't know yet whether P2 is a constructor or a pattern synonym. So for now, we do report conid occurrences in patterns as uses. ********************************************************* * * Name makers * * ********************************************************* Externally abstract type of name makers, which is how you go from a RdrName to a Name -} data NameMaker = LamMk -- Lambdas Bool -- True <=> report unused bindings -- (even if True, the warning only comes out -- if -Wunused-matches is on) | LetMk -- Let bindings, incl top level -- Do *not* check for unused bindings TopLevelFlag MiniFixityEnv topRecNameMaker :: MiniFixityEnv -> NameMaker topRecNameMaker fix_env = LetMk TopLevel fix_env isTopRecNameMaker :: NameMaker -> Bool isTopRecNameMaker (LetMk TopLevel _) = True isTopRecNameMaker _ = False localRecNameMaker :: MiniFixityEnv -> NameMaker localRecNameMaker fix_env = LetMk NotTopLevel fix_env matchNameMaker :: HsMatchContext a -> NameMaker matchNameMaker ctxt = LamMk report_unused where -- Do not report unused names in interactive contexts -- i.e. when you type 'x <- e' at the GHCi prompt report_unused = case ctxt of StmtCtxt GhciStmtCtxt -> False -- also, don't warn in pattern quotes, as there -- is no RHS where the variables can be used! ThPatQuote -> False _ -> True rnHsSigCps :: LHsSigWcType RdrName -> CpsRn (LHsSigWcType Name) rnHsSigCps sig = CpsRn (rnHsSigWcTypeScoped PatCtx sig) newPatLName :: NameMaker -> Located RdrName -> CpsRn (Located Name) newPatLName name_maker rdr_name@(L loc _) = do { name <- newPatName name_maker rdr_name ; return (L loc name) } newPatName :: NameMaker -> Located RdrName -> CpsRn Name newPatName (LamMk report_unused) rdr_name = CpsRn (\ thing_inside -> do { name <- newLocalBndrRn rdr_name ; (res, fvs) <- bindLocalNames [name] (thing_inside name) ; when report_unused $ warnUnusedMatches [name] fvs ; return (res, name `delFV` fvs) }) newPatName (LetMk is_top fix_env) rdr_name = CpsRn (\ thing_inside -> do { name <- case is_top of NotTopLevel -> newLocalBndrRn rdr_name TopLevel -> newTopSrcBinder rdr_name ; bindLocalNames [name] $ -- Do *not* use bindLocalNameFV here -- See Note [View pattern usage] addLocalFixities fix_env [name] $ thing_inside name }) -- Note: the bindLocalNames is somewhat suspicious -- because it binds a top-level name as a local name. -- however, this binding seems to work, and it only exists for -- the duration of the patterns and the continuation; -- then the top-level name is added to the global env -- before going on to the RHSes (see RnSource.hs). {- Note [View pattern usage] ~~~~~~~~~~~~~~~~~~~~~~~~~ Consider let (r, (r -> x)) = x in ... Here the pattern binds 'r', and then uses it *only* in the view pattern. We want to "see" this use, and in let-bindings we collect all uses and report unused variables at the binding level. So we must use bindLocalNames here, *not* bindLocalNameFV. Trac #3943. ********************************************************* * * External entry points * * ********************************************************* There are various entry points to renaming patterns, depending on (1) whether the names created should be top-level names or local names (2) whether the scope of the names is entirely given in a continuation (e.g., in a case or lambda, but not in a let or at the top-level, because of the way mutually recursive bindings are handled) (3) whether the a type signature in the pattern can bind lexically-scoped type variables (for unpacking existential type vars in data constructors) (4) whether we do duplicate and unused variable checking (5) whether there are fixity declarations associated with the names bound by the patterns that need to be brought into scope with them. Rather than burdening the clients of this module with all of these choices, we export the three points in this design space that we actually need: -} -- ----------- Entry point 1: rnPats ------------------- -- Binds local names; the scope of the bindings is entirely in the thing_inside -- * allows type sigs to bind type vars -- * local namemaker -- * unused and duplicate checking -- * no fixities rnPats :: HsMatchContext Name -- for error messages -> [LPat RdrName] -> ([LPat Name] -> RnM (a, FreeVars)) -> RnM (a, FreeVars) rnPats ctxt pats thing_inside = do { envs_before <- getRdrEnvs -- (1) rename the patterns, bringing into scope all of the term variables -- (2) then do the thing inside. ; unCpsRn (rnLPatsAndThen (matchNameMaker ctxt) pats) $ \ pats' -> do { -- Check for duplicated and shadowed names -- Must do this *after* renaming the patterns -- See Note [Collect binders only after renaming] in HsUtils -- Because we don't bind the vars all at once, we can't -- check incrementally for duplicates; -- Nor can we check incrementally for shadowing, else we'll -- complain *twice* about duplicates e.g. f (x,x) = ... ; addErrCtxt doc_pat $ checkDupAndShadowedNames envs_before $ collectPatsBinders pats' ; thing_inside pats' } } where doc_pat = text "In" <+> pprMatchContext ctxt rnPat :: HsMatchContext Name -- for error messages -> LPat RdrName -> (LPat Name -> RnM (a, FreeVars)) -> RnM (a, FreeVars) -- Variables bound by pattern do not -- appear in the result FreeVars rnPat ctxt pat thing_inside = rnPats ctxt [pat] (\pats' -> let [pat'] = pats' in thing_inside pat') applyNameMaker :: NameMaker -> Located RdrName -> RnM (Located Name) applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newPatLName mk rdr) ; return n } -- ----------- Entry point 2: rnBindPat ------------------- -- Binds local names; in a recursive scope that involves other bound vars -- e.g let { (x, Just y) = e1; ... } in ... -- * does NOT allows type sig to bind type vars -- * local namemaker -- * no unused and duplicate checking -- * fixities might be coming in rnBindPat :: NameMaker -> LPat RdrName -> RnM (LPat Name, FreeVars) -- Returned FreeVars are the free variables of the pattern, -- of course excluding variables bound by this pattern rnBindPat name_maker pat = runCps (rnLPatAndThen name_maker pat) {- ********************************************************* * * The main event * * ********************************************************* -} -- ----------- Entry point 3: rnLPatAndThen ------------------- -- General version: parametrized by how you make new names rnLPatsAndThen :: NameMaker -> [LPat RdrName] -> CpsRn [LPat Name] rnLPatsAndThen mk = mapM (rnLPatAndThen mk) -- Despite the map, the monad ensures that each pattern binds -- variables that may be mentioned in subsequent patterns in the list -------------------- -- The workhorse rnLPatAndThen :: NameMaker -> LPat RdrName -> CpsRn (LPat Name) rnLPatAndThen nm lpat = wrapSrcSpanCps (rnPatAndThen nm) lpat rnPatAndThen :: NameMaker -> Pat RdrName -> CpsRn (Pat Name) rnPatAndThen _ (WildPat _) = return (WildPat placeHolderType) rnPatAndThen mk (ParPat pat) = do { pat' <- rnLPatAndThen mk pat; return (ParPat pat') } rnPatAndThen mk (LazyPat pat) = do { pat' <- rnLPatAndThen mk pat; return (LazyPat pat') } rnPatAndThen mk (BangPat pat) = do { pat' <- rnLPatAndThen mk pat; return (BangPat pat') } rnPatAndThen mk (VarPat (L l rdr)) = do { loc <- liftCps getSrcSpanM ; name <- newPatName mk (L loc rdr) ; return (VarPat (L l name)) } -- we need to bind pattern variables for view pattern expressions -- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple) rnPatAndThen mk (SigPatIn pat sig) -- When renaming a pattern type signature (e.g. f (a :: T) = ...), it is -- important to rename its type signature _before_ renaming the rest of the -- pattern, so that type variables are first bound by the _outermost_ pattern -- type signature they occur in. This keeps the type checker happy when -- pattern type signatures happen to be nested (#7827) -- -- f ((Just (x :: a) :: Maybe a) -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~^ `a' is first bound here -- ~~~~~~~~~~~~~~~^ the same `a' then used here = do { sig' <- rnHsSigCps sig ; pat' <- rnLPatAndThen mk pat ; return (SigPatIn pat' sig') } rnPatAndThen mk (LitPat lit) | HsString src s <- lit = do { ovlStr <- liftCps (xoptM LangExt.OverloadedStrings) ; if ovlStr then rnPatAndThen mk (mkNPat (noLoc (mkHsIsString src s placeHolderType)) Nothing) else normal_lit } | otherwise = normal_lit where normal_lit = do { liftCps (rnLit lit); return (LitPat lit) } rnPatAndThen _ (NPat (L l lit) mb_neg _eq _) = do { lit' <- liftCpsFV $ rnOverLit lit ; mb_neg' <- liftCpsFV $ case mb_neg of Nothing -> return (Nothing, emptyFVs) Just _ -> do { (neg, fvs) <- lookupSyntaxName negateName ; return (Just neg, fvs) } ; eq' <- liftCpsFV $ lookupSyntaxName eqName ; return (NPat (L l lit') mb_neg' eq' placeHolderType) } rnPatAndThen mk (NPlusKPat rdr (L l lit) _ _ _ _) = do { new_name <- newPatName mk rdr ; lit' <- liftCpsFV $ rnOverLit lit ; minus <- liftCpsFV $ lookupSyntaxName minusName ; ge <- liftCpsFV $ lookupSyntaxName geName ; return (NPlusKPat (L (nameSrcSpan new_name) new_name) (L l lit') lit' ge minus placeHolderType) } -- The Report says that n+k patterns must be in Integral rnPatAndThen mk (AsPat rdr pat) = do { new_name <- newPatLName mk rdr ; pat' <- rnLPatAndThen mk pat ; return (AsPat new_name pat') } rnPatAndThen mk p@(ViewPat expr pat _ty) = do { liftCps $ do { vp_flag <- xoptM LangExt.ViewPatterns ; checkErr vp_flag (badViewPat p) } -- Because of the way we're arranging the recursive calls, -- this will be in the right context ; expr' <- liftCpsFV $ rnLExpr expr ; pat' <- rnLPatAndThen mk pat -- Note: at this point the PreTcType in ty can only be a placeHolder -- ; return (ViewPat expr' pat' ty) } ; return (ViewPat expr' pat' placeHolderType) } rnPatAndThen mk (ConPatIn con stuff) -- rnConPatAndThen takes care of reconstructing the pattern -- The pattern for the empty list needs to be replaced by an empty explicit list pattern when overloaded lists is turned on. = case unLoc con == nameRdrName (dataConName nilDataCon) of True -> do { ol_flag <- liftCps $ xoptM LangExt.OverloadedLists ; if ol_flag then rnPatAndThen mk (ListPat [] placeHolderType Nothing) else rnConPatAndThen mk con stuff} False -> rnConPatAndThen mk con stuff rnPatAndThen mk (ListPat pats _ _) = do { opt_OverloadedLists <- liftCps $ xoptM LangExt.OverloadedLists ; pats' <- rnLPatsAndThen mk pats ; case opt_OverloadedLists of True -> do { (to_list_name,_) <- liftCps $ lookupSyntaxName toListName ; return (ListPat pats' placeHolderType (Just (placeHolderType, to_list_name)))} False -> return (ListPat pats' placeHolderType Nothing) } rnPatAndThen mk (PArrPat pats _) = do { pats' <- rnLPatsAndThen mk pats ; return (PArrPat pats' placeHolderType) } rnPatAndThen mk (TuplePat pats boxed _) = do { liftCps $ checkTupSize (length pats) ; pats' <- rnLPatsAndThen mk pats ; return (TuplePat pats' boxed []) } rnPatAndThen mk (SplicePat splice) = do { eith <- liftCpsFV $ rnSplicePat splice ; case eith of -- See Note [rnSplicePat] in RnSplice Left not_yet_renamed -> rnPatAndThen mk not_yet_renamed Right already_renamed -> return already_renamed } rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat) -------------------- rnConPatAndThen :: NameMaker -> Located RdrName -- the constructor -> HsConPatDetails RdrName -> CpsRn (Pat Name) rnConPatAndThen mk con (PrefixCon pats) = do { con' <- lookupConCps con ; pats' <- rnLPatsAndThen mk pats ; return (ConPatIn con' (PrefixCon pats')) } rnConPatAndThen mk con (InfixCon pat1 pat2) = do { con' <- lookupConCps con ; pat1' <- rnLPatAndThen mk pat1 ; pat2' <- rnLPatAndThen mk pat2 ; fixity <- liftCps $ lookupFixityRn (unLoc con') ; liftCps $ mkConOpPatRn con' fixity pat1' pat2' } rnConPatAndThen mk con (RecCon rpats) = do { con' <- lookupConCps con ; rpats' <- rnHsRecPatsAndThen mk con' rpats ; return (ConPatIn con' (RecCon rpats')) } -------------------- rnHsRecPatsAndThen :: NameMaker -> Located Name -- Constructor -> HsRecFields RdrName (LPat RdrName) -> CpsRn (HsRecFields Name (LPat Name)) rnHsRecPatsAndThen mk (L _ con) hs_rec_fields@(HsRecFields { rec_dotdot = dd }) = do { flds <- liftCpsFV $ rnHsRecFields (HsRecFieldPat con) mkVarPat hs_rec_fields ; flds' <- mapM rn_field (flds `zip` [1..]) ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) } where mkVarPat l n = VarPat (L l n) rn_field (L l fld, n') = do { arg' <- rnLPatAndThen (nested_mk dd mk n') (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldArg = arg' })) } -- Suppress unused-match reporting for fields introduced by ".." nested_mk Nothing mk _ = mk nested_mk (Just _) mk@(LetMk {}) _ = mk nested_mk (Just n) (LamMk report_unused) n' = LamMk (report_unused && (n' <= n)) {- ************************************************************************ * * Record fields * * ************************************************************************ -} data HsRecFieldContext = HsRecFieldCon Name | HsRecFieldPat Name | HsRecFieldUpd rnHsRecFields :: forall arg. HsRecFieldContext -> (SrcSpan -> RdrName -> arg) -- When punning, use this to build a new field -> HsRecFields RdrName (Located arg) -> RnM ([LHsRecField Name (Located arg)], FreeVars) -- This surprisingly complicated pass -- a) looks up the field name (possibly using disambiguation) -- b) fills in puns and dot-dot stuff -- When we we've finished, we've renamed the LHS, but not the RHS, -- of each x=e binding -- -- This is used for record construction and pattern-matching, but not updates. rnHsRecFields ctxt mk_arg (HsRecFields { rec_flds = flds, rec_dotdot = dotdot }) = do { pun_ok <- xoptM LangExt.RecordPuns ; disambig_ok <- xoptM LangExt.DisambiguateRecordFields ; parent <- check_disambiguation disambig_ok mb_con ; flds1 <- mapM (rn_fld pun_ok parent) flds ; mapM_ (addErr . dupFieldErr ctxt) dup_flds ; dotdot_flds <- rn_dotdot dotdot mb_con flds1 ; let all_flds | null dotdot_flds = flds1 | otherwise = flds1 ++ dotdot_flds ; return (all_flds, mkFVs (getFieldIds all_flds)) } where mb_con = case ctxt of HsRecFieldCon con | not (isUnboundName con) -> Just con HsRecFieldPat con | not (isUnboundName con) -> Just con _ {- update or isUnboundName con -} -> Nothing -- The unbound name test is because if the constructor -- isn't in scope the constructor lookup will add an error -- add an error, but still return an unbound name. -- We don't want that to screw up the dot-dot fill-in stuff. doc = case mb_con of Nothing -> text "constructor field name" Just con -> text "field of constructor" <+> quotes (ppr con) rn_fld :: Bool -> Maybe Name -> LHsRecField RdrName (Located arg) -> RnM (LHsRecField Name (Located arg)) rn_fld pun_ok parent (L l (HsRecField { hsRecFieldLbl = L loc (FieldOcc (L ll lbl) _) , hsRecFieldArg = arg , hsRecPun = pun })) = do { sel <- setSrcSpan loc $ lookupRecFieldOcc parent doc lbl ; arg' <- if pun then do { checkErr pun_ok (badPun (L loc lbl)) -- Discard any module qualifier (#11662) ; let arg_rdr = mkRdrUnqual (rdrNameOcc lbl) ; return (L loc (mk_arg loc arg_rdr)) } else return arg ; return (L l (HsRecField { hsRecFieldLbl = L loc (FieldOcc (L ll lbl) sel) , hsRecFieldArg = arg' , hsRecPun = pun })) } rn_dotdot :: Maybe Int -- See Note [DotDot fields] in HsPat -> Maybe Name -- The constructor (Nothing for an -- out of scope constructor) -> [LHsRecField Name (Located arg)] -- Explicit fields -> RnM [LHsRecField Name (Located arg)] -- Filled in .. fields rn_dotdot Nothing _mb_con _flds -- No ".." at all = return [] rn_dotdot (Just {}) Nothing _flds -- Constructor out of scope = return [] rn_dotdot (Just n) (Just con) flds -- ".." on record construction / pat match = ASSERT( n == length flds ) do { loc <- getSrcSpanM -- Rather approximate ; dd_flag <- xoptM LangExt.RecordWildCards ; checkErr dd_flag (needFlagDotDot ctxt) ; (rdr_env, lcl_env) <- getRdrEnvs ; con_fields <- lookupConstructorFields con ; when (null con_fields) (addErr (badDotDotCon con)) ; let present_flds = map (occNameFS . rdrNameOcc) $ getFieldLbls flds parent_tc = find_tycon rdr_env con -- For constructor uses (but not patterns) -- the arg should be in scope (unqualified) -- ignoring the record field itself -- Eg. data R = R { x,y :: Int } -- f x = R { .. } -- Should expand to R {x=x}, not R{x=x,y=y} arg_in_scope lbl = rdr `elemLocalRdrEnv` lcl_env || notNull [ gre | gre <- lookupGRE_RdrName rdr rdr_env , case gre_par gre of ParentIs p -> Just p /= parent_tc FldParent p _ -> Just p /= parent_tc PatternSynonym -> False NoParent -> True ] where rdr = mkVarUnqual lbl dot_dot_gres = [ (lbl, sel, head gres) | fl <- con_fields , let lbl = flLabel fl , let sel = flSelector fl , not (lbl `elem` present_flds) , let gres = lookupGRE_Field_Name rdr_env sel lbl , not (null gres) -- Check selector is in scope , case ctxt of HsRecFieldCon {} -> arg_in_scope lbl _other -> True ] ; addUsedGREs (map thdOf3 dot_dot_gres) ; return [ L loc (HsRecField { hsRecFieldLbl = L loc (FieldOcc (L loc arg_rdr) sel) , hsRecFieldArg = L loc (mk_arg loc arg_rdr) , hsRecPun = False }) | (lbl, sel, _) <- dot_dot_gres , let arg_rdr = mkVarUnqual lbl ] } check_disambiguation :: Bool -> Maybe Name -> RnM (Maybe Name) -- When disambiguation is on, return name of parent tycon. check_disambiguation disambig_ok mb_con | disambig_ok, Just con <- mb_con = do { env <- getGlobalRdrEnv; return (find_tycon env con) } | otherwise = return Nothing find_tycon :: GlobalRdrEnv -> Name {- DataCon -} -> Maybe Name {- TyCon -} -- Return the parent *type constructor* of the data constructor -- (that is, the parent of the data constructor), -- or 'Nothing' if it is a pattern synonym. -- That's the parent to use for looking up record fields. find_tycon env con | Just (AConLike (RealDataCon dc)) <- wiredInNameTyThing_maybe con = Just (tyConName (dataConTyCon dc)) -- Special case for [], which is built-in syntax -- and not in the GlobalRdrEnv (Trac #8448) | [gre] <- lookupGRE_Name env con = case gre_par gre of ParentIs p -> Just p _ -> Nothing | otherwise = pprPanic "find_tycon" (ppr con $$ ppr (lookupGRE_Name env con)) dup_flds :: [[RdrName]] -- Each list represents a RdrName that occurred more than once -- (the list contains all occurrences) -- Each list in dup_fields is non-empty (_, dup_flds) = removeDups compare (getFieldLbls flds) rnHsRecUpdFields :: [LHsRecUpdField RdrName] -> RnM ([LHsRecUpdField Name], FreeVars) rnHsRecUpdFields flds = do { pun_ok <- xoptM LangExt.RecordPuns ; overload_ok <- xoptM LangExt.DuplicateRecordFields ; (flds1, fvss) <- mapAndUnzipM (rn_fld pun_ok overload_ok) flds ; mapM_ (addErr . dupFieldErr HsRecFieldUpd) dup_flds -- Check for an empty record update e {} -- NB: don't complain about e { .. }, because rn_dotdot has done that already ; when (null flds) $ addErr emptyUpdateErr ; return (flds1, plusFVs fvss) } where doc = text "constructor field name" rn_fld :: Bool -> Bool -> LHsRecUpdField RdrName -> RnM (LHsRecUpdField Name, FreeVars) rn_fld pun_ok overload_ok (L l (HsRecField { hsRecFieldLbl = L loc f , hsRecFieldArg = arg , hsRecPun = pun })) = do { let lbl = rdrNameAmbiguousFieldOcc f ; sel <- setSrcSpan loc $ -- Defer renaming of overloaded fields to the typechecker -- See Note [Disambiguating record fields] in TcExpr if overload_ok then do { mb <- lookupGlobalOccRn_overloaded overload_ok lbl ; case mb of Nothing -> do { addErr (unknownSubordinateErr doc lbl) ; return (Right []) } Just r -> return r } else fmap Left $ lookupGlobalOccRn lbl ; arg' <- if pun then do { checkErr pun_ok (badPun (L loc lbl)) -- Discard any module qualifier (#11662) ; let arg_rdr = mkRdrUnqual (rdrNameOcc lbl) ; return (L loc (HsVar (L loc arg_rdr))) } else return arg ; (arg'', fvs) <- rnLExpr arg' ; let fvs' = case sel of Left sel_name -> fvs `addOneFV` sel_name Right [FieldOcc _ sel_name] -> fvs `addOneFV` sel_name Right _ -> fvs lbl' = case sel of Left sel_name -> L loc (Unambiguous (L loc lbl) sel_name) Right [FieldOcc lbl sel_name] -> L loc (Unambiguous lbl sel_name) Right _ -> L loc (Ambiguous (L loc lbl) PlaceHolder) ; return (L l (HsRecField { hsRecFieldLbl = lbl' , hsRecFieldArg = arg'' , hsRecPun = pun }), fvs') } dup_flds :: [[RdrName]] -- Each list represents a RdrName that occurred more than once -- (the list contains all occurrences) -- Each list in dup_fields is non-empty (_, dup_flds) = removeDups compare (getFieldUpdLbls flds) getFieldIds :: [LHsRecField Name arg] -> [Name] getFieldIds flds = map (unLoc . hsRecFieldSel . unLoc) flds getFieldLbls :: [LHsRecField id arg] -> [RdrName] getFieldLbls flds = map (unLoc . rdrNameFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds getFieldUpdLbls :: [LHsRecUpdField id] -> [RdrName] getFieldUpdLbls flds = map (rdrNameAmbiguousFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds needFlagDotDot :: HsRecFieldContext -> SDoc needFlagDotDot ctxt = vcat [text "Illegal `..' in record" <+> pprRFC ctxt, text "Use RecordWildCards to permit this"] badDotDotCon :: Name -> SDoc badDotDotCon con = vcat [ text "Illegal `..' notation for constructor" <+> quotes (ppr con) , nest 2 (text "The constructor has no labelled fields") ] emptyUpdateErr :: SDoc emptyUpdateErr = text "Empty record update" badPun :: Located RdrName -> SDoc badPun fld = vcat [text "Illegal use of punning for field" <+> quotes (ppr fld), text "Use NamedFieldPuns to permit this"] dupFieldErr :: HsRecFieldContext -> [RdrName] -> SDoc dupFieldErr ctxt dups = hsep [text "duplicate field name", quotes (ppr (head dups)), text "in record", pprRFC ctxt] pprRFC :: HsRecFieldContext -> SDoc pprRFC (HsRecFieldCon {}) = text "construction" pprRFC (HsRecFieldPat {}) = text "pattern" pprRFC (HsRecFieldUpd {}) = text "update" {- ************************************************************************ * * \subsubsection{Literals} * * ************************************************************************ When literals occur we have to make sure that the types and classes they involve are made available. -} rnLit :: HsLit -> RnM () rnLit (HsChar _ c) = checkErr (inCharRange c) (bogusCharError c) rnLit _ = return () -- Turn a Fractional-looking literal which happens to be an integer into an -- Integer-looking literal. generalizeOverLitVal :: OverLitVal -> OverLitVal generalizeOverLitVal (HsFractional (FL {fl_text=src,fl_value=val})) | denominator val == 1 = HsIntegral src (numerator val) generalizeOverLitVal lit = lit rnOverLit :: HsOverLit t -> RnM (HsOverLit Name, FreeVars) rnOverLit origLit = do { opt_NumDecimals <- xoptM LangExt.NumDecimals ; let { lit@(OverLit {ol_val=val}) | opt_NumDecimals = origLit {ol_val = generalizeOverLitVal (ol_val origLit)} | otherwise = origLit } ; let std_name = hsOverLitName val ; (SyntaxExpr { syn_expr = from_thing_name }, fvs) <- lookupSyntaxName std_name ; let rebindable = case from_thing_name of HsVar (L _ v) -> v /= std_name _ -> panic "rnOverLit" ; return (lit { ol_witness = from_thing_name , ol_rebindable = rebindable , ol_type = placeHolderType }, fvs) } {- ************************************************************************ * * \subsubsection{Errors} * * ************************************************************************ -} patSigErr :: Outputable a => a -> SDoc patSigErr ty = (text "Illegal signature in pattern:" <+> ppr ty) $$ nest 4 (text "Use ScopedTypeVariables to permit it") bogusCharError :: Char -> SDoc bogusCharError c = text "character literal out of range: '\\" <> char c <> char '\'' badViewPat :: Pat RdrName -> SDoc badViewPat pat = vcat [text "Illegal view pattern: " <+> ppr pat, text "Use ViewPatterns to enable view patterns"]
vikraman/ghc
compiler/rename/RnPat.hs
bsd-3-clause
34,213
29
23
11,342
6,616
3,567
3,049
-1
-1
-- | POSIX time, if you need to deal with timestamps and the like. -- Most people won't need this module. module Data.Time.Clock.POSIX ( posixDayLength,POSIXTime,posixSecondsToUTCTime,utcTimeToPOSIXSeconds,getPOSIXTime ) where import Data.Time.Clock.UTC import Data.Time.Calendar.Days import Data.Fixed import Control.Monad #ifdef mingw32_HOST_OS import Data.Word ( Word64) import System.Win32.Time #else import Data.Time.Clock.CTimeval #endif -- | 86400 nominal seconds in every day posixDayLength :: NominalDiffTime posixDayLength = 86400 -- | POSIX time is the nominal time since 1970-01-01 00:00 UTC -- -- To convert from a 'Foreign.C.CTime' or 'System.Posix.EpochTime', use 'realToFrac'. -- type POSIXTime = NominalDiffTime unixEpochDay :: Day unixEpochDay = ModifiedJulianDay 40587 posixSecondsToUTCTime :: POSIXTime -> UTCTime posixSecondsToUTCTime i = let (d,t) = divMod' i posixDayLength in UTCTime (addDays d unixEpochDay) (realToFrac t) utcTimeToPOSIXSeconds :: UTCTime -> POSIXTime utcTimeToPOSIXSeconds (UTCTime d t) = (fromInteger (diffDays d unixEpochDay) * posixDayLength) + min posixDayLength (realToFrac t) -- | Get the current POSIX time from the system clock. getPOSIXTime :: IO POSIXTime #ifdef mingw32_HOST_OS -- On Windows, the equlvalent of POSIX time is "file time", defined as -- the number of 100-nanosecond intervals that have elapsed since -- 12:00 A.M. January 1, 1601 (UTC). We can convert this into a POSIX -- time by adjusting the offset to be relative to the POSIX epoch. getPOSIXTime = do FILETIME ft <- System.Win32.Time.getSystemTimeAsFileTime return (fromIntegral (ft - win32_epoch_adjust) / 10000000) win32_epoch_adjust :: Word64 win32_epoch_adjust = 116444736000000000 #else -- Use POSIX time ctimevalToPosixSeconds :: CTimeval -> POSIXTime ctimevalToPosixSeconds (MkCTimeval s mus) = (fromIntegral s) + (fromIntegral mus) / 1000000 getPOSIXTime = liftM ctimevalToPosixSeconds getCTimeval #endif
DavidAlphaFox/ghc
libraries/time/lib/Data/Time/Clock/POSIX.hs
bsd-3-clause
1,961
4
12
278
293
169
124
24
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TupleSections #-} module Stack.Setup ( setupEnv , ensureGHC , SetupOpts (..) , defaultStackSetupYaml ) where import Control.Applicative import Control.Exception.Enclosed (catchIO, tryAny) import Control.Monad (liftM, when, join, void, unless) import Control.Monad.Catch import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger import Control.Monad.Reader (MonadReader, ReaderT (..), asks) import Control.Monad.State (get, put, modify) import Control.Monad.Trans.Control import Crypto.Hash (SHA1(SHA1)) import Data.Aeson.Extended import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.Conduit (Conduit, ($$), (=$), await, yield, awaitForever) import Data.Conduit.Lift (evalStateC) import qualified Data.Conduit.List as CL import Data.Either import Data.Foldable hiding (concatMap, or) import Data.IORef import Data.IORef.RunOnce (runOnce) import Data.List hiding (concat, elem, maximumBy) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Monoid import Data.Ord (comparing) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime) import Data.Typeable (Typeable) import qualified Data.Yaml as Yaml import Distribution.System (OS, Arch (..), Platform (..)) import qualified Distribution.System as Cabal import Distribution.Text (simpleParse) import Network.HTTP.Client.Conduit import Network.HTTP.Download.Verified import Path import Path.IO import Prelude hiding (concat, elem) -- Fix AMP warning import Safe (headMay, readMay) import Stack.Types.Build import Stack.Config (resolvePackageEntry) import Stack.Constants (distRelativeDir) import Stack.Fetch import Stack.GhcPkg (createDatabase, getCabalPkgVer, getGlobalDB) import Stack.Solver (getCompilerVersion) import Stack.Types import Stack.Types.StackT import qualified System.Directory as D import System.Environment (getExecutablePath) import System.Exit (ExitCode (ExitSuccess)) import System.FilePath (searchPathSeparator) import qualified System.FilePath as FP import System.IO.Temp (withSystemTempDirectory) import System.Process (rawSystem) import System.Process.Read import System.Process.Run (runIn) import Text.Printf (printf) -- | Default location of the stack-setup.yaml file defaultStackSetupYaml :: String defaultStackSetupYaml = "https://raw.githubusercontent.com/fpco/stackage-content/master/stack/stack-setup-2.yaml" data SetupOpts = SetupOpts { soptsInstallIfMissing :: !Bool , soptsUseSystem :: !Bool , soptsWantedCompiler :: !CompilerVersion , soptsCompilerCheck :: !VersionCheck , soptsStackYaml :: !(Maybe (Path Abs File)) -- ^ If we got the desired GHC version from that file , soptsForceReinstall :: !Bool , soptsSanityCheck :: !Bool -- ^ Run a sanity check on the selected GHC , soptsSkipGhcCheck :: !Bool -- ^ Don't check for a compatible GHC version/architecture , soptsSkipMsys :: !Bool -- ^ Do not use a custom msys installation on Windows , soptsUpgradeCabal :: !Bool -- ^ Upgrade the global Cabal library in the database to the newest -- version. Only works reliably with a stack-managed installation. , soptsResolveMissingGHC :: !(Maybe Text) -- ^ Message shown to user for how to resolve the missing GHC , soptsStackSetupYaml :: !String } deriving Show data SetupException = UnsupportedSetupCombo OS Arch | MissingDependencies [String] | UnknownCompilerVersion Text CompilerVersion (Set Version) | UnknownOSKey Text | GHCSanityCheckCompileFailed ReadProcessException (Path Abs File) deriving Typeable instance Exception SetupException instance Show SetupException where show (UnsupportedSetupCombo os arch) = concat [ "I don't know how to install GHC for " , show (os, arch) , ", please install manually" ] show (MissingDependencies tools) = "The following executables are missing and must be installed: " ++ intercalate ", " tools show (UnknownCompilerVersion oskey wanted known) = concat [ "No information found for " , T.unpack (compilerVersionName wanted) , ".\nSupported versions for OS key '" ++ T.unpack oskey ++ "': " , intercalate ", " (map show $ Set.toList known) ] show (UnknownOSKey oskey) = "Unable to find installation URLs for OS key: " ++ T.unpack oskey show (GHCSanityCheckCompileFailed e ghc) = concat [ "The GHC located at " , toFilePath ghc , " failed to compile a sanity check. Please see:\n\n" , " https://github.com/commercialhaskell/stack/wiki/Downloads\n\n" , "for more information. Exception was:\n" , show e ] -- | Modify the environment variables (like PATH) appropriately, possibly doing installation too setupEnv :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasBuildConfig env, HasHttpManager env, MonadBaseControl IO m) => Maybe Text -- ^ Message to give user when necessary GHC is not available -> m EnvConfig setupEnv mResolveMissingGHC = do bconfig <- asks getBuildConfig let platform = getPlatform bconfig wc = whichCompiler (bcWantedCompiler bconfig) sopts = SetupOpts { soptsInstallIfMissing = configInstallGHC $ bcConfig bconfig , soptsUseSystem = configSystemGHC $ bcConfig bconfig , soptsWantedCompiler = bcWantedCompiler bconfig , soptsCompilerCheck = configCompilerCheck $ bcConfig bconfig , soptsStackYaml = Just $ bcStackYaml bconfig , soptsForceReinstall = False , soptsSanityCheck = False , soptsSkipGhcCheck = configSkipGHCCheck $ bcConfig bconfig , soptsSkipMsys = configSkipMsys $ bcConfig bconfig , soptsUpgradeCabal = False , soptsResolveMissingGHC = mResolveMissingGHC , soptsStackSetupYaml = defaultStackSetupYaml } mghcBin <- ensureGHC sopts -- Modify the initial environment to include the GHC path, if a local GHC -- is being used menv0 <- getMinimalEnvOverride let env = removeHaskellEnvVars $ augmentPathMap (maybe [] edBins mghcBin) $ unEnvOverride menv0 menv <- mkEnvOverride platform env compilerVer <- getCompilerVersion menv wc cabalVer <- getCabalPkgVer menv wc packages <- mapM (resolvePackageEntry menv (bcRoot bconfig)) (bcPackageEntries bconfig) let envConfig0 = EnvConfig { envConfigBuildConfig = bconfig , envConfigCabalVersion = cabalVer , envConfigCompilerVersion = compilerVer , envConfigPackages = Map.fromList $ concat packages } -- extra installation bin directories mkDirs <- runReaderT extraBinDirs envConfig0 let mpath = Map.lookup "PATH" env mkDirs' = map toFilePath . mkDirs depsPath = augmentPath (mkDirs' False) mpath localsPath = augmentPath (mkDirs' True) mpath deps <- runReaderT packageDatabaseDeps envConfig0 createDatabase menv wc deps localdb <- runReaderT packageDatabaseLocal envConfig0 createDatabase menv wc localdb globalDB <- getGlobalDB menv wc let mkGPP locals = T.pack $ intercalate [searchPathSeparator] $ concat [ [toFilePathNoTrailingSlash localdb | locals] , [toFilePathNoTrailingSlash deps] , [toFilePathNoTrailingSlash globalDB] ] distDir <- runReaderT distRelativeDir envConfig0 executablePath <- liftIO getExecutablePath utf8EnvVars <- getUtf8LocaleVars menv envRef <- liftIO $ newIORef Map.empty let getEnvOverride' es = do m <- readIORef envRef case Map.lookup es m of Just eo -> return eo Nothing -> do eo <- mkEnvOverride platform $ Map.insert "PATH" (if esIncludeLocals es then localsPath else depsPath) $ (if esIncludeGhcPackagePath es then Map.insert "GHC_PACKAGE_PATH" (mkGPP (esIncludeLocals es)) else id) $ (if esStackExe es then Map.insert "STACK_EXE" (T.pack executablePath) else id) $ (if esLocaleUtf8 es then Map.union utf8EnvVars else id) -- For reasoning and duplication, see: https://github.com/fpco/stack/issues/70 $ Map.insert "HASKELL_PACKAGE_SANDBOX" (T.pack $ toFilePathNoTrailingSlash deps) $ Map.insert "HASKELL_PACKAGE_SANDBOXES" (T.pack $ if esIncludeLocals es then intercalate [searchPathSeparator] [ toFilePathNoTrailingSlash localdb , toFilePathNoTrailingSlash deps , "" ] else intercalate [searchPathSeparator] [ toFilePathNoTrailingSlash deps , "" ]) $ Map.insert "HASKELL_DIST_DIR" (T.pack $ toFilePathNoTrailingSlash distDir) $ env !() <- atomicModifyIORef envRef $ \m' -> (Map.insert es eo m', ()) return eo return EnvConfig { envConfigBuildConfig = bconfig { bcConfig = maybe id addIncludeLib mghcBin (bcConfig bconfig) { configEnvOverride = getEnvOverride' } } , envConfigCabalVersion = cabalVer , envConfigCompilerVersion = compilerVer , envConfigPackages = envConfigPackages envConfig0 } -- | Add the include and lib paths to the given Config addIncludeLib :: ExtraDirs -> Config -> Config addIncludeLib (ExtraDirs _bins includes libs) config = config { configExtraIncludeDirs = Set.union (configExtraIncludeDirs config) (Set.fromList $ map T.pack includes) , configExtraLibDirs = Set.union (configExtraLibDirs config) (Set.fromList $ map T.pack libs) } data ExtraDirs = ExtraDirs { edBins :: ![FilePath] , edInclude :: ![FilePath] , edLib :: ![FilePath] } instance Monoid ExtraDirs where mempty = ExtraDirs [] [] [] mappend (ExtraDirs a b c) (ExtraDirs x y z) = ExtraDirs (a ++ x) (b ++ y) (c ++ z) -- | Ensure GHC is installed and provide the PATHs to add if necessary ensureGHC :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupOpts -> m (Maybe ExtraDirs) ensureGHC sopts = do let wc = whichCompiler (soptsWantedCompiler sopts) ghcVersion = case soptsWantedCompiler sopts of GhcVersion v -> v GhcjsVersion _ v -> v when (ghcVersion < $(mkVersion "7.8")) $ do $logWarn "stack will almost certainly fail with GHC below version 7.8" $logWarn "Valiantly attempting to run anyway, but I know this is doomed" $logWarn "For more information, see: https://github.com/commercialhaskell/stack/issues/648" $logWarn "" -- Check the available GHCs menv0 <- getMinimalEnvOverride msystem <- if soptsUseSystem sopts then getSystemCompiler menv0 wc else return Nothing Platform expectedArch _ <- asks getPlatform let needLocal = case msystem of Nothing -> True Just _ | soptsSkipGhcCheck sopts -> False Just (system, arch) -> not (isWanted system) || arch /= expectedArch isWanted = isWantedCompiler (soptsCompilerCheck sopts) (soptsWantedCompiler sopts) -- If we need to install a GHC, try to do so mpaths <- if needLocal then do getSetupInfo' <- runOnce (getSetupInfo sopts =<< asks getHttpManager) config <- asks getConfig installed <- runReaderT listInstalled config -- Install GHC ghcIdent <- case getInstalledTool installed $(mkPackageName "ghc") (isWanted . GhcVersion) of Just ident -> return ident Nothing | soptsInstallIfMissing sopts -> do si <- getSetupInfo' downloadAndInstallGHC menv0 si (soptsWantedCompiler sopts) (soptsCompilerCheck sopts) | otherwise -> do Platform arch _ <- asks getPlatform throwM $ CompilerVersionMismatch msystem (soptsWantedCompiler sopts, arch) (soptsCompilerCheck sopts) (soptsStackYaml sopts) (fromMaybe "Try running stack setup to locally install the correct GHC" $ soptsResolveMissingGHC sopts) -- Install msys2 on windows, if necessary mmsys2Ident <- case configPlatform config of Platform _ os | isWindows os && not (soptsSkipMsys sopts) -> case getInstalledTool installed $(mkPackageName "msys2") (const True) of Just ident -> return (Just ident) Nothing | soptsInstallIfMissing sopts -> do si <- getSetupInfo' osKey <- getOSKey menv0 VersionedDownloadInfo version info <- case Map.lookup osKey $ siMsys2 si of Just x -> return x Nothing -> error $ "MSYS2 not found for " ++ T.unpack osKey Just <$> downloadAndInstallTool si info $(mkPackageName "msys2") version (installMsys2Windows osKey) | otherwise -> do $logWarn "Continuing despite missing tool: msys2" return Nothing _ -> return Nothing let idents = catMaybes [Just ghcIdent, mmsys2Ident] paths <- runReaderT (mapM extraDirs idents) config return $ Just $ mconcat paths else return Nothing menv <- case mpaths of Nothing -> return menv0 Just ed -> do config <- asks getConfig let m0 = unEnvOverride menv0 path0 = Map.lookup "PATH" m0 path = augmentPath (edBins ed) path0 m = Map.insert "PATH" path m0 mkEnvOverride (configPlatform config) (removeHaskellEnvVars m) when (soptsUpgradeCabal sopts) $ do unless needLocal $ do $logWarn "Trying to upgrade Cabal library on a GHC not installed by stack." $logWarn "This may fail, caveat emptor!" upgradeCabal menv wc when (soptsSanityCheck sopts) $ sanityCheck menv return mpaths -- | Install the newest version of Cabal globally upgradeCabal :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m, MonadMask m) => EnvOverride -> WhichCompiler -> m () upgradeCabal menv wc = do let name = $(mkPackageName "Cabal") rmap <- resolvePackages menv Set.empty (Set.singleton name) newest <- case Map.keys rmap of [] -> error "No Cabal library found in index, cannot upgrade" [PackageIdentifier name' version] | name == name' -> return version x -> error $ "Unexpected results for resolvePackages: " ++ show x installed <- getCabalPkgVer menv wc if installed >= newest then $logInfo $ T.concat [ "Currently installed Cabal is " , T.pack $ versionString installed , ", newest is " , T.pack $ versionString newest , ". I'm not upgrading Cabal." ] else withSystemTempDirectory "stack-cabal-upgrade" $ \tmpdir -> do $logInfo $ T.concat [ "Installing Cabal-" , T.pack $ versionString newest , " to replace " , T.pack $ versionString installed ] tmpdir' <- parseAbsDir tmpdir let ident = PackageIdentifier name newest m <- unpackPackageIdents menv tmpdir' Nothing (Set.singleton ident) compilerPath <- join $ findExecutable menv (compilerExeName wc) newestDir <- parseRelDir $ versionString newest let installRoot = toFilePath $ parent (parent compilerPath) </> $(mkRelDir "new-cabal") </> newestDir dir <- case Map.lookup ident m of Nothing -> error $ "upgradeCabal: Invariant violated, dir missing" Just dir -> return dir runIn dir (compilerExeName wc) menv ["Setup.hs"] Nothing let setupExe = toFilePath $ dir </> $(mkRelFile "Setup") dirArgument name' = concat [ "--" , name' , "dir=" , installRoot FP.</> name' ] runIn dir setupExe menv ( "configure" : map dirArgument (words "lib bin data doc") ) Nothing runIn dir setupExe menv ["build"] Nothing runIn dir setupExe menv ["install"] Nothing $logInfo "New Cabal library installed" -- | Get the version of the system compiler, if available getSystemCompiler :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m) => EnvOverride -> WhichCompiler -> m (Maybe (CompilerVersion, Arch)) getSystemCompiler menv wc = do let exeName = case wc of Ghc -> "ghc" Ghcjs -> "ghcjs" exists <- doesExecutableExist menv exeName if exists then do eres <- tryProcessStdout Nothing menv exeName ["--info"] let minfo = do Right bs <- Just eres pairs <- readMay $ S8.unpack bs :: Maybe [(String, String)] version <- lookup "Project version" pairs >>= parseVersionFromString arch <- lookup "Target platform" pairs >>= simpleParse . takeWhile (/= '-') return (version, arch) case (wc, minfo) of (Ghc, Just (version, arch)) -> return (Just (GhcVersion version, arch)) (Ghcjs, Just (_, arch)) -> do eversion <- tryAny $ getCompilerVersion menv Ghcjs case eversion of Left _ -> return Nothing Right version -> return (Just (version, arch)) (_, Nothing) -> return Nothing else return Nothing data DownloadInfo = DownloadInfo { downloadInfoUrl :: Text , downloadInfoContentLength :: Int , downloadInfoSha1 :: Maybe ByteString } deriving Show data VersionedDownloadInfo = VersionedDownloadInfo { vdiVersion :: Version , vdiDownloadInfo :: DownloadInfo } deriving Show parseDownloadInfoFromObject :: Yaml.Object -> Yaml.Parser DownloadInfo parseDownloadInfoFromObject o = do url <- o .: "url" contentLength <- o .: "content-length" sha1TextMay <- o .:? "sha1" return DownloadInfo { downloadInfoUrl = url , downloadInfoContentLength = contentLength , downloadInfoSha1 = fmap T.encodeUtf8 sha1TextMay } instance FromJSON DownloadInfo where parseJSON = withObject "DownloadInfo" parseDownloadInfoFromObject instance FromJSON VersionedDownloadInfo where parseJSON = withObject "VersionedDownloadInfo" $ \o -> do version <- o .: "version" downloadInfo <- parseDownloadInfoFromObject o return VersionedDownloadInfo { vdiVersion = version , vdiDownloadInfo = downloadInfo } data SetupInfo = SetupInfo { siSevenzExe :: DownloadInfo , siSevenzDll :: DownloadInfo , siMsys2 :: Map Text VersionedDownloadInfo , siGHCs :: Map Text (Map Version DownloadInfo) } deriving Show instance FromJSON SetupInfo where parseJSON = withObject "SetupInfo" $ \o -> SetupInfo <$> o .: "sevenzexe-info" <*> o .: "sevenzdll-info" <*> o .: "msys2" <*> o .: "ghc" -- | Download the most recent SetupInfo getSetupInfo :: (MonadIO m, MonadThrow m) => SetupOpts -> Manager -> m SetupInfo getSetupInfo sopts manager = do bs <- case parseUrl $ soptsStackSetupYaml sopts of Just req -> do bss <- liftIO $ flip runReaderT manager $ withResponse req $ \res -> responseBody res $$ CL.consume return $ S8.concat bss Nothing -> liftIO $ S.readFile $ soptsStackSetupYaml sopts either throwM return $ Yaml.decodeEither' bs markInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => PackageIdentifier -- ^ e.g., ghc-7.8.4, msys2-20150512 -> m () markInstalled ident = do dir <- asks $ configLocalPrograms . getConfig fpRel <- parseRelFile $ packageIdentifierString ident ++ ".installed" liftIO $ writeFile (toFilePath $ dir </> fpRel) "installed" unmarkInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => PackageIdentifier -> m () unmarkInstalled ident = do dir <- asks $ configLocalPrograms . getConfig fpRel <- parseRelFile $ packageIdentifierString ident ++ ".installed" removeFileIfExists $ dir </> fpRel listInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => m [PackageIdentifier] listInstalled = do dir <- asks $ configLocalPrograms . getConfig createTree dir (_, files) <- listDirectory dir return $ mapMaybe toIdent files where toIdent fp = do x <- T.stripSuffix ".installed" $ T.pack $ toFilePath $ filename fp parsePackageIdentifierFromString $ T.unpack x installDir :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m) => PackageIdentifier -> m (Path Abs Dir) installDir ident = do config <- asks getConfig reldir <- parseRelDir $ packageIdentifierString ident return $ configLocalPrograms config </> reldir -- | Binary directories for the given installed package extraDirs :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m) => PackageIdentifier -> m ExtraDirs extraDirs ident = do config <- asks getConfig dir <- installDir ident case (configPlatform config, packageNameString $ packageIdentifierName ident) of (Platform _ (isWindows -> True), "ghc") -> return mempty { edBins = goList [ dir </> $(mkRelDir "bin") , dir </> $(mkRelDir "mingw") </> $(mkRelDir "bin") ] } (Platform _ (isWindows -> True), "msys2") -> return mempty { edBins = goList [ dir </> $(mkRelDir "usr") </> $(mkRelDir "bin") ] , edInclude = goList [ dir </> $(mkRelDir "mingw64") </> $(mkRelDir "include") , dir </> $(mkRelDir "mingw32") </> $(mkRelDir "include") ] , edLib = goList [ dir </> $(mkRelDir "mingw64") </> $(mkRelDir "lib") , dir </> $(mkRelDir "mingw32") </> $(mkRelDir "lib") ] } (_, "ghc") -> return mempty { edBins = goList [ dir </> $(mkRelDir "bin") ] } (Platform _ x, tool) -> do $logWarn $ "binDirs: unexpected OS/tool combo: " <> T.pack (show (x, tool)) return mempty where goList = map toFilePathNoTrailingSlash getInstalledTool :: [PackageIdentifier] -- ^ already installed -> PackageName -- ^ package to find -> (Version -> Bool) -- ^ which versions are acceptable -> Maybe PackageIdentifier getInstalledTool installed name goodVersion = if null available then Nothing else Just $ maximumBy (comparing packageIdentifierVersion) available where available = filter goodPackage installed goodPackage pi' = packageIdentifierName pi' == name && goodVersion (packageIdentifierVersion pi') downloadAndInstallTool :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> DownloadInfo -> PackageName -> Version -> (SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m ()) -> m PackageIdentifier downloadAndInstallTool si downloadInfo name version installer = do let ident = PackageIdentifier name version (file, at) <- downloadFromInfo downloadInfo ident dir <- installDir ident unmarkInstalled ident installer si file at dir ident markInstalled ident return ident downloadAndInstallGHC :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => EnvOverride -> SetupInfo -> CompilerVersion -> VersionCheck -> m PackageIdentifier downloadAndInstallGHC menv si wanted versionCheck = do osKey <- getOSKey menv pairs <- case Map.lookup osKey $ siGHCs si of Nothing -> throwM $ UnknownOSKey osKey Just pairs -> return pairs let mpair = listToMaybe $ sortBy (flip (comparing fst)) $ filter (\(v, _) -> isWantedCompiler versionCheck wanted (GhcVersion v)) (Map.toList pairs) (selectedVersion, downloadInfo) <- case mpair of Just pair -> return pair Nothing -> throwM $ UnknownCompilerVersion osKey wanted (Map.keysSet pairs) platform <- asks $ configPlatform . getConfig let installer = case platform of Platform _ os | isWindows os -> installGHCWindows _ -> installGHCPosix $logInfo "Preparing to install GHC to an isolated location." $logInfo "This will not interfere with any system-level installation." downloadAndInstallTool si downloadInfo $(mkPackageName "ghc") selectedVersion installer getOSKey :: (MonadReader env m, MonadThrow m, HasConfig env, MonadLogger m, MonadIO m, MonadCatch m, MonadBaseControl IO m) => EnvOverride -> m Text getOSKey menv = do platform <- asks $ configPlatform . getConfig case platform of Platform I386 Cabal.Linux -> ("linux32" <>) <$> getLinuxSuffix Platform X86_64 Cabal.Linux -> ("linux64" <>) <$> getLinuxSuffix Platform I386 Cabal.OSX -> return "macosx" Platform X86_64 Cabal.OSX -> return "macosx" Platform I386 Cabal.FreeBSD -> return "freebsd32" Platform X86_64 Cabal.FreeBSD -> return "freebsd64" Platform I386 Cabal.OpenBSD -> return "openbsd32" Platform X86_64 Cabal.OpenBSD -> return "openbsd64" Platform I386 Cabal.Windows -> return "windows32" Platform X86_64 Cabal.Windows -> return "windows64" Platform I386 (Cabal.OtherOS "windowsintegersimple") -> return "windowsintegersimple32" Platform X86_64 (Cabal.OtherOS "windowsintegersimple") -> return "windowsintegersimple64" Platform arch os -> throwM $ UnsupportedSetupCombo os arch where getLinuxSuffix = do executablePath <- liftIO getExecutablePath elddOut <- tryProcessStdout Nothing menv "ldd" [executablePath] return $ case elddOut of Left _ -> "" Right lddOut -> if hasLineWithFirstWord "libgmp.so.3" lddOut then "-gmp4" else "" hasLineWithFirstWord w = elem (Just w) . map (headMay . T.words) . T.lines . T.decodeUtf8With T.lenientDecode downloadFromInfo :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => DownloadInfo -> PackageIdentifier -> m (Path Abs File, ArchiveType) downloadFromInfo downloadInfo ident = do config <- asks getConfig at <- case extension of ".tar.xz" -> return TarXz ".tar.bz2" -> return TarBz2 ".7z.exe" -> return SevenZ _ -> error $ "Unknown extension: " ++ extension relfile <- parseRelFile $ packageIdentifierString ident ++ extension let path = configLocalPrograms config </> relfile chattyDownload (packageIdentifierText ident) downloadInfo path return (path, at) where url = downloadInfoUrl downloadInfo extension = loop $ T.unpack url where loop fp | ext `elem` [".tar", ".bz2", ".xz", ".exe", ".7z"] = loop fp' ++ ext | otherwise = "" where (fp', ext) = FP.splitExtension fp data ArchiveType = TarBz2 | TarXz | SevenZ installGHCPosix :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m () installGHCPosix _ archiveFile archiveType destDir ident = do platform <- asks getPlatform menv0 <- getMinimalEnvOverride menv <- mkEnvOverride platform (removeHaskellEnvVars (unEnvOverride menv0)) $logDebug $ "menv = " <> T.pack (show (unEnvOverride menv)) zipTool' <- case archiveType of TarXz -> return "xz" TarBz2 -> return "bzip2" SevenZ -> error "Don't know how to deal with .7z files on non-Windows" (zipTool, makeTool, tarTool) <- checkDependencies $ (,,) <$> checkDependency zipTool' <*> (checkDependency "gmake" <|> checkDependency "make") <*> checkDependency "tar" $logDebug $ "ziptool: " <> T.pack zipTool $logDebug $ "make: " <> T.pack makeTool $logDebug $ "tar: " <> T.pack tarTool withSystemTempDirectory "stack-setup" $ \root' -> do root <- parseAbsDir root' dir <- liftM (root Path.</>) $ parseRelDir $ packageIdentifierString ident $logSticky $ "Unpacking GHC ..." $logDebug $ "Unpacking " <> T.pack (toFilePath archiveFile) readInNull root tarTool menv ["xf", toFilePath archiveFile] Nothing $logSticky "Configuring GHC ..." readInNull dir (toFilePath $ dir Path.</> $(mkRelFile "configure")) menv ["--prefix=" ++ toFilePath destDir] Nothing $logSticky "Installing GHC ..." readInNull dir makeTool menv ["install"] Nothing $logStickyDone $ "Installed GHC." $logDebug $ "GHC installed to " <> T.pack (toFilePath destDir) where -- | Check if given processes appear to be present, throwing an exception if -- missing. checkDependencies :: (MonadIO m, MonadThrow m, MonadReader env m, HasConfig env) => CheckDependency a -> m a checkDependencies (CheckDependency f) = do menv <- getMinimalEnvOverride liftIO (f menv) >>= either (throwM . MissingDependencies) return checkDependency :: String -> CheckDependency String checkDependency tool = CheckDependency $ \menv -> do exists <- doesExecutableExist menv tool return $ if exists then Right tool else Left [tool] newtype CheckDependency a = CheckDependency (EnvOverride -> IO (Either [String] a)) deriving Functor instance Applicative CheckDependency where pure x = CheckDependency $ \_ -> return (Right x) CheckDependency f <*> CheckDependency x = CheckDependency $ \menv -> do f' <- f menv x' <- x menv return $ case (f', x') of (Left e1, Left e2) -> Left $ e1 ++ e2 (Left e, Right _) -> Left e (Right _, Left e) -> Left e (Right f'', Right x'') -> Right $ f'' x'' instance Alternative CheckDependency where empty = CheckDependency $ \_ -> return $ Left [] CheckDependency x <|> CheckDependency y = CheckDependency $ \menv -> do res1 <- x menv case res1 of Left _ -> y menv Right x' -> return $ Right x' installGHCWindows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m () installGHCWindows si archiveFile archiveType destDir _ = do suffix <- case archiveType of TarXz -> return ".xz" TarBz2 -> return ".bz2" _ -> error $ "GHC on Windows must be a tarball file" tarFile <- case T.stripSuffix suffix $ T.pack $ toFilePath archiveFile of Nothing -> error $ "Invalid GHC filename: " ++ show archiveFile Just x -> parseAbsFile $ T.unpack x config <- asks getConfig run7z <- setup7z si config run7z (parent archiveFile) archiveFile run7z (parent archiveFile) tarFile removeFile tarFile `catchIO` \e -> $logWarn (T.concat [ "Exception when removing " , T.pack $ toFilePath tarFile , ": " , T.pack $ show e ]) $logInfo $ "GHC installed to " <> T.pack (toFilePath destDir) installMsys2Windows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => Text -- ^ OS Key -> SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m () installMsys2Windows osKey si archiveFile archiveType destDir _ = do suffix <- case archiveType of TarXz -> return ".xz" TarBz2 -> return ".bz2" _ -> error $ "MSYS2 must be a .tar.xz archive" tarFile <- case T.stripSuffix suffix $ T.pack $ toFilePath archiveFile of Nothing -> error $ "Invalid MSYS2 filename: " ++ show archiveFile Just x -> parseAbsFile $ T.unpack x config <- asks getConfig run7z <- setup7z si config exists <- liftIO $ D.doesDirectoryExist $ toFilePath destDir when exists $ liftIO (D.removeDirectoryRecursive $ toFilePath destDir) `catchIO` \e -> do $logError $ T.pack $ "Could not delete existing msys directory: " ++ toFilePath destDir throwM e run7z (parent archiveFile) archiveFile run7z (parent archiveFile) tarFile removeFile tarFile `catchIO` \e -> $logWarn (T.concat [ "Exception when removing " , T.pack $ toFilePath tarFile , ": " , T.pack $ show e ]) msys <- parseRelDir $ "msys" ++ T.unpack (fromMaybe "32" $ T.stripPrefix "windows" osKey) liftIO $ D.renameDirectory (toFilePath $ parent archiveFile </> msys) (toFilePath destDir) platform <- asks getPlatform menv0 <- getMinimalEnvOverride let oldEnv = unEnvOverride menv0 newEnv = augmentPathMap [toFilePath $ destDir </> $(mkRelDir "usr") </> $(mkRelDir "bin")] oldEnv menv <- mkEnvOverride platform newEnv -- I couldn't find this officially documented anywhere, but you need to run -- the shell once in order to initialize some pacman stuff. Once that run -- happens, you can just run commands as usual. runIn destDir "sh" menv ["--login", "-c", "true"] Nothing -- Install git. We could install other useful things in the future too. runIn destDir "pacman" menv ["-Sy", "--noconfirm", "git"] Nothing -- | Download 7z as necessary, and get a function for unpacking things. -- -- Returned function takes an unpack directory and archive. setup7z :: (MonadReader env m, HasHttpManager env, MonadThrow m, MonadIO m, MonadIO n, MonadLogger m, MonadBaseControl IO m) => SetupInfo -> Config -> m (Path Abs Dir -> Path Abs File -> n ()) setup7z si config = do chattyDownload "7z.dll" (siSevenzDll si) dll chattyDownload "7z.exe" (siSevenzExe si) exe return $ \outdir archive -> liftIO $ do ec <- rawSystem (toFilePath exe) [ "x" , "-o" ++ toFilePath outdir , "-y" , toFilePath archive ] when (ec /= ExitSuccess) $ error $ "Problem while decompressing " ++ toFilePath archive where dir = configLocalPrograms config </> $(mkRelDir "7z") exe = dir </> $(mkRelFile "7z.exe") dll = dir </> $(mkRelFile "7z.dll") chattyDownload :: (MonadReader env m, HasHttpManager env, MonadIO m, MonadLogger m, MonadThrow m, MonadBaseControl IO m) => Text -- ^ label -> DownloadInfo -- ^ URL, content-length, and sha1 -> Path Abs File -- ^ destination -> m () chattyDownload label downloadInfo path = do let url = downloadInfoUrl downloadInfo req <- parseUrl $ T.unpack url $logSticky $ T.concat [ "Preparing to download " , label , " ..." ] $logDebug $ T.concat [ "Downloading from " , url , " to " , T.pack $ toFilePath path , " ..." ] hashChecks <- case downloadInfoSha1 downloadInfo of Just sha1ByteString -> do let sha1 = CheckHexDigestByteString sha1ByteString $logDebug $ T.concat [ "Will check against sha1 hash: " , T.decodeUtf8With T.lenientDecode sha1ByteString ] return [HashCheck SHA1 sha1] Nothing -> do $logWarn $ T.concat [ "No sha1 found in metadata," , " download hash won't be checked." ] return [] let dReq = DownloadRequest { drRequest = req , drHashChecks = hashChecks , drLengthCheck = Just totalSize , drRetryPolicy = drRetryPolicyDefault } runInBase <- liftBaseWith $ \run -> return (void . run) x <- verifiedDownload dReq path (chattyDownloadProgress runInBase) if x then $logStickyDone ("Downloaded " <> label <> ".") else $logStickyDone "Already downloaded." where totalSize = downloadInfoContentLength downloadInfo chattyDownloadProgress runInBase _ = do _ <- liftIO $ runInBase $ $logSticky $ label <> ": download has begun" CL.map (Sum . S.length) =$ chunksOverTime 1 =$ go where go = evalStateC 0 $ awaitForever $ \(Sum size) -> do modify (+ size) totalSoFar <- get liftIO $ runInBase $ $logSticky $ T.pack $ chattyProgressWithTotal totalSoFar totalSize -- Note(DanBurton): Total size is now always known in this file. -- However, printing in the case where it isn't known may still be -- useful in other parts of the codebase. -- So I'm just commenting out the code rather than deleting it. -- case mcontentLength of -- Nothing -> chattyProgressNoTotal totalSoFar -- Just 0 -> chattyProgressNoTotal totalSoFar -- Just total -> chattyProgressWithTotal totalSoFar total ---- Example: ghc: 42.13 KiB downloaded... --chattyProgressNoTotal totalSoFar = -- printf ("%s: " <> bytesfmt "%7.2f" totalSoFar <> " downloaded...") -- (T.unpack label) -- Example: ghc: 50.00 MiB / 100.00 MiB (50.00%) downloaded... chattyProgressWithTotal totalSoFar total = printf ("%s: " <> bytesfmt "%7.2f" totalSoFar <> " / " <> bytesfmt "%.2f" total <> " (%6.2f%%) downloaded...") (T.unpack label) percentage where percentage :: Double percentage = (fromIntegral totalSoFar / fromIntegral total * 100) -- | Given a printf format string for the decimal part and a number of -- bytes, formats the bytes using an appropiate unit and returns the -- formatted string. -- -- >>> bytesfmt "%.2" 512368 -- "500.359375 KiB" bytesfmt :: Integral a => String -> a -> String bytesfmt formatter bs = printf (formatter <> " %s") (fromIntegral (signum bs) * dec :: Double) (bytesSuffixes !! i) where (dec,i) = getSuffix (abs bs) getSuffix n = until p (\(x,y) -> (x / 1024, y+1)) (fromIntegral n,0) where p (n',numDivs) = n' < 1024 || numDivs == (length bytesSuffixes - 1) bytesSuffixes :: [String] bytesSuffixes = ["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"] -- Await eagerly (collect with monoidal append), -- but space out yields by at least the given amount of time. -- The final yield may come sooner, and may be a superfluous mempty. -- Note that Integer and Float literals can be turned into NominalDiffTime -- (these literals are interpreted as "seconds") chunksOverTime :: (Monoid a, MonadIO m) => NominalDiffTime -> Conduit a m a chunksOverTime diff = do currentTime <- liftIO getCurrentTime evalStateC (currentTime, mempty) go where -- State is a tuple of: -- * the last time a yield happened (or the beginning of the sink) -- * the accumulated awaits since the last yield go = await >>= \case Nothing -> do (_, acc) <- get yield acc Just a -> do (lastTime, acc) <- get let acc' = acc <> a currentTime <- liftIO getCurrentTime if diff < diffUTCTime currentTime lastTime then put (currentTime, mempty) >> yield acc' else put (lastTime, acc') go -- | Perform a basic sanity check of GHC sanityCheck :: (MonadIO m, MonadMask m, MonadLogger m, MonadBaseControl IO m) => EnvOverride -> m () sanityCheck menv = withSystemTempDirectory "stack-sanity-check" $ \dir -> do dir' <- parseAbsDir dir let fp = toFilePath $ dir' </> $(mkRelFile "Main.hs") liftIO $ writeFile fp $ unlines [ "import Distribution.Simple" -- ensure Cabal library is present , "main = putStrLn \"Hello World\"" ] ghc <- join $ findExecutable menv "ghc" $logDebug $ "Performing a sanity check on: " <> T.pack (toFilePath ghc) eres <- tryProcessStdout (Just dir') menv "ghc" [ fp , "-no-user-package-db" ] case eres of Left e -> throwM $ GHCSanityCheckCompileFailed e ghc Right _ -> return () -- TODO check that the output of running the command is correct toFilePathNoTrailingSlash :: Path loc Dir -> FilePath toFilePathNoTrailingSlash = FP.dropTrailingPathSeparator . toFilePath -- Remove potentially confusing environment variables removeHaskellEnvVars :: Map Text Text -> Map Text Text removeHaskellEnvVars = Map.delete "GHC_PACKAGE_PATH" . Map.delete "HASKELL_PACKAGE_SANDBOX" . Map.delete "HASKELL_PACKAGE_SANDBOXES" . Map.delete "HASKELL_DIST_DIR" -- | Get map of environment variables to set to change the locale's encoding to UTF-8 getUtf8LocaleVars :: forall m env. (MonadReader env m, HasPlatform env, MonadLogger m, MonadCatch m, MonadBaseControl IO m, MonadIO m) => EnvOverride -> m (Map Text Text) getUtf8LocaleVars menv = do Platform _ os <- asks getPlatform if isWindows os then -- On Windows, locale is controlled by the code page, so we don't set any environment -- variables. return Map.empty else do let checkedVars = map checkVar (Map.toList $ eoTextMap menv) -- List of environment variables that will need to be updated to set UTF-8 (because -- they currently do not specify UTF-8). needChangeVars = concatMap fst checkedVars -- Set of locale-related environment variables that have already have a value. existingVarNames = Set.unions (map snd checkedVars) -- True if a locale is already specified by one of the "global" locale variables. hasAnyExisting = or $ map (`Set.member` existingVarNames) ["LANG", "LANGUAGE", "LC_ALL"] if null needChangeVars && hasAnyExisting then -- If no variables need changes and at least one "global" variable is set, no -- changes to environment need to be made. return Map.empty else do -- Get a list of known locales by running @locale -a@. elocales <- tryProcessStdout Nothing menv "locale" ["-a"] let -- Filter the list to only include locales with UTF-8 encoding. utf8Locales = case elocales of Left _ -> [] Right locales -> filter isUtf8Locale (T.lines $ T.decodeUtf8With T.lenientDecode locales) mfallback = getFallbackLocale utf8Locales when (isNothing mfallback) ($logWarn "Warning: unable to set locale to UTF-8 encoding; GHC may fail with 'invalid character'") let -- Get the new values of variables to adjust. changes = Map.unions $ map (adjustedVarValue utf8Locales mfallback) needChangeVars -- Get the values of variables to add. adds | hasAnyExisting = -- If we already have a "global" variable, then nothing needs -- to be added. Map.empty | otherwise = -- If we don't already have a "global" variable, then set LANG to the -- fallback. case mfallback of Nothing -> Map.empty Just fallback -> Map.singleton "LANG" fallback return (Map.union changes adds) where -- Determines whether an environment variable is locale-related and, if so, whether it needs to -- be adjusted. checkVar :: (Text, Text) -> ([Text], Set Text) checkVar (k,v) = if k `elem` ["LANG", "LANGUAGE"] || "LC_" `T.isPrefixOf` k then if isUtf8Locale v then ([], Set.singleton k) else ([k], Set.singleton k) else ([], Set.empty) -- Adjusted value of an existing locale variable. Looks for valid UTF-8 encodings with -- same language /and/ territory, then with same language, and finally the first UTF-8 locale -- returned by @locale -a@. adjustedVarValue :: [Text] -> Maybe Text -> Text -> Map Text Text adjustedVarValue utf8Locales mfallback k = case Map.lookup k (eoTextMap menv) of Nothing -> Map.empty Just v -> case concatMap (matchingLocales utf8Locales) [ T.takeWhile (/= '.') v <> "." , T.takeWhile (/= '_') v <> "_"] of (v':_) -> Map.singleton k v' [] -> case mfallback of Just fallback -> Map.singleton k fallback Nothing -> Map.empty -- Determine the fallback locale, by looking for any UTF-8 locale prefixed with the list in -- @fallbackPrefixes@, and if not found, picking the first UTF-8 encoding returned by @locale -- -a@. getFallbackLocale :: [Text] -> Maybe Text getFallbackLocale utf8Locales = do case concatMap (matchingLocales utf8Locales) fallbackPrefixes of (v:_) -> Just v [] -> case utf8Locales of [] -> Nothing (v:_) -> Just v -- Filter the list of locales for any with the given prefixes (case-insitive). matchingLocales :: [Text] -> Text -> [Text] matchingLocales utf8Locales prefix = filter (\v -> (T.toLower prefix) `T.isPrefixOf` T.toLower v) utf8Locales -- Does the locale have one of the encodings in @utf8Suffixes@ (case-insensitive)? isUtf8Locale locale = or $ map (\v -> T.toLower v `T.isSuffixOf` T.toLower locale) utf8Suffixes -- Prefixes of fallback locales (case-insensitive) fallbackPrefixes = ["C.", "en_US.", "en_"] -- Suffixes of UTF-8 locales (case-insensitive) utf8Suffixes = [".UTF-8", ".utf8"]
akhileshs/stack
src/Stack/Setup.hs
bsd-3-clause
51,674
0
31
17,441
11,858
5,923
5,935
1,015
15
{----------------------------------------------------------------------------------------- Layout demo. -----------------------------------------------------------------------------------------} module Main where import Graphics.UI.WX main :: IO () main = start gui gui :: IO () gui = do f <- frame [text := "Layout test"] p <- panel f [] -- panel for color and tab management. ok <- button p [text := "Ok", on command := close f] can <- button p [text := "Cancel", on command := infoDialog f "Info" "Pressed 'Cancel'"] xinput <- textEntry p [text := "100", alignment := AlignRight] yinput <- textEntry p [text := "100", alignment := AlignRight] set f [defaultButton := ok ,layout := container p $ margin 10 $ column 5 [boxed "coordinates" (grid 5 5 [[label "x:", hfill $ widget xinput] ,[label "y:", hfill $ widget yinput]]) ,floatBottomRight $ row 5 [widget ok,widget can]] ] return ()
ekmett/wxHaskell
samples/wx/Layout.hs
lgpl-2.1
1,156
0
18
400
325
161
164
20
1
module A (T(..)) where data T = T
forste/haReFork
tools/base/Modules/tests/4/A.hs
bsd-3-clause
36
0
5
10
20
13
7
2
0
{-# LANGUAGE TypeFamilies, PolyKinds, DataKinds, TypeOperators #-} module T7939 where import Data.Kind (Type) class Foo a where type Bar a b type family F a type instance F Int = Bool type family G a where G Int = Bool type family H a where H False = True type family J a where J '[] = False J (h ': t) = True type family K a where K '[] = Nothing K (h ': t) = Just h type family L (a :: k) (b :: Type) :: k where L Int Int = Bool L Maybe Bool = IO
sdiehl/ghc
testsuite/tests/ghci/scripts/T7939.hs
bsd-3-clause
475
0
8
128
193
113
80
20
0
{-# LANGUAGE ForeignFunctionInterface #-} -- $ ghc -O2 --make wrappers.hs functions.c import Numeric.LinearAlgebra import Data.Packed.Development import Foreign(Ptr,unsafePerformIO) import Foreign.C.Types(CInt) ----------------------------------------------------- main = do print $ myDiag $ (3><5) [1..] ----------------------------------------------------- -- arbitrary data order foreign import ccall unsafe "c_diag" cDiag :: CInt -- matrix order -> CInt -> CInt -> Ptr Double -- argument -> CInt -> Ptr Double -- result1 -> CInt -> CInt -> Ptr Double -- result2 -> IO CInt -- exit code myDiag m = unsafePerformIO $ do y <- createVector (min r c) z <- createMatrix (orderOf m) r c app3 (cDiag o) mat m vec y mat z "cDiag" return (y,z) where r = rows m c = cols m o = if orderOf m == RowMajor then 1 else 0
mightymoose/liquidhaskell
benchmarks/hmatrix-0.15.0.1/examples/devel/ej2/wrappers.hs
bsd-3-clause
952
0
15
270
261
137
124
21
2
module Foo where import Data.Binary () import Data.ByteString ()
mathhun/stack
test/integration/tests/345-override-bytestring/files/Foo.hs
bsd-3-clause
66
0
4
10
20
13
7
3
0
import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified Data.Set as Set import qualified Data.Map.Strict as Map import qualified Control.Monad.State as State import System.CPUTime --part1 :: [String] -> Int part1 dat = twos*threes where mmap = map countRepeats dat folder (chr, val) (two, three) | val == 2 = (True, three) | val == 3 = (two, True) | otherwise = (two, three) counts = map (\x -> foldr folder (False, False) (Map.toList x)) mmap (twos, threes) = (counter (map fst counts) 0, counter (map snd counts) 0) counter [] n= n counter (x:xs) n = counter xs (n + if x then 1 else 0) countRepeats word = Map.fromListWith (+) (map (\x -> (x, 1)) word) part2 :: [String] -> String part2 dat = head $ findFst dat where findFst (x:xs) = findSnd xs x ++ findFst xs findSnd (y:ys) x = if dst x y == 1 then [map fst $ filter (\(a,b) -> a==b ) (zip x y) ] else findSnd ys x findSnd [] _ = [] dst x y = sum $ map (\(a,b) -> if a == b then 0 else 1) (zip x y) main = do ls <- fmap Text.lines (Text.readFile "../input/2.in") let dat = map Text.unpack ls print $ part1 dat print $ part2 dat
jO-Osko/adventofcode2015
2018/haskell/day2.hs
mit
1,275
0
13
374
583
314
269
28
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} module WebColor where import Data.Aeson import Data.Data import Data.String import qualified Data.Text as T import Data.Word import GHC.Generics import Numeric import System.Random import Text.ParserCombinators.ReadP import Text.Read (readEither) data RGBColor = RGBColor { rgbRed :: {-# UNPACK #-} !Word8 , rgbGreen :: {-# UNPACK #-} !Word8 , rgbBlue :: {-# UNPACK #-} !Word8 } deriving (Eq, Ord, Bounded, Data, Typeable, Generic) instance Show RGBColor where showsPrec _ RGBColor{..} = \s -> "#" ++ rr ++ rg ++ rb ++ s where rr = pad $ showHex rgbRed "" rg = pad $ showHex rgbGreen "" rb = pad $ showHex rgbBlue "" pad [x] = '0' : [x] pad x = x instance Read RGBColor where readsPrec _ = readP_to_S $ do c <- get if c /= '#' then pfail else do (r1, r2) <- (,) <$> get <*> get (g1, g2) <- (,) <$> get <*> get (b1, b2) <- (,) <$> get <*> get let [(r,_)] = readHex [r1, r2] [(g,_)] = readHex [g1, g2] [(b,_)] = readHex [b1, b2] return $ RGBColor r g b instance ToJSON RGBColor where toJSON = String . T.pack . show instance FromJSON RGBColor where parseJSON = withText "RGBColor" $ return . read . T.unpack instance Random RGBColor where randomR (RGBColor lr lg lb, RGBColor hr hg hb) gen = let (r, gen1) = randomR (lr, hr) gen (g, gen2) = randomR (lg, hg) gen1 (b, gen3) = randomR (lb, hb) gen2 in (RGBColor r g b, gen3) random gen = let (r, gen1) = random gen (g, gen2) = random gen1 (b, gen3) = random gen2 in (RGBColor r g b, gen3) instance IsString RGBColor where fromString = read
AndrewRademacher/lens-testing
src/WebColor.hs
mit
2,185
0
16
854
708
383
325
56
0